@mdbase-dev/connect 0.1.0-beta.125 → 0.1.0-beta.147

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/application-session.d.ts +1 -1
  2. package/dist/application-session.js +1 -1
  3. package/dist/async.d.ts +6 -0
  4. package/dist/async.js +39 -0
  5. package/dist/authorization-refresh.d.ts +2 -0
  6. package/dist/authorization-refresh.js +13 -1
  7. package/dist/browser/integrity.json +1 -1
  8. package/dist/browser/mdbase-connect.min.js +4 -4
  9. package/dist/browser/mdbase-connect.min.js.sha384 +1 -1
  10. package/dist/capabilities.d.ts +1 -1
  11. package/dist/collection-client.d.ts +2 -0
  12. package/dist/collection-client.js +8 -4
  13. package/dist/connect-options.d.ts +1 -1
  14. package/dist/connect.d.ts +1 -1
  15. package/dist/connect.js +1 -1
  16. package/dist/connection.d.ts +2 -1
  17. package/dist/connection.js +3 -1
  18. package/dist/control-timers.d.ts +43 -0
  19. package/dist/control-timers.js +290 -0
  20. package/dist/errors.d.ts +2 -28
  21. package/dist/errors.js +2 -52
  22. package/dist/file-transfer-internals.d.ts +2 -1
  23. package/dist/file-transfer-internals.js +10 -3
  24. package/dist/files.d.ts +4 -0
  25. package/dist/files.js +17 -18
  26. package/dist/index.d.ts +2 -1
  27. package/dist/index.js +1 -0
  28. package/dist/internal-types.d.ts +2 -2
  29. package/dist/internal-types.js +1 -1
  30. package/dist/mdbase-connect.d.ts +1 -1
  31. package/dist/observe.d.ts +81 -0
  32. package/dist/observe.js +390 -0
  33. package/dist/operation-types.d.ts +3 -1
  34. package/dist/outcomes.d.ts +13 -13
  35. package/dist/outcomes.js +17 -0
  36. package/dist/query-pagination-internals.d.ts +1 -1
  37. package/dist/query-pagination-internals.js +4 -2
  38. package/dist/query-pagination.js +1 -1
  39. package/dist/query-wire.d.ts +16 -10
  40. package/dist/query-wire.js +44 -13
  41. package/dist/read-many.js +4 -2
  42. package/dist/runtime-utils.d.ts +1 -1
  43. package/dist/saved-view-pagination.js +1 -1
  44. package/dist/session.d.ts +1 -1
  45. package/dist/session.js +1 -1
  46. package/dist/structured-readiness.d.ts +1 -1
  47. package/package.json +7 -3
  48. package/dist/application-contract.d.ts +0 -22
  49. package/dist/application-contract.js +0 -75
@@ -1,4 +1,4 @@
1
- "use strict";var MdbaseConnect=(()=>{var Gn=Object.defineProperty;var $s=Object.getOwnPropertyDescriptor;var Js=Object.getOwnPropertyNames;var Ys=Object.prototype.hasOwnProperty;var Xs=(t,e)=>{for(var n in e)Gn(t,n,{get:e[n],enumerable:!0})},Zs=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Js(e))!Ys.call(t,o)&&o!==n&&Gn(t,o,{get:()=>e[o],enumerable:!(i=$s(e,o))||i.enumerable});return t};var ea=t=>Zs(Gn({},"__esModule",{value:!0}),t);var _l={};Xs(_l,{ApplicationIdentityStoreError:()=>De,FileTransferCryptoError:()=>ge,GrantFileTransferCipher:()=>ct,IndexedDbApplicationIdentityStore:()=>nt,IndexedDbGrantKeyStore:()=>He,MDBASE_RECORD_CREATED_CONTRACT:()=>To,MDBASE_TIMER_FIRED_CONTRACT:()=>Mo,MdbaseApplicationSession:()=>et,MdbaseBrowserSelection:()=>Qn,MdbaseCollectionClient:()=>at,MdbaseConnect:()=>Kn,MdbaseConnectError:()=>_,MdbaseConnection:()=>ft,MdbaseFileClient:()=>dt,MdbaseMemorySelection:()=>Vn,MdbaseMemoryVerificationStore:()=>Et,MdbasePeopleClient:()=>rt,MdbaseRecordSession:()=>ut,MdbaseRecords:()=>pt,MdbaseSession:()=>Ze,MemoryApplicationIdentityStore:()=>it,MemoryGrantKeyStore:()=>We,PERSON_CONTRACT:()=>Ft,RelayCryptoError:()=>q,applicationIdentity:()=>fn,applicationInstallationId:()=>ot,authorityProofMessage:()=>Ai,connectError:()=>d,connectFailure:()=>g,connectProblem:()=>w,connectSuccess:()=>R,createPkce:()=>At,decryptRelayResponse:()=>$e,deriveFileTransferKey:()=>Bi,deriveP256SharedSecret:()=>St,effectiveCapabilities:()=>Xt,encryptRelayRequest:()=>me,externalStore:()=>Ws,isRetryableConnectError:()=>Eo,linksTo:()=>Hs,normalizeCollectionChange:()=>bi,operationProblem:()=>je,operationsForApplicationCapabilities:()=>io,parseMdbaseNativeNotificationData:()=>Vs,parseMdbasePushPayload:()=>no,sameIdentity:()=>mn,showMdbasePushNotification:()=>Gs,signApplicationAuthorization:()=>qt,signAuthorityRequest:()=>on,validateGrantEncryption:()=>ye});var zt={"collection.read":["describe","changes","read","query","list_views","execute_view","read_view_source","validate","read_type"],"records.create":["create"],"records.edit":["update","rename"],"records.delete":["delete"],"views.manage":["create_view_source","update_view_source","delete_view_source"],"definitions.manage":["create_type","update_type","assess_type_pack","apply_type_pack"],"background.schedule":["list_timers","put_timer","cancel_timer","reconcile_timers"],"offline.replica":["sync"]},Lt=["assess_collection_setup","apply_collection_setup"];function io(t,e={}){let n=e.includeOptional===!1?t.required:[...t.required,...t.optional??[]];return[...new Set(n.flatMap(i=>zt[i]))]}var ta=Object.freeze({"collection.inspect":Object.freeze(["describe"]),"records.watch":Object.freeze(["changes"]),"records.read":Object.freeze(["read"]),"records.query":Object.freeze(["query"]),"records.validate":Object.freeze(["validate"]),"records.create":Object.freeze(["create"]),"records.update":Object.freeze(["update"]),"records.delete":Object.freeze(["delete"]),"records.rename":Object.freeze(["rename"]),"views.list":Object.freeze(["list_views"]),"views.execute":Object.freeze(["execute_view"]),"views.source.read":Object.freeze(["read_view_source"]),"views.source.create":Object.freeze(["create_view_source"]),"views.source.update":Object.freeze(["update_view_source"]),"views.source.delete":Object.freeze(["delete_view_source"]),"definitions.contracts.current":Object.freeze([]),"definitions.read":Object.freeze(["read_type"]),"definitions.create":Object.freeze(["create_type"]),"definitions.update":Object.freeze(["update_type"]),"definitions.type-pack.inspect":Object.freeze(["assess_type_pack"]),"definitions.type-pack.apply":Object.freeze(["assess_type_pack","apply_type_pack"]),"collection.setup.apply":Object.freeze(["assess_collection_setup","apply_collection_setup"]),"timers.list":Object.freeze(["list_timers"]),"timers.put":Object.freeze(["put_timer"]),"timers.cancel":Object.freeze(["cancel_timer"]),"timers.reconcile":Object.freeze(["reconcile_timers"]),"sync.offline-replica":Object.freeze(["sync"]),"notifications.background-delivery":Object.freeze([]),"files.list":Object.freeze([]),"files.read":Object.freeze([]),"files.add":Object.freeze([]),"files.replace":Object.freeze([]),"files.move":Object.freeze([]),"files.delete":Object.freeze([])});function X(t,e){let n=t===1?ta:t===2?zt:void 0;if(!(!n||!Object.hasOwn(n,e)))return[...n[e]]}var Cl=Object.freeze([1,2]),oo="application-authorization-v2-issuance",Hn=Object.freeze(["application-authorization-v2-issuance"]);var ro="yaml-document-records-v1";var Me={access_denied:{category:"authorization",recovery:"reauthorize"},access_paused:{category:"availability",recovery:"resume_connector_access"},application_declaration_mismatch:{category:"authorization",recovery:"reauthorize"},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_busy:{category:"availability",recovery:"retry"},connector_identity_changed:{category:"integrity",recovery:"reauthorize"},connector_offline:{category:"availability",recovery:"retry"},connector_upgrade_required:{category:"compatibility",recovery:"upgrade_connector"},cursor_capacity_exhausted:{category:"availability",recovery:"retry"},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_index_warming:{category:"availability",recovery:"retry"},file_list_changed:{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"},fresh_request_required:{category:"availability",recovery:"retry"},generation_expired:{category:"conflict",recovery:"refresh"},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_read_cursor:{category:"validation",recovery:"fix_request"},invalid_request:{category:"validation",recovery:"fix_request"},invalid_token_response:{category:"integrity",recovery:"contact_support"},legacy_scope_reauthorization_required:{category:"authorization",recovery:"reauthorize"},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"},session_destroyed:{category:"cancellation",recovery:"none"},session_not_started:{category:"validation",recovery:"fix_request"},session_starting:{category:"availability",recovery:"retry"},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"}},na={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 so(t){return Object.hasOwn(Me,t)}function ht(t){if(!ao(t))return!1;let e=t;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"||!so(e.code)||e.server_code!==void 0)return!1;let n=Me[e.code],i=na[e.code],o=i===void 0?e.details===void 0:e.details===void 0?(i.required?.length??0)===0:Wn(e.details,i);return e.category===n.category&&e.recovery===n.recovery&&o}function Wn(t,e){if(e.type===void 0)return!0;if(e.type==="string")return typeof t=="string";if(e.type==="integer")return typeof t=="number"&&Number.isInteger(t);if(e.type==="number")return typeof t=="number"&&Number.isFinite(t);if(e.type==="boolean")return typeof t=="boolean";if(e.type==="array")return Array.isArray(t)&&t.every(i=>Wn(i,e.items??{}));if(!ao(t))return!1;if(!e.properties)return!0;let n=t;return!Object.keys(n).every(i=>Object.hasOwn(e.properties,i))||!(e.required??[]).every(i=>Object.hasOwn(n,i))?!1:Object.entries(n).every(([i,o])=>Wn(o,e.properties[i]))}function ao(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function $n(t,e,n={}){if(so(t)){let i=Me[t],o={problem_version:1,code:t,category:i.category,recovery:i.recovery,message:e,...n.details===void 0?{}:{details:n.details},...n.operation_outcome===void 0?{}:{operation_outcome:n.operation_outcome},...n.trace_id===void 0?{}:{trace_id:n.trace_id}};if(ht(o))return o}return{problem_version:1,code:"unknown",server_code:t,category:"unknown",recovery:"none",message:e,...n.details===void 0?{}:{details:n.details},...n.operation_outcome===void 0?{}:{operation_outcome:n.operation_outcome},...n.trace_id===void 0?{}:{trace_id:n.trace_id}}}var co=new Uint8Array([77,68,66,70]),lo=1,uo=0,Ol=new Uint8Array([77,68,66,82]);var po=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function fo(t,e={}){return{actions:[...new Set([...t.required,...e.includeOptional===!1?[]:t.optional??[]])],scope:structuredClone(t.scope)}}var x=class extends Error{code;constructor(e,n){super(n),this.code=e,this.name="FileFrameError"}};function ia(t){return t==="upload_chunk"?1:2}function oa(t){if(t===1)return"upload_chunk";if(t===2)return"download_chunk";throw new x("invalid_kind",`Unknown file frame kind ${t}`)}function ra(t){if(!t||typeof t!="object"||Array.isArray(t))throw new x("invalid_header","File frame header must be a JSON object");return t}function Nt(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new x("invalid_header",`File frame header ${e} must be a non-empty string`);return n}function Ut(t,e){let n=Nt(t,e);if(!po.test(n))throw new x("invalid_header",`File frame header ${e} must be a UUID`);return n}function Ie(t,e,n=Number.MAX_SAFE_INTEGER){let i=t[e];if(!Number.isSafeInteger(i)||i<0||i>n)throw new x("invalid_header",`File frame header ${e} is outside its allowed range`);return i}function Jn(t){if(t.protocol_version!==1)throw new x("unsupported_version",`Unsupported file transfer protocol ${t.protocol_version}`);if(t.protection!=="grant_aead_v1"&&t.protection!=="transport_tls")throw new x("invalid_header","Unknown file transfer protection");if(t.direction!=="upload"&&t.direction!=="download")throw new x("invalid_header","Unknown file transfer direction");for(let[e,n]of[["grant_id",t.grant_id],["authority_id",t.authority_id],["collection_id",t.collection_id],["transfer_id",t.transfer_id]])if(!po.test(n))throw new x("invalid_header",`File frame header ${e} must be a UUID`);for(let[e,n,i]of[["chunk_size",t.chunk_size,4194304],["chunk_index",t.chunk_index,Number.MAX_SAFE_INTEGER],["offset",t.offset,Number.MAX_SAFE_INTEGER],["plaintext_length",t.plaintext_length,4194304],["total_size",t.total_size,Number.MAX_SAFE_INTEGER]])if(!Number.isSafeInteger(n)||n<0||n>i)throw new x("invalid_header",`File frame header ${e} is outside its allowed range`);if(t.chunk_size<64*1024)throw new x("invalid_header","File frame chunk_size is below the protocol minimum");if(!Number.isSafeInteger(t.scope_epoch)||t.scope_epoch<1)throw new x("invalid_header","File frame header scope_epoch must be a positive integer");if(t.protection==="grant_aead_v1"&&!t.key_id)throw new x("invalid_header","AEAD-protected file frames require key_id");return{protocol_version:1,protection:t.protection,grant_id:t.grant_id,authority_id:t.authority_id,collection_id:t.collection_id,transfer_id:t.transfer_id,direction:t.direction,chunk_size:t.chunk_size,chunk_index:t.chunk_index,offset:t.offset,plaintext_length:t.plaintext_length,total_size:t.total_size,scope_epoch:t.scope_epoch,...t.key_id===void 0?{}:{key_id:t.key_id}}}function sa(t){let e;try{e=new TextDecoder("utf-8",{fatal:!0}).decode(t)}catch{throw new x("invalid_header","File frame header is not valid UTF-8")}let n;try{n=ra(JSON.parse(e))}catch(l){throw l instanceof x?l:new x("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(n).some(l=>!i.has(l)))throw new x("invalid_header","File frame header contains an unknown field");let o=Ie(n,"protocol_version");if(o!==1)throw new x("unsupported_version",`Unsupported file transfer protocol ${o}`);let r=Nt(n,"protection"),s=Nt(n,"direction"),a=n.key_id===void 0?void 0:Nt(n,"key_id"),c=Jn({protocol_version:1,protection:r,grant_id:Ut(n,"grant_id"),authority_id:Ut(n,"authority_id"),collection_id:Ut(n,"collection_id"),transfer_id:Ut(n,"transfer_id"),direction:s,chunk_size:Ie(n,"chunk_size",4194304),chunk_index:Ie(n,"chunk_index"),offset:Ie(n,"offset"),plaintext_length:Ie(n,"plaintext_length",4194304),total_size:Ie(n,"total_size"),scope_epoch:Ie(n,"scope_epoch"),...a===void 0?{}:{key_id:a}});if(JSON.stringify(c)!==e)throw new x("invalid_header","File frame header must use the canonical field order without duplicate fields or whitespace");return c}function Yn(t,e,n){let i=t==="upload_chunk"?"upload":"download";if(e.direction!==i)throw new x("invalid_header",`Frame kind ${t} requires direction ${i}`);let o=e.chunk_index*e.chunk_size;if(!Number.isSafeInteger(o)||e.offset!==o)throw new x("invalid_header","Chunk offset does not match its index and protocol chunk size");if(e.offset+e.plaintext_length>e.total_size)throw new x("invalid_header","Chunk extends past the declared transfer size");let r=e.protection==="grant_aead_v1"?e.plaintext_length+16:e.plaintext_length;if(n!==r)throw new x("invalid_length","Payload length does not match the protected plaintext length")}function aa(t){return t.plaintext_length+(t.protection==="grant_aead_v1"?16:0)}function jt(t,e){let n=Jn(e),i=aa(n);Yn(t,n,i);let o=new TextEncoder().encode(JSON.stringify(n));if(o.byteLength>16384)throw new x("limit_exceeded","File frame header exceeds the protocol limit");let r=new Uint8Array(16+o.byteLength);r.set(co,0);let s=new DataView(r.buffer,r.byteOffset,r.byteLength);return s.setUint8(4,lo),s.setUint8(5,ia(t)),s.setUint16(6,uo,!1),s.setUint32(8,o.byteLength,!1),s.setUint32(12,i,!1),r.set(o,16),r}function ho(t){let e=Jn(t.header);if(Yn(t.kind,e,t.payload.byteLength),t.payload.byteLength>4194320)throw new x("limit_exceeded","File frame payload exceeds the protocol limit");let n=jt(t.kind,e),i=new Uint8Array(n.byteLength+t.payload.byteLength);return i.set(n,0),i.set(t.payload,n.byteLength),i}function Bt(t,e={}){if(t.byteLength<16)throw new x("invalid_length","File frame is shorter than its fixed prefix");if(!co.every((p,h)=>t[h]===p))throw new x("invalid_magic","File frame magic is not MDBF");let n=new DataView(t.buffer,t.byteOffset,t.byteLength),i=n.getUint8(4);if(i!==lo)throw new x("unsupported_version",`Unsupported file frame version ${i}`);let o=oa(n.getUint8(5));if(n.getUint16(6,!1)!==uo)throw new x("unsupported_flags","File frame uses unsupported flags");let r=n.getUint32(8,!1),s=n.getUint32(12,!1),a=e.maxHeaderBytes??16384,c=e.maxPayloadBytes??4194320;if(r===0)throw new x("invalid_length","File frame header must not be empty");if(r>a||s>c)throw new x("limit_exceeded","File frame exceeds the configured decode limits");let l=16+r+s;if(!Number.isSafeInteger(l)||l!==t.byteLength)throw new x("invalid_length","File frame lengths do not match the supplied bytes");let u=16+r,f=sa(t.subarray(16,u));return Yn(o,f,s),{kind:o,header:f,payload:t.slice(u)}}var ca=["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","assess_collection_setup","apply_collection_setup","list_timers","put_timer","cancel_timer","reconcile_timers","sync"],la=["list_files","stat_file","open_file_upload","open_file_download","move_file","delete_file","get_file_transfer_status","commit_file_upload","abort_file_transfer"],da={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",assess_collection_setup:"never",apply_collection_setup:"always",list_timers:"never",put_timer:"always",cancel_timer:"always",reconcile_timers:"always",sync:"sync_action"},ua={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,assess_collection_setup:1,apply_collection_setup:1,list_timers:1,put_timer:1,cancel_timer:1,reconcile_timers:1,sync:1},pa={list_files:1,stat_file: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},fa=new Set(["open_file_upload","move_file","delete_file","commit_file_upload","abort_file_transfer"]),ha=new Set(["delete","rename"]);var ma=new Set(ca),ya=new Set(la);function mo(t){return ma.has(t)}function ga(t){return ya.has(t)}function yo(t,e){if(t==="file_control"){let n=go(e)&&typeof e.type=="string"?e.type:"";if(!ga(n))throw new Error(`Unknown file-control message: ${n}`);return pa[n]}return ua[t]}function be(t,e){let n=go(e)?e:{};if(n.dry_run===!0&&ha.has(t))return null;if(t==="file_control"){let o=typeof n.type=="string"?n.type:"";return fa.has(o)?`file_control:${o}`:null}let i=da[t];return i==="always"?t:i==="sync_action"&&n.action==="mutate"?"sync:mutate":null}function Z(t,e){return be(t,e)!==null}function go(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var Xn={"mdbase.record.created":"record.created","mdbase.record.modified":"record.updated","mdbase.record.deleted":"record.deleted","mdbase.record.renamed":"record.renamed","mdbase.type.changed":"schema.changed","mdbase.config.changed":"config.changed","mdbase.contract.changed":"contract.changed","mdbase.view.changed":"view.changed","mdbase.view_source.changed":"view.changed","mdbase.resource.changed":"file.changed","mdbase.file.put":"file.put","mdbase.file.remove":"file.removed",file_put:"file.put",file_remove:"file.removed","mdbase.collection.invalidated":"gap"};var ba=1,_a="mdbase-connect mutation fingerprint v1\0",Zn=new TextEncoder;function va(t){return ei(t,new Set)}function Ca(t,e){let n=be(t,e);if(n===null)throw new TypeError("The operation is not a canonical mutation.");let i=Zn.encode(n),o=Zn.encode(va(e)),r=Zn.encode(_a),s=new Uint8Array(r.length+4+8+i.length+4+8+o.length),a=new DataView(s.buffer),c=0;return s.set(r,c),c+=r.length,a.setUint32(c,ba,!1),c+=4,c=_o(s,a,c,i),a.setUint32(c,yo(t,e),!1),c+=4,_o(s,a,c,o),s}async function vo(t,e){let n=new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",Ca(t,e).buffer));return wa(n)}function ei(t,e){if(t===null)return"null";if(t===!0)return"true";if(t===!1)return"false";if(typeof t=="string")return bo(t),JSON.stringify(t);if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError("Mutation input numbers must be finite.");return JSON.stringify(t)}if(typeof t!="object")throw new TypeError(`Mutation input contains unsupported ${typeof t}.`);if(e.has(t))throw new TypeError("Mutation input must not contain cycles.");e.add(t);try{if(Array.isArray(t)){if(Object.getOwnPropertySymbols(t).length>0)throw new TypeError("Mutation input must not contain symbol properties.");let o=[];for(let r=0;r<t.length;r+=1){if(!Object.hasOwn(t,r))throw new TypeError("Mutation input arrays must not be sparse.");o.push(ei(t[r],e))}return`[${o.join(",")}]`}let n=Object.getPrototypeOf(t);if(n!==Object.prototype&&n!==null)throw new TypeError("Mutation input objects must be plain JSON objects.");if(Object.getOwnPropertySymbols(t).length>0)throw new TypeError("Mutation input must not contain symbol properties.");let i=Object.entries(t);for(let[o]of i)bo(o);return i.sort(([o],[r])=>o<r?-1:o>r?1:0),`{${i.map(([o,r])=>{let s=Object.getOwnPropertyDescriptor(t,o);if(!s||s.get||s.set)throw new TypeError("Mutation input must not contain accessor properties.");return`${JSON.stringify(o)}:${ei(r,e)}`}).join(",")}}`}finally{e.delete(t)}}function bo(t){for(let e=0;e<t.length;e+=1){let n=t.charCodeAt(e);if(n>=55296&&n<=56319){let i=t.charCodeAt(e+1);if(!(i>=56320&&i<=57343))throw new TypeError("Mutation input strings must not contain lone surrogates.");e+=1}else if(n>=56320&&n<=57343)throw new TypeError("Mutation input strings must not contain lone surrogates.")}}function _o(t,e,n,i){return e.setBigUint64(n,BigInt(i.length),!1),n+=8,t.set(i,n),n+i.length}function wa(t){return btoa(String.fromCharCode(...t)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}var Y=3,Sa=2,Co=[Y,Sa],ce=5,ti=4,wo=[ce,ti],Oa=2,Pa=1,xl={operation_transport:[...Co],authorization_binding:[...wo],semantic_capabilities:[Oa,1],durable_mutation:[Pa]};function ni(t,e,n=[],i=2){let o={operation_transport:Y,authorization_binding:ce,semantic_capabilities:i},r=[...new Set(n)].filter(s=>s!==Y).sort((s,a)=>a-s);return r.length>0&&(o.operation_transport_recovery=r),(t.some(s=>Z(s,{action:"mutate"}))||e?.actions.some(s=>s!=="list"&&s!=="read")===!0)&&(o.durable_mutation=1),o}function mt(t){return Co.includes(t)}function Ro(t){return wo.includes(t)}var Aa=new TextEncoder().encode("mdbase-connect application installation id v2\0"),Ta=new TextEncoder().encode("mdbase-connect application authorization proof v4\0"),Ma=new TextEncoder().encode("mdbase-connect application authorization proof v5\0");async function Oo(t){let e=Kt(t),i=new Uint8Array(await crypto.subtle.digest("SHA-256",ke([Aa,K(e)]))).slice(0,16);return i[6]=i[6]&15|128,i[8]=i[8]&63|128,[yt(i.slice(0,4)),yt(i.slice(4,6)),yt(i.slice(6,8)),yt(i.slice(8,10)),yt(i.slice(10,16))].join("-")}function Po(t){let e=[Kt(t.installation_signing_public_key),Kt(t.grant_agreement_public_key),Kt(t.grant_signing_public_key)];if(e.some((c,l)=>e.slice(l+1).some(u=>Fa(c,u))))throw new Error("Application authorization keys must be distinct.");let n=ii(t.authorization_nonce),i=ii(t.code_challenge),o=t.contracts,r=o.operation_transport_recovery??[],s=t.requested_operations.some(c=>Z(c,{action:"mutate"}))||t.requested_files?.actions.some(c=>!["list","read"].includes(c))===!0;if(!Ro(t.protocol_version)||n.byteLength!==32||!/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)+$/u.test(t.application_declaration_id)||!/^[0-9a-f]{64}$/u.test(t.application_manifest_digest)||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/u.test(t.issued_at)||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/u.test(t.expires_at)||i.byteLength!==32||![o.operation_transport,o.authorization_binding,o.semantic_capabilities,o.durable_mutation??1].every(c=>Number.isInteger(c)&&c>0)||o.authorization_binding!==t.protocol_version||!mt(o.operation_transport)||t.protocol_version===ce&&o.operation_transport!==Y||r.some(c=>!mt(c)||c===o.operation_transport)||new Set(r).size!==r.length||t.protocol_version===ti&&r.length>0||r.length>0&&!s||(s?o.durable_mutation!==1:o.durable_mutation!==void 0)||t.requested_operations.length===0&&t.requested_files===void 0||new Set(t.requested_operations).size!==t.requested_operations.length||t.requested_operations.some(c=>!c||c.includes("\0"))||(t.flow==="authorization_code"?t.redirect_uri===void 0||t.state===void 0:t.flow!=="device_code"||t.redirect_uri!==void 0||t.state!==void 0))throw new Error("Application authorization binding is invalid.");ka(t.requested_files);let a=t.requested_operations.map(c=>K(new TextEncoder().encode(c)));return ke([t.protocol_version===ce?Ma:Ta,ie(t.protocol_version),K(Qt(t.application_id)),K(Qt(t.authorization_id)),K(new TextEncoder().encode(t.application_declaration_id)),K(Ao(t.application_manifest_digest)),K(Qt(t.application_installation_id)),...e.map(K),K(new TextEncoder().encode(t.flow)),K(n),K(new TextEncoder().encode(t.issued_at)),K(new TextEncoder().encode(t.expires_at)),So(t.redirect_uri),So(t.state),K(new TextEncoder().encode(t.code_challenge)),ie(o.operation_transport),...t.protocol_version===ce?[ie(r.length),...r.map(ie)]:[],ie(o.authorization_binding),ie(o.semantic_capabilities),Ia(o.durable_mutation),ie(a.length),...a,xa(t.requested_files),Ea(t.collection_id)])}function Ia(t){return t===void 0?new Uint8Array(1):ke([new Uint8Array([1]),ie(t)])}function ka(t){if(t!==void 0&&(t.actions.length===0||new Set(t.actions).size!==t.actions.length||t.scope.kind==="selected_folders"&&(t.scope.folders.length===0||new Set(t.scope.folders).size!==t.scope.folders.length||t.scope.folders.some(e=>!e||e.includes("\0")))))throw new Error("Application authorization file request is invalid.")}function xa(t){if(t===void 0)return new Uint8Array(1);let e=t.actions.map(n=>K(new TextEncoder().encode(n)));return ke([new Uint8Array([1]),ie(e.length),...e,K(new TextEncoder().encode(t.scope.kind)),...t.scope.kind==="selected_folders"?[ie(t.scope.folders.length),...t.scope.folders.map(n=>K(new TextEncoder().encode(n)))]:[]])}function So(t){return t===void 0?new Uint8Array(1):ke([new Uint8Array([1]),K(new TextEncoder().encode(t))])}function Ea(t){return t===void 0?new Uint8Array(1):ke([new Uint8Array([1]),K(Qt(t))])}function Kt(t){let e=ii(t);if(e.byteLength!==65||e[0]!==4)throw new Error("Application authorization public key is invalid.");return e}function ii(t){if(!/^[A-Za-z0-9_-]+$/u.test(t))throw new Error("Invalid base64url value.");let e=t.replaceAll("-","+").replaceAll("_","/"),n=e.padEnd(Math.ceil(e.length/4)*4,"="),i=Uint8Array.from(atob(n),o=>o.charCodeAt(0));if(qa(i)!==t)throw new Error("Non-canonical base64url value.");return i}function Qt(t){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu.test(t))throw new Error("Invalid UUID value.");let e=t.replaceAll("-","");return Ao(e)}function Ao(t){if(!/^[0-9a-f]+$/u.test(t)||t.length%2!==0)throw new Error("Invalid hexadecimal value.");return Uint8Array.from({length:t.length/2},(e,n)=>Number.parseInt(t.slice(n*2,n*2+2),16))}function K(t){return ke([ie(t.byteLength),t])}function ie(t){let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t,!1),e}function ke(t){let e=new Uint8Array(t.reduce((i,o)=>i+o.byteLength,0)),n=0;for(let i of t)e.set(i,n),n+=i.byteLength;return e}function qa(t){return btoa(String.fromCharCode(...t)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}function Fa(t,e){return t.byteLength===e.byteLength&&t.every((n,i)=>n===e[i])}function yt(t){return[...t].map(e=>e.toString(16).padStart(2,"0")).join("")}var To={id:"mdbase.record.created",version:"1.0.0",digest:"sha256:7f3bed6baa356ee9389e977ae7b77a102e2bee871a7c1d9f2026fc21cacdbfc9"};var Mo={id:"mdbase.runtime.timer.fired",version:"1.0.0",digest:"sha256:41105be7a7abf33b31ced47e1e1965242236e40ccaea286b959b0a8c591f5642"};var Io=28485,gt="P256-HKDF-SHA256-AES256GCM",Vt=1;var Da="contract-setup-v1",za="file-relay-v1",La="protocol-usage-report-v1",Ua="policy-freshness-lease-v1",Na=["application-authorization-v4","authorization-activation","encrypted-relay","policy-ack"];var ja=["durable-mutation-journal-v1","durable-file-lifecycle-v1","contract-metadata-read-v1"],Ba="candidate-b-activation-v1",Nl=[...Hn,...ja,"mutation-replay-after-credential-retirement-v1",Ba],Ka="application-declaration-evidence-v1",jl=[...Hn,Ka,...Na,Ua,"application-authorization-v5",Da,za,La,ro],oi=1;var ko="mdbase-authority-request-proof-v1",bt={version:"x-mdbase-proof-version",timestamp:"x-mdbase-proof-timestamp",nonce:"x-mdbase-proof-nonce",signature:"x-mdbase-proof-signature"};var _=class extends Error{constructor(n,i={}){super(n.message,i.cause===void 0?void 0:{cause:i.cause});this.problem=n;this.name="MdbaseConnectError",this.code=n.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 w(t,e,...[n={}]){let i=Me[t];return{problem_version:1,code:t,category:i.category,recovery:i.recovery,message:e,...n.details===void 0?{}:{details:n.details},...n.operationOutcome===void 0?{}:{operation_outcome:n.operationOutcome},...n.traceId===void 0?{}:{trace_id:n.traceId}}}function xo(t,e,n={}){return $n(t,e,{details:n.details,operation_outcome:n.operationOutcome,trace_id:n.traceId})}function d(t,e,...n){let i=n[0];return new _(w(t,e,...n),{status:i?.status,cause:i?.cause})}function L(t,e,n={}){let{status:i,cause:o,...r}=n;return new _($n(t,e,{details:r.details,operation_outcome:r.operationOutcome,trace_id:r.traceId}),{status:i,cause:o})}function je(t){let e=Va(t.diagnostics),n=Wa(t.diagnostics);if(e==="concurrent_modification"||e==="file_not_found"||e==="invalid_path")return w(e,n,{operationOutcome:"rejected"});if(e==="collection_version_unsupported"){let i=Ga(t.diagnostics);return w(e,n,{operationOutcome:"rejected",details:i})}return e!=="operation_invalid"?w(e,n,{operationOutcome:"rejected",details:{diagnostics:t.diagnostics}}):w(e,n,{operationOutcome:"rejected",details:{diagnostics:t.diagnostics,partial_result:t.result}})}function Va(t){let e=new Set(t.filter(n=>n.severity==="error").map(n=>n.code));if(["migration_required","migration_lossy","unsupported_version"].some(n=>e.has(n)))return"collection_version_unsupported";if(["invalid_config","invalid_configuration","missing_config","missing_spec_version"].some(n=>e.has(n)))return"collection_configuration_invalid";if(["duplicate_type","invalid_contract_definition","invalid_data_contract","invalid_type_definition","invalid_type_path"].some(n=>e.has(n)))return"collection_type_registry_invalid";if(["collection_invalid","collection_open_failed"].some(n=>e.has(n)))return"collection_invalid";for(let n of["concurrent_modification","file_not_found","invalid_path"])if(e.has(n))return n;return"operation_invalid"}function Ga(t){let e=t.map(n=>n.details).find(n=>Ha(n));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 Ha(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Eo(t){return t instanceof _&&t.retryable}function Wa(t){return t.filter(e=>e.severity==="error").map(e=>e.message).join(" ")||t.map(e=>e.message).join(" ")||"The collection rejected this operation."}var $a=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]),Ja=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),xe=class{state=Ja.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 n=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,n+=i,this.blockLength===64&&(this.compress(this.block),this.blockLength=0)}for(;n+64<=e.byteLength;)this.compress(e,n),n+=64;return n<e.byteLength&&(this.block.set(e.subarray(n),0),this.blockLength=e.byteLength-n),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,n=Math.floor(e/4294967296),i=e>>>0;return qo(this.block,56,n),qo(this.block,60,i),this.compress(this.block),[...this.state].map(o=>o.toString(16).padStart(8,"0")).join("")}compress(e,n=0){let i=this.words;for(let p=0;p<16;p+=1){let h=n+p*4;i[p]=(e[h]<<24|e[h+1]<<16|e[h+2]<<8|e[h+3])>>>0}for(let p=16;p<64;p+=1){let h=i[p-15],m=i[p-2],P=le(h,7)^le(h,18)^h>>>3,v=le(m,17)^le(m,19)^m>>>10;i[p]=i[p-16]+P+i[p-7]+v>>>0}let o=this.state[0],r=this.state[1],s=this.state[2],a=this.state[3],c=this.state[4],l=this.state[5],u=this.state[6],f=this.state[7];for(let p=0;p<64;p+=1){let h=le(c,6)^le(c,11)^le(c,25),m=c&l^~c&u,P=f+h+m+$a[p]+i[p]>>>0,v=le(o,2)^le(o,13)^le(o,22),b=o&r^o&s^r&s,C=v+b>>>0;f=u,u=l,l=c,c=a+P>>>0,a=s,s=r,r=o,o=P+C>>>0}this.state[0]=this.state[0]+o>>>0,this.state[1]=this.state[1]+r>>>0,this.state[2]=this.state[2]+s>>>0,this.state[3]=this.state[3]+a>>>0,this.state[4]=this.state[4]+c>>>0,this.state[5]=this.state[5]+l>>>0,this.state[6]=this.state[6]+u>>>0,this.state[7]=this.state[7]+f>>>0}};function le(t,e){return t>>>e|t<<32-e}function qo(t,e,n){t[e]=n>>>24,t[e+1]=n>>>16,t[e+2]=n>>>8,t[e+3]=n}function oe(t,e){return new Promise((n,i)=>{if(e?.aborted){i(e?.reason??new DOMException("Aborted","AbortError"));return}let o=()=>e?.removeEventListener("abort",s),r=setTimeout(()=>{o(),n()},t),s=()=>{clearTimeout(r),o(),i(e?.reason??new DOMException("Aborted","AbortError"))};e?.addEventListener("abort",s,{once:!0})})}var Gt=8,ri=10;function Ht(t){return t instanceof _&&t.code==="connector_busy"}async function Fo(t){if(!Ht(t.error)||t.completedRetries>=Gt)return{retried:!1};try{await Wt(t.completedRetries,t.signal)}catch(e){throw t.attempt.pendingMutation&&(t.knownRejectedMutationRetry||!t.attempt.resumingMutation)&&t.clearPending(t.attempt.requestId),e}return{retried:!0,result:await t.retry(t.attempt.pendingMutationRecord,t.knownRejectedMutationRetry||t.attempt.pendingMutation===!0&&!t.attempt.resumingMutation)}}async function Be(t){if(t.status!==502&&t.status!==503)return!1;let e=await t.clone().json().catch(()=>null);return e?.error==="connector_busy"||typeof e?.error=="object"&&e.error?.code==="connector_busy"}function Wt(t,e){return zo(Lo(50,800,t),e)}function Do(t,e){return zo(Lo(100,1e3,t-1),e)}async function zo(t,e){try{await oe(t,e)}catch(n){throw e?.aborted?e.reason instanceof _?e.reason:d("operation_cancelled","The operation was cancelled while waiting for connector capacity.",{operationOutcome:"not_sent",cause:n}):n}}function Lo(t,e,n){let i=Math.min(e,t*2**Math.max(0,n));return Math.max(1,Math.round(i*(.75+Math.random()*.5)))}var Uo=1024*1024,Ya=4,No=8,_t=3,si=64*1024*1024,jo=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,$t=/^sha256:[0-9a-f]{64}$/u;async function Bo(t,e,n){let i=new xe;for(let o=0;o<t.size;o+=Uo){ee(e);let r=new Uint8Array(await t.slice(o,o+Uo).arrayBuffer());i.update(r),n(Math.min(t.size,o+r.byteLength))}return t.size===0&&n(0),i.digestHex()}function Ko(t,e){if(t instanceof Blob)return e&&e!==t.type?t.slice(0,t.size,e):t;if(t instanceof ArrayBuffer)return new Blob([t],{type:e});let n=new Uint8Array(t.byteLength);return n.set(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),new Blob([n.buffer],{type:e})}function Qo(t){return t instanceof Blob?t.size:t.byteLength}async function Vo(t){return t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t}function ai(t=Ya){if(!Number.isInteger(t)||t<1||t>No)throw d("invalid_request",`File concurrency must be between 1 and ${No}.`);return t}function Go(t){if(!Number.isInteger(t)||t<1||t>1e3)throw d("invalid_request","File page size must be between 1 and 1000.");return t}function ci(t,e,n){if(t.protocol_version!==1||t.type!=="file_transfer"||t.transfer_id!==e||t.direction!==n||!Number.isSafeInteger(t.total_size)||t.total_size<0||!Array.isArray(t.received)||!Xa(t))throw d("invalid_operation_response","The authority returned an invalid file transfer session.");let i=t.strategy.kind==="framed_chunks"?t.strategy.chunk_size:t.strategy.kind==="object_put"?Math.max(1,t.total_size):t.strategy.part_size,o=t.strategy.kind==="object_put"?1:Math.ceil(t.total_size/i);if(new Set(t.received).size!==t.received.length||t.received.some(s=>!Number.isSafeInteger(s)||s<0||s>=o))throw d("invalid_operation_response","The authority returned invalid transfer progress.");let r=t.uploaded_parts??[];if(!Array.isArray(r)||r.some((s,a)=>!Number.isSafeInteger(s?.part_number)||s.part_number<1||s.part_number>o||typeof s.etag!="string"||s.etag.length===0||s.etag.length>255||a>0&&r[a-1].part_number>=s.part_number)||(t.strategy.kind==="object_multipart"?r.length!==t.received.length||r.some((s,a)=>s.part_number-1!==t.received[a]):r.length!==0))throw d("invalid_operation_response","The authority returned invalid uploaded part receipts.")}function li(t,e){let n=e.strategy.kind==="framed_chunks"?e.strategy.chunk_size:e.strategy.kind==="object_put"?Math.max(1,e.total_size):e.strategy.part_size,i=e.strategy.kind==="object_put"?1:Math.ceil(e.total_size/n);if(t?.protocol_version!==1||t.type!=="file_transfer_status"||t.transfer_id!==e.transfer_id||!["open","committed","aborted","expired"].includes(t.state)||!Array.isArray(t.received)||new Set(t.received).size!==t.received.length||t.received.some(r=>!Number.isSafeInteger(r)||r<0||r>=i)||!Number.isSafeInteger(t.received_bytes)||t.received_bytes<0||t.received_bytes>e.total_size||t.received.reduce((r,s)=>r+di(e.total_size,n,s),0)!==t.received_bytes)throw d("invalid_operation_response","The authority returned invalid transfer status.");let o=t.uploaded_parts;if(!Array.isArray(o)||o.some((r,s)=>!Number.isSafeInteger(r?.part_number)||r.part_number<1||r.part_number>i||typeof r.etag!="string"||r.etag.length===0||r.etag.length>255||s>0&&o[s-1].part_number>=r.part_number)||(e.strategy.kind==="object_multipart"?o.length!==t.received.length||o.some((r,s)=>r.part_number-1!==t.received[s]):o.length!==0))throw d("invalid_operation_response","The authority returned invalid uploaded part status.")}function Xa(t){return t.strategy.kind==="framed_chunks"?t.protection==="grant_aead_v1"&&Number.isSafeInteger(t.strategy.chunk_size)&&t.strategy.chunk_size>0:t.protection!=="transport_tls"?!1:t.strategy.kind==="object_put"?!0:Number.isSafeInteger(t.strategy.part_size)&&t.strategy.part_size>0}function di(t,e,n){return Math.min(e,Math.max(0,t-n*e))}async function Jt(t,e){for(let n=1;n<=ri;n+=1){ee(e);try{return await t()}catch(i){if(e?.aborted||n===ri||i instanceof _&&!i.retryable)throw i;await Do(n,e)}}throw new Error("Unreachable file chunk retry state.")}function ui(t,e,n,i,o,r){let s;try{s=new URL(t.url)}catch{throw d("invalid_operation_response","The authority returned an invalid object URL.")}if(t.protocol_version!==1||t.type!=="file_part"||t.transfer_id!==e||t.part_index!==n||t.offset!==i||t.content_length!==o||typeof t.method!="string"||t.method.toUpperCase()!==r||!t.headers||typeof t.headers!="object"||Array.isArray(t.headers)||Object.values(t.headers).some(a=>typeof a!="string")||typeof t.expires_at!="string"||!Number.isFinite(Date.parse(t.expires_at))||s.protocol!=="https:"&&!(s.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(s.hostname))||s.username||s.password)throw d("invalid_operation_response","The authority returned an invalid prepared file part.")}function pi(t){let e=new Headers;for(let[n,i]of Object.entries(t))["host","content-length"].includes(n.toLowerCase())||e.set(n,i);return e}async function Ho(t,e,n){let i=new Array(t),o=0;return await Promise.all(Array.from({length:Math.min(t,e)},async()=>{for(;o<t;){let r=o;o+=1,i[r]=await n(r)}})),i}function ee(t){if(t?.aborted)throw d("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:t.reason})}function _e(t){return t instanceof _?t:typeof DOMException<"u"&&t instanceof DOMException&&t.name==="AbortError"?d("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:t}):d("temporarily_unavailable","The file transfer could not be completed.",{cause:t})}var fi=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu;function hi(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.file_id=="string"&&fi.test(e.file_id)&&typeof e.path=="string"&&typeof e.revision=="string"&&typeof e.content_digest=="string"&&$t.test(e.content_digest)&&Number.isSafeInteger(e.size)&&e.size>=0&&["image","audio","video","pdf","other"].includes(e.media_class)&&typeof e.modified_at=="string"&&(e.media_type===void 0||typeof e.media_type=="string")}function fe(t){if(!hi(t))throw d("invalid_operation_response","The authority returned an invalid file descriptor.");return{fileId:t.file_id,path:t.path,revision:t.revision,contentDigest:t.content_digest,size:t.size,...t.media_type?{mediaType:t.media_type}:{},mediaClass:t.media_class,modifiedAt:t.modified_at}}var Za=Object.entries({path:Q,from:Q,to:Q,revision:Q,previous_revision:Q,types:mi,previous_types:mi,changed_fields:mi,body_changed:nc,before:gi,after:gi}),ec=Object.entries({path:Q,name:Q,revision:Q,previous_revision:Q,reason:Q}),tc=Object.entries({previous_path:Q,revision:Q});function bi(t){let e={cursor:t.cursor,type:t.type,occurredAt:t.occurred_at,payload:t.payload,raw:t},n=a=>({...e,kind:"unknown",reason:a}),i=Object.hasOwn(Xn,t.type)?Xn[t.type]:void 0;if(!i)return n("unrecognized_type");let o=t.payload;if(!gi(o))return n("invalid_payload");if(i.startsWith("record.")){if(!yi(o,Za))return n("invalid_payload");let a=o,c={...a.revision==null?{}:{revision:a.revision},...a.previous_revision==null?{}:{previousRevision:a.previous_revision},...a.types==null?{}:{types:a.types},...a.previous_types==null?{}:{previousTypes:a.previous_types},...a.changed_fields==null?{}:{changedFields:a.changed_fields},...a.body_changed==null?{}:{bodyChanged:a.body_changed},...a.before==null?{}:{before:a.before},...a.after==null?{}:{after:a.after}};if(i==="record.renamed")return Q(o.from)&&Q(o.to)?{...e,...c,kind:i,from:o.from,to:o.to}:n("invalid_payload");if(i==="record.created"||i==="record.updated"||i==="record.deleted")return Q(o.path)?{...e,...c,kind:i,path:o.path}:n("invalid_payload")}if(i==="file.put")return hi(o.file)?{...e,kind:i,file:fe(o.file)}:n("invalid_payload");if(i==="file.removed"){if(!Q(o.file_id)||!yi(o,tc))return n("invalid_payload");let a=o;return{...e,kind:i,fileId:o.file_id,...a.previous_path==null?{}:{previousPath:a.previous_path},...a.revision==null?{}:{revision:a.revision}}}if(!yi(o,ec))return n("invalid_payload");let r=o;if(i==="gap")return{...e,kind:i,...r.reason==null?{}:{reason:r.reason}};let s={...r.revision==null?{}:{revision:r.revision},...r.previous_revision==null?{}:{previousRevision:r.previous_revision}};if(i==="file.changed")return Q(o.path)?{...e,...s,kind:i,path:o.path}:n("invalid_payload");if(i==="schema.changed"||i==="config.changed"||i==="contract.changed"||i==="view.changed")return{...e,...s,kind:i,...r.path==null?{}:{path:r.path},...r.name==null?{}:{name:r.name}};throw new Error(`Unhandled change kind: ${i}`)}function Wo(t){return{events:t.reset?[{kind:"reset",type:"reset",cursor:t.cursor,occurredAt:null,payload:{},raw:t}]:t.events.map(bi),cursor:t.cursor,hasMore:t.has_more,reset:t.reset}}function $o(t){return t.kind==="schema.changed"||t.kind==="config.changed"||t.kind==="contract.changed"||t.kind==="view.changed"||t.kind==="gap"||t.kind==="reset"||t.kind==="unknown"}function Q(t){return typeof t=="string"}function nc(t){return typeof t=="boolean"}function mi(t){return Array.isArray(t)&&t.every(Q)}function gi(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function yi(t,e){return e.every(([n,i])=>t[n]==null||i(t[n]))}var Ee=["describe","changes","read","query"];function V(t){let e=t.capabilities===void 0?1:t.capabilities?.contract_version;return e!==1&&e!==2&&Ke("Unsupported declared capability contract version."),e}function Ke(t){throw d("invalid_application_manifest",t,{details:{issues:[{path:"/requirements/capabilities",keyword:"authorizationSelection",message:t,params:{}}]}})}function re(t,e){if(e.operations!==void 0&&e.capabilities!==void 0&&Ke("Specify operations or capabilities, not both."),e.operations!==void 0&&V(t)!==1&&Ke("Exact operations authorization is only supported for legacy v1 declarations."),e.capabilities!==void 0){let n=new Set([...t.capabilities?.required??[],...t.capabilities?.optional??[]]);e.capabilities.some(i=>!n.has(i)||X(V(t),i)===void 0)&&Ke("Authorization can only include capabilities declared by the application.")}}function Jo(t){let e=t.capabilities;return e?[...new Set([...e.required,...e.optional??[]].flatMap(n=>X(e.contract_version,n)??[]))]:[...Ee]}function _i(t,e){let{requirements:n}=t;if(re(n,e),V(n)===1){if(e.operations!==void 0)return[...new Set(e.operations)];if(e.capabilities===void 0)return[...Ee]}let i=n.capabilities,r=[...i?.required??[],...e.capabilities??i?.optional??[]].flatMap(a=>X(V(n),a)??[]),s=(t.provisions?.type_packs.length??0)>0||(t.provisions?.configuration?.length??0)>0;return[...new Set([...r,...V(n)===2&&s?Lt:[]])]}function Yt(t,e){return[...t.capabilities?.required??[],...t.capabilities?.optional??[]].filter(n=>(X(V(t),n)??[]).every(i=>e.includes(i)))}function vi(t){let e=t.files;if(e)return V(t)===1?((!("actions"in e)||"required"in e||"optional"in e)&&Ke("Legacy file declarations must use exact files.actions."),{actions:[...e.actions],scope:structuredClone(e.scope)}):("actions"in e&&Ke("V2 file declarations must use required/optional file actions."),fo(e))}function Xt(t,e,n){let i=new Set(t.required),o=[...new Set([...t.required,...t.optional??[]])],r={};for(let s of o)r[s]=ic(s,i.has(s),n,t.contract_version,e);return{contractVersion:t.contract_version,values:r,requiredAvailable:t.required.every(s=>r[s]?.state==="available")}}function ic(t,e,n,i,o){let r=X(i,t)??[],s=r.filter(c=>!n.operations.includes(c)),a={id:t,requirement:e?"required":"optional",operations:r,missingOperations:s,evidence:[{source:"application",fact:`${e?"Required":"Optional"} in capability contract v${i}.`}]};if(s.length>0)return{...a,state:"requires_authorization",evidence:[...a.evidence,{source:"authorization",fact:`Missing ${s.join(", ")}.`}],reason:"The current grant does not include every operation for this capability."};if(n.scope.access!=="full_collection")return{...a,state:"requires_authorization",reason:"The current grant uses legacy contract scope and must be reauthorized for the entire collection.",evidence:[...a.evidence,{source:"authorization",fact:"Legacy contract scope is compatibility evidence, not active data authority."}]};if(i===1&&t.startsWith("files.")){let c=t.slice(6);if(!n.fileCapability?.actions.includes(c))return{...a,state:n.fileCapability?"requires_authorization":"unsupported",reason:n.fileCapability?`The current file grant does not include ${c}.`:"This connection has no file capability."}}return i===1&&t==="notifications.background-delivery"&&(o.notifications?.criteria.length??0)===0?{...a,state:"requires_setup",reason:"The application manifest declares no notification criteria."}:{...a,state:"available",evidence:[...a.evidence,{source:"authorization",fact:r.length>0?`Granted operations: ${r.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."}],...t==="offline.replica"||i===1&&t==="sync.offline-replica"?{details:{durability:"device",writes:"queued",authority:n.authority.kind}}:{},...i===1&&t==="notifications.background-delivery"?{details:{delivery:"authority",payload:"opaque"}}:{}}}var Qe=3e4,Ci=1e4,oc=10*6e4,rc=12e4,sc=6e4;function Ve(t={}){return{requestMs:vt(t.requestMs,Qe,"requestMs"),watchStartMs:vt(t.watchStartMs,Ci,"watchStartMs"),fileIndexMs:vt(t.fileIndexMs,oc,"fileIndexMs"),uploadMs:vt(t.uploadMs,rc,"uploadMs"),syncMs:vt(t.syncMs,sc,"syncMs")}}function de(t,e){return{...t,signal:e.signal,...e.deadline===null?{}:{deadlineUnixMs:e.deadline}}}function ve(t={},e=Qe,n=Date.now){let i=t.timeoutMs===void 0?e:t.timeoutMs,o=i===null?null:ac(i),r=new AbortController,s=o===null?null:n()+o,a=()=>r.abort(t.signal?.reason);t.signal?.aborted?a():t.signal?.addEventListener("abort",a,{once:!0});let c=o===null?void 0:setTimeout(()=>r.abort(d("timeout","The operation exceeded its request deadline.",{operationOutcome:"not_sent"})),o),l=!1;return{signal:r.signal,deadline:s,remainingMs:()=>s===null?null:Math.max(0,s-n()),dispose:()=>{l||(l=!0,c!==void 0&&clearTimeout(c),t.signal?.removeEventListener("abort",a))}}}async function k(t,e,n){let i=ve(t,e),o,r=new Promise((a,c)=>{o=c}),s=()=>o?.(te(i.signal));i.signal.addEventListener("abort",s,{once:!0});try{if(i.signal.aborted)throw te(i.signal);return await Promise.race([n(i),r])}finally{i.signal.removeEventListener("abort",s),i.dispose()}}async function W(t,e,n){let i=ve(t,e);try{if(i.signal.aborted)throw te(i.signal);return await n(i)}finally{i.dispose()}}function te(t){return t.reason instanceof _?t.reason:d("operation_cancelled","The operation was cancelled before it changed the collection.",{operationOutcome:"not_sent",cause:t.reason})}function ac(t){if(!Number.isSafeInteger(t)||t<=0)throw new TypeError("timeoutMs must be a positive safe integer or null.");return t}function vt(t,e,n){if(t===void 0)return e;if(t===null)return null;if(!Number.isSafeInteger(t)||t<=0)throw new TypeError(`${n} must be a positive safe integer or null.`);return t}async function Ct(t,e){let n=typeof window>"u"?void 0:globalThis.performance,i=n?.now();try{return await e()}finally{if(n&&i!==void 0)try{let o=`mdbase:startup:${t}`;n.clearMeasures(o),n.measure(o,{start:i,end:n.now()})}catch{}}}async function wi(t){let{collectionId:e,readiness:n,contracts:i,connection:o,controller:r,options:s,requestMs:a,isCurrent:c,publish:l}=t,u=()=>r.abort(s?.signal?.reason);s?.signal?.aborted?u():s?.signal?.addEventListener("abort",u,{once:!0});try{let f=await Ct("contracts",()=>k({...s,signal:r.signal},a,h=>o.describe(h)));if(!c())return!1;if(!f.ok){let h=["access_denied","collection_access_denied","insufficient_access","not_authorized","authorization_expired","application_declaration_mismatch"].includes(f.problem.code);return n.contracts={state:h?"requires_authorization":"temporarily_unavailable",missing:[],evidence:[{source:"runtime",fact:f.problem.message}]},l(h?{status:"authorization_required"}:{status:"blocked",problem:f.problem}),!1}if(f.value.collectionId!==e)return n.contracts={state:"temporarily_unavailable",missing:[],evidence:[]},l({status:"blocked",problem:{code:"collection_not_ready",message:"Description belongs to a different collection."}}),!1;let p=i.filter(h=>!f.value.contracts.some(m=>m.id===h.id&&m.version===h.version&&m.digest===h.digest));if(n.contracts={state:p.length?"requires_setup":"verified",missing:p,evidence:[{source:"authority",fact:"Exact contract ID, version and digest checked by live describe for this collection."}]},p.length)return l({status:"blocked",problem:{code:"collection_not_ready",message:"The collection is missing required exact contracts."}}),!1}catch(f){if(!c())return!1;if(!(f instanceof _))throw f;return n.contracts={state:"temporarily_unavailable",missing:[],evidence:[{source:"runtime",fact:f.problem.message}]},l({status:"blocked",problem:f.problem}),!1}finally{s?.signal?.removeEventListener("abort",u)}return!0}function Yo(t,e,n){let i=structuredClone(t);return i.setup.state!=="not_required"&&i.setup.state!=="current"&&(i.setup.state=e==="ready"?n==="cached"?"cached":"current":e==="setup_review_required"?"review_required":e==="authorization_required"?"requires_authorization":e==="blocked"?"blocked":"checking",i.setup.evidence=[{source:e==="ready"&&n==="cached"?"runtime":"authority",fact:`Collection setup verification: ${i.setup.state}.`}]),i}function Xo(t,e,n,i){return{collectionId:e,info:n,capabilities:Xt(t.requirements.capabilities,t,n),...t.requirements?.capabilities?.contract_version===2?{readiness:lc(t,n)}:{},connections:i}}function Zt(t,e){return`mdbase-application-session:v1:${t.id}:${e}`}function Ri(t){return JSON.stringify({capabilities:t.requirements?.capabilities,requirements:t.requirements?.configuration??[],provisions:t.provisions??{}})}function Zo(t,e){return t.requirements?.access==="full_collection"&&e.scope.access==="full_collection"&&e.scope.contracts.length===0}function er(t){let e={};for(let n of t.typePacks){let i=Object.fromEntries(n.resources.filter(o=>o.action==="conflict"&&o.mode==="managed"&&o.currentDigest!==void 0&&o.installedDigest===void 0).map(o=>[o.target,o.currentDigest]));Object.keys(i).length>0&&(e[n.desired.id]=i)}return e}function tr(t,e,n,i){return{applicationId:e,declarationDigest:n,requirements:{configuration:t.requirements?.configuration??[]},provisions:{configuration:t.provisions?.configuration??[],typePacks:t.provisions?.type_packs??[]},...i?{typePackAdoptions:i}:{}}}function cc(t,e){if(!e||t.kind!==e.kind)return!1;if(t.kind==="collection"||e.kind==="collection")return!0;let n=[...new Set(t.folders)].sort(),i=[...new Set(e.folders)].sort();return JSON.stringify(n)===JSON.stringify(i)}function lc(t,e){let n=t.requirements?.files,i=n&&"required"in n?n:void 0,o=!i||cc(i.scope,e.fileCapability?.scope),r=u=>u.filter(f=>!o||!e.fileCapability?.actions.includes(f)),s=r(i?.required??[]),a=r(i?.optional??[]),c=t.requirements?.contracts??[],l=(t.provisions?.type_packs.length??0)>0||(t.provisions?.configuration?.length??0)>0;return{files:{state:i?s.length?"requires_authorization":"available":"not_required",missingRequiredActions:s,missingOptionalActions:a,scopeMatches:o,evidence:[{source:"authorization",fact:"Compared exact file actions and folder scope with connection.info().fileCapability."}]},contracts:{state:c.length?"checking":"not_required",missing:[],evidence:[]},setup:{state:l?"checking":"not_required",evidence:[]},notifications:{state:t.notifications?.criteria.length?"requires_registration":"not_required",registration:"unverified",evidence:[{source:"runtime",fact:"The connection API exposes registration commands but no current delivery-registration query. Manifest criteria do not prove approval or delivery registration."}]}}}var en=["access_denied","access_paused","application_declaration_mismatch","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"],Ge=Object.keys(Me),qe=["discovery_failed","invalid_operation_response","invalid_application_manifest","invalid_request","manifest_load_failed","rate_limited","temporarily_unavailable","timeout"],Ce=[...qe,"access_denied","application_declaration_mismatch","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","legacy_scope_reauthorization_required","scope_denied","reconnect_required","token_exchange_failed","transport_protocol_incompatible"],wt=[...qe,"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"],Si=["connector_offline","connector_upgrade_required","invalid_operation_response","not_authorized","operation_failed","temporarily_unavailable","timeout"],Ed=[...Ce,"collection_not_ready","collection_not_selected","operation_cancelled","session_destroyed","session_not_started","session_starting","unknown_collection"],dc=["collection_configuration_invalid","collection_invalid","collection_type_registry_invalid","collection_version_unsupported"],Rt=[...en,...dc],ue=[...Rt,"file_not_found","invalid_path","operation_invalid"],pe=[...ue,"cursor_capacity_exhausted","generation_expired","invalid_read_cursor","query_snapshot_changed","sandbox_unsupported"],G=[...ue,"concurrent_modification","invalid_preflight","pending_mutation_unresolved"],tn=[...Rt,"change_cursor_reset"],we=[...G,"type_pack_provision_failed"];function R(t,e=[]){return{ok:!0,value:t,diagnostics:e}}function g(t){return{ok:!1,problem:t}}async function I(t,e){try{return R(await t())}catch(n){if(!(n instanceof _))throw n;let i=n.problem;return i.code==="unknown"||e.includes(i.code)?g(i):g(xo(i.code,i.message,{details:i.details,operationOutcome:i.operation_outcome,traceId:i.trace_id}))}}function se(t){let e=new Uint8Array(t);return crypto.getRandomValues(e),he(e)}var nr=32768;function he(t){let e="";for(let o=0;o<t.length;o+=nr)e+=String.fromCharCode.apply(null,t.subarray(o,o+nr));let n=btoa(e).replaceAll("+","-").replaceAll("/","_"),i=n.length;for(;i>0&&n.charCodeAt(i-1)===61;)i-=1;return n.slice(0,i)}function nn(t){let e=t.replaceAll("-","+").replaceAll("_","/").padEnd(Math.ceil(t.length/4)*4,"="),n=atob(e),i=new Uint8Array(new ArrayBuffer(n.length));for(let o=0;o<n.length;o+=1)i[o]=n.charCodeAt(o);return i}var uc="mdbase-connect-keys",Re="grant-keys",Pi=18446744073709551615n,pc="mdbase-connect relay request key v1",fc="mdbase-connect relay response key v1",ir=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,He=class{database=null;async create(e){let n=await sr(e),i=await this.open();return await rr(i,o=>o.add({...n,counter:"0"})),n}async get(e){let n=await this.open(),i=await bc(n.transaction(Re).objectStore(Re).get(e));return i?{handle:i.handle,agreementPrivateKey:i.agreementPrivateKey,agreementPublicKey:i.agreementPublicKey,signingPrivateKey:i.signingPrivateKey,signingPublicKey:i.signingPublicKey}:null}async nextCounter(e){let n=await this.open();return new Promise((i,o)=>{let r=n.transaction(Re,"readwrite"),s=r.objectStore(Re),a=s.get(e),c=null;a.onerror=()=>o(a.error),a.onsuccess=()=>{let l=a.result;if(!l){r.abort(),o(new q("missing_grant_key","The encrypted grant key is unavailable."));return}let u=BigInt(l.counter)+1n;if(u>Pi){r.abort(),o(new q("counter_exhausted","The encrypted grant must be authorized again."));return}c=u.toString(),s.put({...l,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 n=await this.open();await rr(n,i=>i.delete(e))}open(){if(typeof indexedDB>"u")throw new q("key_storage_unavailable","Encrypted relay authorization requires browser IndexedDB or an injected grant key store.");return this.database||(this.database=new Promise((e,n)=>{let i=indexedDB.open(uc,1);i.onupgradeneeded=()=>{i.result.objectStoreNames.contains(Re)||i.result.createObjectStore(Re,{keyPath:"handle"})},i.onerror=()=>n(i.error),i.onsuccess=()=>e(i.result)})),this.database}},We=class{records=new Map;sequence=Promise.resolve();async create(e){if(this.records.has(e))throw new Error(`Grant key already exists: ${e}`);let n=await sr(e);return this.records.set(e,{...n,counter:"0"}),n}async get(e){let n=this.records.get(e);return n?{handle:n.handle,agreementPrivateKey:n.agreementPrivateKey,agreementPublicKey:n.agreementPublicKey,signingPrivateKey:n.signingPrivateKey,signingPublicKey:n.signingPublicKey}:null}nextCounter(e){let n,i,o=new Promise((r,s)=>{n=r,i=s});return this.sequence=this.sequence.then(()=>{let r=this.records.get(e);if(!r)throw new q("missing_grant_key","The encrypted grant key is unavailable.");let s=BigInt(r.counter)+1n;if(s>Pi)throw new q("counter_exhausted","The encrypted grant must be authorized again.");r.counter=s.toString(),n(r.counter)}).catch(r=>{i(r)}),o}async delete(e){this.records.delete(e)}};async function on(t,e,n,i){let o=await hc(t,e,n),r=i.timestamp??Math.floor(Date.now()/1e3),s=i.nonce??crypto.randomUUID(),a=await Ai({...i,timestamp:r,nonce:s}),c=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},o.signingPrivateKey,new TextEncoder().encode(a));return{[bt.version]:String(oi),[bt.timestamp]:String(r),[bt.nonce]:s,[bt.signature]:he(new Uint8Array(c))}}async function Ai(t){let e=t.method.toUpperCase(),n=await or(t.body??""),i=await or(t.credential);for(let o of[e,t.target,String(t.timestamp),t.nonce])if(!o||o.includes(`
2
- `)||o.includes("\r"))throw new q("invalid_proof_input","Authority request proof metadata is invalid.");return[ko,oi,e,t.target,n,i,t.timestamp,t.nonce].join(`
3
- `)}async function me(t,e,n,i,o,r=crypto.randomUUID(),s){if(ye(n.encryption),s!==void 0&&(!Number.isSafeInteger(s)||s<=0))throw new q("invalid_deadline","The operation deadline is invalid.");let a=await ar(t,e,n.encryption.application_agreement_public_key),c=await t.nextCounter(e),l={binding:n,protocolVersion:Y,requestId:r,operation:i,counter:c},u=await cr(a.agreementPrivateKey,n,l.protocolVersion,"request"),f=new TextEncoder().encode(JSON.stringify(o??{})),p=await crypto.subtle.encrypt({name:"AES-GCM",iv:ur(c),additionalData:new TextEncoder().encode(dr(l,"request")),tagLength:128},u,f);return{type:"encrypted_operation_request",...mc(l),...s===void 0?{}:{deadline_unix_ms:s},ciphertext:he(new Uint8Array(p))}}async function $e(t,e,n,i,o){if(!yc(i,o))throw new q("invalid_encrypted_response","Encrypted response metadata does not match its request.");let r=await ar(t,e,n.encryption.application_agreement_public_key),s={binding:n,protocolVersion:i.protocol_version,requestId:i.request_id,operation:i.operation,counter:i.counter},a=await cr(r.agreementPrivateKey,n,i.protocol_version,"response");try{let c=await crypto.subtle.decrypt({name:"AES-GCM",iv:ur(i.counter),additionalData:new TextEncoder().encode(dr(s,"response")),tagLength:128},a,pr(o.ciphertext)),l=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(c));if(l?.ok===!0&&"result"in l||l?.ok===!1&&ht(l.problem))return l;throw new Error("invalid response body")}catch(c){throw c instanceof q?c:new q("encrypted_response_rejected","The encrypted connector response could not be authenticated.")}}var q=class extends Error{constructor(n,i){super(i);this.code=n}code};async function sr(t){let e=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"]),n=he(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"]),s=he(new Uint8Array(await crypto.subtle.exportKey("raw",r.publicKey))),a=await crypto.subtle.exportKey("pkcs8",r.privateKey),c=await crypto.subtle.importKey("pkcs8",a,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]);return{handle:t,agreementPrivateKey:o,agreementPublicKey:n,signingPrivateKey:c,signingPublicKey:s}}async function ar(t,e,n){let i=await t.get(e);if(!i||i.agreementPublicKey!==n)throw new q("missing_grant_key","The encrypted grant key is unavailable or does not match the grant.");return i}async function hc(t,e,n){let i=await t.get(e);if(!i||i.signingPublicKey!==n)throw new q("missing_grant_key","The remote authority signing key is unavailable or does not match the grant.");return i}async function cr(t,e,n,i){let o=await St(t,e.encryption.connector_agreement_public_key),r=await crypto.subtle.importKey("raw",o,"HKDF",!1,["deriveKey"]),s=new TextEncoder().encode(lr(e,n)),a=await crypto.subtle.digest("SHA-256",s);return crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:a,info:new TextEncoder().encode(i==="request"?pc:fc)},r,{name:"AES-GCM",length:256},!1,i==="request"?["encrypt"]:["decrypt"])}async function St(t,e){try{let n=await crypto.subtle.importKey("raw",gc(Oi(e)),{name:"ECDH",namedCurve:"P-256"},!1,[]);return await crypto.subtle.deriveBits({name:"ECDH",public:n},t,256)}catch{throw new q("invalid_public_key","The connector relay public key is invalid.")}}function lr(t,e){let n=t.encryption;return["mdbase-connect",e,n.suite,t.grantId,t.applicationId,n.connector_id,n.collection_id,n.scope_epoch,n.key_id].join("|")}function dr(t,e){return[lr(t.binding,t.protocolVersion),t.requestId,e,t.operation,t.counter].join("|")}function mc(t){let e=t.binding.encryption;return{protocol_version:t.protocolVersion,suite:gt,request_id:t.requestId,grant_id:t.binding.grantId,application_id:t.binding.applicationId,connector_id:e.connector_id,collection_id:e.collection_id,operation:t.operation,scope_epoch:e.scope_epoch,key_id:e.key_id,counter:t.counter}}function yc(t,e){return e.type==="encrypted_operation_response"&&typeof e.ciphertext=="string"&&t.protocol_version===e.protocol_version&&t.suite===e.suite&&t.request_id===e.request_id&&t.grant_id===e.grant_id&&t.application_id===e.application_id&&t.connector_id===e.connector_id&&t.collection_id===e.collection_id&&t.operation===e.operation&&t.scope_epoch===e.scope_epoch&&t.key_id===e.key_id&&t.counter===e.counter}function ye(t){if(t.protocol_version!==Vt||t.suite!==gt||!Number.isSafeInteger(t.scope_epoch)||t.scope_epoch<=0||typeof t.key_id!="string"||t.key_id.length===0||t.key_id.length>200||t.key_id.includes("|"))throw new q("unsupported_encryption","The grant uses an unsupported relay encryption profile.");if(typeof t.connector_id!="string"||!ir.test(t.connector_id)||typeof t.collection_id!="string"||!ir.test(t.collection_id))throw new q("unsupported_encryption","The grant uses invalid encrypted relay identities.");Oi(t.application_agreement_public_key),Oi(t.connector_agreement_public_key)}function ur(t){let e=BigInt(t);if(e<=0n||e>Pi||e.toString()!==t)throw new q("invalid_counter","The encrypted relay counter is invalid.");let n=new Uint8Array(new ArrayBuffer(12));return new DataView(n.buffer).setBigUint64(4,e,!1),n}async function or(t){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return he(new Uint8Array(e))}function pr(t){if(!/^[A-Za-z0-9_-]+$/.test(t))throw new q("invalid_base64","Encrypted relay data is malformed.");return nn(t)}function Oi(t){let e=pr(t);if(e.length!==65||e[0]!==4)throw new q("invalid_public_key","Encrypted relay public keys must be uncompressed P-256 points.");return e}function gc(t){return Uint8Array.from(t).buffer}function bc(t){return new Promise((e,n)=>{t.onerror=()=>n(t.error),t.onsuccess=()=>e(t.result)})}function rr(t,e){return new Promise((n,i)=>{let o=t.transaction(Re,"readwrite"),r=e(o.objectStore(Re));r.onerror=()=>i(r.error),o.onerror=()=>i(o.error),o.onabort=()=>i(o.error??new Error("Grant key transaction aborted.")),o.oncomplete=()=>n()})}function Se(t){return{...t,credentials:"omit",targetAddressSpace:"loopback"}}async function Ot(){if(typeof navigator>"u"||!navigator.permissions?.query)return null;try{return(await navigator.permissions.query({name:"local-network-access"})).state}catch{return null}}async function Je(t){let{status:e}=t;return e===404||e===405||e===426||e>=500?!0:e===403&&(await t.clone().text()).trim()===""}function fr(t,e){return Z(t,e)}function hr(t,e){if(t.deadline_unix_ms===e)return t;let{deadline_unix_ms:n,...i}=t;return{...i,...e===void 0?{}:{deadline_unix_ms:e}}}function Pt(t){return[...new Set(t)]}function mr(t,e){return t.grantId||e.grantId?t.grantId===e.grantId&&t.keyHandle===e.keyHandle&&t.encryption?.key_id===e.encryption?.key_id:t.accessToken===e.accessToken}function Fe(t){if(t?.aborted)throw d("operation_cancelled","The operation was cancelled before it changed the collection.",{operationOutcome:"not_sent",cause:t.reason})}function rn(t,e,n,i){return t instanceof _?t:e?.aborted?n?J(n,t):e.reason instanceof _?e.reason:d("operation_cancelled","The operation was cancelled before it changed the collection.",{operationOutcome:"not_sent",cause:t}):n?J(n,t):t instanceof TypeError?d(i,i==="hosted_provider_unavailable"?"The hosted collection provider is unavailable.":"The Connect relay is unavailable.",{cause:t}):t instanceof Error?t:new Error(String(t))}function yr(t){return L(t.code==="unknown"?t.server_code:t.code,t.message,{details:t.details,operationOutcome:t.operation_outcome??"rejected",traceId:t.trace_id})}function gr(t,e,n,i,o){return fetch(t,{method:"POST",headers:{authorization:`Bearer ${e}`,"content-type":"application/json",...n},body:i,signal:o})}function Mi(t,e){return e?.aborted===!0||t instanceof _&&t.code==="operation_cancelled"}function br(t,e){if(e.dryRun!==!0||e.wouldRename!==!0||e.from!==t.from||e.to!==t.to)throw d("invalid_preflight","The rename preview does not match this mutation. Run the preview again.")}function _r(t,e){if(e.dryRun!==!0||e.wouldDelete!==!0||e.path!==t.path)throw d("invalid_preflight","The delete preview does not match this mutation. Run the preview again.")}function vr(t,e){if(t.updateRefs===!1)return{affectedRecords:0,totalUnits:1,warnings:0};let n=e.referencesAffected??[];return{affectedRecords:new Set(n.map(i=>i.path)).size,totalUnits:1+n.length,warnings:e.warnings?.length??0}}function Cr(t){return{affectedRecords:new Set((t.brokenLinks??[]).map(e=>e.path)).size,totalUnits:1,warnings:0}}async function wr(t,e){return vo(t,e??{})}function Rr(t){return JSON.stringify(Ti(t))}function Ti(t){return Array.isArray(t)?t.map(e=>Ti(e)):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[n])=>e<n?-1:e>n?1:0).map(([e,n])=>[e,Ti(n)])):t}function J(t,e){return d("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:t},cause:e})}function sn(t,e){let n=F(t.getItem(`${e}:connections`));return n?.version===1&&Array.isArray(n.collectionIds)&&n.collectionIds.every(i=>typeof i=="string")?n.collectionIds:[]}function Sr(t,e,n){Pr(t,e,[...sn(t,e),n])}function Or(t,e,n){Pr(t,e,sn(t,e).filter(i=>i!==n))}function Pr(t,e,n){t.setItem(`${e}:connections`,JSON.stringify({version:1,collectionIds:[...new Set(n)]}))}function Ar(t,e){let n=t instanceof URL?t.href:t??vc(),i=typeof n=="string"?n:n.distribution==="portable"?`bundle:${n.id}:${wc(n)}`:`bundle:${n.id}`,o=e===void 0?typeof n!="string"&&n.distribution==="portable"?"":Cc():String(e);return{manifest:n,manifestSource:i,redirectUri:o}}async function ae(t,e,n,i){try{return await fetch(t,e)}catch(o){throw d(n,i,{cause:o})}}async function E(t,e,n){let i;try{i=await t.text()}catch(o){throw L(e,n,{status:t.status,cause:o})}if(i.trim()==="")throw L(e,n,{status:t.status});try{return JSON.parse(i)}catch(o){throw L(e,n,{status:t.status,cause:o})}}function Tr(t){let e=new URL(t);if(e.protocol!=="http:"||!["127.0.0.1","[::1]"].includes(e.hostname)||e.username||e.password||e.pathname!=="/"||e.search||e.hash)throw d("invalid_loopback_url","loopbackUrl must be an HTTP origin on 127.0.0.1 or ::1.");return e.origin}async function At(){let t=se(32),e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return{verifier:t,challenge:he(new Uint8Array(e))}}function z(t,e,n,i){return L(Tt(t)??t?.error?.code??e,t?.error_description??t?.error?.message??n,{status:i,details:t?.error?.details,operationOutcome:t?.error?.operation_outcome,traceId:t?.error?.trace_id})}function Tt(t){return typeof t?.error=="string"?t.error:void 0}function Mt(t,e){if(!t||typeof t!="object"||Array.isArray(t)||typeof e!="string")return!1;let n=t;if(typeof n.operations_url!="string"||typeof n.sync_url!="string"||typeof n.files_url!="string"||typeof n.replica_id!="string"||n.replica_id.length===0||typeof n.access_token!="string"||n.access_token.length===0||n.proof_public_key!==void 0&&(typeof n.proof_public_key!="string"||n.proof_public_key.length===0))return!1;try{let i=new URL(n.operations_url),o=new URL(n.sync_url),r=new URL(n.files_url);return[i,o,r].every(s=>(s.protocol==="https:"||s.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(s.hostname))&&!s.username&&!s.password&&!s.search&&!s.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 Mr(t,e){return Mt({operations_url:t?.operationsUrl,sync_url:t?.syncUrl,files_url:t?.filesUrl,replica_id:t?.replicaId,access_token:t?.accessToken,proof_public_key:t?.proofPublicKey},e)}function an(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t,n=e.actions;if(e.kind!=="files"||e.protocol_version!==1||!Array.isArray(n)||n.length===0||n.length>6||new Set(n).size!==n.length||n.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&&_c(o))}function _c(t){let e=new Set([".mdbase",".git","node_modules","_contracts","_schemas","_types","_views"]);return!t.startsWith("/")&&!t.endsWith("/")&&!t.includes("\\")&&t.split("/").every(n=>{let i=n.split(".")[0]?.toUpperCase()??"";return n!==""&&n!=="."&&n!==".."&&!n.startsWith(".")&&!n.endsWith(" ")&&!n.endsWith(".")&&!/[<>:"|?*]/.test(n)&&!e.has(n.toLowerCase())&&!["CON","PRN","AUX","NUL"].includes(i)&&!/^(COM|LPT)[1-9]$/.test(i)})}function Ir(t,e){if(!t||typeof t!="object"||Array.isArray(t)||t.collection_id!==e)return!1;try{return ye(t),!0}catch{return!1}}function kr(t){if(typeof t?.device_code!="string"||typeof t?.user_code!="string"||typeof t?.verification_uri!="string"||typeof t?.verification_uri_complete!="string"||!Number.isFinite(t?.expires_in)||!Number.isFinite(t?.interval))throw d("invalid_device_authorization_response","Connect returned an invalid downloaded application authorization response.");return{userCode:t.user_code,verificationUri:t.verification_uri,verificationUriComplete:t.verification_uri_complete,expiresAt:Date.now()+Math.max(1,t.expires_in)*1e3,intervalSeconds:Math.max(1,t.interval)}}function F(t){if(!t)return null;try{return JSON.parse(t)}catch{return null}}function cn(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t;return e.access!=="contract"&&e.access!=="full_collection"||!Array.isArray(e.contracts)||e.contracts.some(n=>!n||typeof n!="object"||n.contract_type!=="record"||typeof n.id!="string"||typeof n.version!="string"||!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(n.version)||!/^sha256:[0-9a-f]{64}$/.test(n.digest)||!n.schema||typeof n.schema!="object"||Array.isArray(n.schema)||!Array.isArray(n.implementations)||n.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 ln(t){return t.access==="full_collection"&&t.contracts.length===0}function xr(t){return t.endsWith("/")?t.slice(0,-1):t}function vc(){if(typeof location>"u")throw d("manifest_required","manifest is required outside a browser environment.");if(location.origin==="null")throw d("manifest_required","Downloaded applications must provide their v1 portable manifest inline.");return new URL("/.well-known/mdbase-app.json",location.origin).href}function Cc(){if(typeof location>"u")throw d("redirect_uri_required","redirectUri is required outside a browser environment.");return location.href.split(/[?#]/)[0]}function Ii(){if(typeof location>"u")return"null";let t=new URL(location.href);return["chrome-extension:","moz-extension:"].includes(t.protocol)?`${t.protocol}//${t.host}`:["http:","https:"].includes(t.protocol)?t.origin:"null"}function Er(t,e,n,i){if(typeof t!="string"&&t.distribution==="portable"||i)return Ii();let o=new URL(n);if(["http:","https:"].includes(o.protocol))return o.origin;if(typeof location<"u")return location.origin;if(typeof t!="string")return new URL(t.homepage).origin;try{return new URL(e).origin}catch{return""}}function qr(t){let e=":token:",n=t.lastIndexOf(e);return n<0?"":t.slice(n+e.length)}function dn(){if(typeof location>"u")throw d("callback_url_required","callbackUrl is required outside a browser environment.");return location.href}function Fr(t){if(t)return new Ye;if(typeof localStorage>"u")throw d("storage_required","storage is required outside a browser environment.");try{let e=`mdbase-connect:probe:${se(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,n){this.values.set(String(e),String(n))}};function Dr(t){return typeof t=="string"||t.distribution!=="portable"?!1:typeof location>"u"||location.origin==="null"||!["http:","https:"].includes(location.protocol)}function wc(t){let e=Rr(t),n=2166136261,i=2654435769;for(let o=0;o<e.length;o+=1){let r=e.charCodeAt(o);n=Math.imul(n^r,16777619),i=Math.imul(i^r,2246822507)}return`${(n>>>0).toString(16).padStart(8,"0")}${(i>>>0).toString(16).padStart(8,"0")}`}async function zr(t,e){let n=await fetch(`${t}/health`,{signal:e,cache:"no-store"}),i=await n.json().catch(()=>null);if(!n.ok||!Array.isArray(i?.capabilities)||!i.capabilities.every(o=>typeof o=="string")||!i.capabilities.includes(oo))throw d("capability_contract_incompatible","This server does not support new version-2 application authorizations.",{details:{contract:"fresh_application_authorization",required:[2],supported:[],peer:"server"}})}function It(t){let e="bundle:";if(!t.startsWith(e)||t.length===e.length)throw new Error("The registered application has no valid declaration identity.");return t.slice(e.length)}function Xe(t,e,n){return t.reason instanceof _?t.reason:d("authorization_cancelled",e,{cause:n})}function kt(t){for(let e of["code","state","error","error_description"])t.searchParams.delete(e);return t}function un(t){let e;try{e=new URL(t)}catch{return!1}return e.searchParams.has("state")&&(e.searchParams.has("code")||e.searchParams.has("error"))}function pn(t){try{let e=new URL(t).searchParams.get("state");return e&&e.length>0?e:null}catch{return null}}function Lr(t){if(!t.details||typeof t.details!="object"||Array.isArray(t.details))return;let e=t.details.return_to;return typeof e=="string"?e:void 0}var Ze=class{constructor(e,n){this.connect=e;this.operations=Pt(n.operations??Ee),this.selection=n.selection,this.autoSelect=n.autoSelect??"only",this.snapshot={status:"not_started",connections:[]}}connect;operations;selection;autoSelect;listeners=new Set;snapshot;snapshotKey="";stopConnections;stopSelection;stopActiveConnection;activeCollectionId=null;unavailableReason="not_authorized";started=!1;destroyed=!1;refreshing=!1;refreshQueued=!1;transactionDepth=0;lifecycleGeneration=0;operationControllers=new Set;startOperation=null;callbackCompletions=new Map;start(e){if(this.destroyed)return Promise.resolve(g(w("session_destroyed","This session has been destroyed.")));if(this.started&&!this.startOperation)return Promise.resolve(R(this.snapshot));let n=this.startOperation??this.beginStart();return this.waitForStart(n,e)}beginStart(){let e=new AbortController,n=++this.lifecycleGeneration;this.publish({status:"starting",connections:this.connect.connections()});let i={promise:this.performStart({signal:e.signal,timeoutMs:null},n),controller:e,waiters:0,generation:n};this.startOperation=i;let o=()=>{this.startOperation===i&&(this.startOperation=null)};return i.promise.then(o,o),i}async waitForStart(e,n){e.waiters+=1;try{return await k(n,Ci,()=>e.promise)}catch(i){if(i instanceof _)return g(i.problem);throw i}finally{e.waiters-=1,e.waiters===0&&this.startOperation===e&&(e.controller.abort(),this.startOperation=null,this.lifecycleGeneration+=1,this.stopLifecycleSubscriptions(),this.started=!1,this.publish({status:"not_started",connections:this.connect.connections()}))}}async performStart(e,n){try{this.started=!0,this.stopConnections=this.connect.onConnectionsChange(()=>this.refresh()),this.stopSelection=this.selection.subscribe(()=>{this.unavailableReason="not_authorized",this.refresh()});let i=this.selection.authorizationCallback();if(i){let o=await this.completeAuthorizationCallback(i,e);if(!o.ok)return n===this.lifecycleGeneration&&!this.destroyed&&(this.stopLifecycleSubscriptions(),this.started=!1,this.publish({status:"start_failed",problem:o.problem,connections:this.connect.connections()})),o}else this.autoSelectOnlyConnection();return n!==this.lifecycleGeneration||this.destroyed?g(w("session_destroyed","This session has been destroyed.")):(this.publishCurrent(),R(this.snapshot))}catch(i){if(i instanceof _){let o=i.problem;return n===this.lifecycleGeneration&&!this.destroyed&&(this.stopLifecycleSubscriptions(),this.started=!1,this.publish({status:"start_failed",problem:o,connections:this.connect.connections()})),g(o)}throw n===this.lifecycleGeneration&&!this.destroyed&&(this.stopLifecycleSubscriptions(),this.started=!1,this.publish({status:"not_started",connections:this.connect.connections()})),i}}destroy(){if(!this.destroyed){this.lifecycleGeneration+=1,this.startOperation?.controller.abort(),this.startOperation=null;for(let e of this.operationControllers)e.abort();this.operationControllers.clear(),this.stopLifecycleSubscriptions(),this.started=!1,this.destroyed=!0,this.callbackCompletions.clear(),this.publish({status:"destroyed",connections:[]}),this.listeners.clear()}}stopLifecycleSubscriptions(){this.stopConnections?.(),this.stopSelection?.(),this.stopActiveConnection?.(),this.stopConnections=void 0,this.stopSelection=void 0,this.stopActiveConnection=void 0,this.activeCollectionId=null}getSnapshot(){return this.snapshot}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}select(e,n={}){let i=this.lifecycleProblem();if(i)return g(i);let o=this.connect.connection(e);return o?(this.unavailableReason="not_authorized",this.selection.select(e,n),this.refresh(),R(o)):g(w("unknown_collection","This collection is not authorized for this application."))}clearSelection(e={}){let n=this.lifecycleProblem();return n?g(n):(this.unavailableReason="not_authorized",this.selection.select(null,e),this.refresh(),R(void 0))}forget(e){let n=this.lifecycleProblem();if(n)return g(n);this.transactionDepth+=1;try{let i=this.selection.selectedCollectionId()===e;this.connect.connection(e)?.forget(),i&&this.selection.select(null,{history:"replace"})}finally{this.transactionDepth-=1,this.refresh()}return R(void 0)}async authorize(e,n={}){let i=this.lifecycleProblem();if(i)return g(i);let o=this.selection.selectedCollectionId();if(e==="selected"&&!o)return g(w("collection_not_selected","Choose a collection before updating its access."));let r=typeof e=="object"?e.collectionId:e==="selected"?o:null,s=this.beginLifecycleOperation(n);this.transactionDepth+=1;try{let a=await this.connect.manifest?.(s.options);if(a&&!a.ok)return a;if(!this.lifecycleCurrent(s.generation))return this.destroyedOutcome(R(void 0));let c=a?V(a.value.requirements):1,l=await this.connect.authorize({...s.options,...c===1&&n.operations===void 0&&n.capabilities===void 0?{operations:this.operations}:{},target:r===null?{kind:"choose"}:{kind:"collection",collectionId:r},returnTo:this.selection.authorizationReturnTo()});return this.lifecycleCurrent(s.generation)?(l.ok&&l.value.kind==="connected"&&this.selection.finishAuthorization(l.value.returnTo,l.value.connection.collectionId),l):this.destroyedOutcome(l)}finally{s.dispose(),this.transactionDepth-=1,this.refresh()}}ensureOperations(e,n){return this.ensureAuthorization({operations:e},n)}ensureCapabilities(e,n){return this.ensureAuthorization({capabilities:e},n)}async ensureAuthorization(e,n){let i=this.lifecycleProblem();if(i)return g(i);let o=this.snapshot;if(o.status!=="ready")return g(w("collection_not_ready","Choose an authorized collection first."));let r=this.beginLifecycleOperation(n);this.transactionDepth+=1;try{let s=await this.connect.manifest?.(r.options);if(s&&!s.ok)return s;if(!this.lifecycleCurrent(r.generation))return this.destroyedOutcome(R(void 0));let a=s?.value.requirements??("operations"in e?{access:"full_collection",contracts:[]}:{access:"full_collection",contracts:[],capabilities:{contract_version:2,required:[],optional:Object.keys(zt)}});re(a,{...n,...e});let c="operations"in e?e.operations:e.capabilities.flatMap(p=>X(V(a),p)??[]),l=o.connection.authorizationCapabilities(c);if(l.sufficient)return R({kind:"unchanged",connection:o.connection});let u="operations"in e||V(a)===1?{operations:Pt([...l.grantedOperations,...c])}:{capabilities:[...new Set([...Yt(a,l.grantedOperations),...e.capabilities])]},f=await this.connect.authorize({...r.options,...u,target:{kind:"collection",collectionId:o.collectionId},returnTo:this.selection.authorizationReturnTo()});return this.lifecycleCurrent(r.generation)?(f.ok&&f.value.kind==="connected"&&this.selection.finishAuthorization(f.value.returnTo,f.value.connection.collectionId),f):this.destroyedOutcome(f)}catch(s){if(s instanceof _)return g(s.problem);throw s}finally{r.dispose(),this.transactionDepth-=1,this.refresh()}}handleAuthorizationCallback(e,n){let i=this.lifecycleProblem();return i?Promise.resolve(g(i)):un(e)?this.completeAuthorizationCallback(e,n):Promise.resolve(g(w("invalid_callback","This URL is not an authorization callback.")))}completeAuthorizationCallback(e,n){if(n?.signal?.aborted){let r=te(n.signal);return Promise.resolve(g(r.problem))}let i=pn(e);if(!i)return Promise.resolve(g(w("invalid_callback","Authorization callback is missing its state.")));let o=this.callbackCompletions.get(i)??this.beginCallbackCompletion(e,i);return this.waitForCallbackCompletion(o,n)}beginCallbackCompletion(e,n){let i=new AbortController,o=this.lifecycleGeneration;this.transactionDepth+=1,this.operationControllers.add(i);let r={state:n,controller:i,waiters:0,settled:!1,abandoned:!1,promise:void 0},s=this.connect.completeAuthorization(e,{signal:i.signal,timeoutMs:null}).catch(a=>{if(a instanceof _)return g(a.problem);throw a});return r.promise=s.then(a=>{if(o!==this.lifecycleGeneration||this.destroyed)return this.destroyedOutcome(a);if(!a.ok){if(!r.abandoned&&a.problem.recovery!=="retry"){let l=Lr(a.problem);this.selection.clearAuthorizationCallback(l)}return this.refresh(),a}let c=a.value;return this.unavailableReason="not_authorized",this.selection.finishAuthorization(c.returnTo,c.connection.collectionId),this.refresh(),R(c.connection,a.diagnostics)}).catch(a=>{if(o!==this.lifecycleGeneration||this.destroyed)return g(w("session_destroyed","This session was destroyed before authorization completion finished."));throw r.abandoned||(this.selection.clearAuthorizationCallback(),this.refresh()),a}).finally(()=>{r.settled=!0,this.operationControllers.delete(i),this.transactionDepth-=1,this.refresh(),this.callbackCompletions.get(n)===r&&this.callbackCompletions.delete(n)}),this.callbackCompletions.set(n,r),r}async waitForCallbackCompletion(e,n){e.waiters+=1;try{return await k(n,Qe,()=>e.promise)}catch(i){if(i instanceof _)return g(i.problem);throw i}finally{e.waiters-=1,e.waiters===0&&!e.settled&&this.callbackCompletions.get(e.state)===e&&(e.abandoned=!0,this.callbackCompletions.delete(e.state),e.controller.abort())}}lifecycleProblem(){return this.destroyed?w("session_destroyed","This session has been destroyed."):this.snapshot.status==="starting"?w("session_starting","The session is still starting."):this.snapshot.status==="start_failed"?this.snapshot.problem:this.started?null:w("session_not_started","Start the session before using it.")}beginLifecycleOperation(e={}){let n=new AbortController,i=()=>n.abort(e.signal?.reason);return e.signal?.aborted?i():e.signal?.addEventListener("abort",i,{once:!0}),this.operationControllers.add(n),{generation:this.lifecycleGeneration,options:{...e,signal:n.signal},dispose:()=>{e.signal?.removeEventListener("abort",i),this.operationControllers.delete(n)}}}lifecycleCurrent(e){return!this.destroyed&&e===this.lifecycleGeneration}destroyedOutcome(e){return!e.ok&&e.problem.code==="operation_outcome_unknown"?e:g(w("session_destroyed","This session was destroyed before the operation finished."))}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.started||this.destroyed||this.snapshot.status==="starting"||this.snapshot.status==="start_failed")){if(this.transactionDepth>0){this.refreshQueued=!0;return}if(this.refreshing){this.refreshQueued=!0;return}this.refreshing=!0;try{do this.refreshQueued=!1,this.publishCurrent();while(this.refreshQueued)}finally{this.refreshing=!1}}}publishCurrent(){let e=this.selection.selectedCollectionId(),n=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(r=>{!r&&this.selection.selectedCollectionId()===i.collectionId&&(this.unavailableReason="authorization_lost"),this.refresh()}));let o;if(!e)o={status:"unselected",connections:n};else if(!i||!i.info())o={status:"unavailable",collectionId:e,reason:this.connect.unavailableReason(e)??this.unavailableReason,connections:n};else{let r=i.info();o={status:"ready",collectionId:e,connection:i,info:r,access:i.authorizationCapabilities(this.operations),connections:n}}this.publish(o)}publish(e){if(this.snapshot.status==="destroyed"&&e.status!=="destroyed")return;let n=Rc(e);if(n!==this.snapshotKey){this.snapshot=e,this.snapshotKey=n;for(let i of this.listeners)i()}}};function Rc(t){return t.status==="not_started"||t.status==="starting"||t.status==="destroyed"?JSON.stringify(t):t.status==="start_failed"?JSON.stringify({status:t.status,problem:t.problem,connections:t.connections}):t.status==="unselected"?JSON.stringify({status:t.status,connections:t.connections}):t.status==="unavailable"?JSON.stringify({status:t.status,collectionId:t.collectionId,reason:t.reason,connections:t.connections}):JSON.stringify({status:t.status,collectionId:t.collectionId,info:t.info,access:t.access,connections:t.connections})}var Et=class{values=new Map;read(e){return this.values.get(e)??null}write(e,n){this.values.set(e,n)}remove(e){this.values.delete(e)}},et=class{constructor(e,n,i=Ve()){this.connect=e;this.options=n;this.timeouts=i;this.verificationStore=n.verificationStore??Ac()}connect;options;timeouts;listeners=new Set;verificationStore;snapshot={status:"not_started",connections:[]};manifest=null;application=null;base=null;stopBase;setupAssessment=null;setupTypePackAdoptions=null;verificationGeneration=0;readinessController;lifecycleGeneration=0;operationControllers=new Set;startOperation=null;start(e){if(this.snapshot.status==="destroyed")return Promise.resolve(g(w("session_destroyed","This application session has been destroyed.")));if(this.base&&!this.startOperation)return Promise.resolve(R(this.snapshot));let n=this.startOperation??this.beginStart();return this.waitForStart(n,e,this.timeouts.watchStartMs)}async waitForStart(e,n,i){e.waiters+=1;try{return await k(n,i,()=>e.promise)}catch(o){if(o instanceof _)return g(o.problem);throw o}finally{e.waiters-=1,e.waiters===0&&this.startOperation===e&&this.abandonStart(e)}}abandonStart(e){e.controller.abort(),this.readinessController?.abort(),this.startOperation=null,this.lifecycleGeneration+=1,this.verificationGeneration+=1,this.base&&this.cleanupBase(this.base),this.application=null,this.manifest=null,this.setupAssessment=null,this.setupTypePackAdoptions=null,this.publish({status:"not_started",connections:this.connect.connections()})}beginStart(){this.publish({status:"starting",connections:this.connect.connections()});let e=new AbortController,n=++this.lifecycleGeneration,i={promise:this.startWithinBudget({signal:e.signal,timeoutMs:null},n),controller:e,waiters:0,generation:n};this.startOperation=i;let o=()=>{this.startOperation===i&&(this.startOperation=null)};return i.promise.then(o,o),i}async startWithinBudget(e,n){try{return await this.performStartWithinBudget(e,n)}catch(i){if(i instanceof _)return this.startFailure(i.problem,n);throw n===this.lifecycleGeneration&&(this.verificationGeneration+=1,this.base&&this.cleanupBase(this.base),this.application=null,this.manifest=null,this.setupAssessment=null,this.setupTypePackAdoptions=null,this.publish({status:"not_started",connections:this.connect.connections()})),i}}async performStartWithinBudget(e,n){let i=await Ct("registration",()=>this.connect.register(e));if(!i.ok)return this.startFailure(i.problem,n);let o=await this.connect.manifest(e);if(!o.ok)return this.startFailure(o.problem,n);if(o.value.requirements?.access!=="full_collection")return this.startFailure(w("invalid_application_manifest","Application sessions require explicit full_collection access.",{details:{issues:[{path:"/requirements/access",keyword:"const",message:"must be full_collection",params:{allowedValue:"full_collection"}}]}}),n);let r=o.value.requirements.capabilities;if(!r)return this.startFailure(w("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:{}}]}}),n);if(n!==this.lifecycleGeneration||e.signal?.aborted)return g(w("operation_cancelled","Application session startup was cancelled.",{operationOutcome:"not_sent"}));this.application=i.value,this.manifest=o.value;let s=new Ze(this.connect,{selection:this.options.selection,autoSelect:this.options.autoSelect,operations:Sc(r,o.value)});this.base=s;try{let a=await s.start(e);return a.ok?n!==this.lifecycleGeneration||e.signal?.aborted?(this.cleanupBase(s),g(w("operation_cancelled","Application session startup was cancelled.",{operationOutcome:"not_sent"}))):(this.stopBase=s.subscribe(()=>{this.base===s&&this.refresh()}),await this.refresh(!0,e),n!==this.lifecycleGeneration||e.signal?.aborted?(this.cleanupBase(s),g(w("operation_cancelled","Application session startup was cancelled.",{operationOutcome:"not_sent"}))):R(this.snapshot)):(this.cleanupBase(s),this.startFailure(a.problem,n))}catch(a){throw this.cleanupBase(s),a}}startFailure(e,n){return n===this.lifecycleGeneration&&this.publish({status:"start_failed",problem:e,connections:this.connect.connections()}),g(e)}destroy(){if(this.snapshot.status!=="destroyed"){this.lifecycleGeneration+=1,this.verificationGeneration+=1,this.readinessController?.abort(),this.startOperation?.controller.abort(),this.startOperation=null;for(let e of this.operationControllers)e.abort();this.operationControllers.clear(),this.base&&this.cleanupBase(this.base),this.application=null,this.manifest=null,this.setupAssessment=null,this.setupTypePackAdoptions=null,this.publish({status:"destroyed",connections:[]}),this.listeners.clear()}}cleanupBase(e){this.base===e&&(this.stopBase?.(),this.stopBase=void 0,e.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,n={}){let i=this.lifecycleBase();return i.ok?i.value.select(e,n):i}clearSelection(e={}){let n=this.lifecycleBase();return n.ok?(n.value.clearSelection(e),R(void 0)):n}forget(e){let n=this.lifecycleBase();return n.ok?(n.value.forget(e),R(void 0)):n}authorize(e,n={}){return this.withLifecycleBase(n,async(i,o,r)=>{let s=await i.authorize(e,{...n,...o});return s.ok&&s.value.kind==="connected"&&this.lifecycleCurrent(r)&&await this.refresh(!0,o),s})}handleAuthorizationCallback(e,n){let i=String(e),o=this.startOperation!==null&&this.options.selection.authorizationCallback()===i;return this.withLifecycleBase(n,async(r,s,a)=>{if(o){let l=r.getSnapshot();return l.status==="ready"?R(l.connection):g(w("collection_not_ready","Authorization did not produce a ready collection."))}let c=await r.handleAuthorizationCallback(i,s);return c.ok&&this.lifecycleCurrent(a)&&await this.refresh(!0,s),c})}completeAuthorization(e,n){let i=e===void 0?dn():String(e),o=this.startOperation!==null&&this.options.selection.authorizationCallback()===i;return this.withLifecycleBase(n,async(r,s,a)=>{if(o){let l=r.getSnapshot();return l.status==="ready"?R(l.connection):g(w("collection_not_ready","Authorization did not produce a ready collection."))}let c=await r.handleAuthorizationCallback(i,s);return c.ok&&this.lifecycleCurrent(a)&&await this.refresh(!0,s),c})}ensureCapabilities(e,n){return this.withLifecycleBase(n,(i,o,r)=>{re(this.manifest.requirements,{...n,capabilities:e});let s=this.manifest.requirements?.capabilities,a=new Set([...s?.required??[],...s?.optional??[]]);return e.some(c=>!a.has(c))?Promise.resolve(g(w("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:[...a]}}]}}))):i.ensureCapabilities(e,o).then(async c=>(c.ok&&c.value.kind==="connected"&&this.lifecycleCurrent(r)&&await this.refresh(!0,o),c))})}ensureOperations(e,n){return this.withLifecycleBase(n,async(i,o,r)=>{re(this.manifest.requirements,{...n,operations:e});let s=await i.ensureOperations(e,o);return s.ok&&s.value.kind==="connected"&&this.lifecycleCurrent(r)&&await this.refresh(!0,o),s})}applyCollectionSetup(e){return this.withLifecycleBase(e,(n,i,o)=>this.applyCollectionSetupStarted(i,o))}async applyCollectionSetupStarted(e,n){if(this.snapshot.status!=="setup_review_required"||!this.setupAssessment)return g(w("collection_not_ready","There is no reviewed collection setup to apply."));if(!this.setupAssessment.applicable)return g(w("collection_not_ready","Resolve the collection setup conflicts before applying this update."));let i=this.connection();if(!i)return g(w("collection_not_ready","The collection is not ready."));let o=this.verificationGeneration,r=this.setupAssessment,s={...this.collectionSetupInput(this.setupTypePackAdoptions??void 0),expectedAssessmentDigest:r.assessmentDigest,expectedCollectionRevision:r.collectionRevision,expectedProvisionDigest:r.provisionDigest,allowTypePackDowngrades:r.typePacks.filter(c=>c.status==="downgrade").map(c=>c.desired.id)},a=await i.applyCollectionSetup(s,e);return this.lifecycleCurrent(n)?o!==this.verificationGeneration||this.connection()!==i?g(w("collection_not_ready","The selected collection changed during setup.")):a.ok?(this.setupAssessment=null,this.setupTypePackAdoptions=null,await this.verifySetup(this.context(i),++this.verificationGeneration,e),R(this.snapshot)):(a.problem.code==="application_declaration_mismatch"&&(this.setupAssessment=null,this.setupTypePackAdoptions=null,this.publish({status:"authorization_required",...this.context(i)})),a):!a.ok&&a.problem.code==="operation_outcome_unknown"?g(a.problem):g(w("session_destroyed",xt("session_destroyed")))}async refresh(e=!1,n){if(!this.base||!this.manifest)return;let i=this.base.getSnapshot();this.readinessController?.abort(),this.verificationGeneration+=1;let o=this.verificationGeneration;if(this.setupAssessment=null,this.setupTypePackAdoptions=null,i.status==="unselected"){this.publish({status:"unselected",connections:i.connections});return}if(i.status==="unavailable"){this.publish(i);return}if(i.status!=="ready")return;let r=this.context(i.connection);if(this.connect.connectionApplicationId(i.collectionId)!==this.application?.id){this.publish({status:"authorization_required",...r});return}if(!r.capabilities.requiredAvailable||r.readiness?.files.state==="requires_authorization"||!Zo(this.manifest,r.info)){this.publish({status:"authorization_required",...r});return}if(!((this.manifest.provisions?.type_packs.length??0)>0||(this.manifest.provisions?.configuration?.length??0)>0)){let l=this.publishReady(r,o,n);e&&await l;return}let a=Zt(this.manifest,i.collectionId);r.readiness?.contracts.state!=="checking"&&this.verificationStore.read(a)===Ri(this.manifest)?this.publish({status:"ready",verification:"cached",...r}):this.publish({status:"checking_setup",...r});let c=this.verifySetup(r,o,n);e&&await c}async verifySetup(e,n,i){let o=this.connection(),r=this.requireManifest();if(!o||o.collectionId!==e.collectionId)return;let s=this.collectionSetupInput(),a=r.requirements?.contracts??[],c=new AbortController;this.readinessController?.abort(),this.readinessController=c;let l=null,u=e.readiness&&a.length?wi({...e,readiness:e.readiness,contracts:a,connection:o,controller:c,options:i,requestMs:this.timeouts.requestMs,isCurrent:()=>n===this.verificationGeneration&&this.connection()===o,publish:m=>{l={...m,...e}}}):Promise.resolve(!0),f=()=>c.abort(i?.signal?.reason);i?.signal?.aborted?f():i?.signal?.addEventListener("abort",f,{once:!0});let p,h;try{[p,h]=await Promise.all([Ct("setup-assessment",()=>o.assessCollectionSetup(s,{...i,signal:c.signal})),u])}catch(m){if(n!==this.verificationGeneration&&c.signal.aborted&&(m===c.signal.reason||m instanceof _&&m.code==="operation_cancelled"))return;throw m}finally{i?.signal?.removeEventListener("abort",f),c.abort(),this.readinessController===c&&(this.readinessController=void 0)}if(n===this.verificationGeneration){if(!p.ok){this.publish(p.problem.code==="application_declaration_mismatch"?{status:"authorization_required",...e}:{status:"blocked",problem:p.problem,...e});return}if(!p.value.applicable){let m=er(p.value);if(Object.keys(m).length>0){if(p=i?await o.assessCollectionSetup(this.collectionSetupInput(m),i):await o.assessCollectionSetup(this.collectionSetupInput(m)),n!==this.verificationGeneration)return;if(!p.ok){this.publish(p.problem.code==="application_declaration_mismatch"?{status:"authorization_required",...e}:{status:"blocked",problem:p.problem,...e});return}this.setupTypePackAdoptions=m}}if(n===this.verificationGeneration){if(p.value.status!=="current"){this.setupAssessment=p.value,this.verificationStore.remove(Zt(r,e.collectionId)),this.publish({status:"setup_review_required",update:Pc(p.value,r.provisions?.type_packs??[]),...e});return}if(this.verificationStore.write(Zt(r,e.collectionId),Ri(r)),e.readiness&&(e.readiness.setup={state:"current",evidence:[{source:"authority",fact:"Collection setup assessment is current."}]}),!h){l&&this.publish(l);return}await this.publishReady(e,n,i,!0)}}}async publishReady(e,n,i,o=!1){let r=this.requireManifest().requirements?.contracts??[];if(!o&&e.readiness&&r.length){let s=this.connection();if(!s||s.collectionId!==e.collectionId)return;this.publish({status:"checking_setup",...e});let a=new AbortController;this.readinessController?.abort(),this.readinessController=a;try{if(!await wi({...e,readiness:e.readiness,contracts:r,connection:s,controller:a,options:i,requestMs:this.timeouts.requestMs,isCurrent:()=>n===this.verificationGeneration&&this.connection()===s,publish:c=>this.publish({...c,...e})}))return}finally{this.readinessController===a&&(this.readinessController=void 0)}}n===this.verificationGeneration&&this.publish({status:"ready",verification:"verified",...e})}collectionSetupInput(e){let n=this.requireManifest(),i=this.requireApplication();return tr(n,It(i.family_identity),`sha256:${i.manifest_digest}`,e)}context(e){return Xo(this.requireManifest(),e.collectionId,e.info(),this.connect.connections())}publish(e){if(!(this.snapshot.status==="destroyed"&&e.status!=="destroyed")&&("readiness"in e&&e.readiness&&(e={...e,readiness:Yo(e.readiness,e.status,e.status==="ready"?e.verification:void 0)}),JSON.stringify(this.snapshot)!==JSON.stringify(e))){this.snapshot=e;for(let n of this.listeners)n()}}lifecycleBase(){let e=this.snapshot.status;if(this.startOperation||e==="starting")return g(w("session_starting","The application session is still starting."));if(this.snapshot.status==="start_failed")return g(this.snapshot.problem);if(this.base)return R(this.base);let n=e==="destroyed"?"session_destroyed":"session_not_started";return g(w(n,xt(n)))}async withLifecycleBase(e,n){let i=this.beginLifecycleOperation(e),o=ve(i.options,this.timeouts.requestMs),r={signal:o.signal,timeoutMs:null};try{let s=this.startOperation;if(s){let l=await this.waitForStart(s,r,null);if(!l.ok)return l}if(!this.lifecycleCurrent(i.generation))return g(w("session_destroyed",xt("session_destroyed")));let a=this.lifecycleBase();if(!a.ok)return a;let c=await n(a.value,r,i.generation);return this.lifecycleCurrent(i.generation)?c:this.destroyedOutcome(c)}catch(s){if(s instanceof _)return this.lifecycleCurrent(i.generation)?g(s.problem):s.problem.code==="operation_outcome_unknown"?g(s.problem):g(w("session_destroyed",xt("session_destroyed")));throw s}finally{o.dispose(),i.dispose()}}beginLifecycleOperation(e={}){let n=new AbortController,i=()=>n.abort(e.signal?.reason);return e.signal?.aborted?i():e.signal?.addEventListener("abort",i,{once:!0}),this.operationControllers.add(n),{generation:this.lifecycleGeneration,options:{...e,signal:n.signal},dispose:()=>{e.signal?.removeEventListener("abort",i),this.operationControllers.delete(n)}}}lifecycleCurrent(e){return this.snapshot.status!=="destroyed"&&e===this.lifecycleGeneration}destroyedOutcome(e){return!e.ok&&e.problem.code==="operation_outcome_unknown"?e:g(w("session_destroyed",xt("session_destroyed")))}requireManifest(){if(!this.manifest)throw new Error("Start the application session before using it.");return this.manifest}requireApplication(){if(!this.application)throw new Error("Start the application session before using it.");return this.application}};function Sc(t,e){let n=(e.provisions?.type_packs.length??0)>0||(e.provisions?.configuration?.length??0)>0;return[...Jo(e.requirements),...t.contract_version===2&&n?Lt:[]]}function Oc(t,e){let n=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:t.manifest.name??e.desired.id,status:e.status,applicable:e.applicable,assessmentDigest:e.assessmentDigest,...e.current?{currentVersion:e.current.version}:{},desiredVersion:e.desired.version,resources:e.resources,contractSetups:e.contractSetups,canApply:e.applicable,reason:n}}function Pc(t,e){let n=t.typePacks.map(r=>{let s=e.find(a=>a.manifest.id===r.desired.id);if(!s)throw new Error(`Collection setup returned undeclared type pack '${r.desired.id}'.`);return Oc(s,r)}),i=t.configuration.filter(r=>r.action!=="current").length,o=t.status==="conflict"?"Existing collection policy conflicts with this application's required setup.":`This application requires ${i} configuration change${i===1?"":"s"} and ${n.length} definition update${n.length===1?"":"s"}.`;return{status:t.status,applicable:t.applicable,assessmentDigest:t.assessmentDigest,collectionRevision:t.collectionRevision,provisionDigest:t.provisionDigest,configuration:t.configuration,typePacks:n,canApply:t.applicable,reason:o}}function xt(t){return t==="session_destroyed"?"This application session has been destroyed.":t==="session_starting"?"The application session is still starting.":"Start the application session before using it."}function Ac(){return typeof localStorage<"u"?{read:t=>localStorage.getItem(t),write:(t,e)=>localStorage.setItem(t,e),remove:t=>localStorage.removeItem(t)}:new Et}var Tc="mdbase-connect-identities",tt="application-identities",ki=BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Mc=ki/2n,nt=class{database=null;async create(e){let n=await Nr(e),i=await this.open();return await Ur(i,o=>o.add(n)),n}async get(e){let n=await this.open();return await Ic(n.transaction(tt).objectStore(tt).get(e))??null}async delete(e){let n=await this.open();await Ur(n,i=>i.delete(e))}open(){if(typeof indexedDB>"u")throw new De("Persistent application identity requires browser IndexedDB or an injected identity store.");return this.database||(this.database=new Promise((e,n)=>{let i=indexedDB.open(Tc,1);i.onupgradeneeded=()=>{i.result.objectStoreNames.contains(tt)||i.result.createObjectStore(tt,{keyPath:"handle"})},i.onerror=()=>n(i.error),i.onsuccess=()=>e(i.result)})),this.database}},it=class{records=new Map;async create(e){if(this.records.has(e))throw new Error(`Application identity already exists: ${e}`);let n=await Nr(e);return this.records.set(e,n),n}async get(e){return this.records.get(e)??null}async delete(e){this.records.delete(e)}},De=class extends Error{constructor(e){super(e),this.name="ApplicationIdentityStoreError"}};async function ot(t){return Oo(t.signingPublicKey)}async function qt(t,e){if(t.installation_signing_public_key!==e.signingPublicKey||t.application_installation_id!==await ot(e))throw new Error("Application authorization identity does not match its binding.");let n=xc(new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},e.signingPrivateKey,Po(t))));return{binding:t,signature:jr(n)}}async function fn(t,e,n){let i=`application-installation:v2:${e}:${n.id}`,o=await t.get(i);if(o)return o;try{return await t.create(i)}catch(r){let s=await t.get(i);if(s)return s;throw r}}async function Nr(t){let e=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign","verify"]),n=jr(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:t,signingPrivateKey:o,signingPublicKey:n}}function Ic(t){return new Promise((e,n)=>{t.onerror=()=>n(t.error),t.onsuccess=()=>e(t.result)})}function Ur(t,e){return new Promise((n,i)=>{let o=t.transaction(tt,"readwrite");e(o.objectStore(tt)).onerror=()=>i(o.error),o.onerror=()=>i(o.error),o.onabort=()=>i(o.error??new Error("Identity transaction aborted.")),o.oncomplete=()=>n()})}function kc(t){let e=new Uint8Array(t.reduce((i,o)=>i+o.byteLength,0)),n=0;for(let i of t)e.set(i,n),n+=i.byteLength;return e}function jr(t){return btoa(String.fromCharCode(...t)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}function xc(t){if(t.byteLength!==64)throw new Error("Application authorization signature is invalid.");let e=Ec(t.slice(32));if(e===0n||e>=ki)throw new Error("Application authorization signature is invalid.");return e<=Mc?t:kc([t.slice(0,32),qc(ki-e,32)])}function Ec(t){return BigInt(`0x${Fc(t)}`)}function qc(t,e){let n=t.toString(16).padStart(e*2,"0");return Uint8Array.from({length:e},(i,o)=>Number.parseInt(n.slice(o*2,o*2+2),16))}function Fc(t){return[...t].map(e=>e.toString(16).padStart(2,"0")).join("")}var Ft={id:"mdbase.person",version:"2.0.0"};function Vr(t,e,n){return k(e,n.requestMs,async i=>{let o=await n.authorizedToken(i.signal);if(!o)throw d("not_authorized","Authorize this collection before reading people.");let r=await ae(`${n.serverUrl}/v1/authorities/${encodeURIComponent(n.collectionId)}/${t}`,{headers:{authorization:`Bearer ${o.accessToken}`},signal:i.signal,credentials:"omit",cache:"no-store",redirect:"error"},"temporarily_unavailable","Account identity information is unavailable.");if(r.status===404)throw d("unsupported_operation","This Connect server does not support people discovery.");if(r.status===401)throw d("authorization_expired","The application authorization is no longer active.");if(r.status===403)throw d("access_denied","This application was not approved to read this identity information.");if(!r.ok)throw d("temporarily_unavailable","Account identity information is unavailable.");return E(r,"invalid_operation_response","Connect returned invalid identity information.")})}var rt=class{constructor(e){this.context=e}context;current(e){return I(()=>this.readCurrent(e),en)}members(e){return I(()=>this.readMembers(e),en)}directory(e={}){return I(async()=>{let{members:n="if-approved",...i}=e,[o,r,s]=await Promise.all([this.readCurrent(i),n==="omit"?void 0:this.readMembers(i).catch(a=>{if(!(n==="if-approved"&&a instanceof _&&a.code==="access_denied"))throw a}),this.readRecords(i)]);return{account:o,me:Dc(s,o),people:s.people,invalid:s.invalid.map(({path:a,reason:c})=>({path:a,reason:c})),...r?{members:r}:{}}},pe)}async readCurrent(e){let n=await this.context.request("identity",e),i=Qr(n),o=n.person_settings_url;if(o===void 0)return i;if(typeof o!="string"||!Gr(o))throw hn();return{...i,personSettingsUrl:o}}async readMembers(e){let n=await this.context.request("members",e);if(!n||typeof n!="object"||!("members"in n)||!Array.isArray(n.members))throw hn();return n.members.map(i=>{let o=Qr(i);if(!i||typeof i!="object"||!("role"in i)||i.role!=="owner"&&i.role!=="editor"&&i.role!=="viewer")throw hn();return{...o,role:i.role}})}async readRecords(e){let i=Kr(await this.context.describe(e)).contracts.find(c=>c.id===Ft.id&&c.version===Ft.version),o=new Map;for(let c of i?.implementations??[])for await(let l of this.context.queryPages({contract:{...Ft,type:c.typeName}},{signal:e.signal,pageSize:200}))for(let u of Kr(l).results){let f=o.get(u.path)??[];f.push({typeName:c.typeName,value:u.frontmatter??{}}),o.set(u.path,f)}let r=[],s=[];for(let[c,l]of o){let u=l.map(h=>zc(h.value)),f=u[0],p=u.find(h=>"reason"in h);p&&"reason"in p?s.push({path:c,reason:p.reason,claims:l.flatMap(h=>Br(h.value))}):u.some(h=>JSON.stringify(h)!==JSON.stringify(f))?s.push({path:c,reason:"Its Person implementations project different values.",claims:l.flatMap(h=>Br(h.value))}):f&&!("reason"in f)&&r.push({path:c,...f,typeNames:l.map(h=>h.typeName).sort()})}let a=(c,l)=>c.path.localeCompare(l.path);return{people:r.sort(a),invalid:s.sort(a)}}};function Dc(t,e){let n=t.invalid.filter(o=>o.claims.some(r=>mn(r,e)));if(n.length)return{status:"invalid",paths:n.map(o=>o.path)};let i=t.people.filter(o=>o.identities.some(r=>mn(r,e)));return i.length===0?{status:"unlinked"}:i.length>1?{status:"ambiguous",paths:i.map(o=>o.path)}:{status:"linked",person:i[0]}}function mn(t,e){return t.issuer===e.issuer&&t.subject===e.subject}function zc(t){let{name:e,identities:n=[]}=t;if(typeof e!="string"||!e.trim())return{reason:"It needs a non-blank name."};if(!Array.isArray(n))return{reason:"Its account identities must be a list."};let i=[];for(let o of n){if(!o||typeof o!="object"||Array.isArray(o)||typeof o.issuer!="string"||typeof o.subject!="string"||!o.subject.trim())return{reason:"Each account identity needs an exact issuer and subject."};i.push({issuer:o.issuer,subject:o.subject})}return{name:e,identities:i}}function Br(t){return(Array.isArray(t.identities)?t.identities:[]).flatMap(n=>n&&typeof n=="object"&&!Array.isArray(n)&&"issuer"in n&&"subject"in n&&typeof n.issuer=="string"&&typeof n.subject=="string"?[{issuer:n.issuer,subject:n.subject}]:[])}function Kr(t){if(!t.ok)throw new _(t.problem);return t.value}function Qr(t){if(!t||typeof t!="object"||!("issuer"in t)||!("subject"in t)||!("name"in t)||typeof t.issuer!="string"||typeof t.subject!="string"||typeof t.name!="string"||!t.subject.trim()||!t.name.trim()||!Gr(t.issuer))throw hn();return{issuer:t.issuer,subject:t.subject,name:t.name}}function Gr(t){try{let e=new URL(t);return e.protocol==="https:"||e.protocol==="http:"}catch{return!1}}function hn(){return d("invalid_operation_response","Connect returned invalid identity information.")}var Oe=class{operations=new Map;run(e,n,i,o){if(n?.signal?.aborted)return Promise.reject(te(n.signal));let r=this.operations.get(e)??this.begin(e,o);return this.wait(e,r,n,i)}begin(e,n){let i=new AbortController,o={controller:i,waiters:0,settled:!1,promise:void 0};return o.promise=Promise.resolve().then(()=>n(i.signal)).finally(()=>{o.settled=!0,this.operations.get(e)===o&&this.operations.delete(e)}),this.operations.set(e,o),o}async wait(e,n,i,o){n.waiters+=1;try{return await k(i,o,()=>n.promise)}finally{n.waiters-=1,n.waiters===0&&!n.settled&&this.operations.get(e)===n&&(this.operations.delete(e),n.controller.abort())}}};var Hr=new Set(["files-stat-v1","query-record-revisions-v1","read-many-documents-v1","query-metadata-v1","contract-query-v1","link-resolution-options-v1"]),xi=Object.freeze([]);function ze(t){if(t===void 0)return xi;if(!Array.isArray(t)||t.some(e=>typeof e!="string"))throw d("invalid_operation_response","The authority returned invalid feature capabilities.");return Object.freeze([...new Set(t.filter(e=>Hr.has(e)))])}var yn=class{constructor(e,n){this.discovery=e;this.timeoutMs=n}discovery;timeoutMs;lifetime;generation=0;cached;pending=new Oe;get capabilities(){return this.refreshLifetime(),this.cached??xi}supports(e,n){return I(()=>k(n,this.timeoutMs,async i=>{if(!Hr.has(e))return!1;for(;;){this.refreshLifetime();let o=this.generation,r=this.cached??await this.pending.run(String(o),{signal:i.signal,timeoutMs:null},null,s=>this.discover(s));if(this.refreshLifetime(),o===this.generation)return i.signal.aborted||(this.cached=r),r.includes(e)}}),Ge)}invalidate(){this.cached=void 0,this.lifetime=void 0}refreshLifetime(){let e=this.discovery.lifetime();e!==this.lifetime&&(this.lifetime=e,this.generation+=1,this.cached=void 0)}async discover(e){if(this.discovery.operations().includes("describe")){let i=await this.discovery.describe({signal:e,timeoutMs:null,coordination:{coalesce:!1}});if(!i.ok)throw new _(i.problem);return ze(i.value.authorityCapabilities)}let n=this.discovery.fileCapability();if(n?.actions.includes("list")){let i=n.scope.kind==="selected_folders"?n.scope.folders[0]:void 0,o=await this.discovery.filesPage(i,e);return Object.freeze(o.filter(r=>r==="files-stat-v1"))}return xi}};function Ei(t){return{...t.output?{output:t.output}:{},...t.types?{types:t.types}:{},...t.timezone?{timezone:t.timezone}:{},...t.context?{context:t.context}:{},...t.projections?{projections:Object.fromEntries(Object.entries(t.projections).map(([e,n])=>[e,{expr:n.expression,...n.description?{description:n.description}:{}}]))}:{},...t.where?{where:t.where}:{},...t.select?{select:t.select.map(e=>typeof e=="string"?e:{name:e.name,expr:e.expression,...e.label?{label:e.label}:{},...e.description?{description:e.description}:{}})}:{},...t.orderBy?{order_by:t.orderBy}:{},...t.groupBy?{group_by:t.groupBy}:{},...t.summaryFunctions?{summary_functions:Object.fromEntries(Object.entries(t.summaryFunctions).map(([e,n])=>[e,{expr:n.expression,...n.description?{description:n.description}:{}}]))}:{},...t.summaries?{summaries:t.summaries}:{},...t.limit===void 0?{}:{limit:t.limit},...t.offset===void 0?{}:{offset:t.offset},...t.pagination?{pagination:t.pagination}:{},...t.cursor?{cursor:t.cursor}:{},...t.snapshot?{snapshot:t.snapshot}:{},...t.includeBody===void 0?{}:{include_body:t.includeBody},...t.frontmatterMode?{frontmatter_mode:t.frontmatterMode}:{},...t.contract?{contract:t.contract}:{}}}function gn(t){return{id:t.id,version:t.version,digest:t.digest,type:t.type,implementationDigest:t.implementation_digest}}function qi(t){let{effective_frontmatter:e,contract:n,...i}=t;return{...i,...e===void 0?{}:{effectiveFrontmatter:e},...n?{contract:gn(n)}:{}}}function Lc(t){if(!t||typeof t.path!="string"||typeof t.revision!="string"||!t.revision||!Array.isArray(t.types)||t.types.some(e=>typeof e!="string")||!t.values||typeof t.values!="object"||Array.isArray(t.values)||Object.keys(t).some(e=>!["path","types","revision","values","contract"].includes(e))||t.contract!==void 0&&(!t.contract||["id","version","digest","type","implementation_digest"].some(e=>typeof t.contract[e]!="string")))throw d("invalid_operation_response","The authority returned an invalid revision-bearing metadata row.");return{path:t.path,types:t.types,revision:t.revision,values:t.values,...t.contract?{contract:gn(t.contract)}:{}}}function Fi(t,e){if(!t||!Array.isArray(t.results)||t.output!==e)throw d("invalid_operation_response","The authority returned an invalid query output mode.");let n=t.meta?{...typeof t.meta.total_count=="number"?{totalCount:t.meta.total_count}:{},...t.meta.total_count_outcome===void 0?{}:{totalCountOutcome:t.meta.total_count_outcome},hasMore:t.meta.has_more,...t.meta.cursor?{cursor:t.meta.cursor}:{},...t.meta.snapshot?{snapshot:t.meta.snapshot}:{}}:void 0;return e==="metadata"?{output:e,results:t.results.map(i=>Lc(i)),...n?{meta:n}:{}}:{results:t.results.map(i=>qi(i)),...n?{meta:n}:{}}}function bn(t){if(!t||t.protocol_version!==1||typeof t.collection_id!="string"||typeof t.display_name!="string"||typeof t.spec_version!="string"||!Array.isArray(t.operations)||!Array.isArray(t.types)||!Array.isArray(t.contracts))throw d("invalid_operation_response","The authority returned an invalid collection description.");return{authorityCapabilities:ze(t.authority_capabilities),protocolVersion:t.protocol_version,collectionId:t.collection_id,displayName:t.display_name,specVersion:t.spec_version,operations:t.operations,changeCursor:t.change_cursor,types:t.types,contracts:t.contracts.map(e=>({contractType:e.contract_type,id:e.id,version:e.version,digest:e.digest,schema:e.schema,...e.binding_schema?{bindingSchema:e.binding_schema}:{},implementations:e.implementations.map(n=>({typeName:n.type_name,typeVersion:n.type_version,...n.type_path?{typePath:n.type_path}:{},digest:n.digest,fields:n.fields,...n.binding?{binding:n.binding}:{}}))})),...t.configuration?{configuration:t.configuration}:{}}}var _n=class{constructor(e,n){this.transport=e;this.requestTimeoutMs=n}transport;requestTimeoutMs;generation=0;description;describing;get schemaGeneration(){return this.generation}invalidate(){this.generation+=1,this.description=void 0,this.describing=void 0}describe(e={}){return I(()=>k(e,this.requestTimeoutMs,async()=>{if(!e.fresh&&this.description&&Date.now()<this.description.expiresAt)return R(this.description.value);if(!this.describing){this.description=void 0;let n=this.generation,i=I(()=>k({},this.requestTimeoutMs,o=>this.transport.operation("describe",{},{signal:o.signal,timeoutMs:this.requestTimeoutMs})),Rt).then(o=>{if(!o.ok)return o;let r=bn(o.value);return this.generation===n&&(this.description={value:r,expiresAt:Date.now()+6e4}),R(r,o.diagnostics)}).finally(()=>{this.describing===i&&(this.describing=void 0)});this.describing=i}return this.describing}),Rt).then(n=>n.ok?n.value:n)}};function vn(t,e,n){let i=n,o=!1,r=()=>{if(!i)return;let a=i;i=void 0,t(a).catch(()=>{})},s=()=>{o||r()};return e?.addEventListener("abort",s,{once:!0}),{startRequest(){o=!0},finishRequest(a){a&&(i=a),o=!1,e?.aborted&&r()},dispose(){e?.removeEventListener("abort",s),r()}}}function Cn(t){if(t===void 0)return 1/0;if(!Number.isSafeInteger(t)||t<0)throw new TypeError("maxResults must be a non-negative safe integer.");return t}function wn(t,e){return typeof t=="number"&&Number.isFinite(t)?Math.max(0,Math.floor(t)):e}function st(t,e){return typeof t=="number"&&Number.isFinite(t)&&t>=1?Math.floor(t):e}async function*Wr(t,e,n={},i={}){let{offset:o,limit:r,cursor:s,pagination:a,snapshot:c,...l}=n,u=wn(o,0),f=st(i.firstPageSize??i.pageSize??r,200),p=st(i.pageSize??r,1e3),h=s,m=s!==void 0,P=Cn(i.maxResults),v=vn(e,i.signal,s),b=c,C=0,y=0;try{for(;!i.signal?.aborted&&C<P;){v.startRequest();let A=h,D={signal:i.signal,timeoutMs:i.pageTimeoutMs,coordination:{...i.coordination,coalesce:!1}},S=y===0&&s===void 0&&a===void 0&&c===void 0&&n.output!=="metadata",T=await t({...l,...m?{}:{limit:Math.min(y===0?f:p,P-C)},...m?A?{cursor:A}:{pagination:"cursor"}:{offset:u,...b?{snapshot:b}:{},...!b&&a==="cursor"?{pagination:"cursor"}:{}},...!m&&!b&&S?{pagination:"cursor"}:{}},D);if(S&&!i.signal?.aborted&&!T.ok&&T.problem.code==="operation_invalid"&&(T=await t({...l,limit:Math.min(f,P-C),offset:u},D)),v.finishRequest(T.ok?T.value.meta?.cursor:void 0),i.signal?.aborted)return;if(!T.ok){v.dispose(),yield T;return}let M=T.value,O=M.meta?.cursor;if(O?(m=!0,h=O):m&&(h=void 0),m&&M.meta?.hasMore&&!O){v.dispose(),yield g(w("invalid_operation_response","The collection authority omitted the cursor required for the next query page."));return}let U=M.meta?.snapshot;if(!m&&b&&U&&b!==U){v.dispose(),yield g(w("query_snapshot_changed","The collection query snapshot changed while paging. Refresh the query before continuing."));return}!m&&!b&&U&&(b=U);let H=P-C,B=M.results.length>H?M.results.slice(0,H):M.results;C+=B.length;let N=C>=P||!M.meta?.hasMore||M.results.length===0,Te={...M.output?{output:M.output}:{},results:B,...M.meta?{meta:M.meta}:{},page:y,offset:u,loaded:C,complete:N,...O?{cursor:O}:{},...!m&&b?{snapshot:b}:{}};if(N&&v.dispose(),i.onProgress?.(Te),yield R(Te,T.diagnostics),N)return;u+=M.results.length,y+=1}}finally{v.dispose()}}async function Jr(t,e,n,i,o,r){let s=$r(o.batchSize??100,1e3,"batchSize"),a=$r(o.concurrency??4,4,"concurrency");if(o.coordination?.latestWins)throw new TypeError("readMany batches cannot use latestWins coordination.");if(o.includeBody!==void 0&&typeof o.includeBody!="boolean")throw new TypeError("includeBody must be boolean.");if(o.frontmatterMode!==void 0&&!["effective","persisted","both"].includes(o.frontmatterMode))throw new TypeError("Invalid frontmatterMode.");let c=[...i];try{return await k(o,r,async l=>{if(!c.length)return R({results:[],errors:[]});let u=de({...o,timeoutMs:null,coordination:{...o.coordination,coalesce:!1}},l),f=[...new Set(c)],p=new Map,h=[],m=[],P=0,v=0,b=(y,A,D)=>{h.push({batch:y,paths:A,failure:D});for(let S of A)p.set(S,{status:"error",path:S,batch:y})},C=async()=>{for(;!l.signal.aborted&&v<f.length;){let y=await n?.("read-many-documents-v1",u);if(y&&!y.ok)throw v=f.length,new _(y.problem);if(l.signal.aborted||v>=f.length)return;let A=y?.value===!0,D=A?Math.min(s,100):s,S=P++,T=f.slice(v,v+D);v+=T.length;let M={where:`file.path in ${JSON.stringify(T)}`,...o.types?{types:o.types}:{}};try{let O=T,U=[];if(A&&o.types!==void 0){let N=await t({...M,select:["file.path"],includeBody:!1},{...u,pageSize:T.length});if(!N.ok){b(S,T,N);continue}let Te=new Set(N.value.results.map(Ne=>Ne.path));O=T.filter(Ne=>Te.has(Ne)),U=N.diagnostics;let ne=await n("read-many-documents-v1",u);if(!ne.ok)throw new _(ne.problem);A=ne.value}if(!A){let N=await t({...M,...o.includeBody===void 0?{}:{includeBody:o.includeBody},...o.frontmatterMode?{frontmatterMode:o.frontmatterMode}:{}},{...u,pageSize:T.length});if(!N.ok){b(S,T,N);continue}m[S]=N.diagnostics;let Te=new Map(N.value.results.map(ne=>[ne.path,ne]));for(let ne of T){let Ne=Te.get(ne);p.set(ne,Ne?{status:"found",path:ne,record:Ne}:{status:"missing",path:ne})}continue}if(l.signal.aborted)return;let H=O.length?await e(O,o.includeBody??!1,u):R({items:[]});if(!H.ok){b(S,T,H);continue}let B=Uc(H.value,O,S,o);for(let N of T)p.set(N,B.entries.get(N)??{status:"missing",path:N});m[S]=[...U,...H.diagnostics],B.errors.length&&h.push({batch:S,paths:B.errors.map(N=>N.path),failure:g(w("operation_invalid","Some batch records could not be read.",{details:{diagnostics:B.errors}}))})}catch(O){if(!(O instanceof _))throw O;let U=await I(async()=>{throw O},pe);b(S,T,U)}}};return await Promise.all(Array.from({length:Math.min(a,f.length)},C)),R({results:c.map(y=>p.get(y)),errors:h.sort((y,A)=>y.batch-A.batch)},m.flat())})}catch(l){if(l instanceof _)return I(async()=>{throw l},pe);throw l}}function Uc(t,e,n,i){(!t||!Array.isArray(t.items)||t.items.length!==e.length)&&Dt();let o=new Map,r=[];return t.items.forEach((s,a)=>{switch((!s||s.path!==e[a])&&Dt(),s.status){case"found":o.set(s.path,{status:"found",path:s.path,record:Nc(s.record,s.path,i)});break;case"missing":o.set(s.path,{status:"missing",path:s.path});break;case"error":(!s.error||typeof s.error.code!="string"||typeof s.error.message!="string")&&Dt(),o.set(s.path,{status:"error",path:s.path,batch:n}),r.push({severity:"error",code:s.error.code,message:s.error.message,path:s.path});break;default:Dt()}}),{entries:o,errors:r}}function Nc(t,e,n){(!t||t.path!==e||typeof t.revision!="string"||!t.revision||!Array.isArray(t.types)||t.types.some(o=>typeof o!="string")||!Di(t.frontmatter)||!Di(t.effective_frontmatter)||!Di(t.file)||(n.includeBody??!1)&&typeof t.body!="string"||t.contract!==void 0)&&Dt();let i=n.frontmatterMode??"effective";return{path:t.path,revision:t.revision,types:t.types,file:t.file,...i!=="effective"?{frontmatter:t.frontmatter}:{},...i!=="persisted"?{effectiveFrontmatter:t.effective_frontmatter}:{},...n.includeBody?{body:t.body}:{}}}function Di(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function Dt(){throw d("invalid_operation_response","The authority returned an invalid or incoherently bound document batch.")}function $r(t,e,n){if(!Number.isSafeInteger(t)||t<1||t>e)throw new TypeError(`${n} must be an integer between 1 and ${e}.`);return t}async function*Yr(t,e,n,i={}){let{offset:o,limit:r,cursor:s,...a}=n,c=wn(o,0),l=st(i.firstPageSize??i.pageSize??r,200),u=st(i.pageSize??r,1e3),f=s,p=s!==void 0,h=Cn(i.maxResults),m=vn(e,i.signal,s),P=0,v=0;try{for(;!i.signal?.aborted&&P<h;){m.startRequest();let b=f,C=await t({...a,...p?{}:{limit:Math.min(v===0?l:u,h-P)},...p&&b?{cursor:b}:{offset:c}},{signal:i.signal,timeoutMs:i.pageTimeoutMs,coordination:{...i.coordination,coalesce:!1}});if(m.finishRequest(C.ok?C.value.meta.cursor:void 0),i.signal?.aborted)return;if(!C.ok){m.dispose(),yield C;return}let y=C.value,A=y.meta.cursor;if(A?(p=!0,f=A):p&&(f=void 0),p&&y.meta.hasMore&&!A){m.dispose(),yield g(w("invalid_operation_response","The collection authority omitted the cursor required for the next saved-view page."));return}let D=h-P,S=y.results.length>D?y.results.slice(0,D):y.results;P+=S.length;let T=P>=h||!y.meta.hasMore||y.results.length===0,M={...y,results:S,page:v,offset:c,loaded:P,complete:T,...A?{cursor:A}:{}};if(T&&m.dispose(),i.onProgress?.(M),yield R(M,C.diagnostics),T)return;c+=y.results.length,v+=1}}finally{m.dispose()}}function Xr(t){if(t!==!1)return{initialDelayMs:Math.max(0,t?.initialDelayMs??500),maxDelayMs:Math.max(0,t?.maxDelayMs??15e3),multiplier:Math.max(1,t?.multiplier??2),...t?.maxAttempts===void 0?{}:{maxAttempts:Math.max(0,t.maxAttempts)}}}var Rn=class{constructor(e,n,i,o,r){this.watch=e;this.input=i;this.watchStartTimeoutMs=r;this.pendingChanges=[...o],this.currentStatus={state:"connected",cursor:n,recovered:!1};let s=i.lifetimeSignal;if(s?.aborted)this.close();else if(s){let a=()=>this.close();s.addEventListener("abort",a,{once:!0}),this.removeLifetimeAbort=()=>s.removeEventListener("abort",a)}this.controller.signal.aborted||this.run(n)}watch;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,n,i){this.changes.add(e),n&&(this.statuses.add(n),n(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),n&&this.statuses.delete(n),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 n=!0,i=this.watch({cursor:e,pollIntervalMs:this.input.pollIntervalMs,retry:this.input.retry,signal:this.controller.signal,timeoutMs:this.watchStartTimeoutMs,onStatus:o=>{if(n&&o.state==="connecting"){n=!1;return}n=!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 n of this.statuses)n(e)}};var at=class{constructor(e,n=Qe,i){this.transport=e;this.requestTimeoutMs=n;this.supportsAuthorityFeature=i;this.descriptions=new _n(e,n)}transport;requestTimeoutMs;supportsAuthorityFeature;descriptions;lastSchemaCursor=-1;get schemaGeneration(){return this.descriptions.schemaGeneration}operation(e,n,i){return I(()=>this.transport.operation(e,n,i),Ge)}describe(e){return this.descriptions.describe(e)}async changes(e={},n){let i=await this.rawOperation("changes",e,tn,n),o=j(i,Wo);if(o.ok){let r=o.value.events.filter($o);(o.value.reset||r.some(s=>s.cursor>this.lastSchemaCursor))&&(this.descriptions.invalidate(),this.lastSchemaCursor=o.value.cursor)}return o}async read(e,n){let i=await this.envelopeOperation("read",jc(e),ue,n);return j(i,Sn)}readMany(e,n={}){return Jr((i,o)=>this.queryAll(i,o),(i,o,r)=>this.envelopeOperation("read",{paths:i,include_body:o,include_document:!1},ue,r),this.supportsAuthorityFeature,e,n,this.requestTimeoutMs)}async query(e={},n){if(e.output!==void 0&&e.output!=="metadata")return g(w("invalid_request","Unknown query output mode."));if(e.output!=="metadata"){let o=await this.envelopeOperation("query",Ei(e),pe,n);return j(o,r=>Fi(r,void 0))}let i=await I(()=>k(n,this.requestTimeoutMs,async o=>{let r=de({...n,timeoutMs:null},o);if(e.includeBody)throw d("invalid_request","Metadata queries cannot include a body.");let s=await this.supportsAuthorityFeature?.("query-metadata-v1",r);if(s&&!s.ok)throw new _(s.problem);if(!s?.value)throw d("unsupported_operation","This authority does not support metadata queries. Use an ordinary query on legacy authorities.");let a=await this.envelopeOperation("query",Ei(e),pe,r);return j(a,c=>Fi(c,e.output))}),pe);return i.ok?i.value:i}async*queryPages(e={},n={}){yield*Wr((i,o)=>this.query(i,o),i=>this.releaseQueryCursor(i,e.output),e,n)}async queryAll(e={},n={}){let i=ve(n,this.requestTimeoutMs),o=[],r,s=[];try{let a={firstPageSize:n.firstPageSize,pageSize:n.pageSize,maxResults:n.maxResults,signal:i.signal,pageTimeoutMs:null,coordination:n.coordination},c=e.output==="metadata"?this.queryPages(e,{...a,onProgress:n.onProgress}):this.queryPages(e,{...a,onProgress:n.onProgress});for await(let u of c){if(!u.ok)return u;let f=u.value;o.push(...f.results),r=f,s.push(...u.diagnostics)}if(i.signal.aborted)throw te(i.signal);let l=r?{...r.meta?.totalCount===void 0?r.meta?.hasMore?{}:{totalCount:o.length}:{totalCount:r.meta.totalCount},...r.meta?.hasMore&&r.meta.totalCountOutcome?{totalCountOutcome:r.meta.totalCountOutcome}:{},hasMore:r.meta?.hasMore??!1,...r.snapshot?{snapshot:r.snapshot}:{}}:void 0;return e.output==="metadata"?R({output:"metadata",results:o,...l?{meta:l}:{}},s):R({results:o,...l?{meta:l}:{}},s)}catch(a){if(a instanceof _)return g(a.problem);throw a}finally{i.dispose()}}async listViews(e){let n=await this.envelopeOperation("list_views",{},ue,e);return j(n,i=>({views:i.views,meta:{totalCount:i.meta.total_count}}))}async executeView(e,n){let i=await this.envelopeOperation("execute_view",e,ue,n);return j(i,$c)}async*executeViewPages(e,n={}){yield*Yr((i,o)=>this.executeView(i,o),i=>this.releaseQueryCursor(i),e,n)}readViewSource(e,n){return this.envelopeOperation("read_view_source",e,ue,n)}createViewSource(e,n){return this.envelopeOperation("create_view_source",e,G,n)}updateViewSource(e,n){return this.envelopeOperation("update_view_source",zi(e),G,n)}deleteViewSource(e,n){return this.envelopeOperation("delete_view_source",zi(e),G,n)}async create(e,n){let i=await this.envelopeOperation("create",Bc(e),G,n);return j(i,Sn)}async update(e,n){let i=await this.envelopeOperation("update",Kc(e),G,n);return j(i,Sn)}async delete(e,n){let i=await this.envelopeOperation("delete",Zr(e),G,n);return j(i,ss)}async preflightDelete(e,n){let i=await this.envelopeOperation("delete",{...Zr(e),check_backlinks:!0,dry_run:!0},G,n);return j(i,Gc)}async rename(e,n){let i=await this.envelopeOperation("rename",es(e),G,n);return j(i,Hc)}async preflightRename(e,n){let i=await this.envelopeOperation("rename",{...es(e),dry_run:!0},G,n);return j(i,Wc)}validate(e={},n){return this.envelopeOperation("validate",e,ue,n)}readType(e,n){return this.envelopeOperation("read_type",e,we,n)}createType(e,n){return this.envelopeOperation("create_type",e,we,n)}updateType(e,n){return this.envelopeOperation("update_type",zi(e),we,n)}async assessTypePack(e,n){let i=await this.envelopeOperation("assess_type_pack",os(e),we,n);return j(i,Ui)}async applyTypePack(e,n){let i=await this.envelopeOperation("apply_type_pack",Qc(e),we,n);return j(i,Yc)}async assessCollectionSetup(e,n){let i=await this.envelopeOperation("assess_collection_setup",rs(e),we,n);return j(i,is)}async applyCollectionSetup(e,n){let i=await this.envelopeOperation("apply_collection_setup",Vc(e),we,n);return j(i,o=>({assessment:is(o.assessment),receipt:Xc(o.receipt)}))}async listTimers(e,n){let i=await this.rawOperation("list_timers",{namespace:e},ue,n);return j(i,o=>({namespace:o.namespace,timers:o.timers.map(Li)}))}async putTimer(e,n){let i=await this.rawOperation("put_timer",{namespace:e.namespace,criterion_id:e.criterionId,timer:ts(e.timer)},G,n);return j(i,Li)}cancelTimer(e,n){return this.rawOperation("cancel_timer",e,G,n)}async reconcileTimers(e,n){let i=await this.rawOperation("reconcile_timers",{namespace:e.namespace,criterion_id:e.criterionId,timers:e.timers.map(ts)},G,n);return j(i,o=>({namespace:o.namespace,timers:o.timers.map(Li),cancelledIds:o.cancelled_ids}))}async*watch(e={}){let n=e.cursor,i=Math.max(100,e.pollIntervalMs??1e3),o=Xr(e.retry),r=0,s=!1;for(e.onStatus?.({state:"connecting",...n===void 0?{}:{cursor:n}});!e.signal?.aborted;){let a=await this.changes(n===void 0?{}:{after:n,limit:200},{signal:e.signal,timeoutMs:e.timeoutMs});if(!a.ok){let u=a.problem;if(e.signal?.aborted)return;if(!o||u.recovery!=="retry"){yield a;return}if(s=!1,r+=1,o.maxAttempts!==void 0&&r>o.maxAttempts){yield a;return}let f=Math.min(o.maxDelayMs,Math.round(o.initialDelayMs*o.multiplier**(r-1)));e.onStatus?.({state:"reconnecting",...n===void 0?{}:{cursor:n},attempt:r,retryInMs:f,problem:u});try{await oe(f,e.signal)}catch{if(!e.signal?.aborted)throw d("operation_failed","Watch retry delay failed unexpectedly.")}continue}let c=a.value;if(n===void 0){n=c.cursor;continue}if(c.reset){let u=w("change_cursor_reset","The collection change cursor expired. Refresh collection state before subscribing again.");e.onStatus?.({state:"reset_required",cursor:n,problem:u}),yield g(u);return}let l=r>0;r=0,(!s||l)&&e.onStatus?.({state:"connected",cursor:n,recovered:l}),s=!0;for(let u of c.events)yield R(u);if(n=c.cursor,!c.hasMore)try{await oe(i,e.signal)}catch{if(!e.signal?.aborted)throw d("operation_failed","Watch polling delay failed unexpectedly.")}}}rawOperation(e,n,i,o){return I(()=>this.transport.operation(e,n,o),i)}async releaseQueryCursor(e,n){try{await k({timeoutMs:2e3},null,async i=>{let o=de({signal:i.signal,timeoutMs:null,coordination:{coalesce:!1}},i);if(n){let r=await this.supportsAuthorityFeature?.("query-metadata-v1",o);if(!r?.ok||!r.value)return}await this.envelopeOperation("query",{release_cursor:e,...n?{output:n}:{}},pe,o)})}catch{}}async envelopeOperation(e,n,i,o){let r=await I(()=>this.transport.operation(e,n,o),i);if(!r.ok)return r;let s=r.value;return s.valid?(["create_type","update_type","apply_type_pack","apply_collection_setup","create_view_source","update_view_source","delete_view_source"].includes(e)&&this.descriptions.invalidate(),R(s.result,s.diagnostics)):g(je(s))}};function j(t,e){if(!t.ok)return t;try{return R(e(t.value),t.diagnostics)}catch(n){if(n instanceof _)return g(n.problem);throw n}}function jc(t){return{path:t.path,...t.contract?{contract:t.contract}:{},...t.includeDocument===void 0?{}:{include_document:t.includeDocument}}}function Bc(t){return{...t.path?{path:t.path}:{},...t.type?{type:t.type}:{},...t.contract?{contract:t.contract}:{},...t.frontmatter?{frontmatter:t.frontmatter}:{},...t.body===void 0?{}:{body:t.body},...t.ifRevision?{if_revision:t.ifRevision}:{},...t.includeDocument===void 0?{}:{include_document:t.includeDocument}}}function Kc(t){return{path:t.path,...t.contract?{contract:t.contract}:{},...t.ifRevision?{if_revision:t.ifRevision}:{},...t.includeDocument===void 0?{}:{include_document:t.includeDocument},...t.document===void 0?{patch:t.patch,...t.body===void 0?{}:{body:t.body}}:{document:t.document}}}function Zr(t){return{path:t.path,...t.contract?{contract:t.contract}:{},...t.checkBacklinks===void 0?{}:{check_backlinks:t.checkBacklinks},...t.ifRevision?{if_revision:t.ifRevision}:{}}}function es(t){return{from:t.from,to:t.to,...t.contract?{contract:t.contract}:{},...t.updateRefs===void 0?{}:{update_refs:t.updateRefs},...t.ifRevision?{if_revision:t.ifRevision}:{},...t.includeDocument===void 0?{}:{include_document:t.includeDocument}}}function zi(t){let{ifRevision:e,...n}=t;return{...n,...e?{if_revision:e}:{}}}function os(t){return{provision:t.provision,installed_by:t.installedBy,...t.adoptResources?{adopt_resources:t.adoptResources}:{},...t.preserveSeedTargets?{preserve_seed_targets:t.preserveSeedTargets}:{},...t.targetOverrides?{target_overrides:t.targetOverrides}:{},...t.contractSetups?{contract_setups:t.contractSetups.map(as)}:{}}}function Qc(t){return{...os(t),expected_assessment_digest:t.expectedAssessmentDigest,...t.allowDowngrade===void 0?{}:{allow_downgrade:t.allowDowngrade}}}function rs(t){return{application_id:t.applicationId,declaration_digest:t.declarationDigest,requirements:t.requirements,provisions:{configuration:t.provisions.configuration,type_packs:t.provisions.typePacks},...t.contractSetups?{contract_setups:t.contractSetups.map(as)}:{},...t.typePackAdoptions?{type_pack_adoptions:t.typePackAdoptions}:{}}}function Vc(t){return{...rs(t),expected_assessment_digest:t.expectedAssessmentDigest,expected_collection_revision:t.expectedCollectionRevision,expected_provision_digest:t.expectedProvisionDigest,...t.allowTypePackDowngrades?{allow_type_pack_downgrades:t.allowTypePackDowngrades}:{}}}function ss(t){return{path:t.path,deleted:t.deleted,...t.broken_links?{brokenLinks:t.broken_links}:{}}}function Gc(t){return{...ss(t),deleted:!1,dryRun:!0,wouldDelete:!0}}function Hc(t){let{references_updated:e,...n}=t;return{...Sn(n),from:t.from,to:t.to,...e?{referencesUpdated:e}:{}}}function Wc(t){return{from:t.from,to:t.to,dryRun:!0,wouldRename:!0,...t.references_affected?{referencesAffected:t.references_affected}:{},...t.warnings?{warnings:t.warnings}:{}}}function ts(t){return{id:t.id,fire_at:t.fireAt,...t.data===void 0?{}:{data:t.data}}}function Li(t){return{id:t.id,fireAt:t.fire_at,...t.data===void 0?{}:{data:t.data},criterionId:t.criterion_id,generation:t.generation,status:t.status,createdAt:t.created_at,updatedAt:t.updated_at,firedAt:t.fired_at}}function as(t){return t.mode==="starter"?t:{contract:t.contract,mode:"existing",type_name:t.typeName,type_revision:t.typeRevision,fields:t.fields,...t.binding?{binding:t.binding}:{}}}function Sn(t){let{effective_frontmatter:e,contract:n,...i}=t;return{...i,effectiveFrontmatter:e,...n?{contract:gn(n)}:{}}}function $c(t){return{results:t.results.map(e=>{let n=qi(e);if(!n.effectiveFrontmatter)throw new Error("Saved view result omitted canonical effective frontmatter.");return{...n,effectiveFrontmatter:n.effectiveFrontmatter}}),meta:{totalCount:t.meta.total_count,hasMore:t.meta.has_more,...t.meta.cursor?{cursor:t.meta.cursor}:{},view:t.meta.view,...t.meta.context?{context:t.meta.context}:{},...t.meta.groups?{groups:t.meta.groups}:{}}}}function ns(t){return{source:t.source,target:t.target,kind:t.kind,mode:t.mode,action:t.action,digest:t.digest,...t.current_digest?{currentDigest:t.current_digest}:{},...t.installed_digest?{installedDigest:t.installed_digest}:{},...t.adopted_from_digest?{adoptedFromDigest:t.adopted_from_digest}:{},...t.upgrade_baseline?{upgradeBaseline:t.upgrade_baseline}:{},...t.reason?{reason:t.reason}:{}}}function On(t){return{id:t.id,version:t.version,digest:t.digest,installedBy:t.installed_by,resources:t.resources.map(e=>({source:e.source,target:e.target,kind:e.kind,mode:e.mode,digest:e.digest,...e.adopted_from_digest?{adoptedFromDigest:e.adopted_from_digest}:{},...e.origin_digest?{originDigest:e.origin_digest}:{}}))}}function Jc(t){return t.mode==="starter"?t:{contract:t.contract,mode:"existing",typeName:t.type_name,typeRevision:t.type_revision,fields:t.fields,...t.binding?{binding:t.binding}:{}}}function Ui(t){return{status:t.status,applicable:t.applicable,assessmentDigest:t.assessment_digest,...t.current?{current:On(t.current)}:{},desired:On(t.desired),resources:t.resources.map(ns),lock:t.lock,contractSetups:{choices:t.contract_setups.choices.map(Jc),resources:t.contract_setups.resources.map(ns)}}}function Yc(t){return{...Ui(t),receipt:On(t.receipt),cleanupDeferred:t.cleanup_deferred}}function is(t){return{status:t.status,applicable:t.applicable,applicationId:t.application_id,declarationDigest:t.declaration_digest,provisionDigest:t.provision_digest,collectionRevision:t.collection_revision,finalCollectionRevision:t.final_collection_revision,configuration:t.configuration,typePacks:t.type_packs.map(Ui),finalResourceRevisions:t.final_resource_revisions,assessmentDigest:t.assessment_digest}}function Xc(t){return{applicationId:t.application_id,declarationDigest:t.declaration_digest,provisionDigest:t.provision_digest,assessmentDigest:t.assessment_digest,collectionRevision:t.collection_revision,configuration:t.configuration,typePacks:t.type_packs.map(On),cleanupDeferred:t.cleanup_deferred}}async function Ni(t,e,n,i){for(;;){ee(n);try{let o=await t("GET",`?${e}`,void 0,n);if(o?.protocol_version!==1||o.type!=="files_page"||!Array.isArray(o.files)||o.next!==void 0&&(typeof o.next!="string"||!o.next))throw d("invalid_operation_response","The authority returned an invalid file page.");return ze(o.authority_capabilities),o}catch(o){let r=_e(o);if(r.code!=="file_index_warming")throw r;i?.(),await oe(500,n)}}}async function*cs(t,e,n,i){let o=ve(n,i);try{ds(t());let r;do{let s=new URLSearchParams({protocol_version:"1",...n.folder?{folder:n.folder}:{},...r?{after:r}:{},...n.pageSize?{limit:String(Go(n.pageSize))}:{}}),a=await Ni(e,s,o.signal,n.onIndexing);for(let c of a.files)ee(o.signal),yield fe(c);r=a.next}while(r)}finally{o.dispose()}}function ls(t,e,n,i,o,r,s){return I(()=>k(r,s,async a=>{if(ds(t()),!o||typeof o!="object"||Object.keys(o).length!==1||!(Object.hasOwn(o,"path")&&typeof o.path=="string"||Object.hasOwn(o,"fileId")&&typeof o.fileId=="string"&&fi.test(o.fileId)))throw d("invalid_request","File stat requires exactly one path or UUID fileId.");if(o.path!==void 0&&(o.path.length>1024||o.path.includes("\\")||o.path.split("/").some(u=>!u||u.startsWith("."))))throw d("invalid_request","File stat requires a collection-relative file path.");let c=await n("files-stat-v1",{signal:a.signal,timeoutMs:null});if(!c.ok)throw new _(c.problem);if(ee(a.signal),c.value){let u=await e("POST","stat",{protocol_version:1,type:"stat_file",...o.path!==void 0?{path:o.path}:{file_id:o.fileId}},a.signal);if(u?.protocol_version!==1||u.type!=="file_stat"||u.file===void 0)throw d("invalid_operation_response","The authority returned an invalid file stat.");if(u.file===null)return null;let f=fe(u.file);if(o.path!==void 0?Pn(f.path)!==Pn(o.path):f.fileId.toLowerCase()!==o.fileId.toLowerCase())throw d("invalid_operation_response","The authority returned a stat for a different file.");return f}let l=o.path?.includes("/")?o.path.slice(0,o.path.lastIndexOf("/")):void 0;for await(let u of i({folder:l,signal:a.signal,timeoutMs:null}))if(ee(a.signal),o.path!==void 0?Pn(u.path)===Pn(o.path):u.fileId.toLowerCase()===o.fileId.toLowerCase())return u;return ee(a.signal),null}),Ge)}function ds(t){if(!t?.actions.includes("list"))throw d("not_authorized","This connection is not authorized to list files.")}function Pn(t){return Array.from(t.normalize("NFC"),e=>e.toLowerCase()).join("").normalize("NFC")}var An=class{constructor(e){this.context=e}context;async registerNotifications(e){return k(e,this.context.requestTimeoutMs,n=>this.registerNotificationsWithinBudget(e,n.signal))}async registerNotificationsWithinBudget(e,n){let i=await this.context.authorizedToken(n);if(!i)throw d("not_authorized","Connect this application before enabling notifications.");let r=(await this.context.register(n)).notifications?.criteria.map(b=>b.id)??[],s=[...new Set(e.criteria??r)],a=s.find(b=>!r.includes(b));if(a)throw d("notification_criterion_not_declared",`The application manifest does not declare notification criterion ${a}.`);if(s.length===0)throw d("notifications_not_declared","This application manifest does not declare any notification criteria.");let c=await ae(`${this.context.serverUrl}/v1/notifications/vapid-public-key`,{signal:n},"notifications_unavailable","Push notifications are unavailable."),l=await E(c,"invalid_operation_response","Connect returned an invalid notification key response.");if(!c.ok)throw z(l,"notifications_unavailable","Push notifications are unavailable.",c.status);let u=await e.serviceWorker.pushManager.getSubscription();u||(u=await e.serviceWorker.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:nn(l.public_key)}));let f=u.toJSON();if(!f.endpoint||!f.keys?.p256dh||!f.keys.auth)throw d("invalid_push_subscription","The browser returned an incomplete push subscription.");let p=F(this.context.storage.getItem(this.context.notificationKey())),h=e.installationId??p?.installationId??se(24),m=await ae(`${this.context.serverUrl}/v1/notifications/channels`,{method:"POST",headers:{authorization:`Bearer ${i.accessToken}`,"content-type":"application/json"},body:JSON.stringify({installation_id:h,criteria:s,subscription:{endpoint:f.endpoint,expirationTime:f.expirationTime??null,keys:f.keys}}),signal:n},"notification_registration_failed","Could not register push notifications."),P=await E(m,"invalid_operation_response","Connect returned an invalid notification registration response.");if(!m.ok)throw z(P,"notification_registration_failed","Could not register push notifications.",m.status);p?.channelId&&p.channelId!==P.channel_id&&fetch(`${this.context.serverUrl}/v1/notifications/channels/${p.channelId}`,{method:"DELETE",headers:{authorization:`Bearer ${i.accessToken}`},signal:n}).catch(()=>{});let v={channelId:P.channel_id,installationId:h,criteria:s};return this.context.storage.setItem(this.context.notificationKey(),JSON.stringify(v)),v}async registerNativeNotifications(e){return k(e,this.context.requestTimeoutMs,n=>this.registerNativeNotificationsWithinBudget(e,n.signal))}async registerNativeNotificationsWithinBudget(e,n){let i=await this.context.authorizedToken(n);if(!i)throw d("not_authorized","Connect this application before enabling notifications.");let o=await this.context.register(n);if(o.notifications?.native_delivery?.mode!=="managed_fcm")throw d("managed_fcm_not_declared","This application does not declare Connect-managed native notifications.");let r=o.notifications.criteria.map(m=>m.id),s=[...new Set(e.criteria??r)],a=s.find(m=>!r.includes(m));if(a)throw d("notification_criterion_not_declared",`The application manifest does not declare notification criterion ${a}.`);if(s.length===0)throw d("notifications_not_declared","This application manifest does not declare any notification criteria.");let c=this.context.notificationKey("fcm"),l=F(this.context.storage.getItem(c)),u=e.installationId??l?.installationId??se(24),f=await ae(`${this.context.serverUrl}/v1/notifications/channels`,{method:"POST",headers:{authorization:`Bearer ${i.accessToken}`,"content-type":"application/json"},body:JSON.stringify({installation_id:u,criteria:s,transport:"fcm",token:e.token}),signal:n},"notification_registration_failed","Could not register native notifications."),p=await E(f,"invalid_operation_response","Connect returned an invalid native notification response.");if(!f.ok)throw z(p,"notification_registration_failed","Could not register native notifications.",f.status);l?.channelId&&l.channelId!==p.channel_id&&this.deleteNotificationChannel(l.channelId,i.accessToken,n).catch(()=>{});let h={channelId:p.channel_id,installationId:u,transport:"fcm",criteria:s};return this.context.storage.setItem(c,JSON.stringify(h)),h}async unregisterNativeNotifications(e={}){return k(e,this.context.requestTimeoutMs,n=>this.unregisterNativeNotificationsWithinBudget(n.signal))}async unregisterNativeNotificationsWithinBudget(e){let n=this.context.notificationKey("fcm"),i=F(this.context.storage.getItem(n)),o=await this.context.authorizedToken(e);if(i?.channelId&&!o)throw d("not_authorized","Reconnect this application before disabling native notifications.");i?.channelId&&o&&await this.deleteNotificationChannel(i.channelId,o.accessToken,e),this.context.storage.removeItem(n)}async unregisterNotifications(e,n={}){return k(n,this.context.requestTimeoutMs,i=>this.unregisterNotificationsWithinBudget(e,i.signal))}async unregisterNotificationsWithinBudget(e,n){let i=F(this.context.storage.getItem(this.context.notificationKey())),o=await this.context.authorizedToken(n);if(i?.channelId&&!o)throw d("not_authorized","Reconnect this application before disabling push notifications.");if(i?.channelId&&o){let s=await ae(`${this.context.serverUrl}/v1/notifications/channels/${i.channelId}`,{method:"DELETE",headers:{authorization:`Bearer ${o.accessToken}`},signal:n},"notification_unregistration_failed","Could not unregister push notifications.");if(!s.ok&&s.status!==404){let a=await E(s,"invalid_operation_response","Connect returned an invalid notification response.");throw z(a,"notification_unregistration_failed","Could not unregister push notifications.",s.status)}}this.context.storage.removeItem(this.context.notificationKey()),await(await e?.pushManager.getSubscription())?.unsubscribe()}async deleteNotificationChannel(e,n,i){let o=await ae(`${this.context.serverUrl}/v1/notifications/channels/${e}`,{method:"DELETE",headers:{authorization:`Bearer ${n}`},signal:i},"notification_unregistration_failed","Could not unregister push notifications.");if(!o.ok&&o.status!==404){let r=await E(o,"invalid_operation_response","Connect returned an invalid notification response.");throw z(r,"notification_unregistration_failed","Could not unregister push notifications.",o.status)}}};async function us(t,e){let n=new TextEncoder().encode(`${t}
4
- ${e}`),i=new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",n));return Array.from(i,o=>o.toString(16).padStart(2,"0")).join("")}async function ps(t,e,n){let i=n?.path;return e==="update"&&typeof i=="string"?us(t,i):void 0}async function fs(t,e,n){let i=await us(e,n);return t.find(o=>o.operation==="update"&&o.recordDigest===i)?.requestId??null}async function Tn(t,e,n,i,o,r){if(!t.authority)throw d("not_remote_authority","This authorization has no remote authority endpoint.");let s=n===""||n.startsWith("?")?n:`/${n}`,a=`${t.authority.filesUrl}${s}`,c=i===void 0?void 0:JSON.stringify(i),l=await r(t,e,a,c,t.authority.accessToken);return fetch(a,{method:e,redirect:"error",headers:{authorization:`Bearer ${t.authority.accessToken}`,...c===void 0?{}:{"content-type":"application/json"},...l},...c===void 0?{}:{body:c},...o?{signal:o}:{}})}async function hs(t,e,n,i,o,r,s,a=async c=>c){let c=t,l=await Tn(c,e,n,i,o,s);if(l.status===401&&c.refreshToken){if(c=await a(await r(o)),!c.authority||!c.fileCapability)throw d("authority_authorization_changed","Reconnect this collection before accessing its files.");l=await Tn(c,e,n,i,o,s)}let u=await E(l,"invalid_operation_response","The hosted authority returned an invalid file response.");if(!l.ok)throw z(u,"operation_failed","Collection file request failed.",l.status);return u}async function ms(t,e,n,i,o,r,s=async a=>a){let a=t,c=await Tn(a,"GET",e,void 0,i,r);if(c.status===401&&a.refreshToken){if(a=await s(await o(i)),!a.authority||!a.fileCapability)throw d("authority_authorization_changed","Reconnect this collection before accessing its files.");c=await Tn(a,"GET",e,void 0,i,r)}if(!c.ok){let u=await E(c,"invalid_operation_response","The hosted authority returned an invalid file range error response.");throw z(u,"operation_failed","Collection file range request failed.",c.status)}let l=c.headers.get("content-length");if(l===null||!/^(0|[1-9][0-9]*)$/u.test(l)||Number(l)!==n)throw await c.body?.cancel().catch(()=>{}),d("invalid_operation_response","The hosted file response declared an unexpected byte length.");if(!c.body)throw d("invalid_operation_response","The hosted file response did not contain a byte stream.");return c.body}var Mn=class{constructor(e,n){this.namespace=e;this.onFinalRelease=n}namespace;onFinalRelease;leases=new Map;locks=Zc();retainAutomaticallyRetiredKeys=this.locks===null;async acquire(e,n,i){let o=this.acquireLocal(e,n);if(!this.locks)return o;try{let r=await el(this.locks,this.lockName(e,n),i);return ji(()=>{r(),o()})}catch(r){throw o(),r}}deleteExclusive(e,n,i){this.retainAutomaticallyRetiredKeys||(this.locks?this.locks.request(this.lockName(e,n),{mode:"exclusive"},i).catch(()=>{}):this.has(e,n)||Promise.resolve().then(i).catch(()=>{}))}has(e,n){return this.leases.get(e)?.has(n)??!1}handles(e){return this.leases.get(e)?.keys()??[]}acquireLocal(e,n){let i=this.leases.get(e)??new Map;return i.set(n,(i.get(n)??0)+1),this.leases.set(e,i),ji(()=>{let o=(i.get(n)??1)-1;o>0?i.set(n,o):(i.delete(n),i.size===0&&this.leases.delete(e),this.onFinalRelease(e,n))})}lockName(e,n){return`mdbase-connect:grant-key:${this.namespace}:${e}:${n}`}},Pe=class{constructor(e,n){this.collectionId=e;this.acquire=n}collectionId;acquire;releases=new Map;async retain(e,n){let i=typeof e=="string"?e:e?.keyHandle;if(!i)return;let o=this.releases.get(i);o||(o=this.acquire(this.collectionId,i,n),this.releases.set(i,o));try{await o}catch(r){throw this.releases.get(i)===o&&this.releases.delete(i),this.release(),r}}release(){for(let e of this.releases.values())e.then(n=>n());this.releases.clear()}};async function $(t,e,n){for(;;){let i=t();if(!i)return null;await e.retain(i,n);let o=t();if(!o)return null;if(o.keyHandle===i.keyHandle)return o}}function Zc(){let t=typeof navigator>"u"?void 0:navigator.locks;return t||(typeof window<"u"||typeof globalThis.importScripts=="function"?null:void 0)}async function el(t,e,n){let i,o,r,s=new Promise((l,u)=>{i=l,o=u}),a=new Promise(l=>{r=l});return t.request(e,{mode:"shared",...n?{signal:n}:{}},async()=>{i(),await a}).catch(o),await s,ji(r)}function ji(t){let e=!1;return()=>{e||(e=!0,t())}}var tl="mdbase-connect file chunk key v1",In=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,ge=class extends Error{constructor(n,i){super(i);this.code=n;this.name="FileTransferCryptoError"}code},ct=class t{constructor(e,n){this.binding=e;this.key=n}binding;key;static async open(e,n,i){ys(i);let o=await e.get(n);if(!o||o.agreementPublicKey!==i.encryption.application_agreement_public_key)throw new q("missing_grant_key","The encrypted grant key is unavailable or does not match the file transfer grant.");let r=await St(o.agreementPrivateKey,i.encryption.connector_agreement_public_key);return t.fromSharedSecret(r,i)}static async fromSharedSecret(e,n){ys(n);let i=await Bi(e,n);return new t(n,i)}async encryptChunk(e,n,i){if(this.validateHeader(n),i.byteLength!==n.plaintext_length)throw new ge("plaintext_length_mismatch","File chunk plaintext length does not match its authenticated header.");let o=jt(e,n),r=await crypto.subtle.encrypt({name:"AES-GCM",iv:gs(n.chunk_index),additionalData:kn(o),tagLength:128},this.key,kn(i));return ho({kind:e,header:n,payload:new Uint8Array(r)})}async decryptChunk(e){let n=Bt(e);this.validateHeader(n.header);let i=jt(n.kind,n.header);try{let o=await crypto.subtle.decrypt({name:"AES-GCM",iv:gs(n.header.chunk_index),additionalData:kn(i),tagLength:128},this.key,kn(n.payload));return new Uint8Array(o)}catch{throw new ge("authentication_failed","The encrypted file chunk could not be authenticated.")}}validateHeader(e){let n=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!==n.collection_id||e.transfer_id!==this.binding.transferId||e.direction!==this.binding.direction||e.scope_epoch!==n.scope_epoch||e.key_id!==n.key_id)throw new ge("header_binding_mismatch","The file frame does not match its transfer encryption binding.")}};async function Bi(t,e){let n=new TextEncoder().encode(nl(e)),i=await crypto.subtle.digest("SHA-256",n),o=await crypto.subtle.importKey("raw",t,"HKDF",!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:i,info:new TextEncoder().encode(tl)},o,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}function ys(t){if(ye(t.encryption),!In.test(t.grantId)||!In.test(t.applicationId)||!In.test(t.authorityId)||!In.test(t.transferId)||t.direction!=="upload"&&t.direction!=="download")throw new ge("invalid_binding","The file transfer encryption binding is invalid.")}function nl(t){let e=t.encryption;return["mdbase-connect","file-transfer",1,e.suite,t.grantId,t.applicationId,e.connector_id,t.authorityId,e.collection_id,e.scope_epoch,e.key_id,t.transferId,t.direction].join("|")}function gs(t){if(!Number.isSafeInteger(t)||t<0)throw new ge("invalid_chunk_index","The file chunk index is invalid.");let e=new Uint8Array(new ArrayBuffer(12));return new DataView(e.buffer).setBigUint64(4,BigInt(t),!1),e}function kn(t){return t.buffer instanceof ArrayBuffer?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Uint8Array.from(t)}var qn=class{constructor(e){this.options=e}options;async control(e,n,i,o,r){let s=this.grantKeyLeases(e.collectionId);try{return e=await this.retainEntryToken(e,s,r),await this.controlAttempt(e,n,i,o,r,!1,0,s)}finally{s.release()}}async controlAttempt(e,n,i,o,r,s,a,c){lt(e);let l=Qi(n,i,o),u=await this.encryptControl(e,l),f,p=await this.options.shouldAttemptDirect(e);if(p){try{f=await fetch(`${this.options.loopbackUrl}/v1/files/control`,Se({method:"POST",headers:{"content-type":"application/mdbase-connect+json"},body:JSON.stringify(u),signal:r}))}catch(h){if(r?.aborted)throw h;this.options.onDirectUnavailable()}if(f&&(!await Je(f)||await Be(f)))return f.ok&&this.options.onDirectAvailable(),this.decryptControlResponse(e,n,i,o,r,u,f,s,a,c);f&&this.options.onDirectUnavailable()}return p&&!Z("file_control",l)&&(e=e.expiresAt>Date.now()+3e4?e:await this.options.refreshAuthorization(r),e=await this.retainEntryToken(e,c,r),En(e),u=await this.encryptControl(e,l)),f=await this.sendRelayControl(e,u,r),await ol(f,e)&&(e=await this.options.refreshAuthorization(r),e=await this.retainEntryToken(e,c,r),En(e),u=await this.encryptControl(e,l),f=await this.sendRelayControl(e,u,r)),f.ok&&this.options.onRelayAvailable(),this.decryptControlResponse(e,n,i,o,r,u,f,s,a,c)}async decryptControlResponse(e,n,i,o,r,s,a,c,l,u){let f=await E(a,"invalid_operation_response","The collection authority returned an invalid file control response.");if(!a.ok){let m=z(f,"operation_failed","Collection file request failed.",a.status);if(Ht(m)&&l<Gt)return await Wt(l,r),this.controlAttempt(e,n,i,o,r,c,l+1,u);if(m.code==="fresh_request_required"&&!Z("file_control",Qi(n,i,o))&&!c)return this.controlAttempt(e,n,i,o,r,!0,l,u);throw m}let p=f?.envelope;if(!p)throw d("invalid_encrypted_response","The connector omitted its encrypted file response.");let h=await $e(this.options.keyStore,e.keyHandle,Vi(e),s,p);if(!h.ok&&h.problem.code==="fresh_request_required"&&!Z("file_control",Qi(n,i,o))&&!c)return this.controlAttempt(e,n,i,o,r,!0,l,u);if(!h.ok){let m=al(h.problem);if(Ht(m)&&l<Gt)return await Wt(l,r),this.controlAttempt(e,n,i,o,r,c,l+1,u);throw m}return h.result}async uploadChunk(e,n,i,o,r){let s=r??await this.localFileToken(e,"upload",o),a=this.grantKeyLeases(s.collectionId);try{let c=await this.retainEntryToken(s,a,o);return Ki(c,e,"upload"),await this.uploadChunkWithLease(c,a,e,n,i,o)}finally{a.release()}}async uploadChunkWithLease(e,n,i,o,r,s){let a=e,c=await bs(this.options.keyStore,a,i,o,r),l;if(await this.options.shouldAttemptDirect(a)){try{l=await fetch(`${this.options.loopbackUrl}/v1/files/upload`,Se(_s(c,s)))}catch(u){if(s?.aborted)throw u;this.options.onDirectUnavailable()}if(l&&(!await Je(l)||await Be(l)))return l.ok&&this.options.onDirectAvailable(),il(l,"Encrypted file chunk upload failed.");l&&this.options.onDirectUnavailable()}if(l=await this.sendRelayUpload(a,c,s),l.status===401&&a.refreshToken&&(a=await this.options.refreshAuthorization(s),a=await this.retainEntryToken(a,n,s),En(a),c=await bs(this.options.keyStore,a,i,o,r),l=await this.sendRelayUpload(a,c,s)),!l.ok){let u=await E(l,"invalid_operation_response","The collection authority returned an invalid file upload response.");throw z(u,"operation_failed","Encrypted file chunk upload failed.",l.status)}this.options.onRelayAvailable()}async downloadChunk(e,n,i,o){let r=o??await this.localFileToken(e,"download",i),s=this.grantKeyLeases(r.collectionId);try{return r=await this.retainEntryToken(r,s,i),Ki(r,e,"download"),await this.downloadChunkWithLease(r,s,e,n,i)}finally{s.release()}}async downloadChunkWithLease(e,n,i,o,r){let s;if(await this.options.shouldAttemptDirect(e)){try{s=await fetch(`${this.options.loopbackUrl}/v1/files/download/${encodeURIComponent(e.grantId)}/${encodeURIComponent(i.transfer_id)}/${o}`,Se({method:"GET",signal:r}))}catch(a){if(r?.aborted)throw a;this.options.onDirectUnavailable()}if(s&&(!await Je(s)||await Be(s)))return s.ok&&this.options.onDirectAvailable(),this.decryptDownloadResponse(e,i,o,s);s&&this.options.onDirectUnavailable()}return s=await this.sendRelayDownload(e,i,o,r),s.status===401&&e.refreshToken&&(e=await this.options.refreshAuthorization(r),e=await this.retainEntryToken(e,n,r),En(e),s=await this.sendRelayDownload(e,i,o,r)),s.ok&&this.options.onRelayAvailable(),this.decryptDownloadResponse(e,i,o,s)}async decryptDownloadResponse(e,n,i,o){if(!o.ok){let a=await E(o,"invalid_operation_response","The collection authority returned an invalid file download response.");throw z(a,"operation_failed","Encrypted file chunk download failed.",o.status)}if(o.headers.get("content-type")?.split(";",1)[0]!=="application/mdbase-connect-file")throw d("invalid_operation_response","The connector returned an invalid file response media type.");let r=new Uint8Array(await o.arrayBuffer()),s;try{sl(n,i,r),s=await(await Cs(this.options.keyStore,e,n)).decryptChunk(r)}catch(a){throw a instanceof _?a:d("invalid_operation_response","The connector returned an invalid encrypted file frame.",{cause:a})}if(s.byteLength!==Gi(n,i))throw d("invalid_operation_response","The connector returned a truncated file chunk.");return s}encryptControl(e,n){return lt(e),me(this.options.keyStore,e.keyHandle,Vi(e),"file_control",n)}sendRelayControl(e,n,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(n),signal:i})}sendRelayUpload(e,n,i){return fetch(`${this.options.serverUrl}/v1/authorities/${encodeURIComponent(e.collectionId)}/files/upload`,{..._s(n,i),headers:{authorization:`Bearer ${e.accessToken}`,"content-type":"application/mdbase-connect-file"}})}sendRelayDownload(e,n,i,o){return fetch(`${this.options.serverUrl}/v1/authorities/${encodeURIComponent(e.collectionId)}/files/download/${encodeURIComponent(n.transfer_id)}/${i}`,{method:"GET",headers:{authorization:`Bearer ${e.accessToken}`},signal:o})}async localFileToken(e,n,i){let o=await this.options.authorizedToken(i);return Ki(o,e,n),o}grantKeyLeases(e){return new Pe(e,this.options.acquireGrantKeyLease??(()=>Promise.resolve(()=>{})))}async retainEntryToken(e,n,i){if(!this.options.currentToken)return await n.retain(e,i),e;let o=await $(this.options.currentToken,n,i);if(o)return o;throw d("not_authorized","Reconnect this application to continue.")}};function Ki(t,e,n){if(!t||t.authority||!t.fileCapability||!t.encryption||!t.grantId||!t.keyHandle||e.direction!==n||e.protection!=="grant_aead_v1")throw d("not_authorized","This connection cannot use encrypted local file delivery.");Fn(e)}function En(t){if(t.authority||!t.fileCapability)throw d("not_authorized","This connection cannot use encrypted local file delivery.");lt(t)}async function bs(t,e,n,i,o){let r=rl(e,n,i,o.byteLength);return(await Cs(t,e,n)).encryptChunk("upload_chunk",r,o)}function _s(t,e){return{method:"POST",headers:{"content-type":"application/mdbase-connect-file"},body:Uint8Array.from(t).buffer,signal:e}}async function il(t,e){if(t.ok)return;let n=await E(t,"invalid_operation_response","The collection authority returned an invalid file transfer response.");throw z(n,"operation_failed",e,t.status)}async function ol(t,e){return e.refreshToken?t.status===401?!0:t.status!==409?!1:(await E(t.clone(),"invalid_operation_response","The collection authority returned an invalid file response.").catch(()=>null))?.error?.code==="encryption_binding_stale":!1}function lt(t){if(!t.encryption||!t.grantId||!t.keyHandle)throw d("missing_grant_key","Reconnect this application to restore encrypted file access.")}function Vi(t){return lt(t),{grantId:t.grantId,applicationId:t.clientId,encryption:t.encryption}}function Cs(t,e,n){return lt(e),ct.open(t,e.keyHandle,{...Vi(e),authorityId:e.encryption.connector_id,transferId:n.transfer_id,direction:n.direction})}function rl(t,e,n,i){lt(t);let o=Fn(e),r=Gi(e,n);if(i!==r)throw d("invalid_request","The file chunk has the wrong byte length.");return{protocol_version:1,protection:"grant_aead_v1",grant_id:t.grantId,authority_id:t.encryption.connector_id,collection_id:t.collectionId,transfer_id:e.transfer_id,direction:e.direction,chunk_size:o,chunk_index:n,offset:n*o,plaintext_length:i,total_size:e.total_size,scope_epoch:t.encryption.scope_epoch,key_id:t.encryption.key_id}}function sl(t,e,n){let i=Bt(n),o=Gi(t,e),r=Fn(t);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!==t.total_size)throw d("invalid_operation_response","The connector returned a file frame for a different chunk.")}function al(t){return L(t.code==="unknown"?t.server_code:t.code,t.message,{details:t.details,operationOutcome:t.operation_outcome??"rejected",traceId:t.trace_id})}function Qi(t,e,n){if(t==="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(t==="GET"&&i.length===2&&i[0]==="transfers")return vs("get_file_transfer_status",i[1]);if(t==="DELETE"&&i.length===2&&i[0]==="transfers")return vs("abort_file_transfer",i[1]);if(t==="POST"&&cl(n)){let o=e==="stat"?"stat_file":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"&&n.file_id===decodeURIComponent(i[0])?"move_file":i.length===2&&i[1]==="delete"&&n.file_id===decodeURIComponent(i[0])?"delete_file":null;if(o&&n.type===o)return{...n}}throw d("invalid_request","The file control request path is invalid.")}function vs(t,e){return{protocol_version:1,type:t,transfer_id:decodeURIComponent(e)}}function Fn(t){if(t.strategy.kind!=="framed_chunks"||!Number.isSafeInteger(t.strategy.chunk_size)||t.strategy.chunk_size<=0)throw d("invalid_operation_response","The connector returned an invalid framed transfer strategy.");return t.strategy.chunk_size}function Gi(t,e){let n=Fn(t);if(!Number.isSafeInteger(e)||e<0||!Number.isSafeInteger(t.total_size)||t.total_size<0)throw d("invalid_request","The file chunk index is invalid.");let i=e*n;if(!Number.isSafeInteger(i)||i>=t.total_size)throw d("invalid_request","The file chunk index is outside the transfer.");return Math.min(n,t.total_size-i)}function cl(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var Dn=class{constructor(e){this.options=e;this.local=new qn(e)}options;local;async control(e,n="",i,o){let r=await this.requireFileToken(o),s=r.token;try{return s.authority?await hs(s,e,n,i,o,this.options.refreshAuthorization,this.options.authorityProofHeaders,r.retain):await this.local.control(s,e,n,i,o)}finally{r.release()}}async uploadChunk(e,n,i,o){let r=await this.requireFileToken(o);try{return await this.local.uploadChunk(e,n,i,o,r.token)}finally{r.release()}}async downloadChunk(e,n,i){let o=await this.requireFileToken(i);try{return await this.local.downloadChunk(e,n,i,o.token)}finally{o.release()}}async downloadHostedPart(e,n,i,o){let r=await this.requireFileToken(o),s=r.token;try{if(!s.authority)throw d("not_remote_authority","Hosted file delivery requires a remote authority endpoint.");return await ms(s,`downloads/${encodeURIComponent(e.transfer_id)}/parts/${n}`,i,o,this.options.refreshAuthorization,this.options.authorityProofHeaders,r.retain)}finally{r.release()}}async requireFileToken(e){let n=new Pe(this.options.collectionId,this.options.acquireGrantKeyLease);try{await $(this.options.currentToken,n,e),await this.options.authorizedToken(e);let i=await $(this.options.currentToken,n,e);if(!i?.fileCapability)throw d("not_authorized","This connection has no file capability.");return{token:i,retain:async o=>{let r=await $(this.options.currentToken,n,e);if(r)return r;throw d("not_authorized","Reconnect this application to continue.")},release:()=>n.release()}}catch(i){throw n.release(),i}}};async function Le(t,e,n,i,o,r){if(!e.authority?.proofPublicKey)return{};if(!e.keyHandle)throw d("missing_grant_key","Reconnect this application to restore remote authority request signing.");try{let s=new URL(i);return await on(t,e.keyHandle,e.authority.proofPublicKey,{method:n,target:`${s.pathname}${s.search}`,body:o,credential:r})}catch(s){throw s instanceof q?L(s.code,s.message):s}}async function ws(t){let e=t.current;if(!e?.refreshToken)throw d("not_authorized","Reconnect this application to continue.");if((e.refreshExpiresAt??0)<=Date.now())throw d("relay_authorization_expired","Direct access is still available on this computer, but using the relay requires reconnecting this application.");let n=e.refreshToken,i=`${t.serverUrl}/oauth/token`,o=new URLSearchParams({grant_type:"refresh_token",refresh_token:e.refreshToken,client_id:e.clientId}).toString(),r=e.authority?await Le(t.keyStore,e,"POST",i,o,e.refreshToken):{},s=await fetch(i,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",...r},body:o,signal:t.signal}),a=await E(s,"invalid_token_response","The authorization service returned an invalid token response.");if(!s.ok){let c=t.currentToken();if(c?.refreshToken&&c.refreshToken!==n)return c;throw t.directCapable(e)||t.removeToken(e.keyHandle),(Tt(a)??a?.error?.code)==="invalid_grant"?d("authorization_expired",a?.error_description??a?.error?.message??"Reconnect this application to continue.",{status:s.status}):z(a,"authorization_expired","Reconnect this application to continue.",s.status)}return t.storeTokenResponse(a,e.clientId,e.keyHandle)}var zn=class{constructor(e,n){this.storage=e;this.baseKey=n}storage;baseKey;list(e){if(!e)return[];let n=F(this.storage.getItem(this.baseKey));if(Rs(n)&&n.collectionId===e){let o=this.key(n.requestId);this.storage.getItem(o)||this.storage.setItem(o,JSON.stringify(n)),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=>F(this.storage.getItem(o))).filter(o=>Rs(o)&&o.collectionId===e).sort((o,r)=>o.createdAt-r.createdAt||o.requestId.localeCompare(r.requestId))}find(e,n){return this.list(e).find(i=>i.requestId===n)??null}identifier(e){return e.mutation??be(e.operation,e.request?.input??(e.operation==="sync"?{action:"mutate"}:{}))??(e.operation==="sync"?"sync:mutate":e.operation)}summary(e){return{requestId:e.requestId,operation:this.identifier(e),fingerprint:e.inputFingerprint,status:"outcome_unknown",createdAt:new Date(e.createdAt).toISOString()}}store(e){this.storage.setItem(this.key(e.requestId),JSON.stringify(e))}take(e){let n=this.key(e),i=F(this.storage.getItem(n));return this.storage.removeItem(n),i}key(e){return`${this.baseKey}:${encodeURIComponent(e)}`}};function Rs(t){return!!(t&&typeof t.collectionId=="string"&&typeof t.requestId=="string"&&t.requestId.length>0&&mo(t.operation)&&typeof t.inputFingerprint=="string"&&Number.isFinite(t.createdAt)&&t.createdAt>0&&(t.envelope||t.request)&&(t.operation==="sync"||be(t.operation,t.request?.input??{})!==null))}function Ss({stored:t,collectionId:e,relayEncryption:n,invalidate:i,directCapable:o}){let r=F(t),s=(c,l="invalid_stored_grant")=>(i(typeof c=="string"?c:void 0,l),null);if(!r)return t&&s(),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(c=>typeof c!="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)))return s(r.keyHandle);let a=cn(r.scope);if(!a)return s(r.keyHandle);if(!ln(a))return s(r.keyHandle,"legacy_scope_reauthorization_required");if(r.fileCapability&&!an(r.fileCapability)||r.authority&&!Mr(r.authority,r.collectionId))return s(r.keyHandle);if(n==="required"){if(r.authority){if(!r.keyHandle||!r.authority.proofPublicKey)return s(r.keyHandle)}else if(!r.grantId||!r.keyHandle||!Ir(r.encryption,r.collectionId))return s(r.keyHandle)}return r.expiresAt<=Date.now()&&(!r.refreshToken||(r.refreshExpiresAt??0)<=Date.now())?o(r)?r:(i(r.keyHandle),null):r}async function Hi(t,e,n,i,o,r){if(!e.authority)throw d("not_remote_authority","This authorization has no remote authority endpoint.");let s=`${e.authority.syncUrl}/${i}`,a=o===void 0?void 0:JSON.stringify(o),c=await Le(t,e,n,s,a,e.authority.accessToken);return fetch(s,{method:n,headers:{authorization:`Bearer ${e.authority.accessToken}`,...o===void 0?{}:{"content-type":"application/json"},...c},...a===void 0?{}:{body:a},signal:r})}async function Os(t,e,n,i,o){if(!e.encryption||!e.grantId||!e.keyHandle)throw d("authorization_binding_incompatible","The refreshed authorization no longer supports encrypted connector operations.",{details:{contract:"grant_encryption",required:[1],supported:e.encryption?[e.encryption.protocol_version]:[],peer:"connector",operation:n}});try{return await me(t,e.keyHandle,{grantId:e.grantId,applicationId:e.clientId,encryption:e.encryption},n,i,void 0,o)}catch(r){throw r instanceof q?L(r.code,r.message):r}}function Ps(t,e){return!t||t.authority||!t.encryption||!t.grantId||!t.keyHandle||e==="disabled"?!1:typeof location>"u"||!t.applicationOrigin||t.applicationOrigin===Ii()}async function As(t,e,n){let i;try{i=await fetch(`${t}/v1/ready`,Se({method:"GET",cache:"no-store",signal:n}))}catch{return!1}if(i.status===403)throw L("operation_failed","The connector rejected direct access from this application. Relay access remains available.",{status:i.status});let o=await E(i,"invalid_operation_response","The connector returned an invalid readiness response.").catch(()=>null);return i.ok&&o?.service==="mdbase-connect"&&o?.loopback_protocol_version===1&&o?.operation_transport_protocol_version===e}async function Ts(t,e){try{return{body:await E(t,"invalid_operation_response","The collection authority returned a response that is not valid JSON.")}}catch(n){if(!t.ok&&e&&ll(t.status))return{body:void 0,httpError:L("operation_failed","Collection operation failed.",{status:t.status,operationOutcome:"rejected"})};throw d("invalid_operation_response","The collection authority returned a response that is not valid JSON.",{cause:n})}}function ll(t){return t>=400&&t<500&&![408,425,429].includes(t)}var Ln=class{serverUrl;storage;keyStore;directAccessMode;loopbackUrl;collectionId;internals;onChange;timeouts;pendingMutationStore;files;refreshOperations=new Oe;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 zn(this.storage,this.internals.pendingMutationKey(this.collectionId)),this.files=new Dn({keyStore:this.keyStore,serverUrl:this.serverUrl,loopbackUrl:this.loopbackUrl,collectionId:this.collectionId,currentToken:()=>this.currentToken(),authorizedToken:n=>this.authorizedToken({signal:n,timeoutMs:null}),refreshAuthorization:n=>this.refreshAuthorization({signal:n,timeoutMs:null}),shouldAttemptDirect:n=>this.shouldAttemptDirect(n),onDirectAvailable:()=>{this.markDirectAvailable(),this.setRoute("direct")},onDirectUnavailable:()=>this.markDirectUnavailable(),onRelayAvailable:()=>this.setRoute("relay"),acquireGrantKeyLease:(n,i,o)=>this.internals.acquireGrantKeyLease(n,i,o),authorityProofHeaders:(n,i,o,r,s)=>Le(this.keyStore,n,i,o,r,s)}),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 k(e,this.timeouts.watchStartMs,n=>this.checkDirectAccessWithinBudget(n.signal))}async checkDirectAccessWithinBudget(e){let n=this.currentToken();if(!this.directEligible(n))return this.setDirectStatus("disabled");let i=await Ot();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 k(e,this.timeouts.watchStartMs,n=>this.requestDirectAccessWithinBudget(n.signal))}async requestDirectAccessWithinBudget(e){let n=this.currentToken();return this.directCapable(n)?(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=>this.pendingMutationStore.summary(e))}async pendingUpdate(e){let n=this.currentToken()?.collectionId;return n?fs(this.storedPendingMutations(),n,e):null}pendingMutation(e){let n=this.storedPendingMutation(e);return n?this.pendingMutationStore.summary(n):null}async recoverPendingMutation(e,n){let i=this.storedPendingMutation(e);if(!i)throw d("no_pending_mutation","There is no interrupted mutation to resume.");return W(n,this.timeouts.requestMs,o=>this.performOperationWithinBudget(i.operation,i.request?.input??{},de(n??{},o),i))}async performOperation(e,n,i={}){return W(i,this.timeouts.requestMs,o=>this.performOperationWithinBudget(e,n,de(i,o)))}async performOperationWithinBudget(e,n,i,o,r=!1,s=0,a=!1){Fe(i.signal);let c=this.grantKeyLeases();try{let l=await $(()=>this.currentToken(),c,i.signal);if(!l)throw d("not_authorized","Connect this application before accessing a collection.");return await c.retain(o?.keyHandle,i.signal),await this.performLeasedOperation(l,e,n,i,c,o,r,s,a)}finally{c.release()}}async performLeasedOperation(e,n,i,o,r,s,a=!1,c=0,l=!1){if(!e.operations.includes(n))throw d("insufficient_access",`This connection does not allow ${n}.`,{details:{required_operations:[n],granted_operations:[...e.operations],missing_operations:[n]}});let u=await this.shouldAttemptDirect(e);if(!u){if(!await this.authorizedToken({signal:o.signal,timeoutMs:null}))throw d("not_authorized","Reconnect this application to continue.");let A=await $(()=>this.currentToken(),r,o.signal);if(!A)throw d("not_authorized","Reconnect this application to continue.");e=A}let f=s?.requestId??(fr(n,i)?crypto.randomUUID():void 0),p;try{p=await this.sendOperation(e,n,i,u,r,o,f,l)}catch(y){throw rn(y,o.signal,f!==void 0&&this.storedPendingMutation(f)!==null?f:void 0,e.authority?"hosted_provider_unavailable":"relay_unavailable")}let h=p.response,m=h.status===409&&(await E(h.clone(),"invalid_operation_response","The collection authority returned an invalid operation response.").catch(()=>null))?.error?.code==="encryption_binding_stale";if((h.status===401||m)&&e.refreshToken){if(p.pendingMutation&&(p.directDeliveryUncertain||p.encryptedRequest&&p.resumingMutation))throw d("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:p.requestId}});p.pendingMutation&&this.clearPendingMutation(p.requestId),e=await this.refreshAuthorization({signal:o.signal,timeoutMs:null});let y=await $(()=>this.currentToken(),r,o.signal);if(!y)throw d("not_authorized","Reconnect this application to continue.");e=y,u=await this.shouldAttemptDirect(e);try{p=await this.sendOperation(e,n,i,u,r,o,f,l)}catch(A){throw rn(A,o.signal,f!==void 0&&this.storedPendingMutation(f)!==null?f:void 0,e.authority?"hosted_provider_unavailable":"relay_unavailable")}h=p.response}let P=y=>Fo({error:y,attempt:p,completedRetries:c,signal:o.signal,knownRejectedMutationRetry:l,clearPending:A=>this.clearPendingMutation(A),retry:(A,D)=>this.performOperationWithinBudget(n,i,o,A,a,c+1,D)}),v;try{v=await Ts(h,e.authority!==void 0)}catch(y){throw p.pendingMutation?J(p.requestId,y):y}let b=v.body;if(!h.ok){let y=v.httpError??z(b,"operation_failed","Collection operation failed.",h.status),A=await P(y);if(A.retried)return A.result;if(y.code==="fresh_request_required"&&!p.pendingMutation&&!a)return this.performOperationWithinBudget(n,i,o,void 0,!0);throw p.pendingMutation&&y.outcomeUnknown?y:p.pendingMutation&&(p.directDeliveryUncertain||p.encryptedRequest&&p.resumingMutation)?J(p.requestId,y):(p.pendingMutation&&!p.directDeliveryUncertain&&this.clearPendingMutation(p.requestId),y.code==="direct_operation_rejected"&&y.status===403&&this.invalidateRejectedAuthorization(e),y)}if(p.encryptedRequest){let y=b?.envelope,A=p.pendingMutationRecord,D=A?.encryption??e.encryption,S=A?.grantId??e.grantId,T=A?.applicationId??e.clientId,M=A?.keyHandle??e.keyHandle;if(!y||!D||!S||!M)throw p.pendingMutation?J(p.requestId,new Error("Encrypted operation response was missing its envelope.")):d("invalid_encrypted_response","The relay did not return an encrypted connector response.");try{let O=await $e(this.keyStore,M,{grantId:S,applicationId:T,encryption:D},p.encryptedRequest,y);if(!O.ok&&O.problem.code==="fresh_request_required"&&!p.pendingMutation&&!a)return this.performOperationWithinBudget(n,i,o,void 0,!0);if(!O.ok){let U=yr(O.problem);throw p.pendingMutation&&!U.outcomeUnknown&&this.clearPendingMutation(p.requestId),U}return p.pendingMutation&&this.clearPendingMutation(p.requestId),O.result}catch(O){throw O instanceof _?O:O instanceof q?p.pendingMutation?J(p.requestId,O):L(O.code,O.message):O}}let C=p.pendingMutationRecord?.request?.protocol_version??Y;if(b?.protocol_version!==C||b?.request_id!==p.requestId)throw p.pendingMutation?J(p.requestId,new Error("Operation response protocol or request ID did not match.")):d("invalid_operation_response","The collection authority returned a response for a different protocol request.");if(b.ok===!1){if(!ht(b.problem))throw p.pendingMutation?J(p.requestId,new Error("Operation rejection did not contain a canonical problem.")):d("invalid_operation_response","The collection authority returned an invalid operation problem.");let y=new _(b.problem),A=await P(y);if(A.retried)return A.result;throw p.pendingMutation&&!y.outcomeUnknown&&this.clearPendingMutation(p.requestId),y}if(b.ok!==!0||!("result"in b))throw p.pendingMutation?J(p.requestId,new Error("Successful operation response did not contain a result.")):d("invalid_operation_response","The collection authority returned an incomplete operation response.");return p.pendingMutation&&this.clearPendingMutation(p.requestId),b.result}async performAuthoritySyncRequest(e,n,i,o,r,s={}){return W(s,this.timeouts.syncMs,async a=>{let c=this.grantKeyLeases();try{let l=await $(()=>this.currentToken(),c,a.signal);l&&await this.authorizedToken({signal:a.signal,timeoutMs:null}),l=await $(()=>this.currentToken(),c,a.signal),Ms(l,e,n);let u=await Hi(this.keyStore,l,i,o,r,a.signal);u.status===401&&l.refreshToken&&(l=await this.refreshAuthorization({signal:a.signal,timeoutMs:null}),l=await $(()=>this.currentToken(),c,a.signal),Ms(l,e,n),u=await Hi(this.keyStore,l,i,o,r,a.signal));let f=await E(u,"invalid_operation_response","The collection authority returned an invalid synchronization response.");if(!u.ok)throw z(f,"sync_failed","Collection synchronization failed.",u.status);return f}catch(l){let u=i==="POST"&&o==="mutations"&&r&&typeof r=="object"&&typeof r.mutation_id=="string"?r.mutation_id:void 0;throw rn(l,a.signal,u,"hosted_provider_unavailable")}finally{c.release()}})}async sendOperation(e,n,i,o,r,s={},a,c=!1){let l=i??{},u,f=!1,p=!1,h=a??crypto.randomUUID(),m=null,P,v;if(a!==void 0){if(m=this.storedPendingMutation(a),P=m?.inputFingerprint??await wr(n,i),m||(v=await ps(e.collectionId,n,i)),m){if(m.collectionId!==e.collectionId||m.operation!==n||m.inputFingerprint!==P)throw d("pending_mutation_unresolved","A previous write still has an unknown outcome. Retry that exact write before making another change.");h=m.requestId,p=!c}f=!0}let b=m?.mutation??be(n,i);if(m?.envelope&&(e.authority||!e.encryption))throw d("pending_mutation_unresolved","The pending write requires its encrypted relay authority. Reconnect that authority before recovery.");if(m?.request&&e.encryption&&!e.authority)throw d("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 d("missing_grant_key","Reconnect this application to restore encrypted access.");try{if(f)if(m){if(!m.envelope)throw d("pending_mutation_unresolved","The pending write belongs to a different transport. Reconnect before retrying it.");u=hr(m.envelope,s.deadlineUnixMs)}else u=await me(this.keyStore,e.keyHandle,{grantId:e.grantId,applicationId:e.clientId,encryption:e.encryption},n,i,h,s.deadlineUnixMs),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:n,mutation:b,inputFingerprint:P,...v?{recordDigest:v}:{},requestId:h,envelope:u,createdAt:Date.now()});else u=await me(this.keyStore,e.keyHandle,{grantId:e.grantId,applicationId:e.clientId,encryption:e.encryption},n,i,void 0,s.deadlineUnixMs)}catch(S){throw S instanceof q?L(S.code,S.message):S}h=u.request_id,l=u}else{let S=m?.request??{protocol_version:Y,request_id:h,input:l};l=S,f&&!m&&this.pendingMutationStore.store({collectionId:e.collectionId,...e.grantId?{grantId:e.grantId}:{},operation:n,mutation:b,inputFingerprint:P,...v?{recordDigest:v}:{},requestId:h,request:S,createdAt:Date.now()})}if(o&&u&&!e.authority){let S=!1;try{let O=await fetch(`${this.loopbackUrl}/v1/operations`,Se({method:"POST",headers:{"content-type":"application/mdbase-connect+json"},body:JSON.stringify(u),signal:s.signal}));if(!await Je(O)||await Be(O))return O.ok&&(this.markDirectAvailable(),this.setRoute("direct")),{response:O,requestId:h,encryptedRequest:u,pendingMutation:f,...f?{pendingMutationRecord:m??this.storedPendingMutation(h)??void 0}:{},resumingMutation:p};S=O.status>=500,this.markDirectUnavailable()}catch(O){if(s.signal?.aborted)throw f?J(h,O):O;S=!0,await Ot()==="denied"?this.setDirectStatus("denied"):this.markDirectUnavailable()}let T;try{e.expiresAt<=Date.now()+3e4&&await this.refreshAuthorization({signal:s.signal,timeoutMs:null});let O=await $(()=>this.currentToken(),r,s.signal);if(!O)throw d("not_authorized","Reconnect this application to continue.");T=O}catch(O){throw f&&(S||p)?J(h,O):O}let M;f||(u=await Os(this.keyStore,T,n,i,s.deadlineUnixMs),h=u.request_id);try{M=await fetch(`${this.serverUrl}/v1/authorities/${encodeURIComponent(T.collectionId)}/operations/${n}`,{method:"POST",headers:{authorization:`Bearer ${T.accessToken}`,"content-type":"application/json"},body:JSON.stringify(u),signal:s.signal})}catch(O){throw f?J(h,O):O}return M.ok&&this.setRoute("relay"),{response:M,requestId:h,encryptedRequest:u,directDeliveryUncertain:S,pendingMutation:f,...f?{pendingMutationRecord:m??this.storedPendingMutation(h)??void 0}:{},resumingMutation:p}}let C=e.authority?`${e.authority.operationsUrl}/${n}`:`${this.serverUrl}/v1/authorities/${encodeURIComponent(e.collectionId)}/operations/${n}`,y=JSON.stringify(l),A=e.authority?await Le(this.keyStore,e,"POST",C,y,e.authority.accessToken):{},D;try{D=await gr(C,e.authority?.accessToken??e.accessToken,A,y,s.signal)}catch(S){throw f?J(h,S):S}return D.ok&&this.setRoute(e.authority?"remote":"relay"),{response:D,requestId:h,encryptedRequest:u,pendingMutation:f,...f?{pendingMutationRecord:m??this.storedPendingMutation(h)??void 0}:{},resumingMutation:p}}directCapable(e){return Ps(e,this.directAccessMode)}hasResumableMutationTransport(){return this.currentToken()!==null}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 n=await Ot();return n==="denied"?(this.setDirectStatus("denied"),!1):(n==="prompt"||n===null)&&this.storage.getItem(this.internals.directPreferenceKey())!=="enabled"?(this.setDirectStatus("permission_required"),!1):(this.setDirectStatus("checking"),!0)}async probeDirectAccess(e){this.setDirectStatus("checking");try{if(await As(this.loopbackUrl,Y,e))return this.markDirectAvailable(),"available"}catch(n){throw this.markDirectUnavailable(),n}return await Ot()==="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 n=F(this.storage.getItem(this.internals.tokenKey(this.collectionId)));!n||!mr(n,e)||(this.internals.removeToken(this.collectionId,n.keyHandle),this.currentRoute="relay",this.directStatus=this.directAccessMode==="disabled"?"disabled":"unavailable",this.emitConnection())}currentToken(){return Ss({stored:this.storage.getItem(this.internals.tokenKey(this.collectionId)),collectionId:this.collectionId,relayEncryption:this.internals.relayEncryption,invalidate:(e,n="invalid_stored_grant")=>this.internals.removeToken(this.collectionId,e,n),directCapable:e=>this.directCapable(e)})}async authorizedToken(e={}){let n=this.currentToken();if(!n)return null;if(n.expiresAt>Date.now()+3e4)return n;if(!n.refreshToken||(n.refreshExpiresAt??0)<=Date.now()){if(this.directCapable(n))throw d("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,n.keyHandle),null}return this.refreshAuthorization(e)}refreshAuthorization(e={}){return this.refreshOperations.run("refresh",e,this.timeouts.requestMs,n=>this.performRefresh(n))}async performRefresh(e){let n=this.grantKeyLeases();try{let i=await $(()=>this.currentToken(),n,e);return await ws({current:i,serverUrl:this.serverUrl,keyStore:this.keyStore,signal:e,currentToken:()=>this.currentToken(),directCapable:o=>this.directCapable(o),removeToken:o=>this.internals.removeToken(this.collectionId,o),storeTokenResponse:(o,r,s)=>this.storeTokenResponse(o,r,s)})}finally{n.release()}}storeTokenResponse(e,n,i){if(e.collection_id!==this.collectionId)throw d("collection_mismatch","The refreshed authorization belongs to a different collection.");let o=this.internals.storeTokenResponse(e,n,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 n=this.pendingMutationStore.take(e);n?.keyHandle&&this.internals.deleteGrantKeyWhenUnused(this.collectionId,n.keyHandle)}grantKeyLeases(){return new Pe(this.collectionId,(e,n,i)=>this.internals.acquireGrantKeyLease(e,n,i))}};function Ms(t,e,n){if(!(t?.authority&&t.collectionId===e&&t.authority.replicaId===n))throw d("authority_authorization_changed","Reconnect this collection authority before synchronizing.")}var Un=class{constructor(e,n){this.signal=n;this.iterator=dl(e)}signal;iterator;remainder=new Uint8Array;remainderOffset=0;maxSourceChunkBytes=null;iteratorClosing=!1;ended=!1;setMaxSourceChunkBytes(e){this.maxSourceChunkBytes=e}async read(e){let n=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,d("invalid_request","Streamed file bytes ended before the declared size.");if(!(r.value instanceof Uint8Array))throw d("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 d("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);n.set(this.remainder.subarray(this.remainderOffset,this.remainderOffset+o),i),i+=o,this.remainderOffset+=o}return n}async expectEnd(){if(this.remainderOffset<this.remainder.byteLength)throw d("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 d("invalid_request","A streamed file chunk was not a Uint8Array.");if(e.value.byteLength>0)throw d("invalid_request","Streamed file bytes exceed the declared size.")}}async close(){this.ended=!0,this.closeIterator()}async nextSourceChunk(){Is(this.signal);let e=this.iterator.next(),n=this.signal;if(!n)return e;let i=()=>{},o=new Promise((r,s)=>{let a=()=>{this.closeIterator(),s(ks(n))};n.addEventListener("abort",a,{once:!0}),i=()=>n.removeEventListener("abort",a),n.aborted&&a()});try{let r=await Promise.race([e,o]);return Is(n),r}finally{i()}}closeIterator(){if(!this.iteratorClosing){this.iteratorClosing=!0;try{this.iterator.return?.()?.catch(()=>{})}catch{}}}};function dl(t){if(typeof t.getReader=="function"){let n=t.getReader(),i=!1,o=()=>{i||(i=!0,n.releaseLock())};return{async next(){if(i)return{done:!0,value:void 0};let r=await n.read();return r.done&&o(),r},async return(){if(!i)try{await n.cancel()}finally{o()}return{done:!0,value:void 0}}}}let e=t;if(typeof e[Symbol.asyncIterator]!="function")throw d("invalid_request","Streamed files require a readable byte stream.");return e[Symbol.asyncIterator]()}function Is(t){if(t?.aborted)throw ks(t)}function ks(t){return d("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:t?.reason})}var dt=class{constructor(e,n,i,o,r=Ve(),s=async()=>R(!1)){this.capability=e;this.request=n;this.framed=i;this.hosted=o;this.timeouts=r;this.supportsAuthorityFeature=s}capability;request;framed;hosted;timeouts;supportsAuthorityFeature;list(e={}){return cs(this.capability,this.request,e,this.timeouts.fileIndexMs)}stat(e,n={}){return ls(this.capability,this.request,this.supportsAuthorityFeature,i=>this.list(i),e,n,this.timeouts.fileIndexMs)}async upload(e,n,i={}){return W(i,this.timeouts.uploadMs,o=>this.uploadWithinBudget(e,n,{...i,signal:o.signal,timeoutMs:null}))}async uploadWithinBudget(e,n,i){this.requireAction(i.ifRevision?"replace":"add");let o=Ko(n,i.mediaType),r=ai(i.concurrency),s=await Bo(o,i.signal,a=>{i.onProgress?.({phase:"hashing",transferredBytes:a,totalBytes:o.size})});return this.uploadKnownSource(e,o.size,`sha256:${s}`,(i.mediaType??o.type)||void 0,i,r,async(a,c,l)=>o.slice(c,c+l))}async uploadStream(e,n,i={}){return W(i,this.timeouts.uploadMs,o=>this.uploadStreamWithinBudget(e,n,{...i,signal:o.signal,timeoutMs:null}))}async uploadStreamWithinBudget(e,n,i){if(this.requireAction(i.ifRevision?"replace":"add"),!Number.isSafeInteger(n.size)||n.size<0)throw d("invalid_request","Streamed file size must be a non-negative safe integer.");if(!$t.test(n.contentDigest))throw d("invalid_request","Streamed files require a lowercase SHA-256 content digest.");let o=new Un(n.stream,i.signal),r=new xe;return this.uploadKnownSource(e,n.size,n.contentDigest,i.mediaType??n.mediaType,i,1,async(s,a,c)=>{let l=await o.read(c);return r.update(l),l},async()=>{if(await o.expectEnd(),`sha256:${r.digestHex()}`!==n.contentDigest)throw d("invalid_request","Streamed file bytes do not match the declared SHA-256 digest.")},()=>o.close(),s=>o.setMaxSourceChunkBytes(s))}async uploadKnownSource(e,n,i,o,r,s,a,c,l,u){let f=r.transferId??crypto.randomUUID();if(!jo.test(f))throw d("invalid_request","File transfer ID must be a UUID.");let p=!1;try{let h=await this.request("POST","uploads",{protocol_version:1,type:"open_file_upload",transfer_id:f,path:e,size:n,content_digest:i,...o?{media_type:o}:{},...r.ifRevision?{if_revision:r.ifRevision}:{}},r.signal);if(ci(h,f,"upload"),h.total_size!==n||h.strategy.kind==="object_ranges")throw d("invalid_operation_response","The authority returned an incompatible upload strategy.");let m=h.strategy.kind==="framed_chunks";if(m&&!this.framed)throw d("invalid_operation_response","Encrypted file chunk delivery is unavailable.");let P=h.strategy.kind==="object_put"?Math.max(1,n):h.strategy.kind==="framed_chunks"?h.strategy.chunk_size:h.strategy.part_size,v=h.strategy.kind==="object_put"?1:Math.ceil(n/P),b=h.prepared_upload_part;if(b!==void 0){if(ui(b,f,0,0,n,"PUT"),h.strategy.kind!=="object_put"||pi(b.headers).get("if-none-match")!=="*")throw d("invalid_operation_response","Upload bootstrap must be a create-only single PUT.");Date.parse(b.expires_at)<=Date.now()+6e4&&(b=void 0)}let C=b?void 0:await this.request("GET",`transfers/${encodeURIComponent(f)}`,void 0,r.signal);if(C&&(li(C,h),C.state!=="open"&&C.state!=="committed"))throw d("invalid_operation_response",`The authority cannot resume a ${C.state} file transfer.`);if(u?.(P),!m&&C?.received.length===v){let M=await this.tryReplayUploadCommit(f,h.strategy.kind==="object_multipart"?C.uploaded_parts:void 0,r.signal);if(M)return p=!0,fe(M.file)}let y=new Set(C?.received??[]),A=new Map((C?.uploaded_parts??[]).map(M=>[M.part_number-1,M])),D=[...y].reduce((M,O)=>M+di(n,P,O),0),S=await Ho(v,s,async M=>{let O=M*P,U=Math.min(P,Math.max(0,n-O)),H=await a(M,O,U);if(Qo(H)!==U)throw d("invalid_request","Streamed file bytes ended before the declared size.");if(y.has(M))return A.get(M)??null;let B=m?await Jt(async()=>this.framed.uploadChunk(h,M,await Vo(H),r.signal),r.signal).then(()=>null):await this.uploadPart(f,M,O,H,U,h.strategy.kind==="object_multipart",r.signal,b?{session:h,part:b}:void 0);return D+=U,r.onProgress?.({phase:"uploading",transferredBytes:D,totalBytes:n}),B});await c?.();let T=await this.commitUpload(f,h.strategy.kind==="object_multipart"?S.filter(M=>M!==null):void 0,r.signal);if(T.protocol_version!==1||T.type!=="file_upload_committed"||T.transfer_id!==f||T.file.path!==e||T.file.size!==n||T.file.content_digest!==i)throw d("invalid_operation_response","The authority returned an invalid file receipt.");return p=!0,fe(T.file)}catch(h){throw _e(h)}finally{await l?.().catch(()=>{}),!p&&r.transferId===void 0&&await this.abort(f)}}async download(e,n={}){let i=await this.downloadBytes(e,n);return new Blob([i.buffer],{type:e.mediaType??""})}async downloadStream(e,n={}){return W(n,this.timeouts.requestMs,i=>this.openDownloadStream(e,n,i.signal))}async openDownloadStream(e,n,i){this.requireAction("read");let o=ai(n.concurrency),r=crypto.randomUUID(),s;try{if(s=await this.request("POST","downloads",{protocol_version:1,type:"open_file_download",transfer_id:r,file_id:e.fileId,revision:e.revision},i),ci(s,r,"download"),s.total_size!==e.size||s.strategy.kind!=="object_ranges"&&s.strategy.kind!=="framed_chunks")throw d("invalid_operation_response","The authority returned an incompatible download session.");if(s.strategy.kind==="framed_chunks"&&!this.framed)throw d("invalid_operation_response","Encrypted file chunk delivery is unavailable.");if(s.strategy.kind==="object_ranges"&&e.size>0&&!this.hosted)throw d("invalid_operation_response","Authenticated hosted file delivery is unavailable.")}catch(S){throw await this.abort(r),_e(S)}let a=s.strategy.kind==="framed_chunks"?s.strategy.chunk_size:s.strategy.part_size,c=Math.ceil(e.size/a),l=new xe,u=0,f=0,p=null,h=0,m=!1,P=new AbortController,v=n.signal?AbortSignal.any([n.signal,P.signal]):P.signal,b=new Map,C=0,y=()=>{if(s.strategy.kind==="framed_chunks")for(;C<c&&b.size<o;){let S=C;C+=1;let T=Jt(()=>this.framed.downloadChunk(s,S,v),v).then(M=>({ok:!0,chunk:M}),M=>({ok:!1,error:M}));b.set(S,T)}},A=async()=>{m||(m=!0,P.abort(),await p?.cancel().catch(()=>{}),p=null,await Promise.all(b.values()),b.clear(),await this.abort(r))},D=()=>{if(h!==e.size||`sha256:${l.digestHex()}`!==e.contentDigest)throw d("invalid_operation_response","Downloaded file bytes failed integrity verification.")};return new ReadableStream({pull:async S=>{try{if(ee(v),s.strategy.kind==="object_ranges")for(;;){if(!p){if(u>=c){D(),S.close(),A();return}let N=u*a;f=Math.min(a,e.size-N),p=(await Jt(()=>this.hosted.downloadPart(s,u,f,v),v)).getReader()}let B=await p.read();if(B.done){if(p.releaseLock(),p=null,f!==0)throw d("invalid_operation_response","A hosted file range ended before its declared byte length.");u+=1;continue}if(!(B.value instanceof Uint8Array))throw d("invalid_operation_response","A hosted file range returned a non-byte chunk.");if(B.value.byteLength!==0){if(B.value.byteLength>f)throw d("invalid_operation_response","A hosted file range exceeded its declared byte length.");f-=B.value.byteLength,l.update(B.value),h+=B.value.byteLength,n.onProgress?.({phase:"downloading",transferredBytes:h,totalBytes:e.size}),S.enqueue(B.value);return}}if(u>=c){D(),S.close(),A();return}let T=u*a,M=Math.min(a,e.size-T);y();let O=b.get(u);if(!O)throw d("invalid_operation_response","A file chunk was not scheduled.");let U=await O;if(b.delete(u),!U.ok)throw U.error;let H=U.chunk;if(H.byteLength!==M)throw d("invalid_operation_response","A file chunk had the wrong byte length.");l.update(H),h+=H.byteLength,u+=1,y(),n.onProgress?.({phase:"downloading",transferredBytes:h,totalBytes:e.size}),u===c&&D(),S.enqueue(H),u===c&&(S.close(),A())}catch(T){let M=n.signal?.aborted?d("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:n.signal.reason}):T;await A(),S.error(_e(M))}},cancel:A})}async downloadBytes(e,n={}){if(e.size>si)throw d("invalid_request",`download() buffers at most ${si} bytes; use downloadStream() for larger files.`);let i=await this.downloadStream(e,n),o=new Uint8Array(e.size),r=i.getReader(),s=0;try{for(;;){let a=await r.read();if(a.done)break;if(a.value.byteLength>o.byteLength-s)throw d("invalid_operation_response","Downloaded file bytes failed integrity verification.");o.set(a.value,s),s+=a.value.byteLength}if(s!==o.byteLength)throw d("invalid_operation_response","Downloaded file bytes failed integrity verification.");return o}catch(a){throw await r.cancel().catch(()=>{}),a}finally{r.releaseLock()}}async move(e,n,i={}){return W(i,this.timeouts.requestMs,o=>this.moveWithinBudget(e,n,{...i,signal:o.signal,timeoutMs:null}))}async moveWithinBudget(e,n,i){this.requireAction("move");let o=i.mutationId??crypto.randomUUID(),r;try{r=await this.request("POST",`${encodeURIComponent(e.fileId)}/move`,{protocol_version:1,type:"move_file",mutation_id:o,file_id:e.fileId,if_revision:i.ifRevision??e.revision,from_path:e.path,path:n,update_references:!1},i.signal)}catch(s){throw _e(s)}if(r.protocol_version!==1||r.type!=="file_moved"||r.mutation_id!==o||r.file.file_id!==e.fileId||r.file.path!==n)throw d("invalid_operation_response","The authority returned an invalid file move receipt.");return fe(r.file)}async delete(e,n={}){return W(n,this.timeouts.requestMs,i=>this.deleteWithinBudget(e,{...n,signal:i.signal,timeoutMs:null}))}async deleteWithinBudget(e,n){this.requireAction("delete");let i=n.mutationId??crypto.randomUUID(),o;try{o=await this.request("POST",`${encodeURIComponent(e.fileId)}/delete`,{protocol_version:1,type:"delete_file",mutation_id:i,file_id:e.fileId,if_revision:n.ifRevision??e.revision,path:e.path},n.signal)}catch(r){throw _e(r)}if(o.protocol_version!==1||o.type!=="file_deleted"||o.mutation_id!==i||o.file_id!==e.fileId||o.previous_path!==e.path)throw d("invalid_operation_response","The authority returned an invalid file delete receipt.");return{protocolVersion:o.protocol_version,type:o.type,mutationId:o.mutation_id,fileId:o.file_id,previousPath:o.previous_path,revision:o.revision}}async uploadPart(e,n,i,o,r,s,a,c){for(let l=1;l<=_t;l+=1){ee(a);try{let u=l===1&&c&&Date.parse(c.part.expires_at)>Date.now()+6e4;if(c&&!u){let v=await this.request("GET",`transfers/${encodeURIComponent(e)}`,void 0,a);if(li(v,c.session),v.state!=="open"&&v.state!=="committed")throw d("invalid_operation_response",`The authority cannot resume a ${v.state} file transfer.`);if(v.received.includes(n))return{part_number:n+1,etag:""}}let f=u?c.part:await this.request("POST",`uploads/${encodeURIComponent(e)}/parts`,{protocol_version:1,type:"prepare_file_upload_part",transfer_id:e,part_number:n+1,content_length:r},a);ui(f,e,n,i,r,"PUT");let p=pi(f.headers),h=await fetch(f.url,{method:f.method,headers:p,body:o,redirect:"error",signal:a});if(h.status===412&&!s&&p.get("if-none-match")==="*")return{part_number:n+1,etag:""};if(!h.ok)throw new Error(`Object upload failed with HTTP ${h.status}.`);let P=h.headers.get("etag");if(s&&!P)throw new Error("Multipart object upload did not return an ETag.");return{part_number:n+1,etag:P??""}}catch(u){if(a?.aborted||l===_t)throw u}}throw new Error("Unreachable upload retry state.")}async tryReplayUploadCommit(e,n,i){try{return await this.commitUpload(e,n,i)}catch(o){if(o instanceof _&&o.code==="file_upload_incomplete")return null;throw o}}async commitUpload(e,n,i){let o;for(let r=1;r<=_t;r+=1){ee(i);try{return await this.request("POST",`uploads/${encodeURIComponent(e)}/commit`,{protocol_version:1,type:"commit_file_upload",transfer_id:e,...n===void 0?{}:{parts:n}},i)}catch(s){if(o=s,i?.aborted||s instanceof _||r===_t)throw s}}throw o}requireAction(e){if(!this.capability()?.actions.includes(e))throw d("not_authorized",`This connection is not authorized to ${e} files.`)}async abort(e){await this.request("DELETE",`transfers/${encodeURIComponent(e)}`).catch(()=>{})}};var ut=class{constructor(e,n,i={}){this.adapter=n;this.record=e,this.baseBody=this.body=n.body(e),this.seen.add(n.revision(e)),this.idleMs=i.autosave===!1?void 0:i.autosave?.idleMs??1e3,this.current=this.compute()}adapter;record;baseBody;body;patch={};remote=null;problem=null;refreshProblem=null;deleted=!1;busy=!1;pending;incoming=[];seen=new Set;listeners=new Set;tail=Promise.resolve();queued=0;inFlight;timer;lastEdit=0;disposed=!1;idleMs;current;get snapshot(){return this.current}getSnapshot=()=>this.current;subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});setBody(e){e!==this.body&&(this.body=e,this.edited())}patchFrontmatter(e){this.patch={...this.patch,...e},this.edited()}restore(e){let n=this.adapter.body(this.record),i=this.adapter.frontmatter?.(this.record)??{},o=Object.fromEntries(Object.entries(e.patch??{}).filter(([r,s])=>JSON.stringify(i[r]??null)!==JSON.stringify(s)));e.body===n&&Object.keys(o).length===0||(this.body=e.body,this.patch=o,(e.body!==n&&e.baseBody!==n||Object.keys(o).some(r=>!e.baseFrontmatter||JSON.stringify(e.baseFrontmatter[r]??null)!==JSON.stringify(i[r]??null)))&&(this.remote=this.record),this.emit())}resumeRecovery(e){this.pending||this.busy||(this.pending={requestId:e,sent:"restored"},this.emit(),this.autosave())}dispose(){this.disposed=!0,clearTimeout(this.timer),this.listeners.clear()}autosave(){this.lastEdit=Date.now(),this.schedule()}receive(e){if(!this.seen.has(this.adapter.revision(e))){if(this.busy||this.pending){this.incoming.push(e);return}this.seen.add(this.adapter.revision(e)),this.classify(e),this.emit()}}refresh(e){return this.run(async()=>{let n=this.adapter.read;if(!n||this.pending)return R(this.record);let i=await n(this.record,e);return i.ok?(this.refreshProblem=null,this.seen.add(this.adapter.revision(i.value)),this.classify(i.value),this.emit(),R(this.record)):(i.problem.code==="file_not_found"?this.markDeleted():(this.refreshProblem=i.problem,this.emit()),i)})}accept(e){this.seen.add(this.adapter.revision(e));let n=this.adapter.body(e);this.body===this.baseBody&&(this.body=n),this.baseBody=n;let i=this.adapter.frontmatter?.(e)??{};for(let[o,r]of Object.entries(this.patch))Ue(i[o],r)&&delete this.patch[o];this.record=e,this.remote=null,this.problem=null,this.refreshProblem=null,this.emit()}markDeleted(){clearTimeout(this.timer),this.deleted=!0,this.emit()}save(e){if(clearTimeout(this.timer),this.inFlight)return this.inFlight;let n=this.run(()=>this.pending?this.recoverPending(e):this.write(e,!0));this.inFlight=n;let i=()=>{this.inFlight===n&&(this.inFlight=void 0)};return n.then(i,i),n}async flush(e){for(;;){if(this.deleted)return g($i());if(this.remote)return g(Wi());if(!this.inFlight&&!this.pending&&!this.dirtyLocally())return R(this.record);let n=await this.save(e);if(!n.ok)return n}}run(e){let n=this.queued===0?e():this.tail.then(e);this.queued+=1;let i=()=>{this.queued-=1};return this.tail=n.then(i,i),n}resolve(e){let n=this.remote;!n||this.busy||(this.record=n,this.remote=null,this.problem=null,this.baseBody=this.adapter.body(n),"body"in e?this.body=e.body:e.keep==="theirs"&&(this.body=this.baseBody,this.patch={}),this.emit(),this.dirtyLocally()&&this.autosave())}discard(){this.busy||(clearTimeout(this.timer),this.record=this.remote??this.record,this.remote=null,this.problem=null,this.baseBody=this.body=this.adapter.body(this.record),this.patch={},this.emit())}edited(){this.problem=null,this.lastEdit=Date.now(),this.emit(),this.schedule()}schedule(){if(clearTimeout(this.timer),this.disposed||this.idleMs===void 0||this.remote||this.deleted)return;let e=Math.max(0,this.lastEdit+this.idleMs-Date.now());this.timer=setTimeout(()=>{this.save()},e)}dirtyLocally(){return this.body!==this.baseBody||Object.keys(this.patch).length>0}async write(e,n){if(this.remote)return g(Wi());if(this.deleted)return g($i());if(!this.dirtyLocally())return R(this.record);let i={};this.body!==this.baseBody&&(i.body=this.body),Object.keys(this.patch).length&&(i.patch=structuredClone(this.patch)),this.busy=!0,this.emit();let o=await this.guard(()=>this.adapter.write(this.record,{...i},e));if(o.ok)return this.acknowledge(o.value,i),R(this.record);let r=ul(o.problem);if(r)return this.busy=!1,this.problem=o.problem,this.pending={requestId:r,sent:i},this.emit(),this.schedule(),o;let s=await this.classifyFailure(o.problem,e);return s==="resolved"?R(this.record):s==="rebased"&&n?this.write(e,!1):this.failure(o.problem)}async recoverPending(e){let n=this.pending,i=this.adapter.recover;if(!i)return g(w("pending_mutation_unresolved","Exact recovery of the interrupted write is unavailable. No new write was attempted."));this.busy=!0,this.emit();let o=await this.guard(()=>i(n.requestId,e));return o.ok?(n.sent==="restored"?(this.pending=void 0,this.busy=!1,this.accept(o.value),this.settle()):this.acknowledge(o.value,n.sent),R(this.record)):o.problem.operation_outcome!=="unknown"&&o.problem.code!=="operation_outcome_unknown"&&this.adapter.isPending?.(n.requestId)===!1?(this.pending=void 0,await this.classifyFailure(o.problem,e),this.failure(o.problem)):(this.busy=!1,this.problem=o.problem,this.emit(),o)}async guard(e){try{return await e()}catch(n){throw this.busy=!1,this.emit(),n}}failure(e){return this.deleted?g($i()):this.remote?g(Wi()):g(e)}acknowledge(e,n){this.seen.add(this.adapter.revision(e)),this.record=e,n.body!==void 0&&(this.baseBody=n.body);for(let[i,o]of Object.entries(n.patch??{}))i in this.patch&&Ue(this.patch[i],o)&&delete this.patch[i];this.problem=null,this.refreshProblem=null,this.pending=void 0,this.settle(),this.dirtyLocally()&&this.schedule()}async classifyFailure(e,n){let i=this.adapter.revision(this.record),o=this.adapter.read,r=o?await this.guard(()=>o(this.record,n)):void 0;return r&&!r.ok&&r.problem.code==="file_not_found"?(this.deleted=!0,this.settle(),"failed"):!r?.ok||this.adapter.revision(r.value)===i?(this.problem=e,this.settle(),"failed"):(this.seen.add(this.adapter.revision(r.value)),this.classify(r.value),this.settle(),this.remote?"failed":this.dirtyLocally()?"rebased":"resolved")}settle(){this.busy=!1;for(let e of this.incoming.splice(0))this.seen.has(this.adapter.revision(e))||(this.seen.add(this.adapter.revision(e)),this.classify(e));this.emit()}classify(e){if(this.adapter.revision(e)===this.adapter.revision(this.record))return;let n=this.adapter.body(this.record),i=this.adapter.body(e),o=i!==n,r=this.body!==this.baseBody,s=this.adapter.frontmatter?.(this.record)??{},a=this.adapter.frontmatter?.(e)??{};if(r&&o&&i!==this.body||Object.entries(this.patch).some(([l,u])=>!Ue(a[l],s[l])&&!Ue(a[l],u))){clearTimeout(this.timer),this.remote=e;return}this.remote=null,this.record=e,o&&(this.baseBody=this.body=i);for(let[l,u]of Object.entries(this.patch))Ue(a[l],u)&&delete this.patch[l];this.dirtyLocally()||(this.problem=null)}compute(){let e=this.busy||!!this.pending||this.dirtyLocally();return{state:this.deleted?"deleted":this.remote?"conflict":this.busy?"saving":this.pending?"recovery":this.problem||this.refreshProblem?"error":e?"unsaved":"saved",body:this.body,frontmatter:{...this.adapter.frontmatter?.(this.record)??{},...this.patch},record:this.record,remote:this.remote,dirty:e,problem:this.problem??this.refreshProblem,...this.pending?{pendingRequestId:this.pending.requestId}:{}}}emit(){this.current=this.compute(),this.listeners.forEach(e=>e())}};function Wi(){return w("concurrent_modification","This record changed elsewhere. Local changes are kept until the conflict is resolved.")}function $i(){return w("file_not_found","This record no longer exists. Local changes are kept.")}function ul(t){return t.code==="operation_outcome_unknown"?t.details.request_id:void 0}function Ue(t,e){if(t===e)return!0;if(typeof t!="object"||typeof e!="object"||t===null||e===null)return!1;if(Array.isArray(t)||Array.isArray(e))return Array.isArray(t)&&Array.isArray(e)&&t.length===e.length&&t.every((i,o)=>Ue(i,e[o]));let n=Object.keys(t);return n.length===Object.keys(e).length&&n.every(i=>i in e&&Ue(t[i],e[i]))}var pl=4,fl=4,pt=class{constructor(e,n=async()=>null){this.connection=e;this.pendingUpdate=n}connection;pendingUpdate;entries=new Map;opening=new Map;refreshes=new Map;refreshQueue=new Set;activeRefreshes=0;followers=0;async open(e,n={}){for(;;){let i=this.entries.get(e);if(i)return R(this.lease(i));let o=this.opening.get(e),r=o??this.load(e,n);o||(this.opening.set(e,r),r.then(()=>this.opening.delete(e)));let s=await r;if(s.ok)return R(this.lease(s.value));if(!(o&&(s.problem.code==="operation_cancelled"||s.problem.code==="timeout"))||n.signal?.aborted)return s}}follow(e){this.followers+=1;let n=e.subscribe(o=>this.apply(o),o=>{if(o.state==="reset_required")for(let r of this.entries.values())this.refresh(r)}),i=!1;return()=>{if(!i&&(i=!0,n(),--this.followers===0)){for(let o of this.refreshes.values())clearTimeout(o.timer),o.stopWaiting?.();this.refreshes.clear(),this.refreshQueue.clear()}}}refresh(e){let n=this.refreshes.get(e);if(n){n.dirty=!0;return}let i={entry:e,dirty:!1,attempts:0};this.refreshes.set(e,i),this.enqueueRefresh(i)}enqueueRefresh(e){e.entry.session.snapshot.pendingRequestId?e.stopWaiting=e.entry.session.subscribe(()=>{e.entry.session.snapshot.pendingRequestId||(e.stopWaiting?.(),e.stopWaiting=void 0,this.enqueueRefresh(e))}):(this.refreshQueue.add(e),this.pumpRefreshes())}pumpRefreshes(){for(;this.activeRefreshes<pl&&this.refreshQueue.size>0;){let e=this.refreshQueue.values().next().value;this.refreshQueue.delete(e),e.dirty=!1,this.activeRefreshes+=1,this.runRefresh(e)}}async runRefresh(e){try{e.attempts+=1;let n=await e.entry.session.refresh();if(this.refreshes.get(e.entry)!==e)return;if(e.entry.session.snapshot.pendingRequestId){e.attempts-=1,this.enqueueRefresh(e);return}!n.ok&&n.problem.code!=="operation_cancelled"&&(n.problem.recovery==="retry"||n.problem.operation_outcome==="not_sent"&&n.problem.category==="availability")&&e.attempts<fl?e.timer=setTimeout(()=>this.enqueueRefresh(e),100*2**(e.attempts-1)):e.dirty?(e.attempts=0,this.enqueueRefresh(e)):this.refreshes.delete(e.entry)}finally{this.activeRefreshes-=1,this.pumpRefreshes()}}async load(e,n){let{autosave:i,...o}=n,r=await this.connection.read({path:e},o);if(!r.ok)return r;let s=this.entries.get(r.value.path);if(s)return R(s);let a={path:r.value.path,leases:0};a.session=new ut(r.value,this.adapter(a),{autosave:i});let c=await this.pendingUpdate(a.path);return c&&a.session.resumeRecovery(c),this.entries.set(a.path,a),R(a)}adapter(e){return{revision:n=>n.revision,body:n=>n.body??"",frontmatter:n=>n.frontmatter,write:(n,i,o)=>this.connection.update({path:e.path,ifRevision:n.revision,patch:i.patch??{},...i.body===void 0?{}:{body:i.body}},o),read:(n,i)=>this.connection.read({path:e.path},i),recover:async(n,i)=>{let o=this.connection.pendingMutation(n);return o?o.recover(i):g(w("no_pending_mutation","The interrupted write is no longer pending."))},isPending:n=>this.connection.pendingMutation(n)!==null}}lease(e){e.leases+=1,e.stopRetiring?.(),e.stopRetiring=void 0;let n=!1;return{session:e.session,release:()=>{n||(n=!0,e.leases-=1,this.retire(e))}}}retire(e){if(e.leases>0)return;let n=()=>{let{state:i,dirty:o}=e.session.snapshot;if(i!=="saved"&&i!=="deleted"&&!(i==="error"&&!o))return!1;e.stopRetiring?.(),e.stopRetiring=void 0,this.entries.get(e.path)===e&&this.entries.delete(e.path);let r=this.refreshes.get(e);return r&&(clearTimeout(r.timer),r.stopWaiting?.(),this.refreshQueue.delete(r),this.refreshes.delete(e)),!0};n()||(e.stopRetiring=e.session.subscribe(()=>{n()}))}apply(e){let{payload:n}=e;if(e.type==="mdbase.record.renamed"){let o=typeof n.from=="string"?this.entries.get(n.from):void 0;if(!o||typeof n.to!="string")return;this.entries.delete(o.path),o.path=n.to,this.entries.set(o.path,o),this.refresh(o);return}if(e.type!=="mdbase.record.modified"&&e.type!=="mdbase.record.deleted")return;let i=typeof n.path=="string"?this.entries.get(n.path):void 0;!i||n.revision===i.session.snapshot.record.revision||this.refresh(i)}};var hl=4,xs=32,Nn=class{constructor(e,n,i={}){this.transport=e;this.requestTimeoutMs=n;this.foregroundCapacity=Ji(i.foregroundCapacity,hl),this.foregroundQueueCapacity=Ji(i.foregroundQueueCapacity,xs),this.mutationQueueCapacity=Ji(i.mutationQueueCapacity,xs)}transport;requestTimeoutMs;foregroundCapacity;foregroundQueueCapacity;mutationQueueCapacity;foregroundQueue=[];mutationQueue=[];identicalReads=new Map;latestFamilies=new Map;activeForeground=0;mutationActive=!1;operation(e,n,i={}){let o=!Z(e,n),r=ml(i.coordination,o),s=o&&r.coalesce!==!1&&!r.latestWins&&i.signal===void 0?yl(e,n,i.timeoutMs):void 0;if(s){let c=this.identicalReads.get(s);if(c)return c}let a=W(i,this.requestTimeoutMs,c=>this.schedule(e,n,i,r,o,c));return s&&(this.identicalReads.set(s,a),a.finally(()=>{this.identicalReads.get(s)===a&&this.identicalReads.delete(s)}).catch(()=>{})),a}schedule(e,n,i,o,r,s){let a=o.latestWins?this.replaceLatest(o.family):void 0,c=gl(s.signal,a?.signal),{coordination:l,...u}=i,f=de({...u,timeoutMs:null},s),p=()=>this.transport.operation(e,n,{...f,signal:c.signal}),h=r?this.foregroundQueue:this.mutationQueue,m=r?this.foregroundQueueCapacity:this.mutationQueueCapacity;return h.length>=m?(c.dispose(),this.releaseLatest(o.family,a),Promise.reject(d("connector_busy","The selected connection request queue is full.",{operationOutcome:"not_sent",status:503}))):new Promise((P,v)=>{let b={budget:s,run:p,resolve:A=>P(A),reject:v,started:!1,settled:!1},C=()=>{b.started||b.settled||(b.settled=!0,h.splice(h.indexOf(b),1),b.reject(te(c.signal)),c.dispose(),this.releaseLatest(o.family,a))};c.signal.addEventListener("abort",C,{once:!0});let y=b.run;b.run=async()=>{c.signal.removeEventListener("abort",C);try{if(c.signal.aborted)throw te(c.signal);return await y()}finally{c.dispose(),this.releaseLatest(o.family,a)}},h.push(b),this.pump()})}replaceLatest(e){let n=new AbortController;return this.latestFamilies.get(e)?.abort(d("operation_cancelled","A newer request replaced this read before it changed the collection.",{operationOutcome:"not_sent"})),this.latestFamilies.set(e,n),n}releaseLatest(e,n){e&&n&&this.latestFamilies.get(e)===n&&this.latestFamilies.delete(e)}pump(){for(;this.activeForeground<this.foregroundCapacity;){let e=Es(this.foregroundQueue);if(!e)break;this.activeForeground+=1,this.start(e,()=>{this.activeForeground-=1,this.pump()})}if(!this.mutationActive){let e=Es(this.mutationQueue);e&&(this.mutationActive=!0,this.start(e,()=>{this.mutationActive=!1,this.pump()}))}}start(e,n){e.started=!0,e.run().then(i=>{e.settled||(e.settled=!0,e.resolve(i))},i=>{e.settled||(e.settled=!0,e.reject(i))}).finally(n)}};function Es(t){for(;t.length>0;){let e=t.shift();if(!e.settled)return e}}function ml(t,e){let n=t??{};if(n.latestWins&&!e)throw new TypeError("latestWins coordination is available only for read operations.");if(n.latestWins&&!n.family?.trim())throw new TypeError("latestWins coordination requires a non-empty family.");return n}function yl(t,e,n){return`${t}:${n===void 0?"default":String(n)}:${Yi(e)}`}function Yi(t){return t===null||typeof t!="object"?JSON.stringify(t)??String(t):Array.isArray(t)?`[${t.map(Yi).join(",")}]`:`{${Object.entries(t).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>`${JSON.stringify(e)}:${Yi(n)}`).join(",")}}`}function gl(t,e){if(!e)return{signal:t,dispose:()=>{}};let n=new AbortController,i=()=>n.abort(t.reason),o=()=>n.abort(e.reason);return t.aborted?i():t.addEventListener("abort",i,{once:!0}),e.aborted?o():e.addEventListener("abort",o,{once:!0}),{signal:n.signal,dispose:()=>{t.removeEventListener("abort",i),e.removeEventListener("abort",o)}}}function Ji(t,e){let n=t??e;if(!Number.isSafeInteger(n)||n<=0)throw new TypeError("Request coordinator capacities must be positive safe integers.");return n}var ft=class{constructor(e,n){this.internals=e;this.collectionId=n;this.transport=new Ln({serverUrl:e.serverUrl,storage:e.storage,keyStore:e.keyStore,directAccessMode:e.directAccessMode,loopbackUrl:e.loopbackUrl,collectionId:n,internals:e,timeouts:e.timeouts,onChange:()=>{this.authorityFeatures.refreshLifetime(),this.emitConnection()}}),this.authorityFeatures=new yn({lifetime:()=>{let i=this.transport.currentToken();return JSON.stringify([i?.savedAt,i?.grantId,i?.keyHandle,i?.authority?.operationsUrl,i?.authority?.filesUrl,i?.authority?.replicaId,i?.authority?.proofPublicKey,i?.clientId,i?.applicationOrigin,i?.encryption,i?.scope,i?.operations,i?.fileCapability,this.transport.route])},operations:()=>this.operations,fileCapability:()=>this.fileCapability,describe:async i=>{let o=bn(await this.transport.performOperation("describe",{},i));if(o.collectionId.toLowerCase()!==this.collectionId.toLowerCase())throw d("invalid_operation_response","The authority described a different collection.");return R(o)},filesPage:async(i,o)=>{let r=await Ni((s,a,c,l)=>this.transport.files.control(s,a,c,l),new URLSearchParams({protocol_version:"1",limit:"1",...i?{folder:i}:{}}),o);return ze(r.authority_capabilities)}},e.timeouts.requestMs),this.people=new rt({request:(i,o)=>Vr(i,o??{},{serverUrl:e.serverUrl,collectionId:n,requestMs:e.timeouts.requestMs,authorizedToken:r=>this.transport.authorizedToken({signal:r,timeoutMs:null})}),describe:i=>this.describe(i),queryPages:(i,o)=>this.queryPages(i,o)}),this.files=new dt(()=>this.fileCapability,(i,o,r,s)=>this.transport.files.control(i,o,r,s),{uploadChunk:(i,o,r,s)=>this.transport.files.uploadChunk(i,o,r,s),downloadChunk:(i,o,r)=>this.transport.files.downloadChunk(i,o,r)},{downloadPart:(i,o,r,s)=>this.transport.files.downloadHostedPart(i,o,r,s)},e.timeouts,(i,o)=>this.supportsAuthorityFeature(i,o)),this.records=new pt(this,i=>this.transport.pendingUpdate(i)),this.collectionClient=new at(new Nn({operation:(i,o,r)=>this.transport.performOperation(i,o,r)},e.timeouts.requestMs),e.timeouts.requestMs,(i,o)=>this.supportsAuthorityFeature(i,o)),this.readMany=this.collectionClient.readMany.bind(this.collectionClient),this.notifications=new An({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(n,i),requestTimeoutMs:e.timeouts.requestMs})}internals;collectionId;collectionClient;notifications;transport;authorityFeatures;files;records;people;readMany;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}supportsAuthorityFeature(e,n){return this.authorityFeatures.supports(e,n)}get authorityCapabilities(){return this.authorityFeatures.capabilities}register(e){return I(()=>this.internals.register(e),qe)}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=Ee){let n=this.operations,i=Pt(e).filter(o=>!n.includes(o));return{authorized:this.info()!==null,sufficient:this.info()!==null&&i.length===0,collectionId:this.collectionId,grantedOperations:n,missingOperations:i}}hasOperations(e){return this.authorizationCapabilities(e).sufficient}authorize(e={}){return I(()=>this.internals.authorize({...e,target:{kind:"collection",collectionId:this.collectionId}}),Ce)}async requestCapabilities(e,n={}){return I(async()=>{let i=await this.internals.register(n);if(re(i.requirements,{...n,capabilities:e}),this.info()!==null&&e.every(s=>(X(V(i.requirements),s)??[]).every(a=>this.operations.includes(a))))return{kind:"unchanged",connection:this};if(V(i.requirements)===1){let{capabilities:s,...a}=n;return this.internals.authorize({...a,target:{kind:"collection",collectionId:this.collectionId},operations:[...new Set([...this.operations,...e.flatMap(c=>X(1,c)??[])])]})}let r=Yt(i.requirements,this.operations);return this.internals.authorize({...n,target:{kind:"collection",collectionId:this.collectionId},capabilities:[...new Set([...r,...e])]})},Ce)}async requestOperations(e,n={}){return I(async()=>{let i=await this.internals.register(n);re(i.requirements,{...n,operations:e});let o=this.authorizationCapabilities(e);return o.sufficient?{kind:"unchanged",connection:this}:this.internals.authorize({...n,target:{kind:"collection",collectionId:this.collectionId},operations:[...new Set([...o.grantedOperations,...e])]})},Ce)}onConnectionChange(e){return this.connectionListeners.add(e),e(this.info()),()=>this.connectionListeners.delete(e)}notifyStorageChanged(){this.authorityFeatures.invalidate(),this.transport.notifyStorageChanged()}checkDirectAccess(e){return I(()=>this.transport.checkDirectAccess(e),Si)}requestDirectAccess(e){return I(()=>this.transport.requestDirectAccess(e),Si)}disableDirectAccess(){this.transport.disableDirectAccess()}sync(){let e=this.transport.currentToken();if(!e)return null;let n=e.collectionId;if(!e.authority){if(!e.grantId||!e.operations.includes("sync"))return null;let o=e.grantId;return{collectionId:n,replicaId:o,transport:{openSession:r=>this.transport.performOperation("sync",{action:"open_session"},jn(r,this.internals.timeouts.syncMs)),snapshot:(r,s,a)=>this.transport.performOperation("sync",{action:"snapshot",snapshot_id:r,...s?{page:s}:{}},jn(a,this.internals.timeouts.syncMs)),changes:(r,s=200,a)=>this.transport.performOperation("sync",{action:"changes",after:r,limit:s},jn(a,this.internals.timeouts.syncMs)),mutate:(r,s)=>this.transport.performOperation("sync",{action:"mutate",mutation:r},jn(s,this.internals.timeouts.syncMs))}}}let i=e.authority.replicaId;return{collectionId:n,replicaId:i,transport:{openSession:o=>this.transport.performAuthoritySyncRequest(n,i,"POST","sessions",void 0,o),snapshot:(o,r,s)=>{let a=new URLSearchParams({snapshot_id:o});return r&&a.set("page",r),this.transport.performAuthoritySyncRequest(n,i,"GET",`snapshot?${a}`,void 0,s)},changes:(o,r=200,s)=>this.transport.performAuthoritySyncRequest(n,i,"GET",`changes?${new URLSearchParams({after:String(o),limit:String(r)})}`,void 0,s),mutate:(o,r)=>this.transport.performAuthoritySyncRequest(n,i,"POST","mutations",o,r)}}}registerNotifications(e){return I(()=>this.notifications.registerNotifications(e),wt)}registerNativeNotifications(e){return I(()=>this.notifications.registerNativeNotifications(e),wt)}unregisterNativeNotifications(e){return I(()=>this.notifications.unregisterNativeNotifications(e),wt)}unregisterNotifications(e,n){return I(()=>this.notifications.unregisterNotifications(e,n),wt)}forget(){let e=this.transport.currentToken();this.internals.removeToken(this.collectionId,e?.keyHandle,"not_authorized",!0),this.transport.notifyStorageChanged()}get schemaGeneration(){return this.collectionClient.schemaGeneration}async describe(e){let n=await this.collectionClient.describe(e);return n.ok&&n.value.collectionId.toLowerCase()!==this.collectionId.toLowerCase()?g(w("invalid_operation_response","The authority described a different collection.")):n}changes(e={},n){return this.collectionClient.changes(e,n)}read(e,n){return this.collectionClient.read(e,n)}query(e={},n){return this.collectionClient.query(e,n)}queryPages(e={},n={}){return e.output==="metadata"?this.collectionClient.queryPages(e,n):this.collectionClient.queryPages(e,n)}queryAll(e={},n={}){return e.output==="metadata"?this.collectionClient.queryAll(e,n):this.collectionClient.queryAll(e,n)}listViews(e){return this.collectionClient.listViews(e)}executeView(e,n){return this.collectionClient.executeView(e,n)}executeViewPages(e,n={}){return this.collectionClient.executeViewPages(e,n)}readViewSource(e,n){return this.collectionClient.readViewSource(e,n)}createViewSource(e,n){return this.collectionClient.createViewSource(e,n)}updateViewSource(e,n){return this.collectionClient.updateViewSource(e,n)}deleteViewSource(e,n){return this.collectionClient.deleteViewSource(e,n)}create(e,n){return this.collectionClient.create(e,n)}update(e,n){return this.collectionClient.update(e,n)}delete(e,n){return this.collectionClient.delete(e,n)}preflightDelete(e,n){return this.collectionClient.preflightDelete(e,n)}rename(e,n){return this.collectionClient.rename(e,n)}preflightRename(e,n){return this.collectionClient.preflightRename(e,n)}async renameWithProgress(e,n={}){return W(n,this.internals.timeouts.requestMs,async i=>{let o=Date.now(),r=!1,s,a=(c,l,u=0)=>{n.onProgress?.({operation:"rename",state:c,elapsedMs:Date.now()-o,cancellable:l,resumed:r,completedUnits:u,...s?{estimate:s}:{}})};try{Fe(i.signal),a("preflighting",!0);let c=n.preflight?R(n.preflight):await this.preflightRename(e,{signal:i.signal,timeoutMs:null});if(!c.ok)return c;let l=c.value;try{br(e,l)}catch(p){if(p instanceof _)return g(p.problem);throw p}s=vr(e,l),a("ready",!0),Fe(i.signal);let u=this.transport.hasResumableMutationTransport();a("applying",u);let f=await this.rename(e,u?{signal:i.signal,timeoutMs:null}:{timeoutMs:qs(i.remainingMs())});return f.ok&&a("completed",!1,s.totalUnits),f}catch(c){if(Mi(c,i.signal)&&a("cancelled",!1),c instanceof _)return g(c.problem);throw c}})}async deleteWithProgress(e,n={}){return W(n,this.internals.timeouts.requestMs,async i=>{let o=Date.now(),r=!1,s,a=(c,l,u=0)=>{n.onProgress?.({operation:"delete",state:c,elapsedMs:Date.now()-o,cancellable:l,resumed:r,completedUnits:u,...s?{estimate:s}:{}})};try{Fe(i.signal),a("preflighting",!0);let c=n.preflight?R(n.preflight):await this.preflightDelete(e,{signal:i.signal,timeoutMs:null});if(!c.ok)return c;let l=c.value;try{_r(e,l)}catch(p){if(p instanceof _)return g(p.problem);throw p}s=Cr(l),a("ready",!0),Fe(i.signal);let u=this.transport.hasResumableMutationTransport();a("applying",u);let f=await this.delete(e,u?{signal:i.signal,timeoutMs:null}:{timeoutMs:qs(i.remainingMs())});return f.ok&&a("completed",!1,s.totalUnits),f}catch(c){if(Mi(c,i.signal)&&a("cancelled",!1),c instanceof _)return g(c.problem);throw c}})}pendingMutations(){return this.transport.pendingMutations().map(e=>({...e,recover:n=>I(()=>this.recoverPendingMutation(e.requestId,n),G)}))}pendingMutation(e){let n=this.transport.pendingMutation(e);return n?{...n,recover:i=>I(()=>this.recoverPendingMutation(e,i),G)}:null}async recoverPendingMutation(e,n){let i=await this.transport.recoverPendingMutation(e,n);if(i&&typeof i=="object"&&"valid"in i){let o=i;if(!o.valid)throw new _(je(o));return o.result}return i}validate(e={},n){return this.collectionClient.validate(e,n)}readType(e,n){return this.collectionClient.readType(e,n)}createType(e,n){return this.collectionClient.createType(e,n)}updateType(e,n){return this.collectionClient.updateType(e,n)}assessTypePack(e,n){return this.collectionClient.assessTypePack(e,n)}applyTypePack(e,n){return this.collectionClient.applyTypePack(e,n)}assessCollectionSetup(e,n){return this.collectionClient.assessCollectionSetup(e,n)}applyCollectionSetup(e,n){return this.collectionClient.applyCollectionSetup(e,n)}listTimers(e,n){return this.collectionClient.listTimers(e,n)}putTimer(e,n){return this.collectionClient.putTimer(e,n)}cancelTimer(e,n){return this.collectionClient.cancelTimer(e,n)}reconcileTimers(e,n){return this.collectionClient.reconcileTimers(e,n)}watch(e={},n={}){return I(()=>k(n,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 _(o.problem);if(o.value.reset)throw new _(w("change_cursor_reset","The collection change cursor expired. Refresh collection state before subscribing again."));return new Rn(r=>this.collectionClient.watch(r),o.value.cursor,e,e.cursor===void 0?[]:o.value.events,this.internals.timeouts.watchStartMs)}),tn)}emitConnection(){let e=this.info();for(let n of this.connectionListeners)n(e)}};function jn(t,e){return{...t,timeoutMs:t?.timeoutMs===void 0?e:t.timeoutMs}}function qs(t){return t===null?null:Math.max(1,Math.ceil(t))}async function zs(t){if(typeof location>"u"&&!t.navigate&&!t.options.openVerification)throw d("browser_required","Authorization navigation requires a browser environment.");let n=(t.options.presentation==="popup"||t.portableDeclared)&&!t.options.openVerification&&!t.navigate&&typeof window<"u"?window.open("","mdbase-connect-authorization","popup,width=620,height=760"):null;try{return{application:await t.register(t.options.signal),popup:n}}catch(i){throw n?.close(),i}}async function Ls(t){let e=Ns(t.storagePrefix,t.state);try{for(;;){let n=F(t.storage.getItem(e));if(n?.version===1){if(t.storage.removeItem(e),n.status==="failed")throw L(n.code,n.message,{details:n.returnTo?{return_to:n.returnTo}:void 0});let i=t.connection(n.collectionId);if(!i)throw d("invalid_callback","Authorization completed without a usable saved connection.");return{kind:"connected",connection:i,...n.returnTo?{returnTo:n.returnTo}:{}}}await oe(200,t.signal)}}finally{t.popup.close(),t.storage.removeItem(e);let n=`${t.storagePrefix}:pending:${t.state}`;F(t.storage.getItem(n))?.state===t.state&&(t.storage.removeItem(n),t.pending.keyHandle&&await t.keyStore.delete(t.pending.keyHandle))}}function Us(t){return t.completion.then(e=>(t.popupAttempt&&Fs(t,{version:1,status:"connected",collectionId:e.connection.collectionId,...e.returnTo?{returnTo:e.returnTo}:{}}),t.popupAttempt&&Ds(),e)).catch(e=>{throw t.popupAttempt&&Fs(t,{version:1,status:"failed",code:e instanceof _?e.code:"invalid_callback",message:e instanceof Error?e.message:"Authorization could not be completed.",...t.pending?.returnTo?{returnTo:t.pending.returnTo}:{}}),t.popupAttempt&&Ds(),e})}function Fs(t,e){t.storage.setItem(Ns(t.storagePrefix,t.state),JSON.stringify(e))}function Ns(t,e){return`${t}:completion:${e}`}function Ds(){typeof window<"u"&&typeof window.close=="function"&&window.close()}function Xi(t,e,n,i){let o=`${e}:pending-mutation:`,r=new Set;for(let s=0;s<t.length;s+=1){let a=t.key(s);if(!a?.startsWith(o))continue;let c=F(t.getItem(a));if(!c||!n.includes(c.operation)||i&&c.collectionId!==i)continue;let l=c.envelope?.protocol_version??c.request?.protocol_version;l!==void 0&&l!==Y&&mt(l)&&r.add(l)}return[...r].sort((s,a)=>a-s)}function Zi(t,e,n){return eo(t,e).has(n)}function eo(t,e){let n=new Set;for(let i=0;i<t.length;i+=1){let o=t.key(i);if(o!==e&&!o?.startsWith(`${e}:`))continue;let r=F(t.getItem(o));r?.keyHandle&&n.add(r.keyHandle)}return n}function js(t,e,n){let i=[e];for(let o=0;o<t.length;o+=1){let r=t.key(o);r?.startsWith(`${e}:`)&&i.push(r)}for(let o of i){let r=F(t.getItem(o));r?.keyHandle&&n(r.keyHandle),t.removeItem(o)}}function Bs({body:t,clientId:e,keyHandle:n,previous:i,retiredKeyHandles:o,defaultApplicationOrigin:r,pinConnectorIdentity:s}){let a=t.collection_id;if(typeof a!="string")throw d("invalid_token_response","Authorization returned no collection ID.");let c=cn(t.scope);if(!c)throw d("invalid_token_response","Authorization returned no valid collection scope.");if(!ln(c))throw d("legacy_scope_reauthorization_required","Authorization returned a legacy contract-scoped grant. Reauthorize for the entire collection.");if(t.authority&&!Mt(t.authority,a))throw d("invalid_token_response","Authorization returned an invalid remote authority capability.");if(t.authority&&t.encryption)throw d("invalid_token_response","Authorization returned conflicting collection transports.");if(t.file_capability!==null&&t.file_capability!==void 0&&!an(t.file_capability))throw d("invalid_token_response","Authorization returned an invalid file capability.");if(t.encryption){try{ye(t.encryption)}catch{throw d("invalid_token_response","Authorization returned an invalid encrypted relay binding.")}if(s(t.encryption.connector_id,t.encryption.connector_agreement_public_key),t.encryption.collection_id!==a||typeof t.grant_id!="string"||t.grant_id.length===0)throw d("invalid_token_response","Authorization returned an encrypted relay binding for another grant.")}if(i?.encryption&&t.encryption&&i.keyHandle&&i.keyHandle===n&&(i.grantId!==t.grant_id||i.encryption.connector_id!==t.encryption.connector_id||i.encryption.connector_agreement_public_key!==t.encryption.connector_agreement_public_key||i.encryption.application_agreement_public_key!==t.encryption.application_agreement_public_key))throw d("connector_identity_changed","The connector identity changed during authorization renewal. Reauthorize before sending collection data.");return{version:1,accessToken:t.access_token,refreshToken:t.refresh_token,clientId:e,collectionId:a,collectionName:t.collection_name??`Collection ${a.slice(0,8)}`,operations:t.operations,scope:c,expiresAt:Date.now()+t.expires_in*1e3,refreshExpiresAt:t.refresh_expires_in?Date.now()+t.refresh_expires_in*1e3:void 0,grantId:t.grant_id,encryption:t.encryption??void 0,fileCapability:t.file_capability??void 0,applicationOrigin:t.application_origin??r,keyHandle:n,...o?.length?{retiredKeyHandles:o}:{},savedAt:Date.now(),authority:t.authority?{operationsUrl:t.authority.operations_url,syncUrl:t.authority.sync_url,filesUrl:t.authority.files_url,replicaId:t.authority.replica_id,accessToken:t.authority.access_token,proofPublicKey:t.authority.proof_public_key}:void 0}}function to(t,e){let n=new Set;if(e&&n.add(e),t?.keyHandle&&n.add(t.keyHandle),Array.isArray(t?.retiredKeyHandles))for(let i of t.retiredKeyHandles)typeof i=="string"&&i.length>0&&n.add(i);return n}function Ks(t,e,n,i,o=[],r=!1){let s=[],a=[],c=to(n);for(let u of eo(t,e))c.add(u);let l=new Set(o);for(let u of l)c.add(u);for(let u of c)u!==i&&(r||l.has(u)||Zi(t,e,u)?s:a).push(u);return{retained:s,disposable:a}}function bl(t,e,n){let i=F(t.getItem(e));if(!i||!Array.isArray(i.retiredKeyHandles))return;let o=i.retiredKeyHandles.filter(r=>r!==n);o.length!==i.retiredKeyHandles.length&&(o.length>0?i.retiredKeyHandles=o:delete i.retiredKeyHandles,t.setItem(e,JSON.stringify(i)))}async function Qs(t,e,n,i,o){F(t.getItem(i))?.keyHandle===o||Zi(t,n,o)||(await e.delete(o),bl(t,i,o))}var Bn=class{serverUrl;manifest;manifestSource;redirectUri;storage;relayEncryption;keyStore;identityStore;directAccessMode;loopbackUrl;navigate;timeouts;credentialStorage;application=null;manifestPromise=null;completionPromises=new Oe;grantKeyLeases;connectionCache=new Map;listeners=new Set;invalidatedConnections=new Map;constructor(e){this.serverUrl=xr(String(e.serverUrl));let n=Ar(e.manifest,e.redirectUri);this.manifest=n.manifest,this.manifestSource=n.manifestSource;let i=Dr(this.manifest);this.redirectUri=n.redirectUri,this.storage=e.storage??Fr(i),this.relayEncryption=e.relayEncryption??"required",this.keyStore=e.keyStore??(i?new We:new He),this.identityStore=e.identityStore??(i?new it:new nt),this.credentialStorage=e.storage||e.keyStore||e.identityStore?"custom":this.storage instanceof Ye?"memory":"persistent",this.directAccessMode=e.directAccess??"auto",this.loopbackUrl=Tr(String(e.loopbackUrl??`http://127.0.0.1:${Io}`)),this.navigate=e.navigate,this.timeouts=Ve(e.timeouts),this.grantKeyLeases=new Mn(this.storagePrefix(),(o,r)=>this.deleteGrantKeyWhenUnused(o,r)),typeof window<"u"&&this.storage===window.localStorage&&window.addEventListener("storage",o=>{o.storageArea!==this.storage||!o.key?.startsWith(this.storagePrefix())||(this.connectionCache.get(qr(o.key))?.notifyStorageChanged(),this.emitConnections())})}environment(){return{distribution:typeof this.manifest!="string"&&this.manifest.distribution==="portable"?"portable":this.application?.distribution??"web",applicationOrigin:this.defaultApplicationOrigin(),credentialStorage:this.credentialStorage}}register(e={}){return k(e,this.timeouts.requestMs,n=>this.registerWithinBudget(n.signal))}async registerWithinBudget(e){if(this.application)return this.application;let n=await ae(`${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 E(n,"invalid_operation_response","Connect returned an invalid application registration response.");if(!n.ok)throw z(i,"discovery_failed","Application discovery failed.",n.status);return this.application=i.application,this.application}manifestDeclaration(e={}){if(this.manifestPromise)return this.manifestPromise;let i=k(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 n=this.manifest,i;try{i=await fetch(n,{headers:{accept:"application/json"},signal:e})}catch(o){throw d("manifest_load_failed","The bundled application declaration could not be loaded.",{cause:o})}if(!i.ok)throw d("manifest_load_failed",`The bundled application declaration returned HTTP ${i.status}.`,{status:i.status});try{return await E(i,"invalid_application_manifest","The bundled application declaration is not valid JSON.")}catch(o){throw d("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={}){let n=e.presentation==="popup"?6e5:this.timeouts.requestMs;return k(e,n,i=>this.authorizeWithinBudget({...e,signal:i.signal,timeoutMs:null}))}async authorizeWithinBudget(e){let n=typeof this.manifest!="string"&&this.manifest.distribution==="portable",{application:i,popup:o}=await zs({options:e,portableDeclared:n,navigate:this.navigate,register:r=>this.registerWithinBudget(r)});try{re(i.requirements,e),i.requirements.capabilities?.contract_version===2&&await zr(this.serverUrl,e.signal)}catch(r){throw o?.close(),r}return i.distribution==="portable"?(e.openVerification&&o?.close(),this.authorizePortable(i,e,e.openVerification?null:o)):this.authorizeWeb(i,e,o)}async authorizeWeb(e,n,i){let{verifier:o,challenge:r}=await At(),s=se(24),a=crypto.randomUUID(),c=n.target?.kind==="collection"?n.target.collectionId:void 0,l=`grant:${e.id}:${s}`,u=await this.keyStore.create(l),f;try{f=await this.loadApplicationIdentity(e)}catch(b){throw await this.keyStore.delete(l),b}let p=_i(e,n),h=vi(e.requirements),m=new Date,P=await qt({protocol_version:ce,authorization_id:a,application_id:e.id,application_declaration_id:It(e.family_identity),application_manifest_digest:e.manifest_digest,application_installation_id:await ot(f),installation_signing_public_key:f.signingPublicKey,grant_agreement_public_key:u.agreementPublicKey,grant_signing_public_key:u.signingPublicKey,flow:"authorization_code",authorization_nonce:se(32),issued_at:m.toISOString(),expires_at:new Date(m.getTime()+600*1e3).toISOString(),redirect_uri:this.redirectUri,state:s,code_challenge:r,contracts:ni(p,h,Xi(this.storage,this.storagePrefix(),p,c),V(e.requirements)),requested_operations:p,...h?{requested_files:h}:{},...c?{collection_id:c}:{}},f),v={version:1,verifier:o,state:s,clientId:e.id,redirectUri:this.redirectUri,relayEncryption:this.relayEncryption,collectionId:c,returnTo:n.returnTo,keyHandle:l,authorizationId:a,applicationAgreementPublicKey:u.agreementPublicKey,applicationSigningPublicKey:u.signingPublicKey,...n.presentation==="popup"&&i?{presentation:"popup"}:{}};this.storage.setItem(this.pendingKey(s),JSON.stringify(v));try{let b=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:r,code_challenge_method:"S256",state:s,operations:p.join(","),...c?{collection_id:c}:{},application_authorization:JSON.stringify(P)}),signal:n.signal}),C=await E(b,"invalid_device_authorization_response","The authorization service returned an invalid authorization response.");if(!b.ok)throw z(C,"device_authorization_failed","Application authorization could not be started.",b.status);if(typeof C.authorization_uri!="string"||C.authorization_id!==a||!Number.isInteger(C.expires_in)||C.expires_in<=0)throw d("invalid_device_authorization_response","The authorization service returned an invalid authorization response.");if(n.presentation==="popup"&&i)return i.location.href=C.authorization_uri,await Ls({storage:this.storage,storagePrefix:this.storagePrefix(),state:s,pending:v,popup:i,signal:n.signal,keyStore:this.keyStore,connection:y=>this.connection(y)});if(i?.close(),this.navigate)await this.navigate(C.authorization_uri);else if(typeof location<"u")location.assign(C.authorization_uri);else throw d("browser_required","Authorization navigation requires a browser environment.");return{kind:"redirecting"}}catch(b){throw i?.close(),this.storage.removeItem(this.pendingKey(s)),await this.keyStore.delete(l),n.signal?.aborted?Xe(n.signal,"Application authorization was cancelled.",b):b}}async authorizePortable(e,n,i){if(this.relayEncryption!=="required")throw i?.close(),d("encryption_required","Downloaded applications require encrypted relay authorization.");let{verifier:o,challenge:r}=await At(),s=`grant:${e.id}:${se(24)}`,a=await this.keyStore.create(s),c;try{c=await this.loadApplicationIdentity(e)}catch(C){throw i?.close(),await this.keyStore.delete(s),C}let l=_i(e,n),u=vi(e.requirements),f=crypto.randomUUID(),p=new Date,h=await qt({protocol_version:ce,authorization_id:f,application_id:e.id,application_declaration_id:It(e.family_identity),application_manifest_digest:e.manifest_digest,application_installation_id:await ot(c),installation_signing_public_key:c.signingPublicKey,grant_agreement_public_key:a.agreementPublicKey,grant_signing_public_key:a.signingPublicKey,flow:"device_code",authorization_nonce:se(32),issued_at:p.toISOString(),expires_at:new Date(p.getTime()+600*1e3).toISOString(),code_challenge:r,contracts:ni(l,u,Xi(this.storage,this.storagePrefix(),l,n.target?.kind==="collection"?n.target.collectionId:void 0),V(e.requirements)),requested_operations:l,...u?{requested_files:u}:{},...n.target?.kind==="collection"?{collection_id:n.target.collectionId}:{}},c),m,P;try{m=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:l.join(","),...n.target?.kind==="collection"?{collection_id:n.target.collectionId}:{},code_challenge:r,code_challenge_method:"S256",application_authorization:JSON.stringify(h)}),signal:n.signal}),P=await E(m,"invalid_device_authorization_response","The authorization service returned an invalid device authorization response.")}catch(C){throw i?.close(),await this.keyStore.delete(s),d("device_authorization_failed","Downloaded application authorization could not be started.",{cause:C})}if(!m.ok)throw i?.close(),await this.keyStore.delete(s),z(P,"device_authorization_failed","Downloaded application authorization could not be started.",m.status);let v;try{v=kr(P)}catch(C){throw i?.close(),await this.keyStore.delete(s),n.signal?.aborted?Xe(n.signal,"Downloaded application authorization was cancelled.",C):C}if(n.onDeviceCode?.(v),n.openVerification)await n.openVerification(v);else if(i)try{i.location.href=v.verificationUriComplete}catch{}else throw await this.keyStore.delete(s),d("approval_window_blocked","The approval window was blocked. Show the provided verification link and code, then try again.",{details:{user_code:v.userCode,verification_uri:v.verificationUri,verification_uri_complete:v.verificationUriComplete,expires_at:v.expiresAt,interval_seconds:v.intervalSeconds}});let b=v.intervalSeconds;try{for(;Date.now()<v.expiresAt;){if(await oe(b*1e3,n.signal),n.signal?.aborted)throw Xe(n.signal,"Downloaded application authorization was cancelled.");let C;try{C=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:P.device_code,client_id:e.id,code_verifier:o}),signal:n.signal})}catch(T){if(n.signal?.aborted)throw Xe(n.signal,"Downloaded application authorization was cancelled.",T);continue}let y=await E(C,"invalid_token_response","The authorization service returned an invalid token response.");if(!C.ok){let T=Tt(y);if(T==="authorization_pending")continue;if(T==="slow_down"){b+=5;continue}throw z(y,"token_exchange_failed","Downloaded application authorization could not be completed.",C.status)}let A=Mt(y.authority,y.collection_id),D=y.encryption&&y.encryption.protocol_version===Vt&&y.encryption.suite===gt&&y.encryption.application_agreement_public_key===a.agreementPublicKey;if(y.application_origin!==this.defaultApplicationOrigin())throw d("invalid_token_response","Authorization did not bind the portable grant to its exact application origin.");if(y.authority&&(!A||y.encryption!=null||y.authority.proof_public_key!==a.signingPublicKey))throw d("invalid_token_response","Authorization returned a remote authority capability that is not bound to this portable grant key.");if(!y.authority&&!D)throw d("encryption_required","Authorization did not establish the expected key-bound local portable grant.");let S=this.storeTokenResponse(y,e.id,s);if(n.target?.kind==="collection"&&n.target.collectionId!==S.collectionId)throw this.removeToken(S.collectionId,S.keyHandle),d("collection_mismatch","The approved collection does not match the collection requested by this link.");return i?.close(),{kind:"connected",connection:this.connection(S.collectionId),...n.returnTo?{returnTo:n.returnTo}:{}}}throw d("expired_token","The downloaded application authorization code expired.")}catch(C){throw i?.close(),await this.keyStore.delete(s),n.signal?.aborted?Xe(n.signal,"Downloaded application authorization was cancelled.",C):C}}completeAuthorization(e,n={}){let i=pn(e);if(!i)return Promise.reject(d("invalid_callback","Authorization callback is missing its state."));let o=F(this.storage.getItem(this.pendingKey(i))),r=o?.presentation==="popup";return this.completionPromises.run(i,n,this.timeouts.requestMs,s=>Us({storage:this.storage,storagePrefix:this.storagePrefix(),state:i,pending:o,popupAttempt:r,completion:this.performAuthorizationCompletion(e,i,s)}))}async performAuthorizationCompletion(e,n,i){let o=new URL(e),r=o.searchParams.get("code"),s=this.pendingKey(n),a=F(this.storage.getItem(s));if(!a||a.version!==1||n!==a.state)throw d("invalid_callback","Authorization callback is missing or does not match this browser session.");if(o.searchParams.has("error"))throw a.keyHandle&&await this.keyStore.delete(a.keyHandle),this.storage.removeItem(s),L(o.searchParams.get("error")??"access_denied",o.searchParams.get("error_description")??"Collection access was not approved.",{details:a.returnTo?{return_to:a.returnTo}:void 0});if(!r)throw d("invalid_callback","Authorization callback is missing its code.");let c=await ae(`${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:a.clientId,redirect_uri:a.redirectUri,code_verifier:a.verifier}),signal:i},"temporarily_unavailable","Authorization completion is temporarily unavailable."),l=await E(c,"invalid_token_response","The authorization service returned an invalid token response.");if(!c.ok)throw z(l,"token_exchange_failed","Authorization could not be completed.",c.status);if(a.relayEncryption==="required"&&!l.authority&&(!l.encryption||!a.keyHandle||l.encryption.application_agreement_public_key!==a.applicationAgreementPublicKey))throw a.keyHandle&&await this.keyStore.delete(a.keyHandle),this.storage.removeItem(s),d("encryption_required","Authorization did not establish the required encrypted relay grant.");if(l.authority?.proof_public_key){if(!a.keyHandle||!a.applicationSigningPublicKey||l.authority.proof_public_key!==a.applicationSigningPublicKey)throw a.keyHandle&&await this.keyStore.delete(a.keyHandle),this.storage.removeItem(s),d("invalid_token_response","Authorization returned a remote authority capability bound to another application key.")}else l.authority&&a.keyHandle&&await this.keyStore.delete(a.keyHandle);let u=this.storeTokenResponse(l,a.clientId,l.authority?.proof_public_key?a.keyHandle:l.authority?void 0:a.keyHandle);if(a.collectionId&&a.collectionId!==u.collectionId)throw this.removeToken(u.collectionId,u.keyHandle),this.storage.removeItem(s),d("collection_mismatch","The approved collection does not match the collection requested by this link.");return this.storage.removeItem(s),{connection:this.connection(u.collectionId),...a.returnTo?{returnTo:a.returnTo}:{}}}connections(){let e=[];for(let n of sn(this.storage,this.storagePrefix())){let i=this.connection(n)?.info();i&&e.push(i)}return e.sort((n,i)=>n.displayName.localeCompare(i.displayName)||n.collectionId.localeCompare(i.collectionId))}connection(e){if(!this.storage.getItem(this.tokenKey(e)))return null;let n=this.connectionCache.get(e);return n||(n=new ft(this,e),this.connectionCache.set(e,n)),n.info()?n:null}unavailableReason(e){return this.invalidatedConnections.get(e)??null}connectionApplicationId(e){if(!this.connection(e))return null;let n=F(this.storage.getItem(this.tokenKey(e)));return typeof n?.clientId=="string"&&n.clientId.length>0?n.clientId:null}onConnectionsChange(e){return this.listeners.add(e),e(this.connections()),()=>this.listeners.delete(e)}storeTokenResponse(e,n,i){let o=e.collection_id;if(typeof o!="string")throw d("invalid_token_response","Authorization returned no collection ID.");let r=F(this.storage.getItem(this.tokenKey(o))),s=Ks(this.storage,this.pendingMutationKey(o),r,i,this.grantKeyLeases.handles(o),this.grantKeyLeases.retainAutomaticallyRetiredKeys),a;try{a=Bs({body:e,clientId:n,keyHandle:i,previous:r,retiredKeyHandles:s.retained,defaultApplicationOrigin:this.defaultApplicationOrigin(),pinConnectorIdentity:(c,l)=>this.pinConnectorIdentity(c,l)})}catch(c){throw c instanceof _&&c.code==="legacy_scope_reauthorization_required"&&this.removeToken(o,i,c.code),c}this.storage.setItem(this.tokenKey(o),JSON.stringify(a));for(let c of s.disposable)this.deleteGrantKeyWhenUnused(o,c);return Sr(this.storage,this.storagePrefix(),o),this.invalidatedConnections.delete(o),this.connectionCache.delete(o),this.emitConnections(),a}forgetConnectorIdentity(e){this.storage.removeItem(this.connectorPinKey(e))}pinConnectorIdentity(e,n){let i=this.connectorPinKey(e),o=F(this.storage.getItem(i));if(o&&(o.version!==1||o.publicKey!==n))throw d("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:n}))}connectorPinKey(e){return`mdbase-connect:${this.serverUrl}:connector-pin:${e}`}async loadApplicationIdentity(e){try{return await fn(this.identityStore,this.serverUrl,e)}catch(n){throw d("application_identity_unavailable",n instanceof De?n.message:"The application installation identity is unavailable.",{cause:n})}}removeToken(e,n,i="authorization_lost",o=!1){this.invalidatedConnections.set(e,i);let r=F(this.storage.getItem(this.tokenKey(e))),s=to(r,n);this.storage.removeItem(this.tokenKey(e)),o&&js(this.storage,this.pendingMutationKey(e),a=>s.add(a));for(let a of s)this.deleteGrantKeyWhenUnused(e,a);for(let a of["web_push","fcm"])this.storage.removeItem(this.notificationKey(e,a));Or(this.storage,this.storagePrefix(),e),this.connectionCache.delete(e),this.emitConnections()}acquireGrantKeyLease(e,n,i){return this.grantKeyLeases.acquire(e,n,i)}deleteGrantKeyWhenUnused(e,n){this.grantKeyLeases.deleteExclusive(e,n,()=>Qs(this.storage,this.keyStore,this.pendingMutationKey(e),this.tokenKey(e),n))}tokenKey(e){return`${this.storagePrefix()}:token:${e}`}pendingMutationKey(e){return`${this.storagePrefix()}:pending-mutation:${e}`}notificationKey(e,n="web_push"){return`${this.storagePrefix()}:notifications:${e}:${n}`}directPreferenceKey(){return`mdbase-connect:direct:${this.defaultApplicationOrigin()}`}defaultApplicationOrigin(){return Er(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}`}emitConnections(){let e=this.connections();for(let n of this.listeners)n(e)}};var Kn=class{internals;constructor(e){this.internals=new Bn(e)}register(e){return I(()=>this.internals.register(e),qe)}authorize(e={}){return I(()=>this.internals.authorize(e),Ce)}application(e){return new et(this,e,this.internals.timeouts)}manifest(e){return I(()=>this.internals.manifestDeclaration(e),qe)}environment(){return this.internals.environment()}completeAuthorization(e,n){return I(()=>this.internals.completeAuthorization(e===void 0?dn():String(e),n),Ce)}connections(){return this.internals.connections()}connection(e){return this.internals.connection(e)}unavailableReason(e){return this.internals.unavailableReason(e)}connectionApplicationId(e){return this.internals.connectionApplicationId(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 no(t){if(!t||typeof t!="object")throw d("invalid_push_payload","The push payload is not an object.");let e=t;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 d("invalid_push_payload","The push payload is not an mdbase notification.");return e}function Vs(t){if(!t||typeof t!="object")throw d("invalid_push_payload","The native notification data is not an object.");let e=t;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 d("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 Gs(t,e){let n=no(e);return t.showNotification(n.presentation.title,{...n.presentation.body?{body:n.presentation.body}:{},...n.presentation.tag?{tag:n.presentation.tag}:{},data:{type:n.type,signal_id:n.signal_id,criterion_id:n.criterion_id,cursor:n.cursor}})}function Hs(t,e,n={}){let i=JSON.stringify(t),o=`record[${i}]`,r=JSON.stringify(e),s=a=>`${a} != null && ${a}.asFile() != null && ${a}.asFile().file.path == ${r}`;return`${i} in record && ${n.multiple?`${o} != null && ${o}.exists(link, ${s("link")})`:s(o)}`}function Ws(t){return{subscribe:e=>t.subscribe(e),getSnapshot:()=>t.getSnapshot()}}var Qn=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,n={}){let i=kt(this.currentUrl());e?i.searchParams.set(this.collectionParameter,e):i.searchParams.delete(this.collectionParameter);let o=this.browserHistory();o[n.history==="push"?"pushState":"replaceState"](o.state,"",i),this.emit()}authorizationReturnTo(){let e=kt(this.currentUrl());return`${e.pathname}${e.search}${e.hash}`}authorizationCallback(){let e=this.currentUrl().href;return un(e)?e:null}finishAuthorization(e,n){let i=this.safeAppUrl(e??this.fallbackPath);kt(i),i.searchParams.set(this.collectionParameter,n),this.browserHistory().replaceState(null,"",i),this.emit()}clearAuthorizationCallback(e){let n=e?this.safeAppUrl(e):this.currentUrl(),i=this.browserHistory();i.replaceState(i.state,"",kt(n)),this.emit()}subscribe(e){let n=this.listeners.size===0;return this.listeners.add(e),n&&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 n=this.currentUrl(),i=new URL(e,n.origin);return i.origin===n.origin?i:new URL(this.fallbackPath,n.origin)}currentUrl(){if(typeof location>"u")throw d("browser_required","Browser selection requires a browser environment.");return new URL(location.href)}browserHistory(){if(typeof history>"u")throw d("browser_required","Browser selection requires a browser environment.");return history}},Vn=class{collectionId=null;listeners=new Set;selectedCollectionId(){return this.collectionId}select(e){if(e!==this.collectionId){this.collectionId=e;for(let n of this.listeners)n()}}authorizationReturnTo(){}authorizationCallback(){return null}finishAuthorization(e,n){this.select(n)}clearAuthorizationCallback(){}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}};return ea(_l);})();
1
+ "use strict";var MdbaseConnect=(()=>{var Yn=Object.defineProperty;var na=Object.getOwnPropertyDescriptor;var ia=Object.getOwnPropertyNames;var oa=Object.prototype.hasOwnProperty;var ra=(t,e)=>{for(var n in e)Yn(t,n,{get:e[n],enumerable:!0})},sa=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ia(e))!oa.call(t,o)&&o!==n&&Yn(t,o,{get:()=>e[o],enumerable:!(i=na(e,o))||i.enumerable});return t};var aa=t=>sa(Yn({},"__esModule",{value:!0}),t);var xl={};ra(xl,{ApplicationIdentityStoreError:()=>Le,FileTransferCryptoError:()=>ge,GrantFileTransferCipher:()=>ut,IndexedDbApplicationIdentityStore:()=>rt,IndexedDbGrantKeyStore:()=>Je,MDBASE_RECORD_CREATED_CONTRACT:()=>qo,MDBASE_TIMER_FIRED_CONTRACT:()=>Fo,MdbaseApplicationSession:()=>it,MdbaseBrowserSelection:()=>Wn,MdbaseCollectionClient:()=>dt,MdbaseConnect:()=>$n,MdbaseConnectError:()=>_,MdbaseConnection:()=>yt,MdbaseFileClient:()=>ht,MdbaseMemorySelection:()=>Jn,MdbaseMemoryVerificationStore:()=>Dt,MdbasePeopleClient:()=>ct,MdbaseQueryObserver:()=>Ge,MdbaseRecordSession:()=>ft,MdbaseRecords:()=>mt,MdbaseSession:()=>nt,MemoryApplicationIdentityStore:()=>st,MemoryGrantKeyStore:()=>Ye,PERSON_CONTRACT:()=>Ut,RelayCryptoError:()=>q,applicationIdentity:()=>bn,applicationInstallationId:()=>at,authorityProofMessage:()=>Ei,connectError:()=>d,connectFailure:()=>b,connectProblem:()=>w,connectSuccess:()=>O,createPkce:()=>kt,decryptRelayResponse:()=>Xe,deriveFileTransferKey:()=>$i,deriveP256SharedSecret:()=>Tt,effectiveCapabilities:()=>sn,encryptRelayRequest:()=>me,externalStore:()=>ta,isRetryableConnectError:()=>Uo,linksTo:()=>ea,normalizeCollectionChange:()=>Ai,operationProblem:()=>Ke,operationsForApplicationCapabilities:()=>lo,parseMdbaseNativeNotificationData:()=>Xs,parseMdbasePushPayload:()=>co,sameIdentity:()=>vn,showMdbasePushNotification:()=>Zs,signApplicationAuthorization:()=>Lt,signAuthorityRequest:()=>ln,validateGrantEncryption:()=>ye});var jt={"collection.read":["describe","changes","read","query","list_views","execute_view","read_view_source","validate","read_type"],"records.create":["create"],"records.edit":["update","rename"],"records.delete":["delete"],"views.manage":["create_view_source","update_view_source","delete_view_source"],"definitions.manage":["create_type","update_type","assess_type_pack","apply_type_pack"],"background.schedule":["list_timers","put_timer","cancel_timer","reconcile_timers"],"offline.replica":["sync"]},Bt=["assess_collection_setup","apply_collection_setup"];function lo(t,e={}){let n=e.includeOptional===!1?t.required:[...t.required,...t.optional??[]];return[...new Set(n.flatMap(i=>jt[i]))]}var ca=Object.freeze({"collection.inspect":Object.freeze(["describe"]),"records.watch":Object.freeze(["changes"]),"records.read":Object.freeze(["read"]),"records.query":Object.freeze(["query"]),"records.validate":Object.freeze(["validate"]),"records.create":Object.freeze(["create"]),"records.update":Object.freeze(["update"]),"records.delete":Object.freeze(["delete"]),"records.rename":Object.freeze(["rename"]),"views.list":Object.freeze(["list_views"]),"views.execute":Object.freeze(["execute_view"]),"views.source.read":Object.freeze(["read_view_source"]),"views.source.create":Object.freeze(["create_view_source"]),"views.source.update":Object.freeze(["update_view_source"]),"views.source.delete":Object.freeze(["delete_view_source"]),"definitions.contracts.current":Object.freeze([]),"definitions.read":Object.freeze(["read_type"]),"definitions.create":Object.freeze(["create_type"]),"definitions.update":Object.freeze(["update_type"]),"definitions.type-pack.inspect":Object.freeze(["assess_type_pack"]),"definitions.type-pack.apply":Object.freeze(["assess_type_pack","apply_type_pack"]),"collection.setup.apply":Object.freeze(["assess_collection_setup","apply_collection_setup"]),"timers.list":Object.freeze(["list_timers"]),"timers.put":Object.freeze(["put_timer"]),"timers.cancel":Object.freeze(["cancel_timer"]),"timers.reconcile":Object.freeze(["reconcile_timers"]),"sync.offline-replica":Object.freeze(["sync"]),"notifications.background-delivery":Object.freeze([]),"files.list":Object.freeze([]),"files.read":Object.freeze([]),"files.add":Object.freeze([]),"files.replace":Object.freeze([]),"files.move":Object.freeze([]),"files.delete":Object.freeze([])});function X(t,e){let n=t===1?ca:t===2?jt:void 0;if(!(!n||!Object.hasOwn(n,e)))return[...n[e]]}var ql=Object.freeze([1,2]),uo="application-authorization-v2-issuance",Xn=Object.freeze(["application-authorization-v2-issuance"]);var po="yaml-document-records-v1";var ke={access_denied:{category:"authorization",recovery:"reauthorize"},access_paused:{category:"availability",recovery:"resume_connector_access"},application_authorization_issuance_disabled:{category:"authorization",recovery:"reauthorize"},application_declaration_mismatch:{category:"authorization",recovery:"reauthorize"},application_identity_unavailable:{category:"compatibility",recovery:"upgrade_application"},application_reauthorization_required:{category:"authorization",recovery:"reauthorize"},application_semantic_version_mismatch:{category:"authorization",recovery:"reauthorize"},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_claimed_by_newer_runtime:{category:"compatibility",recovery:"upgrade_connector"},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_unavailable:{category:"availability",recovery:"choose_collection"},collection_version_unsupported:{category:"compatibility",recovery:"upgrade_collection"},concurrent_modification:{category:"conflict",recovery:"refresh"},connector_busy:{category:"availability",recovery:"retry"},connector_identity_changed:{category:"integrity",recovery:"reauthorize"},connector_offline:{category:"availability",recovery:"retry"},connector_upgrade_required:{category:"compatibility",recovery:"upgrade_connector"},cursor_capacity_exhausted:{category:"availability",recovery:"retry"},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_index_warming:{category:"availability",recovery:"retry"},file_list_changed:{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"},fresh_request_required:{category:"availability",recovery:"retry"},generation_expired:{category:"conflict",recovery:"refresh"},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_read_cursor:{category:"validation",recovery:"fix_request"},invalid_replica:{category:"authorization",recovery:"reauthorize"},invalid_request:{category:"validation",recovery:"fix_request"},invalid_token_response:{category:"integrity",recovery:"contact_support"},legacy_scope_reauthorization_required:{category:"authorization",recovery:"reauthorize"},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_grant_reauthorization_required:{category:"authorization",recovery:"reauthorize"},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"},origin_denied:{category:"authorization",recovery:"reauthorize"},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"},replica_scope_denied:{category:"authorization",recovery:"reauthorize"},sandbox_unsupported:{category:"compatibility",recovery:"fix_request"},scope_changed:{category:"authorization",recovery:"reauthorize"},scope_denied:{category:"authorization",recovery:"reauthorize"},scope_epoch_stale:{category:"authorization",recovery:"reauthorize"},session_destroyed:{category:"cancellation",recovery:"none"},session_not_started:{category:"validation",recovery:"fix_request"},session_starting:{category:"availability",recovery:"retry"},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"},timer_grant_unavailable:{category:"authorization",recovery:"reauthorize"},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"}},la={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_unavailable:{type:"object",required:["reason"],properties:{reason:{type:"string"}}},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 ho(t){return Object.hasOwn(ke,t)}function gt(t){if(!fo(t))return!1;let e=t;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"||!ho(e.code)||e.server_code!==void 0)return!1;let n=ke[e.code],i=la[e.code],o=i===void 0?e.details===void 0:e.details===void 0?(i.required?.length??0)===0:Zn(e.details,i);return e.category===n.category&&e.recovery===n.recovery&&o}function Zn(t,e){if(e.type===void 0)return!0;if(e.type==="string")return typeof t=="string";if(e.type==="integer")return typeof t=="number"&&Number.isInteger(t);if(e.type==="number")return typeof t=="number"&&Number.isFinite(t);if(e.type==="boolean")return typeof t=="boolean";if(e.type==="array")return Array.isArray(t)&&t.every(i=>Zn(i,e.items??{}));if(!fo(t))return!1;if(!e.properties)return!0;let n=t;return!Object.keys(n).every(i=>Object.hasOwn(e.properties,i))||!(e.required??[]).every(i=>Object.hasOwn(n,i))?!1:Object.entries(n).every(([i,o])=>Zn(o,e.properties[i]))}function fo(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function ei(t,e,n={}){if(ho(t)){let i=ke[t],o={problem_version:1,code:t,category:i.category,recovery:i.recovery,message:e,...n.details===void 0?{}:{details:n.details},...n.operation_outcome===void 0?{}:{operation_outcome:n.operation_outcome},...n.trace_id===void 0?{}:{trace_id:n.trace_id}};if(gt(o))return o}return{problem_version:1,code:"unknown",server_code:t,category:"unknown",recovery:"none",message:e,...n.details===void 0?{}:{details:n.details},...n.operation_outcome===void 0?{}:{operation_outcome:n.operation_outcome},...n.trace_id===void 0?{}:{trace_id:n.trace_id}}}var _=class extends Error{problem;code;status;constructor(e,n={}){super(e.message,n.cause===void 0?void 0:{cause:n.cause}),this.problem=e,this.name="MdbaseConnectError",this.code=e.code,this.status=n.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 w(t,e,...[n={}]){let i=ke[t];return{problem_version:1,code:t,category:i.category,recovery:i.recovery,message:e,...n.details===void 0?{}:{details:n.details},...n.operationOutcome===void 0?{}:{operation_outcome:n.operationOutcome},...n.traceId===void 0?{}:{trace_id:n.traceId}}}function d(t,e,...n){let i=n[0];return new _(w(t,e,...n),{status:i?.status,cause:i?.cause})}var mo=new Uint8Array([77,68,66,70]),yo=1,go=0,Nl=new Uint8Array([77,68,66,82]);var bo=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function _o(t,e={}){return{actions:[...new Set([...t.required,...e.includeOptional===!1?[]:t.optional??[]])],scope:structuredClone(t.scope)}}var x=class extends Error{code;constructor(e,n){super(n),this.code=e,this.name="FileFrameError"}};function ua(t){return t==="upload_chunk"?1:2}function pa(t){if(t===1)return"upload_chunk";if(t===2)return"download_chunk";throw new x("invalid_kind",`Unknown file frame kind ${t}`)}function ha(t){if(!t||typeof t!="object"||Array.isArray(t))throw new x("invalid_header","File frame header must be a JSON object");return t}function Kt(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new x("invalid_header",`File frame header ${e} must be a non-empty string`);return n}function Qt(t,e){let n=Kt(t,e);if(!bo.test(n))throw new x("invalid_header",`File frame header ${e} must be a UUID`);return n}function xe(t,e,n=Number.MAX_SAFE_INTEGER){let i=t[e];if(!Number.isSafeInteger(i)||i<0||i>n)throw new x("invalid_header",`File frame header ${e} is outside its allowed range`);return i}function ti(t){if(t.protocol_version!==1)throw new x("unsupported_version",`Unsupported file transfer protocol ${t.protocol_version}`);if(t.protection!=="grant_aead_v1"&&t.protection!=="transport_tls")throw new x("invalid_header","Unknown file transfer protection");if(t.direction!=="upload"&&t.direction!=="download")throw new x("invalid_header","Unknown file transfer direction");for(let[e,n]of[["grant_id",t.grant_id],["authority_id",t.authority_id],["collection_id",t.collection_id],["transfer_id",t.transfer_id]])if(!bo.test(n))throw new x("invalid_header",`File frame header ${e} must be a UUID`);for(let[e,n,i]of[["chunk_size",t.chunk_size,4194304],["chunk_index",t.chunk_index,Number.MAX_SAFE_INTEGER],["offset",t.offset,Number.MAX_SAFE_INTEGER],["plaintext_length",t.plaintext_length,4194304],["total_size",t.total_size,Number.MAX_SAFE_INTEGER]])if(!Number.isSafeInteger(n)||n<0||n>i)throw new x("invalid_header",`File frame header ${e} is outside its allowed range`);if(t.chunk_size<64*1024)throw new x("invalid_header","File frame chunk_size is below the protocol minimum");if(!Number.isSafeInteger(t.scope_epoch)||t.scope_epoch<1)throw new x("invalid_header","File frame header scope_epoch must be a positive integer");if(t.protection==="grant_aead_v1"&&!t.key_id)throw new x("invalid_header","AEAD-protected file frames require key_id");return{protocol_version:1,protection:t.protection,grant_id:t.grant_id,authority_id:t.authority_id,collection_id:t.collection_id,transfer_id:t.transfer_id,direction:t.direction,chunk_size:t.chunk_size,chunk_index:t.chunk_index,offset:t.offset,plaintext_length:t.plaintext_length,total_size:t.total_size,scope_epoch:t.scope_epoch,...t.key_id===void 0?{}:{key_id:t.key_id}}}function fa(t){let e;try{e=new TextDecoder("utf-8",{fatal:!0}).decode(t)}catch{throw new x("invalid_header","File frame header is not valid UTF-8")}let n;try{n=ha(JSON.parse(e))}catch(l){throw l instanceof x?l:new x("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(n).some(l=>!i.has(l)))throw new x("invalid_header","File frame header contains an unknown field");let o=xe(n,"protocol_version");if(o!==1)throw new x("unsupported_version",`Unsupported file transfer protocol ${o}`);let r=Kt(n,"protection"),s=Kt(n,"direction"),a=n.key_id===void 0?void 0:Kt(n,"key_id"),c=ti({protocol_version:1,protection:r,grant_id:Qt(n,"grant_id"),authority_id:Qt(n,"authority_id"),collection_id:Qt(n,"collection_id"),transfer_id:Qt(n,"transfer_id"),direction:s,chunk_size:xe(n,"chunk_size",4194304),chunk_index:xe(n,"chunk_index"),offset:xe(n,"offset"),plaintext_length:xe(n,"plaintext_length",4194304),total_size:xe(n,"total_size"),scope_epoch:xe(n,"scope_epoch"),...a===void 0?{}:{key_id:a}});if(JSON.stringify(c)!==e)throw new x("invalid_header","File frame header must use the canonical field order without duplicate fields or whitespace");return c}function ni(t,e,n){let i=t==="upload_chunk"?"upload":"download";if(e.direction!==i)throw new x("invalid_header",`Frame kind ${t} requires direction ${i}`);let o=e.chunk_index*e.chunk_size;if(!Number.isSafeInteger(o)||e.offset!==o)throw new x("invalid_header","Chunk offset does not match its index and protocol chunk size");if(e.offset+e.plaintext_length>e.total_size)throw new x("invalid_header","Chunk extends past the declared transfer size");let r=e.protection==="grant_aead_v1"?e.plaintext_length+16:e.plaintext_length;if(n!==r)throw new x("invalid_length","Payload length does not match the protected plaintext length")}function ma(t){return t.plaintext_length+(t.protection==="grant_aead_v1"?16:0)}function Vt(t,e){let n=ti(e),i=ma(n);ni(t,n,i);let o=new TextEncoder().encode(JSON.stringify(n));if(o.byteLength>16384)throw new x("limit_exceeded","File frame header exceeds the protocol limit");let r=new Uint8Array(16+o.byteLength);r.set(mo,0);let s=new DataView(r.buffer,r.byteOffset,r.byteLength);return s.setUint8(4,yo),s.setUint8(5,ua(t)),s.setUint16(6,go,!1),s.setUint32(8,o.byteLength,!1),s.setUint32(12,i,!1),r.set(o,16),r}function vo(t){let e=ti(t.header);if(ni(t.kind,e,t.payload.byteLength),t.payload.byteLength>4194320)throw new x("limit_exceeded","File frame payload exceeds the protocol limit");let n=Vt(t.kind,e),i=new Uint8Array(n.byteLength+t.payload.byteLength);return i.set(n,0),i.set(t.payload,n.byteLength),i}function Gt(t,e={}){if(t.byteLength<16)throw new x("invalid_length","File frame is shorter than its fixed prefix");if(!mo.every((p,f)=>t[f]===p))throw new x("invalid_magic","File frame magic is not MDBF");let n=new DataView(t.buffer,t.byteOffset,t.byteLength),i=n.getUint8(4);if(i!==yo)throw new x("unsupported_version",`Unsupported file frame version ${i}`);let o=pa(n.getUint8(5));if(n.getUint16(6,!1)!==go)throw new x("unsupported_flags","File frame uses unsupported flags");let r=n.getUint32(8,!1),s=n.getUint32(12,!1),a=e.maxHeaderBytes??16384,c=e.maxPayloadBytes??4194320;if(r===0)throw new x("invalid_length","File frame header must not be empty");if(r>a||s>c)throw new x("limit_exceeded","File frame exceeds the configured decode limits");let l=16+r+s;if(!Number.isSafeInteger(l)||l!==t.byteLength)throw new x("invalid_length","File frame lengths do not match the supplied bytes");let u=16+r,h=fa(t.subarray(16,u));return ni(o,h,s),{kind:o,header:h,payload:t.slice(u)}}var be=["describe","changes","read","query"];function Q(t){let e=t.capabilities===void 0?1:t.capabilities?.contract_version;return e!==1&&e!==2&&Qe("Unsupported declared capability contract version."),e}function Qe(t){throw d("invalid_application_manifest",t,{details:{issues:[{path:"/requirements/capabilities",keyword:"authorizationSelection",message:t,params:{}}]}})}function Z(t,e){if(e.operations!==void 0&&e.capabilities!==void 0&&Qe("Specify operations or capabilities, not both."),e.operations!==void 0&&Q(t)!==1&&Qe("Exact operations authorization is only supported for legacy v1 declarations."),e.capabilities!==void 0){let n=new Set([...t.capabilities?.required??[],...t.capabilities?.optional??[]]);e.capabilities.some(i=>!n.has(i)||X(Q(t),i)===void 0)&&Qe("Authorization can only include capabilities declared by the application.")}}function ii(t){let e=t.capabilities;return e?[...new Set([...e.required,...e.optional??[]].flatMap(n=>X(e.contract_version,n)??[]))]:[...be]}function Ht(t,e){let{requirements:n}=t;if(Z(n,e),Q(n)===1){if(e.operations!==void 0)return[...new Set(e.operations)];if(e.capabilities===void 0)return[...be]}let i=n.capabilities,r=[...i?.required??[],...e.capabilities??i?.optional??[]].flatMap(a=>X(Q(n),a)??[]),s=(t.provisions?.type_packs.length??0)>0||(t.provisions?.configuration?.length??0)>0;return[...new Set([...r,...Q(n)===2&&s?Bt:[]])]}function bt(t,e){return[...t.capabilities?.required??[],...t.capabilities?.optional??[]].filter(n=>(X(Q(t),n)??[]).every(i=>e.includes(i)))}function $t(t){let e=t.files;if(e)return Q(t)===1?((!("actions"in e)||"required"in e||"optional"in e)&&Qe("Legacy file declarations must use exact files.actions."),{actions:[...e.actions],scope:structuredClone(e.scope)}):("actions"in e&&Qe("V2 file declarations must use required/optional file actions."),_o(e))}var ya=["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","assess_collection_setup","apply_collection_setup","list_timers","put_timer","cancel_timer","reconcile_timers","sync"],ga=["list_files","stat_file","open_file_upload","open_file_download","move_file","delete_file","get_file_transfer_status","commit_file_upload","abort_file_transfer"],ba={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",assess_collection_setup:"never",apply_collection_setup:"always",list_timers:"never",put_timer:"always",cancel_timer:"always",reconcile_timers:"always",sync:"sync_action"},_a={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,assess_collection_setup:1,apply_collection_setup:1,list_timers:1,put_timer:1,cancel_timer:1,reconcile_timers:1,sync:1},va={list_files:1,stat_file: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},Ca=new Set(["open_file_upload","move_file","delete_file","commit_file_upload","abort_file_transfer"]),wa=new Set(["delete","rename"]);var Ra=new Set(ya),Oa=new Set(ga);function Co(t){return Ra.has(t)}function Sa(t){return Oa.has(t)}function wo(t,e){if(t==="file_control"){let n=Ro(e)&&typeof e.type=="string"?e.type:"";if(!Sa(n))throw new Error(`Unknown file-control message: ${n}`);return va[n]}return _a[t]}function _e(t,e){let n=Ro(e)?e:{};if(n.dry_run===!0&&wa.has(t))return null;if(t==="file_control"){let o=typeof n.type=="string"?n.type:"";return Ca.has(o)?`file_control:${o}`:null}let i=ba[t];return i==="always"?t:i==="sync_action"&&n.action==="mutate"?"sync:mutate":null}function ee(t,e){return _e(t,e)!==null}function Ro(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var oi={"mdbase.record.created":"record.created","mdbase.record.modified":"record.updated","mdbase.record.deleted":"record.deleted","mdbase.record.renamed":"record.renamed","mdbase.type.changed":"schema.changed","mdbase.config.changed":"config.changed","mdbase.contract.changed":"contract.changed","mdbase.view.changed":"view.changed","mdbase.view_source.changed":"view.changed","mdbase.resource.changed":"file.changed","mdbase.file.put":"file.put","mdbase.file.remove":"file.removed",file_put:"file.put",file_remove:"file.removed","mdbase.collection.invalidated":"gap"};var Pa=1,Aa="mdbase-connect mutation fingerprint v1\0",ri=new TextEncoder;function Ta(t){return si(t,new Set)}function Ma(t,e){let n=_e(t,e);if(n===null)throw new TypeError("The operation is not a canonical mutation.");let i=ri.encode(n),o=ri.encode(Ta(e)),r=ri.encode(Aa),s=new Uint8Array(r.length+4+8+i.length+4+8+o.length),a=new DataView(s.buffer),c=0;return s.set(r,c),c+=r.length,a.setUint32(c,Pa,!1),c+=4,c=So(s,a,c,i),a.setUint32(c,wo(t,e),!1),c+=4,So(s,a,c,o),s}async function Po(t,e){let n=new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",Ma(t,e).buffer));return Ia(n)}function si(t,e){if(t===null)return"null";if(t===!0)return"true";if(t===!1)return"false";if(typeof t=="string")return Oo(t),JSON.stringify(t);if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError("Mutation input numbers must be finite.");return JSON.stringify(t)}if(typeof t!="object")throw new TypeError(`Mutation input contains unsupported ${typeof t}.`);if(e.has(t))throw new TypeError("Mutation input must not contain cycles.");e.add(t);try{if(Array.isArray(t)){if(Object.getOwnPropertySymbols(t).length>0)throw new TypeError("Mutation input must not contain symbol properties.");let o=[];for(let r=0;r<t.length;r+=1){if(!Object.hasOwn(t,r))throw new TypeError("Mutation input arrays must not be sparse.");o.push(si(t[r],e))}return`[${o.join(",")}]`}let n=Object.getPrototypeOf(t);if(n!==Object.prototype&&n!==null)throw new TypeError("Mutation input objects must be plain JSON objects.");if(Object.getOwnPropertySymbols(t).length>0)throw new TypeError("Mutation input must not contain symbol properties.");let i=Object.entries(t);for(let[o]of i)Oo(o);return i.sort(([o],[r])=>o<r?-1:o>r?1:0),`{${i.map(([o,r])=>{let s=Object.getOwnPropertyDescriptor(t,o);if(!s||s.get||s.set)throw new TypeError("Mutation input must not contain accessor properties.");return`${JSON.stringify(o)}:${si(r,e)}`}).join(",")}}`}finally{e.delete(t)}}function Oo(t){for(let e=0;e<t.length;e+=1){let n=t.charCodeAt(e);if(n>=55296&&n<=56319){let i=t.charCodeAt(e+1);if(!(i>=56320&&i<=57343))throw new TypeError("Mutation input strings must not contain lone surrogates.");e+=1}else if(n>=56320&&n<=57343)throw new TypeError("Mutation input strings must not contain lone surrogates.")}}function So(t,e,n,i){return e.setBigUint64(n,BigInt(i.length),!1),n+=8,t.set(i,n),n+i.length}function Ia(t){return btoa(String.fromCharCode(...t)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}var Y=3,xa=2,Ao=[Y,xa],ce=5,ai=4,To=[ce,ai],Ea=2,qa=1,Yl={operation_transport:[...Ao],authorization_binding:[...To],semantic_capabilities:[Ea,1],durable_mutation:[qa]};function ci(t,e,n=[],i=2){let o={operation_transport:Y,authorization_binding:ce,semantic_capabilities:i},r=[...new Set(n)].filter(s=>s!==Y).sort((s,a)=>a-s);return r.length>0&&(o.operation_transport_recovery=r),(t.some(s=>ee(s,{action:"mutate"}))||e?.actions.some(s=>s!=="list"&&s!=="read")===!0)&&(o.durable_mutation=1),o}function _t(t){return Ao.includes(t)}function Mo(t){return To.includes(t)}var Fa=new TextEncoder().encode("mdbase-connect application installation id v2\0"),za=new TextEncoder().encode("mdbase-connect application authorization proof v4\0"),Da=new TextEncoder().encode("mdbase-connect application authorization proof v5\0");async function ko(t){let e=Wt(t),i=new Uint8Array(await crypto.subtle.digest("SHA-256",Ee([Fa,K(e)]))).slice(0,16);return i[6]=i[6]&15|128,i[8]=i[8]&63|128,[vt(i.slice(0,4)),vt(i.slice(4,6)),vt(i.slice(6,8)),vt(i.slice(8,10)),vt(i.slice(10,16))].join("-")}function xo(t){let e=[Wt(t.installation_signing_public_key),Wt(t.grant_agreement_public_key),Wt(t.grant_signing_public_key)];if(e.some((c,l)=>e.slice(l+1).some(u=>Qa(c,u))))throw new Error("Application authorization keys must be distinct.");let n=li(t.authorization_nonce),i=li(t.code_challenge),o=t.contracts,r=o.operation_transport_recovery??[],s=t.requested_operations.some(c=>ee(c,{action:"mutate"}))||t.requested_files?.actions.some(c=>!["list","read"].includes(c))===!0;if(!Mo(t.protocol_version)||n.byteLength!==32||!/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)+$/u.test(t.application_declaration_id)||!/^[0-9a-f]{64}$/u.test(t.application_manifest_digest)||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/u.test(t.issued_at)||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/u.test(t.expires_at)||i.byteLength!==32||![o.operation_transport,o.authorization_binding,o.semantic_capabilities,o.durable_mutation??1].every(c=>Number.isInteger(c)&&c>0)||o.authorization_binding!==t.protocol_version||!_t(o.operation_transport)||t.protocol_version===ce&&o.operation_transport!==Y||r.some(c=>!_t(c)||c===o.operation_transport)||new Set(r).size!==r.length||t.protocol_version===ai&&r.length>0||r.length>0&&!s||(s?o.durable_mutation!==1:o.durable_mutation!==void 0)||t.requested_operations.length===0&&t.requested_files===void 0||new Set(t.requested_operations).size!==t.requested_operations.length||t.requested_operations.some(c=>!c||c.includes("\0"))||(t.flow==="authorization_code"?t.redirect_uri===void 0||t.state===void 0:t.flow!=="device_code"||t.redirect_uri!==void 0||t.state!==void 0))throw new Error("Application authorization binding is invalid.");Ua(t.requested_files);let a=t.requested_operations.map(c=>K(new TextEncoder().encode(c)));return Ee([t.protocol_version===ce?Da:za,oe(t.protocol_version),K(Jt(t.application_id)),K(Jt(t.authorization_id)),K(new TextEncoder().encode(t.application_declaration_id)),K(Eo(t.application_manifest_digest)),K(Jt(t.application_installation_id)),...e.map(K),K(new TextEncoder().encode(t.flow)),K(n),K(new TextEncoder().encode(t.issued_at)),K(new TextEncoder().encode(t.expires_at)),Io(t.redirect_uri),Io(t.state),K(new TextEncoder().encode(t.code_challenge)),oe(o.operation_transport),...t.protocol_version===ce?[oe(r.length),...r.map(oe)]:[],oe(o.authorization_binding),oe(o.semantic_capabilities),La(o.durable_mutation),oe(a.length),...a,Na(t.requested_files),ja(t.collection_id)])}function La(t){return t===void 0?new Uint8Array(1):Ee([new Uint8Array([1]),oe(t)])}function Ua(t){if(t!==void 0&&(t.actions.length===0||new Set(t.actions).size!==t.actions.length||t.scope.kind==="selected_folders"&&(t.scope.folders.length===0||new Set(t.scope.folders).size!==t.scope.folders.length||t.scope.folders.some(e=>!e||e.includes("\0")))))throw new Error("Application authorization file request is invalid.")}function Na(t){if(t===void 0)return new Uint8Array(1);let e=t.actions.map(n=>K(new TextEncoder().encode(n)));return Ee([new Uint8Array([1]),oe(e.length),...e,K(new TextEncoder().encode(t.scope.kind)),...t.scope.kind==="selected_folders"?[oe(t.scope.folders.length),...t.scope.folders.map(n=>K(new TextEncoder().encode(n)))]:[]])}function Io(t){return t===void 0?new Uint8Array(1):Ee([new Uint8Array([1]),K(new TextEncoder().encode(t))])}function ja(t){return t===void 0?new Uint8Array(1):Ee([new Uint8Array([1]),K(Jt(t))])}function Wt(t){let e=li(t);if(e.byteLength!==65||e[0]!==4)throw new Error("Application authorization public key is invalid.");return e}function li(t){if(!/^[A-Za-z0-9_-]+$/u.test(t))throw new Error("Invalid base64url value.");let e=t.replaceAll("-","+").replaceAll("_","/"),n=e.padEnd(Math.ceil(e.length/4)*4,"="),i=Uint8Array.from(atob(n),o=>o.charCodeAt(0));if(Ba(i)!==t)throw new Error("Non-canonical base64url value.");return i}function Jt(t){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu.test(t))throw new Error("Invalid UUID value.");let e=t.replaceAll("-","");return Eo(e)}function Eo(t){if(!/^[0-9a-f]+$/u.test(t)||t.length%2!==0)throw new Error("Invalid hexadecimal value.");return Uint8Array.from({length:t.length/2},(e,n)=>Number.parseInt(t.slice(n*2,n*2+2),16))}function K(t){return Ee([oe(t.byteLength),t])}function oe(t){let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t,!1),e}function Ee(t){let e=new Uint8Array(t.reduce((i,o)=>i+o.byteLength,0)),n=0;for(let i of t)e.set(i,n),n+=i.byteLength;return e}function Ba(t){return btoa(String.fromCharCode(...t)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}function Qa(t,e){return t.byteLength===e.byteLength&&t.every((n,i)=>n===e[i])}function vt(t){return[...t].map(e=>e.toString(16).padStart(2,"0")).join("")}var qo={id:"mdbase.record.created",version:"1.0.0",digest:"sha256:7f3bed6baa356ee9389e977ae7b77a102e2bee871a7c1d9f2026fc21cacdbfc9"};var Fo={id:"mdbase.runtime.timer.fired",version:"1.0.0",digest:"sha256:41105be7a7abf33b31ced47e1e1965242236e40ccaea286b959b0a8c591f5642"};var zo=28485,Ct="P256-HKDF-SHA256-AES256GCM",Yt=1;var Ka="contract-setup-v1",Va="file-relay-v1",Ga="protocol-usage-report-v1",Ha="policy-freshness-lease-v1";var $a=["application-authorization-v4","authorization-activation","encrypted-relay","policy-ack"];var Wa=["durable-mutation-journal-v1","durable-file-lifecycle-v1","contract-metadata-read-v1"],Ja="candidate-b-activation-v1",rd=[...Xn,...Wa,"mutation-replay-after-credential-retirement-v1",Ja],Ya="application-declaration-evidence-v1",sd=[...Xn,Ya,...$a,Ha,"application-authorization-v5",Ka,Va,Ga,po],di=1;var Do="mdbase-authority-request-proof-v1",wt={version:"x-mdbase-proof-version",timestamp:"x-mdbase-proof-timestamp",nonce:"x-mdbase-proof-nonce",signature:"x-mdbase-proof-signature"};function Lo(t,e,n={}){return ei(t,e,{details:n.details,operation_outcome:n.operationOutcome,trace_id:n.traceId})}function L(t,e,n={}){let{status:i,cause:o,...r}=n;return new _(ei(t,e,{details:r.details,operation_outcome:r.operationOutcome,trace_id:r.traceId}),{status:i,cause:o})}function Ke(t){let e=Xa(t.diagnostics),n=tc(t.diagnostics);if(e==="concurrent_modification"||e==="file_not_found"||e==="invalid_path")return w(e,n,{operationOutcome:"rejected"});if(e==="collection_version_unsupported"){let i=Za(t.diagnostics);return w(e,n,{operationOutcome:"rejected",details:i})}return e!=="operation_invalid"?w(e,n,{operationOutcome:"rejected",details:{diagnostics:t.diagnostics}}):w(e,n,{operationOutcome:"rejected",details:{diagnostics:t.diagnostics,partial_result:t.result}})}function Xa(t){let e=new Set(t.filter(n=>n.severity==="error").map(n=>n.code));if(["migration_required","migration_lossy","unsupported_version"].some(n=>e.has(n)))return"collection_version_unsupported";if(["invalid_config","invalid_configuration","missing_config","missing_spec_version"].some(n=>e.has(n)))return"collection_configuration_invalid";if(["duplicate_type","invalid_contract_definition","invalid_data_contract","invalid_type_definition","invalid_type_path"].some(n=>e.has(n)))return"collection_type_registry_invalid";if(["collection_invalid","collection_open_failed"].some(n=>e.has(n)))return"collection_invalid";for(let n of["concurrent_modification","file_not_found","invalid_path"])if(e.has(n))return n;return"operation_invalid"}function Za(t){let e=t.map(n=>n.details).find(n=>ec(n));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 ec(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Uo(t){return t instanceof _&&t.retryable}function tc(t){return t.filter(e=>e.severity==="error").map(e=>e.message).join(" ")||t.map(e=>e.message).join(" ")||"The collection rejected this operation."}var Xt=["application_authorization_issuance_disabled","application_reauthorization_required","application_semantic_version_mismatch","invalid_replica","notification_grant_reauthorization_required","origin_denied","replica_scope_denied","scope_changed","scope_denied","scope_epoch_stale","timer_grant_unavailable","access_denied","access_paused","application_declaration_mismatch","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"],Ve=Object.keys(ke),qe=["discovery_failed","invalid_operation_response","invalid_application_manifest","invalid_request","manifest_load_failed","rate_limited","temporarily_unavailable","timeout"],ve=[...qe,"application_authorization_issuance_disabled","application_reauthorization_required","application_semantic_version_mismatch","invalid_replica","origin_denied","access_denied","application_declaration_mismatch","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","legacy_scope_reauthorization_required","scope_denied","reconnect_required","token_exchange_failed","transport_protocol_incompatible"],Rt=[...qe,"notification_grant_reauthorization_required","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"],ui=["connector_offline","connector_upgrade_required","invalid_operation_response","not_authorized","operation_failed","temporarily_unavailable","timeout"],Ad=[...ve,"collection_not_ready","collection_not_selected","operation_cancelled","session_destroyed","session_not_started","session_starting","unknown_collection"],nc=["collection_configuration_invalid","collection_invalid","collection_type_registry_invalid","collection_version_unsupported"],Ot=[...Xt,...nc],le=[...Ot,"file_not_found","invalid_path","operation_invalid"],de=[...le,"cursor_capacity_exhausted","generation_expired","invalid_read_cursor","query_snapshot_changed","sandbox_unsupported"],H=[...le,"concurrent_modification","invalid_preflight","pending_mutation_unresolved"],Zt=[...Ot,"change_cursor_reset"],Ce=[...H,"type_pack_provision_failed"];function O(t,e=[]){return{ok:!0,value:t,diagnostics:e}}function b(t){return{ok:!1,problem:t}}async function I(t,e){try{return O(await t())}catch(n){if(!(n instanceof _))throw n;let i=n.problem;return i.code==="unknown"||e.includes(i.code)?b(i):b(Lo(i.code,i.message,{details:i.details,operationOutcome:i.operation_outcome,traceId:i.trace_id}))}}var Ge=class{constructor(e,n,i={},o){this.client=e;this.query=n;this.options=i;this.supports=o;for(let[r,s]of[["pageSize",i.pageSize],["firstPageSize",i.firstPageSize],["maxPendingPaths",i.maxPendingPaths]])if(s!==void 0&&(!Number.isSafeInteger(s)||s<1))throw new TypeError(`${r} must be a positive integer.`);if(i.coalesceMs!==void 0&&(!Number.isFinite(i.coalesceMs)||i.coalesceMs<0))throw new TypeError("coalesceMs must be nonnegative.");if(n.output!==void 0||n.cursor||n.snapshot||n.groupBy||n.summaries||n.summaryFunctions)throw new TypeError("observe requires a record query, not a continuation or aggregate.");if(this.query=structuredClone(n),i.signal?.aborted)this.close();else if(i.signal){let r=()=>this.close();i.signal.addEventListener("abort",r,{once:!0}),this.removeAbort=()=>i.signal?.removeEventListener("abort",r)}this.refresh()}client;query;options;supports;records=new Map;overlays=new Map;pending=new Set;listeners=new Set;changes=new Set;lifetime=new AbortController;request=new AbortController;timer;draining=!1;removeAbort;snapshot=Object.freeze({records:Object.freeze([]),state:"loading",generation:0,problem:null,watchStatus:null});settleReady;ready=new Promise(e=>{this.settleReady=e});getSnapshot=()=>this.snapshot;subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});subscribeChanges(e){return this.changes.add(e),()=>{this.changes.delete(e)}}hydrate(){return this.query.includeBody=!0,this.load(!0)}refresh(){return this.load()}async load(e=!1){if(this.lifetime.signal.aborted)return Fe();this.request.abort(),this.request=new AbortController;let n=this.request.signal,i=this.snapshot.generation+1;this.pending.clear(),clearTimeout(this.timer),this.timer=void 0,this.publish("status",{state:"loading",generation:i,problem:null,watchStatus:null});let o=()=>!n.aborted&&!this.lifetime.signal.aborted;try{let r=this.options.mode==="manual"?null:St(await this.client.changes({},{signal:n})),s=new Map([...this.overlays].filter(([,h])=>h.committed)),a=new Map,c=!0,l={signal:n,firstPageSize:this.options.firstPageSize,pageSize:this.options.pageSize},u=this.client.queryPages(this.query,l)[Symbol.asyncIterator]();try{for(let h=u.next(),p=await h;!p.done;p=await h){let f=p.value;if(h=u.next(),h.catch(()=>{}),!f.ok)throw new _(f.problem);let m=f.value;if(m.page===0&&(c=!m.meta?.hasMore||!!(m.cursor||m.snapshot)),!o())return Fe();let P=we(m.results);for(let y of P)a.set(y.path,y);let v=m.page===0&&!e?this.snapshot.records.filter(y=>!a.has(y.path)&&!this.overlays.get(y.path)?.record).map(y=>y.path):[];if(m.page===0&&!e&&(this.records=a),e)for(let y of P)this.records.set(y.path,y);this.publish("page",{total:m.meta?.totalCount},{upserts:P.filter(y=>!this.overlays.has(y.path)),removed:v})}}finally{await u.return?.()}if(!o())return Fe();this.records=a;for(let[h,p]of s)this.overlays.get(h)===p&&this.overlays.delete(h);return this.settleReady(O(void 0)),this.publish("reload",{state:"ready",total:a.size,problem:null}),r&&(this.follow(r.cursor,n,c),this.schedule()),O(void 0)}catch(r){return o()?this.fail(r):Fe()}}optimistic(e=[],n=[]){if(this.lifetime.signal.aborted)throw new Error("Observer is closed.");let i={},o=[...new Set([...e.map(r=>r.path),...n])];for(let r of e)this.overlays.set(r.path,{token:i,record:we(r),committed:!1});for(let r of n)this.overlays.set(r,{token:i,record:null,committed:!1});return this.publish("local"),{commit:()=>{for(let r of o){let s=this.overlays.get(r);s?.token===i&&(s.committed=!0,this.options.mode!=="manual"&&!this.request.signal.aborted&&this.pending.add(r))}this.schedule()},rollback:()=>this.retire(o,i)}}close(){this.lifetime.signal.aborted||(this.lifetime.abort(),this.request.abort(),clearTimeout(this.timer),this.timer=void 0,this.pending.clear(),this.records=new Map(this.snapshot.records.map(e=>[e.path,e])),this.overlays.clear(),this.removeAbort?.(),this.publish("status",{state:"closed"}),this.settleReady(Fe()),this.listeners.clear(),this.changes.clear())}fullReloadRequired(){return this.options.invalidation==="collection"||!!(this.query.contract||this.query.orderBy||this.query.offset!==void 0||this.query.select||this.query.projections||this.options.invalidation!=="paths"&&(this.query.where||this.query.context))}async follow(e,n,i){if(this.snapshot.generation===1&&await this.ready,!n.aborted)try{for await(let o of this.client.watch({...this.options.watch,cursor:e,signal:n,onStatus:r=>{n.aborted||this.publish("status",{watchStatus:we(r)})}})){if(n.aborted)return;if(!o.ok){if(o.problem.code==="change_cursor_reset"){this.refresh();return}this.fail(new _(o.problem));return}let r=we(o.value);for(let a of this.changes)a(r);if(["reset","gap","unknown","schema.changed","config.changed","contract.changed","view.changed"].includes(r.kind)){this.refresh();return}let s=rc(r);if(this.fullReloadRequired()||!i&&(r.kind==="record.created"||r.kind==="record.deleted"||r.kind==="record.renamed")){this.refresh();return}if(s.length){for(let a of s)this.pending.add(a);this.schedule()}}}catch(o){n.aborted||this.fail(o)}}schedule(){let e=this.request.signal;if(!(e.aborted||this.options.mode==="manual"||!this.pending.size)){if(this.pending.size>(this.options.maxPendingPaths??1e3)){this.refresh();return}if(this.snapshot.state==="ready"){if(this.fullReloadRequired()){this.refresh();return}!this.timer&&!this.draining&&(this.timer=setTimeout(()=>{this.timer=void 0,this.drain(e)},this.options.coalesceMs??50))}}}async drain(e){if(!this.draining){this.draining=!0;try{for(;!e.aborted&&this.pending.size;){let n=[...this.pending];if(this.pending.clear(),!(await this.reread(n,e)).ok)return}}finally{this.draining=!1,this.schedule()}}}async reread(e,n){let i=new Map([...this.overlays].filter(([o,r])=>e.includes(o)&&r.committed));try{let o=`file.path in ${JSON.stringify(e)}`,r={...this.query,where:this.query.where?`(${this.query.where}) && (${o})`:o,includeBody:this.query.includeBody},s=this.supports?St(await this.supports("query-metadata-v1",{signal:n})):!1,a=s?St(await this.client.queryAll({...r,select:ic.map(f=>`file.${f}`),includeBody:!1,output:"metadata"},{signal:n})).results:St(await this.client.queryAll(r,{signal:n})).results,c=new Map(a.map(f=>[f.path,f])),l=this.query.frontmatterMode??"effective",u=new Map(e.flatMap(f=>{let m=i.get(f)?.record??this.records.get(f);return s&&m?.revision&&m.revision===c.get(f)?.revision&&(!this.query.includeBody||m.body!==void 0)&&(l==="effective"||m.frontmatter!==void 0)&&(l==="persisted"||m.effectiveFrontmatter!==void 0)?[[f,m]]:[]})),h=s?St(await this.client.readMany(e.filter(f=>c.has(f)&&!u.has(f)),{signal:n,includeBody:this.query.includeBody,frontmatterMode:this.query.frontmatterMode})):{results:a.map(f=>({status:"found",path:f.path,record:f})),errors:[]};if(n.aborted||this.lifetime.signal.aborted)return Fe();if(h.errors.length)throw new _(h.errors[0].failure.problem);let p=new Map([...u,...h.results.flatMap(f=>f.status==="found"?[[f.path,f.record]]:[])].map(([f,m])=>[f,we(oc(m,c.get(f)))]));for(let f of e)c.has(f)||this.records.delete(f);for(let f of h.results)f.status==="missing"&&this.records.delete(f.path);for(let[f,m]of p)this.records.set(f,m);for(let[f,m]of i)m?.committed&&this.overlays.get(f)===m&&this.overlays.delete(f);return this.publish("changes",{state:"ready",problem:null}),O(void 0)}catch(o){return n.aborted||this.lifetime.signal.aborted?Fe():this.fail(o)}}retire(e,n){for(let i of e)this.overlays.get(i)?.token===n&&this.overlays.delete(i);this.lifetime.signal.aborted||this.publish("local")}fail(e){let n=e instanceof _?e.problem:w("operation_failed",e instanceof Error?e.message:"Query observation failed.");this.request.abort(),clearTimeout(this.timer),this.timer=void 0,this.pending.clear(),this.publish("status",{state:"error",problem:we(n),watchStatus:this.options.mode==="manual"?null:Object.freeze({state:"closed"})});let i=b(n);return this.settleReady(i),i}publish(e,n={},i){let o=this.overlays.size?new Map(this.records):this.records;for(let[l,u]of this.overlays)u.record?o.set(l,u.record):o.delete(l);let r=this.snapshot.records,s=e==="status"?r:Object.freeze([...o.values()]),a=new Map(i||s===r?[]:r.map(l=>[l.path,l])),c=Object.freeze({reason:e,upserts:Object.freeze(i?.upserts??(s===r?[]:s.filter(l=>a.get(l.path)!==l))),removed:Object.freeze(i?.removed??(s===r?[]:r.filter(l=>!o.has(l.path)).map(l=>l.path)))});this.snapshot=Object.freeze({...this.snapshot,...n,records:s,...(n.state??this.snapshot.state)==="ready"?{total:s.length}:{}});for(let l of this.listeners)l(this.snapshot,c)}},ic=["path","name","folder","size","mtime","ctime","tags","links","embeds"];function oc(t,e){let n="file"in e?e.file:e.values;if(!("file"in e))for(let i of["tags","links","embeds"]){let o=n[i];if(!Array.isArray(o)||i==="tags"&&o.some(r=>typeof r!="string"))throw d("invalid_operation_response","Invalid authority-derived file metadata.")}return{...t,file:"file"in e?{...n,...t.file}:{...t.file,...n}}}function St(t){if(!t.ok)throw new _(t.problem);return t.value}function Fe(){return b(w("operation_cancelled","Query observation was cancelled."))}function rc(t){return t.kind==="record.renamed"?[t.from,t.to]:t.kind==="record.created"||t.kind==="record.updated"||t.kind==="record.deleted"?[t.path]:[]}function we(t){if(!t||typeof t!="object")return t;if(Array.isArray(t))return Object.freeze(t.map(we));let e={...t};for(let n in e)Object.hasOwn(e,n)&&e[n]&&typeof e[n]=="object"&&(e[n]=we(e[n]));return Object.freeze(e)}var sc=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]),ac=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ze=class{state=ac.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 n=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,n+=i,this.blockLength===64&&(this.compress(this.block),this.blockLength=0)}for(;n+64<=e.byteLength;)this.compress(e,n),n+=64;return n<e.byteLength&&(this.block.set(e.subarray(n),0),this.blockLength=e.byteLength-n),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,n=Math.floor(e/4294967296),i=e>>>0;return No(this.block,56,n),No(this.block,60,i),this.compress(this.block),[...this.state].map(o=>o.toString(16).padStart(8,"0")).join("")}compress(e,n=0){let i=this.words;for(let p=0;p<16;p+=1){let f=n+p*4;i[p]=(e[f]<<24|e[f+1]<<16|e[f+2]<<8|e[f+3])>>>0}for(let p=16;p<64;p+=1){let f=i[p-15],m=i[p-2],P=ue(f,7)^ue(f,18)^f>>>3,v=ue(m,17)^ue(m,19)^m>>>10;i[p]=i[p-16]+P+i[p-7]+v>>>0}let o=this.state[0],r=this.state[1],s=this.state[2],a=this.state[3],c=this.state[4],l=this.state[5],u=this.state[6],h=this.state[7];for(let p=0;p<64;p+=1){let f=ue(c,6)^ue(c,11)^ue(c,25),m=c&l^~c&u,P=h+f+m+sc[p]+i[p]>>>0,v=ue(o,2)^ue(o,13)^ue(o,22),y=o&r^o&s^r&s,R=v+y>>>0;h=u,u=l,l=c,c=a+P>>>0,a=s,s=r,r=o,o=P+R>>>0}this.state[0]=this.state[0]+o>>>0,this.state[1]=this.state[1]+r>>>0,this.state[2]=this.state[2]+s>>>0,this.state[3]=this.state[3]+a>>>0,this.state[4]=this.state[4]+c>>>0,this.state[5]=this.state[5]+l>>>0,this.state[6]=this.state[6]+u>>>0,this.state[7]=this.state[7]+h>>>0}};function ue(t,e){return t>>>e|t<<32-e}function No(t,e,n){t[e]=n>>>24,t[e+1]=n>>>16,t[e+2]=n>>>8,t[e+3]=n}function re(t,e){return new Promise((n,i)=>{if(e?.aborted){i(e?.reason??new DOMException("Aborted","AbortError"));return}let o=()=>e?.removeEventListener("abort",s),r=setTimeout(()=>{o(),n()},t),s=()=>{clearTimeout(r),o(),i(e?.reason??new DOMException("Aborted","AbortError"))};e?.addEventListener("abort",s,{once:!0})})}var cc=6e4;function jo(t,e){let n=typeof document>"u"?void 0:document;return n?.visibilityState!=="hidden"?re(t,e):new Promise((i,o)=>{if(e?.aborted){o(e.reason??new DOMException("Aborted","AbortError"));return}let r=()=>{clearTimeout(c),n.removeEventListener("visibilitychange",s),e?.removeEventListener("abort",a)},s=()=>{n.visibilityState!=="hidden"&&(r(),i())},a=()=>{r(),o(e?.reason??new DOMException("Aborted","AbortError"))},c=setTimeout(()=>{r(),i()},Math.max(t,cc));n.addEventListener("visibilitychange",s),e?.addEventListener("abort",a,{once:!0})})}var en=8,pi=10;function tn(t){return t instanceof _&&t.code==="connector_busy"}async function Bo(t){if(!tn(t.error)||t.completedRetries>=en)return{retried:!1};try{await nn(t.completedRetries,t.signal)}catch(e){throw t.attempt.pendingMutation&&(t.knownRejectedMutationRetry||!t.attempt.resumingMutation)&&t.clearPending(t.attempt.requestId),e}return{retried:!0,result:await t.retry(t.attempt.pendingMutationRecord,t.knownRejectedMutationRetry||t.attempt.pendingMutation===!0&&!t.attempt.resumingMutation)}}async function He(t){if(t.status!==502&&t.status!==503)return!1;let e=await t.clone().json().catch(()=>null);return e?.error==="connector_busy"||typeof e?.error=="object"&&e.error?.code==="connector_busy"}function nn(t,e){return Ko(Vo(50,800,t),e)}function Qo(t,e){return Ko(Vo(100,1e3,t-1),e)}async function Ko(t,e){try{await re(t,e)}catch(n){throw e?.aborted?e.reason instanceof _?e.reason:d("operation_cancelled","The operation was cancelled while waiting for connector capacity.",{operationOutcome:"not_sent",cause:n}):n}}function Vo(t,e,n){let i=Math.min(e,t*2**Math.max(0,n));return Math.max(1,Math.round(i*(.75+Math.random()*.5)))}var Go=1024*1024,lc=4,Ho=8,hi=3;function fi(t,e){if(e!==void 0&&typeof e!="boolean"||t!==void 0&&(!Number.isInteger(t)||t<1||t>pi))throw d("invalid_request","Invalid upload options.");return t}var mi=64*1024*1024,$o=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,on=/^sha256:[0-9a-f]{64}$/u;async function Wo(t,e,n){let i=new ze;for(let o=0;o<t.size;o+=Go){te(e);let r=new Uint8Array(await t.slice(o,o+Go).arrayBuffer());i.update(r),n(Math.min(t.size,o+r.byteLength))}return t.size===0&&n(0),i.digestHex()}function Jo(t,e){if(t instanceof Blob)return e&&e!==t.type?t.slice(0,t.size,e):t;if(t instanceof ArrayBuffer)return new Blob([t],{type:e});let n=new Uint8Array(t.byteLength);return n.set(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),new Blob([n.buffer],{type:e})}function Yo(t){return t instanceof Blob?t.size:t.byteLength}async function Xo(t){return t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t}function yi(t=lc){if(!Number.isInteger(t)||t<1||t>Ho)throw d("invalid_request",`File concurrency must be between 1 and ${Ho}.`);return t}function Zo(t){if(!Number.isInteger(t)||t<1||t>1e3)throw d("invalid_request","File page size must be between 1 and 1000.");return t}function gi(t,e,n){if(t.protocol_version!==1||t.type!=="file_transfer"||t.transfer_id!==e||t.direction!==n||!Number.isSafeInteger(t.total_size)||t.total_size<0||!Array.isArray(t.received)||!dc(t))throw d("invalid_operation_response","The authority returned an invalid file transfer session.");let i=t.strategy.kind==="framed_chunks"?t.strategy.chunk_size:t.strategy.kind==="object_put"?Math.max(1,t.total_size):t.strategy.part_size,o=t.strategy.kind==="object_put"?1:Math.ceil(t.total_size/i);if(new Set(t.received).size!==t.received.length||t.received.some(s=>!Number.isSafeInteger(s)||s<0||s>=o))throw d("invalid_operation_response","The authority returned invalid transfer progress.");let r=t.uploaded_parts??[];if(!Array.isArray(r)||r.some((s,a)=>!Number.isSafeInteger(s?.part_number)||s.part_number<1||s.part_number>o||typeof s.etag!="string"||s.etag.length===0||s.etag.length>255||a>0&&r[a-1].part_number>=s.part_number)||(t.strategy.kind==="object_multipart"?r.length!==t.received.length||r.some((s,a)=>s.part_number-1!==t.received[a]):r.length!==0))throw d("invalid_operation_response","The authority returned invalid uploaded part receipts.")}function bi(t,e){let n=e.strategy.kind==="framed_chunks"?e.strategy.chunk_size:e.strategy.kind==="object_put"?Math.max(1,e.total_size):e.strategy.part_size,i=e.strategy.kind==="object_put"?1:Math.ceil(e.total_size/n);if(t?.protocol_version!==1||t.type!=="file_transfer_status"||t.transfer_id!==e.transfer_id||!["open","committed","aborted","expired"].includes(t.state)||!Array.isArray(t.received)||new Set(t.received).size!==t.received.length||t.received.some(r=>!Number.isSafeInteger(r)||r<0||r>=i)||!Number.isSafeInteger(t.received_bytes)||t.received_bytes<0||t.received_bytes>e.total_size||t.received.reduce((r,s)=>r+_i(e.total_size,n,s),0)!==t.received_bytes)throw d("invalid_operation_response","The authority returned invalid transfer status.");let o=t.uploaded_parts;if(!Array.isArray(o)||o.some((r,s)=>!Number.isSafeInteger(r?.part_number)||r.part_number<1||r.part_number>i||typeof r.etag!="string"||r.etag.length===0||r.etag.length>255||s>0&&o[s-1].part_number>=r.part_number)||(e.strategy.kind==="object_multipart"?o.length!==t.received.length||o.some((r,s)=>r.part_number-1!==t.received[s]):o.length!==0))throw d("invalid_operation_response","The authority returned invalid uploaded part status.")}function dc(t){return t.strategy.kind==="framed_chunks"?t.protection==="grant_aead_v1"&&Number.isSafeInteger(t.strategy.chunk_size)&&t.strategy.chunk_size>0:t.protection!=="transport_tls"?!1:t.strategy.kind==="object_put"?!0:Number.isSafeInteger(t.strategy.part_size)&&t.strategy.part_size>0}function _i(t,e,n){return Math.min(e,Math.max(0,t-n*e))}async function rn(t,e,n=pi){for(let i=1;i<=n;i+=1){te(e);try{return await t()}catch(o){if(e?.aborted||i===n||o instanceof _&&!o.retryable)throw o;await Qo(i,e)}}throw new Error("Unreachable file chunk retry state.")}function vi(t,e,n,i,o,r){let s;try{s=new URL(t.url)}catch{throw d("invalid_operation_response","The authority returned an invalid object URL.")}if(t.protocol_version!==1||t.type!=="file_part"||t.transfer_id!==e||t.part_index!==n||t.offset!==i||t.content_length!==o||typeof t.method!="string"||t.method.toUpperCase()!==r||!t.headers||typeof t.headers!="object"||Array.isArray(t.headers)||Object.values(t.headers).some(a=>typeof a!="string")||typeof t.expires_at!="string"||!Number.isFinite(Date.parse(t.expires_at))||s.protocol!=="https:"&&!(s.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(s.hostname))||s.username||s.password)throw d("invalid_operation_response","The authority returned an invalid prepared file part.")}function Ci(t){let e=new Headers;for(let[n,i]of Object.entries(t))["host","content-length"].includes(n.toLowerCase())||e.set(n,i);return e}async function er(t,e,n){let i=new Array(t),o=0;return await Promise.all(Array.from({length:Math.min(t,e)},async()=>{for(;o<t;){let r=o;o+=1,i[r]=await n(r)}})),i}function te(t){if(t?.aborted)throw d("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:t.reason})}function Re(t){return t instanceof _?t:typeof DOMException<"u"&&t instanceof DOMException&&t.name==="AbortError"?d("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:t}):d("temporarily_unavailable","The file transfer could not be completed.",{cause:t})}var wi=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu;function Ri(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.file_id=="string"&&wi.test(e.file_id)&&typeof e.path=="string"&&typeof e.revision=="string"&&typeof e.content_digest=="string"&&on.test(e.content_digest)&&Number.isSafeInteger(e.size)&&e.size>=0&&["image","audio","video","pdf","other"].includes(e.media_class)&&typeof e.modified_at=="string"&&(e.media_type===void 0||typeof e.media_type=="string")}function he(t){if(!Ri(t))throw d("invalid_operation_response","The authority returned an invalid file descriptor.");return{fileId:t.file_id,path:t.path,revision:t.revision,contentDigest:t.content_digest,size:t.size,...t.media_type?{mediaType:t.media_type}:{},mediaClass:t.media_class,modifiedAt:t.modified_at}}var uc=Object.entries({path:V,from:V,to:V,revision:V,previous_revision:V,types:Oi,previous_types:Oi,changed_fields:Oi,body_changed:fc,before:Pi,after:Pi}),pc=Object.entries({path:V,name:V,revision:V,previous_revision:V,reason:V}),hc=Object.entries({previous_path:V,revision:V});function Ai(t){let e={cursor:t.cursor,type:t.type,occurredAt:t.occurred_at,payload:t.payload,raw:t},n=a=>({...e,kind:"unknown",reason:a}),i=Object.hasOwn(oi,t.type)?oi[t.type]:void 0;if(!i)return n("unrecognized_type");let o=t.payload;if(!Pi(o))return n("invalid_payload");if(i.startsWith("record.")){if(!Si(o,uc))return n("invalid_payload");let a=o,c={...a.revision==null?{}:{revision:a.revision},...a.previous_revision==null?{}:{previousRevision:a.previous_revision},...a.types==null?{}:{types:a.types},...a.previous_types==null?{}:{previousTypes:a.previous_types},...a.changed_fields==null?{}:{changedFields:a.changed_fields},...a.body_changed==null?{}:{bodyChanged:a.body_changed},...a.before==null?{}:{before:a.before},...a.after==null?{}:{after:a.after}};if(i==="record.renamed")return V(o.from)&&V(o.to)?{...e,...c,kind:i,from:o.from,to:o.to}:n("invalid_payload");if(i==="record.created"||i==="record.updated"||i==="record.deleted")return V(o.path)?{...e,...c,kind:i,path:o.path}:n("invalid_payload")}if(i==="file.put")return Ri(o.file)?{...e,kind:i,file:he(o.file)}:n("invalid_payload");if(i==="file.removed"){if(!V(o.file_id)||!Si(o,hc))return n("invalid_payload");let a=o;return{...e,kind:i,fileId:o.file_id,...a.previous_path==null?{}:{previousPath:a.previous_path},...a.revision==null?{}:{revision:a.revision}}}if(!Si(o,pc))return n("invalid_payload");let r=o;if(i==="gap")return{...e,kind:i,...r.reason==null?{}:{reason:r.reason}};let s={...r.revision==null?{}:{revision:r.revision},...r.previous_revision==null?{}:{previousRevision:r.previous_revision}};if(i==="file.changed")return V(o.path)?{...e,...s,kind:i,path:o.path}:n("invalid_payload");if(i==="schema.changed"||i==="config.changed"||i==="contract.changed"||i==="view.changed")return{...e,...s,kind:i,...r.path==null?{}:{path:r.path},...r.name==null?{}:{name:r.name}};throw new Error(`Unhandled change kind: ${i}`)}function tr(t){return{events:t.reset?[{kind:"reset",type:"reset",cursor:t.cursor,occurredAt:null,payload:{},raw:t}]:t.events.map(Ai),cursor:t.cursor,hasMore:t.has_more,reset:t.reset}}function nr(t){return t.kind==="schema.changed"||t.kind==="config.changed"||t.kind==="contract.changed"||t.kind==="view.changed"||t.kind==="gap"||t.kind==="reset"||t.kind==="unknown"}function V(t){return typeof t=="string"}function fc(t){return typeof t=="boolean"}function Oi(t){return Array.isArray(t)&&t.every(V)}function Pi(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Si(t,e){return e.every(([n,i])=>t[n]==null||i(t[n]))}function sn(t,e,n){let i=new Set(t.required),o=[...new Set([...t.required,...t.optional??[]])],r={};for(let s of o)r[s]=mc(s,i.has(s),n,t.contract_version,e);return{contractVersion:t.contract_version,values:r,requiredAvailable:t.required.every(s=>r[s]?.state==="available")}}function mc(t,e,n,i,o){let r=X(i,t)??[],s=r.filter(c=>!n.operations.includes(c)),a={id:t,requirement:e?"required":"optional",operations:r,missingOperations:s,evidence:[{source:"application",fact:`${e?"Required":"Optional"} in capability contract v${i}.`}]};if(s.length>0)return{...a,state:"requires_authorization",evidence:[...a.evidence,{source:"authorization",fact:`Missing ${s.join(", ")}.`}],reason:"The current grant does not include every operation for this capability."};if(n.scope.access!=="full_collection")return{...a,state:"requires_authorization",reason:"The current grant uses legacy contract scope and must be reauthorized for the entire collection.",evidence:[...a.evidence,{source:"authorization",fact:"Legacy contract scope is compatibility evidence, not active data authority."}]};if(i===1&&t.startsWith("files.")){let c=t.slice(6);if(!n.fileCapability?.actions.includes(c))return{...a,state:n.fileCapability?"requires_authorization":"unsupported",reason:n.fileCapability?`The current file grant does not include ${c}.`:"This connection has no file capability."}}return i===1&&t==="notifications.background-delivery"&&(o.notifications?.criteria.length??0)===0?{...a,state:"requires_setup",reason:"The application manifest declares no notification criteria."}:{...a,state:"available",evidence:[...a.evidence,{source:"authorization",fact:r.length>0?`Granted operations: ${r.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."}],...t==="offline.replica"||i===1&&t==="sync.offline-replica"?{details:{durability:"device",writes:"queued",authority:n.authority.kind}}:{},...i===1&&t==="notifications.background-delivery"?{details:{delivery:"authority",payload:"opaque"}}:{}}}var $e=3e4,Ti=1e4,yc=10*6e4,gc=12e4,bc=6e4;function We(t={}){return{requestMs:Pt(t.requestMs,$e,"requestMs"),watchStartMs:Pt(t.watchStartMs,Ti,"watchStartMs"),fileIndexMs:Pt(t.fileIndexMs,yc,"fileIndexMs"),uploadMs:Pt(t.uploadMs,gc,"uploadMs"),syncMs:Pt(t.syncMs,bc,"syncMs")}}function pe(t,e){return{...t,signal:e.signal,...e.deadline===null?{}:{deadlineUnixMs:e.deadline}}}function Oe(t={},e=$e,n=Date.now){let i=t.timeoutMs===void 0?e:t.timeoutMs,o=i===null?null:_c(i),r=new AbortController,s=o===null?null:n()+o,a=()=>r.abort(t.signal?.reason);t.signal?.aborted?a():t.signal?.addEventListener("abort",a,{once:!0});let c=o===null?void 0:setTimeout(()=>r.abort(d("timeout","The operation exceeded its request deadline.",{operationOutcome:"not_sent"})),o),l=!1;return{signal:r.signal,deadline:s,remainingMs:()=>s===null?null:Math.max(0,s-n()),dispose:()=>{l||(l=!0,c!==void 0&&clearTimeout(c),t.signal?.removeEventListener("abort",a))}}}async function k(t,e,n){let i=Oe(t,e),o,r=new Promise((a,c)=>{o=c}),s=()=>o?.(ne(i.signal));i.signal.addEventListener("abort",s,{once:!0});try{if(i.signal.aborted)throw ne(i.signal);return await Promise.race([n(i),r])}finally{i.signal.removeEventListener("abort",s),i.dispose()}}async function $(t,e,n){let i=Oe(t,e);try{if(i.signal.aborted)throw ne(i.signal);return await n(i)}finally{i.dispose()}}function ne(t){return t.reason instanceof _?t.reason:d("operation_cancelled","The operation was cancelled before it changed the collection.",{operationOutcome:"not_sent",cause:t.reason})}function _c(t){if(!Number.isSafeInteger(t)||t<=0)throw new TypeError("timeoutMs must be a positive safe integer or null.");return t}function Pt(t,e,n){if(t===void 0)return e;if(t===null)return null;if(!Number.isSafeInteger(t)||t<=0)throw new TypeError(`${n} must be a positive safe integer or null.`);return t}async function At(t,e){let n=typeof window>"u"?void 0:globalThis.performance,i=n?.now();try{return await e()}finally{if(n&&i!==void 0)try{let o=`mdbase:startup:${t}`;n.clearMeasures(o),n.measure(o,{start:i,end:n.now()})}catch{}}}async function Mi(t){let{collectionId:e,readiness:n,contracts:i,connection:o,controller:r,options:s,requestMs:a,isCurrent:c,publish:l}=t,u=()=>r.abort(s?.signal?.reason);s?.signal?.aborted?u():s?.signal?.addEventListener("abort",u,{once:!0});try{let h=await At("contracts",()=>k({...s,signal:r.signal},a,f=>o.describe(f)));if(!c())return!1;if(!h.ok){let f=["access_denied","collection_access_denied","insufficient_access","not_authorized","authorization_expired","application_declaration_mismatch"].includes(h.problem.code);return n.contracts={state:f?"requires_authorization":"temporarily_unavailable",missing:[],evidence:[{source:"runtime",fact:h.problem.message}]},l(f?{status:"authorization_required"}:{status:"blocked",problem:h.problem}),!1}if(h.value.collectionId!==e)return n.contracts={state:"temporarily_unavailable",missing:[],evidence:[]},l({status:"blocked",problem:{code:"collection_not_ready",message:"Description belongs to a different collection."}}),!1;let p=i.filter(f=>!h.value.contracts.some(m=>m.id===f.id&&m.version===f.version&&m.digest===f.digest));if(n.contracts={state:p.length?"requires_setup":"verified",missing:p,evidence:[{source:"authority",fact:"Exact contract ID, version and digest checked by live describe for this collection."}]},p.length)return l({status:"blocked",problem:{code:"collection_not_ready",message:"The collection is missing required exact contracts."}}),!1}catch(h){if(!c())return!1;if(!(h instanceof _))throw h;return n.contracts={state:"temporarily_unavailable",missing:[],evidence:[{source:"runtime",fact:h.problem.message}]},l({status:"blocked",problem:h.problem}),!1}finally{s?.signal?.removeEventListener("abort",u)}return!0}function ir(t,e,n){let i=structuredClone(t);return i.setup.state!=="not_required"&&i.setup.state!=="current"&&(i.setup.state=e==="ready"?n==="cached"?"cached":"current":e==="setup_review_required"?"review_required":e==="authorization_required"?"requires_authorization":e==="blocked"?"blocked":"checking",i.setup.evidence=[{source:e==="ready"&&n==="cached"?"runtime":"authority",fact:`Collection setup verification: ${i.setup.state}.`}]),i}function or(t,e,n,i){return{collectionId:e,info:n,capabilities:sn(t.requirements.capabilities,t,n),...t.requirements?.capabilities?.contract_version===2?{readiness:Cc(t,n)}:{},connections:i}}function an(t,e){return`mdbase-application-session:v1:${t.id}:${e}`}function Ii(t){return JSON.stringify({capabilities:t.requirements?.capabilities,requirements:t.requirements?.configuration??[],provisions:t.provisions??{}})}function rr(t,e){return t.requirements?.access==="full_collection"&&e.scope.access==="full_collection"&&e.scope.contracts.length===0}function sr(t){let e={};for(let n of t.typePacks){let i=Object.fromEntries(n.resources.filter(o=>o.action==="conflict"&&o.mode==="managed"&&o.currentDigest!==void 0&&o.installedDigest===void 0).map(o=>[o.target,o.currentDigest]));Object.keys(i).length>0&&(e[n.desired.id]=i)}return e}function ar(t,e,n,i){return{applicationId:e,declarationDigest:n,requirements:{configuration:t.requirements?.configuration??[]},provisions:{configuration:t.provisions?.configuration??[],typePacks:t.provisions?.type_packs??[]},...i?{typePackAdoptions:i}:{}}}function vc(t,e){if(!e||t.kind!==e.kind)return!1;if(t.kind==="collection"||e.kind==="collection")return!0;let n=[...new Set(t.folders)].sort(),i=[...new Set(e.folders)].sort();return JSON.stringify(n)===JSON.stringify(i)}function Cc(t,e){let n=t.requirements?.files,i=n&&"required"in n?n:void 0,o=!i||vc(i.scope,e.fileCapability?.scope),r=u=>u.filter(h=>!o||!e.fileCapability?.actions.includes(h)),s=r(i?.required??[]),a=r(i?.optional??[]),c=t.requirements?.contracts??[],l=(t.provisions?.type_packs.length??0)>0||(t.provisions?.configuration?.length??0)>0;return{files:{state:i?s.length?"requires_authorization":"available":"not_required",missingRequiredActions:s,missingOptionalActions:a,scopeMatches:o,evidence:[{source:"authorization",fact:"Compared exact file actions and folder scope with connection.info().fileCapability."}]},contracts:{state:c.length?"checking":"not_required",missing:[],evidence:[]},setup:{state:l?"checking":"not_required",evidence:[]},notifications:{state:t.notifications?.criteria.length?"requires_registration":"not_required",registration:"unverified",evidence:[{source:"runtime",fact:"The connection API exposes registration commands but no current delivery-registration query. Manifest criteria do not prove approval or delivery registration."}]}}}function se(t){let e=new Uint8Array(t);return crypto.getRandomValues(e),fe(e)}var cr=32768;function fe(t){let e="";for(let o=0;o<t.length;o+=cr)e+=String.fromCharCode.apply(null,t.subarray(o,o+cr));let n=btoa(e).replaceAll("+","-").replaceAll("/","_"),i=n.length;for(;i>0&&n.charCodeAt(i-1)===61;)i-=1;return n.slice(0,i)}function cn(t){let e=t.replaceAll("-","+").replaceAll("_","/").padEnd(Math.ceil(t.length/4)*4,"="),n=atob(e),i=new Uint8Array(new ArrayBuffer(n.length));for(let o=0;o<n.length;o+=1)i[o]=n.charCodeAt(o);return i}var wc="mdbase-connect-keys",Se="grant-keys",xi=18446744073709551615n,Rc="mdbase-connect relay request key v1",Oc="mdbase-connect relay response key v1",lr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Je=class{database=null;async create(e){let n=await pr(e),i=await this.open();return await ur(i,o=>o.add({...n,counter:"0"})),n}async get(e){let n=await this.open(),i=await Mc(n.transaction(Se).objectStore(Se).get(e));return i?{handle:i.handle,agreementPrivateKey:i.agreementPrivateKey,agreementPublicKey:i.agreementPublicKey,signingPrivateKey:i.signingPrivateKey,signingPublicKey:i.signingPublicKey}:null}async nextCounter(e){let n=await this.open();return new Promise((i,o)=>{let r=n.transaction(Se,"readwrite"),s=r.objectStore(Se),a=s.get(e),c=null;a.onerror=()=>o(a.error),a.onsuccess=()=>{let l=a.result;if(!l){r.abort(),o(new q("missing_grant_key","The encrypted grant key is unavailable."));return}let u=BigInt(l.counter)+1n;if(u>xi){r.abort(),o(new q("counter_exhausted","The encrypted grant must be authorized again."));return}c=u.toString(),s.put({...l,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 n=await this.open();await ur(n,i=>i.delete(e))}open(){if(typeof indexedDB>"u")throw new q("key_storage_unavailable","Encrypted relay authorization requires browser IndexedDB or an injected grant key store.");return this.database||(this.database=new Promise((e,n)=>{let i=indexedDB.open(wc,1);i.onupgradeneeded=()=>{i.result.objectStoreNames.contains(Se)||i.result.createObjectStore(Se,{keyPath:"handle"})},i.onerror=()=>n(i.error),i.onsuccess=()=>e(i.result)})),this.database}},Ye=class{records=new Map;sequence=Promise.resolve();async create(e){if(this.records.has(e))throw new Error(`Grant key already exists: ${e}`);let n=await pr(e);return this.records.set(e,{...n,counter:"0"}),n}async get(e){let n=this.records.get(e);return n?{handle:n.handle,agreementPrivateKey:n.agreementPrivateKey,agreementPublicKey:n.agreementPublicKey,signingPrivateKey:n.signingPrivateKey,signingPublicKey:n.signingPublicKey}:null}nextCounter(e){let n,i,o=new Promise((r,s)=>{n=r,i=s});return this.sequence=this.sequence.then(()=>{let r=this.records.get(e);if(!r)throw new q("missing_grant_key","The encrypted grant key is unavailable.");let s=BigInt(r.counter)+1n;if(s>xi)throw new q("counter_exhausted","The encrypted grant must be authorized again.");r.counter=s.toString(),n(r.counter)}).catch(r=>{i(r)}),o}async delete(e){this.records.delete(e)}};async function ln(t,e,n,i){let o=await Sc(t,e,n),r=i.timestamp??Math.floor(Date.now()/1e3),s=i.nonce??crypto.randomUUID(),a=await Ei({...i,timestamp:r,nonce:s}),c=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},o.signingPrivateKey,new TextEncoder().encode(a));return{[wt.version]:String(di),[wt.timestamp]:String(r),[wt.nonce]:s,[wt.signature]:fe(new Uint8Array(c))}}async function Ei(t){let e=t.method.toUpperCase(),n=await dr(t.body??""),i=await dr(t.credential);for(let o of[e,t.target,String(t.timestamp),t.nonce])if(!o||o.includes(`
2
+ `)||o.includes("\r"))throw new q("invalid_proof_input","Authority request proof metadata is invalid.");return[Do,di,e,t.target,n,i,t.timestamp,t.nonce].join(`
3
+ `)}async function me(t,e,n,i,o,r=crypto.randomUUID(),s){if(ye(n.encryption),s!==void 0&&(!Number.isSafeInteger(s)||s<=0))throw new q("invalid_deadline","The operation deadline is invalid.");let a=await hr(t,e,n.encryption.application_agreement_public_key),c=await t.nextCounter(e),l={binding:n,protocolVersion:Y,requestId:r,operation:i,counter:c},u=await fr(a.agreementPrivateKey,n,l.protocolVersion,"request"),h=new TextEncoder().encode(JSON.stringify(o??{})),p=await crypto.subtle.encrypt({name:"AES-GCM",iv:gr(c),additionalData:new TextEncoder().encode(yr(l,"request")),tagLength:128},u,h);return{type:"encrypted_operation_request",...Pc(l),...s===void 0?{}:{deadline_unix_ms:s},ciphertext:fe(new Uint8Array(p))}}async function Xe(t,e,n,i,o){if(!Ac(i,o))throw new q("invalid_encrypted_response","Encrypted response metadata does not match its request.");let r=await hr(t,e,n.encryption.application_agreement_public_key),s={binding:n,protocolVersion:i.protocol_version,requestId:i.request_id,operation:i.operation,counter:i.counter},a=await fr(r.agreementPrivateKey,n,i.protocol_version,"response");try{let c=await crypto.subtle.decrypt({name:"AES-GCM",iv:gr(i.counter),additionalData:new TextEncoder().encode(yr(s,"response")),tagLength:128},a,br(o.ciphertext)),l=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(c));if(l?.ok===!0&&"result"in l||l?.ok===!1&&gt(l.problem))return l;throw new Error("invalid response body")}catch(c){throw c instanceof q?c:new q("encrypted_response_rejected","The encrypted connector response could not be authenticated.")}}var q=class extends Error{constructor(n,i){super(i);this.code=n}code};async function pr(t){let e=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"]),n=fe(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"]),s=fe(new Uint8Array(await crypto.subtle.exportKey("raw",r.publicKey))),a=await crypto.subtle.exportKey("pkcs8",r.privateKey),c=await crypto.subtle.importKey("pkcs8",a,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]);return{handle:t,agreementPrivateKey:o,agreementPublicKey:n,signingPrivateKey:c,signingPublicKey:s}}async function hr(t,e,n){let i=await t.get(e);if(!i||i.agreementPublicKey!==n)throw new q("missing_grant_key","The encrypted grant key is unavailable or does not match the grant.");return i}async function Sc(t,e,n){let i=await t.get(e);if(!i||i.signingPublicKey!==n)throw new q("missing_grant_key","The remote authority signing key is unavailable or does not match the grant.");return i}async function fr(t,e,n,i){let o=await Tt(t,e.encryption.connector_agreement_public_key),r=await crypto.subtle.importKey("raw",o,"HKDF",!1,["deriveKey"]),s=new TextEncoder().encode(mr(e,n)),a=await crypto.subtle.digest("SHA-256",s);return crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:a,info:new TextEncoder().encode(i==="request"?Rc:Oc)},r,{name:"AES-GCM",length:256},!1,i==="request"?["encrypt"]:["decrypt"])}async function Tt(t,e){try{let n=await crypto.subtle.importKey("raw",Tc(ki(e)),{name:"ECDH",namedCurve:"P-256"},!1,[]);return await crypto.subtle.deriveBits({name:"ECDH",public:n},t,256)}catch{throw new q("invalid_public_key","The connector relay public key is invalid.")}}function mr(t,e){let n=t.encryption;return["mdbase-connect",e,n.suite,t.grantId,t.applicationId,n.connector_id,n.collection_id,n.scope_epoch,n.key_id].join("|")}function yr(t,e){return[mr(t.binding,t.protocolVersion),t.requestId,e,t.operation,t.counter].join("|")}function Pc(t){let e=t.binding.encryption;return{protocol_version:t.protocolVersion,suite:Ct,request_id:t.requestId,grant_id:t.binding.grantId,application_id:t.binding.applicationId,connector_id:e.connector_id,collection_id:e.collection_id,operation:t.operation,scope_epoch:e.scope_epoch,key_id:e.key_id,counter:t.counter}}function Ac(t,e){return e.type==="encrypted_operation_response"&&typeof e.ciphertext=="string"&&t.protocol_version===e.protocol_version&&t.suite===e.suite&&t.request_id===e.request_id&&t.grant_id===e.grant_id&&t.application_id===e.application_id&&t.connector_id===e.connector_id&&t.collection_id===e.collection_id&&t.operation===e.operation&&t.scope_epoch===e.scope_epoch&&t.key_id===e.key_id&&t.counter===e.counter}function ye(t){if(t.protocol_version!==Yt||t.suite!==Ct||!Number.isSafeInteger(t.scope_epoch)||t.scope_epoch<=0||typeof t.key_id!="string"||t.key_id.length===0||t.key_id.length>200||t.key_id.includes("|"))throw new q("unsupported_encryption","The grant uses an unsupported relay encryption profile.");if(typeof t.connector_id!="string"||!lr.test(t.connector_id)||typeof t.collection_id!="string"||!lr.test(t.collection_id))throw new q("unsupported_encryption","The grant uses invalid encrypted relay identities.");ki(t.application_agreement_public_key),ki(t.connector_agreement_public_key)}function gr(t){let e=BigInt(t);if(e<=0n||e>xi||e.toString()!==t)throw new q("invalid_counter","The encrypted relay counter is invalid.");let n=new Uint8Array(new ArrayBuffer(12));return new DataView(n.buffer).setBigUint64(4,e,!1),n}async function dr(t){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return fe(new Uint8Array(e))}function br(t){if(!/^[A-Za-z0-9_-]+$/.test(t))throw new q("invalid_base64","Encrypted relay data is malformed.");return cn(t)}function ki(t){let e=br(t);if(e.length!==65||e[0]!==4)throw new q("invalid_public_key","Encrypted relay public keys must be uncompressed P-256 points.");return e}function Tc(t){return Uint8Array.from(t).buffer}function Mc(t){return new Promise((e,n)=>{t.onerror=()=>n(t.error),t.onsuccess=()=>e(t.result)})}function ur(t,e){return new Promise((n,i)=>{let o=t.transaction(Se,"readwrite"),r=e(o.objectStore(Se));r.onerror=()=>i(r.error),o.onerror=()=>i(o.error),o.onabort=()=>i(o.error??new Error("Grant key transaction aborted.")),o.oncomplete=()=>n()})}function Pe(t){return{...t,credentials:"omit",targetAddressSpace:"loopback"}}async function Mt(){if(typeof navigator>"u"||!navigator.permissions?.query)return null;try{return(await navigator.permissions.query({name:"local-network-access"})).state}catch{return null}}async function Ze(t){let{status:e}=t;return e===404||e===405||e===426||e>=500?!0:e===403&&(await t.clone().text()).trim()===""}function _r(t,e){return ee(t,e)}function vr(t,e){if(t.deadline_unix_ms===e)return t;let{deadline_unix_ms:n,...i}=t;return{...i,...e===void 0?{}:{deadline_unix_ms:e}}}function It(t){return[...new Set(t)]}function Cr(t,e){return t.grantId||e.grantId?t.grantId===e.grantId&&t.keyHandle===e.keyHandle&&t.encryption?.key_id===e.encryption?.key_id:t.accessToken===e.accessToken}function De(t){if(t?.aborted)throw d("operation_cancelled","The operation was cancelled before it changed the collection.",{operationOutcome:"not_sent",cause:t.reason})}function dn(t,e,n,i){return t instanceof _?t:e?.aborted?n?J(n,t):e.reason instanceof _?e.reason:d("operation_cancelled","The operation was cancelled before it changed the collection.",{operationOutcome:"not_sent",cause:t}):n?J(n,t):t instanceof TypeError?d(i,i==="hosted_provider_unavailable"?"The hosted collection provider is unavailable.":"The Connect relay is unavailable.",{cause:t}):t instanceof Error?t:new Error(String(t))}function wr(t){return L(t.code==="unknown"?t.server_code:t.code,t.message,{details:t.details,operationOutcome:t.operation_outcome??"rejected",traceId:t.trace_id})}function Rr(t,e,n,i,o){return fetch(t,{method:"POST",headers:{authorization:`Bearer ${e}`,"content-type":"application/json",...n},body:i,signal:o})}function Fi(t,e){return e?.aborted===!0||t instanceof _&&t.code==="operation_cancelled"}function Or(t,e){if(e.dryRun!==!0||e.wouldRename!==!0||e.from!==t.from||e.to!==t.to)throw d("invalid_preflight","The rename preview does not match this mutation. Run the preview again.")}function Sr(t,e){if(e.dryRun!==!0||e.wouldDelete!==!0||e.path!==t.path)throw d("invalid_preflight","The delete preview does not match this mutation. Run the preview again.")}function Pr(t,e){if(t.updateRefs===!1)return{affectedRecords:0,totalUnits:1,warnings:0};let n=e.referencesAffected??[];return{affectedRecords:new Set(n.map(i=>i.path)).size,totalUnits:1+n.length,warnings:e.warnings?.length??0}}function Ar(t){return{affectedRecords:new Set((t.brokenLinks??[]).map(e=>e.path)).size,totalUnits:1,warnings:0}}async function Tr(t,e){return Po(t,e??{})}function Mr(t){return JSON.stringify(qi(t))}function qi(t){return Array.isArray(t)?t.map(e=>qi(e)):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[n])=>e<n?-1:e>n?1:0).map(([e,n])=>[e,qi(n)])):t}function J(t,e){return d("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:t},cause:e})}function un(t,e){let n=F(t.getItem(`${e}:connections`));return n?.version===1&&Array.isArray(n.collectionIds)&&n.collectionIds.every(i=>typeof i=="string")?n.collectionIds:[]}function Ir(t,e,n){xr(t,e,[...un(t,e),n])}function kr(t,e,n){xr(t,e,un(t,e).filter(i=>i!==n))}function xr(t,e,n){t.setItem(`${e}:connections`,JSON.stringify({version:1,collectionIds:[...new Set(n)]}))}function Er(t,e){let n=t instanceof URL?t.href:t??kc(),i=typeof n=="string"?n:n.distribution==="portable"?`bundle:${n.id}:${Ec(n)}`:`bundle:${n.id}`,o=e===void 0?typeof n!="string"&&n.distribution==="portable"?"":xc():String(e);return{manifest:n,manifestSource:i,redirectUri:o}}async function ae(t,e,n,i){try{return await fetch(t,e)}catch(o){throw d(n,i,{cause:o})}}async function E(t,e,n){let i;try{i=await t.text()}catch(o){throw L(e,n,{status:t.status,cause:o})}if(i.trim()==="")throw L(e,n,{status:t.status});try{return JSON.parse(i)}catch(o){throw L(e,n,{status:t.status,cause:o})}}function qr(t){let e=new URL(t);if(e.protocol!=="http:"||!["127.0.0.1","[::1]"].includes(e.hostname)||e.username||e.password||e.pathname!=="/"||e.search||e.hash)throw d("invalid_loopback_url","loopbackUrl must be an HTTP origin on 127.0.0.1 or ::1.");return e.origin}async function kt(){let t=se(32),e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return{verifier:t,challenge:fe(new Uint8Array(e))}}function D(t,e,n,i){return L(xt(t)??t?.error?.code??e,t?.error_description??t?.error?.message??n,{status:i,details:t?.error?.details,operationOutcome:t?.error?.operation_outcome,traceId:t?.error?.trace_id})}function xt(t){return typeof t?.error=="string"?t.error:void 0}function Et(t,e){if(!t||typeof t!="object"||Array.isArray(t)||typeof e!="string")return!1;let n=t;if(typeof n.operations_url!="string"||typeof n.sync_url!="string"||typeof n.files_url!="string"||typeof n.replica_id!="string"||n.replica_id.length===0||typeof n.access_token!="string"||n.access_token.length===0||n.proof_public_key!==void 0&&(typeof n.proof_public_key!="string"||n.proof_public_key.length===0))return!1;try{let i=new URL(n.operations_url),o=new URL(n.sync_url),r=new URL(n.files_url);return[i,o,r].every(s=>(s.protocol==="https:"||s.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(s.hostname))&&!s.username&&!s.password&&!s.search&&!s.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 Fr(t,e){return Et({operations_url:t?.operationsUrl,sync_url:t?.syncUrl,files_url:t?.filesUrl,replica_id:t?.replicaId,access_token:t?.accessToken,proof_public_key:t?.proofPublicKey},e)}function pn(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t,n=e.actions;if(e.kind!=="files"||e.protocol_version!==1||!Array.isArray(n)||n.length===0||n.length>6||new Set(n).size!==n.length||n.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&&Ic(o))}function Ic(t){let e=new Set([".mdbase",".git","node_modules","_contracts","_schemas","_types","_views"]);return!t.startsWith("/")&&!t.endsWith("/")&&!t.includes("\\")&&t.split("/").every(n=>{let i=n.split(".")[0]?.toUpperCase()??"";return n!==""&&n!=="."&&n!==".."&&!n.startsWith(".")&&!n.endsWith(" ")&&!n.endsWith(".")&&!/[<>:"|?*]/.test(n)&&!e.has(n.toLowerCase())&&!["CON","PRN","AUX","NUL"].includes(i)&&!/^(COM|LPT)[1-9]$/.test(i)})}function zr(t,e){if(!t||typeof t!="object"||Array.isArray(t)||t.collection_id!==e)return!1;try{return ye(t),!0}catch{return!1}}function Dr(t){if(typeof t?.device_code!="string"||typeof t?.user_code!="string"||typeof t?.verification_uri!="string"||typeof t?.verification_uri_complete!="string"||!Number.isFinite(t?.expires_in)||!Number.isFinite(t?.interval))throw d("invalid_device_authorization_response","Connect returned an invalid downloaded application authorization response.");return{userCode:t.user_code,verificationUri:t.verification_uri,verificationUriComplete:t.verification_uri_complete,expiresAt:Date.now()+Math.max(1,t.expires_in)*1e3,intervalSeconds:Math.max(1,t.interval)}}function F(t){if(!t)return null;try{return JSON.parse(t)}catch{return null}}function hn(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t;return e.access!=="contract"&&e.access!=="full_collection"||!Array.isArray(e.contracts)||e.contracts.some(n=>!n||typeof n!="object"||n.contract_type!=="record"||typeof n.id!="string"||typeof n.version!="string"||!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(n.version)||!/^sha256:[0-9a-f]{64}$/.test(n.digest)||!n.schema||typeof n.schema!="object"||Array.isArray(n.schema)||!Array.isArray(n.implementations)||n.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 fn(t){return t.access==="full_collection"&&t.contracts.length===0}function Lr(t){return t.endsWith("/")?t.slice(0,-1):t}function kc(){if(typeof location>"u")throw d("manifest_required","manifest is required outside a browser environment.");if(location.origin==="null")throw d("manifest_required","Downloaded applications must provide their v1 portable manifest inline.");return new URL("/.well-known/mdbase-app.json",location.origin).href}function xc(){if(typeof location>"u")throw d("redirect_uri_required","redirectUri is required outside a browser environment.");return location.href.split(/[?#]/)[0]}function zi(){if(typeof location>"u")return"null";let t=new URL(location.href);return["chrome-extension:","moz-extension:"].includes(t.protocol)?`${t.protocol}//${t.host}`:["http:","https:"].includes(t.protocol)?t.origin:"null"}function Ur(t,e,n,i){if(typeof t!="string"&&t.distribution==="portable"||i)return zi();let o=new URL(n);if(["http:","https:"].includes(o.protocol))return o.origin;if(typeof location<"u")return location.origin;if(typeof t!="string")return new URL(t.homepage).origin;try{return new URL(e).origin}catch{return""}}function Nr(t){let e=":token:",n=t.lastIndexOf(e);return n<0?"":t.slice(n+e.length)}function mn(){if(typeof location>"u")throw d("callback_url_required","callbackUrl is required outside a browser environment.");return location.href}function jr(t){if(t)return new et;if(typeof localStorage>"u")throw d("storage_required","storage is required outside a browser environment.");try{let e=`mdbase-connect:probe:${se(8)}`;return localStorage.setItem(e,"1"),localStorage.removeItem(e),localStorage}catch{return new et}}var et=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,n){this.values.set(String(e),String(n))}};function Br(t){return typeof t=="string"||t.distribution!=="portable"?!1:typeof location>"u"||location.origin==="null"||!["http:","https:"].includes(location.protocol)}function Ec(t){let e=Mr(t),n=2166136261,i=2654435769;for(let o=0;o<e.length;o+=1){let r=e.charCodeAt(o);n=Math.imul(n^r,16777619),i=Math.imul(i^r,2246822507)}return`${(n>>>0).toString(16).padStart(8,"0")}${(i>>>0).toString(16).padStart(8,"0")}`}async function Qr(t,e){let n=await fetch(`${t}/health`,{signal:e,cache:"no-store"}),i=await n.json().catch(()=>null);if(!n.ok||!Array.isArray(i?.capabilities)||!i.capabilities.every(o=>typeof o=="string")||!i.capabilities.includes(uo))throw d("capability_contract_incompatible","This server does not support new version-2 application authorizations.",{details:{contract:"fresh_application_authorization",required:[2],supported:[],peer:"server"}})}function qt(t){let e="bundle:";if(!t.startsWith(e)||t.length===e.length)throw new Error("The registered application has no valid declaration identity.");return t.slice(e.length)}function tt(t,e,n){return t.reason instanceof _?t.reason:d("authorization_cancelled",e,{cause:n})}function Ft(t){for(let e of["code","state","error","error_description"])t.searchParams.delete(e);return t}function yn(t){let e;try{e=new URL(t)}catch{return!1}return e.searchParams.has("state")&&(e.searchParams.has("code")||e.searchParams.has("error"))}function gn(t){try{let e=new URL(t).searchParams.get("state");return e&&e.length>0?e:null}catch{return null}}function Kr(t){if(!t.details||typeof t.details!="object"||Array.isArray(t.details))return;let e=t.details.return_to;return typeof e=="string"?e:void 0}var nt=class{constructor(e,n){this.connect=e;this.operations=It(n.operations??be),this.selection=n.selection,this.autoSelect=n.autoSelect??"only",this.snapshot={status:"not_started",connections:[]}}connect;operations;selection;autoSelect;listeners=new Set;snapshot;snapshotKey="";stopConnections;stopSelection;stopActiveConnection;activeCollectionId=null;unavailableReason="not_authorized";started=!1;destroyed=!1;refreshing=!1;refreshQueued=!1;transactionDepth=0;lifecycleGeneration=0;operationControllers=new Set;startOperation=null;callbackCompletions=new Map;start(e){if(this.destroyed)return Promise.resolve(b(w("session_destroyed","This session has been destroyed.")));if(this.started&&!this.startOperation)return Promise.resolve(O(this.snapshot));let n=this.startOperation??this.beginStart();return this.waitForStart(n,e)}beginStart(){let e=new AbortController,n=++this.lifecycleGeneration;this.publish({status:"starting",connections:this.connect.connections()});let i={promise:this.performStart({signal:e.signal,timeoutMs:null},n),controller:e,waiters:0,generation:n};this.startOperation=i;let o=()=>{this.startOperation===i&&(this.startOperation=null)};return i.promise.then(o,o),i}async waitForStart(e,n){e.waiters+=1;try{return await k(n,Ti,()=>e.promise)}catch(i){if(i instanceof _)return b(i.problem);throw i}finally{e.waiters-=1,e.waiters===0&&this.startOperation===e&&(e.controller.abort(),this.startOperation=null,this.lifecycleGeneration+=1,this.stopLifecycleSubscriptions(),this.started=!1,this.publish({status:"not_started",connections:this.connect.connections()}))}}async performStart(e,n){try{this.started=!0,this.stopConnections=this.connect.onConnectionsChange(()=>this.refresh()),this.stopSelection=this.selection.subscribe(()=>{this.unavailableReason="not_authorized",this.refresh()});let i=this.selection.authorizationCallback();if(i){let o=await this.completeAuthorizationCallback(i,e);if(!o.ok)return n===this.lifecycleGeneration&&!this.destroyed&&(this.stopLifecycleSubscriptions(),this.started=!1,this.publish({status:"start_failed",problem:o.problem,connections:this.connect.connections()})),o}else this.autoSelectOnlyConnection();return n!==this.lifecycleGeneration||this.destroyed?b(w("session_destroyed","This session has been destroyed.")):(this.publishCurrent(),O(this.snapshot))}catch(i){if(i instanceof _){let o=i.problem;return n===this.lifecycleGeneration&&!this.destroyed&&(this.stopLifecycleSubscriptions(),this.started=!1,this.publish({status:"start_failed",problem:o,connections:this.connect.connections()})),b(o)}throw n===this.lifecycleGeneration&&!this.destroyed&&(this.stopLifecycleSubscriptions(),this.started=!1,this.publish({status:"not_started",connections:this.connect.connections()})),i}}destroy(){if(!this.destroyed){this.lifecycleGeneration+=1,this.startOperation?.controller.abort(),this.startOperation=null;for(let e of this.operationControllers)e.abort();this.operationControllers.clear(),this.stopLifecycleSubscriptions(),this.started=!1,this.destroyed=!0,this.callbackCompletions.clear(),this.publish({status:"destroyed",connections:[]}),this.listeners.clear()}}stopLifecycleSubscriptions(){this.stopConnections?.(),this.stopSelection?.(),this.stopActiveConnection?.(),this.stopConnections=void 0,this.stopSelection=void 0,this.stopActiveConnection=void 0,this.activeCollectionId=null}getSnapshot(){return this.snapshot}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}select(e,n={}){let i=this.lifecycleProblem();if(i)return b(i);let o=this.connect.connection(e);return o?(this.unavailableReason="not_authorized",this.selection.select(e,n),this.refresh(),O(o)):b(w("unknown_collection","This collection is not authorized for this application."))}clearSelection(e={}){let n=this.lifecycleProblem();return n?b(n):(this.unavailableReason="not_authorized",this.selection.select(null,e),this.refresh(),O(void 0))}forget(e){let n=this.lifecycleProblem();if(n)return b(n);this.transactionDepth+=1;try{let i=this.selection.selectedCollectionId()===e;this.connect.connection(e)?.forget(),i&&this.selection.select(null,{history:"replace"})}finally{this.transactionDepth-=1,this.refresh()}return O(void 0)}async authorize(e,n={}){let i=this.lifecycleProblem();if(i)return b(i);let o=this.selection.selectedCollectionId();if(e==="selected"&&!o)return b(w("collection_not_selected","Choose a collection before updating its access."));let r=typeof e=="object"?e.collectionId:e==="selected"?o:null,s=this.beginLifecycleOperation(n);this.transactionDepth+=1;try{let a=await this.connect.manifest?.(s.options);if(a&&!a.ok)return a;if(!this.lifecycleCurrent(s.generation))return this.destroyedOutcome(O(void 0));let c=a?Q(a.value.requirements):1,l=await this.connect.authorize({...s.options,...c===1&&n.operations===void 0&&n.capabilities===void 0?{operations:this.operations}:{},target:r===null?{kind:"choose"}:{kind:"collection",collectionId:r},returnTo:this.selection.authorizationReturnTo()});return this.lifecycleCurrent(s.generation)?(l.ok&&l.value.kind==="connected"&&this.selection.finishAuthorization(l.value.returnTo,l.value.connection.collectionId),l):this.destroyedOutcome(l)}finally{s.dispose(),this.transactionDepth-=1,this.refresh()}}ensureOperations(e,n){return this.ensureAuthorization({operations:e},n)}ensureCapabilities(e,n){return this.ensureAuthorization({capabilities:e},n)}async ensureAuthorization(e,n){let i=this.lifecycleProblem();if(i)return b(i);let o=this.snapshot;if(o.status!=="ready")return b(w("collection_not_ready","Choose an authorized collection first."));let r=this.beginLifecycleOperation(n);this.transactionDepth+=1;try{let s=await this.connect.manifest?.(r.options);if(s&&!s.ok)return s;if(!this.lifecycleCurrent(r.generation))return this.destroyedOutcome(O(void 0));let a=s?.value.requirements??("operations"in e?{access:"full_collection",contracts:[]}:{access:"full_collection",contracts:[],capabilities:{contract_version:2,required:[],optional:Object.keys(jt)}});Z(a,{...n,...e});let c="operations"in e?e.operations:e.capabilities.flatMap(p=>X(Q(a),p)??[]),l=o.connection.authorizationCapabilities(c);if(l.sufficient)return O({kind:"unchanged",connection:o.connection});let u="operations"in e||Q(a)===1?{operations:It([...l.grantedOperations,...c])}:{capabilities:[...new Set([...bt(a,l.grantedOperations),...e.capabilities])]},h=await this.connect.authorize({...r.options,...u,target:{kind:"collection",collectionId:o.collectionId},returnTo:this.selection.authorizationReturnTo()});return this.lifecycleCurrent(r.generation)?(h.ok&&h.value.kind==="connected"&&this.selection.finishAuthorization(h.value.returnTo,h.value.connection.collectionId),h):this.destroyedOutcome(h)}catch(s){if(s instanceof _)return b(s.problem);throw s}finally{r.dispose(),this.transactionDepth-=1,this.refresh()}}handleAuthorizationCallback(e,n){let i=this.lifecycleProblem();return i?Promise.resolve(b(i)):yn(e)?this.completeAuthorizationCallback(e,n):Promise.resolve(b(w("invalid_callback","This URL is not an authorization callback.")))}completeAuthorizationCallback(e,n){if(n?.signal?.aborted){let r=ne(n.signal);return Promise.resolve(b(r.problem))}let i=gn(e);if(!i)return Promise.resolve(b(w("invalid_callback","Authorization callback is missing its state.")));let o=this.callbackCompletions.get(i)??this.beginCallbackCompletion(e,i);return this.waitForCallbackCompletion(o,n)}beginCallbackCompletion(e,n){let i=new AbortController,o=this.lifecycleGeneration;this.transactionDepth+=1,this.operationControllers.add(i);let r={state:n,controller:i,waiters:0,settled:!1,abandoned:!1,promise:void 0},s=this.connect.completeAuthorization(e,{signal:i.signal,timeoutMs:null}).catch(a=>{if(a instanceof _)return b(a.problem);throw a});return r.promise=s.then(a=>{if(o!==this.lifecycleGeneration||this.destroyed)return this.destroyedOutcome(a);if(!a.ok){if(!r.abandoned&&a.problem.recovery!=="retry"){let l=Kr(a.problem);this.selection.clearAuthorizationCallback(l)}return this.refresh(),a}let c=a.value;return this.unavailableReason="not_authorized",this.selection.finishAuthorization(c.returnTo,c.connection.collectionId),this.refresh(),O(c.connection,a.diagnostics)}).catch(a=>{if(o!==this.lifecycleGeneration||this.destroyed)return b(w("session_destroyed","This session was destroyed before authorization completion finished."));throw r.abandoned||(this.selection.clearAuthorizationCallback(),this.refresh()),a}).finally(()=>{r.settled=!0,this.operationControllers.delete(i),this.transactionDepth-=1,this.refresh(),this.callbackCompletions.get(n)===r&&this.callbackCompletions.delete(n)}),this.callbackCompletions.set(n,r),r}async waitForCallbackCompletion(e,n){e.waiters+=1;try{return await k(n,$e,()=>e.promise)}catch(i){if(i instanceof _)return b(i.problem);throw i}finally{e.waiters-=1,e.waiters===0&&!e.settled&&this.callbackCompletions.get(e.state)===e&&(e.abandoned=!0,this.callbackCompletions.delete(e.state),e.controller.abort())}}lifecycleProblem(){return this.destroyed?w("session_destroyed","This session has been destroyed."):this.snapshot.status==="starting"?w("session_starting","The session is still starting."):this.snapshot.status==="start_failed"?this.snapshot.problem:this.started?null:w("session_not_started","Start the session before using it.")}beginLifecycleOperation(e={}){let n=new AbortController,i=()=>n.abort(e.signal?.reason);return e.signal?.aborted?i():e.signal?.addEventListener("abort",i,{once:!0}),this.operationControllers.add(n),{generation:this.lifecycleGeneration,options:{...e,signal:n.signal},dispose:()=>{e.signal?.removeEventListener("abort",i),this.operationControllers.delete(n)}}}lifecycleCurrent(e){return!this.destroyed&&e===this.lifecycleGeneration}destroyedOutcome(e){return!e.ok&&e.problem.code==="operation_outcome_unknown"?e:b(w("session_destroyed","This session was destroyed before the operation finished."))}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.started||this.destroyed||this.snapshot.status==="starting"||this.snapshot.status==="start_failed")){if(this.transactionDepth>0){this.refreshQueued=!0;return}if(this.refreshing){this.refreshQueued=!0;return}this.refreshing=!0;try{do this.refreshQueued=!1,this.publishCurrent();while(this.refreshQueued)}finally{this.refreshing=!1}}}publishCurrent(){let e=this.selection.selectedCollectionId(),n=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(r=>{!r&&this.selection.selectedCollectionId()===i.collectionId&&(this.unavailableReason="authorization_lost"),this.refresh()}));let o;if(!e)o={status:"unselected",connections:n};else if(!i||!i.info())o={status:"unavailable",collectionId:e,reason:this.connect.unavailableReason(e)??this.unavailableReason,connections:n};else{let r=i.info();o={status:"ready",collectionId:e,connection:i,info:r,access:i.authorizationCapabilities(this.operations),connections:n}}this.publish(o)}publish(e){if(this.snapshot.status==="destroyed"&&e.status!=="destroyed")return;let n=qc(e);if(n!==this.snapshotKey){this.snapshot=e,this.snapshotKey=n;for(let i of this.listeners)i()}}};function qc(t){return t.status==="not_started"||t.status==="starting"||t.status==="destroyed"?JSON.stringify(t):t.status==="start_failed"?JSON.stringify({status:t.status,problem:t.problem,connections:t.connections}):t.status==="unselected"?JSON.stringify({status:t.status,connections:t.connections}):t.status==="unavailable"?JSON.stringify({status:t.status,collectionId:t.collectionId,reason:t.reason,connections:t.connections}):JSON.stringify({status:t.status,collectionId:t.collectionId,info:t.info,access:t.access,connections:t.connections})}var Dt=class{values=new Map;read(e){return this.values.get(e)??null}write(e,n){this.values.set(e,n)}remove(e){this.values.delete(e)}},it=class{constructor(e,n,i=We()){this.connect=e;this.options=n;this.timeouts=i;this.verificationStore=n.verificationStore??Lc()}connect;options;timeouts;listeners=new Set;verificationStore;snapshot={status:"not_started",connections:[]};manifest=null;application=null;base=null;stopBase;setupAssessment=null;setupTypePackAdoptions=null;verificationGeneration=0;readinessController;lifecycleGeneration=0;operationControllers=new Set;startOperation=null;start(e){if(this.snapshot.status==="destroyed")return Promise.resolve(b(w("session_destroyed","This application session has been destroyed.")));if(this.base&&!this.startOperation)return Promise.resolve(O(this.snapshot));let n=this.startOperation??this.beginStart();return this.waitForStart(n,e,this.timeouts.watchStartMs)}async waitForStart(e,n,i){e.waiters+=1;try{return await k(n,i,()=>e.promise)}catch(o){if(o instanceof _)return b(o.problem);throw o}finally{e.waiters-=1,e.waiters===0&&this.startOperation===e&&this.abandonStart(e)}}abandonStart(e){e.controller.abort(),this.readinessController?.abort(),this.startOperation=null,this.lifecycleGeneration+=1,this.verificationGeneration+=1,this.base&&this.cleanupBase(this.base),this.application=null,this.manifest=null,this.setupAssessment=null,this.setupTypePackAdoptions=null,this.publish({status:"not_started",connections:this.connect.connections()})}beginStart(){this.publish({status:"starting",connections:this.connect.connections()});let e=new AbortController,n=++this.lifecycleGeneration,i={promise:this.startWithinBudget({signal:e.signal,timeoutMs:null},n),controller:e,waiters:0,generation:n};this.startOperation=i;let o=()=>{this.startOperation===i&&(this.startOperation=null)};return i.promise.then(o,o),i}async startWithinBudget(e,n){try{return await this.performStartWithinBudget(e,n)}catch(i){if(i instanceof _)return this.startFailure(i.problem,n);throw n===this.lifecycleGeneration&&(this.verificationGeneration+=1,this.base&&this.cleanupBase(this.base),this.application=null,this.manifest=null,this.setupAssessment=null,this.setupTypePackAdoptions=null,this.publish({status:"not_started",connections:this.connect.connections()})),i}}async performStartWithinBudget(e,n){let i=await At("registration",()=>this.connect.register(e));if(!i.ok)return this.startFailure(i.problem,n);let o=await this.connect.manifest(e);if(!o.ok)return this.startFailure(o.problem,n);if(o.value.requirements?.access!=="full_collection")return this.startFailure(w("invalid_application_manifest","Application sessions require explicit full_collection access.",{details:{issues:[{path:"/requirements/access",keyword:"const",message:"must be full_collection",params:{allowedValue:"full_collection"}}]}}),n);let r=o.value.requirements.capabilities;if(!r)return this.startFailure(w("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:{}}]}}),n);if(n!==this.lifecycleGeneration||e.signal?.aborted)return b(w("operation_cancelled","Application session startup was cancelled.",{operationOutcome:"not_sent"}));this.application=i.value,this.manifest=o.value;let s=new nt(this.connect,{selection:this.options.selection,autoSelect:this.options.autoSelect,operations:Fc(r,o.value)});this.base=s;try{let a=await s.start(e);return a.ok?n!==this.lifecycleGeneration||e.signal?.aborted?(this.cleanupBase(s),b(w("operation_cancelled","Application session startup was cancelled.",{operationOutcome:"not_sent"}))):(this.stopBase=s.subscribe(()=>{this.base===s&&this.refresh()}),await this.refresh(!0,e),n!==this.lifecycleGeneration||e.signal?.aborted?(this.cleanupBase(s),b(w("operation_cancelled","Application session startup was cancelled.",{operationOutcome:"not_sent"}))):O(this.snapshot)):(this.cleanupBase(s),this.startFailure(a.problem,n))}catch(a){throw this.cleanupBase(s),a}}startFailure(e,n){return n===this.lifecycleGeneration&&this.publish({status:"start_failed",problem:e,connections:this.connect.connections()}),b(e)}destroy(){if(this.snapshot.status!=="destroyed"){this.lifecycleGeneration+=1,this.verificationGeneration+=1,this.readinessController?.abort(),this.startOperation?.controller.abort(),this.startOperation=null;for(let e of this.operationControllers)e.abort();this.operationControllers.clear(),this.base&&this.cleanupBase(this.base),this.application=null,this.manifest=null,this.setupAssessment=null,this.setupTypePackAdoptions=null,this.publish({status:"destroyed",connections:[]}),this.listeners.clear()}}cleanupBase(e){this.base===e&&(this.stopBase?.(),this.stopBase=void 0,e.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,n={}){let i=this.lifecycleBase();return i.ok?i.value.select(e,n):i}clearSelection(e={}){let n=this.lifecycleBase();return n.ok?(n.value.clearSelection(e),O(void 0)):n}forget(e){let n=this.lifecycleBase();return n.ok?(n.value.forget(e),O(void 0)):n}authorize(e,n={}){return this.withLifecycleBase(n,async(i,o,r)=>{let s=await i.authorize(e,{...n,...o});return s.ok&&s.value.kind==="connected"&&this.lifecycleCurrent(r)&&await this.refresh(!0,o),s})}handleAuthorizationCallback(e,n){let i=String(e),o=this.startOperation!==null&&this.options.selection.authorizationCallback()===i;return this.withLifecycleBase(n,async(r,s,a)=>{if(o){let l=r.getSnapshot();return l.status==="ready"?O(l.connection):b(w("collection_not_ready","Authorization did not produce a ready collection."))}let c=await r.handleAuthorizationCallback(i,s);return c.ok&&this.lifecycleCurrent(a)&&await this.refresh(!0,s),c})}completeAuthorization(e,n){let i=e===void 0?mn():String(e),o=this.startOperation!==null&&this.options.selection.authorizationCallback()===i;return this.withLifecycleBase(n,async(r,s,a)=>{if(o){let l=r.getSnapshot();return l.status==="ready"?O(l.connection):b(w("collection_not_ready","Authorization did not produce a ready collection."))}let c=await r.handleAuthorizationCallback(i,s);return c.ok&&this.lifecycleCurrent(a)&&await this.refresh(!0,s),c})}ensureCapabilities(e,n){return this.withLifecycleBase(n,(i,o,r)=>{Z(this.manifest.requirements,{...n,capabilities:e});let s=this.manifest.requirements?.capabilities,a=new Set([...s?.required??[],...s?.optional??[]]);return e.some(c=>!a.has(c))?Promise.resolve(b(w("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:[...a]}}]}}))):i.ensureCapabilities(e,o).then(async c=>(c.ok&&c.value.kind==="connected"&&this.lifecycleCurrent(r)&&await this.refresh(!0,o),c))})}ensureOperations(e,n){return this.withLifecycleBase(n,async(i,o,r)=>{Z(this.manifest.requirements,{...n,operations:e});let s=await i.ensureOperations(e,o);return s.ok&&s.value.kind==="connected"&&this.lifecycleCurrent(r)&&await this.refresh(!0,o),s})}applyCollectionSetup(e){return this.withLifecycleBase(e,(n,i,o)=>this.applyCollectionSetupStarted(i,o))}async applyCollectionSetupStarted(e,n){if(this.snapshot.status!=="setup_review_required"||!this.setupAssessment)return b(w("collection_not_ready","There is no reviewed collection setup to apply."));if(!this.setupAssessment.applicable)return b(w("collection_not_ready","Resolve the collection setup conflicts before applying this update."));let i=this.connection();if(!i)return b(w("collection_not_ready","The collection is not ready."));let o=this.verificationGeneration,r=this.setupAssessment,s={...this.collectionSetupInput(this.setupTypePackAdoptions??void 0),expectedAssessmentDigest:r.assessmentDigest,expectedCollectionRevision:r.collectionRevision,expectedProvisionDigest:r.provisionDigest,allowTypePackDowngrades:r.typePacks.filter(c=>c.status==="downgrade").map(c=>c.desired.id)},a=await i.applyCollectionSetup(s,e);return this.lifecycleCurrent(n)?o!==this.verificationGeneration||this.connection()!==i?b(w("collection_not_ready","The selected collection changed during setup.")):a.ok?(this.setupAssessment=null,this.setupTypePackAdoptions=null,await this.verifySetup(this.context(i),++this.verificationGeneration,e),O(this.snapshot)):(a.problem.code==="application_declaration_mismatch"&&(this.setupAssessment=null,this.setupTypePackAdoptions=null,this.publish({status:"authorization_required",...this.context(i)})),a):!a.ok&&a.problem.code==="operation_outcome_unknown"?b(a.problem):b(w("session_destroyed",zt("session_destroyed")))}async refresh(e=!1,n){if(!this.base||!this.manifest)return;let i=this.base.getSnapshot();this.readinessController?.abort(),this.verificationGeneration+=1;let o=this.verificationGeneration;if(this.setupAssessment=null,this.setupTypePackAdoptions=null,i.status==="unselected"){this.publish({status:"unselected",connections:i.connections});return}if(i.status==="unavailable"){this.publish(i);return}if(i.status!=="ready")return;let r=this.context(i.connection);if(this.connect.connectionApplicationId(i.collectionId)!==this.application?.id){this.publish({status:"authorization_required",...r});return}if(!r.capabilities.requiredAvailable||r.readiness?.files.state==="requires_authorization"||!rr(this.manifest,r.info)){this.publish({status:"authorization_required",...r});return}if(!((this.manifest.provisions?.type_packs.length??0)>0||(this.manifest.provisions?.configuration?.length??0)>0)){let l=this.publishReady(r,o,n);e&&await l;return}let a=an(this.manifest,i.collectionId);r.readiness?.contracts.state!=="checking"&&this.verificationStore.read(a)===Ii(this.manifest)?this.publish({status:"ready",verification:"cached",...r}):this.publish({status:"checking_setup",...r});let c=this.verifySetup(r,o,n);e&&await c}async verifySetup(e,n,i){let o=this.connection(),r=this.requireManifest();if(!o||o.collectionId!==e.collectionId)return;let s=this.collectionSetupInput(),a=r.requirements?.contracts??[],c=new AbortController;this.readinessController?.abort(),this.readinessController=c;let l=null,u=e.readiness&&a.length?Mi({...e,readiness:e.readiness,contracts:a,connection:o,controller:c,options:i,requestMs:this.timeouts.requestMs,isCurrent:()=>n===this.verificationGeneration&&this.connection()===o,publish:m=>{l={...m,...e}}}):Promise.resolve(!0),h=()=>c.abort(i?.signal?.reason);i?.signal?.aborted?h():i?.signal?.addEventListener("abort",h,{once:!0});let p,f;try{[p,f]=await Promise.all([At("setup-assessment",()=>o.assessCollectionSetup(s,{...i,signal:c.signal})),u])}catch(m){if(n!==this.verificationGeneration&&c.signal.aborted&&(m===c.signal.reason||m instanceof _&&m.code==="operation_cancelled"))return;throw m}finally{i?.signal?.removeEventListener("abort",h),c.abort(),this.readinessController===c&&(this.readinessController=void 0)}if(n===this.verificationGeneration){if(!p.ok){this.publish(p.problem.code==="application_declaration_mismatch"?{status:"authorization_required",...e}:{status:"blocked",problem:p.problem,...e});return}if(!p.value.applicable){let m=sr(p.value);if(Object.keys(m).length>0){if(p=i?await o.assessCollectionSetup(this.collectionSetupInput(m),i):await o.assessCollectionSetup(this.collectionSetupInput(m)),n!==this.verificationGeneration)return;if(!p.ok){this.publish(p.problem.code==="application_declaration_mismatch"?{status:"authorization_required",...e}:{status:"blocked",problem:p.problem,...e});return}this.setupTypePackAdoptions=m}}if(n===this.verificationGeneration){if(p.value.status!=="current"){this.setupAssessment=p.value,this.verificationStore.remove(an(r,e.collectionId)),this.publish({status:"setup_review_required",update:Dc(p.value,r.provisions?.type_packs??[]),...e});return}if(this.verificationStore.write(an(r,e.collectionId),Ii(r)),e.readiness&&(e.readiness.setup={state:"current",evidence:[{source:"authority",fact:"Collection setup assessment is current."}]}),!f){l&&this.publish(l);return}await this.publishReady(e,n,i,!0)}}}async publishReady(e,n,i,o=!1){let r=this.requireManifest().requirements?.contracts??[];if(!o&&e.readiness&&r.length){let s=this.connection();if(!s||s.collectionId!==e.collectionId)return;this.publish({status:"checking_setup",...e});let a=new AbortController;this.readinessController?.abort(),this.readinessController=a;try{if(!await Mi({...e,readiness:e.readiness,contracts:r,connection:s,controller:a,options:i,requestMs:this.timeouts.requestMs,isCurrent:()=>n===this.verificationGeneration&&this.connection()===s,publish:c=>this.publish({...c,...e})}))return}finally{this.readinessController===a&&(this.readinessController=void 0)}}n===this.verificationGeneration&&this.publish({status:"ready",verification:"verified",...e})}collectionSetupInput(e){let n=this.requireManifest(),i=this.requireApplication();return ar(n,qt(i.family_identity),`sha256:${i.manifest_digest}`,e)}context(e){return or(this.requireManifest(),e.collectionId,e.info(),this.connect.connections())}publish(e){if(!(this.snapshot.status==="destroyed"&&e.status!=="destroyed")&&("readiness"in e&&e.readiness&&(e={...e,readiness:ir(e.readiness,e.status,e.status==="ready"?e.verification:void 0)}),JSON.stringify(this.snapshot)!==JSON.stringify(e))){this.snapshot=e;for(let n of this.listeners)n()}}lifecycleBase(){let e=this.snapshot.status;if(this.startOperation||e==="starting")return b(w("session_starting","The application session is still starting."));if(this.snapshot.status==="start_failed")return b(this.snapshot.problem);if(this.base)return O(this.base);let n=e==="destroyed"?"session_destroyed":"session_not_started";return b(w(n,zt(n)))}async withLifecycleBase(e,n){let i=this.beginLifecycleOperation(e),o=Oe(i.options,this.timeouts.requestMs),r={signal:o.signal,timeoutMs:null};try{let s=this.startOperation;if(s){let l=await this.waitForStart(s,r,null);if(!l.ok)return l}if(!this.lifecycleCurrent(i.generation))return b(w("session_destroyed",zt("session_destroyed")));let a=this.lifecycleBase();if(!a.ok)return a;let c=await n(a.value,r,i.generation);return this.lifecycleCurrent(i.generation)?c:this.destroyedOutcome(c)}catch(s){if(s instanceof _)return this.lifecycleCurrent(i.generation)?b(s.problem):s.problem.code==="operation_outcome_unknown"?b(s.problem):b(w("session_destroyed",zt("session_destroyed")));throw s}finally{o.dispose(),i.dispose()}}beginLifecycleOperation(e={}){let n=new AbortController,i=()=>n.abort(e.signal?.reason);return e.signal?.aborted?i():e.signal?.addEventListener("abort",i,{once:!0}),this.operationControllers.add(n),{generation:this.lifecycleGeneration,options:{...e,signal:n.signal},dispose:()=>{e.signal?.removeEventListener("abort",i),this.operationControllers.delete(n)}}}lifecycleCurrent(e){return this.snapshot.status!=="destroyed"&&e===this.lifecycleGeneration}destroyedOutcome(e){return!e.ok&&e.problem.code==="operation_outcome_unknown"?e:b(w("session_destroyed",zt("session_destroyed")))}requireManifest(){if(!this.manifest)throw new Error("Start the application session before using it.");return this.manifest}requireApplication(){if(!this.application)throw new Error("Start the application session before using it.");return this.application}};function Fc(t,e){let n=(e.provisions?.type_packs.length??0)>0||(e.provisions?.configuration?.length??0)>0;return[...ii(e.requirements),...t.contract_version===2&&n?Bt:[]]}function zc(t,e){let n=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:t.manifest.name??e.desired.id,status:e.status,applicable:e.applicable,assessmentDigest:e.assessmentDigest,...e.current?{currentVersion:e.current.version}:{},desiredVersion:e.desired.version,resources:e.resources,contractSetups:e.contractSetups,canApply:e.applicable,reason:n}}function Dc(t,e){let n=t.typePacks.map(r=>{let s=e.find(a=>a.manifest.id===r.desired.id);if(!s)throw new Error(`Collection setup returned undeclared type pack '${r.desired.id}'.`);return zc(s,r)}),i=t.configuration.filter(r=>r.action!=="current").length,o=t.status==="conflict"?"Existing collection policy conflicts with this application's required setup.":`This application requires ${i} configuration change${i===1?"":"s"} and ${n.length} definition update${n.length===1?"":"s"}.`;return{status:t.status,applicable:t.applicable,assessmentDigest:t.assessmentDigest,collectionRevision:t.collectionRevision,provisionDigest:t.provisionDigest,configuration:t.configuration,typePacks:n,canApply:t.applicable,reason:o}}function zt(t){return t==="session_destroyed"?"This application session has been destroyed.":t==="session_starting"?"The application session is still starting.":"Start the application session before using it."}function Lc(){return typeof localStorage<"u"?{read:t=>localStorage.getItem(t),write:(t,e)=>localStorage.setItem(t,e),remove:t=>localStorage.removeItem(t)}:new Dt}var Uc="mdbase-connect-identities",ot="application-identities",Di=BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Nc=Di/2n,rt=class{database=null;async create(e){let n=await Gr(e),i=await this.open();return await Vr(i,o=>o.add(n)),n}async get(e){let n=await this.open();return await jc(n.transaction(ot).objectStore(ot).get(e))??null}async delete(e){let n=await this.open();await Vr(n,i=>i.delete(e))}open(){if(typeof indexedDB>"u")throw new Le("Persistent application identity requires browser IndexedDB or an injected identity store.");return this.database||(this.database=new Promise((e,n)=>{let i=indexedDB.open(Uc,1);i.onupgradeneeded=()=>{i.result.objectStoreNames.contains(ot)||i.result.createObjectStore(ot,{keyPath:"handle"})},i.onerror=()=>n(i.error),i.onsuccess=()=>e(i.result)})),this.database}},st=class{records=new Map;async create(e){if(this.records.has(e))throw new Error(`Application identity already exists: ${e}`);let n=await Gr(e);return this.records.set(e,n),n}async get(e){return this.records.get(e)??null}async delete(e){this.records.delete(e)}},Le=class extends Error{constructor(e){super(e),this.name="ApplicationIdentityStoreError"}};async function at(t){return ko(t.signingPublicKey)}async function Lt(t,e){if(t.installation_signing_public_key!==e.signingPublicKey||t.application_installation_id!==await at(e))throw new Error("Application authorization identity does not match its binding.");let n=Qc(new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},e.signingPrivateKey,xo(t))));return{binding:t,signature:Hr(n)}}async function bn(t,e,n){let i=`application-installation:v2:${e}:${n.id}`,o=await t.get(i);if(o)return o;try{return await t.create(i)}catch(r){let s=await t.get(i);if(s)return s;throw r}}async function Gr(t){let e=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign","verify"]),n=Hr(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:t,signingPrivateKey:o,signingPublicKey:n}}function jc(t){return new Promise((e,n)=>{t.onerror=()=>n(t.error),t.onsuccess=()=>e(t.result)})}function Vr(t,e){return new Promise((n,i)=>{let o=t.transaction(ot,"readwrite");e(o.objectStore(ot)).onerror=()=>i(o.error),o.onerror=()=>i(o.error),o.onabort=()=>i(o.error??new Error("Identity transaction aborted.")),o.oncomplete=()=>n()})}function Bc(t){let e=new Uint8Array(t.reduce((i,o)=>i+o.byteLength,0)),n=0;for(let i of t)e.set(i,n),n+=i.byteLength;return e}function Hr(t){return btoa(String.fromCharCode(...t)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}function Qc(t){if(t.byteLength!==64)throw new Error("Application authorization signature is invalid.");let e=Kc(t.slice(32));if(e===0n||e>=Di)throw new Error("Application authorization signature is invalid.");return e<=Nc?t:Bc([t.slice(0,32),Vc(Di-e,32)])}function Kc(t){return BigInt(`0x${Gc(t)}`)}function Vc(t,e){let n=t.toString(16).padStart(e*2,"0");return Uint8Array.from({length:e},(i,o)=>Number.parseInt(n.slice(o*2,o*2+2),16))}function Gc(t){return[...t].map(e=>e.toString(16).padStart(2,"0")).join("")}var Ut={id:"mdbase.person",version:"2.0.0"};function Yr(t,e,n){return k(e,n.requestMs,async i=>{let o=await n.authorizedToken(i.signal);if(!o)throw d("not_authorized","Authorize this collection before reading people.");let r=await ae(`${n.serverUrl}/v1/authorities/${encodeURIComponent(n.collectionId)}/${t}`,{headers:{authorization:`Bearer ${o.accessToken}`},signal:i.signal,credentials:"omit",cache:"no-store",redirect:"error"},"temporarily_unavailable","Account identity information is unavailable.");if(r.status===404)throw d("unsupported_operation","This Connect server does not support people discovery.");if(r.status===401)throw d("authorization_expired","The application authorization is no longer active.");if(r.status===403)throw d("access_denied","This application was not approved to read this identity information.");if(!r.ok)throw d("temporarily_unavailable","Account identity information is unavailable.");return E(r,"invalid_operation_response","Connect returned invalid identity information.")})}var ct=class{constructor(e){this.context=e}context;current(e){return I(()=>this.readCurrent(e),Xt)}members(e){return I(()=>this.readMembers(e),Xt)}directory(e={}){return I(async()=>{let{members:n="if-approved",...i}=e,[o,r,s]=await Promise.all([this.readCurrent(i),n==="omit"?void 0:this.readMembers(i).catch(a=>{if(!(n==="if-approved"&&a instanceof _&&a.code==="access_denied"))throw a}),this.readRecords(i)]);return{account:o,me:Hc(s,o),people:s.people,invalid:s.invalid.map(({path:a,reason:c})=>({path:a,reason:c})),...r?{members:r}:{}}},de)}async readCurrent(e){let n=await this.context.request("identity",e),i=Jr(n),o=n.person_settings_url;if(o===void 0)return i;if(typeof o!="string"||!Xr(o))throw _n();return{...i,personSettingsUrl:o}}async readMembers(e){let n=await this.context.request("members",e);if(!n||typeof n!="object"||!("members"in n)||!Array.isArray(n.members))throw _n();return n.members.map(i=>{let o=Jr(i);if(!i||typeof i!="object"||!("role"in i)||i.role!=="owner"&&i.role!=="editor"&&i.role!=="viewer")throw _n();return{...o,role:i.role}})}async readRecords(e){let i=Wr(await this.context.describe(e)).contracts.find(c=>c.id===Ut.id&&c.version===Ut.version),o=new Map;for(let c of i?.implementations??[])for await(let l of this.context.queryPages({contract:{...Ut,type:c.typeName}},{signal:e.signal,pageSize:200}))for(let u of Wr(l).results){let h=o.get(u.path)??[];h.push({typeName:c.typeName,value:u.frontmatter??{}}),o.set(u.path,h)}let r=[],s=[];for(let[c,l]of o){let u=l.map(f=>$c(f.value)),h=u[0],p=u.find(f=>"reason"in f);p&&"reason"in p?s.push({path:c,reason:p.reason,claims:l.flatMap(f=>$r(f.value))}):u.some(f=>JSON.stringify(f)!==JSON.stringify(h))?s.push({path:c,reason:"Its Person implementations project different values.",claims:l.flatMap(f=>$r(f.value))}):h&&!("reason"in h)&&r.push({path:c,...h,typeNames:l.map(f=>f.typeName).sort()})}let a=(c,l)=>c.path.localeCompare(l.path);return{people:r.sort(a),invalid:s.sort(a)}}};function Hc(t,e){let n=t.invalid.filter(o=>o.claims.some(r=>vn(r,e)));if(n.length)return{status:"invalid",paths:n.map(o=>o.path)};let i=t.people.filter(o=>o.identities.some(r=>vn(r,e)));return i.length===0?{status:"unlinked"}:i.length>1?{status:"ambiguous",paths:i.map(o=>o.path)}:{status:"linked",person:i[0]}}function vn(t,e){return t.issuer===e.issuer&&t.subject===e.subject}function $c(t){let{name:e,identities:n=[]}=t;if(typeof e!="string"||!e.trim())return{reason:"It needs a non-blank name."};if(!Array.isArray(n))return{reason:"Its account identities must be a list."};let i=[];for(let o of n){if(!o||typeof o!="object"||Array.isArray(o)||typeof o.issuer!="string"||typeof o.subject!="string"||!o.subject.trim())return{reason:"Each account identity needs an exact issuer and subject."};i.push({issuer:o.issuer,subject:o.subject})}return{name:e,identities:i}}function $r(t){return(Array.isArray(t.identities)?t.identities:[]).flatMap(n=>n&&typeof n=="object"&&!Array.isArray(n)&&"issuer"in n&&"subject"in n&&typeof n.issuer=="string"&&typeof n.subject=="string"?[{issuer:n.issuer,subject:n.subject}]:[])}function Wr(t){if(!t.ok)throw new _(t.problem);return t.value}function Jr(t){if(!t||typeof t!="object"||!("issuer"in t)||!("subject"in t)||!("name"in t)||typeof t.issuer!="string"||typeof t.subject!="string"||typeof t.name!="string"||!t.subject.trim()||!t.name.trim()||!Xr(t.issuer))throw _n();return{issuer:t.issuer,subject:t.subject,name:t.name}}function Xr(t){try{let e=new URL(t);return e.protocol==="https:"||e.protocol==="http:"}catch{return!1}}function _n(){return d("invalid_operation_response","Connect returned invalid identity information.")}var Ae=class{operations=new Map;run(e,n,i,o){if(n?.signal?.aborted)return Promise.reject(ne(n.signal));let r=this.operations.get(e)??this.begin(e,o);return this.wait(e,r,n,i)}begin(e,n){let i=new AbortController,o={controller:i,waiters:0,settled:!1,promise:void 0};return o.promise=Promise.resolve().then(()=>n(i.signal)).finally(()=>{o.settled=!0,this.operations.get(e)===o&&this.operations.delete(e)}),this.operations.set(e,o),o}async wait(e,n,i,o){n.waiters+=1;try{return await k(i,o,()=>n.promise)}finally{n.waiters-=1,n.waiters===0&&!n.settled&&this.operations.get(e)===n&&(this.operations.delete(e),n.controller.abort())}}};var Zr=new Set(["files-stat-v1","query-record-revisions-v1","read-many-documents-v1","query-metadata-v1","contract-query-v1","link-resolution-options-v1"]),Li=Object.freeze([]);function Ue(t){if(t===void 0)return Li;if(!Array.isArray(t)||t.some(e=>typeof e!="string"))throw d("invalid_operation_response","The authority returned invalid feature capabilities.");return Object.freeze([...new Set(t.filter(e=>Zr.has(e)))])}var Cn=class{constructor(e,n){this.discovery=e;this.timeoutMs=n}discovery;timeoutMs;lifetime;generation=0;cached;pending=new Ae;get capabilities(){return this.refreshLifetime(),this.cached??Li}supports(e,n){return I(()=>k(n,this.timeoutMs,async i=>{if(!Zr.has(e))return!1;for(;;){this.refreshLifetime();let o=this.generation,r=this.cached??await this.pending.run(String(o),{signal:i.signal,timeoutMs:null},null,s=>this.discover(s));if(this.refreshLifetime(),o===this.generation)return i.signal.aborted||(this.cached=r),r.includes(e)}}),Ve)}invalidate(){this.cached=void 0,this.lifetime=void 0}refreshLifetime(){let e=this.discovery.lifetime();e!==this.lifetime&&(this.lifetime=e,this.generation+=1,this.cached=void 0)}async discover(e){if(this.discovery.operations().includes("describe")){let i=await this.discovery.describe({signal:e,timeoutMs:null,coordination:{coalesce:!1}});if(!i.ok)throw new _(i.problem);return Ue(i.value.authorityCapabilities)}let n=this.discovery.fileCapability();if(n?.actions.includes("list")){let i=n.scope.kind==="selected_folders"?n.scope.folders[0]:void 0,o=await this.discovery.filesPage(i,e);return Object.freeze(o.filter(r=>r==="files-stat-v1"))}return Li}};function es(t){let e={...t.projections},n=new Map,i=new Set([...Object.keys(e),...(t.select??[]).filter(s=>typeof s=="string").map(s=>s.replace(/^projection\./,""))]),o=t.select?.map((s,a)=>{if(typeof s=="string")return s;let c=`connect_select_${a}`;for(;i.has(c);)c+="_";return i.add(c),e[c]={expression:t.where?`(${t.where}) ? (${s.expression}) : null`:s.expression},n.set(c,s.name),`projection.${c}`});return{projections:e,aliases:n,select:o,field:s=>{for(let[a,c]of n)if(c===s)return a;return s}}}function Ui(t){let e=es(t);return{...t.output?{output:t.output}:{},...t.types?{types:t.types}:{},...t.timezone?{timezone:t.timezone}:{},...t.context?{context:t.context}:{},...Object.keys(e.projections).length?{projections:Object.fromEntries(Object.entries(e.projections).map(([n,i])=>[n,{expr:i.expression,...i.description?{description:i.description}:{}}]))}:{},...t.where?{where:t.where}:{},...e.select?{select:e.select}:{},...t.orderBy?{order_by:t.orderBy.map(n=>({...n,field:e.field(n.field)}))}:{},...t.groupBy?{group_by:t.groupBy.map(n=>({...n,field:e.field(n.field)}))}:{},...t.summaryFunctions?{summary_functions:Object.fromEntries(Object.entries(t.summaryFunctions).map(([n,i])=>[n,{expr:i.expression,...i.description?{description:i.description}:{}}]))}:{},...t.summaries?{summaries:t.summaries.map(n=>({...n,field:e.field(n.field)}))}:{},...t.limit===void 0?{}:{limit:t.limit},...t.offset===void 0?{}:{offset:t.offset},...t.pagination?{pagination:t.pagination}:{},...t.cursor?{cursor:t.cursor}:{},...t.snapshot?{snapshot:t.snapshot}:{},...t.includeBody===void 0?{}:{include_body:t.includeBody},...t.frontmatterMode?{frontmatter_mode:t.frontmatterMode}:{},...t.contract?{contract:t.contract}:{}}}function wn(t){return{id:t.id,version:t.version,digest:t.digest,type:t.type,implementationDigest:t.implementation_digest}}function Ni(t){let{effective_frontmatter:e,contract:n,...i}=t;return{...i,...e===void 0?{}:{effectiveFrontmatter:e},...n?{contract:wn(n)}:{}}}function Wc(t){if(!t||typeof t.path!="string"||typeof t.revision!="string"||!t.revision||!Array.isArray(t.types)||t.types.some(e=>typeof e!="string")||!t.values||typeof t.values!="object"||Array.isArray(t.values)||Object.keys(t).some(e=>!["path","types","revision","values","contract"].includes(e))||t.contract!==void 0&&(!t.contract||["id","version","digest","type","implementation_digest"].some(e=>typeof t.contract[e]!="string")))throw d("invalid_operation_response","The authority returned an invalid revision-bearing metadata row.");return{path:t.path,types:t.types,revision:t.revision,values:t.values,...t.contract?{contract:wn(t.contract)}:{}}}function ji(t,e,n){if(!t||!Array.isArray(t.results)||t.output!==e)throw d("invalid_operation_response","The authority returned an invalid query output mode.");let i=n?es(n).aliases:new Map;i.size&&(t={...t,results:t.results.map(r=>({...r,...r.values?{values:Object.fromEntries(Object.entries(r.values).map(([s,a])=>[i.get(s)??s,a]))}:{}}))});let o=t.meta?{...typeof t.meta.total_count=="number"?{totalCount:t.meta.total_count}:{},...t.meta.total_count_outcome===void 0?{}:{totalCountOutcome:t.meta.total_count_outcome},hasMore:t.meta.has_more,...t.meta.cursor?{cursor:t.meta.cursor}:{},...t.meta.snapshot?{snapshot:t.meta.snapshot}:{}}:void 0;return e==="metadata"?{output:e,results:t.results.map(r=>Wc(r)),...o?{meta:o}:{}}:{results:t.results.map(r=>Ni(r)),...o?{meta:o}:{}}}function Rn(t){if(!t||t.protocol_version!==1||typeof t.collection_id!="string"||typeof t.display_name!="string"||typeof t.spec_version!="string"||!Array.isArray(t.operations)||!Array.isArray(t.types)||!Array.isArray(t.contracts))throw d("invalid_operation_response","The authority returned an invalid collection description.");return{authorityCapabilities:Ue(t.authority_capabilities),protocolVersion:t.protocol_version,collectionId:t.collection_id,displayName:t.display_name,specVersion:t.spec_version,operations:t.operations,changeCursor:t.change_cursor,types:t.types,contracts:t.contracts.map(e=>({contractType:e.contract_type,id:e.id,version:e.version,digest:e.digest,schema:e.schema,...e.binding_schema?{bindingSchema:e.binding_schema}:{},implementations:e.implementations.map(n=>({typeName:n.type_name,typeVersion:n.type_version,...n.type_path?{typePath:n.type_path}:{},digest:n.digest,fields:n.fields,...n.binding?{binding:n.binding}:{}}))})),...t.configuration?{configuration:t.configuration}:{}}}var On=class{constructor(e,n){this.transport=e;this.requestTimeoutMs=n}transport;requestTimeoutMs;generation=0;description;describing;get schemaGeneration(){return this.generation}invalidate(){this.generation+=1,this.description=void 0,this.describing=void 0}describe(e={}){return I(()=>k(e,this.requestTimeoutMs,async()=>{if(!e.fresh&&this.description&&Date.now()<this.description.expiresAt)return O(this.description.value);if(!this.describing){this.description=void 0;let n=this.generation,i=I(()=>k({},this.requestTimeoutMs,o=>this.transport.operation("describe",{},{signal:o.signal,timeoutMs:this.requestTimeoutMs})),Ot).then(o=>{if(!o.ok)return o;let r=Rn(o.value);return this.generation===n&&(this.description={value:r,expiresAt:Date.now()+6e4}),O(r,o.diagnostics)}).finally(()=>{this.describing===i&&(this.describing=void 0)});this.describing=i}return this.describing}),Ot).then(n=>n.ok?n.value:n)}};function Sn(t,e,n){let i=n,o=!1,r=()=>{if(!i)return;let a=i;i=void 0,t(a).catch(()=>{})},s=()=>{o||r()};return e?.addEventListener("abort",s,{once:!0}),{startRequest(){o=!0},finishRequest(a,c){c&&(i=a),o=!1,e?.aborted&&r()},dispose(){e?.removeEventListener("abort",s),r()}}}function Pn(t){if(t===void 0)return 1/0;if(!Number.isSafeInteger(t)||t<0)throw new TypeError("maxResults must be a non-negative safe integer.");return t}function An(t,e){return typeof t=="number"&&Number.isFinite(t)?Math.max(0,Math.floor(t)):e}function lt(t,e){return typeof t=="number"&&Number.isFinite(t)&&t>=1?Math.floor(t):e}async function*ts(t,e,n={},i={}){let{offset:o,limit:r,cursor:s,pagination:a,snapshot:c,...l}=n,u=An(o,0),h=lt(i.firstPageSize??i.pageSize??r,200),p=lt(i.pageSize??r,1e3),f=s,m=s!==void 0,P=Pn(i.maxResults),v=Sn(e,i.signal,s),y=c,R=0,g=0;try{for(;!i.signal?.aborted&&R<P;){v.startRequest();let A=f,z={signal:i.signal,timeoutMs:i.pageTimeoutMs,coordination:{...i.coordination,coalesce:!1}},S=g===0&&s===void 0&&a===void 0&&c===void 0&&n.output!=="metadata",T=await t({...l,...m?{}:{limit:Math.min(g===0?h:p,P-R)},...m?A?{cursor:A}:{pagination:"cursor"}:{offset:u,...y?{snapshot:y}:{},...!y&&a==="cursor"?{pagination:"cursor"}:{}},...!m&&!y&&S?{pagination:"cursor"}:{}},z);if(S&&!i.signal?.aborted&&!T.ok&&T.problem.code==="operation_invalid"&&(T=await t({...l,limit:Math.min(h,P-R),offset:u},z)),v.finishRequest(T.ok?T.value.meta?.cursor:void 0,T.ok),i.signal?.aborted)return;if(!T.ok){v.dispose(),yield T;return}let M=T.value,C=M.meta?.cursor;if(C?(m=!0,f=C):m&&(f=void 0),m&&M.meta?.hasMore&&!C){v.dispose(),yield b(w("invalid_operation_response","The collection authority omitted the cursor required for the next query page."));return}let N=M.meta?.snapshot;if(!m&&y&&N&&y!==N){v.dispose(),yield b(w("query_snapshot_changed","The collection query snapshot changed while paging. Refresh the query before continuing."));return}!m&&!y&&N&&(y=N);let G=P-R,j=M.results.length>G?M.results.slice(0,G):M.results;R+=j.length;let U=R>=P||!M.meta?.hasMore||M.results.length===0,Ie={...M.output?{output:M.output}:{},results:j,...M.meta?{meta:M.meta}:{},page:g,offset:u,loaded:R,complete:U,...C?{cursor:C}:{},...!m&&y?{snapshot:y}:{}};if(U&&v.dispose(),i.onProgress?.(Ie),yield O(Ie,T.diagnostics),U)return;u+=M.results.length,g+=1}}finally{v.dispose()}}async function is(t,e,n,i,o,r){if(o.revisions!==void 0&&typeof o.revisions!="boolean")throw new TypeError("revisions must be boolean.");let s=ns(o.batchSize??(o.revisions===!1?1e3:100),1e3,"batchSize"),a=ns(o.concurrency??4,4,"concurrency");if(o.coordination?.latestWins)throw new TypeError("readMany batches cannot use latestWins coordination.");if(o.includeBody!==void 0&&typeof o.includeBody!="boolean")throw new TypeError("includeBody must be boolean.");if(o.frontmatterMode!==void 0&&!["effective","persisted","both"].includes(o.frontmatterMode))throw new TypeError("Invalid frontmatterMode.");let c=[...i];try{return await k(o,r,async l=>{if(!c.length)return O({results:[],errors:[]});let u=pe({...o,timeoutMs:null,coordination:{...o.coordination,coalesce:!1}},l),h=[...new Set(c)],p=new Map,f=[],m=[],P=0,v=0,y=(g,A,z)=>{f.push({batch:g,paths:A,failure:z});for(let S of A)p.set(S,{status:"error",path:S,batch:g})},R=async()=>{for(;!l.signal.aborted&&v<h.length;){let g=o.revisions===!1?void 0:await n?.("read-many-documents-v1",u);if(g&&!g.ok)throw v=h.length,new _(g.problem);if(l.signal.aborted||v>=h.length)return;let A=g?.value===!0,z=A?Math.min(s,100):s,S=P++,T=h.slice(v,v+z);v+=T.length;let M={where:`file.path in ${JSON.stringify(T)}`,...o.types?{types:o.types}:{}};try{let C=T,N=[];if(A&&o.types!==void 0){let U=await t({...M,select:["file.path"],includeBody:!1},{...u,pageSize:T.length});if(!U.ok){y(S,T,U);continue}let Ie=new Set(U.value.results.map(Be=>Be.path));C=T.filter(Be=>Ie.has(Be)),N=U.diagnostics;let ie=await n("read-many-documents-v1",u);if(!ie.ok)throw new _(ie.problem);A=ie.value}if(!A){let U=await t({...M,...o.includeBody===void 0?{}:{includeBody:o.includeBody},...o.frontmatterMode?{frontmatterMode:o.frontmatterMode}:{}},{...u,pageSize:T.length});if(!U.ok){y(S,T,U);continue}m[S]=U.diagnostics;let Ie=new Map(U.value.results.map(ie=>[ie.path,ie]));for(let ie of T){let Be=Ie.get(ie);p.set(ie,Be?{status:"found",path:ie,record:Be}:{status:"missing",path:ie})}continue}if(l.signal.aborted)return;let G=C.length?await e(C,o.includeBody??!1,u):O({items:[]});if(!G.ok){y(S,T,G);continue}let j=Jc(G.value,C,S,o);for(let U of T)p.set(U,j.entries.get(U)??{status:"missing",path:U});m[S]=[...N,...G.diagnostics],j.errors.length&&f.push({batch:S,paths:j.errors.map(U=>U.path),failure:b(w("operation_invalid","Some batch records could not be read.",{details:{diagnostics:j.errors}}))})}catch(C){if(!(C instanceof _))throw C;let N=await I(async()=>{throw C},de);y(S,T,N)}}};return await Promise.all(Array.from({length:Math.min(a,h.length)},R)),O({results:c.map(g=>p.get(g)),errors:f.sort((g,A)=>g.batch-A.batch)},m.flat())})}catch(l){if(l instanceof _)return I(async()=>{throw l},de);throw l}}function Jc(t,e,n,i){(!t||!Array.isArray(t.items)||t.items.length!==e.length)&&Nt();let o=new Map,r=[];return t.items.forEach((s,a)=>{switch((!s||s.path!==e[a])&&Nt(),s.status){case"found":o.set(s.path,{status:"found",path:s.path,record:Yc(s.record,s.path,i)});break;case"missing":o.set(s.path,{status:"missing",path:s.path});break;case"error":(!s.error||typeof s.error.code!="string"||typeof s.error.message!="string")&&Nt(),o.set(s.path,{status:"error",path:s.path,batch:n}),r.push({severity:"error",code:s.error.code,message:s.error.message,path:s.path});break;default:Nt()}}),{entries:o,errors:r}}function Yc(t,e,n){(!t||t.path!==e||typeof t.revision!="string"||!t.revision||!Array.isArray(t.types)||t.types.some(o=>typeof o!="string")||!Bi(t.frontmatter)||!Bi(t.effective_frontmatter)||!Bi(t.file)||(n.includeBody??!1)&&typeof t.body!="string"||t.contract!==void 0)&&Nt();let i=n.frontmatterMode??"effective";return{path:t.path,revision:t.revision,types:t.types,file:t.file,...i!=="effective"?{frontmatter:t.frontmatter}:{},...i!=="persisted"?{effectiveFrontmatter:t.effective_frontmatter}:{},...n.includeBody?{body:t.body}:{}}}function Bi(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function Nt(){throw d("invalid_operation_response","The authority returned an invalid or incoherently bound document batch.")}function ns(t,e,n){if(!Number.isSafeInteger(t)||t<1||t>e)throw new TypeError(`${n} must be an integer between 1 and ${e}.`);return t}async function*os(t,e,n,i={}){let{offset:o,limit:r,cursor:s,...a}=n,c=An(o,0),l=lt(i.firstPageSize??i.pageSize??r,200),u=lt(i.pageSize??r,1e3),h=s,p=s!==void 0,f=Pn(i.maxResults),m=Sn(e,i.signal,s),P=0,v=0;try{for(;!i.signal?.aborted&&P<f;){m.startRequest();let y=h,R=await t({...a,...p?{}:{limit:Math.min(v===0?l:u,f-P)},...p&&y?{cursor:y}:{offset:c}},{signal:i.signal,timeoutMs:i.pageTimeoutMs,coordination:{...i.coordination,coalesce:!1}});if(m.finishRequest(R.ok?R.value.meta.cursor:void 0,R.ok),i.signal?.aborted)return;if(!R.ok){m.dispose(),yield R;return}let g=R.value,A=g.meta.cursor;if(A?(p=!0,h=A):p&&(h=void 0),p&&g.meta.hasMore&&!A){m.dispose(),yield b(w("invalid_operation_response","The collection authority omitted the cursor required for the next saved-view page."));return}let z=f-P,S=g.results.length>z?g.results.slice(0,z):g.results;P+=S.length;let T=P>=f||!g.meta.hasMore||g.results.length===0,M={...g,results:S,page:v,offset:c,loaded:P,complete:T,...A?{cursor:A}:{}};if(T&&m.dispose(),i.onProgress?.(M),yield O(M,R.diagnostics),T)return;c+=g.results.length,v+=1}}finally{m.dispose()}}function rs(t){if(t!==!1)return{initialDelayMs:Math.max(0,t?.initialDelayMs??500),maxDelayMs:Math.max(0,t?.maxDelayMs??15e3),multiplier:Math.max(1,t?.multiplier??2),...t?.maxAttempts===void 0?{}:{maxAttempts:Math.max(0,t.maxAttempts)}}}var Tn=class{constructor(e,n,i,o,r){this.watch=e;this.input=i;this.watchStartTimeoutMs=r;this.pendingChanges=[...o],this.currentStatus={state:"connected",cursor:n,recovered:!1};let s=i.lifetimeSignal;if(s?.aborted)this.close();else if(s){let a=()=>this.close();s.addEventListener("abort",a,{once:!0}),this.removeLifetimeAbort=()=>s.removeEventListener("abort",a)}this.controller.signal.aborted||this.run(n)}watch;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,n,i){this.changes.add(e),n&&(this.statuses.add(n),n(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),n&&this.statuses.delete(n),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 n=!0,i=this.watch({cursor:e,pollIntervalMs:this.input.pollIntervalMs,retry:this.input.retry,signal:this.controller.signal,timeoutMs:this.watchStartTimeoutMs,onStatus:o=>{if(n&&o.state==="connecting"){n=!1;return}n=!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 n of this.statuses)n(e)}};var dt=class{constructor(e,n=$e,i){this.transport=e;this.requestTimeoutMs=n;this.supportsAuthorityFeature=i;this.descriptions=new On(e,n)}transport;requestTimeoutMs;supportsAuthorityFeature;descriptions;lastSchemaCursor=-1;get schemaGeneration(){return this.descriptions.schemaGeneration}operation(e,n,i){return I(()=>this.transport.operation(e,n,i),Ve)}describe(e){return this.descriptions.describe(e)}async changes(e={},n){let i=await this.rawOperation("changes",e,Zt,n),o=B(i,tr);if(o.ok){let r=o.value.events.filter(nr);(o.value.reset||r.some(s=>s.cursor>this.lastSchemaCursor))&&(this.descriptions.invalidate(),this.lastSchemaCursor=o.value.cursor)}return o}async read(e,n){let i=await this.envelopeOperation("read",Xc(e),le,n);return B(i,Mn)}readMany(e,n={}){return is((i,o)=>this.queryAll(i,o),(i,o,r)=>this.envelopeOperation("read",{paths:i,include_body:o,include_document:!1},le,r),this.supportsAuthorityFeature,e,n,this.requestTimeoutMs)}observe(e={},n={}){return new Ge(this,e,n,this.supportsAuthorityFeature)}async query(e={},n){if(e.output!==void 0&&e.output!=="metadata")return b(w("invalid_request","Unknown query output mode."));if(e.output!=="metadata"){let o=await this.envelopeOperation("query",Ui(e),de,n);return B(o,r=>ji(r,void 0,e))}let i=await I(()=>k(n,this.requestTimeoutMs,async o=>{let r=pe({...n,timeoutMs:null},o);if(e.includeBody)throw d("invalid_request","Metadata queries cannot include a body.");let s=await this.supportsAuthorityFeature?.("query-metadata-v1",r);if(s&&!s.ok)throw new _(s.problem);if(!s?.value)throw d("unsupported_operation","This authority does not support metadata queries. Use an ordinary query on legacy authorities.");let a=await this.envelopeOperation("query",Ui(e),de,r);return B(a,c=>ji(c,e.output,e))}),de);return i.ok?i.value:i}async*queryPages(e={},n={}){yield*ts((i,o)=>this.query(i,o),i=>this.releaseQueryCursor(i,e.output),e,n)}async queryAll(e={},n={}){let i=Oe(n,this.requestTimeoutMs),o=[],r,s=[];try{let a={firstPageSize:n.firstPageSize,pageSize:n.pageSize,maxResults:n.maxResults,signal:i.signal,pageTimeoutMs:null,coordination:n.coordination},c=e.output==="metadata"?this.queryPages(e,{...a,onProgress:n.onProgress}):this.queryPages(e,{...a,onProgress:n.onProgress});for await(let u of c){if(!u.ok)return u;let h=u.value;o.push(...h.results),r=h,s.push(...u.diagnostics)}if(i.signal.aborted)throw ne(i.signal);let l=r?{...r.meta?.totalCount===void 0?r.meta?.hasMore?{}:{totalCount:o.length}:{totalCount:r.meta.totalCount},...r.meta?.hasMore&&r.meta.totalCountOutcome?{totalCountOutcome:r.meta.totalCountOutcome}:{},hasMore:r.meta?.hasMore??!1,...r.snapshot?{snapshot:r.snapshot}:{}}:void 0;return e.output==="metadata"?O({output:"metadata",results:o,...l?{meta:l}:{}},s):O({results:o,...l?{meta:l}:{}},s)}catch(a){if(a instanceof _)return b(a.problem);throw a}finally{i.dispose()}}async listViews(e){let n=await this.envelopeOperation("list_views",{},le,e);return B(n,i=>({views:i.views,meta:{totalCount:i.meta.total_count}}))}async executeView(e,n){let i=await this.envelopeOperation("execute_view",e,le,n);return B(i,sl)}async*executeViewPages(e,n={}){yield*os((i,o)=>this.executeView(i,o),i=>this.releaseQueryCursor(i),e,n)}readViewSource(e,n){return this.envelopeOperation("read_view_source",e,le,n)}createViewSource(e,n){return this.envelopeOperation("create_view_source",e,H,n)}updateViewSource(e,n){return this.envelopeOperation("update_view_source",Qi(e),H,n)}deleteViewSource(e,n){return this.envelopeOperation("delete_view_source",Qi(e),H,n)}async create(e,n){let i=await this.envelopeOperation("create",Zc(e),H,n);return B(i,Mn)}async update(e,n){let i=await this.envelopeOperation("update",el(e),H,n);return B(i,Mn)}async delete(e,n){let i=await this.envelopeOperation("delete",ss(e),H,n);return B(i,hs)}async preflightDelete(e,n){let i=await this.envelopeOperation("delete",{...ss(e),check_backlinks:!0,dry_run:!0},H,n);return B(i,il)}async rename(e,n){let i=await this.envelopeOperation("rename",as(e),H,n);return B(i,ol)}async preflightRename(e,n){let i=await this.envelopeOperation("rename",{...as(e),dry_run:!0},H,n);return B(i,rl)}validate(e={},n){return this.envelopeOperation("validate",e,le,n)}readType(e,n){return this.envelopeOperation("read_type",e,Ce,n)}createType(e,n){return this.envelopeOperation("create_type",e,Ce,n)}updateType(e,n){return this.envelopeOperation("update_type",Qi(e),Ce,n)}async assessTypePack(e,n){let i=await this.envelopeOperation("assess_type_pack",us(e),Ce,n);return B(i,Vi)}async applyTypePack(e,n){let i=await this.envelopeOperation("apply_type_pack",tl(e),Ce,n);return B(i,cl)}async assessCollectionSetup(e,n){let i=await this.envelopeOperation("assess_collection_setup",ps(e),Ce,n);return B(i,ds)}async applyCollectionSetup(e,n){let i=await this.envelopeOperation("apply_collection_setup",nl(e),Ce,n);return B(i,o=>({assessment:ds(o.assessment),receipt:ll(o.receipt)}))}async listTimers(e,n){let i=await this.rawOperation("list_timers",{namespace:e},le,n);return B(i,o=>({namespace:o.namespace,timers:o.timers.map(Ki)}))}async putTimer(e,n){let i=await this.rawOperation("put_timer",{namespace:e.namespace,criterion_id:e.criterionId,timer:cs(e.timer)},H,n);return B(i,Ki)}cancelTimer(e,n){return this.rawOperation("cancel_timer",e,H,n)}async reconcileTimers(e,n){let i=await this.rawOperation("reconcile_timers",{namespace:e.namespace,criterion_id:e.criterionId,timers:e.timers.map(cs)},H,n);return B(i,o=>({namespace:o.namespace,timers:o.timers.map(Ki),cancelledIds:o.cancelled_ids}))}async*watch(e={}){let n=e.cursor,i=Math.max(100,e.pollIntervalMs??1e3),o=rs(e.retry),r=0,s=!1;for(e.onStatus?.({state:"connecting",...n===void 0?{}:{cursor:n}});!e.signal?.aborted;){let a=await this.changes(n===void 0?{}:{after:n,limit:200},{signal:e.signal,timeoutMs:e.timeoutMs});if(!a.ok){let u=a.problem;if(e.signal?.aborted)return;if(!o||u.recovery!=="retry"){yield a;return}if(s=!1,r+=1,o.maxAttempts!==void 0&&r>o.maxAttempts){yield a;return}let h=Math.min(o.maxDelayMs,Math.round(o.initialDelayMs*o.multiplier**(r-1)));e.onStatus?.({state:"reconnecting",...n===void 0?{}:{cursor:n},attempt:r,retryInMs:h,problem:u});try{await re(h,e.signal)}catch{if(!e.signal?.aborted)throw d("operation_failed","Watch retry delay failed unexpectedly.")}continue}let c=a.value;if(n===void 0){n=c.cursor;continue}if(c.reset){let u=w("change_cursor_reset","The collection change cursor expired. Refresh collection state before subscribing again.");e.onStatus?.({state:"reset_required",cursor:n,problem:u}),yield b(u);return}let l=r>0;r=0,(!s||l)&&e.onStatus?.({state:"connected",cursor:n,recovered:l}),s=!0;for(let u of c.events)yield O(u);if(n=c.cursor,!c.hasMore)try{await jo(i,e.signal)}catch{if(!e.signal?.aborted)throw d("operation_failed","Watch polling delay failed unexpectedly.")}}}rawOperation(e,n,i,o){return I(()=>this.transport.operation(e,n,o),i)}async releaseQueryCursor(e,n){try{await k({timeoutMs:2e3},null,async i=>{let o=pe({signal:i.signal,timeoutMs:null,coordination:{coalesce:!1}},i);if(n){let r=await this.supportsAuthorityFeature?.("query-metadata-v1",o);if(!r?.ok||!r.value)return}await this.envelopeOperation("query",{release_cursor:e,...n?{output:n}:{}},de,o)})}catch{}}async envelopeOperation(e,n,i,o){let r=await I(()=>this.transport.operation(e,n,o),i);if(!r.ok)return r;let s=r.value;return s.valid?(["create_type","update_type","apply_type_pack","apply_collection_setup","create_view_source","update_view_source","delete_view_source"].includes(e)&&this.descriptions.invalidate(),O(s.result,s.diagnostics)):b(Ke(s))}};function B(t,e){if(!t.ok)return t;try{return O(e(t.value),t.diagnostics)}catch(n){if(n instanceof _)return b(n.problem);throw n}}function Xc(t){return{path:t.path,...t.contract?{contract:t.contract}:{},...t.includeDocument===void 0?{}:{include_document:t.includeDocument}}}function Zc(t){return{...t.path?{path:t.path}:{},...t.type?{type:t.type}:{},...t.contract?{contract:t.contract}:{},...t.frontmatter?{frontmatter:t.frontmatter}:{},...t.body===void 0?{}:{body:t.body},...t.ifRevision?{if_revision:t.ifRevision}:{},...t.includeDocument===void 0?{}:{include_document:t.includeDocument}}}function el(t){return{path:t.path,...t.contract?{contract:t.contract}:{},...t.ifRevision?{if_revision:t.ifRevision}:{},...t.includeDocument===void 0?{}:{include_document:t.includeDocument},...t.document===void 0?{patch:t.patch,...t.body===void 0?{}:{body:t.body}}:{document:t.document}}}function ss(t){return{path:t.path,...t.contract?{contract:t.contract}:{},...t.checkBacklinks===void 0?{}:{check_backlinks:t.checkBacklinks},...t.ifRevision?{if_revision:t.ifRevision}:{}}}function as(t){return{from:t.from,to:t.to,...t.contract?{contract:t.contract}:{},...t.updateRefs===void 0?{}:{update_refs:t.updateRefs},...t.ifRevision?{if_revision:t.ifRevision}:{},...t.includeDocument===void 0?{}:{include_document:t.includeDocument}}}function Qi(t){let{ifRevision:e,...n}=t;return{...n,...e?{if_revision:e}:{}}}function us(t){return{provision:t.provision,installed_by:t.installedBy,...t.adoptResources?{adopt_resources:t.adoptResources}:{},...t.preserveSeedTargets?{preserve_seed_targets:t.preserveSeedTargets}:{},...t.targetOverrides?{target_overrides:t.targetOverrides}:{},...t.contractSetups?{contract_setups:t.contractSetups.map(fs)}:{}}}function tl(t){return{...us(t),expected_assessment_digest:t.expectedAssessmentDigest,...t.allowDowngrade===void 0?{}:{allow_downgrade:t.allowDowngrade}}}function ps(t){return{application_id:t.applicationId,declaration_digest:t.declarationDigest,requirements:t.requirements,provisions:{configuration:t.provisions.configuration,type_packs:t.provisions.typePacks},...t.contractSetups?{contract_setups:t.contractSetups.map(fs)}:{},...t.typePackAdoptions?{type_pack_adoptions:t.typePackAdoptions}:{}}}function nl(t){return{...ps(t),expected_assessment_digest:t.expectedAssessmentDigest,expected_collection_revision:t.expectedCollectionRevision,expected_provision_digest:t.expectedProvisionDigest,...t.allowTypePackDowngrades?{allow_type_pack_downgrades:t.allowTypePackDowngrades}:{}}}function hs(t){return{path:t.path,deleted:t.deleted,...t.broken_links?{brokenLinks:t.broken_links}:{}}}function il(t){return{...hs(t),deleted:!1,dryRun:!0,wouldDelete:!0}}function ol(t){let{references_updated:e,...n}=t;return{...Mn(n),from:t.from,to:t.to,...e?{referencesUpdated:e}:{}}}function rl(t){return{from:t.from,to:t.to,dryRun:!0,wouldRename:!0,...t.references_affected?{referencesAffected:t.references_affected}:{},...t.warnings?{warnings:t.warnings}:{}}}function cs(t){return{id:t.id,fire_at:t.fireAt,...t.data===void 0?{}:{data:t.data}}}function Ki(t){return{id:t.id,fireAt:t.fire_at,...t.data===void 0?{}:{data:t.data},criterionId:t.criterion_id,generation:t.generation,status:t.status,createdAt:t.created_at,updatedAt:t.updated_at,firedAt:t.fired_at}}function fs(t){return t.mode==="starter"?t:{contract:t.contract,mode:"existing",type_name:t.typeName,type_revision:t.typeRevision,fields:t.fields,...t.binding?{binding:t.binding}:{}}}function Mn(t){let{effective_frontmatter:e,contract:n,...i}=t;return{...i,effectiveFrontmatter:e,...n?{contract:wn(n)}:{}}}function sl(t){return{results:t.results.map(e=>{let n=Ni(e);if(!n.effectiveFrontmatter)throw new Error("Saved view result omitted canonical effective frontmatter.");return{...n,effectiveFrontmatter:n.effectiveFrontmatter}}),meta:{totalCount:t.meta.total_count,hasMore:t.meta.has_more,...t.meta.cursor?{cursor:t.meta.cursor}:{},view:t.meta.view,...t.meta.context?{context:t.meta.context}:{},...t.meta.groups?{groups:t.meta.groups}:{}}}}function ls(t){return{source:t.source,target:t.target,kind:t.kind,mode:t.mode,action:t.action,digest:t.digest,...t.current_digest?{currentDigest:t.current_digest}:{},...t.installed_digest?{installedDigest:t.installed_digest}:{},...t.adopted_from_digest?{adoptedFromDigest:t.adopted_from_digest}:{},...t.upgrade_baseline?{upgradeBaseline:t.upgrade_baseline}:{},...t.reason?{reason:t.reason}:{}}}function In(t){return{id:t.id,version:t.version,digest:t.digest,installedBy:t.installed_by,resources:t.resources.map(e=>({source:e.source,target:e.target,kind:e.kind,mode:e.mode,digest:e.digest,...e.adopted_from_digest?{adoptedFromDigest:e.adopted_from_digest}:{},...e.origin_digest?{originDigest:e.origin_digest}:{}}))}}function al(t){return t.mode==="starter"?t:{contract:t.contract,mode:"existing",typeName:t.type_name,typeRevision:t.type_revision,fields:t.fields,...t.binding?{binding:t.binding}:{}}}function Vi(t){return{status:t.status,applicable:t.applicable,assessmentDigest:t.assessment_digest,...t.current?{current:In(t.current)}:{},desired:In(t.desired),resources:t.resources.map(ls),lock:t.lock,contractSetups:{choices:t.contract_setups.choices.map(al),resources:t.contract_setups.resources.map(ls)}}}function cl(t){return{...Vi(t),receipt:In(t.receipt),cleanupDeferred:t.cleanup_deferred}}function ds(t){return{status:t.status,applicable:t.applicable,applicationId:t.application_id,declarationDigest:t.declaration_digest,provisionDigest:t.provision_digest,collectionRevision:t.collection_revision,finalCollectionRevision:t.final_collection_revision,configuration:t.configuration,typePacks:t.type_packs.map(Vi),finalResourceRevisions:t.final_resource_revisions,assessmentDigest:t.assessment_digest}}function ll(t){return{applicationId:t.application_id,declarationDigest:t.declaration_digest,provisionDigest:t.provision_digest,assessmentDigest:t.assessment_digest,collectionRevision:t.collection_revision,configuration:t.configuration,typePacks:t.type_packs.map(In),cleanupDeferred:t.cleanup_deferred}}async function Gi(t,e,n,i){for(;;){te(n);try{let o=await t("GET",`?${e}`,void 0,n);if(o?.protocol_version!==1||o.type!=="files_page"||!Array.isArray(o.files)||o.next!==void 0&&(typeof o.next!="string"||!o.next))throw d("invalid_operation_response","The authority returned an invalid file page.");return Ue(o.authority_capabilities),o}catch(o){let r=Re(o);if(r.code!=="file_index_warming")throw r;i?.(),await re(500,n)}}}async function*ms(t,e,n,i){let o=Oe(n,i);try{gs(t());let r;do{let s=new URLSearchParams({protocol_version:"1",...n.folder?{folder:n.folder}:{},...r?{after:r}:{},...n.pageSize?{limit:String(Zo(n.pageSize))}:{}}),a=await Gi(e,s,o.signal,n.onIndexing);for(let c of a.files)te(o.signal),yield he(c);r=a.next}while(r)}finally{o.dispose()}}function ys(t,e,n,i,o,r,s){return I(()=>k(r,s,async a=>{if(gs(t()),!o||typeof o!="object"||Object.keys(o).length!==1||!(Object.hasOwn(o,"path")&&typeof o.path=="string"||Object.hasOwn(o,"fileId")&&typeof o.fileId=="string"&&wi.test(o.fileId)))throw d("invalid_request","File stat requires exactly one path or UUID fileId.");if(o.path!==void 0&&(o.path.length>1024||o.path.includes("\\")||o.path.split("/").some(u=>!u||u.startsWith("."))))throw d("invalid_request","File stat requires a collection-relative file path.");let c=await n("files-stat-v1",{signal:a.signal,timeoutMs:null});if(!c.ok)throw new _(c.problem);if(te(a.signal),c.value){let u=await e("POST","stat",{protocol_version:1,type:"stat_file",...o.path!==void 0?{path:o.path}:{file_id:o.fileId}},a.signal);if(u?.protocol_version!==1||u.type!=="file_stat"||u.file===void 0)throw d("invalid_operation_response","The authority returned an invalid file stat.");if(u.file===null)return null;let h=he(u.file);if(o.path!==void 0?kn(h.path)!==kn(o.path):h.fileId.toLowerCase()!==o.fileId.toLowerCase())throw d("invalid_operation_response","The authority returned a stat for a different file.");return h}let l=o.path?.includes("/")?o.path.slice(0,o.path.lastIndexOf("/")):void 0;for await(let u of i({folder:l,signal:a.signal,timeoutMs:null}))if(te(a.signal),o.path!==void 0?kn(u.path)===kn(o.path):u.fileId.toLowerCase()===o.fileId.toLowerCase())return u;return te(a.signal),null}),Ve)}function gs(t){if(!t?.actions.includes("list"))throw d("not_authorized","This connection is not authorized to list files.")}function kn(t){return Array.from(t.normalize("NFC"),e=>e.toLowerCase()).join("").normalize("NFC")}var xn=class{constructor(e){this.context=e}context;async registerNotifications(e){return k(e,this.context.requestTimeoutMs,n=>this.registerNotificationsWithinBudget(e,n.signal))}async registerNotificationsWithinBudget(e,n){let i=await this.context.authorizedToken(n);if(!i)throw d("not_authorized","Connect this application before enabling notifications.");let r=(await this.context.register(n)).notifications?.criteria.map(y=>y.id)??[],s=[...new Set(e.criteria??r)],a=s.find(y=>!r.includes(y));if(a)throw d("notification_criterion_not_declared",`The application manifest does not declare notification criterion ${a}.`);if(s.length===0)throw d("notifications_not_declared","This application manifest does not declare any notification criteria.");let c=await ae(`${this.context.serverUrl}/v1/notifications/vapid-public-key`,{signal:n},"notifications_unavailable","Push notifications are unavailable."),l=await E(c,"invalid_operation_response","Connect returned an invalid notification key response.");if(!c.ok)throw D(l,"notifications_unavailable","Push notifications are unavailable.",c.status);let u=await e.serviceWorker.pushManager.getSubscription();u||(u=await e.serviceWorker.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:cn(l.public_key)}));let h=u.toJSON();if(!h.endpoint||!h.keys?.p256dh||!h.keys.auth)throw d("invalid_push_subscription","The browser returned an incomplete push subscription.");let p=F(this.context.storage.getItem(this.context.notificationKey())),f=e.installationId??p?.installationId??se(24),m=await ae(`${this.context.serverUrl}/v1/notifications/channels`,{method:"POST",headers:{authorization:`Bearer ${i.accessToken}`,"content-type":"application/json"},body:JSON.stringify({installation_id:f,criteria:s,subscription:{endpoint:h.endpoint,expirationTime:h.expirationTime??null,keys:h.keys}}),signal:n},"notification_registration_failed","Could not register push notifications."),P=await E(m,"invalid_operation_response","Connect returned an invalid notification registration response.");if(!m.ok)throw D(P,"notification_registration_failed","Could not register push notifications.",m.status);p?.channelId&&p.channelId!==P.channel_id&&fetch(`${this.context.serverUrl}/v1/notifications/channels/${p.channelId}`,{method:"DELETE",headers:{authorization:`Bearer ${i.accessToken}`},signal:n}).catch(()=>{});let v={channelId:P.channel_id,installationId:f,criteria:s};return this.context.storage.setItem(this.context.notificationKey(),JSON.stringify(v)),v}async registerNativeNotifications(e){return k(e,this.context.requestTimeoutMs,n=>this.registerNativeNotificationsWithinBudget(e,n.signal))}async registerNativeNotificationsWithinBudget(e,n){let i=await this.context.authorizedToken(n);if(!i)throw d("not_authorized","Connect this application before enabling notifications.");let o=await this.context.register(n);if(o.notifications?.native_delivery?.mode!=="managed_fcm")throw d("managed_fcm_not_declared","This application does not declare Connect-managed native notifications.");let r=o.notifications.criteria.map(m=>m.id),s=[...new Set(e.criteria??r)],a=s.find(m=>!r.includes(m));if(a)throw d("notification_criterion_not_declared",`The application manifest does not declare notification criterion ${a}.`);if(s.length===0)throw d("notifications_not_declared","This application manifest does not declare any notification criteria.");let c=this.context.notificationKey("fcm"),l=F(this.context.storage.getItem(c)),u=e.installationId??l?.installationId??se(24),h=await ae(`${this.context.serverUrl}/v1/notifications/channels`,{method:"POST",headers:{authorization:`Bearer ${i.accessToken}`,"content-type":"application/json"},body:JSON.stringify({installation_id:u,criteria:s,transport:"fcm",token:e.token}),signal:n},"notification_registration_failed","Could not register native notifications."),p=await E(h,"invalid_operation_response","Connect returned an invalid native notification response.");if(!h.ok)throw D(p,"notification_registration_failed","Could not register native notifications.",h.status);l?.channelId&&l.channelId!==p.channel_id&&this.deleteNotificationChannel(l.channelId,i.accessToken,n).catch(()=>{});let f={channelId:p.channel_id,installationId:u,transport:"fcm",criteria:s};return this.context.storage.setItem(c,JSON.stringify(f)),f}async unregisterNativeNotifications(e={}){return k(e,this.context.requestTimeoutMs,n=>this.unregisterNativeNotificationsWithinBudget(n.signal))}async unregisterNativeNotificationsWithinBudget(e){let n=this.context.notificationKey("fcm"),i=F(this.context.storage.getItem(n)),o=await this.context.authorizedToken(e);if(i?.channelId&&!o)throw d("not_authorized","Reconnect this application before disabling native notifications.");i?.channelId&&o&&await this.deleteNotificationChannel(i.channelId,o.accessToken,e),this.context.storage.removeItem(n)}async unregisterNotifications(e,n={}){return k(n,this.context.requestTimeoutMs,i=>this.unregisterNotificationsWithinBudget(e,i.signal))}async unregisterNotificationsWithinBudget(e,n){let i=F(this.context.storage.getItem(this.context.notificationKey())),o=await this.context.authorizedToken(n);if(i?.channelId&&!o)throw d("not_authorized","Reconnect this application before disabling push notifications.");if(i?.channelId&&o){let s=await ae(`${this.context.serverUrl}/v1/notifications/channels/${i.channelId}`,{method:"DELETE",headers:{authorization:`Bearer ${o.accessToken}`},signal:n},"notification_unregistration_failed","Could not unregister push notifications.");if(!s.ok&&s.status!==404){let a=await E(s,"invalid_operation_response","Connect returned an invalid notification response.");throw D(a,"notification_unregistration_failed","Could not unregister push notifications.",s.status)}}this.context.storage.removeItem(this.context.notificationKey()),await(await e?.pushManager.getSubscription())?.unsubscribe()}async deleteNotificationChannel(e,n,i){let o=await ae(`${this.context.serverUrl}/v1/notifications/channels/${e}`,{method:"DELETE",headers:{authorization:`Bearer ${n}`},signal:i},"notification_unregistration_failed","Could not unregister push notifications.");if(!o.ok&&o.status!==404){let r=await E(o,"invalid_operation_response","Connect returned an invalid notification response.");throw D(r,"notification_unregistration_failed","Could not unregister push notifications.",o.status)}}};async function bs(t,e){let n=new TextEncoder().encode(`${t}
4
+ ${e}`),i=new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",n));return Array.from(i,o=>o.toString(16).padStart(2,"0")).join("")}async function _s(t,e,n){let i=n?.path;return e==="update"&&typeof i=="string"?bs(t,i):void 0}async function vs(t,e,n){let i=await bs(e,n);return t.find(o=>o.operation==="update"&&o.recordDigest===i)?.requestId??null}async function En(t,e,n,i,o,r){if(!t.authority)throw d("not_remote_authority","This authorization has no remote authority endpoint.");let s=n===""||n.startsWith("?")?n:`/${n}`,a=`${t.authority.filesUrl}${s}`,c=i===void 0?void 0:JSON.stringify(i),l=await r(t,e,a,c,t.authority.accessToken);return fetch(a,{method:e,redirect:"error",headers:{authorization:`Bearer ${t.authority.accessToken}`,...c===void 0?{}:{"content-type":"application/json"},...l},...c===void 0?{}:{body:c},...o?{signal:o}:{}})}async function Cs(t,e,n,i,o,r,s,a=async c=>c){let c=t,l=await En(c,e,n,i,o,s);if(l.status===401&&c.refreshToken){if(c=await a(await r(o)),!c.authority||!c.fileCapability)throw d("authority_authorization_changed","Reconnect this collection before accessing its files.");l=await En(c,e,n,i,o,s)}let u=await E(l,"invalid_operation_response","The hosted authority returned an invalid file response.");if(!l.ok)throw D(u,"operation_failed","Collection file request failed.",l.status);return u}async function ws(t,e,n,i,o,r,s=async a=>a){let a=t,c=await En(a,"GET",e,void 0,i,r);if(c.status===401&&a.refreshToken){if(a=await s(await o(i)),!a.authority||!a.fileCapability)throw d("authority_authorization_changed","Reconnect this collection before accessing its files.");c=await En(a,"GET",e,void 0,i,r)}if(!c.ok){let u=await E(c,"invalid_operation_response","The hosted authority returned an invalid file range error response.");throw D(u,"operation_failed","Collection file range request failed.",c.status)}let l=c.headers.get("content-length");if(l===null||!/^(0|[1-9][0-9]*)$/u.test(l)||Number(l)!==n)throw await c.body?.cancel().catch(()=>{}),d("invalid_operation_response","The hosted file response declared an unexpected byte length.");if(!c.body)throw d("invalid_operation_response","The hosted file response did not contain a byte stream.");return c.body}var qn=class{constructor(e,n){this.namespace=e;this.onFinalRelease=n}namespace;onFinalRelease;leases=new Map;locks=dl();retainAutomaticallyRetiredKeys=this.locks===null;async acquire(e,n,i){let o=this.acquireLocal(e,n);if(!this.locks)return o;try{let r=await ul(this.locks,this.lockName(e,n),i);return Hi(()=>{r(),o()})}catch(r){throw o(),r}}deleteExclusive(e,n,i){this.retainAutomaticallyRetiredKeys||(this.locks?this.locks.request(this.lockName(e,n),{mode:"exclusive"},i).catch(()=>{}):this.has(e,n)||Promise.resolve().then(i).catch(()=>{}))}has(e,n){return this.leases.get(e)?.has(n)??!1}handles(e){return this.leases.get(e)?.keys()??[]}acquireLocal(e,n){let i=this.leases.get(e)??new Map;return i.set(n,(i.get(n)??0)+1),this.leases.set(e,i),Hi(()=>{let o=(i.get(n)??1)-1;o>0?i.set(n,o):(i.delete(n),i.size===0&&this.leases.delete(e),this.onFinalRelease(e,n))})}lockName(e,n){return`mdbase-connect:grant-key:${this.namespace}:${e}:${n}`}},Te=class{constructor(e,n){this.collectionId=e;this.acquire=n}collectionId;acquire;releases=new Map;async retain(e,n){let i=typeof e=="string"?e:e?.keyHandle;if(!i)return;let o=this.releases.get(i);o||(o=this.acquire(this.collectionId,i,n),this.releases.set(i,o));try{await o}catch(r){throw this.releases.get(i)===o&&this.releases.delete(i),this.release(),r}}release(){for(let e of this.releases.values())e.then(n=>n());this.releases.clear()}};async function W(t,e,n){for(;;){let i=t();if(!i)return null;await e.retain(i,n);let o=t();if(!o)return null;if(o.keyHandle===i.keyHandle)return o}}function dl(){let t=typeof navigator>"u"?void 0:navigator.locks;return t||(typeof window<"u"||typeof globalThis.importScripts=="function"?null:void 0)}async function ul(t,e,n){let i,o,r,s=new Promise((l,u)=>{i=l,o=u}),a=new Promise(l=>{r=l});return t.request(e,{mode:"shared",...n?{signal:n}:{}},async()=>{i(),await a}).catch(o),await s,Hi(r)}function Hi(t){let e=!1;return()=>{e||(e=!0,t())}}var pl="mdbase-connect file chunk 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,ge=class extends Error{constructor(n,i){super(i);this.code=n;this.name="FileTransferCryptoError"}code},ut=class t{constructor(e,n){this.binding=e;this.key=n}binding;key;static async open(e,n,i){Rs(i);let o=await e.get(n);if(!o||o.agreementPublicKey!==i.encryption.application_agreement_public_key)throw new q("missing_grant_key","The encrypted grant key is unavailable or does not match the file transfer grant.");let r=await Tt(o.agreementPrivateKey,i.encryption.connector_agreement_public_key);return t.fromSharedSecret(r,i)}static async fromSharedSecret(e,n){Rs(n);let i=await $i(e,n);return new t(n,i)}async encryptChunk(e,n,i){if(this.validateHeader(n),i.byteLength!==n.plaintext_length)throw new ge("plaintext_length_mismatch","File chunk plaintext length does not match its authenticated header.");let o=Vt(e,n),r=await crypto.subtle.encrypt({name:"AES-GCM",iv:Os(n.chunk_index),additionalData:zn(o),tagLength:128},this.key,zn(i));return vo({kind:e,header:n,payload:new Uint8Array(r)})}async decryptChunk(e){let n=Gt(e);this.validateHeader(n.header);let i=Vt(n.kind,n.header);try{let o=await crypto.subtle.decrypt({name:"AES-GCM",iv:Os(n.header.chunk_index),additionalData:zn(i),tagLength:128},this.key,zn(n.payload));return new Uint8Array(o)}catch{throw new ge("authentication_failed","The encrypted file chunk could not be authenticated.")}}validateHeader(e){let n=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!==n.collection_id||e.transfer_id!==this.binding.transferId||e.direction!==this.binding.direction||e.scope_epoch!==n.scope_epoch||e.key_id!==n.key_id)throw new ge("header_binding_mismatch","The file frame does not match its transfer encryption binding.")}};async function $i(t,e){let n=new TextEncoder().encode(hl(e)),i=await crypto.subtle.digest("SHA-256",n),o=await crypto.subtle.importKey("raw",t,"HKDF",!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:i,info:new TextEncoder().encode(pl)},o,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}function Rs(t){if(ye(t.encryption),!Fn.test(t.grantId)||!Fn.test(t.applicationId)||!Fn.test(t.authorityId)||!Fn.test(t.transferId)||t.direction!=="upload"&&t.direction!=="download")throw new ge("invalid_binding","The file transfer encryption binding is invalid.")}function hl(t){let e=t.encryption;return["mdbase-connect","file-transfer",1,e.suite,t.grantId,t.applicationId,e.connector_id,t.authorityId,e.collection_id,e.scope_epoch,e.key_id,t.transferId,t.direction].join("|")}function Os(t){if(!Number.isSafeInteger(t)||t<0)throw new ge("invalid_chunk_index","The file chunk index is invalid.");let e=new Uint8Array(new ArrayBuffer(12));return new DataView(e.buffer).setBigUint64(4,BigInt(t),!1),e}function zn(t){return t.buffer instanceof ArrayBuffer?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Uint8Array.from(t)}var Un=class{constructor(e){this.options=e}options;async control(e,n,i,o,r){let s=this.grantKeyLeases(e.collectionId);try{return e=await this.retainEntryToken(e,s,r),await this.controlAttempt(e,n,i,o,r,!1,0,s)}finally{s.release()}}async controlAttempt(e,n,i,o,r,s,a,c){pt(e);let l=Ji(n,i,o),u=await this.encryptControl(e,l),h,p=await this.options.shouldAttemptDirect(e);if(p){try{h=await fetch(`${this.options.loopbackUrl}/v1/files/control`,Pe({method:"POST",headers:{"content-type":"application/mdbase-connect+json"},body:JSON.stringify(u),signal:r}))}catch(f){if(r?.aborted)throw f;this.options.onDirectUnavailable()}if(h&&(!await Ze(h)||await He(h)))return h.ok&&this.options.onDirectAvailable(),this.decryptControlResponse(e,n,i,o,r,u,h,s,a,c);h&&this.options.onDirectUnavailable()}return p&&!ee("file_control",l)&&(e=e.expiresAt>Date.now()+3e4?e:await this.options.refreshAuthorization(r),e=await this.retainEntryToken(e,c,r),Ln(e),u=await this.encryptControl(e,l)),h=await this.sendRelayControl(e,u,r),await ml(h,e)&&(e=await this.options.refreshAuthorization(r),e=await this.retainEntryToken(e,c,r),Ln(e),u=await this.encryptControl(e,l),h=await this.sendRelayControl(e,u,r)),h.ok&&this.options.onRelayAvailable(),this.decryptControlResponse(e,n,i,o,r,u,h,s,a,c)}async decryptControlResponse(e,n,i,o,r,s,a,c,l,u){let h=await E(a,"invalid_operation_response","The collection authority returned an invalid file control response.");if(!a.ok){let m=D(h,"operation_failed","Collection file request failed.",a.status);if(tn(m)&&l<en)return await nn(l,r),this.controlAttempt(e,n,i,o,r,c,l+1,u);if(m.code==="fresh_request_required"&&!ee("file_control",Ji(n,i,o))&&!c)return this.controlAttempt(e,n,i,o,r,!0,l,u);throw m}let p=h?.envelope;if(!p)throw d("invalid_encrypted_response","The connector omitted its encrypted file response.");let f=await Xe(this.options.keyStore,e.keyHandle,Yi(e),s,p);if(!f.ok&&f.problem.code==="fresh_request_required"&&!ee("file_control",Ji(n,i,o))&&!c)return this.controlAttempt(e,n,i,o,r,!0,l,u);if(!f.ok){let m=bl(f.problem);if(tn(m)&&l<en)return await nn(l,r),this.controlAttempt(e,n,i,o,r,c,l+1,u);throw m}return f.result}async uploadChunk(e,n,i,o,r){let s=r??await this.localFileToken(e,"upload",o),a=this.grantKeyLeases(s.collectionId);try{let c=await this.retainEntryToken(s,a,o);return Wi(c,e,"upload"),await this.uploadChunkWithLease(c,a,e,n,i,o)}finally{a.release()}}async uploadChunkWithLease(e,n,i,o,r,s){let a=e,c=await Ss(this.options.keyStore,a,i,o,r),l;if(await this.options.shouldAttemptDirect(a)){try{l=await fetch(`${this.options.loopbackUrl}/v1/files/upload`,Pe(Ps(c,s)))}catch(u){if(s?.aborted)throw u;this.options.onDirectUnavailable()}if(l&&(!await Ze(l)||await He(l)))return l.ok&&this.options.onDirectAvailable(),fl(l,"Encrypted file chunk upload failed.");l&&this.options.onDirectUnavailable()}if(l=await this.sendRelayUpload(a,c,s),l.status===401&&a.refreshToken&&(a=await this.options.refreshAuthorization(s),a=await this.retainEntryToken(a,n,s),Ln(a),c=await Ss(this.options.keyStore,a,i,o,r),l=await this.sendRelayUpload(a,c,s)),!l.ok){let u=await E(l,"invalid_operation_response","The collection authority returned an invalid file upload response.");throw D(u,"operation_failed","Encrypted file chunk upload failed.",l.status)}this.options.onRelayAvailable()}async downloadChunk(e,n,i,o){let r=o??await this.localFileToken(e,"download",i),s=this.grantKeyLeases(r.collectionId);try{return r=await this.retainEntryToken(r,s,i),Wi(r,e,"download"),await this.downloadChunkWithLease(r,s,e,n,i)}finally{s.release()}}async downloadChunkWithLease(e,n,i,o,r){let s;if(await this.options.shouldAttemptDirect(e)){try{s=await fetch(`${this.options.loopbackUrl}/v1/files/download/${encodeURIComponent(e.grantId)}/${encodeURIComponent(i.transfer_id)}/${o}`,Pe({method:"GET",signal:r}))}catch(a){if(r?.aborted)throw a;this.options.onDirectUnavailable()}if(s&&(!await Ze(s)||await He(s)))return s.ok&&this.options.onDirectAvailable(),this.decryptDownloadResponse(e,i,o,s);s&&this.options.onDirectUnavailable()}return s=await this.sendRelayDownload(e,i,o,r),s.status===401&&e.refreshToken&&(e=await this.options.refreshAuthorization(r),e=await this.retainEntryToken(e,n,r),Ln(e),s=await this.sendRelayDownload(e,i,o,r)),s.ok&&this.options.onRelayAvailable(),this.decryptDownloadResponse(e,i,o,s)}async decryptDownloadResponse(e,n,i,o){if(!o.ok){let a=await E(o,"invalid_operation_response","The collection authority returned an invalid file download response.");throw D(a,"operation_failed","Encrypted file chunk download failed.",o.status)}if(o.headers.get("content-type")?.split(";",1)[0]!=="application/mdbase-connect-file")throw d("invalid_operation_response","The connector returned an invalid file response media type.");let r=new Uint8Array(await o.arrayBuffer()),s;try{gl(n,i,r),s=await(await Ts(this.options.keyStore,e,n)).decryptChunk(r)}catch(a){throw a instanceof _?a:d("invalid_operation_response","The connector returned an invalid encrypted file frame.",{cause:a})}if(s.byteLength!==Xi(n,i))throw d("invalid_operation_response","The connector returned a truncated file chunk.");return s}encryptControl(e,n){return pt(e),me(this.options.keyStore,e.keyHandle,Yi(e),"file_control",n)}sendRelayControl(e,n,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(n),signal:i})}sendRelayUpload(e,n,i){return fetch(`${this.options.serverUrl}/v1/authorities/${encodeURIComponent(e.collectionId)}/files/upload`,{...Ps(n,i),headers:{authorization:`Bearer ${e.accessToken}`,"content-type":"application/mdbase-connect-file"}})}sendRelayDownload(e,n,i,o){return fetch(`${this.options.serverUrl}/v1/authorities/${encodeURIComponent(e.collectionId)}/files/download/${encodeURIComponent(n.transfer_id)}/${i}`,{method:"GET",headers:{authorization:`Bearer ${e.accessToken}`},signal:o})}async localFileToken(e,n,i){let o=await this.options.authorizedToken(i);return Wi(o,e,n),o}grantKeyLeases(e){return new Te(e,this.options.acquireGrantKeyLease??(()=>Promise.resolve(()=>{})))}async retainEntryToken(e,n,i){if(!this.options.currentToken)return await n.retain(e,i),e;let o=await W(this.options.currentToken,n,i);if(o)return o;throw d("not_authorized","Reconnect this application to continue.")}};function Wi(t,e,n){if(!t||t.authority||!t.fileCapability||!t.encryption||!t.grantId||!t.keyHandle||e.direction!==n||e.protection!=="grant_aead_v1")throw d("not_authorized","This connection cannot use encrypted local file delivery.");Nn(e)}function Ln(t){if(t.authority||!t.fileCapability)throw d("not_authorized","This connection cannot use encrypted local file delivery.");pt(t)}async function Ss(t,e,n,i,o){let r=yl(e,n,i,o.byteLength);return(await Ts(t,e,n)).encryptChunk("upload_chunk",r,o)}function Ps(t,e){return{method:"POST",headers:{"content-type":"application/mdbase-connect-file"},body:Uint8Array.from(t).buffer,signal:e}}async function fl(t,e){if(t.ok)return;let n=await E(t,"invalid_operation_response","The collection authority returned an invalid file transfer response.");throw D(n,"operation_failed",e,t.status)}async function ml(t,e){return e.refreshToken?t.status===401?!0:t.status!==409?!1:(await E(t.clone(),"invalid_operation_response","The collection authority returned an invalid file response.").catch(()=>null))?.error?.code==="encryption_binding_stale":!1}function pt(t){if(!t.encryption||!t.grantId||!t.keyHandle)throw d("missing_grant_key","Reconnect this application to restore encrypted file access.")}function Yi(t){return pt(t),{grantId:t.grantId,applicationId:t.clientId,encryption:t.encryption}}function Ts(t,e,n){return pt(e),ut.open(t,e.keyHandle,{...Yi(e),authorityId:e.encryption.connector_id,transferId:n.transfer_id,direction:n.direction})}function yl(t,e,n,i){pt(t);let o=Nn(e),r=Xi(e,n);if(i!==r)throw d("invalid_request","The file chunk has the wrong byte length.");return{protocol_version:1,protection:"grant_aead_v1",grant_id:t.grantId,authority_id:t.encryption.connector_id,collection_id:t.collectionId,transfer_id:e.transfer_id,direction:e.direction,chunk_size:o,chunk_index:n,offset:n*o,plaintext_length:i,total_size:e.total_size,scope_epoch:t.encryption.scope_epoch,key_id:t.encryption.key_id}}function gl(t,e,n){let i=Gt(n),o=Xi(t,e),r=Nn(t);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!==t.total_size)throw d("invalid_operation_response","The connector returned a file frame for a different chunk.")}function bl(t){return L(t.code==="unknown"?t.server_code:t.code,t.message,{details:t.details,operationOutcome:t.operation_outcome??"rejected",traceId:t.trace_id})}function Ji(t,e,n){if(t==="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(t==="GET"&&i.length===2&&i[0]==="transfers")return As("get_file_transfer_status",i[1]);if(t==="DELETE"&&i.length===2&&i[0]==="transfers")return As("abort_file_transfer",i[1]);if(t==="POST"&&_l(n)){let o=e==="stat"?"stat_file":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"&&n.file_id===decodeURIComponent(i[0])?"move_file":i.length===2&&i[1]==="delete"&&n.file_id===decodeURIComponent(i[0])?"delete_file":null;if(o&&n.type===o)return{...n}}throw d("invalid_request","The file control request path is invalid.")}function As(t,e){return{protocol_version:1,type:t,transfer_id:decodeURIComponent(e)}}function Nn(t){if(t.strategy.kind!=="framed_chunks"||!Number.isSafeInteger(t.strategy.chunk_size)||t.strategy.chunk_size<=0)throw d("invalid_operation_response","The connector returned an invalid framed transfer strategy.");return t.strategy.chunk_size}function Xi(t,e){let n=Nn(t);if(!Number.isSafeInteger(e)||e<0||!Number.isSafeInteger(t.total_size)||t.total_size<0)throw d("invalid_request","The file chunk index is invalid.");let i=e*n;if(!Number.isSafeInteger(i)||i>=t.total_size)throw d("invalid_request","The file chunk index is outside the transfer.");return Math.min(n,t.total_size-i)}function _l(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var jn=class{constructor(e){this.options=e;this.local=new Un(e)}options;local;async control(e,n="",i,o){let r=await this.requireFileToken(o),s=r.token;try{return s.authority?await Cs(s,e,n,i,o,this.options.refreshAuthorization,this.options.authorityProofHeaders,r.retain):await this.local.control(s,e,n,i,o)}finally{r.release()}}async uploadChunk(e,n,i,o){let r=await this.requireFileToken(o);try{return await this.local.uploadChunk(e,n,i,o,r.token)}finally{r.release()}}async downloadChunk(e,n,i){let o=await this.requireFileToken(i);try{return await this.local.downloadChunk(e,n,i,o.token)}finally{o.release()}}async downloadHostedPart(e,n,i,o){let r=await this.requireFileToken(o),s=r.token;try{if(!s.authority)throw d("not_remote_authority","Hosted file delivery requires a remote authority endpoint.");return await ws(s,`downloads/${encodeURIComponent(e.transfer_id)}/parts/${n}`,i,o,this.options.refreshAuthorization,this.options.authorityProofHeaders,r.retain)}finally{r.release()}}async requireFileToken(e){let n=new Te(this.options.collectionId,this.options.acquireGrantKeyLease);try{await W(this.options.currentToken,n,e),await this.options.authorizedToken(e);let i=await W(this.options.currentToken,n,e);if(!i?.fileCapability)throw d("not_authorized","This connection has no file capability.");return{token:i,retain:async o=>{let r=await W(this.options.currentToken,n,e);if(r)return r;throw d("not_authorized","Reconnect this application to continue.")},release:()=>n.release()}}catch(i){throw n.release(),i}}};async function Ne(t,e,n,i,o,r){if(!e.authority?.proofPublicKey)return{};if(!e.keyHandle)throw d("missing_grant_key","Reconnect this application to restore remote authority request signing.");try{let s=new URL(i);return await ln(t,e.keyHandle,e.authority.proofPublicKey,{method:n,target:`${s.pathname}${s.search}`,body:o,credential:r})}catch(s){throw s instanceof q?L(s.code,s.message):s}}async function Ms(t){let e=t.current;if(!e?.refreshToken)throw d("not_authorized","Reconnect this application to continue.");if((e.refreshExpiresAt??0)<=Date.now())throw d("relay_authorization_expired","Direct access is still available on this computer, but using the relay requires reconnecting this application.");let n=e.refreshToken,i=`${t.serverUrl}/oauth/token`,o=new URLSearchParams({grant_type:"refresh_token",refresh_token:e.refreshToken,client_id:e.clientId}).toString(),r=e.authority?await Ne(t.keyStore,e,"POST",i,o,e.refreshToken):{},s=await fetch(i,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",...r},body:o,signal:t.signal}),a=await E(s,"invalid_token_response","The authorization service returned an invalid token response.");if(!s.ok){let c=t.currentToken();if(c?.refreshToken&&c.refreshToken!==n)return c;let l=xt(a)??a?.error?.code;throw Cl(s.status,l)?(t.directCapable(e)||t.removeToken(e.keyHandle),l==="invalid_grant"?d("authorization_expired",a?.error_description??a?.error?.message??"Reconnect this application to continue.",{status:s.status}):D(a,"authorization_expired","Reconnect this application to continue.",s.status)):D(a,"temporarily_unavailable","mdbase is temporarily unavailable. Try again in a few minutes.",s.status)}return t.storeTokenResponse(a,e.clientId,e.keyHandle)}var vl=new Set(["invalid_grant","invalid_client","unauthorized_client","invalid_token"]);function Cl(t,e){return t===401||typeof e=="string"&&vl.has(e)}var Bn=class{constructor(e,n){this.storage=e;this.baseKey=n}storage;baseKey;list(e){if(!e)return[];let n=F(this.storage.getItem(this.baseKey));if(Is(n)&&n.collectionId===e){let o=this.key(n.requestId);this.storage.getItem(o)||this.storage.setItem(o,JSON.stringify(n)),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=>F(this.storage.getItem(o))).filter(o=>Is(o)&&o.collectionId===e).sort((o,r)=>o.createdAt-r.createdAt||o.requestId.localeCompare(r.requestId))}find(e,n){return this.list(e).find(i=>i.requestId===n)??null}identifier(e){return e.mutation??_e(e.operation,e.request?.input??(e.operation==="sync"?{action:"mutate"}:{}))??(e.operation==="sync"?"sync:mutate":e.operation)}summary(e){return{requestId:e.requestId,operation:this.identifier(e),fingerprint:e.inputFingerprint,status:"outcome_unknown",createdAt:new Date(e.createdAt).toISOString()}}store(e){this.storage.setItem(this.key(e.requestId),JSON.stringify(e))}take(e){let n=this.key(e),i=F(this.storage.getItem(n));return this.storage.removeItem(n),i}key(e){return`${this.baseKey}:${encodeURIComponent(e)}`}};function Is(t){return!!(t&&typeof t.collectionId=="string"&&typeof t.requestId=="string"&&t.requestId.length>0&&Co(t.operation)&&typeof t.inputFingerprint=="string"&&Number.isFinite(t.createdAt)&&t.createdAt>0&&(t.envelope||t.request)&&(t.operation==="sync"||_e(t.operation,t.request?.input??{})!==null))}function ks({stored:t,collectionId:e,relayEncryption:n,invalidate:i,directCapable:o}){let r=F(t),s=(c,l="invalid_stored_grant")=>(i(typeof c=="string"?c:void 0,l),null);if(!r)return t&&s(),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(c=>typeof c!="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)))return s(r.keyHandle);let a=hn(r.scope);if(!a)return s(r.keyHandle);if(!fn(a))return s(r.keyHandle,"legacy_scope_reauthorization_required");if(r.fileCapability&&!pn(r.fileCapability)||r.authority&&!Fr(r.authority,r.collectionId))return s(r.keyHandle);if(n==="required"){if(r.authority){if(!r.keyHandle||!r.authority.proofPublicKey)return s(r.keyHandle)}else if(!r.grantId||!r.keyHandle||!zr(r.encryption,r.collectionId))return s(r.keyHandle)}return r.expiresAt<=Date.now()&&(!r.refreshToken||(r.refreshExpiresAt??0)<=Date.now())?o(r)?r:(i(r.keyHandle),null):r}async function Zi(t,e,n,i,o,r){if(!e.authority)throw d("not_remote_authority","This authorization has no remote authority endpoint.");let s=`${e.authority.syncUrl}/${i}`,a=o===void 0?void 0:JSON.stringify(o),c=await Ne(t,e,n,s,a,e.authority.accessToken);return fetch(s,{method:n,headers:{authorization:`Bearer ${e.authority.accessToken}`,...o===void 0?{}:{"content-type":"application/json"},...c},...a===void 0?{}:{body:a},signal:r})}async function xs(t,e,n,i,o){if(!e.encryption||!e.grantId||!e.keyHandle)throw d("authorization_binding_incompatible","The refreshed authorization no longer supports encrypted connector operations.",{details:{contract:"grant_encryption",required:[1],supported:e.encryption?[e.encryption.protocol_version]:[],peer:"connector",operation:n}});try{return await me(t,e.keyHandle,{grantId:e.grantId,applicationId:e.clientId,encryption:e.encryption},n,i,void 0,o)}catch(r){throw r instanceof q?L(r.code,r.message):r}}function Es(t,e){return!t||t.authority||!t.encryption||!t.grantId||!t.keyHandle||e==="disabled"?!1:typeof location>"u"||!t.applicationOrigin||t.applicationOrigin===zi()}async function qs(t,e,n){let i;try{i=await fetch(`${t}/v1/ready`,Pe({method:"GET",cache:"no-store",signal:n}))}catch{return!1}if(i.status===403)throw L("operation_failed","The connector rejected direct access from this application. Relay access remains available.",{status:i.status});let o=await E(i,"invalid_operation_response","The connector returned an invalid readiness response.").catch(()=>null);return i.ok&&o?.service==="mdbase-connect"&&o?.loopback_protocol_version===1&&o?.operation_transport_protocol_version===e}async function Fs(t,e){try{return{body:await E(t,"invalid_operation_response","The collection authority returned a response that is not valid JSON.")}}catch(n){if(!t.ok&&e&&wl(t.status))return{body:void 0,httpError:L("operation_failed","Collection operation failed.",{status:t.status,operationOutcome:"rejected"})};throw d("invalid_operation_response","The collection authority returned a response that is not valid JSON.",{cause:n})}}function wl(t){return t>=400&&t<500&&![408,425,429].includes(t)}var Qn=class{serverUrl;storage;keyStore;directAccessMode;loopbackUrl;collectionId;internals;onChange;timeouts;pendingMutationStore;files;refreshOperations=new Ae;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 Bn(this.storage,this.internals.pendingMutationKey(this.collectionId)),this.files=new jn({keyStore:this.keyStore,serverUrl:this.serverUrl,loopbackUrl:this.loopbackUrl,collectionId:this.collectionId,currentToken:()=>this.currentToken(),authorizedToken:n=>this.authorizedToken({signal:n,timeoutMs:null}),refreshAuthorization:n=>this.refreshAuthorization({signal:n,timeoutMs:null}),shouldAttemptDirect:n=>this.shouldAttemptDirect(n),onDirectAvailable:()=>{this.markDirectAvailable(),this.setRoute("direct")},onDirectUnavailable:()=>this.markDirectUnavailable(),onRelayAvailable:()=>this.setRoute("relay"),acquireGrantKeyLease:(n,i,o)=>this.internals.acquireGrantKeyLease(n,i,o),authorityProofHeaders:(n,i,o,r,s)=>Ne(this.keyStore,n,i,o,r,s)}),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 k(e,this.timeouts.watchStartMs,n=>this.checkDirectAccessWithinBudget(n.signal))}async checkDirectAccessWithinBudget(e){let n=this.currentToken();if(!this.directEligible(n))return this.setDirectStatus("disabled");let i=await Mt();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 k(e,this.timeouts.watchStartMs,n=>this.requestDirectAccessWithinBudget(n.signal))}async requestDirectAccessWithinBudget(e){let n=this.currentToken();return this.directCapable(n)?(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=>this.pendingMutationStore.summary(e))}async pendingUpdate(e){let n=this.currentToken()?.collectionId;return n?vs(this.storedPendingMutations(),n,e):null}pendingMutation(e){let n=this.storedPendingMutation(e);return n?this.pendingMutationStore.summary(n):null}async recoverPendingMutation(e,n){let i=this.storedPendingMutation(e);if(!i)throw d("no_pending_mutation","There is no interrupted mutation to resume.");return $(n,this.timeouts.requestMs,o=>this.performOperationWithinBudget(i.operation,i.request?.input??{},pe(n??{},o),i))}async performOperation(e,n,i={}){return $(i,this.timeouts.requestMs,o=>this.performOperationWithinBudget(e,n,pe(i,o)))}async performOperationWithinBudget(e,n,i,o,r=!1,s=0,a=!1){De(i.signal);let c=this.grantKeyLeases();try{let l=await W(()=>this.currentToken(),c,i.signal);if(!l)throw d("not_authorized","Connect this application before accessing a collection.");return await c.retain(o?.keyHandle,i.signal),await this.performLeasedOperation(l,e,n,i,c,o,r,s,a)}finally{c.release()}}async performLeasedOperation(e,n,i,o,r,s,a=!1,c=0,l=!1){if(!e.operations.includes(n))throw d("insufficient_access",`This connection does not allow ${n}.`,{details:{required_operations:[n],granted_operations:[...e.operations],missing_operations:[n]}});let u=await this.shouldAttemptDirect(e);if(!u){if(!await this.authorizedToken({signal:o.signal,timeoutMs:null}))throw d("not_authorized","Reconnect this application to continue.");let A=await W(()=>this.currentToken(),r,o.signal);if(!A)throw d("not_authorized","Reconnect this application to continue.");e=A}let h=s?.requestId??(_r(n,i)?crypto.randomUUID():void 0),p;try{p=await this.sendOperation(e,n,i,u,r,o,h,l)}catch(g){throw dn(g,o.signal,h!==void 0&&this.storedPendingMutation(h)!==null?h:void 0,e.authority?"hosted_provider_unavailable":"relay_unavailable")}let f=p.response,m=f.status===409&&(await E(f.clone(),"invalid_operation_response","The collection authority returned an invalid operation response.").catch(()=>null))?.error?.code==="encryption_binding_stale";if((f.status===401||m)&&e.refreshToken){if(p.pendingMutation&&(p.directDeliveryUncertain||p.encryptedRequest&&p.resumingMutation))throw d("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:p.requestId}});p.pendingMutation&&this.clearPendingMutation(p.requestId),e=await this.refreshAuthorization({signal:o.signal,timeoutMs:null});let g=await W(()=>this.currentToken(),r,o.signal);if(!g)throw d("not_authorized","Reconnect this application to continue.");e=g,u=await this.shouldAttemptDirect(e);try{p=await this.sendOperation(e,n,i,u,r,o,h,l)}catch(A){throw dn(A,o.signal,h!==void 0&&this.storedPendingMutation(h)!==null?h:void 0,e.authority?"hosted_provider_unavailable":"relay_unavailable")}f=p.response}let P=g=>Bo({error:g,attempt:p,completedRetries:c,signal:o.signal,knownRejectedMutationRetry:l,clearPending:A=>this.clearPendingMutation(A),retry:(A,z)=>this.performOperationWithinBudget(n,i,o,A,a,c+1,z)}),v;try{v=await Fs(f,e.authority!==void 0)}catch(g){throw p.pendingMutation?J(p.requestId,g):g}let y=v.body;if(!f.ok){let g=v.httpError??D(y,"operation_failed","Collection operation failed.",f.status),A=await P(g);if(A.retried)return A.result;if(g.code==="fresh_request_required"&&!p.pendingMutation&&!a)return this.performOperationWithinBudget(n,i,o,void 0,!0);throw p.pendingMutation&&g.outcomeUnknown?g:p.pendingMutation&&(p.directDeliveryUncertain||p.encryptedRequest&&p.resumingMutation)?J(p.requestId,g):(p.pendingMutation&&!p.directDeliveryUncertain&&this.clearPendingMutation(p.requestId),g.code==="direct_operation_rejected"&&g.status===403&&this.invalidateRejectedAuthorization(e),g)}if(p.encryptedRequest){let g=y?.envelope,A=p.pendingMutationRecord,z=A?.encryption??e.encryption,S=A?.grantId??e.grantId,T=A?.applicationId??e.clientId,M=A?.keyHandle??e.keyHandle;if(!g||!z||!S||!M)throw p.pendingMutation?J(p.requestId,new Error("Encrypted operation response was missing its envelope.")):d("invalid_encrypted_response","The relay did not return an encrypted connector response.");try{let C=await Xe(this.keyStore,M,{grantId:S,applicationId:T,encryption:z},p.encryptedRequest,g);if(!C.ok&&C.problem.code==="fresh_request_required"&&!p.pendingMutation&&!a)return this.performOperationWithinBudget(n,i,o,void 0,!0);if(!C.ok){let N=wr(C.problem);throw p.pendingMutation&&!N.outcomeUnknown&&this.clearPendingMutation(p.requestId),N}return p.pendingMutation&&this.clearPendingMutation(p.requestId),C.result}catch(C){throw C instanceof _?C:C instanceof q?p.pendingMutation?J(p.requestId,C):L(C.code,C.message):C}}let R=p.pendingMutationRecord?.request?.protocol_version??Y;if(y?.protocol_version!==R||y?.request_id!==p.requestId)throw p.pendingMutation?J(p.requestId,new Error("Operation response protocol or request ID did not match.")):d("invalid_operation_response","The collection authority returned a response for a different protocol request.");if(y.ok===!1){if(!gt(y.problem))throw p.pendingMutation?J(p.requestId,new Error("Operation rejection did not contain a canonical problem.")):d("invalid_operation_response","The collection authority returned an invalid operation problem.");let g=new _(y.problem),A=await P(g);if(A.retried)return A.result;throw p.pendingMutation&&!g.outcomeUnknown&&this.clearPendingMutation(p.requestId),g}if(y.ok!==!0||!("result"in y))throw p.pendingMutation?J(p.requestId,new Error("Successful operation response did not contain a result.")):d("invalid_operation_response","The collection authority returned an incomplete operation response.");return p.pendingMutation&&this.clearPendingMutation(p.requestId),y.result}async performAuthoritySyncRequest(e,n,i,o,r,s={}){return $(s,this.timeouts.syncMs,async a=>{let c=this.grantKeyLeases();try{let l=await W(()=>this.currentToken(),c,a.signal);l&&await this.authorizedToken({signal:a.signal,timeoutMs:null}),l=await W(()=>this.currentToken(),c,a.signal),zs(l,e,n);let u=await Zi(this.keyStore,l,i,o,r,a.signal);u.status===401&&l.refreshToken&&(l=await this.refreshAuthorization({signal:a.signal,timeoutMs:null}),l=await W(()=>this.currentToken(),c,a.signal),zs(l,e,n),u=await Zi(this.keyStore,l,i,o,r,a.signal));let h=await E(u,"invalid_operation_response","The collection authority returned an invalid synchronization response.");if(!u.ok)throw D(h,"sync_failed","Collection synchronization failed.",u.status);return h}catch(l){let u=i==="POST"&&o==="mutations"&&r&&typeof r=="object"&&typeof r.mutation_id=="string"?r.mutation_id:void 0;throw dn(l,a.signal,u,"hosted_provider_unavailable")}finally{c.release()}})}async sendOperation(e,n,i,o,r,s={},a,c=!1){let l=i??{},u,h=!1,p=!1,f=a??crypto.randomUUID(),m=null,P,v;if(a!==void 0){if(m=this.storedPendingMutation(a),P=m?.inputFingerprint??await Tr(n,i),m||(v=await _s(e.collectionId,n,i)),m){if(m.collectionId!==e.collectionId||m.operation!==n||m.inputFingerprint!==P)throw d("pending_mutation_unresolved","A previous write still has an unknown outcome. Retry that exact write before making another change.");f=m.requestId,p=!c}h=!0}let y=m?.mutation??_e(n,i);if(m?.envelope&&(e.authority||!e.encryption))throw d("pending_mutation_unresolved","The pending write requires its encrypted relay authority. Reconnect that authority before recovery.");if(m?.request&&e.encryption&&!e.authority)throw d("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 d("missing_grant_key","Reconnect this application to restore encrypted access.");try{if(h)if(m){if(!m.envelope)throw d("pending_mutation_unresolved","The pending write belongs to a different transport. Reconnect before retrying it.");u=vr(m.envelope,s.deadlineUnixMs)}else u=await me(this.keyStore,e.keyHandle,{grantId:e.grantId,applicationId:e.clientId,encryption:e.encryption},n,i,f,s.deadlineUnixMs),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:n,mutation:y,inputFingerprint:P,...v?{recordDigest:v}:{},requestId:f,envelope:u,createdAt:Date.now()});else u=await me(this.keyStore,e.keyHandle,{grantId:e.grantId,applicationId:e.clientId,encryption:e.encryption},n,i,void 0,s.deadlineUnixMs)}catch(S){throw S instanceof q?L(S.code,S.message):S}f=u.request_id,l=u}else{let S=m?.request??{protocol_version:Y,request_id:f,input:l};l=S,h&&!m&&this.pendingMutationStore.store({collectionId:e.collectionId,...e.grantId?{grantId:e.grantId}:{},operation:n,mutation:y,inputFingerprint:P,...v?{recordDigest:v}:{},requestId:f,request:S,createdAt:Date.now()})}if(o&&u&&!e.authority){let S=!1;try{let C=await fetch(`${this.loopbackUrl}/v1/operations`,Pe({method:"POST",headers:{"content-type":"application/mdbase-connect+json"},body:JSON.stringify(u),signal:s.signal}));if(!await Ze(C)||await He(C))return C.ok&&(this.markDirectAvailable(),this.setRoute("direct")),{response:C,requestId:f,encryptedRequest:u,pendingMutation:h,...h?{pendingMutationRecord:m??this.storedPendingMutation(f)??void 0}:{},resumingMutation:p};S=C.status>=500,this.markDirectUnavailable()}catch(C){if(s.signal?.aborted)throw h?J(f,C):C;S=!0,await Mt()==="denied"?this.setDirectStatus("denied"):this.markDirectUnavailable()}let T;try{e.expiresAt<=Date.now()+3e4&&await this.refreshAuthorization({signal:s.signal,timeoutMs:null});let C=await W(()=>this.currentToken(),r,s.signal);if(!C)throw d("not_authorized","Reconnect this application to continue.");T=C}catch(C){throw h&&(S||p)?J(f,C):C}let M;h||(u=await xs(this.keyStore,T,n,i,s.deadlineUnixMs),f=u.request_id);try{M=await fetch(`${this.serverUrl}/v1/authorities/${encodeURIComponent(T.collectionId)}/operations/${n}`,{method:"POST",headers:{authorization:`Bearer ${T.accessToken}`,"content-type":"application/json"},body:JSON.stringify(u),signal:s.signal})}catch(C){throw h?J(f,C):C}return M.ok&&this.setRoute("relay"),{response:M,requestId:f,encryptedRequest:u,directDeliveryUncertain:S,pendingMutation:h,...h?{pendingMutationRecord:m??this.storedPendingMutation(f)??void 0}:{},resumingMutation:p}}let R=e.authority?`${e.authority.operationsUrl}/${n}`:`${this.serverUrl}/v1/authorities/${encodeURIComponent(e.collectionId)}/operations/${n}`,g=JSON.stringify(l),A=e.authority?await Ne(this.keyStore,e,"POST",R,g,e.authority.accessToken):{},z;try{z=await Rr(R,e.authority?.accessToken??e.accessToken,A,g,s.signal)}catch(S){throw h?J(f,S):S}return z.ok&&this.setRoute(e.authority?"remote":"relay"),{response:z,requestId:f,encryptedRequest:u,pendingMutation:h,...h?{pendingMutationRecord:m??this.storedPendingMutation(f)??void 0}:{},resumingMutation:p}}directCapable(e){return Es(e,this.directAccessMode)}hasResumableMutationTransport(){return this.currentToken()!==null}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 n=await Mt();return n==="denied"?(this.setDirectStatus("denied"),!1):(n==="prompt"||n===null)&&this.storage.getItem(this.internals.directPreferenceKey())!=="enabled"?(this.setDirectStatus("permission_required"),!1):(this.setDirectStatus("checking"),!0)}async probeDirectAccess(e){this.setDirectStatus("checking");try{if(await qs(this.loopbackUrl,Y,e))return this.markDirectAvailable(),"available"}catch(n){throw this.markDirectUnavailable(),n}return await Mt()==="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 n=F(this.storage.getItem(this.internals.tokenKey(this.collectionId)));!n||!Cr(n,e)||(this.internals.removeToken(this.collectionId,n.keyHandle),this.currentRoute="relay",this.directStatus=this.directAccessMode==="disabled"?"disabled":"unavailable",this.emitConnection())}currentToken(){return ks({stored:this.storage.getItem(this.internals.tokenKey(this.collectionId)),collectionId:this.collectionId,relayEncryption:this.internals.relayEncryption,invalidate:(e,n="invalid_stored_grant")=>this.internals.removeToken(this.collectionId,e,n),directCapable:e=>this.directCapable(e)})}async authorizedToken(e={}){let n=this.currentToken();if(!n)return null;if(n.expiresAt>Date.now()+3e4)return n;if(!n.refreshToken||(n.refreshExpiresAt??0)<=Date.now()){if(this.directCapable(n))throw d("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,n.keyHandle),null}return this.refreshAuthorization(e)}refreshAuthorization(e={}){return this.refreshOperations.run("refresh",e,this.timeouts.requestMs,n=>this.performRefresh(n))}async performRefresh(e){let n=this.grantKeyLeases();try{let i=await W(()=>this.currentToken(),n,e);return await Ms({current:i,serverUrl:this.serverUrl,keyStore:this.keyStore,signal:e,currentToken:()=>this.currentToken(),directCapable:o=>this.directCapable(o),removeToken:o=>this.internals.removeToken(this.collectionId,o),storeTokenResponse:(o,r,s)=>this.storeTokenResponse(o,r,s)})}finally{n.release()}}storeTokenResponse(e,n,i){if(e.collection_id!==this.collectionId)throw d("collection_mismatch","The refreshed authorization belongs to a different collection.");let o=this.internals.storeTokenResponse(e,n,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 n=this.pendingMutationStore.take(e);n?.keyHandle&&this.internals.deleteGrantKeyWhenUnused(this.collectionId,n.keyHandle)}grantKeyLeases(){return new Te(this.collectionId,(e,n,i)=>this.internals.acquireGrantKeyLease(e,n,i))}};function zs(t,e,n){if(!(t?.authority&&t.collectionId===e&&t.authority.replicaId===n))throw d("authority_authorization_changed","Reconnect this collection authority before synchronizing.")}var Kn=class{constructor(e,n){this.signal=n;this.iterator=Rl(e)}signal;iterator;remainder=new Uint8Array;remainderOffset=0;maxSourceChunkBytes=null;iteratorClosing=!1;ended=!1;setMaxSourceChunkBytes(e){this.maxSourceChunkBytes=e}async read(e){let n=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,d("invalid_request","Streamed file bytes ended before the declared size.");if(!(r.value instanceof Uint8Array))throw d("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 d("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);n.set(this.remainder.subarray(this.remainderOffset,this.remainderOffset+o),i),i+=o,this.remainderOffset+=o}return n}async expectEnd(){if(this.remainderOffset<this.remainder.byteLength)throw d("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 d("invalid_request","A streamed file chunk was not a Uint8Array.");if(e.value.byteLength>0)throw d("invalid_request","Streamed file bytes exceed the declared size.")}}async close(){this.ended=!0,this.closeIterator()}async nextSourceChunk(){Ds(this.signal);let e=this.iterator.next(),n=this.signal;if(!n)return e;let i=()=>{},o=new Promise((r,s)=>{let a=()=>{this.closeIterator(),s(Ls(n))};n.addEventListener("abort",a,{once:!0}),i=()=>n.removeEventListener("abort",a),n.aborted&&a()});try{let r=await Promise.race([e,o]);return Ds(n),r}finally{i()}}closeIterator(){if(!this.iteratorClosing){this.iteratorClosing=!0;try{this.iterator.return?.()?.catch(()=>{})}catch{}}}};function Rl(t){if(typeof t.getReader=="function"){let n=t.getReader(),i=!1,o=()=>{i||(i=!0,n.releaseLock())};return{async next(){if(i)return{done:!0,value:void 0};let r=await n.read();return r.done&&o(),r},async return(){if(!i)try{await n.cancel()}finally{o()}return{done:!0,value:void 0}}}}let e=t;if(typeof e[Symbol.asyncIterator]!="function")throw d("invalid_request","Streamed files require a readable byte stream.");return e[Symbol.asyncIterator]()}function Ds(t){if(t?.aborted)throw Ls(t)}function Ls(t){return d("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:t?.reason})}var ht=class{constructor(e,n,i,o,r=We(),s=async()=>O(!1)){this.capability=e;this.request=n;this.framed=i;this.hosted=o;this.timeouts=r;this.supportsAuthorityFeature=s}capability;request;framed;hosted;timeouts;supportsAuthorityFeature;list(e={}){return ms(this.capability,this.request,e,this.timeouts.fileIndexMs)}stat(e,n={}){return ys(this.capability,this.request,this.supportsAuthorityFeature,i=>this.list(i),e,n,this.timeouts.fileIndexMs)}async upload(e,n,i={}){return $(i,this.timeouts.uploadMs,o=>this.uploadWithinBudget(e,n,{...i,signal:o.signal,timeoutMs:null}))}async uploadWithinBudget(e,n,i){this.requireAction(i.ifRevision?"replace":"add");let o=Jo(n,i.mediaType),r=yi(i.concurrency),s=await Wo(o,i.signal,a=>{i.onProgress?.({phase:"hashing",transferredBytes:a,totalBytes:o.size})});return this.uploadKnownSource(e,o.size,`sha256:${s}`,(i.mediaType??o.type)||void 0,i,r,async(a,c,l)=>o.slice(c,c+l))}async uploadStream(e,n,i={}){return $(i,this.timeouts.uploadMs,o=>this.uploadStreamWithinBudget(e,n,{...i,signal:o.signal,timeoutMs:null}))}async uploadStreamWithinBudget(e,n,i){if(this.requireAction(i.ifRevision?"replace":"add"),!Number.isSafeInteger(n.size)||n.size<0)throw d("invalid_request","Streamed file size must be a non-negative safe integer.");if(!on.test(n.contentDigest))throw d("invalid_request","Streamed files require a lowercase SHA-256 content digest.");fi(i.maxAttempts,i.noAutoAbort);let o=new Kn(n.stream,i.signal),r=new ze;return this.uploadKnownSource(e,n.size,n.contentDigest,i.mediaType??n.mediaType,i,1,async(s,a,c)=>{let l=await o.read(c);return r.update(l),l},async()=>{if(await o.expectEnd(),`sha256:${r.digestHex()}`!==n.contentDigest)throw d("invalid_request","Streamed file bytes do not match the declared SHA-256 digest.")},()=>o.close(),s=>o.setMaxSourceChunkBytes(s))}async uploadKnownSource(e,n,i,o,r,s,a,c,l,u){let h=fi(r.maxAttempts,r.noAutoAbort),p=r.transferId??crypto.randomUUID();if(!$o.test(p))throw d("invalid_request","File transfer ID must be a UUID.");let f=!1;try{let m=await this.request("POST","uploads",{protocol_version:1,type:"open_file_upload",transfer_id:p,path:e,size:n,content_digest:i,...o?{media_type:o}:{},...r.ifRevision?{if_revision:r.ifRevision}:{}},r.signal);if(gi(m,p,"upload"),m.total_size!==n||m.strategy.kind==="object_ranges")throw d("invalid_operation_response","The authority returned an incompatible upload strategy.");let P=m.strategy.kind==="framed_chunks";if(P&&!this.framed)throw d("invalid_operation_response","Encrypted file chunk delivery is unavailable.");let v=m.strategy.kind==="object_put"?Math.max(1,n):m.strategy.kind==="framed_chunks"?m.strategy.chunk_size:m.strategy.part_size,y=m.strategy.kind==="object_put"?1:Math.ceil(n/v),R=m.prepared_upload_part;if(R!==void 0){if(vi(R,p,0,0,n,"PUT"),m.strategy.kind!=="object_put"||Ci(R.headers).get("if-none-match")!=="*")throw d("invalid_operation_response","Upload bootstrap must be a create-only single PUT.");Date.parse(R.expires_at)<=Date.now()+6e4&&(R=void 0)}let g=R?void 0:await this.request("GET",`transfers/${encodeURIComponent(p)}`,void 0,r.signal);if(g&&(bi(g,m),g.state!=="open"&&g.state!=="committed"))throw d("invalid_operation_response",`The authority cannot resume a ${g.state} file transfer.`);if(u?.(v),!P&&g?.received.length===y){let C=await this.tryReplayUploadCommit(p,m.strategy.kind==="object_multipart"?g.uploaded_parts:void 0,r.signal,h);if(C)return f=!0,he(C.file)}let A=new Set(g?.received??[]),z=new Map((g?.uploaded_parts??[]).map(C=>[C.part_number-1,C])),S=[...A].reduce((C,N)=>C+_i(n,v,N),0),T=await er(y,s,async C=>{let N=C*v,G=Math.min(v,Math.max(0,n-N)),j=await a(C,N,G);if(Yo(j)!==G)throw d("invalid_request","Streamed file bytes ended before the declared size.");if(A.has(C))return z.get(C)??null;let U=P?await rn(async()=>this.framed.uploadChunk(m,C,await Xo(j),r.signal),r.signal,h).then(()=>null):await this.uploadPart(p,C,N,j,G,m.strategy.kind==="object_multipart",r.signal,R?{session:m,part:R}:void 0,h);return S+=G,r.onProgress?.({phase:"uploading",transferredBytes:S,totalBytes:n}),U});await c?.();let M=await this.commitUpload(p,m.strategy.kind==="object_multipart"?T.filter(C=>C!==null):void 0,r.signal,h);if(M.protocol_version!==1||M.type!=="file_upload_committed"||M.transfer_id!==p||M.file.path!==e||M.file.size!==n||M.file.content_digest!==i)throw d("invalid_operation_response","The authority returned an invalid file receipt.");return f=!0,he(M.file)}catch(m){throw Re(m)}finally{await l?.().catch(()=>{}),!f&&r.transferId===void 0&&!r.noAutoAbort&&await this.abort(p)}}async download(e,n={}){let i=await this.downloadBytes(e,n);return new Blob([i.buffer],{type:e.mediaType??""})}async downloadStream(e,n={}){return $(n,this.timeouts.requestMs,i=>this.openDownloadStream(e,n,i.signal))}async openDownloadStream(e,n,i){this.requireAction("read");let o=yi(n.concurrency),r=crypto.randomUUID(),s;try{if(s=await this.request("POST","downloads",{protocol_version:1,type:"open_file_download",transfer_id:r,file_id:e.fileId,revision:e.revision},i),gi(s,r,"download"),s.total_size!==e.size||s.strategy.kind!=="object_ranges"&&s.strategy.kind!=="framed_chunks")throw d("invalid_operation_response","The authority returned an incompatible download session.");if(s.strategy.kind==="framed_chunks"&&!this.framed)throw d("invalid_operation_response","Encrypted file chunk delivery is unavailable.");if(s.strategy.kind==="object_ranges"&&e.size>0&&!this.hosted)throw d("invalid_operation_response","Authenticated hosted file delivery is unavailable.")}catch(S){throw await this.abort(r),Re(S)}let a=s.strategy.kind==="framed_chunks"?s.strategy.chunk_size:s.strategy.part_size,c=Math.ceil(e.size/a),l=new ze,u=0,h=0,p=null,f=0,m=!1,P=new AbortController,v=n.signal?AbortSignal.any([n.signal,P.signal]):P.signal,y=new Map,R=0,g=()=>{if(s.strategy.kind==="framed_chunks")for(;R<c&&y.size<o;){let S=R;R+=1;let T=rn(()=>this.framed.downloadChunk(s,S,v),v).then(M=>({ok:!0,chunk:M}),M=>({ok:!1,error:M}));y.set(S,T)}},A=async()=>{m||(m=!0,P.abort(),await p?.cancel().catch(()=>{}),p=null,await Promise.all(y.values()),y.clear(),await this.abort(r))},z=()=>{if(f!==e.size||`sha256:${l.digestHex()}`!==e.contentDigest)throw d("invalid_operation_response","Downloaded file bytes failed integrity verification.")};return new ReadableStream({pull:async S=>{try{if(te(v),s.strategy.kind==="object_ranges")for(;;){if(!p){if(u>=c){z(),S.close(),A();return}let U=u*a;h=Math.min(a,e.size-U),p=(await rn(()=>this.hosted.downloadPart(s,u,h,v),v)).getReader()}let j=await p.read();if(j.done){if(p.releaseLock(),p=null,h!==0)throw d("invalid_operation_response","A hosted file range ended before its declared byte length.");u+=1;continue}if(!(j.value instanceof Uint8Array))throw d("invalid_operation_response","A hosted file range returned a non-byte chunk.");if(j.value.byteLength!==0){if(j.value.byteLength>h)throw d("invalid_operation_response","A hosted file range exceeded its declared byte length.");h-=j.value.byteLength,l.update(j.value),f+=j.value.byteLength,n.onProgress?.({phase:"downloading",transferredBytes:f,totalBytes:e.size}),S.enqueue(j.value);return}}if(u>=c){z(),S.close(),A();return}let T=u*a,M=Math.min(a,e.size-T);g();let C=y.get(u);if(!C)throw d("invalid_operation_response","A file chunk was not scheduled.");let N=await C;if(y.delete(u),!N.ok)throw N.error;let G=N.chunk;if(G.byteLength!==M)throw d("invalid_operation_response","A file chunk had the wrong byte length.");l.update(G),f+=G.byteLength,u+=1,g(),n.onProgress?.({phase:"downloading",transferredBytes:f,totalBytes:e.size}),u===c&&z(),S.enqueue(G),u===c&&(S.close(),A())}catch(T){let M=n.signal?.aborted?d("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:n.signal.reason}):T;await A(),S.error(Re(M))}},cancel:A})}async downloadBytes(e,n={}){if(e.size>mi)throw d("invalid_request",`download() buffers at most ${mi} bytes; use downloadStream() for larger files.`);let i=await this.downloadStream(e,n),o=new Uint8Array(e.size),r=i.getReader(),s=0;try{for(;;){let a=await r.read();if(a.done)break;if(a.value.byteLength>o.byteLength-s)throw d("invalid_operation_response","Downloaded file bytes failed integrity verification.");o.set(a.value,s),s+=a.value.byteLength}if(s!==o.byteLength)throw d("invalid_operation_response","Downloaded file bytes failed integrity verification.");return o}catch(a){throw await r.cancel().catch(()=>{}),a}finally{r.releaseLock()}}async move(e,n,i={}){return $(i,this.timeouts.requestMs,o=>this.moveWithinBudget(e,n,{...i,signal:o.signal,timeoutMs:null}))}async moveWithinBudget(e,n,i){this.requireAction("move");let o=i.mutationId??crypto.randomUUID(),r;try{r=await this.request("POST",`${encodeURIComponent(e.fileId)}/move`,{protocol_version:1,type:"move_file",mutation_id:o,file_id:e.fileId,if_revision:i.ifRevision??e.revision,from_path:e.path,path:n,update_references:!1},i.signal)}catch(s){throw Re(s)}if(r.protocol_version!==1||r.type!=="file_moved"||r.mutation_id!==o||r.file.file_id!==e.fileId||r.file.path!==n)throw d("invalid_operation_response","The authority returned an invalid file move receipt.");return he(r.file)}async delete(e,n={}){return $(n,this.timeouts.requestMs,i=>this.deleteWithinBudget(e,{...n,signal:i.signal,timeoutMs:null}))}async deleteWithinBudget(e,n){this.requireAction("delete");let i=n.mutationId??crypto.randomUUID(),o;try{o=await this.request("POST",`${encodeURIComponent(e.fileId)}/delete`,{protocol_version:1,type:"delete_file",mutation_id:i,file_id:e.fileId,if_revision:n.ifRevision??e.revision,path:e.path},n.signal)}catch(r){throw Re(r)}if(o.protocol_version!==1||o.type!=="file_deleted"||o.mutation_id!==i||o.file_id!==e.fileId||o.previous_path!==e.path)throw d("invalid_operation_response","The authority returned an invalid file delete receipt.");return{protocolVersion:o.protocol_version,type:o.type,mutationId:o.mutation_id,fileId:o.file_id,previousPath:o.previous_path,revision:o.revision}}async uploadPart(e,n,i,o,r,s,a,c,l=hi){for(let u=1;;u+=1){te(a);try{let h=u===1&&c&&Date.parse(c.part.expires_at)>Date.now()+6e4;if(c&&!h){let y=await this.request("GET",`transfers/${encodeURIComponent(e)}`,void 0,a);if(bi(y,c.session),y.state!=="open"&&y.state!=="committed")throw d("invalid_operation_response",`The authority cannot resume a ${y.state} file transfer.`);if(y.received.includes(n))return{part_number:n+1,etag:""}}let p=h?c.part:await this.request("POST",`uploads/${encodeURIComponent(e)}/parts`,{protocol_version:1,type:"prepare_file_upload_part",transfer_id:e,part_number:n+1,content_length:r},a);vi(p,e,n,i,r,"PUT");let f=Ci(p.headers),m=await fetch(p.url,{method:p.method,headers:f,body:o,redirect:"error",signal:a});if(m.status===412&&!s&&f.get("if-none-match")==="*")return{part_number:n+1,etag:""};if(!m.ok)throw new Error(`Object upload failed with HTTP ${m.status}.`);let v=m.headers.get("etag");if(s&&!v)throw new Error("Multipart object upload did not return an ETag.");return{part_number:n+1,etag:v??""}}catch(h){if(a?.aborted||u===l)throw h}}}async tryReplayUploadCommit(e,n,i,o){try{return await this.commitUpload(e,n,i,o)}catch(r){if(r instanceof _&&r.code==="file_upload_incomplete")return null;throw r}}async commitUpload(e,n,i,o=hi){for(let r=1;;r+=1){te(i);try{return await this.request("POST",`uploads/${encodeURIComponent(e)}/commit`,{protocol_version:1,type:"commit_file_upload",transfer_id:e,...n===void 0?{}:{parts:n}},i)}catch(s){if(i?.aborted||s instanceof _||r===o)throw s}}}requireAction(e){if(!this.capability()?.actions.includes(e))throw d("not_authorized",`This connection is not authorized to ${e} files.`)}async abort(e){await this.request("DELETE",`transfers/${encodeURIComponent(e)}`).catch(()=>{})}};var ft=class{constructor(e,n,i={}){this.adapter=n;this.record=e,this.baseBody=this.body=n.body(e),this.seen.add(n.revision(e)),this.idleMs=i.autosave===!1?void 0:i.autosave?.idleMs??1e3,this.current=this.compute()}adapter;record;baseBody;body;patch={};remote=null;problem=null;refreshProblem=null;deleted=!1;busy=!1;pending;incoming=[];seen=new Set;listeners=new Set;tail=Promise.resolve();queued=0;inFlight;timer;lastEdit=0;disposed=!1;idleMs;current;get snapshot(){return this.current}getSnapshot=()=>this.current;subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});setBody(e){e!==this.body&&(this.body=e,this.edited())}patchFrontmatter(e){this.patch={...this.patch,...e},this.edited()}restore(e){let n=this.adapter.body(this.record),i=this.adapter.frontmatter?.(this.record)??{},o=Object.fromEntries(Object.entries(e.patch??{}).filter(([r,s])=>JSON.stringify(i[r]??null)!==JSON.stringify(s)));e.body===n&&Object.keys(o).length===0||(this.body=e.body,this.patch=o,(e.body!==n&&e.baseBody!==n||Object.keys(o).some(r=>!e.baseFrontmatter||JSON.stringify(e.baseFrontmatter[r]??null)!==JSON.stringify(i[r]??null)))&&(this.remote=this.record),this.emit())}resumeRecovery(e){this.pending||this.busy||(this.pending={requestId:e,sent:"restored"},this.emit(),this.autosave())}dispose(){this.disposed=!0,clearTimeout(this.timer),this.listeners.clear()}autosave(){this.lastEdit=Date.now(),this.schedule()}receive(e){if(!this.seen.has(this.adapter.revision(e))){if(this.busy||this.pending){this.incoming.push(e);return}this.seen.add(this.adapter.revision(e)),this.classify(e),this.emit()}}refresh(e){return this.run(async()=>{let n=this.adapter.read;if(!n||this.pending)return O(this.record);let i=await n(this.record,e);return i.ok?(this.refreshProblem=null,this.seen.add(this.adapter.revision(i.value)),this.classify(i.value),this.emit(),O(this.record)):(i.problem.code==="file_not_found"?this.markDeleted():(this.refreshProblem=i.problem,this.emit()),i)})}accept(e){this.seen.add(this.adapter.revision(e));let n=this.adapter.body(e);this.body===this.baseBody&&(this.body=n),this.baseBody=n;let i=this.adapter.frontmatter?.(e)??{};for(let[o,r]of Object.entries(this.patch))je(i[o],r)&&delete this.patch[o];this.record=e,this.remote=null,this.problem=null,this.refreshProblem=null,this.emit()}markDeleted(){clearTimeout(this.timer),this.deleted=!0,this.emit()}save(e){if(clearTimeout(this.timer),this.inFlight)return this.inFlight;let n=this.run(()=>this.pending?this.recoverPending(e):this.write(e,!0));this.inFlight=n;let i=()=>{this.inFlight===n&&(this.inFlight=void 0)};return n.then(i,i),n}async flush(e){for(;;){if(this.deleted)return b(to());if(this.remote)return b(eo());if(!this.inFlight&&!this.pending&&!this.dirtyLocally())return O(this.record);let n=await this.save(e);if(!n.ok)return n}}run(e){let n=this.queued===0?e():this.tail.then(e);this.queued+=1;let i=()=>{this.queued-=1};return this.tail=n.then(i,i),n}resolve(e){let n=this.remote;!n||this.busy||(this.record=n,this.remote=null,this.problem=null,this.baseBody=this.adapter.body(n),"body"in e?this.body=e.body:e.keep==="theirs"&&(this.body=this.baseBody,this.patch={}),this.emit(),this.dirtyLocally()&&this.autosave())}discard(){this.busy||(clearTimeout(this.timer),this.record=this.remote??this.record,this.remote=null,this.problem=null,this.baseBody=this.body=this.adapter.body(this.record),this.patch={},this.emit())}edited(){this.problem=null,this.lastEdit=Date.now(),this.emit(),this.schedule()}schedule(){if(clearTimeout(this.timer),this.disposed||this.idleMs===void 0||this.remote||this.deleted)return;let e=Math.max(0,this.lastEdit+this.idleMs-Date.now());this.timer=setTimeout(()=>{this.save()},e)}dirtyLocally(){return this.body!==this.baseBody||Object.keys(this.patch).length>0}async write(e,n){if(this.remote)return b(eo());if(this.deleted)return b(to());if(!this.dirtyLocally())return O(this.record);let i={};this.body!==this.baseBody&&(i.body=this.body),Object.keys(this.patch).length&&(i.patch=structuredClone(this.patch)),this.busy=!0,this.emit();let o=await this.guard(()=>this.adapter.write(this.record,{...i},e));if(o.ok)return this.acknowledge(o.value,i),O(this.record);let r=Ol(o.problem);if(r)return this.busy=!1,this.problem=o.problem,this.pending={requestId:r,sent:i},this.emit(),this.schedule(),o;let s=await this.classifyFailure(o.problem,e);return s==="resolved"?O(this.record):s==="rebased"&&n?this.write(e,!1):this.failure(o.problem)}async recoverPending(e){let n=this.pending,i=this.adapter.recover;if(!i)return b(w("pending_mutation_unresolved","Exact recovery of the interrupted write is unavailable. No new write was attempted."));this.busy=!0,this.emit();let o=await this.guard(()=>i(n.requestId,e));return o.ok?(n.sent==="restored"?(this.pending=void 0,this.busy=!1,this.accept(o.value),this.settle()):this.acknowledge(o.value,n.sent),O(this.record)):o.problem.operation_outcome!=="unknown"&&o.problem.code!=="operation_outcome_unknown"&&this.adapter.isPending?.(n.requestId)===!1?(this.pending=void 0,await this.classifyFailure(o.problem,e),this.failure(o.problem)):(this.busy=!1,this.problem=o.problem,this.emit(),o)}async guard(e){try{return await e()}catch(n){throw this.busy=!1,this.emit(),n}}failure(e){return this.deleted?b(to()):this.remote?b(eo()):b(e)}acknowledge(e,n){this.seen.add(this.adapter.revision(e)),this.record=e,n.body!==void 0&&(this.baseBody=n.body);for(let[i,o]of Object.entries(n.patch??{}))i in this.patch&&je(this.patch[i],o)&&delete this.patch[i];this.problem=null,this.refreshProblem=null,this.pending=void 0,this.settle(),this.dirtyLocally()&&this.schedule()}async classifyFailure(e,n){let i=this.adapter.revision(this.record),o=this.adapter.read,r=o?await this.guard(()=>o(this.record,n)):void 0;return r&&!r.ok&&r.problem.code==="file_not_found"?(this.deleted=!0,this.settle(),"failed"):!r?.ok||this.adapter.revision(r.value)===i?(this.problem=e,this.settle(),"failed"):(this.seen.add(this.adapter.revision(r.value)),this.classify(r.value),this.settle(),this.remote?"failed":this.dirtyLocally()?"rebased":"resolved")}settle(){this.busy=!1;for(let e of this.incoming.splice(0))this.seen.has(this.adapter.revision(e))||(this.seen.add(this.adapter.revision(e)),this.classify(e));this.emit()}classify(e){if(this.adapter.revision(e)===this.adapter.revision(this.record))return;let n=this.adapter.body(this.record),i=this.adapter.body(e),o=i!==n,r=this.body!==this.baseBody,s=this.adapter.frontmatter?.(this.record)??{},a=this.adapter.frontmatter?.(e)??{};if(r&&o&&i!==this.body||Object.entries(this.patch).some(([l,u])=>!je(a[l],s[l])&&!je(a[l],u))){clearTimeout(this.timer),this.remote=e;return}this.remote=null,this.record=e,o&&(this.baseBody=this.body=i);for(let[l,u]of Object.entries(this.patch))je(a[l],u)&&delete this.patch[l];this.dirtyLocally()||(this.problem=null)}compute(){let e=this.busy||!!this.pending||this.dirtyLocally();return{state:this.deleted?"deleted":this.remote?"conflict":this.busy?"saving":this.pending?"recovery":this.problem||this.refreshProblem?"error":e?"unsaved":"saved",body:this.body,frontmatter:{...this.adapter.frontmatter?.(this.record)??{},...this.patch},record:this.record,remote:this.remote,dirty:e,problem:this.problem??this.refreshProblem,...this.pending?{pendingRequestId:this.pending.requestId}:{}}}emit(){this.current=this.compute(),this.listeners.forEach(e=>e())}};function eo(){return w("concurrent_modification","This record changed elsewhere. Local changes are kept until the conflict is resolved.")}function to(){return w("file_not_found","This record no longer exists. Local changes are kept.")}function Ol(t){return t.code==="operation_outcome_unknown"?t.details.request_id:void 0}function je(t,e){if(t===e)return!0;if(typeof t!="object"||typeof e!="object"||t===null||e===null)return!1;if(Array.isArray(t)||Array.isArray(e))return Array.isArray(t)&&Array.isArray(e)&&t.length===e.length&&t.every((i,o)=>je(i,e[o]));let n=Object.keys(t);return n.length===Object.keys(e).length&&n.every(i=>i in e&&je(t[i],e[i]))}var Sl=4,Pl=4,mt=class{constructor(e,n=async()=>null){this.connection=e;this.pendingUpdate=n}connection;pendingUpdate;entries=new Map;opening=new Map;refreshes=new Map;refreshQueue=new Set;activeRefreshes=0;followers=0;async open(e,n={}){for(;;){let i=this.entries.get(e);if(i)return O(this.lease(i));let o=this.opening.get(e),r=o??this.load(e,n);o||(this.opening.set(e,r),r.then(()=>this.opening.delete(e)));let s=await r;if(s.ok)return O(this.lease(s.value));if(!(o&&(s.problem.code==="operation_cancelled"||s.problem.code==="timeout"))||n.signal?.aborted)return s}}follow(e){this.followers+=1;let n=e.subscribe(o=>this.apply(o),o=>{if(o.state==="reset_required")for(let r of this.entries.values())this.refresh(r)}),i=!1;return()=>{if(!i&&(i=!0,n(),--this.followers===0)){for(let o of this.refreshes.values())clearTimeout(o.timer),o.stopWaiting?.();this.refreshes.clear(),this.refreshQueue.clear()}}}refresh(e){let n=this.refreshes.get(e);if(n){n.dirty=!0;return}let i={entry:e,dirty:!1,attempts:0};this.refreshes.set(e,i),this.enqueueRefresh(i)}enqueueRefresh(e){e.entry.session.snapshot.pendingRequestId?e.stopWaiting=e.entry.session.subscribe(()=>{e.entry.session.snapshot.pendingRequestId||(e.stopWaiting?.(),e.stopWaiting=void 0,this.enqueueRefresh(e))}):(this.refreshQueue.add(e),this.pumpRefreshes())}pumpRefreshes(){for(;this.activeRefreshes<Sl&&this.refreshQueue.size>0;){let e=this.refreshQueue.values().next().value;this.refreshQueue.delete(e),e.dirty=!1,this.activeRefreshes+=1,this.runRefresh(e)}}async runRefresh(e){try{e.attempts+=1;let n=await e.entry.session.refresh();if(this.refreshes.get(e.entry)!==e)return;if(e.entry.session.snapshot.pendingRequestId){e.attempts-=1,this.enqueueRefresh(e);return}!n.ok&&n.problem.code!=="operation_cancelled"&&(n.problem.recovery==="retry"||n.problem.operation_outcome==="not_sent"&&n.problem.category==="availability")&&e.attempts<Pl?e.timer=setTimeout(()=>this.enqueueRefresh(e),100*2**(e.attempts-1)):e.dirty?(e.attempts=0,this.enqueueRefresh(e)):this.refreshes.delete(e.entry)}finally{this.activeRefreshes-=1,this.pumpRefreshes()}}async load(e,n){let{autosave:i,...o}=n,r=await this.connection.read({path:e},o);if(!r.ok)return r;let s=this.entries.get(r.value.path);if(s)return O(s);let a={path:r.value.path,leases:0};a.session=new ft(r.value,this.adapter(a),{autosave:i});let c=await this.pendingUpdate(a.path);return c&&a.session.resumeRecovery(c),this.entries.set(a.path,a),O(a)}adapter(e){return{revision:n=>n.revision,body:n=>n.body??"",frontmatter:n=>n.frontmatter,write:(n,i,o)=>this.connection.update({path:e.path,ifRevision:n.revision,patch:i.patch??{},...i.body===void 0?{}:{body:i.body}},o),read:(n,i)=>this.connection.read({path:e.path},i),recover:async(n,i)=>{let o=this.connection.pendingMutation(n);return o?o.recover(i):b(w("no_pending_mutation","The interrupted write is no longer pending."))},isPending:n=>this.connection.pendingMutation(n)!==null}}lease(e){e.leases+=1,e.stopRetiring?.(),e.stopRetiring=void 0;let n=!1;return{session:e.session,release:()=>{n||(n=!0,e.leases-=1,this.retire(e))}}}retire(e){if(e.leases>0)return;let n=()=>{let{state:i,dirty:o}=e.session.snapshot;if(i!=="saved"&&i!=="deleted"&&!(i==="error"&&!o))return!1;e.stopRetiring?.(),e.stopRetiring=void 0,this.entries.get(e.path)===e&&this.entries.delete(e.path);let r=this.refreshes.get(e);return r&&(clearTimeout(r.timer),r.stopWaiting?.(),this.refreshQueue.delete(r),this.refreshes.delete(e)),!0};n()||(e.stopRetiring=e.session.subscribe(()=>{n()}))}apply(e){let{payload:n}=e;if(e.type==="mdbase.record.renamed"){let o=typeof n.from=="string"?this.entries.get(n.from):void 0;if(!o||typeof n.to!="string")return;this.entries.delete(o.path),o.path=n.to,this.entries.set(o.path,o),this.refresh(o);return}if(e.type!=="mdbase.record.modified"&&e.type!=="mdbase.record.deleted")return;let i=typeof n.path=="string"?this.entries.get(n.path):void 0;!i||n.revision===i.session.snapshot.record.revision||this.refresh(i)}};var Al=4,Us=32,Vn=class{constructor(e,n,i={}){this.transport=e;this.requestTimeoutMs=n;this.foregroundCapacity=no(i.foregroundCapacity,Al),this.foregroundQueueCapacity=no(i.foregroundQueueCapacity,Us),this.mutationQueueCapacity=no(i.mutationQueueCapacity,Us)}transport;requestTimeoutMs;foregroundCapacity;foregroundQueueCapacity;mutationQueueCapacity;foregroundQueue=[];mutationQueue=[];identicalReads=new Map;latestFamilies=new Map;activeForeground=0;mutationActive=!1;operation(e,n,i={}){let o=!ee(e,n),r=Tl(i.coordination,o),s=o&&r.coalesce!==!1&&!r.latestWins&&i.signal===void 0?Ml(e,n,i.timeoutMs):void 0;if(s){let c=this.identicalReads.get(s);if(c)return c}let a=$(i,this.requestTimeoutMs,c=>this.schedule(e,n,i,r,o,c));return s&&(this.identicalReads.set(s,a),a.finally(()=>{this.identicalReads.get(s)===a&&this.identicalReads.delete(s)}).catch(()=>{})),a}schedule(e,n,i,o,r,s){let a=o.latestWins?this.replaceLatest(o.family):void 0,c=Il(s.signal,a?.signal),{coordination:l,...u}=i,h=pe({...u,timeoutMs:null},s),p=()=>this.transport.operation(e,n,{...h,signal:c.signal}),f=r?this.foregroundQueue:this.mutationQueue,m=r?this.foregroundQueueCapacity:this.mutationQueueCapacity;return f.length>=m?(c.dispose(),this.releaseLatest(o.family,a),Promise.reject(d("connector_busy","The selected connection request queue is full.",{operationOutcome:"not_sent",status:503}))):new Promise((P,v)=>{let y={budget:s,run:p,resolve:A=>P(A),reject:v,started:!1,settled:!1},R=()=>{y.started||y.settled||(y.settled=!0,f.splice(f.indexOf(y),1),y.reject(ne(c.signal)),c.dispose(),this.releaseLatest(o.family,a))};c.signal.addEventListener("abort",R,{once:!0});let g=y.run;y.run=async()=>{c.signal.removeEventListener("abort",R);try{if(c.signal.aborted)throw ne(c.signal);return await g()}finally{c.dispose(),this.releaseLatest(o.family,a)}},f.push(y),this.pump()})}replaceLatest(e){let n=new AbortController;return this.latestFamilies.get(e)?.abort(d("operation_cancelled","A newer request replaced this read before it changed the collection.",{operationOutcome:"not_sent"})),this.latestFamilies.set(e,n),n}releaseLatest(e,n){e&&n&&this.latestFamilies.get(e)===n&&this.latestFamilies.delete(e)}pump(){for(;this.activeForeground<this.foregroundCapacity;){let e=Ns(this.foregroundQueue);if(!e)break;this.activeForeground+=1,this.start(e,()=>{this.activeForeground-=1,this.pump()})}if(!this.mutationActive){let e=Ns(this.mutationQueue);e&&(this.mutationActive=!0,this.start(e,()=>{this.mutationActive=!1,this.pump()}))}}start(e,n){e.started=!0,e.run().then(i=>{e.settled||(e.settled=!0,e.resolve(i))},i=>{e.settled||(e.settled=!0,e.reject(i))}).finally(n)}};function Ns(t){for(;t.length>0;){let e=t.shift();if(!e.settled)return e}}function Tl(t,e){let n=t??{};if(n.latestWins&&!e)throw new TypeError("latestWins coordination is available only for read operations.");if(n.latestWins&&!n.family?.trim())throw new TypeError("latestWins coordination requires a non-empty family.");return n}function Ml(t,e,n){return`${t}:${n===void 0?"default":String(n)}:${io(e)}`}function io(t){return t===null||typeof t!="object"?JSON.stringify(t)??String(t):Array.isArray(t)?`[${t.map(io).join(",")}]`:`{${Object.entries(t).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>`${JSON.stringify(e)}:${io(n)}`).join(",")}}`}function Il(t,e){if(!e)return{signal:t,dispose:()=>{}};let n=new AbortController,i=()=>n.abort(t.reason),o=()=>n.abort(e.reason);return t.aborted?i():t.addEventListener("abort",i,{once:!0}),e.aborted?o():e.addEventListener("abort",o,{once:!0}),{signal:n.signal,dispose:()=>{t.removeEventListener("abort",i),e.removeEventListener("abort",o)}}}function no(t,e){let n=t??e;if(!Number.isSafeInteger(n)||n<=0)throw new TypeError("Request coordinator capacities must be positive safe integers.");return n}var yt=class{constructor(e,n){this.internals=e;this.collectionId=n;this.transport=new Qn({serverUrl:e.serverUrl,storage:e.storage,keyStore:e.keyStore,directAccessMode:e.directAccessMode,loopbackUrl:e.loopbackUrl,collectionId:n,internals:e,timeouts:e.timeouts,onChange:()=>{this.authorityFeatures.refreshLifetime(),this.emitConnection()}}),this.authorityFeatures=new Cn({lifetime:()=>{let i=this.transport.currentToken();return JSON.stringify([i?.savedAt,i?.grantId,i?.keyHandle,i?.authority?.operationsUrl,i?.authority?.filesUrl,i?.authority?.replicaId,i?.authority?.proofPublicKey,i?.clientId,i?.applicationOrigin,i?.encryption,i?.scope,i?.operations,i?.fileCapability,this.transport.route])},operations:()=>this.operations,fileCapability:()=>this.fileCapability,describe:async i=>{let o=Rn(await this.transport.performOperation("describe",{},i));if(o.collectionId.toLowerCase()!==this.collectionId.toLowerCase())throw d("invalid_operation_response","The authority described a different collection.");return O(o)},filesPage:async(i,o)=>{let r=await Gi((s,a,c,l)=>this.transport.files.control(s,a,c,l),new URLSearchParams({protocol_version:"1",limit:"1",...i?{folder:i}:{}}),o);return Ue(r.authority_capabilities)}},e.timeouts.requestMs),this.people=new ct({request:(i,o)=>Yr(i,o??{},{serverUrl:e.serverUrl,collectionId:n,requestMs:e.timeouts.requestMs,authorizedToken:r=>this.transport.authorizedToken({signal:r,timeoutMs:null})}),describe:i=>this.describe(i),queryPages:(i,o)=>this.queryPages(i,o)}),this.files=new ht(()=>this.fileCapability,(i,o,r,s)=>this.transport.files.control(i,o,r,s),{uploadChunk:(i,o,r,s)=>this.transport.files.uploadChunk(i,o,r,s),downloadChunk:(i,o,r)=>this.transport.files.downloadChunk(i,o,r)},{downloadPart:(i,o,r,s)=>this.transport.files.downloadHostedPart(i,o,r,s)},e.timeouts,(i,o)=>this.supportsAuthorityFeature(i,o)),this.records=new mt(this,i=>this.transport.pendingUpdate(i)),this.collectionClient=new dt(new Vn({operation:(i,o,r)=>this.transport.performOperation(i,o,r)},e.timeouts.requestMs),e.timeouts.requestMs,(i,o)=>this.supportsAuthorityFeature(i,o)),this.readMany=this.collectionClient.readMany.bind(this.collectionClient),this.observe=this.collectionClient.observe.bind(this.collectionClient),this.notifications=new xn({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(n,i),requestTimeoutMs:e.timeouts.requestMs})}internals;collectionId;collectionClient;notifications;transport;authorityFeatures;files;records;people;readMany;observe;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}supportsAuthorityFeature(e,n){return this.authorityFeatures.supports(e,n)}get authorityCapabilities(){return this.authorityFeatures.capabilities}register(e){return I(()=>this.internals.register(e),qe)}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=be){let n=this.operations,i=It(e).filter(o=>!n.includes(o));return{authorized:this.info()!==null,sufficient:this.info()!==null&&i.length===0,collectionId:this.collectionId,grantedOperations:n,missingOperations:i}}hasOperations(e){return this.authorizationCapabilities(e).sufficient}authorize(e={}){return I(()=>this.internals.authorize({...e,target:{kind:"collection",collectionId:this.collectionId}}),ve)}async requestCapabilities(e,n={}){return I(async()=>{let i=await this.internals.register(n);if(Z(i.requirements,{...n,capabilities:e}),this.info()!==null&&e.every(s=>(X(Q(i.requirements),s)??[]).every(a=>this.operations.includes(a))))return{kind:"unchanged",connection:this};if(Q(i.requirements)===1){let{capabilities:s,...a}=n;return this.internals.authorize({...a,target:{kind:"collection",collectionId:this.collectionId},operations:[...new Set([...this.operations,...e.flatMap(c=>X(1,c)??[])])]})}let r=bt(i.requirements,this.operations);return this.internals.authorize({...n,target:{kind:"collection",collectionId:this.collectionId},capabilities:[...new Set([...r,...e])]})},ve)}async requestOperations(e,n={}){return I(async()=>{let i=await this.internals.register(n);Z(i.requirements,{...n,operations:e});let o=this.authorizationCapabilities(e);return o.sufficient?{kind:"unchanged",connection:this}:this.internals.authorize({...n,target:{kind:"collection",collectionId:this.collectionId},operations:[...new Set([...o.grantedOperations,...e])]})},ve)}onConnectionChange(e){return this.connectionListeners.add(e),e(this.info()),()=>this.connectionListeners.delete(e)}notifyStorageChanged(){this.authorityFeatures.invalidate(),this.transport.notifyStorageChanged()}checkDirectAccess(e){return I(()=>this.transport.checkDirectAccess(e),ui)}requestDirectAccess(e){return I(()=>this.transport.requestDirectAccess(e),ui)}disableDirectAccess(){this.transport.disableDirectAccess()}sync(){let e=this.transport.currentToken();if(!e)return null;let n=e.collectionId;if(!e.authority){if(!e.grantId||!e.operations.includes("sync"))return null;let o=e.grantId;return{collectionId:n,replicaId:o,transport:{openSession:r=>this.transport.performOperation("sync",{action:"open_session"},Gn(r,this.internals.timeouts.syncMs)),snapshot:(r,s,a)=>this.transport.performOperation("sync",{action:"snapshot",snapshot_id:r,...s?{page:s}:{}},Gn(a,this.internals.timeouts.syncMs)),changes:(r,s=200,a)=>this.transport.performOperation("sync",{action:"changes",after:r,limit:s},Gn(a,this.internals.timeouts.syncMs)),mutate:(r,s)=>this.transport.performOperation("sync",{action:"mutate",mutation:r},Gn(s,this.internals.timeouts.syncMs))}}}let i=e.authority.replicaId;return{collectionId:n,replicaId:i,transport:{openSession:o=>this.transport.performAuthoritySyncRequest(n,i,"POST","sessions",void 0,o),snapshot:(o,r,s)=>{let a=new URLSearchParams({snapshot_id:o});return r&&a.set("page",r),this.transport.performAuthoritySyncRequest(n,i,"GET",`snapshot?${a}`,void 0,s)},changes:(o,r=200,s)=>this.transport.performAuthoritySyncRequest(n,i,"GET",`changes?${new URLSearchParams({after:String(o),limit:String(r)})}`,void 0,s),mutate:(o,r)=>this.transport.performAuthoritySyncRequest(n,i,"POST","mutations",o,r)}}}registerNotifications(e){return I(()=>this.notifications.registerNotifications(e),Rt)}registerNativeNotifications(e){return I(()=>this.notifications.registerNativeNotifications(e),Rt)}unregisterNativeNotifications(e){return I(()=>this.notifications.unregisterNativeNotifications(e),Rt)}unregisterNotifications(e,n){return I(()=>this.notifications.unregisterNotifications(e,n),Rt)}forget(){let e=this.transport.currentToken();this.internals.removeToken(this.collectionId,e?.keyHandle,"not_authorized",!0),this.transport.notifyStorageChanged()}get schemaGeneration(){return this.collectionClient.schemaGeneration}async describe(e){let n=await this.collectionClient.describe(e);return n.ok&&n.value.collectionId.toLowerCase()!==this.collectionId.toLowerCase()?b(w("invalid_operation_response","The authority described a different collection.")):n}changes(e={},n){return this.collectionClient.changes(e,n)}read(e,n){return this.collectionClient.read(e,n)}query(e={},n){return this.collectionClient.query(e,n)}queryPages(e={},n={}){return e.output==="metadata"?this.collectionClient.queryPages(e,n):this.collectionClient.queryPages(e,n)}queryAll(e={},n={}){return e.output==="metadata"?this.collectionClient.queryAll(e,n):this.collectionClient.queryAll(e,n)}listViews(e){return this.collectionClient.listViews(e)}executeView(e,n){return this.collectionClient.executeView(e,n)}executeViewPages(e,n={}){return this.collectionClient.executeViewPages(e,n)}readViewSource(e,n){return this.collectionClient.readViewSource(e,n)}createViewSource(e,n){return this.collectionClient.createViewSource(e,n)}updateViewSource(e,n){return this.collectionClient.updateViewSource(e,n)}deleteViewSource(e,n){return this.collectionClient.deleteViewSource(e,n)}create(e,n){return this.collectionClient.create(e,n)}update(e,n){return this.collectionClient.update(e,n)}delete(e,n){return this.collectionClient.delete(e,n)}preflightDelete(e,n){return this.collectionClient.preflightDelete(e,n)}rename(e,n){return this.collectionClient.rename(e,n)}preflightRename(e,n){return this.collectionClient.preflightRename(e,n)}async renameWithProgress(e,n={}){return $(n,this.internals.timeouts.requestMs,async i=>{let o=Date.now(),r=!1,s,a=(c,l,u=0)=>{n.onProgress?.({operation:"rename",state:c,elapsedMs:Date.now()-o,cancellable:l,resumed:r,completedUnits:u,...s?{estimate:s}:{}})};try{De(i.signal),a("preflighting",!0);let c=n.preflight?O(n.preflight):await this.preflightRename(e,{signal:i.signal,timeoutMs:null});if(!c.ok)return c;let l=c.value;try{Or(e,l)}catch(p){if(p instanceof _)return b(p.problem);throw p}s=Pr(e,l),a("ready",!0),De(i.signal);let u=this.transport.hasResumableMutationTransport();a("applying",u);let h=await this.rename(e,u?{signal:i.signal,timeoutMs:null}:{timeoutMs:js(i.remainingMs())});return h.ok&&a("completed",!1,s.totalUnits),h}catch(c){if(Fi(c,i.signal)&&a("cancelled",!1),c instanceof _)return b(c.problem);throw c}})}async deleteWithProgress(e,n={}){return $(n,this.internals.timeouts.requestMs,async i=>{let o=Date.now(),r=!1,s,a=(c,l,u=0)=>{n.onProgress?.({operation:"delete",state:c,elapsedMs:Date.now()-o,cancellable:l,resumed:r,completedUnits:u,...s?{estimate:s}:{}})};try{De(i.signal),a("preflighting",!0);let c=n.preflight?O(n.preflight):await this.preflightDelete(e,{signal:i.signal,timeoutMs:null});if(!c.ok)return c;let l=c.value;try{Sr(e,l)}catch(p){if(p instanceof _)return b(p.problem);throw p}s=Ar(l),a("ready",!0),De(i.signal);let u=this.transport.hasResumableMutationTransport();a("applying",u);let h=await this.delete(e,u?{signal:i.signal,timeoutMs:null}:{timeoutMs:js(i.remainingMs())});return h.ok&&a("completed",!1,s.totalUnits),h}catch(c){if(Fi(c,i.signal)&&a("cancelled",!1),c instanceof _)return b(c.problem);throw c}})}pendingMutations(){return this.transport.pendingMutations().map(e=>({...e,recover:n=>I(()=>this.recoverPendingMutation(e.requestId,n),H)}))}pendingMutation(e){let n=this.transport.pendingMutation(e);return n?{...n,recover:i=>I(()=>this.recoverPendingMutation(e,i),H)}:null}async recoverPendingMutation(e,n){let i=await this.transport.recoverPendingMutation(e,n);if(i&&typeof i=="object"&&"valid"in i){let o=i;if(!o.valid)throw new _(Ke(o));return o.result}return i}validate(e={},n){return this.collectionClient.validate(e,n)}readType(e,n){return this.collectionClient.readType(e,n)}createType(e,n){return this.collectionClient.createType(e,n)}updateType(e,n){return this.collectionClient.updateType(e,n)}assessTypePack(e,n){return this.collectionClient.assessTypePack(e,n)}applyTypePack(e,n){return this.collectionClient.applyTypePack(e,n)}assessCollectionSetup(e,n){return this.collectionClient.assessCollectionSetup(e,n)}applyCollectionSetup(e,n){return this.collectionClient.applyCollectionSetup(e,n)}listTimers(e,n){return this.collectionClient.listTimers(e,n)}putTimer(e,n){return this.collectionClient.putTimer(e,n)}cancelTimer(e,n){return this.collectionClient.cancelTimer(e,n)}reconcileTimers(e,n){return this.collectionClient.reconcileTimers(e,n)}watch(e={},n={}){return I(()=>k(n,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 _(o.problem);if(o.value.reset)throw new _(w("change_cursor_reset","The collection change cursor expired. Refresh collection state before subscribing again."));return new Tn(r=>this.collectionClient.watch(r),o.value.cursor,e,e.cursor===void 0?[]:o.value.events,this.internals.timeouts.watchStartMs)}),Zt)}emitConnection(){let e=this.info();for(let n of this.connectionListeners)n(e)}};function Gn(t,e){return{...t,timeoutMs:t?.timeoutMs===void 0?e:t.timeoutMs}}function js(t){return t===null?null:Math.max(1,Math.ceil(t))}async function Ks(t){if(typeof location>"u"&&!t.navigate&&!t.options.openVerification)throw d("browser_required","Authorization navigation requires a browser environment.");let n=(t.options.presentation==="popup"||t.portableDeclared)&&!t.options.openVerification&&!t.navigate&&typeof window<"u"?window.open("","mdbase-connect-authorization","popup,width=620,height=760"):null;try{return{application:await t.register(t.options.signal),popup:n}}catch(i){throw n?.close(),i}}async function Vs(t){let e=Hs(t.storagePrefix,t.state);try{for(;;){let n=F(t.storage.getItem(e));if(n?.version===1){if(t.storage.removeItem(e),n.status==="failed")throw L(n.code,n.message,{details:n.returnTo?{return_to:n.returnTo}:void 0});let i=t.connection(n.collectionId);if(!i)throw d("invalid_callback","Authorization completed without a usable saved connection.");return{kind:"connected",connection:i,...n.returnTo?{returnTo:n.returnTo}:{}}}await re(200,t.signal)}}finally{t.popup.close(),t.storage.removeItem(e);let n=`${t.storagePrefix}:pending:${t.state}`;F(t.storage.getItem(n))?.state===t.state&&(t.storage.removeItem(n),t.pending.keyHandle&&await t.keyStore.delete(t.pending.keyHandle))}}function Gs(t){return t.completion.then(e=>(t.popupAttempt&&Bs(t,{version:1,status:"connected",collectionId:e.connection.collectionId,...e.returnTo?{returnTo:e.returnTo}:{}}),t.popupAttempt&&Qs(),e)).catch(e=>{throw t.popupAttempt&&Bs(t,{version:1,status:"failed",code:e instanceof _?e.code:"invalid_callback",message:e instanceof Error?e.message:"Authorization could not be completed.",...t.pending?.returnTo?{returnTo:t.pending.returnTo}:{}}),t.popupAttempt&&Qs(),e})}function Bs(t,e){t.storage.setItem(Hs(t.storagePrefix,t.state),JSON.stringify(e))}function Hs(t,e){return`${t}:completion:${e}`}function Qs(){typeof window<"u"&&typeof window.close=="function"&&window.close()}function oo(t,e,n,i){let o=`${e}:pending-mutation:`,r=new Set;for(let s=0;s<t.length;s+=1){let a=t.key(s);if(!a?.startsWith(o))continue;let c=F(t.getItem(a));if(!c||!n.includes(c.operation)||i&&c.collectionId!==i)continue;let l=c.envelope?.protocol_version??c.request?.protocol_version;l!==void 0&&l!==Y&&_t(l)&&r.add(l)}return[...r].sort((s,a)=>a-s)}function ro(t,e,n){return so(t,e).has(n)}function so(t,e){let n=new Set;for(let i=0;i<t.length;i+=1){let o=t.key(i);if(o!==e&&!o?.startsWith(`${e}:`))continue;let r=F(t.getItem(o));r?.keyHandle&&n.add(r.keyHandle)}return n}function $s(t,e,n){let i=[e];for(let o=0;o<t.length;o+=1){let r=t.key(o);r?.startsWith(`${e}:`)&&i.push(r)}for(let o of i){let r=F(t.getItem(o));r?.keyHandle&&n(r.keyHandle),t.removeItem(o)}}function Ws({body:t,clientId:e,keyHandle:n,previous:i,retiredKeyHandles:o,defaultApplicationOrigin:r,pinConnectorIdentity:s}){let a=t.collection_id;if(typeof a!="string")throw d("invalid_token_response","Authorization returned no collection ID.");let c=hn(t.scope);if(!c)throw d("invalid_token_response","Authorization returned no valid collection scope.");if(!fn(c))throw d("legacy_scope_reauthorization_required","Authorization returned a legacy contract-scoped grant. Reauthorize for the entire collection.");if(t.authority&&!Et(t.authority,a))throw d("invalid_token_response","Authorization returned an invalid remote authority capability.");if(t.authority&&t.encryption)throw d("invalid_token_response","Authorization returned conflicting collection transports.");if(t.file_capability!==null&&t.file_capability!==void 0&&!pn(t.file_capability))throw d("invalid_token_response","Authorization returned an invalid file capability.");if(t.encryption){try{ye(t.encryption)}catch{throw d("invalid_token_response","Authorization returned an invalid encrypted relay binding.")}if(s(t.encryption.connector_id,t.encryption.connector_agreement_public_key),t.encryption.collection_id!==a||typeof t.grant_id!="string"||t.grant_id.length===0)throw d("invalid_token_response","Authorization returned an encrypted relay binding for another grant.")}if(i?.encryption&&t.encryption&&i.keyHandle&&i.keyHandle===n&&(i.grantId!==t.grant_id||i.encryption.connector_id!==t.encryption.connector_id||i.encryption.connector_agreement_public_key!==t.encryption.connector_agreement_public_key||i.encryption.application_agreement_public_key!==t.encryption.application_agreement_public_key))throw d("connector_identity_changed","The connector identity changed during authorization renewal. Reauthorize before sending collection data.");return{version:1,accessToken:t.access_token,refreshToken:t.refresh_token,clientId:e,collectionId:a,collectionName:t.collection_name??`Collection ${a.slice(0,8)}`,operations:t.operations,scope:c,expiresAt:Date.now()+t.expires_in*1e3,refreshExpiresAt:t.refresh_expires_in?Date.now()+t.refresh_expires_in*1e3:void 0,grantId:t.grant_id,encryption:t.encryption??void 0,fileCapability:t.file_capability??void 0,applicationOrigin:t.application_origin??r,keyHandle:n,...o?.length?{retiredKeyHandles:o}:{},savedAt:Date.now(),authority:t.authority?{operationsUrl:t.authority.operations_url,syncUrl:t.authority.sync_url,filesUrl:t.authority.files_url,replicaId:t.authority.replica_id,accessToken:t.authority.access_token,proofPublicKey:t.authority.proof_public_key}:void 0}}function ao(t,e){let n=new Set;if(e&&n.add(e),t?.keyHandle&&n.add(t.keyHandle),Array.isArray(t?.retiredKeyHandles))for(let i of t.retiredKeyHandles)typeof i=="string"&&i.length>0&&n.add(i);return n}function Js(t,e,n,i,o=[],r=!1){let s=[],a=[],c=ao(n);for(let u of so(t,e))c.add(u);let l=new Set(o);for(let u of l)c.add(u);for(let u of c)u!==i&&(r||l.has(u)||ro(t,e,u)?s:a).push(u);return{retained:s,disposable:a}}function kl(t,e,n){let i=F(t.getItem(e));if(!i||!Array.isArray(i.retiredKeyHandles))return;let o=i.retiredKeyHandles.filter(r=>r!==n);o.length!==i.retiredKeyHandles.length&&(o.length>0?i.retiredKeyHandles=o:delete i.retiredKeyHandles,t.setItem(e,JSON.stringify(i)))}async function Ys(t,e,n,i,o){F(t.getItem(i))?.keyHandle===o||ro(t,n,o)||(await e.delete(o),kl(t,i,o))}var Hn=class{serverUrl;manifest;manifestSource;redirectUri;storage;relayEncryption;keyStore;identityStore;directAccessMode;loopbackUrl;navigate;timeouts;credentialStorage;application=null;manifestPromise=null;completionPromises=new Ae;grantKeyLeases;connectionCache=new Map;listeners=new Set;invalidatedConnections=new Map;constructor(e){this.serverUrl=Lr(String(e.serverUrl));let n=Er(e.manifest,e.redirectUri);this.manifest=n.manifest,this.manifestSource=n.manifestSource;let i=Br(this.manifest);this.redirectUri=n.redirectUri,this.storage=e.storage??jr(i),this.relayEncryption=e.relayEncryption??"required",this.keyStore=e.keyStore??(i?new Ye:new Je),this.identityStore=e.identityStore??(i?new st:new rt),this.credentialStorage=e.storage||e.keyStore||e.identityStore?"custom":this.storage instanceof et?"memory":"persistent",this.directAccessMode=e.directAccess??"auto",this.loopbackUrl=qr(String(e.loopbackUrl??`http://127.0.0.1:${zo}`)),this.navigate=e.navigate,this.timeouts=We(e.timeouts),this.grantKeyLeases=new qn(this.storagePrefix(),(o,r)=>this.deleteGrantKeyWhenUnused(o,r)),typeof window<"u"&&this.storage===window.localStorage&&window.addEventListener("storage",o=>{o.storageArea!==this.storage||!o.key?.startsWith(this.storagePrefix())||(this.connectionCache.get(Nr(o.key))?.notifyStorageChanged(),this.emitConnections())})}environment(){return{distribution:typeof this.manifest!="string"&&this.manifest.distribution==="portable"?"portable":this.application?.distribution??"web",applicationOrigin:this.defaultApplicationOrigin(),credentialStorage:this.credentialStorage}}register(e={}){return k(e,this.timeouts.requestMs,n=>this.registerWithinBudget(n.signal))}async registerWithinBudget(e){if(this.application)return this.application;let n=await ae(`${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 E(n,"invalid_operation_response","Connect returned an invalid application registration response.");if(!n.ok)throw D(i,"discovery_failed","Application discovery failed.",n.status);return this.application=i.application,this.application}manifestDeclaration(e={}){if(this.manifestPromise)return this.manifestPromise;let i=k(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 n=this.manifest,i;try{i=await fetch(n,{headers:{accept:"application/json"},signal:e})}catch(o){throw d("manifest_load_failed","The bundled application declaration could not be loaded.",{cause:o})}if(!i.ok)throw d("manifest_load_failed",`The bundled application declaration returned HTTP ${i.status}.`,{status:i.status});try{return await E(i,"invalid_application_manifest","The bundled application declaration is not valid JSON.")}catch(o){throw d("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={}){let n=e.presentation==="popup"?6e5:this.timeouts.requestMs;return k(e,n,i=>this.authorizeWithinBudget({...e,signal:i.signal,timeoutMs:null}))}async authorizeWithinBudget(e){let n=typeof this.manifest!="string"&&this.manifest.distribution==="portable",{application:i,popup:o}=await Ks({options:e,portableDeclared:n,navigate:this.navigate,register:r=>this.registerWithinBudget(r)});try{Z(i.requirements,e),i.requirements.capabilities?.contract_version===2&&await Qr(this.serverUrl,e.signal)}catch(r){throw o?.close(),r}return i.distribution==="portable"?(e.openVerification&&o?.close(),this.authorizePortable(i,e,e.openVerification?null:o)):this.authorizeWeb(i,e,o)}async authorizeWeb(e,n,i){let{verifier:o,challenge:r}=await kt(),s=se(24),a=crypto.randomUUID(),c=n.target?.kind==="collection"?n.target.collectionId:void 0,l=`grant:${e.id}:${s}`,u=await this.keyStore.create(l),h;try{h=await this.loadApplicationIdentity(e)}catch(y){throw await this.keyStore.delete(l),y}let p=Ht(e,n),f=$t(e.requirements),m=new Date,P=await Lt({protocol_version:ce,authorization_id:a,application_id:e.id,application_declaration_id:qt(e.family_identity),application_manifest_digest:e.manifest_digest,application_installation_id:await at(h),installation_signing_public_key:h.signingPublicKey,grant_agreement_public_key:u.agreementPublicKey,grant_signing_public_key:u.signingPublicKey,flow:"authorization_code",authorization_nonce:se(32),issued_at:m.toISOString(),expires_at:new Date(m.getTime()+600*1e3).toISOString(),redirect_uri:this.redirectUri,state:s,code_challenge:r,contracts:ci(p,f,oo(this.storage,this.storagePrefix(),p,c),Q(e.requirements)),requested_operations:p,...f?{requested_files:f}:{},...c?{collection_id:c}:{}},h),v={version:1,verifier:o,state:s,clientId:e.id,redirectUri:this.redirectUri,relayEncryption:this.relayEncryption,collectionId:c,returnTo:n.returnTo,keyHandle:l,authorizationId:a,applicationAgreementPublicKey:u.agreementPublicKey,applicationSigningPublicKey:u.signingPublicKey,...n.presentation==="popup"&&i?{presentation:"popup"}:{}};this.storage.setItem(this.pendingKey(s),JSON.stringify(v));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:r,code_challenge_method:"S256",state:s,operations:p.join(","),...c?{collection_id:c}:{},application_authorization:JSON.stringify(P)}),signal:n.signal}),R=await E(y,"invalid_device_authorization_response","The authorization service returned an invalid authorization response.");if(!y.ok)throw D(R,"device_authorization_failed","Application authorization could not be started.",y.status);if(typeof R.authorization_uri!="string"||R.authorization_id!==a||!Number.isInteger(R.expires_in)||R.expires_in<=0)throw d("invalid_device_authorization_response","The authorization service returned an invalid authorization response.");if(n.presentation==="popup"&&i)return i.location.href=R.authorization_uri,await Vs({storage:this.storage,storagePrefix:this.storagePrefix(),state:s,pending:v,popup:i,signal:n.signal,keyStore:this.keyStore,connection:g=>this.connection(g)});if(i?.close(),this.navigate)await this.navigate(R.authorization_uri);else if(typeof location<"u")location.assign(R.authorization_uri);else throw d("browser_required","Authorization navigation requires a browser environment.");return{kind:"redirecting"}}catch(y){throw i?.close(),this.storage.removeItem(this.pendingKey(s)),await this.keyStore.delete(l),n.signal?.aborted?tt(n.signal,"Application authorization was cancelled.",y):y}}async authorizePortable(e,n,i){if(this.relayEncryption!=="required")throw i?.close(),d("encryption_required","Downloaded applications require encrypted relay authorization.");let{verifier:o,challenge:r}=await kt(),s=`grant:${e.id}:${se(24)}`,a=await this.keyStore.create(s),c;try{c=await this.loadApplicationIdentity(e)}catch(R){throw i?.close(),await this.keyStore.delete(s),R}let l=Ht(e,n),u=$t(e.requirements),h=crypto.randomUUID(),p=new Date,f=await Lt({protocol_version:ce,authorization_id:h,application_id:e.id,application_declaration_id:qt(e.family_identity),application_manifest_digest:e.manifest_digest,application_installation_id:await at(c),installation_signing_public_key:c.signingPublicKey,grant_agreement_public_key:a.agreementPublicKey,grant_signing_public_key:a.signingPublicKey,flow:"device_code",authorization_nonce:se(32),issued_at:p.toISOString(),expires_at:new Date(p.getTime()+600*1e3).toISOString(),code_challenge:r,contracts:ci(l,u,oo(this.storage,this.storagePrefix(),l,n.target?.kind==="collection"?n.target.collectionId:void 0),Q(e.requirements)),requested_operations:l,...u?{requested_files:u}:{},...n.target?.kind==="collection"?{collection_id:n.target.collectionId}:{}},c),m,P;try{m=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:l.join(","),...n.target?.kind==="collection"?{collection_id:n.target.collectionId}:{},code_challenge:r,code_challenge_method:"S256",application_authorization:JSON.stringify(f)}),signal:n.signal}),P=await E(m,"invalid_device_authorization_response","The authorization service returned an invalid device authorization response.")}catch(R){throw i?.close(),await this.keyStore.delete(s),d("device_authorization_failed","Downloaded application authorization could not be started.",{cause:R})}if(!m.ok)throw i?.close(),await this.keyStore.delete(s),D(P,"device_authorization_failed","Downloaded application authorization could not be started.",m.status);let v;try{v=Dr(P)}catch(R){throw i?.close(),await this.keyStore.delete(s),n.signal?.aborted?tt(n.signal,"Downloaded application authorization was cancelled.",R):R}if(n.onDeviceCode?.(v),n.openVerification)await n.openVerification(v);else if(i)try{i.location.href=v.verificationUriComplete}catch{}else throw await this.keyStore.delete(s),d("approval_window_blocked","The approval window was blocked. Show the provided verification link and code, then try again.",{details:{user_code:v.userCode,verification_uri:v.verificationUri,verification_uri_complete:v.verificationUriComplete,expires_at:v.expiresAt,interval_seconds:v.intervalSeconds}});let y=v.intervalSeconds;try{for(;Date.now()<v.expiresAt;){if(await re(y*1e3,n.signal),n.signal?.aborted)throw tt(n.signal,"Downloaded application authorization was cancelled.");let R;try{R=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:P.device_code,client_id:e.id,code_verifier:o}),signal:n.signal})}catch(T){if(n.signal?.aborted)throw tt(n.signal,"Downloaded application authorization was cancelled.",T);continue}let g=await E(R,"invalid_token_response","The authorization service returned an invalid token response.");if(!R.ok){let T=xt(g);if(T==="authorization_pending")continue;if(T==="slow_down"){y+=5;continue}throw D(g,"token_exchange_failed","Downloaded application authorization could not be completed.",R.status)}let A=Et(g.authority,g.collection_id),z=g.encryption&&g.encryption.protocol_version===Yt&&g.encryption.suite===Ct&&g.encryption.application_agreement_public_key===a.agreementPublicKey;if(g.application_origin!==this.defaultApplicationOrigin())throw d("invalid_token_response","Authorization did not bind the portable grant to its exact application origin.");if(g.authority&&(!A||g.encryption!=null||g.authority.proof_public_key!==a.signingPublicKey))throw d("invalid_token_response","Authorization returned a remote authority capability that is not bound to this portable grant key.");if(!g.authority&&!z)throw d("encryption_required","Authorization did not establish the expected key-bound local portable grant.");let S=this.storeTokenResponse(g,e.id,s);if(n.target?.kind==="collection"&&n.target.collectionId!==S.collectionId)throw this.removeToken(S.collectionId,S.keyHandle),d("collection_mismatch","The approved collection does not match the collection requested by this link.");return i?.close(),{kind:"connected",connection:this.connection(S.collectionId),...n.returnTo?{returnTo:n.returnTo}:{}}}throw d("expired_token","The downloaded application authorization code expired.")}catch(R){throw i?.close(),await this.keyStore.delete(s),n.signal?.aborted?tt(n.signal,"Downloaded application authorization was cancelled.",R):R}}completeAuthorization(e,n={}){let i=gn(e);if(!i)return Promise.reject(d("invalid_callback","Authorization callback is missing its state."));let o=F(this.storage.getItem(this.pendingKey(i))),r=o?.presentation==="popup";return this.completionPromises.run(i,n,this.timeouts.requestMs,s=>Gs({storage:this.storage,storagePrefix:this.storagePrefix(),state:i,pending:o,popupAttempt:r,completion:this.performAuthorizationCompletion(e,i,s)}))}async performAuthorizationCompletion(e,n,i){let o=new URL(e),r=o.searchParams.get("code"),s=this.pendingKey(n),a=F(this.storage.getItem(s));if(!a||a.version!==1||n!==a.state)throw d("invalid_callback","Authorization callback is missing or does not match this browser session.");if(o.searchParams.has("error"))throw a.keyHandle&&await this.keyStore.delete(a.keyHandle),this.storage.removeItem(s),L(o.searchParams.get("error")??"access_denied",o.searchParams.get("error_description")??"Collection access was not approved.",{details:a.returnTo?{return_to:a.returnTo}:void 0});if(!r)throw d("invalid_callback","Authorization callback is missing its code.");let c=await ae(`${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:a.clientId,redirect_uri:a.redirectUri,code_verifier:a.verifier}),signal:i},"temporarily_unavailable","Authorization completion is temporarily unavailable."),l=await E(c,"invalid_token_response","The authorization service returned an invalid token response.");if(!c.ok)throw D(l,"token_exchange_failed","Authorization could not be completed.",c.status);if(a.relayEncryption==="required"&&!l.authority&&(!l.encryption||!a.keyHandle||l.encryption.application_agreement_public_key!==a.applicationAgreementPublicKey))throw a.keyHandle&&await this.keyStore.delete(a.keyHandle),this.storage.removeItem(s),d("encryption_required","Authorization did not establish the required encrypted relay grant.");if(l.authority?.proof_public_key){if(!a.keyHandle||!a.applicationSigningPublicKey||l.authority.proof_public_key!==a.applicationSigningPublicKey)throw a.keyHandle&&await this.keyStore.delete(a.keyHandle),this.storage.removeItem(s),d("invalid_token_response","Authorization returned a remote authority capability bound to another application key.")}else l.authority&&a.keyHandle&&await this.keyStore.delete(a.keyHandle);let u=this.storeTokenResponse(l,a.clientId,l.authority?.proof_public_key?a.keyHandle:l.authority?void 0:a.keyHandle);if(a.collectionId&&a.collectionId!==u.collectionId)throw this.removeToken(u.collectionId,u.keyHandle),this.storage.removeItem(s),d("collection_mismatch","The approved collection does not match the collection requested by this link.");return this.storage.removeItem(s),{connection:this.connection(u.collectionId),...a.returnTo?{returnTo:a.returnTo}:{}}}connections(){let e=[];for(let n of un(this.storage,this.storagePrefix())){let i=this.connection(n)?.info();i&&e.push(i)}return e.sort((n,i)=>n.displayName.localeCompare(i.displayName)||n.collectionId.localeCompare(i.collectionId))}connection(e){if(!this.storage.getItem(this.tokenKey(e)))return null;let n=this.connectionCache.get(e);return n||(n=new yt(this,e),this.connectionCache.set(e,n)),n.info()?n:null}unavailableReason(e){return this.invalidatedConnections.get(e)??null}connectionApplicationId(e){if(!this.connection(e))return null;let n=F(this.storage.getItem(this.tokenKey(e)));return typeof n?.clientId=="string"&&n.clientId.length>0?n.clientId:null}onConnectionsChange(e){return this.listeners.add(e),e(this.connections()),()=>this.listeners.delete(e)}storeTokenResponse(e,n,i){let o=e.collection_id;if(typeof o!="string")throw d("invalid_token_response","Authorization returned no collection ID.");let r=F(this.storage.getItem(this.tokenKey(o))),s=Js(this.storage,this.pendingMutationKey(o),r,i,this.grantKeyLeases.handles(o),this.grantKeyLeases.retainAutomaticallyRetiredKeys),a;try{a=Ws({body:e,clientId:n,keyHandle:i,previous:r,retiredKeyHandles:s.retained,defaultApplicationOrigin:this.defaultApplicationOrigin(),pinConnectorIdentity:(c,l)=>this.pinConnectorIdentity(c,l)})}catch(c){throw c instanceof _&&c.code==="legacy_scope_reauthorization_required"&&this.removeToken(o,i,c.code),c}this.storage.setItem(this.tokenKey(o),JSON.stringify(a));for(let c of s.disposable)this.deleteGrantKeyWhenUnused(o,c);return Ir(this.storage,this.storagePrefix(),o),this.invalidatedConnections.delete(o),this.connectionCache.delete(o),this.emitConnections(),a}forgetConnectorIdentity(e){this.storage.removeItem(this.connectorPinKey(e))}pinConnectorIdentity(e,n){let i=this.connectorPinKey(e),o=F(this.storage.getItem(i));if(o&&(o.version!==1||o.publicKey!==n))throw d("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:n}))}connectorPinKey(e){return`mdbase-connect:${this.serverUrl}:connector-pin:${e}`}async loadApplicationIdentity(e){try{return await bn(this.identityStore,this.serverUrl,e)}catch(n){throw d("application_identity_unavailable",n instanceof Le?n.message:"The application installation identity is unavailable.",{cause:n})}}removeToken(e,n,i="authorization_lost",o=!1){this.invalidatedConnections.set(e,i);let r=F(this.storage.getItem(this.tokenKey(e))),s=ao(r,n);this.storage.removeItem(this.tokenKey(e)),o&&$s(this.storage,this.pendingMutationKey(e),a=>s.add(a));for(let a of s)this.deleteGrantKeyWhenUnused(e,a);for(let a of["web_push","fcm"])this.storage.removeItem(this.notificationKey(e,a));kr(this.storage,this.storagePrefix(),e),this.connectionCache.delete(e),this.emitConnections()}acquireGrantKeyLease(e,n,i){return this.grantKeyLeases.acquire(e,n,i)}deleteGrantKeyWhenUnused(e,n){this.grantKeyLeases.deleteExclusive(e,n,()=>Ys(this.storage,this.keyStore,this.pendingMutationKey(e),this.tokenKey(e),n))}tokenKey(e){return`${this.storagePrefix()}:token:${e}`}pendingMutationKey(e){return`${this.storagePrefix()}:pending-mutation:${e}`}notificationKey(e,n="web_push"){return`${this.storagePrefix()}:notifications:${e}:${n}`}directPreferenceKey(){return`mdbase-connect:direct:${this.defaultApplicationOrigin()}`}defaultApplicationOrigin(){return Ur(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}`}emitConnections(){let e=this.connections();for(let n of this.listeners)n(e)}};var $n=class{internals;constructor(e){this.internals=new Hn(e)}register(e){return I(()=>this.internals.register(e),qe)}authorize(e={}){return I(()=>this.internals.authorize(e),ve)}application(e){return new it(this,e,this.internals.timeouts)}manifest(e){return I(()=>this.internals.manifestDeclaration(e),qe)}environment(){return this.internals.environment()}completeAuthorization(e,n){return I(()=>this.internals.completeAuthorization(e===void 0?mn():String(e),n),ve)}connections(){return this.internals.connections()}connection(e){return this.internals.connection(e)}unavailableReason(e){return this.internals.unavailableReason(e)}connectionApplicationId(e){return this.internals.connectionApplicationId(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 co(t){if(!t||typeof t!="object")throw d("invalid_push_payload","The push payload is not an object.");let e=t;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 d("invalid_push_payload","The push payload is not an mdbase notification.");return e}function Xs(t){if(!t||typeof t!="object")throw d("invalid_push_payload","The native notification data is not an object.");let e=t;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 d("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 Zs(t,e){let n=co(e);return t.showNotification(n.presentation.title,{...n.presentation.body?{body:n.presentation.body}:{},...n.presentation.tag?{tag:n.presentation.tag}:{},data:{type:n.type,signal_id:n.signal_id,criterion_id:n.criterion_id,cursor:n.cursor}})}function ea(t,e,n={}){let i=JSON.stringify(t),o=`record[${i}]`,r=JSON.stringify(e),s=a=>`${a} != null && ${a}.asFile() != null && ${a}.asFile().file.path == ${r}`;return`${i} in record && ${n.multiple?`${o} != null && ${o}.exists(link, ${s("link")})`:s(o)}`}function ta(t){return{subscribe:e=>t.subscribe(e),getSnapshot:()=>t.getSnapshot()}}var Wn=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,n={}){let i=Ft(this.currentUrl());e?i.searchParams.set(this.collectionParameter,e):i.searchParams.delete(this.collectionParameter);let o=this.browserHistory();o[n.history==="push"?"pushState":"replaceState"](o.state,"",i),this.emit()}authorizationReturnTo(){let e=Ft(this.currentUrl());return`${e.pathname}${e.search}${e.hash}`}authorizationCallback(){let e=this.currentUrl().href;return yn(e)?e:null}finishAuthorization(e,n){let i=this.safeAppUrl(e??this.fallbackPath);Ft(i),i.searchParams.set(this.collectionParameter,n),this.browserHistory().replaceState(null,"",i),this.emit()}clearAuthorizationCallback(e){let n=e?this.safeAppUrl(e):this.currentUrl(),i=this.browserHistory();i.replaceState(i.state,"",Ft(n)),this.emit()}subscribe(e){let n=this.listeners.size===0;return this.listeners.add(e),n&&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 n=this.currentUrl(),i=new URL(e,n.origin);return i.origin===n.origin?i:new URL(this.fallbackPath,n.origin)}currentUrl(){if(typeof location>"u")throw d("browser_required","Browser selection requires a browser environment.");return new URL(location.href)}browserHistory(){if(typeof history>"u")throw d("browser_required","Browser selection requires a browser environment.");return history}},Jn=class{collectionId=null;listeners=new Set;selectedCollectionId(){return this.collectionId}select(e){if(e!==this.collectionId){this.collectionId=e;for(let n of this.listeners)n()}}authorizationReturnTo(){}authorizationCallback(){return null}finishAuthorization(e,n){this.select(n)}clearAuthorizationCallback(){}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}};return aa(xl);})();