@mdbase-dev/connect 0.1.0-beta.121 → 0.1.0-beta.124
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +161 -6
- package/dist/application-session.js +51 -27
- package/dist/authority-features.d.ts +29 -0
- package/dist/authority-features.js +84 -0
- package/dist/browser/integrity.json +1 -1
- package/dist/browser/mdbase-connect.min.js +4 -4
- package/dist/browser/mdbase-connect.min.js.sha384 +1 -1
- package/dist/change-events.d.ts +6 -0
- package/dist/change-events.js +95 -0
- package/dist/collection-client.d.ts +13 -3
- package/dist/collection-client.js +98 -140
- package/dist/connection.d.ts +12 -2
- package/dist/connection.js +57 -117
- package/dist/description-cache.d.ts +14 -0
- package/dist/description-cache.js +46 -0
- package/dist/file-crypto.js +10 -6
- package/dist/file-descriptor.d.ts +14 -0
- package/dist/file-descriptor.js +29 -0
- package/dist/file-metadata.d.ts +21 -0
- package/dist/file-metadata.js +112 -0
- package/dist/file-sha256.js +3 -3
- package/dist/files.d.ts +9 -19
- package/dist/files.js +49 -75
- package/dist/index.d.ts +5 -2
- package/dist/index.js +2 -0
- package/dist/local-file-transport.js +18 -16
- package/dist/operation-types.d.ts +155 -14
- package/dist/query-pagination-internals.d.ts +9 -0
- package/dist/query-pagination-internals.js +52 -0
- package/dist/query-pagination.d.ts +7 -3
- package/dist/query-pagination.js +31 -27
- package/dist/query-predicates.d.ts +11 -0
- package/dist/query-predicates.js +15 -0
- package/dist/query-wire.d.ts +61 -0
- package/dist/query-wire.js +110 -0
- package/dist/read-many.d.ts +7 -0
- package/dist/read-many.js +175 -0
- package/dist/record-session.d.ts +3 -2
- package/dist/record-session.js +11 -2
- package/dist/records.d.ts +15 -2
- package/dist/records.js +109 -7
- package/dist/saved-view-pagination.js +20 -20
- package/dist/startup-timing.d.ts +2 -0
- package/dist/startup-timing.js +20 -0
- package/dist/structured-readiness.d.ts +3 -1
- package/dist/structured-readiness.js +21 -1
- package/dist/watch-policy.d.ts +22 -1
- package/dist/watch-policy.js +104 -0
- package/package.json +2 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var MdbaseConnect=(()=>{var On=Object.defineProperty;var ps=Object.getOwnPropertyDescriptor;var fs=Object.getOwnPropertyNames;var hs=Object.prototype.hasOwnProperty;var ms=(t,e)=>{for(var n in e)On(t,n,{get:e[n],enumerable:!0})},ys=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of fs(e))!hs.call(t,o)&&o!==n&&On(t,o,{get:()=>e[o],enumerable:!(i=ps(e,o))||i.enumerable});return t};var gs=t=>ys(On({},"__esModule",{value:!0}),t);var Dc={};ms(Dc,{ApplicationIdentityStoreError:()=>Oe,FileTransferCryptoError:()=>le,GrantFileTransferCipher:()=>Je,IndexedDbApplicationIdentityStore:()=>Ve,IndexedDbGrantKeyStore:()=>Fe,MDBASE_RECORD_CREATED_CONTRACT:()=>$i,MDBASE_TIMER_FIRED_CONTRACT:()=>Wi,MdbaseApplicationSession:()=>Be,MdbaseBrowserSelection:()=>Rn,MdbaseCollectionClient:()=>We,MdbaseConnect:()=>Sn,MdbaseConnectError:()=>v,MdbaseConnection:()=>nt,MdbaseFileClient:()=>Ze,MdbaseMemorySelection:()=>Pn,MdbaseMemoryVerificationStore:()=>Ct,MdbasePeopleClient:()=>$e,MdbaseRecordSession:()=>et,MdbaseRecords:()=>tt,MdbaseSession:()=>je,MemoryApplicationIdentityStore:()=>Ge,MemoryGrantKeyStore:()=>De,PERSON_CONTRACT:()=>St,RelayCryptoError:()=>x,applicationIdentity:()=>Qt,applicationInstallationId:()=>He,authorityProofMessage:()=>Gn,connectError:()=>d,connectFailure:()=>y,connectProblem:()=>w,connectSuccess:()=>S,createPkce:()=>mt,decryptRelayResponse:()=>ze,deriveFileTransferKey:()=>ei,deriveP256SharedSecret:()=>pt,effectiveCapabilities:()=>Ft,encryptRelayRequest:()=>ae,externalStore:()=>ds,isRetryableConnectError:()=>Xi,operationProblem:()=>Me,operationsForApplicationCapabilities:()=>Si,parseMdbaseNativeNotificationData:()=>cs,parseMdbasePushPayload:()=>wi,sameIdentity:()=>Xt,showMdbasePushNotification:()=>ls,signApplicationAuthorization:()=>wt,signAuthorityRequest:()=>jt,validateGrantEncryption:()=>ce});var Pt={"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"]},Ot=["assess_collection_setup","apply_collection_setup"];function Si(t,e={}){let n=e.includeOptional===!1?t.required:[...t.required,...t.optional??[]];return[...new Set(n.flatMap(i=>Pt[i]))]}var bs=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 W(t,e){let n=t===1?bs:t===2?Pt:void 0;if(!(!n||!Object.hasOwn(n,e)))return[...n[e]]}var Lc=Object.freeze([1,2]),Ri="application-authorization-v2-issuance",An=Object.freeze(["application-authorization-v2-issuance"]);var Pi="yaml-document-records-v1";var ve={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_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"}},_s={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 Oi(t){return Object.hasOwn(ve,t)}function it(t){if(!Ai(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"||!Oi(e.code)||e.server_code!==void 0)return!1;let n=ve[e.code],i=_s[e.code],o=i===void 0?e.details===void 0:e.details===void 0?(i.required?.length??0)===0:Tn(e.details,i);return e.category===n.category&&e.recovery===n.recovery&&o}function Tn(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=>Tn(i,e.items??{}));if(!Ai(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])=>Tn(o,e.properties[i]))}function Ai(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function kn(t,e,n={}){if(Oi(t)){let i=ve[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(it(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 Ti=new Uint8Array([77,68,66,70]),ki=1,Ii=0,Kc=new Uint8Array([77,68,66,82]);var Mi=/^[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 xi(t,e={}){return{actions:[...new Set([...t.required,...e.includeOptional===!1?[]:t.optional??[]])],scope:structuredClone(t.scope)}}var I=class extends Error{code;constructor(e,n){super(n),this.code=e,this.name="FileFrameError"}};function vs(t){return t==="upload_chunk"?1:2}function Cs(t){if(t===1)return"upload_chunk";if(t===2)return"download_chunk";throw new I("invalid_kind",`Unknown file frame kind ${t}`)}function ws(t){if(!t||typeof t!="object"||Array.isArray(t))throw new I("invalid_header","File frame header must be a JSON object");return t}function Tt(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new I("invalid_header",`File frame header ${e} must be a non-empty string`);return n}function At(t,e){let n=Tt(t,e);if(!Mi.test(n))throw new I("invalid_header",`File frame header ${e} must be a UUID`);return n}function Ce(t,e,n=Number.MAX_SAFE_INTEGER){let i=t[e];if(!Number.isSafeInteger(i)||i<0||i>n)throw new I("invalid_header",`File frame header ${e} is outside its allowed range`);return i}function In(t){if(t.protocol_version!==1)throw new I("unsupported_version",`Unsupported file transfer protocol ${t.protocol_version}`);if(t.protection!=="grant_aead_v1"&&t.protection!=="transport_tls")throw new I("invalid_header","Unknown file transfer protection");if(t.direction!=="upload"&&t.direction!=="download")throw new I("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(!Mi.test(n))throw new I("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 I("invalid_header",`File frame header ${e} is outside its allowed range`);if(t.chunk_size<64*1024)throw new I("invalid_header","File frame chunk_size is below the protocol minimum");if(!Number.isSafeInteger(t.scope_epoch)||t.scope_epoch<1)throw new I("invalid_header","File frame header scope_epoch must be a positive integer");if(t.protection==="grant_aead_v1"&&!t.key_id)throw new I("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 Ss(t){let e;try{e=new TextDecoder("utf-8",{fatal:!0}).decode(t)}catch{throw new I("invalid_header","File frame header is not valid UTF-8")}let n;try{n=ws(JSON.parse(e))}catch(l){throw l instanceof I?l:new I("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 I("invalid_header","File frame header contains an unknown field");let o=Ce(n,"protocol_version");if(o!==1)throw new I("unsupported_version",`Unsupported file transfer protocol ${o}`);let r=Tt(n,"protection"),s=Tt(n,"direction"),a=n.key_id===void 0?void 0:Tt(n,"key_id"),c=In({protocol_version:1,protection:r,grant_id:At(n,"grant_id"),authority_id:At(n,"authority_id"),collection_id:At(n,"collection_id"),transfer_id:At(n,"transfer_id"),direction:s,chunk_size:Ce(n,"chunk_size",4194304),chunk_index:Ce(n,"chunk_index"),offset:Ce(n,"offset"),plaintext_length:Ce(n,"plaintext_length",4194304),total_size:Ce(n,"total_size"),scope_epoch:Ce(n,"scope_epoch"),...a===void 0?{}:{key_id:a}});if(JSON.stringify(c)!==e)throw new I("invalid_header","File frame header must use the canonical field order without duplicate fields or whitespace");return c}function Mn(t,e,n){let i=t==="upload_chunk"?"upload":"download";if(e.direction!==i)throw new I("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 I("invalid_header","Chunk offset does not match its index and protocol chunk size");if(e.offset+e.plaintext_length>e.total_size)throw new I("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 I("invalid_length","Payload length does not match the protected plaintext length")}function Rs(t){return t.plaintext_length+(t.protection==="grant_aead_v1"?16:0)}function kt(t,e){let n=In(e),i=Rs(n);Mn(t,n,i);let o=new TextEncoder().encode(JSON.stringify(n));if(o.byteLength>16384)throw new I("limit_exceeded","File frame header exceeds the protocol limit");let r=new Uint8Array(16+o.byteLength);r.set(Ti,0);let s=new DataView(r.buffer,r.byteOffset,r.byteLength);return s.setUint8(4,ki),s.setUint8(5,vs(t)),s.setUint16(6,Ii,!1),s.setUint32(8,o.byteLength,!1),s.setUint32(12,i,!1),r.set(o,16),r}function Ei(t){let e=In(t.header);if(Mn(t.kind,e,t.payload.byteLength),t.payload.byteLength>4194320)throw new I("limit_exceeded","File frame payload exceeds the protocol limit");let n=kt(t.kind,e),i=new Uint8Array(n.byteLength+t.payload.byteLength);return i.set(n,0),i.set(t.payload,n.byteLength),i}function It(t,e={}){if(t.byteLength<16)throw new I("invalid_length","File frame is shorter than its fixed prefix");if(!Ti.every((f,h)=>t[h]===f))throw new I("invalid_magic","File frame magic is not MDBF");let n=new DataView(t.buffer,t.byteOffset,t.byteLength),i=n.getUint8(4);if(i!==ki)throw new I("unsupported_version",`Unsupported file frame version ${i}`);let o=Cs(n.getUint8(5));if(n.getUint16(6,!1)!==Ii)throw new I("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 I("invalid_length","File frame header must not be empty");if(r>a||s>c)throw new I("limit_exceeded","File frame exceeds the configured decode limits");let l=16+r+s;if(!Number.isSafeInteger(l)||l!==t.byteLength)throw new I("invalid_length","File frame lengths do not match the supplied bytes");let u=16+r,p=Ss(t.subarray(16,u));return Mn(o,p,s),{kind:o,header:p,payload:t.slice(u)}}var Ps=["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"],Os=["list_files","open_file_upload","open_file_download","move_file","delete_file","get_file_transfer_status","commit_file_upload","abort_file_transfer"],As={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"},Ts={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},ks={list_files:1,open_file_upload:1,open_file_download:1,move_file:1,delete_file:1,get_file_transfer_status:1,commit_file_upload:1,abort_file_transfer:1},Is=new Set(["open_file_upload","move_file","delete_file","commit_file_upload","abort_file_transfer"]),Ms=new Set(["delete","rename"]);var xs=new Set(Ps),Es=new Set(Os);function qi(t){return xs.has(t)}function qs(t){return Es.has(t)}function Fi(t,e){if(t==="file_control"){let n=Di(e)&&typeof e.type=="string"?e.type:"";if(!qs(n))throw new Error(`Unknown file-control message: ${n}`);return ks[n]}return Ts[t]}function ue(t,e){let n=Di(e)?e:{};if(n.dry_run===!0&&Ms.has(t))return null;if(t==="file_control"){let o=typeof n.type=="string"?n.type:"";return Is.has(o)?`file_control:${o}`:null}let i=As[t];return i==="always"?t:i==="sync_action"&&n.action==="mutate"?"sync:mutate":null}function pe(t,e){return ue(t,e)!==null}function Di(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var Fs=1,Ds="mdbase-connect mutation fingerprint v1\0",xn=new TextEncoder;function zs(t){return En(t,new Set)}function Us(t,e){let n=ue(t,e);if(n===null)throw new TypeError("The operation is not a canonical mutation.");let i=xn.encode(n),o=xn.encode(zs(e)),r=xn.encode(Ds),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,Fs,!1),c+=4,c=Ui(s,a,c,i),a.setUint32(c,Fi(t,e),!1),c+=4,Ui(s,a,c,o),s}async function Li(t,e){let n=new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",Us(t,e).buffer));return Ls(n)}function En(t,e){if(t===null)return"null";if(t===!0)return"true";if(t===!1)return"false";if(typeof t=="string")return zi(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(En(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)zi(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)}:${En(r,e)}`}).join(",")}}`}finally{e.delete(t)}}function zi(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 Ui(t,e,n,i){return e.setBigUint64(n,BigInt(i.length),!1),n+=8,t.set(i,n),n+i.length}function Ls(t){return btoa(String.fromCharCode(...t)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}var $=3,js=2,Ni=[$,js],ie=5,qn=4,ji=[ie,qn],Bs=2,Ks=1,Jc={operation_transport:[...Ni],authorization_binding:[...ji],semantic_capabilities:[Bs,1],durable_mutation:[Ks]};function Fn(t,e,n=[],i=2){let o={operation_transport:$,authorization_binding:ie,semantic_capabilities:i},r=[...new Set(n)].filter(s=>s!==$).sort((s,a)=>a-s);return r.length>0&&(o.operation_transport_recovery=r),(t.some(s=>pe(s,{action:"mutate"}))||e?.actions.some(s=>s!=="list"&&s!=="read")===!0)&&(o.durable_mutation=1),o}function ot(t){return Ni.includes(t)}function Bi(t){return ji.includes(t)}var Vs=new TextEncoder().encode("mdbase-connect application installation id v2\0"),Gs=new TextEncoder().encode("mdbase-connect application authorization proof v4\0"),Hs=new TextEncoder().encode("mdbase-connect application authorization proof v5\0");async function Vi(t){let e=Mt(t),i=new Uint8Array(await crypto.subtle.digest("SHA-256",we([Vs,N(e)]))).slice(0,16);return i[6]=i[6]&15|128,i[8]=i[8]&63|128,[rt(i.slice(0,4)),rt(i.slice(4,6)),rt(i.slice(6,8)),rt(i.slice(8,10)),rt(i.slice(10,16))].join("-")}function Gi(t){let e=[Mt(t.installation_signing_public_key),Mt(t.grant_agreement_public_key),Mt(t.grant_signing_public_key)];if(e.some((c,l)=>e.slice(l+1).some(u=>Xs(c,u))))throw new Error("Application authorization keys must be distinct.");let n=Dn(t.authorization_nonce),i=Dn(t.code_challenge),o=t.contracts,r=o.operation_transport_recovery??[],s=t.requested_operations.some(c=>pe(c,{action:"mutate"}))||t.requested_files?.actions.some(c=>!["list","read"].includes(c))===!0;if(!Bi(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||!ot(o.operation_transport)||t.protocol_version===ie&&o.operation_transport!==$||r.some(c=>!ot(c)||c===o.operation_transport)||new Set(r).size!==r.length||t.protocol_version===qn&&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.");Ws(t.requested_files);let a=t.requested_operations.map(c=>N(new TextEncoder().encode(c)));return we([t.protocol_version===ie?Hs:Gs,Y(t.protocol_version),N(xt(t.application_id)),N(xt(t.authorization_id)),N(new TextEncoder().encode(t.application_declaration_id)),N(Hi(t.application_manifest_digest)),N(xt(t.application_installation_id)),...e.map(N),N(new TextEncoder().encode(t.flow)),N(n),N(new TextEncoder().encode(t.issued_at)),N(new TextEncoder().encode(t.expires_at)),Ki(t.redirect_uri),Ki(t.state),N(new TextEncoder().encode(t.code_challenge)),Y(o.operation_transport),...t.protocol_version===ie?[Y(r.length),...r.map(Y)]:[],Y(o.authorization_binding),Y(o.semantic_capabilities),$s(o.durable_mutation),Y(a.length),...a,Js(t.requested_files),Qs(t.collection_id)])}function $s(t){return t===void 0?new Uint8Array(1):we([new Uint8Array([1]),Y(t)])}function Ws(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 Js(t){if(t===void 0)return new Uint8Array(1);let e=t.actions.map(n=>N(new TextEncoder().encode(n)));return we([new Uint8Array([1]),Y(e.length),...e,N(new TextEncoder().encode(t.scope.kind)),...t.scope.kind==="selected_folders"?[Y(t.scope.folders.length),...t.scope.folders.map(n=>N(new TextEncoder().encode(n)))]:[]])}function Ki(t){return t===void 0?new Uint8Array(1):we([new Uint8Array([1]),N(new TextEncoder().encode(t))])}function Qs(t){return t===void 0?new Uint8Array(1):we([new Uint8Array([1]),N(xt(t))])}function Mt(t){let e=Dn(t);if(e.byteLength!==65||e[0]!==4)throw new Error("Application authorization public key is invalid.");return e}function Dn(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(Ys(i)!==t)throw new Error("Non-canonical base64url value.");return i}function xt(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 Hi(e)}function Hi(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 N(t){return we([Y(t.byteLength),t])}function Y(t){let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t,!1),e}function we(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 Ys(t){return btoa(String.fromCharCode(...t)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}function Xs(t,e){return t.byteLength===e.byteLength&&t.every((n,i)=>n===e[i])}function rt(t){return[...t].map(e=>e.toString(16).padStart(2,"0")).join("")}var $i={id:"mdbase.record.created",version:"1.0.0",digest:"sha256:7f3bed6baa356ee9389e977ae7b77a102e2bee871a7c1d9f2026fc21cacdbfc9"};var Wi={id:"mdbase.runtime.timer.fired",version:"1.0.0",digest:"sha256:41105be7a7abf33b31ced47e1e1965242236e40ccaea286b959b0a8c591f5642"};var Ji=28485,st="P256-HKDF-SHA256-AES256GCM",Et=1;var Zs="contract-setup-v1",ea="file-relay-v1",ta="protocol-usage-report-v1",na="policy-freshness-lease-v1",ia=["application-authorization-v4","authorization-activation","encrypted-relay","policy-ack"];var oa=["durable-mutation-journal-v1","durable-file-lifecycle-v1","contract-metadata-read-v1"],ra="candidate-b-activation-v1",il=[...An,...oa,"mutation-replay-after-credential-retirement-v1",ra],sa="application-declaration-evidence-v1",ol=[...An,sa,...ia,na,"application-authorization-v5",Zs,ea,ta,Pi],zn=1;var Qi="mdbase-authority-request-proof-v1",at={version:"x-mdbase-proof-version",timestamp:"x-mdbase-proof-timestamp",nonce:"x-mdbase-proof-nonce",signature:"x-mdbase-proof-signature"};var v=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=ve[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 Yi(t,e,n={}){return kn(t,e,{details:n.details,operation_outcome:n.operationOutcome,trace_id:n.traceId})}function d(t,e,...n){let i=n[0];return new v(w(t,e,...n),{status:i?.status,cause:i?.cause})}function z(t,e,n={}){let{status:i,cause:o,...r}=n;return new v(kn(t,e,{details:r.details,operation_outcome:r.operationOutcome,trace_id:r.traceId}),{status:i,cause:o})}function Me(t){let e=ca(t.diagnostics),n=ua(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=la(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 ca(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 la(t){let e=t.map(n=>n.details).find(n=>da(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 da(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Xi(t){return t instanceof v&&t.retryable}function ua(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 Se=["describe","changes","read","query"];function j(t){let e=t.capabilities===void 0?1:t.capabilities?.contract_version;return e!==1&&e!==2&&xe("Unsupported declared capability contract version."),e}function xe(t){throw d("invalid_application_manifest",t,{details:{issues:[{path:"/requirements/capabilities",keyword:"authorizationSelection",message:t,params:{}}]}})}function X(t,e){if(e.operations!==void 0&&e.capabilities!==void 0&&xe("Specify operations or capabilities, not both."),e.operations!==void 0&&j(t)!==1&&xe("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)||W(j(t),i)===void 0)&&xe("Authorization can only include capabilities declared by the application.")}}function Zi(t){let e=t.capabilities;return e?[...new Set([...e.required,...e.optional??[]].flatMap(n=>W(e.contract_version,n)??[]))]:[...Se]}function Un(t,e){let{requirements:n}=t;if(X(n,e),j(n)===1){if(e.operations!==void 0)return[...new Set(e.operations)];if(e.capabilities===void 0)return[...Se]}let i=n.capabilities,r=[...i?.required??[],...e.capabilities??i?.optional??[]].flatMap(a=>W(j(n),a)??[]),s=(t.provisions?.type_packs.length??0)>0||(t.provisions?.configuration?.length??0)>0;return[...new Set([...r,...j(n)===2&&s?Ot:[]])]}function qt(t,e){return[...t.capabilities?.required??[],...t.capabilities?.optional??[]].filter(n=>(W(j(t),n)??[]).every(i=>e.includes(i)))}function Ln(t){let e=t.files;if(e)return j(t)===1?((!("actions"in e)||"required"in e||"optional"in e)&&xe("Legacy file declarations must use exact files.actions."),{actions:[...e.actions],scope:structuredClone(e.scope)}):("actions"in e&&xe("V2 file declarations must use required/optional file actions."),xi(e))}function Ft(t,e,n){let i=new Set(t.required),o=[...new Set([...t.required,...t.optional??[]])],r={};for(let s of o)r[s]=pa(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 pa(t,e,n,i,o){let r=W(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 Ee=3e4,Nn=1e4,fa=10*6e4,ha=12e4,ma=6e4;function qe(t={}){return{requestMs:ct(t.requestMs,Ee,"requestMs"),watchStartMs:ct(t.watchStartMs,Nn,"watchStartMs"),fileIndexMs:ct(t.fileIndexMs,fa,"fileIndexMs"),uploadMs:ct(t.uploadMs,ha,"uploadMs"),syncMs:ct(t.syncMs,ma,"syncMs")}}function lt(t,e){return{...t,signal:e.signal,...e.deadline===null?{}:{deadlineUnixMs:e.deadline}}}function fe(t={},e=Ee,n=Date.now){let i=t.timeoutMs===void 0?e:t.timeoutMs,o=i===null?null:ya(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 F(t,e,n){let i=fe(t,e),o,r=new Promise((a,c)=>{o=c}),s=()=>o?.(J(i.signal));i.signal.addEventListener("abort",s,{once:!0});try{if(i.signal.aborted)throw J(i.signal);return await Promise.race([n(i),r])}finally{i.signal.removeEventListener("abort",s),i.dispose()}}async function K(t,e,n){let i=fe(t,e);try{if(i.signal.aborted)throw J(i.signal);return await n(i)}finally{i.dispose()}}function J(t){return t.reason instanceof v?t.reason:d("operation_cancelled","The operation was cancelled before it changed the collection.",{operationOutcome:"not_sent",cause:t.reason})}function ya(t){if(!Number.isSafeInteger(t)||t<=0)throw new TypeError("timeoutMs must be a positive safe integer or null.");return t}function ct(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 eo(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 p=await F({...s,signal:r.signal},a,h=>o.describe(h));if(!c())return!1;if(!p.ok){let h=["access_denied","collection_access_denied","insufficient_access","not_authorized","authorization_expired","application_declaration_mismatch"].includes(p.problem.code);return n.contracts={state:h?"requires_authorization":"temporarily_unavailable",missing:[],evidence:[{source:"runtime",fact:p.problem.message}]},l(h?{status:"authorization_required"}:{status:"blocked",problem:p.problem}),!1}if(p.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 f=i.filter(h=>!p.value.contracts.some(m=>m.id===h.id&&m.version===h.version&&m.digest===h.digest));if(n.contracts={state:f.length?"requires_setup":"verified",missing:f,evidence:[{source:"authority",fact:"Exact contract ID, version and digest checked by live describe for this collection."}]},f.length)return l({status:"blocked",problem:{code:"collection_not_ready",message:"The collection is missing required exact contracts."}}),!1}catch(p){if(!c())return!1;if(!(p instanceof v))throw p;return n.contracts={state:"temporarily_unavailable",missing:[],evidence:[{source:"runtime",fact:p.problem.message}]},l({status:"blocked",problem:p.problem}),!1}finally{s?.signal?.removeEventListener("abort",u)}return!0}function to(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 no(t,e,n,i){return{collectionId:e,info:n,capabilities:Ft(t.requirements.capabilities,t,n),...t.requirements?.capabilities?.contract_version===2?{readiness:ba(t,n)}:{},connections:i}}function Dt(t,e){return`mdbase-application-session:v1:${t.id}:${e}`}function jn(t){return JSON.stringify({capabilities:t.requirements?.capabilities,requirements:t.requirements?.configuration??[],provisions:t.provisions??{}})}function io(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 ga(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 ba(t,e){let n=t.requirements?.files,i=n&&"required"in n?n:void 0,o=!i||ga(i.scope,e.fileCapability?.scope),r=u=>u.filter(p=>!o||!e.fileCapability?.actions.includes(p)),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 zt=["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"],oo=Object.keys(ve),Re=["discovery_failed","invalid_operation_response","invalid_application_manifest","invalid_request","manifest_load_failed","rate_limited","temporarily_unavailable","timeout"],he=[...Re,"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"],dt=[...Re,"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"],Bn=["connector_offline","connector_upgrade_required","invalid_operation_response","not_authorized","operation_failed","temporarily_unavailable","timeout"],Ml=[...he,"collection_not_ready","collection_not_selected","operation_cancelled","session_destroyed","session_not_started","session_starting","unknown_collection"],_a=["collection_configuration_invalid","collection_invalid","collection_type_registry_invalid","collection_version_unsupported"],Ut=[...zt,..._a],re=[...Ut,"file_not_found","invalid_path","operation_invalid"],ut=[...re,"cursor_capacity_exhausted","generation_expired","invalid_read_cursor","query_snapshot_changed","sandbox_unsupported"],B=[...re,"concurrent_modification","invalid_preflight","pending_mutation_unresolved"],Lt=[...Ut,"change_cursor_reset"],me=[...B,"type_pack_provision_failed"];function S(t,e=[]){return{ok:!0,value:t,diagnostics:e}}function y(t){return{ok:!1,problem:t}}async function q(t,e){try{return S(await t())}catch(n){if(!(n instanceof v))throw n;let i=n.problem;return i.code==="unknown"||e.includes(i.code)?y(i):y(Yi(i.code,i.message,{details:i.details,operationOutcome:i.operation_outcome,traceId:i.trace_id}))}}function Z(t){let e=new Uint8Array(t);return crypto.getRandomValues(e),se(e)}var ro=32768;function se(t){let e="";for(let o=0;o<t.length;o+=ro)e+=String.fromCharCode.apply(null,t.subarray(o,o+ro));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 Nt(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 va="mdbase-connect-keys",ye="grant-keys",Vn=18446744073709551615n,Ca="mdbase-connect relay request key v1",wa="mdbase-connect relay response key v1",so=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Fe=class{database=null;async create(e){let n=await lo(e),i=await this.open();return await co(i,o=>o.add({...n,counter:"0"})),n}async get(e){let n=await this.open(),i=await Aa(n.transaction(ye).objectStore(ye).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(ye,"readwrite"),s=r.objectStore(ye),a=s.get(e),c=null;a.onerror=()=>o(a.error),a.onsuccess=()=>{let l=a.result;if(!l){r.abort(),o(new x("missing_grant_key","The encrypted grant key is unavailable."));return}let u=BigInt(l.counter)+1n;if(u>Vn){r.abort(),o(new x("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 co(n,i=>i.delete(e))}open(){if(typeof indexedDB>"u")throw new x("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(va,1);i.onupgradeneeded=()=>{i.result.objectStoreNames.contains(ye)||i.result.createObjectStore(ye,{keyPath:"handle"})},i.onerror=()=>n(i.error),i.onsuccess=()=>e(i.result)})),this.database}},De=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 lo(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 x("missing_grant_key","The encrypted grant key is unavailable.");let s=BigInt(r.counter)+1n;if(s>Vn)throw new x("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 jt(t,e,n,i){let o=await Sa(t,e,n),r=i.timestamp??Math.floor(Date.now()/1e3),s=i.nonce??crypto.randomUUID(),a=await Gn({...i,timestamp:r,nonce:s}),c=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},o.signingPrivateKey,new TextEncoder().encode(a));return{[at.version]:String(zn),[at.timestamp]:String(r),[at.nonce]:s,[at.signature]:se(new Uint8Array(c))}}async function Gn(t){let e=t.method.toUpperCase(),n=await ao(t.body??""),i=await ao(t.credential);for(let o of[e,t.target,String(t.timestamp),t.nonce])if(!o||o.includes(`
|
|
2
|
-
`)||o.includes("\r"))throw new
|
|
3
|
-
`)}async function ae(t,e,n,i,o,r=crypto.randomUUID(),s){if(ce(n.encryption),s!==void 0&&(!Number.isSafeInteger(s)||s<=0))throw new x("invalid_deadline","The operation deadline is invalid.");let a=await uo(t,e,n.encryption.application_agreement_public_key),c=await t.nextCounter(e),l={binding:n,protocolVersion:$,requestId:r,operation:i,counter:c},u=await po(a.agreementPrivateKey,n,l.protocolVersion,"request"),p=new TextEncoder().encode(JSON.stringify(o??{})),f=await crypto.subtle.encrypt({name:"AES-GCM",iv:mo(c),additionalData:new TextEncoder().encode(ho(l,"request")),tagLength:128},u,p);return{type:"encrypted_operation_request",...Ra(l),...s===void 0?{}:{deadline_unix_ms:s},ciphertext:se(new Uint8Array(f))}}async function ze(t,e,n,i,o){if(!Pa(i,o))throw new x("invalid_encrypted_response","Encrypted response metadata does not match its request.");let r=await uo(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 po(r.agreementPrivateKey,n,i.protocol_version,"response");try{let c=await crypto.subtle.decrypt({name:"AES-GCM",iv:mo(i.counter),additionalData:new TextEncoder().encode(ho(s,"response")),tagLength:128},a,yo(o.ciphertext)),l=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(c));if(l?.ok===!0&&"result"in l||l?.ok===!1&&it(l.problem))return l;throw new Error("invalid response body")}catch(c){throw c instanceof x?c:new x("encrypted_response_rejected","The encrypted connector response could not be authenticated.")}}var x=class extends Error{constructor(n,i){super(i);this.code=n}code};async function lo(t){let e=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"]),n=se(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=se(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 uo(t,e,n){let i=await t.get(e);if(!i||i.agreementPublicKey!==n)throw new x("missing_grant_key","The encrypted grant key is unavailable or does not match the grant.");return i}async function Sa(t,e,n){let i=await t.get(e);if(!i||i.signingPublicKey!==n)throw new x("missing_grant_key","The remote authority signing key is unavailable or does not match the grant.");return i}async function po(t,e,n,i){let o=await pt(t,e.encryption.connector_agreement_public_key),r=await crypto.subtle.importKey("raw",o,"HKDF",!1,["deriveKey"]),s=new TextEncoder().encode(fo(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"?Ca:wa)},r,{name:"AES-GCM",length:256},!1,i==="request"?["encrypt"]:["decrypt"])}async function pt(t,e){try{let n=await crypto.subtle.importKey("raw",Oa(Kn(e)),{name:"ECDH",namedCurve:"P-256"},!1,[]);return await crypto.subtle.deriveBits({name:"ECDH",public:n},t,256)}catch{throw new x("invalid_public_key","The connector relay public key is invalid.")}}function fo(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 ho(t,e){return[fo(t.binding,t.protocolVersion),t.requestId,e,t.operation,t.counter].join("|")}function Ra(t){let e=t.binding.encryption;return{protocol_version:t.protocolVersion,suite:st,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 Pa(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 ce(t){if(t.protocol_version!==Et||t.suite!==st||!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 x("unsupported_encryption","The grant uses an unsupported relay encryption profile.");if(typeof t.connector_id!="string"||!so.test(t.connector_id)||typeof t.collection_id!="string"||!so.test(t.collection_id))throw new x("unsupported_encryption","The grant uses invalid encrypted relay identities.");Kn(t.application_agreement_public_key),Kn(t.connector_agreement_public_key)}function mo(t){let e=BigInt(t);if(e<=0n||e>Vn||e.toString()!==t)throw new x("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 ao(t){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return se(new Uint8Array(e))}function yo(t){if(!/^[A-Za-z0-9_-]+$/.test(t))throw new x("invalid_base64","Encrypted relay data is malformed.");return Nt(t)}function Kn(t){let e=yo(t);if(e.length!==65||e[0]!==4)throw new x("invalid_public_key","Encrypted relay public keys must be uncompressed P-256 points.");return e}function Oa(t){return Uint8Array.from(t).buffer}function Aa(t){return new Promise((e,n)=>{t.onerror=()=>n(t.error),t.onsuccess=()=>e(t.result)})}function co(t,e){return new Promise((n,i)=>{let o=t.transaction(ye,"readwrite"),r=e(o.objectStore(ye));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 ge(t){return{...t,credentials:"omit",targetAddressSpace:"loopback"}}async function ft(){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 Ue(t){let{status:e}=t;return e===404||e===405||e===426||e>=500?!0:e===403&&(await t.clone().text()).trim()===""}function go(t,e){return pe(t,e)}function bo(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 ht(t){return[...new Set(t)]}function _o(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 Pe(t){if(t?.aborted)throw d("operation_cancelled","The operation was cancelled before it changed the collection.",{operationOutcome:"not_sent",cause:t.reason})}function Bt(t,e,n,i){return t instanceof v?t:e?.aborted?n?H(n,t):e.reason instanceof v?e.reason:d("operation_cancelled","The operation was cancelled before it changed the collection.",{operationOutcome:"not_sent",cause:t}):n?H(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 vo(t){return z(t.code==="unknown"?t.server_code:t.code,t.message,{details:t.details,operationOutcome:t.operation_outcome??"rejected",traceId:t.trace_id})}function Co(t,e,n,i,o){return fetch(t,{method:"POST",headers:{authorization:`Bearer ${e}`,"content-type":"application/json",...n},body:i,signal:o})}function $n(t,e){return e?.aborted===!0||t instanceof v&&t.code==="operation_cancelled"}function wo(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 So(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 Ro(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 Po(t){return{affectedRecords:new Set((t.brokenLinks??[]).map(e=>e.path)).size,totalUnits:1,warnings:0}}async function Oo(t,e){return Li(t,e??{})}function Ao(t){return JSON.stringify(Hn(t))}function Hn(t){return Array.isArray(t)?t.map(e=>Hn(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,Hn(n)])):t}function H(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 Kt(t,e){let n=E(t.getItem(`${e}:connections`));return n?.version===1&&Array.isArray(n.collectionIds)&&n.collectionIds.every(i=>typeof i=="string")?n.collectionIds:[]}function To(t,e,n){Io(t,e,[...Kt(t,e),n])}function ko(t,e,n){Io(t,e,Kt(t,e).filter(i=>i!==n))}function Io(t,e,n){t.setItem(`${e}:connections`,JSON.stringify({version:1,collectionIds:[...new Set(n)]}))}function Mo(t,e){let n=t instanceof URL?t.href:t??ka(),i=typeof n=="string"?n:n.distribution==="portable"?`bundle:${n.id}:${Ma(n)}`:`bundle:${n.id}`,o=e===void 0?typeof n!="string"&&n.distribution==="portable"?"":Ia():String(e);return{manifest:n,manifestSource:i,redirectUri:o}}async function ee(t,e,n,i){try{return await fetch(t,e)}catch(o){throw d(n,i,{cause:o})}}async function M(t,e,n){let i;try{i=await t.text()}catch(o){throw z(e,n,{status:t.status,cause:o})}if(i.trim()==="")throw z(e,n,{status:t.status});try{return JSON.parse(i)}catch(o){throw z(e,n,{status:t.status,cause:o})}}function xo(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 mt(){let t=Z(32),e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return{verifier:t,challenge:se(new Uint8Array(e))}}function D(t,e,n,i){return z(yt(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 yt(t){return typeof t?.error=="string"?t.error:void 0}function gt(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 Eo(t,e){return gt({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 Vt(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&&Ta(o))}function Ta(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 qo(t,e){if(!t||typeof t!="object"||Array.isArray(t)||t.collection_id!==e)return!1;try{return ce(t),!0}catch{return!1}}function Fo(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 E(t){if(!t)return null;try{return JSON.parse(t)}catch{return null}}function Gt(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 Ht(t){return t.access==="full_collection"&&t.contracts.length===0}function Do(t){return t.endsWith("/")?t.slice(0,-1):t}function ka(){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 Ia(){if(typeof location>"u")throw d("redirect_uri_required","redirectUri is required outside a browser environment.");return location.href.split(/[?#]/)[0]}function Wn(){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 zo(t,e,n,i){if(typeof t!="string"&&t.distribution==="portable"||i)return Wn();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 Uo(t){let e=":token:",n=t.lastIndexOf(e);return n<0?"":t.slice(n+e.length)}function $t(){if(typeof location>"u")throw d("callback_url_required","callbackUrl is required outside a browser environment.");return location.href}function Lo(t){if(t)return new Le;if(typeof localStorage>"u")throw d("storage_required","storage is required outside a browser environment.");try{let e=`mdbase-connect:probe:${Z(8)}`;return localStorage.setItem(e,"1"),localStorage.removeItem(e),localStorage}catch{return new Le}}var Le=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 No(t){return typeof t=="string"||t.distribution!=="portable"?!1:typeof location>"u"||location.origin==="null"||!["http:","https:"].includes(location.protocol)}function Ma(t){let e=Ao(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 jo(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(Ri))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 bt(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 Ne(t,e,n){return t.reason instanceof v?t.reason:d("authorization_cancelled",e,{cause:n})}function _t(t){for(let e of["code","state","error","error_description"])t.searchParams.delete(e);return t}function Wt(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 Jt(t){try{let e=new URL(t).searchParams.get("state");return e&&e.length>0?e:null}catch{return null}}function Bo(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 je=class{constructor(e,n){this.connect=e;this.operations=ht(n.operations??Se),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(y(w("session_destroyed","This session has been destroyed.")));if(this.started&&!this.startOperation)return Promise.resolve(S(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 F(n,Nn,()=>e.promise)}catch(i){if(i instanceof v)return y(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?y(w("session_destroyed","This session has been destroyed.")):(this.publishCurrent(),S(this.snapshot))}catch(i){if(i instanceof v){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()})),y(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 y(i);let o=this.connect.connection(e);return o?(this.unavailableReason="not_authorized",this.selection.select(e,n),this.refresh(),S(o)):y(w("unknown_collection","This collection is not authorized for this application."))}clearSelection(e={}){let n=this.lifecycleProblem();return n?y(n):(this.unavailableReason="not_authorized",this.selection.select(null,e),this.refresh(),S(void 0))}forget(e){let n=this.lifecycleProblem();if(n)return y(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 S(void 0)}async authorize(e,n={}){let i=this.lifecycleProblem();if(i)return y(i);let o=this.selection.selectedCollectionId();if(e==="selected"&&!o)return y(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(S(void 0));let c=a?j(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 y(i);let o=this.snapshot;if(o.status!=="ready")return y(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(S(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(Pt)}});X(a,{...n,...e});let c="operations"in e?e.operations:e.capabilities.flatMap(f=>W(j(a),f)??[]),l=o.connection.authorizationCapabilities(c);if(l.sufficient)return S({kind:"unchanged",connection:o.connection});let u="operations"in e||j(a)===1?{operations:ht([...l.grantedOperations,...c])}:{capabilities:[...new Set([...qt(a,l.grantedOperations),...e.capabilities])]},p=await this.connect.authorize({...r.options,...u,target:{kind:"collection",collectionId:o.collectionId},returnTo:this.selection.authorizationReturnTo()});return this.lifecycleCurrent(r.generation)?(p.ok&&p.value.kind==="connected"&&this.selection.finishAuthorization(p.value.returnTo,p.value.connection.collectionId),p):this.destroyedOutcome(p)}catch(s){if(s instanceof v)return y(s.problem);throw s}finally{r.dispose(),this.transactionDepth-=1,this.refresh()}}handleAuthorizationCallback(e,n){let i=this.lifecycleProblem();return i?Promise.resolve(y(i)):Wt(e)?this.completeAuthorizationCallback(e,n):Promise.resolve(y(w("invalid_callback","This URL is not an authorization callback.")))}completeAuthorizationCallback(e,n){if(n?.signal?.aborted){let r=J(n.signal);return Promise.resolve(y(r.problem))}let i=Jt(e);if(!i)return Promise.resolve(y(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 v)return y(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=Bo(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(),S(c.connection,a.diagnostics)}).catch(a=>{if(o!==this.lifecycleGeneration||this.destroyed)return y(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 F(n,Ee,()=>e.promise)}catch(i){if(i instanceof v)return y(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:y(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=xa(e);if(n!==this.snapshotKey){this.snapshot=e,this.snapshotKey=n;for(let i of this.listeners)i()}}};function xa(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 Ct=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)}},Be=class{constructor(e,n,i=qe()){this.connect=e;this.options=n;this.timeouts=i;this.verificationStore=n.verificationStore??Ua()}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(y(w("session_destroyed","This application session has been destroyed.")));if(this.base&&!this.startOperation)return Promise.resolve(S(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 F(n,i,()=>e.promise)}catch(o){if(o instanceof v)return y(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 v)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 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 y(w("operation_cancelled","Application session startup was cancelled.",{operationOutcome:"not_sent"}));this.application=i.value,this.manifest=o.value;let s=new je(this.connect,{selection:this.options.selection,autoSelect:this.options.autoSelect,operations:Ea(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),y(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),y(w("operation_cancelled","Application session startup was cancelled.",{operationOutcome:"not_sent"}))):S(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()}),y(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),S(void 0)):n}forget(e){let n=this.lifecycleBase();return n.ok?(n.value.forget(e),S(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"?S(l.connection):y(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?$t():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"?S(l.connection):y(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)=>{X(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(y(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)=>{X(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 y(w("collection_not_ready","There is no reviewed collection setup to apply."));if(!this.setupAssessment.applicable)return y(w("collection_not_ready","Resolve the collection setup conflicts before applying this update."));let i=this.connection();if(!i)return y(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?y(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),S(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"?y(a.problem):y(w("session_destroyed",vt("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"||!za(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=Dt(this.manifest,i.collectionId);r.readiness?.contracts.state!=="checking"&&this.verificationStore.read(a)===jn(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=i?await o.assessCollectionSetup(s,i):await o.assessCollectionSetup(s);if(n===this.verificationGeneration){if(!a.ok){this.publish(a.problem.code==="application_declaration_mismatch"?{status:"authorization_required",...e}:{status:"blocked",problem:a.problem,...e});return}if(!a.value.applicable){let c=Da(a.value);if(Object.keys(c).length>0){if(a=i?await o.assessCollectionSetup(this.collectionSetupInput(c),i):await o.assessCollectionSetup(this.collectionSetupInput(c)),n!==this.verificationGeneration)return;if(!a.ok){this.publish(a.problem.code==="application_declaration_mismatch"?{status:"authorization_required",...e}:{status:"blocked",problem:a.problem,...e});return}this.setupTypePackAdoptions=c}}if(n===this.verificationGeneration){if(a.value.status!=="current"){this.setupAssessment=a.value,this.verificationStore.remove(Dt(r,e.collectionId)),this.publish({status:"setup_review_required",update:Fa(a.value,r.provisions?.type_packs??[]),...e});return}this.verificationStore.write(Dt(r,e.collectionId),jn(r)),e.readiness&&(e.readiness.setup={state:"current",evidence:[{source:"authority",fact:"Collection setup assessment is current."}]}),await this.publishReady(e,n,i)}}}async publishReady(e,n,i){let o=this.requireManifest().requirements?.contracts??[];if(e.readiness&&o.length){let r=this.connection();if(!r||r.collectionId!==e.collectionId)return;this.publish({status:"checking_setup",...e});let s=new AbortController;this.readinessController?.abort(),this.readinessController=s;try{if(!await eo({...e,readiness:e.readiness,contracts:o,connection:r,controller:s,options:i,requestMs:this.timeouts.requestMs,isCurrent:()=>n===this.verificationGeneration&&this.connection()===r,publish:a=>this.publish({...a,...e})}))return}finally{this.readinessController===s&&(this.readinessController=void 0)}}n===this.verificationGeneration&&this.publish({status:"ready",verification:"verified",...e})}collectionSetupInput(e){let n=this.requireManifest(),i=this.requireApplication();return io(n,bt(i.family_identity),`sha256:${i.manifest_digest}`,e)}context(e){return no(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:to(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 y(w("session_starting","The application session is still starting."));if(this.snapshot.status==="start_failed")return y(this.snapshot.problem);if(this.base)return S(this.base);let n=e==="destroyed"?"session_destroyed":"session_not_started";return y(w(n,vt(n)))}async withLifecycleBase(e,n){let i=this.beginLifecycleOperation(e),o=fe(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 y(w("session_destroyed",vt("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 v)return this.lifecycleCurrent(i.generation)?y(s.problem):s.problem.code==="operation_outcome_unknown"?y(s.problem):y(w("session_destroyed",vt("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:y(w("session_destroyed",vt("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 Ea(t,e){let n=(e.provisions?.type_packs.length??0)>0||(e.provisions?.configuration?.length??0)>0;return[...Zi(e.requirements),...t.contract_version===2&&n?Ot:[]]}function qa(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 Fa(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 qa(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 Da(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 za(t,e){return t.requirements?.access==="full_collection"&&e.scope.access==="full_collection"&&e.scope.contracts.length===0}function vt(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 Ua(){return typeof localStorage<"u"?{read:t=>localStorage.getItem(t),write:(t,e)=>localStorage.setItem(t,e),remove:t=>localStorage.removeItem(t)}:new Ct}function te(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 La="mdbase-connect-identities",Ke="application-identities",Jn=BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Na=Jn/2n,Ve=class{database=null;async create(e){let n=await Vo(e),i=await this.open();return await Ko(i,o=>o.add(n)),n}async get(e){let n=await this.open();return await ja(n.transaction(Ke).objectStore(Ke).get(e))??null}async delete(e){let n=await this.open();await Ko(n,i=>i.delete(e))}open(){if(typeof indexedDB>"u")throw new Oe("Persistent application identity requires browser IndexedDB or an injected identity store.");return this.database||(this.database=new Promise((e,n)=>{let i=indexedDB.open(La,1);i.onupgradeneeded=()=>{i.result.objectStoreNames.contains(Ke)||i.result.createObjectStore(Ke,{keyPath:"handle"})},i.onerror=()=>n(i.error),i.onsuccess=()=>e(i.result)})),this.database}},Ge=class{records=new Map;async create(e){if(this.records.has(e))throw new Error(`Application identity already exists: ${e}`);let n=await Vo(e);return this.records.set(e,n),n}async get(e){return this.records.get(e)??null}async delete(e){this.records.delete(e)}},Oe=class extends Error{constructor(e){super(e),this.name="ApplicationIdentityStoreError"}};async function He(t){return Vi(t.signingPublicKey)}async function wt(t,e){if(t.installation_signing_public_key!==e.signingPublicKey||t.application_installation_id!==await He(e))throw new Error("Application authorization identity does not match its binding.");let n=Ka(new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},e.signingPrivateKey,Gi(t))));return{binding:t,signature:Go(n)}}async function Qt(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 Vo(t){let e=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign","verify"]),n=Go(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 ja(t){return new Promise((e,n)=>{t.onerror=()=>n(t.error),t.onsuccess=()=>e(t.result)})}function Ko(t,e){return new Promise((n,i)=>{let o=t.transaction(Ke,"readwrite");e(o.objectStore(Ke)).onerror=()=>i(o.error),o.onerror=()=>i(o.error),o.onabort=()=>i(o.error??new Error("Identity transaction aborted.")),o.oncomplete=()=>n()})}function Ba(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 Go(t){return btoa(String.fromCharCode(...t)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}function Ka(t){if(t.byteLength!==64)throw new Error("Application authorization signature is invalid.");let e=Va(t.slice(32));if(e===0n||e>=Jn)throw new Error("Application authorization signature is invalid.");return e<=Na?t:Ba([t.slice(0,32),Ga(Jn-e,32)])}function Va(t){return BigInt(`0x${Ha(t)}`)}function Ga(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 Ha(t){return[...t].map(e=>e.toString(16).padStart(2,"0")).join("")}var St={id:"mdbase.person",version:"2.0.0"};function Jo(t,e,n){return F(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 ee(`${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 M(r,"invalid_operation_response","Connect returned invalid identity information.")})}var $e=class{constructor(e){this.context=e}context;current(e){return q(()=>this.readCurrent(e),zt)}members(e){return q(()=>this.readMembers(e),zt)}directory(e={}){return q(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 v&&a.code==="access_denied"))throw a}),this.readRecords(i)]);return{account:o,me:$a(s,o),people:s.people,invalid:s.invalid.map(({path:a,reason:c})=>({path:a,reason:c})),...r?{members:r}:{}}},ut)}async readCurrent(e){let n=await this.context.request("identity",e),i=Wo(n),o=n.person_settings_url;if(o===void 0)return i;if(typeof o!="string"||!Qo(o))throw Yt();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 Yt();return n.members.map(i=>{let o=Wo(i);if(!i||typeof i!="object"||!("role"in i)||i.role!=="owner"&&i.role!=="editor"&&i.role!=="viewer")throw Yt();return{...o,role:i.role}})}async readRecords(e){let i=$o(await this.context.describe(e)).contracts.find(c=>c.id===St.id&&c.version===St.version),o=new Map;for(let c of i?.implementations??[])for await(let l of this.context.queryPages({contract:{...St,type:c.typeName}},{signal:e.signal,pageSize:200}))for(let u of $o(l).results){let p=o.get(u.path)??[];p.push({typeName:c.typeName,value:u.frontmatter??{}}),o.set(u.path,p)}let r=[],s=[];for(let[c,l]of o){let u=l.map(h=>Wa(h.value)),p=u[0],f=u.find(h=>"reason"in h);f&&"reason"in f?s.push({path:c,reason:f.reason,claims:l.flatMap(h=>Ho(h.value))}):u.some(h=>JSON.stringify(h)!==JSON.stringify(p))?s.push({path:c,reason:"Its Person implementations project different values.",claims:l.flatMap(h=>Ho(h.value))}):p&&!("reason"in p)&&r.push({path:c,...p,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 $a(t,e){let n=t.invalid.filter(o=>o.claims.some(r=>Xt(r,e)));if(n.length)return{status:"invalid",paths:n.map(o=>o.path)};let i=t.people.filter(o=>o.identities.some(r=>Xt(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 Xt(t,e){return t.issuer===e.issuer&&t.subject===e.subject}function Wa(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 Ho(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 $o(t){if(!t.ok)throw new v(t.problem);return t.value}function Wo(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()||!Qo(t.issuer))throw Yt();return{issuer:t.issuer,subject:t.subject,name:t.name}}function Qo(t){try{let e=new URL(t);return e.protocol==="https:"||e.protocol==="http:"}catch{return!1}}function Yt(){return d("invalid_operation_response","Connect returned invalid identity information.")}async function*Xo(t,e,n={},i={}){let{offset:o,limit:r,cursor:s,pagination:a,snapshot:c,...l}=n,u=Ja(o,0),p=Yo(i.firstPageSize??i.pageSize??r,200),f=Yo(i.pageSize??r,1e3),h=s,m=s!==void 0,R=s,_=c,b=0,C=0;try{for(;!i.signal?.aborted;){let g=h,A={signal:i.signal,timeoutMs:i.pageTimeoutMs,coordination:{...i.coordination,coalesce:!1}},U=C===0&&s===void 0&&a===void 0&&c===void 0,P=await t({...l,...m?{}:{limit:C===0?p:f},...m?g?{cursor:g}:{pagination:"cursor"}:{offset:u,..._?{snapshot:_}:{},...!_&&a==="cursor"?{pagination:"cursor"}:{}},...!m&&!_&&U?{pagination:"cursor"}:{}},A);if(U&&!P.ok&&P.problem.code==="operation_invalid"&&(P=await t({...l,limit:p,offset:u},A)),!P.ok){yield P;return}let k=P.value,T=k.meta?.cursor;if(T?(m=!0,h=T,R=T):m&&(h=void 0,R=g),m&&k.meta?.hasMore&&!T){yield y(w("invalid_operation_response","The collection authority omitted the cursor required for the next query page."));return}let O=k.meta?.snapshot;if(!m&&_&&O&&_!==O){yield y(w("query_snapshot_changed","The collection query snapshot changed while paging. Refresh the query before continuing."));return}!m&&!_&&O&&(_=O),b+=k.results.length;let G=!k.meta?.hasMore||k.results.length===0,Q={results:k.results,...k.meta?{meta:k.meta}:{},page:C,offset:u,loaded:b,complete:G,...T?{cursor:T}:{},...!m&&_?{snapshot:_}:{}};if(i.onProgress?.(Q),yield S(Q,P.diagnostics),G)return;u+=k.results.length,C+=1}}finally{m&&R&&e(R).catch(()=>{})}}function Ja(t,e){return typeof t=="number"&&Number.isFinite(t)?Math.max(0,Math.floor(t)):e}function Yo(t,e){return typeof t=="number"&&Number.isFinite(t)&&t>0?Math.floor(t):e}async function*er(t,e,n,i={}){let{offset:o,limit:r,cursor:s,...a}=n,c=Qa(o,0),l=Zo(i.firstPageSize??r,200),u=Zo(i.pageSize??r,1e3),p=s,f=s!==void 0,h=s,m=0,R=0;try{for(;!i.signal?.aborted;){let _=p,b=await t({...a,limit:R===0?l:u,...f&&_?{cursor:_}:{offset:c}},{signal:i.signal,timeoutMs:i.pageTimeoutMs,coordination:{...i.coordination,coalesce:!1}});if(!b.ok){yield b;return}let C=b.value,g=C.meta.cursor;if(g?(f=!0,p=g,h=g):f&&(p=void 0,h=_),f&&C.meta.hasMore&&!g){yield y(w("invalid_operation_response","The collection authority omitted the cursor required for the next saved-view page."));return}m+=C.results.length;let A=!C.meta.hasMore||C.results.length===0,U={...C,page:R,offset:c,loaded:m,complete:A,...g?{cursor:g}:{}};if(i.onProgress?.(U),yield S(U,b.diagnostics),A)return;c+=C.results.length,R+=1}}finally{f&&h&&await e(h)}}function Qa(t,e){return typeof t=="number"&&Number.isFinite(t)?Math.max(0,Math.floor(t)):e}function Zo(t,e){return typeof t=="number"&&Number.isFinite(t)&&t>0?Math.floor(t):e}function tr(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 We=class{constructor(e,n=Ee){this.transport=e;this.requestTimeoutMs=n}transport;requestTimeoutMs;operation(e,n,i){return q(()=>this.transport.operation(e,n,i),oo)}async describe(e){let n=await this.rawOperation("describe",{},Ut,e);return L(n,pc)}async changes(e={},n){let i=await this.rawOperation("changes",e,Lt,n);return L(i,uc)}async read(e,n){let i=await this.envelopeOperation("read",Ya(e),re,n);return L(i,Zt)}async query(e={},n){let i=await this.envelopeOperation("query",Xa(e),ut,n);return L(i,({results:o,meta:r})=>({results:o.map(pr),...r?{meta:{...typeof r.total_count=="number"?{totalCount:r.total_count}:{},...r.total_count_outcome===void 0?{}:{totalCountOutcome:r.total_count_outcome},hasMore:r.has_more,...r.cursor?{cursor:r.cursor}:{},...r.snapshot?{snapshot:r.snapshot}:{}}}:{}}))}async*queryPages(e={},n={}){yield*Xo((i,o)=>this.query(i,o),i=>this.releaseQueryCursor(i),e,n)}async queryAll(e={},n={}){let i=fe(n,this.requestTimeoutMs),o=[],r,s=[];try{for await(let a of this.queryPages(e,{firstPageSize:n.firstPageSize,pageSize:n.pageSize,signal:i.signal,pageTimeoutMs:null,coordination:n.coordination,onProgress:n.onProgress})){if(!a.ok)return a;let c=a.value;o.push(...c.results),r=c,s.push(...a.diagnostics)}if(i.signal.aborted)throw J(i.signal);return S({results:o,meta:{totalCount:r?.meta?.totalCount??o.length,hasMore:r?!r.complete:!1,...r?.snapshot?{snapshot:r.snapshot}:{}}},s)}catch(a){if(a instanceof v)return y(a.problem);throw a}finally{i.dispose()}}async listViews(e){let n=await this.envelopeOperation("list_views",{},re,e);return L(n,i=>({views:i.views,meta:{totalCount:i.meta.total_count}}))}async executeView(e,n){let i=await this.envelopeOperation("execute_view",e,re,n);return L(i,sc)}async*executeViewPages(e,n={}){yield*er((i,o)=>this.executeView(i,o),i=>this.releaseQueryCursor(i),e,n)}readViewSource(e,n){return this.envelopeOperation("read_view_source",e,re,n)}createViewSource(e,n){return this.envelopeOperation("create_view_source",e,B,n)}updateViewSource(e,n){return this.envelopeOperation("update_view_source",Qn(e),B,n)}deleteViewSource(e,n){return this.envelopeOperation("delete_view_source",Qn(e),B,n)}async create(e,n){let i=await this.envelopeOperation("create",Za(e),B,n);return L(i,Zt)}async update(e,n){let i=await this.envelopeOperation("update",ec(e),B,n);return L(i,Zt)}async delete(e,n){let i=await this.envelopeOperation("delete",nr(e),B,n);return L(i,lr)}async preflightDelete(e,n){let i=await this.envelopeOperation("delete",{...nr(e),check_backlinks:!0,dry_run:!0},B,n);return L(i,ic)}async rename(e,n){let i=await this.envelopeOperation("rename",ir(e),B,n);return L(i,oc)}async preflightRename(e,n){let i=await this.envelopeOperation("rename",{...ir(e),dry_run:!0},B,n);return L(i,rc)}validate(e={},n){return this.envelopeOperation("validate",e,re,n)}readType(e,n){return this.envelopeOperation("read_type",e,me,n)}createType(e,n){return this.envelopeOperation("create_type",e,me,n)}updateType(e,n){return this.envelopeOperation("update_type",Qn(e),me,n)}async assessTypePack(e,n){let i=await this.envelopeOperation("assess_type_pack",ar(e),me,n);return L(i,Xn)}async applyTypePack(e,n){let i=await this.envelopeOperation("apply_type_pack",tc(e),me,n);return L(i,cc)}async assessCollectionSetup(e,n){let i=await this.envelopeOperation("assess_collection_setup",cr(e),me,n);return L(i,sr)}async applyCollectionSetup(e,n){let i=await this.envelopeOperation("apply_collection_setup",nc(e),me,n);return L(i,o=>({assessment:sr(o.assessment),receipt:lc(o.receipt)}))}async listTimers(e,n){let i=await this.rawOperation("list_timers",{namespace:e},re,n);return L(i,o=>({namespace:o.namespace,timers:o.timers.map(Yn)}))}async putTimer(e,n){let i=await this.rawOperation("put_timer",{namespace:e.namespace,criterion_id:e.criterionId,timer:or(e.timer)},B,n);return L(i,Yn)}cancelTimer(e,n){return this.rawOperation("cancel_timer",e,B,n)}async reconcileTimers(e,n){let i=await this.rawOperation("reconcile_timers",{namespace:e.namespace,criterion_id:e.criterionId,timers:e.timers.map(or)},B,n);return L(i,o=>({namespace:o.namespace,timers:o.timers.map(Yn),cancelledIds:o.cancelled_ids}))}async*watch(e={}){let n=e.cursor,i=Math.max(100,e.pollIntervalMs??1e3),o=tr(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 p=Math.min(o.maxDelayMs,Math.round(o.initialDelayMs*o.multiplier**(r-1)));e.onStatus?.({state:"reconnecting",...n===void 0?{}:{cursor:n},attempt:r,retryInMs:p,problem:u});try{await te(p,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 y(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 S(u);if(n=c.cursor,!c.hasMore)try{await te(i,e.signal)}catch{if(!e.signal?.aborted)throw d("operation_failed","Watch polling delay failed unexpectedly.")}}}rawOperation(e,n,i,o){return q(()=>this.transport.operation(e,n,o),i)}async releaseQueryCursor(e){try{await this.envelopeOperation("query",{release_cursor:e},ut,{timeoutMs:2e3,coordination:{coalesce:!1}})}catch{}}async envelopeOperation(e,n,i,o){let r=await q(()=>this.transport.operation(e,n,o),i);if(!r.ok)return r;let s=r.value;return s.valid?S(s.result,s.diagnostics):y(Me(s))}};function L(t,e){return t.ok?S(e(t.value),t.diagnostics):t}function Ya(t){return{path:t.path,...t.contract?{contract:t.contract}:{},...t.includeDocument===void 0?{}:{include_document:t.includeDocument}}}function Xa(t){return{...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 Za(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 ec(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 nr(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 ir(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 Qn(t){let{ifRevision:e,...n}=t;return{...n,...e?{if_revision:e}:{}}}function ar(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(dr)}:{}}}function tc(t){return{...ar(t),expected_assessment_digest:t.expectedAssessmentDigest,...t.allowDowngrade===void 0?{}:{allow_downgrade:t.allowDowngrade}}}function cr(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(dr)}:{},...t.typePackAdoptions?{type_pack_adoptions:t.typePackAdoptions}:{}}}function nc(t){return{...cr(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 lr(t){return{path:t.path,deleted:t.deleted,...t.broken_links?{brokenLinks:t.broken_links}:{}}}function ic(t){return{...lr(t),deleted:!1,dryRun:!0,wouldDelete:!0}}function oc(t){let{references_updated:e,...n}=t;return{...Zt(n),from:t.from,to:t.to,...e?{referencesUpdated:e}:{}}}function rc(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 or(t){return{id:t.id,fire_at:t.fireAt,...t.data===void 0?{}:{data:t.data}}}function Yn(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 dr(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 ur(t){return{id:t.id,version:t.version,digest:t.digest,type:t.type,implementationDigest:t.implementation_digest}}function pr(t){let{effective_frontmatter:e,contract:n,...i}=t;return{...i,...e===void 0?{}:{effectiveFrontmatter:e},...n?{contract:ur(n)}:{}}}function Zt(t){let{effective_frontmatter:e,contract:n,...i}=t;return{...i,effectiveFrontmatter:e,...n?{contract:ur(n)}:{}}}function sc(t){return{results:t.results.map(e=>{let n=pr(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 rr(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.reason?{reason:t.reason}:{}}}function en(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}:{}}))}}function ac(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 Xn(t){return{status:t.status,applicable:t.applicable,assessmentDigest:t.assessment_digest,...t.current?{current:en(t.current)}:{},desired:en(t.desired),resources:t.resources.map(rr),lock:t.lock,contractSetups:{choices:t.contract_setups.choices.map(ac),resources:t.contract_setups.resources.map(rr)}}}function cc(t){return{...Xn(t),receipt:en(t.receipt),cleanupDeferred:t.cleanup_deferred}}function sr(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(Xn),finalResourceRevisions:t.final_resource_revisions,assessmentDigest:t.assessment_digest}}function lc(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(en),cleanupDeferred:t.cleanup_deferred}}function dc(t){return{cursor:t.cursor,type:t.type,occurredAt:t.occurred_at,payload:t.payload}}function uc(t){return{events:t.events.map(dc),cursor:t.cursor,hasMore:t.has_more,reset:t.reset}}function pc(t){return{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 tn=class{constructor(e){this.context=e}context;async registerNotifications(e){return F(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 ee(`${this.context.serverUrl}/v1/notifications/vapid-public-key`,{signal:n},"notifications_unavailable","Push notifications are unavailable."),l=await M(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:Nt(l.public_key)}));let p=u.toJSON();if(!p.endpoint||!p.keys?.p256dh||!p.keys.auth)throw d("invalid_push_subscription","The browser returned an incomplete push subscription.");let f=E(this.context.storage.getItem(this.context.notificationKey())),h=e.installationId??f?.installationId??Z(24),m=await ee(`${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:p.endpoint,expirationTime:p.expirationTime??null,keys:p.keys}}),signal:n},"notification_registration_failed","Could not register push notifications."),R=await M(m,"invalid_operation_response","Connect returned an invalid notification registration response.");if(!m.ok)throw D(R,"notification_registration_failed","Could not register push notifications.",m.status);f?.channelId&&f.channelId!==R.channel_id&&fetch(`${this.context.serverUrl}/v1/notifications/channels/${f.channelId}`,{method:"DELETE",headers:{authorization:`Bearer ${i.accessToken}`},signal:n}).catch(()=>{});let _={channelId:R.channel_id,installationId:h,criteria:s};return this.context.storage.setItem(this.context.notificationKey(),JSON.stringify(_)),_}async registerNativeNotifications(e){return F(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=E(this.context.storage.getItem(c)),u=e.installationId??l?.installationId??Z(24),p=await ee(`${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."),f=await M(p,"invalid_operation_response","Connect returned an invalid native notification response.");if(!p.ok)throw D(f,"notification_registration_failed","Could not register native notifications.",p.status);l?.channelId&&l.channelId!==f.channel_id&&this.deleteNotificationChannel(l.channelId,i.accessToken,n).catch(()=>{});let h={channelId:f.channel_id,installationId:u,transport:"fcm",criteria:s};return this.context.storage.setItem(c,JSON.stringify(h)),h}async unregisterNativeNotifications(e={}){return F(e,this.context.requestTimeoutMs,n=>this.unregisterNativeNotificationsWithinBudget(n.signal))}async unregisterNativeNotificationsWithinBudget(e){let n=this.context.notificationKey("fcm"),i=E(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 F(n,this.context.requestTimeoutMs,i=>this.unregisterNotificationsWithinBudget(e,i.signal))}async unregisterNotificationsWithinBudget(e,n){let i=E(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 ee(`${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 M(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 ee(`${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 M(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 fr(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 hr(t,e,n){let i=n?.path;return e==="update"&&typeof i=="string"?fr(t,i):void 0}async function mr(t,e,n){let i=await fr(e,n);return t.find(o=>o.operation==="update"&&o.recordDigest===i)?.requestId??null}async function nn(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 yr(t,e,n,i,o,r,s,a=async c=>c){let c=t,l=await nn(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 nn(c,e,n,i,o,s)}let u=await M(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 gr(t,e,n,i,o,r,s=async a=>a){let a=t,c=await nn(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 nn(a,"GET",e,void 0,i,r)}if(!c.ok){let u=await M(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 on=class{constructor(e,n){this.namespace=e;this.onFinalRelease=n}namespace;onFinalRelease;leases=new Map;locks=fc();retainAutomaticallyRetiredKeys=this.locks===null;async acquire(e,n,i){let o=this.acquireLocal(e,n);if(!this.locks)return o;try{let r=await hc(this.locks,this.lockName(e,n),i);return Zn(()=>{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),Zn(()=>{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}`}},be=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 V(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 fc(){let t=typeof navigator>"u"?void 0:navigator.locks;return t||(typeof window<"u"||typeof globalThis.importScripts=="function"?null:void 0)}async function hc(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,Zn(r)}function Zn(t){let e=!1;return()=>{e||(e=!0,t())}}var mc="mdbase-connect file chunk key v1",rn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,le=class extends Error{constructor(n,i){super(i);this.code=n;this.name="FileTransferCryptoError"}code},Je=class t{constructor(e,n){this.binding=e;this.key=n}binding;key;static async open(e,n,i){br(i);let o=await e.get(n);if(!o||o.agreementPublicKey!==i.encryption.application_agreement_public_key)throw new x("missing_grant_key","The encrypted grant key is unavailable or does not match the file transfer grant.");let r=await pt(o.agreementPrivateKey,i.encryption.connector_agreement_public_key);return t.fromSharedSecret(r,i)}static async fromSharedSecret(e,n){br(n);let i=await ei(e,n);return new t(n,i)}async encryptChunk(e,n,i){if(this.validateHeader(n),i.byteLength!==n.plaintext_length)throw new le("plaintext_length_mismatch","File chunk plaintext length does not match its authenticated header.");let o=kt(e,n),r=await crypto.subtle.encrypt({name:"AES-GCM",iv:_r(n.chunk_index),additionalData:sn(o),tagLength:128},this.key,sn(i));return Ei({kind:e,header:n,payload:new Uint8Array(r)})}async decryptChunk(e){let n=It(e);this.validateHeader(n.header);let i=kt(n.kind,n.header);try{let o=await crypto.subtle.decrypt({name:"AES-GCM",iv:_r(n.header.chunk_index),additionalData:sn(i),tagLength:128},this.key,sn(n.payload));return new Uint8Array(o)}catch{throw new le("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 le("header_binding_mismatch","The file frame does not match its transfer encryption binding.")}};async function ei(t,e){let n=new TextEncoder().encode(yc(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(mc)},o,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}function br(t){if(ce(t.encryption),!rn.test(t.grantId)||!rn.test(t.applicationId)||!rn.test(t.authorityId)||!rn.test(t.transferId)||t.direction!=="upload"&&t.direction!=="download")throw new le("invalid_binding","The file transfer encryption binding is invalid.")}function yc(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 _r(t){if(!Number.isSafeInteger(t)||t<0)throw new le("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 sn(t){return Uint8Array.from(t).buffer}var cn=8,ti=10;function ln(t){return t instanceof v&&t.code==="connector_busy"}async function vr(t){if(!ln(t.error)||t.completedRetries>=cn)return{retried:!1};try{await dn(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 Qe(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 dn(t,e){return wr(Sr(50,800,t),e)}function Cr(t,e){return wr(Sr(100,1e3,t-1),e)}async function wr(t,e){try{await te(t,e)}catch(n){throw e?.aborted?e.reason instanceof v?e.reason:d("operation_cancelled","The operation was cancelled while waiting for connector capacity.",{operationOutcome:"not_sent",cause:n}):n}}function Sr(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 pn=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){Ye(e);let l=wc(n,i,o),u=await this.encryptControl(e,l),p,f=await this.options.shouldAttemptDirect(e);if(f){try{p=await fetch(`${this.options.loopbackUrl}/v1/files/control`,ge({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(p&&(!await Ue(p)||await Qe(p)))return p.ok&&this.options.onDirectAvailable(),this.decryptControlResponse(e,n,i,o,r,u,p,s,a,c);p&&this.options.onDirectUnavailable()}return f&&n==="GET"&&(e=e.expiresAt>Date.now()+3e4?e:await this.options.refreshAuthorization(r),e=await this.retainEntryToken(e,c,r),un(e),u=await this.encryptControl(e,l)),p=await this.sendRelayControl(e,u,r),await bc(p,e)&&(e=await this.options.refreshAuthorization(r),e=await this.retainEntryToken(e,c,r),un(e),u=await this.encryptControl(e,l),p=await this.sendRelayControl(e,u,r)),p.ok&&this.options.onRelayAvailable(),this.decryptControlResponse(e,n,i,o,r,u,p,s,a,c)}async decryptControlResponse(e,n,i,o,r,s,a,c,l,u){let p=await M(a,"invalid_operation_response","The collection authority returned an invalid file control response.");if(!a.ok){let m=D(p,"operation_failed","Collection file request failed.",a.status);if(ln(m)&&l<cn)return await dn(l,r),this.controlAttempt(e,n,i,o,r,c,l+1,u);if(m.code==="fresh_request_required"&&n==="GET"&&!c)return this.controlAttempt(e,n,i,o,r,!0,l,u);throw m}let f=p?.envelope;if(!f)throw d("invalid_encrypted_response","The connector omitted its encrypted file response.");let h=await ze(this.options.keyStore,e.keyHandle,ii(e),s,f);if(!h.ok&&h.problem.code==="fresh_request_required"&&n==="GET"&&!c)return this.controlAttempt(e,n,i,o,r,!0,l,u);if(!h.ok){let m=Cc(h.problem);if(ln(m)&&l<cn)return await dn(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 ni(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 Rr(this.options.keyStore,a,i,o,r),l;if(await this.options.shouldAttemptDirect(a)){try{l=await fetch(`${this.options.loopbackUrl}/v1/files/upload`,ge(Pr(c,s)))}catch(u){if(s?.aborted)throw u;this.options.onDirectUnavailable()}if(l&&(!await Ue(l)||await Qe(l)))return l.ok&&this.options.onDirectAvailable(),gc(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),un(a),c=await Rr(this.options.keyStore,a,i,o,r),l=await this.sendRelayUpload(a,c,s)),!l.ok){let u=await M(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),ni(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}`,ge({method:"GET",signal:r}))}catch(a){if(r?.aborted)throw a;this.options.onDirectUnavailable()}if(s&&(!await Ue(s)||await Qe(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),un(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 M(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{vc(n,i,r),s=await(await Ar(this.options.keyStore,e,n)).decryptChunk(r)}catch(a){throw a instanceof v?a:d("invalid_operation_response","The connector returned an invalid encrypted file frame.",{cause:a})}if(s.byteLength!==oi(n,i))throw d("invalid_operation_response","The connector returned a truncated file chunk.");return s}encryptControl(e,n){return Ye(e),ae(this.options.keyStore,e.keyHandle,ii(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`,{...Pr(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 ni(o,e,n),o}grantKeyLeases(e){return new be(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 V(this.options.currentToken,n,i);if(o)return o;throw d("not_authorized","Reconnect this application to continue.")}};function ni(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 un(t){if(t.authority||!t.fileCapability)throw d("not_authorized","This connection cannot use encrypted local file delivery.");Ye(t)}async function Rr(t,e,n,i,o){let r=_c(e,n,i,o.byteLength);return(await Ar(t,e,n)).encryptChunk("upload_chunk",r,o)}function Pr(t,e){return{method:"POST",headers:{"content-type":"application/mdbase-connect-file"},body:Uint8Array.from(t).buffer,signal:e}}async function gc(t,e){if(t.ok)return;let n=await M(t,"invalid_operation_response","The collection authority returned an invalid file transfer response.");throw D(n,"operation_failed",e,t.status)}async function bc(t,e){return e.refreshToken?t.status===401?!0:t.status!==409?!1:(await M(t.clone(),"invalid_operation_response","The collection authority returned an invalid file response.").catch(()=>null))?.error?.code==="encryption_binding_stale":!1}function Ye(t){if(!t.encryption||!t.grantId||!t.keyHandle)throw d("missing_grant_key","Reconnect this application to restore encrypted file access.")}function ii(t){return Ye(t),{grantId:t.grantId,applicationId:t.clientId,encryption:t.encryption}}function Ar(t,e,n){return Ye(e),Je.open(t,e.keyHandle,{...ii(e),authorityId:e.encryption.connector_id,transferId:n.transfer_id,direction:n.direction})}function _c(t,e,n,i){Ye(t);let o=fn(e),r=oi(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 vc(t,e,n){let i=It(n),o=oi(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 Cc(t){return z(t.code==="unknown"?t.server_code:t.code,t.message,{details:t.details,operationOutcome:t.operation_outcome??"rejected",traceId:t.trace_id})}function wc(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 Or("get_file_transfer_status",i[1]);if(t==="DELETE"&&i.length===2&&i[0]==="transfers")return Or("abort_file_transfer",i[1]);if(t==="POST"&&Sc(n)){let o=e==="uploads"?"open_file_upload":e==="downloads"?"open_file_download":i.length===3&&i[0]==="uploads"&&i[2]==="commit"?"commit_file_upload":i.length===2&&i[1]==="move"&&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 Or(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 oi(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 Sc(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var hn=class{constructor(e){this.options=e;this.local=new pn(e)}options;local;async control(e,n="",i,o){let r=await this.requireFileToken(o),s=r.token;try{return s.authority?await yr(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 gr(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 be(this.options.collectionId,this.options.acquireGrantKeyLease);try{await V(this.options.currentToken,n,e),await this.options.authorizedToken(e);let i=await V(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 V(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 Ae(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 jt(t,e.keyHandle,e.authority.proofPublicKey,{method:n,target:`${s.pathname}${s.search}`,body:o,credential:r})}catch(s){throw s instanceof x?z(s.code,s.message):s}}async function Tr(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 Ae(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 M(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),(yt(a)??a?.error?.code)==="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)}return t.storeTokenResponse(a,e.clientId,e.keyHandle)}var mn=class{constructor(e,n){this.storage=e;this.baseKey=n}storage;baseKey;list(e){if(!e)return[];let n=E(this.storage.getItem(this.baseKey));if(kr(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=>E(this.storage.getItem(o))).filter(o=>kr(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??ue(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=E(this.storage.getItem(n));return this.storage.removeItem(n),i}key(e){return`${this.baseKey}:${encodeURIComponent(e)}`}};function kr(t){return!!(t&&typeof t.collectionId=="string"&&typeof t.requestId=="string"&&t.requestId.length>0&&qi(t.operation)&&typeof t.inputFingerprint=="string"&&Number.isFinite(t.createdAt)&&t.createdAt>0&&(t.envelope||t.request)&&(t.operation==="sync"||ue(t.operation,t.request?.input??{})!==null))}function Ir({stored:t,collectionId:e,relayEncryption:n,invalidate:i,directCapable:o}){let r=E(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=Gt(r.scope);if(!a)return s(r.keyHandle);if(!Ht(a))return s(r.keyHandle,"legacy_scope_reauthorization_required");if(r.fileCapability&&!Vt(r.fileCapability)||r.authority&&!Eo(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||!qo(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 ri(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 Ae(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 Mr(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 ae(t,e.keyHandle,{grantId:e.grantId,applicationId:e.clientId,encryption:e.encryption},n,i,void 0,o)}catch(r){throw r instanceof x?z(r.code,r.message):r}}var Xe=class{operations=new Map;run(e,n,i,o){if(n?.signal?.aborted)return Promise.reject(J(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 F(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())}}};function xr(t,e){return!t||t.authority||!t.encryption||!t.grantId||!t.keyHandle||e==="disabled"?!1:typeof location>"u"||!t.applicationOrigin||t.applicationOrigin===Wn()}async function Er(t,e,n){let i;try{i=await fetch(`${t}/v1/ready`,ge({method:"GET",cache:"no-store",signal:n}))}catch{return!1}if(i.status===403)throw z("operation_failed","The connector rejected direct access from this application. Relay access remains available.",{status:i.status});let o=await M(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 qr(t,e){try{return{body:await M(t,"invalid_operation_response","The collection authority returned a response that is not valid JSON.")}}catch(n){if(!t.ok&&e&&Rc(t.status))return{body:void 0,httpError:z("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 Rc(t){return t>=400&&t<500&&![408,425,429].includes(t)}var yn=class{serverUrl;storage;keyStore;directAccessMode;loopbackUrl;collectionId;internals;onChange;timeouts;pendingMutationStore;files;refreshOperations=new Xe;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 mn(this.storage,this.internals.pendingMutationKey(this.collectionId)),this.files=new hn({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)=>Ae(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 F(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 ft();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 F(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?mr(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 K(n,this.timeouts.requestMs,o=>this.performOperationWithinBudget(i.operation,i.request?.input??{},lt(n??{},o),i))}async performOperation(e,n,i={}){return K(i,this.timeouts.requestMs,o=>this.performOperationWithinBudget(e,n,lt(i,o)))}async performOperationWithinBudget(e,n,i,o,r=!1,s=0,a=!1){Pe(i.signal);let c=this.grantKeyLeases();try{let l=await V(()=>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 V(()=>this.currentToken(),r,o.signal);if(!A)throw d("not_authorized","Reconnect this application to continue.");e=A}let p=s?.requestId??(go(n,i)?crypto.randomUUID():void 0),f;try{f=await this.sendOperation(e,n,i,u,r,o,p,l)}catch(g){throw Bt(g,o.signal,p!==void 0&&this.storedPendingMutation(p)!==null?p:void 0,e.authority?"hosted_provider_unavailable":"relay_unavailable")}let h=f.response,m=h.status===409&&(await M(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(f.pendingMutation&&(f.directDeliveryUncertain||f.encryptedRequest&&f.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:f.requestId}});f.pendingMutation&&this.clearPendingMutation(f.requestId),e=await this.refreshAuthorization({signal:o.signal,timeoutMs:null});let g=await V(()=>this.currentToken(),r,o.signal);if(!g)throw d("not_authorized","Reconnect this application to continue.");e=g,u=await this.shouldAttemptDirect(e);try{f=await this.sendOperation(e,n,i,u,r,o,p,l)}catch(A){throw Bt(A,o.signal,p!==void 0&&this.storedPendingMutation(p)!==null?p:void 0,e.authority?"hosted_provider_unavailable":"relay_unavailable")}h=f.response}let R=g=>vr({error:g,attempt:f,completedRetries:c,signal:o.signal,knownRejectedMutationRetry:l,clearPending:A=>this.clearPendingMutation(A),retry:(A,U)=>this.performOperationWithinBudget(n,i,o,A,a,c+1,U)}),_;try{_=await qr(h,e.authority!==void 0)}catch(g){throw f.pendingMutation?H(f.requestId,g):g}let b=_.body;if(!h.ok){let g=_.httpError??D(b,"operation_failed","Collection operation failed.",h.status),A=await R(g);if(A.retried)return A.result;if(g.code==="fresh_request_required"&&!f.pendingMutation&&!a)return this.performOperationWithinBudget(n,i,o,void 0,!0);throw f.pendingMutation&&g.outcomeUnknown?g:f.pendingMutation&&(f.directDeliveryUncertain||f.encryptedRequest&&f.resumingMutation)?H(f.requestId,g):(f.pendingMutation&&!f.directDeliveryUncertain&&this.clearPendingMutation(f.requestId),g.code==="direct_operation_rejected"&&g.status===403&&this.invalidateRejectedAuthorization(e),g)}if(f.encryptedRequest){let g=b?.envelope,A=f.pendingMutationRecord,U=A?.encryption??e.encryption,P=A?.grantId??e.grantId,k=A?.applicationId??e.clientId,T=A?.keyHandle??e.keyHandle;if(!g||!U||!P||!T)throw f.pendingMutation?H(f.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 ze(this.keyStore,T,{grantId:P,applicationId:k,encryption:U},f.encryptedRequest,g);if(!O.ok&&O.problem.code==="fresh_request_required"&&!f.pendingMutation&&!a)return this.performOperationWithinBudget(n,i,o,void 0,!0);if(!O.ok){let G=vo(O.problem);throw f.pendingMutation&&!G.outcomeUnknown&&this.clearPendingMutation(f.requestId),G}return f.pendingMutation&&this.clearPendingMutation(f.requestId),O.result}catch(O){throw O instanceof v?O:O instanceof x?f.pendingMutation?H(f.requestId,O):z(O.code,O.message):O}}let C=f.pendingMutationRecord?.request?.protocol_version??$;if(b?.protocol_version!==C||b?.request_id!==f.requestId)throw f.pendingMutation?H(f.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(!it(b.problem))throw f.pendingMutation?H(f.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 v(b.problem),A=await R(g);if(A.retried)return A.result;throw f.pendingMutation&&!g.outcomeUnknown&&this.clearPendingMutation(f.requestId),g}if(b.ok!==!0||!("result"in b))throw f.pendingMutation?H(f.requestId,new Error("Successful operation response did not contain a result.")):d("invalid_operation_response","The collection authority returned an incomplete operation response.");return f.pendingMutation&&this.clearPendingMutation(f.requestId),b.result}async performAuthoritySyncRequest(e,n,i,o,r,s={}){return K(s,this.timeouts.syncMs,async a=>{let c=this.grantKeyLeases();try{let l=await V(()=>this.currentToken(),c,a.signal);l&&await this.authorizedToken({signal:a.signal,timeoutMs:null}),l=await V(()=>this.currentToken(),c,a.signal),Fr(l,e,n);let u=await ri(this.keyStore,l,i,o,r,a.signal);u.status===401&&l.refreshToken&&(l=await this.refreshAuthorization({signal:a.signal,timeoutMs:null}),l=await V(()=>this.currentToken(),c,a.signal),Fr(l,e,n),u=await ri(this.keyStore,l,i,o,r,a.signal));let p=await M(u,"invalid_operation_response","The collection authority returned an invalid synchronization response.");if(!u.ok)throw D(p,"sync_failed","Collection synchronization failed.",u.status);return p}catch(l){let u=i==="POST"&&o==="mutations"&&r&&typeof r=="object"&&typeof r.mutation_id=="string"?r.mutation_id:void 0;throw Bt(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,p=!1,f=!1,h=a??crypto.randomUUID(),m=null,R,_;if(a!==void 0){if(m=this.storedPendingMutation(a),R=m?.inputFingerprint??await Oo(n,i),m||(_=await hr(e.collectionId,n,i)),m){if(m.collectionId!==e.collectionId||m.operation!==n||m.inputFingerprint!==R)throw d("pending_mutation_unresolved","A previous write still has an unknown outcome. Retry that exact write before making another change.");h=m.requestId,f=!c}p=!0}let b=m?.mutation??ue(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(p)if(m){if(!m.envelope)throw d("pending_mutation_unresolved","The pending write belongs to a different transport. Reconnect before retrying it.");u=bo(m.envelope,s.deadlineUnixMs)}else u=await ae(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:R,..._?{recordDigest:_}:{},requestId:h,envelope:u,createdAt:Date.now()});else u=await ae(this.keyStore,e.keyHandle,{grantId:e.grantId,applicationId:e.clientId,encryption:e.encryption},n,i,void 0,s.deadlineUnixMs)}catch(P){throw P instanceof x?z(P.code,P.message):P}h=u.request_id,l=u}else{let P=m?.request??{protocol_version:$,request_id:h,input:l};l=P,p&&!m&&this.pendingMutationStore.store({collectionId:e.collectionId,...e.grantId?{grantId:e.grantId}:{},operation:n,mutation:b,inputFingerprint:R,..._?{recordDigest:_}:{},requestId:h,request:P,createdAt:Date.now()})}if(o&&u&&!e.authority){let P=!1;try{let O=await fetch(`${this.loopbackUrl}/v1/operations`,ge({method:"POST",headers:{"content-type":"application/mdbase-connect+json"},body:JSON.stringify(u),signal:s.signal}));if(!await Ue(O)||await Qe(O))return O.ok&&(this.markDirectAvailable(),this.setRoute("direct")),{response:O,requestId:h,encryptedRequest:u,pendingMutation:p,...p?{pendingMutationRecord:m??this.storedPendingMutation(h)??void 0}:{},resumingMutation:f};P=O.status>=500,this.markDirectUnavailable()}catch(O){if(s.signal?.aborted)throw p?H(h,O):O;P=!0,await ft()==="denied"?this.setDirectStatus("denied"):this.markDirectUnavailable()}let k;try{e.expiresAt<=Date.now()+3e4&&await this.refreshAuthorization({signal:s.signal,timeoutMs:null});let O=await V(()=>this.currentToken(),r,s.signal);if(!O)throw d("not_authorized","Reconnect this application to continue.");k=O}catch(O){throw p&&(P||f)?H(h,O):O}let T;p||(u=await Mr(this.keyStore,k,n,i,s.deadlineUnixMs),h=u.request_id);try{T=await fetch(`${this.serverUrl}/v1/authorities/${encodeURIComponent(k.collectionId)}/operations/${n}`,{method:"POST",headers:{authorization:`Bearer ${k.accessToken}`,"content-type":"application/json"},body:JSON.stringify(u),signal:s.signal})}catch(O){throw p?H(h,O):O}return T.ok&&this.setRoute("relay"),{response:T,requestId:h,encryptedRequest:u,directDeliveryUncertain:P,pendingMutation:p,...p?{pendingMutationRecord:m??this.storedPendingMutation(h)??void 0}:{},resumingMutation:f}}let C=e.authority?`${e.authority.operationsUrl}/${n}`:`${this.serverUrl}/v1/authorities/${encodeURIComponent(e.collectionId)}/operations/${n}`,g=JSON.stringify(l),A=e.authority?await Ae(this.keyStore,e,"POST",C,g,e.authority.accessToken):{},U;try{U=await Co(C,e.authority?.accessToken??e.accessToken,A,g,s.signal)}catch(P){throw p?H(h,P):P}return U.ok&&this.setRoute(e.authority?"remote":"relay"),{response:U,requestId:h,encryptedRequest:u,pendingMutation:p,...p?{pendingMutationRecord:m??this.storedPendingMutation(h)??void 0}:{},resumingMutation:f}}directCapable(e){return xr(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 ft();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 Er(this.loopbackUrl,$,e))return this.markDirectAvailable(),"available"}catch(n){throw this.markDirectUnavailable(),n}return await ft()==="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=E(this.storage.getItem(this.internals.tokenKey(this.collectionId)));!n||!_o(n,e)||(this.internals.removeToken(this.collectionId,n.keyHandle),this.currentRoute="relay",this.directStatus=this.directAccessMode==="disabled"?"disabled":"unavailable",this.emitConnection())}currentToken(){return Ir({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 V(()=>this.currentToken(),n,e);return await Tr({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 be(this.collectionId,(e,n,i)=>this.internals.acquireGrantKeyLease(e,n,i))}};function Fr(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 Pc=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]),Oc=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Te=class{state=Oc.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.subarray(n,n+64)),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 Dr(this.block,56,n),Dr(this.block,60,i),this.compress(this.block),[...this.state].map(o=>o.toString(16).padStart(8,"0")).join("")}compress(e){let n=this.words;for(let p=0;p<16;p+=1){let f=p*4;n[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=n[p-15],h=n[p-2],m=oe(f,7)^oe(f,18)^f>>>3,R=oe(h,17)^oe(h,19)^h>>>10;n[p]=n[p-16]+m+n[p-7]+R>>>0}let i=this.state[0],o=this.state[1],r=this.state[2],s=this.state[3],a=this.state[4],c=this.state[5],l=this.state[6],u=this.state[7];for(let p=0;p<64;p+=1){let f=oe(a,6)^oe(a,11)^oe(a,25),h=a&c^~a&l,m=u+f+h+Pc[p]+n[p]>>>0,R=oe(i,2)^oe(i,13)^oe(i,22),_=i&o^i&r^o&r,b=R+_>>>0;u=l,l=c,c=a,a=s+m>>>0,s=r,r=o,o=i,i=m+b>>>0}this.state[0]=this.state[0]+i>>>0,this.state[1]=this.state[1]+o>>>0,this.state[2]=this.state[2]+r>>>0,this.state[3]=this.state[3]+s>>>0,this.state[4]=this.state[4]+a>>>0,this.state[5]=this.state[5]+c>>>0,this.state[6]=this.state[6]+l>>>0,this.state[7]=this.state[7]+u>>>0}};function oe(t,e){return t>>>e|t<<32-e}function Dr(t,e,n){t[e]=n>>>24,t[e+1]=n>>>16,t[e+2]=n>>>8,t[e+3]=n}var gn=class{constructor(e,n){this.signal=n;this.iterator=Ac(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(){zr(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(Ur(n))};n.addEventListener("abort",a,{once:!0}),i=()=>n.removeEventListener("abort",a),n.aborted&&a()});try{let r=await Promise.race([e,o]);return zr(n),r}finally{i()}}closeIterator(){if(!this.iteratorClosing){this.iteratorClosing=!0;try{this.iterator.return?.()?.catch(()=>{})}catch{}}}};function Ac(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 zr(t){if(t?.aborted)throw Ur(t)}function Ur(t){return d("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:t?.reason})}var Lr=1024*1024,Tc=4,Nr=8,Rt=3,si=64*1024*1024,jr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Br=/^sha256:[0-9a-f]{64}$/u;async function Kr(t,e,n){let i=new Te;for(let o=0;o<t.size;o+=Lr){_e(e);let r=new Uint8Array(await t.slice(o,o+Lr).arrayBuffer());i.update(r),n(Math.min(t.size,o+r.byteLength))}return t.size===0&&n(0),i.digestHex()}function Vr(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 Gr(t){return t instanceof Blob?t.size:t.byteLength}async function Hr(t){return t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t}function ai(t=Tc){if(!Number.isInteger(t)||t<1||t>Nr)throw d("invalid_request",`File concurrency must be between 1 and ${Nr}.`);return t}function $r(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)||!kc(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 kc(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 bn(t,e){for(let n=1;n<=ti;n+=1){_e(e);try{return await t()}catch(i){if(e?.aborted||n===ti||i instanceof v&&!i.retryable)throw i;await Cr(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 Wr(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 _e(t){if(t?.aborted)throw d("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:t.reason})}function ke(t){return t instanceof v?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 Ze=class{constructor(e,n,i,o,r=qe()){this.capability=e;this.request=n;this.framed=i;this.hosted=o;this.timeouts=r}capability;request;framed;hosted;timeouts;async*list(e={}){let n=fe(e,this.timeouts.fileIndexMs),i=n.signal;try{this.requireAction("list");let o;do{_e(i);let r=new URLSearchParams({protocol_version:String(1),...e.folder?{folder:e.folder}:{},...o?{after:o}:{},...e.pageSize?{limit:String($r(e.pageSize))}:{}}),s;for(;;)try{s=await this.request("GET",`?${r.toString()}`,void 0,i);break}catch(a){let c=ke(a);if(c.code!=="file_index_warming")throw c;e.onIndexing?.(),await te(500,i)}if(s.protocol_version!==1||s.type!=="files_page"||!Array.isArray(s.files))throw d("invalid_operation_response","The authority returned an invalid file page.");for(let a of s.files)_e(i),yield _n(a);o=s.next}while(o)}finally{n.dispose()}}async upload(e,n,i={}){return K(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=Vr(n,i.mediaType),r=ai(i.concurrency),s=await Kr(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 K(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(!Br.test(n.contentDigest))throw d("invalid_request","Streamed files require a lowercase SHA-256 content digest.");let o=new gn(n.stream,i.signal),r=new Te;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 p=r.transferId??crypto.randomUUID();if(!jr.test(p))throw d("invalid_request","File transfer ID must be a UUID.");let f=!1;try{let h=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(ci(h,p,"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 R=h.strategy.kind==="object_put"?Math.max(1,n):h.strategy.kind==="framed_chunks"?h.strategy.chunk_size:h.strategy.part_size,_=h.strategy.kind==="object_put"?1:Math.ceil(n/R),b=h.prepared_upload_part;if(b!==void 0){if(ui(b,p,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(p)}`,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?.(R),!m&&C?.received.length===_){let T=await this.tryReplayUploadCommit(p,h.strategy.kind==="object_multipart"?C.uploaded_parts:void 0,r.signal);if(T)return f=!0,_n(T.file)}let g=new Set(C?.received??[]),A=new Map((C?.uploaded_parts??[]).map(T=>[T.part_number-1,T])),U=[...g].reduce((T,O)=>T+di(n,R,O),0),P=await Wr(_,s,async T=>{let O=T*R,G=Math.min(R,Math.max(0,n-O)),Q=await a(T,O,G);if(Gr(Q)!==G)throw d("invalid_request","Streamed file bytes ended before the declared size.");if(g.has(T))return A.get(T)??null;let ne=m?await bn(async()=>this.framed.uploadChunk(h,T,await Hr(Q),r.signal),r.signal).then(()=>null):await this.uploadPart(p,T,O,Q,G,h.strategy.kind==="object_multipart",r.signal,b?{session:h,part:b}:void 0);return U+=G,r.onProgress?.({phase:"uploading",transferredBytes:U,totalBytes:n}),ne});await c?.();let k=await this.commitUpload(p,h.strategy.kind==="object_multipart"?P.filter(T=>T!==null):void 0,r.signal);if(k.protocol_version!==1||k.type!=="file_upload_committed"||k.transfer_id!==p||k.file.path!==e||k.file.size!==n||k.file.content_digest!==i)throw d("invalid_operation_response","The authority returned an invalid file receipt.");return f=!0,_n(k.file)}catch(h){throw ke(h)}finally{await l?.().catch(()=>{}),!f&&r.transferId===void 0&&await this.abort(p)}}async download(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=[],r=i.getReader();for(;;){let s=await r.read();if(s.done)break;o.push(s.value)}return new Blob(o.map(s=>{let a=new Uint8Array(s.byteLength);return a.set(s),a.buffer}),{type:e.mediaType??""})}async downloadStream(e,n={}){return K(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(P){throw await this.abort(r),ke(P)}let a=s.strategy.kind==="framed_chunks"?s.strategy.chunk_size:s.strategy.part_size,c=Math.ceil(e.size/a),l=new Te,u=0,p=0,f=null,h=0,m=!1,R=new AbortController,_=n.signal?AbortSignal.any([n.signal,R.signal]):R.signal,b=new Map,C=0,g=()=>{if(s.strategy.kind==="framed_chunks")for(;C<c&&b.size<o;){let P=C;C+=1;let k=bn(()=>this.framed.downloadChunk(s,P,_),_).then(T=>({ok:!0,chunk:T}),T=>({ok:!1,error:T}));b.set(P,k)}},A=async()=>{m||(m=!0,R.abort(),await f?.cancel().catch(()=>{}),f=null,await Promise.all(b.values()),b.clear(),await this.abort(r))},U=()=>{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 P=>{try{if(_e(_),s.strategy.kind==="object_ranges")for(;;){if(!f){if(u>=c){U(),P.close(),A();return}let us=u*a;p=Math.min(a,e.size-us),f=(await bn(()=>this.hosted.downloadPart(s,u,p,_),_)).getReader()}let ne=await f.read();if(ne.done){if(f.releaseLock(),f=null,p!==0)throw d("invalid_operation_response","A hosted file range ended before its declared byte length.");u+=1;continue}if(!(ne.value instanceof Uint8Array))throw d("invalid_operation_response","A hosted file range returned a non-byte chunk.");if(ne.value.byteLength!==0){if(ne.value.byteLength>p)throw d("invalid_operation_response","A hosted file range exceeded its declared byte length.");p-=ne.value.byteLength,l.update(ne.value),h+=ne.value.byteLength,n.onProgress?.({phase:"downloading",transferredBytes:h,totalBytes:e.size}),P.enqueue(ne.value);return}}if(u>=c){U(),P.close(),A();return}let k=u*a,T=Math.min(a,e.size-k);g();let O=b.get(u);if(!O)throw d("invalid_operation_response","A file chunk was not scheduled.");let G=await O;if(b.delete(u),!G.ok)throw G.error;let Q=G.chunk;if(Q.byteLength!==T)throw d("invalid_operation_response","A file chunk had the wrong byte length.");l.update(Q),h+=Q.byteLength,u+=1,g(),n.onProgress?.({phase:"downloading",transferredBytes:h,totalBytes:e.size}),u===c&&U(),P.enqueue(Q),u===c&&(P.close(),A())}catch(k){let T=n.signal?.aborted?d("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:n.signal.reason}):k;await A(),P.error(ke(T))}},cancel:A})}async downloadBytes(e,n={}){return new Uint8Array(await(await this.download(e,n)).arrayBuffer())}async move(e,n,i={}){return K(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 ke(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 _n(r.file)}async delete(e,n={}){return K(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 ke(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<=Rt;l+=1){_e(a);try{let u=l===1&&c&&Date.parse(c.part.expires_at)>Date.now()+6e4;if(c&&!u){let _=await this.request("GET",`transfers/${encodeURIComponent(e)}`,void 0,a);if(li(_,c.session),_.state!=="open"&&_.state!=="committed")throw d("invalid_operation_response",`The authority cannot resume a ${_.state} file transfer.`);if(_.received.includes(n))return{part_number:n+1,etag:""}}let p=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(p,e,n,i,r,"PUT");let f=pi(p.headers),h=await fetch(p.url,{method:p.method,headers:f,body:o,redirect:"error",signal:a});if(h.status===412&&!s&&f.get("if-none-match")==="*")return{part_number:n+1,etag:""};if(!h.ok)throw new Error(`Object upload failed with HTTP ${h.status}.`);let R=h.headers.get("etag");if(s&&!R)throw new Error("Multipart object upload did not return an ETag.");return{part_number:n+1,etag:R??""}}catch(u){if(a?.aborted||l===Rt)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 v&&o.code==="file_upload_incomplete")return null;throw o}}async commitUpload(e,n,i){let o;for(let r=1;r<=Rt;r+=1){_e(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 v||r===Rt)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(()=>{})}};function _n(t){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 et=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;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 S(this.record);let i=await n(this.record,e);return i.ok?(this.seen.add(this.adapter.revision(i.value)),this.classify(i.value),this.emit(),S(this.record)):(i.problem.code==="file_not_found"&&this.markDeleted(),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))Ie(i[o],r)&&delete this.patch[o];this.record=e,this.remote=null,this.problem=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 y(hi());if(this.remote)return y(fi());if(!this.inFlight&&!this.pending&&!this.dirtyLocally())return S(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 y(fi());if(this.deleted)return y(hi());if(!this.dirtyLocally())return S(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),S(this.record);let r=Ic(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"?S(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 y(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),S(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?y(hi()):this.remote?y(fi()):y(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&&Ie(this.patch[i],o)&&delete this.patch[i];this.problem=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])=>!Ie(a[l],s[l])&&!Ie(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))Ie(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?"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.pending?{pendingRequestId:this.pending.requestId}:{}}}emit(){this.current=this.compute(),this.listeners.forEach(e=>e())}};function fi(){return w("concurrent_modification","This record changed elsewhere. Local changes are kept until the conflict is resolved.")}function hi(){return w("file_not_found","This record no longer exists. Local changes are kept.")}function Ic(t){return t.code==="operation_outcome_unknown"?t.details.request_id:void 0}function Ie(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)=>Ie(i,e[o]));let n=Object.keys(t);return n.length===Object.keys(e).length&&n.every(i=>i in e&&Ie(t[i],e[i]))}var tt=class{constructor(e,n=async()=>null){this.connection=e;this.pendingUpdate=n}connection;pendingUpdate;entries=new Map;opening=new Map;async open(e,n={}){for(;;){let i=this.entries.get(e);if(i)return S(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 S(this.lease(s.value));if(!(o&&(s.problem.code==="operation_cancelled"||s.problem.code==="timeout"))||n.signal?.aborted)return s}}follow(e){return e.subscribe(n=>this.apply(n),n=>{if(n.state==="reset_required")for(let i of this.entries.values())i.session.refresh()})}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 S(s);let a={path:r.value.path,leases:0};a.session=new et(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),S(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):y(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}=e.session.snapshot;return i!=="saved"&&i!=="deleted"?!1:(e.stopRetiring?.(),e.stopRetiring=void 0,this.entries.get(e.path)===e&&this.entries.delete(e.path),!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),o.session.refresh();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||i.session.refresh()}};var Mc=4,Jr=32,vn=class{constructor(e,n,i={}){this.transport=e;this.requestTimeoutMs=n;this.foregroundCapacity=mi(i.foregroundCapacity,Mc),this.foregroundQueueCapacity=mi(i.foregroundQueueCapacity,Jr),this.mutationQueueCapacity=mi(i.mutationQueueCapacity,Jr)}transport;requestTimeoutMs;foregroundCapacity;foregroundQueueCapacity;mutationQueueCapacity;foregroundQueue=[];mutationQueue=[];identicalReads=new Map;latestFamilies=new Map;activeForeground=0;mutationActive=!1;operation(e,n,i={}){let o=!pe(e,n),r=xc(i.coordination,o),s=o&&r.coalesce!==!1&&!r.latestWins&&i.signal===void 0?Ec(e,n,i.timeoutMs):void 0;if(s){let c=this.identicalReads.get(s);if(c)return c}let a=K(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=qc(s.signal,a?.signal),{coordination:l,...u}=i,p=lt({...u,timeoutMs:null},s),f=()=>this.transport.operation(e,n,{...p,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((R,_)=>{let b={budget:s,run:f,resolve:A=>R(A),reject:_,started:!1,settled:!1},C=()=>{b.started||b.settled||(b.settled=!0,h.splice(h.indexOf(b),1),b.reject(J(c.signal)),c.dispose(),this.releaseLatest(o.family,a))};c.signal.addEventListener("abort",C,{once:!0});let g=b.run;b.run=async()=>{c.signal.removeEventListener("abort",C);try{if(c.signal.aborted)throw J(c.signal);return await g()}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=Qr(this.foregroundQueue);if(!e)break;this.activeForeground+=1,this.start(e,()=>{this.activeForeground-=1,this.pump()})}if(!this.mutationActive){let e=Qr(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 Qr(t){for(;t.length>0;){let e=t.shift();if(!e.settled)return e}}function xc(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 Ec(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 qc(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 mi(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 nt=class{constructor(e,n){this.internals=e;this.collectionId=n;this.transport=new yn({serverUrl:e.serverUrl,storage:e.storage,keyStore:e.keyStore,directAccessMode:e.directAccessMode,loopbackUrl:e.loopbackUrl,collectionId:n,internals:e,timeouts:e.timeouts,onChange:()=>this.emitConnection()}),this.people=new $e({request:(i,o)=>Jo(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 Ze(()=>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),this.records=new tt(this,i=>this.transport.pendingUpdate(i)),this.collectionClient=new We(new vn({operation:(i,o,r)=>this.transport.performOperation(i,o,r)},e.timeouts.requestMs),e.timeouts.requestMs),this.notifications=new tn({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;files;records;people;connectionListeners=new Set;get displayName(){return this.transport.currentToken()?.collectionName??`Collection ${this.collectionId.slice(0,8)}`}get operations(){return[...this.transport.currentToken()?.operations??[]]}get scope(){return this.transport.currentToken()?.scope??null}get fileCapability(){return this.transport.currentToken()?.fileCapability??null}get directAccess(){return this.transport.directAccess}get route(){return this.transport.route}register(e){return q(()=>this.internals.register(e),Re)}info(){let e=this.transport.currentToken();return e?{collectionId:e.collectionId,displayName:e.collectionName,operations:[...e.operations],scope:e.scope,...e.fileCapability?{fileCapability:e.fileCapability}:{},authority:e.authority?{kind:"hosted",durability:"provider"}:{kind:"connector",durability:"computer"},route:this.transport.route,directAccess:this.transport.directAccess}:null}authorizationCapabilities(e=Se){let n=this.operations,i=ht(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 q(()=>this.internals.authorize({...e,target:{kind:"collection",collectionId:this.collectionId}}),he)}async requestCapabilities(e,n={}){return q(async()=>{let i=await this.internals.register(n);if(X(i.requirements,{...n,capabilities:e}),this.info()!==null&&e.every(s=>(W(j(i.requirements),s)??[]).every(a=>this.operations.includes(a))))return{kind:"unchanged",connection:this};if(j(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=>W(1,c)??[])])]})}let r=qt(i.requirements,this.operations);return this.internals.authorize({...n,target:{kind:"collection",collectionId:this.collectionId},capabilities:[...new Set([...r,...e])]})},he)}async requestOperations(e,n={}){return q(async()=>{let i=await this.internals.register(n);X(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])]})},he)}onConnectionChange(e){return this.connectionListeners.add(e),e(this.info()),()=>this.connectionListeners.delete(e)}notifyStorageChanged(){this.transport.notifyStorageChanged()}checkDirectAccess(e){return q(()=>this.transport.checkDirectAccess(e),Bn)}requestDirectAccess(e){return q(()=>this.transport.requestDirectAccess(e),Bn)}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"},Cn(r,this.internals.timeouts.syncMs)),snapshot:(r,s,a)=>this.transport.performOperation("sync",{action:"snapshot",snapshot_id:r,...s?{page:s}:{}},Cn(a,this.internals.timeouts.syncMs)),changes:(r,s=200,a)=>this.transport.performOperation("sync",{action:"changes",after:r,limit:s},Cn(a,this.internals.timeouts.syncMs)),mutate:(r,s)=>this.transport.performOperation("sync",{action:"mutate",mutation:r},Cn(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 q(()=>this.notifications.registerNotifications(e),dt)}registerNativeNotifications(e){return q(()=>this.notifications.registerNativeNotifications(e),dt)}unregisterNativeNotifications(e){return q(()=>this.notifications.unregisterNativeNotifications(e),dt)}unregisterNotifications(e,n){return q(()=>this.notifications.unregisterNotifications(e,n),dt)}forget(){let e=this.transport.currentToken();this.internals.removeToken(this.collectionId,e?.keyHandle,"not_authorized",!0),this.transport.notifyStorageChanged()}describe(e){return this.collectionClient.describe(e)}changes(e={},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 this.collectionClient.queryPages(e,n)}queryAll(e={},n={}){return 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 K(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{Pe(i.signal),a("preflighting",!0);let c=n.preflight?S(n.preflight):await this.preflightRename(e,{signal:i.signal,timeoutMs:null});if(!c.ok)return c;let l=c.value;try{wo(e,l)}catch(f){if(f instanceof v)return y(f.problem);throw f}s=Ro(e,l),a("ready",!0),Pe(i.signal);let u=this.transport.hasResumableMutationTransport();a("applying",u);let p=await this.rename(e,u?{signal:i.signal,timeoutMs:null}:{timeoutMs:Yr(i.remainingMs())});return p.ok&&a("completed",!1,s.totalUnits),p}catch(c){if($n(c,i.signal)&&a("cancelled",!1),c instanceof v)return y(c.problem);throw c}})}async deleteWithProgress(e,n={}){return K(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{Pe(i.signal),a("preflighting",!0);let c=n.preflight?S(n.preflight):await this.preflightDelete(e,{signal:i.signal,timeoutMs:null});if(!c.ok)return c;let l=c.value;try{So(e,l)}catch(f){if(f instanceof v)return y(f.problem);throw f}s=Po(l),a("ready",!0),Pe(i.signal);let u=this.transport.hasResumableMutationTransport();a("applying",u);let p=await this.delete(e,u?{signal:i.signal,timeoutMs:null}:{timeoutMs:Yr(i.remainingMs())});return p.ok&&a("completed",!1,s.totalUnits),p}catch(c){if($n(c,i.signal)&&a("cancelled",!1),c instanceof v)return y(c.problem);throw c}})}pendingMutations(){return this.transport.pendingMutations().map(e=>({...e,recover:n=>q(()=>this.recoverPendingMutation(e.requestId,n),B)}))}pendingMutation(e){let n=this.transport.pendingMutation(e);return n?{...n,recover:i=>q(()=>this.recoverPendingMutation(e,i),B)}: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 v(Me(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 q(()=>F(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 v(o.problem);if(o.value.reset)throw new v(w("change_cursor_reset","The collection change cursor expired. Refresh collection state before subscribing again."));return new gi(this.collectionClient,o.value.cursor,e,e.cursor===void 0?[]:o.value.events,this.internals.timeouts.watchStartMs)}),Lt)}emitConnection(){let e=this.info();for(let n of this.connectionListeners)n(e)}},gi=class{constructor(e,n,i,o,r){this.client=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)}client;input;watchStartTimeoutMs;changes=new Set;statuses=new Set;problems=new Set;controller=new AbortController;removeLifetimeAbort;currentStatus;currentProblem=null;pendingChanges;get status(){return this.currentStatus}get problem(){return this.currentProblem}subscribe(e,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.client.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)}};function Cn(t,e){return{...t,timeoutMs:t?.timeoutMs===void 0?e:t.timeoutMs}}function Yr(t){return t===null?null:Math.max(1,Math.ceil(t))}async function es(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 ts(t){let e=is(t.storagePrefix,t.state);try{for(;;){let n=E(t.storage.getItem(e));if(n?.version===1){if(t.storage.removeItem(e),n.status==="failed")throw z(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 te(200,t.signal)}}finally{t.popup.close(),t.storage.removeItem(e);let n=`${t.storagePrefix}:pending:${t.state}`;E(t.storage.getItem(n))?.state===t.state&&(t.storage.removeItem(n),t.pending.keyHandle&&await t.keyStore.delete(t.pending.keyHandle))}}function ns(t){return t.completion.then(e=>(t.popupAttempt&&Xr(t,{version:1,status:"connected",collectionId:e.connection.collectionId,...e.returnTo?{returnTo:e.returnTo}:{}}),t.popupAttempt&&Zr(),e)).catch(e=>{throw t.popupAttempt&&Xr(t,{version:1,status:"failed",code:e instanceof v?e.code:"invalid_callback",message:e instanceof Error?e.message:"Authorization could not be completed.",...t.pending?.returnTo?{returnTo:t.pending.returnTo}:{}}),t.popupAttempt&&Zr(),e})}function Xr(t,e){t.storage.setItem(is(t.storagePrefix,t.state),JSON.stringify(e))}function is(t,e){return`${t}:completion:${e}`}function Zr(){typeof window<"u"&&typeof window.close=="function"&&window.close()}function bi(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=E(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!==$&&ot(l)&&r.add(l)}return[...r].sort((s,a)=>a-s)}function _i(t,e,n){return vi(t,e).has(n)}function vi(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=E(t.getItem(o));r?.keyHandle&&n.add(r.keyHandle)}return n}function os(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=E(t.getItem(o));r?.keyHandle&&n(r.keyHandle),t.removeItem(o)}}function rs({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=Gt(t.scope);if(!c)throw d("invalid_token_response","Authorization returned no valid collection scope.");if(!Ht(c))throw d("legacy_scope_reauthorization_required","Authorization returned a legacy contract-scoped grant. Reauthorize for the entire collection.");if(t.authority&&!gt(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&&!Vt(t.file_capability))throw d("invalid_token_response","Authorization returned an invalid file capability.");if(t.encryption){try{ce(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 Ci(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 ss(t,e,n,i,o=[],r=!1){let s=[],a=[],c=Ci(n);for(let u of vi(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)||_i(t,e,u)?s:a).push(u);return{retained:s,disposable:a}}function Fc(t,e,n){let i=E(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 as(t,e,n,i,o){E(t.getItem(i))?.keyHandle===o||_i(t,n,o)||(await e.delete(o),Fc(t,i,o))}var wn=class{serverUrl;manifest;manifestSource;redirectUri;storage;relayEncryption;keyStore;identityStore;directAccessMode;loopbackUrl;navigate;timeouts;credentialStorage;application=null;manifestPromise=null;completionPromises=new Xe;grantKeyLeases;connectionCache=new Map;listeners=new Set;invalidatedConnections=new Map;constructor(e){this.serverUrl=Do(String(e.serverUrl));let n=Mo(e.manifest,e.redirectUri);this.manifest=n.manifest,this.manifestSource=n.manifestSource;let i=No(this.manifest);this.redirectUri=n.redirectUri,this.storage=e.storage??Lo(i),this.relayEncryption=e.relayEncryption??"required",this.keyStore=e.keyStore??(i?new De:new Fe),this.identityStore=e.identityStore??(i?new Ge:new Ve),this.credentialStorage=e.storage||e.keyStore||e.identityStore?"custom":this.storage instanceof Le?"memory":"persistent",this.directAccessMode=e.directAccess??"auto",this.loopbackUrl=xo(String(e.loopbackUrl??`http://127.0.0.1:${Ji}`)),this.navigate=e.navigate,this.timeouts=qe(e.timeouts),this.grantKeyLeases=new on(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(Uo(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 F(e,this.timeouts.requestMs,n=>this.registerWithinBudget(n.signal))}async registerWithinBudget(e){if(this.application)return this.application;let n=await ee(`${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 M(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=F(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 M(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 F(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 es({options:e,portableDeclared:n,navigate:this.navigate,register:r=>this.registerWithinBudget(r)});try{X(i.requirements,e),i.requirements.capabilities?.contract_version===2&&await jo(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 mt(),s=Z(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),p;try{p=await this.loadApplicationIdentity(e)}catch(b){throw await this.keyStore.delete(l),b}let f=Un(e,n),h=Ln(e.requirements),m=new Date,R=await wt({protocol_version:ie,authorization_id:a,application_id:e.id,application_declaration_id:bt(e.family_identity),application_manifest_digest:e.manifest_digest,application_installation_id:await He(p),installation_signing_public_key:p.signingPublicKey,grant_agreement_public_key:u.agreementPublicKey,grant_signing_public_key:u.signingPublicKey,flow:"authorization_code",authorization_nonce:Z(32),issued_at:m.toISOString(),expires_at:new Date(m.getTime()+600*1e3).toISOString(),redirect_uri:this.redirectUri,state:s,code_challenge:r,contracts:Fn(f,h,bi(this.storage,this.storagePrefix(),f,c),j(e.requirements)),requested_operations:f,...h?{requested_files:h}:{},...c?{collection_id:c}:{}},p),_={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(_));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:f.join(","),...c?{collection_id:c}:{},application_authorization:JSON.stringify(R)}),signal:n.signal}),C=await M(b,"invalid_device_authorization_response","The authorization service returned an invalid authorization response.");if(!b.ok)throw D(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 ts({storage:this.storage,storagePrefix:this.storagePrefix(),state:s,pending:_,popup:i,signal:n.signal,keyStore:this.keyStore,connection:g=>this.connection(g)});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?Ne(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 mt(),s=`grant:${e.id}:${Z(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=Un(e,n),u=Ln(e.requirements),p=crypto.randomUUID(),f=new Date,h=await wt({protocol_version:ie,authorization_id:p,application_id:e.id,application_declaration_id:bt(e.family_identity),application_manifest_digest:e.manifest_digest,application_installation_id:await He(c),installation_signing_public_key:c.signingPublicKey,grant_agreement_public_key:a.agreementPublicKey,grant_signing_public_key:a.signingPublicKey,flow:"device_code",authorization_nonce:Z(32),issued_at:f.toISOString(),expires_at:new Date(f.getTime()+600*1e3).toISOString(),code_challenge:r,contracts:Fn(l,u,bi(this.storage,this.storagePrefix(),l,n.target?.kind==="collection"?n.target.collectionId:void 0),j(e.requirements)),requested_operations:l,...u?{requested_files:u}:{},...n.target?.kind==="collection"?{collection_id:n.target.collectionId}:{}},c),m,R;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}),R=await M(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),D(R,"device_authorization_failed","Downloaded application authorization could not be started.",m.status);let _;try{_=Fo(R)}catch(C){throw i?.close(),await this.keyStore.delete(s),n.signal?.aborted?Ne(n.signal,"Downloaded application authorization was cancelled.",C):C}if(n.onDeviceCode?.(_),n.openVerification)await n.openVerification(_);else if(i)try{i.location.href=_.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:_.userCode,verification_uri:_.verificationUri,verification_uri_complete:_.verificationUriComplete,expires_at:_.expiresAt,interval_seconds:_.intervalSeconds}});let b=_.intervalSeconds;try{for(;Date.now()<_.expiresAt;){if(await te(b*1e3,n.signal),n.signal?.aborted)throw Ne(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:R.device_code,client_id:e.id,code_verifier:o}),signal:n.signal})}catch(k){if(n.signal?.aborted)throw Ne(n.signal,"Downloaded application authorization was cancelled.",k);continue}let g=await M(C,"invalid_token_response","The authorization service returned an invalid token response.");if(!C.ok){let k=yt(g);if(k==="authorization_pending")continue;if(k==="slow_down"){b+=5;continue}throw D(g,"token_exchange_failed","Downloaded application authorization could not be completed.",C.status)}let A=gt(g.authority,g.collection_id),U=g.encryption&&g.encryption.protocol_version===Et&&g.encryption.suite===st&&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&&!U)throw d("encryption_required","Authorization did not establish the expected key-bound local portable grant.");let P=this.storeTokenResponse(g,e.id,s);if(n.target?.kind==="collection"&&n.target.collectionId!==P.collectionId)throw this.removeToken(P.collectionId,P.keyHandle),d("collection_mismatch","The approved collection does not match the collection requested by this link.");return i?.close(),{kind:"connected",connection:this.connection(P.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?Ne(n.signal,"Downloaded application authorization was cancelled.",C):C}}completeAuthorization(e,n={}){let i=Jt(e);if(!i)return Promise.reject(d("invalid_callback","Authorization callback is missing its state."));let o=E(this.storage.getItem(this.pendingKey(i))),r=o?.presentation==="popup";return this.completionPromises.run(i,n,this.timeouts.requestMs,s=>ns({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=E(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),z(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 ee(`${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 M(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 Kt(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 nt(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=E(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=E(this.storage.getItem(this.tokenKey(o))),s=ss(this.storage,this.pendingMutationKey(o),r,i,this.grantKeyLeases.handles(o),this.grantKeyLeases.retainAutomaticallyRetiredKeys),a;try{a=rs({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 v&&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 To(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=E(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 Qt(this.identityStore,this.serverUrl,e)}catch(n){throw d("application_identity_unavailable",n instanceof Oe?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=E(this.storage.getItem(this.tokenKey(e))),s=Ci(r,n);this.storage.removeItem(this.tokenKey(e)),o&&os(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));ko(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,()=>as(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 zo(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 Sn=class{internals;constructor(e){this.internals=new wn(e)}register(e){return q(()=>this.internals.register(e),Re)}authorize(e={}){return q(()=>this.internals.authorize(e),he)}application(e){return new Be(this,e,this.internals.timeouts)}manifest(e){return q(()=>this.internals.manifestDeclaration(e),Re)}environment(){return this.internals.environment()}completeAuthorization(e,n){return q(()=>this.internals.completeAuthorization(e===void 0?$t():String(e),n),he)}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 wi(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 cs(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 ls(t,e){let n=wi(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 ds(t){return{subscribe:e=>t.subscribe(e),getSnapshot:()=>t.getSnapshot()}}var Rn=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=_t(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=_t(this.currentUrl());return`${e.pathname}${e.search}${e.hash}`}authorizationCallback(){let e=this.currentUrl().href;return Wt(e)?e:null}finishAuthorization(e,n){let i=this.safeAppUrl(e??this.fallbackPath);_t(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,"",_t(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}},Pn=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 gs(Dc);})();
|
|
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.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}:{}}))}}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);})();
|