@mdbase-dev/connect 0.1.0-beta.21

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 (46) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +405 -0
  3. package/dist/async.d.ts +1 -0
  4. package/dist/async.js +13 -0
  5. package/dist/authorization-types.d.ts +7 -0
  6. package/dist/authorization-types.js +1 -0
  7. package/dist/authorization-url.d.ts +3 -0
  8. package/dist/authorization-url.js +27 -0
  9. package/dist/base64.d.ts +3 -0
  10. package/dist/base64.js +21 -0
  11. package/dist/browser/integrity.json +4 -0
  12. package/dist/browser/mdbase-connect.min.js +3 -0
  13. package/dist/browser/mdbase-connect.min.js.sha384 +1 -0
  14. package/dist/collection-client.d.ts +57 -0
  15. package/dist/collection-client.js +214 -0
  16. package/dist/connect.d.ts +39 -0
  17. package/dist/connect.js +620 -0
  18. package/dist/connection-notifications.d.ts +25 -0
  19. package/dist/connection-notifications.js +179 -0
  20. package/dist/connection-transport.d.ts +80 -0
  21. package/dist/connection-transport.js +670 -0
  22. package/dist/connection-types.d.ts +29 -0
  23. package/dist/connection-types.js +1 -0
  24. package/dist/connection.d.ts +154 -0
  25. package/dist/connection.js +371 -0
  26. package/dist/crypto.d.ts +64 -0
  27. package/dist/crypto.js +391 -0
  28. package/dist/errors.d.ts +31 -0
  29. package/dist/errors.js +83 -0
  30. package/dist/index.d.ts +13 -0
  31. package/dist/index.js +12 -0
  32. package/dist/internal-types.d.ts +70 -0
  33. package/dist/internal-types.js +1 -0
  34. package/dist/notifications.d.ts +47 -0
  35. package/dist/notifications.js +52 -0
  36. package/dist/operation-helpers.d.ts +24 -0
  37. package/dist/operation-helpers.js +129 -0
  38. package/dist/operation-types.d.ts +254 -0
  39. package/dist/operation-types.js +1 -0
  40. package/dist/runtime-utils.d.ts +33 -0
  41. package/dist/runtime-utils.js +224 -0
  42. package/dist/selection.d.ts +48 -0
  43. package/dist/selection.js +112 -0
  44. package/dist/session.d.ts +76 -0
  45. package/dist/session.js +271 -0
  46. package/package.json +41 -0
@@ -0,0 +1,3 @@
1
+ "use strict";var MdbaseConnect=(()=>{var ie=Object.defineProperty;var Xe=Object.getOwnPropertyDescriptor;var et=Object.getOwnPropertyNames;var tt=Object.prototype.hasOwnProperty;var nt=(n,e)=>{for(var t in e)ie(n,t,{get:e[t],enumerable:!0})},it=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of et(e))!tt.call(n,r)&&r!==t&&ie(n,r,{get:()=>e[r],enumerable:!(i=Xe(e,r))||i.enumerable});return n};var rt=n=>it(ie({},"__esModule",{value:!0}),n);var St={};nt(St,{IndexedDbGrantKeyStore:()=>A,MdbaseBrowserSelection:()=>ge,MdbaseCollectionClient:()=>N,MdbaseConnect:()=>ye,MdbaseConnectError:()=>s,MdbaseConnection:()=>L,MdbaseMemorySelection:()=>me,MdbaseOperationValidationError:()=>J,MdbaseSession:()=>G,MemoryGrantKeyStore:()=>M,RelayCryptoError:()=>f,createPkce:()=>V,decryptRelayResponse:()=>B,encryptRelayRequest:()=>U,isRetryableConnectError:()=>se,parseMdbaseNativeNotificationData:()=>_t,parseMdbasePushPayload:()=>Ze,showMdbasePushNotification:()=>kt,unwrapOperation:()=>O});var x="P256-HKDF-SHA256-AES256GCM";var ot="contract-setup-v1",at=["authorization-activation","encrypted-relay","policy-ack"],Pt=[...at,ot],re=1;var be="mdbase-authority-request-proof-v1",E={version:"x-mdbase-proof-version",timestamp:"x-mdbase-proof-timestamp",nonce:"x-mdbase-proof-nonce",signature:"x-mdbase-proof-signature"};var st="mdbase-connect-keys",P="grant-keys",ae=18446744073709551615n,ct="mdbase-connect relay request key v1",lt="mdbase-connect relay response key v1",we=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,A=class{database=null;async create(e){let t=await Se(e),i=await this.open();return await _e(i,r=>r.add({...t,counter:"0"})),t}async get(e){let t=await this.open(),i=await yt(t.transaction(P).objectStore(P).get(e));return i?{handle:i.handle,agreementPrivateKey:i.agreementPrivateKey,agreementPublicKey:i.agreementPublicKey,signingPrivateKey:i.signingPrivateKey,signingPublicKey:i.signingPublicKey}:null}async nextCounter(e){let t=await this.open();return new Promise((i,r)=>{let a=t.transaction(P,"readwrite"),o=a.objectStore(P),c=o.get(e),l=null;c.onerror=()=>r(c.error),c.onsuccess=()=>{let d=c.result;if(!d){a.abort(),r(new f("missing_grant_key","The encrypted grant key is unavailable."));return}let u=BigInt(d.counter)+1n;if(u>ae){a.abort(),r(new f("counter_exhausted","The encrypted grant must be authorized again."));return}l=u.toString(),o.put({...d,counter:l})},a.onerror=()=>r(a.error),a.onabort=()=>r(a.error??new Error("Key counter transaction aborted.")),a.oncomplete=()=>{l&&i(l)}})}async delete(e){let t=await this.open();await _e(t,i=>i.delete(e))}open(){if(typeof indexedDB>"u")throw new f("key_storage_unavailable","Encrypted relay authorization requires browser IndexedDB or an injected grant key store.");return this.database||(this.database=new Promise((e,t)=>{let i=indexedDB.open(st,1);i.onupgradeneeded=()=>{i.result.objectStoreNames.contains(P)||i.result.createObjectStore(P,{keyPath:"handle"})},i.onerror=()=>t(i.error),i.onsuccess=()=>e(i.result)})),this.database}},M=class{records=new Map;sequence=Promise.resolve();async create(e){if(this.records.has(e))throw new Error(`Grant key already exists: ${e}`);let t=await Se(e);return this.records.set(e,{...t,counter:"0"}),t}async get(e){let t=this.records.get(e);return t?{handle:t.handle,agreementPrivateKey:t.agreementPrivateKey,agreementPublicKey:t.agreementPublicKey,signingPrivateKey:t.signingPrivateKey,signingPublicKey:t.signingPublicKey}:null}nextCounter(e){let t,i,r=new Promise((a,o)=>{t=a,i=o});return this.sequence=this.sequence.then(()=>{let a=this.records.get(e);if(!a)throw new f("missing_grant_key","The encrypted grant key is unavailable.");let o=BigInt(a.counter)+1n;if(o>ae)throw new f("counter_exhausted","The encrypted grant must be authorized again.");a.counter=o.toString(),t(a.counter)}).catch(a=>{i(a)}),r}async delete(e){this.records.delete(e)}};async function ke(n,e,t,i){let r=await ut(n,e,t),a=i.timestamp??Math.floor(Date.now()/1e3),o=i.nonce??crypto.randomUUID(),c=await dt({...i,timestamp:a,nonce:o}),l=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},r.signingPrivateKey,new TextEncoder().encode(c));return{[E.version]:String(re),[E.timestamp]:String(a),[E.nonce]:o,[E.signature]:D(new Uint8Array(l))}}async function dt(n){let e=n.method.toUpperCase(),t=await ve(n.body??""),i=await ve(n.credential);for(let r of[e,n.target,String(n.timestamp),n.nonce])if(!r||r.includes(`
2
+ `)||r.includes("\r"))throw new f("invalid_proof_input","Authority request proof metadata is invalid.");return[be,re,e,n.target,t,i,n.timestamp,n.nonce].join(`
3
+ `)}async function U(n,e,t,i,r,a=crypto.randomUUID()){K(t.encryption);let o=await Re(n,e,t.encryption.application_agreement_public_key),c=await n.nextCounter(e),l={binding:t,requestId:a,operation:i,counter:c},d=await Pe(o.agreementPrivateKey,t,"request"),u=new TextEncoder().encode(JSON.stringify(r??{})),p=await crypto.subtle.encrypt({name:"AES-GCM",iv:Ae(c),additionalData:new TextEncoder().encode(Ce(l,"request")),tagLength:128},d,u);return{type:"encrypted_operation_request",...pt(l),ciphertext:D(new Uint8Array(p))}}async function B(n,e,t,i,r){if(!ht(i,r))throw new f("invalid_encrypted_response","Encrypted response metadata does not match its request.");let a=await Re(n,e,t.encryption.application_agreement_public_key),o={binding:t,requestId:i.request_id,operation:i.operation,counter:i.counter},c=await Pe(a.agreementPrivateKey,t,"response");try{let l=await crypto.subtle.decrypt({name:"AES-GCM",iv:Ae(i.counter),additionalData:new TextEncoder().encode(Ce(o,"response")),tagLength:128},c,Oe(Me(r.ciphertext))),d=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(l));if(d?.ok===!0&&"result"in d||d?.ok===!1&&typeof d.error?.code=="string"&&typeof d.error?.message=="string")return d;throw new Error("invalid response body")}catch(l){throw l instanceof f?l:new f("encrypted_response_rejected","The encrypted connector response could not be authenticated.")}}var f=class extends Error{constructor(t,i){super(i);this.code=t}code};async function Se(n){let e=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"]),t=D(new Uint8Array(await crypto.subtle.exportKey("raw",e.publicKey))),i=await crypto.subtle.exportKey("pkcs8",e.privateKey),r=await crypto.subtle.importKey("pkcs8",i,{name:"ECDH",namedCurve:"P-256"},!1,["deriveBits"]),a=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign","verify"]),o=D(new Uint8Array(await crypto.subtle.exportKey("raw",a.publicKey))),c=await crypto.subtle.exportKey("pkcs8",a.privateKey),l=await crypto.subtle.importKey("pkcs8",c,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]);return{handle:n,agreementPrivateKey:r,agreementPublicKey:t,signingPrivateKey:l,signingPublicKey:o}}async function Re(n,e,t){let i=await n.get(e);if(!i||i.agreementPublicKey!==t)throw new f("missing_grant_key","The encrypted grant key is unavailable or does not match the grant.");return i}async function ut(n,e,t){let i=await n.get(e);if(!i||i.signingPublicKey!==t)throw new f("missing_grant_key","The remote authority signing key is unavailable or does not match the grant.");return i}async function Pe(n,e,t){let i,r;try{i=await crypto.subtle.importKey("raw",Oe(oe(e.encryption.connector_agreement_public_key)),{name:"ECDH",namedCurve:"P-256"},!1,[]),r=await crypto.subtle.deriveBits({name:"ECDH",public:i},n,256)}catch{throw new f("invalid_public_key","The connector relay public key is invalid.")}let a=await crypto.subtle.importKey("raw",r,"HKDF",!1,["deriveKey"]),o=new TextEncoder().encode(Ie(e)),c=await crypto.subtle.digest("SHA-256",o);return crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:c,info:new TextEncoder().encode(t==="request"?ct:lt)},a,{name:"AES-GCM",length:256},!1,t==="request"?["encrypt"]:["decrypt"])}function Ie(n){let e=n.encryption;return["mdbase-connect",1,e.suite,n.grantId,n.applicationId,e.connector_id,e.collection_id,e.scope_epoch,e.key_id].join("|")}function Ce(n,e){return[Ie(n.binding),n.requestId,e,n.operation,n.counter].join("|")}function pt(n){let e=n.binding.encryption;return{protocol_version:1,suite:x,request_id:n.requestId,grant_id:n.binding.grantId,application_id:n.binding.applicationId,connector_id:e.connector_id,collection_id:e.collection_id,operation:n.operation,scope_epoch:e.scope_epoch,key_id:e.key_id,counter:n.counter}}function ht(n,e){return e.type==="encrypted_operation_response"&&typeof e.ciphertext=="string"&&n.protocol_version===e.protocol_version&&n.suite===e.suite&&n.request_id===e.request_id&&n.grant_id===e.grant_id&&n.application_id===e.application_id&&n.connector_id===e.connector_id&&n.collection_id===e.collection_id&&n.operation===e.operation&&n.scope_epoch===e.scope_epoch&&n.key_id===e.key_id&&n.counter===e.counter}function K(n){if(n.protocol_version!==1||n.suite!==x||!Number.isSafeInteger(n.scope_epoch)||n.scope_epoch<=0||typeof n.key_id!="string"||n.key_id.length===0||n.key_id.length>200||n.key_id.includes("|"))throw new f("unsupported_encryption","The grant uses an unsupported relay encryption profile.");if(typeof n.connector_id!="string"||!we.test(n.connector_id)||typeof n.collection_id!="string"||!we.test(n.collection_id))throw new f("unsupported_encryption","The grant uses invalid encrypted relay identities.");oe(n.application_agreement_public_key),oe(n.connector_agreement_public_key)}function Ae(n){let e=BigInt(n);if(e<=0n||e>ae||e.toString()!==n)throw new f("invalid_counter","The encrypted relay counter is invalid.");let t=new Uint8Array(new ArrayBuffer(12));return new DataView(t.buffer).setBigUint64(4,e,!1),t}function D(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}async function ve(n){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n));return D(new Uint8Array(e))}function Me(n){if(!/^[A-Za-z0-9_-]+$/.test(n))throw new f("invalid_base64","Encrypted relay data is malformed.");let e="=".repeat((4-n.length%4)%4),t=atob(n.replaceAll("-","+").replaceAll("_","/")+e);return Uint8Array.from(t,i=>i.charCodeAt(0))}function oe(n){let e=Me(n);if(e.length!==65||e[0]!==4)throw new f("invalid_public_key","Encrypted relay public keys must be uncompressed P-256 points.");return e}function Oe(n){return Uint8Array.from(n).buffer}function yt(n){return new Promise((e,t)=>{n.onerror=()=>t(n.error),n.onsuccess=()=>e(n.result)})}function _e(n,e){return new Promise((t,i)=>{let r=n.transaction(P,"readwrite"),a=e(r.objectStore(P));a.onerror=()=>i(a.error),r.onerror=()=>i(r.error),r.onabort=()=>i(r.error??new Error("Grant key transaction aborted.")),r.oncomplete=()=>t()})}function q(n,e){return new Promise((t,i)=>{if(e?.aborted){i(e.reason??new DOMException("Aborted","AbortError"));return}let r=setTimeout(t,n);e?.addEventListener("abort",()=>{clearTimeout(r),i(e.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}var s=class extends Error{constructor(t,i,r={}){super(i);this.code=t;this.name="MdbaseConnectError";let a=ft(t,r.status);this.status=r.status,this.retryable=r.retryable??a.retryable,this.requiresAuthorization=r.requiresAuthorization??a.requiresAuthorization,this.outcomeUnknown=r.outcomeUnknown??a.outcomeUnknown,this.recovery=r.recovery??a.recovery,this.details=r.details,r.cause!==void 0&&Object.defineProperty(this,"cause",{value:r.cause,configurable:!0})}code;status;retryable;requiresAuthorization;outcomeUnknown;recovery;details},J=class extends Error{constructor(t,i){super(t.filter(r=>r.severity==="error").map(r=>r.message).join(" ")||t.map(r=>r.message).join(" ")||"The collection rejected this operation.");this.diagnostics=t;this.result=i;this.name="MdbaseOperationValidationError"}diagnostics;result;code="operation_invalid"};function O(n){if(!n.valid)throw new J(n.diagnostics,n.result);return n.result}function se(n){return n instanceof s?n.retryable&&!n.outcomeUnknown:n instanceof TypeError}function ft(n,e){let t=new Set(["authorization_expired","direct_operation_rejected","encryption_required","insufficient_access","missing_grant_key","not_authorized","relay_authorization_expired"]),i=n==="direct_outcome_unknown"||n==="pending_mutation_unresolved",r=t.has(n)||e===401,a=new Set(["connector_offline","discovery_failed","relay_unavailable","sync_failed","temporarily_unavailable","timeout"]),o=e===408||e===425||e===429||e!==void 0&&e>=500,c=!i&&!r&&(a.has(n)||o),l=i?"resolve_outcome":r?"reauthorize":n==="change_cursor_reset"?"refresh":c?"retry":e!==void 0&&e>=400&&e<500?"fix_request":"none";return{retryable:c,requiresAuthorization:r,outcomeUnknown:i,recovery:l}}var N=class{constructor(e){this.transport=e}transport;operation(e,t,i){return this.transport.operation(e,t,i)}describe(){return this.operation("describe",{})}changes(e={},t){return this.operation("changes",e,t)}read(e){return this.operation("read",e)}query(e={},t){return this.operation("query",e,t)}async*queryPages(e={},t={}){let{offset:i,limit:r,snapshot:a,...o}=e,c=mt(i,0),l=Te(t.firstPageSize??r,200),d=Te(t.pageSize??r,1e3),u=a,p=0,h=0;for(;!t.signal?.aborted;){let y=O(await this.query({...o,offset:c,limit:h===0?l:d,...u?{snapshot:u}:{}},{signal:t.signal})),v=y.meta?.snapshot;if(u&&v&&u!==v)throw new s("query_snapshot_changed","The collection query snapshot changed while paging. Refresh the query before continuing.",{recovery:"refresh"});!u&&v&&(u=v),p+=y.results.length;let S=!y.meta?.has_more||y.results.length===0,b={results:y.results,...y.meta?{meta:y.meta}:{},page:h,offset:c,loaded:p,complete:S,...u?{snapshot:u}:{}};if(t.onProgress?.(b),yield b,S)return;c+=y.results.length,h+=1}}async queryAll(e={},t={}){let i=[],r;for await(let a of this.queryPages(e,t))i.push(...a.results),r=a;return{results:i,meta:{...r?.meta??{},total_count:r?.meta?.total_count??i.length,has_more:r?!r.complete:!1,...r?.snapshot?{snapshot:r.snapshot}:{}}}}listViews(){return this.operation("list_views",{})}executeView(e){return this.operation("execute_view",e)}readViewSource(e){return this.operation("read_view_source",e)}createViewSource(e){return this.operation("create_view_source",e)}updateViewSource(e){return this.operation("update_view_source",e)}deleteViewSource(e){return this.operation("delete_view_source",e)}create(e){return this.operation("create",e)}update(e){return this.operation("update",e)}delete(e,t){return this.operation("delete",e,t)}preflightDelete(e,t){return this.operation("delete",{...e,check_backlinks:!0,dry_run:!0},t)}rename(e,t){return this.operation("rename",e,t)}preflightRename(e,t){return this.operation("rename",{...e,dry_run:!0},t)}validate(e={}){return this.operation("validate",e)}readType(e){return this.operation("read_type",e)}createType(e){return this.operation("create_type",e)}updateType(e){return this.operation("update_type",e)}installTypePack(e){return this.operation("install_type_pack",e)}listTimers(e){return this.operation("list_timers",{namespace:e})}putTimer(e){return this.operation("put_timer",e)}cancelTimer(e){return this.operation("cancel_timer",e)}reconcileTimers(e){return this.operation("reconcile_timers",e)}async*watch(e={}){let t=e.cursor,i=Math.max(100,e.pollIntervalMs??1e3),r=gt(e.retry),a=0,o=!1;for(e.onStatus?.({state:"connecting",...t===void 0?{}:{cursor:t}});!e.signal?.aborted;)try{t===void 0&&(t=(await this.changes({},{signal:e.signal})).cursor);let c=await this.changes({after:t,limit:200},{signal:e.signal});if(c.reset){let d=new s("change_cursor_reset","The collection change cursor expired. Refresh collection state before subscribing again.");throw e.onStatus?.({state:"reset_required",cursor:t,error:d}),d}let l=a>0;a=0,(!o||l)&&e.onStatus?.({state:"connected",cursor:t,recovered:l}),o=!0;for(let d of c.events)yield d;t=c.cursor,c.has_more||await q(i,e.signal)}catch(c){if(e.signal?.aborted)return;if(!r||!se(c)||(o=!1,a+=1,r.maxAttempts!==void 0&&a>r.maxAttempts))throw c;let l=Math.min(r.maxDelayMs,Math.round(r.initialDelayMs*r.multiplier**(a-1)));e.onStatus?.({state:"reconnecting",...t===void 0?{}:{cursor:t},attempt:a,retryInMs:l,error:c}),await q(l,e.signal)}}};function gt(n){if(n!==!1)return{initialDelayMs:Math.max(0,n?.initialDelayMs??500),maxDelayMs:Math.max(0,n?.maxDelayMs??15e3),multiplier:Math.max(1,n?.multiplier??2),...n?.maxAttempts===void 0?{}:{maxAttempts:Math.max(0,n.maxAttempts)}}}function mt(n,e){return typeof n=="number"&&Number.isFinite(n)?Math.max(0,Math.floor(n)):e}function Te(n,e){return typeof n=="number"&&Number.isFinite(n)&&n>0?Math.floor(n):e}function R(n){let e=new Uint8Array(n);return crypto.getRandomValues(e),j(e)}function j(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function xe(n){let e=n.replaceAll("-","+").replaceAll("_","/").padEnd(Math.ceil(n.length/4)*4,"="),t=atob(e),i=new Uint8Array(new ArrayBuffer(t.length));for(let r=0;r<t.length;r+=1)i[r]=t.charCodeAt(r);return i}function le(n){return{...n,credentials:"omit",targetAddressSpace:"loopback"}}async function F(){if(typeof navigator>"u"||!navigator.permissions?.query)return null;try{return(await navigator.permissions.query({name:"local-network-access"})).state}catch{return null}}function Ee(n){return n===404||n===405||n===426||n>=500}function Q(n,e){return e&&typeof e=="object"&&!Array.isArray(e)&&e.dry_run===!0?!1:n==="sync"&&e!==null&&typeof e=="object"&&!Array.isArray(e)&&e.action==="mutate"||n==="create"||n==="update"||n==="delete"||n==="rename"||n==="create_type"||n==="update_type"||n==="install_type_pack"||n==="put_timer"||n==="cancel_timer"||n==="reconcile_timers"}function k(n){return[...new Set(n)]}function De(n,e){return n.grantId||e.grantId?n.grantId===e.grantId&&n.keyHandle===e.keyHandle&&n.encryption?.key_id===e.encryption?.key_id:n.accessToken===e.accessToken}function I(n){if(n?.aborted)throw new s("operation_cancelled","The operation was cancelled before it changed the collection.",{recovery:"none",cause:n.reason})}function de(n,e,t){return e?.aborted?new s("operation_cancelled",t?"Waiting was cancelled after the mutation was sent. Resume the pending mutation to recover its authoritative result.":"The operation was cancelled before it changed the collection.",{outcomeUnknown:t,recovery:t?"resolve_outcome":"none",cause:n}):t?n instanceof s&&n.outcomeUnknown?n:H(n):n instanceof Error?n:new Error(String(n))}function ue(n,e){return e?.aborted===!0||n instanceof s&&n.code==="operation_cancelled"}function ze(n,e){if(e.dry_run!==!0||e.would_rename!==!0||e.from!==n.from||e.to!==n.to)throw new s("invalid_preflight","The rename preview does not match this mutation. Run the preview again.",{recovery:"fix_request"})}function Ue(n,e){if(e.dry_run!==!0||e.would_delete!==!0||e.path!==n.path)throw new s("invalid_preflight","The delete preview does not match this mutation. Run the preview again.",{recovery:"fix_request"})}function Ke(n,e){if(n.update_refs===!1)return{affectedRecords:0,totalUnits:1,warnings:0};let t=e.references_affected??[];return{affectedRecords:new Set(t.map(i=>i.path)).size,totalUnits:1+t.length,warnings:e.warnings?.length??0}}function qe(n){return{affectedRecords:new Set((n.broken_links??[]).map(e=>e.path)).size,totalUnits:1,warnings:0}}async function Ne(n,e){let t=new TextEncoder().encode(`${n}\0${pe(e??{})}`),i=await crypto.subtle.digest("SHA-256",t);return j(new Uint8Array(i))}function pe(n){return JSON.stringify(ce(n))}function ce(n){return Array.isArray(n)?n.map(e=>ce(e)):n&&typeof n=="object"?Object.fromEntries(Object.entries(n).filter(([,e])=>e!==void 0).sort(([e],[t])=>e<t?-1:e>t?1:0).map(([e,t])=>[e,ce(t)])):n}function H(n){return new s("direct_outcome_unknown","The direct write may have completed, and mdbase could not recover its receipt through the relay. Retry the exact same write to recover safely.",{cause:n})}function je(n){let e=new URL(n);if(e.protocol!=="http:"||!["127.0.0.1","[::1]"].includes(e.hostname)||e.username||e.password||e.pathname!=="/"||e.search||e.hash)throw new s("invalid_loopback_url","loopbackUrl must be an HTTP origin on 127.0.0.1 or ::1.");return e.origin}async function V(){let n=R(32),e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n));return{verifier:n,challenge:j(new Uint8Array(e))}}function m(n,e,t,i){return new s(he(n)??n?.error?.code??e,n?.error_description??n?.error?.message??t,{status:i,details:n?.error?.details})}function he(n){return typeof n?.error=="string"?n.error:void 0}function Y(n,e){if(!n||typeof n!="object"||Array.isArray(n)||typeof e!="string")return!1;let t=n;if(typeof t.operations_url!="string"||typeof t.sync_url!="string"||typeof t.replica_id!="string"||t.replica_id.length===0||typeof t.access_token!="string"||t.access_token.length===0||t.proof_public_key!==void 0&&(typeof t.proof_public_key!="string"||t.proof_public_key.length===0))return!1;try{let i=new URL(t.operations_url),r=new URL(t.sync_url);return[i,r].every(a=>(a.protocol==="https:"||a.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(a.hostname))&&!a.username&&!a.password&&!a.search&&!a.hash)&&/^\/v1\/authorities\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/operations$/i.test(i.pathname)&&/^\/v1\/authorities\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/sync$/i.test(r.pathname)&&i.origin===r.origin&&i.pathname.split("/")[3]===e&&r.pathname.split("/")[3]===e}catch{return!1}}function Fe(n,e){return Y({operations_url:n?.operationsUrl,sync_url:n?.syncUrl,replica_id:n?.replicaId,access_token:n?.accessToken,proof_public_key:n?.proofPublicKey},e)}function He(n,e){if(!n||typeof n!="object"||Array.isArray(n)||n.collection_id!==e)return!1;try{return K(n),!0}catch{return!1}}function Ve(n){if(typeof n?.device_code!="string"||typeof n?.user_code!="string"||typeof n?.verification_uri!="string"||typeof n?.verification_uri_complete!="string"||!Number.isFinite(n?.expires_in)||!Number.isFinite(n?.interval))throw new s("invalid_device_authorization_response","Connect returned an invalid downloaded application authorization response.");return{userCode:n.user_code,verificationUri:n.verification_uri,verificationUriComplete:n.verification_uri_complete,expiresAt:Date.now()+Math.max(1,n.expires_in)*1e3,intervalSeconds:Math.max(1,n.interval)}}function w(n){if(!n)return null;try{return JSON.parse(n)}catch{return null}}function W(n){if(!n||typeof n!="object"||Array.isArray(n))return null;let e=n;return e.access!=="contract"&&e.access!=="full_collection"||!Array.isArray(e.contracts)||e.contracts.some(t=>!t||typeof t!="object"||t.contract_type!=="record"||typeof t.id!="string"||typeof t.version!="string"||!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(t.version)||!/^sha256:[0-9a-f]{64}$/.test(t.digest)||!t.schema||typeof t.schema!="object"||Array.isArray(t.schema)||!Array.isArray(t.implementations)||t.implementations.some(i=>!i||typeof i!="object"||typeof i.type_name!="string"||!Number.isInteger(i.type_version)||!/^sha256:[0-9a-f]{64}$/.test(i.digest)||!i.fields||typeof i.fields!="object"||Array.isArray(i.fields)||Object.values(i.fields).some(r=>typeof r!="string")))?null:e}function Le(n){return n.endsWith("/")?n.slice(0,-1):n}function $e(){if(typeof location>"u")throw new s("manifest_required","manifest is required outside a browser environment.");if(location.origin==="null")throw new s("manifest_required","Downloaded applications must provide their v1 portable manifest inline.");return new URL("/.well-known/mdbase-app.json",location.origin).href}function Ge(){if(typeof location>"u")throw new s("redirect_uri_required","redirectUri is required outside a browser environment.");return location.href.split(/[?#]/)[0]}function Be(){if(typeof location>"u")throw new s("callback_url_required","callbackUrl is required outside a browser environment.");return location.href}function Je(n){if(n)return new T;if(typeof localStorage>"u")throw new s("storage_required","storage is required outside a browser environment.");try{let e=`mdbase-connect:probe:${R(8)}`;return localStorage.setItem(e,"1"),localStorage.removeItem(e),localStorage}catch{return new T}}var T=class{values=new Map;get length(){return this.values.size}clear(){this.values.clear()}getItem(e){return this.values.get(e)??null}key(e){return[...this.values.keys()][e]??null}removeItem(e){this.values.delete(e)}setItem(e,t){this.values.set(String(e),String(t))}};function Qe(n){return typeof n=="string"||n.distribution!=="portable"?!1:typeof location>"u"||location.origin==="null"||!["http:","https:"].includes(location.protocol)}function Ye(n){let e=pe(n),t=2166136261,i=2654435769;for(let r=0;r<e.length;r+=1){let a=e.charCodeAt(r);t=Math.imul(t^a,16777619),i=Math.imul(i^a,2246822507)}return`${(t>>>0).toString(16).padStart(8,"0")}${(i>>>0).toString(16).padStart(8,"0")}`}var Z=class{constructor(e){this.context=e}context;async registerNotifications(e){let t=await this.context.authorizedToken();if(!t)throw new s("not_authorized","Connect this application before enabling notifications.");let r=(await this.context.register()).notifications?.criteria.map(b=>b.id)??[],a=[...new Set(e.criteria??r)],o=a.find(b=>!r.includes(b));if(o)throw new s("notification_criterion_not_declared",`The application manifest does not declare notification criterion ${o}.`);if(a.length===0)throw new s("notifications_not_declared","This application manifest does not declare any notification criteria.");let c=await fetch(`${this.context.serverUrl}/v1/notifications/vapid-public-key`),l=await c.json();if(!c.ok)throw m(l,"notifications_unavailable","Push notifications are unavailable.",c.status);let d=await e.serviceWorker.pushManager.getSubscription();d||(d=await e.serviceWorker.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:xe(l.public_key)}));let u=d.toJSON();if(!u.endpoint||!u.keys?.p256dh||!u.keys.auth)throw new s("invalid_push_subscription","The browser returned an incomplete push subscription.");let p=w(this.context.storage.getItem(this.context.notificationKey())),h=e.installationId??p?.installationId??R(24),y=await fetch(`${this.context.serverUrl}/v1/notifications/channels`,{method:"POST",headers:{authorization:`Bearer ${t.accessToken}`,"content-type":"application/json"},body:JSON.stringify({installation_id:h,criteria:a,subscription:{endpoint:u.endpoint,expirationTime:u.expirationTime??null,keys:u.keys}})}),v=await y.json();if(!y.ok)throw m(v,"notification_registration_failed","Could not register push notifications.",y.status);p?.channelId&&p.channelId!==v.channel_id&&fetch(`${this.context.serverUrl}/v1/notifications/channels/${p.channelId}`,{method:"DELETE",headers:{authorization:`Bearer ${t.accessToken}`}}).catch(()=>{});let S={channelId:v.channel_id,installationId:h,criteria:a};return this.context.storage.setItem(this.context.notificationKey(),JSON.stringify(S)),S}async registerNativeNotifications(e){let t=await this.context.authorizedToken();if(!t)throw new s("not_authorized","Connect this application before enabling notifications.");let i=await this.context.register();if(i.notifications?.native_delivery?.mode!=="managed_fcm")throw new s("managed_fcm_not_declared","This application does not declare Connect-managed native notifications.");let r=i.notifications.criteria.map(y=>y.id),a=[...new Set(e.criteria??r)],o=a.find(y=>!r.includes(y));if(o)throw new s("notification_criterion_not_declared",`The application manifest does not declare notification criterion ${o}.`);if(a.length===0)throw new s("notifications_not_declared","This application manifest does not declare any notification criteria.");let c=this.context.notificationKey("fcm"),l=w(this.context.storage.getItem(c)),d=e.installationId??l?.installationId??R(24),u=await fetch(`${this.context.serverUrl}/v1/notifications/channels`,{method:"POST",headers:{authorization:`Bearer ${t.accessToken}`,"content-type":"application/json"},body:JSON.stringify({installation_id:d,criteria:a,transport:"fcm",token:e.token})}),p=await u.json();if(!u.ok)throw m(p,"notification_registration_failed","Could not register native notifications.",u.status);l?.channelId&&l.channelId!==p.channel_id&&this.deleteNotificationChannel(l.channelId,t.accessToken).catch(()=>{});let h={channelId:p.channel_id,installationId:d,transport:"fcm",criteria:a};return this.context.storage.setItem(c,JSON.stringify(h)),h}async unregisterNativeNotifications(){let e=this.context.notificationKey("fcm"),t=w(this.context.storage.getItem(e)),i=await this.context.authorizedToken();if(t?.channelId&&!i)throw new s("not_authorized","Reconnect this application before disabling native notifications.");t?.channelId&&i&&await this.deleteNotificationChannel(t.channelId,i.accessToken),this.context.storage.removeItem(e)}async unregisterNotifications(e){let t=w(this.context.storage.getItem(this.context.notificationKey())),i=await this.context.authorizedToken();if(t?.channelId&&!i)throw new s("not_authorized","Reconnect this application before disabling push notifications.");if(t?.channelId&&i){let a=await fetch(`${this.context.serverUrl}/v1/notifications/channels/${t.channelId}`,{method:"DELETE",headers:{authorization:`Bearer ${i.accessToken}`}});if(!a.ok&&a.status!==404){let o=await a.json();throw m(o,"notification_unregistration_failed","Could not unregister push notifications.",a.status)}}this.context.storage.removeItem(this.context.notificationKey()),await(await e?.pushManager.getSubscription())?.unsubscribe()}async deleteNotificationChannel(e,t){let i=await fetch(`${this.context.serverUrl}/v1/notifications/channels/${e}`,{method:"DELETE",headers:{authorization:`Bearer ${t}`}});if(!i.ok&&i.status!==404){let r=await i.json();throw m(r,"notification_unregistration_failed","Could not unregister push notifications.",i.status)}}};var X=class{serverUrl;storage;keyStore;directAccessMode;loopbackUrl;collectionId;internals;onChange;refreshPromise=null;directStatus;currentRoute="relay";directFailures=0;directRetryAt=0;constructor(e){this.serverUrl=e.serverUrl,this.storage=e.storage,this.keyStore=e.keyStore,this.directAccessMode=e.directAccessMode,this.loopbackUrl=e.loopbackUrl,this.collectionId=e.collectionId,this.internals=e.internals,this.onChange=e.onChange,this.directStatus=this.directAccessMode==="disabled"?"disabled":"unavailable"}get directAccess(){return this.currentToken()?.authority?"disabled":this.directStatus}get route(){return this.currentToken()?.authority?"remote":this.currentRoute}notifyStorageChanged(){this.emitConnection()}async checkDirectAccess(){let e=this.currentToken();if(!this.directEligible(e))return this.setDirectStatus("disabled");let t=await F();return t==="denied"?this.setDirectStatus("denied"):(t==="prompt"||t===null)&&this.storage.getItem(this.directPreferenceKey())!=="enabled"?this.setDirectStatus("permission_required"):this.probeDirectAccess()}async requestDirectAccess(){let e=this.currentToken();return this.directCapable(e)?(this.storage.setItem(this.directPreferenceKey(),"enabled"),this.directRetryAt=0,this.probeDirectAccess()):this.setDirectStatus("disabled")}disableDirectAccess(){this.storage.setItem(this.directPreferenceKey(),"disabled"),this.setDirectStatus("disabled"),this.setRoute("relay")}pendingMutation(){let e=w(this.storage.getItem(this.pendingMutationKey())),t=this.currentToken();return!e||!t||e.collectionId!==t.collectionId||e.grantId!==t.grantId||e.keyId!==t.encryption?.key_id?null:{operation:e.operation,createdAt:e.createdAt,resumable:!0}}async resumePendingMutation(e,t){let i=this.pendingMutation();if(!i)throw new s("no_pending_mutation","There is no interrupted mutation to resume.",{recovery:"none"});return this.performOperation(i.operation,e,t)}async performOperation(e,t,i={}){I(i.signal);let r=this.currentToken();if(!r)throw new s("not_authorized","Connect this application before accessing a collection.");if(!r.operations.includes(e))throw new s("insufficient_access",`This connection does not allow ${e}.`,{requiresAuthorization:!0,recovery:"reauthorize",details:{requiredOperations:[e],grantedOperations:[...r.operations],missingOperations:[e]}});let a=await this.shouldAttemptDirect(r);if(!a&&(r=await this.authorizedToken(),!r))throw new s("not_authorized","Reconnect this application to continue.");let o;try{o=await this.sendOperation(r,e,t,a,i)}catch(u){throw de(u,i.signal,Q(e,t)&&this.pendingMutation()!==null)}let c=o.response,l=c.status===409&&(await c.clone().json().catch(()=>null))?.error?.code==="encryption_binding_stale";if((c.status===401||l)&&r.refreshToken){if(o.pendingMutation&&(o.directDeliveryUncertain||o.encryptedRequest&&o.resumingMutation))throw new s("direct_outcome_unknown","The direct operation may have completed, but its encrypted grant changed before the response could be recovered. Refresh before making another change.");o.pendingMutation&&this.clearPendingMutation(),r=await this.refreshAuthorization(),a=await this.shouldAttemptDirect(r);try{o=await this.sendOperation(r,e,t,a,i)}catch(u){throw de(u,i.signal,Q(e,t)&&this.pendingMutation()!==null)}c=o.response}let d=await c.json();if(!c.ok){let u=m(d,"operation_failed","Collection operation failed.",c.status);throw o.pendingMutation&&(o.directDeliveryUncertain||o.encryptedRequest&&o.resumingMutation)?H(u):(o.pendingMutation&&!o.directDeliveryUncertain&&this.clearPendingMutation(),u.code==="direct_operation_rejected"&&u.status===403&&this.invalidateRejectedAuthorization(r),u)}if(o.encryptedRequest){let u=d?.envelope;if(!u||!r.encryption||!r.grantId||!r.keyHandle)throw new s("invalid_encrypted_response","The relay did not return an encrypted connector response.");try{let p=await B(this.keyStore,r.keyHandle,{grantId:r.grantId,applicationId:r.clientId,encryption:r.encryption},o.encryptedRequest,u);if(o.pendingMutation&&this.clearPendingMutation(),!p.ok)throw new s(p.error.code,p.error.message);return p.result}catch(p){throw p instanceof s?p:p instanceof f?new s(p.code,p.message):p}}if(d?.protocol_version!==1||d?.request_id!==o.requestId)throw new s("invalid_operation_response","The collection authority returned a response for a different protocol request.");return o.pendingMutation&&this.clearPendingMutation(),d.result}async performAuthoritySyncRequest(e,t,i,r,a){let o=await this.authorizedToken();if(!o?.authority||o.collectionId!==e||o.authority.replicaId!==t)throw new s("authority_authorization_changed","Reconnect this collection authority before synchronizing.");let c=await this.sendAuthoritySyncRequest(o,i,r,a);if(c.status===401&&o.refreshToken){if(o=await this.refreshAuthorization(),!o.authority||o.collectionId!==e||o.authority.replicaId!==t)throw new s("authority_authorization_changed","Reconnect this collection authority before synchronizing.");c=await this.sendAuthoritySyncRequest(o,i,r,a)}let l=await c.json();if(!c.ok)throw m(l,"sync_failed","Collection synchronization failed.",c.status);return l}async sendAuthoritySyncRequest(e,t,i,r){if(!e.authority)throw new s("not_remote_authority","This authorization has no remote authority endpoint.");let a=`${e.authority.syncUrl}/${i}`,o=r===void 0?void 0:JSON.stringify(r),c=await this.authorityProofHeaders(e,t,a,o,e.authority.accessToken);return fetch(a,{method:t,headers:{authorization:`Bearer ${e.authority.accessToken}`,...r===void 0?{}:{"content-type":"application/json"},...c},...o===void 0?{}:{body:o}})}async sendOperation(e,t,i,r,a={}){let o=i??{},c,l=!1,d=!1,u=crypto.randomUUID(),p=null,h;if(Q(t,i)){if(h=await Ne(t,i),p=w(this.storage.getItem(this.pendingMutationKey())),p){if(p.collectionId!==e.collectionId||p.grantId!==e.grantId||p.keyId!==e.encryption?.key_id||p.operation!==t||p.inputFingerprint!==h)throw new s("pending_mutation_unresolved","A previous write still has an unknown outcome. Retry that exact write before making another change.");u=p.requestId,d=!0}l=!0}if(e.encryption&&!e.authority){if(!e.grantId||!e.keyHandle)throw new s("missing_grant_key","Reconnect this application to restore encrypted access.");try{if(l)if(p){if(!p.envelope)throw new s("pending_mutation_unresolved","The pending write belongs to a different transport. Reconnect before retrying it.");c=p.envelope}else c=await U(this.keyStore,e.keyHandle,{grantId:e.grantId,applicationId:e.clientId,encryption:e.encryption},t,i,u),this.storage.setItem(this.pendingMutationKey(),JSON.stringify({collectionId:e.collectionId,...e.grantId?{grantId:e.grantId}:{},keyId:e.encryption.key_id,operation:t,inputFingerprint:h,requestId:u,envelope:c,createdAt:Date.now()}));else c=await U(this.keyStore,e.keyHandle,{grantId:e.grantId,applicationId:e.clientId,encryption:e.encryption},t,i)}catch(g){throw g instanceof f?new s(g.code,g.message):g}o=c}else o={protocol_version:1,request_id:u,input:o},l&&!p&&this.storage.setItem(this.pendingMutationKey(),JSON.stringify({collectionId:e.collectionId,...e.grantId?{grantId:e.grantId}:{},operation:t,inputFingerprint:h,requestId:u,createdAt:Date.now()}));if(r&&c&&!e.authority){let g=!1;try{let _=await fetch(`${this.loopbackUrl}/v1/operations`,le({method:"POST",headers:{"content-type":"application/mdbase-connect+json"},body:JSON.stringify(c),signal:a.signal}));if(!Ee(_.status))return _.ok&&(this.markDirectAvailable(),this.setRoute("direct")),{response:_,requestId:u,encryptedRequest:c,pendingMutation:l,resumingMutation:d};g=_.status>=500,this.markDirectUnavailable()}catch(_){if(a.signal?.aborted)throw _;g=!0,await F()==="denied"?this.setDirectStatus("denied"):this.markDirectUnavailable()}let te;try{te=e.expiresAt>Date.now()+3e4?e:await this.refreshAuthorization()}catch(_){throw l&&(g||d)?H(_):_}let ne;try{ne=await fetch(`${this.serverUrl}/v1/authorities/${encodeURIComponent(te.collectionId)}/operations/${t}`,{method:"POST",headers:{authorization:`Bearer ${te.accessToken}`,"content-type":"application/json"},body:JSON.stringify(c),signal:a.signal})}catch(_){throw l&&(g||d)?H(_):_}return ne.ok&&this.setRoute("relay"),{response:ne,requestId:u,encryptedRequest:c,directDeliveryUncertain:g,pendingMutation:l,resumingMutation:d}}let y=e.authority?`${e.authority.operationsUrl}/${t}`:`${this.serverUrl}/v1/authorities/${encodeURIComponent(e.collectionId)}/operations/${t}`,v=JSON.stringify(o),S=e.authority?await this.authorityProofHeaders(e,"POST",y,v,e.authority.accessToken):{},b=await fetch(y,{method:"POST",headers:{authorization:`Bearer ${e.authority?.accessToken??e.accessToken}`,"content-type":"application/json",...S},body:v,signal:a.signal});return b.ok&&this.setRoute(e.authority?"remote":"relay"),{response:b,requestId:u,encryptedRequest:c,pendingMutation:l,resumingMutation:d}}directCapable(e){return!(!e||e.authority||!e.encryption||!e.grantId||!e.keyHandle||this.directAccessMode==="disabled"||typeof location<"u"&&e.applicationOrigin&&e.applicationOrigin!==location.origin)}hasResumableMutationTransport(){return!!this.currentToken()}directEligible(e){return e!==null&&this.directCapable(e)&&this.storage.getItem(this.directPreferenceKey())!=="disabled"}async shouldAttemptDirect(e){if(!this.directEligible(e))return!1;if(this.directStatus==="available")return!0;if(this.directStatus==="unavailable"&&Date.now()<this.directRetryAt)return!1;let t=await F();return t==="denied"?(this.setDirectStatus("denied"),!1):(t==="prompt"||t===null)&&this.storage.getItem(this.directPreferenceKey())!=="enabled"?(this.setDirectStatus("permission_required"),!1):(this.setDirectStatus("checking"),!0)}async probeDirectAccess(){this.setDirectStatus("checking");try{let e=await fetch(`${this.loopbackUrl}/v1/ready`,le({method:"GET",cache:"no-store"})),t=await e.json().catch(()=>null);if(e.ok&&t?.service==="mdbase-connect"&&t?.loopback_protocol_version===1&&t?.encrypted_protocol_version===1)return this.markDirectAvailable(),"available"}catch{}return await F()==="denied"?this.setDirectStatus("denied"):(this.markDirectUnavailable(),"unavailable")}markDirectAvailable(){this.directFailures=0,this.directRetryAt=0,this.setDirectStatus("available")}markDirectUnavailable(){this.directFailures+=1,this.directRetryAt=Date.now()+Math.min(6e4,1e3*2**(this.directFailures-1)),this.setDirectStatus("unavailable")}setDirectStatus(e){return this.directStatus!==e&&(this.directStatus=e,this.emitConnection()),e}setRoute(e){this.currentRoute!==e&&(this.currentRoute=e,this.emitConnection())}emitConnection(){this.onChange()}invalidateRejectedAuthorization(e){let t=w(this.storage.getItem(this.tokenKey()));!t||!De(t,e)||(this.internals.removeToken(this.collectionId,t.keyHandle),this.currentRoute="relay",this.directStatus=this.directAccessMode==="disabled"?"disabled":"unavailable",this.emitConnection())}currentToken(){let e=this.storage.getItem(this.tokenKey()),t=w(e),i=r=>(this.internals.removeToken(this.collectionId,typeof r=="string"?r:void 0,"invalid_stored_grant"),null);if(!t)return e&&i(),null;if(t.version!==1||typeof t.accessToken!="string"||t.accessToken.length===0||typeof t.clientId!="string"||t.clientId.length===0||t.collectionId!==this.collectionId||typeof t.collectionName!="string"||t.collectionName.length===0||!Array.isArray(t.operations)||t.operations.some(r=>typeof r!="string")||typeof t.expiresAt!="number"||!Number.isFinite(t.expiresAt)||t.refreshToken!==void 0&&(typeof t.refreshToken!="string"||t.refreshToken.length===0)||t.refreshExpiresAt!==void 0&&(typeof t.refreshExpiresAt!="number"||!Number.isFinite(t.refreshExpiresAt))||!W(t.scope)||t.authority&&!Fe(t.authority,t.collectionId))return i(t.keyHandle);if(this.internals.relayEncryption==="required"){if(t.authority){if(!t.keyHandle||!t.authority.proofPublicKey)return i(t.keyHandle)}else if(!t.grantId||!t.keyHandle||!He(t.encryption,t.collectionId))return i(t.keyHandle)}return t.expiresAt<=Date.now()&&(!t.refreshToken||(t.refreshExpiresAt??0)<=Date.now())?this.directCapable(t)?t:(this.internals.removeToken(this.collectionId,t.keyHandle),null):t}async authorizedToken(){let e=this.currentToken();if(!e)return null;if(e.expiresAt>Date.now()+3e4)return e;if(!e.refreshToken||(e.refreshExpiresAt??0)<=Date.now()){if(this.directCapable(e))throw new s("relay_authorization_expired","Direct access is still available on this computer, but using the relay requires reconnecting this application.");return this.internals.removeToken(this.collectionId,e.keyHandle),null}return this.refreshAuthorization()}refreshAuthorization(){return this.refreshPromise?this.refreshPromise:(this.refreshPromise=this.performRefresh().finally(()=>{this.refreshPromise=null}),this.refreshPromise)}async performRefresh(){let e=this.currentToken();if(!e?.refreshToken)throw new s("not_authorized","Reconnect this application to continue.");if((e.refreshExpiresAt??0)<=Date.now())throw new s("relay_authorization_expired","Direct access is still available on this computer, but using the relay requires reconnecting this application.");let t=e.refreshToken,i=`${this.serverUrl}/oauth/token`,r=new URLSearchParams({grant_type:"refresh_token",refresh_token:e.refreshToken,client_id:e.clientId}).toString(),a=e.authority?await this.authorityProofHeaders(e,"POST",i,r,e.refreshToken):{},o=await fetch(i,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",...a},body:r}),c=await o.json();if(!o.ok){let l=this.currentToken();if(l?.refreshToken&&l.refreshToken!==t)return l;throw this.directCapable(e)||this.internals.removeToken(this.collectionId,e.keyHandle),m(c,"authorization_expired","Reconnect this application to continue.",o.status)}return this.storeTokenResponse(c,e.clientId,e.keyHandle)}async authorityProofHeaders(e,t,i,r,a){if(!e.authority?.proofPublicKey)return{};if(!e.keyHandle)throw new s("missing_grant_key","Reconnect this application to restore remote authority request signing.");try{let o=new URL(i);return await ke(this.keyStore,e.keyHandle,e.authority.proofPublicKey,{method:t,target:`${o.pathname}${o.search}`,body:r,credential:a})}catch(o){throw o instanceof f?new s(o.code,o.message):o}}storeTokenResponse(e,t,i){if(e.collection_id!==this.collectionId)throw new s("collection_mismatch","The refreshed authorization belongs to a different collection.");let r=this.internals.storeTokenResponse(e,t,i);return this.currentRoute=r.authority?"remote":"relay",this.directStatus=r.authority||this.directAccessMode==="disabled"?"disabled":"unavailable",this.emitConnection(),r}tokenKey(){return this.internals.tokenKey(this.collectionId)}notificationKey(e="web_push"){return this.internals.notificationKey(this.collectionId,e)}pendingMutationKey(){return this.internals.pendingMutationKey(this.collectionId)}clearPendingMutation(){this.storage.removeItem(this.pendingMutationKey())}directPreferenceKey(){return this.internals.directPreferenceKey()}};var C=["describe","changes","read","query"];var L=class{constructor(e,t){this.internals=e;this.collectionId=t;this.transport=new X({serverUrl:e.serverUrl,storage:e.storage,keyStore:e.keyStore,directAccessMode:e.directAccessMode,loopbackUrl:e.loopbackUrl,collectionId:t,internals:e,onChange:()=>this.emitConnection()}),this.collectionClient=new N({operation:(i,r,a)=>this.transport.performOperation(i,r,a)}),this.notifications=new Z({serverUrl:e.serverUrl,storage:e.storage,authorizedToken:()=>this.transport.authorizedToken(),register:()=>this.register(),notificationKey:i=>e.notificationKey(t,i)})}internals;collectionId;collectionClient;notifications;transport;connectionListeners=new Set;get displayName(){return this.transport.currentToken()?.collectionName??`Collection ${this.collectionId.slice(0,8)}`}get operations(){return[...this.transport.currentToken()?.operations??[]]}get scope(){let e=this.transport.currentToken()?.scope;if(!e)throw new s("not_authorized","This collection is no longer authorized for this application.");return e}get directAccess(){return this.transport.directAccess}get route(){return this.transport.route}register(){return this.internals.register()}info(){let e=this.transport.currentToken();return e?{collectionId:e.collectionId,displayName:e.collectionName,operations:[...e.operations],scope:e.scope,route:this.transport.route,directAccess:this.transport.directAccess}:null}authorizationCapabilities(e=C){let t=this.operations,i=k(e).filter(r=>!t.includes(r));return{authorized:this.info()!==null,sufficient:this.info()!==null&&i.length===0,collectionId:this.collectionId,grantedOperations:t,missingOperations:i}}hasOperations(e){return this.authorizationCapabilities(e).sufficient}authorize(e={}){return this.internals.authorize({...e,target:{kind:"collection",collectionId:this.collectionId}})}async requestOperations(e,t={}){let i=this.authorizationCapabilities(e);return i.sufficient?{kind:"unchanged",connection:this}:this.authorize({...t,operations:k([...i.grantedOperations,...i.missingOperations])})}onConnectionChange(e){return this.connectionListeners.add(e),e(this.info()),()=>this.connectionListeners.delete(e)}notifyStorageChanged(){this.transport.notifyStorageChanged()}checkDirectAccess(){return this.transport.checkDirectAccess()}requestDirectAccess(){return this.transport.requestDirectAccess()}disableDirectAccess(){this.transport.disableDirectAccess()}sync(){let e=this.transport.currentToken();if(!e)return null;let t=e.collectionId;if(!e.authority){if(!e.grantId||!e.operations.includes("sync"))return null;let r=e.grantId;return{collectionId:t,replicaId:r,transport:{openSession:()=>this.transport.performOperation("sync",{action:"open_session"}),snapshot:(a,o)=>this.transport.performOperation("sync",{action:"snapshot",snapshot_id:a,...o?{page:o}:{}}),changes:(a,o=200)=>this.transport.performOperation("sync",{action:"changes",after:a,limit:o}),mutate:a=>this.transport.performOperation("sync",{action:"mutate",mutation:a})}}}let i=e.authority.replicaId;return{collectionId:t,replicaId:i,transport:{openSession:()=>this.transport.performAuthoritySyncRequest(t,i,"POST","sessions"),snapshot:(r,a)=>{let o=new URLSearchParams({snapshot_id:r});return a&&o.set("page",a),this.transport.performAuthoritySyncRequest(t,i,"GET",`snapshot?${o}`)},changes:(r,a=200)=>this.transport.performAuthoritySyncRequest(t,i,"GET",`changes?${new URLSearchParams({after:String(r),limit:String(a)})}`),mutate:r=>this.transport.performAuthoritySyncRequest(t,i,"POST","mutations",r)}}}registerNotifications(e){return this.notifications.registerNotifications(e)}registerNativeNotifications(e){return this.notifications.registerNativeNotifications(e)}unregisterNativeNotifications(){return this.notifications.unregisterNativeNotifications()}unregisterNotifications(e){return this.notifications.unregisterNotifications(e)}forget(){let e=this.transport.currentToken();this.internals.removeToken(this.collectionId,e?.keyHandle,"not_authorized"),this.transport.notifyStorageChanged()}describe(){return this.collectionClient.describe()}changes(e={},t){return this.collectionClient.changes(e,t)}read(e){return this.collectionClient.read(e)}query(e={},t){return this.collectionClient.query(e,t)}queryPages(e={},t={}){return this.collectionClient.queryPages(e,t)}queryAll(e={},t={}){return this.collectionClient.queryAll(e,t)}listViews(){return this.collectionClient.listViews()}executeView(e){return this.collectionClient.executeView(e)}readViewSource(e){return this.collectionClient.readViewSource(e)}createViewSource(e){return this.collectionClient.createViewSource(e)}updateViewSource(e){return this.collectionClient.updateViewSource(e)}deleteViewSource(e){return this.collectionClient.deleteViewSource(e)}create(e){return this.collectionClient.create(e)}update(e){return this.collectionClient.update(e)}delete(e,t){return this.collectionClient.delete(e,t)}preflightDelete(e,t){return this.collectionClient.preflightDelete(e,t)}rename(e,t){return this.collectionClient.rename(e,t)}preflightRename(e,t){return this.collectionClient.preflightRename(e,t)}async renameWithProgress(e,t={}){let i=Date.now(),r=this.pendingMutation()?.operation==="rename",a,o=(c,l,d=0)=>{t.onProgress?.({operation:"rename",state:c,elapsedMs:Date.now()-i,cancellable:l,resumed:r,completedUnits:d,...a?{estimate:a}:{}})};try{I(t.signal),o("preflighting",!0);let c=t.preflight??O(await this.preflightRename(e,{signal:t.signal}));ze(e,c),a=Ke(e,c),o("ready",!0),I(t.signal);let l=this.transport.hasResumableMutationTransport();o("applying",l);let d=await this.rename(e,l?{signal:t.signal}:void 0);return o("completed",!1,a.totalUnits),d}catch(c){throw ue(c,t.signal)&&o("cancelled",!1),c}}async deleteWithProgress(e,t={}){let i=Date.now(),r=this.pendingMutation()?.operation==="delete",a,o=(c,l,d=0)=>{t.onProgress?.({operation:"delete",state:c,elapsedMs:Date.now()-i,cancellable:l,resumed:r,completedUnits:d,...a?{estimate:a}:{}})};try{I(t.signal),o("preflighting",!0);let c=t.preflight??O(await this.preflightDelete(e,{signal:t.signal}));Ue(e,c),a=qe(c),o("ready",!0),I(t.signal);let l=this.transport.hasResumableMutationTransport();o("applying",l);let d=await this.delete(e,l?{signal:t.signal}:void 0);return o("completed",!1,a.totalUnits),d}catch(c){throw ue(c,t.signal)&&o("cancelled",!1),c}}pendingMutation(){return this.transport.pendingMutation()}async resumePendingMutation(e,t){return this.transport.resumePendingMutation(e,t)}validate(e={}){return this.collectionClient.validate(e)}readType(e){return this.collectionClient.readType(e)}createType(e){return this.collectionClient.createType(e)}updateType(e){return this.collectionClient.updateType(e)}installTypePack(e){return this.collectionClient.installTypePack(e)}listTimers(e){return this.collectionClient.listTimers(e)}putTimer(e){return this.collectionClient.putTimer(e)}cancelTimer(e){return this.collectionClient.cancelTimer(e)}reconcileTimers(e){return this.collectionClient.reconcileTimers(e)}async*watch(e={}){yield*this.collectionClient.watch(e)}async operation(e,t,i){return this.collectionClient.operation(e,t,i)}emitConnection(){let e=this.info();for(let t of this.connectionListeners)t(e)}};function $(n){for(let e of["code","state","error","error_description"])n.searchParams.delete(e);return n}function ee(n){let e;try{e=new URL(n)}catch{return!1}return e.searchParams.has("state")&&(e.searchParams.has("code")||e.searchParams.has("error"))}function We(n){if(!(n instanceof s)||!n.details||typeof n.details!="object"||Array.isArray(n.details))return;let e=n.details.returnTo;return typeof e=="string"?e:void 0}var G=class{constructor(e,t){this.connect=e;this.operations=k(t.operations??C),this.selection=t.selection,this.autoSelect=t.autoSelect??"only",this.snapshot={status:"unselected",connections:[]},this.refresh()}connect;operations;selection;autoSelect;listeners=new Set;snapshot;snapshotKey="";stopConnections;stopSelection;stopActiveConnection;activeCollectionId=null;unavailableReason="not_authorized";started=!1;refreshing=!1;refreshQueued=!1;transactionDepth=0;callbackPromise=null;async start(){this.started||(this.started=!0,this.stopConnections=this.connect.onConnectionsChange(()=>this.refresh()),this.stopSelection=this.selection.subscribe(()=>{this.unavailableReason="not_authorized",this.refresh()}));let e=this.selection.authorizationCallback();return e?await this.handleAuthorizationCallback(e):this.autoSelectOnlyConnection(),this.refresh(),this.snapshot}destroy(){this.stopConnections?.(),this.stopSelection?.(),this.stopActiveConnection?.(),this.stopConnections=void 0,this.stopSelection=void 0,this.stopActiveConnection=void 0,this.activeCollectionId=null,this.started=!1}getSnapshot(){return this.snapshot}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}select(e,t={}){let i=this.connect.connection(e);if(!i)throw new s("unknown_collection","This collection is not authorized for this application.");return this.unavailableReason="not_authorized",this.selection.select(e,t),this.refresh(),i}clearSelection(e={}){this.unavailableReason="not_authorized",this.selection.select(null,e),this.refresh()}forget(e){this.transactionDepth+=1;try{let t=this.selection.selectedCollectionId()===e;this.connect.connection(e)?.forget(),t&&this.selection.select(null,{history:"replace"})}finally{this.transactionDepth-=1,this.refresh()}}async authorize(e,t={}){let i=this.selection.selectedCollectionId();if(e==="selected"&&!i)throw new s("collection_not_selected","Choose a collection before updating its access.");let r=typeof e=="object"?e.collectionId:e==="selected"?i:null;this.transactionDepth+=1;try{let a=await this.connect.authorize({...t,operations:this.operations,target:r===null?{kind:"choose"}:{kind:"collection",collectionId:r},returnTo:this.selection.authorizationReturnTo()});return a.kind==="connected"&&this.selection.finishAuthorization(a.returnTo,a.connection.collectionId),a}finally{this.transactionDepth-=1,this.refresh()}}async ensureOperations(e){let t=this.snapshot;if(t.status!=="ready")throw new s("collection_not_ready","Choose an authorized collection first.");let i=k(e),r=t.connection.authorizationCapabilities(i);if(r.sufficient)return{kind:"unchanged",connection:t.connection};this.transactionDepth+=1;try{let a=await this.connect.authorize({operations:k([...r.grantedOperations,...r.missingOperations]),target:{kind:"collection",collectionId:t.collectionId},returnTo:this.selection.authorizationReturnTo()});return a.kind==="connected"&&this.selection.finishAuthorization(a.returnTo,a.connection.collectionId),a}finally{this.transactionDepth-=1,this.refresh()}}handleAuthorizationCallback(e){if(!ee(e))return Promise.reject(new s("invalid_callback","This URL is not an authorization callback."));if(this.callbackPromise)return this.callbackPromise;this.transactionDepth+=1;let t=this.connect.completeAuthorization(e).then(i=>(this.unavailableReason="not_authorized",this.selection.finishAuthorization(i.returnTo,i.connection.collectionId),this.refresh(),i.connection)).catch(i=>{let r=We(i);throw this.selection.clearAuthorizationCallback(r),this.refresh(),i}).finally(()=>{this.transactionDepth-=1,this.refresh(),this.callbackPromise===t&&(this.callbackPromise=null)});return this.callbackPromise=t,t}autoSelectOnlyConnection(){if(this.autoSelect!=="only"||this.selection.selectedCollectionId())return;let e=this.connect.connections();e.length===1&&this.selection.select(e[0].collectionId,{history:"replace"})}refresh(){if(this.transactionDepth>0){this.refreshQueued=!0;return}if(this.refreshing){this.refreshQueued=!0;return}this.refreshing=!0;try{do this.refreshQueued=!1,this.refreshOnce();while(this.refreshQueued)}finally{this.refreshing=!1}}refreshOnce(){let e=this.selection.selectedCollectionId(),t=this.connect.connections(),i=e?this.connect.connection(e):null;i?.collectionId!==this.activeCollectionId&&(this.stopActiveConnection?.(),this.activeCollectionId=i?.collectionId??null,this.stopActiveConnection=i?.onConnectionChange(o=>{!o&&this.selection.selectedCollectionId()===i.collectionId&&(this.unavailableReason="authorization_lost"),this.refresh()}));let r;if(!e)r={status:"unselected",connections:t};else if(!i||!i.info())r={status:"unavailable",collectionId:e,reason:this.connect.unavailableReason(e)??this.unavailableReason,connections:t};else{let o=i.info();r={status:"ready",collectionId:e,connection:i,info:o,access:i.authorizationCapabilities(this.operations),connections:t}}let a=bt(r);if(a!==this.snapshotKey){this.snapshot=r,this.snapshotKey=a;for(let o of this.listeners)o()}}};function bt(n){return n.status==="unselected"?JSON.stringify({status:n.status,connections:n.connections}):n.status==="unavailable"?JSON.stringify({status:n.status,collectionId:n.collectionId,reason:n.reason,connections:n.connections}):JSON.stringify({status:n.status,collectionId:n.collectionId,info:n.info,access:n.access,connections:n.connections})}var ye=class{internals;constructor(e){this.internals=new fe(e)}register(){return this.internals.register()}authorize(e={}){return this.internals.authorize(e)}createSession(e){return new G(this,e)}environment(){return this.internals.environment()}completeAuthorization(e=Be()){return this.internals.completeAuthorization(e)}connections(){return this.internals.connections()}connection(e){return this.internals.connection(e)}unavailableReason(e){return this.internals.unavailableReason(e)}onConnectionsChange(e){return this.internals.onConnectionsChange(e)}forgetAll(){for(let e of this.connections())this.connection(e.collectionId)?.forget()}},fe=class{serverUrl;manifest;manifestSource;redirectUri;storage;relayEncryption;keyStore;directAccessMode;loopbackUrl;navigate;credentialStorage;application=null;completionPromises=new Map;connectionCache=new Map;listeners=new Set;invalidatedConnections=new Map;constructor(e){this.serverUrl=Le(e.serverUrl),this.manifest=e.manifest??$e(),this.manifestSource=typeof this.manifest=="string"?this.manifest:this.manifest.distribution==="portable"?`bundle:${this.manifest.id}:${Ye(this.manifest)}`:`bundle:${this.manifest.id}`;let t=Qe(this.manifest);this.redirectUri=e.redirectUri??(typeof this.manifest!="string"&&this.manifest.distribution==="portable"?"":Ge()),this.storage=e.storage??Je(t),this.relayEncryption=e.relayEncryption??"required",this.keyStore=e.keyStore??(t?new M:new A),this.credentialStorage=e.storage||e.keyStore?"custom":this.storage instanceof T?"memory":"persistent",this.directAccessMode=e.directAccess??"auto",this.loopbackUrl=je(e.loopbackUrl??`http://127.0.0.1:${28485}`),this.navigate=e.navigate,typeof window<"u"&&this.storage===window.localStorage&&window.addEventListener("storage",i=>{i.storageArea!==this.storage||!i.key?.startsWith(this.storagePrefix())||(this.connectionCache.get(vt(i.key))?.notifyStorageChanged(),this.emitConnections())})}environment(){let e=typeof this.manifest!="string"&&this.manifest.distribution==="portable"?"portable":this.application?.distribution??"web";return{distribution:e,applicationOrigin:e==="portable"?"null":this.defaultApplicationOrigin(),credentialStorage:this.credentialStorage}}async register(){if(this.application)return this.application;let e=await fetch(`${this.serverUrl}/v1/apps/register`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({manifest:await this.loadManifest()})}),t=await e.json();if(!e.ok)throw m(t,"discovery_failed","Application discovery failed.",e.status);return this.application=t.application,this.application}async loadManifest(){if(typeof this.manifest!="string")return this.manifest;let e=this.manifest,t;try{t=await fetch(e,{headers:{accept:"application/json"}})}catch(i){throw new s("manifest_load_failed","The bundled application declaration could not be loaded.",{cause:i})}if(!t.ok)throw new s("manifest_load_failed",`The bundled application declaration returned HTTP ${t.status}.`,{status:t.status});try{return await t.json()}catch(i){throw new s("invalid_application_manifest","The bundled application declaration is not valid JSON.",{cause:i})}}async authorize(e={}){if(typeof location>"u"&&!this.navigate&&!e.openVerification)throw new s("browser_required","Authorization navigation requires a browser environment.");let i=typeof this.manifest!="string"&&this.manifest.distribution==="portable"&&!e.openVerification&&typeof window<"u"?window.open(`${this.serverUrl}/device`,"mdbase-connect-authorization","popup,width=620,height=760"):null,r;try{r=await this.register()}catch(y){throw i?.close(),y}if(r.distribution==="portable")return this.authorizePortable(r,e,i);i?.close();let{verifier:a,challenge:o}=await V(),c=R(24),l=e.target?.kind==="collection"?e.target.collectionId:void 0,d=this.relayEncryption==="required"?`grant:${r.id}:${c}`:void 0,u=d?await this.keyStore.create(d):void 0,p={version:1,verifier:a,state:c,clientId:r.id,redirectUri:this.redirectUri,relayEncryption:this.relayEncryption,collectionId:l,returnTo:e.returnTo,keyHandle:d,applicationAgreementPublicKey:u?.agreementPublicKey,applicationSigningPublicKey:u?.signingPublicKey};this.storage.setItem(this.pendingKey(c),JSON.stringify(p));let h=new URL(`${this.serverUrl}/oauth/authorize`);return h.searchParams.set("client_id",r.id),h.searchParams.set("redirect_uri",this.redirectUri),h.searchParams.set("code_challenge",o),h.searchParams.set("code_challenge_method","S256"),h.searchParams.set("state",c),h.searchParams.set("operations",k(e.operations??C).join(",")),l&&h.searchParams.set("collection_id",l),u&&(h.searchParams.set("relay_protocol","1"),h.searchParams.set("application_agreement_public_key",u.agreementPublicKey),h.searchParams.set("application_signing_public_key",u.signingPublicKey)),this.navigate?await this.navigate(h.href):location.assign(h.href),{kind:"redirecting"}}async authorizePortable(e,t,i){if(this.relayEncryption!=="required")throw i?.close(),new s("encryption_required","Downloaded applications require encrypted relay authorization.");let{verifier:r,challenge:a}=await V(),o=`grant:${e.id}:${R(24)}`,c=await this.keyStore.create(o),l,d;try{l=await fetch(`${this.serverUrl}/oauth/device_authorization`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e.id,operations:k(t.operations??C).join(","),...t.target?.kind==="collection"?{collection_id:t.target.collectionId}:{},code_challenge:a,code_challenge_method:"S256",relay_protocol:"1",application_agreement_public_key:c.agreementPublicKey,application_signing_public_key:c.signingPublicKey})}),d=await l.json()}catch(h){throw i?.close(),await this.keyStore.delete(o),new s("device_authorization_failed","Downloaded application authorization could not be started.",{cause:h})}if(!l.ok)throw i?.close(),await this.keyStore.delete(o),m(d,"device_authorization_failed","Downloaded application authorization could not be started.",l.status);let u;try{u=Ve(d)}catch(h){throw i?.close(),await this.keyStore.delete(o),h}if(t.onDeviceCode?.(u),t.openVerification)await t.openVerification(u);else if(i)try{i.location.href=u.verificationUriComplete}catch{}else throw await this.keyStore.delete(o),new s("approval_window_blocked","The approval window was blocked. Show the provided verification link and code, then try again.",{details:u});let p=u.intervalSeconds;try{for(;Date.now()<u.expiresAt;){if(await q(p*1e3,t.signal),t.signal?.aborted)throw new s("authorization_cancelled","Downloaded application authorization was cancelled.");let h;try{h=await fetch(`${this.serverUrl}/oauth/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:d.device_code,client_id:e.id,code_verifier:r}),signal:t.signal})}catch(g){if(t.signal?.aborted)throw new s("authorization_cancelled","Downloaded application authorization was cancelled.",{cause:g});continue}let y=await h.json();if(!h.ok){let g=he(y);if(g==="authorization_pending")continue;if(g==="slow_down"){p+=5;continue}throw m(y,"token_exchange_failed","Downloaded application authorization could not be completed.",h.status)}let v=Y(y.authority,y.collection_id),S=y.encryption&&y.encryption.protocol_version===1&&y.encryption.suite===x&&y.encryption.application_agreement_public_key===c.agreementPublicKey;if(y.application_origin!=="null")throw new s("invalid_token_response","Authorization did not bind the portable grant to its opaque application origin.");if(y.authority&&(!v||y.encryption!=null||y.authority.proof_public_key!==c.signingPublicKey))throw new s("invalid_token_response","Authorization returned a remote authority capability that is not bound to this portable grant key.");if(!y.authority&&!S)throw new s("encryption_required","Authorization did not establish the expected key-bound local portable grant.");let b=this.storeTokenResponse(y,e.id,o);if(t.target?.kind==="collection"&&t.target.collectionId!==b.collectionId)throw this.removeToken(b.collectionId,b.keyHandle),new s("collection_mismatch","The approved collection does not match the collection requested by this link.");return i?.close(),{kind:"connected",connection:this.connection(b.collectionId),...t.returnTo?{returnTo:t.returnTo}:{}}}throw new s("expired_token","The downloaded application authorization code expired.")}catch(h){throw i?.close(),await this.keyStore.delete(o),h}}completeAuthorization(e){let t=new URL(e).searchParams.get("state");if(!t)return Promise.reject(new s("invalid_callback","Authorization callback is missing its state."));let i=this.completionPromises.get(t);if(i)return i;let a=this.performAuthorizationCompletion(e,t).finally(()=>{this.completionPromises.get(t)===a&&this.completionPromises.delete(t)});return this.completionPromises.set(t,a),a}async performAuthorizationCompletion(e,t){let i=new URL(e),r=i.searchParams.get("code"),a=this.pendingKey(t),o=w(this.storage.getItem(a));if(!o||o.version!==1||t!==o.state)throw new s("invalid_callback","Authorization callback is missing or does not match this browser session.");if(i.searchParams.has("error"))throw o.keyHandle&&await this.keyStore.delete(o.keyHandle),this.storage.removeItem(a),new s(i.searchParams.get("error")??"access_denied",i.searchParams.get("error_description")??"Collection access was not approved.",{details:o.returnTo?{returnTo:o.returnTo}:void 0});if(!r)throw new s("invalid_callback","Authorization callback is missing its code.");let c=await fetch(`${this.serverUrl}/oauth/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:r,client_id:o.clientId,redirect_uri:o.redirectUri,code_verifier:o.verifier})}),l=await c.json();if(!c.ok)throw m(l,"token_exchange_failed","Authorization could not be completed.",c.status);if(o.relayEncryption==="required"&&!l.authority&&(!l.encryption||!o.keyHandle||l.encryption.application_agreement_public_key!==o.applicationAgreementPublicKey))throw o.keyHandle&&await this.keyStore.delete(o.keyHandle),this.storage.removeItem(a),new s("encryption_required","Authorization did not establish the required encrypted relay grant.");if(l.authority?.proof_public_key){if(!o.keyHandle||!o.applicationSigningPublicKey||l.authority.proof_public_key!==o.applicationSigningPublicKey)throw o.keyHandle&&await this.keyStore.delete(o.keyHandle),this.storage.removeItem(a),new s("invalid_token_response","Authorization returned a remote authority capability bound to another application key.")}else l.authority&&o.keyHandle&&await this.keyStore.delete(o.keyHandle);let d=this.storeTokenResponse(l,o.clientId,l.authority?.proof_public_key?o.keyHandle:l.authority?void 0:o.keyHandle);if(o.collectionId&&o.collectionId!==d.collectionId)throw this.removeToken(d.collectionId,d.keyHandle),this.storage.removeItem(a),new s("collection_mismatch","The approved collection does not match the collection requested by this link.");return this.storage.removeItem(a),{connection:this.connection(d.collectionId),...o.returnTo?{returnTo:o.returnTo}:{}}}connections(){let e=[];for(let t of this.connectionIds()){let i=this.connection(t)?.info();i&&e.push(i)}return e.sort((t,i)=>t.displayName.localeCompare(i.displayName)||t.collectionId.localeCompare(i.collectionId))}connection(e){if(!this.storage.getItem(this.tokenKey(e)))return null;let t=this.connectionCache.get(e);return t||(t=new L(this,e),this.connectionCache.set(e,t)),t.info()?t:null}unavailableReason(e){return this.invalidatedConnections.get(e)??null}onConnectionsChange(e){return this.listeners.add(e),e(this.connections()),()=>this.listeners.delete(e)}storeTokenResponse(e,t,i){let r=e.collection_id;if(typeof r!="string")throw new s("invalid_token_response","Authorization returned no collection ID.");let a=W(e.scope);if(!a)throw new s("invalid_token_response","Authorization returned no valid collection scope.");if(e.authority&&!Y(e.authority,r))throw new s("invalid_token_response","Authorization returned an invalid remote authority capability.");if(e.authority&&e.encryption)throw new s("invalid_token_response","Authorization returned conflicting collection transports.");if(e.encryption){try{K(e.encryption)}catch{throw new s("invalid_token_response","Authorization returned an invalid encrypted relay binding.")}if(e.encryption.collection_id!==r||typeof e.grant_id!="string"||e.grant_id.length===0)throw new s("invalid_token_response","Authorization returned an encrypted relay binding for another grant.")}let o=w(this.storage.getItem(this.tokenKey(r)));if(o?.encryption&&e.encryption&&o.keyHandle&&o.keyHandle===i&&(o.grantId!==e.grant_id||o.encryption.connector_id!==e.encryption.connector_id||o.encryption.connector_agreement_public_key!==e.encryption.connector_agreement_public_key||o.encryption.application_agreement_public_key!==e.encryption.application_agreement_public_key))throw new s("connector_identity_changed","The connector identity changed during authorization renewal. Reauthorize before sending collection data.",{requiresAuthorization:!0,recovery:"reauthorize"});o?.keyHandle&&o.keyHandle!==i&&this.keyStore.delete(o.keyHandle).catch(()=>{});let c={version:1,accessToken:e.access_token,refreshToken:e.refresh_token,clientId:t,collectionId:r,collectionName:e.collection_name??`Collection ${r.slice(0,8)}`,operations:e.operations,scope:a,expiresAt:Date.now()+e.expires_in*1e3,refreshExpiresAt:e.refresh_expires_in?Date.now()+e.refresh_expires_in*1e3:void 0,grantId:e.grant_id,encryption:e.encryption??void 0,applicationOrigin:e.application_origin??this.defaultApplicationOrigin(),keyHandle:i,savedAt:Date.now(),authority:e.authority?{operationsUrl:e.authority.operations_url,syncUrl:e.authority.sync_url,replicaId:e.authority.replica_id,accessToken:e.authority.access_token,proofPublicKey:e.authority.proof_public_key}:void 0};return this.storage.setItem(this.tokenKey(r),JSON.stringify(c)),this.addConnectionId(r),this.invalidatedConnections.delete(r),this.connectionCache.delete(r),this.emitConnections(),c}removeToken(e,t,i="authorization_lost"){this.invalidatedConnections.set(e,i),t&&this.keyStore.delete(t).catch(()=>{}),this.storage.removeItem(this.tokenKey(e)),this.storage.removeItem(this.pendingMutationKey(e));for(let r of["web_push","fcm"])this.storage.removeItem(this.notificationKey(e,r));this.storage.setItem(this.connectionsKey(),JSON.stringify({version:1,collectionIds:this.connectionIds().filter(r=>r!==e)})),this.connectionCache.delete(e),this.emitConnections()}tokenKey(e){return`${this.storagePrefix()}:token:${e}`}pendingMutationKey(e){return`${this.storagePrefix()}:pending-mutation:${e}`}notificationKey(e,t="web_push"){return`${this.storagePrefix()}:notifications:${e}:${t}`}directPreferenceKey(){return`mdbase-connect:direct:${this.defaultApplicationOrigin()}`}defaultApplicationOrigin(){if(typeof this.manifest!="string"&&this.manifest.distribution==="portable"||this.application?.distribution==="portable")return"null";let e=new URL(this.redirectUri);if(["http:","https:"].includes(e.protocol))return e.origin;if(typeof location<"u")return location.origin;if(this.manifest&&typeof this.manifest!="string")return new URL(this.manifest.homepage).origin;try{return new URL(this.manifestSource).origin}catch{return""}}pendingKey(e){return`${this.storagePrefix()}:pending:${e}`}storagePrefix(){return`mdbase-connect:${this.serverUrl}:${this.manifestSource}`}connectionsKey(){return`${this.storagePrefix()}:connections`}connectionIds(){let e=w(this.storage.getItem(this.connectionsKey()));return e?.version===1&&Array.isArray(e.collectionIds)&&e.collectionIds.every(t=>typeof t=="string")?e.collectionIds:[]}addConnectionId(e){this.storage.setItem(this.connectionsKey(),JSON.stringify({version:1,collectionIds:[...new Set([...this.connectionIds(),e])]}))}emitConnections(){let e=this.connections();for(let t of this.listeners)t(e)}};function vt(n){let e=":token:",t=n.lastIndexOf(e);return t<0?"":n.slice(t+e.length)}function Ze(n){if(!n||typeof n!="object")throw new s("invalid_push_payload","The push payload is not an object.");let e=n;if(e.type!=="mdbase.notification"||e.version!==1||typeof e.signal_id!="string"||typeof e.criterion_id!="string"||typeof e.cursor!="string"||!e.presentation||typeof e.presentation.title!="string")throw new s("invalid_push_payload","The push payload is not an mdbase notification.");return e}function _t(n){if(!n||typeof n!="object")throw new s("invalid_push_payload","The native notification data is not an object.");let e=n;if(e.type!=="mdbase.notification"||e.version!==1&&e.version!=="1"||typeof e.signal_id!="string"||typeof e.criterion_id!="string"||typeof e.cursor!="string")throw new s("invalid_push_payload","The native notification data is not an mdbase notification.");return{type:"mdbase.notification",version:1,signal_id:e.signal_id,criterion_id:e.criterion_id,cursor:e.cursor}}function kt(n,e){let t=Ze(e);return n.showNotification(t.presentation.title,{...t.presentation.body?{body:t.presentation.body}:{},...t.presentation.tag?{tag:t.presentation.tag}:{},data:{type:t.type,signal_id:t.signal_id,criterion_id:t.criterion_id,cursor:t.cursor}})}var ge=class{collectionParameter;fallbackPath;listeners=new Set;handlePopState=()=>this.emit();constructor(e={}){this.collectionParameter=e.collectionParameter??"collection",this.fallbackPath=e.fallbackPath??"/"}selectedCollectionId(){return this.currentUrl().searchParams.get(this.collectionParameter)}select(e,t={}){let i=$(this.currentUrl());e?i.searchParams.set(this.collectionParameter,e):i.searchParams.delete(this.collectionParameter);let r=this.browserHistory();r[t.history==="push"?"pushState":"replaceState"](r.state,"",i),this.emit()}authorizationReturnTo(){let e=$(this.currentUrl());return`${e.pathname}${e.search}${e.hash}`}authorizationCallback(){let e=this.currentUrl().href;return ee(e)?e:null}finishAuthorization(e,t){let i=this.safeAppUrl(e??this.fallbackPath);$(i),i.searchParams.set(this.collectionParameter,t),this.browserHistory().replaceState(null,"",i),this.emit()}clearAuthorizationCallback(e){let t=e?this.safeAppUrl(e):this.currentUrl(),i=this.browserHistory();i.replaceState(i.state,"",$(t)),this.emit()}subscribe(e){let t=this.listeners.size===0;return this.listeners.add(e),t&&typeof window<"u"&&window.addEventListener("popstate",this.handlePopState),()=>{this.listeners.delete(e),this.listeners.size===0&&typeof window<"u"&&window.removeEventListener("popstate",this.handlePopState)}}emit(){for(let e of this.listeners)e()}safeAppUrl(e){let t=this.currentUrl(),i=new URL(e,t.origin);return i.origin===t.origin?i:new URL(this.fallbackPath,t.origin)}currentUrl(){if(typeof location>"u")throw new s("browser_required","Browser selection requires a browser environment.");return new URL(location.href)}browserHistory(){if(typeof history>"u")throw new s("browser_required","Browser selection requires a browser environment.");return history}},me=class{collectionId=null;listeners=new Set;selectedCollectionId(){return this.collectionId}select(e){if(e!==this.collectionId){this.collectionId=e;for(let t of this.listeners)t()}}authorizationReturnTo(){}authorizationCallback(){return null}finishAuthorization(e,t){this.select(t)}clearAuthorizationCallback(){}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}};return rt(St);})();
@@ -0,0 +1 @@
1
+ sha384-u+z1WOpeMWPwuYV9kDMHHAqQEZKGn+NwX9tjAYtNztyMD7WJbsdj+Be++i43R9nY
@@ -0,0 +1,57 @@
1
+ import type { CollectionChange, CollectionChangesPage, CollectionDescription, CollectionOperation, CollectionTypeDocument, CreateViewSourceInput, DeleteViewSourceInput, DeleteViewSourceResult, ExecuteViewInput, JsonObject, MdbaseOperationEnvelope, ReadViewSourceInput, RecordDocument, SavedViewExecution, SavedViewList, SavedViewSourceDocument, TypePackInstallResult, TypePackProvision, UpdateViewSourceInput } from "@mdbase-dev/connect-protocol";
2
+ import type { ChangesInput, CreateInput, CreateTypeInput, DeleteInput, DeletePreflightResult, DeleteResult, MdbaseCollectionTransport, MdbaseDesiredTimer, MdbaseTimer, MdbaseTimerList, MdbaseTimerReconciliation, OperationRequestOptions, QueryInput, QueryPage, QueryPagesOptions, QueryResult, ReadInput, ReadTypeInput, RenameInput, RenamePreflightResult, RenameResult, UpdateInput, UpdateTypeInput, WatchOptions } from "./operation-types.js";
3
+ /**
4
+ * Typed collection operations independent of OAuth, HTTP, or storage.
5
+ *
6
+ * Application code can use this surface against Connect, the developer
7
+ * sandbox, or another provider without changing its record logic.
8
+ */
9
+ export declare class MdbaseCollectionClient<Frontmatter extends JsonObject = JsonObject> {
10
+ private readonly transport;
11
+ constructor(transport: MdbaseCollectionTransport);
12
+ operation<Result>(operation: CollectionOperation, input: unknown, options?: OperationRequestOptions): Promise<Result>;
13
+ describe(): Promise<CollectionDescription>;
14
+ changes(input?: ChangesInput, options?: OperationRequestOptions): Promise<CollectionChangesPage>;
15
+ read(input: ReadInput): Promise<MdbaseOperationEnvelope<RecordDocument<Frontmatter>>>;
16
+ query(input?: QueryInput, options?: OperationRequestOptions): Promise<MdbaseOperationEnvelope<QueryResult<Frontmatter>>>;
17
+ queryPages(input?: QueryInput, options?: QueryPagesOptions<Frontmatter>): AsyncGenerator<QueryPage<Frontmatter>>;
18
+ queryAll(input?: QueryInput, options?: QueryPagesOptions<Frontmatter>): Promise<QueryResult<Frontmatter>>;
19
+ listViews(): Promise<MdbaseOperationEnvelope<SavedViewList>>;
20
+ executeView(input: ExecuteViewInput): Promise<MdbaseOperationEnvelope<SavedViewExecution<Frontmatter>>>;
21
+ readViewSource(input: ReadViewSourceInput): Promise<MdbaseOperationEnvelope<SavedViewSourceDocument>>;
22
+ createViewSource(input: CreateViewSourceInput): Promise<MdbaseOperationEnvelope<SavedViewSourceDocument>>;
23
+ updateViewSource(input: UpdateViewSourceInput): Promise<MdbaseOperationEnvelope<SavedViewSourceDocument>>;
24
+ deleteViewSource(input: DeleteViewSourceInput): Promise<MdbaseOperationEnvelope<DeleteViewSourceResult>>;
25
+ create(input: CreateInput<Frontmatter>): Promise<MdbaseOperationEnvelope<RecordDocument<Frontmatter>>>;
26
+ update(input: UpdateInput<Frontmatter>): Promise<MdbaseOperationEnvelope<RecordDocument<Frontmatter>>>;
27
+ delete(input: DeleteInput, options?: OperationRequestOptions): Promise<MdbaseOperationEnvelope<DeleteResult>>;
28
+ preflightDelete(input: DeleteInput, options?: OperationRequestOptions): Promise<MdbaseOperationEnvelope<DeletePreflightResult>>;
29
+ rename(input: RenameInput, options?: OperationRequestOptions): Promise<MdbaseOperationEnvelope<RenameResult>>;
30
+ preflightRename(input: RenameInput, options?: OperationRequestOptions): Promise<MdbaseOperationEnvelope<RenamePreflightResult>>;
31
+ validate(input?: JsonObject): Promise<MdbaseOperationEnvelope>;
32
+ readType(input: ReadTypeInput): Promise<MdbaseOperationEnvelope<CollectionTypeDocument>>;
33
+ createType(input: CreateTypeInput): Promise<MdbaseOperationEnvelope<CollectionTypeDocument>>;
34
+ updateType(input: UpdateTypeInput): Promise<MdbaseOperationEnvelope<CollectionTypeDocument>>;
35
+ installTypePack(input: TypePackProvision): Promise<MdbaseOperationEnvelope<TypePackInstallResult>>;
36
+ listTimers(namespace: string): Promise<MdbaseTimerList>;
37
+ putTimer(input: {
38
+ namespace: string;
39
+ criterion_id: string;
40
+ timer: MdbaseDesiredTimer;
41
+ }): Promise<MdbaseTimer>;
42
+ cancelTimer(input: {
43
+ namespace: string;
44
+ id: string;
45
+ generation?: number;
46
+ }): Promise<{
47
+ namespace: string;
48
+ id: string;
49
+ cancelled: boolean;
50
+ }>;
51
+ reconcileTimers(input: {
52
+ namespace: string;
53
+ criterion_id: string;
54
+ timers: MdbaseDesiredTimer[];
55
+ }): Promise<MdbaseTimerReconciliation>;
56
+ watch(options?: WatchOptions): AsyncGenerator<CollectionChange>;
57
+ }
@@ -0,0 +1,214 @@
1
+ import { abortableDelay } from "./async.js";
2
+ import { MdbaseConnectError, isRetryableConnectError, unwrapOperation } from "./errors.js";
3
+ /**
4
+ * Typed collection operations independent of OAuth, HTTP, or storage.
5
+ *
6
+ * Application code can use this surface against Connect, the developer
7
+ * sandbox, or another provider without changing its record logic.
8
+ */
9
+ export class MdbaseCollectionClient {
10
+ transport;
11
+ constructor(transport) {
12
+ this.transport = transport;
13
+ }
14
+ operation(operation, input, options) {
15
+ return this.transport.operation(operation, input, options);
16
+ }
17
+ describe() {
18
+ return this.operation("describe", {});
19
+ }
20
+ changes(input = {}, options) {
21
+ return this.operation("changes", input, options);
22
+ }
23
+ read(input) {
24
+ return this.operation("read", input);
25
+ }
26
+ query(input = {}, options) {
27
+ return this.operation("query", input, options);
28
+ }
29
+ async *queryPages(input = {}, options = {}) {
30
+ const { offset: requestedOffset, limit: requestedLimit, snapshot: requestedSnapshot, ...criteria } = input;
31
+ let offset = nonNegativeInteger(requestedOffset, 0);
32
+ const firstPageSize = positiveInteger(options.firstPageSize ?? requestedLimit, 200);
33
+ const pageSize = positiveInteger(options.pageSize ?? requestedLimit, 1_000);
34
+ let snapshot = requestedSnapshot;
35
+ let loaded = 0;
36
+ let pageNumber = 0;
37
+ while (!options.signal?.aborted) {
38
+ const result = unwrapOperation(await this.query({
39
+ ...criteria,
40
+ offset,
41
+ limit: pageNumber === 0 ? firstPageSize : pageSize,
42
+ ...(snapshot ? { snapshot } : {})
43
+ }, { signal: options.signal }));
44
+ const returnedSnapshot = result.meta?.snapshot;
45
+ if (snapshot && returnedSnapshot && snapshot !== returnedSnapshot) {
46
+ throw new MdbaseConnectError("query_snapshot_changed", "The collection query snapshot changed while paging. Refresh the query before continuing.", { recovery: "refresh" });
47
+ }
48
+ if (!snapshot && returnedSnapshot)
49
+ snapshot = returnedSnapshot;
50
+ loaded += result.results.length;
51
+ const complete = !result.meta?.has_more || result.results.length === 0;
52
+ const page = {
53
+ results: result.results,
54
+ ...(result.meta ? { meta: result.meta } : {}),
55
+ page: pageNumber,
56
+ offset,
57
+ loaded,
58
+ complete,
59
+ ...(snapshot ? { snapshot } : {})
60
+ };
61
+ options.onProgress?.(page);
62
+ yield page;
63
+ if (complete)
64
+ return;
65
+ offset += result.results.length;
66
+ pageNumber += 1;
67
+ }
68
+ }
69
+ async queryAll(input = {}, options = {}) {
70
+ const results = [];
71
+ let finalPage;
72
+ for await (const page of this.queryPages(input, options)) {
73
+ results.push(...page.results);
74
+ finalPage = page;
75
+ }
76
+ return {
77
+ results,
78
+ meta: {
79
+ ...(finalPage?.meta ?? {}),
80
+ total_count: finalPage?.meta?.total_count ?? results.length,
81
+ has_more: finalPage ? !finalPage.complete : false,
82
+ ...(finalPage?.snapshot ? { snapshot: finalPage.snapshot } : {})
83
+ }
84
+ };
85
+ }
86
+ listViews() {
87
+ return this.operation("list_views", {});
88
+ }
89
+ executeView(input) {
90
+ return this.operation("execute_view", input);
91
+ }
92
+ readViewSource(input) {
93
+ return this.operation("read_view_source", input);
94
+ }
95
+ createViewSource(input) {
96
+ return this.operation("create_view_source", input);
97
+ }
98
+ updateViewSource(input) {
99
+ return this.operation("update_view_source", input);
100
+ }
101
+ deleteViewSource(input) {
102
+ return this.operation("delete_view_source", input);
103
+ }
104
+ create(input) {
105
+ return this.operation("create", input);
106
+ }
107
+ update(input) {
108
+ return this.operation("update", input);
109
+ }
110
+ delete(input, options) {
111
+ return this.operation("delete", input, options);
112
+ }
113
+ preflightDelete(input, options) {
114
+ return this.operation("delete", { ...input, check_backlinks: true, dry_run: true }, options);
115
+ }
116
+ rename(input, options) {
117
+ return this.operation("rename", input, options);
118
+ }
119
+ preflightRename(input, options) {
120
+ return this.operation("rename", { ...input, dry_run: true }, options);
121
+ }
122
+ validate(input = {}) {
123
+ return this.operation("validate", input);
124
+ }
125
+ readType(input) {
126
+ return this.operation("read_type", input);
127
+ }
128
+ createType(input) {
129
+ return this.operation("create_type", input);
130
+ }
131
+ updateType(input) {
132
+ return this.operation("update_type", input);
133
+ }
134
+ installTypePack(input) {
135
+ return this.operation("install_type_pack", input);
136
+ }
137
+ listTimers(namespace) {
138
+ return this.operation("list_timers", { namespace });
139
+ }
140
+ putTimer(input) {
141
+ return this.operation("put_timer", input);
142
+ }
143
+ cancelTimer(input) {
144
+ return this.operation("cancel_timer", input);
145
+ }
146
+ reconcileTimers(input) {
147
+ return this.operation("reconcile_timers", input);
148
+ }
149
+ async *watch(options = {}) {
150
+ let cursor = options.cursor;
151
+ const pollInterval = Math.max(100, options.pollIntervalMs ?? 1_000);
152
+ const retry = watchRetryPolicy(options.retry);
153
+ let failures = 0;
154
+ let connected = false;
155
+ options.onStatus?.({ state: "connecting", ...(cursor === undefined ? {} : { cursor }) });
156
+ while (!options.signal?.aborted) {
157
+ try {
158
+ if (cursor === undefined)
159
+ cursor = (await this.changes({}, { signal: options.signal })).cursor;
160
+ const page = await this.changes({ after: cursor, limit: 200 }, { signal: options.signal });
161
+ if (page.reset) {
162
+ const error = new MdbaseConnectError("change_cursor_reset", "The collection change cursor expired. Refresh collection state before subscribing again.");
163
+ options.onStatus?.({ state: "reset_required", cursor, error });
164
+ throw error;
165
+ }
166
+ const recovered = failures > 0;
167
+ failures = 0;
168
+ if (!connected || recovered)
169
+ options.onStatus?.({ state: "connected", cursor, recovered });
170
+ connected = true;
171
+ for (const event of page.events)
172
+ yield event;
173
+ cursor = page.cursor;
174
+ if (!page.has_more)
175
+ await abortableDelay(pollInterval, options.signal);
176
+ }
177
+ catch (error) {
178
+ if (options.signal?.aborted)
179
+ return;
180
+ if (!retry || !isRetryableConnectError(error))
181
+ throw error;
182
+ connected = false;
183
+ failures += 1;
184
+ if (retry.maxAttempts !== undefined && failures > retry.maxAttempts)
185
+ throw error;
186
+ const retryInMs = Math.min(retry.maxDelayMs, Math.round(retry.initialDelayMs * retry.multiplier ** (failures - 1)));
187
+ options.onStatus?.({
188
+ state: "reconnecting",
189
+ ...(cursor === undefined ? {} : { cursor }),
190
+ attempt: failures,
191
+ retryInMs,
192
+ error
193
+ });
194
+ await abortableDelay(retryInMs, options.signal);
195
+ }
196
+ }
197
+ }
198
+ }
199
+ function watchRetryPolicy(options) {
200
+ if (options === false)
201
+ return undefined;
202
+ return {
203
+ initialDelayMs: Math.max(0, options?.initialDelayMs ?? 500),
204
+ maxDelayMs: Math.max(0, options?.maxDelayMs ?? 15_000),
205
+ multiplier: Math.max(1, options?.multiplier ?? 2),
206
+ ...(options?.maxAttempts === undefined ? {} : { maxAttempts: Math.max(0, options.maxAttempts) })
207
+ };
208
+ }
209
+ function nonNegativeInteger(value, fallback) {
210
+ return typeof value === "number" && Number.isFinite(value) ? Math.max(0, Math.floor(value)) : fallback;
211
+ }
212
+ function positiveInteger(value, fallback) {
213
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : fallback;
214
+ }
@@ -0,0 +1,39 @@
1
+ import type { JsonObject, MdbaseAppManifest } from "@mdbase-dev/connect-protocol";
2
+ import { MdbaseConnection, type MdbaseAuthorizationOutcome, type MdbaseAuthorizationResult, type MdbaseAuthorizeOptions, type MdbaseConnectEnvironment } from "./connection.js";
3
+ import type { MdbaseConnectionInfo } from "./connection-types.js";
4
+ import { type GrantKeyStore } from "./crypto.js";
5
+ import { type Application } from "./internal-types.js";
6
+ import { MdbaseSession, type MdbaseSessionOptions, type MdbaseUnavailableReason } from "./session.js";
7
+ export interface MdbaseConnectOptions {
8
+ serverUrl: string;
9
+ /**
10
+ * A bundled v1 application manifest or its app-local URL. String values
11
+ * are loaded by this SDK and posted inline; Connect never fetches them.
12
+ */
13
+ manifest?: MdbaseAppManifest | string;
14
+ redirectUri?: string;
15
+ storage?: Storage;
16
+ /** Encrypted relay is required by default for newly authorized grants. */
17
+ relayEncryption?: "required" | "disabled";
18
+ keyStore?: GrantKeyStore;
19
+ /** Prefer same-computer connector access when the browser permits it. */
20
+ directAccess?: "auto" | "disabled";
21
+ /** Loopback origin override for development and automated testing. */
22
+ loopbackUrl?: string;
23
+ /** Override browser navigation, for example to use a native system browser. */
24
+ navigate?: (url: string) => void | Promise<void>;
25
+ }
26
+ export declare class MdbaseConnect<Frontmatter extends JsonObject = JsonObject> {
27
+ private readonly internals;
28
+ constructor(options: MdbaseConnectOptions);
29
+ register(): Promise<Application>;
30
+ authorize(options?: MdbaseAuthorizeOptions): Promise<MdbaseAuthorizationOutcome<Frontmatter>>;
31
+ createSession(options: MdbaseSessionOptions): MdbaseSession<Frontmatter>;
32
+ environment(): MdbaseConnectEnvironment;
33
+ completeAuthorization(callbackUrl?: string): Promise<MdbaseAuthorizationResult<Frontmatter>>;
34
+ connections(): MdbaseConnectionInfo[];
35
+ connection(collectionId: string): MdbaseConnection<Frontmatter> | null;
36
+ unavailableReason(collectionId: string): MdbaseUnavailableReason | null;
37
+ onConnectionsChange(listener: (connections: MdbaseConnectionInfo[]) => void): () => void;
38
+ forgetAll(): void;
39
+ }