@mdbase-dev/connect 0.1.0-beta.31 → 0.1.0-beta.32

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 (64) hide show
  1. package/README.md +75 -19
  2. package/dist/advanced.d.ts +7 -0
  3. package/dist/advanced.js +4 -0
  4. package/dist/application-session.d.ts +10 -5
  5. package/dist/application-session.js +32 -16
  6. package/dist/async.js +11 -5
  7. package/dist/authority-proof.d.ts +3 -0
  8. package/dist/authority-proof.js +24 -0
  9. package/dist/browser/integrity.json +1 -1
  10. package/dist/browser/mdbase-connect.min.js +3 -3
  11. package/dist/browser/mdbase-connect.min.js.sha384 +1 -1
  12. package/dist/browser.d.ts +3 -0
  13. package/dist/browser.js +5 -0
  14. package/dist/capabilities.js +2 -1
  15. package/dist/collection-client.d.ts +28 -28
  16. package/dist/collection-client.js +42 -42
  17. package/dist/connect-options.d.ts +12 -4
  18. package/dist/connect.d.ts +12 -4
  19. package/dist/connect.js +105 -104
  20. package/dist/connection-file-transport.d.ts +2 -2
  21. package/dist/connection-file-transport.js +4 -4
  22. package/dist/connection-notifications.d.ts +10 -4
  23. package/dist/connection-notifications.js +41 -23
  24. package/dist/connection-transport.d.ts +19 -15
  25. package/dist/connection-transport.js +202 -202
  26. package/dist/connection-types.d.ts +5 -4
  27. package/dist/connection.d.ts +43 -43
  28. package/dist/connection.js +221 -77
  29. package/dist/crypto-entry.d.ts +4 -0
  30. package/dist/crypto-entry.js +4 -0
  31. package/dist/crypto.js +4 -4
  32. package/dist/external-store.d.ts +10 -0
  33. package/dist/external-store.js +10 -0
  34. package/dist/file-transfer-internals.d.ts +22 -0
  35. package/dist/file-transfer-internals.js +186 -0
  36. package/dist/files.d.ts +16 -12
  37. package/dist/files.js +52 -206
  38. package/dist/hosted-file-request.js +3 -3
  39. package/dist/index.d.ts +2 -5
  40. package/dist/index.js +1 -5
  41. package/dist/internal-types.d.ts +8 -1
  42. package/dist/local-file-transport.d.ts +2 -2
  43. package/dist/local-file-transport.js +13 -13
  44. package/dist/mdbase-connect.d.ts +6 -4
  45. package/dist/mdbase-connect.js +9 -8
  46. package/dist/notifications.d.ts +3 -2
  47. package/dist/operation-helpers.d.ts +3 -3
  48. package/dist/operation-helpers.js +12 -29
  49. package/dist/operation-types.d.ts +33 -8
  50. package/dist/outcomes.d.ts +15 -15
  51. package/dist/outcomes.js +13 -1
  52. package/dist/pending-mutation-store.d.ts +13 -0
  53. package/dist/pending-mutation-store.js +64 -0
  54. package/dist/request-budget.d.ts +27 -0
  55. package/dist/request-budget.js +95 -0
  56. package/dist/runtime-utils.d.ts +2 -0
  57. package/dist/runtime-utils.js +19 -0
  58. package/dist/session.d.ts +4 -3
  59. package/dist/session.js +4 -4
  60. package/dist/stored-token.d.ts +10 -0
  61. package/dist/stored-token.js +60 -0
  62. package/dist/token-response.d.ts +11 -0
  63. package/dist/token-response.js +77 -0
  64. package/package.json +12 -2
@@ -1,3 +1,3 @@
1
- "use strict";var MdbaseConnect=(()=>{var yt=Object.defineProperty;var un=Object.getOwnPropertyDescriptor;var pn=Object.getOwnPropertyNames;var hn=Object.prototype.hasOwnProperty;var fn=(i,e)=>{for(var t in e)yt(i,t,{get:e[t],enumerable:!0})},yn=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of pn(e))!hn.call(i,o)&&o!==t&&yt(i,o,{get:()=>e[o],enumerable:!(n=un(e,o))||n.enumerable});return i};var mn=i=>yn(yt({},"__esModule",{value:!0}),i);var Bo={};fn(Bo,{ALL_CONNECT_PROBLEM_CODES:()=>It,AUTHORIZATION_PROBLEM_CODES:()=>X,ApplicationIdentityStoreError:()=>Q,COLLECTION_CHANGES_PROBLEM_CODES:()=>Et,COLLECTION_DESCRIPTION_PROBLEM_CODES:()=>Re,COLLECTION_MUTATION_PROBLEM_CODES:()=>E,COLLECTION_QUERY_PROBLEM_CODES:()=>xt,COLLECTION_READ_PROBLEM_CODES:()=>q,COLLECTION_SETUP_PROBLEM_CODES:()=>Ai,COLLECTION_TYPE_PROBLEM_CODES:()=>W,COMMON_OPERATION_PROBLEM_CODES:()=>Pi,ConnectOutcomeError:()=>Xe,DIRECT_ACCESS_PROBLEM_CODES:()=>We,FileTransferCryptoError:()=>B,GrantFileTransferCipher:()=>ce,IndexedDbApplicationIdentityStore:()=>de,IndexedDbGrantKeyStore:()=>re,MdbaseApplicationSession:()=>xe,MdbaseBrowserSelection:()=>jt,MdbaseCollectionClient:()=>Me,MdbaseConnect:()=>Kt,MdbaseConnectError:()=>C,MdbaseConnection:()=>qe,MdbaseFileClient:()=>Fe,MdbaseMemorySelection:()=>Ht,MdbaseMemoryVerificationStore:()=>it,MemoryApplicationIdentityStore:()=>ue,MemoryGrantKeyStore:()=>ae,NOTIFICATION_PROBLEM_CODES:()=>he,REGISTRATION_PROBLEM_CODES:()=>$,RelayCryptoError:()=>v,SESSION_PROBLEM_CODES:()=>ro,applicationInstallationId:()=>pe,authorizationSigningMessage:()=>Ge,captureConnectOutcome:()=>k,connectError:()=>l,connectFailure:()=>A,connectProblem:()=>R,connectSuccess:()=>O,createPkce:()=>ze,decryptRelayResponse:()=>se,effectiveCapabilities:()=>Rt,encryptRelayRequest:()=>Y,isRetryableConnectError:()=>no,operationProblem:()=>Tt,parseMdbaseNativeNotificationData:()=>Lo,parseMdbasePushPayload:()=>ln,serverConnectError:()=>D,showMdbasePushNotification:()=>No,signApplicationAuthorization:()=>ke,unknownConnectProblem:()=>Ot,unwrapConnectOutcome:()=>ao});var V={access_denied:{category:"authorization",recovery:"reauthorize"},access_paused:{category:"availability",recovery:"resume_connector_access"},application_identity_unavailable:{category:"compatibility",recovery:"upgrade_application"},approval_window_blocked:{category:"authorization",recovery:"reauthorize"},authority_authorization_changed:{category:"authorization",recovery:"reauthorize"},authorization_cancelled:{category:"cancellation",recovery:"none"},authorization_expired:{category:"authorization",recovery:"reauthorize"},authorization_replayed:{category:"integrity",recovery:"reauthorize"},browser_required:{category:"compatibility",recovery:"none"},callback_url_required:{category:"validation",recovery:"fix_request"},change_cursor_reset:{category:"conflict",recovery:"refresh"},collection_access_denied:{category:"authorization",recovery:"reauthorize"},collection_configuration_invalid:{category:"validation",recovery:"repair_collection"},collection_contracts_missing:{category:"compatibility",recovery:"choose_collection"},collection_incompatible:{category:"compatibility",recovery:"choose_collection"},collection_invalid:{category:"validation",recovery:"repair_collection"},collection_kind_unsupported:{category:"compatibility",recovery:"choose_collection"},collection_mismatch:{category:"selection",recovery:"choose_collection"},collection_not_found:{category:"selection",recovery:"choose_collection"},collection_not_ready:{category:"selection",recovery:"choose_collection"},collection_not_selected:{category:"selection",recovery:"choose_collection"},collection_type_registry_invalid:{category:"validation",recovery:"repair_collection"},collection_version_unsupported:{category:"compatibility",recovery:"upgrade_collection"},concurrent_modification:{category:"conflict",recovery:"refresh"},connector_identity_changed:{category:"integrity",recovery:"reauthorize"},connector_offline:{category:"availability",recovery:"retry"},connector_upgrade_required:{category:"compatibility",recovery:"upgrade_connector"},device_authorization_failed:{category:"authorization",recovery:"reauthorize"},direct_operation_rejected:{category:"authorization",recovery:"reauthorize"},discovery_failed:{category:"availability",recovery:"retry"},encrypted_relay_rejected:{category:"authorization",recovery:"reauthorize"},encryption_required:{category:"authorization",recovery:"reauthorize"},expired_token:{category:"authorization",recovery:"reauthorize"},file_changed_during_move:{category:"conflict",recovery:"refresh"},file_changed_during_read:{category:"conflict",recovery:"refresh"},file_move_failed:{category:"internal",recovery:"contact_support"},file_mutation_conflict:{category:"conflict",recovery:"resolve_conflict"},file_not_found:{category:"conflict",recovery:"refresh"},file_source_mismatch:{category:"conflict",recovery:"refresh"},file_upload_incomplete:{category:"conflict",recovery:"retry"},hosted_provider_unavailable:{category:"availability",recovery:"retry"},insufficient_access:{category:"authorization",recovery:"reauthorize"},invalid_application_authorization:{category:"validation",recovery:"fix_request"},invalid_application_manifest:{category:"validation",recovery:"fix_request"},invalid_callback:{category:"validation",recovery:"fix_request"},invalid_device_authorization_response:{category:"integrity",recovery:"contact_support"},invalid_encrypted_response:{category:"integrity",recovery:"contact_support"},invalid_loopback_url:{category:"validation",recovery:"fix_request"},invalid_mutation_id:{category:"validation",recovery:"fix_request"},invalid_operation_response:{category:"integrity",recovery:"contact_support"},invalid_path:{category:"validation",recovery:"fix_request"},invalid_preflight:{category:"conflict",recovery:"refresh"},invalid_push_payload:{category:"validation",recovery:"fix_request"},invalid_push_subscription:{category:"validation",recovery:"fix_request"},invalid_request:{category:"validation",recovery:"fix_request"},invalid_token_response:{category:"integrity",recovery:"contact_support"},managed_fcm_not_declared:{category:"compatibility",recovery:"fix_request"},manifest_load_failed:{category:"availability",recovery:"retry"},manifest_required:{category:"validation",recovery:"fix_request"},missing_grant_key:{category:"authorization",recovery:"reauthorize"},no_pending_mutation:{category:"conflict",recovery:"refresh"},not_authorized:{category:"authorization",recovery:"reauthorize"},not_remote_authority:{category:"compatibility",recovery:"choose_collection"},notification_criterion_not_declared:{category:"validation",recovery:"fix_request"},notification_reauthorization_required:{category:"authorization",recovery:"reauthorize"},notification_registration_failed:{category:"availability",recovery:"retry"},notification_unregistration_failed:{category:"availability",recovery:"retry"},notifications_not_declared:{category:"compatibility",recovery:"fix_request"},notifications_unavailable:{category:"availability",recovery:"retry"},operation_cancelled:{category:"cancellation",recovery:"none"},operation_failed:{category:"internal",recovery:"contact_support"},operation_invalid:{category:"validation",recovery:"fix_request"},operation_outcome_unknown:{category:"conflict",recovery:"resolve_outcome"},path_occupied:{category:"conflict",recovery:"resolve_conflict"},pending_mutation_unresolved:{category:"conflict",recovery:"resolve_outcome"},query_snapshot_changed:{category:"conflict",recovery:"refresh"},rate_limited:{category:"availability",recovery:"retry"},reconnect_required:{category:"authorization",recovery:"reauthorize"},redirect_uri_required:{category:"validation",recovery:"fix_request"},reference_updates_unsupported:{category:"compatibility",recovery:"fix_request"},relay_authorization_expired:{category:"authorization",recovery:"reauthorize"},relay_unavailable:{category:"availability",recovery:"retry"},sandbox_unsupported:{category:"compatibility",recovery:"fix_request"},scope_denied:{category:"authorization",recovery:"reauthorize"},stale_file_revision:{category:"conflict",recovery:"refresh"},storage_required:{category:"compatibility",recovery:"none"},sync_failed:{category:"availability",recovery:"retry"},temporarily_unavailable:{category:"availability",recovery:"retry"},timeout:{category:"availability",recovery:"retry"},token_exchange_failed:{category:"availability",recovery:"retry"},type_pack_provision_failed:{category:"validation",recovery:"repair_collection"},unknown_collection:{category:"selection",recovery:"choose_collection"},unsafe_file_path:{category:"validation",recovery:"fix_request"},unsupported_encryption:{category:"compatibility",recovery:"upgrade_application"},unsupported_operation:{category:"compatibility",recovery:"fix_request"}},gn={access_denied:{type:"object",required:[],properties:{return_to:{type:"string"}}},approval_window_blocked:{type:"object",required:["user_code","verification_uri","verification_uri_complete","expires_at","interval_seconds"],properties:{user_code:{type:"string"},verification_uri:{type:"string"},verification_uri_complete:{type:"string"},expires_at:{type:"integer"},interval_seconds:{type:"integer"}}},collection_configuration_invalid:{type:"object",required:["diagnostics"],properties:{diagnostics:{type:"array",items:{type:"object"}}}},collection_contracts_missing:{type:"object",required:["contracts"],properties:{contracts:{type:"array",items:{type:"object",required:["id","version"],properties:{id:{type:"string"},version:{type:"string"}}}}}},collection_invalid:{type:"object",required:["diagnostics"],properties:{diagnostics:{type:"array",items:{type:"object"}}}},collection_type_registry_invalid:{type:"object",required:["diagnostics"],properties:{diagnostics:{type:"array",items:{type:"object"}}}},collection_version_unsupported:{type:"object",required:["current_version","required_version"],properties:{current_version:{type:"string"},required_version:{type:"string"}}},connector_offline:{type:"object",required:[],properties:{connector_name:{type:"string"}}},insufficient_access:{type:"object",required:["required_operations","granted_operations","missing_operations"],properties:{required_operations:{type:"array",items:{type:"string"}},granted_operations:{type:"array",items:{type:"string"}},missing_operations:{type:"array",items:{type:"string"}}}},invalid_application_manifest:{type:"object",required:["issues"],properties:{issues:{type:"array",items:{type:"object",required:["path","keyword","message","params"],properties:{path:{type:"string"},keyword:{type:"string"},message:{type:"string"},params:{type:"object"}}}}}},operation_invalid:{type:"object",required:["diagnostics"],properties:{diagnostics:{type:"array",items:{type:"object"}},partial_result:{}}},rate_limited:{type:"object",required:[],properties:{retry_after_ms:{type:"integer"}}}};function $t(i){return Object.hasOwn(V,i)}function ve(i){if(!Vt(i))return!1;let e=i;if(e.problem_version!==1||typeof e.message!="string"||e.message.length===0||e.operation_outcome!==void 0&&e.operation_outcome!=="not_sent"&&e.operation_outcome!=="rejected"&&e.operation_outcome!=="unknown"||e.trace_id!==void 0&&(typeof e.trace_id!="string"||e.trace_id.length===0))return!1;if(e.code==="unknown")return typeof e.server_code=="string"&&e.server_code.length>0&&e.category==="unknown"&&e.recovery==="none";if(typeof e.code!="string"||!$t(e.code)||e.server_code!==void 0)return!1;let t=V[e.code],n=gn[e.code],o=n===void 0?e.details===void 0:e.details===void 0?(n.required?.length??0)===0:mt(e.details,n);return e.category===t.category&&e.recovery===t.recovery&&o}function mt(i,e){if(e.type===void 0)return!0;if(e.type==="string")return typeof i=="string";if(e.type==="integer")return typeof i=="number"&&Number.isInteger(i);if(e.type==="number")return typeof i=="number"&&Number.isFinite(i);if(e.type==="boolean")return typeof i=="boolean";if(e.type==="array")return Array.isArray(i)&&i.every(n=>mt(n,e.items??{}));if(!Vt(i))return!1;if(!e.properties)return!0;let t=i;return!Object.keys(t).every(n=>Object.hasOwn(e.properties,n))||!(e.required??[]).every(n=>Object.hasOwn(t,n))?!1:Object.entries(t).every(([n,o])=>mt(o,e.properties[n]))}function Vt(i){return i!==null&&typeof i=="object"&&!Array.isArray(i)}function gt(i,e,t={}){if($t(i)){let n=V[i],o={problem_version:1,code:i,category:n.category,recovery:n.recovery,message:e,...t.details===void 0?{}:{details:t.details},...t.operation_outcome===void 0?{}:{operation_outcome:t.operation_outcome},...t.trace_id===void 0?{}:{trace_id:t.trace_id}};if(ve(o))return o}return{problem_version:1,code:"unknown",server_code:i,category:"unknown",recovery:"none",message:e,...t.details===void 0?{}:{details:t.details},...t.operation_outcome===void 0?{}:{operation_outcome:t.operation_outcome},...t.trace_id===void 0?{}:{trace_id:t.trace_id}}}var Gt=new Uint8Array([77,68,66,70]),Yt=1,Jt=0,Ho=new Uint8Array([77,68,66,82]);var Qt=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,_=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name="FileFrameError"}};function _n(i){return i==="upload_chunk"?1:2}function bn(i){if(i===1)return"upload_chunk";if(i===2)return"download_chunk";throw new _("invalid_kind",`Unknown file frame kind ${i}`)}function vn(i){if(!i||typeof i!="object"||Array.isArray(i))throw new _("invalid_header","File frame header must be a JSON object");return i}function Be(i,e){let t=i[e];if(typeof t!="string"||t.length===0)throw new _("invalid_header",`File frame header ${e} must be a non-empty string`);return t}function Ne(i,e){let t=Be(i,e);if(!Qt.test(t))throw new _("invalid_header",`File frame header ${e} must be a UUID`);return t}function G(i,e,t=Number.MAX_SAFE_INTEGER){let n=i[e];if(!Number.isSafeInteger(n)||n<0||n>t)throw new _("invalid_header",`File frame header ${e} is outside its allowed range`);return n}function _t(i){if(i.protocol_version!==1)throw new _("unsupported_version",`Unsupported file transfer protocol ${i.protocol_version}`);if(i.protection!=="grant_aead_v1"&&i.protection!=="transport_tls")throw new _("invalid_header","Unknown file transfer protection");if(i.direction!=="upload"&&i.direction!=="download")throw new _("invalid_header","Unknown file transfer direction");for(let[e,t]of[["grant_id",i.grant_id],["authority_id",i.authority_id],["collection_id",i.collection_id],["transfer_id",i.transfer_id]])if(!Qt.test(t))throw new _("invalid_header",`File frame header ${e} must be a UUID`);for(let[e,t,n]of[["chunk_size",i.chunk_size,4194304],["chunk_index",i.chunk_index,Number.MAX_SAFE_INTEGER],["offset",i.offset,Number.MAX_SAFE_INTEGER],["plaintext_length",i.plaintext_length,4194304],["total_size",i.total_size,Number.MAX_SAFE_INTEGER]])if(!Number.isSafeInteger(t)||t<0||t>n)throw new _("invalid_header",`File frame header ${e} is outside its allowed range`);if(i.chunk_size<64*1024)throw new _("invalid_header","File frame chunk_size is below the protocol minimum");if(!Number.isSafeInteger(i.scope_epoch)||i.scope_epoch<1)throw new _("invalid_header","File frame header scope_epoch must be a positive integer");if(i.protection==="grant_aead_v1"&&!i.key_id)throw new _("invalid_header","AEAD-protected file frames require key_id");return{protocol_version:1,protection:i.protection,grant_id:i.grant_id,authority_id:i.authority_id,collection_id:i.collection_id,transfer_id:i.transfer_id,direction:i.direction,chunk_size:i.chunk_size,chunk_index:i.chunk_index,offset:i.offset,plaintext_length:i.plaintext_length,total_size:i.total_size,scope_epoch:i.scope_epoch,...i.key_id===void 0?{}:{key_id:i.key_id}}}function wn(i){let e;try{e=new TextDecoder("utf-8",{fatal:!0}).decode(i)}catch{throw new _("invalid_header","File frame header is not valid UTF-8")}let t;try{t=vn(JSON.parse(e))}catch(d){throw d instanceof _?d:new _("invalid_header","File frame header is not valid JSON")}let n=new Set(["protocol_version","protection","grant_id","authority_id","collection_id","transfer_id","direction","chunk_size","chunk_index","offset","plaintext_length","total_size","scope_epoch","key_id"]);if(Object.keys(t).some(d=>!n.has(d)))throw new _("invalid_header","File frame header contains an unknown field");let o=G(t,"protocol_version");if(o!==1)throw new _("unsupported_version",`Unsupported file transfer protocol ${o}`);let r=Be(t,"protection"),a=Be(t,"direction"),s=t.key_id===void 0?void 0:Be(t,"key_id"),c=_t({protocol_version:1,protection:r,grant_id:Ne(t,"grant_id"),authority_id:Ne(t,"authority_id"),collection_id:Ne(t,"collection_id"),transfer_id:Ne(t,"transfer_id"),direction:a,chunk_size:G(t,"chunk_size",4194304),chunk_index:G(t,"chunk_index"),offset:G(t,"offset"),plaintext_length:G(t,"plaintext_length",4194304),total_size:G(t,"total_size"),scope_epoch:G(t,"scope_epoch"),...s===void 0?{}:{key_id:s}});if(JSON.stringify(c)!==e)throw new _("invalid_header","File frame header must use the canonical field order without duplicate fields or whitespace");return c}function bt(i,e,t){let n=i==="upload_chunk"?"upload":"download";if(e.direction!==n)throw new _("invalid_header",`Frame kind ${i} requires direction ${n}`);let o=e.chunk_index*e.chunk_size;if(!Number.isSafeInteger(o)||e.offset!==o)throw new _("invalid_header","Chunk offset does not match its index and protocol chunk size");if(e.offset+e.plaintext_length>e.total_size)throw new _("invalid_header","Chunk extends past the declared transfer size");let r=e.protection==="grant_aead_v1"?e.plaintext_length+16:e.plaintext_length;if(t!==r)throw new _("invalid_length","Payload length does not match the protected plaintext length")}function Cn(i){return i.plaintext_length+(i.protection==="grant_aead_v1"?16:0)}function Ke(i,e){let t=_t(e),n=Cn(t);bt(i,t,n);let o=new TextEncoder().encode(JSON.stringify(t));if(o.byteLength>16384)throw new _("limit_exceeded","File frame header exceeds the protocol limit");let r=new Uint8Array(16+o.byteLength);r.set(Gt,0);let a=new DataView(r.buffer,r.byteOffset,r.byteLength);return a.setUint8(4,Yt),a.setUint8(5,_n(i)),a.setUint16(6,Jt,!1),a.setUint32(8,o.byteLength,!1),a.setUint32(12,n,!1),r.set(o,16),r}function Xt(i){let e=_t(i.header);if(bt(i.kind,e,i.payload.byteLength),i.payload.byteLength>4194320)throw new _("limit_exceeded","File frame payload exceeds the protocol limit");let t=Ke(i.kind,e),n=new Uint8Array(t.byteLength+i.payload.byteLength);return n.set(t,0),n.set(i.payload,t.byteLength),n}function je(i,e={}){if(i.byteLength<16)throw new _("invalid_length","File frame is shorter than its fixed prefix");if(!Gt.every((y,h)=>i[h]===y))throw new _("invalid_magic","File frame magic is not MDBF");let t=new DataView(i.buffer,i.byteOffset,i.byteLength),n=t.getUint8(4);if(n!==Yt)throw new _("unsupported_version",`Unsupported file frame version ${n}`);let o=bn(t.getUint8(5));if(t.getUint16(6,!1)!==Jt)throw new _("unsupported_flags","File frame uses unsupported flags");let r=t.getUint32(8,!1),a=t.getUint32(12,!1),s=e.maxHeaderBytes??16384,c=e.maxPayloadBytes??4194320;if(r===0)throw new _("invalid_length","File frame header must not be empty");if(r>s||a>c)throw new _("limit_exceeded","File frame exceeds the configured decode limits");let d=16+r+a;if(!Number.isSafeInteger(d)||d!==i.byteLength)throw new _("invalid_length","File frame lengths do not match the supplied bytes");let p=16+r,u=wn(i.subarray(16,p));return bt(o,u,a),{kind:o,header:u,payload:i.slice(p)}}var Wt={"collection.inspect":["describe"],"records.watch":["changes"],"records.read":["read"],"records.query":["query"],"records.validate":["validate"],"records.create":["create"],"records.update":["update"],"records.delete":["delete"],"records.rename":["rename"],"views.list":["list_views"],"views.execute":["execute_view"],"views.source.read":["read_view_source"],"views.source.create":["create_view_source"],"views.source.update":["update_view_source"],"views.source.delete":["delete_view_source"],"definitions.contracts.current":[],"definitions.read":["read_type"],"definitions.create":["create_type"],"definitions.update":["update_type"],"definitions.type-pack.inspect":["assess_type_pack"],"definitions.type-pack.apply":["assess_type_pack","apply_type_pack"],"timers.list":["list_timers"],"timers.put":["put_timer"],"timers.cancel":["cancel_timer"],"timers.reconcile":["reconcile_timers"],"sync.offline-replica":["sync"],"notifications.background-delivery":[],"files.list":[],"files.read":[],"files.add":[],"files.replace":[],"files.move":[],"files.delete":[]};function Zt(i,e={}){let t=e.includeOptional===!1?i.required:[...i.required,...i.optional??[]];return[...new Set(t.flatMap(n=>Wt[n]))]}function He(i){return[...Wt[i]]}var Pn=new TextEncoder().encode("mdbase-connect application installation id v2\0"),An=new TextEncoder().encode("mdbase-connect application authorization proof v2\0");async function ti(i){let e=$e(i),n=new Uint8Array(await crypto.subtle.digest("SHA-256",ne([Pn,x(e)]))).slice(0,16);return n[6]=n[6]&15|128,n[8]=n[8]&63|128,[we(n.slice(0,4)),we(n.slice(4,6)),we(n.slice(6,8)),we(n.slice(8,10)),we(n.slice(10,16))].join("-")}function Ge(i){let e=[$e(i.installation_signing_public_key),$e(i.grant_agreement_public_key),$e(i.grant_signing_public_key)];if(e.some((r,a)=>e.slice(a+1).some(s=>Tn(r,s))))throw new Error("Application authorization keys must be distinct.");let t=vt(i.authorization_nonce),n=vt(i.code_challenge);if(i.protocol_version!==2||t.byteLength!==32||!/^[0-9a-f]{64}$/u.test(i.application_manifest_digest)||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/u.test(i.issued_at)||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/u.test(i.expires_at)||n.byteLength!==32||i.requested_operations.length===0&&i.requested_files===void 0||new Set(i.requested_operations).size!==i.requested_operations.length||i.requested_operations.some(r=>!r||r.includes("\0"))||(i.flow==="authorization_code"?i.redirect_uri===void 0||i.state===void 0:i.flow!=="device_code"||i.redirect_uri!==void 0||i.state!==void 0))throw new Error("Application authorization binding is invalid.");Sn(i.requested_files);let o=i.requested_operations.map(r=>x(new TextEncoder().encode(r)));return ne([An,Ce(i.protocol_version),x(Ve(i.application_id)),x(Ve(i.authorization_id)),x(ii(i.application_manifest_digest)),x(Ve(i.application_installation_id)),...e.map(x),x(new TextEncoder().encode(i.flow)),x(t),x(new TextEncoder().encode(i.issued_at)),x(new TextEncoder().encode(i.expires_at)),ei(i.redirect_uri),ei(i.state),x(new TextEncoder().encode(i.code_challenge)),Ce(o.length),...o,kn(i.requested_files),Rn(i.collection_id)])}function Sn(i){if(i!==void 0&&(i.actions.length===0||new Set(i.actions).size!==i.actions.length||i.scope.kind==="selected_folders"&&(i.scope.folders.length===0||new Set(i.scope.folders).size!==i.scope.folders.length||i.scope.folders.some(e=>!e||e.includes("\0")))))throw new Error("Application authorization file request is invalid.")}function kn(i){if(i===void 0)return new Uint8Array([0]);let e=i.actions.map(t=>x(new TextEncoder().encode(t)));return ne([new Uint8Array([1]),Ce(e.length),...e,x(new TextEncoder().encode(i.scope.kind)),...i.scope.kind==="selected_folders"?[Ce(i.scope.folders.length),...i.scope.folders.map(t=>x(new TextEncoder().encode(t)))]:[]])}function ei(i){return i===void 0?new Uint8Array([0]):ne([new Uint8Array([1]),x(new TextEncoder().encode(i))])}function Rn(i){return i===void 0?new Uint8Array([0]):ne([new Uint8Array([1]),x(Ve(i))])}function $e(i){let e=vt(i);if(e.byteLength!==65||e[0]!==4)throw new Error("Application authorization public key is invalid.");return e}function vt(i){if(!/^[A-Za-z0-9_-]+$/u.test(i))throw new Error("Invalid base64url value.");let e=i.replaceAll("-","+").replaceAll("_","/"),t=e.padEnd(Math.ceil(e.length/4)*4,"="),n=Uint8Array.from(atob(t),o=>o.charCodeAt(0));if(On(n)!==i)throw new Error("Non-canonical base64url value.");return n}function Ve(i){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu.test(i))throw new Error("Invalid UUID value.");let e=i.replaceAll("-","");return ii(e)}function ii(i){if(!/^[0-9a-f]+$/u.test(i)||i.length%2!==0)throw new Error("Invalid hexadecimal value.");return Uint8Array.from({length:i.length/2},(e,t)=>Number.parseInt(i.slice(t*2,t*2+2),16))}function x(i){return ne([Ce(i.byteLength),i])}function Ce(i){let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,i,!1),e}function ne(i){let e=new Uint8Array(i.reduce((n,o)=>n+o.byteLength,0)),t=0;for(let n of i)e.set(n,t),t+=n.byteLength;return e}function On(i){return btoa(String.fromCharCode(...i)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}function Tn(i,e){return i.byteLength===e.byteLength&&i.every((t,n)=>t===e[n])}function we(i){return[...i].map(e=>e.toString(16).padStart(2,"0")).join("")}var oe=1,wt=2;var ni=28485,Pe="P256-HKDF-SHA256-AES256GCM";var In="contract-setup-v1",xn="file-relay-v1",En=["application-authorization-v2","authorization-activation","encrypted-relay","policy-ack"],Yo=[...En,In,xn],Ct=1;var oi="mdbase-authority-request-proof-v1",Ae={version:"x-mdbase-proof-version",timestamp:"x-mdbase-proof-timestamp",nonce:"x-mdbase-proof-nonce",signature:"x-mdbase-proof-signature"};var Mn="mdbase-connect-keys",H="grant-keys",At=18446744073709551615n,zn="mdbase-connect relay request key v1",Dn="mdbase-connect relay response key v1",ri=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,re=class{database=null;async create(e){let t=await li(e),n=await this.open();return await si(n,o=>o.add({...t,counter:"0"})),t}async get(e){let t=await this.open(),n=await Nn(t.transaction(H).objectStore(H).get(e));return n?{handle:n.handle,agreementPrivateKey:n.agreementPrivateKey,agreementPublicKey:n.agreementPublicKey,signingPrivateKey:n.signingPrivateKey,signingPublicKey:n.signingPublicKey}:null}async nextCounter(e){let t=await this.open();return new Promise((n,o)=>{let r=t.transaction(H,"readwrite"),a=r.objectStore(H),s=a.get(e),c=null;s.onerror=()=>o(s.error),s.onsuccess=()=>{let d=s.result;if(!d){r.abort(),o(new v("missing_grant_key","The encrypted grant key is unavailable."));return}let p=BigInt(d.counter)+1n;if(p>At){r.abort(),o(new v("counter_exhausted","The encrypted grant must be authorized again."));return}c=p.toString(),a.put({...d,counter:c})},r.onerror=()=>o(r.error),r.onabort=()=>o(r.error??new Error("Key counter transaction aborted.")),r.oncomplete=()=>{c&&n(c)}})}async delete(e){let t=await this.open();await si(t,n=>n.delete(e))}open(){if(typeof indexedDB>"u")throw new v("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 n=indexedDB.open(Mn,1);n.onupgradeneeded=()=>{n.result.objectStoreNames.contains(H)||n.result.createObjectStore(H,{keyPath:"handle"})},n.onerror=()=>t(n.error),n.onsuccess=()=>e(n.result)})),this.database}},ae=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 li(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,n,o=new Promise((r,a)=>{t=r,n=a});return this.sequence=this.sequence.then(()=>{let r=this.records.get(e);if(!r)throw new v("missing_grant_key","The encrypted grant key is unavailable.");let a=BigInt(r.counter)+1n;if(a>At)throw new v("counter_exhausted","The encrypted grant must be authorized again.");r.counter=a.toString(),t(r.counter)}).catch(r=>{n(r)}),o}async delete(e){this.records.delete(e)}};async function ci(i,e,t,n){let o=await Fn(i,e,t),r=n.timestamp??Math.floor(Date.now()/1e3),a=n.nonce??crypto.randomUUID(),s=await Un({...n,timestamp:r,nonce:a}),c=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},o.signingPrivateKey,new TextEncoder().encode(s));return{[Ae.version]:String(Ct),[Ae.timestamp]:String(r),[Ae.nonce]:a,[Ae.signature]:Se(new Uint8Array(c))}}async function Un(i){let e=i.method.toUpperCase(),t=await ai(i.body??""),n=await ai(i.credential);for(let o of[e,i.target,String(i.timestamp),i.nonce])if(!o||o.includes(`
2
- `)||o.includes("\r"))throw new v("invalid_proof_input","Authority request proof metadata is invalid.");return[oi,Ct,e,i.target,t,n,i.timestamp,i.nonce].join(`
3
- `)}async function Y(i,e,t,n,o,r=crypto.randomUUID()){J(t.encryption);let a=await di(i,e,t.encryption.application_agreement_public_key),s=await i.nextCounter(e),c={binding:t,requestId:r,operation:n,counter:s},d=await ui(a.agreementPrivateKey,t,"request"),p=new TextEncoder().encode(JSON.stringify(o??{})),u=await crypto.subtle.encrypt({name:"AES-GCM",iv:fi(s),additionalData:new TextEncoder().encode(hi(c,"request")),tagLength:128},d,p);return{type:"encrypted_operation_request",...qn(c),ciphertext:Se(new Uint8Array(u))}}async function se(i,e,t,n,o){if(!Ln(n,o))throw new v("invalid_encrypted_response","Encrypted response metadata does not match its request.");let r=await di(i,e,t.encryption.application_agreement_public_key),a={binding:t,requestId:n.request_id,operation:n.operation,counter:n.counter},s=await ui(r.agreementPrivateKey,t,"response");try{let c=await crypto.subtle.decrypt({name:"AES-GCM",iv:fi(n.counter),additionalData:new TextEncoder().encode(hi(a,"response")),tagLength:128},s,mi(yi(o.ciphertext))),d=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(c));if(d?.ok===!0&&"result"in d||d?.ok===!1&&ve(d.problem))return d;throw new Error("invalid response body")}catch(c){throw c instanceof v?c:new v("encrypted_response_rejected","The encrypted connector response could not be authenticated.")}}var v=class extends Error{constructor(t,n){super(n);this.code=t}code};async function li(i){let e=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"]),t=Se(new Uint8Array(await crypto.subtle.exportKey("raw",e.publicKey))),n=await crypto.subtle.exportKey("pkcs8",e.privateKey),o=await crypto.subtle.importKey("pkcs8",n,{name:"ECDH",namedCurve:"P-256"},!1,["deriveBits"]),r=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign","verify"]),a=Se(new Uint8Array(await crypto.subtle.exportKey("raw",r.publicKey))),s=await crypto.subtle.exportKey("pkcs8",r.privateKey),c=await crypto.subtle.importKey("pkcs8",s,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]);return{handle:i,agreementPrivateKey:o,agreementPublicKey:t,signingPrivateKey:c,signingPublicKey:a}}async function di(i,e,t){let n=await i.get(e);if(!n||n.agreementPublicKey!==t)throw new v("missing_grant_key","The encrypted grant key is unavailable or does not match the grant.");return n}async function Fn(i,e,t){let n=await i.get(e);if(!n||n.signingPublicKey!==t)throw new v("missing_grant_key","The remote authority signing key is unavailable or does not match the grant.");return n}async function ui(i,e,t){let n=await St(i,e.encryption.connector_agreement_public_key),o=await crypto.subtle.importKey("raw",n,"HKDF",!1,["deriveKey"]),r=new TextEncoder().encode(pi(e)),a=await crypto.subtle.digest("SHA-256",r);return crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:a,info:new TextEncoder().encode(t==="request"?zn:Dn)},o,{name:"AES-GCM",length:256},!1,t==="request"?["encrypt"]:["decrypt"])}async function St(i,e){try{let t=await crypto.subtle.importKey("raw",mi(Pt(e)),{name:"ECDH",namedCurve:"P-256"},!1,[]);return await crypto.subtle.deriveBits({name:"ECDH",public:t},i,256)}catch{throw new v("invalid_public_key","The connector relay public key is invalid.")}}function pi(i){let e=i.encryption;return["mdbase-connect",oe,e.suite,i.grantId,i.applicationId,e.connector_id,e.collection_id,e.scope_epoch,e.key_id].join("|")}function hi(i,e){return[pi(i.binding),i.requestId,e,i.operation,i.counter].join("|")}function qn(i){let e=i.binding.encryption;return{protocol_version:oe,suite:Pe,request_id:i.requestId,grant_id:i.binding.grantId,application_id:i.binding.applicationId,connector_id:e.connector_id,collection_id:e.collection_id,operation:i.operation,scope_epoch:e.scope_epoch,key_id:e.key_id,counter:i.counter}}function Ln(i,e){return e.type==="encrypted_operation_response"&&typeof e.ciphertext=="string"&&i.protocol_version===e.protocol_version&&i.suite===e.suite&&i.request_id===e.request_id&&i.grant_id===e.grant_id&&i.application_id===e.application_id&&i.connector_id===e.connector_id&&i.collection_id===e.collection_id&&i.operation===e.operation&&i.scope_epoch===e.scope_epoch&&i.key_id===e.key_id&&i.counter===e.counter}function J(i){if(i.protocol_version!==oe||i.suite!==Pe||!Number.isSafeInteger(i.scope_epoch)||i.scope_epoch<=0||typeof i.key_id!="string"||i.key_id.length===0||i.key_id.length>200||i.key_id.includes("|"))throw new v("unsupported_encryption","The grant uses an unsupported relay encryption profile.");if(typeof i.connector_id!="string"||!ri.test(i.connector_id)||typeof i.collection_id!="string"||!ri.test(i.collection_id))throw new v("unsupported_encryption","The grant uses invalid encrypted relay identities.");Pt(i.application_agreement_public_key),Pt(i.connector_agreement_public_key)}function fi(i){let e=BigInt(i);if(e<=0n||e>At||e.toString()!==i)throw new v("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 Se(i){let e="";for(let t of i)e+=String.fromCharCode(t);return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}async function ai(i){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(i));return Se(new Uint8Array(e))}function yi(i){if(!/^[A-Za-z0-9_-]+$/.test(i))throw new v("invalid_base64","Encrypted relay data is malformed.");let e="=".repeat((4-i.length%4)%4),t=atob(i.replaceAll("-","+").replaceAll("_","/")+e);return Uint8Array.from(t,n=>n.charCodeAt(0))}function Pt(i){let e=yi(i);if(e.length!==65||e[0]!==4)throw new v("invalid_public_key","Encrypted relay public keys must be uncompressed P-256 points.");return e}function mi(i){return Uint8Array.from(i).buffer}function Nn(i){return new Promise((e,t)=>{i.onerror=()=>t(i.error),i.onsuccess=()=>e(i.result)})}function si(i,e){return new Promise((t,n)=>{let o=i.transaction(H,"readwrite"),r=e(o.objectStore(H));r.onerror=()=>n(r.error),o.onerror=()=>n(o.error),o.onabort=()=>n(o.error??new Error("Grant key transaction aborted.")),o.oncomplete=()=>t()})}var Bn="mdbase-connect file chunk key v1",Ye=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,B=class extends Error{constructor(t,n){super(n);this.code=t;this.name="FileTransferCryptoError"}code},ce=class i{constructor(e,t){this.binding=e;this.key=t}binding;key;static async open(e,t,n){gi(n);let o=await e.get(t);if(!o||o.agreementPublicKey!==n.encryption.application_agreement_public_key)throw new v("missing_grant_key","The encrypted grant key is unavailable or does not match the file transfer grant.");let r=await St(o.agreementPrivateKey,n.encryption.connector_agreement_public_key);return i.fromSharedSecret(r,n)}static async fromSharedSecret(e,t){gi(t);let n=await Kn(e,t);return new i(t,n)}async encryptChunk(e,t,n){if(this.validateHeader(t),n.byteLength!==t.plaintext_length)throw new B("plaintext_length_mismatch","File chunk plaintext length does not match its authenticated header.");let o=Ke(e,t),r=await crypto.subtle.encrypt({name:"AES-GCM",iv:_i(t.chunk_index),additionalData:Je(o),tagLength:128},this.key,Je(n));return Xt({kind:e,header:t,payload:new Uint8Array(r)})}async decryptChunk(e){let t=je(e);this.validateHeader(t.header);let n=Ke(t.kind,t.header);try{let o=await crypto.subtle.decrypt({name:"AES-GCM",iv:_i(t.header.chunk_index),additionalData:Je(n),tagLength:128},this.key,Je(t.payload));return new Uint8Array(o)}catch{throw new B("authentication_failed","The encrypted file chunk could not be authenticated.")}}validateHeader(e){let t=this.binding.encryption;if(e.protocol_version!==1||e.protection!=="grant_aead_v1"||e.grant_id!==this.binding.grantId||e.authority_id!==this.binding.authorityId||e.collection_id!==t.collection_id||e.transfer_id!==this.binding.transferId||e.direction!==this.binding.direction||e.scope_epoch!==t.scope_epoch||e.key_id!==t.key_id)throw new B("header_binding_mismatch","The file frame does not match its transfer encryption binding.")}};async function Kn(i,e){let t=new TextEncoder().encode(jn(e)),n=await crypto.subtle.digest("SHA-256",t),o=await crypto.subtle.importKey("raw",i,"HKDF",!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:n,info:new TextEncoder().encode(Bn)},o,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}function gi(i){if(J(i.encryption),!Ye.test(i.grantId)||!Ye.test(i.applicationId)||!Ye.test(i.authorityId)||!Ye.test(i.transferId)||i.direction!=="upload"&&i.direction!=="download")throw new B("invalid_binding","The file transfer encryption binding is invalid.")}function jn(i){let e=i.encryption;return["mdbase-connect","file-transfer",1,e.suite,i.grantId,i.applicationId,e.connector_id,i.authorityId,e.collection_id,e.scope_epoch,e.key_id,i.transferId,i.direction].join("|")}function _i(i){if(!Number.isSafeInteger(i)||i<0)throw new B("invalid_chunk_index","The file chunk index is invalid.");let e=new Uint8Array(new ArrayBuffer(12));return new DataView(e.buffer).setBigUint64(4,BigInt(i),!1),e}function Je(i){return Uint8Array.from(i).buffer}var Hn="mdbase-connect-identities",le="application-identities",kt=BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),$n=kt/2n,de=class{database=null;async create(e){let t=await wi(e),n=await this.open();return await bi(n,o=>o.add(t)),t}async get(e){let t=await this.open();return await Vn(t.transaction(le).objectStore(le).get(e))??null}async delete(e){let t=await this.open();await bi(t,n=>n.delete(e))}open(){if(typeof indexedDB>"u")throw new Q("Persistent application identity requires browser IndexedDB or an injected identity store.");return this.database||(this.database=new Promise((e,t)=>{let n=indexedDB.open(Hn,1);n.onupgradeneeded=()=>{n.result.objectStoreNames.contains(le)||n.result.createObjectStore(le,{keyPath:"handle"})},n.onerror=()=>t(n.error),n.onsuccess=()=>e(n.result)})),this.database}},ue=class{records=new Map;async create(e){if(this.records.has(e))throw new Error(`Application identity already exists: ${e}`);let t=await wi(e);return this.records.set(e,t),t}async get(e){return this.records.get(e)??null}async delete(e){this.records.delete(e)}},Q=class extends Error{constructor(e){super(e),this.name="ApplicationIdentityStoreError"}};async function pe(i){return ti(i.signingPublicKey)}async function ke(i,e){if(i.installation_signing_public_key!==e.signingPublicKey||i.application_installation_id!==await pe(e))throw new Error("Application authorization identity does not match its binding.");let t=Yn(new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},e.signingPrivateKey,Ge(i))));return{binding:i,signature:Ci(t)}}async function vi(i,e,t){let n=`application-installation:v2:${e}:${t.id}`,o=await i.get(n);if(o)return o;try{return await i.create(n)}catch(r){let a=await i.get(n);if(a)return a;throw r}}async function wi(i){let e=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign","verify"]),t=Ci(new Uint8Array(await crypto.subtle.exportKey("raw",e.publicKey))),n=await crypto.subtle.exportKey("pkcs8",e.privateKey),o=await crypto.subtle.importKey("pkcs8",n,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]);return{handle:i,signingPrivateKey:o,signingPublicKey:t}}function Vn(i){return new Promise((e,t)=>{i.onerror=()=>t(i.error),i.onsuccess=()=>e(i.result)})}function bi(i,e){return new Promise((t,n)=>{let o=i.transaction(le,"readwrite");e(o.objectStore(le)).onerror=()=>n(o.error),o.onerror=()=>n(o.error),o.onabort=()=>n(o.error??new Error("Identity transaction aborted.")),o.oncomplete=()=>t()})}function Gn(i){let e=new Uint8Array(i.reduce((n,o)=>n+o.byteLength,0)),t=0;for(let n of i)e.set(n,t),t+=n.byteLength;return e}function Ci(i){return btoa(String.fromCharCode(...i)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}function Yn(i){if(i.byteLength!==64)throw new Error("Application authorization signature is invalid.");let e=Jn(i.slice(32));if(e===0n||e>=kt)throw new Error("Application authorization signature is invalid.");return e<=$n?i:Gn([i.slice(0,32),Qn(kt-e,32)])}function Jn(i){return BigInt(`0x${Xn(i)}`)}function Qn(i,e){let t=i.toString(16).padStart(e*2,"0");return Uint8Array.from({length:e},(n,o)=>Number.parseInt(t.slice(o*2,o*2+2),16))}function Xn(i){return[...i].map(e=>e.toString(16).padStart(2,"0")).join("")}function Rt(i,e,t){let n=new Set(i.required),o=[...new Set([...i.required,...i.optional??[]])],r={};for(let a of o)r[a]=Wn(a,n.has(a),e,t);return{contractVersion:1,values:r,requiredAvailable:i.required.every(a=>r[a]?.state==="available")}}function Wn(i,e,t,n){let o=He(i),r=o.filter(s=>!n.operations.includes(s)),a={id:i,requirement:e?"required":"optional",operations:o,missingOperations:r,evidence:[{source:"application",fact:`${e?"Required":"Optional"} in capability contract v1.`}]};if(r.length>0)return{...a,state:"requires_authorization",evidence:[...a.evidence,{source:"authorization",fact:`Missing ${r.join(", ")}.`}],reason:"The current grant does not include every operation for this capability."};if(i==="definitions.contracts.current"){let s=new Set(n.scope.contracts.map(({id:d,version:p,digest:u})=>`${d}@${p}:${u}`)),c=(t.requirements?.contracts??[]).filter(({id:d,version:p,digest:u})=>!s.has(`${d}@${p}:${u}`));if(c.length>0)return{...a,state:"requires_authorization",reason:"The current grant does not approve the exact required contract definitions.",evidence:[...a.evidence,{source:"authorization",fact:`Missing ${c.map(({id:d,version:p})=>`${d}@${p}`).join(", ")}.`}],details:{missingContracts:c}}}if(i.startsWith("files.")){let s=i.slice(6);if(!n.fileCapability?.actions.includes(s))return{...a,state:n.fileCapability?"requires_authorization":"unsupported",reason:n.fileCapability?`The current file grant does not include ${s}.`:"This connection has no file capability.",evidence:[...a.evidence,{source:"authorization",fact:n.fileCapability?`Granted file actions: ${n.fileCapability.actions.join(", ")}.`:"No file capability was granted."}]}}return i==="notifications.background-delivery"&&(t.notifications?.criteria.length??0)===0?{...a,state:"requires_setup",reason:"The application manifest declares no notification criteria.",evidence:[...a.evidence,{source:"application",fact:"No authority notification criteria are declared."}]}:{...a,state:"available",evidence:[...a.evidence,{source:"authorization",fact:o.length>0?`Granted operations: ${o.join(", ")}.`:"No record operation is required."},{source:"authority",fact:n.authority.kind==="hosted"?"Backed by a durable hosted mdbase authority.":"Backed by a user-operated mdbase connector."}],...i==="sync.offline-replica"?{details:{durability:"device",writes:"queued",authority:n.authority.kind}}:{},...i==="notifications.background-delivery"?{details:{delivery:"authority",payload:"opaque"}}:{}}}var C=class extends Error{constructor(t,n={}){super(t.message,n.cause===void 0?void 0:{cause:n.cause});this.problem=t;this.name="MdbaseConnectError",this.code=t.code,this.status=n.status}problem;code;status;get retryable(){return this.problem.recovery==="retry"&&this.problem.operation_outcome!=="unknown"}get requiresAuthorization(){return this.problem.category==="authorization"}get outcomeUnknown(){return this.problem.operation_outcome==="unknown"}get recovery(){return this.problem.recovery}get details(){return this.problem.details}};function R(i,e,...[t={}]){let n=V[i];return{problem_version:1,code:i,category:n.category,recovery:n.recovery,message:e,...t.details===void 0?{}:{details:t.details},...t.operationOutcome===void 0?{}:{operation_outcome:t.operationOutcome},...t.traceId===void 0?{}:{trace_id:t.traceId}}}function Ot(i,e,t={}){return gt(i,e,{details:t.details,operation_outcome:t.operationOutcome,trace_id:t.traceId})}function l(i,e,...t){let n=t[0];return new C(R(i,e,...t),{status:n?.status,cause:n?.cause})}function D(i,e,t={}){let{status:n,cause:o,...r}=t;return new C(gt(i,e,{details:r.details,operation_outcome:r.operationOutcome,trace_id:r.traceId}),{status:n,cause:o})}function Tt(i){let e=eo(i.diagnostics),t=oo(i.diagnostics);if(e==="collection_version_unsupported"){let n=to(i.diagnostics);return R(e,t,{operationOutcome:"rejected",details:n})}return e!=="operation_invalid"?R(e,t,{operationOutcome:"rejected",details:{diagnostics:i.diagnostics}}):R(e,t,{operationOutcome:"rejected",details:{diagnostics:i.diagnostics,partial_result:i.result}})}function eo(i){let e=new Set(i.filter(t=>t.severity==="error").map(t=>t.code));return["migration_required","migration_lossy","unsupported_version"].some(t=>e.has(t))?"collection_version_unsupported":["invalid_config","invalid_configuration","missing_config","missing_spec_version"].some(t=>e.has(t))?"collection_configuration_invalid":["duplicate_type","invalid_contract_definition","invalid_data_contract","invalid_type_definition","invalid_type_path"].some(t=>e.has(t))?"collection_type_registry_invalid":["collection_invalid","collection_open_failed"].some(t=>e.has(t))?"collection_invalid":"operation_invalid"}function to(i){let e=i.map(t=>t.details).find(t=>io(t));return{current_version:typeof e?.current_version=="string"?e.current_version:"0.2.x",required_version:typeof e?.required_version=="string"?e.required_version:"0.3.0"}}function io(i){return i!==null&&typeof i=="object"&&!Array.isArray(i)}function no(i){return i instanceof C&&i.retryable}function oo(i){return i.filter(e=>e.severity==="error").map(e=>e.message).join(" ")||i.map(e=>e.message).join(" ")||"The collection rejected this operation."}var Pi=["access_denied","access_paused","authorization_expired","collection_access_denied","connector_identity_changed","connector_offline","connector_upgrade_required","direct_operation_rejected","operation_outcome_unknown","encryption_required","encrypted_relay_rejected","hosted_provider_unavailable","insufficient_access","invalid_encrypted_response","invalid_operation_response","invalid_request","missing_grant_key","not_authorized","operation_cancelled","operation_failed","rate_limited","relay_authorization_expired","relay_unavailable","temporarily_unavailable","timeout","unsupported_operation"],It=Object.keys(V),$=["discovery_failed","invalid_application_manifest","invalid_request","manifest_load_failed","rate_limited","temporarily_unavailable","timeout"],X=[...$,"access_denied","application_identity_unavailable","approval_window_blocked","authorization_cancelled","authorization_replayed","browser_required","collection_access_denied","collection_configuration_invalid","collection_contracts_missing","collection_incompatible","collection_invalid","collection_kind_unsupported","collection_mismatch","collection_not_found","collection_type_registry_invalid","collection_version_unsupported","connector_identity_changed","connector_offline","connector_upgrade_required","device_authorization_failed","encryption_required","expired_token","invalid_application_authorization","invalid_callback","invalid_device_authorization_response","invalid_token_response","scope_denied","reconnect_required","token_exchange_failed"],he=[...$,"authorization_expired","invalid_push_subscription","managed_fcm_not_declared","not_authorized","notification_criterion_not_declared","notification_reauthorization_required","notification_registration_failed","notification_unregistration_failed","notifications_not_declared","notifications_unavailable"],We=["connector_offline","connector_upgrade_required","invalid_operation_response","not_authorized","operation_failed","temporarily_unavailable","timeout"],ro=[...X,"collection_not_ready","collection_not_selected","unknown_collection"],Ai=["collection_configuration_invalid","collection_invalid","collection_type_registry_invalid","collection_version_unsupported"],Re=[...Pi,...Ai],q=[...Re,"invalid_path","operation_invalid"],xt=[...q,"query_snapshot_changed","sandbox_unsupported"],E=[...q,"concurrent_modification","invalid_preflight","pending_mutation_unresolved"],Et=[...Re,"change_cursor_reset"],W=[...E,"type_pack_provision_failed"];function O(i,e=[]){return{ok:!0,value:i,diagnostics:e}}function A(i){return{ok:!1,problem:i}}async function k(i,e){try{return O(await i())}catch(t){if(!(t instanceof C))throw t;let n=t.problem;return n.code==="unknown"||e.includes(n.code)?A(n):A(Ot(n.code,n.message,{details:n.details,operationOutcome:n.operation_outcome,traceId:n.trace_id}))}}var Xe=class extends Error{constructor(t){super(t.message);this.problem=t;this.name="ConnectOutcomeError"}problem};function ao(i){if(!i.ok)throw new Xe(i.problem);return i.value}function Oe(i){for(let e of["code","state","error","error_description"])i.searchParams.delete(e);return i}function Ze(i){let e;try{e=new URL(i)}catch{return!1}return e.searchParams.has("state")&&(e.searchParams.has("code")||e.searchParams.has("error"))}function Si(i){if(!i.details||typeof i.details!="object"||Array.isArray(i.details))return;let e=i.details.return_to;return typeof e=="string"?e:void 0}var Z=["describe","changes","read","query"];function F(i){let e=new Uint8Array(i);return crypto.getRandomValues(e),Te(e)}function Te(i){let e="";for(let t of i)e+=String.fromCharCode(t);return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function ki(i){let e=i.replaceAll("-","+").replaceAll("_","/").padEnd(Math.ceil(i.length/4)*4,"="),t=atob(e),n=new Uint8Array(new ArrayBuffer(t.length));for(let o=0;o<t.length;o+=1)n[o]=t.charCodeAt(o);return n}function ee(i){return{...i,credentials:"omit",targetAddressSpace:"loopback"}}async function Ie(){if(typeof navigator>"u"||!navigator.permissions?.query)return null;try{return(await navigator.permissions.query({name:"local-network-access"})).state}catch{return null}}function fe(i){return i===404||i===405||i===426||i>=500}function et(i,e){return e&&typeof e=="object"&&!Array.isArray(e)&&e.dry_run===!0?!1:i==="sync"&&e!==null&&typeof e=="object"&&!Array.isArray(e)&&e.action==="mutate"||i==="create"||i==="update"||i==="delete"||i==="rename"||i==="create_type"||i==="update_type"||i==="apply_type_pack"||i==="put_timer"||i==="cancel_timer"||i==="reconcile_timers"}function L(i){return[...new Set(i)]}function Ri(i,e){return i.grantId||e.grantId?i.grantId===e.grantId&&i.keyHandle===e.keyHandle&&i.encryption?.key_id===e.encryption?.key_id:i.accessToken===e.accessToken}function te(i){if(i?.aborted)throw l("operation_cancelled","The operation was cancelled before it changed the collection.",{operationOutcome:"not_sent",cause:i.reason})}function zt(i,e,t,n){return i instanceof C?i:e?.aborted?t?U(i):l("operation_cancelled","The operation was cancelled before it changed the collection.",{operationOutcome:"not_sent",cause:i}):t?U(i):i instanceof TypeError?l(n,n==="hosted_provider_unavailable"?"The hosted collection provider is unavailable.":"The Connect relay is unavailable.",{cause:i}):i instanceof Error?i:new Error(String(i))}function Dt(i,e){return e?.aborted===!0||i instanceof C&&i.code==="operation_cancelled"}function Oi(i,e){if(e.dry_run!==!0||e.would_rename!==!0||e.from!==i.from||e.to!==i.to)throw l("invalid_preflight","The rename preview does not match this mutation. Run the preview again.")}function Ti(i,e){if(e.dry_run!==!0||e.would_delete!==!0||e.path!==i.path)throw l("invalid_preflight","The delete preview does not match this mutation. Run the preview again.")}function Ii(i,e){if(i.update_refs===!1)return{affectedRecords:0,totalUnits:1,warnings:0};let t=e.references_affected??[];return{affectedRecords:new Set(t.map(n=>n.path)).size,totalUnits:1+t.length,warnings:e.warnings?.length??0}}function xi(i){return{affectedRecords:new Set((i.broken_links??[]).map(e=>e.path)).size,totalUnits:1,warnings:0}}async function Ei(i,e){let t=new TextEncoder().encode(`${i}\0${Ut(e??{})}`),n=await crypto.subtle.digest("SHA-256",t);return Te(new Uint8Array(n))}function Ut(i){return JSON.stringify(Mt(i))}function Mt(i){return Array.isArray(i)?i.map(e=>Mt(e)):i&&typeof i=="object"?Object.fromEntries(Object.entries(i).filter(([,e])=>e!==void 0).sort(([e],[t])=>e<t?-1:e>t?1:0).map(([e,t])=>[e,Mt(t)])):i}function U(i){return l("operation_outcome_unknown","The write may have completed, but mdbase could not recover its authoritative result. Retry the exact same write to recover safely.",{operationOutcome:"unknown",cause:i})}var tt=class{constructor(e,t){this.connect=e;this.operations=L(t.operations??Z),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();if(e){let t=await this.handleAuthorizationCallback(e);if(!t.ok)return t}else this.autoSelectOnlyConnection();return this.refresh(),O(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 n=this.connect.connection(e);return n?(this.unavailableReason="not_authorized",this.selection.select(e,t),this.refresh(),O(n)):A(R("unknown_collection","This collection is not authorized for this application."))}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 n=this.selection.selectedCollectionId();if(e==="selected"&&!n)return A(R("collection_not_selected","Choose a collection before updating its access."));let o=typeof e=="object"?e.collectionId:e==="selected"?n:null;this.transactionDepth+=1;try{let r=await this.connect.authorize({...t,operations:this.operations,target:o===null?{kind:"choose"}:{kind:"collection",collectionId:o},returnTo:this.selection.authorizationReturnTo()});return r.ok&&r.value.kind==="connected"&&this.selection.finishAuthorization(r.value.returnTo,r.value.connection.collectionId),r}finally{this.transactionDepth-=1,this.refresh()}}async ensureOperations(e){let t=this.snapshot;if(t.status!=="ready")return A(R("collection_not_ready","Choose an authorized collection first."));let n=L(e),o=t.connection.authorizationCapabilities(n);if(o.sufficient)return O({kind:"unchanged",connection:t.connection});this.transactionDepth+=1;try{let r=await this.connect.authorize({operations:L([...o.grantedOperations,...o.missingOperations]),target:{kind:"collection",collectionId:t.collectionId},returnTo:this.selection.authorizationReturnTo()});return r.ok&&r.value.kind==="connected"&&this.selection.finishAuthorization(r.value.returnTo,r.value.connection.collectionId),r}finally{this.transactionDepth-=1,this.refresh()}}handleAuthorizationCallback(e){if(!Ze(e))return Promise.resolve(A(R("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(n=>{if(!n.ok){let r=Si(n.problem);return this.selection.clearAuthorizationCallback(r),this.refresh(),n}let o=n.value;return this.unavailableReason="not_authorized",this.selection.finishAuthorization(o.returnTo,o.connection.collectionId),this.refresh(),O(o.connection,n.diagnostics)}).catch(n=>{throw this.selection.clearAuthorizationCallback(),this.refresh(),n}).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(),n=e?this.connect.connection(e):null;n?.collectionId!==this.activeCollectionId&&(this.stopActiveConnection?.(),this.activeCollectionId=n?.collectionId??null,this.stopActiveConnection=n?.onConnectionChange(a=>{!a&&this.selection.selectedCollectionId()===n.collectionId&&(this.unavailableReason="authorization_lost"),this.refresh()}));let o;if(!e)o={status:"unselected",connections:t};else if(!n||!n.info())o={status:"unavailable",collectionId:e,reason:this.connect.unavailableReason(e)??this.unavailableReason,connections:t};else{let a=n.info();o={status:"ready",collectionId:e,connection:n,info:a,access:n.authorizationCapabilities(this.operations),connections:t}}let r=so(o);if(r!==this.snapshotKey){this.snapshot=o,this.snapshotKey=r;for(let a of this.listeners)a()}}};function so(i){return i.status==="unselected"?JSON.stringify({status:i.status,connections:i.connections}):i.status==="unavailable"?JSON.stringify({status:i.status,collectionId:i.collectionId,reason:i.reason,connections:i.connections}):JSON.stringify({status:i.status,collectionId:i.collectionId,info:i.info,access:i.access,connections:i.connections})}var it=class{values=new Map;read(e){return this.values.get(e)??null}write(e,t){this.values.set(e,t)}remove(e){this.values.delete(e)}},xe=class{constructor(e,t){this.connect=e;this.options=t;this.verificationStore=t.verificationStore??po()}connect;options;listeners=new Set;verificationStore;snapshot={status:"opening",connections:[]};manifest=null;base=null;stopBase;reviewEntries=[];verificationGeneration=0;async start(){let e=await this.connect.manifest();if(!e.ok)return e;let t=e.value.requirements?.capabilities;if(!t)return A(R("invalid_application_manifest","Application sessions require a versioned semantic capability contract.",{details:{issues:[{path:"/requirements/capabilities",keyword:"required",message:"is required for application sessions",params:{}}]}}));this.manifest=e.value,this.base=new tt(this.connect,{selection:this.options.selection,autoSelect:this.options.autoSelect,operations:co(t)}),this.stopBase=this.base.subscribe(()=>this.refresh());let n=await this.base.start();return n.ok?(await this.refresh(!0),O(this.snapshot)):n}destroy(){this.verificationGeneration+=1,this.stopBase?.(),this.stopBase=void 0,this.base?.destroy(),this.base=null}getSnapshot(){return this.snapshot}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}connection(){let e=this.base?.getSnapshot();return e?.status==="ready"?e.connection:null}select(e,t={}){return this.requireBase().select(e,t)}clearSelection(e={}){this.requireBase().clearSelection(e)}forget(e){this.requireBase().forget(e)}authorize(e,t={}){return this.requireBase().authorize(e,t)}handleAuthorizationCallback(e){return this.requireBase().handleAuthorizationCallback(e)}ensureCapabilities(e){let t=this.requireManifest().requirements?.capabilities,n=new Set([...t?.required??[],...t?.optional??[]]);return e.some(o=>!n.has(o))?Promise.resolve(A(R("invalid_application_manifest","Applications may only request capabilities declared in their manifest.",{details:{issues:[{path:"/requirements/capabilities",keyword:"undeclaredCapability",message:"must declare every capability requested by the application",params:{requested:e,declared:[...n]}}]}}))):this.requireBase().ensureOperations(lo(e))}async applyDefinitionUpdates(){if(this.snapshot.status!=="definition_review_required"||this.reviewEntries.length===0)return A(R("collection_not_ready","There are no reviewed definition updates to apply."));if(this.reviewEntries.some(({assessment:t})=>!t.applicable))return A(R("collection_not_ready","Resolve the definition conflicts before applying this update."));let e=this.connection();if(!e)return A(R("collection_not_ready","The collection is not ready."));for(let{provision:t,assessment:n}of this.reviewEntries){let o=await e.applyTypePack({provision:t,installed_by:this.requireManifest().id,expected_assessment_digest:n.assessment_digest,...n.status==="downgrade"?{allow_downgrade:!0}:{}});if(!o.ok)return o}return this.reviewEntries=[],await this.verifyDefinitions(this.context(e),++this.verificationGeneration),O(this.snapshot)}async refresh(e=!1){if(!this.base||!this.manifest)return;let t=this.base.getSnapshot();this.verificationGeneration+=1;let n=this.verificationGeneration;if(this.reviewEntries=[],t.status==="unselected"){this.publish({status:"unselected",connections:t.connections});return}if(t.status==="unavailable"){this.publish(t);return}let o=this.context(t.connection);if(!o.capabilities.requiredAvailable){this.publish({status:"authorization_required",...o});return}if((this.manifest.requirements?.capabilities?.required.includes("definitions.type-pack.apply")??!1?this.manifest.provisions?.type_packs??[]:[]).length===0){this.publish({status:"ready",verification:"verified",...o});return}let s=Ft(this.manifest,t.collectionId);this.verificationStore.read(s)===Mi(this.manifest)?this.publish({status:"ready",verification:"cached",...o}):this.publish({status:"checking_definitions",...o});let c=this.verifyDefinitions(o,n);e&&await c}async verifyDefinitions(e,t){let n=this.connection(),o=this.requireManifest();if(!n||n.collectionId!==e.collectionId)return;let r=[],a=o.requirements?.capabilities?.required.includes("definitions.type-pack.apply")??!1;for(let s of a?o.provisions?.type_packs??[]:[]){let c=await n.assessTypePack({provision:s,installed_by:o.id});if(t!==this.verificationGeneration)return;if(!c.ok){this.publish({status:"blocked",problem:c.problem,...e});return}c.value.status!=="current"&&r.push({provision:s,assessment:c.value})}if(t===this.verificationGeneration){if(r.length>0){this.reviewEntries=r,this.verificationStore.remove(Ft(o,e.collectionId)),this.publish({status:"definition_review_required",updates:r.map(uo),...e});return}this.verificationStore.write(Ft(o,e.collectionId),Mi(o)),this.publish({status:"ready",verification:"verified",...e})}}context(e){let t=e.info();return{collectionId:e.collectionId,info:t,capabilities:Rt(this.requireManifest().requirements.capabilities,this.requireManifest(),t),connections:this.connect.connections()}}publish(e){if(JSON.stringify(this.snapshot)!==JSON.stringify(e)){this.snapshot=e;for(let t of this.listeners)t()}}requireBase(){if(!this.base)throw new Error("Start the application session before using it.");return this.base}requireManifest(){if(!this.manifest)throw new Error("Start the application session before using it.");return this.manifest}};function co(i){return Zt(i)}function lo(i){let e=i.flatMap(t=>He(t));return[...new Set(e)]}function uo(i){let{assessment:e}=i,t=e.status==="conflict"?"Existing user-owned resources conflict with this application definition pack.":e.status==="install"?"This collection needs the application definitions installed.":`This collection has a ${e.status} definition change to review.`;return{id:e.desired.id,name:i.provision.manifest.name??e.desired.id,status:e.status,applicable:e.applicable,assessmentDigest:e.assessment_digest,...e.current?{currentVersion:e.current.version}:{},desiredVersion:e.desired.version,resources:e.resources,contractSetups:e.contract_setups,canApply:e.applicable,reason:t}}function Ft(i,e){return`mdbase-application-session:v1:${i.id}:${e}`}function Mi(i){return JSON.stringify({capabilities:i.requirements?.capabilities,provisions:i.provisions?.type_packs??[]})}function po(){return typeof localStorage<"u"?{read:i=>localStorage.getItem(i),write:(i,e)=>localStorage.setItem(i,e),remove:i=>localStorage.removeItem(i)}:new it}function Ee(i,e){return new Promise((t,n)=>{if(e?.aborted){n(e.reason??new DOMException("Aborted","AbortError"));return}let o=setTimeout(t,i);e?.addEventListener("abort",()=>{clearTimeout(o),n(e.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}var Me=class{constructor(e){this.transport=e}transport;operation(e,t,n){return k(()=>this.transport.operation(e,t,n),It)}describe(){return this.rawOperation("describe",{},Re)}changes(e={},t){return this.rawOperation("changes",e,Et,t)}read(e){return this.envelopeOperation("read",e,q)}query(e={},t){return this.envelopeOperation("query",e,xt,t)}async*queryPages(e={},t={}){let{offset:n,limit:o,snapshot:r,...a}=e,s=fo(n,0),c=zi(t.firstPageSize??o,200),d=zi(t.pageSize??o,1e3),p=r,u=0,y=0;for(;!t.signal?.aborted;){let h=await this.query({...a,offset:s,limit:y===0?c:d,...p?{snapshot:p}:{}},{signal:t.signal});if(!h.ok){yield h;return}let g=h.value,f=g.meta?.snapshot;if(p&&f&&p!==f){yield A(R("query_snapshot_changed","The collection query snapshot changed while paging. Refresh the query before continuing."));return}!p&&f&&(p=f),u+=g.results.length;let b=!g.meta?.has_more||g.results.length===0,m={results:g.results,...g.meta?{meta:g.meta}:{},page:y,offset:s,loaded:u,complete:b,...p?{snapshot:p}:{}};if(t.onProgress?.(m),yield O(m,h.diagnostics),b)return;s+=g.results.length,y+=1}}async queryAll(e={},t={}){let n=[],o,r=[];for await(let a of this.queryPages(e,t)){if(!a.ok)return a;let s=a.value;n.push(...s.results),o=s,r.push(...a.diagnostics)}return O({results:n,meta:{...o?.meta??{},total_count:o?.meta?.total_count??n.length,has_more:o?!o.complete:!1,...o?.snapshot?{snapshot:o.snapshot}:{}}},r)}listViews(){return this.envelopeOperation("list_views",{},q)}executeView(e){return this.envelopeOperation("execute_view",e,q)}readViewSource(e){return this.envelopeOperation("read_view_source",e,q)}createViewSource(e){return this.envelopeOperation("create_view_source",e,E)}updateViewSource(e){return this.envelopeOperation("update_view_source",e,E)}deleteViewSource(e){return this.envelopeOperation("delete_view_source",e,E)}create(e){return this.envelopeOperation("create",e,E)}update(e){return this.envelopeOperation("update",e,E)}delete(e,t){return this.envelopeOperation("delete",e,E,t)}preflightDelete(e,t){return this.envelopeOperation("delete",{...e,check_backlinks:!0,dry_run:!0},E,t)}rename(e,t){return this.envelopeOperation("rename",e,E,t)}preflightRename(e,t){return this.envelopeOperation("rename",{...e,dry_run:!0},E,t)}validate(e={}){return this.envelopeOperation("validate",e,q)}readType(e){return this.envelopeOperation("read_type",e,W)}createType(e){return this.envelopeOperation("create_type",e,W)}updateType(e){return this.envelopeOperation("update_type",e,W)}assessTypePack(e){return this.envelopeOperation("assess_type_pack",e,W)}applyTypePack(e){return this.envelopeOperation("apply_type_pack",e,W)}listTimers(e){return this.rawOperation("list_timers",{namespace:e},q)}putTimer(e){return this.rawOperation("put_timer",e,E)}cancelTimer(e){return this.rawOperation("cancel_timer",e,E)}reconcileTimers(e){return this.rawOperation("reconcile_timers",e,E)}async*watch(e={}){let t=e.cursor,n=Math.max(100,e.pollIntervalMs??1e3),o=ho(e.retry),r=0,a=!1;for(e.onStatus?.({state:"connecting",...t===void 0?{}:{cursor:t}});!e.signal?.aborted;){let s=await this.changes(t===void 0?{}:{after:t,limit:200},{signal:e.signal});if(!s.ok){let p=s.problem;if(e.signal?.aborted)return;if(!o||p.recovery!=="retry"){yield s;return}if(a=!1,r+=1,o.maxAttempts!==void 0&&r>o.maxAttempts){yield s;return}let u=Math.min(o.maxDelayMs,Math.round(o.initialDelayMs*o.multiplier**(r-1)));e.onStatus?.({state:"reconnecting",...t===void 0?{}:{cursor:t},attempt:r,retryInMs:u,problem:p});try{await Ee(u,e.signal)}catch{if(!e.signal?.aborted)throw l("operation_failed","Watch retry delay failed unexpectedly.")}continue}let c=s.value;if(t===void 0){t=c.cursor;continue}if(c.reset){let p=R("change_cursor_reset","The collection change cursor expired. Refresh collection state before subscribing again.");e.onStatus?.({state:"reset_required",cursor:t,problem:p}),yield A(p);return}let d=r>0;r=0,(!a||d)&&e.onStatus?.({state:"connected",cursor:t,recovered:d}),a=!0;for(let p of c.events)yield O(p);if(t=c.cursor,!c.has_more)try{await Ee(n,e.signal)}catch{if(!e.signal?.aborted)throw l("operation_failed","Watch polling delay failed unexpectedly.")}}}rawOperation(e,t,n,o){return k(()=>this.transport.operation(e,t,o),n)}async envelopeOperation(e,t,n,o){let r=await k(()=>this.transport.operation(e,t,o),n);if(!r.ok)return r;let a=r.value;return a.valid?O(a.result,a.diagnostics):A(Tt(a))}};function ho(i){if(i!==!1)return{initialDelayMs:Math.max(0,i?.initialDelayMs??500),maxDelayMs:Math.max(0,i?.maxDelayMs??15e3),multiplier:Math.max(1,i?.multiplier??2),...i?.maxAttempts===void 0?{}:{maxAttempts:Math.max(0,i.maxAttempts)}}}function fo(i,e){return typeof i=="number"&&Number.isFinite(i)?Math.max(0,Math.floor(i)):e}function zi(i,e){return typeof i=="number"&&Number.isFinite(i)&&i>0?Math.floor(i):e}async function K(i,e,t,n){try{return await fetch(i,e)}catch(o){throw l(t,n,{cause:o})}}function Di(i){let e=new URL(i);if(e.protocol!=="http:"||!["127.0.0.1","[::1]"].includes(e.hostname)||e.username||e.password||e.pathname!=="/"||e.search||e.hash)throw l("invalid_loopback_url","loopbackUrl must be an HTTP origin on 127.0.0.1 or ::1.");return e.origin}async function ze(){let i=F(32),e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(i));return{verifier:i,challenge:Te(new Uint8Array(e))}}function P(i,e,t,n){return D(De(i)??i?.error?.code??e,i?.error_description??i?.error?.message??t,{status:n,details:i?.error?.details})}function De(i){return typeof i?.error=="string"?i.error:void 0}function nt(i,e){if(!i||typeof i!="object"||Array.isArray(i)||typeof e!="string")return!1;let t=i;if(typeof t.operations_url!="string"||typeof t.sync_url!="string"||typeof t.files_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 n=new URL(t.operations_url),o=new URL(t.sync_url),r=new URL(t.files_url);return[n,o,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(n.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(o.pathname)&&/^\/v1\/authorities\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/files$/i.test(r.pathname)&&n.origin===o.origin&&n.origin===r.origin&&n.pathname.split("/")[3]===e&&o.pathname.split("/")[3]===e&&r.pathname.split("/")[3]===e}catch{return!1}}function Ui(i,e){return nt({operations_url:i?.operationsUrl,sync_url:i?.syncUrl,files_url:i?.filesUrl,replica_id:i?.replicaId,access_token:i?.accessToken,proof_public_key:i?.proofPublicKey},e)}function ot(i){if(!i||typeof i!="object"||Array.isArray(i))return!1;let e=i,t=e.actions;if(e.kind!=="files"||e.protocol_version!==1||!Array.isArray(t)||t.length===0||t.length>6||new Set(t).size!==t.length||t.some(o=>!["list","read","add","replace","move","delete"].includes(o)))return!1;let n=e.scope;return!n||typeof n!="object"||Array.isArray(n)?!1:n.kind==="collection"?Object.keys(n).length===1:n.kind==="selected_folders"&&Object.keys(n).length===2&&Array.isArray(n.folders)&&n.folders.length>0&&n.folders.length<=100&&new Set(n.folders).size===n.folders.length&&n.folders.every(o=>typeof o=="string"&&o.length>0&&o.length<=1024&&yo(o))}function yo(i){let e=new Set([".mdbase",".git","node_modules","_contracts","_schemas","_types","_views"]);return!i.startsWith("/")&&!i.endsWith("/")&&!i.includes("\\")&&i.split("/").every(t=>{let n=t.split(".")[0]?.toUpperCase()??"";return t!==""&&t!=="."&&t!==".."&&!t.startsWith(".")&&!t.endsWith(" ")&&!t.endsWith(".")&&!/[<>:"|?*]/.test(t)&&!e.has(t.toLowerCase())&&!["CON","PRN","AUX","NUL"].includes(n)&&!/^(COM|LPT)[1-9]$/.test(n)})}function Fi(i,e){if(!i||typeof i!="object"||Array.isArray(i)||i.collection_id!==e)return!1;try{return J(i),!0}catch{return!1}}function qi(i){if(typeof i?.device_code!="string"||typeof i?.user_code!="string"||typeof i?.verification_uri!="string"||typeof i?.verification_uri_complete!="string"||!Number.isFinite(i?.expires_in)||!Number.isFinite(i?.interval))throw l("invalid_device_authorization_response","Connect returned an invalid downloaded application authorization response.");return{userCode:i.user_code,verificationUri:i.verification_uri,verificationUriComplete:i.verification_uri_complete,expiresAt:Date.now()+Math.max(1,i.expires_in)*1e3,intervalSeconds:Math.max(1,i.interval)}}function M(i){if(!i)return null;try{return JSON.parse(i)}catch{return null}}function rt(i){if(!i||typeof i!="object"||Array.isArray(i))return null;let e=i;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(n=>!n||typeof n!="object"||typeof n.type_name!="string"||!Number.isInteger(n.type_version)||!/^sha256:[0-9a-f]{64}$/.test(n.digest)||!n.fields||typeof n.fields!="object"||Array.isArray(n.fields)||Object.values(n.fields).some(o=>typeof o!="string")))?null:e}function Li(i){return i.endsWith("/")?i.slice(0,-1):i}function Ni(){if(typeof location>"u")throw l("manifest_required","manifest is required outside a browser environment.");if(location.origin==="null")throw l("manifest_required","Downloaded applications must provide their v1 portable manifest inline.");return new URL("/.well-known/mdbase-app.json",location.origin).href}function Bi(){if(typeof location>"u")throw l("redirect_uri_required","redirectUri is required outside a browser environment.");return location.href.split(/[?#]/)[0]}function Ki(i,e,t,n){if(typeof i!="string"&&i.distribution==="portable"||n)return"null";let o=new URL(t);if(["http:","https:"].includes(o.protocol))return o.origin;if(typeof location<"u")return location.origin;if(typeof i!="string")return new URL(i.homepage).origin;try{return new URL(e).origin}catch{return""}}function ji(i){let e=":token:",t=i.lastIndexOf(e);return t<0?"":i.slice(t+e.length)}function Hi(){if(typeof location>"u")throw l("callback_url_required","callbackUrl is required outside a browser environment.");return location.href}function $i(i){if(i)return new ye;if(typeof localStorage>"u")throw l("storage_required","storage is required outside a browser environment.");try{let e=`mdbase-connect:probe:${F(8)}`;return localStorage.setItem(e,"1"),localStorage.removeItem(e),localStorage}catch{return new ye}}var ye=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 Vi(i){return typeof i=="string"||i.distribution!=="portable"?!1:typeof location>"u"||location.origin==="null"||!["http:","https:"].includes(location.protocol)}function Gi(i){let e=Ut(i),t=2166136261,n=2654435769;for(let o=0;o<e.length;o+=1){let r=e.charCodeAt(o);t=Math.imul(t^r,16777619),n=Math.imul(n^r,2246822507)}return`${(t>>>0).toString(16).padStart(8,"0")}${(n>>>0).toString(16).padStart(8,"0")}`}var at=class{constructor(e){this.context=e}context;async registerNotifications(e){let t=await this.context.authorizedToken();if(!t)throw l("not_authorized","Connect this application before enabling notifications.");let o=(await this.context.register()).notifications?.criteria.map(b=>b.id)??[],r=[...new Set(e.criteria??o)],a=r.find(b=>!o.includes(b));if(a)throw l("notification_criterion_not_declared",`The application manifest does not declare notification criterion ${a}.`);if(r.length===0)throw l("notifications_not_declared","This application manifest does not declare any notification criteria.");let s=await K(`${this.context.serverUrl}/v1/notifications/vapid-public-key`,void 0,"notifications_unavailable","Push notifications are unavailable."),c=await s.json();if(!s.ok)throw P(c,"notifications_unavailable","Push notifications are unavailable.",s.status);let d=await e.serviceWorker.pushManager.getSubscription();d||(d=await e.serviceWorker.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:ki(c.public_key)}));let p=d.toJSON();if(!p.endpoint||!p.keys?.p256dh||!p.keys.auth)throw l("invalid_push_subscription","The browser returned an incomplete push subscription.");let u=M(this.context.storage.getItem(this.context.notificationKey())),y=e.installationId??u?.installationId??F(24),h=await K(`${this.context.serverUrl}/v1/notifications/channels`,{method:"POST",headers:{authorization:`Bearer ${t.accessToken}`,"content-type":"application/json"},body:JSON.stringify({installation_id:y,criteria:r,subscription:{endpoint:p.endpoint,expirationTime:p.expirationTime??null,keys:p.keys}})},"notification_registration_failed","Could not register push notifications."),g=await h.json();if(!h.ok)throw P(g,"notification_registration_failed","Could not register push notifications.",h.status);u?.channelId&&u.channelId!==g.channel_id&&fetch(`${this.context.serverUrl}/v1/notifications/channels/${u.channelId}`,{method:"DELETE",headers:{authorization:`Bearer ${t.accessToken}`}}).catch(()=>{});let f={channelId:g.channel_id,installationId:y,criteria:r};return this.context.storage.setItem(this.context.notificationKey(),JSON.stringify(f)),f}async registerNativeNotifications(e){let t=await this.context.authorizedToken();if(!t)throw l("not_authorized","Connect this application before enabling notifications.");let n=await this.context.register();if(n.notifications?.native_delivery?.mode!=="managed_fcm")throw l("managed_fcm_not_declared","This application does not declare Connect-managed native notifications.");let o=n.notifications.criteria.map(h=>h.id),r=[...new Set(e.criteria??o)],a=r.find(h=>!o.includes(h));if(a)throw l("notification_criterion_not_declared",`The application manifest does not declare notification criterion ${a}.`);if(r.length===0)throw l("notifications_not_declared","This application manifest does not declare any notification criteria.");let s=this.context.notificationKey("fcm"),c=M(this.context.storage.getItem(s)),d=e.installationId??c?.installationId??F(24),p=await K(`${this.context.serverUrl}/v1/notifications/channels`,{method:"POST",headers:{authorization:`Bearer ${t.accessToken}`,"content-type":"application/json"},body:JSON.stringify({installation_id:d,criteria:r,transport:"fcm",token:e.token})},"notification_registration_failed","Could not register native notifications."),u=await p.json();if(!p.ok)throw P(u,"notification_registration_failed","Could not register native notifications.",p.status);c?.channelId&&c.channelId!==u.channel_id&&this.deleteNotificationChannel(c.channelId,t.accessToken).catch(()=>{});let y={channelId:u.channel_id,installationId:d,transport:"fcm",criteria:r};return this.context.storage.setItem(s,JSON.stringify(y)),y}async unregisterNativeNotifications(){let e=this.context.notificationKey("fcm"),t=M(this.context.storage.getItem(e)),n=await this.context.authorizedToken();if(t?.channelId&&!n)throw l("not_authorized","Reconnect this application before disabling native notifications.");t?.channelId&&n&&await this.deleteNotificationChannel(t.channelId,n.accessToken),this.context.storage.removeItem(e)}async unregisterNotifications(e){let t=M(this.context.storage.getItem(this.context.notificationKey())),n=await this.context.authorizedToken();if(t?.channelId&&!n)throw l("not_authorized","Reconnect this application before disabling push notifications.");if(t?.channelId&&n){let r=await K(`${this.context.serverUrl}/v1/notifications/channels/${t.channelId}`,{method:"DELETE",headers:{authorization:`Bearer ${n.accessToken}`}},"notification_unregistration_failed","Could not unregister push notifications.");if(!r.ok&&r.status!==404){let a=await r.json();throw P(a,"notification_unregistration_failed","Could not unregister push notifications.",r.status)}}this.context.storage.removeItem(this.context.notificationKey()),await(await e?.pushManager.getSubscription())?.unsubscribe()}async deleteNotificationChannel(e,t){let n=await K(`${this.context.serverUrl}/v1/notifications/channels/${e}`,{method:"DELETE",headers:{authorization:`Bearer ${t}`}},"notification_unregistration_failed","Could not unregister push notifications.");if(!n.ok&&n.status!==404){let o=await n.json();throw P(o,"notification_unregistration_failed","Could not unregister push notifications.",n.status)}}};async function st(i,e,t,n,o,r){if(!i.authority)throw l("not_remote_authority","This authorization has no remote authority endpoint.");let a=t===""||t.startsWith("?")?t:`/${t}`,s=`${i.authority.filesUrl}${a}`,c=n===void 0?void 0:JSON.stringify(n),d=await r(i,e,s,c,i.authority.accessToken);return fetch(s,{method:e,redirect:"error",headers:{authorization:`Bearer ${i.authority.accessToken}`,...c===void 0?{}:{"content-type":"application/json"},...d},...c===void 0?{}:{body:c},...o?{signal:o}:{}})}async function Yi(i,e,t,n,o,r,a){let s=i,c=await st(s,e,t,n,o,a);if(c.status===401&&s.refreshToken){if(s=await r(),!s.authority||!s.fileCapability)throw l("authority_authorization_changed","Reconnect this collection before accessing its files.");c=await st(s,e,t,n,o,a)}let d=await c.json().catch(()=>({}));if(!c.ok)throw P(d,"operation_failed","Collection file request failed.",c.status);return d}async function Ji(i,e,t,n,o,r){let a=i,s=await st(a,"GET",e,void 0,n,r);if(s.status===401&&a.refreshToken){if(a=await o(),!a.authority||!a.fileCapability)throw l("authority_authorization_changed","Reconnect this collection before accessing its files.");s=await st(a,"GET",e,void 0,n,r)}if(!s.ok){let d=await s.json().catch(()=>({}));throw P(d,"operation_failed","Collection file range request failed.",s.status)}let c=s.headers.get("content-length");if(c===null||!/^(0|[1-9][0-9]*)$/u.test(c)||Number(c)!==t)throw await s.body?.cancel().catch(()=>{}),l("invalid_operation_response","The hosted file response declared an unexpected byte length.");if(!s.body)throw l("invalid_operation_response","The hosted file response did not contain a byte stream.");return s.body}var ct=class{constructor(e){this.options=e}options;async control(e,t,n,o,r){me(e);let a=wo(t,n,o),s=await this.encryptControl(e,a),c;if(await this.options.shouldAttemptDirect(e)){try{c=await fetch(`${this.options.loopbackUrl}/v1/files/control`,ee({method:"POST",headers:{"content-type":"application/mdbase-connect+json"},body:JSON.stringify(s),signal:r}))}catch(d){if(r?.aborted)throw d;this.options.onDirectUnavailable()}if(c&&!fe(c.status))return c.ok&&this.options.onDirectAvailable(),this.decryptControlResponse(e,s,c);c&&this.options.onDirectUnavailable()}return c=await this.sendRelayControl(e,s,r),await go(c,e)&&(e=await this.options.refreshAuthorization(),qt(e),s=await this.encryptControl(e,a),c=await this.sendRelayControl(e,s,r)),c.ok&&this.options.onRelayAvailable(),this.decryptControlResponse(e,s,c)}async decryptControlResponse(e,t,n){let o=await n.json().catch(()=>({}));if(!n.ok)throw P(o,"operation_failed","Collection file request failed.",n.status);let r=o?.envelope;if(!r)throw l("invalid_encrypted_response","The connector omitted its encrypted file response.");let a=await se(this.options.keyStore,e.keyHandle,Lt(e),t,r);return a.ok||vo(a.problem),a.result}async uploadChunk(e,t,n,o){let a=await this.localFileToken(e,"upload"),s=await Qi(this.options.keyStore,a,e,t,n),c;if(await this.options.shouldAttemptDirect(a)){try{c=await fetch(`${this.options.loopbackUrl}/v1/files/upload`,ee(Xi(s,o)))}catch(d){if(o?.aborted)throw d;this.options.onDirectUnavailable()}if(c&&!fe(c.status))return c.ok&&this.options.onDirectAvailable(),mo(c,"Encrypted file chunk upload failed.");c&&this.options.onDirectUnavailable()}if(c=await this.sendRelayUpload(a,s,o),c.status===401&&a.refreshToken&&(a=await this.options.refreshAuthorization(),qt(a),s=await Qi(this.options.keyStore,a,e,t,n),c=await this.sendRelayUpload(a,s,o)),!c.ok){let d=await c.json().catch(()=>({}));throw P(d,"operation_failed","Encrypted file chunk upload failed.",c.status)}this.options.onRelayAvailable()}async downloadChunk(e,t,n){let o=await this.localFileToken(e,"download"),r;if(await this.options.shouldAttemptDirect(o)){try{r=await fetch(`${this.options.loopbackUrl}/v1/files/download/${encodeURIComponent(o.grantId)}/${encodeURIComponent(e.transfer_id)}/${t}`,ee({method:"GET",signal:n}))}catch(a){if(n?.aborted)throw a;this.options.onDirectUnavailable()}if(r&&!fe(r.status))return r.ok&&this.options.onDirectAvailable(),this.decryptDownloadResponse(o,e,t,r);r&&this.options.onDirectUnavailable()}return r=await this.sendRelayDownload(o,e,t,n),r.status===401&&o.refreshToken&&(o=await this.options.refreshAuthorization(),qt(o),r=await this.sendRelayDownload(o,e,t,n)),r.ok&&this.options.onRelayAvailable(),this.decryptDownloadResponse(o,e,t,r)}async decryptDownloadResponse(e,t,n,o){if(!o.ok){let s=await o.json().catch(()=>({}));throw P(s,"operation_failed","Encrypted file chunk download failed.",o.status)}if(o.headers.get("content-type")?.split(";",1)[0]!=="application/mdbase-connect-file")throw l("invalid_operation_response","The connector returned an invalid file response media type.");let r=new Uint8Array(await o.arrayBuffer()),a;try{bo(t,n,r),a=await(await Zi(this.options.keyStore,e,t)).decryptChunk(r)}catch(s){throw s instanceof C?s:l("invalid_operation_response","The connector returned an invalid encrypted file frame.",{cause:s})}if(a.byteLength!==Nt(t,n))throw l("invalid_operation_response","The connector returned a truncated file chunk.");return a}encryptControl(e,t){return me(e),Y(this.options.keyStore,e.keyHandle,Lt(e),"file_control",t)}sendRelayControl(e,t,n){return fetch(`${this.options.serverUrl}/v1/authorities/${encodeURIComponent(e.collectionId)}/files/control`,{method:"POST",headers:{authorization:`Bearer ${e.accessToken}`,"content-type":"application/json"},body:JSON.stringify(t),signal:n})}sendRelayUpload(e,t,n){return fetch(`${this.options.serverUrl}/v1/authorities/${encodeURIComponent(e.collectionId)}/files/upload`,{...Xi(t,n),headers:{authorization:`Bearer ${e.accessToken}`,"content-type":"application/mdbase-connect-file"}})}sendRelayDownload(e,t,n,o){return fetch(`${this.options.serverUrl}/v1/authorities/${encodeURIComponent(e.collectionId)}/files/download/${encodeURIComponent(t.transfer_id)}/${n}`,{method:"GET",headers:{authorization:`Bearer ${e.accessToken}`},signal:o})}async localFileToken(e,t){let n=await this.options.authorizedToken();if(!n||n.authority||!n.fileCapability||!n.encryption||!n.grantId||!n.keyHandle||e.direction!==t||e.protection!=="grant_aead_v1")throw l("not_authorized","This connection cannot use encrypted local file delivery.");return lt(e),n}};function qt(i){if(i.authority||!i.fileCapability)throw l("not_authorized","This connection cannot use encrypted local file delivery.");me(i)}async function Qi(i,e,t,n,o){let r=_o(e,t,n,o.byteLength);return(await Zi(i,e,t)).encryptChunk("upload_chunk",r,o)}function Xi(i,e){return{method:"POST",headers:{"content-type":"application/mdbase-connect-file"},body:Uint8Array.from(i).buffer,signal:e}}async function mo(i,e){if(i.ok)return;let t=await i.json().catch(()=>({}));throw P(t,"operation_failed",e,i.status)}async function go(i,e){return e.refreshToken?i.status===401?!0:i.status!==409?!1:(await i.clone().json().catch(()=>null))?.error?.code==="encryption_binding_stale":!1}function me(i){if(!i.encryption||!i.grantId||!i.keyHandle)throw l("missing_grant_key","Reconnect this application to restore encrypted file access.")}function Lt(i){return me(i),{grantId:i.grantId,applicationId:i.clientId,encryption:i.encryption}}function Zi(i,e,t){return me(e),ce.open(i,e.keyHandle,{...Lt(e),authorityId:e.encryption.connector_id,transferId:t.transfer_id,direction:t.direction})}function _o(i,e,t,n){me(i);let o=lt(e),r=Nt(e,t);if(n!==r)throw l("invalid_request","The file chunk has the wrong byte length.");return{protocol_version:1,protection:"grant_aead_v1",grant_id:i.grantId,authority_id:i.encryption.connector_id,collection_id:i.collectionId,transfer_id:e.transfer_id,direction:e.direction,chunk_size:o,chunk_index:t,offset:t*o,plaintext_length:n,total_size:e.total_size,scope_epoch:i.encryption.scope_epoch,key_id:i.encryption.key_id}}function bo(i,e,t){let n=je(t),o=Nt(i,e),r=lt(i);if(n.kind!=="download_chunk"||n.header.chunk_index!==e||n.header.chunk_size!==r||n.header.offset!==e*r||n.header.plaintext_length!==o||n.header.total_size!==i.total_size)throw l("invalid_operation_response","The connector returned a file frame for a different chunk.")}function vo(i){throw D(i.code==="unknown"?i.server_code:i.code,i.message,{details:i.details,operationOutcome:i.operation_outcome??"rejected",traceId:i.trace_id})}function wo(i,e,t){if(i==="GET"&&(e===""||e.startsWith("?"))){let o=new URLSearchParams(e.startsWith("?")?e.slice(1):e),r=o.get("limit");return{protocol_version:1,type:"list_files",...o.get("folder")?{folder:o.get("folder")}:{},...o.get("after")?{after:o.get("after")}:{},...r?{limit:Number(r)}:{}}}let n=e.split("/");if(i==="GET"&&n.length===2&&n[0]==="transfers")return Wi("get_file_transfer_status",n[1]);if(i==="DELETE"&&n.length===2&&n[0]==="transfers")return Wi("abort_file_transfer",n[1]);if(i==="POST"&&Co(t)){let o=e==="uploads"?"open_file_upload":e==="downloads"?"open_file_download":n.length===3&&n[0]==="uploads"&&n[2]==="commit"?"commit_file_upload":n.length===2&&n[1]==="move"&&t.file_id===decodeURIComponent(n[0])?"move_file":n.length===2&&n[1]==="delete"&&t.file_id===decodeURIComponent(n[0])?"delete_file":null;if(o&&t.type===o)return{...t}}throw l("invalid_request","The file control request path is invalid.")}function Wi(i,e){return{protocol_version:1,type:i,transfer_id:decodeURIComponent(e)}}function lt(i){if(i.strategy.kind!=="framed_chunks"||!Number.isSafeInteger(i.strategy.chunk_size)||i.strategy.chunk_size<=0)throw l("invalid_operation_response","The connector returned an invalid framed transfer strategy.");return i.strategy.chunk_size}function Nt(i,e){let t=lt(i);if(!Number.isSafeInteger(e)||e<0||!Number.isSafeInteger(i.total_size)||i.total_size<0)throw l("invalid_request","The file chunk index is invalid.");let n=e*t;if(!Number.isSafeInteger(n)||n>=i.total_size)throw l("invalid_request","The file chunk index is outside the transfer.");return Math.min(t,i.total_size-n)}function Co(i){return i!==null&&typeof i=="object"&&!Array.isArray(i)}var dt=class{constructor(e){this.options=e;this.local=new ct(e)}options;local;async control(e,t="",n,o){let r=await this.requireFileToken();return r.authority?Yi(r,e,t,n,o,this.options.refreshAuthorization,this.options.authorityProofHeaders):this.local.control(r,e,t,n,o)}uploadChunk(e,t,n,o){return this.local.uploadChunk(e,t,n,o)}downloadChunk(e,t,n){return this.local.downloadChunk(e,t,n)}async downloadHostedPart(e,t,n,o){let r=await this.requireFileToken();if(!r.authority)throw l("not_remote_authority","Hosted file delivery requires a remote authority endpoint.");return Ji(r,`downloads/${encodeURIComponent(e.transfer_id)}/parts/${t}`,n,o,this.options.refreshAuthorization,this.options.authorityProofHeaders)}async requireFileToken(){let e=await this.options.authorizedToken();if(!e?.fileCapability)throw l("not_authorized","This connection has no file capability.");return e}};var ut=class{serverUrl;storage;keyStore;directAccessMode;loopbackUrl;collectionId;internals;onChange;files;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.files=new dt({keyStore:this.keyStore,serverUrl:this.serverUrl,loopbackUrl:this.loopbackUrl,authorizedToken:()=>this.authorizedToken(),refreshAuthorization:()=>this.refreshAuthorization(),shouldAttemptDirect:t=>this.shouldAttemptDirect(t),onDirectAvailable:()=>{this.markDirectAvailable(),this.setRoute("direct")},onDirectUnavailable:()=>this.markDirectUnavailable(),onRelayAvailable:()=>this.setRoute("relay"),authorityProofHeaders:(t,n,o,r,a)=>this.authorityProofHeaders(t,n,o,r,a)}),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 Ie();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=M(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 n=this.pendingMutation();if(!n)throw l("no_pending_mutation","There is no interrupted mutation to resume.");return this.performOperation(n.operation,e,t)}async performOperation(e,t,n={}){te(n.signal);let o=this.currentToken();if(!o)throw l("not_authorized","Connect this application before accessing a collection.");if(!o.operations.includes(e))throw l("insufficient_access",`This connection does not allow ${e}.`,{details:{required_operations:[e],granted_operations:[...o.operations],missing_operations:[e]}});let r=await this.shouldAttemptDirect(o);if(!r&&(o=await this.authorizedToken(),!o))throw l("not_authorized","Reconnect this application to continue.");let a;try{a=await this.sendOperation(o,e,t,r,n)}catch(p){throw zt(p,n.signal,et(e,t)&&this.pendingMutation()!==null,o.authority?"hosted_provider_unavailable":"relay_unavailable")}let s=a.response,c=s.status===409&&(await s.clone().json().catch(()=>null))?.error?.code==="encryption_binding_stale";if((s.status===401||c)&&o.refreshToken){if(a.pendingMutation&&(a.directDeliveryUncertain||a.encryptedRequest&&a.resumingMutation))throw l("operation_outcome_unknown","The direct operation may have completed, but its encrypted grant changed before the response could be recovered. Refresh before making another change.",{operationOutcome:"unknown"});a.pendingMutation&&this.clearPendingMutation(),o=await this.refreshAuthorization(),r=await this.shouldAttemptDirect(o);try{a=await this.sendOperation(o,e,t,r,n)}catch(p){throw zt(p,n.signal,et(e,t)&&this.pendingMutation()!==null,o.authority?"hosted_provider_unavailable":"relay_unavailable")}s=a.response}let d;try{d=await s.json()}catch(p){throw a.pendingMutation?U(p):l("invalid_operation_response","The collection authority returned a response that is not valid JSON.",{cause:p})}if(!s.ok){let p=P(d,"operation_failed","Collection operation failed.",s.status);throw a.pendingMutation&&(a.directDeliveryUncertain||a.encryptedRequest&&a.resumingMutation)?U(p):(a.pendingMutation&&!a.directDeliveryUncertain&&this.clearPendingMutation(),p.code==="direct_operation_rejected"&&p.status===403&&this.invalidateRejectedAuthorization(o),p)}if(a.encryptedRequest){let p=d?.envelope;if(!p||!o.encryption||!o.grantId||!o.keyHandle)throw a.pendingMutation?U(new Error("Encrypted operation response was missing its envelope.")):l("invalid_encrypted_response","The relay did not return an encrypted connector response.");try{let u=await se(this.keyStore,o.keyHandle,{grantId:o.grantId,applicationId:o.clientId,encryption:o.encryption},a.encryptedRequest,p);if(a.pendingMutation&&this.clearPendingMutation(),!u.ok)throw D(u.problem.code==="unknown"?u.problem.server_code:u.problem.code,u.problem.message,{details:u.problem.details,operationOutcome:u.problem.operation_outcome??"rejected",traceId:u.problem.trace_id});return u.result}catch(u){throw u instanceof C?u:u instanceof v?a.pendingMutation?U(u):D(u.code,u.message):u}}if(d?.protocol_version!==1||d?.request_id!==a.requestId)throw a.pendingMutation?U(new Error("Operation response protocol or request ID did not match.")):l("invalid_operation_response","The collection authority returned a response for a different protocol request.");if(d.ok===!1)throw ve(d.problem)?(a.pendingMutation&&this.clearPendingMutation(),new C(d.problem)):a.pendingMutation?U(new Error("Operation rejection did not contain a canonical problem.")):l("invalid_operation_response","The collection authority returned an invalid operation problem.");if(d.ok!==!0||!("result"in d))throw a.pendingMutation?U(new Error("Successful operation response did not contain a result.")):l("invalid_operation_response","The collection authority returned an incomplete operation response.");return a.pendingMutation&&this.clearPendingMutation(),d.result}async performAuthoritySyncRequest(e,t,n,o,r){let a=await this.authorizedToken();if(!a?.authority||a.collectionId!==e||a.authority.replicaId!==t)throw l("authority_authorization_changed","Reconnect this collection authority before synchronizing.");let s=await this.sendAuthoritySyncRequest(a,n,o,r);if(s.status===401&&a.refreshToken){if(a=await this.refreshAuthorization(),!a.authority||a.collectionId!==e||a.authority.replicaId!==t)throw l("authority_authorization_changed","Reconnect this collection authority before synchronizing.");s=await this.sendAuthoritySyncRequest(a,n,o,r)}let c=await s.json();if(!s.ok)throw P(c,"sync_failed","Collection synchronization failed.",s.status);return c}async sendAuthoritySyncRequest(e,t,n,o){if(!e.authority)throw l("not_remote_authority","This authorization has no remote authority endpoint.");let r=`${e.authority.syncUrl}/${n}`,a=o===void 0?void 0:JSON.stringify(o),s=await this.authorityProofHeaders(e,t,r,a,e.authority.accessToken);return fetch(r,{method:t,headers:{authorization:`Bearer ${e.authority.accessToken}`,...o===void 0?{}:{"content-type":"application/json"},...s},...a===void 0?{}:{body:a}})}async sendOperation(e,t,n,o,r={}){let a=n??{},s,c=!1,d=!1,p=crypto.randomUUID(),u=null,y;if(et(t,n)){if(y=await Ei(t,n),u=M(this.storage.getItem(this.pendingMutationKey())),u){if(u.collectionId!==e.collectionId||u.grantId!==e.grantId||u.keyId!==e.encryption?.key_id||u.operation!==t||u.inputFingerprint!==y)throw l("pending_mutation_unresolved","A previous write still has an unknown outcome. Retry that exact write before making another change.");p=u.requestId,d=!0}c=!0}if(e.encryption&&!e.authority){if(!e.grantId||!e.keyHandle)throw l("missing_grant_key","Reconnect this application to restore encrypted access.");try{if(c)if(u){if(!u.envelope)throw l("pending_mutation_unresolved","The pending write belongs to a different transport. Reconnect before retrying it.");s=u.envelope}else s=await Y(this.keyStore,e.keyHandle,{grantId:e.grantId,applicationId:e.clientId,encryption:e.encryption},t,n,p),this.storage.setItem(this.pendingMutationKey(),JSON.stringify({collectionId:e.collectionId,...e.grantId?{grantId:e.grantId}:{},keyId:e.encryption.key_id,operation:t,inputFingerprint:y,requestId:p,envelope:s,createdAt:Date.now()}));else s=await Y(this.keyStore,e.keyHandle,{grantId:e.grantId,applicationId:e.clientId,encryption:e.encryption},t,n)}catch(m){throw m instanceof v?D(m.code,m.message):m}a=s}else a={protocol_version:1,request_id:p,input:a},c&&!u&&this.storage.setItem(this.pendingMutationKey(),JSON.stringify({collectionId:e.collectionId,...e.grantId?{grantId:e.grantId}:{},operation:t,inputFingerprint:y,requestId:p,createdAt:Date.now()}));if(o&&s&&!e.authority){let m=!1;try{let T=await fetch(`${this.loopbackUrl}/v1/operations`,ee({method:"POST",headers:{"content-type":"application/mdbase-connect+json"},body:JSON.stringify(s),signal:r.signal}));if(!fe(T.status))return T.ok&&(this.markDirectAvailable(),this.setRoute("direct")),{response:T,requestId:p,encryptedRequest:s,pendingMutation:c,resumingMutation:d};m=T.status>=500,this.markDirectUnavailable()}catch(T){if(r.signal?.aborted)throw T;m=!0,await Ie()==="denied"?this.setDirectStatus("denied"):this.markDirectUnavailable()}let w;try{w=e.expiresAt>Date.now()+3e4?e:await this.refreshAuthorization()}catch(T){throw c&&(m||d)?U(T):T}let I;try{I=await fetch(`${this.serverUrl}/v1/authorities/${encodeURIComponent(w.collectionId)}/operations/${t}`,{method:"POST",headers:{authorization:`Bearer ${w.accessToken}`,"content-type":"application/json"},body:JSON.stringify(s),signal:r.signal})}catch(T){throw c&&(m||d)?U(T):T}return I.ok&&this.setRoute("relay"),{response:I,requestId:p,encryptedRequest:s,directDeliveryUncertain:m,pendingMutation:c,resumingMutation:d}}let h=e.authority?`${e.authority.operationsUrl}/${t}`:`${this.serverUrl}/v1/authorities/${encodeURIComponent(e.collectionId)}/operations/${t}`,g=JSON.stringify(a),f=e.authority?await this.authorityProofHeaders(e,"POST",h,g,e.authority.accessToken):{},b=await fetch(h,{method:"POST",headers:{authorization:`Bearer ${e.authority?.accessToken??e.accessToken}`,"content-type":"application/json",...f},body:g,signal:r.signal});return b.ok&&this.setRoute(e.authority?"remote":"relay"),{response:b,requestId:p,encryptedRequest:s,pendingMutation:c,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 Ie();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`,ee({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 Ie()==="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=M(this.storage.getItem(this.tokenKey()));!t||!Ri(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=M(e),n=o=>(this.internals.removeToken(this.collectionId,typeof o=="string"?o:void 0,"invalid_stored_grant"),null);if(!t)return e&&n(),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(o=>typeof o!="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))||!rt(t.scope)||t.fileCapability&&!ot(t.fileCapability)||t.authority&&!Ui(t.authority,t.collectionId))return n(t.keyHandle);if(this.internals.relayEncryption==="required"){if(t.authority){if(!t.keyHandle||!t.authority.proofPublicKey)return n(t.keyHandle)}else if(!t.grantId||!t.keyHandle||!Fi(t.encryption,t.collectionId))return n(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 l("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 l("not_authorized","Reconnect this application to continue.");if((e.refreshExpiresAt??0)<=Date.now())throw l("relay_authorization_expired","Direct access is still available on this computer, but using the relay requires reconnecting this application.");let t=e.refreshToken,n=`${this.serverUrl}/oauth/token`,o=new URLSearchParams({grant_type:"refresh_token",refresh_token:e.refreshToken,client_id:e.clientId}).toString(),r=e.authority?await this.authorityProofHeaders(e,"POST",n,o,e.refreshToken):{},a=await fetch(n,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",...r},body:o}),s=await a.json();if(!a.ok){let c=this.currentToken();if(c?.refreshToken&&c.refreshToken!==t)return c;throw this.directCapable(e)||this.internals.removeToken(this.collectionId,e.keyHandle),(De(s)??s?.error?.code)==="invalid_grant"?l("authorization_expired",s?.error_description??s?.error?.message??"Reconnect this application to continue.",{status:a.status}):P(s,"authorization_expired","Reconnect this application to continue.",a.status)}return this.storeTokenResponse(s,e.clientId,e.keyHandle)}async authorityProofHeaders(e,t,n,o,r){if(!e.authority?.proofPublicKey)return{};if(!e.keyHandle)throw l("missing_grant_key","Reconnect this application to restore remote authority request signing.");try{let a=new URL(n);return await ci(this.keyStore,e.keyHandle,e.authority.proofPublicKey,{method:t,target:`${a.pathname}${a.search}`,body:o,credential:r})}catch(a){throw a instanceof v?D(a.code,a.message):a}}storeTokenResponse(e,t,n){if(e.collection_id!==this.collectionId)throw l("collection_mismatch","The refreshed authorization belongs to a different collection.");let o=this.internals.storeTokenResponse(e,t,n);return this.currentRoute=o.authority?"remote":"relay",this.directStatus=o.authority||this.directAccessMode==="disabled"?"disabled":"unavailable",this.emitConnection(),o}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 Po=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ao=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ge=class{state=Ao.slice();block=new Uint8Array(64);words=new Uint32Array(64);blockLength=0;byteLength=0;finished=!1;update(e){if(this.finished)throw new Error("SHA-256 digest is already finalized.");if(this.byteLength+=e.byteLength,!Number.isSafeInteger(this.byteLength))throw new Error("SHA-256 input exceeds the safe browser byte range.");let t=0;if(this.blockLength>0){let n=Math.min(64-this.blockLength,e.byteLength);this.block.set(e.subarray(0,n),this.blockLength),this.blockLength+=n,t+=n,this.blockLength===64&&(this.compress(this.block),this.blockLength=0)}for(;t+64<=e.byteLength;)this.compress(e.subarray(t,t+64)),t+=64;return t<e.byteLength&&(this.block.set(e.subarray(t),0),this.blockLength=e.byteLength-t),this}digestHex(){if(this.finished)throw new Error("SHA-256 digest is already finalized.");this.finished=!0,this.block[this.blockLength]=128,this.block.fill(0,this.blockLength+1),this.blockLength>=56&&(this.compress(this.block),this.block.fill(0));let e=this.byteLength*8,t=Math.floor(e/4294967296),n=e>>>0;return en(this.block,56,t),en(this.block,60,n),this.compress(this.block),[...this.state].map(o=>o.toString(16).padStart(8,"0")).join("")}compress(e){let t=this.words;for(let u=0;u<16;u+=1){let y=u*4;t[u]=(e[y]<<24|e[y+1]<<16|e[y+2]<<8|e[y+3])>>>0}for(let u=16;u<64;u+=1){let y=t[u-15],h=t[u-2],g=N(y,7)^N(y,18)^y>>>3,f=N(h,17)^N(h,19)^h>>>10;t[u]=t[u-16]+g+t[u-7]+f>>>0}let n=this.state[0],o=this.state[1],r=this.state[2],a=this.state[3],s=this.state[4],c=this.state[5],d=this.state[6],p=this.state[7];for(let u=0;u<64;u+=1){let y=N(s,6)^N(s,11)^N(s,25),h=s&c^~s&d,g=p+y+h+Po[u]+t[u]>>>0,f=N(n,2)^N(n,13)^N(n,22),b=n&o^n&r^o&r,m=f+b>>>0;p=d,d=c,c=s,s=a+g>>>0,a=r,r=o,o=n,n=g+m>>>0}this.state[0]=this.state[0]+n>>>0,this.state[1]=this.state[1]+o>>>0,this.state[2]=this.state[2]+r>>>0,this.state[3]=this.state[3]+a>>>0,this.state[4]=this.state[4]+s>>>0,this.state[5]=this.state[5]+c>>>0,this.state[6]=this.state[6]+d>>>0,this.state[7]=this.state[7]+p>>>0}};function N(i,e){return i>>>e|i<<32-e}function en(i,e,t){i[e]=t>>>24,i[e+1]=t>>>16,i[e+2]=t>>>8,i[e+3]=t}var pt=class{constructor(e,t){this.signal=t;this.iterator=So(e)}signal;iterator;remainder=new Uint8Array;remainderOffset=0;maxSourceChunkBytes=null;iteratorClosing=!1;ended=!1;setMaxSourceChunkBytes(e){this.maxSourceChunkBytes=e}async read(e){let t=new Uint8Array(e),n=0;for(;n<e;){if(this.remainderOffset===this.remainder.byteLength){let r=await this.nextSourceChunk();if(r.done)throw this.ended=!0,l("invalid_request","Streamed file bytes ended before the declared size.");if(!(r.value instanceof Uint8Array))throw l("invalid_request","A streamed file chunk was not a Uint8Array.");if(this.maxSourceChunkBytes===null)throw new Error("Stream source was read before upload negotiation completed.");if(r.value.byteLength>this.maxSourceChunkBytes)throw l("invalid_request",`A streamed file chunk exceeded the negotiated ${this.maxSourceChunkBytes}-byte upload part size.`);if(this.remainder=r.value,this.remainderOffset=0,this.remainder.byteLength===0)continue}let o=Math.min(e-n,this.remainder.byteLength-this.remainderOffset);t.set(this.remainder.subarray(this.remainderOffset,this.remainderOffset+o),n),n+=o,this.remainderOffset+=o}return t}async expectEnd(){if(this.remainderOffset<this.remainder.byteLength)throw l("invalid_request","Streamed file bytes exceed the declared size.");for(;!this.ended;){let e=await this.nextSourceChunk();if(e.done){this.ended=!0;return}if(!(e.value instanceof Uint8Array))throw l("invalid_request","A streamed file chunk was not a Uint8Array.");if(e.value.byteLength>0)throw l("invalid_request","Streamed file bytes exceed the declared size.")}}async close(){this.ended=!0,this.closeIterator()}async nextSourceChunk(){tn(this.signal);let e=this.iterator.next(),t=this.signal;if(!t)return e;let n=()=>{},o=new Promise((r,a)=>{let s=()=>{this.closeIterator(),a(nn(t))};t.addEventListener("abort",s,{once:!0}),n=()=>t.removeEventListener("abort",s),t.aborted&&s()});try{let r=await Promise.race([e,o]);return tn(t),r}finally{n()}}closeIterator(){if(!this.iteratorClosing){this.iteratorClosing=!0;try{this.iterator.return?.()?.catch(()=>{})}catch{}}}};function So(i){if(typeof i.getReader=="function"){let t=i.getReader(),n=!1,o=()=>{n||(n=!0,t.releaseLock())};return{async next(){if(n)return{done:!0,value:void 0};let r=await t.read();return r.done&&o(),r},async return(){if(!n)try{await t.cancel()}finally{o()}return{done:!0,value:void 0}}}}let e=i;if(typeof e[Symbol.asyncIterator]!="function")throw l("invalid_request","Streamed files require a readable byte stream.");return e[Symbol.asyncIterator]()}function tn(i){if(i?.aborted)throw nn(i)}function nn(i){return l("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:i?.reason})}var on=1024*1024,ko=4,rn=8,_e=3,an=64*1024*1024,Ro=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Oo=/^sha256:[0-9a-f]{64}$/u,Fe=class{constructor(e,t,n,o){this.capability=e;this.request=t;this.framed=n;this.hosted=o}capability;request;framed;hosted;async*list(e={}){this.requireAction("list");let t;do{ie(e.signal);let n=new URLSearchParams({protocol_version:String(1),...e.folder?{folder:e.folder}:{},...t?{after:t}:{},...e.pageSize?{limit:String(Mo(e.pageSize))}:{}}),o=await this.request("GET",`?${n.toString()}`,void 0,e.signal);if(o.protocol_version!==1||o.type!=="files_page"||!Array.isArray(o.files))throw l("invalid_operation_response","The authority returned an invalid file page.");for(let r of o.files)ie(e.signal),yield r;t=o.next}while(t)}async upload(e,t,n={}){this.requireAction(n.ifRevision?"replace":"add");let o=Io(t,n.mediaType),r=sn(n.concurrency),a=await To(o,n.signal,s=>{n.onProgress?.({phase:"hashing",transferredBytes:s,totalBytes:o.size})});return this.uploadKnownSource(e,o.size,`sha256:${a}`,(n.mediaType??o.type)||void 0,n,r,async(s,c,d)=>o.slice(c,c+d))}async uploadStream(e,t,n={}){if(this.requireAction(n.ifRevision?"replace":"add"),!Number.isSafeInteger(t.size)||t.size<0)throw l("invalid_request","Streamed file size must be a non-negative safe integer.");if(!Oo.test(t.contentDigest))throw l("invalid_request","Streamed files require a lowercase SHA-256 content digest.");let o=new pt(t.stream,n.signal),r=new ge;return this.uploadKnownSource(e,t.size,t.contentDigest,n.mediaType??t.mediaType,n,1,async(a,s,c)=>{let d=await o.read(c);return r.update(d),d},async()=>{if(await o.expectEnd(),`sha256:${r.digestHex()}`!==t.contentDigest)throw l("invalid_request","Streamed file bytes do not match the declared SHA-256 digest.")},()=>o.close(),a=>o.setMaxSourceChunkBytes(a))}async uploadKnownSource(e,t,n,o,r,a,s,c,d,p){let u=r.transferId??crypto.randomUUID();if(!Ro.test(u))throw l("invalid_request","File transfer ID must be a UUID.");let y=!1;try{let h=await this.request("POST","uploads",{protocol_version:1,type:"open_file_upload",transfer_id:u,path:e,size:t,content_digest:n,...o?{media_type:o}:{},...r.ifRevision?{if_revision:r.ifRevision}:{}},r.signal);if(cn(h,u,"upload"),h.total_size!==t||h.strategy.kind==="object_ranges")throw l("invalid_operation_response","The authority returned an incompatible upload strategy.");let g=h.strategy.kind==="framed_chunks";if(g&&!this.framed)throw l("invalid_operation_response","Encrypted file chunk delivery is unavailable.");let f=h.strategy.kind==="object_put"?Math.max(1,t):h.strategy.kind==="framed_chunks"?h.strategy.chunk_size:h.strategy.part_size,b=h.strategy.kind==="object_put"?1:Math.ceil(t/f);if(p?.(f),!g&&h.received.length===b){let S=await this.tryReplayUploadCommit(u,h.strategy.kind==="object_multipart"?h.uploaded_parts:void 0,r.signal);if(S)return y=!0,S.file}let m=new Set(h.received),w=new Map((h.uploaded_parts??[]).map(S=>[S.part_number-1,S])),I=[...m].reduce((S,be)=>S+Do(t,f,be),0),T=await qo(b,a,async S=>{let be=S*f,Le=Math.min(f,Math.max(0,t-be)),ft=await s(S,be,Le);if(xo(ft)!==Le)throw l("invalid_request","Streamed file bytes ended before the declared size.");if(m.has(S))return w.get(S)??null;let dn=g?await Bt(async()=>this.framed.uploadChunk(h,S,await Eo(ft),r.signal),r.signal).then(()=>null):await this.uploadPart(u,S,be,ft,Le,h.strategy.kind==="object_multipart",r.signal);return I+=Le,r.onProgress?.({phase:"uploading",transferredBytes:I,totalBytes:t}),dn});await c?.();let z=await this.commitUpload(u,h.strategy.kind==="object_multipart"?T.filter(S=>S!==null):void 0,r.signal);if(z.protocol_version!==1||z.type!=="file_upload_committed"||z.transfer_id!==u||z.file.path!==e||z.file.size!==t||z.file.content_digest!==n)throw l("invalid_operation_response","The authority returned an invalid file receipt.");return y=!0,z.file}catch(h){throw Ue(h)}finally{await d?.().catch(()=>{}),!y&&r.transferId===void 0&&await this.abort(u)}}async download(e,t={}){if(e.size>an)throw l("invalid_request",`download() buffers at most ${an} bytes; use downloadStream() for larger files.`);let n=await this.downloadStream(e,t),o=[],r=n.getReader();for(;;){let a=await r.read();if(a.done)break;o.push(a.value)}return new Blob(o.map(a=>{let s=new Uint8Array(a.byteLength);return s.set(a),s.buffer}),{type:e.media_type??""})}async downloadStream(e,t={}){this.requireAction("read"),sn(t.concurrency);let n=crypto.randomUUID(),o;try{if(o=await this.request("POST","downloads",{protocol_version:1,type:"open_file_download",transfer_id:n,file_id:e.file_id,revision:e.revision},t.signal),cn(o,n,"download"),o.total_size!==e.size||o.strategy.kind!=="object_ranges"&&o.strategy.kind!=="framed_chunks")throw l("invalid_operation_response","The authority returned an incompatible download session.");if(o.strategy.kind==="framed_chunks"&&!this.framed)throw l("invalid_operation_response","Encrypted file chunk delivery is unavailable.");if(o.strategy.kind==="object_ranges"&&e.size>0&&!this.hosted)throw l("invalid_operation_response","Authenticated hosted file delivery is unavailable.")}catch(f){throw await this.abort(n),Ue(f)}let r=o.strategy.kind==="framed_chunks"?o.strategy.chunk_size:o.strategy.part_size,a=Math.ceil(e.size/r),s=new ge,c=0,d=0,p=null,u=0,y=!1,h=async()=>{y||(y=!0,await p?.cancel().catch(()=>{}),p=null,await this.abort(n))},g=()=>{if(u!==e.size||`sha256:${s.digestHex()}`!==e.content_digest)throw l("invalid_operation_response","Downloaded file bytes failed integrity verification.")};return new ReadableStream({pull:async f=>{try{if(ie(t.signal),o.strategy.kind==="object_ranges")for(;;){if(!p){if(c>=a){g(),await h(),f.close();return}let T=c*r;d=Math.min(r,e.size-T),p=(await Bt(()=>this.hosted.downloadPart(o,c,d,t.signal),t.signal)).getReader()}let I=await p.read();if(I.done){if(p.releaseLock(),p=null,d!==0)throw l("invalid_operation_response","A hosted file range ended before its declared byte length.");c+=1;continue}if(!(I.value instanceof Uint8Array))throw l("invalid_operation_response","A hosted file range returned a non-byte chunk.");if(I.value.byteLength!==0){if(I.value.byteLength>d)throw l("invalid_operation_response","A hosted file range exceeded its declared byte length.");d-=I.value.byteLength,s.update(I.value),u+=I.value.byteLength,t.onProgress?.({phase:"downloading",transferredBytes:u,totalBytes:e.size}),f.enqueue(I.value);return}}if(c>=a){g(),await h(),f.close();return}let b=c*r,m=Math.min(r,e.size-b),w=await Bt(()=>this.framed.downloadChunk(o,c,t.signal),t.signal);if(w.byteLength!==m)throw l("invalid_operation_response","A file chunk had the wrong byte length.");s.update(w),u+=w.byteLength,c+=1,t.onProgress?.({phase:"downloading",transferredBytes:u,totalBytes:e.size}),c===a&&g(),f.enqueue(w),c===a&&(await h(),f.close())}catch(b){await h(),f.error(Ue(b))}},cancel:h})}async downloadBytes(e,t={}){return new Uint8Array(await(await this.download(e,t)).arrayBuffer())}async move(e,t,n={}){this.requireAction("move");let o=n.mutationId??crypto.randomUUID(),r;try{r=await this.request("POST",`${encodeURIComponent(e.file_id)}/move`,{protocol_version:1,type:"move_file",mutation_id:o,file_id:e.file_id,if_revision:n.ifRevision??e.revision,from_path:e.path,path:t,update_references:!1},n.signal)}catch(a){throw Ue(a)}if(r.protocol_version!==1||r.type!=="file_moved"||r.mutation_id!==o||r.file.file_id!==e.file_id||r.file.path!==t)throw l("invalid_operation_response","The authority returned an invalid file move receipt.");return r.file}async delete(e,t={}){this.requireAction("delete");let n=t.mutationId??crypto.randomUUID(),o;try{o=await this.request("POST",`${encodeURIComponent(e.file_id)}/delete`,{protocol_version:1,type:"delete_file",mutation_id:n,file_id:e.file_id,if_revision:t.ifRevision??e.revision,path:e.path},t.signal)}catch(r){throw Ue(r)}if(o.protocol_version!==1||o.type!=="file_deleted"||o.mutation_id!==n||o.file_id!==e.file_id||o.previous_path!==e.path)throw l("invalid_operation_response","The authority returned an invalid file delete receipt.");return o}async uploadPart(e,t,n,o,r,a,s){for(let c=1;c<=_e;c+=1){ie(s);try{let d=await this.request("POST",`uploads/${encodeURIComponent(e)}/parts`,{protocol_version:1,type:"prepare_file_upload_part",transfer_id:e,part_number:t+1,content_length:r},s);Uo(d,e,t,n,r,"PUT");let p=await fetch(d.url,{method:d.method,headers:Fo(d.headers),body:o,redirect:"error",signal:s});if(!p.ok)throw new Error(`Object upload failed with HTTP ${p.status}.`);let u=p.headers.get("etag");if(a&&!u)throw new Error("Multipart object upload did not return an ETag.");return{part_number:t+1,etag:u??""}}catch(d){if(s?.aborted||c===_e)throw d}}throw new Error("Unreachable upload retry state.")}async tryReplayUploadCommit(e,t,n){try{return await this.commitUpload(e,t,n)}catch(o){if(o instanceof C&&o.code==="file_upload_incomplete")return null;throw o}}async commitUpload(e,t,n){let o;for(let r=1;r<=_e;r+=1){ie(n);try{return await this.request("POST",`uploads/${encodeURIComponent(e)}/commit`,{protocol_version:1,type:"commit_file_upload",transfer_id:e,...t===void 0?{}:{parts:t}},n)}catch(a){if(o=a,n?.aborted||a instanceof C||r===_e)throw a}}throw o}requireAction(e){if(!this.capability()?.actions.includes(e))throw l("not_authorized",`This connection is not authorized to ${e} files.`)}async abort(e){await this.request("DELETE",`transfers/${encodeURIComponent(e)}`).catch(()=>{})}};async function To(i,e,t){let n=new ge;for(let o=0;o<i.size;o+=on){ie(e);let r=new Uint8Array(await i.slice(o,o+on).arrayBuffer());n.update(r),t(Math.min(i.size,o+r.byteLength))}return i.size===0&&t(0),n.digestHex()}function Io(i,e){if(i instanceof Blob)return e&&e!==i.type?i.slice(0,i.size,e):i;if(i instanceof ArrayBuffer)return new Blob([i],{type:e});let t=new Uint8Array(i.byteLength);return t.set(new Uint8Array(i.buffer,i.byteOffset,i.byteLength)),new Blob([t.buffer],{type:e})}function xo(i){return i instanceof Blob?i.size:i.byteLength}async function Eo(i){return i instanceof Blob?new Uint8Array(await i.arrayBuffer()):i}function sn(i=ko){if(!Number.isInteger(i)||i<1||i>rn)throw l("invalid_request",`File concurrency must be between 1 and ${rn}.`);return i}function Mo(i){if(!Number.isInteger(i)||i<1||i>1e3)throw l("invalid_request","File page size must be between 1 and 1000.");return i}function cn(i,e,t){if(i.protocol_version!==1||i.type!=="file_transfer"||i.transfer_id!==e||i.direction!==t||!Number.isSafeInteger(i.total_size)||i.total_size<0||!Array.isArray(i.received)||!zo(i))throw l("invalid_operation_response","The authority returned an invalid file transfer session.");let n=i.strategy.kind==="framed_chunks"?i.strategy.chunk_size:i.strategy.kind==="object_put"?Math.max(1,i.total_size):i.strategy.part_size,o=i.strategy.kind==="object_put"?1:Math.ceil(i.total_size/n);if(new Set(i.received).size!==i.received.length||i.received.some(a=>!Number.isSafeInteger(a)||a<0||a>=o))throw l("invalid_operation_response","The authority returned invalid transfer progress.");let r=i.uploaded_parts??[];if(!Array.isArray(r)||r.some((a,s)=>!Number.isSafeInteger(a?.part_number)||a.part_number<1||a.part_number>o||typeof a.etag!="string"||a.etag.length===0||a.etag.length>255||s>0&&r[s-1].part_number>=a.part_number)||(i.strategy.kind==="object_multipart"?r.length!==i.received.length||r.some((a,s)=>a.part_number-1!==i.received[s]):r.length!==0))throw l("invalid_operation_response","The authority returned invalid uploaded part receipts.")}function zo(i){return i.strategy.kind==="framed_chunks"?i.protection==="grant_aead_v1"&&Number.isSafeInteger(i.strategy.chunk_size)&&i.strategy.chunk_size>0:i.protection!=="transport_tls"?!1:i.strategy.kind==="object_put"?!0:Number.isSafeInteger(i.strategy.part_size)&&i.strategy.part_size>0}function Do(i,e,t){return Math.min(e,Math.max(0,i-t*e))}async function Bt(i,e){for(let t=1;t<=_e;t+=1){ie(e);try{return await i()}catch(n){if(e?.aborted||t===_e)throw n}}throw new Error("Unreachable file chunk retry state.")}function Uo(i,e,t,n,o,r){let a;try{a=new URL(i.url)}catch{throw l("invalid_operation_response","The authority returned an invalid object URL.")}if(i.protocol_version!==1||i.type!=="file_part"||i.transfer_id!==e||i.part_index!==t||i.offset!==n||i.content_length!==o||i.method.toUpperCase()!==r||a.protocol!=="https:"&&!(a.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(a.hostname))||a.username||a.password)throw l("invalid_operation_response","The authority returned an invalid prepared file part.")}function Fo(i){let e=new Headers;for(let[t,n]of Object.entries(i))["host","content-length"].includes(t.toLowerCase())||e.set(t,n);return e}async function qo(i,e,t){let n=new Array(i),o=0;return await Promise.all(Array.from({length:Math.min(i,e)},async()=>{for(;o<i;){let r=o;o+=1,n[r]=await t(r)}})),n}function ie(i){if(i?.aborted)throw l("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:i.reason})}function Ue(i){return i instanceof C?i:typeof DOMException<"u"&&i instanceof DOMException&&i.name==="AbortError"?l("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:i}):l("temporarily_unavailable","The file transfer could not be completed.",{cause:i})}var qe=class{constructor(e,t){this.internals=e;this.collectionId=t;this.transport=new ut({serverUrl:e.serverUrl,storage:e.storage,keyStore:e.keyStore,directAccessMode:e.directAccessMode,loopbackUrl:e.loopbackUrl,collectionId:t,internals:e,onChange:()=>this.emitConnection()}),this.files=new Fe(()=>this.fileCapability,(n,o,r,a)=>this.transport.files.control(n,o,r,a),{uploadChunk:(n,o,r,a)=>this.transport.files.uploadChunk(n,o,r,a),downloadChunk:(n,o,r)=>this.transport.files.downloadChunk(n,o,r)},{downloadPart:(n,o,r,a)=>this.transport.files.downloadHostedPart(n,o,r,a)}),this.collectionClient=new Me({operation:(n,o,r)=>this.transport.performOperation(n,o,r)}),this.notifications=new at({serverUrl:e.serverUrl,storage:e.storage,authorizedToken:()=>this.transport.authorizedToken(),register:()=>this.internals.register(),notificationKey:n=>e.notificationKey(t,n)})}internals;collectionId;collectionClient;notifications;transport;files;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(){return this.transport.currentToken()?.scope??null}get fileCapability(){return this.transport.currentToken()?.fileCapability??null}get directAccess(){return this.transport.directAccess}get route(){return this.transport.route}register(){return k(()=>this.internals.register(),$)}info(){let e=this.transport.currentToken();return e?{collectionId:e.collectionId,displayName:e.collectionName,operations:[...e.operations],scope:e.scope,...e.fileCapability?{fileCapability:e.fileCapability}:{},authority:e.authority?{kind:"hosted",durability:"provider"}:{kind:"connector",durability:"computer"},route:this.transport.route,directAccess:this.transport.directAccess}:null}authorizationCapabilities(e=Z){let t=this.operations,n=L(e).filter(o=>!t.includes(o));return{authorized:this.info()!==null,sufficient:this.info()!==null&&n.length===0,collectionId:this.collectionId,grantedOperations:t,missingOperations:n}}hasOperations(e){return this.authorizationCapabilities(e).sufficient}authorize(e={}){return k(()=>this.internals.authorize({...e,target:{kind:"collection",collectionId:this.collectionId}}),X)}async requestOperations(e,t={}){let n=this.authorizationCapabilities(e);return n.sufficient?O({kind:"unchanged",connection:this}):this.authorize({...t,operations:L([...n.grantedOperations,...n.missingOperations])})}onConnectionChange(e){return this.connectionListeners.add(e),e(this.info()),()=>this.connectionListeners.delete(e)}notifyStorageChanged(){this.transport.notifyStorageChanged()}checkDirectAccess(){return k(()=>this.transport.checkDirectAccess(),We)}requestDirectAccess(){return k(()=>this.transport.requestDirectAccess(),We)}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 o=e.grantId;return{collectionId:t,replicaId:o,transport:{openSession:()=>this.transport.performOperation("sync",{action:"open_session"}),snapshot:(r,a)=>this.transport.performOperation("sync",{action:"snapshot",snapshot_id:r,...a?{page:a}:{}}),changes:(r,a=200)=>this.transport.performOperation("sync",{action:"changes",after:r,limit:a}),mutate:r=>this.transport.performOperation("sync",{action:"mutate",mutation:r})}}}let n=e.authority.replicaId;return{collectionId:t,replicaId:n,transport:{openSession:()=>this.transport.performAuthoritySyncRequest(t,n,"POST","sessions"),snapshot:(o,r)=>{let a=new URLSearchParams({snapshot_id:o});return r&&a.set("page",r),this.transport.performAuthoritySyncRequest(t,n,"GET",`snapshot?${a}`)},changes:(o,r=200)=>this.transport.performAuthoritySyncRequest(t,n,"GET",`changes?${new URLSearchParams({after:String(o),limit:String(r)})}`),mutate:o=>this.transport.performAuthoritySyncRequest(t,n,"POST","mutations",o)}}}registerNotifications(e){return k(()=>this.notifications.registerNotifications(e),he)}registerNativeNotifications(e){return k(()=>this.notifications.registerNativeNotifications(e),he)}unregisterNativeNotifications(){return k(()=>this.notifications.unregisterNativeNotifications(),he)}unregisterNotifications(e){return k(()=>this.notifications.unregisterNotifications(e),he)}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 n=Date.now(),o=this.pendingMutation()?.operation==="rename",r,a=(s,c,d=0)=>{t.onProgress?.({operation:"rename",state:s,elapsedMs:Date.now()-n,cancellable:c,resumed:o,completedUnits:d,...r?{estimate:r}:{}})};try{te(t.signal),a("preflighting",!0);let s=t.preflight?O(t.preflight):await this.preflightRename(e,{signal:t.signal});if(!s.ok)return s;let c=s.value;try{Oi(e,c)}catch(u){if(u instanceof C)return A(u.problem);throw u}r=Ii(e,c),a("ready",!0),te(t.signal);let d=this.transport.hasResumableMutationTransport();a("applying",d);let p=await this.rename(e,d?{signal:t.signal}:void 0);return p.ok&&a("completed",!1,r.totalUnits),p}catch(s){if(Dt(s,t.signal)&&a("cancelled",!1),s instanceof C)return A(s.problem);throw s}}async deleteWithProgress(e,t={}){let n=Date.now(),o=this.pendingMutation()?.operation==="delete",r,a=(s,c,d=0)=>{t.onProgress?.({operation:"delete",state:s,elapsedMs:Date.now()-n,cancellable:c,resumed:o,completedUnits:d,...r?{estimate:r}:{}})};try{te(t.signal),a("preflighting",!0);let s=t.preflight?O(t.preflight):await this.preflightDelete(e,{signal:t.signal});if(!s.ok)return s;let c=s.value;try{Ti(e,c)}catch(u){if(u instanceof C)return A(u.problem);throw u}r=xi(c),a("ready",!0),te(t.signal);let d=this.transport.hasResumableMutationTransport();a("applying",d);let p=await this.delete(e,d?{signal:t.signal}:void 0);return p.ok&&a("completed",!1,r.totalUnits),p}catch(s){if(Dt(s,t.signal)&&a("cancelled",!1),s instanceof C)return A(s.problem);throw s}}pendingMutation(){return this.transport.pendingMutation()}resumePendingMutation(e,t){return k(()=>this.transport.resumePendingMutation(e,t),E)}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)}assessTypePack(e){return this.collectionClient.assessTypePack(e)}applyTypePack(e){return this.collectionClient.applyTypePack(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)}watch(e={}){return this.collectionClient.watch(e)}operation(e,t,n){return this.collectionClient.operation(e,t,n)}emitConnection(){let e=this.info();for(let t of this.connectionListeners)t(e)}};var ht=class{serverUrl;manifest;manifestSource;redirectUri;storage;relayEncryption;keyStore;identityStore;directAccessMode;loopbackUrl;navigate;credentialStorage;application=null;manifestPromise=null;completionPromises=new Map;connectionCache=new Map;listeners=new Set;invalidatedConnections=new Map;constructor(e){this.serverUrl=Li(e.serverUrl),this.manifest=e.manifest??Ni(),this.manifestSource=typeof this.manifest=="string"?this.manifest:this.manifest.distribution==="portable"?`bundle:${this.manifest.id}:${Gi(this.manifest)}`:`bundle:${this.manifest.id}`;let t=Vi(this.manifest);this.redirectUri=e.redirectUri??(typeof this.manifest!="string"&&this.manifest.distribution==="portable"?"":Bi()),this.storage=e.storage??$i(t),this.relayEncryption=e.relayEncryption??"required",this.keyStore=e.keyStore??(t?new ae:new re),this.identityStore=e.identityStore??(t?new ue:new de),this.credentialStorage=e.storage||e.keyStore||e.identityStore?"custom":this.storage instanceof ye?"memory":"persistent",this.directAccessMode=e.directAccess??"auto",this.loopbackUrl=Di(e.loopbackUrl??`http://127.0.0.1:${ni}`),this.navigate=e.navigate,typeof window<"u"&&this.storage===window.localStorage&&window.addEventListener("storage",n=>{n.storageArea!==this.storage||!n.key?.startsWith(this.storagePrefix())||(this.connectionCache.get(ji(n.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 K(`${this.serverUrl}/v1/apps/register`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({manifest:await this.manifestDeclaration()})},"temporarily_unavailable","Application registration is temporarily unavailable."),t=await e.json();if(!e.ok)throw P(t,"discovery_failed","Application discovery failed.",e.status);return this.application=t.application,this.application}manifestDeclaration(){return this.manifestPromise?this.manifestPromise:(this.manifestPromise=this.loadManifest(),this.manifestPromise)}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(n){throw l("manifest_load_failed","The bundled application declaration could not be loaded.",{cause:n})}if(!t.ok)throw l("manifest_load_failed",`The bundled application declaration returned HTTP ${t.status}.`,{status:t.status});try{return await t.json()}catch(n){throw l("invalid_application_manifest","The bundled application declaration is not valid JSON.",{cause:n,details:{issues:[{path:"/",keyword:"json",message:"must be valid JSON",params:{}}]}})}}async authorize(e={}){if(typeof location>"u"&&!this.navigate&&!e.openVerification)throw l("browser_required","Authorization navigation requires a browser environment.");let n=typeof this.manifest!="string"&&this.manifest.distribution==="portable"&&!e.openVerification&&!this.navigate&&typeof window<"u"?window.open("","mdbase-connect-authorization","popup,width=620,height=760"):null,o;try{o=await this.register()}catch(r){throw n?.close(),r}return o.distribution==="portable"?(e.openVerification&&n?.close(),this.authorizePortable(o,e,e.openVerification?null:n)):(n?.close(),this.authorizeWeb(o,e))}async authorizeWeb(e,t){let{verifier:n,challenge:o}=await ze(),r=F(24),a=crypto.randomUUID(),s=t.target?.kind==="collection"?t.target.collectionId:void 0,c=`grant:${e.id}:${r}`,d=await this.keyStore.create(c),p;try{p=await this.loadApplicationIdentity(e)}catch(f){throw await this.keyStore.delete(c),f}let u=L(t.operations??Z),y=new Date,h=await ke({protocol_version:wt,authorization_id:a,application_id:e.id,application_manifest_digest:e.manifest_digest,application_installation_id:await pe(p),installation_signing_public_key:p.signingPublicKey,grant_agreement_public_key:d.agreementPublicKey,grant_signing_public_key:d.signingPublicKey,flow:"authorization_code",authorization_nonce:F(32),issued_at:y.toISOString(),expires_at:new Date(y.getTime()+600*1e3).toISOString(),redirect_uri:this.redirectUri,state:r,code_challenge:o,requested_operations:u,...e.requirements?.files?{requested_files:e.requirements.files}:{},...s?{collection_id:s}:{}},p),g={version:1,verifier:n,state:r,clientId:e.id,redirectUri:this.redirectUri,relayEncryption:this.relayEncryption,collectionId:s,returnTo:t.returnTo,keyHandle:c,authorizationId:a,applicationAgreementPublicKey:d.agreementPublicKey,applicationSigningPublicKey:d.signingPublicKey};this.storage.setItem(this.pendingKey(r),JSON.stringify(g));try{let f=await fetch(`${this.serverUrl}/oauth/authorization_request`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e.id,redirect_uri:this.redirectUri,code_challenge:o,code_challenge_method:"S256",state:r,operations:u.join(","),...s?{collection_id:s}:{},application_authorization:JSON.stringify(h)}),signal:t.signal}),b=await f.json();if(!f.ok)throw P(b,"device_authorization_failed","Application authorization could not be started.",f.status);if(typeof b.authorization_uri!="string"||b.authorization_id!==a||!Number.isInteger(b.expires_in)||b.expires_in<=0)throw l("invalid_device_authorization_response","The authorization service returned an invalid authorization response.");if(this.navigate)await this.navigate(b.authorization_uri);else if(typeof location<"u")location.assign(b.authorization_uri);else throw l("browser_required","Authorization navigation requires a browser environment.");return{kind:"redirecting"}}catch(f){throw this.storage.removeItem(this.pendingKey(r)),await this.keyStore.delete(c),t.signal?.aborted?l("authorization_cancelled","Application authorization was cancelled.",{cause:f}):f}}async authorizePortable(e,t,n){if(this.relayEncryption!=="required")throw n?.close(),l("encryption_required","Downloaded applications require encrypted relay authorization.");let{verifier:o,challenge:r}=await ze(),a=`grant:${e.id}:${F(24)}`,s=await this.keyStore.create(a),c;try{c=await this.loadApplicationIdentity(e)}catch(m){throw n?.close(),await this.keyStore.delete(a),m}let d=L(t.operations??Z),p=crypto.randomUUID(),u=new Date,y=await ke({protocol_version:wt,authorization_id:p,application_id:e.id,application_manifest_digest:e.manifest_digest,application_installation_id:await pe(c),installation_signing_public_key:c.signingPublicKey,grant_agreement_public_key:s.agreementPublicKey,grant_signing_public_key:s.signingPublicKey,flow:"device_code",authorization_nonce:F(32),issued_at:u.toISOString(),expires_at:new Date(u.getTime()+600*1e3).toISOString(),code_challenge:r,requested_operations:d,...e.requirements?.files?{requested_files:e.requirements.files}:{},...t.target?.kind==="collection"?{collection_id:t.target.collectionId}:{}},c),h,g;try{h=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:d.join(","),...t.target?.kind==="collection"?{collection_id:t.target.collectionId}:{},code_challenge:r,code_challenge_method:"S256",application_authorization:JSON.stringify(y)})}),g=await h.json()}catch(m){throw n?.close(),await this.keyStore.delete(a),l("device_authorization_failed","Downloaded application authorization could not be started.",{cause:m})}if(!h.ok)throw n?.close(),await this.keyStore.delete(a),P(g,"device_authorization_failed","Downloaded application authorization could not be started.",h.status);let f;try{f=qi(g)}catch(m){throw n?.close(),await this.keyStore.delete(a),t.signal?.aborted?l("authorization_cancelled","Downloaded application authorization was cancelled.",{cause:m}):m}if(t.onDeviceCode?.(f),t.openVerification)await t.openVerification(f);else if(n)try{n.location.href=f.verificationUriComplete}catch{}else throw await this.keyStore.delete(a),l("approval_window_blocked","The approval window was blocked. Show the provided verification link and code, then try again.",{details:{user_code:f.userCode,verification_uri:f.verificationUri,verification_uri_complete:f.verificationUriComplete,expires_at:f.expiresAt,interval_seconds:f.intervalSeconds}});let b=f.intervalSeconds;try{for(;Date.now()<f.expiresAt;){if(await Ee(b*1e3,t.signal),t.signal?.aborted)throw l("authorization_cancelled","Downloaded application authorization was cancelled.");let m;try{m=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:g.device_code,client_id:e.id,code_verifier:o}),signal:t.signal})}catch(S){if(t.signal?.aborted)throw l("authorization_cancelled","Downloaded application authorization was cancelled.",{cause:S});continue}let w=await m.json();if(!m.ok){let S=De(w);if(S==="authorization_pending")continue;if(S==="slow_down"){b+=5;continue}throw P(w,"token_exchange_failed","Downloaded application authorization could not be completed.",m.status)}let I=nt(w.authority,w.collection_id),T=w.encryption&&w.encryption.protocol_version===oe&&w.encryption.suite===Pe&&w.encryption.application_agreement_public_key===s.agreementPublicKey;if(w.application_origin!=="null")throw l("invalid_token_response","Authorization did not bind the portable grant to its opaque application origin.");if(w.authority&&(!I||w.encryption!=null||w.authority.proof_public_key!==s.signingPublicKey))throw l("invalid_token_response","Authorization returned a remote authority capability that is not bound to this portable grant key.");if(!w.authority&&!T)throw l("encryption_required","Authorization did not establish the expected key-bound local portable grant.");let z=this.storeTokenResponse(w,e.id,a);if(t.target?.kind==="collection"&&t.target.collectionId!==z.collectionId)throw this.removeToken(z.collectionId,z.keyHandle),l("collection_mismatch","The approved collection does not match the collection requested by this link.");return n?.close(),{kind:"connected",connection:this.connection(z.collectionId),...t.returnTo?{returnTo:t.returnTo}:{}}}throw l("expired_token","The downloaded application authorization code expired.")}catch(m){throw n?.close(),await this.keyStore.delete(a),t.signal?.aborted?l("authorization_cancelled","Downloaded application authorization was cancelled.",{cause:m}):m}}completeAuthorization(e){let t=new URL(e).searchParams.get("state");if(!t)return Promise.reject(l("invalid_callback","Authorization callback is missing its state."));let n=this.completionPromises.get(t);if(n)return n;let r=this.performAuthorizationCompletion(e,t).finally(()=>{this.completionPromises.get(t)===r&&this.completionPromises.delete(t)});return this.completionPromises.set(t,r),r}async performAuthorizationCompletion(e,t){let n=new URL(e),o=n.searchParams.get("code"),r=this.pendingKey(t),a=M(this.storage.getItem(r));if(!a||a.version!==1||t!==a.state)throw l("invalid_callback","Authorization callback is missing or does not match this browser session.");if(n.searchParams.has("error"))throw a.keyHandle&&await this.keyStore.delete(a.keyHandle),this.storage.removeItem(r),D(n.searchParams.get("error")??"access_denied",n.searchParams.get("error_description")??"Collection access was not approved.",{details:a.returnTo?{return_to:a.returnTo}:void 0});if(!o)throw l("invalid_callback","Authorization callback is missing its code.");let s=await K(`${this.serverUrl}/oauth/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:o,client_id:a.clientId,redirect_uri:a.redirectUri,code_verifier:a.verifier})},"temporarily_unavailable","Authorization completion is temporarily unavailable."),c=await s.json();if(!s.ok)throw P(c,"token_exchange_failed","Authorization could not be completed.",s.status);if(a.relayEncryption==="required"&&!c.authority&&(!c.encryption||!a.keyHandle||c.encryption.application_agreement_public_key!==a.applicationAgreementPublicKey))throw a.keyHandle&&await this.keyStore.delete(a.keyHandle),this.storage.removeItem(r),l("encryption_required","Authorization did not establish the required encrypted relay grant.");if(c.authority?.proof_public_key){if(!a.keyHandle||!a.applicationSigningPublicKey||c.authority.proof_public_key!==a.applicationSigningPublicKey)throw a.keyHandle&&await this.keyStore.delete(a.keyHandle),this.storage.removeItem(r),l("invalid_token_response","Authorization returned a remote authority capability bound to another application key.")}else c.authority&&a.keyHandle&&await this.keyStore.delete(a.keyHandle);let d=this.storeTokenResponse(c,a.clientId,c.authority?.proof_public_key?a.keyHandle:c.authority?void 0:a.keyHandle);if(a.collectionId&&a.collectionId!==d.collectionId)throw this.removeToken(d.collectionId,d.keyHandle),this.storage.removeItem(r),l("collection_mismatch","The approved collection does not match the collection requested by this link.");return this.storage.removeItem(r),{connection:this.connection(d.collectionId),...a.returnTo?{returnTo:a.returnTo}:{}}}connections(){let e=[];for(let t of this.connectionIds()){let n=this.connection(t)?.info();n&&e.push(n)}return e.sort((t,n)=>t.displayName.localeCompare(n.displayName)||t.collectionId.localeCompare(n.collectionId))}connection(e){if(!this.storage.getItem(this.tokenKey(e)))return null;let t=this.connectionCache.get(e);return t||(t=new qe(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,n){let o=e.collection_id;if(typeof o!="string")throw l("invalid_token_response","Authorization returned no collection ID.");let r=rt(e.scope);if(!r)throw l("invalid_token_response","Authorization returned no valid collection scope.");if(e.authority&&!nt(e.authority,o))throw l("invalid_token_response","Authorization returned an invalid remote authority capability.");if(e.authority&&e.encryption)throw l("invalid_token_response","Authorization returned conflicting collection transports.");if(e.file_capability!==null&&e.file_capability!==void 0&&!ot(e.file_capability))throw l("invalid_token_response","Authorization returned an invalid file capability.");if(e.encryption){try{J(e.encryption)}catch{throw l("invalid_token_response","Authorization returned an invalid encrypted relay binding.")}if(this.pinConnectorIdentity(e.encryption.connector_id,e.encryption.connector_agreement_public_key),e.encryption.collection_id!==o||typeof e.grant_id!="string"||e.grant_id.length===0)throw l("invalid_token_response","Authorization returned an encrypted relay binding for another grant.")}let a=M(this.storage.getItem(this.tokenKey(o)));if(a?.encryption&&e.encryption&&a.keyHandle&&a.keyHandle===n&&(a.grantId!==e.grant_id||a.encryption.connector_id!==e.encryption.connector_id||a.encryption.connector_agreement_public_key!==e.encryption.connector_agreement_public_key||a.encryption.application_agreement_public_key!==e.encryption.application_agreement_public_key))throw l("connector_identity_changed","The connector identity changed during authorization renewal. Reauthorize before sending collection data.");a?.keyHandle&&a.keyHandle!==n&&this.keyStore.delete(a.keyHandle).catch(()=>{});let s={version:1,accessToken:e.access_token,refreshToken:e.refresh_token,clientId:t,collectionId:o,collectionName:e.collection_name??`Collection ${o.slice(0,8)}`,operations:e.operations,scope:r,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,fileCapability:e.file_capability??void 0,applicationOrigin:e.application_origin??this.defaultApplicationOrigin(),keyHandle:n,savedAt:Date.now(),authority:e.authority?{operationsUrl:e.authority.operations_url,syncUrl:e.authority.sync_url,filesUrl:e.authority.files_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(o),JSON.stringify(s)),this.addConnectionId(o),this.invalidatedConnections.delete(o),this.connectionCache.delete(o),this.emitConnections(),s}forgetConnectorIdentity(e){this.storage.removeItem(this.connectorPinKey(e))}pinConnectorIdentity(e,t){let n=this.connectorPinKey(e),o=M(this.storage.getItem(n));if(o&&(o.version!==1||o.publicKey!==t))throw l("connector_identity_changed","The connector identity changed since this application first connected. Forget the saved connector identity only after verifying the computer, then authorize again.");o||this.storage.setItem(n,JSON.stringify({version:1,publicKey:t}))}connectorPinKey(e){return`mdbase-connect:${this.serverUrl}:connector-pin:${e}`}async loadApplicationIdentity(e){try{return await vi(this.identityStore,this.serverUrl,e)}catch(t){throw l("application_identity_unavailable",t instanceof Q?t.message:"The application installation identity is unavailable.",{cause:t})}}removeToken(e,t,n="authorization_lost"){this.invalidatedConnections.set(e,n),t&&this.keyStore.delete(t).catch(()=>{}),this.storage.removeItem(this.tokenKey(e)),this.storage.removeItem(this.pendingMutationKey(e));for(let o of["web_push","fcm"])this.storage.removeItem(this.notificationKey(e,o));this.storage.setItem(this.connectionsKey(),JSON.stringify({version:1,collectionIds:this.connectionIds().filter(o=>o!==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(){return Ki(this.manifest,this.manifestSource,this.redirectUri,this.application?.distribution==="portable")}pendingKey(e){return`${this.storagePrefix()}:pending:${e}`}storagePrefix(){return`mdbase-connect:${this.serverUrl}:${this.manifestSource}`}connectionsKey(){return`${this.storagePrefix()}:connections`}connectionIds(){let e=M(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)}};var Kt=class{internals;constructor(e){this.internals=new ht(e)}register(){return k(()=>this.internals.register(),$)}authorize(e={}){return k(()=>this.internals.authorize(e),X)}createApplicationSession(e){return new xe(this,e)}manifest(){return k(()=>this.internals.manifestDeclaration(),$)}environment(){return this.internals.environment()}completeAuthorization(e){return k(()=>this.internals.completeAuthorization(e??Hi()),X)}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()}forgetConnectorIdentity(e){this.internals.forgetConnectorIdentity(e)}};function ln(i){if(!i||typeof i!="object")throw l("invalid_push_payload","The push payload is not an object.");let e=i;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 l("invalid_push_payload","The push payload is not an mdbase notification.");return e}function Lo(i){if(!i||typeof i!="object")throw l("invalid_push_payload","The native notification data is not an object.");let e=i;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 l("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 No(i,e){let t=ln(e);return i.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 jt=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 n=Oe(this.currentUrl());e?n.searchParams.set(this.collectionParameter,e):n.searchParams.delete(this.collectionParameter);let o=this.browserHistory();o[t.history==="push"?"pushState":"replaceState"](o.state,"",n),this.emit()}authorizationReturnTo(){let e=Oe(this.currentUrl());return`${e.pathname}${e.search}${e.hash}`}authorizationCallback(){let e=this.currentUrl().href;return Ze(e)?e:null}finishAuthorization(e,t){let n=this.safeAppUrl(e??this.fallbackPath);Oe(n),n.searchParams.set(this.collectionParameter,t),this.browserHistory().replaceState(null,"",n),this.emit()}clearAuthorizationCallback(e){let t=e?this.safeAppUrl(e):this.currentUrl(),n=this.browserHistory();n.replaceState(n.state,"",Oe(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(),n=new URL(e,t.origin);return n.origin===t.origin?n:new URL(this.fallbackPath,t.origin)}currentUrl(){if(typeof location>"u")throw l("browser_required","Browser selection requires a browser environment.");return new URL(location.href)}browserHistory(){if(typeof history>"u")throw l("browser_required","Browser selection requires a browser environment.");return history}},Ht=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 mn(Bo);})();
1
+ "use strict";var MdbaseConnect=(()=>{var Et=Object.defineProperty;var Xi=Object.getOwnPropertyDescriptor;var Zi=Object.getOwnPropertyNames;var eo=Object.prototype.hasOwnProperty;var to=(n,e)=>{for(var t in e)Et(n,t,{get:e[t],enumerable:!0})},no=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Zi(e))!eo.call(n,o)&&o!==t&&Et(n,o,{get:()=>e[o],enumerable:!(i=Xi(e,o))||i.enumerable});return n};var io=n=>no(Et({},"__esModule",{value:!0}),n);var zr={};to(zr,{ALL_CONNECT_PROBLEM_CODES:()=>$t,AUTHORIZATION_PROBLEM_CODES:()=>ie,ApplicationIdentityStoreError:()=>_e,COLLECTION_CHANGES_PROBLEM_CODES:()=>Te,COLLECTION_DESCRIPTION_PROBLEM_CODES:()=>ke,COLLECTION_MUTATION_PROBLEM_CODES:()=>x,COLLECTION_QUERY_PROBLEM_CODES:()=>Vt,COLLECTION_READ_PROBLEM_CODES:()=>L,COLLECTION_SETUP_PROBLEM_CODES:()=>Un,COLLECTION_TYPE_PROBLEM_CODES:()=>oe,COMMON_OPERATION_PROBLEM_CODES:()=>qn,ConnectOutcomeError:()=>rt,DIRECT_ACCESS_PROBLEM_CODES:()=>at,FileTransferCryptoError:()=>X,GrantFileTransferCipher:()=>He,IndexedDbApplicationIdentityStore:()=>Be,IndexedDbGrantKeyStore:()=>Ie,MdbaseApplicationSession:()=>Ne,MdbaseBrowserSelection:()=>pn,MdbaseCollectionClient:()=>ge,MdbaseConnect:()=>un,MdbaseConnectError:()=>C,MdbaseConnection:()=>Ge,MdbaseFileClient:()=>Ve,MdbaseMemorySelection:()=>hn,MdbaseMemoryVerificationStore:()=>yt,MdbaseSession:()=>ye,MemoryApplicationIdentityStore:()=>Ke,MemoryGrantKeyStore:()=>Me,NOTIFICATION_PROBLEM_CODES:()=>de,REGISTRATION_PROBLEM_CODES:()=>J,RelayCryptoError:()=>R,SESSION_PROBLEM_CODES:()=>Ho,applicationIdentity:()=>nn,applicationInstallationId:()=>je,authorityProofMessage:()=>Ln,authorizationSigningMessage:()=>Bt,captureConnectOutcome:()=>k,connectError:()=>l,connectFailure:()=>A,connectProblem:()=>T,connectSuccess:()=>M,createPkce:()=>Ue,decryptRelayResponse:()=>xe,deriveFileTransferKey:()=>Oi,deriveP256SharedSecret:()=>lt,effectiveCapabilities:()=>jt,encryptRelayRequest:()=>pe,externalStore:()=>Ur,isRetryableConnectError:()=>Ko,operationProblem:()=>Ae,parseMdbaseNativeNotificationData:()=>xr,parseMdbasePushPayload:()=>Wi,serverConnectError:()=>F,showMdbasePushNotification:()=>qr,signApplicationAuthorization:()=>mt,signAuthorityRequest:()=>Wt,unknownConnectProblem:()=>Ht,unwrapConnectOutcome:()=>$o,validateGrantEncryption:()=>Q});var ee={access_denied:{category:"authorization",recovery:"reauthorize"},access_paused:{category:"availability",recovery:"resume_connector_access"},application_identity_unavailable:{category:"compatibility",recovery:"upgrade_application"},approval_window_blocked:{category:"authorization",recovery:"reauthorize"},authority_authorization_changed:{category:"authorization",recovery:"reauthorize"},authorization_binding_incompatible:{category:"compatibility",recovery:"upgrade_application"},authorization_cancelled:{category:"cancellation",recovery:"none"},authorization_expired:{category:"authorization",recovery:"reauthorize"},authorization_replayed:{category:"integrity",recovery:"reauthorize"},browser_required:{category:"compatibility",recovery:"none"},callback_url_required:{category:"validation",recovery:"fix_request"},capability_contract_incompatible:{category:"compatibility",recovery:"upgrade_application"},change_cursor_reset:{category:"conflict",recovery:"refresh"},collection_access_denied:{category:"authorization",recovery:"reauthorize"},collection_configuration_invalid:{category:"validation",recovery:"repair_collection"},collection_contracts_missing:{category:"compatibility",recovery:"choose_collection"},collection_incompatible:{category:"compatibility",recovery:"choose_collection"},collection_invalid:{category:"validation",recovery:"repair_collection"},collection_kind_unsupported:{category:"compatibility",recovery:"choose_collection"},collection_mismatch:{category:"selection",recovery:"choose_collection"},collection_not_found:{category:"selection",recovery:"choose_collection"},collection_not_ready:{category:"selection",recovery:"choose_collection"},collection_not_selected:{category:"selection",recovery:"choose_collection"},collection_type_registry_invalid:{category:"validation",recovery:"repair_collection"},collection_version_unsupported:{category:"compatibility",recovery:"upgrade_collection"},concurrent_modification:{category:"conflict",recovery:"refresh"},connector_identity_changed:{category:"integrity",recovery:"reauthorize"},connector_offline:{category:"availability",recovery:"retry"},connector_upgrade_required:{category:"compatibility",recovery:"upgrade_connector"},device_authorization_failed:{category:"authorization",recovery:"reauthorize"},direct_operation_rejected:{category:"authorization",recovery:"reauthorize"},discovery_failed:{category:"availability",recovery:"retry"},durable_mutation_unsupported:{category:"compatibility",recovery:"upgrade_connector"},encrypted_relay_rejected:{category:"authorization",recovery:"reauthorize"},encryption_required:{category:"authorization",recovery:"reauthorize"},expired_token:{category:"authorization",recovery:"reauthorize"},file_changed_during_move:{category:"conflict",recovery:"refresh"},file_changed_during_read:{category:"conflict",recovery:"refresh"},file_move_failed:{category:"internal",recovery:"contact_support"},file_mutation_conflict:{category:"conflict",recovery:"resolve_conflict"},file_not_found:{category:"conflict",recovery:"refresh"},file_source_mismatch:{category:"conflict",recovery:"refresh"},file_upload_incomplete:{category:"conflict",recovery:"retry"},hosted_provider_unavailable:{category:"availability",recovery:"retry"},insufficient_access:{category:"authorization",recovery:"reauthorize"},invalid_application_authorization:{category:"validation",recovery:"fix_request"},invalid_application_manifest:{category:"validation",recovery:"fix_request"},invalid_callback:{category:"validation",recovery:"fix_request"},invalid_device_authorization_response:{category:"integrity",recovery:"contact_support"},invalid_encrypted_response:{category:"integrity",recovery:"contact_support"},invalid_loopback_url:{category:"validation",recovery:"fix_request"},invalid_mutation_id:{category:"validation",recovery:"fix_request"},invalid_operation_response:{category:"integrity",recovery:"contact_support"},invalid_path:{category:"validation",recovery:"fix_request"},invalid_preflight:{category:"conflict",recovery:"refresh"},invalid_push_payload:{category:"validation",recovery:"fix_request"},invalid_push_subscription:{category:"validation",recovery:"fix_request"},invalid_request:{category:"validation",recovery:"fix_request"},invalid_token_response:{category:"integrity",recovery:"contact_support"},managed_fcm_not_declared:{category:"compatibility",recovery:"fix_request"},manifest_load_failed:{category:"availability",recovery:"retry"},manifest_required:{category:"validation",recovery:"fix_request"},missing_grant_key:{category:"authorization",recovery:"reauthorize"},mutation_recovery_expired:{category:"compatibility",recovery:"none"},mutation_request_conflict:{category:"conflict",recovery:"resolve_conflict"},no_pending_mutation:{category:"conflict",recovery:"refresh"},not_authorized:{category:"authorization",recovery:"reauthorize"},not_remote_authority:{category:"compatibility",recovery:"choose_collection"},notification_criterion_not_declared:{category:"validation",recovery:"fix_request"},notification_reauthorization_required:{category:"authorization",recovery:"reauthorize"},notification_registration_failed:{category:"availability",recovery:"retry"},notification_unregistration_failed:{category:"availability",recovery:"retry"},notifications_not_declared:{category:"compatibility",recovery:"fix_request"},notifications_unavailable:{category:"availability",recovery:"retry"},operation_cancelled:{category:"cancellation",recovery:"none"},operation_failed:{category:"internal",recovery:"contact_support"},operation_invalid:{category:"validation",recovery:"fix_request"},operation_outcome_unknown:{category:"conflict",recovery:"resolve_outcome"},path_occupied:{category:"conflict",recovery:"resolve_conflict"},pending_mutation_unresolved:{category:"conflict",recovery:"resolve_outcome"},query_snapshot_changed:{category:"conflict",recovery:"refresh"},rate_limited:{category:"availability",recovery:"retry"},reconnect_required:{category:"authorization",recovery:"reauthorize"},redirect_uri_required:{category:"validation",recovery:"fix_request"},reference_updates_unsupported:{category:"compatibility",recovery:"fix_request"},registry_backup_invalid:{category:"integrity",recovery:"contact_support"},registry_busy:{category:"availability",recovery:"retry"},registry_corrupt:{category:"integrity",recovery:"repair_collection"},registry_migration_failed:{category:"internal",recovery:"contact_support"},registry_schema_incompatible:{category:"compatibility",recovery:"upgrade_connector"},relay_authorization_expired:{category:"authorization",recovery:"reauthorize"},relay_unavailable:{category:"availability",recovery:"retry"},sandbox_unsupported:{category:"compatibility",recovery:"fix_request"},scope_denied:{category:"authorization",recovery:"reauthorize"},stale_file_revision:{category:"conflict",recovery:"refresh"},storage_required:{category:"compatibility",recovery:"none"},sync_failed:{category:"availability",recovery:"retry"},temporarily_unavailable:{category:"availability",recovery:"retry"},timeout:{category:"availability",recovery:"retry"},token_exchange_failed:{category:"availability",recovery:"retry"},transport_protocol_incompatible:{category:"compatibility",recovery:"upgrade_connector"},type_pack_provision_failed:{category:"validation",recovery:"repair_collection"},unknown_collection:{category:"selection",recovery:"choose_collection"},unsafe_file_path:{category:"validation",recovery:"fix_request"},unsupported_encryption:{category:"compatibility",recovery:"upgrade_application"},unsupported_operation:{category:"compatibility",recovery:"fix_request"}},oo={access_denied:{type:"object",required:[],properties:{return_to:{type:"string"}}},approval_window_blocked:{type:"object",required:["user_code","verification_uri","verification_uri_complete","expires_at","interval_seconds"],properties:{user_code:{type:"string"},verification_uri:{type:"string"},verification_uri_complete:{type:"string"},expires_at:{type:"integer"},interval_seconds:{type:"integer"}}},authorization_binding_incompatible:{type:"object",required:["contract","required","supported","peer"],properties:{contract:{type:"string"},required:{type:"array",items:{type:"integer"}},supported:{type:"array",items:{type:"integer"}},peer:{type:"string"},operation:{type:"string"}}},capability_contract_incompatible:{type:"object",required:["contract","required","supported","peer"],properties:{contract:{type:"string"},required:{type:"array",items:{type:"integer"}},supported:{type:"array",items:{type:"integer"}},peer:{type:"string"},operation:{type:"string"}}},collection_configuration_invalid:{type:"object",required:["diagnostics"],properties:{diagnostics:{type:"array",items:{type:"object"}}}},collection_contracts_missing:{type:"object",required:["contracts"],properties:{contracts:{type:"array",items:{type:"object",required:["id","version"],properties:{id:{type:"string"},version:{type:"string"}}}}}},collection_invalid:{type:"object",required:["diagnostics"],properties:{diagnostics:{type:"array",items:{type:"object"}}}},collection_type_registry_invalid:{type:"object",required:["diagnostics"],properties:{diagnostics:{type:"array",items:{type:"object"}}}},collection_version_unsupported:{type:"object",required:["current_version","required_version"],properties:{current_version:{type:"string"},required_version:{type:"string"}}},connector_offline:{type:"object",required:[],properties:{connector_name:{type:"string"}}},durable_mutation_unsupported:{type:"object",required:["contract","required","supported","peer"],properties:{contract:{type:"string"},required:{type:"array",items:{type:"integer"}},supported:{type:"array",items:{type:"integer"}},peer:{type:"string"},operation:{type:"string"}}},insufficient_access:{type:"object",required:["required_operations","granted_operations","missing_operations"],properties:{required_operations:{type:"array",items:{type:"string"}},granted_operations:{type:"array",items:{type:"string"}},missing_operations:{type:"array",items:{type:"string"}}}},invalid_application_manifest:{type:"object",required:["issues"],properties:{issues:{type:"array",items:{type:"object",required:["path","keyword","message","params"],properties:{path:{type:"string"},keyword:{type:"string"},message:{type:"string"},params:{type:"object"}}}}}},mutation_request_conflict:{type:"object",required:["request_id"],properties:{request_id:{type:"string"}}},operation_invalid:{type:"object",required:["diagnostics"],properties:{diagnostics:{type:"array",items:{type:"object"}},partial_result:{}}},operation_outcome_unknown:{type:"object",required:["request_id"],properties:{request_id:{type:"string"}}},rate_limited:{type:"object",required:[],properties:{retry_after_ms:{type:"integer"}}},transport_protocol_incompatible:{type:"object",required:["contract","required","supported","peer"],properties:{contract:{type:"string"},required:{type:"array",items:{type:"integer"}},supported:{type:"array",items:{type:"integer"}},peer:{type:"string"},operation:{type:"string"}}}};function fn(n){return Object.hasOwn(ee,n)}function Ce(n){if(!yn(n))return!1;let e=n;if(e.problem_version!==1||typeof e.message!="string"||e.message.length===0||e.operation_outcome!==void 0&&e.operation_outcome!=="not_sent"&&e.operation_outcome!=="rejected"&&e.operation_outcome!=="unknown"||e.trace_id!==void 0&&(typeof e.trace_id!="string"||e.trace_id.length===0))return!1;if(e.code==="unknown")return typeof e.server_code=="string"&&e.server_code.length>0&&e.category==="unknown"&&e.recovery==="none";if(typeof e.code!="string"||!fn(e.code)||e.server_code!==void 0)return!1;let t=ee[e.code],i=oo[e.code],o=i===void 0?e.details===void 0:e.details===void 0?(i.required?.length??0)===0:xt(e.details,i);return e.category===t.category&&e.recovery===t.recovery&&o}function xt(n,e){if(e.type===void 0)return!0;if(e.type==="string")return typeof n=="string";if(e.type==="integer")return typeof n=="number"&&Number.isInteger(n);if(e.type==="number")return typeof n=="number"&&Number.isFinite(n);if(e.type==="boolean")return typeof n=="boolean";if(e.type==="array")return Array.isArray(n)&&n.every(i=>xt(i,e.items??{}));if(!yn(n))return!1;if(!e.properties)return!0;let t=n;return!Object.keys(t).every(i=>Object.hasOwn(e.properties,i))||!(e.required??[]).every(i=>Object.hasOwn(t,i))?!1:Object.entries(t).every(([i,o])=>xt(o,e.properties[i]))}function yn(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function qt(n,e,t={}){if(fn(n)){let i=ee[n],o={problem_version:1,code:n,category:i.category,recovery:i.recovery,message:e,...t.details===void 0?{}:{details:t.details},...t.operation_outcome===void 0?{}:{operation_outcome:t.operation_outcome},...t.trace_id===void 0?{}:{trace_id:t.trace_id}};if(Ce(o))return o}return{problem_version:1,code:"unknown",server_code:n,category:"unknown",recovery:"none",message:e,...t.details===void 0?{}:{details:t.details},...t.operation_outcome===void 0?{}:{operation_outcome:t.operation_outcome},...t.trace_id===void 0?{}:{trace_id:t.trace_id}}}var mn=new Uint8Array([77,68,66,70]),_n=1,gn=0,Nr=new Uint8Array([77,68,66,82]);var bn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,w=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name="FileFrameError"}};function ro(n){return n==="upload_chunk"?1:2}function ao(n){if(n===1)return"upload_chunk";if(n===2)return"download_chunk";throw new w("invalid_kind",`Unknown file frame kind ${n}`)}function so(n){if(!n||typeof n!="object"||Array.isArray(n))throw new w("invalid_header","File frame header must be a JSON object");return n}function Qe(n,e){let t=n[e];if(typeof t!="string"||t.length===0)throw new w("invalid_header",`File frame header ${e} must be a non-empty string`);return t}function We(n,e){let t=Qe(n,e);if(!bn.test(t))throw new w("invalid_header",`File frame header ${e} must be a UUID`);return t}function te(n,e,t=Number.MAX_SAFE_INTEGER){let i=n[e];if(!Number.isSafeInteger(i)||i<0||i>t)throw new w("invalid_header",`File frame header ${e} is outside its allowed range`);return i}function Ut(n){if(n.protocol_version!==1)throw new w("unsupported_version",`Unsupported file transfer protocol ${n.protocol_version}`);if(n.protection!=="grant_aead_v1"&&n.protection!=="transport_tls")throw new w("invalid_header","Unknown file transfer protection");if(n.direction!=="upload"&&n.direction!=="download")throw new w("invalid_header","Unknown file transfer direction");for(let[e,t]of[["grant_id",n.grant_id],["authority_id",n.authority_id],["collection_id",n.collection_id],["transfer_id",n.transfer_id]])if(!bn.test(t))throw new w("invalid_header",`File frame header ${e} must be a UUID`);for(let[e,t,i]of[["chunk_size",n.chunk_size,4194304],["chunk_index",n.chunk_index,Number.MAX_SAFE_INTEGER],["offset",n.offset,Number.MAX_SAFE_INTEGER],["plaintext_length",n.plaintext_length,4194304],["total_size",n.total_size,Number.MAX_SAFE_INTEGER]])if(!Number.isSafeInteger(t)||t<0||t>i)throw new w("invalid_header",`File frame header ${e} is outside its allowed range`);if(n.chunk_size<64*1024)throw new w("invalid_header","File frame chunk_size is below the protocol minimum");if(!Number.isSafeInteger(n.scope_epoch)||n.scope_epoch<1)throw new w("invalid_header","File frame header scope_epoch must be a positive integer");if(n.protection==="grant_aead_v1"&&!n.key_id)throw new w("invalid_header","AEAD-protected file frames require key_id");return{protocol_version:1,protection:n.protection,grant_id:n.grant_id,authority_id:n.authority_id,collection_id:n.collection_id,transfer_id:n.transfer_id,direction:n.direction,chunk_size:n.chunk_size,chunk_index:n.chunk_index,offset:n.offset,plaintext_length:n.plaintext_length,total_size:n.total_size,scope_epoch:n.scope_epoch,...n.key_id===void 0?{}:{key_id:n.key_id}}}function co(n){let e;try{e=new TextDecoder("utf-8",{fatal:!0}).decode(n)}catch{throw new w("invalid_header","File frame header is not valid UTF-8")}let t;try{t=so(JSON.parse(e))}catch(d){throw d instanceof w?d:new w("invalid_header","File frame header is not valid JSON")}let i=new Set(["protocol_version","protection","grant_id","authority_id","collection_id","transfer_id","direction","chunk_size","chunk_index","offset","plaintext_length","total_size","scope_epoch","key_id"]);if(Object.keys(t).some(d=>!i.has(d)))throw new w("invalid_header","File frame header contains an unknown field");let o=te(t,"protocol_version");if(o!==1)throw new w("unsupported_version",`Unsupported file transfer protocol ${o}`);let r=Qe(t,"protection"),a=Qe(t,"direction"),s=t.key_id===void 0?void 0:Qe(t,"key_id"),c=Ut({protocol_version:1,protection:r,grant_id:We(t,"grant_id"),authority_id:We(t,"authority_id"),collection_id:We(t,"collection_id"),transfer_id:We(t,"transfer_id"),direction:a,chunk_size:te(t,"chunk_size",4194304),chunk_index:te(t,"chunk_index"),offset:te(t,"offset"),plaintext_length:te(t,"plaintext_length",4194304),total_size:te(t,"total_size"),scope_epoch:te(t,"scope_epoch"),...s===void 0?{}:{key_id:s}});if(JSON.stringify(c)!==e)throw new w("invalid_header","File frame header must use the canonical field order without duplicate fields or whitespace");return c}function zt(n,e,t){let i=n==="upload_chunk"?"upload":"download";if(e.direction!==i)throw new w("invalid_header",`Frame kind ${n} requires direction ${i}`);let o=e.chunk_index*e.chunk_size;if(!Number.isSafeInteger(o)||e.offset!==o)throw new w("invalid_header","Chunk offset does not match its index and protocol chunk size");if(e.offset+e.plaintext_length>e.total_size)throw new w("invalid_header","Chunk extends past the declared transfer size");let r=e.protection==="grant_aead_v1"?e.plaintext_length+16:e.plaintext_length;if(t!==r)throw new w("invalid_length","Payload length does not match the protected plaintext length")}function lo(n){return n.plaintext_length+(n.protection==="grant_aead_v1"?16:0)}function Xe(n,e){let t=Ut(e),i=lo(t);zt(n,t,i);let o=new TextEncoder().encode(JSON.stringify(t));if(o.byteLength>16384)throw new w("limit_exceeded","File frame header exceeds the protocol limit");let r=new Uint8Array(16+o.byteLength);r.set(mn,0);let a=new DataView(r.buffer,r.byteOffset,r.byteLength);return a.setUint8(4,_n),a.setUint8(5,ro(n)),a.setUint16(6,gn,!1),a.setUint32(8,o.byteLength,!1),a.setUint32(12,i,!1),r.set(o,16),r}function vn(n){let e=Ut(n.header);if(zt(n.kind,e,n.payload.byteLength),n.payload.byteLength>4194320)throw new w("limit_exceeded","File frame payload exceeds the protocol limit");let t=Xe(n.kind,e),i=new Uint8Array(t.byteLength+n.payload.byteLength);return i.set(t,0),i.set(n.payload,t.byteLength),i}function Ze(n,e={}){if(n.byteLength<16)throw new w("invalid_length","File frame is shorter than its fixed prefix");if(!mn.every((h,f)=>n[f]===h))throw new w("invalid_magic","File frame magic is not MDBF");let t=new DataView(n.buffer,n.byteOffset,n.byteLength),i=t.getUint8(4);if(i!==_n)throw new w("unsupported_version",`Unsupported file frame version ${i}`);let o=ao(t.getUint8(5));if(t.getUint16(6,!1)!==gn)throw new w("unsupported_flags","File frame uses unsupported flags");let r=t.getUint32(8,!1),a=t.getUint32(12,!1),s=e.maxHeaderBytes??16384,c=e.maxPayloadBytes??4194320;if(r===0)throw new w("invalid_length","File frame header must not be empty");if(r>s||a>c)throw new w("limit_exceeded","File frame exceeds the configured decode limits");let d=16+r+a;if(!Number.isSafeInteger(d)||d!==n.byteLength)throw new w("invalid_length","File frame lengths do not match the supplied bytes");let p=16+r,u=co(n.subarray(16,p));return zt(o,u,a),{kind:o,header:u,payload:n.slice(p)}}var uo=["describe","changes","read","query","list_views","execute_view","read_view_source","create_view_source","update_view_source","delete_view_source","validate","create","update","delete","rename","read_type","create_type","update_type","assess_type_pack","apply_type_pack","list_timers","put_timer","cancel_timer","reconcile_timers","sync"],po=["list_files","open_file_upload","open_file_download","move_file","delete_file","get_file_transfer_status","commit_file_upload","abort_file_transfer"],ho={describe:"never",changes:"never",read:"never",query:"never",list_views:"never",execute_view:"never",read_view_source:"never",create_view_source:"always",update_view_source:"always",delete_view_source:"always",validate:"never",create:"always",update:"always",delete:"always",rename:"always",read_type:"never",create_type:"always",update_type:"always",assess_type_pack:"never",apply_type_pack:"always",list_timers:"never",put_timer:"always",cancel_timer:"always",reconcile_timers:"always",sync:"sync_action"},fo={describe:1,changes:1,read:1,query:1,list_views:1,execute_view:1,read_view_source:1,create_view_source:1,update_view_source:1,delete_view_source:1,validate:1,create:1,update:1,delete:1,rename:1,read_type:1,create_type:1,update_type:1,assess_type_pack:1,apply_type_pack:1,list_timers:1,put_timer:1,cancel_timer:1,reconcile_timers:1,sync:1},yo={list_files:1,open_file_upload:1,open_file_download:1,move_file:1,delete_file:1,get_file_transfer_status:1,commit_file_upload:1,abort_file_transfer:1},mo=new Set(["open_file_upload","move_file","delete_file","commit_file_upload","abort_file_transfer"]);var _o=new Set(uo),go=new Set(po);function wn(n){return _o.has(n)}function bo(n){return go.has(n)}function Cn(n,e){if(n==="file_control"){let t=Sn(e)&&typeof e.type=="string"?e.type:"";if(!bo(t))throw new Error(`Unknown file-control message: ${t}`);return yo[t]}return fo[n]}function G(n,e){let t=Sn(e)?e:{};if(t.dry_run===!0)return null;if(n==="file_control"){let o=typeof t.type=="string"?t.type:"";return mo.has(o)?`file_control:${o}`:null}let i=ho[n];return i==="always"?n:i==="sync_action"&&t.action==="mutate"?"sync:mutate":null}function et(n,e){return G(n,e)!==null}function Sn(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}var vo=1,wo="mdbase-connect mutation fingerprint v1\0",Ft=new TextEncoder;function Co(n){return Dt(n,new Set)}function So(n,e){let t=G(n,e);if(t===null)throw new TypeError("The operation is not a canonical mutation.");let i=Ft.encode(t),o=Ft.encode(Co(e)),r=Ft.encode(wo),a=new Uint8Array(r.length+4+8+i.length+4+8+o.length),s=new DataView(a.buffer),c=0;return a.set(r,c),c+=r.length,s.setUint32(c,vo,!1),c+=4,c=Pn(a,s,c,i),s.setUint32(c,Cn(n,e),!1),c+=4,Pn(a,s,c,o),a}async function On(n,e){let t=new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",So(n,e).buffer));return Ro(t)}function Dt(n,e){if(n===null)return"null";if(n===!0)return"true";if(n===!1)return"false";if(typeof n=="string")return Rn(n),JSON.stringify(n);if(typeof n=="number"){if(!Number.isFinite(n))throw new TypeError("Mutation input numbers must be finite.");return JSON.stringify(n)}if(typeof n!="object")throw new TypeError(`Mutation input contains unsupported ${typeof n}.`);if(e.has(n))throw new TypeError("Mutation input must not contain cycles.");e.add(n);try{if(Array.isArray(n)){if(Object.getOwnPropertySymbols(n).length>0)throw new TypeError("Mutation input must not contain symbol properties.");let o=[];for(let r=0;r<n.length;r+=1){if(!Object.hasOwn(n,r))throw new TypeError("Mutation input arrays must not be sparse.");o.push(Dt(n[r],e))}return`[${o.join(",")}]`}let t=Object.getPrototypeOf(n);if(t!==Object.prototype&&t!==null)throw new TypeError("Mutation input objects must be plain JSON objects.");if(Object.getOwnPropertySymbols(n).length>0)throw new TypeError("Mutation input must not contain symbol properties.");let i=Object.entries(n);for(let[o]of i)Rn(o);return i.sort(([o],[r])=>o<r?-1:o>r?1:0),`{${i.map(([o,r])=>{let a=Object.getOwnPropertyDescriptor(n,o);if(!a||a.get||a.set)throw new TypeError("Mutation input must not contain accessor properties.");return`${JSON.stringify(o)}:${Dt(r,e)}`}).join(",")}}`}finally{e.delete(n)}}function Rn(n){for(let e=0;e<n.length;e+=1){let t=n.charCodeAt(e);if(t>=55296&&t<=56319){let i=n.charCodeAt(e+1);if(!(i>=56320&&i<=57343))throw new TypeError("Mutation input strings must not contain lone surrogates.");e+=1}else if(t>=56320&&t<=57343)throw new TypeError("Mutation input strings must not contain lone surrogates.")}}function Pn(n,e,t,i){return e.setBigUint64(t,BigInt(i.length),!1),t+=8,n.set(i,t),t+i.length}function Ro(n){return btoa(String.fromCharCode(...n)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}var Y=2,Se=3;function Nt(n,e){let t={operation_transport:Y,authorization_binding:Se,semantic_capabilities:1};return(n.some(i=>et(i,{action:"mutate"}))||e?.actions.some(i=>i!=="list"&&i!=="read")===!0)&&(t.durable_mutation=1),t}var An={"collection.inspect":["describe"],"records.watch":["changes"],"records.read":["read"],"records.query":["query"],"records.validate":["validate"],"records.create":["create"],"records.update":["update"],"records.delete":["delete"],"records.rename":["rename"],"views.list":["list_views"],"views.execute":["execute_view"],"views.source.read":["read_view_source"],"views.source.create":["create_view_source"],"views.source.update":["update_view_source"],"views.source.delete":["delete_view_source"],"definitions.contracts.current":[],"definitions.read":["read_type"],"definitions.create":["create_type"],"definitions.update":["update_type"],"definitions.type-pack.inspect":["assess_type_pack"],"definitions.type-pack.apply":["assess_type_pack","apply_type_pack"],"timers.list":["list_timers"],"timers.put":["put_timer"],"timers.cancel":["cancel_timer"],"timers.reconcile":["reconcile_timers"],"sync.offline-replica":["sync"],"notifications.background-delivery":[],"files.list":[],"files.read":[],"files.add":[],"files.replace":[],"files.move":[],"files.delete":[]};function kn(n,e={}){let t=e.includeOptional===!1?n.required:[...n.required,...n.optional??[]];return[...new Set(t.flatMap(i=>An[i]))]}function tt(n){return[...An[n]]}var Po=new TextEncoder().encode("mdbase-connect application installation id v2\0"),Oo=new TextEncoder().encode("mdbase-connect application authorization proof v3\0");async function In(n){let e=nt(n),i=new Uint8Array(await crypto.subtle.digest("SHA-256",ne([Po,q(e)]))).slice(0,16);return i[6]=i[6]&15|128,i[8]=i[8]&63|128,[Re(i.slice(0,4)),Re(i.slice(4,6)),Re(i.slice(6,8)),Re(i.slice(8,10)),Re(i.slice(10,16))].join("-")}function Bt(n){let e=[nt(n.installation_signing_public_key),nt(n.grant_agreement_public_key),nt(n.grant_signing_public_key)];if(e.some((a,s)=>e.slice(s+1).some(c=>Eo(a,c))))throw new Error("Application authorization keys must be distinct.");let t=Lt(n.authorization_nonce),i=Lt(n.code_challenge),o=n.contracts;if(n.protocol_version!==3||t.byteLength!==32||!/^[0-9a-f]{64}$/u.test(n.application_manifest_digest)||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/u.test(n.issued_at)||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/u.test(n.expires_at)||i.byteLength!==32||![o.operation_transport,o.authorization_binding,o.semantic_capabilities,o.durable_mutation??1].every(a=>Number.isInteger(a)&&a>0)||n.requested_operations.length===0&&n.requested_files===void 0||new Set(n.requested_operations).size!==n.requested_operations.length||n.requested_operations.some(a=>!a||a.includes("\0"))||(n.flow==="authorization_code"?n.redirect_uri===void 0||n.state===void 0:n.flow!=="device_code"||n.redirect_uri!==void 0||n.state!==void 0))throw new Error("Application authorization binding is invalid.");ko(n.requested_files);let r=n.requested_operations.map(a=>q(new TextEncoder().encode(a)));return ne([Oo,H(n.protocol_version),q(it(n.application_id)),q(it(n.authorization_id)),q(Mn(n.application_manifest_digest)),q(it(n.application_installation_id)),...e.map(q),q(new TextEncoder().encode(n.flow)),q(t),q(new TextEncoder().encode(n.issued_at)),q(new TextEncoder().encode(n.expires_at)),Tn(n.redirect_uri),Tn(n.state),q(new TextEncoder().encode(n.code_challenge)),H(o.operation_transport),H(o.authorization_binding),H(o.semantic_capabilities),Ao(o.durable_mutation),H(r.length),...r,To(n.requested_files),Io(n.collection_id)])}function Ao(n){return n===void 0?new Uint8Array(1):ne([new Uint8Array([1]),H(n)])}function ko(n){if(n!==void 0&&(n.actions.length===0||new Set(n.actions).size!==n.actions.length||n.scope.kind==="selected_folders"&&(n.scope.folders.length===0||new Set(n.scope.folders).size!==n.scope.folders.length||n.scope.folders.some(e=>!e||e.includes("\0")))))throw new Error("Application authorization file request is invalid.")}function To(n){if(n===void 0)return new Uint8Array(1);let e=n.actions.map(t=>q(new TextEncoder().encode(t)));return ne([new Uint8Array([1]),H(e.length),...e,q(new TextEncoder().encode(n.scope.kind)),...n.scope.kind==="selected_folders"?[H(n.scope.folders.length),...n.scope.folders.map(t=>q(new TextEncoder().encode(t)))]:[]])}function Tn(n){return n===void 0?new Uint8Array(1):ne([new Uint8Array([1]),q(new TextEncoder().encode(n))])}function Io(n){return n===void 0?new Uint8Array(1):ne([new Uint8Array([1]),q(it(n))])}function nt(n){let e=Lt(n);if(e.byteLength!==65||e[0]!==4)throw new Error("Application authorization public key is invalid.");return e}function Lt(n){if(!/^[A-Za-z0-9_-]+$/u.test(n))throw new Error("Invalid base64url value.");let e=n.replaceAll("-","+").replaceAll("_","/"),t=e.padEnd(Math.ceil(e.length/4)*4,"="),i=Uint8Array.from(atob(t),o=>o.charCodeAt(0));if(Mo(i)!==n)throw new Error("Non-canonical base64url value.");return i}function it(n){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu.test(n))throw new Error("Invalid UUID value.");let e=n.replaceAll("-","");return Mn(e)}function Mn(n){if(!/^[0-9a-f]+$/u.test(n)||n.length%2!==0)throw new Error("Invalid hexadecimal value.");return Uint8Array.from({length:n.length/2},(e,t)=>Number.parseInt(n.slice(t*2,t*2+2),16))}function q(n){return ne([H(n.byteLength),n])}function H(n){let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,n,!1),e}function ne(n){let e=new Uint8Array(n.reduce((i,o)=>i+o.byteLength,0)),t=0;for(let i of n)e.set(i,t),t+=i.byteLength;return e}function Mo(n){return btoa(String.fromCharCode(...n)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}function Eo(n,e){return n.byteLength===e.byteLength&&n.every((t,i)=>t===e[i])}function Re(n){return[...n].map(e=>e.toString(16).padStart(2,"0")).join("")}var En=28485,Pe="P256-HKDF-SHA256-AES256GCM",ot=1;var xo="contract-setup-v1",qo="file-relay-v1",Uo=["application-authorization-v3","authorization-activation","encrypted-relay","policy-ack"];var zo=["durable-mutation-journal-v1","durable-file-lifecycle-v1"],Yr=[...zo,"mutation-replay-after-credential-retirement-v1"],Jr=[...Uo,xo,qo],Kt=1;var xn="mdbase-authority-request-proof-v1",Oe={version:"x-mdbase-proof-version",timestamp:"x-mdbase-proof-timestamp",nonce:"x-mdbase-proof-nonce",signature:"x-mdbase-proof-signature"};function jt(n,e,t){let i=new Set(n.required),o=[...new Set([...n.required,...n.optional??[]])],r={};for(let a of o)r[a]=Fo(a,i.has(a),e,t);return{contractVersion:1,values:r,requiredAvailable:n.required.every(a=>r[a]?.state==="available")}}function Fo(n,e,t,i){let o=tt(n),r=o.filter(s=>!i.operations.includes(s)),a={id:n,requirement:e?"required":"optional",operations:o,missingOperations:r,evidence:[{source:"application",fact:`${e?"Required":"Optional"} in capability contract v1.`}]};if(r.length>0)return{...a,state:"requires_authorization",evidence:[...a.evidence,{source:"authorization",fact:`Missing ${r.join(", ")}.`}],reason:"The current grant does not include every operation for this capability."};if(n==="definitions.contracts.current"&&i.scope.access!=="full_collection"){let s=new Set(i.scope.contracts.map(({id:d,version:p,digest:u})=>`${d}@${p}:${u}`)),c=(t.requirements?.contracts??[]).filter(({id:d,version:p,digest:u})=>!s.has(`${d}@${p}:${u}`));if(c.length>0)return{...a,state:"requires_authorization",reason:"The current grant does not approve the exact required contract definitions.",evidence:[...a.evidence,{source:"authorization",fact:`Missing ${c.map(({id:d,version:p})=>`${d}@${p}`).join(", ")}.`}],details:{missingContracts:c}}}if(n.startsWith("files.")){let s=n.slice(6);if(!i.fileCapability?.actions.includes(s))return{...a,state:i.fileCapability?"requires_authorization":"unsupported",reason:i.fileCapability?`The current file grant does not include ${s}.`:"This connection has no file capability.",evidence:[...a.evidence,{source:"authorization",fact:i.fileCapability?`Granted file actions: ${i.fileCapability.actions.join(", ")}.`:"No file capability was granted."}]}}return n==="notifications.background-delivery"&&(t.notifications?.criteria.length??0)===0?{...a,state:"requires_setup",reason:"The application manifest declares no notification criteria.",evidence:[...a.evidence,{source:"application",fact:"No authority notification criteria are declared."}]}:{...a,state:"available",evidence:[...a.evidence,{source:"authorization",fact:o.length>0?`Granted operations: ${o.join(", ")}.`:"No record operation is required."},{source:"authority",fact:i.authority.kind==="hosted"?"Backed by a durable hosted mdbase authority.":"Backed by a user-operated mdbase connector."}],...n==="sync.offline-replica"?{details:{durability:"device",writes:"queued",authority:i.authority.kind}}:{},...n==="notifications.background-delivery"?{details:{delivery:"authority",payload:"opaque"}}:{}}}var C=class extends Error{constructor(t,i={}){super(t.message,i.cause===void 0?void 0:{cause:i.cause});this.problem=t;this.name="MdbaseConnectError",this.code=t.code,this.status=i.status}problem;code;status;get retryable(){return this.problem.recovery==="retry"&&this.problem.operation_outcome!=="unknown"}get requiresAuthorization(){return this.problem.category==="authorization"}get outcomeUnknown(){return this.problem.operation_outcome==="unknown"}get recovery(){return this.problem.recovery}get details(){return this.problem.details}};function T(n,e,...[t={}]){let i=ee[n];return{problem_version:1,code:n,category:i.category,recovery:i.recovery,message:e,...t.details===void 0?{}:{details:t.details},...t.operationOutcome===void 0?{}:{operation_outcome:t.operationOutcome},...t.traceId===void 0?{}:{trace_id:t.traceId}}}function Ht(n,e,t={}){return qt(n,e,{details:t.details,operation_outcome:t.operationOutcome,trace_id:t.traceId})}function l(n,e,...t){let i=t[0];return new C(T(n,e,...t),{status:i?.status,cause:i?.cause})}function F(n,e,t={}){let{status:i,cause:o,...r}=t;return new C(qt(n,e,{details:r.details,operation_outcome:r.operationOutcome,trace_id:r.traceId}),{status:i,cause:o})}function Ae(n){let e=No(n.diagnostics),t=jo(n.diagnostics);if(e==="collection_version_unsupported"){let i=Lo(n.diagnostics);return T(e,t,{operationOutcome:"rejected",details:i})}return e!=="operation_invalid"?T(e,t,{operationOutcome:"rejected",details:{diagnostics:n.diagnostics}}):T(e,t,{operationOutcome:"rejected",details:{diagnostics:n.diagnostics,partial_result:n.result}})}function No(n){let e=new Set(n.filter(t=>t.severity==="error").map(t=>t.code));return["migration_required","migration_lossy","unsupported_version"].some(t=>e.has(t))?"collection_version_unsupported":["invalid_config","invalid_configuration","missing_config","missing_spec_version"].some(t=>e.has(t))?"collection_configuration_invalid":["duplicate_type","invalid_contract_definition","invalid_data_contract","invalid_type_definition","invalid_type_path"].some(t=>e.has(t))?"collection_type_registry_invalid":["collection_invalid","collection_open_failed"].some(t=>e.has(t))?"collection_invalid":"operation_invalid"}function Lo(n){let e=n.map(t=>t.details).find(t=>Bo(t));return{current_version:typeof e?.current_version=="string"?e.current_version:"0.2.x",required_version:typeof e?.required_version=="string"?e.required_version:"0.3.0"}}function Bo(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function Ko(n){return n instanceof C&&n.retryable}function jo(n){return n.filter(e=>e.severity==="error").map(e=>e.message).join(" ")||n.map(e=>e.message).join(" ")||"The collection rejected this operation."}var qn=["access_denied","access_paused","authorization_binding_incompatible","authorization_expired","capability_contract_incompatible","collection_access_denied","connector_identity_changed","connector_offline","connector_upgrade_required","direct_operation_rejected","durable_mutation_unsupported","operation_outcome_unknown","encryption_required","encrypted_relay_rejected","hosted_provider_unavailable","insufficient_access","invalid_encrypted_response","invalid_operation_response","invalid_request","missing_grant_key","mutation_recovery_expired","mutation_request_conflict","not_authorized","operation_cancelled","operation_failed","rate_limited","relay_authorization_expired","relay_unavailable","temporarily_unavailable","timeout","transport_protocol_incompatible","unsupported_operation"],$t=Object.keys(ee),J=["discovery_failed","invalid_operation_response","invalid_application_manifest","invalid_request","manifest_load_failed","rate_limited","temporarily_unavailable","timeout"],ie=[...J,"access_denied","application_identity_unavailable","approval_window_blocked","authorization_binding_incompatible","authorization_cancelled","authorization_replayed","browser_required","capability_contract_incompatible","collection_access_denied","collection_configuration_invalid","collection_contracts_missing","collection_incompatible","collection_invalid","collection_kind_unsupported","collection_mismatch","collection_not_found","collection_type_registry_invalid","collection_version_unsupported","connector_identity_changed","connector_offline","connector_upgrade_required","device_authorization_failed","durable_mutation_unsupported","encryption_required","expired_token","invalid_application_authorization","invalid_callback","invalid_device_authorization_response","invalid_token_response","scope_denied","reconnect_required","token_exchange_failed","transport_protocol_incompatible"],de=[...J,"authorization_expired","invalid_operation_response","invalid_push_subscription","managed_fcm_not_declared","not_authorized","notification_criterion_not_declared","notification_reauthorization_required","notification_registration_failed","notification_unregistration_failed","notifications_not_declared","notifications_unavailable"],at=["connector_offline","connector_upgrade_required","invalid_operation_response","not_authorized","operation_failed","temporarily_unavailable","timeout"],Ho=[...ie,"collection_not_ready","collection_not_selected","unknown_collection"],Un=["collection_configuration_invalid","collection_invalid","collection_type_registry_invalid","collection_version_unsupported"],ke=[...qn,...Un],L=[...ke,"invalid_path","operation_invalid"],Vt=[...L,"query_snapshot_changed","sandbox_unsupported"],x=[...L,"concurrent_modification","invalid_preflight","pending_mutation_unresolved"],Te=[...ke,"change_cursor_reset"],oe=[...x,"type_pack_provision_failed"];function M(n,e=[]){return{ok:!0,value:n,diagnostics:e}}function A(n){return{ok:!1,problem:n}}async function k(n,e){try{return M(await n())}catch(t){if(!(t instanceof C))throw t;let i=t.problem;return i.code==="unknown"||e.includes(i.code)?A(i):A(Ht(i.code,i.message,{details:i.details,operationOutcome:i.operation_outcome,traceId:i.trace_id}))}}var rt=class extends Error{constructor(t){super(t.message);this.problem=t;this.name="ConnectOutcomeError"}problem};function $o(n){if(!n.ok)throw new rt(n.problem);return n.value}var zn=3e4,Vo=1e4,Go=12e4,Yo=6e4;function ue(n={}){return{requestMs:st(n.requestMs,zn,"requestMs"),watchStartMs:st(n.watchStartMs,Vo,"watchStartMs"),uploadMs:st(n.uploadMs,Go,"uploadMs"),syncMs:st(n.syncMs,Yo,"syncMs")}}function ct(n={},e=zn,t=Date.now){let i=n.timeoutMs===void 0?e:n.timeoutMs,o=i===null?null:Jo(i),r=new AbortController,a=o===null?null:t()+o,s=()=>r.abort(n.signal?.reason);n.signal?.aborted?s():n.signal?.addEventListener("abort",s,{once:!0});let c=o===null?void 0:setTimeout(()=>r.abort(l("timeout","The operation exceeded its request deadline.",{operationOutcome:"not_sent"})),o),d=!1;return{signal:r.signal,deadline:a,remainingMs:()=>a===null?null:Math.max(0,a-t()),dispose:()=>{d||(d=!0,c!==void 0&&clearTimeout(c),n.signal?.removeEventListener("abort",s))}}}async function U(n,e,t){let i=ct(n,e),o,r=new Promise((s,c)=>{o=c}),a=()=>o?.(Gt(i.signal));i.signal.addEventListener("abort",a,{once:!0});try{if(i.signal.aborted)throw Gt(i.signal);return await Promise.race([t(i),r])}finally{i.signal.removeEventListener("abort",a),i.dispose()}}async function B(n,e,t){let i=ct(n,e);try{if(i.signal.aborted)throw Gt(i.signal);return await t(i)}finally{i.dispose()}}function Gt(n){return n.reason instanceof C?n.reason:l("operation_cancelled","The operation was cancelled before it changed the collection.",{operationOutcome:"not_sent",cause:n.reason})}function Jo(n){if(!Number.isSafeInteger(n)||n<=0)throw new TypeError("timeoutMs must be a positive safe integer or null.");return n}function st(n,e,t){if(n===void 0)return e;if(n===null)return null;if(!Number.isSafeInteger(n)||n<=0)throw new TypeError(`${t} must be a positive safe integer or null.`);return n}var Wo="mdbase-connect-keys",W="grant-keys",Jt=18446744073709551615n,Qo="mdbase-connect relay request key v1",Xo="mdbase-connect relay response key v1",Fn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Ie=class{database=null;async create(e){let t=await Bn(e),i=await this.open();return await Nn(i,o=>o.add({...t,counter:"0"})),t}async get(e){let t=await this.open(),i=await nr(t.transaction(W).objectStore(W).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,o)=>{let r=t.transaction(W,"readwrite"),a=r.objectStore(W),s=a.get(e),c=null;s.onerror=()=>o(s.error),s.onsuccess=()=>{let d=s.result;if(!d){r.abort(),o(new R("missing_grant_key","The encrypted grant key is unavailable."));return}let p=BigInt(d.counter)+1n;if(p>Jt){r.abort(),o(new R("counter_exhausted","The encrypted grant must be authorized again."));return}c=p.toString(),a.put({...d,counter:c})},r.onerror=()=>o(r.error),r.onabort=()=>o(r.error??new Error("Key counter transaction aborted.")),r.oncomplete=()=>{c&&i(c)}})}async delete(e){let t=await this.open();await Nn(t,i=>i.delete(e))}open(){if(typeof indexedDB>"u")throw new R("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(Wo,1);i.onupgradeneeded=()=>{i.result.objectStoreNames.contains(W)||i.result.createObjectStore(W,{keyPath:"handle"})},i.onerror=()=>t(i.error),i.onsuccess=()=>e(i.result)})),this.database}},Me=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 Bn(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,o=new Promise((r,a)=>{t=r,i=a});return this.sequence=this.sequence.then(()=>{let r=this.records.get(e);if(!r)throw new R("missing_grant_key","The encrypted grant key is unavailable.");let a=BigInt(r.counter)+1n;if(a>Jt)throw new R("counter_exhausted","The encrypted grant must be authorized again.");r.counter=a.toString(),t(r.counter)}).catch(r=>{i(r)}),o}async delete(e){this.records.delete(e)}};async function Wt(n,e,t,i){let o=await Zo(n,e,t),r=i.timestamp??Math.floor(Date.now()/1e3),a=i.nonce??crypto.randomUUID(),s=await Ln({...i,timestamp:r,nonce:a}),c=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},o.signingPrivateKey,new TextEncoder().encode(s));return{[Oe.version]:String(Kt),[Oe.timestamp]:String(r),[Oe.nonce]:a,[Oe.signature]:Ee(new Uint8Array(c))}}async function Ln(n){let e=n.method.toUpperCase(),t=await Dn(n.body??""),i=await Dn(n.credential);for(let o of[e,n.target,String(n.timestamp),n.nonce])if(!o||o.includes(`
2
+ `)||o.includes("\r"))throw new R("invalid_proof_input","Authority request proof metadata is invalid.");return[xn,Kt,e,n.target,t,i,n.timestamp,n.nonce].join(`
3
+ `)}async function pe(n,e,t,i,o,r=crypto.randomUUID()){Q(t.encryption);let a=await Kn(n,e,t.encryption.application_agreement_public_key),s=await n.nextCounter(e),c={binding:t,requestId:r,operation:i,counter:s},d=await jn(a.agreementPrivateKey,t,"request"),p=new TextEncoder().encode(JSON.stringify(o??{})),u=await crypto.subtle.encrypt({name:"AES-GCM",iv:Vn(s),additionalData:new TextEncoder().encode($n(c,"request")),tagLength:128},d,p);return{type:"encrypted_operation_request",...er(c),ciphertext:Ee(new Uint8Array(u))}}async function xe(n,e,t,i,o){if(!tr(i,o))throw new R("invalid_encrypted_response","Encrypted response metadata does not match its request.");let r=await Kn(n,e,t.encryption.application_agreement_public_key),a={binding:t,requestId:i.request_id,operation:i.operation,counter:i.counter},s=await jn(r.agreementPrivateKey,t,"response");try{let c=await crypto.subtle.decrypt({name:"AES-GCM",iv:Vn(i.counter),additionalData:new TextEncoder().encode($n(a,"response")),tagLength:128},s,Yn(Gn(o.ciphertext))),d=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(c));if(d?.ok===!0&&"result"in d||d?.ok===!1&&Ce(d.problem))return d;throw new Error("invalid response body")}catch(c){throw c instanceof R?c:new R("encrypted_response_rejected","The encrypted connector response could not be authenticated.")}}var R=class extends Error{constructor(t,i){super(i);this.code=t}code};async function Bn(n){let e=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"]),t=Ee(new Uint8Array(await crypto.subtle.exportKey("raw",e.publicKey))),i=await crypto.subtle.exportKey("pkcs8",e.privateKey),o=await crypto.subtle.importKey("pkcs8",i,{name:"ECDH",namedCurve:"P-256"},!1,["deriveBits"]),r=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign","verify"]),a=Ee(new Uint8Array(await crypto.subtle.exportKey("raw",r.publicKey))),s=await crypto.subtle.exportKey("pkcs8",r.privateKey),c=await crypto.subtle.importKey("pkcs8",s,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]);return{handle:n,agreementPrivateKey:o,agreementPublicKey:t,signingPrivateKey:c,signingPublicKey:a}}async function Kn(n,e,t){let i=await n.get(e);if(!i||i.agreementPublicKey!==t)throw new R("missing_grant_key","The encrypted grant key is unavailable or does not match the grant.");return i}async function Zo(n,e,t){let i=await n.get(e);if(!i||i.signingPublicKey!==t)throw new R("missing_grant_key","The remote authority signing key is unavailable or does not match the grant.");return i}async function jn(n,e,t){let i=await lt(n,e.encryption.connector_agreement_public_key),o=await crypto.subtle.importKey("raw",i,"HKDF",!1,["deriveKey"]),r=new TextEncoder().encode(Hn(e)),a=await crypto.subtle.digest("SHA-256",r);return crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:a,info:new TextEncoder().encode(t==="request"?Qo:Xo)},o,{name:"AES-GCM",length:256},!1,t==="request"?["encrypt"]:["decrypt"])}async function lt(n,e){try{let t=await crypto.subtle.importKey("raw",Yn(Yt(e)),{name:"ECDH",namedCurve:"P-256"},!1,[]);return await crypto.subtle.deriveBits({name:"ECDH",public:t},n,256)}catch{throw new R("invalid_public_key","The connector relay public key is invalid.")}}function Hn(n){let e=n.encryption;return["mdbase-connect",Y,e.suite,n.grantId,n.applicationId,e.connector_id,e.collection_id,e.scope_epoch,e.key_id].join("|")}function $n(n,e){return[Hn(n.binding),n.requestId,e,n.operation,n.counter].join("|")}function er(n){let e=n.binding.encryption;return{protocol_version:Y,suite:Pe,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 tr(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 Q(n){if(n.protocol_version!==ot||n.suite!==Pe||!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 R("unsupported_encryption","The grant uses an unsupported relay encryption profile.");if(typeof n.connector_id!="string"||!Fn.test(n.connector_id)||typeof n.collection_id!="string"||!Fn.test(n.collection_id))throw new R("unsupported_encryption","The grant uses invalid encrypted relay identities.");Yt(n.application_agreement_public_key),Yt(n.connector_agreement_public_key)}function Vn(n){let e=BigInt(n);if(e<=0n||e>Jt||e.toString()!==n)throw new R("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 Ee(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}async function Dn(n){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n));return Ee(new Uint8Array(e))}function Gn(n){if(!/^[A-Za-z0-9_-]+$/.test(n))throw new R("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 Yt(n){let e=Gn(n);if(e.length!==65||e[0]!==4)throw new R("invalid_public_key","Encrypted relay public keys must be uncompressed P-256 points.");return e}function Yn(n){return Uint8Array.from(n).buffer}function nr(n){return new Promise((e,t)=>{n.onerror=()=>t(n.error),n.onsuccess=()=>e(n.result)})}function Nn(n,e){return new Promise((t,i)=>{let o=n.transaction(W,"readwrite"),r=e(o.objectStore(W));r.onerror=()=>i(r.error),o.onerror=()=>i(o.error),o.onabort=()=>i(o.error??new Error("Grant key transaction aborted.")),o.oncomplete=()=>t()})}function re(n){return{...n,credentials:"omit",targetAddressSpace:"loopback"}}async function qe(){if(typeof navigator>"u"||!navigator.permissions?.query)return null;try{return(await navigator.permissions.query({name:"local-network-access"})).state}catch{return null}}function he(n){return n===404||n===405||n===426||n>=500}function Jn(n,e){return et(n,e)}function K(n){return[...new Set(n)]}function Wn(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 ae(n){if(n?.aborted)throw l("operation_cancelled","The operation was cancelled before it changed the collection.",{operationOutcome:"not_sent",cause:n.reason})}function dt(n,e,t,i){return n instanceof C?n:e?.aborted?t?D(t,n):e.reason instanceof C?e.reason:l("operation_cancelled","The operation was cancelled before it changed the collection.",{operationOutcome:"not_sent",cause:n}):t?D(t,n):n instanceof TypeError?l(i,i==="hosted_provider_unavailable"?"The hosted collection provider is unavailable.":"The Connect relay is unavailable.",{cause:n}):n instanceof Error?n:new Error(String(n))}function Xt(n,e){return e?.aborted===!0||n instanceof C&&n.code==="operation_cancelled"}function Qn(n,e){if(e.dry_run!==!0||e.would_rename!==!0||e.from!==n.from||e.to!==n.to)throw l("invalid_preflight","The rename preview does not match this mutation. Run the preview again.")}function Xn(n,e){if(e.dry_run!==!0||e.would_delete!==!0||e.path!==n.path)throw l("invalid_preflight","The delete preview does not match this mutation. Run the preview again.")}function Zn(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 ei(n){return{affectedRecords:new Set((n.broken_links??[]).map(e=>e.path)).size,totalUnits:1,warnings:0}}async function ti(n,e){return On(n,e??{})}function ni(n){return JSON.stringify(Qt(n))}function Qt(n){return Array.isArray(n)?n.map(e=>Qt(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,Qt(t)])):n}function D(n,e){return l("operation_outcome_unknown","The write may have completed, but mdbase could not recover its authoritative result. Retry the exact same write to recover safely.",{operationOutcome:"unknown",details:{request_id:n},cause:e})}function N(n){let e=new Uint8Array(n);return crypto.getRandomValues(e),Zt(e)}function Zt(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function ii(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 o=0;o<t.length;o+=1)i[o]=t.charCodeAt(o);return i}async function $(n,e,t,i){try{return await fetch(n,e)}catch(o){throw l(t,i,{cause:o})}}async function S(n,e,t){let i;try{i=await n.text()}catch(o){throw F(e,t,{status:n.status,cause:o})}if(i.trim()==="")throw F(e,t,{status:n.status});try{return JSON.parse(i)}catch(o){throw F(e,t,{status:n.status,cause:o})}}function oi(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 l("invalid_loopback_url","loopbackUrl must be an HTTP origin on 127.0.0.1 or ::1.");return e.origin}async function Ue(){let n=N(32),e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n));return{verifier:n,challenge:Zt(new Uint8Array(e))}}function P(n,e,t,i){return F(ze(n)??n?.error?.code??e,n?.error_description??n?.error?.message??t,{status:i,details:n?.error?.details})}function ze(n){return typeof n?.error=="string"?n.error:void 0}function Fe(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.files_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),o=new URL(t.sync_url),r=new URL(t.files_url);return[i,o,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(o.pathname)&&/^\/v1\/authorities\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/files$/i.test(r.pathname)&&i.origin===o.origin&&i.origin===r.origin&&i.pathname.split("/")[3]===e&&o.pathname.split("/")[3]===e&&r.pathname.split("/")[3]===e}catch{return!1}}function ri(n,e){return Fe({operations_url:n?.operationsUrl,sync_url:n?.syncUrl,files_url:n?.filesUrl,replica_id:n?.replicaId,access_token:n?.accessToken,proof_public_key:n?.proofPublicKey},e)}function ut(n){if(!n||typeof n!="object"||Array.isArray(n))return!1;let e=n,t=e.actions;if(e.kind!=="files"||e.protocol_version!==1||!Array.isArray(t)||t.length===0||t.length>6||new Set(t).size!==t.length||t.some(o=>!["list","read","add","replace","move","delete"].includes(o)))return!1;let i=e.scope;return!i||typeof i!="object"||Array.isArray(i)?!1:i.kind==="collection"?Object.keys(i).length===1:i.kind==="selected_folders"&&Object.keys(i).length===2&&Array.isArray(i.folders)&&i.folders.length>0&&i.folders.length<=100&&new Set(i.folders).size===i.folders.length&&i.folders.every(o=>typeof o=="string"&&o.length>0&&o.length<=1024&&ir(o))}function ir(n){let e=new Set([".mdbase",".git","node_modules","_contracts","_schemas","_types","_views"]);return!n.startsWith("/")&&!n.endsWith("/")&&!n.includes("\\")&&n.split("/").every(t=>{let i=t.split(".")[0]?.toUpperCase()??"";return t!==""&&t!=="."&&t!==".."&&!t.startsWith(".")&&!t.endsWith(" ")&&!t.endsWith(".")&&!/[<>:"|?*]/.test(t)&&!e.has(t.toLowerCase())&&!["CON","PRN","AUX","NUL"].includes(i)&&!/^(COM|LPT)[1-9]$/.test(i)})}function ai(n,e){if(!n||typeof n!="object"||Array.isArray(n)||n.collection_id!==e)return!1;try{return Q(n),!0}catch{return!1}}function si(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 l("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 I(n){if(!n)return null;try{return JSON.parse(n)}catch{return null}}function pt(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(o=>typeof o!="string")))?null:e}function ci(n){return n.endsWith("/")?n.slice(0,-1):n}function li(){if(typeof location>"u")throw l("manifest_required","manifest is required outside a browser environment.");if(location.origin==="null")throw l("manifest_required","Downloaded applications must provide their v1 portable manifest inline.");return new URL("/.well-known/mdbase-app.json",location.origin).href}function di(){if(typeof location>"u")throw l("redirect_uri_required","redirectUri is required outside a browser environment.");return location.href.split(/[?#]/)[0]}function ui(n,e,t,i){if(typeof n!="string"&&n.distribution==="portable"||i)return"null";let o=new URL(t);if(["http:","https:"].includes(o.protocol))return o.origin;if(typeof location<"u")return location.origin;if(typeof n!="string")return new URL(n.homepage).origin;try{return new URL(e).origin}catch{return""}}function pi(n){let e=":token:",t=n.lastIndexOf(e);return t<0?"":n.slice(t+e.length)}function ht(){if(typeof location>"u")throw l("callback_url_required","callbackUrl is required outside a browser environment.");return location.href}function hi(n){if(n)return new fe;if(typeof localStorage>"u")throw l("storage_required","storage is required outside a browser environment.");try{let e=`mdbase-connect:probe:${N(8)}`;return localStorage.setItem(e,"1"),localStorage.removeItem(e),localStorage}catch{return new fe}}var fe=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 fi(n){return typeof n=="string"||n.distribution!=="portable"?!1:typeof location>"u"||location.origin==="null"||!["http:","https:"].includes(location.protocol)}function yi(n){let e=ni(n),t=2166136261,i=2654435769;for(let o=0;o<e.length;o+=1){let r=e.charCodeAt(o);t=Math.imul(t^r,16777619),i=Math.imul(i^r,2246822507)}return`${(t>>>0).toString(16).padStart(8,"0")}${(i>>>0).toString(16).padStart(8,"0")}`}function De(n){for(let e of["code","state","error","error_description"])n.searchParams.delete(e);return n}function ft(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 mi(n){if(!n.details||typeof n.details!="object"||Array.isArray(n.details))return;let e=n.details.return_to;return typeof e=="string"?e:void 0}var se=["describe","changes","read","query"];var ye=class{constructor(e,t){this.connect=e;this.operations=K(t.operations??se),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(e){this.started||(this.started=!0,this.stopConnections=this.connect.onConnectionsChange(()=>this.refresh()),this.stopSelection=this.selection.subscribe(()=>{this.unavailableReason="not_authorized",this.refresh()}));let t=this.selection.authorizationCallback();if(t){let i=await this.handleAuthorizationCallback(t,e);if(!i.ok)return i}else this.autoSelectOnlyConnection();return this.refresh(),M(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);return i?(this.unavailableReason="not_authorized",this.selection.select(e,t),this.refresh(),M(i)):A(T("unknown_collection","This collection is not authorized for this application."))}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)return A(T("collection_not_selected","Choose a collection before updating its access."));let o=typeof e=="object"?e.collectionId:e==="selected"?i:null;this.transactionDepth+=1;try{let r=await this.connect.authorize({...t,operations:this.operations,target:o===null?{kind:"choose"}:{kind:"collection",collectionId:o},returnTo:this.selection.authorizationReturnTo()});return r.ok&&r.value.kind==="connected"&&this.selection.finishAuthorization(r.value.returnTo,r.value.connection.collectionId),r}finally{this.transactionDepth-=1,this.refresh()}}async ensureOperations(e){let t=this.snapshot;if(t.status!=="ready")return A(T("collection_not_ready","Choose an authorized collection first."));let i=K(e),o=t.connection.authorizationCapabilities(i);if(o.sufficient)return M({kind:"unchanged",connection:t.connection});this.transactionDepth+=1;try{let r=await this.connect.authorize({operations:K([...o.grantedOperations,...o.missingOperations]),target:{kind:"collection",collectionId:t.collectionId},returnTo:this.selection.authorizationReturnTo()});return r.ok&&r.value.kind==="connected"&&this.selection.finishAuthorization(r.value.returnTo,r.value.connection.collectionId),r}finally{this.transactionDepth-=1,this.refresh()}}handleAuthorizationCallback(e,t){if(!ft(e))return Promise.resolve(A(T("invalid_callback","This URL is not an authorization callback.")));if(this.callbackPromise)return this.callbackPromise;this.transactionDepth+=1;let i=this.connect.completeAuthorization(e,t).then(o=>{if(!o.ok){let a=mi(o.problem);return this.selection.clearAuthorizationCallback(a),this.refresh(),o}let r=o.value;return this.unavailableReason="not_authorized",this.selection.finishAuthorization(r.returnTo,r.connection.collectionId),this.refresh(),M(r.connection,o.diagnostics)}).catch(o=>{throw this.selection.clearAuthorizationCallback(),this.refresh(),o}).finally(()=>{this.transactionDepth-=1,this.refresh(),this.callbackPromise===i&&(this.callbackPromise=null)});return this.callbackPromise=i,i}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(a=>{!a&&this.selection.selectedCollectionId()===i.collectionId&&(this.unavailableReason="authorization_lost"),this.refresh()}));let o;if(!e)o={status:"unselected",connections:t};else if(!i||!i.info())o={status:"unavailable",collectionId:e,reason:this.connect.unavailableReason(e)??this.unavailableReason,connections:t};else{let a=i.info();o={status:"ready",collectionId:e,connection:i,info:a,access:i.authorizationCapabilities(this.operations),connections:t}}let r=or(o);if(r!==this.snapshotKey){this.snapshot=o,this.snapshotKey=r;for(let a of this.listeners)a()}}};function or(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 yt=class{values=new Map;read(e){return this.values.get(e)??null}write(e,t){this.values.set(e,t)}remove(e){this.values.delete(e)}},Ne=class{constructor(e,t,i=ue()){this.connect=e;this.options=t;this.timeouts=i;this.verificationStore=t.verificationStore??cr()}connect;options;timeouts;listeners=new Set;verificationStore;snapshot={status:"opening",connections:[]};manifest=null;base=null;stopBase;reviewEntries=[];verificationGeneration=0;start(e){return U(e,this.timeouts.watchStartMs,t=>this.startWithinBudget({signal:t.signal,timeoutMs:null}))}async startWithinBudget(e){let t=await this.connect.manifest(e);if(!t.ok)return t;let i=t.value.requirements?.capabilities;if(!i)return A(T("invalid_application_manifest","Application sessions require a versioned semantic capability contract.",{details:{issues:[{path:"/requirements/capabilities",keyword:"required",message:"is required for application sessions",params:{}}]}}));this.manifest=t.value,this.base=new ye(this.connect,{selection:this.options.selection,autoSelect:this.options.autoSelect,operations:rr(i)}),this.stopBase=this.base.subscribe(()=>this.refresh());let o=await this.base.start(e);return o.ok?(await this.refresh(!0,e),M(this.snapshot)):o}destroy(){this.verificationGeneration+=1,this.stopBase?.(),this.stopBase=void 0,this.base?.destroy(),this.base=null}getSnapshot(){return this.snapshot}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}connection(){let e=this.base?.getSnapshot();return e?.status==="ready"?e.connection:null}select(e,t={}){return this.requireBase().select(e,t)}clearSelection(e={}){this.requireBase().clearSelection(e)}forget(e){this.requireBase().forget(e)}authorize(e,t={}){return this.requireBase().authorize(e,t)}handleAuthorizationCallback(e,t){return this.requireBase().handleAuthorizationCallback(String(e),t)}completeAuthorization(e,t){return this.requireBase().handleAuthorizationCallback(e===void 0?ht():String(e),t)}ensureCapabilities(e){let t=this.requireManifest().requirements?.capabilities,i=new Set([...t?.required??[],...t?.optional??[]]);return e.some(o=>!i.has(o))?Promise.resolve(A(T("invalid_application_manifest","Applications may only request capabilities declared in their manifest.",{details:{issues:[{path:"/requirements/capabilities",keyword:"undeclaredCapability",message:"must declare every capability requested by the application",params:{requested:e,declared:[...i]}}]}}))):this.requireBase().ensureOperations(ar(e))}async applyDefinitionUpdates(e){if(this.snapshot.status!=="definition_review_required"||this.reviewEntries.length===0)return A(T("collection_not_ready","There are no reviewed definition updates to apply."));if(this.reviewEntries.some(({assessment:i})=>!i.applicable))return A(T("collection_not_ready","Resolve the definition conflicts before applying this update."));let t=this.connection();if(!t)return A(T("collection_not_ready","The collection is not ready."));for(let{provision:i,assessment:o}of this.reviewEntries){let r={provision:i,installed_by:this.requireManifest().id,expected_assessment_digest:o.assessment_digest,...o.status==="downgrade"?{allow_downgrade:!0}:{}},a=e?await t.applyTypePack(r,e):await t.applyTypePack(r);if(!a.ok)return a}return this.reviewEntries=[],await this.verifyDefinitions(this.context(t),++this.verificationGeneration,e),M(this.snapshot)}async refresh(e=!1,t){if(!this.base||!this.manifest)return;let i=this.base.getSnapshot();this.verificationGeneration+=1;let o=this.verificationGeneration;if(this.reviewEntries=[],i.status==="unselected"){this.publish({status:"unselected",connections:i.connections});return}if(i.status==="unavailable"){this.publish(i);return}let r=this.context(i.connection);if(!r.capabilities.requiredAvailable){this.publish({status:"authorization_required",...r});return}if((this.manifest.requirements?.capabilities?.required.includes("definitions.type-pack.apply")??!1?this.manifest.provisions?.type_packs??[]:[]).length===0){this.publish({status:"ready",verification:"verified",...r});return}let c=en(this.manifest,i.collectionId);this.verificationStore.read(c)===_i(this.manifest)?this.publish({status:"ready",verification:"cached",...r}):this.publish({status:"checking_definitions",...r});let d=this.verifyDefinitions(r,o,t);e&&await d}async verifyDefinitions(e,t,i){let o=this.connection(),r=this.requireManifest();if(!o||o.collectionId!==e.collectionId)return;let a=[],s=r.requirements?.capabilities?.required.includes("definitions.type-pack.apply")??!1;for(let c of s?r.provisions?.type_packs??[]:[]){let d={provision:c,installed_by:r.id},p=i?await o.assessTypePack(d,i):await o.assessTypePack(d);if(t!==this.verificationGeneration)return;if(!p.ok){this.publish({status:"blocked",problem:p.problem,...e});return}p.value.status!=="current"&&a.push({provision:c,assessment:p.value})}if(t===this.verificationGeneration){if(a.length>0){this.reviewEntries=a,this.verificationStore.remove(en(r,e.collectionId)),this.publish({status:"definition_review_required",updates:a.map(sr),...e});return}this.verificationStore.write(en(r,e.collectionId),_i(r)),this.publish({status:"ready",verification:"verified",...e})}}context(e){let t=e.info();return{collectionId:e.collectionId,info:t,capabilities:jt(this.requireManifest().requirements.capabilities,this.requireManifest(),t),connections:this.connect.connections()}}publish(e){if(JSON.stringify(this.snapshot)!==JSON.stringify(e)){this.snapshot=e;for(let t of this.listeners)t()}}requireBase(){if(!this.base)throw new Error("Start the application session before using it.");return this.base}requireManifest(){if(!this.manifest)throw new Error("Start the application session before using it.");return this.manifest}};function rr(n){return kn(n)}function ar(n){let e=n.flatMap(t=>tt(t));return[...new Set(e)]}function sr(n){let{assessment:e}=n,t=e.status==="conflict"?"Existing user-owned resources conflict with this application definition pack.":e.status==="install"?"This collection needs the application definitions installed.":`This collection has a ${e.status} definition change to review.`;return{id:e.desired.id,name:n.provision.manifest.name??e.desired.id,status:e.status,applicable:e.applicable,assessmentDigest:e.assessment_digest,...e.current?{currentVersion:e.current.version}:{},desiredVersion:e.desired.version,resources:e.resources,contractSetups:e.contract_setups,canApply:e.applicable,reason:t}}function en(n,e){return`mdbase-application-session:v1:${n.id}:${e}`}function _i(n){return JSON.stringify({capabilities:n.requirements?.capabilities,provisions:n.provisions?.type_packs??[]})}function cr(){return typeof localStorage<"u"?{read:n=>localStorage.getItem(n),write:(n,e)=>localStorage.setItem(n,e),remove:n=>localStorage.removeItem(n)}:new yt}function Le(n,e){return new Promise((t,i)=>{if(e?.aborted){i(e?.reason??new DOMException("Aborted","AbortError"));return}let o=()=>e?.removeEventListener("abort",a),r=setTimeout(()=>{o(),t()},n),a=()=>{clearTimeout(r),o(),i(e?.reason??new DOMException("Aborted","AbortError"))};e?.addEventListener("abort",a,{once:!0})})}var lr="mdbase-connect-identities",me="application-identities",tn=BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),dr=tn/2n,Be=class{database=null;async create(e){let t=await bi(e),i=await this.open();return await gi(i,o=>o.add(t)),t}async get(e){let t=await this.open();return await ur(t.transaction(me).objectStore(me).get(e))??null}async delete(e){let t=await this.open();await gi(t,i=>i.delete(e))}open(){if(typeof indexedDB>"u")throw new _e("Persistent application identity requires browser IndexedDB or an injected identity store.");return this.database||(this.database=new Promise((e,t)=>{let i=indexedDB.open(lr,1);i.onupgradeneeded=()=>{i.result.objectStoreNames.contains(me)||i.result.createObjectStore(me,{keyPath:"handle"})},i.onerror=()=>t(i.error),i.onsuccess=()=>e(i.result)})),this.database}},Ke=class{records=new Map;async create(e){if(this.records.has(e))throw new Error(`Application identity already exists: ${e}`);let t=await bi(e);return this.records.set(e,t),t}async get(e){return this.records.get(e)??null}async delete(e){this.records.delete(e)}},_e=class extends Error{constructor(e){super(e),this.name="ApplicationIdentityStoreError"}};async function je(n){return In(n.signingPublicKey)}async function mt(n,e){if(n.installation_signing_public_key!==e.signingPublicKey||n.application_installation_id!==await je(e))throw new Error("Application authorization identity does not match its binding.");let t=hr(new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},e.signingPrivateKey,Bt(n))));return{binding:n,signature:vi(t)}}async function nn(n,e,t){let i=`application-installation:v2:${e}:${t.id}`,o=await n.get(i);if(o)return o;try{return await n.create(i)}catch(r){let a=await n.get(i);if(a)return a;throw r}}async function bi(n){let e=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign","verify"]),t=vi(new Uint8Array(await crypto.subtle.exportKey("raw",e.publicKey))),i=await crypto.subtle.exportKey("pkcs8",e.privateKey),o=await crypto.subtle.importKey("pkcs8",i,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]);return{handle:n,signingPrivateKey:o,signingPublicKey:t}}function ur(n){return new Promise((e,t)=>{n.onerror=()=>t(n.error),n.onsuccess=()=>e(n.result)})}function gi(n,e){return new Promise((t,i)=>{let o=n.transaction(me,"readwrite");e(o.objectStore(me)).onerror=()=>i(o.error),o.onerror=()=>i(o.error),o.onabort=()=>i(o.error??new Error("Identity transaction aborted.")),o.oncomplete=()=>t()})}function pr(n){let e=new Uint8Array(n.reduce((i,o)=>i+o.byteLength,0)),t=0;for(let i of n)e.set(i,t),t+=i.byteLength;return e}function vi(n){return btoa(String.fromCharCode(...n)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}function hr(n){if(n.byteLength!==64)throw new Error("Application authorization signature is invalid.");let e=fr(n.slice(32));if(e===0n||e>=tn)throw new Error("Application authorization signature is invalid.");return e<=dr?n:pr([n.slice(0,32),yr(tn-e,32)])}function fr(n){return BigInt(`0x${mr(n)}`)}function yr(n,e){let t=n.toString(16).padStart(e*2,"0");return Uint8Array.from({length:e},(i,o)=>Number.parseInt(t.slice(o*2,o*2+2),16))}function mr(n){return[...n].map(e=>e.toString(16).padStart(2,"0")).join("")}var ge=class{constructor(e){this.transport=e}transport;operation(e,t,i){return k(()=>this.transport.operation(e,t,i),$t)}describe(e){return this.rawOperation("describe",{},ke,e)}changes(e={},t){return this.rawOperation("changes",e,Te,t)}read(e,t){return this.envelopeOperation("read",e,L,t)}query(e={},t){return this.envelopeOperation("query",e,Vt,t)}async*queryPages(e={},t={}){let{offset:i,limit:o,snapshot:r,...a}=e,s=gr(i,0),c=wi(t.firstPageSize??o,200),d=wi(t.pageSize??o,1e3),p=r,u=0,h=0;for(;!t.signal?.aborted;){let f=await this.query({...a,offset:s,limit:h===0?c:d,...p?{snapshot:p}:{}},{signal:t.signal,timeoutMs:t.timeoutMs});if(!f.ok){yield f;return}let m=f.value,y=m.meta?.snapshot;if(p&&y&&p!==y){yield A(T("query_snapshot_changed","The collection query snapshot changed while paging. Refresh the query before continuing."));return}!p&&y&&(p=y),u+=m.results.length;let g=!m.meta?.has_more||m.results.length===0,b={results:m.results,...m.meta?{meta:m.meta}:{},page:h,offset:s,loaded:u,complete:g,...p?{snapshot:p}:{}};if(t.onProgress?.(b),yield M(b,f.diagnostics),g)return;s+=m.results.length,h+=1}}async queryAll(e={},t={}){let i=[],o,r=[];for await(let a of this.queryPages(e,t)){if(!a.ok)return a;let s=a.value;i.push(...s.results),o=s,r.push(...a.diagnostics)}return M({results:i,meta:{...o?.meta??{},total_count:o?.meta?.total_count??i.length,has_more:o?!o.complete:!1,...o?.snapshot?{snapshot:o.snapshot}:{}}},r)}listViews(e){return this.envelopeOperation("list_views",{},L,e)}executeView(e,t){return this.envelopeOperation("execute_view",e,L,t)}readViewSource(e,t){return this.envelopeOperation("read_view_source",e,L,t)}createViewSource(e,t){return this.envelopeOperation("create_view_source",e,x,t)}updateViewSource(e,t){return this.envelopeOperation("update_view_source",e,x,t)}deleteViewSource(e,t){return this.envelopeOperation("delete_view_source",e,x,t)}create(e,t){return this.envelopeOperation("create",e,x,t)}update(e,t){return this.envelopeOperation("update",e,x,t)}delete(e,t){return this.envelopeOperation("delete",e,x,t)}preflightDelete(e,t){return this.envelopeOperation("delete",{...e,check_backlinks:!0,dry_run:!0},x,t)}rename(e,t){return this.envelopeOperation("rename",e,x,t)}preflightRename(e,t){return this.envelopeOperation("rename",{...e,dry_run:!0},x,t)}validate(e={},t){return this.envelopeOperation("validate",e,L,t)}readType(e,t){return this.envelopeOperation("read_type",e,oe,t)}createType(e,t){return this.envelopeOperation("create_type",e,oe,t)}updateType(e,t){return this.envelopeOperation("update_type",e,oe,t)}assessTypePack(e,t){return this.envelopeOperation("assess_type_pack",e,oe,t)}applyTypePack(e,t){return this.envelopeOperation("apply_type_pack",e,oe,t)}listTimers(e,t){return this.rawOperation("list_timers",{namespace:e},L,t)}putTimer(e,t){return this.rawOperation("put_timer",e,x,t)}cancelTimer(e,t){return this.rawOperation("cancel_timer",e,x,t)}reconcileTimers(e,t){return this.rawOperation("reconcile_timers",e,x,t)}async*watch(e={}){let t=e.cursor,i=Math.max(100,e.pollIntervalMs??1e3),o=_r(e.retry),r=0,a=!1;for(e.onStatus?.({state:"connecting",...t===void 0?{}:{cursor:t}});!e.signal?.aborted;){let s=await this.changes(t===void 0?{}:{after:t,limit:200},{signal:e.signal,timeoutMs:e.timeoutMs});if(!s.ok){let p=s.problem;if(e.signal?.aborted)return;if(!o||p.recovery!=="retry"){yield s;return}if(a=!1,r+=1,o.maxAttempts!==void 0&&r>o.maxAttempts){yield s;return}let u=Math.min(o.maxDelayMs,Math.round(o.initialDelayMs*o.multiplier**(r-1)));e.onStatus?.({state:"reconnecting",...t===void 0?{}:{cursor:t},attempt:r,retryInMs:u,problem:p});try{await Le(u,e.signal)}catch{if(!e.signal?.aborted)throw l("operation_failed","Watch retry delay failed unexpectedly.")}continue}let c=s.value;if(t===void 0){t=c.cursor;continue}if(c.reset){let p=T("change_cursor_reset","The collection change cursor expired. Refresh collection state before subscribing again.");e.onStatus?.({state:"reset_required",cursor:t,problem:p}),yield A(p);return}let d=r>0;r=0,(!a||d)&&e.onStatus?.({state:"connected",cursor:t,recovered:d}),a=!0;for(let p of c.events)yield M(p);if(t=c.cursor,!c.has_more)try{await Le(i,e.signal)}catch{if(!e.signal?.aborted)throw l("operation_failed","Watch polling delay failed unexpectedly.")}}}rawOperation(e,t,i,o){return k(()=>this.transport.operation(e,t,o),i)}async envelopeOperation(e,t,i,o){let r=await k(()=>this.transport.operation(e,t,o),i);if(!r.ok)return r;let a=r.value;return a.valid?M(a.result,a.diagnostics):A(Ae(a))}};function _r(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 gr(n,e){return typeof n=="number"&&Number.isFinite(n)?Math.max(0,Math.floor(n)):e}function wi(n,e){return typeof n=="number"&&Number.isFinite(n)&&n>0?Math.floor(n):e}var _t=class{constructor(e){this.context=e}context;async registerNotifications(e){return U(e,this.context.requestTimeoutMs,t=>this.registerNotificationsWithinBudget(e,t.signal))}async registerNotificationsWithinBudget(e,t){let i=await this.context.authorizedToken(t);if(!i)throw l("not_authorized","Connect this application before enabling notifications.");let r=(await this.context.register(t)).notifications?.criteria.map(b=>b.id)??[],a=[...new Set(e.criteria??r)],s=a.find(b=>!r.includes(b));if(s)throw l("notification_criterion_not_declared",`The application manifest does not declare notification criterion ${s}.`);if(a.length===0)throw l("notifications_not_declared","This application manifest does not declare any notification criteria.");let c=await $(`${this.context.serverUrl}/v1/notifications/vapid-public-key`,{signal:t},"notifications_unavailable","Push notifications are unavailable."),d=await S(c,"invalid_operation_response","Connect returned an invalid notification key response.");if(!c.ok)throw P(d,"notifications_unavailable","Push notifications are unavailable.",c.status);let p=await e.serviceWorker.pushManager.getSubscription();p||(p=await e.serviceWorker.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:ii(d.public_key)}));let u=p.toJSON();if(!u.endpoint||!u.keys?.p256dh||!u.keys.auth)throw l("invalid_push_subscription","The browser returned an incomplete push subscription.");let h=I(this.context.storage.getItem(this.context.notificationKey())),f=e.installationId??h?.installationId??N(24),m=await $(`${this.context.serverUrl}/v1/notifications/channels`,{method:"POST",headers:{authorization:`Bearer ${i.accessToken}`,"content-type":"application/json"},body:JSON.stringify({installation_id:f,criteria:a,subscription:{endpoint:u.endpoint,expirationTime:u.expirationTime??null,keys:u.keys}}),signal:t},"notification_registration_failed","Could not register push notifications."),y=await S(m,"invalid_operation_response","Connect returned an invalid notification registration response.");if(!m.ok)throw P(y,"notification_registration_failed","Could not register push notifications.",m.status);h?.channelId&&h.channelId!==y.channel_id&&fetch(`${this.context.serverUrl}/v1/notifications/channels/${h.channelId}`,{method:"DELETE",headers:{authorization:`Bearer ${i.accessToken}`},signal:t}).catch(()=>{});let g={channelId:y.channel_id,installationId:f,criteria:a};return this.context.storage.setItem(this.context.notificationKey(),JSON.stringify(g)),g}async registerNativeNotifications(e){return U(e,this.context.requestTimeoutMs,t=>this.registerNativeNotificationsWithinBudget(e,t.signal))}async registerNativeNotificationsWithinBudget(e,t){let i=await this.context.authorizedToken(t);if(!i)throw l("not_authorized","Connect this application before enabling notifications.");let o=await this.context.register(t);if(o.notifications?.native_delivery?.mode!=="managed_fcm")throw l("managed_fcm_not_declared","This application does not declare Connect-managed native notifications.");let r=o.notifications.criteria.map(m=>m.id),a=[...new Set(e.criteria??r)],s=a.find(m=>!r.includes(m));if(s)throw l("notification_criterion_not_declared",`The application manifest does not declare notification criterion ${s}.`);if(a.length===0)throw l("notifications_not_declared","This application manifest does not declare any notification criteria.");let c=this.context.notificationKey("fcm"),d=I(this.context.storage.getItem(c)),p=e.installationId??d?.installationId??N(24),u=await $(`${this.context.serverUrl}/v1/notifications/channels`,{method:"POST",headers:{authorization:`Bearer ${i.accessToken}`,"content-type":"application/json"},body:JSON.stringify({installation_id:p,criteria:a,transport:"fcm",token:e.token}),signal:t},"notification_registration_failed","Could not register native notifications."),h=await S(u,"invalid_operation_response","Connect returned an invalid native notification response.");if(!u.ok)throw P(h,"notification_registration_failed","Could not register native notifications.",u.status);d?.channelId&&d.channelId!==h.channel_id&&this.deleteNotificationChannel(d.channelId,i.accessToken,t).catch(()=>{});let f={channelId:h.channel_id,installationId:p,transport:"fcm",criteria:a};return this.context.storage.setItem(c,JSON.stringify(f)),f}async unregisterNativeNotifications(e={}){return U(e,this.context.requestTimeoutMs,t=>this.unregisterNativeNotificationsWithinBudget(t.signal))}async unregisterNativeNotificationsWithinBudget(e){let t=this.context.notificationKey("fcm"),i=I(this.context.storage.getItem(t)),o=await this.context.authorizedToken(e);if(i?.channelId&&!o)throw l("not_authorized","Reconnect this application before disabling native notifications.");i?.channelId&&o&&await this.deleteNotificationChannel(i.channelId,o.accessToken,e),this.context.storage.removeItem(t)}async unregisterNotifications(e,t={}){return U(t,this.context.requestTimeoutMs,i=>this.unregisterNotificationsWithinBudget(e,i.signal))}async unregisterNotificationsWithinBudget(e,t){let i=I(this.context.storage.getItem(this.context.notificationKey())),o=await this.context.authorizedToken(t);if(i?.channelId&&!o)throw l("not_authorized","Reconnect this application before disabling push notifications.");if(i?.channelId&&o){let a=await $(`${this.context.serverUrl}/v1/notifications/channels/${i.channelId}`,{method:"DELETE",headers:{authorization:`Bearer ${o.accessToken}`},signal:t},"notification_unregistration_failed","Could not unregister push notifications.");if(!a.ok&&a.status!==404){let s=await S(a,"invalid_operation_response","Connect returned an invalid notification response.");throw P(s,"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,i){let o=await $(`${this.context.serverUrl}/v1/notifications/channels/${e}`,{method:"DELETE",headers:{authorization:`Bearer ${t}`},signal:i},"notification_unregistration_failed","Could not unregister push notifications.");if(!o.ok&&o.status!==404){let r=await S(o,"invalid_operation_response","Connect returned an invalid notification response.");throw P(r,"notification_unregistration_failed","Could not unregister push notifications.",o.status)}}};async function gt(n,e,t,i,o,r){if(!n.authority)throw l("not_remote_authority","This authorization has no remote authority endpoint.");let a=t===""||t.startsWith("?")?t:`/${t}`,s=`${n.authority.filesUrl}${a}`,c=i===void 0?void 0:JSON.stringify(i),d=await r(n,e,s,c,n.authority.accessToken);return fetch(s,{method:e,redirect:"error",headers:{authorization:`Bearer ${n.authority.accessToken}`,...c===void 0?{}:{"content-type":"application/json"},...d},...c===void 0?{}:{body:c},...o?{signal:o}:{}})}async function Ci(n,e,t,i,o,r,a){let s=n,c=await gt(s,e,t,i,o,a);if(c.status===401&&s.refreshToken){if(s=await r(),!s.authority||!s.fileCapability)throw l("authority_authorization_changed","Reconnect this collection before accessing its files.");c=await gt(s,e,t,i,o,a)}let d=await S(c,"invalid_operation_response","The hosted authority returned an invalid file response.");if(!c.ok)throw P(d,"operation_failed","Collection file request failed.",c.status);return d}async function Si(n,e,t,i,o,r){let a=n,s=await gt(a,"GET",e,void 0,i,r);if(s.status===401&&a.refreshToken){if(a=await o(),!a.authority||!a.fileCapability)throw l("authority_authorization_changed","Reconnect this collection before accessing its files.");s=await gt(a,"GET",e,void 0,i,r)}if(!s.ok){let d=await S(s,"invalid_operation_response","The hosted authority returned an invalid file range error response.");throw P(d,"operation_failed","Collection file range request failed.",s.status)}let c=s.headers.get("content-length");if(c===null||!/^(0|[1-9][0-9]*)$/u.test(c)||Number(c)!==t)throw await s.body?.cancel().catch(()=>{}),l("invalid_operation_response","The hosted file response declared an unexpected byte length.");if(!s.body)throw l("invalid_operation_response","The hosted file response did not contain a byte stream.");return s.body}var br="mdbase-connect file chunk key v1",bt=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,X=class extends Error{constructor(t,i){super(i);this.code=t;this.name="FileTransferCryptoError"}code},He=class n{constructor(e,t){this.binding=e;this.key=t}binding;key;static async open(e,t,i){Ri(i);let o=await e.get(t);if(!o||o.agreementPublicKey!==i.encryption.application_agreement_public_key)throw new R("missing_grant_key","The encrypted grant key is unavailable or does not match the file transfer grant.");let r=await lt(o.agreementPrivateKey,i.encryption.connector_agreement_public_key);return n.fromSharedSecret(r,i)}static async fromSharedSecret(e,t){Ri(t);let i=await Oi(e,t);return new n(t,i)}async encryptChunk(e,t,i){if(this.validateHeader(t),i.byteLength!==t.plaintext_length)throw new X("plaintext_length_mismatch","File chunk plaintext length does not match its authenticated header.");let o=Xe(e,t),r=await crypto.subtle.encrypt({name:"AES-GCM",iv:Pi(t.chunk_index),additionalData:vt(o),tagLength:128},this.key,vt(i));return vn({kind:e,header:t,payload:new Uint8Array(r)})}async decryptChunk(e){let t=Ze(e);this.validateHeader(t.header);let i=Xe(t.kind,t.header);try{let o=await crypto.subtle.decrypt({name:"AES-GCM",iv:Pi(t.header.chunk_index),additionalData:vt(i),tagLength:128},this.key,vt(t.payload));return new Uint8Array(o)}catch{throw new X("authentication_failed","The encrypted file chunk could not be authenticated.")}}validateHeader(e){let t=this.binding.encryption;if(e.protocol_version!==1||e.protection!=="grant_aead_v1"||e.grant_id!==this.binding.grantId||e.authority_id!==this.binding.authorityId||e.collection_id!==t.collection_id||e.transfer_id!==this.binding.transferId||e.direction!==this.binding.direction||e.scope_epoch!==t.scope_epoch||e.key_id!==t.key_id)throw new X("header_binding_mismatch","The file frame does not match its transfer encryption binding.")}};async function Oi(n,e){let t=new TextEncoder().encode(vr(e)),i=await crypto.subtle.digest("SHA-256",t),o=await crypto.subtle.importKey("raw",n,"HKDF",!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:i,info:new TextEncoder().encode(br)},o,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}function Ri(n){if(Q(n.encryption),!bt.test(n.grantId)||!bt.test(n.applicationId)||!bt.test(n.authorityId)||!bt.test(n.transferId)||n.direction!=="upload"&&n.direction!=="download")throw new X("invalid_binding","The file transfer encryption binding is invalid.")}function vr(n){let e=n.encryption;return["mdbase-connect","file-transfer",1,e.suite,n.grantId,n.applicationId,e.connector_id,n.authorityId,e.collection_id,e.scope_epoch,e.key_id,n.transferId,n.direction].join("|")}function Pi(n){if(!Number.isSafeInteger(n)||n<0)throw new X("invalid_chunk_index","The file chunk index is invalid.");let e=new Uint8Array(new ArrayBuffer(12));return new DataView(e.buffer).setBigUint64(4,BigInt(n),!1),e}function vt(n){return Uint8Array.from(n).buffer}var Ct=class{constructor(e){this.options=e}options;async control(e,t,i,o,r){be(e);let a=Or(t,i,o),s=await this.encryptControl(e,a),c;if(await this.options.shouldAttemptDirect(e)){try{c=await fetch(`${this.options.loopbackUrl}/v1/files/control`,re({method:"POST",headers:{"content-type":"application/mdbase-connect+json"},body:JSON.stringify(s),signal:r}))}catch(d){if(r?.aborted)throw d;this.options.onDirectUnavailable()}if(c&&!he(c.status))return c.ok&&this.options.onDirectAvailable(),this.decryptControlResponse(e,s,c);c&&this.options.onDirectUnavailable()}return c=await this.sendRelayControl(e,s,r),await Cr(c,e)&&(e=await this.options.refreshAuthorization(r),on(e),s=await this.encryptControl(e,a),c=await this.sendRelayControl(e,s,r)),c.ok&&this.options.onRelayAvailable(),this.decryptControlResponse(e,s,c)}async decryptControlResponse(e,t,i){let o=await S(i,"invalid_operation_response","The collection authority returned an invalid file control response.");if(!i.ok)throw P(o,"operation_failed","Collection file request failed.",i.status);let r=o?.envelope;if(!r)throw l("invalid_encrypted_response","The connector omitted its encrypted file response.");let a=await xe(this.options.keyStore,e.keyHandle,rn(e),t,r);return a.ok||Pr(a.problem),a.result}async uploadChunk(e,t,i,o){let a=await this.localFileToken(e,"upload",o),s=await Ai(this.options.keyStore,a,e,t,i),c;if(await this.options.shouldAttemptDirect(a)){try{c=await fetch(`${this.options.loopbackUrl}/v1/files/upload`,re(ki(s,o)))}catch(d){if(o?.aborted)throw d;this.options.onDirectUnavailable()}if(c&&!he(c.status))return c.ok&&this.options.onDirectAvailable(),wr(c,"Encrypted file chunk upload failed.");c&&this.options.onDirectUnavailable()}if(c=await this.sendRelayUpload(a,s,o),c.status===401&&a.refreshToken&&(a=await this.options.refreshAuthorization(o),on(a),s=await Ai(this.options.keyStore,a,e,t,i),c=await this.sendRelayUpload(a,s,o)),!c.ok){let d=await S(c,"invalid_operation_response","The collection authority returned an invalid file upload response.");throw P(d,"operation_failed","Encrypted file chunk upload failed.",c.status)}this.options.onRelayAvailable()}async downloadChunk(e,t,i){let o=await this.localFileToken(e,"download",i),r;if(await this.options.shouldAttemptDirect(o)){try{r=await fetch(`${this.options.loopbackUrl}/v1/files/download/${encodeURIComponent(o.grantId)}/${encodeURIComponent(e.transfer_id)}/${t}`,re({method:"GET",signal:i}))}catch(a){if(i?.aborted)throw a;this.options.onDirectUnavailable()}if(r&&!he(r.status))return r.ok&&this.options.onDirectAvailable(),this.decryptDownloadResponse(o,e,t,r);r&&this.options.onDirectUnavailable()}return r=await this.sendRelayDownload(o,e,t,i),r.status===401&&o.refreshToken&&(o=await this.options.refreshAuthorization(i),on(o),r=await this.sendRelayDownload(o,e,t,i)),r.ok&&this.options.onRelayAvailable(),this.decryptDownloadResponse(o,e,t,r)}async decryptDownloadResponse(e,t,i,o){if(!o.ok){let s=await S(o,"invalid_operation_response","The collection authority returned an invalid file download response.");throw P(s,"operation_failed","Encrypted file chunk download failed.",o.status)}if(o.headers.get("content-type")?.split(";",1)[0]!=="application/mdbase-connect-file")throw l("invalid_operation_response","The connector returned an invalid file response media type.");let r=new Uint8Array(await o.arrayBuffer()),a;try{Rr(t,i,r),a=await(await Ii(this.options.keyStore,e,t)).decryptChunk(r)}catch(s){throw s instanceof C?s:l("invalid_operation_response","The connector returned an invalid encrypted file frame.",{cause:s})}if(a.byteLength!==an(t,i))throw l("invalid_operation_response","The connector returned a truncated file chunk.");return a}encryptControl(e,t){return be(e),pe(this.options.keyStore,e.keyHandle,rn(e),"file_control",t)}sendRelayControl(e,t,i){return fetch(`${this.options.serverUrl}/v1/authorities/${encodeURIComponent(e.collectionId)}/files/control`,{method:"POST",headers:{authorization:`Bearer ${e.accessToken}`,"content-type":"application/json"},body:JSON.stringify(t),signal:i})}sendRelayUpload(e,t,i){return fetch(`${this.options.serverUrl}/v1/authorities/${encodeURIComponent(e.collectionId)}/files/upload`,{...ki(t,i),headers:{authorization:`Bearer ${e.accessToken}`,"content-type":"application/mdbase-connect-file"}})}sendRelayDownload(e,t,i,o){return fetch(`${this.options.serverUrl}/v1/authorities/${encodeURIComponent(e.collectionId)}/files/download/${encodeURIComponent(t.transfer_id)}/${i}`,{method:"GET",headers:{authorization:`Bearer ${e.accessToken}`},signal:o})}async localFileToken(e,t,i){let o=await this.options.authorizedToken(i);if(!o||o.authority||!o.fileCapability||!o.encryption||!o.grantId||!o.keyHandle||e.direction!==t||e.protection!=="grant_aead_v1")throw l("not_authorized","This connection cannot use encrypted local file delivery.");return St(e),o}};function on(n){if(n.authority||!n.fileCapability)throw l("not_authorized","This connection cannot use encrypted local file delivery.");be(n)}async function Ai(n,e,t,i,o){let r=Sr(e,t,i,o.byteLength);return(await Ii(n,e,t)).encryptChunk("upload_chunk",r,o)}function ki(n,e){return{method:"POST",headers:{"content-type":"application/mdbase-connect-file"},body:Uint8Array.from(n).buffer,signal:e}}async function wr(n,e){if(n.ok)return;let t=await S(n,"invalid_operation_response","The collection authority returned an invalid file transfer response.");throw P(t,"operation_failed",e,n.status)}async function Cr(n,e){return e.refreshToken?n.status===401?!0:n.status!==409?!1:(await S(n.clone(),"invalid_operation_response","The collection authority returned an invalid file response.").catch(()=>null))?.error?.code==="encryption_binding_stale":!1}function be(n){if(!n.encryption||!n.grantId||!n.keyHandle)throw l("missing_grant_key","Reconnect this application to restore encrypted file access.")}function rn(n){return be(n),{grantId:n.grantId,applicationId:n.clientId,encryption:n.encryption}}function Ii(n,e,t){return be(e),He.open(n,e.keyHandle,{...rn(e),authorityId:e.encryption.connector_id,transferId:t.transfer_id,direction:t.direction})}function Sr(n,e,t,i){be(n);let o=St(e),r=an(e,t);if(i!==r)throw l("invalid_request","The file chunk has the wrong byte length.");return{protocol_version:1,protection:"grant_aead_v1",grant_id:n.grantId,authority_id:n.encryption.connector_id,collection_id:n.collectionId,transfer_id:e.transfer_id,direction:e.direction,chunk_size:o,chunk_index:t,offset:t*o,plaintext_length:i,total_size:e.total_size,scope_epoch:n.encryption.scope_epoch,key_id:n.encryption.key_id}}function Rr(n,e,t){let i=Ze(t),o=an(n,e),r=St(n);if(i.kind!=="download_chunk"||i.header.chunk_index!==e||i.header.chunk_size!==r||i.header.offset!==e*r||i.header.plaintext_length!==o||i.header.total_size!==n.total_size)throw l("invalid_operation_response","The connector returned a file frame for a different chunk.")}function Pr(n){throw F(n.code==="unknown"?n.server_code:n.code,n.message,{details:n.details,operationOutcome:n.operation_outcome??"rejected",traceId:n.trace_id})}function Or(n,e,t){if(n==="GET"&&(e===""||e.startsWith("?"))){let o=new URLSearchParams(e.startsWith("?")?e.slice(1):e),r=o.get("limit");return{protocol_version:1,type:"list_files",...o.get("folder")?{folder:o.get("folder")}:{},...o.get("after")?{after:o.get("after")}:{},...r?{limit:Number(r)}:{}}}let i=e.split("/");if(n==="GET"&&i.length===2&&i[0]==="transfers")return Ti("get_file_transfer_status",i[1]);if(n==="DELETE"&&i.length===2&&i[0]==="transfers")return Ti("abort_file_transfer",i[1]);if(n==="POST"&&Ar(t)){let o=e==="uploads"?"open_file_upload":e==="downloads"?"open_file_download":i.length===3&&i[0]==="uploads"&&i[2]==="commit"?"commit_file_upload":i.length===2&&i[1]==="move"&&t.file_id===decodeURIComponent(i[0])?"move_file":i.length===2&&i[1]==="delete"&&t.file_id===decodeURIComponent(i[0])?"delete_file":null;if(o&&t.type===o)return{...t}}throw l("invalid_request","The file control request path is invalid.")}function Ti(n,e){return{protocol_version:1,type:n,transfer_id:decodeURIComponent(e)}}function St(n){if(n.strategy.kind!=="framed_chunks"||!Number.isSafeInteger(n.strategy.chunk_size)||n.strategy.chunk_size<=0)throw l("invalid_operation_response","The connector returned an invalid framed transfer strategy.");return n.strategy.chunk_size}function an(n,e){let t=St(n);if(!Number.isSafeInteger(e)||e<0||!Number.isSafeInteger(n.total_size)||n.total_size<0)throw l("invalid_request","The file chunk index is invalid.");let i=e*t;if(!Number.isSafeInteger(i)||i>=n.total_size)throw l("invalid_request","The file chunk index is outside the transfer.");return Math.min(t,n.total_size-i)}function Ar(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}var Rt=class{constructor(e){this.options=e;this.local=new Ct(e)}options;local;async control(e,t="",i,o){let r=await this.requireFileToken(o);return r.authority?Ci(r,e,t,i,o,this.options.refreshAuthorization,this.options.authorityProofHeaders):this.local.control(r,e,t,i,o)}uploadChunk(e,t,i,o){return this.local.uploadChunk(e,t,i,o)}downloadChunk(e,t,i){return this.local.downloadChunk(e,t,i)}async downloadHostedPart(e,t,i,o){let r=await this.requireFileToken(o);if(!r.authority)throw l("not_remote_authority","Hosted file delivery requires a remote authority endpoint.");return Si(r,`downloads/${encodeURIComponent(e.transfer_id)}/parts/${t}`,i,o,this.options.refreshAuthorization,this.options.authorityProofHeaders)}async requireFileToken(e){let t=await this.options.authorizedToken(e);if(!t?.fileCapability)throw l("not_authorized","This connection has no file capability.");return t}};async function $e(n,e,t,i,o,r){if(!e.authority?.proofPublicKey)return{};if(!e.keyHandle)throw l("missing_grant_key","Reconnect this application to restore remote authority request signing.");try{let a=new URL(i);return await Wt(n,e.keyHandle,e.authority.proofPublicKey,{method:t,target:`${a.pathname}${a.search}`,body:o,credential:r})}catch(a){throw a instanceof R?F(a.code,a.message):a}}var Pt=class{constructor(e,t){this.storage=e;this.baseKey=t}storage;baseKey;list(e){if(!e)return[];let t=I(this.storage.getItem(this.baseKey));if(Mi(t)&&t.collectionId===e){let o=this.key(t.requestId);this.storage.getItem(o)||this.storage.setItem(o,JSON.stringify(t)),this.storage.removeItem(this.baseKey)}let i=[];for(let o=0;o<this.storage.length;o+=1){let r=this.storage.key(o);r?.startsWith(`${this.baseKey}:`)&&i.push(r)}return i.map(o=>I(this.storage.getItem(o))).filter(o=>Mi(o)&&o.collectionId===e).sort((o,r)=>o.createdAt-r.createdAt||o.requestId.localeCompare(r.requestId))}find(e,t){return this.list(e).find(i=>i.requestId===t)??null}identifier(e){return e.mutation??G(e.operation,e.request?.input??(e.operation==="sync"?{action:"mutate"}:{}))??(e.operation==="sync"?"sync:mutate":e.operation)}store(e){this.storage.setItem(this.key(e.requestId),JSON.stringify(e))}take(e){let t=this.key(e),i=I(this.storage.getItem(t));return this.storage.removeItem(t),i}key(e){return`${this.baseKey}:${encodeURIComponent(e)}`}};function Mi(n){return!!(n&&typeof n.collectionId=="string"&&typeof n.requestId=="string"&&n.requestId.length>0&&wn(n.operation)&&typeof n.inputFingerprint=="string"&&Number.isFinite(n.createdAt)&&n.createdAt>0&&(n.envelope||n.request)&&(n.operation==="sync"||G(n.operation,n.request?.input??{})!==null))}function Ei({stored:n,collectionId:e,relayEncryption:t,invalidate:i,directCapable:o}){let r=I(n),a=s=>(i(typeof s=="string"?s:void 0),null);if(!r)return n&&a(),null;if(r.version!==1||typeof r.accessToken!="string"||r.accessToken.length===0||typeof r.clientId!="string"||r.clientId.length===0||r.collectionId!==e||typeof r.collectionName!="string"||r.collectionName.length===0||!Array.isArray(r.operations)||r.operations.some(s=>typeof s!="string")||typeof r.expiresAt!="number"||!Number.isFinite(r.expiresAt)||r.refreshToken!==void 0&&(typeof r.refreshToken!="string"||r.refreshToken.length===0)||r.refreshExpiresAt!==void 0&&(typeof r.refreshExpiresAt!="number"||!Number.isFinite(r.refreshExpiresAt))||!pt(r.scope)||r.fileCapability&&!ut(r.fileCapability)||r.authority&&!ri(r.authority,r.collectionId))return a(r.keyHandle);if(t==="required"){if(r.authority){if(!r.keyHandle||!r.authority.proofPublicKey)return a(r.keyHandle)}else if(!r.grantId||!r.keyHandle||!ai(r.encryption,r.collectionId))return a(r.keyHandle)}return r.expiresAt<=Date.now()&&(!r.refreshToken||(r.refreshExpiresAt??0)<=Date.now())?o(r)?r:(i(r.keyHandle),null):r}var Ot=class{serverUrl;storage;keyStore;directAccessMode;loopbackUrl;collectionId;internals;onChange;timeouts;pendingMutationStore;files;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.timeouts=e.timeouts,this.pendingMutationStore=new Pt(this.storage,this.internals.pendingMutationKey(this.collectionId)),this.files=new Rt({keyStore:this.keyStore,serverUrl:this.serverUrl,loopbackUrl:this.loopbackUrl,authorizedToken:t=>this.authorizedToken({signal:t,timeoutMs:null}),refreshAuthorization:t=>this.refreshAuthorization(t),shouldAttemptDirect:t=>this.shouldAttemptDirect(t),onDirectAvailable:()=>{this.markDirectAvailable(),this.setRoute("direct")},onDirectUnavailable:()=>this.markDirectUnavailable(),onRelayAvailable:()=>this.setRoute("relay"),authorityProofHeaders:(t,i,o,r,a)=>$e(this.keyStore,t,i,o,r,a)}),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(e={}){return U(e,this.timeouts.watchStartMs,t=>this.checkDirectAccessWithinBudget(t.signal))}async checkDirectAccessWithinBudget(e){let t=this.currentToken();if(!this.directEligible(t))return this.setDirectStatus("disabled");let i=await qe();return i==="denied"?this.setDirectStatus("denied"):(i==="prompt"||i===null)&&this.storage.getItem(this.internals.directPreferenceKey())!=="enabled"?this.setDirectStatus("permission_required"):this.probeDirectAccess(e)}async requestDirectAccess(e={}){return U(e,this.timeouts.watchStartMs,t=>this.requestDirectAccessWithinBudget(t.signal))}async requestDirectAccessWithinBudget(e){let t=this.currentToken();return this.directCapable(t)?(this.storage.setItem(this.internals.directPreferenceKey(),"enabled"),this.directRetryAt=0,this.probeDirectAccess(e)):this.setDirectStatus("disabled")}disableDirectAccess(){this.storage.setItem(this.internals.directPreferenceKey(),"disabled"),this.setDirectStatus("disabled"),this.setRoute("relay")}pendingMutations(){return this.storedPendingMutations().map(e=>({requestId:e.requestId,operation:this.pendingMutationStore.identifier(e),fingerprint:e.inputFingerprint,status:"outcome_unknown",createdAt:new Date(e.createdAt).toISOString()}))}pendingMutation(e){let t=this.storedPendingMutation(e);return t?{requestId:t.requestId,operation:this.pendingMutationStore.identifier(t),fingerprint:t.inputFingerprint,status:"outcome_unknown",createdAt:new Date(t.createdAt).toISOString()}:null}async recoverPendingMutation(e,t){let i=this.storedPendingMutation(e);if(!i)throw l("no_pending_mutation","There is no interrupted mutation to resume.");return B(t,this.timeouts.requestMs,o=>this.performOperationWithinBudget(i.operation,i.request?.input??{},{...t,signal:o.signal},i))}async performOperation(e,t,i={}){return B(i,this.timeouts.requestMs,o=>this.performOperationWithinBudget(e,t,{...i,signal:o.signal}))}async performOperationWithinBudget(e,t,i,o){ae(i.signal);let r=this.currentToken();if(!r)throw l("not_authorized","Connect this application before accessing a collection.");if(!r.operations.includes(e))throw l("insufficient_access",`This connection does not allow ${e}.`,{details:{required_operations:[e],granted_operations:[...r.operations],missing_operations:[e]}});let a=await this.shouldAttemptDirect(r);if(!a&&(r=await this.authorizedToken({signal:i.signal,timeoutMs:null}),!r))throw l("not_authorized","Reconnect this application to continue.");let s=o?.requestId??(Jn(e,t)?crypto.randomUUID():void 0),c;try{c=await this.sendOperation(r,e,t,a,i,s)}catch(h){throw dt(h,i.signal,s!==void 0&&this.storedPendingMutation(s)!==null?s:void 0,r.authority?"hosted_provider_unavailable":"relay_unavailable")}let d=c.response,p=d.status===409&&(await S(d.clone(),"invalid_operation_response","The collection authority returned an invalid operation response.").catch(()=>null))?.error?.code==="encryption_binding_stale";if((d.status===401||p)&&r.refreshToken){if(c.pendingMutation&&(c.directDeliveryUncertain||c.encryptedRequest&&c.resumingMutation))throw l("operation_outcome_unknown","The direct operation may have completed, but its encrypted grant changed before the response could be recovered. Refresh before making another change.",{operationOutcome:"unknown",details:{request_id:c.requestId}});c.pendingMutation&&this.clearPendingMutation(c.requestId),r=await this.refreshAuthorization(i.signal),a=await this.shouldAttemptDirect(r);try{c=await this.sendOperation(r,e,t,a,i,s)}catch(h){throw dt(h,i.signal,s!==void 0&&this.storedPendingMutation(s)!==null?s:void 0,r.authority?"hosted_provider_unavailable":"relay_unavailable")}d=c.response}let u;try{u=await S(d,"invalid_operation_response","The collection authority returned a response that is not valid JSON.")}catch(h){throw c.pendingMutation?D(c.requestId,h):l("invalid_operation_response","The collection authority returned a response that is not valid JSON.",{cause:h})}if(!d.ok){let h=P(u,"operation_failed","Collection operation failed.",d.status);throw c.pendingMutation&&(c.directDeliveryUncertain||c.encryptedRequest&&c.resumingMutation)?D(c.requestId,h):(c.pendingMutation&&!c.directDeliveryUncertain&&this.clearPendingMutation(c.requestId),h.code==="direct_operation_rejected"&&h.status===403&&this.invalidateRejectedAuthorization(r),h)}if(c.encryptedRequest){let h=u?.envelope,f=c.pendingMutationRecord,m=f?.encryption??r.encryption,y=f?.grantId??r.grantId,g=f?.applicationId??r.clientId,b=f?.keyHandle??r.keyHandle;if(!h||!m||!y||!b)throw c.pendingMutation?D(c.requestId,new Error("Encrypted operation response was missing its envelope.")):l("invalid_encrypted_response","The relay did not return an encrypted connector response.");try{let _=await xe(this.keyStore,b,{grantId:y,applicationId:g,encryption:m},c.encryptedRequest,h);if(c.pendingMutation&&this.clearPendingMutation(c.requestId),!_.ok)throw F(_.problem.code==="unknown"?_.problem.server_code:_.problem.code,_.problem.message,{details:_.problem.details,operationOutcome:_.problem.operation_outcome??"rejected",traceId:_.problem.trace_id});return _.result}catch(_){throw _ instanceof C?_:_ instanceof R?c.pendingMutation?D(c.requestId,_):F(_.code,_.message):_}}if(u?.protocol_version!==Y||u?.request_id!==c.requestId)throw c.pendingMutation?D(c.requestId,new Error("Operation response protocol or request ID did not match.")):l("invalid_operation_response","The collection authority returned a response for a different protocol request.");if(u.ok===!1)throw Ce(u.problem)?(c.pendingMutation&&this.clearPendingMutation(c.requestId),new C(u.problem)):c.pendingMutation?D(c.requestId,new Error("Operation rejection did not contain a canonical problem.")):l("invalid_operation_response","The collection authority returned an invalid operation problem.");if(u.ok!==!0||!("result"in u))throw c.pendingMutation?D(c.requestId,new Error("Successful operation response did not contain a result.")):l("invalid_operation_response","The collection authority returned an incomplete operation response.");return c.pendingMutation&&this.clearPendingMutation(c.requestId),u.result}async performAuthoritySyncRequest(e,t,i,o,r,a={}){return B(a,this.timeouts.syncMs,async s=>{let c=await this.authorizedToken({signal:s.signal,timeoutMs:null});if(!c?.authority||c.collectionId!==e||c.authority.replicaId!==t)throw l("authority_authorization_changed","Reconnect this collection authority before synchronizing.");try{let d=await this.sendAuthoritySyncRequest(c,i,o,r,s.signal);if(d.status===401&&c.refreshToken){if(c=await this.refreshAuthorization(s.signal),!c.authority||c.collectionId!==e||c.authority.replicaId!==t)throw l("authority_authorization_changed","Reconnect this collection authority before synchronizing.");d=await this.sendAuthoritySyncRequest(c,i,o,r,s.signal)}let p=await S(d,"invalid_operation_response","The collection authority returned an invalid synchronization response.");if(!d.ok)throw P(p,"sync_failed","Collection synchronization failed.",d.status);return p}catch(d){let p=i==="POST"&&o==="mutations"&&r&&typeof r=="object"&&typeof r.mutation_id=="string"?r.mutation_id:void 0;throw dt(d,s.signal,p,"hosted_provider_unavailable")}})}async sendAuthoritySyncRequest(e,t,i,o,r){if(!e.authority)throw l("not_remote_authority","This authorization has no remote authority endpoint.");let a=`${e.authority.syncUrl}/${i}`,s=o===void 0?void 0:JSON.stringify(o),c=await $e(this.keyStore,e,t,a,s,e.authority.accessToken);return fetch(a,{method:t,headers:{authorization:`Bearer ${e.authority.accessToken}`,...o===void 0?{}:{"content-type":"application/json"},...c},...s===void 0?{}:{body:s},signal:r})}async sendOperation(e,t,i,o,r={},a){let s=i??{},c,d=!1,p=!1,u=a??crypto.randomUUID(),h=null,f;if(a!==void 0){if(h=this.storedPendingMutation(a),f=h?.inputFingerprint??await ti(t,i),h){if(h.collectionId!==e.collectionId||h.operation!==t||h.inputFingerprint!==f)throw l("pending_mutation_unresolved","A previous write still has an unknown outcome. Retry that exact write before making another change.");u=h.requestId,p=!0}d=!0}let m=h?.mutation??G(t,i);if(h?.envelope&&(e.authority||!e.encryption))throw l("pending_mutation_unresolved","The pending write requires its encrypted relay authority. Reconnect that authority before recovery.");if(h?.request&&e.encryption&&!e.authority)throw l("pending_mutation_unresolved","The pending write belongs to a different authority transport. Reconnect that authority before recovery.");if(e.encryption&&!e.authority){if(!e.grantId||!e.keyHandle)throw l("missing_grant_key","Reconnect this application to restore encrypted access.");try{if(d)if(h){if(!h.envelope)throw l("pending_mutation_unresolved","The pending write belongs to a different transport. Reconnect before retrying it.");c=h.envelope}else c=await pe(this.keyStore,e.keyHandle,{grantId:e.grantId,applicationId:e.clientId,encryption:e.encryption},t,i,u),this.pendingMutationStore.store({collectionId:e.collectionId,...e.grantId?{grantId:e.grantId}:{},keyId:e.encryption.key_id,keyHandle:e.keyHandle,applicationId:e.clientId,encryption:e.encryption,operation:t,mutation:m,inputFingerprint:f,requestId:u,envelope:c,createdAt:Date.now()});else c=await pe(this.keyStore,e.keyHandle,{grantId:e.grantId,applicationId:e.clientId,encryption:e.encryption},t,i)}catch(O){throw O instanceof R?F(O.code,O.message):O}s=c}else{let O=h?.request??{protocol_version:Y,request_id:u,input:s};s=O,d&&!h&&this.pendingMutationStore.store({collectionId:e.collectionId,...e.grantId?{grantId:e.grantId}:{},operation:t,mutation:m,inputFingerprint:f,requestId:u,request:O,createdAt:Date.now()})}if(o&&c&&!e.authority){let O=!1;try{let v=await fetch(`${this.loopbackUrl}/v1/operations`,re({method:"POST",headers:{"content-type":"application/mdbase-connect+json"},body:JSON.stringify(c),signal:r.signal}));if(!he(v.status))return v.ok&&(this.markDirectAvailable(),this.setRoute("direct")),{response:v,requestId:u,encryptedRequest:c,pendingMutation:d,...d?{pendingMutationRecord:h??this.storedPendingMutation(u)??void 0}:{},resumingMutation:p};O=v.status>=500,this.markDirectUnavailable()}catch(v){if(r.signal?.aborted)throw v;O=!0,await qe()==="denied"?this.setDirectStatus("denied"):this.markDirectUnavailable()}let z;try{z=e.expiresAt>Date.now()+3e4?e:await this.refreshAuthorization(r.signal)}catch(v){throw d&&(O||p)?D(u,v):v}let E;try{E=await fetch(`${this.serverUrl}/v1/authorities/${encodeURIComponent(z.collectionId)}/operations/${t}`,{method:"POST",headers:{authorization:`Bearer ${z.accessToken}`,"content-type":"application/json"},body:JSON.stringify(c),signal:r.signal})}catch(v){throw d&&(O||p)?D(u,v):v}return E.ok&&this.setRoute("relay"),{response:E,requestId:u,encryptedRequest:c,directDeliveryUncertain:O,pendingMutation:d,...d?{pendingMutationRecord:h??this.storedPendingMutation(u)??void 0}:{},resumingMutation:p}}let y=e.authority?`${e.authority.operationsUrl}/${t}`:`${this.serverUrl}/v1/authorities/${encodeURIComponent(e.collectionId)}/operations/${t}`,g=JSON.stringify(s),b=e.authority?await $e(this.keyStore,e,"POST",y,g,e.authority.accessToken):{},_=await fetch(y,{method:"POST",headers:{authorization:`Bearer ${e.authority?.accessToken??e.accessToken}`,"content-type":"application/json",...b},body:g,signal:r.signal});return _.ok&&this.setRoute(e.authority?"remote":"relay"),{response:_,requestId:u,encryptedRequest:c,pendingMutation:d,...d?{pendingMutationRecord:h??this.storedPendingMutation(u)??void 0}:{},resumingMutation:p}}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.internals.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 qe();return t==="denied"?(this.setDirectStatus("denied"),!1):(t==="prompt"||t===null)&&this.storage.getItem(this.internals.directPreferenceKey())!=="enabled"?(this.setDirectStatus("permission_required"),!1):(this.setDirectStatus("checking"),!0)}async probeDirectAccess(e){this.setDirectStatus("checking");try{let t=await fetch(`${this.loopbackUrl}/v1/ready`,re({method:"GET",cache:"no-store",signal:e})),i=await S(t,"invalid_operation_response","The connector returned an invalid readiness response.").catch(()=>null);if(t.ok&&i?.service==="mdbase-connect"&&i?.loopback_protocol_version===1&&i?.operation_transport_protocol_version===Y)return this.markDirectAvailable(),"available"}catch{}return await qe()==="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=I(this.storage.getItem(this.internals.tokenKey(this.collectionId)));!t||!Wn(t,e)||(this.internals.removeToken(this.collectionId,t.keyHandle),this.currentRoute="relay",this.directStatus=this.directAccessMode==="disabled"?"disabled":"unavailable",this.emitConnection())}currentToken(){return Ei({stored:this.storage.getItem(this.internals.tokenKey(this.collectionId)),collectionId:this.collectionId,relayEncryption:this.internals.relayEncryption,invalidate:e=>this.internals.removeToken(this.collectionId,e,"invalid_stored_grant"),directCapable:e=>this.directCapable(e)})}async authorizedToken(e={}){let t=this.currentToken();if(!t)return null;if(t.expiresAt>Date.now()+3e4)return t;if(!t.refreshToken||(t.refreshExpiresAt??0)<=Date.now()){if(this.directCapable(t))throw l("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,t.keyHandle),null}return this.refreshAuthorization(e.signal)}refreshAuthorization(e){return this.refreshPromise?this.refreshPromise:(this.refreshPromise=this.performRefresh(e).finally(()=>{this.refreshPromise=null}),this.refreshPromise)}async performRefresh(e){let t=this.currentToken();if(!t?.refreshToken)throw l("not_authorized","Reconnect this application to continue.");if((t.refreshExpiresAt??0)<=Date.now())throw l("relay_authorization_expired","Direct access is still available on this computer, but using the relay requires reconnecting this application.");let i=t.refreshToken,o=`${this.serverUrl}/oauth/token`,r=new URLSearchParams({grant_type:"refresh_token",refresh_token:t.refreshToken,client_id:t.clientId}).toString(),a=t.authority?await $e(this.keyStore,t,"POST",o,r,t.refreshToken):{},s=await fetch(o,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",...a},body:r,signal:e}),c=await S(s,"invalid_token_response","The authorization service returned an invalid token response.");if(!s.ok){let d=this.currentToken();if(d?.refreshToken&&d.refreshToken!==i)return d;throw this.directCapable(t)||this.internals.removeToken(this.collectionId,t.keyHandle),(ze(c)??c?.error?.code)==="invalid_grant"?l("authorization_expired",c?.error_description??c?.error?.message??"Reconnect this application to continue.",{status:s.status}):P(c,"authorization_expired","Reconnect this application to continue.",s.status)}return this.storeTokenResponse(c,t.clientId,t.keyHandle)}storeTokenResponse(e,t,i){if(e.collection_id!==this.collectionId)throw l("collection_mismatch","The refreshed authorization belongs to a different collection.");let o=this.internals.storeTokenResponse(e,t,i);return this.currentRoute=o.authority?"remote":"relay",this.directStatus=o.authority||this.directAccessMode==="disabled"?"disabled":"unavailable",this.emitConnection(),o}storedPendingMutations(){return this.pendingMutationStore.list(this.currentToken()?.collectionId??null)}storedPendingMutation(e){return this.pendingMutationStore.find(this.currentToken()?.collectionId??null,e)}clearPendingMutation(e){let t=this.pendingMutationStore.take(e),i=this.currentToken()?.keyHandle;t?.keyHandle&&t.keyHandle!==i&&this.keyStore.delete(t.keyHandle).catch(()=>{})}};var kr=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Tr=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ce=class{state=Tr.slice();block=new Uint8Array(64);words=new Uint32Array(64);blockLength=0;byteLength=0;finished=!1;update(e){if(this.finished)throw new Error("SHA-256 digest is already finalized.");if(this.byteLength+=e.byteLength,!Number.isSafeInteger(this.byteLength))throw new Error("SHA-256 input exceeds the safe browser byte range.");let t=0;if(this.blockLength>0){let i=Math.min(64-this.blockLength,e.byteLength);this.block.set(e.subarray(0,i),this.blockLength),this.blockLength+=i,t+=i,this.blockLength===64&&(this.compress(this.block),this.blockLength=0)}for(;t+64<=e.byteLength;)this.compress(e.subarray(t,t+64)),t+=64;return t<e.byteLength&&(this.block.set(e.subarray(t),0),this.blockLength=e.byteLength-t),this}digestHex(){if(this.finished)throw new Error("SHA-256 digest is already finalized.");this.finished=!0,this.block[this.blockLength]=128,this.block.fill(0,this.blockLength+1),this.blockLength>=56&&(this.compress(this.block),this.block.fill(0));let e=this.byteLength*8,t=Math.floor(e/4294967296),i=e>>>0;return xi(this.block,56,t),xi(this.block,60,i),this.compress(this.block),[...this.state].map(o=>o.toString(16).padStart(8,"0")).join("")}compress(e){let t=this.words;for(let u=0;u<16;u+=1){let h=u*4;t[u]=(e[h]<<24|e[h+1]<<16|e[h+2]<<8|e[h+3])>>>0}for(let u=16;u<64;u+=1){let h=t[u-15],f=t[u-2],m=j(h,7)^j(h,18)^h>>>3,y=j(f,17)^j(f,19)^f>>>10;t[u]=t[u-16]+m+t[u-7]+y>>>0}let i=this.state[0],o=this.state[1],r=this.state[2],a=this.state[3],s=this.state[4],c=this.state[5],d=this.state[6],p=this.state[7];for(let u=0;u<64;u+=1){let h=j(s,6)^j(s,11)^j(s,25),f=s&c^~s&d,m=p+h+f+kr[u]+t[u]>>>0,y=j(i,2)^j(i,13)^j(i,22),g=i&o^i&r^o&r,b=y+g>>>0;p=d,d=c,c=s,s=a+m>>>0,a=r,r=o,o=i,i=m+b>>>0}this.state[0]=this.state[0]+i>>>0,this.state[1]=this.state[1]+o>>>0,this.state[2]=this.state[2]+r>>>0,this.state[3]=this.state[3]+a>>>0,this.state[4]=this.state[4]+s>>>0,this.state[5]=this.state[5]+c>>>0,this.state[6]=this.state[6]+d>>>0,this.state[7]=this.state[7]+p>>>0}};function j(n,e){return n>>>e|n<<32-e}function xi(n,e,t){n[e]=t>>>24,n[e+1]=t>>>16,n[e+2]=t>>>8,n[e+3]=t}var At=class{constructor(e,t){this.signal=t;this.iterator=Ir(e)}signal;iterator;remainder=new Uint8Array;remainderOffset=0;maxSourceChunkBytes=null;iteratorClosing=!1;ended=!1;setMaxSourceChunkBytes(e){this.maxSourceChunkBytes=e}async read(e){let t=new Uint8Array(e),i=0;for(;i<e;){if(this.remainderOffset===this.remainder.byteLength){let r=await this.nextSourceChunk();if(r.done)throw this.ended=!0,l("invalid_request","Streamed file bytes ended before the declared size.");if(!(r.value instanceof Uint8Array))throw l("invalid_request","A streamed file chunk was not a Uint8Array.");if(this.maxSourceChunkBytes===null)throw new Error("Stream source was read before upload negotiation completed.");if(r.value.byteLength>this.maxSourceChunkBytes)throw l("invalid_request",`A streamed file chunk exceeded the negotiated ${this.maxSourceChunkBytes}-byte upload part size.`);if(this.remainder=r.value,this.remainderOffset=0,this.remainder.byteLength===0)continue}let o=Math.min(e-i,this.remainder.byteLength-this.remainderOffset);t.set(this.remainder.subarray(this.remainderOffset,this.remainderOffset+o),i),i+=o,this.remainderOffset+=o}return t}async expectEnd(){if(this.remainderOffset<this.remainder.byteLength)throw l("invalid_request","Streamed file bytes exceed the declared size.");for(;!this.ended;){let e=await this.nextSourceChunk();if(e.done){this.ended=!0;return}if(!(e.value instanceof Uint8Array))throw l("invalid_request","A streamed file chunk was not a Uint8Array.");if(e.value.byteLength>0)throw l("invalid_request","Streamed file bytes exceed the declared size.")}}async close(){this.ended=!0,this.closeIterator()}async nextSourceChunk(){qi(this.signal);let e=this.iterator.next(),t=this.signal;if(!t)return e;let i=()=>{},o=new Promise((r,a)=>{let s=()=>{this.closeIterator(),a(Ui(t))};t.addEventListener("abort",s,{once:!0}),i=()=>t.removeEventListener("abort",s),t.aborted&&s()});try{let r=await Promise.race([e,o]);return qi(t),r}finally{i()}}closeIterator(){if(!this.iteratorClosing){this.iteratorClosing=!0;try{this.iterator.return?.()?.catch(()=>{})}catch{}}}};function Ir(n){if(typeof n.getReader=="function"){let t=n.getReader(),i=!1,o=()=>{i||(i=!0,t.releaseLock())};return{async next(){if(i)return{done:!0,value:void 0};let r=await t.read();return r.done&&o(),r},async return(){if(!i)try{await t.cancel()}finally{o()}return{done:!0,value:void 0}}}}let e=n;if(typeof e[Symbol.asyncIterator]!="function")throw l("invalid_request","Streamed files require a readable byte stream.");return e[Symbol.asyncIterator]()}function qi(n){if(n?.aborted)throw Ui(n)}function Ui(n){return l("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:n?.reason})}var zi=1024*1024,Mr=4,Fi=8,le=3,sn=64*1024*1024,Di=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Ni=/^sha256:[0-9a-f]{64}$/u;async function Li(n,e,t){let i=new ce;for(let o=0;o<n.size;o+=zi){Z(e);let r=new Uint8Array(await n.slice(o,o+zi).arrayBuffer());i.update(r),t(Math.min(n.size,o+r.byteLength))}return n.size===0&&t(0),i.digestHex()}function Bi(n,e){if(n instanceof Blob)return e&&e!==n.type?n.slice(0,n.size,e):n;if(n instanceof ArrayBuffer)return new Blob([n],{type:e});let t=new Uint8Array(n.byteLength);return t.set(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)),new Blob([t.buffer],{type:e})}function Ki(n){return n instanceof Blob?n.size:n.byteLength}async function ji(n){return n instanceof Blob?new Uint8Array(await n.arrayBuffer()):n}function cn(n=Mr){if(!Number.isInteger(n)||n<1||n>Fi)throw l("invalid_request",`File concurrency must be between 1 and ${Fi}.`);return n}function Hi(n){if(!Number.isInteger(n)||n<1||n>1e3)throw l("invalid_request","File page size must be between 1 and 1000.");return n}function ln(n,e,t){if(n.protocol_version!==1||n.type!=="file_transfer"||n.transfer_id!==e||n.direction!==t||!Number.isSafeInteger(n.total_size)||n.total_size<0||!Array.isArray(n.received)||!Er(n))throw l("invalid_operation_response","The authority returned an invalid file transfer session.");let i=n.strategy.kind==="framed_chunks"?n.strategy.chunk_size:n.strategy.kind==="object_put"?Math.max(1,n.total_size):n.strategy.part_size,o=n.strategy.kind==="object_put"?1:Math.ceil(n.total_size/i);if(new Set(n.received).size!==n.received.length||n.received.some(a=>!Number.isSafeInteger(a)||a<0||a>=o))throw l("invalid_operation_response","The authority returned invalid transfer progress.");let r=n.uploaded_parts??[];if(!Array.isArray(r)||r.some((a,s)=>!Number.isSafeInteger(a?.part_number)||a.part_number<1||a.part_number>o||typeof a.etag!="string"||a.etag.length===0||a.etag.length>255||s>0&&r[s-1].part_number>=a.part_number)||(n.strategy.kind==="object_multipart"?r.length!==n.received.length||r.some((a,s)=>a.part_number-1!==n.received[s]):r.length!==0))throw l("invalid_operation_response","The authority returned invalid uploaded part receipts.")}function Er(n){return n.strategy.kind==="framed_chunks"?n.protection==="grant_aead_v1"&&Number.isSafeInteger(n.strategy.chunk_size)&&n.strategy.chunk_size>0:n.protection!=="transport_tls"?!1:n.strategy.kind==="object_put"?!0:Number.isSafeInteger(n.strategy.part_size)&&n.strategy.part_size>0}function $i(n,e,t){return Math.min(e,Math.max(0,n-t*e))}async function kt(n,e){for(let t=1;t<=le;t+=1){Z(e);try{return await n()}catch(i){if(e?.aborted||t===le)throw i}}throw new Error("Unreachable file chunk retry state.")}function Vi(n,e,t,i,o,r){let a;try{a=new URL(n.url)}catch{throw l("invalid_operation_response","The authority returned an invalid object URL.")}if(n.protocol_version!==1||n.type!=="file_part"||n.transfer_id!==e||n.part_index!==t||n.offset!==i||n.content_length!==o||n.method.toUpperCase()!==r||a.protocol!=="https:"&&!(a.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(a.hostname))||a.username||a.password)throw l("invalid_operation_response","The authority returned an invalid prepared file part.")}function Gi(n){let e=new Headers;for(let[t,i]of Object.entries(n))["host","content-length"].includes(t.toLowerCase())||e.set(t,i);return e}async function Yi(n,e,t){let i=new Array(n),o=0;return await Promise.all(Array.from({length:Math.min(n,e)},async()=>{for(;o<n;){let r=o;o+=1,i[r]=await t(r)}})),i}function Z(n){if(n?.aborted)throw l("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:n.reason})}function ve(n){return n instanceof C?n:typeof DOMException<"u"&&n instanceof DOMException&&n.name==="AbortError"?l("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:n}):l("temporarily_unavailable","The file transfer could not be completed.",{cause:n})}var Ve=class{constructor(e,t,i,o,r=ue()){this.capability=e;this.request=t;this.framed=i;this.hosted=o;this.timeouts=r}capability;request;framed;hosted;timeouts;async*list(e={}){let t=ct(e,this.timeouts.requestMs),i=t.signal;try{this.requireAction("list");let o;do{Z(i);let r=new URLSearchParams({protocol_version:String(1),...e.folder?{folder:e.folder}:{},...o?{after:o}:{},...e.pageSize?{limit:String(Hi(e.pageSize))}:{}}),a=await this.request("GET",`?${r.toString()}`,void 0,i);if(a.protocol_version!==1||a.type!=="files_page"||!Array.isArray(a.files))throw l("invalid_operation_response","The authority returned an invalid file page.");for(let s of a.files)Z(i),yield s;o=a.next}while(o)}finally{t.dispose()}}async upload(e,t,i={}){return B(i,this.timeouts.uploadMs,o=>this.uploadWithinBudget(e,t,{...i,signal:o.signal,timeoutMs:null}))}async uploadWithinBudget(e,t,i){this.requireAction(i.ifRevision?"replace":"add");let o=Bi(t,i.mediaType),r=cn(i.concurrency),a=await Li(o,i.signal,s=>{i.onProgress?.({phase:"hashing",transferredBytes:s,totalBytes:o.size})});return this.uploadKnownSource(e,o.size,`sha256:${a}`,(i.mediaType??o.type)||void 0,i,r,async(s,c,d)=>o.slice(c,c+d))}async uploadStream(e,t,i={}){return B(i,this.timeouts.uploadMs,o=>this.uploadStreamWithinBudget(e,t,{...i,signal:o.signal,timeoutMs:null}))}async uploadStreamWithinBudget(e,t,i){if(this.requireAction(i.ifRevision?"replace":"add"),!Number.isSafeInteger(t.size)||t.size<0)throw l("invalid_request","Streamed file size must be a non-negative safe integer.");if(!Ni.test(t.contentDigest))throw l("invalid_request","Streamed files require a lowercase SHA-256 content digest.");let o=new At(t.stream,i.signal),r=new ce;return this.uploadKnownSource(e,t.size,t.contentDigest,i.mediaType??t.mediaType,i,1,async(a,s,c)=>{let d=await o.read(c);return r.update(d),d},async()=>{if(await o.expectEnd(),`sha256:${r.digestHex()}`!==t.contentDigest)throw l("invalid_request","Streamed file bytes do not match the declared SHA-256 digest.")},()=>o.close(),a=>o.setMaxSourceChunkBytes(a))}async uploadKnownSource(e,t,i,o,r,a,s,c,d,p){let u=r.transferId??crypto.randomUUID();if(!Di.test(u))throw l("invalid_request","File transfer ID must be a UUID.");let h=!1;try{let f=await this.request("POST","uploads",{protocol_version:1,type:"open_file_upload",transfer_id:u,path:e,size:t,content_digest:i,...o?{media_type:o}:{},...r.ifRevision?{if_revision:r.ifRevision}:{}},r.signal);if(ln(f,u,"upload"),f.total_size!==t||f.strategy.kind==="object_ranges")throw l("invalid_operation_response","The authority returned an incompatible upload strategy.");let m=f.strategy.kind==="framed_chunks";if(m&&!this.framed)throw l("invalid_operation_response","Encrypted file chunk delivery is unavailable.");let y=f.strategy.kind==="object_put"?Math.max(1,t):f.strategy.kind==="framed_chunks"?f.strategy.chunk_size:f.strategy.part_size,g=f.strategy.kind==="object_put"?1:Math.ceil(t/y);if(p?.(y),!m&&f.received.length===g){let v=await this.tryReplayUploadCommit(u,f.strategy.kind==="object_multipart"?f.uploaded_parts:void 0,r.signal);if(v)return h=!0,v.file}let b=new Set(f.received),_=new Map((f.uploaded_parts??[]).map(v=>[v.part_number-1,v])),O=[...b].reduce((v,we)=>v+$i(t,y,we),0),z=await Yi(g,a,async v=>{let we=v*y,Je=Math.min(y,Math.max(0,t-we)),Mt=await s(v,we,Je);if(Ki(Mt)!==Je)throw l("invalid_request","Streamed file bytes ended before the declared size.");if(b.has(v))return _.get(v)??null;let Qi=m?await kt(async()=>this.framed.uploadChunk(f,v,await ji(Mt),r.signal),r.signal).then(()=>null):await this.uploadPart(u,v,we,Mt,Je,f.strategy.kind==="object_multipart",r.signal);return O+=Je,r.onProgress?.({phase:"uploading",transferredBytes:O,totalBytes:t}),Qi});await c?.();let E=await this.commitUpload(u,f.strategy.kind==="object_multipart"?z.filter(v=>v!==null):void 0,r.signal);if(E.protocol_version!==1||E.type!=="file_upload_committed"||E.transfer_id!==u||E.file.path!==e||E.file.size!==t||E.file.content_digest!==i)throw l("invalid_operation_response","The authority returned an invalid file receipt.");return h=!0,E.file}catch(f){throw ve(f)}finally{await d?.().catch(()=>{}),!h&&r.transferId===void 0&&await this.abort(u)}}async download(e,t={}){if(e.size>sn)throw l("invalid_request",`download() buffers at most ${sn} bytes; use downloadStream() for larger files.`);let i=await this.downloadStream(e,t),o=[],r=i.getReader();for(;;){let a=await r.read();if(a.done)break;o.push(a.value)}return new Blob(o.map(a=>{let s=new Uint8Array(a.byteLength);return s.set(a),s.buffer}),{type:e.media_type??""})}async downloadStream(e,t={}){return B(t,this.timeouts.requestMs,i=>this.openDownloadStream(e,t,i.signal))}async openDownloadStream(e,t,i){this.requireAction("read"),cn(t.concurrency);let o=crypto.randomUUID(),r;try{if(r=await this.request("POST","downloads",{protocol_version:1,type:"open_file_download",transfer_id:o,file_id:e.file_id,revision:e.revision},i),ln(r,o,"download"),r.total_size!==e.size||r.strategy.kind!=="object_ranges"&&r.strategy.kind!=="framed_chunks")throw l("invalid_operation_response","The authority returned an incompatible download session.");if(r.strategy.kind==="framed_chunks"&&!this.framed)throw l("invalid_operation_response","Encrypted file chunk delivery is unavailable.");if(r.strategy.kind==="object_ranges"&&e.size>0&&!this.hosted)throw l("invalid_operation_response","Authenticated hosted file delivery is unavailable.")}catch(g){throw await this.abort(o),ve(g)}let a=r.strategy.kind==="framed_chunks"?r.strategy.chunk_size:r.strategy.part_size,s=Math.ceil(e.size/a),c=new ce,d=0,p=0,u=null,h=0,f=!1,m=async()=>{f||(f=!0,await u?.cancel().catch(()=>{}),u=null,await this.abort(o))},y=()=>{if(h!==e.size||`sha256:${c.digestHex()}`!==e.content_digest)throw l("invalid_operation_response","Downloaded file bytes failed integrity verification.")};return new ReadableStream({pull:async g=>{try{if(Z(t.signal),r.strategy.kind==="object_ranges")for(;;){if(!u){if(d>=s){y(),await m(),g.close();return}let E=d*a;p=Math.min(a,e.size-E),u=(await kt(()=>this.hosted.downloadPart(r,d,p,t.signal),t.signal)).getReader()}let z=await u.read();if(z.done){if(u.releaseLock(),u=null,p!==0)throw l("invalid_operation_response","A hosted file range ended before its declared byte length.");d+=1;continue}if(!(z.value instanceof Uint8Array))throw l("invalid_operation_response","A hosted file range returned a non-byte chunk.");if(z.value.byteLength!==0){if(z.value.byteLength>p)throw l("invalid_operation_response","A hosted file range exceeded its declared byte length.");p-=z.value.byteLength,c.update(z.value),h+=z.value.byteLength,t.onProgress?.({phase:"downloading",transferredBytes:h,totalBytes:e.size}),g.enqueue(z.value);return}}if(d>=s){y(),await m(),g.close();return}let b=d*a,_=Math.min(a,e.size-b),O=await kt(()=>this.framed.downloadChunk(r,d,t.signal),t.signal);if(O.byteLength!==_)throw l("invalid_operation_response","A file chunk had the wrong byte length.");c.update(O),h+=O.byteLength,d+=1,t.onProgress?.({phase:"downloading",transferredBytes:h,totalBytes:e.size}),d===s&&y(),g.enqueue(O),d===s&&(await m(),g.close())}catch(b){await m(),g.error(ve(b))}},cancel:m})}async downloadBytes(e,t={}){return new Uint8Array(await(await this.download(e,t)).arrayBuffer())}async move(e,t,i={}){return B(i,this.timeouts.requestMs,o=>this.moveWithinBudget(e,t,{...i,signal:o.signal,timeoutMs:null}))}async moveWithinBudget(e,t,i){this.requireAction("move");let o=i.mutationId??crypto.randomUUID(),r;try{r=await this.request("POST",`${encodeURIComponent(e.file_id)}/move`,{protocol_version:1,type:"move_file",mutation_id:o,file_id:e.file_id,if_revision:i.ifRevision??e.revision,from_path:e.path,path:t,update_references:!1},i.signal)}catch(a){throw ve(a)}if(r.protocol_version!==1||r.type!=="file_moved"||r.mutation_id!==o||r.file.file_id!==e.file_id||r.file.path!==t)throw l("invalid_operation_response","The authority returned an invalid file move receipt.");return r.file}async delete(e,t={}){return B(t,this.timeouts.requestMs,i=>this.deleteWithinBudget(e,{...t,signal:i.signal,timeoutMs:null}))}async deleteWithinBudget(e,t){this.requireAction("delete");let i=t.mutationId??crypto.randomUUID(),o;try{o=await this.request("POST",`${encodeURIComponent(e.file_id)}/delete`,{protocol_version:1,type:"delete_file",mutation_id:i,file_id:e.file_id,if_revision:t.ifRevision??e.revision,path:e.path},t.signal)}catch(r){throw ve(r)}if(o.protocol_version!==1||o.type!=="file_deleted"||o.mutation_id!==i||o.file_id!==e.file_id||o.previous_path!==e.path)throw l("invalid_operation_response","The authority returned an invalid file delete receipt.");return o}async uploadPart(e,t,i,o,r,a,s){for(let c=1;c<=le;c+=1){Z(s);try{let d=await this.request("POST",`uploads/${encodeURIComponent(e)}/parts`,{protocol_version:1,type:"prepare_file_upload_part",transfer_id:e,part_number:t+1,content_length:r},s);Vi(d,e,t,i,r,"PUT");let p=await fetch(d.url,{method:d.method,headers:Gi(d.headers),body:o,redirect:"error",signal:s});if(!p.ok)throw new Error(`Object upload failed with HTTP ${p.status}.`);let u=p.headers.get("etag");if(a&&!u)throw new Error("Multipart object upload did not return an ETag.");return{part_number:t+1,etag:u??""}}catch(d){if(s?.aborted||c===le)throw d}}throw new Error("Unreachable upload retry state.")}async tryReplayUploadCommit(e,t,i){try{return await this.commitUpload(e,t,i)}catch(o){if(o instanceof C&&o.code==="file_upload_incomplete")return null;throw o}}async commitUpload(e,t,i){let o;for(let r=1;r<=le;r+=1){Z(i);try{return await this.request("POST",`uploads/${encodeURIComponent(e)}/commit`,{protocol_version:1,type:"commit_file_upload",transfer_id:e,...t===void 0?{}:{parts:t}},i)}catch(a){if(o=a,i?.aborted||a instanceof C||r===le)throw a}}throw o}requireAction(e){if(!this.capability()?.actions.includes(e))throw l("not_authorized",`This connection is not authorized to ${e} files.`)}async abort(e){await this.request("DELETE",`transfers/${encodeURIComponent(e)}`).catch(()=>{})}};var Ge=class{constructor(e,t){this.internals=e;this.collectionId=t;this.transport=new Ot({serverUrl:e.serverUrl,storage:e.storage,keyStore:e.keyStore,directAccessMode:e.directAccessMode,loopbackUrl:e.loopbackUrl,collectionId:t,internals:e,timeouts:e.timeouts,onChange:()=>this.emitConnection()}),this.files=new Ve(()=>this.fileCapability,(i,o,r,a)=>this.transport.files.control(i,o,r,a),{uploadChunk:(i,o,r,a)=>this.transport.files.uploadChunk(i,o,r,a),downloadChunk:(i,o,r)=>this.transport.files.downloadChunk(i,o,r)},{downloadPart:(i,o,r,a)=>this.transport.files.downloadHostedPart(i,o,r,a)},e.timeouts),this.collectionClient=new ge({operation:(i,o,r)=>this.transport.performOperation(i,o,r)}),this.notifications=new _t({serverUrl:e.serverUrl,storage:e.storage,authorizedToken:i=>this.transport.authorizedToken({signal:i,timeoutMs:null}),register:i=>this.internals.register({signal:i,timeoutMs:null}),notificationKey:i=>e.notificationKey(t,i),requestTimeoutMs:e.timeouts.requestMs})}internals;collectionId;collectionClient;notifications;transport;files;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(){return this.transport.currentToken()?.scope??null}get fileCapability(){return this.transport.currentToken()?.fileCapability??null}get directAccess(){return this.transport.directAccess}get route(){return this.transport.route}register(e){return k(()=>this.internals.register(e),J)}info(){let e=this.transport.currentToken();return e?{collectionId:e.collectionId,displayName:e.collectionName,operations:[...e.operations],scope:e.scope,...e.fileCapability?{fileCapability:e.fileCapability}:{},authority:e.authority?{kind:"hosted",durability:"provider"}:{kind:"connector",durability:"computer"},route:this.transport.route,directAccess:this.transport.directAccess}:null}authorizationCapabilities(e=se){let t=this.operations,i=K(e).filter(o=>!t.includes(o));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 k(()=>this.internals.authorize({...e,target:{kind:"collection",collectionId:this.collectionId}}),ie)}async requestOperations(e,t={}){let i=this.authorizationCapabilities(e);return i.sufficient?M({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(e){return k(()=>this.transport.checkDirectAccess(e),at)}requestDirectAccess(e){return k(()=>this.transport.requestDirectAccess(e),at)}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 o=e.grantId;return{collectionId:t,replicaId:o,transport:{openSession:r=>this.transport.performOperation("sync",{action:"open_session"},Tt(r,this.internals.timeouts.syncMs)),snapshot:(r,a,s)=>this.transport.performOperation("sync",{action:"snapshot",snapshot_id:r,...a?{page:a}:{}},Tt(s,this.internals.timeouts.syncMs)),changes:(r,a=200,s)=>this.transport.performOperation("sync",{action:"changes",after:r,limit:a},Tt(s,this.internals.timeouts.syncMs)),mutate:(r,a)=>this.transport.performOperation("sync",{action:"mutate",mutation:r},Tt(a,this.internals.timeouts.syncMs))}}}let i=e.authority.replicaId;return{collectionId:t,replicaId:i,transport:{openSession:o=>this.transport.performAuthoritySyncRequest(t,i,"POST","sessions",void 0,o),snapshot:(o,r,a)=>{let s=new URLSearchParams({snapshot_id:o});return r&&s.set("page",r),this.transport.performAuthoritySyncRequest(t,i,"GET",`snapshot?${s}`,void 0,a)},changes:(o,r=200,a)=>this.transport.performAuthoritySyncRequest(t,i,"GET",`changes?${new URLSearchParams({after:String(o),limit:String(r)})}`,void 0,a),mutate:(o,r)=>this.transport.performAuthoritySyncRequest(t,i,"POST","mutations",o,r)}}}registerNotifications(e){return k(()=>this.notifications.registerNotifications(e),de)}registerNativeNotifications(e){return k(()=>this.notifications.registerNativeNotifications(e),de)}unregisterNativeNotifications(e){return k(()=>this.notifications.unregisterNativeNotifications(e),de)}unregisterNotifications(e,t){return k(()=>this.notifications.unregisterNotifications(e,t),de)}forget(){let e=this.transport.currentToken();this.internals.removeToken(this.collectionId,e?.keyHandle,"not_authorized",!0),this.transport.notifyStorageChanged()}describe(e){return this.collectionClient.describe(e)}changes(e={},t){return this.collectionClient.changes(e,t)}read(e,t){return this.collectionClient.read(e,t)}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(e){return this.collectionClient.listViews(e)}executeView(e,t){return this.collectionClient.executeView(e,t)}readViewSource(e,t){return this.collectionClient.readViewSource(e,t)}createViewSource(e,t){return this.collectionClient.createViewSource(e,t)}updateViewSource(e,t){return this.collectionClient.updateViewSource(e,t)}deleteViewSource(e,t){return this.collectionClient.deleteViewSource(e,t)}create(e,t){return this.collectionClient.create(e,t)}update(e,t){return this.collectionClient.update(e,t)}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(),o=!1,r,a=(s,c,d=0)=>{t.onProgress?.({operation:"rename",state:s,elapsedMs:Date.now()-i,cancellable:c,resumed:o,completedUnits:d,...r?{estimate:r}:{}})};try{ae(t.signal),a("preflighting",!0);let s=t.preflight?M(t.preflight):await this.preflightRename(e,{signal:t.signal});if(!s.ok)return s;let c=s.value;try{Qn(e,c)}catch(u){if(u instanceof C)return A(u.problem);throw u}r=Zn(e,c),a("ready",!0),ae(t.signal);let d=this.transport.hasResumableMutationTransport();a("applying",d);let p=await this.rename(e,d?{signal:t.signal}:void 0);return p.ok&&a("completed",!1,r.totalUnits),p}catch(s){if(Xt(s,t.signal)&&a("cancelled",!1),s instanceof C)return A(s.problem);throw s}}async deleteWithProgress(e,t={}){let i=Date.now(),o=!1,r,a=(s,c,d=0)=>{t.onProgress?.({operation:"delete",state:s,elapsedMs:Date.now()-i,cancellable:c,resumed:o,completedUnits:d,...r?{estimate:r}:{}})};try{ae(t.signal),a("preflighting",!0);let s=t.preflight?M(t.preflight):await this.preflightDelete(e,{signal:t.signal});if(!s.ok)return s;let c=s.value;try{Xn(e,c)}catch(u){if(u instanceof C)return A(u.problem);throw u}r=ei(c),a("ready",!0),ae(t.signal);let d=this.transport.hasResumableMutationTransport();a("applying",d);let p=await this.delete(e,d?{signal:t.signal}:void 0);return p.ok&&a("completed",!1,r.totalUnits),p}catch(s){if(Xt(s,t.signal)&&a("cancelled",!1),s instanceof C)return A(s.problem);throw s}}pendingMutations(){return this.transport.pendingMutations().map(e=>({...e,recover:t=>k(()=>this.recoverPendingMutation(e.requestId,t),x)}))}pendingMutation(e){let t=this.transport.pendingMutation(e);return t?{...t,recover:i=>k(()=>this.recoverPendingMutation(e,i),x)}:null}async recoverPendingMutation(e,t){let i=await this.transport.recoverPendingMutation(e,t);if(i&&typeof i=="object"&&"valid"in i){let o=i;if(!o.valid)throw new C(Ae(o));return o.result}return i}validate(e={},t){return this.collectionClient.validate(e,t)}readType(e,t){return this.collectionClient.readType(e,t)}createType(e,t){return this.collectionClient.createType(e,t)}updateType(e,t){return this.collectionClient.updateType(e,t)}assessTypePack(e,t){return this.collectionClient.assessTypePack(e,t)}applyTypePack(e,t){return this.collectionClient.applyTypePack(e,t)}listTimers(e,t){return this.collectionClient.listTimers(e,t)}putTimer(e,t){return this.collectionClient.putTimer(e,t)}cancelTimer(e,t){return this.collectionClient.cancelTimer(e,t)}reconcileTimers(e,t){return this.collectionClient.reconcileTimers(e,t)}watch(e={},t={}){return k(()=>U(t,this.internals.timeouts.watchStartMs,async i=>{let o=await this.collectionClient.changes(e.cursor===void 0?{}:{after:e.cursor,limit:200},{signal:i.signal,timeoutMs:null});if(!o.ok)throw new C(o.problem);if(o.value.reset)throw new C(T("change_cursor_reset","The collection change cursor expired. Refresh collection state before subscribing again."));return new dn(this.collectionClient,o.value.cursor,e,e.cursor===void 0?[]:o.value.events,this.internals.timeouts.watchStartMs)}),Te)}operation(e,t,i){return this.collectionClient.operation(e,t,i)}emitConnection(){let e=this.info();for(let t of this.connectionListeners)t(e)}},dn=class{constructor(e,t,i,o,r){this.client=e;this.input=i;this.watchStartTimeoutMs=r;this.pendingChanges=[...o],this.currentStatus={state:"connected",cursor:t,recovered:!1};let a=i.lifetimeSignal;if(a?.aborted)this.close();else if(a){let s=()=>this.close();a.addEventListener("abort",s,{once:!0}),this.removeLifetimeAbort=()=>a.removeEventListener("abort",s)}this.controller.signal.aborted||this.run(t)}client;input;watchStartTimeoutMs;changes=new Set;statuses=new Set;problems=new Set;controller=new AbortController;removeLifetimeAbort;currentStatus;currentProblem=null;pendingChanges;get status(){return this.currentStatus}get problem(){return this.currentProblem}subscribe(e,t,i){this.changes.add(e),t&&(this.statuses.add(t),t(this.currentStatus)),i&&(this.problems.add(i),this.currentProblem&&i(this.currentProblem));for(let o of this.pendingChanges)e(o);return this.pendingChanges=[],()=>{this.changes.delete(e),t&&this.statuses.delete(t),i&&this.problems.delete(i)}}close(){if(this.controller.signal.aborted)return;this.controller.abort(),this.removeLifetimeAbort?.(),this.removeLifetimeAbort=void 0;let e="cursor"in this.currentStatus?this.currentStatus.cursor:void 0;this.publishStatus({state:"closed",...e===void 0?{}:{cursor:e}})}async run(e){let t=!0,i=this.client.watch({cursor:e,pollIntervalMs:this.input.pollIntervalMs,retry:this.input.retry,signal:this.controller.signal,timeoutMs:this.watchStartTimeoutMs,onStatus:o=>{if(t&&o.state==="connecting"){t=!1;return}t=!1,this.publishStatus(o)}});try{for await(let o of i){if(this.controller.signal.aborted)return;if(!o.ok){this.currentProblem=o.problem;for(let r of this.problems)r(o.problem);return}for(let r of this.changes)r(o.value)}}finally{this.controller.signal.aborted||this.close()}}publishStatus(e){this.currentStatus=e;for(let t of this.statuses)t(e)}};function Tt(n,e){return{...n,timeoutMs:n?.timeoutMs===void 0?e:n.timeoutMs}}function Ji({body:n,clientId:e,keyHandle:t,previous:i,defaultApplicationOrigin:o,pinConnectorIdentity:r}){let a=n.collection_id;if(typeof a!="string")throw l("invalid_token_response","Authorization returned no collection ID.");let s=pt(n.scope);if(!s)throw l("invalid_token_response","Authorization returned no valid collection scope.");if(n.authority&&!Fe(n.authority,a))throw l("invalid_token_response","Authorization returned an invalid remote authority capability.");if(n.authority&&n.encryption)throw l("invalid_token_response","Authorization returned conflicting collection transports.");if(n.file_capability!==null&&n.file_capability!==void 0&&!ut(n.file_capability))throw l("invalid_token_response","Authorization returned an invalid file capability.");if(n.encryption){try{Q(n.encryption)}catch{throw l("invalid_token_response","Authorization returned an invalid encrypted relay binding.")}if(r(n.encryption.connector_id,n.encryption.connector_agreement_public_key),n.encryption.collection_id!==a||typeof n.grant_id!="string"||n.grant_id.length===0)throw l("invalid_token_response","Authorization returned an encrypted relay binding for another grant.")}if(i?.encryption&&n.encryption&&i.keyHandle&&i.keyHandle===t&&(i.grantId!==n.grant_id||i.encryption.connector_id!==n.encryption.connector_id||i.encryption.connector_agreement_public_key!==n.encryption.connector_agreement_public_key||i.encryption.application_agreement_public_key!==n.encryption.application_agreement_public_key))throw l("connector_identity_changed","The connector identity changed during authorization renewal. Reauthorize before sending collection data.");return{version:1,accessToken:n.access_token,refreshToken:n.refresh_token,clientId:e,collectionId:a,collectionName:n.collection_name??`Collection ${a.slice(0,8)}`,operations:n.operations,scope:s,expiresAt:Date.now()+n.expires_in*1e3,refreshExpiresAt:n.refresh_expires_in?Date.now()+n.refresh_expires_in*1e3:void 0,grantId:n.grant_id,encryption:n.encryption??void 0,fileCapability:n.file_capability??void 0,applicationOrigin:n.application_origin??o,keyHandle:t,savedAt:Date.now(),authority:n.authority?{operationsUrl:n.authority.operations_url,syncUrl:n.authority.sync_url,filesUrl:n.authority.files_url,replicaId:n.authority.replica_id,accessToken:n.authority.access_token,proofPublicKey:n.authority.proof_public_key}:void 0}}var It=class{serverUrl;manifest;manifestSource;redirectUri;storage;relayEncryption;keyStore;identityStore;directAccessMode;loopbackUrl;navigate;timeouts;credentialStorage;application=null;manifestPromise=null;completionPromises=new Map;connectionCache=new Map;listeners=new Set;invalidatedConnections=new Map;constructor(e){this.serverUrl=ci(String(e.serverUrl)),this.manifest=e.manifest instanceof URL?e.manifest.href:e.manifest??li(),this.manifestSource=typeof this.manifest=="string"?this.manifest:this.manifest.distribution==="portable"?`bundle:${this.manifest.id}:${yi(this.manifest)}`:`bundle:${this.manifest.id}`;let t=fi(this.manifest);this.redirectUri=e.redirectUri===void 0?typeof this.manifest!="string"&&this.manifest.distribution==="portable"?"":di():String(e.redirectUri),this.storage=e.storage??hi(t),this.relayEncryption=e.relayEncryption??"required",this.keyStore=e.keyStore??(t?new Me:new Ie),this.identityStore=e.identityStore??(t?new Ke:new Be),this.credentialStorage=e.storage||e.keyStore||e.identityStore?"custom":this.storage instanceof fe?"memory":"persistent",this.directAccessMode=e.directAccess??"auto",this.loopbackUrl=oi(String(e.loopbackUrl??`http://127.0.0.1:${En}`)),this.navigate=e.navigate,this.timeouts=ue(e.timeouts),typeof window<"u"&&this.storage===window.localStorage&&window.addEventListener("storage",i=>{i.storageArea!==this.storage||!i.key?.startsWith(this.storagePrefix())||(this.connectionCache.get(pi(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}}register(e={}){return U(e,this.timeouts.requestMs,t=>this.registerWithinBudget(t.signal))}async registerWithinBudget(e){if(this.application)return this.application;let t=await $(`${this.serverUrl}/v1/apps/register`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({manifest:await this.manifestDeclaration({signal:e,timeoutMs:null})}),signal:e},"temporarily_unavailable","Application registration is temporarily unavailable."),i=await S(t,"invalid_operation_response","Connect returned an invalid application registration response.");if(!t.ok)throw P(i,"discovery_failed","Application discovery failed.",t.status);return this.application=i.application,this.application}manifestDeclaration(e={}){if(this.manifestPromise)return this.manifestPromise;let i=U(e,this.timeouts.requestMs,o=>this.loadManifest(o.signal)).catch(o=>{throw this.manifestPromise===i&&(this.manifestPromise=null),o});return this.manifestPromise=i,this.manifestPromise}async loadManifest(e){if(typeof this.manifest!="string")return this.manifest;let t=this.manifest,i;try{i=await fetch(t,{headers:{accept:"application/json"},signal:e})}catch(o){throw l("manifest_load_failed","The bundled application declaration could not be loaded.",{cause:o})}if(!i.ok)throw l("manifest_load_failed",`The bundled application declaration returned HTTP ${i.status}.`,{status:i.status});try{return await S(i,"invalid_application_manifest","The bundled application declaration is not valid JSON.")}catch(o){throw l("invalid_application_manifest","The bundled application declaration is not valid JSON.",{cause:o,details:{issues:[{path:"/",keyword:"json",message:"must be valid JSON",params:{}}]}})}}async authorize(e={}){return U(e,this.timeouts.requestMs,t=>this.authorizeWithinBudget({...e,signal:t.signal,timeoutMs:null}))}async authorizeWithinBudget(e){if(typeof location>"u"&&!this.navigate&&!e.openVerification)throw l("browser_required","Authorization navigation requires a browser environment.");let i=typeof this.manifest!="string"&&this.manifest.distribution==="portable"&&!e.openVerification&&!this.navigate&&typeof window<"u"?window.open("","mdbase-connect-authorization","popup,width=620,height=760"):null,o;try{o=await this.registerWithinBudget(e.signal)}catch(r){throw i?.close(),r}return o.distribution==="portable"?(e.openVerification&&i?.close(),this.authorizePortable(o,e,e.openVerification?null:i)):(i?.close(),this.authorizeWeb(o,e))}async authorizeWeb(e,t){let{verifier:i,challenge:o}=await Ue(),r=N(24),a=crypto.randomUUID(),s=t.target?.kind==="collection"?t.target.collectionId:void 0,c=`grant:${e.id}:${r}`,d=await this.keyStore.create(c),p;try{p=await this.loadApplicationIdentity(e)}catch(y){throw await this.keyStore.delete(c),y}let u=K(t.operations??se),h=new Date,f=await mt({protocol_version:Se,authorization_id:a,application_id:e.id,application_manifest_digest:e.manifest_digest,application_installation_id:await je(p),installation_signing_public_key:p.signingPublicKey,grant_agreement_public_key:d.agreementPublicKey,grant_signing_public_key:d.signingPublicKey,flow:"authorization_code",authorization_nonce:N(32),issued_at:h.toISOString(),expires_at:new Date(h.getTime()+600*1e3).toISOString(),redirect_uri:this.redirectUri,state:r,code_challenge:o,contracts:Nt(u,e.requirements?.files),requested_operations:u,...e.requirements?.files?{requested_files:e.requirements.files}:{},...s?{collection_id:s}:{}},p),m={version:1,verifier:i,state:r,clientId:e.id,redirectUri:this.redirectUri,relayEncryption:this.relayEncryption,collectionId:s,returnTo:t.returnTo,keyHandle:c,authorizationId:a,applicationAgreementPublicKey:d.agreementPublicKey,applicationSigningPublicKey:d.signingPublicKey};this.storage.setItem(this.pendingKey(r),JSON.stringify(m));try{let y=await fetch(`${this.serverUrl}/oauth/authorization_request`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e.id,redirect_uri:this.redirectUri,code_challenge:o,code_challenge_method:"S256",state:r,operations:u.join(","),...s?{collection_id:s}:{},application_authorization:JSON.stringify(f)}),signal:t.signal}),g=await S(y,"invalid_device_authorization_response","The authorization service returned an invalid authorization response.");if(!y.ok)throw P(g,"device_authorization_failed","Application authorization could not be started.",y.status);if(typeof g.authorization_uri!="string"||g.authorization_id!==a||!Number.isInteger(g.expires_in)||g.expires_in<=0)throw l("invalid_device_authorization_response","The authorization service returned an invalid authorization response.");if(this.navigate)await this.navigate(g.authorization_uri);else if(typeof location<"u")location.assign(g.authorization_uri);else throw l("browser_required","Authorization navigation requires a browser environment.");return{kind:"redirecting"}}catch(y){throw this.storage.removeItem(this.pendingKey(r)),await this.keyStore.delete(c),t.signal?.aborted?Ye(t.signal,"Application authorization was cancelled.",y):y}}async authorizePortable(e,t,i){if(this.relayEncryption!=="required")throw i?.close(),l("encryption_required","Downloaded applications require encrypted relay authorization.");let{verifier:o,challenge:r}=await Ue(),a=`grant:${e.id}:${N(24)}`,s=await this.keyStore.create(a),c;try{c=await this.loadApplicationIdentity(e)}catch(b){throw i?.close(),await this.keyStore.delete(a),b}let d=K(t.operations??se),p=crypto.randomUUID(),u=new Date,h=await mt({protocol_version:Se,authorization_id:p,application_id:e.id,application_manifest_digest:e.manifest_digest,application_installation_id:await je(c),installation_signing_public_key:c.signingPublicKey,grant_agreement_public_key:s.agreementPublicKey,grant_signing_public_key:s.signingPublicKey,flow:"device_code",authorization_nonce:N(32),issued_at:u.toISOString(),expires_at:new Date(u.getTime()+600*1e3).toISOString(),code_challenge:r,contracts:Nt(d,e.requirements?.files),requested_operations:d,...e.requirements?.files?{requested_files:e.requirements.files}:{},...t.target?.kind==="collection"?{collection_id:t.target.collectionId}:{}},c),f,m;try{f=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:d.join(","),...t.target?.kind==="collection"?{collection_id:t.target.collectionId}:{},code_challenge:r,code_challenge_method:"S256",application_authorization:JSON.stringify(h)}),signal:t.signal}),m=await S(f,"invalid_device_authorization_response","The authorization service returned an invalid device authorization response.")}catch(b){throw i?.close(),await this.keyStore.delete(a),l("device_authorization_failed","Downloaded application authorization could not be started.",{cause:b})}if(!f.ok)throw i?.close(),await this.keyStore.delete(a),P(m,"device_authorization_failed","Downloaded application authorization could not be started.",f.status);let y;try{y=si(m)}catch(b){throw i?.close(),await this.keyStore.delete(a),t.signal?.aborted?Ye(t.signal,"Downloaded application authorization was cancelled.",b):b}if(t.onDeviceCode?.(y),t.openVerification)await t.openVerification(y);else if(i)try{i.location.href=y.verificationUriComplete}catch{}else throw await this.keyStore.delete(a),l("approval_window_blocked","The approval window was blocked. Show the provided verification link and code, then try again.",{details:{user_code:y.userCode,verification_uri:y.verificationUri,verification_uri_complete:y.verificationUriComplete,expires_at:y.expiresAt,interval_seconds:y.intervalSeconds}});let g=y.intervalSeconds;try{for(;Date.now()<y.expiresAt;){if(await Le(g*1e3,t.signal),t.signal?.aborted)throw Ye(t.signal,"Downloaded application authorization was cancelled.");let b;try{b=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:m.device_code,client_id:e.id,code_verifier:o}),signal:t.signal})}catch(v){if(t.signal?.aborted)throw Ye(t.signal,"Downloaded application authorization was cancelled.",v);continue}let _=await S(b,"invalid_token_response","The authorization service returned an invalid token response.");if(!b.ok){let v=ze(_);if(v==="authorization_pending")continue;if(v==="slow_down"){g+=5;continue}throw P(_,"token_exchange_failed","Downloaded application authorization could not be completed.",b.status)}let O=Fe(_.authority,_.collection_id),z=_.encryption&&_.encryption.protocol_version===ot&&_.encryption.suite===Pe&&_.encryption.application_agreement_public_key===s.agreementPublicKey;if(_.application_origin!=="null")throw l("invalid_token_response","Authorization did not bind the portable grant to its opaque application origin.");if(_.authority&&(!O||_.encryption!=null||_.authority.proof_public_key!==s.signingPublicKey))throw l("invalid_token_response","Authorization returned a remote authority capability that is not bound to this portable grant key.");if(!_.authority&&!z)throw l("encryption_required","Authorization did not establish the expected key-bound local portable grant.");let E=this.storeTokenResponse(_,e.id,a);if(t.target?.kind==="collection"&&t.target.collectionId!==E.collectionId)throw this.removeToken(E.collectionId,E.keyHandle),l("collection_mismatch","The approved collection does not match the collection requested by this link.");return i?.close(),{kind:"connected",connection:this.connection(E.collectionId),...t.returnTo?{returnTo:t.returnTo}:{}}}throw l("expired_token","The downloaded application authorization code expired.")}catch(b){throw i?.close(),await this.keyStore.delete(a),t.signal?.aborted?Ye(t.signal,"Downloaded application authorization was cancelled.",b):b}}completeAuthorization(e,t={}){return U(t,this.timeouts.requestMs,i=>this.completeAuthorizationWithinBudget(e,i.signal))}completeAuthorizationWithinBudget(e,t){let i=new URL(e).searchParams.get("state");if(!i)return Promise.reject(l("invalid_callback","Authorization callback is missing its state."));let o=this.completionPromises.get(i);if(o)return o;let a=this.performAuthorizationCompletion(e,i,t).finally(()=>{this.completionPromises.get(i)===a&&this.completionPromises.delete(i)});return this.completionPromises.set(i,a),a}async performAuthorizationCompletion(e,t,i){let o=new URL(e),r=o.searchParams.get("code"),a=this.pendingKey(t),s=I(this.storage.getItem(a));if(!s||s.version!==1||t!==s.state)throw l("invalid_callback","Authorization callback is missing or does not match this browser session.");if(o.searchParams.has("error"))throw s.keyHandle&&await this.keyStore.delete(s.keyHandle),this.storage.removeItem(a),F(o.searchParams.get("error")??"access_denied",o.searchParams.get("error_description")??"Collection access was not approved.",{details:s.returnTo?{return_to:s.returnTo}:void 0});if(!r)throw l("invalid_callback","Authorization callback is missing its code.");let c=await $(`${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:s.clientId,redirect_uri:s.redirectUri,code_verifier:s.verifier}),signal:i},"temporarily_unavailable","Authorization completion is temporarily unavailable."),d=await S(c,"invalid_token_response","The authorization service returned an invalid token response.");if(!c.ok)throw P(d,"token_exchange_failed","Authorization could not be completed.",c.status);if(s.relayEncryption==="required"&&!d.authority&&(!d.encryption||!s.keyHandle||d.encryption.application_agreement_public_key!==s.applicationAgreementPublicKey))throw s.keyHandle&&await this.keyStore.delete(s.keyHandle),this.storage.removeItem(a),l("encryption_required","Authorization did not establish the required encrypted relay grant.");if(d.authority?.proof_public_key){if(!s.keyHandle||!s.applicationSigningPublicKey||d.authority.proof_public_key!==s.applicationSigningPublicKey)throw s.keyHandle&&await this.keyStore.delete(s.keyHandle),this.storage.removeItem(a),l("invalid_token_response","Authorization returned a remote authority capability bound to another application key.")}else d.authority&&s.keyHandle&&await this.keyStore.delete(s.keyHandle);let p=this.storeTokenResponse(d,s.clientId,d.authority?.proof_public_key?s.keyHandle:d.authority?void 0:s.keyHandle);if(s.collectionId&&s.collectionId!==p.collectionId)throw this.removeToken(p.collectionId,p.keyHandle),this.storage.removeItem(a),l("collection_mismatch","The approved collection does not match the collection requested by this link.");return this.storage.removeItem(a),{connection:this.connection(p.collectionId),...s.returnTo?{returnTo:s.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 Ge(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 o=e.collection_id;if(typeof o!="string")throw l("invalid_token_response","Authorization returned no collection ID.");let r=I(this.storage.getItem(this.tokenKey(o))),a=Ji({body:e,clientId:t,keyHandle:i,previous:r,defaultApplicationOrigin:this.defaultApplicationOrigin(),pinConnectorIdentity:(s,c)=>this.pinConnectorIdentity(s,c)});return r?.keyHandle&&r.keyHandle!==i&&this.keyStore.delete(r.keyHandle).catch(()=>{}),this.storage.setItem(this.tokenKey(o),JSON.stringify(a)),this.addConnectionId(o),this.invalidatedConnections.delete(o),this.connectionCache.delete(o),this.emitConnections(),a}forgetConnectorIdentity(e){this.storage.removeItem(this.connectorPinKey(e))}pinConnectorIdentity(e,t){let i=this.connectorPinKey(e),o=I(this.storage.getItem(i));if(o&&(o.version!==1||o.publicKey!==t))throw l("connector_identity_changed","The connector identity changed since this application first connected. Forget the saved connector identity only after verifying the computer, then authorize again.");o||this.storage.setItem(i,JSON.stringify({version:1,publicKey:t}))}connectorPinKey(e){return`mdbase-connect:${this.serverUrl}:connector-pin:${e}`}async loadApplicationIdentity(e){try{return await nn(this.identityStore,this.serverUrl,e)}catch(t){throw l("application_identity_unavailable",t instanceof _e?t.message:"The application installation identity is unavailable.",{cause:t})}}removeToken(e,t,i="authorization_lost",o=!1){this.invalidatedConnections.set(e,i),t&&(o||!this.pendingMutationsUseKey(e,t))&&this.keyStore.delete(t).catch(()=>{}),this.storage.removeItem(this.tokenKey(e)),o&&this.removePendingMutations(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}`}removePendingMutations(e){let t=this.pendingMutationKey(e),i=[t];for(let o=0;o<this.storage.length;o+=1){let r=this.storage.key(o);r?.startsWith(`${t}:`)&&i.push(r)}for(let o of i){let r=I(this.storage.getItem(o));r?.keyHandle&&this.keyStore.delete(r.keyHandle).catch(()=>{}),this.storage.removeItem(o)}}pendingMutationsUseKey(e,t){let i=this.pendingMutationKey(e);for(let o=0;o<this.storage.length;o+=1){let r=this.storage.key(o);if(r!==i&&!r?.startsWith(`${i}:`))continue;if(I(this.storage.getItem(r))?.keyHandle===t)return!0}return!1}notificationKey(e,t="web_push"){return`${this.storagePrefix()}:notifications:${e}:${t}`}directPreferenceKey(){return`mdbase-connect:direct:${this.defaultApplicationOrigin()}`}defaultApplicationOrigin(){return ui(this.manifest,this.manifestSource,this.redirectUri,this.application?.distribution==="portable")}pendingKey(e){return`${this.storagePrefix()}:pending:${e}`}storagePrefix(){return`mdbase-connect:${this.serverUrl}:${this.manifestSource}`}connectionsKey(){return`${this.storagePrefix()}:connections`}connectionIds(){let e=I(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 Ye(n,e,t){return n.reason instanceof C?n.reason:l("authorization_cancelled",e,{cause:t})}var un=class{internals;constructor(e){this.internals=new It(e)}register(e){return k(()=>this.internals.register(e),J)}authorize(e={}){return k(()=>this.internals.authorize(e),ie)}application(e){return new Ne(this,e,this.internals.timeouts)}manifest(e){return k(()=>this.internals.manifestDeclaration(e),J)}environment(){return this.internals.environment()}completeAuthorization(e,t){return k(()=>this.internals.completeAuthorization(e===void 0?ht():String(e),t),ie)}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()}forgetConnectorIdentity(e){this.internals.forgetConnectorIdentity(e)}};function Wi(n){if(!n||typeof n!="object")throw l("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 l("invalid_push_payload","The push payload is not an mdbase notification.");return e}function xr(n){if(!n||typeof n!="object")throw l("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 l("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 qr(n,e){let t=Wi(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}})}function Ur(n){return{subscribe:e=>n.subscribe(e),getSnapshot:()=>n.getSnapshot()}}var pn=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=De(this.currentUrl());e?i.searchParams.set(this.collectionParameter,e):i.searchParams.delete(this.collectionParameter);let o=this.browserHistory();o[t.history==="push"?"pushState":"replaceState"](o.state,"",i),this.emit()}authorizationReturnTo(){let e=De(this.currentUrl());return`${e.pathname}${e.search}${e.hash}`}authorizationCallback(){let e=this.currentUrl().href;return ft(e)?e:null}finishAuthorization(e,t){let i=this.safeAppUrl(e??this.fallbackPath);De(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,"",De(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 l("browser_required","Browser selection requires a browser environment.");return new URL(location.href)}browserHistory(){if(typeof history>"u")throw l("browser_required","Browser selection requires a browser environment.");return history}},hn=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 io(zr);})();