@mdbase-dev/connect 0.1.0-beta.123 → 0.1.0-beta.125
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 +77 -2
- package/dist/application-session.js +9 -3
- 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.js +2 -9
- package/dist/collection-client.d.ts +7 -2
- package/dist/collection-client.js +76 -97
- package/dist/connection.d.ts +8 -1
- package/dist/connection.js +55 -116
- package/dist/description-cache.js +1 -28
- package/dist/file-descriptor.d.ts +2 -0
- package/dist/file-descriptor.js +17 -0
- package/dist/file-metadata.d.ts +21 -0
- package/dist/file-metadata.js +112 -0
- package/dist/files.d.ts +7 -8
- package/dist/files.js +13 -45
- package/dist/index.d.ts +2 -2
- package/dist/local-file-transport.js +18 -16
- package/dist/operation-types.d.ts +44 -16
- package/dist/query-pagination.d.ts +7 -3
- package/dist/query-pagination.js +3 -1
- package/dist/query-wire.d.ts +61 -0
- package/dist/query-wire.js +110 -0
- package/dist/read-many.d.ts +4 -3
- package/dist/read-many.js +160 -55
- package/dist/watch-policy.d.ts +22 -1
- package/dist/watch-policy.js +104 -0
- package/package.json +3 -3
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var MdbaseConnect=(()=>{var Dn=Object.defineProperty;var Ms=Object.getOwnPropertyDescriptor;var Is=Object.getOwnPropertyNames;var xs=Object.prototype.hasOwnProperty;var Es=(t,e)=>{for(var n in e)Dn(t,n,{get:e[n],enumerable:!0})},qs=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Is(e))!xs.call(t,o)&&o!==n&&Dn(t,o,{get:()=>e[o],enumerable:!(i=Ms(e,o))||i.enumerable});return t};var Fs=t=>qs(Dn({},"__esModule",{value:!0}),t);var tl={};Es(tl,{ApplicationIdentityStoreError:()=>Te,FileTransferCryptoError:()=>ue,GrantFileTransferCipher:()=>Xe,IndexedDbApplicationIdentityStore:()=>He,IndexedDbGrantKeyStore:()=>ze,MDBASE_RECORD_CREATED_CONTRACT:()=>co,MDBASE_TIMER_FIRED_CONTRACT:()=>lo,MdbaseApplicationSession:()=>Ve,MdbaseBrowserSelection:()=>En,MdbaseCollectionClient:()=>Ye,MdbaseConnect:()=>xn,MdbaseConnectError:()=>w,MdbaseConnection:()=>rt,MdbaseFileClient:()=>nt,MdbaseMemorySelection:()=>qn,MdbaseMemoryVerificationStore:()=>At,MdbasePeopleClient:()=>Je,MdbaseRecordSession:()=>it,MdbaseRecords:()=>ot,MdbaseSession:()=>Ke,MemoryApplicationIdentityStore:()=>$e,MemoryGrantKeyStore:()=>Le,PERSON_CONTRACT:()=>kt,RelayCryptoError:()=>x,applicationIdentity:()=>nn,applicationInstallationId:()=>We,authorityProofMessage:()=>si,connectError:()=>d,connectFailure:()=>g,connectProblem:()=>R,connectSuccess:()=>S,createPkce:()=>Ct,decryptRelayResponse:()=>Ue,deriveFileTransferKey:()=>mi,deriveP256SharedSecret:()=>bt,effectiveCapabilities:()=>Bt,encryptRelayRequest:()=>le,externalStore:()=>ks,isRetryableConnectError:()=>yo,linksTo:()=>Ts,normalizeCollectionChange:()=>Yn,operationProblem:()=>Ee,operationsForApplicationCapabilities:()=>Li,parseMdbaseNativeNotificationData:()=>Os,parseMdbasePushPayload:()=>zi,sameIdentity:()=>rn,showMdbasePushNotification:()=>As,signApplicationAuthorization:()=>Tt,signAuthorityRequest:()=>$t,validateGrantEncryption:()=>de});var It={"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"]},xt=["assess_collection_setup","apply_collection_setup"];function Li(t,e={}){let n=e.includeOptional===!1?t.required:[...t.required,...t.optional??[]];return[...new Set(n.flatMap(i=>It[i]))]}var Ds=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 Y(t,e){let n=t===1?Ds:t===2?It:void 0;if(!(!n||!Object.hasOwn(n,e)))return[...n[e]]}var il=Object.freeze([1,2]),Ui="application-authorization-v2-issuance",zn=Object.freeze(["application-authorization-v2-issuance"]);var Ni="yaml-document-records-v1";var Ce={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"}},zs={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 ji(t){return Object.hasOwn(Ce,t)}function at(t){if(!Bi(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"||!ji(e.code)||e.server_code!==void 0)return!1;let n=Ce[e.code],i=zs[e.code],o=i===void 0?e.details===void 0:e.details===void 0?(i.required?.length??0)===0:Ln(e.details,i);return e.category===n.category&&e.recovery===n.recovery&&o}function Ln(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=>Ln(i,e.items??{}));if(!Bi(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])=>Ln(o,e.properties[i]))}function Bi(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Un(t,e,n={}){if(ji(t)){let i=Ce[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(at(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 Ki=new Uint8Array([77,68,66,70]),Vi=1,Gi=0,al=new Uint8Array([77,68,66,82]);var Hi=/^[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 $i(t,e={}){return{actions:[...new Set([...t.required,...e.includeOptional===!1?[]:t.optional??[]])],scope:structuredClone(t.scope)}}var M=class extends Error{code;constructor(e,n){super(n),this.code=e,this.name="FileFrameError"}};function Ls(t){return t==="upload_chunk"?1:2}function Us(t){if(t===1)return"upload_chunk";if(t===2)return"download_chunk";throw new M("invalid_kind",`Unknown file frame kind ${t}`)}function Ns(t){if(!t||typeof t!="object"||Array.isArray(t))throw new M("invalid_header","File frame header must be a JSON object");return t}function qt(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new M("invalid_header",`File frame header ${e} must be a non-empty string`);return n}function Et(t,e){let n=qt(t,e);if(!Hi.test(n))throw new M("invalid_header",`File frame header ${e} must be a UUID`);return n}function we(t,e,n=Number.MAX_SAFE_INTEGER){let i=t[e];if(!Number.isSafeInteger(i)||i<0||i>n)throw new M("invalid_header",`File frame header ${e} is outside its allowed range`);return i}function Nn(t){if(t.protocol_version!==1)throw new M("unsupported_version",`Unsupported file transfer protocol ${t.protocol_version}`);if(t.protection!=="grant_aead_v1"&&t.protection!=="transport_tls")throw new M("invalid_header","Unknown file transfer protection");if(t.direction!=="upload"&&t.direction!=="download")throw new M("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(!Hi.test(n))throw new M("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 M("invalid_header",`File frame header ${e} is outside its allowed range`);if(t.chunk_size<64*1024)throw new M("invalid_header","File frame chunk_size is below the protocol minimum");if(!Number.isSafeInteger(t.scope_epoch)||t.scope_epoch<1)throw new M("invalid_header","File frame header scope_epoch must be a positive integer");if(t.protection==="grant_aead_v1"&&!t.key_id)throw new M("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 js(t){let e;try{e=new TextDecoder("utf-8",{fatal:!0}).decode(t)}catch{throw new M("invalid_header","File frame header is not valid UTF-8")}let n;try{n=Ns(JSON.parse(e))}catch(l){throw l instanceof M?l:new M("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 M("invalid_header","File frame header contains an unknown field");let o=we(n,"protocol_version");if(o!==1)throw new M("unsupported_version",`Unsupported file transfer protocol ${o}`);let r=qt(n,"protection"),s=qt(n,"direction"),a=n.key_id===void 0?void 0:qt(n,"key_id"),c=Nn({protocol_version:1,protection:r,grant_id:Et(n,"grant_id"),authority_id:Et(n,"authority_id"),collection_id:Et(n,"collection_id"),transfer_id:Et(n,"transfer_id"),direction:s,chunk_size:we(n,"chunk_size",4194304),chunk_index:we(n,"chunk_index"),offset:we(n,"offset"),plaintext_length:we(n,"plaintext_length",4194304),total_size:we(n,"total_size"),scope_epoch:we(n,"scope_epoch"),...a===void 0?{}:{key_id:a}});if(JSON.stringify(c)!==e)throw new M("invalid_header","File frame header must use the canonical field order without duplicate fields or whitespace");return c}function jn(t,e,n){let i=t==="upload_chunk"?"upload":"download";if(e.direction!==i)throw new M("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 M("invalid_header","Chunk offset does not match its index and protocol chunk size");if(e.offset+e.plaintext_length>e.total_size)throw new M("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 M("invalid_length","Payload length does not match the protected plaintext length")}function Bs(t){return t.plaintext_length+(t.protection==="grant_aead_v1"?16:0)}function Ft(t,e){let n=Nn(e),i=Bs(n);jn(t,n,i);let o=new TextEncoder().encode(JSON.stringify(n));if(o.byteLength>16384)throw new M("limit_exceeded","File frame header exceeds the protocol limit");let r=new Uint8Array(16+o.byteLength);r.set(Ki,0);let s=new DataView(r.buffer,r.byteOffset,r.byteLength);return s.setUint8(4,Vi),s.setUint8(5,Ls(t)),s.setUint16(6,Gi,!1),s.setUint32(8,o.byteLength,!1),s.setUint32(12,i,!1),r.set(o,16),r}function Wi(t){let e=Nn(t.header);if(jn(t.kind,e,t.payload.byteLength),t.payload.byteLength>4194320)throw new M("limit_exceeded","File frame payload exceeds the protocol limit");let n=Ft(t.kind,e),i=new Uint8Array(n.byteLength+t.payload.byteLength);return i.set(n,0),i.set(t.payload,n.byteLength),i}function Dt(t,e={}){if(t.byteLength<16)throw new M("invalid_length","File frame is shorter than its fixed prefix");if(!Ki.every((p,h)=>t[h]===p))throw new M("invalid_magic","File frame magic is not MDBF");let n=new DataView(t.buffer,t.byteOffset,t.byteLength),i=n.getUint8(4);if(i!==Vi)throw new M("unsupported_version",`Unsupported file frame version ${i}`);let o=Us(n.getUint8(5));if(n.getUint16(6,!1)!==Gi)throw new M("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 M("invalid_length","File frame header must not be empty");if(r>a||s>c)throw new M("limit_exceeded","File frame exceeds the configured decode limits");let l=16+r+s;if(!Number.isSafeInteger(l)||l!==t.byteLength)throw new M("invalid_length","File frame lengths do not match the supplied bytes");let u=16+r,f=js(t.subarray(16,u));return jn(o,f,s),{kind:o,header:f,payload:t.slice(u)}}var Ks=["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"],Vs=["list_files","open_file_upload","open_file_download","move_file","delete_file","get_file_transfer_status","commit_file_upload","abort_file_transfer"],Gs={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"},Hs={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},$s={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},Ws=new Set(["open_file_upload","move_file","delete_file","commit_file_upload","abort_file_transfer"]),Js=new Set(["delete","rename"]);var Qs=new Set(Ks),Ys=new Set(Vs);function Ji(t){return Qs.has(t)}function Xs(t){return Ys.has(t)}function Qi(t,e){if(t==="file_control"){let n=Yi(e)&&typeof e.type=="string"?e.type:"";if(!Xs(n))throw new Error(`Unknown file-control message: ${n}`);return $s[n]}return Hs[t]}function fe(t,e){let n=Yi(e)?e:{};if(n.dry_run===!0&&Js.has(t))return null;if(t==="file_control"){let o=typeof n.type=="string"?n.type:"";return Ws.has(o)?`file_control:${o}`:null}let i=Gs[t];return i==="always"?t:i==="sync_action"&&n.action==="mutate"?"sync:mutate":null}function he(t,e){return fe(t,e)!==null}function Yi(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var Bn={"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 Zs=1,ea="mdbase-connect mutation fingerprint v1\0",Kn=new TextEncoder;function ta(t){return Vn(t,new Set)}function na(t,e){let n=fe(t,e);if(n===null)throw new TypeError("The operation is not a canonical mutation.");let i=Kn.encode(n),o=Kn.encode(ta(e)),r=Kn.encode(ea),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,Zs,!1),c+=4,c=Zi(s,a,c,i),a.setUint32(c,Qi(t,e),!1),c+=4,Zi(s,a,c,o),s}async function eo(t,e){let n=new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",na(t,e).buffer));return ia(n)}function Vn(t,e){if(t===null)return"null";if(t===!0)return"true";if(t===!1)return"false";if(typeof t=="string")return Xi(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(Vn(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)Xi(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)}:${Vn(r,e)}`}).join(",")}}`}finally{e.delete(t)}}function Xi(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 Zi(t,e,n,i){return e.setBigUint64(n,BigInt(i.length),!1),n+=8,t.set(i,n),n+i.length}function ia(t){return btoa(String.fromCharCode(...t)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}var Q=3,ra=2,to=[Q,ra],oe=5,Gn=4,no=[oe,Gn],sa=2,aa=1,hl={operation_transport:[...to],authorization_binding:[...no],semantic_capabilities:[sa,1],durable_mutation:[aa]};function Hn(t,e,n=[],i=2){let o={operation_transport:Q,authorization_binding:oe,semantic_capabilities:i},r=[...new Set(n)].filter(s=>s!==Q).sort((s,a)=>a-s);return r.length>0&&(o.operation_transport_recovery=r),(t.some(s=>he(s,{action:"mutate"}))||e?.actions.some(s=>s!=="list"&&s!=="read")===!0)&&(o.durable_mutation=1),o}function ct(t){return to.includes(t)}function io(t){return no.includes(t)}var ca=new TextEncoder().encode("mdbase-connect application installation id v2\0"),la=new TextEncoder().encode("mdbase-connect application authorization proof v4\0"),da=new TextEncoder().encode("mdbase-connect application authorization proof v5\0");async function ro(t){let e=zt(t),i=new Uint8Array(await crypto.subtle.digest("SHA-256",Re([ca,N(e)]))).slice(0,16);return i[6]=i[6]&15|128,i[8]=i[8]&63|128,[lt(i.slice(0,4)),lt(i.slice(4,6)),lt(i.slice(6,8)),lt(i.slice(8,10)),lt(i.slice(10,16))].join("-")}function so(t){let e=[zt(t.installation_signing_public_key),zt(t.grant_agreement_public_key),zt(t.grant_signing_public_key)];if(e.some((c,l)=>e.slice(l+1).some(u=>ya(c,u))))throw new Error("Application authorization keys must be distinct.");let n=$n(t.authorization_nonce),i=$n(t.code_challenge),o=t.contracts,r=o.operation_transport_recovery??[],s=t.requested_operations.some(c=>he(c,{action:"mutate"}))||t.requested_files?.actions.some(c=>!["list","read"].includes(c))===!0;if(!io(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||!ct(o.operation_transport)||t.protocol_version===oe&&o.operation_transport!==Q||r.some(c=>!ct(c)||c===o.operation_transport)||new Set(r).size!==r.length||t.protocol_version===Gn&&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.");pa(t.requested_files);let a=t.requested_operations.map(c=>N(new TextEncoder().encode(c)));return Re([t.protocol_version===oe?da:la,Z(t.protocol_version),N(Lt(t.application_id)),N(Lt(t.authorization_id)),N(new TextEncoder().encode(t.application_declaration_id)),N(ao(t.application_manifest_digest)),N(Lt(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)),oo(t.redirect_uri),oo(t.state),N(new TextEncoder().encode(t.code_challenge)),Z(o.operation_transport),...t.protocol_version===oe?[Z(r.length),...r.map(Z)]:[],Z(o.authorization_binding),Z(o.semantic_capabilities),ua(o.durable_mutation),Z(a.length),...a,fa(t.requested_files),ha(t.collection_id)])}function ua(t){return t===void 0?new Uint8Array(1):Re([new Uint8Array([1]),Z(t)])}function pa(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 fa(t){if(t===void 0)return new Uint8Array(1);let e=t.actions.map(n=>N(new TextEncoder().encode(n)));return Re([new Uint8Array([1]),Z(e.length),...e,N(new TextEncoder().encode(t.scope.kind)),...t.scope.kind==="selected_folders"?[Z(t.scope.folders.length),...t.scope.folders.map(n=>N(new TextEncoder().encode(n)))]:[]])}function oo(t){return t===void 0?new Uint8Array(1):Re([new Uint8Array([1]),N(new TextEncoder().encode(t))])}function ha(t){return t===void 0?new Uint8Array(1):Re([new Uint8Array([1]),N(Lt(t))])}function zt(t){let e=$n(t);if(e.byteLength!==65||e[0]!==4)throw new Error("Application authorization public key is invalid.");return e}function $n(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(ma(i)!==t)throw new Error("Non-canonical base64url value.");return i}function Lt(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 N(t){return Re([Z(t.byteLength),t])}function Z(t){let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t,!1),e}function Re(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 ma(t){return btoa(String.fromCharCode(...t)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}function ya(t,e){return t.byteLength===e.byteLength&&t.every((n,i)=>n===e[i])}function lt(t){return[...t].map(e=>e.toString(16).padStart(2,"0")).join("")}var co={id:"mdbase.record.created",version:"1.0.0",digest:"sha256:7f3bed6baa356ee9389e977ae7b77a102e2bee871a7c1d9f2026fc21cacdbfc9"};var lo={id:"mdbase.runtime.timer.fired",version:"1.0.0",digest:"sha256:41105be7a7abf33b31ced47e1e1965242236e40ccaea286b959b0a8c591f5642"};var uo=28485,dt="P256-HKDF-SHA256-AES256GCM",Ut=1;var ga="contract-setup-v1",ba="file-relay-v1",_a="protocol-usage-report-v1",va="policy-freshness-lease-v1",Ca=["application-authorization-v4","authorization-activation","encrypted-relay","policy-ack"];var wa=["durable-mutation-journal-v1","durable-file-lifecycle-v1","contract-metadata-read-v1"],Ra="candidate-b-activation-v1",wl=[...zn,...wa,"mutation-replay-after-credential-retirement-v1",Ra],Sa="application-declaration-evidence-v1",Rl=[...zn,Sa,...Ca,va,"application-authorization-v5",ga,ba,_a,Ni],Wn=1;var po="mdbase-authority-request-proof-v1",ut={version:"x-mdbase-proof-version",timestamp:"x-mdbase-proof-timestamp",nonce:"x-mdbase-proof-nonce",signature:"x-mdbase-proof-signature"};function Se(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 Pa=Object.entries({path:z,from:z,to:z,revision:z,previous_revision:z,types:Jn,previous_types:Jn,changed_fields:Jn,body_changed:Ta,before:Nt,after:Nt}),Oa=Object.entries({path:z,name:z,revision:z,previous_revision:z,reason:z}),Aa=Object.entries({previous_path:z,revision:z});function Yn(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(Bn,t.type)?Bn[t.type]:void 0;if(!i)return n("unrecognized_type");let o=t.payload;if(!Nt(o))return n("invalid_payload");if(i.startsWith("record.")){if(!Qn(o,Pa))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 z(o.from)&&z(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 z(o.path)?{...e,...c,kind:i,path:o.path}:n("invalid_payload")}if(i==="file.put")return ka(o.file)?{...e,kind:i,file:Se(o.file)}:n("invalid_payload");if(i==="file.removed"){if(!z(o.file_id)||!Qn(o,Aa))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(!Qn(o,Oa))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 z(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 fo(t){return{events:t.reset?[{kind:"reset",type:"reset",cursor:t.cursor,occurredAt:null,payload:{},raw:t}]:t.events.map(Yn),cursor:t.cursor,hasMore:t.has_more,reset:t.reset}}function ho(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 z(t){return typeof t=="string"}function Ta(t){return typeof t=="boolean"}function Jn(t){return Array.isArray(t)&&t.every(z)}function Nt(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Qn(t,e){return e.every(([n,i])=>t[n]==null||i(t[n]))}function ka(t){return Nt(t)&&z(t.file_id)&&z(t.path)&&z(t.revision)&&z(t.content_digest)&&t.content_digest.startsWith("sha256:")&&typeof t.size=="number"&&Number.isSafeInteger(t.size)&&t.size>=0&&["image","audio","video","pdf","other"].includes(t.media_class)&&z(t.modified_at)&&(t.media_type==null||z(t.media_type))}var w=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 R(t,e,...[n={}]){let i=Ce[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 mo(t,e,n={}){return Un(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(R(t,e,...n),{status:i?.status,cause:i?.cause})}function L(t,e,n={}){let{status:i,cause:o,...r}=n;return new w(Un(t,e,{details:r.details,operation_outcome:r.operationOutcome,trace_id:r.traceId}),{status:i,cause:o})}function Ee(t){let e=Ia(t.diagnostics),n=qa(t.diagnostics);if(e==="concurrent_modification"||e==="file_not_found"||e==="invalid_path")return R(e,n,{operationOutcome:"rejected"});if(e==="collection_version_unsupported"){let i=xa(t.diagnostics);return R(e,n,{operationOutcome:"rejected",details:i})}return e!=="operation_invalid"?R(e,n,{operationOutcome:"rejected",details:{diagnostics:t.diagnostics}}):R(e,n,{operationOutcome:"rejected",details:{diagnostics:t.diagnostics,partial_result:t.result}})}function Ia(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 xa(t){let e=t.map(n=>n.details).find(n=>Ea(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 Ea(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function yo(t){return t instanceof w&&t.retryable}function qa(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 Pe=["describe","changes","read","query"];function B(t){let e=t.capabilities===void 0?1:t.capabilities?.contract_version;return e!==1&&e!==2&&qe("Unsupported declared capability contract version."),e}function qe(t){throw d("invalid_application_manifest",t,{details:{issues:[{path:"/requirements/capabilities",keyword:"authorizationSelection",message:t,params:{}}]}})}function ee(t,e){if(e.operations!==void 0&&e.capabilities!==void 0&&qe("Specify operations or capabilities, not both."),e.operations!==void 0&&B(t)!==1&&qe("Exact operations authorization is only supported for legacy v1 declarations."),e.capabilities!==void 0){let n=new Set([...t.capabilities?.required??[],...t.capabilities?.optional??[]]);e.capabilities.some(i=>!n.has(i)||Y(B(t),i)===void 0)&&qe("Authorization can only include capabilities declared by the application.")}}function go(t){let e=t.capabilities;return e?[...new Set([...e.required,...e.optional??[]].flatMap(n=>Y(e.contract_version,n)??[]))]:[...Pe]}function Xn(t,e){let{requirements:n}=t;if(ee(n,e),B(n)===1){if(e.operations!==void 0)return[...new Set(e.operations)];if(e.capabilities===void 0)return[...Pe]}let i=n.capabilities,r=[...i?.required??[],...e.capabilities??i?.optional??[]].flatMap(a=>Y(B(n),a)??[]),s=(t.provisions?.type_packs.length??0)>0||(t.provisions?.configuration?.length??0)>0;return[...new Set([...r,...B(n)===2&&s?xt:[]])]}function jt(t,e){return[...t.capabilities?.required??[],...t.capabilities?.optional??[]].filter(n=>(Y(B(t),n)??[]).every(i=>e.includes(i)))}function Zn(t){let e=t.files;if(e)return B(t)===1?((!("actions"in e)||"required"in e||"optional"in e)&&qe("Legacy file declarations must use exact files.actions."),{actions:[...e.actions],scope:structuredClone(e.scope)}):("actions"in e&&qe("V2 file declarations must use required/optional file actions."),$i(e))}function Bt(t,e,n){let i=new Set(t.required),o=[...new Set([...t.required,...t.optional??[]])],r={};for(let s of o)r[s]=Fa(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 Fa(t,e,n,i,o){let r=Y(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 Fe=3e4,ei=1e4,Da=10*6e4,za=12e4,La=6e4;function De(t={}){return{requestMs:pt(t.requestMs,Fe,"requestMs"),watchStartMs:pt(t.watchStartMs,ei,"watchStartMs"),fileIndexMs:pt(t.fileIndexMs,Da,"fileIndexMs"),uploadMs:pt(t.uploadMs,za,"uploadMs"),syncMs:pt(t.syncMs,La,"syncMs")}}function ft(t,e){return{...t,signal:e.signal,...e.deadline===null?{}:{deadlineUnixMs:e.deadline}}}function re(t={},e=Fe,n=Date.now){let i=t.timeoutMs===void 0?e:t.timeoutMs,o=i===null?null:Ua(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=re(t,e),o,r=new Promise((a,c)=>{o=c}),s=()=>o?.($(i.signal));i.signal.addEventListener("abort",s,{once:!0});try{if(i.signal.aborted)throw $(i.signal);return await Promise.race([n(i),r])}finally{i.signal.removeEventListener("abort",s),i.dispose()}}async function G(t,e,n){let i=re(t,e);try{if(i.signal.aborted)throw $(i.signal);return await n(i)}finally{i.dispose()}}function $(t){return t.reason instanceof w?t.reason:d("operation_cancelled","The operation was cancelled before it changed the collection.",{operationOutcome:"not_sent",cause:t.reason})}function Ua(t){if(!Number.isSafeInteger(t)||t<=0)throw new TypeError("timeoutMs must be a positive safe integer or null.");return t}function pt(t,e,n){if(t===void 0)return e;if(t===null)return null;if(!Number.isSafeInteger(t)||t<=0)throw new TypeError(`${n} must be a positive safe integer or null.`);return t}async function ht(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 ti(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 ht("contracts",()=>F({...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 w))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 bo(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 _o(t,e,n,i){return{collectionId:e,info:n,capabilities:Bt(t.requirements.capabilities,t,n),...t.requirements?.capabilities?.contract_version===2?{readiness:ja(t,n)}:{},connections:i}}function Kt(t,e){return`mdbase-application-session:v1:${t.id}:${e}`}function ni(t){return JSON.stringify({capabilities:t.requirements?.capabilities,requirements:t.requirements?.configuration??[],provisions:t.provisions??{}})}function vo(t,e){return t.requirements?.access==="full_collection"&&e.scope.access==="full_collection"&&e.scope.contracts.length===0}function Co(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 wo(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 Na(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 ja(t,e){let n=t.requirements?.files,i=n&&"required"in n?n:void 0,o=!i||Na(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 Vt=["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"],Ro=Object.keys(Ce),Oe=["discovery_failed","invalid_operation_response","invalid_application_manifest","invalid_request","manifest_load_failed","rate_limited","temporarily_unavailable","timeout"],me=[...Oe,"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"],mt=[...Oe,"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"],ii=["connector_offline","connector_upgrade_required","invalid_operation_response","not_authorized","operation_failed","temporarily_unavailable","timeout"],id=[...me,"collection_not_ready","collection_not_selected","operation_cancelled","session_destroyed","session_not_started","session_starting","unknown_collection"],Ba=["collection_configuration_invalid","collection_invalid","collection_type_registry_invalid","collection_version_unsupported"],yt=[...Vt,...Ba],ae=[...yt,"file_not_found","invalid_path","operation_invalid"],gt=[...ae,"cursor_capacity_exhausted","generation_expired","invalid_read_cursor","query_snapshot_changed","sandbox_unsupported"],K=[...ae,"concurrent_modification","invalid_preflight","pending_mutation_unresolved"],Gt=[...yt,"change_cursor_reset"],ye=[...K,"type_pack_provision_failed"];function S(t,e=[]){return{ok:!0,value:t,diagnostics:e}}function g(t){return{ok:!1,problem:t}}async function q(t,e){try{return S(await t())}catch(n){if(!(n instanceof w))throw n;let i=n.problem;return i.code==="unknown"||e.includes(i.code)?g(i):g(mo(i.code,i.message,{details:i.details,operationOutcome:i.operation_outcome,traceId:i.trace_id}))}}function te(t){let e=new Uint8Array(t);return crypto.getRandomValues(e),ce(e)}var So=32768;function ce(t){let e="";for(let o=0;o<t.length;o+=So)e+=String.fromCharCode.apply(null,t.subarray(o,o+So));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 Ht(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 Ka="mdbase-connect-keys",ge="grant-keys",ri=18446744073709551615n,Va="mdbase-connect relay request key v1",Ga="mdbase-connect relay response key v1",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,ze=class{database=null;async create(e){let n=await To(e),i=await this.open();return await Ao(i,o=>o.add({...n,counter:"0"})),n}async get(e){let n=await this.open(),i=await Qa(n.transaction(ge).objectStore(ge).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(ge,"readwrite"),s=r.objectStore(ge),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>ri){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 Ao(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(Ka,1);i.onupgradeneeded=()=>{i.result.objectStoreNames.contains(ge)||i.result.createObjectStore(ge,{keyPath:"handle"})},i.onerror=()=>n(i.error),i.onsuccess=()=>e(i.result)})),this.database}},Le=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 To(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>ri)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 $t(t,e,n,i){let o=await Ha(t,e,n),r=i.timestamp??Math.floor(Date.now()/1e3),s=i.nonce??crypto.randomUUID(),a=await si({...i,timestamp:r,nonce:s}),c=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},o.signingPrivateKey,new TextEncoder().encode(a));return{[ut.version]:String(Wn),[ut.timestamp]:String(r),[ut.nonce]:s,[ut.signature]:ce(new Uint8Array(c))}}async function si(t){let e=t.method.toUpperCase(),n=await Oo(t.body??""),i=await Oo(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 le(t,e,n,i,o,r=crypto.randomUUID(),s){if(de(n.encryption),s!==void 0&&(!Number.isSafeInteger(s)||s<=0))throw new x("invalid_deadline","The operation deadline is invalid.");let a=await ko(t,e,n.encryption.application_agreement_public_key),c=await t.nextCounter(e),l={binding:n,protocolVersion:Q,requestId:r,operation:i,counter:c},u=await Mo(a.agreementPrivateKey,n,l.protocolVersion,"request"),f=new TextEncoder().encode(JSON.stringify(o??{})),p=await crypto.subtle.encrypt({name:"AES-GCM",iv:Eo(c),additionalData:new TextEncoder().encode(xo(l,"request")),tagLength:128},u,f);return{type:"encrypted_operation_request",...$a(l),...s===void 0?{}:{deadline_unix_ms:s},ciphertext:ce(new Uint8Array(p))}}async function Ue(t,e,n,i,o){if(!Wa(i,o))throw new x("invalid_encrypted_response","Encrypted response metadata does not match its request.");let r=await ko(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 Mo(r.agreementPrivateKey,n,i.protocol_version,"response");try{let c=await crypto.subtle.decrypt({name:"AES-GCM",iv:Eo(i.counter),additionalData:new TextEncoder().encode(xo(s,"response")),tagLength:128},a,qo(o.ciphertext)),l=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(c));if(l?.ok===!0&&"result"in l||l?.ok===!1&&at(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 To(t){let e=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"]),n=ce(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=ce(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 ko(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 Ha(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 Mo(t,e,n,i){let o=await bt(t,e.encryption.connector_agreement_public_key),r=await crypto.subtle.importKey("raw",o,"HKDF",!1,["deriveKey"]),s=new TextEncoder().encode(Io(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"?Va:Ga)},r,{name:"AES-GCM",length:256},!1,i==="request"?["encrypt"]:["decrypt"])}async function bt(t,e){try{let n=await crypto.subtle.importKey("raw",Ja(oi(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 Io(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 xo(t,e){return[Io(t.binding,t.protocolVersion),t.requestId,e,t.operation,t.counter].join("|")}function $a(t){let e=t.binding.encryption;return{protocol_version:t.protocolVersion,suite:dt,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 Wa(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 de(t){if(t.protocol_version!==Ut||t.suite!==dt||!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"||!Po.test(t.connector_id)||typeof t.collection_id!="string"||!Po.test(t.collection_id))throw new x("unsupported_encryption","The grant uses invalid encrypted relay identities.");oi(t.application_agreement_public_key),oi(t.connector_agreement_public_key)}function Eo(t){let e=BigInt(t);if(e<=0n||e>ri||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 Oo(t){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return ce(new Uint8Array(e))}function qo(t){if(!/^[A-Za-z0-9_-]+$/.test(t))throw new x("invalid_base64","Encrypted relay data is malformed.");return Ht(t)}function oi(t){let e=qo(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 Ja(t){return Uint8Array.from(t).buffer}function Qa(t){return new Promise((e,n)=>{t.onerror=()=>n(t.error),t.onsuccess=()=>e(t.result)})}function Ao(t,e){return new Promise((n,i)=>{let o=t.transaction(ge,"readwrite"),r=e(o.objectStore(ge));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 be(t){return{...t,credentials:"omit",targetAddressSpace:"loopback"}}async function _t(){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 Ne(t){let{status:e}=t;return e===404||e===405||e===426||e>=500?!0:e===403&&(await t.clone().text()).trim()===""}function Fo(t,e){return he(t,e)}function Do(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 vt(t){return[...new Set(t)]}function zo(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 Ae(t){if(t?.aborted)throw d("operation_cancelled","The operation was cancelled before it changed the collection.",{operationOutcome:"not_sent",cause:t.reason})}function Wt(t,e,n,i){return t instanceof w?t:e?.aborted?n?W(n,t):e.reason instanceof w?e.reason:d("operation_cancelled","The operation was cancelled before it changed the collection.",{operationOutcome:"not_sent",cause:t}):n?W(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 Lo(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 Uo(t,e,n,i,o){return fetch(t,{method:"POST",headers:{authorization:`Bearer ${e}`,"content-type":"application/json",...n},body:i,signal:o})}function ci(t,e){return e?.aborted===!0||t instanceof w&&t.code==="operation_cancelled"}function No(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 jo(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 Bo(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 Ko(t){return{affectedRecords:new Set((t.brokenLinks??[]).map(e=>e.path)).size,totalUnits:1,warnings:0}}async function Vo(t,e){return eo(t,e??{})}function Go(t){return JSON.stringify(ai(t))}function ai(t){return Array.isArray(t)?t.map(e=>ai(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,ai(n)])):t}function W(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 Jt(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 Ho(t,e,n){Wo(t,e,[...Jt(t,e),n])}function $o(t,e,n){Wo(t,e,Jt(t,e).filter(i=>i!==n))}function Wo(t,e,n){t.setItem(`${e}:connections`,JSON.stringify({version:1,collectionIds:[...new Set(n)]}))}function Jo(t,e){let n=t instanceof URL?t.href:t??Xa(),i=typeof n=="string"?n:n.distribution==="portable"?`bundle:${n.id}:${ec(n)}`:`bundle:${n.id}`,o=e===void 0?typeof n!="string"&&n.distribution==="portable"?"":Za():String(e);return{manifest:n,manifestSource:i,redirectUri:o}}async function ne(t,e,n,i){try{return await fetch(t,e)}catch(o){throw d(n,i,{cause:o})}}async function I(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 Qo(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 Ct(){let t=te(32),e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return{verifier:t,challenge:ce(new Uint8Array(e))}}function D(t,e,n,i){return L(wt(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 wt(t){return typeof t?.error=="string"?t.error:void 0}function Rt(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 Yo(t,e){return Rt({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 Qt(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&&Ya(o))}function Ya(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 Xo(t,e){if(!t||typeof t!="object"||Array.isArray(t)||t.collection_id!==e)return!1;try{return de(t),!0}catch{return!1}}function Zo(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 Yt(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 Xt(t){return t.access==="full_collection"&&t.contracts.length===0}function er(t){return t.endsWith("/")?t.slice(0,-1):t}function Xa(){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 Za(){if(typeof location>"u")throw d("redirect_uri_required","redirectUri is required outside a browser environment.");return location.href.split(/[?#]/)[0]}function li(){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 tr(t,e,n,i){if(typeof t!="string"&&t.distribution==="portable"||i)return li();let o=new URL(n);if(["http:","https:"].includes(o.protocol))return o.origin;if(typeof location<"u")return location.origin;if(typeof t!="string")return new URL(t.homepage).origin;try{return new URL(e).origin}catch{return""}}function nr(t){let e=":token:",n=t.lastIndexOf(e);return n<0?"":t.slice(n+e.length)}function Zt(){if(typeof location>"u")throw d("callback_url_required","callbackUrl is required outside a browser environment.");return location.href}function ir(t){if(t)return new je;if(typeof localStorage>"u")throw d("storage_required","storage is required outside a browser environment.");try{let e=`mdbase-connect:probe:${te(8)}`;return localStorage.setItem(e,"1"),localStorage.removeItem(e),localStorage}catch{return new je}}var je=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 or(t){return typeof t=="string"||t.distribution!=="portable"?!1:typeof location>"u"||location.origin==="null"||!["http:","https:"].includes(location.protocol)}function ec(t){let e=Go(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 rr(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(Ui))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 St(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 Be(t,e,n){return t.reason instanceof w?t.reason:d("authorization_cancelled",e,{cause:n})}function Pt(t){for(let e of["code","state","error","error_description"])t.searchParams.delete(e);return t}function en(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 tn(t){try{let e=new URL(t).searchParams.get("state");return e&&e.length>0?e:null}catch{return null}}function sr(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 Ke=class{constructor(e,n){this.connect=e;this.operations=vt(n.operations??Pe),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(R("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,ei,()=>e.promise)}catch(i){if(i instanceof w)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(R("session_destroyed","This session has been destroyed.")):(this.publishCurrent(),S(this.snapshot))}catch(i){if(i instanceof w){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(),S(o)):g(R("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(),S(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 S(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(R("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?B(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(R("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(It)}});ee(a,{...n,...e});let c="operations"in e?e.operations:e.capabilities.flatMap(p=>Y(B(a),p)??[]),l=o.connection.authorizationCapabilities(c);if(l.sufficient)return S({kind:"unchanged",connection:o.connection});let u="operations"in e||B(a)===1?{operations:vt([...l.grantedOperations,...c])}:{capabilities:[...new Set([...jt(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 w)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)):en(e)?this.completeAuthorizationCallback(e,n):Promise.resolve(g(R("invalid_callback","This URL is not an authorization callback.")))}completeAuthorizationCallback(e,n){if(n?.signal?.aborted){let r=$(n.signal);return Promise.resolve(g(r.problem))}let i=tn(e);if(!i)return Promise.resolve(g(R("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 w)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=sr(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 g(R("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,Fe,()=>e.promise)}catch(i){if(i instanceof w)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?R("session_destroyed","This session has been destroyed."):this.snapshot.status==="starting"?R("session_starting","The session is still starting."):this.snapshot.status==="start_failed"?this.snapshot.problem:this.started?null:R("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(R("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=tc(e);if(n!==this.snapshotKey){this.snapshot=e,this.snapshotKey=n;for(let i of this.listeners)i()}}};function tc(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 At=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)}},Ve=class{constructor(e,n,i=De()){this.connect=e;this.options=n;this.timeouts=i;this.verificationStore=n.verificationStore??rc()}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(R("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 w)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 w)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 ht("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(R("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(R("invalid_application_manifest","Application sessions require a versioned semantic capability contract.",{details:{issues:[{path:"/requirements/capabilities",keyword:"required",message:"is required for application sessions",params:{}}]}}),n);if(n!==this.lifecycleGeneration||e.signal?.aborted)return g(R("operation_cancelled","Application session startup was cancelled.",{operationOutcome:"not_sent"}));this.application=i.value,this.manifest=o.value;let s=new Ke(this.connect,{selection:this.options.selection,autoSelect:this.options.autoSelect,operations:nc(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(R("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(R("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()}),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),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):g(R("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?Zt():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):g(R("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)=>{ee(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(R("invalid_application_manifest","Applications may only request capabilities declared in their manifest.",{details:{issues:[{path:"/requirements/capabilities",keyword:"undeclaredCapability",message:"must declare every capability requested by the application",params:{requested:e,declared:[...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)=>{ee(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(R("collection_not_ready","There is no reviewed collection setup to apply."));if(!this.setupAssessment.applicable)return g(R("collection_not_ready","Resolve the collection setup conflicts before applying this update."));let i=this.connection();if(!i)return g(R("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(R("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"?g(a.problem):g(R("session_destroyed",Ot("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"||!vo(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=Kt(this.manifest,i.collectionId);r.readiness?.contracts.state!=="checking"&&this.verificationStore.read(a)===ni(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?ti({...e,readiness:e.readiness,contracts:a,connection:o,controller:c,options:i,requestMs:this.timeouts.requestMs,isCurrent:()=>n===this.verificationGeneration&&this.connection()===o,publish:_=>{l={..._,...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([ht("setup-assessment",()=>o.assessCollectionSetup(s,{...i,signal:c.signal})),u])}finally{i?.signal?.removeEventListener("abort",f),c.abort(),this.readinessController===c&&(this.readinessController=void 0)}let m=p;if(n===this.verificationGeneration){if(!m.ok){this.publish(m.problem.code==="application_declaration_mismatch"?{status:"authorization_required",...e}:{status:"blocked",problem:m.problem,...e});return}if(!m.value.applicable){let _=Co(m.value);if(Object.keys(_).length>0){if(m=i?await o.assessCollectionSetup(this.collectionSetupInput(_),i):await o.assessCollectionSetup(this.collectionSetupInput(_)),n!==this.verificationGeneration)return;if(!m.ok){this.publish(m.problem.code==="application_declaration_mismatch"?{status:"authorization_required",...e}:{status:"blocked",problem:m.problem,...e});return}this.setupTypePackAdoptions=_}}if(n===this.verificationGeneration){if(m.value.status!=="current"){this.setupAssessment=m.value,this.verificationStore.remove(Kt(r,e.collectionId)),this.publish({status:"setup_review_required",update:oc(m.value,r.provisions?.type_packs??[]),...e});return}if(this.verificationStore.write(Kt(r,e.collectionId),ni(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 ti({...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 wo(n,St(i.family_identity),`sha256:${i.manifest_digest}`,e)}context(e){return _o(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:bo(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(R("session_starting","The application session is still starting."));if(this.snapshot.status==="start_failed")return g(this.snapshot.problem);if(this.base)return S(this.base);let n=e==="destroyed"?"session_destroyed":"session_not_started";return g(R(n,Ot(n)))}async withLifecycleBase(e,n){let i=this.beginLifecycleOperation(e),o=re(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(R("session_destroyed",Ot("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 w)return this.lifecycleCurrent(i.generation)?g(s.problem):s.problem.code==="operation_outcome_unknown"?g(s.problem):g(R("session_destroyed",Ot("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(R("session_destroyed",Ot("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 nc(t,e){let n=(e.provisions?.type_packs.length??0)>0||(e.provisions?.configuration?.length??0)>0;return[...go(e.requirements),...t.contract_version===2&&n?xt:[]]}function ic(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 oc(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 ic(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 Ot(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 rc(){return typeof localStorage<"u"?{read:t=>localStorage.getItem(t),write:(t,e)=>localStorage.setItem(t,e),remove:t=>localStorage.removeItem(t)}:new At}function ie(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 sc="mdbase-connect-identities",Ge="application-identities",di=BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),ac=di/2n,He=class{database=null;async create(e){let n=await cr(e),i=await this.open();return await ar(i,o=>o.add(n)),n}async get(e){let n=await this.open();return await cc(n.transaction(Ge).objectStore(Ge).get(e))??null}async delete(e){let n=await this.open();await ar(n,i=>i.delete(e))}open(){if(typeof indexedDB>"u")throw new Te("Persistent application identity requires browser IndexedDB or an injected identity store.");return this.database||(this.database=new Promise((e,n)=>{let i=indexedDB.open(sc,1);i.onupgradeneeded=()=>{i.result.objectStoreNames.contains(Ge)||i.result.createObjectStore(Ge,{keyPath:"handle"})},i.onerror=()=>n(i.error),i.onsuccess=()=>e(i.result)})),this.database}},$e=class{records=new Map;async create(e){if(this.records.has(e))throw new Error(`Application identity already exists: ${e}`);let n=await cr(e);return this.records.set(e,n),n}async get(e){return this.records.get(e)??null}async delete(e){this.records.delete(e)}},Te=class extends Error{constructor(e){super(e),this.name="ApplicationIdentityStoreError"}};async function We(t){return ro(t.signingPublicKey)}async function Tt(t,e){if(t.installation_signing_public_key!==e.signingPublicKey||t.application_installation_id!==await We(e))throw new Error("Application authorization identity does not match its binding.");let n=dc(new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},e.signingPrivateKey,so(t))));return{binding:t,signature:lr(n)}}async function nn(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 cr(t){let e=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign","verify"]),n=lr(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 cc(t){return new Promise((e,n)=>{t.onerror=()=>n(t.error),t.onsuccess=()=>e(t.result)})}function ar(t,e){return new Promise((n,i)=>{let o=t.transaction(Ge,"readwrite");e(o.objectStore(Ge)).onerror=()=>i(o.error),o.onerror=()=>i(o.error),o.onabort=()=>i(o.error??new Error("Identity transaction aborted.")),o.oncomplete=()=>n()})}function lc(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 lr(t){return btoa(String.fromCharCode(...t)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}function dc(t){if(t.byteLength!==64)throw new Error("Application authorization signature is invalid.");let e=uc(t.slice(32));if(e===0n||e>=di)throw new Error("Application authorization signature is invalid.");return e<=ac?t:lc([t.slice(0,32),pc(di-e,32)])}function uc(t){return BigInt(`0x${fc(t)}`)}function pc(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 kt={id:"mdbase.person",version:"2.0.0"};function fr(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 ne(`${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 I(r,"invalid_operation_response","Connect returned invalid identity information.")})}var Je=class{constructor(e){this.context=e}context;current(e){return q(()=>this.readCurrent(e),Vt)}members(e){return q(()=>this.readMembers(e),Vt)}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 w&&a.code==="access_denied"))throw a}),this.readRecords(i)]);return{account:o,me:hc(s,o),people:s.people,invalid:s.invalid.map(({path:a,reason:c})=>({path:a,reason:c})),...r?{members:r}:{}}},gt)}async readCurrent(e){let n=await this.context.request("identity",e),i=pr(n),o=n.person_settings_url;if(o===void 0)return i;if(typeof o!="string"||!hr(o))throw on();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 on();return n.members.map(i=>{let o=pr(i);if(!i||typeof i!="object"||!("role"in i)||i.role!=="owner"&&i.role!=="editor"&&i.role!=="viewer")throw on();return{...o,role:i.role}})}async readRecords(e){let i=ur(await this.context.describe(e)).contracts.find(c=>c.id===kt.id&&c.version===kt.version),o=new Map;for(let c of i?.implementations??[])for await(let l of this.context.queryPages({contract:{...kt,type:c.typeName}},{signal:e.signal,pageSize:200}))for(let u of ur(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=>mc(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=>dr(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=>dr(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 hc(t,e){let n=t.invalid.filter(o=>o.claims.some(r=>rn(r,e)));if(n.length)return{status:"invalid",paths:n.map(o=>o.path)};let i=t.people.filter(o=>o.identities.some(r=>rn(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 rn(t,e){return t.issuer===e.issuer&&t.subject===e.subject}function mc(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 dr(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 ur(t){if(!t.ok)throw new w(t.problem);return t.value}function pr(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()||!hr(t.issuer))throw on();return{issuer:t.issuer,subject:t.subject,name:t.name}}function hr(t){try{let e=new URL(t);return e.protocol==="https:"||e.protocol==="http:"}catch{return!1}}function on(){return d("invalid_operation_response","Connect returned invalid identity information.")}var sn=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 q(()=>F(e,this.requestTimeoutMs,async()=>{if(!e.fresh&&this.description&&Date.now()<this.description.expiresAt)return S(this.description.value);if(!this.describing){this.description=void 0;let n=this.generation,i=q(()=>F({},this.requestTimeoutMs,o=>this.transport.operation("describe",{},{signal:o.signal,timeoutMs:this.requestTimeoutMs})),yt).then(o=>{if(!o.ok)return o;let r=yc(o.value);return this.generation===n&&(this.description={value:r,expiresAt:Date.now()+6e4}),S(r,o.diagnostics)}).finally(()=>{this.describing===i&&(this.describing=void 0)});this.describing=i}return this.describing}),yt).then(n=>n.ok?n.value:n)}};function yc(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}:{}}}function an(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 ln(t,e){return typeof t=="number"&&Number.isFinite(t)?Math.max(0,Math.floor(t)):e}function Qe(t,e){return typeof t=="number"&&Number.isFinite(t)&&t>=1?Math.floor(t):e}async function*mr(t,e,n={},i={}){let{offset:o,limit:r,cursor:s,pagination:a,snapshot:c,...l}=n,u=ln(o,0),f=Qe(i.firstPageSize??i.pageSize??r,200),p=Qe(i.pageSize??r,1e3),h=s,m=s!==void 0,_=cn(i.maxResults),v=an(e,i.signal,s),b=c,C=0,y=0;try{for(;!i.signal?.aborted&&C<_;){v.startRequest();let A=h,U={signal:i.signal,timeoutMs:i.pageTimeoutMs,coordination:{...i.coordination,coalesce:!1}},T=y===0&&s===void 0&&a===void 0&&c===void 0,k=await t({...l,...m?{}:{limit:Math.min(y===0?f:p,_-C)},...m?A?{cursor:A}:{pagination:"cursor"}:{offset:u,...b?{snapshot:b}:{},...!b&&a==="cursor"?{pagination:"cursor"}:{}},...!m&&!b&&T?{pagination:"cursor"}:{}},U);if(T&&!i.signal?.aborted&&!k.ok&&k.problem.code==="operation_invalid"&&(k=await t({...l,limit:Math.min(f,_-C),offset:u},U)),v.finishRequest(k.ok?k.value.meta?.cursor:void 0),i.signal?.aborted)return;if(!k.ok){v.dispose(),yield k;return}let P=k.value,O=P.meta?.cursor;if(O?(m=!0,h=O):m&&(h=void 0),m&&P.meta?.hasMore&&!O){v.dispose(),yield g(R("invalid_operation_response","The collection authority omitted the cursor required for the next query page."));return}let V=P.meta?.snapshot;if(!m&&b&&V&&b!==V){v.dispose(),yield g(R("query_snapshot_changed","The collection query snapshot changed while paging. Refresh the query before continuing."));return}!m&&!b&&V&&(b=V);let X=_-C,J=P.results.length>X?P.results.slice(0,X):P.results;C+=J.length;let st=C>=_||!P.meta?.hasMore||P.results.length===0,Fn={results:J,...P.meta?{meta:P.meta}:{},page:y,offset:u,loaded:C,complete:st,...O?{cursor:O}:{},...!m&&b?{snapshot:b}:{}};if(st&&v.dispose(),i.onProgress?.(Fn),yield S(Fn,k.diagnostics),st)return;u+=P.results.length,y+=1}}finally{v.dispose()}}async function gr(t,e,n,i){let o=yr(n.batchSize??100,1e3,"batchSize"),r=yr(n.concurrency??4,4,"concurrency");if(n.coordination?.latestWins)throw new TypeError("readMany batches cannot use latestWins coordination.");let s=[...e],a=[...new Set(s)],c=new Map,l=[],u=re(n,i),f=0,p=Math.ceil(a.length/o),h=[],m=async()=>{for(;!u.signal.aborted&&f<p;){let _=f++,v=a.slice(_*o,(_+1)*o),b=await t({where:`file.path in ${JSON.stringify(v)}`,...n.types?{types:n.types}:{},...n.includeBody===void 0?{}:{includeBody:n.includeBody},...n.frontmatterMode?{frontmatterMode:n.frontmatterMode}:{}},{pageSize:v.length,signal:u.signal,timeoutMs:null,coordination:n.coordination});if(!b.ok){l.push({batch:_,paths:v,failure:b});for(let y of v)c.set(y,{status:"error",path:y,batch:_});continue}h[_]=b.diagnostics;let C=new Map(b.value.results.map(y=>[y.path,y]));for(let y of v){let A=C.get(y);c.set(y,A?{status:"found",path:y,record:A}:{status:"missing",path:y})}}};try{if(await Promise.all(Array.from({length:Math.min(r,p)},m)),u.signal.aborted)throw $(u.signal);return S({results:s.map(_=>c.get(_)),errors:l.sort((_,v)=>_.batch-v.batch)},h.flat())}catch(_){if(_ instanceof w)return g(_.problem);throw _}finally{u.dispose()}}function yr(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*br(t,e,n,i={}){let{offset:o,limit:r,cursor:s,...a}=n,c=ln(o,0),l=Qe(i.firstPageSize??i.pageSize??r,200),u=Qe(i.pageSize??r,1e3),f=s,p=s!==void 0,h=cn(i.maxResults),m=an(e,i.signal,s),_=0,v=0;try{for(;!i.signal?.aborted&&_<h;){m.startRequest();let b=f,C=await t({...a,...p?{}:{limit:Math.min(v===0?l:u,h-_)},...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(R("invalid_operation_response","The collection authority omitted the cursor required for the next saved-view page."));return}let U=h-_,T=y.results.length>U?y.results.slice(0,U):y.results;_+=T.length;let k=_>=h||!y.meta.hasMore||y.results.length===0,P={...y,results:T,page:v,offset:c,loaded:_,complete:k,...A?{cursor:A}:{}};if(k&&m.dispose(),i.onProgress?.(P),yield S(P,C.diagnostics),k)return;c+=y.results.length,v+=1}}finally{m.dispose()}}function _r(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 Ye=class{constructor(e,n=Fe){this.transport=e;this.requestTimeoutMs=n;this.descriptions=new sn(e,n)}transport;requestTimeoutMs;descriptions;lastSchemaCursor=-1;get schemaGeneration(){return this.descriptions.schemaGeneration}operation(e,n,i){return q(()=>this.transport.operation(e,n,i),Ro)}describe(e){return this.descriptions.describe(e)}async changes(e={},n){let i=await this.rawOperation("changes",e,Gt,n),o=j(i,fo);if(o.ok){let r=o.value.events.filter(ho);(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",gc(e),ae,n);return j(i,dn)}readMany(e,n={}){return gr((i,o)=>this.queryAll(i,o),e,n,this.requestTimeoutMs)}async query(e={},n){let i=await this.envelopeOperation("query",bc(e),gt,n);return j(i,({results:o,meta:r})=>({results:o.map(Mr),...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*mr((i,o)=>this.query(i,o),i=>this.releaseQueryCursor(i),e,n)}async queryAll(e={},n={}){let i=re(n,this.requestTimeoutMs),o=[],r,s=[];try{for await(let a of this.queryPages(e,{firstPageSize:n.firstPageSize,pageSize:n.pageSize,maxResults:n.maxResults,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 $(i.signal);return S({results:o,...r?{meta:{...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}:{}}}:{}},s)}catch(a){if(a instanceof w)return g(a.problem);throw a}finally{i.dispose()}}async listViews(e){let n=await this.envelopeOperation("list_views",{},ae,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,ae,n);return j(i,Oc)}async*executeViewPages(e,n={}){yield*br((i,o)=>this.executeView(i,o),i=>this.releaseQueryCursor(i),e,n)}readViewSource(e,n){return this.envelopeOperation("read_view_source",e,ae,n)}createViewSource(e,n){return this.envelopeOperation("create_view_source",e,K,n)}updateViewSource(e,n){return this.envelopeOperation("update_view_source",ui(e),K,n)}deleteViewSource(e,n){return this.envelopeOperation("delete_view_source",ui(e),K,n)}async create(e,n){let i=await this.envelopeOperation("create",_c(e),K,n);return j(i,dn)}async update(e,n){let i=await this.envelopeOperation("update",vc(e),K,n);return j(i,dn)}async delete(e,n){let i=await this.envelopeOperation("delete",vr(e),K,n);return j(i,Ar)}async preflightDelete(e,n){let i=await this.envelopeOperation("delete",{...vr(e),check_backlinks:!0,dry_run:!0},K,n);return j(i,Rc)}async rename(e,n){let i=await this.envelopeOperation("rename",Cr(e),K,n);return j(i,Sc)}async preflightRename(e,n){let i=await this.envelopeOperation("rename",{...Cr(e),dry_run:!0},K,n);return j(i,Pc)}validate(e={},n){return this.envelopeOperation("validate",e,ae,n)}readType(e,n){return this.envelopeOperation("read_type",e,ye,n)}createType(e,n){return this.envelopeOperation("create_type",e,ye,n)}updateType(e,n){return this.envelopeOperation("update_type",ui(e),ye,n)}async assessTypePack(e,n){let i=await this.envelopeOperation("assess_type_pack",Pr(e),ye,n);return j(i,fi)}async applyTypePack(e,n){let i=await this.envelopeOperation("apply_type_pack",Cc(e),ye,n);return j(i,Tc)}async assessCollectionSetup(e,n){let i=await this.envelopeOperation("assess_collection_setup",Or(e),ye,n);return j(i,Sr)}async applyCollectionSetup(e,n){let i=await this.envelopeOperation("apply_collection_setup",wc(e),ye,n);return j(i,o=>({assessment:Sr(o.assessment),receipt:kc(o.receipt)}))}async listTimers(e,n){let i=await this.rawOperation("list_timers",{namespace:e},ae,n);return j(i,o=>({namespace:o.namespace,timers:o.timers.map(pi)}))}async putTimer(e,n){let i=await this.rawOperation("put_timer",{namespace:e.namespace,criterion_id:e.criterionId,timer:wr(e.timer)},K,n);return j(i,pi)}cancelTimer(e,n){return this.rawOperation("cancel_timer",e,K,n)}async reconcileTimers(e,n){let i=await this.rawOperation("reconcile_timers",{namespace:e.namespace,criterion_id:e.criterionId,timers:e.timers.map(wr)},K,n);return j(i,o=>({namespace:o.namespace,timers:o.timers.map(pi),cancelledIds:o.cancelled_ids}))}async*watch(e={}){let n=e.cursor,i=Math.max(100,e.pollIntervalMs??1e3),o=_r(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 ie(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=R("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 S(u);if(n=c.cursor,!c.hasMore)try{await ie(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},gt,{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?(["create_type","update_type","apply_type_pack","apply_collection_setup","create_view_source","update_view_source","delete_view_source"].includes(e)&&this.descriptions.invalidate(),S(s.result,s.diagnostics)):g(Ee(s))}};function j(t,e){return t.ok?S(e(t.value),t.diagnostics):t}function gc(t){return{path:t.path,...t.contract?{contract:t.contract}:{},...t.includeDocument===void 0?{}:{include_document:t.includeDocument}}}function bc(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 _c(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 vc(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 vr(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 Cr(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 ui(t){let{ifRevision:e,...n}=t;return{...n,...e?{if_revision:e}:{}}}function Pr(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(Tr)}:{}}}function Cc(t){return{...Pr(t),expected_assessment_digest:t.expectedAssessmentDigest,...t.allowDowngrade===void 0?{}:{allow_downgrade:t.allowDowngrade}}}function Or(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(Tr)}:{},...t.typePackAdoptions?{type_pack_adoptions:t.typePackAdoptions}:{}}}function wc(t){return{...Or(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 Ar(t){return{path:t.path,deleted:t.deleted,...t.broken_links?{brokenLinks:t.broken_links}:{}}}function Rc(t){return{...Ar(t),deleted:!1,dryRun:!0,wouldDelete:!0}}function Sc(t){let{references_updated:e,...n}=t;return{...dn(n),from:t.from,to:t.to,...e?{referencesUpdated:e}:{}}}function Pc(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 wr(t){return{id:t.id,fire_at:t.fireAt,...t.data===void 0?{}:{data:t.data}}}function pi(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 Tr(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 kr(t){return{id:t.id,version:t.version,digest:t.digest,type:t.type,implementationDigest:t.implementation_digest}}function Mr(t){let{effective_frontmatter:e,contract:n,...i}=t;return{...i,...e===void 0?{}:{effectiveFrontmatter:e},...n?{contract:kr(n)}:{}}}function dn(t){let{effective_frontmatter:e,contract:n,...i}=t;return{...i,effectiveFrontmatter:e,...n?{contract:kr(n)}:{}}}function Oc(t){return{results:t.results.map(e=>{let n=Mr(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 un(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 fi(t){return{status:t.status,applicable:t.applicable,assessmentDigest:t.assessment_digest,...t.current?{current:un(t.current)}:{},desired:un(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 Tc(t){return{...fi(t),receipt:un(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(fi),finalResourceRevisions:t.final_resource_revisions,assessmentDigest:t.assessment_digest}}function kc(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(un),cleanupDeferred:t.cleanup_deferred}}var pn=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 ne(`${this.context.serverUrl}/v1/notifications/vapid-public-key`,{signal:n},"notifications_unavailable","Push notifications are unavailable."),l=await I(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:Ht(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=E(this.context.storage.getItem(this.context.notificationKey())),h=e.installationId??p?.installationId??te(24),m=await ne(`${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."),_=await I(m,"invalid_operation_response","Connect returned an invalid notification registration response.");if(!m.ok)throw D(_,"notification_registration_failed","Could not register push notifications.",m.status);p?.channelId&&p.channelId!==_.channel_id&&fetch(`${this.context.serverUrl}/v1/notifications/channels/${p.channelId}`,{method:"DELETE",headers:{authorization:`Bearer ${i.accessToken}`},signal:n}).catch(()=>{});let v={channelId:_.channel_id,installationId:h,criteria:s};return this.context.storage.setItem(this.context.notificationKey(),JSON.stringify(v)),v}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??te(24),f=await ne(`${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 I(f,"invalid_operation_response","Connect returned an invalid native notification response.");if(!f.ok)throw D(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 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 ne(`${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 I(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 ne(`${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 I(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 Ir(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 xr(t,e,n){let i=n?.path;return e==="update"&&typeof i=="string"?Ir(t,i):void 0}async function Er(t,e,n){let i=await Ir(e,n);return t.find(o=>o.operation==="update"&&o.recordDigest===i)?.requestId??null}async function fn(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 qr(t,e,n,i,o,r,s,a=async c=>c){let c=t,l=await fn(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 fn(c,e,n,i,o,s)}let u=await I(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 Fr(t,e,n,i,o,r,s=async a=>a){let a=t,c=await fn(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 fn(a,"GET",e,void 0,i,r)}if(!c.ok){let u=await I(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 hn=class{constructor(e,n){this.namespace=e;this.onFinalRelease=n}namespace;onFinalRelease;leases=new Map;locks=Mc();retainAutomaticallyRetiredKeys=this.locks===null;async acquire(e,n,i){let o=this.acquireLocal(e,n);if(!this.locks)return o;try{let r=await Ic(this.locks,this.lockName(e,n),i);return hi(()=>{r(),o()})}catch(r){throw o(),r}}deleteExclusive(e,n,i){this.retainAutomaticallyRetiredKeys||(this.locks?this.locks.request(this.lockName(e,n),{mode:"exclusive"},i).catch(()=>{}):this.has(e,n)||Promise.resolve().then(i).catch(()=>{}))}has(e,n){return this.leases.get(e)?.has(n)??!1}handles(e){return this.leases.get(e)?.keys()??[]}acquireLocal(e,n){let i=this.leases.get(e)??new Map;return i.set(n,(i.get(n)??0)+1),this.leases.set(e,i),hi(()=>{let o=(i.get(n)??1)-1;o>0?i.set(n,o):(i.delete(n),i.size===0&&this.leases.delete(e),this.onFinalRelease(e,n))})}lockName(e,n){return`mdbase-connect:grant-key:${this.namespace}:${e}:${n}`}},_e=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 H(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 Mc(){let t=typeof navigator>"u"?void 0:navigator.locks;return t||(typeof window<"u"||typeof globalThis.importScripts=="function"?null:void 0)}async function Ic(t,e,n){let i,o,r,s=new Promise((l,u)=>{i=l,o=u}),a=new Promise(l=>{r=l});return t.request(e,{mode:"shared",...n?{signal:n}:{}},async()=>{i(),await a}).catch(o),await s,hi(r)}function hi(t){let e=!1;return()=>{e||(e=!0,t())}}var xc="mdbase-connect file chunk key v1",mn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,ue=class extends Error{constructor(n,i){super(i);this.code=n;this.name="FileTransferCryptoError"}code},Xe=class t{constructor(e,n){this.binding=e;this.key=n}binding;key;static async open(e,n,i){Dr(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 bt(o.agreementPrivateKey,i.encryption.connector_agreement_public_key);return t.fromSharedSecret(r,i)}static async fromSharedSecret(e,n){Dr(n);let i=await mi(e,n);return new t(n,i)}async encryptChunk(e,n,i){if(this.validateHeader(n),i.byteLength!==n.plaintext_length)throw new ue("plaintext_length_mismatch","File chunk plaintext length does not match its authenticated header.");let o=Ft(e,n),r=await crypto.subtle.encrypt({name:"AES-GCM",iv:zr(n.chunk_index),additionalData:yn(o),tagLength:128},this.key,yn(i));return Wi({kind:e,header:n,payload:new Uint8Array(r)})}async decryptChunk(e){let n=Dt(e);this.validateHeader(n.header);let i=Ft(n.kind,n.header);try{let o=await crypto.subtle.decrypt({name:"AES-GCM",iv:zr(n.header.chunk_index),additionalData:yn(i),tagLength:128},this.key,yn(n.payload));return new Uint8Array(o)}catch{throw new ue("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 ue("header_binding_mismatch","The file frame does not match its transfer encryption binding.")}};async function mi(t,e){let n=new TextEncoder().encode(Ec(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(xc)},o,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}function Dr(t){if(de(t.encryption),!mn.test(t.grantId)||!mn.test(t.applicationId)||!mn.test(t.authorityId)||!mn.test(t.transferId)||t.direction!=="upload"&&t.direction!=="download")throw new ue("invalid_binding","The file transfer encryption binding is invalid.")}function Ec(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 zr(t){if(!Number.isSafeInteger(t)||t<0)throw new ue("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 yn(t){return t.buffer instanceof ArrayBuffer?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Uint8Array.from(t)}var bn=8,yi=10;function _n(t){return t instanceof w&&t.code==="connector_busy"}async function Lr(t){if(!_n(t.error)||t.completedRetries>=bn)return{retried:!1};try{await vn(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 Ze(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 vn(t,e){return Nr(jr(50,800,t),e)}function Ur(t,e){return Nr(jr(100,1e3,t-1),e)}async function Nr(t,e){try{await ie(t,e)}catch(n){throw e?.aborted?e.reason instanceof w?e.reason:d("operation_cancelled","The operation was cancelled while waiting for connector capacity.",{operationOutcome:"not_sent",cause:n}):n}}function jr(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 wn=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){et(e);let l=Uc(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`,be({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 Ne(f)||await Ze(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&&n==="GET"&&(e=e.expiresAt>Date.now()+3e4?e:await this.options.refreshAuthorization(r),e=await this.retainEntryToken(e,c,r),Cn(e),u=await this.encryptControl(e,l)),f=await this.sendRelayControl(e,u,r),await Fc(f,e)&&(e=await this.options.refreshAuthorization(r),e=await this.retainEntryToken(e,c,r),Cn(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 I(a,"invalid_operation_response","The collection authority returned an invalid file control response.");if(!a.ok){let m=D(f,"operation_failed","Collection file request failed.",a.status);if(_n(m)&&l<bn)return await vn(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 p=f?.envelope;if(!p)throw d("invalid_encrypted_response","The connector omitted its encrypted file response.");let h=await Ue(this.options.keyStore,e.keyHandle,bi(e),s,p);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=Lc(h.problem);if(_n(m)&&l<bn)return await vn(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 gi(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 Br(this.options.keyStore,a,i,o,r),l;if(await this.options.shouldAttemptDirect(a)){try{l=await fetch(`${this.options.loopbackUrl}/v1/files/upload`,be(Kr(c,s)))}catch(u){if(s?.aborted)throw u;this.options.onDirectUnavailable()}if(l&&(!await Ne(l)||await Ze(l)))return l.ok&&this.options.onDirectAvailable(),qc(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),Cn(a),c=await Br(this.options.keyStore,a,i,o,r),l=await this.sendRelayUpload(a,c,s)),!l.ok){let u=await I(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),gi(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}`,be({method:"GET",signal:r}))}catch(a){if(r?.aborted)throw a;this.options.onDirectUnavailable()}if(s&&(!await Ne(s)||await Ze(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),Cn(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 I(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{zc(n,i,r),s=await(await Gr(this.options.keyStore,e,n)).decryptChunk(r)}catch(a){throw a instanceof w?a:d("invalid_operation_response","The connector returned an invalid encrypted file frame.",{cause:a})}if(s.byteLength!==_i(n,i))throw d("invalid_operation_response","The connector returned a truncated file chunk.");return s}encryptControl(e,n){return et(e),le(this.options.keyStore,e.keyHandle,bi(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`,{...Kr(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 gi(o,e,n),o}grantKeyLeases(e){return new _e(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 H(this.options.currentToken,n,i);if(o)return o;throw d("not_authorized","Reconnect this application to continue.")}};function gi(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.");Rn(e)}function Cn(t){if(t.authority||!t.fileCapability)throw d("not_authorized","This connection cannot use encrypted local file delivery.");et(t)}async function Br(t,e,n,i,o){let r=Dc(e,n,i,o.byteLength);return(await Gr(t,e,n)).encryptChunk("upload_chunk",r,o)}function Kr(t,e){return{method:"POST",headers:{"content-type":"application/mdbase-connect-file"},body:Uint8Array.from(t).buffer,signal:e}}async function qc(t,e){if(t.ok)return;let n=await I(t,"invalid_operation_response","The collection authority returned an invalid file transfer response.");throw D(n,"operation_failed",e,t.status)}async function Fc(t,e){return e.refreshToken?t.status===401?!0:t.status!==409?!1:(await I(t.clone(),"invalid_operation_response","The collection authority returned an invalid file response.").catch(()=>null))?.error?.code==="encryption_binding_stale":!1}function et(t){if(!t.encryption||!t.grantId||!t.keyHandle)throw d("missing_grant_key","Reconnect this application to restore encrypted file access.")}function bi(t){return et(t),{grantId:t.grantId,applicationId:t.clientId,encryption:t.encryption}}function Gr(t,e,n){return et(e),Xe.open(t,e.keyHandle,{...bi(e),authorityId:e.encryption.connector_id,transferId:n.transfer_id,direction:n.direction})}function Dc(t,e,n,i){et(t);let o=Rn(e),r=_i(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 zc(t,e,n){let i=Dt(n),o=_i(t,e),r=Rn(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 Lc(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 Uc(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 Vr("get_file_transfer_status",i[1]);if(t==="DELETE"&&i.length===2&&i[0]==="transfers")return Vr("abort_file_transfer",i[1]);if(t==="POST"&&Nc(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 Vr(t,e){return{protocol_version:1,type:t,transfer_id:decodeURIComponent(e)}}function Rn(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 _i(t,e){let n=Rn(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 Nc(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var Sn=class{constructor(e){this.options=e;this.local=new wn(e)}options;local;async control(e,n="",i,o){let r=await this.requireFileToken(o),s=r.token;try{return s.authority?await qr(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 Fr(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 _e(this.options.collectionId,this.options.acquireGrantKeyLease);try{await H(this.options.currentToken,n,e),await this.options.authorizedToken(e);let i=await H(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 H(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 ke(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 $t(t,e.keyHandle,e.authority.proofPublicKey,{method:n,target:`${s.pathname}${s.search}`,body:o,credential:r})}catch(s){throw s instanceof x?L(s.code,s.message):s}}async function Hr(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 ke(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 I(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),(wt(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 Pn=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($r(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=>$r(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??fe(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 $r(t){return!!(t&&typeof t.collectionId=="string"&&typeof t.requestId=="string"&&t.requestId.length>0&&Ji(t.operation)&&typeof t.inputFingerprint=="string"&&Number.isFinite(t.createdAt)&&t.createdAt>0&&(t.envelope||t.request)&&(t.operation==="sync"||fe(t.operation,t.request?.input??{})!==null))}function Wr({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=Yt(r.scope);if(!a)return s(r.keyHandle);if(!Xt(a))return s(r.keyHandle,"legacy_scope_reauthorization_required");if(r.fileCapability&&!Qt(r.fileCapability)||r.authority&&!Yo(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||!Xo(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 vi(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 ke(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 Jr(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 le(t,e.keyHandle,{grantId:e.grantId,applicationId:e.clientId,encryption:e.encryption},n,i,void 0,o)}catch(r){throw r instanceof x?L(r.code,r.message):r}}var tt=class{operations=new Map;run(e,n,i,o){if(n?.signal?.aborted)return Promise.reject($(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 Qr(t,e){return!t||t.authority||!t.encryption||!t.grantId||!t.keyHandle||e==="disabled"?!1:typeof location>"u"||!t.applicationOrigin||t.applicationOrigin===li()}async function Yr(t,e,n){let i;try{i=await fetch(`${t}/v1/ready`,be({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 I(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 Xr(t,e){try{return{body:await I(t,"invalid_operation_response","The collection authority returned a response that is not valid JSON.")}}catch(n){if(!t.ok&&e&&jc(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 jc(t){return t>=400&&t<500&&![408,425,429].includes(t)}var On=class{serverUrl;storage;keyStore;directAccessMode;loopbackUrl;collectionId;internals;onChange;timeouts;pendingMutationStore;files;refreshOperations=new tt;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 Pn(this.storage,this.internals.pendingMutationKey(this.collectionId)),this.files=new Sn({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)=>ke(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 _t();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?Er(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 G(n,this.timeouts.requestMs,o=>this.performOperationWithinBudget(i.operation,i.request?.input??{},ft(n??{},o),i))}async performOperation(e,n,i={}){return G(i,this.timeouts.requestMs,o=>this.performOperationWithinBudget(e,n,ft(i,o)))}async performOperationWithinBudget(e,n,i,o,r=!1,s=0,a=!1){Ae(i.signal);let c=this.grantKeyLeases();try{let l=await H(()=>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 H(()=>this.currentToken(),r,o.signal);if(!A)throw d("not_authorized","Reconnect this application to continue.");e=A}let f=s?.requestId??(Fo(n,i)?crypto.randomUUID():void 0),p;try{p=await this.sendOperation(e,n,i,u,r,o,f,l)}catch(y){throw Wt(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 I(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 H(()=>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 Wt(A,o.signal,f!==void 0&&this.storedPendingMutation(f)!==null?f:void 0,e.authority?"hosted_provider_unavailable":"relay_unavailable")}h=p.response}let _=y=>Lr({error:y,attempt:p,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)}),v;try{v=await Xr(h,e.authority!==void 0)}catch(y){throw p.pendingMutation?W(p.requestId,y):y}let b=v.body;if(!h.ok){let y=v.httpError??D(b,"operation_failed","Collection operation failed.",h.status),A=await _(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)?W(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,U=A?.encryption??e.encryption,T=A?.grantId??e.grantId,k=A?.applicationId??e.clientId,P=A?.keyHandle??e.keyHandle;if(!y||!U||!T||!P)throw p.pendingMutation?W(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 Ue(this.keyStore,P,{grantId:T,applicationId:k,encryption:U},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 V=Lo(O.problem);throw p.pendingMutation&&!V.outcomeUnknown&&this.clearPendingMutation(p.requestId),V}return p.pendingMutation&&this.clearPendingMutation(p.requestId),O.result}catch(O){throw O instanceof w?O:O instanceof x?p.pendingMutation?W(p.requestId,O):L(O.code,O.message):O}}let C=p.pendingMutationRecord?.request?.protocol_version??Q;if(b?.protocol_version!==C||b?.request_id!==p.requestId)throw p.pendingMutation?W(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(!at(b.problem))throw p.pendingMutation?W(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 w(b.problem),A=await _(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?W(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 G(s,this.timeouts.syncMs,async a=>{let c=this.grantKeyLeases();try{let l=await H(()=>this.currentToken(),c,a.signal);l&&await this.authorizedToken({signal:a.signal,timeoutMs:null}),l=await H(()=>this.currentToken(),c,a.signal),Zr(l,e,n);let u=await vi(this.keyStore,l,i,o,r,a.signal);u.status===401&&l.refreshToken&&(l=await this.refreshAuthorization({signal:a.signal,timeoutMs:null}),l=await H(()=>this.currentToken(),c,a.signal),Zr(l,e,n),u=await vi(this.keyStore,l,i,o,r,a.signal));let f=await I(u,"invalid_operation_response","The collection authority returned an invalid synchronization response.");if(!u.ok)throw D(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 Wt(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,_,v;if(a!==void 0){if(m=this.storedPendingMutation(a),_=m?.inputFingerprint??await Vo(n,i),m||(v=await xr(e.collectionId,n,i)),m){if(m.collectionId!==e.collectionId||m.operation!==n||m.inputFingerprint!==_)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??fe(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=Do(m.envelope,s.deadlineUnixMs)}else u=await le(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:_,...v?{recordDigest:v}:{},requestId:h,envelope:u,createdAt:Date.now()});else u=await le(this.keyStore,e.keyHandle,{grantId:e.grantId,applicationId:e.clientId,encryption:e.encryption},n,i,void 0,s.deadlineUnixMs)}catch(T){throw T instanceof x?L(T.code,T.message):T}h=u.request_id,l=u}else{let T=m?.request??{protocol_version:Q,request_id:h,input:l};l=T,f&&!m&&this.pendingMutationStore.store({collectionId:e.collectionId,...e.grantId?{grantId:e.grantId}:{},operation:n,mutation:b,inputFingerprint:_,...v?{recordDigest:v}:{},requestId:h,request:T,createdAt:Date.now()})}if(o&&u&&!e.authority){let T=!1;try{let O=await fetch(`${this.loopbackUrl}/v1/operations`,be({method:"POST",headers:{"content-type":"application/mdbase-connect+json"},body:JSON.stringify(u),signal:s.signal}));if(!await Ne(O)||await Ze(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};T=O.status>=500,this.markDirectUnavailable()}catch(O){if(s.signal?.aborted)throw f?W(h,O):O;T=!0,await _t()==="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 H(()=>this.currentToken(),r,s.signal);if(!O)throw d("not_authorized","Reconnect this application to continue.");k=O}catch(O){throw f&&(T||p)?W(h,O):O}let P;f||(u=await Jr(this.keyStore,k,n,i,s.deadlineUnixMs),h=u.request_id);try{P=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 f?W(h,O):O}return P.ok&&this.setRoute("relay"),{response:P,requestId:h,encryptedRequest:u,directDeliveryUncertain:T,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 ke(this.keyStore,e,"POST",C,y,e.authority.accessToken):{},U;try{U=await Uo(C,e.authority?.accessToken??e.accessToken,A,y,s.signal)}catch(T){throw f?W(h,T):T}return U.ok&&this.setRoute(e.authority?"remote":"relay"),{response:U,requestId:h,encryptedRequest:u,pendingMutation:f,...f?{pendingMutationRecord:m??this.storedPendingMutation(h)??void 0}:{},resumingMutation:p}}directCapable(e){return Qr(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 _t();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 Yr(this.loopbackUrl,Q,e))return this.markDirectAvailable(),"available"}catch(n){throw this.markDirectUnavailable(),n}return await _t()==="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||!zo(n,e)||(this.internals.removeToken(this.collectionId,n.keyHandle),this.currentRoute="relay",this.directStatus=this.directAccessMode==="disabled"?"disabled":"unavailable",this.emitConnection())}currentToken(){return Wr({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 H(()=>this.currentToken(),n,e);return await Hr({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 _e(this.collectionId,(e,n,i)=>this.internals.acquireGrantKeyLease(e,n,i))}};function Zr(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 Bc=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]),Kc=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Me=class{state=Kc.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 es(this.block,56,n),es(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],_=se(h,7)^se(h,18)^h>>>3,v=se(m,17)^se(m,19)^m>>>10;i[p]=i[p-16]+_+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=se(c,6)^se(c,11)^se(c,25),m=c&l^~c&u,_=f+h+m+Bc[p]+i[p]>>>0,v=se(o,2)^se(o,13)^se(o,22),b=o&r^o&s^r&s,C=v+b>>>0;f=u,u=l,l=c,c=a+_>>>0,a=s,s=r,r=o,o=_+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 se(t,e){return t>>>e|t<<32-e}function es(t,e,n){t[e]=n>>>24,t[e+1]=n>>>16,t[e+2]=n>>>8,t[e+3]=n}var An=class{constructor(e,n){this.signal=n;this.iterator=Vc(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(){ts(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(ns(n))};n.addEventListener("abort",a,{once:!0}),i=()=>n.removeEventListener("abort",a),n.aborted&&a()});try{let r=await Promise.race([e,o]);return ts(n),r}finally{i()}}closeIterator(){if(!this.iteratorClosing){this.iteratorClosing=!0;try{this.iterator.return?.()?.catch(()=>{})}catch{}}}};function Vc(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 ts(t){if(t?.aborted)throw ns(t)}function ns(t){return d("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:t?.reason})}var is=1024*1024,Gc=4,os=8,Mt=3,Ci=64*1024*1024,rs=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,ss=/^sha256:[0-9a-f]{64}$/u;async function as(t,e,n){let i=new Me;for(let o=0;o<t.size;o+=is){ve(e);let r=new Uint8Array(await t.slice(o,o+is).arrayBuffer());i.update(r),n(Math.min(t.size,o+r.byteLength))}return t.size===0&&n(0),i.digestHex()}function cs(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 ls(t){return t instanceof Blob?t.size:t.byteLength}async function ds(t){return t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t}function wi(t=Gc){if(!Number.isInteger(t)||t<1||t>os)throw d("invalid_request",`File concurrency must be between 1 and ${os}.`);return t}function us(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 Ri(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)||!Hc(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 Si(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+Pi(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 Hc(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 Pi(t,e,n){return Math.min(e,Math.max(0,t-n*e))}async function Tn(t,e){for(let n=1;n<=yi;n+=1){ve(e);try{return await t()}catch(i){if(e?.aborted||n===yi||i instanceof w&&!i.retryable)throw i;await Ur(n,e)}}throw new Error("Unreachable file chunk retry state.")}function Oi(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 Ai(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 ps(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 ve(t){if(t?.aborted)throw d("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:t.reason})}function Ie(t){return t instanceof w?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 nt=class{constructor(e,n,i,o,r=De()){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=re(e,this.timeouts.fileIndexMs),i=n.signal;try{this.requireAction("list");let o;do{ve(i);let r=new URLSearchParams({protocol_version:String(1),...e.folder?{folder:e.folder}:{},...o?{after:o}:{},...e.pageSize?{limit:String(us(e.pageSize))}:{}}),s;for(;;)try{s=await this.request("GET",`?${r.toString()}`,void 0,i);break}catch(a){let c=Ie(a);if(c.code!=="file_index_warming")throw c;e.onIndexing?.(),await ie(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)ve(i),yield Se(a);o=s.next}while(o)}finally{n.dispose()}}async upload(e,n,i={}){return G(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=cs(n,i.mediaType),r=wi(i.concurrency),s=await as(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 G(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(!ss.test(n.contentDigest))throw d("invalid_request","Streamed files require a lowercase SHA-256 content digest.");let o=new An(n.stream,i.signal),r=new Me;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(!rs.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(Ri(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 _=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/_),b=h.prepared_upload_part;if(b!==void 0){if(Oi(b,f,0,0,n,"PUT"),h.strategy.kind!=="object_put"||Ai(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&&(Si(C,h),C.state!=="open"&&C.state!=="committed"))throw d("invalid_operation_response",`The authority cannot resume a ${C.state} file transfer.`);if(u?.(_),!m&&C?.received.length===v){let P=await this.tryReplayUploadCommit(f,h.strategy.kind==="object_multipart"?C.uploaded_parts:void 0,r.signal);if(P)return p=!0,Se(P.file)}let y=new Set(C?.received??[]),A=new Map((C?.uploaded_parts??[]).map(P=>[P.part_number-1,P])),U=[...y].reduce((P,O)=>P+Pi(n,_,O),0),T=await ps(v,s,async P=>{let O=P*_,V=Math.min(_,Math.max(0,n-O)),X=await a(P,O,V);if(ls(X)!==V)throw d("invalid_request","Streamed file bytes ended before the declared size.");if(y.has(P))return A.get(P)??null;let J=m?await Tn(async()=>this.framed.uploadChunk(h,P,await ds(X),r.signal),r.signal).then(()=>null):await this.uploadPart(f,P,O,X,V,h.strategy.kind==="object_multipart",r.signal,b?{session:h,part:b}:void 0);return U+=V,r.onProgress?.({phase:"uploading",transferredBytes:U,totalBytes:n}),J});await c?.();let k=await this.commitUpload(f,h.strategy.kind==="object_multipart"?T.filter(P=>P!==null):void 0,r.signal);if(k.protocol_version!==1||k.type!=="file_upload_committed"||k.transfer_id!==f||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 p=!0,Se(k.file)}catch(h){throw Ie(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 G(n,this.timeouts.requestMs,i=>this.openDownloadStream(e,n,i.signal))}async openDownloadStream(e,n,i){this.requireAction("read");let o=wi(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),Ri(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(T){throw await this.abort(r),Ie(T)}let a=s.strategy.kind==="framed_chunks"?s.strategy.chunk_size:s.strategy.part_size,c=Math.ceil(e.size/a),l=new Me,u=0,f=0,p=null,h=0,m=!1,_=new AbortController,v=n.signal?AbortSignal.any([n.signal,_.signal]):_.signal,b=new Map,C=0,y=()=>{if(s.strategy.kind==="framed_chunks")for(;C<c&&b.size<o;){let T=C;C+=1;let k=Tn(()=>this.framed.downloadChunk(s,T,v),v).then(P=>({ok:!0,chunk:P}),P=>({ok:!1,error:P}));b.set(T,k)}},A=async()=>{m||(m=!0,_.abort(),await p?.cancel().catch(()=>{}),p=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 T=>{try{if(ve(v),s.strategy.kind==="object_ranges")for(;;){if(!p){if(u>=c){U(),T.close(),A();return}let st=u*a;f=Math.min(a,e.size-st),p=(await Tn(()=>this.hosted.downloadPart(s,u,f,v),v)).getReader()}let J=await p.read();if(J.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(!(J.value instanceof Uint8Array))throw d("invalid_operation_response","A hosted file range returned a non-byte chunk.");if(J.value.byteLength!==0){if(J.value.byteLength>f)throw d("invalid_operation_response","A hosted file range exceeded its declared byte length.");f-=J.value.byteLength,l.update(J.value),h+=J.value.byteLength,n.onProgress?.({phase:"downloading",transferredBytes:h,totalBytes:e.size}),T.enqueue(J.value);return}}if(u>=c){U(),T.close(),A();return}let k=u*a,P=Math.min(a,e.size-k);y();let O=b.get(u);if(!O)throw d("invalid_operation_response","A file chunk was not scheduled.");let V=await O;if(b.delete(u),!V.ok)throw V.error;let X=V.chunk;if(X.byteLength!==P)throw d("invalid_operation_response","A file chunk had the wrong byte length.");l.update(X),h+=X.byteLength,u+=1,y(),n.onProgress?.({phase:"downloading",transferredBytes:h,totalBytes:e.size}),u===c&&U(),T.enqueue(X),u===c&&(T.close(),A())}catch(k){let P=n.signal?.aborted?d("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:n.signal.reason}):k;await A(),T.error(Ie(P))}},cancel:A})}async downloadBytes(e,n={}){if(e.size>Ci)throw d("invalid_request",`download() buffers at most ${Ci} 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 G(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 Ie(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 Se(r.file)}async delete(e,n={}){return G(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 Ie(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<=Mt;l+=1){ve(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(Si(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);Oi(f,e,n,i,r,"PUT");let p=Ai(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 _=h.headers.get("etag");if(s&&!_)throw new Error("Multipart object upload did not return an ETag.");return{part_number:n+1,etag:_??""}}catch(u){if(a?.aborted||l===Mt)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 w&&o.code==="file_upload_incomplete")return null;throw o}}async commitUpload(e,n,i){let o;for(let r=1;r<=Mt;r+=1){ve(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 w||r===Mt)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 it=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 S(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(),S(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))xe(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(ki());if(this.remote)return g(Ti());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 g(Ti());if(this.deleted)return g(ki());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=$c(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 g(R("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?g(ki()):this.remote?g(Ti()):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&&xe(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])=>!xe(a[l],s[l])&&!xe(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))xe(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 Ti(){return R("concurrent_modification","This record changed elsewhere. Local changes are kept until the conflict is resolved.")}function ki(){return R("file_not_found","This record no longer exists. Local changes are kept.")}function $c(t){return t.code==="operation_outcome_unknown"?t.details.request_id:void 0}function xe(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)=>xe(i,e[o]));let n=Object.keys(t);return n.length===Object.keys(e).length&&n.every(i=>i in e&&xe(t[i],e[i]))}var Wc=4,Jc=4,ot=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 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){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<Wc&&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<Jc?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 S(s);let a={path:r.value.path,leases:0};a.session=new it(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):g(R("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 Qc=4,fs=32,kn=class{constructor(e,n,i={}){this.transport=e;this.requestTimeoutMs=n;this.foregroundCapacity=Mi(i.foregroundCapacity,Qc),this.foregroundQueueCapacity=Mi(i.foregroundQueueCapacity,fs),this.mutationQueueCapacity=Mi(i.mutationQueueCapacity,fs)}transport;requestTimeoutMs;foregroundCapacity;foregroundQueueCapacity;mutationQueueCapacity;foregroundQueue=[];mutationQueue=[];identicalReads=new Map;latestFamilies=new Map;activeForeground=0;mutationActive=!1;operation(e,n,i={}){let o=!he(e,n),r=Yc(i.coordination,o),s=o&&r.coalesce!==!1&&!r.latestWins&&i.signal===void 0?Xc(e,n,i.timeoutMs):void 0;if(s){let c=this.identicalReads.get(s);if(c)return c}let a=G(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=Zc(s.signal,a?.signal),{coordination:l,...u}=i,f=ft({...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((_,v)=>{let b={budget:s,run:p,resolve:A=>_(A),reject:v,started:!1,settled:!1},C=()=>{b.started||b.settled||(b.settled=!0,h.splice(h.indexOf(b),1),b.reject($(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 $(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=hs(this.foregroundQueue);if(!e)break;this.activeForeground+=1,this.start(e,()=>{this.activeForeground-=1,this.pump()})}if(!this.mutationActive){let e=hs(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 hs(t){for(;t.length>0;){let e=t.shift();if(!e.settled)return e}}function Yc(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 Xc(t,e,n){return`${t}:${n===void 0?"default":String(n)}:${Ii(e)}`}function Ii(t){return t===null||typeof t!="object"?JSON.stringify(t)??String(t):Array.isArray(t)?`[${t.map(Ii).join(",")}]`:`{${Object.entries(t).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>`${JSON.stringify(e)}:${Ii(n)}`).join(",")}}`}function Zc(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 rt=class{constructor(e,n){this.internals=e;this.collectionId=n;this.transport=new On({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 Je({request:(i,o)=>fr(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 nt(()=>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 ot(this,i=>this.transport.pendingUpdate(i)),this.collectionClient=new Ye(new kn({operation:(i,o,r)=>this.transport.performOperation(i,o,r)},e.timeouts.requestMs),e.timeouts.requestMs),this.readMany=this.collectionClient.readMany.bind(this.collectionClient),this.notifications=new pn({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;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}register(e){return q(()=>this.internals.register(e),Oe)}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=Pe){let n=this.operations,i=vt(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}}),me)}async requestCapabilities(e,n={}){return q(async()=>{let i=await this.internals.register(n);if(ee(i.requirements,{...n,capabilities:e}),this.info()!==null&&e.every(s=>(Y(B(i.requirements),s)??[]).every(a=>this.operations.includes(a))))return{kind:"unchanged",connection:this};if(B(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=>Y(1,c)??[])])]})}let r=jt(i.requirements,this.operations);return this.internals.authorize({...n,target:{kind:"collection",collectionId:this.collectionId},capabilities:[...new Set([...r,...e])]})},me)}async requestOperations(e,n={}){return q(async()=>{let i=await this.internals.register(n);ee(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])]})},me)}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),ii)}requestDirectAccess(e){return q(()=>this.transport.requestDirectAccess(e),ii)}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"},Mn(r,this.internals.timeouts.syncMs)),snapshot:(r,s,a)=>this.transport.performOperation("sync",{action:"snapshot",snapshot_id:r,...s?{page:s}:{}},Mn(a,this.internals.timeouts.syncMs)),changes:(r,s=200,a)=>this.transport.performOperation("sync",{action:"changes",after:r,limit:s},Mn(a,this.internals.timeouts.syncMs)),mutate:(r,s)=>this.transport.performOperation("sync",{action:"mutate",mutation:r},Mn(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),mt)}registerNativeNotifications(e){return q(()=>this.notifications.registerNativeNotifications(e),mt)}unregisterNativeNotifications(e){return q(()=>this.notifications.unregisterNativeNotifications(e),mt)}unregisterNotifications(e,n){return q(()=>this.notifications.unregisterNotifications(e,n),mt)}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}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 G(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{Ae(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{No(e,l)}catch(p){if(p instanceof w)return g(p.problem);throw p}s=Bo(e,l),a("ready",!0),Ae(i.signal);let u=this.transport.hasResumableMutationTransport();a("applying",u);let f=await this.rename(e,u?{signal:i.signal,timeoutMs:null}:{timeoutMs:ms(i.remainingMs())});return f.ok&&a("completed",!1,s.totalUnits),f}catch(c){if(ci(c,i.signal)&&a("cancelled",!1),c instanceof w)return g(c.problem);throw c}})}async deleteWithProgress(e,n={}){return G(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{Ae(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{jo(e,l)}catch(p){if(p instanceof w)return g(p.problem);throw p}s=Ko(l),a("ready",!0),Ae(i.signal);let u=this.transport.hasResumableMutationTransport();a("applying",u);let f=await this.delete(e,u?{signal:i.signal,timeoutMs:null}:{timeoutMs:ms(i.remainingMs())});return f.ok&&a("completed",!1,s.totalUnits),f}catch(c){if(ci(c,i.signal)&&a("cancelled",!1),c instanceof w)return g(c.problem);throw c}})}pendingMutations(){return this.transport.pendingMutations().map(e=>({...e,recover:n=>q(()=>this.recoverPendingMutation(e.requestId,n),K)}))}pendingMutation(e){let n=this.transport.pendingMutation(e);return n?{...n,recover:i=>q(()=>this.recoverPendingMutation(e,i),K)}: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 w(Ee(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 w(o.problem);if(o.value.reset)throw new w(R("change_cursor_reset","The collection change cursor expired. Refresh collection state before subscribing again."));return new xi(this.collectionClient,o.value.cursor,e,e.cursor===void 0?[]:o.value.events,this.internals.timeouts.watchStartMs)}),Gt)}emitConnection(){let e=this.info();for(let n of this.connectionListeners)n(e)}},xi=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 Mn(t,e){return{...t,timeoutMs:t?.timeoutMs===void 0?e:t.timeoutMs}}function ms(t){return t===null?null:Math.max(1,Math.ceil(t))}async function bs(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 _s(t){let e=Cs(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 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 ie(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 vs(t){return t.completion.then(e=>(t.popupAttempt&&ys(t,{version:1,status:"connected",collectionId:e.connection.collectionId,...e.returnTo?{returnTo:e.returnTo}:{}}),t.popupAttempt&&gs(),e)).catch(e=>{throw t.popupAttempt&&ys(t,{version:1,status:"failed",code:e instanceof w?e.code:"invalid_callback",message:e instanceof Error?e.message:"Authorization could not be completed.",...t.pending?.returnTo?{returnTo:t.pending.returnTo}:{}}),t.popupAttempt&&gs(),e})}function ys(t,e){t.storage.setItem(Cs(t.storagePrefix,t.state),JSON.stringify(e))}function Cs(t,e){return`${t}:completion:${e}`}function gs(){typeof window<"u"&&typeof window.close=="function"&&window.close()}function Ei(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!==Q&&ct(l)&&r.add(l)}return[...r].sort((s,a)=>a-s)}function qi(t,e,n){return Fi(t,e).has(n)}function Fi(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 ws(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=Yt(t.scope);if(!c)throw d("invalid_token_response","Authorization returned no valid collection scope.");if(!Xt(c))throw d("legacy_scope_reauthorization_required","Authorization returned a legacy contract-scoped grant. Reauthorize for the entire collection.");if(t.authority&&!Rt(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&&!Qt(t.file_capability))throw d("invalid_token_response","Authorization returned an invalid file capability.");if(t.encryption){try{de(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 Di(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=Di(n);for(let u of Fi(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)||qi(t,e,u)?s:a).push(u);return{retained:s,disposable:a}}function el(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 Ps(t,e,n,i,o){E(t.getItem(i))?.keyHandle===o||qi(t,n,o)||(await e.delete(o),el(t,i,o))}var In=class{serverUrl;manifest;manifestSource;redirectUri;storage;relayEncryption;keyStore;identityStore;directAccessMode;loopbackUrl;navigate;timeouts;credentialStorage;application=null;manifestPromise=null;completionPromises=new tt;grantKeyLeases;connectionCache=new Map;listeners=new Set;invalidatedConnections=new Map;constructor(e){this.serverUrl=er(String(e.serverUrl));let n=Jo(e.manifest,e.redirectUri);this.manifest=n.manifest,this.manifestSource=n.manifestSource;let i=or(this.manifest);this.redirectUri=n.redirectUri,this.storage=e.storage??ir(i),this.relayEncryption=e.relayEncryption??"required",this.keyStore=e.keyStore??(i?new Le:new ze),this.identityStore=e.identityStore??(i?new $e:new He),this.credentialStorage=e.storage||e.keyStore||e.identityStore?"custom":this.storage instanceof je?"memory":"persistent",this.directAccessMode=e.directAccess??"auto",this.loopbackUrl=Qo(String(e.loopbackUrl??`http://127.0.0.1:${uo}`)),this.navigate=e.navigate,this.timeouts=De(e.timeouts),this.grantKeyLeases=new hn(this.storagePrefix(),(o,r)=>this.deleteGrantKeyWhenUnused(o,r)),typeof window<"u"&&this.storage===window.localStorage&&window.addEventListener("storage",o=>{o.storageArea!==this.storage||!o.key?.startsWith(this.storagePrefix())||(this.connectionCache.get(nr(o.key))?.notifyStorageChanged(),this.emitConnections())})}environment(){return{distribution:typeof this.manifest!="string"&&this.manifest.distribution==="portable"?"portable":this.application?.distribution??"web",applicationOrigin:this.defaultApplicationOrigin(),credentialStorage:this.credentialStorage}}register(e={}){return F(e,this.timeouts.requestMs,n=>this.registerWithinBudget(n.signal))}async registerWithinBudget(e){if(this.application)return this.application;let n=await ne(`${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 I(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 I(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 bs({options:e,portableDeclared:n,navigate:this.navigate,register:r=>this.registerWithinBudget(r)});try{ee(i.requirements,e),i.requirements.capabilities?.contract_version===2&&await rr(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 Ct(),s=te(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=Xn(e,n),h=Zn(e.requirements),m=new Date,_=await Tt({protocol_version:oe,authorization_id:a,application_id:e.id,application_declaration_id:St(e.family_identity),application_manifest_digest:e.manifest_digest,application_installation_id:await We(f),installation_signing_public_key:f.signingPublicKey,grant_agreement_public_key:u.agreementPublicKey,grant_signing_public_key:u.signingPublicKey,flow:"authorization_code",authorization_nonce:te(32),issued_at:m.toISOString(),expires_at:new Date(m.getTime()+600*1e3).toISOString(),redirect_uri:this.redirectUri,state:s,code_challenge:r,contracts:Hn(p,h,Ei(this.storage,this.storagePrefix(),p,c),B(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(_)}),signal:n.signal}),C=await I(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 _s({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?Be(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 Ct(),s=`grant:${e.id}:${te(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=Xn(e,n),u=Zn(e.requirements),f=crypto.randomUUID(),p=new Date,h=await Tt({protocol_version:oe,authorization_id:f,application_id:e.id,application_declaration_id:St(e.family_identity),application_manifest_digest:e.manifest_digest,application_installation_id:await We(c),installation_signing_public_key:c.signingPublicKey,grant_agreement_public_key:a.agreementPublicKey,grant_signing_public_key:a.signingPublicKey,flow:"device_code",authorization_nonce:te(32),issued_at:p.toISOString(),expires_at:new Date(p.getTime()+600*1e3).toISOString(),code_challenge:r,contracts:Hn(l,u,Ei(this.storage,this.storagePrefix(),l,n.target?.kind==="collection"?n.target.collectionId:void 0),B(e.requirements)),requested_operations:l,...u?{requested_files:u}:{},...n.target?.kind==="collection"?{collection_id:n.target.collectionId}:{}},c),m,_;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}),_=await I(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(_,"device_authorization_failed","Downloaded application authorization could not be started.",m.status);let v;try{v=Zo(_)}catch(C){throw i?.close(),await this.keyStore.delete(s),n.signal?.aborted?Be(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 ie(b*1e3,n.signal),n.signal?.aborted)throw Be(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:_.device_code,client_id:e.id,code_verifier:o}),signal:n.signal})}catch(k){if(n.signal?.aborted)throw Be(n.signal,"Downloaded application authorization was cancelled.",k);continue}let y=await I(C,"invalid_token_response","The authorization service returned an invalid token response.");if(!C.ok){let k=wt(y);if(k==="authorization_pending")continue;if(k==="slow_down"){b+=5;continue}throw D(y,"token_exchange_failed","Downloaded application authorization could not be completed.",C.status)}let A=Rt(y.authority,y.collection_id),U=y.encryption&&y.encryption.protocol_version===Ut&&y.encryption.suite===dt&&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&&!U)throw d("encryption_required","Authorization did not establish the expected key-bound local portable grant.");let T=this.storeTokenResponse(y,e.id,s);if(n.target?.kind==="collection"&&n.target.collectionId!==T.collectionId)throw this.removeToken(T.collectionId,T.keyHandle),d("collection_mismatch","The approved collection does not match the collection requested by this link.");return i?.close(),{kind:"connected",connection:this.connection(T.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?Be(n.signal,"Downloaded application authorization was cancelled.",C):C}}completeAuthorization(e,n={}){let i=tn(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=>vs({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),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 ne(`${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 I(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 Jt(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 rt(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 w&&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 Ho(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 nn(this.identityStore,this.serverUrl,e)}catch(n){throw d("application_identity_unavailable",n instanceof Te?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=Di(r,n);this.storage.removeItem(this.tokenKey(e)),o&&ws(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));$o(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,()=>Ps(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 tr(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 xn=class{internals;constructor(e){this.internals=new In(e)}register(e){return q(()=>this.internals.register(e),Oe)}authorize(e={}){return q(()=>this.internals.authorize(e),me)}application(e){return new Ve(this,e,this.internals.timeouts)}manifest(e){return q(()=>this.internals.manifestDeclaration(e),Oe)}environment(){return this.internals.environment()}completeAuthorization(e,n){return q(()=>this.internals.completeAuthorization(e===void 0?Zt():String(e),n),me)}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 zi(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 Os(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 As(t,e){let n=zi(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 Ts(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 ks(t){return{subscribe:e=>t.subscribe(e),getSnapshot:()=>t.getSnapshot()}}var En=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=Pt(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=Pt(this.currentUrl());return`${e.pathname}${e.search}${e.hash}`}authorizationCallback(){let e=this.currentUrl().href;return en(e)?e:null}finishAuthorization(e,n){let i=this.safeAppUrl(e??this.fallbackPath);Pt(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,"",Pt(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}},qn=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 Fs(tl);})();
|
|
1
|
+
"use strict";var MdbaseConnect=(()=>{var Gn=Object.defineProperty;var $s=Object.getOwnPropertyDescriptor;var Js=Object.getOwnPropertyNames;var Ys=Object.prototype.hasOwnProperty;var Xs=(t,e)=>{for(var n in e)Gn(t,n,{get:e[n],enumerable:!0})},Zs=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Js(e))!Ys.call(t,o)&&o!==n&&Gn(t,o,{get:()=>e[o],enumerable:!(i=$s(e,o))||i.enumerable});return t};var ea=t=>Zs(Gn({},"__esModule",{value:!0}),t);var _l={};Xs(_l,{ApplicationIdentityStoreError:()=>De,FileTransferCryptoError:()=>ge,GrantFileTransferCipher:()=>ct,IndexedDbApplicationIdentityStore:()=>nt,IndexedDbGrantKeyStore:()=>He,MDBASE_RECORD_CREATED_CONTRACT:()=>To,MDBASE_TIMER_FIRED_CONTRACT:()=>Mo,MdbaseApplicationSession:()=>et,MdbaseBrowserSelection:()=>Qn,MdbaseCollectionClient:()=>at,MdbaseConnect:()=>Kn,MdbaseConnectError:()=>_,MdbaseConnection:()=>ft,MdbaseFileClient:()=>dt,MdbaseMemorySelection:()=>Vn,MdbaseMemoryVerificationStore:()=>Et,MdbasePeopleClient:()=>rt,MdbaseRecordSession:()=>ut,MdbaseRecords:()=>pt,MdbaseSession:()=>Ze,MemoryApplicationIdentityStore:()=>it,MemoryGrantKeyStore:()=>We,PERSON_CONTRACT:()=>Ft,RelayCryptoError:()=>q,applicationIdentity:()=>fn,applicationInstallationId:()=>ot,authorityProofMessage:()=>Ai,connectError:()=>d,connectFailure:()=>g,connectProblem:()=>w,connectSuccess:()=>R,createPkce:()=>At,decryptRelayResponse:()=>$e,deriveFileTransferKey:()=>Bi,deriveP256SharedSecret:()=>St,effectiveCapabilities:()=>Xt,encryptRelayRequest:()=>me,externalStore:()=>Ws,isRetryableConnectError:()=>Eo,linksTo:()=>Hs,normalizeCollectionChange:()=>bi,operationProblem:()=>je,operationsForApplicationCapabilities:()=>io,parseMdbaseNativeNotificationData:()=>Vs,parseMdbasePushPayload:()=>no,sameIdentity:()=>mn,showMdbasePushNotification:()=>Gs,signApplicationAuthorization:()=>qt,signAuthorityRequest:()=>on,validateGrantEncryption:()=>ye});var zt={"collection.read":["describe","changes","read","query","list_views","execute_view","read_view_source","validate","read_type"],"records.create":["create"],"records.edit":["update","rename"],"records.delete":["delete"],"views.manage":["create_view_source","update_view_source","delete_view_source"],"definitions.manage":["create_type","update_type","assess_type_pack","apply_type_pack"],"background.schedule":["list_timers","put_timer","cancel_timer","reconcile_timers"],"offline.replica":["sync"]},Lt=["assess_collection_setup","apply_collection_setup"];function io(t,e={}){let n=e.includeOptional===!1?t.required:[...t.required,...t.optional??[]];return[...new Set(n.flatMap(i=>zt[i]))]}var ta=Object.freeze({"collection.inspect":Object.freeze(["describe"]),"records.watch":Object.freeze(["changes"]),"records.read":Object.freeze(["read"]),"records.query":Object.freeze(["query"]),"records.validate":Object.freeze(["validate"]),"records.create":Object.freeze(["create"]),"records.update":Object.freeze(["update"]),"records.delete":Object.freeze(["delete"]),"records.rename":Object.freeze(["rename"]),"views.list":Object.freeze(["list_views"]),"views.execute":Object.freeze(["execute_view"]),"views.source.read":Object.freeze(["read_view_source"]),"views.source.create":Object.freeze(["create_view_source"]),"views.source.update":Object.freeze(["update_view_source"]),"views.source.delete":Object.freeze(["delete_view_source"]),"definitions.contracts.current":Object.freeze([]),"definitions.read":Object.freeze(["read_type"]),"definitions.create":Object.freeze(["create_type"]),"definitions.update":Object.freeze(["update_type"]),"definitions.type-pack.inspect":Object.freeze(["assess_type_pack"]),"definitions.type-pack.apply":Object.freeze(["assess_type_pack","apply_type_pack"]),"collection.setup.apply":Object.freeze(["assess_collection_setup","apply_collection_setup"]),"timers.list":Object.freeze(["list_timers"]),"timers.put":Object.freeze(["put_timer"]),"timers.cancel":Object.freeze(["cancel_timer"]),"timers.reconcile":Object.freeze(["reconcile_timers"]),"sync.offline-replica":Object.freeze(["sync"]),"notifications.background-delivery":Object.freeze([]),"files.list":Object.freeze([]),"files.read":Object.freeze([]),"files.add":Object.freeze([]),"files.replace":Object.freeze([]),"files.move":Object.freeze([]),"files.delete":Object.freeze([])});function X(t,e){let n=t===1?ta:t===2?zt:void 0;if(!(!n||!Object.hasOwn(n,e)))return[...n[e]]}var Cl=Object.freeze([1,2]),oo="application-authorization-v2-issuance",Hn=Object.freeze(["application-authorization-v2-issuance"]);var ro="yaml-document-records-v1";var Me={access_denied:{category:"authorization",recovery:"reauthorize"},access_paused:{category:"availability",recovery:"resume_connector_access"},application_declaration_mismatch:{category:"authorization",recovery:"reauthorize"},application_identity_unavailable:{category:"compatibility",recovery:"upgrade_application"},approval_window_blocked:{category:"authorization",recovery:"reauthorize"},authority_authorization_changed:{category:"authorization",recovery:"reauthorize"},authorization_binding_incompatible:{category:"compatibility",recovery:"upgrade_application"},authorization_cancelled:{category:"cancellation",recovery:"none"},authorization_expired:{category:"authorization",recovery:"reauthorize"},authorization_replayed:{category:"integrity",recovery:"reauthorize"},browser_required:{category:"compatibility",recovery:"none"},callback_url_required:{category:"validation",recovery:"fix_request"},capability_contract_incompatible:{category:"compatibility",recovery:"upgrade_application"},change_cursor_reset:{category:"conflict",recovery:"refresh"},collection_access_denied:{category:"authorization",recovery:"reauthorize"},collection_configuration_invalid:{category:"validation",recovery:"repair_collection"},collection_contracts_missing:{category:"compatibility",recovery:"choose_collection"},collection_incompatible:{category:"compatibility",recovery:"choose_collection"},collection_invalid:{category:"validation",recovery:"repair_collection"},collection_kind_unsupported:{category:"compatibility",recovery:"choose_collection"},collection_mismatch:{category:"selection",recovery:"choose_collection"},collection_not_found:{category:"selection",recovery:"choose_collection"},collection_not_ready:{category:"selection",recovery:"choose_collection"},collection_not_selected:{category:"selection",recovery:"choose_collection"},collection_type_registry_invalid:{category:"validation",recovery:"repair_collection"},collection_version_unsupported:{category:"compatibility",recovery:"upgrade_collection"},concurrent_modification:{category:"conflict",recovery:"refresh"},connector_busy:{category:"availability",recovery:"retry"},connector_identity_changed:{category:"integrity",recovery:"reauthorize"},connector_offline:{category:"availability",recovery:"retry"},connector_upgrade_required:{category:"compatibility",recovery:"upgrade_connector"},cursor_capacity_exhausted:{category:"availability",recovery:"retry"},device_authorization_failed:{category:"authorization",recovery:"reauthorize"},direct_operation_rejected:{category:"authorization",recovery:"reauthorize"},discovery_failed:{category:"availability",recovery:"retry"},durable_mutation_unsupported:{category:"compatibility",recovery:"upgrade_connector"},encrypted_relay_rejected:{category:"authorization",recovery:"reauthorize"},encryption_required:{category:"authorization",recovery:"reauthorize"},expired_token:{category:"authorization",recovery:"reauthorize"},file_changed_during_move:{category:"conflict",recovery:"refresh"},file_changed_during_read:{category:"conflict",recovery:"refresh"},file_index_warming:{category:"availability",recovery:"retry"},file_list_changed:{category:"conflict",recovery:"refresh"},file_move_failed:{category:"internal",recovery:"contact_support"},file_mutation_conflict:{category:"conflict",recovery:"resolve_conflict"},file_not_found:{category:"conflict",recovery:"refresh"},file_source_mismatch:{category:"conflict",recovery:"refresh"},file_upload_incomplete:{category:"conflict",recovery:"retry"},fresh_request_required:{category:"availability",recovery:"retry"},generation_expired:{category:"conflict",recovery:"refresh"},hosted_provider_unavailable:{category:"availability",recovery:"retry"},insufficient_access:{category:"authorization",recovery:"reauthorize"},invalid_application_authorization:{category:"validation",recovery:"fix_request"},invalid_application_manifest:{category:"validation",recovery:"fix_request"},invalid_callback:{category:"validation",recovery:"fix_request"},invalid_device_authorization_response:{category:"integrity",recovery:"contact_support"},invalid_encrypted_response:{category:"integrity",recovery:"contact_support"},invalid_loopback_url:{category:"validation",recovery:"fix_request"},invalid_mutation_id:{category:"validation",recovery:"fix_request"},invalid_operation_response:{category:"integrity",recovery:"contact_support"},invalid_path:{category:"validation",recovery:"fix_request"},invalid_preflight:{category:"conflict",recovery:"refresh"},invalid_push_payload:{category:"validation",recovery:"fix_request"},invalid_push_subscription:{category:"validation",recovery:"fix_request"},invalid_read_cursor:{category:"validation",recovery:"fix_request"},invalid_request:{category:"validation",recovery:"fix_request"},invalid_token_response:{category:"integrity",recovery:"contact_support"},legacy_scope_reauthorization_required:{category:"authorization",recovery:"reauthorize"},managed_fcm_not_declared:{category:"compatibility",recovery:"fix_request"},manifest_load_failed:{category:"availability",recovery:"retry"},manifest_required:{category:"validation",recovery:"fix_request"},missing_grant_key:{category:"authorization",recovery:"reauthorize"},mutation_recovery_expired:{category:"compatibility",recovery:"none"},mutation_request_conflict:{category:"conflict",recovery:"resolve_conflict"},no_pending_mutation:{category:"conflict",recovery:"refresh"},not_authorized:{category:"authorization",recovery:"reauthorize"},not_remote_authority:{category:"compatibility",recovery:"choose_collection"},notification_criterion_not_declared:{category:"validation",recovery:"fix_request"},notification_reauthorization_required:{category:"authorization",recovery:"reauthorize"},notification_registration_failed:{category:"availability",recovery:"retry"},notification_unregistration_failed:{category:"availability",recovery:"retry"},notifications_not_declared:{category:"compatibility",recovery:"fix_request"},notifications_unavailable:{category:"availability",recovery:"retry"},operation_cancelled:{category:"cancellation",recovery:"none"},operation_failed:{category:"internal",recovery:"contact_support"},operation_invalid:{category:"validation",recovery:"fix_request"},operation_outcome_unknown:{category:"conflict",recovery:"resolve_outcome"},path_occupied:{category:"conflict",recovery:"resolve_conflict"},pending_mutation_unresolved:{category:"conflict",recovery:"resolve_outcome"},query_snapshot_changed:{category:"conflict",recovery:"refresh"},rate_limited:{category:"availability",recovery:"retry"},reconnect_required:{category:"authorization",recovery:"reauthorize"},redirect_uri_required:{category:"validation",recovery:"fix_request"},reference_updates_unsupported:{category:"compatibility",recovery:"fix_request"},registry_backup_invalid:{category:"integrity",recovery:"contact_support"},registry_busy:{category:"availability",recovery:"retry"},registry_corrupt:{category:"integrity",recovery:"repair_collection"},registry_migration_failed:{category:"internal",recovery:"contact_support"},registry_schema_incompatible:{category:"compatibility",recovery:"upgrade_connector"},relay_authorization_expired:{category:"authorization",recovery:"reauthorize"},relay_unavailable:{category:"availability",recovery:"retry"},sandbox_unsupported:{category:"compatibility",recovery:"fix_request"},scope_denied:{category:"authorization",recovery:"reauthorize"},session_destroyed:{category:"cancellation",recovery:"none"},session_not_started:{category:"validation",recovery:"fix_request"},session_starting:{category:"availability",recovery:"retry"},stale_file_revision:{category:"conflict",recovery:"refresh"},storage_required:{category:"compatibility",recovery:"none"},sync_failed:{category:"availability",recovery:"retry"},temporarily_unavailable:{category:"availability",recovery:"retry"},timeout:{category:"availability",recovery:"retry"},token_exchange_failed:{category:"availability",recovery:"retry"},transport_protocol_incompatible:{category:"compatibility",recovery:"upgrade_connector"},type_pack_provision_failed:{category:"validation",recovery:"repair_collection"},unknown_collection:{category:"selection",recovery:"choose_collection"},unsafe_file_path:{category:"validation",recovery:"fix_request"},unsupported_encryption:{category:"compatibility",recovery:"upgrade_application"},unsupported_operation:{category:"compatibility",recovery:"fix_request"}},na={access_denied:{type:"object",required:[],properties:{return_to:{type:"string"}}},approval_window_blocked:{type:"object",required:["user_code","verification_uri","verification_uri_complete","expires_at","interval_seconds"],properties:{user_code:{type:"string"},verification_uri:{type:"string"},verification_uri_complete:{type:"string"},expires_at:{type:"integer"},interval_seconds:{type:"integer"}}},authorization_binding_incompatible:{type:"object",required:["contract","required","supported","peer"],properties:{contract:{type:"string"},required:{type:"array",items:{type:"integer"}},supported:{type:"array",items:{type:"integer"}},peer:{type:"string"},operation:{type:"string"}}},capability_contract_incompatible:{type:"object",required:["contract","required","supported","peer"],properties:{contract:{type:"string"},required:{type:"array",items:{type:"integer"}},supported:{type:"array",items:{type:"integer"}},peer:{type:"string"},operation:{type:"string"}}},collection_configuration_invalid:{type:"object",required:["diagnostics"],properties:{diagnostics:{type:"array",items:{type:"object"}}}},collection_contracts_missing:{type:"object",required:["contracts"],properties:{contracts:{type:"array",items:{type:"object",required:["id","version"],properties:{id:{type:"string"},version:{type:"string"}}}}}},collection_invalid:{type:"object",required:["diagnostics"],properties:{diagnostics:{type:"array",items:{type:"object"}}}},collection_type_registry_invalid:{type:"object",required:["diagnostics"],properties:{diagnostics:{type:"array",items:{type:"object"}}}},collection_version_unsupported:{type:"object",required:["current_version","required_version"],properties:{current_version:{type:"string"},required_version:{type:"string"}}},connector_offline:{type:"object",required:[],properties:{connector_name:{type:"string"}}},durable_mutation_unsupported:{type:"object",required:["contract","required","supported","peer"],properties:{contract:{type:"string"},required:{type:"array",items:{type:"integer"}},supported:{type:"array",items:{type:"integer"}},peer:{type:"string"},operation:{type:"string"}}},insufficient_access:{type:"object",required:["required_operations","granted_operations","missing_operations"],properties:{required_operations:{type:"array",items:{type:"string"}},granted_operations:{type:"array",items:{type:"string"}},missing_operations:{type:"array",items:{type:"string"}}}},invalid_application_manifest:{type:"object",required:["issues"],properties:{issues:{type:"array",items:{type:"object",required:["path","keyword","message","params"],properties:{path:{type:"string"},keyword:{type:"string"},message:{type:"string"},params:{type:"object"}}}}}},mutation_request_conflict:{type:"object",required:["request_id"],properties:{request_id:{type:"string"}}},operation_invalid:{type:"object",required:["diagnostics"],properties:{diagnostics:{type:"array",items:{type:"object"}},partial_result:{}}},operation_outcome_unknown:{type:"object",required:["request_id"],properties:{request_id:{type:"string"}}},rate_limited:{type:"object",required:[],properties:{retry_after_ms:{type:"integer"}}},transport_protocol_incompatible:{type:"object",required:["contract","required","supported","peer"],properties:{contract:{type:"string"},required:{type:"array",items:{type:"integer"}},supported:{type:"array",items:{type:"integer"}},peer:{type:"string"},operation:{type:"string"}}}};function so(t){return Object.hasOwn(Me,t)}function ht(t){if(!ao(t))return!1;let e=t;if(e.problem_version!==1||typeof e.message!="string"||e.message.length===0||e.operation_outcome!==void 0&&e.operation_outcome!=="not_sent"&&e.operation_outcome!=="rejected"&&e.operation_outcome!=="unknown"||e.trace_id!==void 0&&(typeof e.trace_id!="string"||e.trace_id.length===0))return!1;if(e.code==="unknown")return typeof e.server_code=="string"&&e.server_code.length>0&&e.category==="unknown"&&e.recovery==="none";if(typeof e.code!="string"||!so(e.code)||e.server_code!==void 0)return!1;let n=Me[e.code],i=na[e.code],o=i===void 0?e.details===void 0:e.details===void 0?(i.required?.length??0)===0:Wn(e.details,i);return e.category===n.category&&e.recovery===n.recovery&&o}function Wn(t,e){if(e.type===void 0)return!0;if(e.type==="string")return typeof t=="string";if(e.type==="integer")return typeof t=="number"&&Number.isInteger(t);if(e.type==="number")return typeof t=="number"&&Number.isFinite(t);if(e.type==="boolean")return typeof t=="boolean";if(e.type==="array")return Array.isArray(t)&&t.every(i=>Wn(i,e.items??{}));if(!ao(t))return!1;if(!e.properties)return!0;let n=t;return!Object.keys(n).every(i=>Object.hasOwn(e.properties,i))||!(e.required??[]).every(i=>Object.hasOwn(n,i))?!1:Object.entries(n).every(([i,o])=>Wn(o,e.properties[i]))}function ao(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function $n(t,e,n={}){if(so(t)){let i=Me[t],o={problem_version:1,code:t,category:i.category,recovery:i.recovery,message:e,...n.details===void 0?{}:{details:n.details},...n.operation_outcome===void 0?{}:{operation_outcome:n.operation_outcome},...n.trace_id===void 0?{}:{trace_id:n.trace_id}};if(ht(o))return o}return{problem_version:1,code:"unknown",server_code:t,category:"unknown",recovery:"none",message:e,...n.details===void 0?{}:{details:n.details},...n.operation_outcome===void 0?{}:{operation_outcome:n.operation_outcome},...n.trace_id===void 0?{}:{trace_id:n.trace_id}}}var co=new Uint8Array([77,68,66,70]),lo=1,uo=0,Ol=new Uint8Array([77,68,66,82]);var po=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function fo(t,e={}){return{actions:[...new Set([...t.required,...e.includeOptional===!1?[]:t.optional??[]])],scope:structuredClone(t.scope)}}var x=class extends Error{code;constructor(e,n){super(n),this.code=e,this.name="FileFrameError"}};function ia(t){return t==="upload_chunk"?1:2}function oa(t){if(t===1)return"upload_chunk";if(t===2)return"download_chunk";throw new x("invalid_kind",`Unknown file frame kind ${t}`)}function ra(t){if(!t||typeof t!="object"||Array.isArray(t))throw new x("invalid_header","File frame header must be a JSON object");return t}function Nt(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new x("invalid_header",`File frame header ${e} must be a non-empty string`);return n}function Ut(t,e){let n=Nt(t,e);if(!po.test(n))throw new x("invalid_header",`File frame header ${e} must be a UUID`);return n}function Ie(t,e,n=Number.MAX_SAFE_INTEGER){let i=t[e];if(!Number.isSafeInteger(i)||i<0||i>n)throw new x("invalid_header",`File frame header ${e} is outside its allowed range`);return i}function Jn(t){if(t.protocol_version!==1)throw new x("unsupported_version",`Unsupported file transfer protocol ${t.protocol_version}`);if(t.protection!=="grant_aead_v1"&&t.protection!=="transport_tls")throw new x("invalid_header","Unknown file transfer protection");if(t.direction!=="upload"&&t.direction!=="download")throw new x("invalid_header","Unknown file transfer direction");for(let[e,n]of[["grant_id",t.grant_id],["authority_id",t.authority_id],["collection_id",t.collection_id],["transfer_id",t.transfer_id]])if(!po.test(n))throw new x("invalid_header",`File frame header ${e} must be a UUID`);for(let[e,n,i]of[["chunk_size",t.chunk_size,4194304],["chunk_index",t.chunk_index,Number.MAX_SAFE_INTEGER],["offset",t.offset,Number.MAX_SAFE_INTEGER],["plaintext_length",t.plaintext_length,4194304],["total_size",t.total_size,Number.MAX_SAFE_INTEGER]])if(!Number.isSafeInteger(n)||n<0||n>i)throw new x("invalid_header",`File frame header ${e} is outside its allowed range`);if(t.chunk_size<64*1024)throw new x("invalid_header","File frame chunk_size is below the protocol minimum");if(!Number.isSafeInteger(t.scope_epoch)||t.scope_epoch<1)throw new x("invalid_header","File frame header scope_epoch must be a positive integer");if(t.protection==="grant_aead_v1"&&!t.key_id)throw new x("invalid_header","AEAD-protected file frames require key_id");return{protocol_version:1,protection:t.protection,grant_id:t.grant_id,authority_id:t.authority_id,collection_id:t.collection_id,transfer_id:t.transfer_id,direction:t.direction,chunk_size:t.chunk_size,chunk_index:t.chunk_index,offset:t.offset,plaintext_length:t.plaintext_length,total_size:t.total_size,scope_epoch:t.scope_epoch,...t.key_id===void 0?{}:{key_id:t.key_id}}}function sa(t){let e;try{e=new TextDecoder("utf-8",{fatal:!0}).decode(t)}catch{throw new x("invalid_header","File frame header is not valid UTF-8")}let n;try{n=ra(JSON.parse(e))}catch(l){throw l instanceof x?l:new x("invalid_header","File frame header is not valid JSON")}let i=new Set(["protocol_version","protection","grant_id","authority_id","collection_id","transfer_id","direction","chunk_size","chunk_index","offset","plaintext_length","total_size","scope_epoch","key_id"]);if(Object.keys(n).some(l=>!i.has(l)))throw new x("invalid_header","File frame header contains an unknown field");let o=Ie(n,"protocol_version");if(o!==1)throw new x("unsupported_version",`Unsupported file transfer protocol ${o}`);let r=Nt(n,"protection"),s=Nt(n,"direction"),a=n.key_id===void 0?void 0:Nt(n,"key_id"),c=Jn({protocol_version:1,protection:r,grant_id:Ut(n,"grant_id"),authority_id:Ut(n,"authority_id"),collection_id:Ut(n,"collection_id"),transfer_id:Ut(n,"transfer_id"),direction:s,chunk_size:Ie(n,"chunk_size",4194304),chunk_index:Ie(n,"chunk_index"),offset:Ie(n,"offset"),plaintext_length:Ie(n,"plaintext_length",4194304),total_size:Ie(n,"total_size"),scope_epoch:Ie(n,"scope_epoch"),...a===void 0?{}:{key_id:a}});if(JSON.stringify(c)!==e)throw new x("invalid_header","File frame header must use the canonical field order without duplicate fields or whitespace");return c}function Yn(t,e,n){let i=t==="upload_chunk"?"upload":"download";if(e.direction!==i)throw new x("invalid_header",`Frame kind ${t} requires direction ${i}`);let o=e.chunk_index*e.chunk_size;if(!Number.isSafeInteger(o)||e.offset!==o)throw new x("invalid_header","Chunk offset does not match its index and protocol chunk size");if(e.offset+e.plaintext_length>e.total_size)throw new x("invalid_header","Chunk extends past the declared transfer size");let r=e.protection==="grant_aead_v1"?e.plaintext_length+16:e.plaintext_length;if(n!==r)throw new x("invalid_length","Payload length does not match the protected plaintext length")}function aa(t){return t.plaintext_length+(t.protection==="grant_aead_v1"?16:0)}function jt(t,e){let n=Jn(e),i=aa(n);Yn(t,n,i);let o=new TextEncoder().encode(JSON.stringify(n));if(o.byteLength>16384)throw new x("limit_exceeded","File frame header exceeds the protocol limit");let r=new Uint8Array(16+o.byteLength);r.set(co,0);let s=new DataView(r.buffer,r.byteOffset,r.byteLength);return s.setUint8(4,lo),s.setUint8(5,ia(t)),s.setUint16(6,uo,!1),s.setUint32(8,o.byteLength,!1),s.setUint32(12,i,!1),r.set(o,16),r}function ho(t){let e=Jn(t.header);if(Yn(t.kind,e,t.payload.byteLength),t.payload.byteLength>4194320)throw new x("limit_exceeded","File frame payload exceeds the protocol limit");let n=jt(t.kind,e),i=new Uint8Array(n.byteLength+t.payload.byteLength);return i.set(n,0),i.set(t.payload,n.byteLength),i}function Bt(t,e={}){if(t.byteLength<16)throw new x("invalid_length","File frame is shorter than its fixed prefix");if(!co.every((p,h)=>t[h]===p))throw new x("invalid_magic","File frame magic is not MDBF");let n=new DataView(t.buffer,t.byteOffset,t.byteLength),i=n.getUint8(4);if(i!==lo)throw new x("unsupported_version",`Unsupported file frame version ${i}`);let o=oa(n.getUint8(5));if(n.getUint16(6,!1)!==uo)throw new x("unsupported_flags","File frame uses unsupported flags");let r=n.getUint32(8,!1),s=n.getUint32(12,!1),a=e.maxHeaderBytes??16384,c=e.maxPayloadBytes??4194320;if(r===0)throw new x("invalid_length","File frame header must not be empty");if(r>a||s>c)throw new x("limit_exceeded","File frame exceeds the configured decode limits");let l=16+r+s;if(!Number.isSafeInteger(l)||l!==t.byteLength)throw new x("invalid_length","File frame lengths do not match the supplied bytes");let u=16+r,f=sa(t.subarray(16,u));return Yn(o,f,s),{kind:o,header:f,payload:t.slice(u)}}var ca=["describe","changes","read","query","list_views","execute_view","read_view_source","create_view_source","update_view_source","delete_view_source","validate","create","update","delete","rename","read_type","create_type","update_type","assess_type_pack","apply_type_pack","assess_collection_setup","apply_collection_setup","list_timers","put_timer","cancel_timer","reconcile_timers","sync"],la=["list_files","stat_file","open_file_upload","open_file_download","move_file","delete_file","get_file_transfer_status","commit_file_upload","abort_file_transfer"],da={describe:"never",changes:"never",read:"never",query:"never",list_views:"never",execute_view:"never",read_view_source:"never",create_view_source:"always",update_view_source:"always",delete_view_source:"always",validate:"never",create:"always",update:"always",delete:"always",rename:"always",read_type:"never",create_type:"always",update_type:"always",assess_type_pack:"never",apply_type_pack:"always",assess_collection_setup:"never",apply_collection_setup:"always",list_timers:"never",put_timer:"always",cancel_timer:"always",reconcile_timers:"always",sync:"sync_action"},ua={describe:1,changes:1,read:1,query:1,list_views:1,execute_view:1,read_view_source:1,create_view_source:1,update_view_source:1,delete_view_source:1,validate:1,create:1,update:1,delete:1,rename:1,read_type:1,create_type:1,update_type:1,assess_type_pack:1,apply_type_pack:1,assess_collection_setup:1,apply_collection_setup:1,list_timers:1,put_timer:1,cancel_timer:1,reconcile_timers:1,sync:1},pa={list_files:1,stat_file:1,open_file_upload:1,open_file_download:1,move_file:1,delete_file:1,get_file_transfer_status:1,commit_file_upload:1,abort_file_transfer:1},fa=new Set(["open_file_upload","move_file","delete_file","commit_file_upload","abort_file_transfer"]),ha=new Set(["delete","rename"]);var ma=new Set(ca),ya=new Set(la);function mo(t){return ma.has(t)}function ga(t){return ya.has(t)}function yo(t,e){if(t==="file_control"){let n=go(e)&&typeof e.type=="string"?e.type:"";if(!ga(n))throw new Error(`Unknown file-control message: ${n}`);return pa[n]}return ua[t]}function be(t,e){let n=go(e)?e:{};if(n.dry_run===!0&&ha.has(t))return null;if(t==="file_control"){let o=typeof n.type=="string"?n.type:"";return fa.has(o)?`file_control:${o}`:null}let i=da[t];return i==="always"?t:i==="sync_action"&&n.action==="mutate"?"sync:mutate":null}function Z(t,e){return be(t,e)!==null}function go(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var Xn={"mdbase.record.created":"record.created","mdbase.record.modified":"record.updated","mdbase.record.deleted":"record.deleted","mdbase.record.renamed":"record.renamed","mdbase.type.changed":"schema.changed","mdbase.config.changed":"config.changed","mdbase.contract.changed":"contract.changed","mdbase.view.changed":"view.changed","mdbase.view_source.changed":"view.changed","mdbase.resource.changed":"file.changed","mdbase.file.put":"file.put","mdbase.file.remove":"file.removed",file_put:"file.put",file_remove:"file.removed","mdbase.collection.invalidated":"gap"};var ba=1,_a="mdbase-connect mutation fingerprint v1\0",Zn=new TextEncoder;function va(t){return ei(t,new Set)}function Ca(t,e){let n=be(t,e);if(n===null)throw new TypeError("The operation is not a canonical mutation.");let i=Zn.encode(n),o=Zn.encode(va(e)),r=Zn.encode(_a),s=new Uint8Array(r.length+4+8+i.length+4+8+o.length),a=new DataView(s.buffer),c=0;return s.set(r,c),c+=r.length,a.setUint32(c,ba,!1),c+=4,c=_o(s,a,c,i),a.setUint32(c,yo(t,e),!1),c+=4,_o(s,a,c,o),s}async function vo(t,e){let n=new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",Ca(t,e).buffer));return wa(n)}function ei(t,e){if(t===null)return"null";if(t===!0)return"true";if(t===!1)return"false";if(typeof t=="string")return bo(t),JSON.stringify(t);if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError("Mutation input numbers must be finite.");return JSON.stringify(t)}if(typeof t!="object")throw new TypeError(`Mutation input contains unsupported ${typeof t}.`);if(e.has(t))throw new TypeError("Mutation input must not contain cycles.");e.add(t);try{if(Array.isArray(t)){if(Object.getOwnPropertySymbols(t).length>0)throw new TypeError("Mutation input must not contain symbol properties.");let o=[];for(let r=0;r<t.length;r+=1){if(!Object.hasOwn(t,r))throw new TypeError("Mutation input arrays must not be sparse.");o.push(ei(t[r],e))}return`[${o.join(",")}]`}let n=Object.getPrototypeOf(t);if(n!==Object.prototype&&n!==null)throw new TypeError("Mutation input objects must be plain JSON objects.");if(Object.getOwnPropertySymbols(t).length>0)throw new TypeError("Mutation input must not contain symbol properties.");let i=Object.entries(t);for(let[o]of i)bo(o);return i.sort(([o],[r])=>o<r?-1:o>r?1:0),`{${i.map(([o,r])=>{let s=Object.getOwnPropertyDescriptor(t,o);if(!s||s.get||s.set)throw new TypeError("Mutation input must not contain accessor properties.");return`${JSON.stringify(o)}:${ei(r,e)}`}).join(",")}}`}finally{e.delete(t)}}function bo(t){for(let e=0;e<t.length;e+=1){let n=t.charCodeAt(e);if(n>=55296&&n<=56319){let i=t.charCodeAt(e+1);if(!(i>=56320&&i<=57343))throw new TypeError("Mutation input strings must not contain lone surrogates.");e+=1}else if(n>=56320&&n<=57343)throw new TypeError("Mutation input strings must not contain lone surrogates.")}}function _o(t,e,n,i){return e.setBigUint64(n,BigInt(i.length),!1),n+=8,t.set(i,n),n+i.length}function wa(t){return btoa(String.fromCharCode(...t)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}var Y=3,Sa=2,Co=[Y,Sa],ce=5,ti=4,wo=[ce,ti],Oa=2,Pa=1,xl={operation_transport:[...Co],authorization_binding:[...wo],semantic_capabilities:[Oa,1],durable_mutation:[Pa]};function ni(t,e,n=[],i=2){let o={operation_transport:Y,authorization_binding:ce,semantic_capabilities:i},r=[...new Set(n)].filter(s=>s!==Y).sort((s,a)=>a-s);return r.length>0&&(o.operation_transport_recovery=r),(t.some(s=>Z(s,{action:"mutate"}))||e?.actions.some(s=>s!=="list"&&s!=="read")===!0)&&(o.durable_mutation=1),o}function mt(t){return Co.includes(t)}function Ro(t){return wo.includes(t)}var Aa=new TextEncoder().encode("mdbase-connect application installation id v2\0"),Ta=new TextEncoder().encode("mdbase-connect application authorization proof v4\0"),Ma=new TextEncoder().encode("mdbase-connect application authorization proof v5\0");async function Oo(t){let e=Kt(t),i=new Uint8Array(await crypto.subtle.digest("SHA-256",ke([Aa,K(e)]))).slice(0,16);return i[6]=i[6]&15|128,i[8]=i[8]&63|128,[yt(i.slice(0,4)),yt(i.slice(4,6)),yt(i.slice(6,8)),yt(i.slice(8,10)),yt(i.slice(10,16))].join("-")}function Po(t){let e=[Kt(t.installation_signing_public_key),Kt(t.grant_agreement_public_key),Kt(t.grant_signing_public_key)];if(e.some((c,l)=>e.slice(l+1).some(u=>Fa(c,u))))throw new Error("Application authorization keys must be distinct.");let n=ii(t.authorization_nonce),i=ii(t.code_challenge),o=t.contracts,r=o.operation_transport_recovery??[],s=t.requested_operations.some(c=>Z(c,{action:"mutate"}))||t.requested_files?.actions.some(c=>!["list","read"].includes(c))===!0;if(!Ro(t.protocol_version)||n.byteLength!==32||!/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)+$/u.test(t.application_declaration_id)||!/^[0-9a-f]{64}$/u.test(t.application_manifest_digest)||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/u.test(t.issued_at)||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/u.test(t.expires_at)||i.byteLength!==32||![o.operation_transport,o.authorization_binding,o.semantic_capabilities,o.durable_mutation??1].every(c=>Number.isInteger(c)&&c>0)||o.authorization_binding!==t.protocol_version||!mt(o.operation_transport)||t.protocol_version===ce&&o.operation_transport!==Y||r.some(c=>!mt(c)||c===o.operation_transport)||new Set(r).size!==r.length||t.protocol_version===ti&&r.length>0||r.length>0&&!s||(s?o.durable_mutation!==1:o.durable_mutation!==void 0)||t.requested_operations.length===0&&t.requested_files===void 0||new Set(t.requested_operations).size!==t.requested_operations.length||t.requested_operations.some(c=>!c||c.includes("\0"))||(t.flow==="authorization_code"?t.redirect_uri===void 0||t.state===void 0:t.flow!=="device_code"||t.redirect_uri!==void 0||t.state!==void 0))throw new Error("Application authorization binding is invalid.");ka(t.requested_files);let a=t.requested_operations.map(c=>K(new TextEncoder().encode(c)));return ke([t.protocol_version===ce?Ma:Ta,ie(t.protocol_version),K(Qt(t.application_id)),K(Qt(t.authorization_id)),K(new TextEncoder().encode(t.application_declaration_id)),K(Ao(t.application_manifest_digest)),K(Qt(t.application_installation_id)),...e.map(K),K(new TextEncoder().encode(t.flow)),K(n),K(new TextEncoder().encode(t.issued_at)),K(new TextEncoder().encode(t.expires_at)),So(t.redirect_uri),So(t.state),K(new TextEncoder().encode(t.code_challenge)),ie(o.operation_transport),...t.protocol_version===ce?[ie(r.length),...r.map(ie)]:[],ie(o.authorization_binding),ie(o.semantic_capabilities),Ia(o.durable_mutation),ie(a.length),...a,xa(t.requested_files),Ea(t.collection_id)])}function Ia(t){return t===void 0?new Uint8Array(1):ke([new Uint8Array([1]),ie(t)])}function ka(t){if(t!==void 0&&(t.actions.length===0||new Set(t.actions).size!==t.actions.length||t.scope.kind==="selected_folders"&&(t.scope.folders.length===0||new Set(t.scope.folders).size!==t.scope.folders.length||t.scope.folders.some(e=>!e||e.includes("\0")))))throw new Error("Application authorization file request is invalid.")}function xa(t){if(t===void 0)return new Uint8Array(1);let e=t.actions.map(n=>K(new TextEncoder().encode(n)));return ke([new Uint8Array([1]),ie(e.length),...e,K(new TextEncoder().encode(t.scope.kind)),...t.scope.kind==="selected_folders"?[ie(t.scope.folders.length),...t.scope.folders.map(n=>K(new TextEncoder().encode(n)))]:[]])}function So(t){return t===void 0?new Uint8Array(1):ke([new Uint8Array([1]),K(new TextEncoder().encode(t))])}function Ea(t){return t===void 0?new Uint8Array(1):ke([new Uint8Array([1]),K(Qt(t))])}function Kt(t){let e=ii(t);if(e.byteLength!==65||e[0]!==4)throw new Error("Application authorization public key is invalid.");return e}function ii(t){if(!/^[A-Za-z0-9_-]+$/u.test(t))throw new Error("Invalid base64url value.");let e=t.replaceAll("-","+").replaceAll("_","/"),n=e.padEnd(Math.ceil(e.length/4)*4,"="),i=Uint8Array.from(atob(n),o=>o.charCodeAt(0));if(qa(i)!==t)throw new Error("Non-canonical base64url value.");return i}function Qt(t){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu.test(t))throw new Error("Invalid UUID value.");let e=t.replaceAll("-","");return Ao(e)}function Ao(t){if(!/^[0-9a-f]+$/u.test(t)||t.length%2!==0)throw new Error("Invalid hexadecimal value.");return Uint8Array.from({length:t.length/2},(e,n)=>Number.parseInt(t.slice(n*2,n*2+2),16))}function K(t){return ke([ie(t.byteLength),t])}function ie(t){let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t,!1),e}function ke(t){let e=new Uint8Array(t.reduce((i,o)=>i+o.byteLength,0)),n=0;for(let i of t)e.set(i,n),n+=i.byteLength;return e}function qa(t){return btoa(String.fromCharCode(...t)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}function Fa(t,e){return t.byteLength===e.byteLength&&t.every((n,i)=>n===e[i])}function yt(t){return[...t].map(e=>e.toString(16).padStart(2,"0")).join("")}var To={id:"mdbase.record.created",version:"1.0.0",digest:"sha256:7f3bed6baa356ee9389e977ae7b77a102e2bee871a7c1d9f2026fc21cacdbfc9"};var Mo={id:"mdbase.runtime.timer.fired",version:"1.0.0",digest:"sha256:41105be7a7abf33b31ced47e1e1965242236e40ccaea286b959b0a8c591f5642"};var Io=28485,gt="P256-HKDF-SHA256-AES256GCM",Vt=1;var Da="contract-setup-v1",za="file-relay-v1",La="protocol-usage-report-v1",Ua="policy-freshness-lease-v1",Na=["application-authorization-v4","authorization-activation","encrypted-relay","policy-ack"];var ja=["durable-mutation-journal-v1","durable-file-lifecycle-v1","contract-metadata-read-v1"],Ba="candidate-b-activation-v1",Nl=[...Hn,...ja,"mutation-replay-after-credential-retirement-v1",Ba],Ka="application-declaration-evidence-v1",jl=[...Hn,Ka,...Na,Ua,"application-authorization-v5",Da,za,La,ro],oi=1;var ko="mdbase-authority-request-proof-v1",bt={version:"x-mdbase-proof-version",timestamp:"x-mdbase-proof-timestamp",nonce:"x-mdbase-proof-nonce",signature:"x-mdbase-proof-signature"};var _=class extends Error{constructor(n,i={}){super(n.message,i.cause===void 0?void 0:{cause:i.cause});this.problem=n;this.name="MdbaseConnectError",this.code=n.code,this.status=i.status}problem;code;status;get retryable(){return this.problem.recovery==="retry"&&this.problem.operation_outcome!=="unknown"}get requiresAuthorization(){return this.problem.category==="authorization"}get outcomeUnknown(){return this.problem.operation_outcome==="unknown"}get recovery(){return this.problem.recovery}get details(){return this.problem.details}};function w(t,e,...[n={}]){let i=Me[t];return{problem_version:1,code:t,category:i.category,recovery:i.recovery,message:e,...n.details===void 0?{}:{details:n.details},...n.operationOutcome===void 0?{}:{operation_outcome:n.operationOutcome},...n.traceId===void 0?{}:{trace_id:n.traceId}}}function xo(t,e,n={}){return $n(t,e,{details:n.details,operation_outcome:n.operationOutcome,trace_id:n.traceId})}function d(t,e,...n){let i=n[0];return new _(w(t,e,...n),{status:i?.status,cause:i?.cause})}function L(t,e,n={}){let{status:i,cause:o,...r}=n;return new _($n(t,e,{details:r.details,operation_outcome:r.operationOutcome,trace_id:r.traceId}),{status:i,cause:o})}function je(t){let e=Va(t.diagnostics),n=Wa(t.diagnostics);if(e==="concurrent_modification"||e==="file_not_found"||e==="invalid_path")return w(e,n,{operationOutcome:"rejected"});if(e==="collection_version_unsupported"){let i=Ga(t.diagnostics);return w(e,n,{operationOutcome:"rejected",details:i})}return e!=="operation_invalid"?w(e,n,{operationOutcome:"rejected",details:{diagnostics:t.diagnostics}}):w(e,n,{operationOutcome:"rejected",details:{diagnostics:t.diagnostics,partial_result:t.result}})}function Va(t){let e=new Set(t.filter(n=>n.severity==="error").map(n=>n.code));if(["migration_required","migration_lossy","unsupported_version"].some(n=>e.has(n)))return"collection_version_unsupported";if(["invalid_config","invalid_configuration","missing_config","missing_spec_version"].some(n=>e.has(n)))return"collection_configuration_invalid";if(["duplicate_type","invalid_contract_definition","invalid_data_contract","invalid_type_definition","invalid_type_path"].some(n=>e.has(n)))return"collection_type_registry_invalid";if(["collection_invalid","collection_open_failed"].some(n=>e.has(n)))return"collection_invalid";for(let n of["concurrent_modification","file_not_found","invalid_path"])if(e.has(n))return n;return"operation_invalid"}function Ga(t){let e=t.map(n=>n.details).find(n=>Ha(n));return{current_version:typeof e?.current_version=="string"?e.current_version:"0.2.x",required_version:typeof e?.required_version=="string"?e.required_version:"0.3.0"}}function Ha(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Eo(t){return t instanceof _&&t.retryable}function Wa(t){return t.filter(e=>e.severity==="error").map(e=>e.message).join(" ")||t.map(e=>e.message).join(" ")||"The collection rejected this operation."}var $a=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ja=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),xe=class{state=Ja.slice();block=new Uint8Array(64);words=new Uint32Array(64);blockLength=0;byteLength=0;finished=!1;update(e){if(this.finished)throw new Error("SHA-256 digest is already finalized.");if(this.byteLength+=e.byteLength,!Number.isSafeInteger(this.byteLength))throw new Error("SHA-256 input exceeds the safe browser byte range.");let n=0;if(this.blockLength>0){let i=Math.min(64-this.blockLength,e.byteLength);this.block.set(e.subarray(0,i),this.blockLength),this.blockLength+=i,n+=i,this.blockLength===64&&(this.compress(this.block),this.blockLength=0)}for(;n+64<=e.byteLength;)this.compress(e,n),n+=64;return n<e.byteLength&&(this.block.set(e.subarray(n),0),this.blockLength=e.byteLength-n),this}digestHex(){if(this.finished)throw new Error("SHA-256 digest is already finalized.");this.finished=!0,this.block[this.blockLength]=128,this.block.fill(0,this.blockLength+1),this.blockLength>=56&&(this.compress(this.block),this.block.fill(0));let e=this.byteLength*8,n=Math.floor(e/4294967296),i=e>>>0;return qo(this.block,56,n),qo(this.block,60,i),this.compress(this.block),[...this.state].map(o=>o.toString(16).padStart(8,"0")).join("")}compress(e,n=0){let i=this.words;for(let p=0;p<16;p+=1){let h=n+p*4;i[p]=(e[h]<<24|e[h+1]<<16|e[h+2]<<8|e[h+3])>>>0}for(let p=16;p<64;p+=1){let h=i[p-15],m=i[p-2],P=le(h,7)^le(h,18)^h>>>3,v=le(m,17)^le(m,19)^m>>>10;i[p]=i[p-16]+P+i[p-7]+v>>>0}let o=this.state[0],r=this.state[1],s=this.state[2],a=this.state[3],c=this.state[4],l=this.state[5],u=this.state[6],f=this.state[7];for(let p=0;p<64;p+=1){let h=le(c,6)^le(c,11)^le(c,25),m=c&l^~c&u,P=f+h+m+$a[p]+i[p]>>>0,v=le(o,2)^le(o,13)^le(o,22),b=o&r^o&s^r&s,C=v+b>>>0;f=u,u=l,l=c,c=a+P>>>0,a=s,s=r,r=o,o=P+C>>>0}this.state[0]=this.state[0]+o>>>0,this.state[1]=this.state[1]+r>>>0,this.state[2]=this.state[2]+s>>>0,this.state[3]=this.state[3]+a>>>0,this.state[4]=this.state[4]+c>>>0,this.state[5]=this.state[5]+l>>>0,this.state[6]=this.state[6]+u>>>0,this.state[7]=this.state[7]+f>>>0}};function le(t,e){return t>>>e|t<<32-e}function qo(t,e,n){t[e]=n>>>24,t[e+1]=n>>>16,t[e+2]=n>>>8,t[e+3]=n}function oe(t,e){return new Promise((n,i)=>{if(e?.aborted){i(e?.reason??new DOMException("Aborted","AbortError"));return}let o=()=>e?.removeEventListener("abort",s),r=setTimeout(()=>{o(),n()},t),s=()=>{clearTimeout(r),o(),i(e?.reason??new DOMException("Aborted","AbortError"))};e?.addEventListener("abort",s,{once:!0})})}var Gt=8,ri=10;function Ht(t){return t instanceof _&&t.code==="connector_busy"}async function Fo(t){if(!Ht(t.error)||t.completedRetries>=Gt)return{retried:!1};try{await Wt(t.completedRetries,t.signal)}catch(e){throw t.attempt.pendingMutation&&(t.knownRejectedMutationRetry||!t.attempt.resumingMutation)&&t.clearPending(t.attempt.requestId),e}return{retried:!0,result:await t.retry(t.attempt.pendingMutationRecord,t.knownRejectedMutationRetry||t.attempt.pendingMutation===!0&&!t.attempt.resumingMutation)}}async function Be(t){if(t.status!==502&&t.status!==503)return!1;let e=await t.clone().json().catch(()=>null);return e?.error==="connector_busy"||typeof e?.error=="object"&&e.error?.code==="connector_busy"}function Wt(t,e){return zo(Lo(50,800,t),e)}function Do(t,e){return zo(Lo(100,1e3,t-1),e)}async function zo(t,e){try{await oe(t,e)}catch(n){throw e?.aborted?e.reason instanceof _?e.reason:d("operation_cancelled","The operation was cancelled while waiting for connector capacity.",{operationOutcome:"not_sent",cause:n}):n}}function Lo(t,e,n){let i=Math.min(e,t*2**Math.max(0,n));return Math.max(1,Math.round(i*(.75+Math.random()*.5)))}var Uo=1024*1024,Ya=4,No=8,_t=3,si=64*1024*1024,jo=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,$t=/^sha256:[0-9a-f]{64}$/u;async function Bo(t,e,n){let i=new xe;for(let o=0;o<t.size;o+=Uo){ee(e);let r=new Uint8Array(await t.slice(o,o+Uo).arrayBuffer());i.update(r),n(Math.min(t.size,o+r.byteLength))}return t.size===0&&n(0),i.digestHex()}function Ko(t,e){if(t instanceof Blob)return e&&e!==t.type?t.slice(0,t.size,e):t;if(t instanceof ArrayBuffer)return new Blob([t],{type:e});let n=new Uint8Array(t.byteLength);return n.set(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),new Blob([n.buffer],{type:e})}function Qo(t){return t instanceof Blob?t.size:t.byteLength}async function Vo(t){return t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t}function ai(t=Ya){if(!Number.isInteger(t)||t<1||t>No)throw d("invalid_request",`File concurrency must be between 1 and ${No}.`);return t}function Go(t){if(!Number.isInteger(t)||t<1||t>1e3)throw d("invalid_request","File page size must be between 1 and 1000.");return t}function ci(t,e,n){if(t.protocol_version!==1||t.type!=="file_transfer"||t.transfer_id!==e||t.direction!==n||!Number.isSafeInteger(t.total_size)||t.total_size<0||!Array.isArray(t.received)||!Xa(t))throw d("invalid_operation_response","The authority returned an invalid file transfer session.");let i=t.strategy.kind==="framed_chunks"?t.strategy.chunk_size:t.strategy.kind==="object_put"?Math.max(1,t.total_size):t.strategy.part_size,o=t.strategy.kind==="object_put"?1:Math.ceil(t.total_size/i);if(new Set(t.received).size!==t.received.length||t.received.some(s=>!Number.isSafeInteger(s)||s<0||s>=o))throw d("invalid_operation_response","The authority returned invalid transfer progress.");let r=t.uploaded_parts??[];if(!Array.isArray(r)||r.some((s,a)=>!Number.isSafeInteger(s?.part_number)||s.part_number<1||s.part_number>o||typeof s.etag!="string"||s.etag.length===0||s.etag.length>255||a>0&&r[a-1].part_number>=s.part_number)||(t.strategy.kind==="object_multipart"?r.length!==t.received.length||r.some((s,a)=>s.part_number-1!==t.received[a]):r.length!==0))throw d("invalid_operation_response","The authority returned invalid uploaded part receipts.")}function li(t,e){let n=e.strategy.kind==="framed_chunks"?e.strategy.chunk_size:e.strategy.kind==="object_put"?Math.max(1,e.total_size):e.strategy.part_size,i=e.strategy.kind==="object_put"?1:Math.ceil(e.total_size/n);if(t?.protocol_version!==1||t.type!=="file_transfer_status"||t.transfer_id!==e.transfer_id||!["open","committed","aborted","expired"].includes(t.state)||!Array.isArray(t.received)||new Set(t.received).size!==t.received.length||t.received.some(r=>!Number.isSafeInteger(r)||r<0||r>=i)||!Number.isSafeInteger(t.received_bytes)||t.received_bytes<0||t.received_bytes>e.total_size||t.received.reduce((r,s)=>r+di(e.total_size,n,s),0)!==t.received_bytes)throw d("invalid_operation_response","The authority returned invalid transfer status.");let o=t.uploaded_parts;if(!Array.isArray(o)||o.some((r,s)=>!Number.isSafeInteger(r?.part_number)||r.part_number<1||r.part_number>i||typeof r.etag!="string"||r.etag.length===0||r.etag.length>255||s>0&&o[s-1].part_number>=r.part_number)||(e.strategy.kind==="object_multipart"?o.length!==t.received.length||o.some((r,s)=>r.part_number-1!==t.received[s]):o.length!==0))throw d("invalid_operation_response","The authority returned invalid uploaded part status.")}function Xa(t){return t.strategy.kind==="framed_chunks"?t.protection==="grant_aead_v1"&&Number.isSafeInteger(t.strategy.chunk_size)&&t.strategy.chunk_size>0:t.protection!=="transport_tls"?!1:t.strategy.kind==="object_put"?!0:Number.isSafeInteger(t.strategy.part_size)&&t.strategy.part_size>0}function di(t,e,n){return Math.min(e,Math.max(0,t-n*e))}async function Jt(t,e){for(let n=1;n<=ri;n+=1){ee(e);try{return await t()}catch(i){if(e?.aborted||n===ri||i instanceof _&&!i.retryable)throw i;await Do(n,e)}}throw new Error("Unreachable file chunk retry state.")}function ui(t,e,n,i,o,r){let s;try{s=new URL(t.url)}catch{throw d("invalid_operation_response","The authority returned an invalid object URL.")}if(t.protocol_version!==1||t.type!=="file_part"||t.transfer_id!==e||t.part_index!==n||t.offset!==i||t.content_length!==o||typeof t.method!="string"||t.method.toUpperCase()!==r||!t.headers||typeof t.headers!="object"||Array.isArray(t.headers)||Object.values(t.headers).some(a=>typeof a!="string")||typeof t.expires_at!="string"||!Number.isFinite(Date.parse(t.expires_at))||s.protocol!=="https:"&&!(s.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(s.hostname))||s.username||s.password)throw d("invalid_operation_response","The authority returned an invalid prepared file part.")}function pi(t){let e=new Headers;for(let[n,i]of Object.entries(t))["host","content-length"].includes(n.toLowerCase())||e.set(n,i);return e}async function Ho(t,e,n){let i=new Array(t),o=0;return await Promise.all(Array.from({length:Math.min(t,e)},async()=>{for(;o<t;){let r=o;o+=1,i[r]=await n(r)}})),i}function ee(t){if(t?.aborted)throw d("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:t.reason})}function _e(t){return t instanceof _?t:typeof DOMException<"u"&&t instanceof DOMException&&t.name==="AbortError"?d("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:t}):d("temporarily_unavailable","The file transfer could not be completed.",{cause:t})}var fi=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu;function hi(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.file_id=="string"&&fi.test(e.file_id)&&typeof e.path=="string"&&typeof e.revision=="string"&&typeof e.content_digest=="string"&&$t.test(e.content_digest)&&Number.isSafeInteger(e.size)&&e.size>=0&&["image","audio","video","pdf","other"].includes(e.media_class)&&typeof e.modified_at=="string"&&(e.media_type===void 0||typeof e.media_type=="string")}function fe(t){if(!hi(t))throw d("invalid_operation_response","The authority returned an invalid file descriptor.");return{fileId:t.file_id,path:t.path,revision:t.revision,contentDigest:t.content_digest,size:t.size,...t.media_type?{mediaType:t.media_type}:{},mediaClass:t.media_class,modifiedAt:t.modified_at}}var Za=Object.entries({path:Q,from:Q,to:Q,revision:Q,previous_revision:Q,types:mi,previous_types:mi,changed_fields:mi,body_changed:nc,before:gi,after:gi}),ec=Object.entries({path:Q,name:Q,revision:Q,previous_revision:Q,reason:Q}),tc=Object.entries({previous_path:Q,revision:Q});function bi(t){let e={cursor:t.cursor,type:t.type,occurredAt:t.occurred_at,payload:t.payload,raw:t},n=a=>({...e,kind:"unknown",reason:a}),i=Object.hasOwn(Xn,t.type)?Xn[t.type]:void 0;if(!i)return n("unrecognized_type");let o=t.payload;if(!gi(o))return n("invalid_payload");if(i.startsWith("record.")){if(!yi(o,Za))return n("invalid_payload");let a=o,c={...a.revision==null?{}:{revision:a.revision},...a.previous_revision==null?{}:{previousRevision:a.previous_revision},...a.types==null?{}:{types:a.types},...a.previous_types==null?{}:{previousTypes:a.previous_types},...a.changed_fields==null?{}:{changedFields:a.changed_fields},...a.body_changed==null?{}:{bodyChanged:a.body_changed},...a.before==null?{}:{before:a.before},...a.after==null?{}:{after:a.after}};if(i==="record.renamed")return Q(o.from)&&Q(o.to)?{...e,...c,kind:i,from:o.from,to:o.to}:n("invalid_payload");if(i==="record.created"||i==="record.updated"||i==="record.deleted")return Q(o.path)?{...e,...c,kind:i,path:o.path}:n("invalid_payload")}if(i==="file.put")return hi(o.file)?{...e,kind:i,file:fe(o.file)}:n("invalid_payload");if(i==="file.removed"){if(!Q(o.file_id)||!yi(o,tc))return n("invalid_payload");let a=o;return{...e,kind:i,fileId:o.file_id,...a.previous_path==null?{}:{previousPath:a.previous_path},...a.revision==null?{}:{revision:a.revision}}}if(!yi(o,ec))return n("invalid_payload");let r=o;if(i==="gap")return{...e,kind:i,...r.reason==null?{}:{reason:r.reason}};let s={...r.revision==null?{}:{revision:r.revision},...r.previous_revision==null?{}:{previousRevision:r.previous_revision}};if(i==="file.changed")return Q(o.path)?{...e,...s,kind:i,path:o.path}:n("invalid_payload");if(i==="schema.changed"||i==="config.changed"||i==="contract.changed"||i==="view.changed")return{...e,...s,kind:i,...r.path==null?{}:{path:r.path},...r.name==null?{}:{name:r.name}};throw new Error(`Unhandled change kind: ${i}`)}function Wo(t){return{events:t.reset?[{kind:"reset",type:"reset",cursor:t.cursor,occurredAt:null,payload:{},raw:t}]:t.events.map(bi),cursor:t.cursor,hasMore:t.has_more,reset:t.reset}}function $o(t){return t.kind==="schema.changed"||t.kind==="config.changed"||t.kind==="contract.changed"||t.kind==="view.changed"||t.kind==="gap"||t.kind==="reset"||t.kind==="unknown"}function Q(t){return typeof t=="string"}function nc(t){return typeof t=="boolean"}function mi(t){return Array.isArray(t)&&t.every(Q)}function gi(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function yi(t,e){return e.every(([n,i])=>t[n]==null||i(t[n]))}var Ee=["describe","changes","read","query"];function V(t){let e=t.capabilities===void 0?1:t.capabilities?.contract_version;return e!==1&&e!==2&&Ke("Unsupported declared capability contract version."),e}function Ke(t){throw d("invalid_application_manifest",t,{details:{issues:[{path:"/requirements/capabilities",keyword:"authorizationSelection",message:t,params:{}}]}})}function re(t,e){if(e.operations!==void 0&&e.capabilities!==void 0&&Ke("Specify operations or capabilities, not both."),e.operations!==void 0&&V(t)!==1&&Ke("Exact operations authorization is only supported for legacy v1 declarations."),e.capabilities!==void 0){let n=new Set([...t.capabilities?.required??[],...t.capabilities?.optional??[]]);e.capabilities.some(i=>!n.has(i)||X(V(t),i)===void 0)&&Ke("Authorization can only include capabilities declared by the application.")}}function Jo(t){let e=t.capabilities;return e?[...new Set([...e.required,...e.optional??[]].flatMap(n=>X(e.contract_version,n)??[]))]:[...Ee]}function _i(t,e){let{requirements:n}=t;if(re(n,e),V(n)===1){if(e.operations!==void 0)return[...new Set(e.operations)];if(e.capabilities===void 0)return[...Ee]}let i=n.capabilities,r=[...i?.required??[],...e.capabilities??i?.optional??[]].flatMap(a=>X(V(n),a)??[]),s=(t.provisions?.type_packs.length??0)>0||(t.provisions?.configuration?.length??0)>0;return[...new Set([...r,...V(n)===2&&s?Lt:[]])]}function Yt(t,e){return[...t.capabilities?.required??[],...t.capabilities?.optional??[]].filter(n=>(X(V(t),n)??[]).every(i=>e.includes(i)))}function vi(t){let e=t.files;if(e)return V(t)===1?((!("actions"in e)||"required"in e||"optional"in e)&&Ke("Legacy file declarations must use exact files.actions."),{actions:[...e.actions],scope:structuredClone(e.scope)}):("actions"in e&&Ke("V2 file declarations must use required/optional file actions."),fo(e))}function Xt(t,e,n){let i=new Set(t.required),o=[...new Set([...t.required,...t.optional??[]])],r={};for(let s of o)r[s]=ic(s,i.has(s),n,t.contract_version,e);return{contractVersion:t.contract_version,values:r,requiredAvailable:t.required.every(s=>r[s]?.state==="available")}}function ic(t,e,n,i,o){let r=X(i,t)??[],s=r.filter(c=>!n.operations.includes(c)),a={id:t,requirement:e?"required":"optional",operations:r,missingOperations:s,evidence:[{source:"application",fact:`${e?"Required":"Optional"} in capability contract v${i}.`}]};if(s.length>0)return{...a,state:"requires_authorization",evidence:[...a.evidence,{source:"authorization",fact:`Missing ${s.join(", ")}.`}],reason:"The current grant does not include every operation for this capability."};if(n.scope.access!=="full_collection")return{...a,state:"requires_authorization",reason:"The current grant uses legacy contract scope and must be reauthorized for the entire collection.",evidence:[...a.evidence,{source:"authorization",fact:"Legacy contract scope is compatibility evidence, not active data authority."}]};if(i===1&&t.startsWith("files.")){let c=t.slice(6);if(!n.fileCapability?.actions.includes(c))return{...a,state:n.fileCapability?"requires_authorization":"unsupported",reason:n.fileCapability?`The current file grant does not include ${c}.`:"This connection has no file capability."}}return i===1&&t==="notifications.background-delivery"&&(o.notifications?.criteria.length??0)===0?{...a,state:"requires_setup",reason:"The application manifest declares no notification criteria."}:{...a,state:"available",evidence:[...a.evidence,{source:"authorization",fact:r.length>0?`Granted operations: ${r.join(", ")}.`:"No record operation is required."},{source:"authority",fact:n.authority.kind==="hosted"?"Backed by a durable hosted mdbase authority.":"Backed by a user-operated mdbase connector."}],...t==="offline.replica"||i===1&&t==="sync.offline-replica"?{details:{durability:"device",writes:"queued",authority:n.authority.kind}}:{},...i===1&&t==="notifications.background-delivery"?{details:{delivery:"authority",payload:"opaque"}}:{}}}var Qe=3e4,Ci=1e4,oc=10*6e4,rc=12e4,sc=6e4;function Ve(t={}){return{requestMs:vt(t.requestMs,Qe,"requestMs"),watchStartMs:vt(t.watchStartMs,Ci,"watchStartMs"),fileIndexMs:vt(t.fileIndexMs,oc,"fileIndexMs"),uploadMs:vt(t.uploadMs,rc,"uploadMs"),syncMs:vt(t.syncMs,sc,"syncMs")}}function de(t,e){return{...t,signal:e.signal,...e.deadline===null?{}:{deadlineUnixMs:e.deadline}}}function ve(t={},e=Qe,n=Date.now){let i=t.timeoutMs===void 0?e:t.timeoutMs,o=i===null?null:ac(i),r=new AbortController,s=o===null?null:n()+o,a=()=>r.abort(t.signal?.reason);t.signal?.aborted?a():t.signal?.addEventListener("abort",a,{once:!0});let c=o===null?void 0:setTimeout(()=>r.abort(d("timeout","The operation exceeded its request deadline.",{operationOutcome:"not_sent"})),o),l=!1;return{signal:r.signal,deadline:s,remainingMs:()=>s===null?null:Math.max(0,s-n()),dispose:()=>{l||(l=!0,c!==void 0&&clearTimeout(c),t.signal?.removeEventListener("abort",a))}}}async function k(t,e,n){let i=ve(t,e),o,r=new Promise((a,c)=>{o=c}),s=()=>o?.(te(i.signal));i.signal.addEventListener("abort",s,{once:!0});try{if(i.signal.aborted)throw te(i.signal);return await Promise.race([n(i),r])}finally{i.signal.removeEventListener("abort",s),i.dispose()}}async function W(t,e,n){let i=ve(t,e);try{if(i.signal.aborted)throw te(i.signal);return await n(i)}finally{i.dispose()}}function te(t){return t.reason instanceof _?t.reason:d("operation_cancelled","The operation was cancelled before it changed the collection.",{operationOutcome:"not_sent",cause:t.reason})}function ac(t){if(!Number.isSafeInteger(t)||t<=0)throw new TypeError("timeoutMs must be a positive safe integer or null.");return t}function vt(t,e,n){if(t===void 0)return e;if(t===null)return null;if(!Number.isSafeInteger(t)||t<=0)throw new TypeError(`${n} must be a positive safe integer or null.`);return t}async function Ct(t,e){let n=typeof window>"u"?void 0:globalThis.performance,i=n?.now();try{return await e()}finally{if(n&&i!==void 0)try{let o=`mdbase:startup:${t}`;n.clearMeasures(o),n.measure(o,{start:i,end:n.now()})}catch{}}}async function wi(t){let{collectionId:e,readiness:n,contracts:i,connection:o,controller:r,options:s,requestMs:a,isCurrent:c,publish:l}=t,u=()=>r.abort(s?.signal?.reason);s?.signal?.aborted?u():s?.signal?.addEventListener("abort",u,{once:!0});try{let f=await Ct("contracts",()=>k({...s,signal:r.signal},a,h=>o.describe(h)));if(!c())return!1;if(!f.ok){let h=["access_denied","collection_access_denied","insufficient_access","not_authorized","authorization_expired","application_declaration_mismatch"].includes(f.problem.code);return n.contracts={state:h?"requires_authorization":"temporarily_unavailable",missing:[],evidence:[{source:"runtime",fact:f.problem.message}]},l(h?{status:"authorization_required"}:{status:"blocked",problem:f.problem}),!1}if(f.value.collectionId!==e)return n.contracts={state:"temporarily_unavailable",missing:[],evidence:[]},l({status:"blocked",problem:{code:"collection_not_ready",message:"Description belongs to a different collection."}}),!1;let p=i.filter(h=>!f.value.contracts.some(m=>m.id===h.id&&m.version===h.version&&m.digest===h.digest));if(n.contracts={state:p.length?"requires_setup":"verified",missing:p,evidence:[{source:"authority",fact:"Exact contract ID, version and digest checked by live describe for this collection."}]},p.length)return l({status:"blocked",problem:{code:"collection_not_ready",message:"The collection is missing required exact contracts."}}),!1}catch(f){if(!c())return!1;if(!(f instanceof _))throw f;return n.contracts={state:"temporarily_unavailable",missing:[],evidence:[{source:"runtime",fact:f.problem.message}]},l({status:"blocked",problem:f.problem}),!1}finally{s?.signal?.removeEventListener("abort",u)}return!0}function Yo(t,e,n){let i=structuredClone(t);return i.setup.state!=="not_required"&&i.setup.state!=="current"&&(i.setup.state=e==="ready"?n==="cached"?"cached":"current":e==="setup_review_required"?"review_required":e==="authorization_required"?"requires_authorization":e==="blocked"?"blocked":"checking",i.setup.evidence=[{source:e==="ready"&&n==="cached"?"runtime":"authority",fact:`Collection setup verification: ${i.setup.state}.`}]),i}function Xo(t,e,n,i){return{collectionId:e,info:n,capabilities:Xt(t.requirements.capabilities,t,n),...t.requirements?.capabilities?.contract_version===2?{readiness:lc(t,n)}:{},connections:i}}function Zt(t,e){return`mdbase-application-session:v1:${t.id}:${e}`}function Ri(t){return JSON.stringify({capabilities:t.requirements?.capabilities,requirements:t.requirements?.configuration??[],provisions:t.provisions??{}})}function Zo(t,e){return t.requirements?.access==="full_collection"&&e.scope.access==="full_collection"&&e.scope.contracts.length===0}function er(t){let e={};for(let n of t.typePacks){let i=Object.fromEntries(n.resources.filter(o=>o.action==="conflict"&&o.mode==="managed"&&o.currentDigest!==void 0&&o.installedDigest===void 0).map(o=>[o.target,o.currentDigest]));Object.keys(i).length>0&&(e[n.desired.id]=i)}return e}function tr(t,e,n,i){return{applicationId:e,declarationDigest:n,requirements:{configuration:t.requirements?.configuration??[]},provisions:{configuration:t.provisions?.configuration??[],typePacks:t.provisions?.type_packs??[]},...i?{typePackAdoptions:i}:{}}}function cc(t,e){if(!e||t.kind!==e.kind)return!1;if(t.kind==="collection"||e.kind==="collection")return!0;let n=[...new Set(t.folders)].sort(),i=[...new Set(e.folders)].sort();return JSON.stringify(n)===JSON.stringify(i)}function lc(t,e){let n=t.requirements?.files,i=n&&"required"in n?n:void 0,o=!i||cc(i.scope,e.fileCapability?.scope),r=u=>u.filter(f=>!o||!e.fileCapability?.actions.includes(f)),s=r(i?.required??[]),a=r(i?.optional??[]),c=t.requirements?.contracts??[],l=(t.provisions?.type_packs.length??0)>0||(t.provisions?.configuration?.length??0)>0;return{files:{state:i?s.length?"requires_authorization":"available":"not_required",missingRequiredActions:s,missingOptionalActions:a,scopeMatches:o,evidence:[{source:"authorization",fact:"Compared exact file actions and folder scope with connection.info().fileCapability."}]},contracts:{state:c.length?"checking":"not_required",missing:[],evidence:[]},setup:{state:l?"checking":"not_required",evidence:[]},notifications:{state:t.notifications?.criteria.length?"requires_registration":"not_required",registration:"unverified",evidence:[{source:"runtime",fact:"The connection API exposes registration commands but no current delivery-registration query. Manifest criteria do not prove approval or delivery registration."}]}}}var en=["access_denied","access_paused","application_declaration_mismatch","authorization_binding_incompatible","authorization_expired","capability_contract_incompatible","collection_access_denied","connector_identity_changed","connector_offline","connector_upgrade_required","direct_operation_rejected","durable_mutation_unsupported","operation_outcome_unknown","encryption_required","encrypted_relay_rejected","hosted_provider_unavailable","insufficient_access","invalid_encrypted_response","invalid_operation_response","invalid_request","missing_grant_key","mutation_recovery_expired","mutation_request_conflict","not_authorized","operation_cancelled","operation_failed","rate_limited","relay_authorization_expired","relay_unavailable","temporarily_unavailable","timeout","transport_protocol_incompatible","unsupported_operation"],Ge=Object.keys(Me),qe=["discovery_failed","invalid_operation_response","invalid_application_manifest","invalid_request","manifest_load_failed","rate_limited","temporarily_unavailable","timeout"],Ce=[...qe,"access_denied","application_declaration_mismatch","application_identity_unavailable","approval_window_blocked","authorization_binding_incompatible","authorization_cancelled","authorization_replayed","browser_required","capability_contract_incompatible","collection_access_denied","collection_configuration_invalid","collection_contracts_missing","collection_incompatible","collection_invalid","collection_kind_unsupported","collection_mismatch","collection_not_found","collection_type_registry_invalid","collection_version_unsupported","connector_identity_changed","connector_offline","connector_upgrade_required","device_authorization_failed","durable_mutation_unsupported","encryption_required","expired_token","invalid_application_authorization","invalid_callback","invalid_device_authorization_response","invalid_token_response","legacy_scope_reauthorization_required","scope_denied","reconnect_required","token_exchange_failed","transport_protocol_incompatible"],wt=[...qe,"authorization_expired","invalid_operation_response","invalid_push_subscription","managed_fcm_not_declared","not_authorized","notification_criterion_not_declared","notification_reauthorization_required","notification_registration_failed","notification_unregistration_failed","notifications_not_declared","notifications_unavailable"],Si=["connector_offline","connector_upgrade_required","invalid_operation_response","not_authorized","operation_failed","temporarily_unavailable","timeout"],Ed=[...Ce,"collection_not_ready","collection_not_selected","operation_cancelled","session_destroyed","session_not_started","session_starting","unknown_collection"],dc=["collection_configuration_invalid","collection_invalid","collection_type_registry_invalid","collection_version_unsupported"],Rt=[...en,...dc],ue=[...Rt,"file_not_found","invalid_path","operation_invalid"],pe=[...ue,"cursor_capacity_exhausted","generation_expired","invalid_read_cursor","query_snapshot_changed","sandbox_unsupported"],G=[...ue,"concurrent_modification","invalid_preflight","pending_mutation_unresolved"],tn=[...Rt,"change_cursor_reset"],we=[...G,"type_pack_provision_failed"];function R(t,e=[]){return{ok:!0,value:t,diagnostics:e}}function g(t){return{ok:!1,problem:t}}async function I(t,e){try{return R(await t())}catch(n){if(!(n instanceof _))throw n;let i=n.problem;return i.code==="unknown"||e.includes(i.code)?g(i):g(xo(i.code,i.message,{details:i.details,operationOutcome:i.operation_outcome,traceId:i.trace_id}))}}function se(t){let e=new Uint8Array(t);return crypto.getRandomValues(e),he(e)}var nr=32768;function he(t){let e="";for(let o=0;o<t.length;o+=nr)e+=String.fromCharCode.apply(null,t.subarray(o,o+nr));let n=btoa(e).replaceAll("+","-").replaceAll("/","_"),i=n.length;for(;i>0&&n.charCodeAt(i-1)===61;)i-=1;return n.slice(0,i)}function nn(t){let e=t.replaceAll("-","+").replaceAll("_","/").padEnd(Math.ceil(t.length/4)*4,"="),n=atob(e),i=new Uint8Array(new ArrayBuffer(n.length));for(let o=0;o<n.length;o+=1)i[o]=n.charCodeAt(o);return i}var uc="mdbase-connect-keys",Re="grant-keys",Pi=18446744073709551615n,pc="mdbase-connect relay request key v1",fc="mdbase-connect relay response key v1",ir=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,He=class{database=null;async create(e){let n=await sr(e),i=await this.open();return await rr(i,o=>o.add({...n,counter:"0"})),n}async get(e){let n=await this.open(),i=await bc(n.transaction(Re).objectStore(Re).get(e));return i?{handle:i.handle,agreementPrivateKey:i.agreementPrivateKey,agreementPublicKey:i.agreementPublicKey,signingPrivateKey:i.signingPrivateKey,signingPublicKey:i.signingPublicKey}:null}async nextCounter(e){let n=await this.open();return new Promise((i,o)=>{let r=n.transaction(Re,"readwrite"),s=r.objectStore(Re),a=s.get(e),c=null;a.onerror=()=>o(a.error),a.onsuccess=()=>{let l=a.result;if(!l){r.abort(),o(new q("missing_grant_key","The encrypted grant key is unavailable."));return}let u=BigInt(l.counter)+1n;if(u>Pi){r.abort(),o(new q("counter_exhausted","The encrypted grant must be authorized again."));return}c=u.toString(),s.put({...l,counter:c})},r.onerror=()=>o(r.error),r.onabort=()=>o(r.error??new Error("Key counter transaction aborted.")),r.oncomplete=()=>{c&&i(c)}})}async delete(e){let n=await this.open();await rr(n,i=>i.delete(e))}open(){if(typeof indexedDB>"u")throw new q("key_storage_unavailable","Encrypted relay authorization requires browser IndexedDB or an injected grant key store.");return this.database||(this.database=new Promise((e,n)=>{let i=indexedDB.open(uc,1);i.onupgradeneeded=()=>{i.result.objectStoreNames.contains(Re)||i.result.createObjectStore(Re,{keyPath:"handle"})},i.onerror=()=>n(i.error),i.onsuccess=()=>e(i.result)})),this.database}},We=class{records=new Map;sequence=Promise.resolve();async create(e){if(this.records.has(e))throw new Error(`Grant key already exists: ${e}`);let n=await sr(e);return this.records.set(e,{...n,counter:"0"}),n}async get(e){let n=this.records.get(e);return n?{handle:n.handle,agreementPrivateKey:n.agreementPrivateKey,agreementPublicKey:n.agreementPublicKey,signingPrivateKey:n.signingPrivateKey,signingPublicKey:n.signingPublicKey}:null}nextCounter(e){let n,i,o=new Promise((r,s)=>{n=r,i=s});return this.sequence=this.sequence.then(()=>{let r=this.records.get(e);if(!r)throw new q("missing_grant_key","The encrypted grant key is unavailable.");let s=BigInt(r.counter)+1n;if(s>Pi)throw new q("counter_exhausted","The encrypted grant must be authorized again.");r.counter=s.toString(),n(r.counter)}).catch(r=>{i(r)}),o}async delete(e){this.records.delete(e)}};async function on(t,e,n,i){let o=await hc(t,e,n),r=i.timestamp??Math.floor(Date.now()/1e3),s=i.nonce??crypto.randomUUID(),a=await Ai({...i,timestamp:r,nonce:s}),c=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},o.signingPrivateKey,new TextEncoder().encode(a));return{[bt.version]:String(oi),[bt.timestamp]:String(r),[bt.nonce]:s,[bt.signature]:he(new Uint8Array(c))}}async function Ai(t){let e=t.method.toUpperCase(),n=await or(t.body??""),i=await or(t.credential);for(let o of[e,t.target,String(t.timestamp),t.nonce])if(!o||o.includes(`
|
|
2
|
+
`)||o.includes("\r"))throw new q("invalid_proof_input","Authority request proof metadata is invalid.");return[ko,oi,e,t.target,n,i,t.timestamp,t.nonce].join(`
|
|
3
|
+
`)}async function me(t,e,n,i,o,r=crypto.randomUUID(),s){if(ye(n.encryption),s!==void 0&&(!Number.isSafeInteger(s)||s<=0))throw new q("invalid_deadline","The operation deadline is invalid.");let a=await ar(t,e,n.encryption.application_agreement_public_key),c=await t.nextCounter(e),l={binding:n,protocolVersion:Y,requestId:r,operation:i,counter:c},u=await cr(a.agreementPrivateKey,n,l.protocolVersion,"request"),f=new TextEncoder().encode(JSON.stringify(o??{})),p=await crypto.subtle.encrypt({name:"AES-GCM",iv:ur(c),additionalData:new TextEncoder().encode(dr(l,"request")),tagLength:128},u,f);return{type:"encrypted_operation_request",...mc(l),...s===void 0?{}:{deadline_unix_ms:s},ciphertext:he(new Uint8Array(p))}}async function $e(t,e,n,i,o){if(!yc(i,o))throw new q("invalid_encrypted_response","Encrypted response metadata does not match its request.");let r=await ar(t,e,n.encryption.application_agreement_public_key),s={binding:n,protocolVersion:i.protocol_version,requestId:i.request_id,operation:i.operation,counter:i.counter},a=await cr(r.agreementPrivateKey,n,i.protocol_version,"response");try{let c=await crypto.subtle.decrypt({name:"AES-GCM",iv:ur(i.counter),additionalData:new TextEncoder().encode(dr(s,"response")),tagLength:128},a,pr(o.ciphertext)),l=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(c));if(l?.ok===!0&&"result"in l||l?.ok===!1&&ht(l.problem))return l;throw new Error("invalid response body")}catch(c){throw c instanceof q?c:new q("encrypted_response_rejected","The encrypted connector response could not be authenticated.")}}var q=class extends Error{constructor(n,i){super(i);this.code=n}code};async function sr(t){let e=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"]),n=he(new Uint8Array(await crypto.subtle.exportKey("raw",e.publicKey))),i=await crypto.subtle.exportKey("pkcs8",e.privateKey),o=await crypto.subtle.importKey("pkcs8",i,{name:"ECDH",namedCurve:"P-256"},!1,["deriveBits"]),r=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign","verify"]),s=he(new Uint8Array(await crypto.subtle.exportKey("raw",r.publicKey))),a=await crypto.subtle.exportKey("pkcs8",r.privateKey),c=await crypto.subtle.importKey("pkcs8",a,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]);return{handle:t,agreementPrivateKey:o,agreementPublicKey:n,signingPrivateKey:c,signingPublicKey:s}}async function ar(t,e,n){let i=await t.get(e);if(!i||i.agreementPublicKey!==n)throw new q("missing_grant_key","The encrypted grant key is unavailable or does not match the grant.");return i}async function hc(t,e,n){let i=await t.get(e);if(!i||i.signingPublicKey!==n)throw new q("missing_grant_key","The remote authority signing key is unavailable or does not match the grant.");return i}async function cr(t,e,n,i){let o=await St(t,e.encryption.connector_agreement_public_key),r=await crypto.subtle.importKey("raw",o,"HKDF",!1,["deriveKey"]),s=new TextEncoder().encode(lr(e,n)),a=await crypto.subtle.digest("SHA-256",s);return crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:a,info:new TextEncoder().encode(i==="request"?pc:fc)},r,{name:"AES-GCM",length:256},!1,i==="request"?["encrypt"]:["decrypt"])}async function St(t,e){try{let n=await crypto.subtle.importKey("raw",gc(Oi(e)),{name:"ECDH",namedCurve:"P-256"},!1,[]);return await crypto.subtle.deriveBits({name:"ECDH",public:n},t,256)}catch{throw new q("invalid_public_key","The connector relay public key is invalid.")}}function lr(t,e){let n=t.encryption;return["mdbase-connect",e,n.suite,t.grantId,t.applicationId,n.connector_id,n.collection_id,n.scope_epoch,n.key_id].join("|")}function dr(t,e){return[lr(t.binding,t.protocolVersion),t.requestId,e,t.operation,t.counter].join("|")}function mc(t){let e=t.binding.encryption;return{protocol_version:t.protocolVersion,suite:gt,request_id:t.requestId,grant_id:t.binding.grantId,application_id:t.binding.applicationId,connector_id:e.connector_id,collection_id:e.collection_id,operation:t.operation,scope_epoch:e.scope_epoch,key_id:e.key_id,counter:t.counter}}function yc(t,e){return e.type==="encrypted_operation_response"&&typeof e.ciphertext=="string"&&t.protocol_version===e.protocol_version&&t.suite===e.suite&&t.request_id===e.request_id&&t.grant_id===e.grant_id&&t.application_id===e.application_id&&t.connector_id===e.connector_id&&t.collection_id===e.collection_id&&t.operation===e.operation&&t.scope_epoch===e.scope_epoch&&t.key_id===e.key_id&&t.counter===e.counter}function ye(t){if(t.protocol_version!==Vt||t.suite!==gt||!Number.isSafeInteger(t.scope_epoch)||t.scope_epoch<=0||typeof t.key_id!="string"||t.key_id.length===0||t.key_id.length>200||t.key_id.includes("|"))throw new q("unsupported_encryption","The grant uses an unsupported relay encryption profile.");if(typeof t.connector_id!="string"||!ir.test(t.connector_id)||typeof t.collection_id!="string"||!ir.test(t.collection_id))throw new q("unsupported_encryption","The grant uses invalid encrypted relay identities.");Oi(t.application_agreement_public_key),Oi(t.connector_agreement_public_key)}function ur(t){let e=BigInt(t);if(e<=0n||e>Pi||e.toString()!==t)throw new q("invalid_counter","The encrypted relay counter is invalid.");let n=new Uint8Array(new ArrayBuffer(12));return new DataView(n.buffer).setBigUint64(4,e,!1),n}async function or(t){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return he(new Uint8Array(e))}function pr(t){if(!/^[A-Za-z0-9_-]+$/.test(t))throw new q("invalid_base64","Encrypted relay data is malformed.");return nn(t)}function Oi(t){let e=pr(t);if(e.length!==65||e[0]!==4)throw new q("invalid_public_key","Encrypted relay public keys must be uncompressed P-256 points.");return e}function gc(t){return Uint8Array.from(t).buffer}function bc(t){return new Promise((e,n)=>{t.onerror=()=>n(t.error),t.onsuccess=()=>e(t.result)})}function rr(t,e){return new Promise((n,i)=>{let o=t.transaction(Re,"readwrite"),r=e(o.objectStore(Re));r.onerror=()=>i(r.error),o.onerror=()=>i(o.error),o.onabort=()=>i(o.error??new Error("Grant key transaction aborted.")),o.oncomplete=()=>n()})}function Se(t){return{...t,credentials:"omit",targetAddressSpace:"loopback"}}async function Ot(){if(typeof navigator>"u"||!navigator.permissions?.query)return null;try{return(await navigator.permissions.query({name:"local-network-access"})).state}catch{return null}}async function Je(t){let{status:e}=t;return e===404||e===405||e===426||e>=500?!0:e===403&&(await t.clone().text()).trim()===""}function fr(t,e){return Z(t,e)}function hr(t,e){if(t.deadline_unix_ms===e)return t;let{deadline_unix_ms:n,...i}=t;return{...i,...e===void 0?{}:{deadline_unix_ms:e}}}function Pt(t){return[...new Set(t)]}function mr(t,e){return t.grantId||e.grantId?t.grantId===e.grantId&&t.keyHandle===e.keyHandle&&t.encryption?.key_id===e.encryption?.key_id:t.accessToken===e.accessToken}function Fe(t){if(t?.aborted)throw d("operation_cancelled","The operation was cancelled before it changed the collection.",{operationOutcome:"not_sent",cause:t.reason})}function rn(t,e,n,i){return t instanceof _?t:e?.aborted?n?J(n,t):e.reason instanceof _?e.reason:d("operation_cancelled","The operation was cancelled before it changed the collection.",{operationOutcome:"not_sent",cause:t}):n?J(n,t):t instanceof TypeError?d(i,i==="hosted_provider_unavailable"?"The hosted collection provider is unavailable.":"The Connect relay is unavailable.",{cause:t}):t instanceof Error?t:new Error(String(t))}function yr(t){return L(t.code==="unknown"?t.server_code:t.code,t.message,{details:t.details,operationOutcome:t.operation_outcome??"rejected",traceId:t.trace_id})}function gr(t,e,n,i,o){return fetch(t,{method:"POST",headers:{authorization:`Bearer ${e}`,"content-type":"application/json",...n},body:i,signal:o})}function Mi(t,e){return e?.aborted===!0||t instanceof _&&t.code==="operation_cancelled"}function br(t,e){if(e.dryRun!==!0||e.wouldRename!==!0||e.from!==t.from||e.to!==t.to)throw d("invalid_preflight","The rename preview does not match this mutation. Run the preview again.")}function _r(t,e){if(e.dryRun!==!0||e.wouldDelete!==!0||e.path!==t.path)throw d("invalid_preflight","The delete preview does not match this mutation. Run the preview again.")}function vr(t,e){if(t.updateRefs===!1)return{affectedRecords:0,totalUnits:1,warnings:0};let n=e.referencesAffected??[];return{affectedRecords:new Set(n.map(i=>i.path)).size,totalUnits:1+n.length,warnings:e.warnings?.length??0}}function Cr(t){return{affectedRecords:new Set((t.brokenLinks??[]).map(e=>e.path)).size,totalUnits:1,warnings:0}}async function wr(t,e){return vo(t,e??{})}function Rr(t){return JSON.stringify(Ti(t))}function Ti(t){return Array.isArray(t)?t.map(e=>Ti(e)):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[n])=>e<n?-1:e>n?1:0).map(([e,n])=>[e,Ti(n)])):t}function J(t,e){return d("operation_outcome_unknown","The write may have completed, but mdbase could not recover its authoritative result. Retry the exact same write to recover safely.",{operationOutcome:"unknown",details:{request_id:t},cause:e})}function sn(t,e){let n=F(t.getItem(`${e}:connections`));return n?.version===1&&Array.isArray(n.collectionIds)&&n.collectionIds.every(i=>typeof i=="string")?n.collectionIds:[]}function Sr(t,e,n){Pr(t,e,[...sn(t,e),n])}function Or(t,e,n){Pr(t,e,sn(t,e).filter(i=>i!==n))}function Pr(t,e,n){t.setItem(`${e}:connections`,JSON.stringify({version:1,collectionIds:[...new Set(n)]}))}function Ar(t,e){let n=t instanceof URL?t.href:t??vc(),i=typeof n=="string"?n:n.distribution==="portable"?`bundle:${n.id}:${wc(n)}`:`bundle:${n.id}`,o=e===void 0?typeof n!="string"&&n.distribution==="portable"?"":Cc():String(e);return{manifest:n,manifestSource:i,redirectUri:o}}async function ae(t,e,n,i){try{return await fetch(t,e)}catch(o){throw d(n,i,{cause:o})}}async function E(t,e,n){let i;try{i=await t.text()}catch(o){throw L(e,n,{status:t.status,cause:o})}if(i.trim()==="")throw L(e,n,{status:t.status});try{return JSON.parse(i)}catch(o){throw L(e,n,{status:t.status,cause:o})}}function Tr(t){let e=new URL(t);if(e.protocol!=="http:"||!["127.0.0.1","[::1]"].includes(e.hostname)||e.username||e.password||e.pathname!=="/"||e.search||e.hash)throw d("invalid_loopback_url","loopbackUrl must be an HTTP origin on 127.0.0.1 or ::1.");return e.origin}async function At(){let t=se(32),e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return{verifier:t,challenge:he(new Uint8Array(e))}}function z(t,e,n,i){return L(Tt(t)??t?.error?.code??e,t?.error_description??t?.error?.message??n,{status:i,details:t?.error?.details,operationOutcome:t?.error?.operation_outcome,traceId:t?.error?.trace_id})}function Tt(t){return typeof t?.error=="string"?t.error:void 0}function Mt(t,e){if(!t||typeof t!="object"||Array.isArray(t)||typeof e!="string")return!1;let n=t;if(typeof n.operations_url!="string"||typeof n.sync_url!="string"||typeof n.files_url!="string"||typeof n.replica_id!="string"||n.replica_id.length===0||typeof n.access_token!="string"||n.access_token.length===0||n.proof_public_key!==void 0&&(typeof n.proof_public_key!="string"||n.proof_public_key.length===0))return!1;try{let i=new URL(n.operations_url),o=new URL(n.sync_url),r=new URL(n.files_url);return[i,o,r].every(s=>(s.protocol==="https:"||s.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(s.hostname))&&!s.username&&!s.password&&!s.search&&!s.hash)&&/^\/v1\/authorities\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/operations$/i.test(i.pathname)&&/^\/v1\/authorities\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/sync$/i.test(o.pathname)&&/^\/v1\/authorities\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/files$/i.test(r.pathname)&&i.origin===o.origin&&i.origin===r.origin&&i.pathname.split("/")[3]===e&&o.pathname.split("/")[3]===e&&r.pathname.split("/")[3]===e}catch{return!1}}function Mr(t,e){return Mt({operations_url:t?.operationsUrl,sync_url:t?.syncUrl,files_url:t?.filesUrl,replica_id:t?.replicaId,access_token:t?.accessToken,proof_public_key:t?.proofPublicKey},e)}function an(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t,n=e.actions;if(e.kind!=="files"||e.protocol_version!==1||!Array.isArray(n)||n.length===0||n.length>6||new Set(n).size!==n.length||n.some(o=>!["list","read","add","replace","move","delete"].includes(o)))return!1;let i=e.scope;return!i||typeof i!="object"||Array.isArray(i)?!1:i.kind==="collection"?Object.keys(i).length===1:i.kind==="selected_folders"&&Object.keys(i).length===2&&Array.isArray(i.folders)&&i.folders.length>0&&i.folders.length<=100&&new Set(i.folders).size===i.folders.length&&i.folders.every(o=>typeof o=="string"&&o.length>0&&o.length<=1024&&_c(o))}function _c(t){let e=new Set([".mdbase",".git","node_modules","_contracts","_schemas","_types","_views"]);return!t.startsWith("/")&&!t.endsWith("/")&&!t.includes("\\")&&t.split("/").every(n=>{let i=n.split(".")[0]?.toUpperCase()??"";return n!==""&&n!=="."&&n!==".."&&!n.startsWith(".")&&!n.endsWith(" ")&&!n.endsWith(".")&&!/[<>:"|?*]/.test(n)&&!e.has(n.toLowerCase())&&!["CON","PRN","AUX","NUL"].includes(i)&&!/^(COM|LPT)[1-9]$/.test(i)})}function Ir(t,e){if(!t||typeof t!="object"||Array.isArray(t)||t.collection_id!==e)return!1;try{return ye(t),!0}catch{return!1}}function kr(t){if(typeof t?.device_code!="string"||typeof t?.user_code!="string"||typeof t?.verification_uri!="string"||typeof t?.verification_uri_complete!="string"||!Number.isFinite(t?.expires_in)||!Number.isFinite(t?.interval))throw d("invalid_device_authorization_response","Connect returned an invalid downloaded application authorization response.");return{userCode:t.user_code,verificationUri:t.verification_uri,verificationUriComplete:t.verification_uri_complete,expiresAt:Date.now()+Math.max(1,t.expires_in)*1e3,intervalSeconds:Math.max(1,t.interval)}}function F(t){if(!t)return null;try{return JSON.parse(t)}catch{return null}}function cn(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t;return e.access!=="contract"&&e.access!=="full_collection"||!Array.isArray(e.contracts)||e.contracts.some(n=>!n||typeof n!="object"||n.contract_type!=="record"||typeof n.id!="string"||typeof n.version!="string"||!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(n.version)||!/^sha256:[0-9a-f]{64}$/.test(n.digest)||!n.schema||typeof n.schema!="object"||Array.isArray(n.schema)||!Array.isArray(n.implementations)||n.implementations.some(i=>!i||typeof i!="object"||typeof i.type_name!="string"||!Number.isInteger(i.type_version)||!/^sha256:[0-9a-f]{64}$/.test(i.digest)||!i.fields||typeof i.fields!="object"||Array.isArray(i.fields)||Object.values(i.fields).some(o=>typeof o!="string")))?null:e}function ln(t){return t.access==="full_collection"&&t.contracts.length===0}function xr(t){return t.endsWith("/")?t.slice(0,-1):t}function vc(){if(typeof location>"u")throw d("manifest_required","manifest is required outside a browser environment.");if(location.origin==="null")throw d("manifest_required","Downloaded applications must provide their v1 portable manifest inline.");return new URL("/.well-known/mdbase-app.json",location.origin).href}function Cc(){if(typeof location>"u")throw d("redirect_uri_required","redirectUri is required outside a browser environment.");return location.href.split(/[?#]/)[0]}function Ii(){if(typeof location>"u")return"null";let t=new URL(location.href);return["chrome-extension:","moz-extension:"].includes(t.protocol)?`${t.protocol}//${t.host}`:["http:","https:"].includes(t.protocol)?t.origin:"null"}function Er(t,e,n,i){if(typeof t!="string"&&t.distribution==="portable"||i)return Ii();let o=new URL(n);if(["http:","https:"].includes(o.protocol))return o.origin;if(typeof location<"u")return location.origin;if(typeof t!="string")return new URL(t.homepage).origin;try{return new URL(e).origin}catch{return""}}function qr(t){let e=":token:",n=t.lastIndexOf(e);return n<0?"":t.slice(n+e.length)}function dn(){if(typeof location>"u")throw d("callback_url_required","callbackUrl is required outside a browser environment.");return location.href}function Fr(t){if(t)return new Ye;if(typeof localStorage>"u")throw d("storage_required","storage is required outside a browser environment.");try{let e=`mdbase-connect:probe:${se(8)}`;return localStorage.setItem(e,"1"),localStorage.removeItem(e),localStorage}catch{return new Ye}}var Ye=class{values=new Map;get length(){return this.values.size}clear(){this.values.clear()}getItem(e){return this.values.get(e)??null}key(e){return[...this.values.keys()][e]??null}removeItem(e){this.values.delete(e)}setItem(e,n){this.values.set(String(e),String(n))}};function Dr(t){return typeof t=="string"||t.distribution!=="portable"?!1:typeof location>"u"||location.origin==="null"||!["http:","https:"].includes(location.protocol)}function wc(t){let e=Rr(t),n=2166136261,i=2654435769;for(let o=0;o<e.length;o+=1){let r=e.charCodeAt(o);n=Math.imul(n^r,16777619),i=Math.imul(i^r,2246822507)}return`${(n>>>0).toString(16).padStart(8,"0")}${(i>>>0).toString(16).padStart(8,"0")}`}async function zr(t,e){let n=await fetch(`${t}/health`,{signal:e,cache:"no-store"}),i=await n.json().catch(()=>null);if(!n.ok||!Array.isArray(i?.capabilities)||!i.capabilities.every(o=>typeof o=="string")||!i.capabilities.includes(oo))throw d("capability_contract_incompatible","This server does not support new version-2 application authorizations.",{details:{contract:"fresh_application_authorization",required:[2],supported:[],peer:"server"}})}function It(t){let e="bundle:";if(!t.startsWith(e)||t.length===e.length)throw new Error("The registered application has no valid declaration identity.");return t.slice(e.length)}function Xe(t,e,n){return t.reason instanceof _?t.reason:d("authorization_cancelled",e,{cause:n})}function kt(t){for(let e of["code","state","error","error_description"])t.searchParams.delete(e);return t}function un(t){let e;try{e=new URL(t)}catch{return!1}return e.searchParams.has("state")&&(e.searchParams.has("code")||e.searchParams.has("error"))}function pn(t){try{let e=new URL(t).searchParams.get("state");return e&&e.length>0?e:null}catch{return null}}function Lr(t){if(!t.details||typeof t.details!="object"||Array.isArray(t.details))return;let e=t.details.return_to;return typeof e=="string"?e:void 0}var Ze=class{constructor(e,n){this.connect=e;this.operations=Pt(n.operations??Ee),this.selection=n.selection,this.autoSelect=n.autoSelect??"only",this.snapshot={status:"not_started",connections:[]}}connect;operations;selection;autoSelect;listeners=new Set;snapshot;snapshotKey="";stopConnections;stopSelection;stopActiveConnection;activeCollectionId=null;unavailableReason="not_authorized";started=!1;destroyed=!1;refreshing=!1;refreshQueued=!1;transactionDepth=0;lifecycleGeneration=0;operationControllers=new Set;startOperation=null;callbackCompletions=new Map;start(e){if(this.destroyed)return Promise.resolve(g(w("session_destroyed","This session has been destroyed.")));if(this.started&&!this.startOperation)return Promise.resolve(R(this.snapshot));let n=this.startOperation??this.beginStart();return this.waitForStart(n,e)}beginStart(){let e=new AbortController,n=++this.lifecycleGeneration;this.publish({status:"starting",connections:this.connect.connections()});let i={promise:this.performStart({signal:e.signal,timeoutMs:null},n),controller:e,waiters:0,generation:n};this.startOperation=i;let o=()=>{this.startOperation===i&&(this.startOperation=null)};return i.promise.then(o,o),i}async waitForStart(e,n){e.waiters+=1;try{return await k(n,Ci,()=>e.promise)}catch(i){if(i instanceof _)return g(i.problem);throw i}finally{e.waiters-=1,e.waiters===0&&this.startOperation===e&&(e.controller.abort(),this.startOperation=null,this.lifecycleGeneration+=1,this.stopLifecycleSubscriptions(),this.started=!1,this.publish({status:"not_started",connections:this.connect.connections()}))}}async performStart(e,n){try{this.started=!0,this.stopConnections=this.connect.onConnectionsChange(()=>this.refresh()),this.stopSelection=this.selection.subscribe(()=>{this.unavailableReason="not_authorized",this.refresh()});let i=this.selection.authorizationCallback();if(i){let o=await this.completeAuthorizationCallback(i,e);if(!o.ok)return n===this.lifecycleGeneration&&!this.destroyed&&(this.stopLifecycleSubscriptions(),this.started=!1,this.publish({status:"start_failed",problem:o.problem,connections:this.connect.connections()})),o}else this.autoSelectOnlyConnection();return n!==this.lifecycleGeneration||this.destroyed?g(w("session_destroyed","This session has been destroyed.")):(this.publishCurrent(),R(this.snapshot))}catch(i){if(i instanceof _){let o=i.problem;return n===this.lifecycleGeneration&&!this.destroyed&&(this.stopLifecycleSubscriptions(),this.started=!1,this.publish({status:"start_failed",problem:o,connections:this.connect.connections()})),g(o)}throw n===this.lifecycleGeneration&&!this.destroyed&&(this.stopLifecycleSubscriptions(),this.started=!1,this.publish({status:"not_started",connections:this.connect.connections()})),i}}destroy(){if(!this.destroyed){this.lifecycleGeneration+=1,this.startOperation?.controller.abort(),this.startOperation=null;for(let e of this.operationControllers)e.abort();this.operationControllers.clear(),this.stopLifecycleSubscriptions(),this.started=!1,this.destroyed=!0,this.callbackCompletions.clear(),this.publish({status:"destroyed",connections:[]}),this.listeners.clear()}}stopLifecycleSubscriptions(){this.stopConnections?.(),this.stopSelection?.(),this.stopActiveConnection?.(),this.stopConnections=void 0,this.stopSelection=void 0,this.stopActiveConnection=void 0,this.activeCollectionId=null}getSnapshot(){return this.snapshot}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}select(e,n={}){let i=this.lifecycleProblem();if(i)return g(i);let o=this.connect.connection(e);return o?(this.unavailableReason="not_authorized",this.selection.select(e,n),this.refresh(),R(o)):g(w("unknown_collection","This collection is not authorized for this application."))}clearSelection(e={}){let n=this.lifecycleProblem();return n?g(n):(this.unavailableReason="not_authorized",this.selection.select(null,e),this.refresh(),R(void 0))}forget(e){let n=this.lifecycleProblem();if(n)return g(n);this.transactionDepth+=1;try{let i=this.selection.selectedCollectionId()===e;this.connect.connection(e)?.forget(),i&&this.selection.select(null,{history:"replace"})}finally{this.transactionDepth-=1,this.refresh()}return R(void 0)}async authorize(e,n={}){let i=this.lifecycleProblem();if(i)return g(i);let o=this.selection.selectedCollectionId();if(e==="selected"&&!o)return g(w("collection_not_selected","Choose a collection before updating its access."));let r=typeof e=="object"?e.collectionId:e==="selected"?o:null,s=this.beginLifecycleOperation(n);this.transactionDepth+=1;try{let a=await this.connect.manifest?.(s.options);if(a&&!a.ok)return a;if(!this.lifecycleCurrent(s.generation))return this.destroyedOutcome(R(void 0));let c=a?V(a.value.requirements):1,l=await this.connect.authorize({...s.options,...c===1&&n.operations===void 0&&n.capabilities===void 0?{operations:this.operations}:{},target:r===null?{kind:"choose"}:{kind:"collection",collectionId:r},returnTo:this.selection.authorizationReturnTo()});return this.lifecycleCurrent(s.generation)?(l.ok&&l.value.kind==="connected"&&this.selection.finishAuthorization(l.value.returnTo,l.value.connection.collectionId),l):this.destroyedOutcome(l)}finally{s.dispose(),this.transactionDepth-=1,this.refresh()}}ensureOperations(e,n){return this.ensureAuthorization({operations:e},n)}ensureCapabilities(e,n){return this.ensureAuthorization({capabilities:e},n)}async ensureAuthorization(e,n){let i=this.lifecycleProblem();if(i)return g(i);let o=this.snapshot;if(o.status!=="ready")return g(w("collection_not_ready","Choose an authorized collection first."));let r=this.beginLifecycleOperation(n);this.transactionDepth+=1;try{let s=await this.connect.manifest?.(r.options);if(s&&!s.ok)return s;if(!this.lifecycleCurrent(r.generation))return this.destroyedOutcome(R(void 0));let a=s?.value.requirements??("operations"in e?{access:"full_collection",contracts:[]}:{access:"full_collection",contracts:[],capabilities:{contract_version:2,required:[],optional:Object.keys(zt)}});re(a,{...n,...e});let c="operations"in e?e.operations:e.capabilities.flatMap(p=>X(V(a),p)??[]),l=o.connection.authorizationCapabilities(c);if(l.sufficient)return R({kind:"unchanged",connection:o.connection});let u="operations"in e||V(a)===1?{operations:Pt([...l.grantedOperations,...c])}:{capabilities:[...new Set([...Yt(a,l.grantedOperations),...e.capabilities])]},f=await this.connect.authorize({...r.options,...u,target:{kind:"collection",collectionId:o.collectionId},returnTo:this.selection.authorizationReturnTo()});return this.lifecycleCurrent(r.generation)?(f.ok&&f.value.kind==="connected"&&this.selection.finishAuthorization(f.value.returnTo,f.value.connection.collectionId),f):this.destroyedOutcome(f)}catch(s){if(s instanceof _)return g(s.problem);throw s}finally{r.dispose(),this.transactionDepth-=1,this.refresh()}}handleAuthorizationCallback(e,n){let i=this.lifecycleProblem();return i?Promise.resolve(g(i)):un(e)?this.completeAuthorizationCallback(e,n):Promise.resolve(g(w("invalid_callback","This URL is not an authorization callback.")))}completeAuthorizationCallback(e,n){if(n?.signal?.aborted){let r=te(n.signal);return Promise.resolve(g(r.problem))}let i=pn(e);if(!i)return Promise.resolve(g(w("invalid_callback","Authorization callback is missing its state.")));let o=this.callbackCompletions.get(i)??this.beginCallbackCompletion(e,i);return this.waitForCallbackCompletion(o,n)}beginCallbackCompletion(e,n){let i=new AbortController,o=this.lifecycleGeneration;this.transactionDepth+=1,this.operationControllers.add(i);let r={state:n,controller:i,waiters:0,settled:!1,abandoned:!1,promise:void 0},s=this.connect.completeAuthorization(e,{signal:i.signal,timeoutMs:null}).catch(a=>{if(a instanceof _)return g(a.problem);throw a});return r.promise=s.then(a=>{if(o!==this.lifecycleGeneration||this.destroyed)return this.destroyedOutcome(a);if(!a.ok){if(!r.abandoned&&a.problem.recovery!=="retry"){let l=Lr(a.problem);this.selection.clearAuthorizationCallback(l)}return this.refresh(),a}let c=a.value;return this.unavailableReason="not_authorized",this.selection.finishAuthorization(c.returnTo,c.connection.collectionId),this.refresh(),R(c.connection,a.diagnostics)}).catch(a=>{if(o!==this.lifecycleGeneration||this.destroyed)return g(w("session_destroyed","This session was destroyed before authorization completion finished."));throw r.abandoned||(this.selection.clearAuthorizationCallback(),this.refresh()),a}).finally(()=>{r.settled=!0,this.operationControllers.delete(i),this.transactionDepth-=1,this.refresh(),this.callbackCompletions.get(n)===r&&this.callbackCompletions.delete(n)}),this.callbackCompletions.set(n,r),r}async waitForCallbackCompletion(e,n){e.waiters+=1;try{return await k(n,Qe,()=>e.promise)}catch(i){if(i instanceof _)return g(i.problem);throw i}finally{e.waiters-=1,e.waiters===0&&!e.settled&&this.callbackCompletions.get(e.state)===e&&(e.abandoned=!0,this.callbackCompletions.delete(e.state),e.controller.abort())}}lifecycleProblem(){return this.destroyed?w("session_destroyed","This session has been destroyed."):this.snapshot.status==="starting"?w("session_starting","The session is still starting."):this.snapshot.status==="start_failed"?this.snapshot.problem:this.started?null:w("session_not_started","Start the session before using it.")}beginLifecycleOperation(e={}){let n=new AbortController,i=()=>n.abort(e.signal?.reason);return e.signal?.aborted?i():e.signal?.addEventListener("abort",i,{once:!0}),this.operationControllers.add(n),{generation:this.lifecycleGeneration,options:{...e,signal:n.signal},dispose:()=>{e.signal?.removeEventListener("abort",i),this.operationControllers.delete(n)}}}lifecycleCurrent(e){return!this.destroyed&&e===this.lifecycleGeneration}destroyedOutcome(e){return!e.ok&&e.problem.code==="operation_outcome_unknown"?e:g(w("session_destroyed","This session was destroyed before the operation finished."))}autoSelectOnlyConnection(){if(this.autoSelect!=="only"||this.selection.selectedCollectionId())return;let e=this.connect.connections();e.length===1&&this.selection.select(e[0].collectionId,{history:"replace"})}refresh(){if(!(!this.started||this.destroyed||this.snapshot.status==="starting"||this.snapshot.status==="start_failed")){if(this.transactionDepth>0){this.refreshQueued=!0;return}if(this.refreshing){this.refreshQueued=!0;return}this.refreshing=!0;try{do this.refreshQueued=!1,this.publishCurrent();while(this.refreshQueued)}finally{this.refreshing=!1}}}publishCurrent(){let e=this.selection.selectedCollectionId(),n=this.connect.connections(),i=e?this.connect.connection(e):null;i?.collectionId!==this.activeCollectionId&&(this.stopActiveConnection?.(),this.activeCollectionId=i?.collectionId??null,this.stopActiveConnection=i?.onConnectionChange(r=>{!r&&this.selection.selectedCollectionId()===i.collectionId&&(this.unavailableReason="authorization_lost"),this.refresh()}));let o;if(!e)o={status:"unselected",connections:n};else if(!i||!i.info())o={status:"unavailable",collectionId:e,reason:this.connect.unavailableReason(e)??this.unavailableReason,connections:n};else{let r=i.info();o={status:"ready",collectionId:e,connection:i,info:r,access:i.authorizationCapabilities(this.operations),connections:n}}this.publish(o)}publish(e){if(this.snapshot.status==="destroyed"&&e.status!=="destroyed")return;let n=Rc(e);if(n!==this.snapshotKey){this.snapshot=e,this.snapshotKey=n;for(let i of this.listeners)i()}}};function Rc(t){return t.status==="not_started"||t.status==="starting"||t.status==="destroyed"?JSON.stringify(t):t.status==="start_failed"?JSON.stringify({status:t.status,problem:t.problem,connections:t.connections}):t.status==="unselected"?JSON.stringify({status:t.status,connections:t.connections}):t.status==="unavailable"?JSON.stringify({status:t.status,collectionId:t.collectionId,reason:t.reason,connections:t.connections}):JSON.stringify({status:t.status,collectionId:t.collectionId,info:t.info,access:t.access,connections:t.connections})}var Et=class{values=new Map;read(e){return this.values.get(e)??null}write(e,n){this.values.set(e,n)}remove(e){this.values.delete(e)}},et=class{constructor(e,n,i=Ve()){this.connect=e;this.options=n;this.timeouts=i;this.verificationStore=n.verificationStore??Ac()}connect;options;timeouts;listeners=new Set;verificationStore;snapshot={status:"not_started",connections:[]};manifest=null;application=null;base=null;stopBase;setupAssessment=null;setupTypePackAdoptions=null;verificationGeneration=0;readinessController;lifecycleGeneration=0;operationControllers=new Set;startOperation=null;start(e){if(this.snapshot.status==="destroyed")return Promise.resolve(g(w("session_destroyed","This application session has been destroyed.")));if(this.base&&!this.startOperation)return Promise.resolve(R(this.snapshot));let n=this.startOperation??this.beginStart();return this.waitForStart(n,e,this.timeouts.watchStartMs)}async waitForStart(e,n,i){e.waiters+=1;try{return await k(n,i,()=>e.promise)}catch(o){if(o instanceof _)return g(o.problem);throw o}finally{e.waiters-=1,e.waiters===0&&this.startOperation===e&&this.abandonStart(e)}}abandonStart(e){e.controller.abort(),this.readinessController?.abort(),this.startOperation=null,this.lifecycleGeneration+=1,this.verificationGeneration+=1,this.base&&this.cleanupBase(this.base),this.application=null,this.manifest=null,this.setupAssessment=null,this.setupTypePackAdoptions=null,this.publish({status:"not_started",connections:this.connect.connections()})}beginStart(){this.publish({status:"starting",connections:this.connect.connections()});let e=new AbortController,n=++this.lifecycleGeneration,i={promise:this.startWithinBudget({signal:e.signal,timeoutMs:null},n),controller:e,waiters:0,generation:n};this.startOperation=i;let o=()=>{this.startOperation===i&&(this.startOperation=null)};return i.promise.then(o,o),i}async startWithinBudget(e,n){try{return await this.performStartWithinBudget(e,n)}catch(i){if(i instanceof _)return this.startFailure(i.problem,n);throw n===this.lifecycleGeneration&&(this.verificationGeneration+=1,this.base&&this.cleanupBase(this.base),this.application=null,this.manifest=null,this.setupAssessment=null,this.setupTypePackAdoptions=null,this.publish({status:"not_started",connections:this.connect.connections()})),i}}async performStartWithinBudget(e,n){let i=await Ct("registration",()=>this.connect.register(e));if(!i.ok)return this.startFailure(i.problem,n);let o=await this.connect.manifest(e);if(!o.ok)return this.startFailure(o.problem,n);if(o.value.requirements?.access!=="full_collection")return this.startFailure(w("invalid_application_manifest","Application sessions require explicit full_collection access.",{details:{issues:[{path:"/requirements/access",keyword:"const",message:"must be full_collection",params:{allowedValue:"full_collection"}}]}}),n);let r=o.value.requirements.capabilities;if(!r)return this.startFailure(w("invalid_application_manifest","Application sessions require a versioned semantic capability contract.",{details:{issues:[{path:"/requirements/capabilities",keyword:"required",message:"is required for application sessions",params:{}}]}}),n);if(n!==this.lifecycleGeneration||e.signal?.aborted)return g(w("operation_cancelled","Application session startup was cancelled.",{operationOutcome:"not_sent"}));this.application=i.value,this.manifest=o.value;let s=new Ze(this.connect,{selection:this.options.selection,autoSelect:this.options.autoSelect,operations:Sc(r,o.value)});this.base=s;try{let a=await s.start(e);return a.ok?n!==this.lifecycleGeneration||e.signal?.aborted?(this.cleanupBase(s),g(w("operation_cancelled","Application session startup was cancelled.",{operationOutcome:"not_sent"}))):(this.stopBase=s.subscribe(()=>{this.base===s&&this.refresh()}),await this.refresh(!0,e),n!==this.lifecycleGeneration||e.signal?.aborted?(this.cleanupBase(s),g(w("operation_cancelled","Application session startup was cancelled.",{operationOutcome:"not_sent"}))):R(this.snapshot)):(this.cleanupBase(s),this.startFailure(a.problem,n))}catch(a){throw this.cleanupBase(s),a}}startFailure(e,n){return n===this.lifecycleGeneration&&this.publish({status:"start_failed",problem:e,connections:this.connect.connections()}),g(e)}destroy(){if(this.snapshot.status!=="destroyed"){this.lifecycleGeneration+=1,this.verificationGeneration+=1,this.readinessController?.abort(),this.startOperation?.controller.abort(),this.startOperation=null;for(let e of this.operationControllers)e.abort();this.operationControllers.clear(),this.base&&this.cleanupBase(this.base),this.application=null,this.manifest=null,this.setupAssessment=null,this.setupTypePackAdoptions=null,this.publish({status:"destroyed",connections:[]}),this.listeners.clear()}}cleanupBase(e){this.base===e&&(this.stopBase?.(),this.stopBase=void 0,e.destroy(),this.base=null)}getSnapshot(){return this.snapshot}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}connection(){let e=this.base?.getSnapshot();return e?.status==="ready"?e.connection:null}select(e,n={}){let i=this.lifecycleBase();return i.ok?i.value.select(e,n):i}clearSelection(e={}){let n=this.lifecycleBase();return n.ok?(n.value.clearSelection(e),R(void 0)):n}forget(e){let n=this.lifecycleBase();return n.ok?(n.value.forget(e),R(void 0)):n}authorize(e,n={}){return this.withLifecycleBase(n,async(i,o,r)=>{let s=await i.authorize(e,{...n,...o});return s.ok&&s.value.kind==="connected"&&this.lifecycleCurrent(r)&&await this.refresh(!0,o),s})}handleAuthorizationCallback(e,n){let i=String(e),o=this.startOperation!==null&&this.options.selection.authorizationCallback()===i;return this.withLifecycleBase(n,async(r,s,a)=>{if(o){let l=r.getSnapshot();return l.status==="ready"?R(l.connection):g(w("collection_not_ready","Authorization did not produce a ready collection."))}let c=await r.handleAuthorizationCallback(i,s);return c.ok&&this.lifecycleCurrent(a)&&await this.refresh(!0,s),c})}completeAuthorization(e,n){let i=e===void 0?dn():String(e),o=this.startOperation!==null&&this.options.selection.authorizationCallback()===i;return this.withLifecycleBase(n,async(r,s,a)=>{if(o){let l=r.getSnapshot();return l.status==="ready"?R(l.connection):g(w("collection_not_ready","Authorization did not produce a ready collection."))}let c=await r.handleAuthorizationCallback(i,s);return c.ok&&this.lifecycleCurrent(a)&&await this.refresh(!0,s),c})}ensureCapabilities(e,n){return this.withLifecycleBase(n,(i,o,r)=>{re(this.manifest.requirements,{...n,capabilities:e});let s=this.manifest.requirements?.capabilities,a=new Set([...s?.required??[],...s?.optional??[]]);return e.some(c=>!a.has(c))?Promise.resolve(g(w("invalid_application_manifest","Applications may only request capabilities declared in their manifest.",{details:{issues:[{path:"/requirements/capabilities",keyword:"undeclaredCapability",message:"must declare every capability requested by the application",params:{requested:e,declared:[...a]}}]}}))):i.ensureCapabilities(e,o).then(async c=>(c.ok&&c.value.kind==="connected"&&this.lifecycleCurrent(r)&&await this.refresh(!0,o),c))})}ensureOperations(e,n){return this.withLifecycleBase(n,async(i,o,r)=>{re(this.manifest.requirements,{...n,operations:e});let s=await i.ensureOperations(e,o);return s.ok&&s.value.kind==="connected"&&this.lifecycleCurrent(r)&&await this.refresh(!0,o),s})}applyCollectionSetup(e){return this.withLifecycleBase(e,(n,i,o)=>this.applyCollectionSetupStarted(i,o))}async applyCollectionSetupStarted(e,n){if(this.snapshot.status!=="setup_review_required"||!this.setupAssessment)return g(w("collection_not_ready","There is no reviewed collection setup to apply."));if(!this.setupAssessment.applicable)return g(w("collection_not_ready","Resolve the collection setup conflicts before applying this update."));let i=this.connection();if(!i)return g(w("collection_not_ready","The collection is not ready."));let o=this.verificationGeneration,r=this.setupAssessment,s={...this.collectionSetupInput(this.setupTypePackAdoptions??void 0),expectedAssessmentDigest:r.assessmentDigest,expectedCollectionRevision:r.collectionRevision,expectedProvisionDigest:r.provisionDigest,allowTypePackDowngrades:r.typePacks.filter(c=>c.status==="downgrade").map(c=>c.desired.id)},a=await i.applyCollectionSetup(s,e);return this.lifecycleCurrent(n)?o!==this.verificationGeneration||this.connection()!==i?g(w("collection_not_ready","The selected collection changed during setup.")):a.ok?(this.setupAssessment=null,this.setupTypePackAdoptions=null,await this.verifySetup(this.context(i),++this.verificationGeneration,e),R(this.snapshot)):(a.problem.code==="application_declaration_mismatch"&&(this.setupAssessment=null,this.setupTypePackAdoptions=null,this.publish({status:"authorization_required",...this.context(i)})),a):!a.ok&&a.problem.code==="operation_outcome_unknown"?g(a.problem):g(w("session_destroyed",xt("session_destroyed")))}async refresh(e=!1,n){if(!this.base||!this.manifest)return;let i=this.base.getSnapshot();this.readinessController?.abort(),this.verificationGeneration+=1;let o=this.verificationGeneration;if(this.setupAssessment=null,this.setupTypePackAdoptions=null,i.status==="unselected"){this.publish({status:"unselected",connections:i.connections});return}if(i.status==="unavailable"){this.publish(i);return}if(i.status!=="ready")return;let r=this.context(i.connection);if(this.connect.connectionApplicationId(i.collectionId)!==this.application?.id){this.publish({status:"authorization_required",...r});return}if(!r.capabilities.requiredAvailable||r.readiness?.files.state==="requires_authorization"||!Zo(this.manifest,r.info)){this.publish({status:"authorization_required",...r});return}if(!((this.manifest.provisions?.type_packs.length??0)>0||(this.manifest.provisions?.configuration?.length??0)>0)){let l=this.publishReady(r,o,n);e&&await l;return}let a=Zt(this.manifest,i.collectionId);r.readiness?.contracts.state!=="checking"&&this.verificationStore.read(a)===Ri(this.manifest)?this.publish({status:"ready",verification:"cached",...r}):this.publish({status:"checking_setup",...r});let c=this.verifySetup(r,o,n);e&&await c}async verifySetup(e,n,i){let o=this.connection(),r=this.requireManifest();if(!o||o.collectionId!==e.collectionId)return;let s=this.collectionSetupInput(),a=r.requirements?.contracts??[],c=new AbortController;this.readinessController?.abort(),this.readinessController=c;let l=null,u=e.readiness&&a.length?wi({...e,readiness:e.readiness,contracts:a,connection:o,controller:c,options:i,requestMs:this.timeouts.requestMs,isCurrent:()=>n===this.verificationGeneration&&this.connection()===o,publish:m=>{l={...m,...e}}}):Promise.resolve(!0),f=()=>c.abort(i?.signal?.reason);i?.signal?.aborted?f():i?.signal?.addEventListener("abort",f,{once:!0});let p,h;try{[p,h]=await Promise.all([Ct("setup-assessment",()=>o.assessCollectionSetup(s,{...i,signal:c.signal})),u])}catch(m){if(n!==this.verificationGeneration&&c.signal.aborted&&(m===c.signal.reason||m instanceof _&&m.code==="operation_cancelled"))return;throw m}finally{i?.signal?.removeEventListener("abort",f),c.abort(),this.readinessController===c&&(this.readinessController=void 0)}if(n===this.verificationGeneration){if(!p.ok){this.publish(p.problem.code==="application_declaration_mismatch"?{status:"authorization_required",...e}:{status:"blocked",problem:p.problem,...e});return}if(!p.value.applicable){let m=er(p.value);if(Object.keys(m).length>0){if(p=i?await o.assessCollectionSetup(this.collectionSetupInput(m),i):await o.assessCollectionSetup(this.collectionSetupInput(m)),n!==this.verificationGeneration)return;if(!p.ok){this.publish(p.problem.code==="application_declaration_mismatch"?{status:"authorization_required",...e}:{status:"blocked",problem:p.problem,...e});return}this.setupTypePackAdoptions=m}}if(n===this.verificationGeneration){if(p.value.status!=="current"){this.setupAssessment=p.value,this.verificationStore.remove(Zt(r,e.collectionId)),this.publish({status:"setup_review_required",update:Pc(p.value,r.provisions?.type_packs??[]),...e});return}if(this.verificationStore.write(Zt(r,e.collectionId),Ri(r)),e.readiness&&(e.readiness.setup={state:"current",evidence:[{source:"authority",fact:"Collection setup assessment is current."}]}),!h){l&&this.publish(l);return}await this.publishReady(e,n,i,!0)}}}async publishReady(e,n,i,o=!1){let r=this.requireManifest().requirements?.contracts??[];if(!o&&e.readiness&&r.length){let s=this.connection();if(!s||s.collectionId!==e.collectionId)return;this.publish({status:"checking_setup",...e});let a=new AbortController;this.readinessController?.abort(),this.readinessController=a;try{if(!await wi({...e,readiness:e.readiness,contracts:r,connection:s,controller:a,options:i,requestMs:this.timeouts.requestMs,isCurrent:()=>n===this.verificationGeneration&&this.connection()===s,publish:c=>this.publish({...c,...e})}))return}finally{this.readinessController===a&&(this.readinessController=void 0)}}n===this.verificationGeneration&&this.publish({status:"ready",verification:"verified",...e})}collectionSetupInput(e){let n=this.requireManifest(),i=this.requireApplication();return tr(n,It(i.family_identity),`sha256:${i.manifest_digest}`,e)}context(e){return Xo(this.requireManifest(),e.collectionId,e.info(),this.connect.connections())}publish(e){if(!(this.snapshot.status==="destroyed"&&e.status!=="destroyed")&&("readiness"in e&&e.readiness&&(e={...e,readiness:Yo(e.readiness,e.status,e.status==="ready"?e.verification:void 0)}),JSON.stringify(this.snapshot)!==JSON.stringify(e))){this.snapshot=e;for(let n of this.listeners)n()}}lifecycleBase(){let e=this.snapshot.status;if(this.startOperation||e==="starting")return g(w("session_starting","The application session is still starting."));if(this.snapshot.status==="start_failed")return g(this.snapshot.problem);if(this.base)return R(this.base);let n=e==="destroyed"?"session_destroyed":"session_not_started";return g(w(n,xt(n)))}async withLifecycleBase(e,n){let i=this.beginLifecycleOperation(e),o=ve(i.options,this.timeouts.requestMs),r={signal:o.signal,timeoutMs:null};try{let s=this.startOperation;if(s){let l=await this.waitForStart(s,r,null);if(!l.ok)return l}if(!this.lifecycleCurrent(i.generation))return g(w("session_destroyed",xt("session_destroyed")));let a=this.lifecycleBase();if(!a.ok)return a;let c=await n(a.value,r,i.generation);return this.lifecycleCurrent(i.generation)?c:this.destroyedOutcome(c)}catch(s){if(s instanceof _)return this.lifecycleCurrent(i.generation)?g(s.problem):s.problem.code==="operation_outcome_unknown"?g(s.problem):g(w("session_destroyed",xt("session_destroyed")));throw s}finally{o.dispose(),i.dispose()}}beginLifecycleOperation(e={}){let n=new AbortController,i=()=>n.abort(e.signal?.reason);return e.signal?.aborted?i():e.signal?.addEventListener("abort",i,{once:!0}),this.operationControllers.add(n),{generation:this.lifecycleGeneration,options:{...e,signal:n.signal},dispose:()=>{e.signal?.removeEventListener("abort",i),this.operationControllers.delete(n)}}}lifecycleCurrent(e){return this.snapshot.status!=="destroyed"&&e===this.lifecycleGeneration}destroyedOutcome(e){return!e.ok&&e.problem.code==="operation_outcome_unknown"?e:g(w("session_destroyed",xt("session_destroyed")))}requireManifest(){if(!this.manifest)throw new Error("Start the application session before using it.");return this.manifest}requireApplication(){if(!this.application)throw new Error("Start the application session before using it.");return this.application}};function Sc(t,e){let n=(e.provisions?.type_packs.length??0)>0||(e.provisions?.configuration?.length??0)>0;return[...Jo(e.requirements),...t.contract_version===2&&n?Lt:[]]}function Oc(t,e){let n=e.status==="conflict"?"Existing user-owned resources conflict with this application definition pack.":e.status==="install"?"This collection needs the application definitions installed.":`This collection has a ${e.status} definition change to review.`;return{id:e.desired.id,name:t.manifest.name??e.desired.id,status:e.status,applicable:e.applicable,assessmentDigest:e.assessmentDigest,...e.current?{currentVersion:e.current.version}:{},desiredVersion:e.desired.version,resources:e.resources,contractSetups:e.contractSetups,canApply:e.applicable,reason:n}}function Pc(t,e){let n=t.typePacks.map(r=>{let s=e.find(a=>a.manifest.id===r.desired.id);if(!s)throw new Error(`Collection setup returned undeclared type pack '${r.desired.id}'.`);return Oc(s,r)}),i=t.configuration.filter(r=>r.action!=="current").length,o=t.status==="conflict"?"Existing collection policy conflicts with this application's required setup.":`This application requires ${i} configuration change${i===1?"":"s"} and ${n.length} definition update${n.length===1?"":"s"}.`;return{status:t.status,applicable:t.applicable,assessmentDigest:t.assessmentDigest,collectionRevision:t.collectionRevision,provisionDigest:t.provisionDigest,configuration:t.configuration,typePacks:n,canApply:t.applicable,reason:o}}function xt(t){return t==="session_destroyed"?"This application session has been destroyed.":t==="session_starting"?"The application session is still starting.":"Start the application session before using it."}function Ac(){return typeof localStorage<"u"?{read:t=>localStorage.getItem(t),write:(t,e)=>localStorage.setItem(t,e),remove:t=>localStorage.removeItem(t)}:new Et}var Tc="mdbase-connect-identities",tt="application-identities",ki=BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Mc=ki/2n,nt=class{database=null;async create(e){let n=await Nr(e),i=await this.open();return await Ur(i,o=>o.add(n)),n}async get(e){let n=await this.open();return await Ic(n.transaction(tt).objectStore(tt).get(e))??null}async delete(e){let n=await this.open();await Ur(n,i=>i.delete(e))}open(){if(typeof indexedDB>"u")throw new De("Persistent application identity requires browser IndexedDB or an injected identity store.");return this.database||(this.database=new Promise((e,n)=>{let i=indexedDB.open(Tc,1);i.onupgradeneeded=()=>{i.result.objectStoreNames.contains(tt)||i.result.createObjectStore(tt,{keyPath:"handle"})},i.onerror=()=>n(i.error),i.onsuccess=()=>e(i.result)})),this.database}},it=class{records=new Map;async create(e){if(this.records.has(e))throw new Error(`Application identity already exists: ${e}`);let n=await Nr(e);return this.records.set(e,n),n}async get(e){return this.records.get(e)??null}async delete(e){this.records.delete(e)}},De=class extends Error{constructor(e){super(e),this.name="ApplicationIdentityStoreError"}};async function ot(t){return Oo(t.signingPublicKey)}async function qt(t,e){if(t.installation_signing_public_key!==e.signingPublicKey||t.application_installation_id!==await ot(e))throw new Error("Application authorization identity does not match its binding.");let n=xc(new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},e.signingPrivateKey,Po(t))));return{binding:t,signature:jr(n)}}async function fn(t,e,n){let i=`application-installation:v2:${e}:${n.id}`,o=await t.get(i);if(o)return o;try{return await t.create(i)}catch(r){let s=await t.get(i);if(s)return s;throw r}}async function Nr(t){let e=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign","verify"]),n=jr(new Uint8Array(await crypto.subtle.exportKey("raw",e.publicKey))),i=await crypto.subtle.exportKey("pkcs8",e.privateKey),o=await crypto.subtle.importKey("pkcs8",i,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]);return{handle:t,signingPrivateKey:o,signingPublicKey:n}}function Ic(t){return new Promise((e,n)=>{t.onerror=()=>n(t.error),t.onsuccess=()=>e(t.result)})}function Ur(t,e){return new Promise((n,i)=>{let o=t.transaction(tt,"readwrite");e(o.objectStore(tt)).onerror=()=>i(o.error),o.onerror=()=>i(o.error),o.onabort=()=>i(o.error??new Error("Identity transaction aborted.")),o.oncomplete=()=>n()})}function kc(t){let e=new Uint8Array(t.reduce((i,o)=>i+o.byteLength,0)),n=0;for(let i of t)e.set(i,n),n+=i.byteLength;return e}function jr(t){return btoa(String.fromCharCode(...t)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}function xc(t){if(t.byteLength!==64)throw new Error("Application authorization signature is invalid.");let e=Ec(t.slice(32));if(e===0n||e>=ki)throw new Error("Application authorization signature is invalid.");return e<=Mc?t:kc([t.slice(0,32),qc(ki-e,32)])}function Ec(t){return BigInt(`0x${Fc(t)}`)}function qc(t,e){let n=t.toString(16).padStart(e*2,"0");return Uint8Array.from({length:e},(i,o)=>Number.parseInt(n.slice(o*2,o*2+2),16))}function Fc(t){return[...t].map(e=>e.toString(16).padStart(2,"0")).join("")}var Ft={id:"mdbase.person",version:"2.0.0"};function Vr(t,e,n){return k(e,n.requestMs,async i=>{let o=await n.authorizedToken(i.signal);if(!o)throw d("not_authorized","Authorize this collection before reading people.");let r=await ae(`${n.serverUrl}/v1/authorities/${encodeURIComponent(n.collectionId)}/${t}`,{headers:{authorization:`Bearer ${o.accessToken}`},signal:i.signal,credentials:"omit",cache:"no-store",redirect:"error"},"temporarily_unavailable","Account identity information is unavailable.");if(r.status===404)throw d("unsupported_operation","This Connect server does not support people discovery.");if(r.status===401)throw d("authorization_expired","The application authorization is no longer active.");if(r.status===403)throw d("access_denied","This application was not approved to read this identity information.");if(!r.ok)throw d("temporarily_unavailable","Account identity information is unavailable.");return E(r,"invalid_operation_response","Connect returned invalid identity information.")})}var rt=class{constructor(e){this.context=e}context;current(e){return I(()=>this.readCurrent(e),en)}members(e){return I(()=>this.readMembers(e),en)}directory(e={}){return I(async()=>{let{members:n="if-approved",...i}=e,[o,r,s]=await Promise.all([this.readCurrent(i),n==="omit"?void 0:this.readMembers(i).catch(a=>{if(!(n==="if-approved"&&a instanceof _&&a.code==="access_denied"))throw a}),this.readRecords(i)]);return{account:o,me:Dc(s,o),people:s.people,invalid:s.invalid.map(({path:a,reason:c})=>({path:a,reason:c})),...r?{members:r}:{}}},pe)}async readCurrent(e){let n=await this.context.request("identity",e),i=Qr(n),o=n.person_settings_url;if(o===void 0)return i;if(typeof o!="string"||!Gr(o))throw hn();return{...i,personSettingsUrl:o}}async readMembers(e){let n=await this.context.request("members",e);if(!n||typeof n!="object"||!("members"in n)||!Array.isArray(n.members))throw hn();return n.members.map(i=>{let o=Qr(i);if(!i||typeof i!="object"||!("role"in i)||i.role!=="owner"&&i.role!=="editor"&&i.role!=="viewer")throw hn();return{...o,role:i.role}})}async readRecords(e){let i=Kr(await this.context.describe(e)).contracts.find(c=>c.id===Ft.id&&c.version===Ft.version),o=new Map;for(let c of i?.implementations??[])for await(let l of this.context.queryPages({contract:{...Ft,type:c.typeName}},{signal:e.signal,pageSize:200}))for(let u of Kr(l).results){let f=o.get(u.path)??[];f.push({typeName:c.typeName,value:u.frontmatter??{}}),o.set(u.path,f)}let r=[],s=[];for(let[c,l]of o){let u=l.map(h=>zc(h.value)),f=u[0],p=u.find(h=>"reason"in h);p&&"reason"in p?s.push({path:c,reason:p.reason,claims:l.flatMap(h=>Br(h.value))}):u.some(h=>JSON.stringify(h)!==JSON.stringify(f))?s.push({path:c,reason:"Its Person implementations project different values.",claims:l.flatMap(h=>Br(h.value))}):f&&!("reason"in f)&&r.push({path:c,...f,typeNames:l.map(h=>h.typeName).sort()})}let a=(c,l)=>c.path.localeCompare(l.path);return{people:r.sort(a),invalid:s.sort(a)}}};function Dc(t,e){let n=t.invalid.filter(o=>o.claims.some(r=>mn(r,e)));if(n.length)return{status:"invalid",paths:n.map(o=>o.path)};let i=t.people.filter(o=>o.identities.some(r=>mn(r,e)));return i.length===0?{status:"unlinked"}:i.length>1?{status:"ambiguous",paths:i.map(o=>o.path)}:{status:"linked",person:i[0]}}function mn(t,e){return t.issuer===e.issuer&&t.subject===e.subject}function zc(t){let{name:e,identities:n=[]}=t;if(typeof e!="string"||!e.trim())return{reason:"It needs a non-blank name."};if(!Array.isArray(n))return{reason:"Its account identities must be a list."};let i=[];for(let o of n){if(!o||typeof o!="object"||Array.isArray(o)||typeof o.issuer!="string"||typeof o.subject!="string"||!o.subject.trim())return{reason:"Each account identity needs an exact issuer and subject."};i.push({issuer:o.issuer,subject:o.subject})}return{name:e,identities:i}}function Br(t){return(Array.isArray(t.identities)?t.identities:[]).flatMap(n=>n&&typeof n=="object"&&!Array.isArray(n)&&"issuer"in n&&"subject"in n&&typeof n.issuer=="string"&&typeof n.subject=="string"?[{issuer:n.issuer,subject:n.subject}]:[])}function Kr(t){if(!t.ok)throw new _(t.problem);return t.value}function Qr(t){if(!t||typeof t!="object"||!("issuer"in t)||!("subject"in t)||!("name"in t)||typeof t.issuer!="string"||typeof t.subject!="string"||typeof t.name!="string"||!t.subject.trim()||!t.name.trim()||!Gr(t.issuer))throw hn();return{issuer:t.issuer,subject:t.subject,name:t.name}}function Gr(t){try{let e=new URL(t);return e.protocol==="https:"||e.protocol==="http:"}catch{return!1}}function hn(){return d("invalid_operation_response","Connect returned invalid identity information.")}var Oe=class{operations=new Map;run(e,n,i,o){if(n?.signal?.aborted)return Promise.reject(te(n.signal));let r=this.operations.get(e)??this.begin(e,o);return this.wait(e,r,n,i)}begin(e,n){let i=new AbortController,o={controller:i,waiters:0,settled:!1,promise:void 0};return o.promise=Promise.resolve().then(()=>n(i.signal)).finally(()=>{o.settled=!0,this.operations.get(e)===o&&this.operations.delete(e)}),this.operations.set(e,o),o}async wait(e,n,i,o){n.waiters+=1;try{return await k(i,o,()=>n.promise)}finally{n.waiters-=1,n.waiters===0&&!n.settled&&this.operations.get(e)===n&&(this.operations.delete(e),n.controller.abort())}}};var Hr=new Set(["files-stat-v1","query-record-revisions-v1","read-many-documents-v1","query-metadata-v1","contract-query-v1","link-resolution-options-v1"]),xi=Object.freeze([]);function ze(t){if(t===void 0)return xi;if(!Array.isArray(t)||t.some(e=>typeof e!="string"))throw d("invalid_operation_response","The authority returned invalid feature capabilities.");return Object.freeze([...new Set(t.filter(e=>Hr.has(e)))])}var yn=class{constructor(e,n){this.discovery=e;this.timeoutMs=n}discovery;timeoutMs;lifetime;generation=0;cached;pending=new Oe;get capabilities(){return this.refreshLifetime(),this.cached??xi}supports(e,n){return I(()=>k(n,this.timeoutMs,async i=>{if(!Hr.has(e))return!1;for(;;){this.refreshLifetime();let o=this.generation,r=this.cached??await this.pending.run(String(o),{signal:i.signal,timeoutMs:null},null,s=>this.discover(s));if(this.refreshLifetime(),o===this.generation)return i.signal.aborted||(this.cached=r),r.includes(e)}}),Ge)}invalidate(){this.cached=void 0,this.lifetime=void 0}refreshLifetime(){let e=this.discovery.lifetime();e!==this.lifetime&&(this.lifetime=e,this.generation+=1,this.cached=void 0)}async discover(e){if(this.discovery.operations().includes("describe")){let i=await this.discovery.describe({signal:e,timeoutMs:null,coordination:{coalesce:!1}});if(!i.ok)throw new _(i.problem);return ze(i.value.authorityCapabilities)}let n=this.discovery.fileCapability();if(n?.actions.includes("list")){let i=n.scope.kind==="selected_folders"?n.scope.folders[0]:void 0,o=await this.discovery.filesPage(i,e);return Object.freeze(o.filter(r=>r==="files-stat-v1"))}return xi}};function Ei(t){return{...t.output?{output:t.output}:{},...t.types?{types:t.types}:{},...t.timezone?{timezone:t.timezone}:{},...t.context?{context:t.context}:{},...t.projections?{projections:Object.fromEntries(Object.entries(t.projections).map(([e,n])=>[e,{expr:n.expression,...n.description?{description:n.description}:{}}]))}:{},...t.where?{where:t.where}:{},...t.select?{select:t.select.map(e=>typeof e=="string"?e:{name:e.name,expr:e.expression,...e.label?{label:e.label}:{},...e.description?{description:e.description}:{}})}:{},...t.orderBy?{order_by:t.orderBy}:{},...t.groupBy?{group_by:t.groupBy}:{},...t.summaryFunctions?{summary_functions:Object.fromEntries(Object.entries(t.summaryFunctions).map(([e,n])=>[e,{expr:n.expression,...n.description?{description:n.description}:{}}]))}:{},...t.summaries?{summaries:t.summaries}:{},...t.limit===void 0?{}:{limit:t.limit},...t.offset===void 0?{}:{offset:t.offset},...t.pagination?{pagination:t.pagination}:{},...t.cursor?{cursor:t.cursor}:{},...t.snapshot?{snapshot:t.snapshot}:{},...t.includeBody===void 0?{}:{include_body:t.includeBody},...t.frontmatterMode?{frontmatter_mode:t.frontmatterMode}:{},...t.contract?{contract:t.contract}:{}}}function gn(t){return{id:t.id,version:t.version,digest:t.digest,type:t.type,implementationDigest:t.implementation_digest}}function qi(t){let{effective_frontmatter:e,contract:n,...i}=t;return{...i,...e===void 0?{}:{effectiveFrontmatter:e},...n?{contract:gn(n)}:{}}}function Lc(t){if(!t||typeof t.path!="string"||typeof t.revision!="string"||!t.revision||!Array.isArray(t.types)||t.types.some(e=>typeof e!="string")||!t.values||typeof t.values!="object"||Array.isArray(t.values)||Object.keys(t).some(e=>!["path","types","revision","values","contract"].includes(e))||t.contract!==void 0&&(!t.contract||["id","version","digest","type","implementation_digest"].some(e=>typeof t.contract[e]!="string")))throw d("invalid_operation_response","The authority returned an invalid revision-bearing metadata row.");return{path:t.path,types:t.types,revision:t.revision,values:t.values,...t.contract?{contract:gn(t.contract)}:{}}}function Fi(t,e){if(!t||!Array.isArray(t.results)||t.output!==e)throw d("invalid_operation_response","The authority returned an invalid query output mode.");let n=t.meta?{...typeof t.meta.total_count=="number"?{totalCount:t.meta.total_count}:{},...t.meta.total_count_outcome===void 0?{}:{totalCountOutcome:t.meta.total_count_outcome},hasMore:t.meta.has_more,...t.meta.cursor?{cursor:t.meta.cursor}:{},...t.meta.snapshot?{snapshot:t.meta.snapshot}:{}}:void 0;return e==="metadata"?{output:e,results:t.results.map(i=>Lc(i)),...n?{meta:n}:{}}:{results:t.results.map(i=>qi(i)),...n?{meta:n}:{}}}function bn(t){if(!t||t.protocol_version!==1||typeof t.collection_id!="string"||typeof t.display_name!="string"||typeof t.spec_version!="string"||!Array.isArray(t.operations)||!Array.isArray(t.types)||!Array.isArray(t.contracts))throw d("invalid_operation_response","The authority returned an invalid collection description.");return{authorityCapabilities:ze(t.authority_capabilities),protocolVersion:t.protocol_version,collectionId:t.collection_id,displayName:t.display_name,specVersion:t.spec_version,operations:t.operations,changeCursor:t.change_cursor,types:t.types,contracts:t.contracts.map(e=>({contractType:e.contract_type,id:e.id,version:e.version,digest:e.digest,schema:e.schema,...e.binding_schema?{bindingSchema:e.binding_schema}:{},implementations:e.implementations.map(n=>({typeName:n.type_name,typeVersion:n.type_version,...n.type_path?{typePath:n.type_path}:{},digest:n.digest,fields:n.fields,...n.binding?{binding:n.binding}:{}}))})),...t.configuration?{configuration:t.configuration}:{}}}var _n=class{constructor(e,n){this.transport=e;this.requestTimeoutMs=n}transport;requestTimeoutMs;generation=0;description;describing;get schemaGeneration(){return this.generation}invalidate(){this.generation+=1,this.description=void 0,this.describing=void 0}describe(e={}){return I(()=>k(e,this.requestTimeoutMs,async()=>{if(!e.fresh&&this.description&&Date.now()<this.description.expiresAt)return R(this.description.value);if(!this.describing){this.description=void 0;let n=this.generation,i=I(()=>k({},this.requestTimeoutMs,o=>this.transport.operation("describe",{},{signal:o.signal,timeoutMs:this.requestTimeoutMs})),Rt).then(o=>{if(!o.ok)return o;let r=bn(o.value);return this.generation===n&&(this.description={value:r,expiresAt:Date.now()+6e4}),R(r,o.diagnostics)}).finally(()=>{this.describing===i&&(this.describing=void 0)});this.describing=i}return this.describing}),Rt).then(n=>n.ok?n.value:n)}};function vn(t,e,n){let i=n,o=!1,r=()=>{if(!i)return;let a=i;i=void 0,t(a).catch(()=>{})},s=()=>{o||r()};return e?.addEventListener("abort",s,{once:!0}),{startRequest(){o=!0},finishRequest(a){a&&(i=a),o=!1,e?.aborted&&r()},dispose(){e?.removeEventListener("abort",s),r()}}}function Cn(t){if(t===void 0)return 1/0;if(!Number.isSafeInteger(t)||t<0)throw new TypeError("maxResults must be a non-negative safe integer.");return t}function wn(t,e){return typeof t=="number"&&Number.isFinite(t)?Math.max(0,Math.floor(t)):e}function st(t,e){return typeof t=="number"&&Number.isFinite(t)&&t>=1?Math.floor(t):e}async function*Wr(t,e,n={},i={}){let{offset:o,limit:r,cursor:s,pagination:a,snapshot:c,...l}=n,u=wn(o,0),f=st(i.firstPageSize??i.pageSize??r,200),p=st(i.pageSize??r,1e3),h=s,m=s!==void 0,P=Cn(i.maxResults),v=vn(e,i.signal,s),b=c,C=0,y=0;try{for(;!i.signal?.aborted&&C<P;){v.startRequest();let A=h,D={signal:i.signal,timeoutMs:i.pageTimeoutMs,coordination:{...i.coordination,coalesce:!1}},S=y===0&&s===void 0&&a===void 0&&c===void 0&&n.output!=="metadata",T=await t({...l,...m?{}:{limit:Math.min(y===0?f:p,P-C)},...m?A?{cursor:A}:{pagination:"cursor"}:{offset:u,...b?{snapshot:b}:{},...!b&&a==="cursor"?{pagination:"cursor"}:{}},...!m&&!b&&S?{pagination:"cursor"}:{}},D);if(S&&!i.signal?.aborted&&!T.ok&&T.problem.code==="operation_invalid"&&(T=await t({...l,limit:Math.min(f,P-C),offset:u},D)),v.finishRequest(T.ok?T.value.meta?.cursor:void 0),i.signal?.aborted)return;if(!T.ok){v.dispose(),yield T;return}let M=T.value,O=M.meta?.cursor;if(O?(m=!0,h=O):m&&(h=void 0),m&&M.meta?.hasMore&&!O){v.dispose(),yield g(w("invalid_operation_response","The collection authority omitted the cursor required for the next query page."));return}let U=M.meta?.snapshot;if(!m&&b&&U&&b!==U){v.dispose(),yield g(w("query_snapshot_changed","The collection query snapshot changed while paging. Refresh the query before continuing."));return}!m&&!b&&U&&(b=U);let H=P-C,B=M.results.length>H?M.results.slice(0,H):M.results;C+=B.length;let N=C>=P||!M.meta?.hasMore||M.results.length===0,Te={...M.output?{output:M.output}:{},results:B,...M.meta?{meta:M.meta}:{},page:y,offset:u,loaded:C,complete:N,...O?{cursor:O}:{},...!m&&b?{snapshot:b}:{}};if(N&&v.dispose(),i.onProgress?.(Te),yield R(Te,T.diagnostics),N)return;u+=M.results.length,y+=1}}finally{v.dispose()}}async function Jr(t,e,n,i,o,r){let s=$r(o.batchSize??100,1e3,"batchSize"),a=$r(o.concurrency??4,4,"concurrency");if(o.coordination?.latestWins)throw new TypeError("readMany batches cannot use latestWins coordination.");if(o.includeBody!==void 0&&typeof o.includeBody!="boolean")throw new TypeError("includeBody must be boolean.");if(o.frontmatterMode!==void 0&&!["effective","persisted","both"].includes(o.frontmatterMode))throw new TypeError("Invalid frontmatterMode.");let c=[...i];try{return await k(o,r,async l=>{if(!c.length)return R({results:[],errors:[]});let u=de({...o,timeoutMs:null,coordination:{...o.coordination,coalesce:!1}},l),f=[...new Set(c)],p=new Map,h=[],m=[],P=0,v=0,b=(y,A,D)=>{h.push({batch:y,paths:A,failure:D});for(let S of A)p.set(S,{status:"error",path:S,batch:y})},C=async()=>{for(;!l.signal.aborted&&v<f.length;){let y=await n?.("read-many-documents-v1",u);if(y&&!y.ok)throw v=f.length,new _(y.problem);if(l.signal.aborted||v>=f.length)return;let A=y?.value===!0,D=A?Math.min(s,100):s,S=P++,T=f.slice(v,v+D);v+=T.length;let M={where:`file.path in ${JSON.stringify(T)}`,...o.types?{types:o.types}:{}};try{let O=T,U=[];if(A&&o.types!==void 0){let N=await t({...M,select:["file.path"],includeBody:!1},{...u,pageSize:T.length});if(!N.ok){b(S,T,N);continue}let Te=new Set(N.value.results.map(Ne=>Ne.path));O=T.filter(Ne=>Te.has(Ne)),U=N.diagnostics;let ne=await n("read-many-documents-v1",u);if(!ne.ok)throw new _(ne.problem);A=ne.value}if(!A){let N=await t({...M,...o.includeBody===void 0?{}:{includeBody:o.includeBody},...o.frontmatterMode?{frontmatterMode:o.frontmatterMode}:{}},{...u,pageSize:T.length});if(!N.ok){b(S,T,N);continue}m[S]=N.diagnostics;let Te=new Map(N.value.results.map(ne=>[ne.path,ne]));for(let ne of T){let Ne=Te.get(ne);p.set(ne,Ne?{status:"found",path:ne,record:Ne}:{status:"missing",path:ne})}continue}if(l.signal.aborted)return;let H=O.length?await e(O,o.includeBody??!1,u):R({items:[]});if(!H.ok){b(S,T,H);continue}let B=Uc(H.value,O,S,o);for(let N of T)p.set(N,B.entries.get(N)??{status:"missing",path:N});m[S]=[...U,...H.diagnostics],B.errors.length&&h.push({batch:S,paths:B.errors.map(N=>N.path),failure:g(w("operation_invalid","Some batch records could not be read.",{details:{diagnostics:B.errors}}))})}catch(O){if(!(O instanceof _))throw O;let U=await I(async()=>{throw O},pe);b(S,T,U)}}};return await Promise.all(Array.from({length:Math.min(a,f.length)},C)),R({results:c.map(y=>p.get(y)),errors:h.sort((y,A)=>y.batch-A.batch)},m.flat())})}catch(l){if(l instanceof _)return I(async()=>{throw l},pe);throw l}}function Uc(t,e,n,i){(!t||!Array.isArray(t.items)||t.items.length!==e.length)&&Dt();let o=new Map,r=[];return t.items.forEach((s,a)=>{switch((!s||s.path!==e[a])&&Dt(),s.status){case"found":o.set(s.path,{status:"found",path:s.path,record:Nc(s.record,s.path,i)});break;case"missing":o.set(s.path,{status:"missing",path:s.path});break;case"error":(!s.error||typeof s.error.code!="string"||typeof s.error.message!="string")&&Dt(),o.set(s.path,{status:"error",path:s.path,batch:n}),r.push({severity:"error",code:s.error.code,message:s.error.message,path:s.path});break;default:Dt()}}),{entries:o,errors:r}}function Nc(t,e,n){(!t||t.path!==e||typeof t.revision!="string"||!t.revision||!Array.isArray(t.types)||t.types.some(o=>typeof o!="string")||!Di(t.frontmatter)||!Di(t.effective_frontmatter)||!Di(t.file)||(n.includeBody??!1)&&typeof t.body!="string"||t.contract!==void 0)&&Dt();let i=n.frontmatterMode??"effective";return{path:t.path,revision:t.revision,types:t.types,file:t.file,...i!=="effective"?{frontmatter:t.frontmatter}:{},...i!=="persisted"?{effectiveFrontmatter:t.effective_frontmatter}:{},...n.includeBody?{body:t.body}:{}}}function Di(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function Dt(){throw d("invalid_operation_response","The authority returned an invalid or incoherently bound document batch.")}function $r(t,e,n){if(!Number.isSafeInteger(t)||t<1||t>e)throw new TypeError(`${n} must be an integer between 1 and ${e}.`);return t}async function*Yr(t,e,n,i={}){let{offset:o,limit:r,cursor:s,...a}=n,c=wn(o,0),l=st(i.firstPageSize??i.pageSize??r,200),u=st(i.pageSize??r,1e3),f=s,p=s!==void 0,h=Cn(i.maxResults),m=vn(e,i.signal,s),P=0,v=0;try{for(;!i.signal?.aborted&&P<h;){m.startRequest();let b=f,C=await t({...a,...p?{}:{limit:Math.min(v===0?l:u,h-P)},...p&&b?{cursor:b}:{offset:c}},{signal:i.signal,timeoutMs:i.pageTimeoutMs,coordination:{...i.coordination,coalesce:!1}});if(m.finishRequest(C.ok?C.value.meta.cursor:void 0),i.signal?.aborted)return;if(!C.ok){m.dispose(),yield C;return}let y=C.value,A=y.meta.cursor;if(A?(p=!0,f=A):p&&(f=void 0),p&&y.meta.hasMore&&!A){m.dispose(),yield g(w("invalid_operation_response","The collection authority omitted the cursor required for the next saved-view page."));return}let D=h-P,S=y.results.length>D?y.results.slice(0,D):y.results;P+=S.length;let T=P>=h||!y.meta.hasMore||y.results.length===0,M={...y,results:S,page:v,offset:c,loaded:P,complete:T,...A?{cursor:A}:{}};if(T&&m.dispose(),i.onProgress?.(M),yield R(M,C.diagnostics),T)return;c+=y.results.length,v+=1}}finally{m.dispose()}}function Xr(t){if(t!==!1)return{initialDelayMs:Math.max(0,t?.initialDelayMs??500),maxDelayMs:Math.max(0,t?.maxDelayMs??15e3),multiplier:Math.max(1,t?.multiplier??2),...t?.maxAttempts===void 0?{}:{maxAttempts:Math.max(0,t.maxAttempts)}}}var Rn=class{constructor(e,n,i,o,r){this.watch=e;this.input=i;this.watchStartTimeoutMs=r;this.pendingChanges=[...o],this.currentStatus={state:"connected",cursor:n,recovered:!1};let s=i.lifetimeSignal;if(s?.aborted)this.close();else if(s){let a=()=>this.close();s.addEventListener("abort",a,{once:!0}),this.removeLifetimeAbort=()=>s.removeEventListener("abort",a)}this.controller.signal.aborted||this.run(n)}watch;input;watchStartTimeoutMs;changes=new Set;statuses=new Set;problems=new Set;controller=new AbortController;removeLifetimeAbort;currentStatus;currentProblem=null;pendingChanges;get status(){return this.currentStatus}get problem(){return this.currentProblem}subscribe(e,n,i){this.changes.add(e),n&&(this.statuses.add(n),n(this.currentStatus)),i&&(this.problems.add(i),this.currentProblem&&i(this.currentProblem));for(let o of this.pendingChanges)e(o);return this.pendingChanges=[],()=>{this.changes.delete(e),n&&this.statuses.delete(n),i&&this.problems.delete(i)}}close(){if(this.controller.signal.aborted)return;this.controller.abort(),this.removeLifetimeAbort?.(),this.removeLifetimeAbort=void 0;let e="cursor"in this.currentStatus?this.currentStatus.cursor:void 0;this.publishStatus({state:"closed",...e===void 0?{}:{cursor:e}})}async run(e){let n=!0,i=this.watch({cursor:e,pollIntervalMs:this.input.pollIntervalMs,retry:this.input.retry,signal:this.controller.signal,timeoutMs:this.watchStartTimeoutMs,onStatus:o=>{if(n&&o.state==="connecting"){n=!1;return}n=!1,this.publishStatus(o)}});try{for await(let o of i){if(this.controller.signal.aborted)return;if(!o.ok){this.currentProblem=o.problem;for(let r of this.problems)r(o.problem);return}for(let r of this.changes)r(o.value)}}finally{this.controller.signal.aborted||this.close()}}publishStatus(e){this.currentStatus=e;for(let n of this.statuses)n(e)}};var at=class{constructor(e,n=Qe,i){this.transport=e;this.requestTimeoutMs=n;this.supportsAuthorityFeature=i;this.descriptions=new _n(e,n)}transport;requestTimeoutMs;supportsAuthorityFeature;descriptions;lastSchemaCursor=-1;get schemaGeneration(){return this.descriptions.schemaGeneration}operation(e,n,i){return I(()=>this.transport.operation(e,n,i),Ge)}describe(e){return this.descriptions.describe(e)}async changes(e={},n){let i=await this.rawOperation("changes",e,tn,n),o=j(i,Wo);if(o.ok){let r=o.value.events.filter($o);(o.value.reset||r.some(s=>s.cursor>this.lastSchemaCursor))&&(this.descriptions.invalidate(),this.lastSchemaCursor=o.value.cursor)}return o}async read(e,n){let i=await this.envelopeOperation("read",jc(e),ue,n);return j(i,Sn)}readMany(e,n={}){return Jr((i,o)=>this.queryAll(i,o),(i,o,r)=>this.envelopeOperation("read",{paths:i,include_body:o,include_document:!1},ue,r),this.supportsAuthorityFeature,e,n,this.requestTimeoutMs)}async query(e={},n){if(e.output!==void 0&&e.output!=="metadata")return g(w("invalid_request","Unknown query output mode."));if(e.output!=="metadata"){let o=await this.envelopeOperation("query",Ei(e),pe,n);return j(o,r=>Fi(r,void 0))}let i=await I(()=>k(n,this.requestTimeoutMs,async o=>{let r=de({...n,timeoutMs:null},o);if(e.includeBody)throw d("invalid_request","Metadata queries cannot include a body.");let s=await this.supportsAuthorityFeature?.("query-metadata-v1",r);if(s&&!s.ok)throw new _(s.problem);if(!s?.value)throw d("unsupported_operation","This authority does not support metadata queries. Use an ordinary query on legacy authorities.");let a=await this.envelopeOperation("query",Ei(e),pe,r);return j(a,c=>Fi(c,e.output))}),pe);return i.ok?i.value:i}async*queryPages(e={},n={}){yield*Wr((i,o)=>this.query(i,o),i=>this.releaseQueryCursor(i,e.output),e,n)}async queryAll(e={},n={}){let i=ve(n,this.requestTimeoutMs),o=[],r,s=[];try{let a={firstPageSize:n.firstPageSize,pageSize:n.pageSize,maxResults:n.maxResults,signal:i.signal,pageTimeoutMs:null,coordination:n.coordination},c=e.output==="metadata"?this.queryPages(e,{...a,onProgress:n.onProgress}):this.queryPages(e,{...a,onProgress:n.onProgress});for await(let u of c){if(!u.ok)return u;let f=u.value;o.push(...f.results),r=f,s.push(...u.diagnostics)}if(i.signal.aborted)throw te(i.signal);let l=r?{...r.meta?.totalCount===void 0?r.meta?.hasMore?{}:{totalCount:o.length}:{totalCount:r.meta.totalCount},...r.meta?.hasMore&&r.meta.totalCountOutcome?{totalCountOutcome:r.meta.totalCountOutcome}:{},hasMore:r.meta?.hasMore??!1,...r.snapshot?{snapshot:r.snapshot}:{}}:void 0;return e.output==="metadata"?R({output:"metadata",results:o,...l?{meta:l}:{}},s):R({results:o,...l?{meta:l}:{}},s)}catch(a){if(a instanceof _)return g(a.problem);throw a}finally{i.dispose()}}async listViews(e){let n=await this.envelopeOperation("list_views",{},ue,e);return j(n,i=>({views:i.views,meta:{totalCount:i.meta.total_count}}))}async executeView(e,n){let i=await this.envelopeOperation("execute_view",e,ue,n);return j(i,$c)}async*executeViewPages(e,n={}){yield*Yr((i,o)=>this.executeView(i,o),i=>this.releaseQueryCursor(i),e,n)}readViewSource(e,n){return this.envelopeOperation("read_view_source",e,ue,n)}createViewSource(e,n){return this.envelopeOperation("create_view_source",e,G,n)}updateViewSource(e,n){return this.envelopeOperation("update_view_source",zi(e),G,n)}deleteViewSource(e,n){return this.envelopeOperation("delete_view_source",zi(e),G,n)}async create(e,n){let i=await this.envelopeOperation("create",Bc(e),G,n);return j(i,Sn)}async update(e,n){let i=await this.envelopeOperation("update",Kc(e),G,n);return j(i,Sn)}async delete(e,n){let i=await this.envelopeOperation("delete",Zr(e),G,n);return j(i,ss)}async preflightDelete(e,n){let i=await this.envelopeOperation("delete",{...Zr(e),check_backlinks:!0,dry_run:!0},G,n);return j(i,Gc)}async rename(e,n){let i=await this.envelopeOperation("rename",es(e),G,n);return j(i,Hc)}async preflightRename(e,n){let i=await this.envelopeOperation("rename",{...es(e),dry_run:!0},G,n);return j(i,Wc)}validate(e={},n){return this.envelopeOperation("validate",e,ue,n)}readType(e,n){return this.envelopeOperation("read_type",e,we,n)}createType(e,n){return this.envelopeOperation("create_type",e,we,n)}updateType(e,n){return this.envelopeOperation("update_type",zi(e),we,n)}async assessTypePack(e,n){let i=await this.envelopeOperation("assess_type_pack",os(e),we,n);return j(i,Ui)}async applyTypePack(e,n){let i=await this.envelopeOperation("apply_type_pack",Qc(e),we,n);return j(i,Yc)}async assessCollectionSetup(e,n){let i=await this.envelopeOperation("assess_collection_setup",rs(e),we,n);return j(i,is)}async applyCollectionSetup(e,n){let i=await this.envelopeOperation("apply_collection_setup",Vc(e),we,n);return j(i,o=>({assessment:is(o.assessment),receipt:Xc(o.receipt)}))}async listTimers(e,n){let i=await this.rawOperation("list_timers",{namespace:e},ue,n);return j(i,o=>({namespace:o.namespace,timers:o.timers.map(Li)}))}async putTimer(e,n){let i=await this.rawOperation("put_timer",{namespace:e.namespace,criterion_id:e.criterionId,timer:ts(e.timer)},G,n);return j(i,Li)}cancelTimer(e,n){return this.rawOperation("cancel_timer",e,G,n)}async reconcileTimers(e,n){let i=await this.rawOperation("reconcile_timers",{namespace:e.namespace,criterion_id:e.criterionId,timers:e.timers.map(ts)},G,n);return j(i,o=>({namespace:o.namespace,timers:o.timers.map(Li),cancelledIds:o.cancelled_ids}))}async*watch(e={}){let n=e.cursor,i=Math.max(100,e.pollIntervalMs??1e3),o=Xr(e.retry),r=0,s=!1;for(e.onStatus?.({state:"connecting",...n===void 0?{}:{cursor:n}});!e.signal?.aborted;){let a=await this.changes(n===void 0?{}:{after:n,limit:200},{signal:e.signal,timeoutMs:e.timeoutMs});if(!a.ok){let u=a.problem;if(e.signal?.aborted)return;if(!o||u.recovery!=="retry"){yield a;return}if(s=!1,r+=1,o.maxAttempts!==void 0&&r>o.maxAttempts){yield a;return}let f=Math.min(o.maxDelayMs,Math.round(o.initialDelayMs*o.multiplier**(r-1)));e.onStatus?.({state:"reconnecting",...n===void 0?{}:{cursor:n},attempt:r,retryInMs:f,problem:u});try{await oe(f,e.signal)}catch{if(!e.signal?.aborted)throw d("operation_failed","Watch retry delay failed unexpectedly.")}continue}let c=a.value;if(n===void 0){n=c.cursor;continue}if(c.reset){let u=w("change_cursor_reset","The collection change cursor expired. Refresh collection state before subscribing again.");e.onStatus?.({state:"reset_required",cursor:n,problem:u}),yield g(u);return}let l=r>0;r=0,(!s||l)&&e.onStatus?.({state:"connected",cursor:n,recovered:l}),s=!0;for(let u of c.events)yield R(u);if(n=c.cursor,!c.hasMore)try{await oe(i,e.signal)}catch{if(!e.signal?.aborted)throw d("operation_failed","Watch polling delay failed unexpectedly.")}}}rawOperation(e,n,i,o){return I(()=>this.transport.operation(e,n,o),i)}async releaseQueryCursor(e,n){try{await k({timeoutMs:2e3},null,async i=>{let o=de({signal:i.signal,timeoutMs:null,coordination:{coalesce:!1}},i);if(n){let r=await this.supportsAuthorityFeature?.("query-metadata-v1",o);if(!r?.ok||!r.value)return}await this.envelopeOperation("query",{release_cursor:e,...n?{output:n}:{}},pe,o)})}catch{}}async envelopeOperation(e,n,i,o){let r=await I(()=>this.transport.operation(e,n,o),i);if(!r.ok)return r;let s=r.value;return s.valid?(["create_type","update_type","apply_type_pack","apply_collection_setup","create_view_source","update_view_source","delete_view_source"].includes(e)&&this.descriptions.invalidate(),R(s.result,s.diagnostics)):g(je(s))}};function j(t,e){if(!t.ok)return t;try{return R(e(t.value),t.diagnostics)}catch(n){if(n instanceof _)return g(n.problem);throw n}}function jc(t){return{path:t.path,...t.contract?{contract:t.contract}:{},...t.includeDocument===void 0?{}:{include_document:t.includeDocument}}}function Bc(t){return{...t.path?{path:t.path}:{},...t.type?{type:t.type}:{},...t.contract?{contract:t.contract}:{},...t.frontmatter?{frontmatter:t.frontmatter}:{},...t.body===void 0?{}:{body:t.body},...t.ifRevision?{if_revision:t.ifRevision}:{},...t.includeDocument===void 0?{}:{include_document:t.includeDocument}}}function Kc(t){return{path:t.path,...t.contract?{contract:t.contract}:{},...t.ifRevision?{if_revision:t.ifRevision}:{},...t.includeDocument===void 0?{}:{include_document:t.includeDocument},...t.document===void 0?{patch:t.patch,...t.body===void 0?{}:{body:t.body}}:{document:t.document}}}function Zr(t){return{path:t.path,...t.contract?{contract:t.contract}:{},...t.checkBacklinks===void 0?{}:{check_backlinks:t.checkBacklinks},...t.ifRevision?{if_revision:t.ifRevision}:{}}}function es(t){return{from:t.from,to:t.to,...t.contract?{contract:t.contract}:{},...t.updateRefs===void 0?{}:{update_refs:t.updateRefs},...t.ifRevision?{if_revision:t.ifRevision}:{},...t.includeDocument===void 0?{}:{include_document:t.includeDocument}}}function zi(t){let{ifRevision:e,...n}=t;return{...n,...e?{if_revision:e}:{}}}function os(t){return{provision:t.provision,installed_by:t.installedBy,...t.adoptResources?{adopt_resources:t.adoptResources}:{},...t.preserveSeedTargets?{preserve_seed_targets:t.preserveSeedTargets}:{},...t.targetOverrides?{target_overrides:t.targetOverrides}:{},...t.contractSetups?{contract_setups:t.contractSetups.map(as)}:{}}}function Qc(t){return{...os(t),expected_assessment_digest:t.expectedAssessmentDigest,...t.allowDowngrade===void 0?{}:{allow_downgrade:t.allowDowngrade}}}function rs(t){return{application_id:t.applicationId,declaration_digest:t.declarationDigest,requirements:t.requirements,provisions:{configuration:t.provisions.configuration,type_packs:t.provisions.typePacks},...t.contractSetups?{contract_setups:t.contractSetups.map(as)}:{},...t.typePackAdoptions?{type_pack_adoptions:t.typePackAdoptions}:{}}}function Vc(t){return{...rs(t),expected_assessment_digest:t.expectedAssessmentDigest,expected_collection_revision:t.expectedCollectionRevision,expected_provision_digest:t.expectedProvisionDigest,...t.allowTypePackDowngrades?{allow_type_pack_downgrades:t.allowTypePackDowngrades}:{}}}function ss(t){return{path:t.path,deleted:t.deleted,...t.broken_links?{brokenLinks:t.broken_links}:{}}}function Gc(t){return{...ss(t),deleted:!1,dryRun:!0,wouldDelete:!0}}function Hc(t){let{references_updated:e,...n}=t;return{...Sn(n),from:t.from,to:t.to,...e?{referencesUpdated:e}:{}}}function Wc(t){return{from:t.from,to:t.to,dryRun:!0,wouldRename:!0,...t.references_affected?{referencesAffected:t.references_affected}:{},...t.warnings?{warnings:t.warnings}:{}}}function ts(t){return{id:t.id,fire_at:t.fireAt,...t.data===void 0?{}:{data:t.data}}}function Li(t){return{id:t.id,fireAt:t.fire_at,...t.data===void 0?{}:{data:t.data},criterionId:t.criterion_id,generation:t.generation,status:t.status,createdAt:t.created_at,updatedAt:t.updated_at,firedAt:t.fired_at}}function as(t){return t.mode==="starter"?t:{contract:t.contract,mode:"existing",type_name:t.typeName,type_revision:t.typeRevision,fields:t.fields,...t.binding?{binding:t.binding}:{}}}function Sn(t){let{effective_frontmatter:e,contract:n,...i}=t;return{...i,effectiveFrontmatter:e,...n?{contract:gn(n)}:{}}}function $c(t){return{results:t.results.map(e=>{let n=qi(e);if(!n.effectiveFrontmatter)throw new Error("Saved view result omitted canonical effective frontmatter.");return{...n,effectiveFrontmatter:n.effectiveFrontmatter}}),meta:{totalCount:t.meta.total_count,hasMore:t.meta.has_more,...t.meta.cursor?{cursor:t.meta.cursor}:{},view:t.meta.view,...t.meta.context?{context:t.meta.context}:{},...t.meta.groups?{groups:t.meta.groups}:{}}}}function ns(t){return{source:t.source,target:t.target,kind:t.kind,mode:t.mode,action:t.action,digest:t.digest,...t.current_digest?{currentDigest:t.current_digest}:{},...t.installed_digest?{installedDigest:t.installed_digest}:{},...t.adopted_from_digest?{adoptedFromDigest:t.adopted_from_digest}:{},...t.upgrade_baseline?{upgradeBaseline:t.upgrade_baseline}:{},...t.reason?{reason:t.reason}:{}}}function On(t){return{id:t.id,version:t.version,digest:t.digest,installedBy:t.installed_by,resources:t.resources.map(e=>({source:e.source,target:e.target,kind:e.kind,mode:e.mode,digest:e.digest,...e.adopted_from_digest?{adoptedFromDigest:e.adopted_from_digest}:{},...e.origin_digest?{originDigest:e.origin_digest}:{}}))}}function Jc(t){return t.mode==="starter"?t:{contract:t.contract,mode:"existing",typeName:t.type_name,typeRevision:t.type_revision,fields:t.fields,...t.binding?{binding:t.binding}:{}}}function Ui(t){return{status:t.status,applicable:t.applicable,assessmentDigest:t.assessment_digest,...t.current?{current:On(t.current)}:{},desired:On(t.desired),resources:t.resources.map(ns),lock:t.lock,contractSetups:{choices:t.contract_setups.choices.map(Jc),resources:t.contract_setups.resources.map(ns)}}}function Yc(t){return{...Ui(t),receipt:On(t.receipt),cleanupDeferred:t.cleanup_deferred}}function is(t){return{status:t.status,applicable:t.applicable,applicationId:t.application_id,declarationDigest:t.declaration_digest,provisionDigest:t.provision_digest,collectionRevision:t.collection_revision,finalCollectionRevision:t.final_collection_revision,configuration:t.configuration,typePacks:t.type_packs.map(Ui),finalResourceRevisions:t.final_resource_revisions,assessmentDigest:t.assessment_digest}}function Xc(t){return{applicationId:t.application_id,declarationDigest:t.declaration_digest,provisionDigest:t.provision_digest,assessmentDigest:t.assessment_digest,collectionRevision:t.collection_revision,configuration:t.configuration,typePacks:t.type_packs.map(On),cleanupDeferred:t.cleanup_deferred}}async function Ni(t,e,n,i){for(;;){ee(n);try{let o=await t("GET",`?${e}`,void 0,n);if(o?.protocol_version!==1||o.type!=="files_page"||!Array.isArray(o.files)||o.next!==void 0&&(typeof o.next!="string"||!o.next))throw d("invalid_operation_response","The authority returned an invalid file page.");return ze(o.authority_capabilities),o}catch(o){let r=_e(o);if(r.code!=="file_index_warming")throw r;i?.(),await oe(500,n)}}}async function*cs(t,e,n,i){let o=ve(n,i);try{ds(t());let r;do{let s=new URLSearchParams({protocol_version:"1",...n.folder?{folder:n.folder}:{},...r?{after:r}:{},...n.pageSize?{limit:String(Go(n.pageSize))}:{}}),a=await Ni(e,s,o.signal,n.onIndexing);for(let c of a.files)ee(o.signal),yield fe(c);r=a.next}while(r)}finally{o.dispose()}}function ls(t,e,n,i,o,r,s){return I(()=>k(r,s,async a=>{if(ds(t()),!o||typeof o!="object"||Object.keys(o).length!==1||!(Object.hasOwn(o,"path")&&typeof o.path=="string"||Object.hasOwn(o,"fileId")&&typeof o.fileId=="string"&&fi.test(o.fileId)))throw d("invalid_request","File stat requires exactly one path or UUID fileId.");if(o.path!==void 0&&(o.path.length>1024||o.path.includes("\\")||o.path.split("/").some(u=>!u||u.startsWith("."))))throw d("invalid_request","File stat requires a collection-relative file path.");let c=await n("files-stat-v1",{signal:a.signal,timeoutMs:null});if(!c.ok)throw new _(c.problem);if(ee(a.signal),c.value){let u=await e("POST","stat",{protocol_version:1,type:"stat_file",...o.path!==void 0?{path:o.path}:{file_id:o.fileId}},a.signal);if(u?.protocol_version!==1||u.type!=="file_stat"||u.file===void 0)throw d("invalid_operation_response","The authority returned an invalid file stat.");if(u.file===null)return null;let f=fe(u.file);if(o.path!==void 0?Pn(f.path)!==Pn(o.path):f.fileId.toLowerCase()!==o.fileId.toLowerCase())throw d("invalid_operation_response","The authority returned a stat for a different file.");return f}let l=o.path?.includes("/")?o.path.slice(0,o.path.lastIndexOf("/")):void 0;for await(let u of i({folder:l,signal:a.signal,timeoutMs:null}))if(ee(a.signal),o.path!==void 0?Pn(u.path)===Pn(o.path):u.fileId.toLowerCase()===o.fileId.toLowerCase())return u;return ee(a.signal),null}),Ge)}function ds(t){if(!t?.actions.includes("list"))throw d("not_authorized","This connection is not authorized to list files.")}function Pn(t){return Array.from(t.normalize("NFC"),e=>e.toLowerCase()).join("").normalize("NFC")}var An=class{constructor(e){this.context=e}context;async registerNotifications(e){return k(e,this.context.requestTimeoutMs,n=>this.registerNotificationsWithinBudget(e,n.signal))}async registerNotificationsWithinBudget(e,n){let i=await this.context.authorizedToken(n);if(!i)throw d("not_authorized","Connect this application before enabling notifications.");let r=(await this.context.register(n)).notifications?.criteria.map(b=>b.id)??[],s=[...new Set(e.criteria??r)],a=s.find(b=>!r.includes(b));if(a)throw d("notification_criterion_not_declared",`The application manifest does not declare notification criterion ${a}.`);if(s.length===0)throw d("notifications_not_declared","This application manifest does not declare any notification criteria.");let c=await ae(`${this.context.serverUrl}/v1/notifications/vapid-public-key`,{signal:n},"notifications_unavailable","Push notifications are unavailable."),l=await E(c,"invalid_operation_response","Connect returned an invalid notification key response.");if(!c.ok)throw z(l,"notifications_unavailable","Push notifications are unavailable.",c.status);let u=await e.serviceWorker.pushManager.getSubscription();u||(u=await e.serviceWorker.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:nn(l.public_key)}));let f=u.toJSON();if(!f.endpoint||!f.keys?.p256dh||!f.keys.auth)throw d("invalid_push_subscription","The browser returned an incomplete push subscription.");let p=F(this.context.storage.getItem(this.context.notificationKey())),h=e.installationId??p?.installationId??se(24),m=await ae(`${this.context.serverUrl}/v1/notifications/channels`,{method:"POST",headers:{authorization:`Bearer ${i.accessToken}`,"content-type":"application/json"},body:JSON.stringify({installation_id:h,criteria:s,subscription:{endpoint:f.endpoint,expirationTime:f.expirationTime??null,keys:f.keys}}),signal:n},"notification_registration_failed","Could not register push notifications."),P=await E(m,"invalid_operation_response","Connect returned an invalid notification registration response.");if(!m.ok)throw z(P,"notification_registration_failed","Could not register push notifications.",m.status);p?.channelId&&p.channelId!==P.channel_id&&fetch(`${this.context.serverUrl}/v1/notifications/channels/${p.channelId}`,{method:"DELETE",headers:{authorization:`Bearer ${i.accessToken}`},signal:n}).catch(()=>{});let v={channelId:P.channel_id,installationId:h,criteria:s};return this.context.storage.setItem(this.context.notificationKey(),JSON.stringify(v)),v}async registerNativeNotifications(e){return k(e,this.context.requestTimeoutMs,n=>this.registerNativeNotificationsWithinBudget(e,n.signal))}async registerNativeNotificationsWithinBudget(e,n){let i=await this.context.authorizedToken(n);if(!i)throw d("not_authorized","Connect this application before enabling notifications.");let o=await this.context.register(n);if(o.notifications?.native_delivery?.mode!=="managed_fcm")throw d("managed_fcm_not_declared","This application does not declare Connect-managed native notifications.");let r=o.notifications.criteria.map(m=>m.id),s=[...new Set(e.criteria??r)],a=s.find(m=>!r.includes(m));if(a)throw d("notification_criterion_not_declared",`The application manifest does not declare notification criterion ${a}.`);if(s.length===0)throw d("notifications_not_declared","This application manifest does not declare any notification criteria.");let c=this.context.notificationKey("fcm"),l=F(this.context.storage.getItem(c)),u=e.installationId??l?.installationId??se(24),f=await ae(`${this.context.serverUrl}/v1/notifications/channels`,{method:"POST",headers:{authorization:`Bearer ${i.accessToken}`,"content-type":"application/json"},body:JSON.stringify({installation_id:u,criteria:s,transport:"fcm",token:e.token}),signal:n},"notification_registration_failed","Could not register native notifications."),p=await E(f,"invalid_operation_response","Connect returned an invalid native notification response.");if(!f.ok)throw z(p,"notification_registration_failed","Could not register native notifications.",f.status);l?.channelId&&l.channelId!==p.channel_id&&this.deleteNotificationChannel(l.channelId,i.accessToken,n).catch(()=>{});let h={channelId:p.channel_id,installationId:u,transport:"fcm",criteria:s};return this.context.storage.setItem(c,JSON.stringify(h)),h}async unregisterNativeNotifications(e={}){return k(e,this.context.requestTimeoutMs,n=>this.unregisterNativeNotificationsWithinBudget(n.signal))}async unregisterNativeNotificationsWithinBudget(e){let n=this.context.notificationKey("fcm"),i=F(this.context.storage.getItem(n)),o=await this.context.authorizedToken(e);if(i?.channelId&&!o)throw d("not_authorized","Reconnect this application before disabling native notifications.");i?.channelId&&o&&await this.deleteNotificationChannel(i.channelId,o.accessToken,e),this.context.storage.removeItem(n)}async unregisterNotifications(e,n={}){return k(n,this.context.requestTimeoutMs,i=>this.unregisterNotificationsWithinBudget(e,i.signal))}async unregisterNotificationsWithinBudget(e,n){let i=F(this.context.storage.getItem(this.context.notificationKey())),o=await this.context.authorizedToken(n);if(i?.channelId&&!o)throw d("not_authorized","Reconnect this application before disabling push notifications.");if(i?.channelId&&o){let s=await ae(`${this.context.serverUrl}/v1/notifications/channels/${i.channelId}`,{method:"DELETE",headers:{authorization:`Bearer ${o.accessToken}`},signal:n},"notification_unregistration_failed","Could not unregister push notifications.");if(!s.ok&&s.status!==404){let a=await E(s,"invalid_operation_response","Connect returned an invalid notification response.");throw z(a,"notification_unregistration_failed","Could not unregister push notifications.",s.status)}}this.context.storage.removeItem(this.context.notificationKey()),await(await e?.pushManager.getSubscription())?.unsubscribe()}async deleteNotificationChannel(e,n,i){let o=await ae(`${this.context.serverUrl}/v1/notifications/channels/${e}`,{method:"DELETE",headers:{authorization:`Bearer ${n}`},signal:i},"notification_unregistration_failed","Could not unregister push notifications.");if(!o.ok&&o.status!==404){let r=await E(o,"invalid_operation_response","Connect returned an invalid notification response.");throw z(r,"notification_unregistration_failed","Could not unregister push notifications.",o.status)}}};async function us(t,e){let n=new TextEncoder().encode(`${t}
|
|
4
|
+
${e}`),i=new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",n));return Array.from(i,o=>o.toString(16).padStart(2,"0")).join("")}async function ps(t,e,n){let i=n?.path;return e==="update"&&typeof i=="string"?us(t,i):void 0}async function fs(t,e,n){let i=await us(e,n);return t.find(o=>o.operation==="update"&&o.recordDigest===i)?.requestId??null}async function Tn(t,e,n,i,o,r){if(!t.authority)throw d("not_remote_authority","This authorization has no remote authority endpoint.");let s=n===""||n.startsWith("?")?n:`/${n}`,a=`${t.authority.filesUrl}${s}`,c=i===void 0?void 0:JSON.stringify(i),l=await r(t,e,a,c,t.authority.accessToken);return fetch(a,{method:e,redirect:"error",headers:{authorization:`Bearer ${t.authority.accessToken}`,...c===void 0?{}:{"content-type":"application/json"},...l},...c===void 0?{}:{body:c},...o?{signal:o}:{}})}async function hs(t,e,n,i,o,r,s,a=async c=>c){let c=t,l=await Tn(c,e,n,i,o,s);if(l.status===401&&c.refreshToken){if(c=await a(await r(o)),!c.authority||!c.fileCapability)throw d("authority_authorization_changed","Reconnect this collection before accessing its files.");l=await Tn(c,e,n,i,o,s)}let u=await E(l,"invalid_operation_response","The hosted authority returned an invalid file response.");if(!l.ok)throw z(u,"operation_failed","Collection file request failed.",l.status);return u}async function ms(t,e,n,i,o,r,s=async a=>a){let a=t,c=await Tn(a,"GET",e,void 0,i,r);if(c.status===401&&a.refreshToken){if(a=await s(await o(i)),!a.authority||!a.fileCapability)throw d("authority_authorization_changed","Reconnect this collection before accessing its files.");c=await Tn(a,"GET",e,void 0,i,r)}if(!c.ok){let u=await E(c,"invalid_operation_response","The hosted authority returned an invalid file range error response.");throw z(u,"operation_failed","Collection file range request failed.",c.status)}let l=c.headers.get("content-length");if(l===null||!/^(0|[1-9][0-9]*)$/u.test(l)||Number(l)!==n)throw await c.body?.cancel().catch(()=>{}),d("invalid_operation_response","The hosted file response declared an unexpected byte length.");if(!c.body)throw d("invalid_operation_response","The hosted file response did not contain a byte stream.");return c.body}var Mn=class{constructor(e,n){this.namespace=e;this.onFinalRelease=n}namespace;onFinalRelease;leases=new Map;locks=Zc();retainAutomaticallyRetiredKeys=this.locks===null;async acquire(e,n,i){let o=this.acquireLocal(e,n);if(!this.locks)return o;try{let r=await el(this.locks,this.lockName(e,n),i);return ji(()=>{r(),o()})}catch(r){throw o(),r}}deleteExclusive(e,n,i){this.retainAutomaticallyRetiredKeys||(this.locks?this.locks.request(this.lockName(e,n),{mode:"exclusive"},i).catch(()=>{}):this.has(e,n)||Promise.resolve().then(i).catch(()=>{}))}has(e,n){return this.leases.get(e)?.has(n)??!1}handles(e){return this.leases.get(e)?.keys()??[]}acquireLocal(e,n){let i=this.leases.get(e)??new Map;return i.set(n,(i.get(n)??0)+1),this.leases.set(e,i),ji(()=>{let o=(i.get(n)??1)-1;o>0?i.set(n,o):(i.delete(n),i.size===0&&this.leases.delete(e),this.onFinalRelease(e,n))})}lockName(e,n){return`mdbase-connect:grant-key:${this.namespace}:${e}:${n}`}},Pe=class{constructor(e,n){this.collectionId=e;this.acquire=n}collectionId;acquire;releases=new Map;async retain(e,n){let i=typeof e=="string"?e:e?.keyHandle;if(!i)return;let o=this.releases.get(i);o||(o=this.acquire(this.collectionId,i,n),this.releases.set(i,o));try{await o}catch(r){throw this.releases.get(i)===o&&this.releases.delete(i),this.release(),r}}release(){for(let e of this.releases.values())e.then(n=>n());this.releases.clear()}};async function $(t,e,n){for(;;){let i=t();if(!i)return null;await e.retain(i,n);let o=t();if(!o)return null;if(o.keyHandle===i.keyHandle)return o}}function Zc(){let t=typeof navigator>"u"?void 0:navigator.locks;return t||(typeof window<"u"||typeof globalThis.importScripts=="function"?null:void 0)}async function el(t,e,n){let i,o,r,s=new Promise((l,u)=>{i=l,o=u}),a=new Promise(l=>{r=l});return t.request(e,{mode:"shared",...n?{signal:n}:{}},async()=>{i(),await a}).catch(o),await s,ji(r)}function ji(t){let e=!1;return()=>{e||(e=!0,t())}}var tl="mdbase-connect file chunk key v1",In=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,ge=class extends Error{constructor(n,i){super(i);this.code=n;this.name="FileTransferCryptoError"}code},ct=class t{constructor(e,n){this.binding=e;this.key=n}binding;key;static async open(e,n,i){ys(i);let o=await e.get(n);if(!o||o.agreementPublicKey!==i.encryption.application_agreement_public_key)throw new q("missing_grant_key","The encrypted grant key is unavailable or does not match the file transfer grant.");let r=await St(o.agreementPrivateKey,i.encryption.connector_agreement_public_key);return t.fromSharedSecret(r,i)}static async fromSharedSecret(e,n){ys(n);let i=await Bi(e,n);return new t(n,i)}async encryptChunk(e,n,i){if(this.validateHeader(n),i.byteLength!==n.plaintext_length)throw new ge("plaintext_length_mismatch","File chunk plaintext length does not match its authenticated header.");let o=jt(e,n),r=await crypto.subtle.encrypt({name:"AES-GCM",iv:gs(n.chunk_index),additionalData:kn(o),tagLength:128},this.key,kn(i));return ho({kind:e,header:n,payload:new Uint8Array(r)})}async decryptChunk(e){let n=Bt(e);this.validateHeader(n.header);let i=jt(n.kind,n.header);try{let o=await crypto.subtle.decrypt({name:"AES-GCM",iv:gs(n.header.chunk_index),additionalData:kn(i),tagLength:128},this.key,kn(n.payload));return new Uint8Array(o)}catch{throw new ge("authentication_failed","The encrypted file chunk could not be authenticated.")}}validateHeader(e){let n=this.binding.encryption;if(e.protocol_version!==1||e.protection!=="grant_aead_v1"||e.grant_id!==this.binding.grantId||e.authority_id!==this.binding.authorityId||e.collection_id!==n.collection_id||e.transfer_id!==this.binding.transferId||e.direction!==this.binding.direction||e.scope_epoch!==n.scope_epoch||e.key_id!==n.key_id)throw new ge("header_binding_mismatch","The file frame does not match its transfer encryption binding.")}};async function Bi(t,e){let n=new TextEncoder().encode(nl(e)),i=await crypto.subtle.digest("SHA-256",n),o=await crypto.subtle.importKey("raw",t,"HKDF",!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:i,info:new TextEncoder().encode(tl)},o,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}function ys(t){if(ye(t.encryption),!In.test(t.grantId)||!In.test(t.applicationId)||!In.test(t.authorityId)||!In.test(t.transferId)||t.direction!=="upload"&&t.direction!=="download")throw new ge("invalid_binding","The file transfer encryption binding is invalid.")}function nl(t){let e=t.encryption;return["mdbase-connect","file-transfer",1,e.suite,t.grantId,t.applicationId,e.connector_id,t.authorityId,e.collection_id,e.scope_epoch,e.key_id,t.transferId,t.direction].join("|")}function gs(t){if(!Number.isSafeInteger(t)||t<0)throw new ge("invalid_chunk_index","The file chunk index is invalid.");let e=new Uint8Array(new ArrayBuffer(12));return new DataView(e.buffer).setBigUint64(4,BigInt(t),!1),e}function kn(t){return t.buffer instanceof ArrayBuffer?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Uint8Array.from(t)}var qn=class{constructor(e){this.options=e}options;async control(e,n,i,o,r){let s=this.grantKeyLeases(e.collectionId);try{return e=await this.retainEntryToken(e,s,r),await this.controlAttempt(e,n,i,o,r,!1,0,s)}finally{s.release()}}async controlAttempt(e,n,i,o,r,s,a,c){lt(e);let l=Qi(n,i,o),u=await this.encryptControl(e,l),f,p=await this.options.shouldAttemptDirect(e);if(p){try{f=await fetch(`${this.options.loopbackUrl}/v1/files/control`,Se({method:"POST",headers:{"content-type":"application/mdbase-connect+json"},body:JSON.stringify(u),signal:r}))}catch(h){if(r?.aborted)throw h;this.options.onDirectUnavailable()}if(f&&(!await Je(f)||await Be(f)))return f.ok&&this.options.onDirectAvailable(),this.decryptControlResponse(e,n,i,o,r,u,f,s,a,c);f&&this.options.onDirectUnavailable()}return p&&!Z("file_control",l)&&(e=e.expiresAt>Date.now()+3e4?e:await this.options.refreshAuthorization(r),e=await this.retainEntryToken(e,c,r),En(e),u=await this.encryptControl(e,l)),f=await this.sendRelayControl(e,u,r),await ol(f,e)&&(e=await this.options.refreshAuthorization(r),e=await this.retainEntryToken(e,c,r),En(e),u=await this.encryptControl(e,l),f=await this.sendRelayControl(e,u,r)),f.ok&&this.options.onRelayAvailable(),this.decryptControlResponse(e,n,i,o,r,u,f,s,a,c)}async decryptControlResponse(e,n,i,o,r,s,a,c,l,u){let f=await E(a,"invalid_operation_response","The collection authority returned an invalid file control response.");if(!a.ok){let m=z(f,"operation_failed","Collection file request failed.",a.status);if(Ht(m)&&l<Gt)return await Wt(l,r),this.controlAttempt(e,n,i,o,r,c,l+1,u);if(m.code==="fresh_request_required"&&!Z("file_control",Qi(n,i,o))&&!c)return this.controlAttempt(e,n,i,o,r,!0,l,u);throw m}let p=f?.envelope;if(!p)throw d("invalid_encrypted_response","The connector omitted its encrypted file response.");let h=await $e(this.options.keyStore,e.keyHandle,Vi(e),s,p);if(!h.ok&&h.problem.code==="fresh_request_required"&&!Z("file_control",Qi(n,i,o))&&!c)return this.controlAttempt(e,n,i,o,r,!0,l,u);if(!h.ok){let m=al(h.problem);if(Ht(m)&&l<Gt)return await Wt(l,r),this.controlAttempt(e,n,i,o,r,c,l+1,u);throw m}return h.result}async uploadChunk(e,n,i,o,r){let s=r??await this.localFileToken(e,"upload",o),a=this.grantKeyLeases(s.collectionId);try{let c=await this.retainEntryToken(s,a,o);return Ki(c,e,"upload"),await this.uploadChunkWithLease(c,a,e,n,i,o)}finally{a.release()}}async uploadChunkWithLease(e,n,i,o,r,s){let a=e,c=await bs(this.options.keyStore,a,i,o,r),l;if(await this.options.shouldAttemptDirect(a)){try{l=await fetch(`${this.options.loopbackUrl}/v1/files/upload`,Se(_s(c,s)))}catch(u){if(s?.aborted)throw u;this.options.onDirectUnavailable()}if(l&&(!await Je(l)||await Be(l)))return l.ok&&this.options.onDirectAvailable(),il(l,"Encrypted file chunk upload failed.");l&&this.options.onDirectUnavailable()}if(l=await this.sendRelayUpload(a,c,s),l.status===401&&a.refreshToken&&(a=await this.options.refreshAuthorization(s),a=await this.retainEntryToken(a,n,s),En(a),c=await bs(this.options.keyStore,a,i,o,r),l=await this.sendRelayUpload(a,c,s)),!l.ok){let u=await E(l,"invalid_operation_response","The collection authority returned an invalid file upload response.");throw z(u,"operation_failed","Encrypted file chunk upload failed.",l.status)}this.options.onRelayAvailable()}async downloadChunk(e,n,i,o){let r=o??await this.localFileToken(e,"download",i),s=this.grantKeyLeases(r.collectionId);try{return r=await this.retainEntryToken(r,s,i),Ki(r,e,"download"),await this.downloadChunkWithLease(r,s,e,n,i)}finally{s.release()}}async downloadChunkWithLease(e,n,i,o,r){let s;if(await this.options.shouldAttemptDirect(e)){try{s=await fetch(`${this.options.loopbackUrl}/v1/files/download/${encodeURIComponent(e.grantId)}/${encodeURIComponent(i.transfer_id)}/${o}`,Se({method:"GET",signal:r}))}catch(a){if(r?.aborted)throw a;this.options.onDirectUnavailable()}if(s&&(!await Je(s)||await Be(s)))return s.ok&&this.options.onDirectAvailable(),this.decryptDownloadResponse(e,i,o,s);s&&this.options.onDirectUnavailable()}return s=await this.sendRelayDownload(e,i,o,r),s.status===401&&e.refreshToken&&(e=await this.options.refreshAuthorization(r),e=await this.retainEntryToken(e,n,r),En(e),s=await this.sendRelayDownload(e,i,o,r)),s.ok&&this.options.onRelayAvailable(),this.decryptDownloadResponse(e,i,o,s)}async decryptDownloadResponse(e,n,i,o){if(!o.ok){let a=await E(o,"invalid_operation_response","The collection authority returned an invalid file download response.");throw z(a,"operation_failed","Encrypted file chunk download failed.",o.status)}if(o.headers.get("content-type")?.split(";",1)[0]!=="application/mdbase-connect-file")throw d("invalid_operation_response","The connector returned an invalid file response media type.");let r=new Uint8Array(await o.arrayBuffer()),s;try{sl(n,i,r),s=await(await Cs(this.options.keyStore,e,n)).decryptChunk(r)}catch(a){throw a instanceof _?a:d("invalid_operation_response","The connector returned an invalid encrypted file frame.",{cause:a})}if(s.byteLength!==Gi(n,i))throw d("invalid_operation_response","The connector returned a truncated file chunk.");return s}encryptControl(e,n){return lt(e),me(this.options.keyStore,e.keyHandle,Vi(e),"file_control",n)}sendRelayControl(e,n,i){return fetch(`${this.options.serverUrl}/v1/authorities/${encodeURIComponent(e.collectionId)}/files/control`,{method:"POST",headers:{authorization:`Bearer ${e.accessToken}`,"content-type":"application/json"},body:JSON.stringify(n),signal:i})}sendRelayUpload(e,n,i){return fetch(`${this.options.serverUrl}/v1/authorities/${encodeURIComponent(e.collectionId)}/files/upload`,{..._s(n,i),headers:{authorization:`Bearer ${e.accessToken}`,"content-type":"application/mdbase-connect-file"}})}sendRelayDownload(e,n,i,o){return fetch(`${this.options.serverUrl}/v1/authorities/${encodeURIComponent(e.collectionId)}/files/download/${encodeURIComponent(n.transfer_id)}/${i}`,{method:"GET",headers:{authorization:`Bearer ${e.accessToken}`},signal:o})}async localFileToken(e,n,i){let o=await this.options.authorizedToken(i);return Ki(o,e,n),o}grantKeyLeases(e){return new Pe(e,this.options.acquireGrantKeyLease??(()=>Promise.resolve(()=>{})))}async retainEntryToken(e,n,i){if(!this.options.currentToken)return await n.retain(e,i),e;let o=await $(this.options.currentToken,n,i);if(o)return o;throw d("not_authorized","Reconnect this application to continue.")}};function Ki(t,e,n){if(!t||t.authority||!t.fileCapability||!t.encryption||!t.grantId||!t.keyHandle||e.direction!==n||e.protection!=="grant_aead_v1")throw d("not_authorized","This connection cannot use encrypted local file delivery.");Fn(e)}function En(t){if(t.authority||!t.fileCapability)throw d("not_authorized","This connection cannot use encrypted local file delivery.");lt(t)}async function bs(t,e,n,i,o){let r=rl(e,n,i,o.byteLength);return(await Cs(t,e,n)).encryptChunk("upload_chunk",r,o)}function _s(t,e){return{method:"POST",headers:{"content-type":"application/mdbase-connect-file"},body:Uint8Array.from(t).buffer,signal:e}}async function il(t,e){if(t.ok)return;let n=await E(t,"invalid_operation_response","The collection authority returned an invalid file transfer response.");throw z(n,"operation_failed",e,t.status)}async function ol(t,e){return e.refreshToken?t.status===401?!0:t.status!==409?!1:(await E(t.clone(),"invalid_operation_response","The collection authority returned an invalid file response.").catch(()=>null))?.error?.code==="encryption_binding_stale":!1}function lt(t){if(!t.encryption||!t.grantId||!t.keyHandle)throw d("missing_grant_key","Reconnect this application to restore encrypted file access.")}function Vi(t){return lt(t),{grantId:t.grantId,applicationId:t.clientId,encryption:t.encryption}}function Cs(t,e,n){return lt(e),ct.open(t,e.keyHandle,{...Vi(e),authorityId:e.encryption.connector_id,transferId:n.transfer_id,direction:n.direction})}function rl(t,e,n,i){lt(t);let o=Fn(e),r=Gi(e,n);if(i!==r)throw d("invalid_request","The file chunk has the wrong byte length.");return{protocol_version:1,protection:"grant_aead_v1",grant_id:t.grantId,authority_id:t.encryption.connector_id,collection_id:t.collectionId,transfer_id:e.transfer_id,direction:e.direction,chunk_size:o,chunk_index:n,offset:n*o,plaintext_length:i,total_size:e.total_size,scope_epoch:t.encryption.scope_epoch,key_id:t.encryption.key_id}}function sl(t,e,n){let i=Bt(n),o=Gi(t,e),r=Fn(t);if(i.kind!=="download_chunk"||i.header.chunk_index!==e||i.header.chunk_size!==r||i.header.offset!==e*r||i.header.plaintext_length!==o||i.header.total_size!==t.total_size)throw d("invalid_operation_response","The connector returned a file frame for a different chunk.")}function al(t){return L(t.code==="unknown"?t.server_code:t.code,t.message,{details:t.details,operationOutcome:t.operation_outcome??"rejected",traceId:t.trace_id})}function Qi(t,e,n){if(t==="GET"&&(e===""||e.startsWith("?"))){let o=new URLSearchParams(e.startsWith("?")?e.slice(1):e),r=o.get("limit");return{protocol_version:1,type:"list_files",...o.get("folder")?{folder:o.get("folder")}:{},...o.get("after")?{after:o.get("after")}:{},...r?{limit:Number(r)}:{}}}let i=e.split("/");if(t==="GET"&&i.length===2&&i[0]==="transfers")return vs("get_file_transfer_status",i[1]);if(t==="DELETE"&&i.length===2&&i[0]==="transfers")return vs("abort_file_transfer",i[1]);if(t==="POST"&&cl(n)){let o=e==="stat"?"stat_file":e==="uploads"?"open_file_upload":e==="downloads"?"open_file_download":i.length===3&&i[0]==="uploads"&&i[2]==="commit"?"commit_file_upload":i.length===2&&i[1]==="move"&&n.file_id===decodeURIComponent(i[0])?"move_file":i.length===2&&i[1]==="delete"&&n.file_id===decodeURIComponent(i[0])?"delete_file":null;if(o&&n.type===o)return{...n}}throw d("invalid_request","The file control request path is invalid.")}function vs(t,e){return{protocol_version:1,type:t,transfer_id:decodeURIComponent(e)}}function Fn(t){if(t.strategy.kind!=="framed_chunks"||!Number.isSafeInteger(t.strategy.chunk_size)||t.strategy.chunk_size<=0)throw d("invalid_operation_response","The connector returned an invalid framed transfer strategy.");return t.strategy.chunk_size}function Gi(t,e){let n=Fn(t);if(!Number.isSafeInteger(e)||e<0||!Number.isSafeInteger(t.total_size)||t.total_size<0)throw d("invalid_request","The file chunk index is invalid.");let i=e*n;if(!Number.isSafeInteger(i)||i>=t.total_size)throw d("invalid_request","The file chunk index is outside the transfer.");return Math.min(n,t.total_size-i)}function cl(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var Dn=class{constructor(e){this.options=e;this.local=new qn(e)}options;local;async control(e,n="",i,o){let r=await this.requireFileToken(o),s=r.token;try{return s.authority?await hs(s,e,n,i,o,this.options.refreshAuthorization,this.options.authorityProofHeaders,r.retain):await this.local.control(s,e,n,i,o)}finally{r.release()}}async uploadChunk(e,n,i,o){let r=await this.requireFileToken(o);try{return await this.local.uploadChunk(e,n,i,o,r.token)}finally{r.release()}}async downloadChunk(e,n,i){let o=await this.requireFileToken(i);try{return await this.local.downloadChunk(e,n,i,o.token)}finally{o.release()}}async downloadHostedPart(e,n,i,o){let r=await this.requireFileToken(o),s=r.token;try{if(!s.authority)throw d("not_remote_authority","Hosted file delivery requires a remote authority endpoint.");return await ms(s,`downloads/${encodeURIComponent(e.transfer_id)}/parts/${n}`,i,o,this.options.refreshAuthorization,this.options.authorityProofHeaders,r.retain)}finally{r.release()}}async requireFileToken(e){let n=new Pe(this.options.collectionId,this.options.acquireGrantKeyLease);try{await $(this.options.currentToken,n,e),await this.options.authorizedToken(e);let i=await $(this.options.currentToken,n,e);if(!i?.fileCapability)throw d("not_authorized","This connection has no file capability.");return{token:i,retain:async o=>{let r=await $(this.options.currentToken,n,e);if(r)return r;throw d("not_authorized","Reconnect this application to continue.")},release:()=>n.release()}}catch(i){throw n.release(),i}}};async function Le(t,e,n,i,o,r){if(!e.authority?.proofPublicKey)return{};if(!e.keyHandle)throw d("missing_grant_key","Reconnect this application to restore remote authority request signing.");try{let s=new URL(i);return await on(t,e.keyHandle,e.authority.proofPublicKey,{method:n,target:`${s.pathname}${s.search}`,body:o,credential:r})}catch(s){throw s instanceof q?L(s.code,s.message):s}}async function ws(t){let e=t.current;if(!e?.refreshToken)throw d("not_authorized","Reconnect this application to continue.");if((e.refreshExpiresAt??0)<=Date.now())throw d("relay_authorization_expired","Direct access is still available on this computer, but using the relay requires reconnecting this application.");let n=e.refreshToken,i=`${t.serverUrl}/oauth/token`,o=new URLSearchParams({grant_type:"refresh_token",refresh_token:e.refreshToken,client_id:e.clientId}).toString(),r=e.authority?await Le(t.keyStore,e,"POST",i,o,e.refreshToken):{},s=await fetch(i,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",...r},body:o,signal:t.signal}),a=await E(s,"invalid_token_response","The authorization service returned an invalid token response.");if(!s.ok){let c=t.currentToken();if(c?.refreshToken&&c.refreshToken!==n)return c;throw t.directCapable(e)||t.removeToken(e.keyHandle),(Tt(a)??a?.error?.code)==="invalid_grant"?d("authorization_expired",a?.error_description??a?.error?.message??"Reconnect this application to continue.",{status:s.status}):z(a,"authorization_expired","Reconnect this application to continue.",s.status)}return t.storeTokenResponse(a,e.clientId,e.keyHandle)}var zn=class{constructor(e,n){this.storage=e;this.baseKey=n}storage;baseKey;list(e){if(!e)return[];let n=F(this.storage.getItem(this.baseKey));if(Rs(n)&&n.collectionId===e){let o=this.key(n.requestId);this.storage.getItem(o)||this.storage.setItem(o,JSON.stringify(n)),this.storage.removeItem(this.baseKey)}let i=[];for(let o=0;o<this.storage.length;o+=1){let r=this.storage.key(o);r?.startsWith(`${this.baseKey}:`)&&i.push(r)}return i.map(o=>F(this.storage.getItem(o))).filter(o=>Rs(o)&&o.collectionId===e).sort((o,r)=>o.createdAt-r.createdAt||o.requestId.localeCompare(r.requestId))}find(e,n){return this.list(e).find(i=>i.requestId===n)??null}identifier(e){return e.mutation??be(e.operation,e.request?.input??(e.operation==="sync"?{action:"mutate"}:{}))??(e.operation==="sync"?"sync:mutate":e.operation)}summary(e){return{requestId:e.requestId,operation:this.identifier(e),fingerprint:e.inputFingerprint,status:"outcome_unknown",createdAt:new Date(e.createdAt).toISOString()}}store(e){this.storage.setItem(this.key(e.requestId),JSON.stringify(e))}take(e){let n=this.key(e),i=F(this.storage.getItem(n));return this.storage.removeItem(n),i}key(e){return`${this.baseKey}:${encodeURIComponent(e)}`}};function Rs(t){return!!(t&&typeof t.collectionId=="string"&&typeof t.requestId=="string"&&t.requestId.length>0&&mo(t.operation)&&typeof t.inputFingerprint=="string"&&Number.isFinite(t.createdAt)&&t.createdAt>0&&(t.envelope||t.request)&&(t.operation==="sync"||be(t.operation,t.request?.input??{})!==null))}function Ss({stored:t,collectionId:e,relayEncryption:n,invalidate:i,directCapable:o}){let r=F(t),s=(c,l="invalid_stored_grant")=>(i(typeof c=="string"?c:void 0,l),null);if(!r)return t&&s(),null;if(r.version!==1||typeof r.accessToken!="string"||r.accessToken.length===0||typeof r.clientId!="string"||r.clientId.length===0||r.collectionId!==e||typeof r.collectionName!="string"||r.collectionName.length===0||!Array.isArray(r.operations)||r.operations.some(c=>typeof c!="string")||typeof r.expiresAt!="number"||!Number.isFinite(r.expiresAt)||r.refreshToken!==void 0&&(typeof r.refreshToken!="string"||r.refreshToken.length===0)||r.refreshExpiresAt!==void 0&&(typeof r.refreshExpiresAt!="number"||!Number.isFinite(r.refreshExpiresAt)))return s(r.keyHandle);let a=cn(r.scope);if(!a)return s(r.keyHandle);if(!ln(a))return s(r.keyHandle,"legacy_scope_reauthorization_required");if(r.fileCapability&&!an(r.fileCapability)||r.authority&&!Mr(r.authority,r.collectionId))return s(r.keyHandle);if(n==="required"){if(r.authority){if(!r.keyHandle||!r.authority.proofPublicKey)return s(r.keyHandle)}else if(!r.grantId||!r.keyHandle||!Ir(r.encryption,r.collectionId))return s(r.keyHandle)}return r.expiresAt<=Date.now()&&(!r.refreshToken||(r.refreshExpiresAt??0)<=Date.now())?o(r)?r:(i(r.keyHandle),null):r}async function Hi(t,e,n,i,o,r){if(!e.authority)throw d("not_remote_authority","This authorization has no remote authority endpoint.");let s=`${e.authority.syncUrl}/${i}`,a=o===void 0?void 0:JSON.stringify(o),c=await Le(t,e,n,s,a,e.authority.accessToken);return fetch(s,{method:n,headers:{authorization:`Bearer ${e.authority.accessToken}`,...o===void 0?{}:{"content-type":"application/json"},...c},...a===void 0?{}:{body:a},signal:r})}async function Os(t,e,n,i,o){if(!e.encryption||!e.grantId||!e.keyHandle)throw d("authorization_binding_incompatible","The refreshed authorization no longer supports encrypted connector operations.",{details:{contract:"grant_encryption",required:[1],supported:e.encryption?[e.encryption.protocol_version]:[],peer:"connector",operation:n}});try{return await me(t,e.keyHandle,{grantId:e.grantId,applicationId:e.clientId,encryption:e.encryption},n,i,void 0,o)}catch(r){throw r instanceof q?L(r.code,r.message):r}}function Ps(t,e){return!t||t.authority||!t.encryption||!t.grantId||!t.keyHandle||e==="disabled"?!1:typeof location>"u"||!t.applicationOrigin||t.applicationOrigin===Ii()}async function As(t,e,n){let i;try{i=await fetch(`${t}/v1/ready`,Se({method:"GET",cache:"no-store",signal:n}))}catch{return!1}if(i.status===403)throw L("operation_failed","The connector rejected direct access from this application. Relay access remains available.",{status:i.status});let o=await E(i,"invalid_operation_response","The connector returned an invalid readiness response.").catch(()=>null);return i.ok&&o?.service==="mdbase-connect"&&o?.loopback_protocol_version===1&&o?.operation_transport_protocol_version===e}async function Ts(t,e){try{return{body:await E(t,"invalid_operation_response","The collection authority returned a response that is not valid JSON.")}}catch(n){if(!t.ok&&e&&ll(t.status))return{body:void 0,httpError:L("operation_failed","Collection operation failed.",{status:t.status,operationOutcome:"rejected"})};throw d("invalid_operation_response","The collection authority returned a response that is not valid JSON.",{cause:n})}}function ll(t){return t>=400&&t<500&&![408,425,429].includes(t)}var Ln=class{serverUrl;storage;keyStore;directAccessMode;loopbackUrl;collectionId;internals;onChange;timeouts;pendingMutationStore;files;refreshOperations=new Oe;directStatus;currentRoute="relay";directFailures=0;directRetryAt=0;constructor(e){this.serverUrl=e.serverUrl,this.storage=e.storage,this.keyStore=e.keyStore,this.directAccessMode=e.directAccessMode,this.loopbackUrl=e.loopbackUrl,this.collectionId=e.collectionId,this.internals=e.internals,this.onChange=e.onChange,this.timeouts=e.timeouts,this.pendingMutationStore=new zn(this.storage,this.internals.pendingMutationKey(this.collectionId)),this.files=new Dn({keyStore:this.keyStore,serverUrl:this.serverUrl,loopbackUrl:this.loopbackUrl,collectionId:this.collectionId,currentToken:()=>this.currentToken(),authorizedToken:n=>this.authorizedToken({signal:n,timeoutMs:null}),refreshAuthorization:n=>this.refreshAuthorization({signal:n,timeoutMs:null}),shouldAttemptDirect:n=>this.shouldAttemptDirect(n),onDirectAvailable:()=>{this.markDirectAvailable(),this.setRoute("direct")},onDirectUnavailable:()=>this.markDirectUnavailable(),onRelayAvailable:()=>this.setRoute("relay"),acquireGrantKeyLease:(n,i,o)=>this.internals.acquireGrantKeyLease(n,i,o),authorityProofHeaders:(n,i,o,r,s)=>Le(this.keyStore,n,i,o,r,s)}),this.directStatus=this.directAccessMode==="disabled"?"disabled":"unavailable"}get directAccess(){return this.currentToken()?.authority?"disabled":this.directStatus}get route(){return this.currentToken()?.authority?"remote":this.currentRoute}notifyStorageChanged(){this.emitConnection()}async checkDirectAccess(e={}){return k(e,this.timeouts.watchStartMs,n=>this.checkDirectAccessWithinBudget(n.signal))}async checkDirectAccessWithinBudget(e){let n=this.currentToken();if(!this.directEligible(n))return this.setDirectStatus("disabled");let i=await Ot();return i==="denied"?this.setDirectStatus("denied"):(i==="prompt"||i===null)&&this.storage.getItem(this.internals.directPreferenceKey())!=="enabled"?this.setDirectStatus("permission_required"):this.probeDirectAccess(e)}async requestDirectAccess(e={}){return k(e,this.timeouts.watchStartMs,n=>this.requestDirectAccessWithinBudget(n.signal))}async requestDirectAccessWithinBudget(e){let n=this.currentToken();return this.directCapable(n)?(this.storage.setItem(this.internals.directPreferenceKey(),"enabled"),this.directRetryAt=0,this.probeDirectAccess(e)):this.setDirectStatus("disabled")}disableDirectAccess(){this.storage.setItem(this.internals.directPreferenceKey(),"disabled"),this.setDirectStatus("disabled"),this.setRoute("relay")}pendingMutations(){return this.storedPendingMutations().map(e=>this.pendingMutationStore.summary(e))}async pendingUpdate(e){let n=this.currentToken()?.collectionId;return n?fs(this.storedPendingMutations(),n,e):null}pendingMutation(e){let n=this.storedPendingMutation(e);return n?this.pendingMutationStore.summary(n):null}async recoverPendingMutation(e,n){let i=this.storedPendingMutation(e);if(!i)throw d("no_pending_mutation","There is no interrupted mutation to resume.");return W(n,this.timeouts.requestMs,o=>this.performOperationWithinBudget(i.operation,i.request?.input??{},de(n??{},o),i))}async performOperation(e,n,i={}){return W(i,this.timeouts.requestMs,o=>this.performOperationWithinBudget(e,n,de(i,o)))}async performOperationWithinBudget(e,n,i,o,r=!1,s=0,a=!1){Fe(i.signal);let c=this.grantKeyLeases();try{let l=await $(()=>this.currentToken(),c,i.signal);if(!l)throw d("not_authorized","Connect this application before accessing a collection.");return await c.retain(o?.keyHandle,i.signal),await this.performLeasedOperation(l,e,n,i,c,o,r,s,a)}finally{c.release()}}async performLeasedOperation(e,n,i,o,r,s,a=!1,c=0,l=!1){if(!e.operations.includes(n))throw d("insufficient_access",`This connection does not allow ${n}.`,{details:{required_operations:[n],granted_operations:[...e.operations],missing_operations:[n]}});let u=await this.shouldAttemptDirect(e);if(!u){if(!await this.authorizedToken({signal:o.signal,timeoutMs:null}))throw d("not_authorized","Reconnect this application to continue.");let A=await $(()=>this.currentToken(),r,o.signal);if(!A)throw d("not_authorized","Reconnect this application to continue.");e=A}let f=s?.requestId??(fr(n,i)?crypto.randomUUID():void 0),p;try{p=await this.sendOperation(e,n,i,u,r,o,f,l)}catch(y){throw rn(y,o.signal,f!==void 0&&this.storedPendingMutation(f)!==null?f:void 0,e.authority?"hosted_provider_unavailable":"relay_unavailable")}let h=p.response,m=h.status===409&&(await E(h.clone(),"invalid_operation_response","The collection authority returned an invalid operation response.").catch(()=>null))?.error?.code==="encryption_binding_stale";if((h.status===401||m)&&e.refreshToken){if(p.pendingMutation&&(p.directDeliveryUncertain||p.encryptedRequest&&p.resumingMutation))throw d("operation_outcome_unknown","The direct operation may have completed, but its encrypted grant changed before the response could be recovered. Refresh before making another change.",{operationOutcome:"unknown",details:{request_id:p.requestId}});p.pendingMutation&&this.clearPendingMutation(p.requestId),e=await this.refreshAuthorization({signal:o.signal,timeoutMs:null});let y=await $(()=>this.currentToken(),r,o.signal);if(!y)throw d("not_authorized","Reconnect this application to continue.");e=y,u=await this.shouldAttemptDirect(e);try{p=await this.sendOperation(e,n,i,u,r,o,f,l)}catch(A){throw rn(A,o.signal,f!==void 0&&this.storedPendingMutation(f)!==null?f:void 0,e.authority?"hosted_provider_unavailable":"relay_unavailable")}h=p.response}let P=y=>Fo({error:y,attempt:p,completedRetries:c,signal:o.signal,knownRejectedMutationRetry:l,clearPending:A=>this.clearPendingMutation(A),retry:(A,D)=>this.performOperationWithinBudget(n,i,o,A,a,c+1,D)}),v;try{v=await Ts(h,e.authority!==void 0)}catch(y){throw p.pendingMutation?J(p.requestId,y):y}let b=v.body;if(!h.ok){let y=v.httpError??z(b,"operation_failed","Collection operation failed.",h.status),A=await P(y);if(A.retried)return A.result;if(y.code==="fresh_request_required"&&!p.pendingMutation&&!a)return this.performOperationWithinBudget(n,i,o,void 0,!0);throw p.pendingMutation&&y.outcomeUnknown?y:p.pendingMutation&&(p.directDeliveryUncertain||p.encryptedRequest&&p.resumingMutation)?J(p.requestId,y):(p.pendingMutation&&!p.directDeliveryUncertain&&this.clearPendingMutation(p.requestId),y.code==="direct_operation_rejected"&&y.status===403&&this.invalidateRejectedAuthorization(e),y)}if(p.encryptedRequest){let y=b?.envelope,A=p.pendingMutationRecord,D=A?.encryption??e.encryption,S=A?.grantId??e.grantId,T=A?.applicationId??e.clientId,M=A?.keyHandle??e.keyHandle;if(!y||!D||!S||!M)throw p.pendingMutation?J(p.requestId,new Error("Encrypted operation response was missing its envelope.")):d("invalid_encrypted_response","The relay did not return an encrypted connector response.");try{let O=await $e(this.keyStore,M,{grantId:S,applicationId:T,encryption:D},p.encryptedRequest,y);if(!O.ok&&O.problem.code==="fresh_request_required"&&!p.pendingMutation&&!a)return this.performOperationWithinBudget(n,i,o,void 0,!0);if(!O.ok){let U=yr(O.problem);throw p.pendingMutation&&!U.outcomeUnknown&&this.clearPendingMutation(p.requestId),U}return p.pendingMutation&&this.clearPendingMutation(p.requestId),O.result}catch(O){throw O instanceof _?O:O instanceof q?p.pendingMutation?J(p.requestId,O):L(O.code,O.message):O}}let C=p.pendingMutationRecord?.request?.protocol_version??Y;if(b?.protocol_version!==C||b?.request_id!==p.requestId)throw p.pendingMutation?J(p.requestId,new Error("Operation response protocol or request ID did not match.")):d("invalid_operation_response","The collection authority returned a response for a different protocol request.");if(b.ok===!1){if(!ht(b.problem))throw p.pendingMutation?J(p.requestId,new Error("Operation rejection did not contain a canonical problem.")):d("invalid_operation_response","The collection authority returned an invalid operation problem.");let y=new _(b.problem),A=await P(y);if(A.retried)return A.result;throw p.pendingMutation&&!y.outcomeUnknown&&this.clearPendingMutation(p.requestId),y}if(b.ok!==!0||!("result"in b))throw p.pendingMutation?J(p.requestId,new Error("Successful operation response did not contain a result.")):d("invalid_operation_response","The collection authority returned an incomplete operation response.");return p.pendingMutation&&this.clearPendingMutation(p.requestId),b.result}async performAuthoritySyncRequest(e,n,i,o,r,s={}){return W(s,this.timeouts.syncMs,async a=>{let c=this.grantKeyLeases();try{let l=await $(()=>this.currentToken(),c,a.signal);l&&await this.authorizedToken({signal:a.signal,timeoutMs:null}),l=await $(()=>this.currentToken(),c,a.signal),Ms(l,e,n);let u=await Hi(this.keyStore,l,i,o,r,a.signal);u.status===401&&l.refreshToken&&(l=await this.refreshAuthorization({signal:a.signal,timeoutMs:null}),l=await $(()=>this.currentToken(),c,a.signal),Ms(l,e,n),u=await Hi(this.keyStore,l,i,o,r,a.signal));let f=await E(u,"invalid_operation_response","The collection authority returned an invalid synchronization response.");if(!u.ok)throw z(f,"sync_failed","Collection synchronization failed.",u.status);return f}catch(l){let u=i==="POST"&&o==="mutations"&&r&&typeof r=="object"&&typeof r.mutation_id=="string"?r.mutation_id:void 0;throw rn(l,a.signal,u,"hosted_provider_unavailable")}finally{c.release()}})}async sendOperation(e,n,i,o,r,s={},a,c=!1){let l=i??{},u,f=!1,p=!1,h=a??crypto.randomUUID(),m=null,P,v;if(a!==void 0){if(m=this.storedPendingMutation(a),P=m?.inputFingerprint??await wr(n,i),m||(v=await ps(e.collectionId,n,i)),m){if(m.collectionId!==e.collectionId||m.operation!==n||m.inputFingerprint!==P)throw d("pending_mutation_unresolved","A previous write still has an unknown outcome. Retry that exact write before making another change.");h=m.requestId,p=!c}f=!0}let b=m?.mutation??be(n,i);if(m?.envelope&&(e.authority||!e.encryption))throw d("pending_mutation_unresolved","The pending write requires its encrypted relay authority. Reconnect that authority before recovery.");if(m?.request&&e.encryption&&!e.authority)throw d("pending_mutation_unresolved","The pending write belongs to a different authority transport. Reconnect that authority before recovery.");if(e.encryption&&!e.authority){if(!e.grantId||!e.keyHandle)throw d("missing_grant_key","Reconnect this application to restore encrypted access.");try{if(f)if(m){if(!m.envelope)throw d("pending_mutation_unresolved","The pending write belongs to a different transport. Reconnect before retrying it.");u=hr(m.envelope,s.deadlineUnixMs)}else u=await me(this.keyStore,e.keyHandle,{grantId:e.grantId,applicationId:e.clientId,encryption:e.encryption},n,i,h,s.deadlineUnixMs),this.pendingMutationStore.store({collectionId:e.collectionId,...e.grantId?{grantId:e.grantId}:{},keyId:e.encryption.key_id,keyHandle:e.keyHandle,applicationId:e.clientId,encryption:e.encryption,operation:n,mutation:b,inputFingerprint:P,...v?{recordDigest:v}:{},requestId:h,envelope:u,createdAt:Date.now()});else u=await me(this.keyStore,e.keyHandle,{grantId:e.grantId,applicationId:e.clientId,encryption:e.encryption},n,i,void 0,s.deadlineUnixMs)}catch(S){throw S instanceof q?L(S.code,S.message):S}h=u.request_id,l=u}else{let S=m?.request??{protocol_version:Y,request_id:h,input:l};l=S,f&&!m&&this.pendingMutationStore.store({collectionId:e.collectionId,...e.grantId?{grantId:e.grantId}:{},operation:n,mutation:b,inputFingerprint:P,...v?{recordDigest:v}:{},requestId:h,request:S,createdAt:Date.now()})}if(o&&u&&!e.authority){let S=!1;try{let O=await fetch(`${this.loopbackUrl}/v1/operations`,Se({method:"POST",headers:{"content-type":"application/mdbase-connect+json"},body:JSON.stringify(u),signal:s.signal}));if(!await Je(O)||await Be(O))return O.ok&&(this.markDirectAvailable(),this.setRoute("direct")),{response:O,requestId:h,encryptedRequest:u,pendingMutation:f,...f?{pendingMutationRecord:m??this.storedPendingMutation(h)??void 0}:{},resumingMutation:p};S=O.status>=500,this.markDirectUnavailable()}catch(O){if(s.signal?.aborted)throw f?J(h,O):O;S=!0,await Ot()==="denied"?this.setDirectStatus("denied"):this.markDirectUnavailable()}let T;try{e.expiresAt<=Date.now()+3e4&&await this.refreshAuthorization({signal:s.signal,timeoutMs:null});let O=await $(()=>this.currentToken(),r,s.signal);if(!O)throw d("not_authorized","Reconnect this application to continue.");T=O}catch(O){throw f&&(S||p)?J(h,O):O}let M;f||(u=await Os(this.keyStore,T,n,i,s.deadlineUnixMs),h=u.request_id);try{M=await fetch(`${this.serverUrl}/v1/authorities/${encodeURIComponent(T.collectionId)}/operations/${n}`,{method:"POST",headers:{authorization:`Bearer ${T.accessToken}`,"content-type":"application/json"},body:JSON.stringify(u),signal:s.signal})}catch(O){throw f?J(h,O):O}return M.ok&&this.setRoute("relay"),{response:M,requestId:h,encryptedRequest:u,directDeliveryUncertain:S,pendingMutation:f,...f?{pendingMutationRecord:m??this.storedPendingMutation(h)??void 0}:{},resumingMutation:p}}let C=e.authority?`${e.authority.operationsUrl}/${n}`:`${this.serverUrl}/v1/authorities/${encodeURIComponent(e.collectionId)}/operations/${n}`,y=JSON.stringify(l),A=e.authority?await Le(this.keyStore,e,"POST",C,y,e.authority.accessToken):{},D;try{D=await gr(C,e.authority?.accessToken??e.accessToken,A,y,s.signal)}catch(S){throw f?J(h,S):S}return D.ok&&this.setRoute(e.authority?"remote":"relay"),{response:D,requestId:h,encryptedRequest:u,pendingMutation:f,...f?{pendingMutationRecord:m??this.storedPendingMutation(h)??void 0}:{},resumingMutation:p}}directCapable(e){return Ps(e,this.directAccessMode)}hasResumableMutationTransport(){return this.currentToken()!==null}directEligible(e){return e!==null&&this.directCapable(e)&&this.storage.getItem(this.internals.directPreferenceKey())!=="disabled"}async shouldAttemptDirect(e){if(!this.directEligible(e))return!1;if(this.directStatus==="available")return!0;if(this.directStatus==="unavailable"&&Date.now()<this.directRetryAt)return!1;let n=await Ot();return n==="denied"?(this.setDirectStatus("denied"),!1):(n==="prompt"||n===null)&&this.storage.getItem(this.internals.directPreferenceKey())!=="enabled"?(this.setDirectStatus("permission_required"),!1):(this.setDirectStatus("checking"),!0)}async probeDirectAccess(e){this.setDirectStatus("checking");try{if(await As(this.loopbackUrl,Y,e))return this.markDirectAvailable(),"available"}catch(n){throw this.markDirectUnavailable(),n}return await Ot()==="denied"?this.setDirectStatus("denied"):(this.markDirectUnavailable(),"unavailable")}markDirectAvailable(){this.directFailures=0,this.directRetryAt=0,this.setDirectStatus("available")}markDirectUnavailable(){this.directFailures+=1,this.directRetryAt=Date.now()+Math.min(6e4,1e3*2**(this.directFailures-1)),this.setDirectStatus("unavailable")}setDirectStatus(e){return this.directStatus!==e&&(this.directStatus=e,this.emitConnection()),e}setRoute(e){this.currentRoute!==e&&(this.currentRoute=e,this.emitConnection())}emitConnection(){this.onChange()}invalidateRejectedAuthorization(e){let n=F(this.storage.getItem(this.internals.tokenKey(this.collectionId)));!n||!mr(n,e)||(this.internals.removeToken(this.collectionId,n.keyHandle),this.currentRoute="relay",this.directStatus=this.directAccessMode==="disabled"?"disabled":"unavailable",this.emitConnection())}currentToken(){return Ss({stored:this.storage.getItem(this.internals.tokenKey(this.collectionId)),collectionId:this.collectionId,relayEncryption:this.internals.relayEncryption,invalidate:(e,n="invalid_stored_grant")=>this.internals.removeToken(this.collectionId,e,n),directCapable:e=>this.directCapable(e)})}async authorizedToken(e={}){let n=this.currentToken();if(!n)return null;if(n.expiresAt>Date.now()+3e4)return n;if(!n.refreshToken||(n.refreshExpiresAt??0)<=Date.now()){if(this.directCapable(n))throw d("relay_authorization_expired","Direct access is still available on this computer, but using the relay requires reconnecting this application.");return this.internals.removeToken(this.collectionId,n.keyHandle),null}return this.refreshAuthorization(e)}refreshAuthorization(e={}){return this.refreshOperations.run("refresh",e,this.timeouts.requestMs,n=>this.performRefresh(n))}async performRefresh(e){let n=this.grantKeyLeases();try{let i=await $(()=>this.currentToken(),n,e);return await ws({current:i,serverUrl:this.serverUrl,keyStore:this.keyStore,signal:e,currentToken:()=>this.currentToken(),directCapable:o=>this.directCapable(o),removeToken:o=>this.internals.removeToken(this.collectionId,o),storeTokenResponse:(o,r,s)=>this.storeTokenResponse(o,r,s)})}finally{n.release()}}storeTokenResponse(e,n,i){if(e.collection_id!==this.collectionId)throw d("collection_mismatch","The refreshed authorization belongs to a different collection.");let o=this.internals.storeTokenResponse(e,n,i);return this.currentRoute=o.authority?"remote":"relay",this.directStatus=o.authority||this.directAccessMode==="disabled"?"disabled":"unavailable",this.emitConnection(),o}storedPendingMutations(){return this.pendingMutationStore.list(this.currentToken()?.collectionId??null)}storedPendingMutation(e){return this.pendingMutationStore.find(this.currentToken()?.collectionId??null,e)}clearPendingMutation(e){let n=this.pendingMutationStore.take(e);n?.keyHandle&&this.internals.deleteGrantKeyWhenUnused(this.collectionId,n.keyHandle)}grantKeyLeases(){return new Pe(this.collectionId,(e,n,i)=>this.internals.acquireGrantKeyLease(e,n,i))}};function Ms(t,e,n){if(!(t?.authority&&t.collectionId===e&&t.authority.replicaId===n))throw d("authority_authorization_changed","Reconnect this collection authority before synchronizing.")}var Un=class{constructor(e,n){this.signal=n;this.iterator=dl(e)}signal;iterator;remainder=new Uint8Array;remainderOffset=0;maxSourceChunkBytes=null;iteratorClosing=!1;ended=!1;setMaxSourceChunkBytes(e){this.maxSourceChunkBytes=e}async read(e){let n=new Uint8Array(e),i=0;for(;i<e;){if(this.remainderOffset===this.remainder.byteLength){let r=await this.nextSourceChunk();if(r.done)throw this.ended=!0,d("invalid_request","Streamed file bytes ended before the declared size.");if(!(r.value instanceof Uint8Array))throw d("invalid_request","A streamed file chunk was not a Uint8Array.");if(this.maxSourceChunkBytes===null)throw new Error("Stream source was read before upload negotiation completed.");if(r.value.byteLength>this.maxSourceChunkBytes)throw d("invalid_request",`A streamed file chunk exceeded the negotiated ${this.maxSourceChunkBytes}-byte upload part size.`);if(this.remainder=r.value,this.remainderOffset=0,this.remainder.byteLength===0)continue}let o=Math.min(e-i,this.remainder.byteLength-this.remainderOffset);n.set(this.remainder.subarray(this.remainderOffset,this.remainderOffset+o),i),i+=o,this.remainderOffset+=o}return n}async expectEnd(){if(this.remainderOffset<this.remainder.byteLength)throw d("invalid_request","Streamed file bytes exceed the declared size.");for(;!this.ended;){let e=await this.nextSourceChunk();if(e.done){this.ended=!0;return}if(!(e.value instanceof Uint8Array))throw d("invalid_request","A streamed file chunk was not a Uint8Array.");if(e.value.byteLength>0)throw d("invalid_request","Streamed file bytes exceed the declared size.")}}async close(){this.ended=!0,this.closeIterator()}async nextSourceChunk(){Is(this.signal);let e=this.iterator.next(),n=this.signal;if(!n)return e;let i=()=>{},o=new Promise((r,s)=>{let a=()=>{this.closeIterator(),s(ks(n))};n.addEventListener("abort",a,{once:!0}),i=()=>n.removeEventListener("abort",a),n.aborted&&a()});try{let r=await Promise.race([e,o]);return Is(n),r}finally{i()}}closeIterator(){if(!this.iteratorClosing){this.iteratorClosing=!0;try{this.iterator.return?.()?.catch(()=>{})}catch{}}}};function dl(t){if(typeof t.getReader=="function"){let n=t.getReader(),i=!1,o=()=>{i||(i=!0,n.releaseLock())};return{async next(){if(i)return{done:!0,value:void 0};let r=await n.read();return r.done&&o(),r},async return(){if(!i)try{await n.cancel()}finally{o()}return{done:!0,value:void 0}}}}let e=t;if(typeof e[Symbol.asyncIterator]!="function")throw d("invalid_request","Streamed files require a readable byte stream.");return e[Symbol.asyncIterator]()}function Is(t){if(t?.aborted)throw ks(t)}function ks(t){return d("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:t?.reason})}var dt=class{constructor(e,n,i,o,r=Ve(),s=async()=>R(!1)){this.capability=e;this.request=n;this.framed=i;this.hosted=o;this.timeouts=r;this.supportsAuthorityFeature=s}capability;request;framed;hosted;timeouts;supportsAuthorityFeature;list(e={}){return cs(this.capability,this.request,e,this.timeouts.fileIndexMs)}stat(e,n={}){return ls(this.capability,this.request,this.supportsAuthorityFeature,i=>this.list(i),e,n,this.timeouts.fileIndexMs)}async upload(e,n,i={}){return W(i,this.timeouts.uploadMs,o=>this.uploadWithinBudget(e,n,{...i,signal:o.signal,timeoutMs:null}))}async uploadWithinBudget(e,n,i){this.requireAction(i.ifRevision?"replace":"add");let o=Ko(n,i.mediaType),r=ai(i.concurrency),s=await Bo(o,i.signal,a=>{i.onProgress?.({phase:"hashing",transferredBytes:a,totalBytes:o.size})});return this.uploadKnownSource(e,o.size,`sha256:${s}`,(i.mediaType??o.type)||void 0,i,r,async(a,c,l)=>o.slice(c,c+l))}async uploadStream(e,n,i={}){return W(i,this.timeouts.uploadMs,o=>this.uploadStreamWithinBudget(e,n,{...i,signal:o.signal,timeoutMs:null}))}async uploadStreamWithinBudget(e,n,i){if(this.requireAction(i.ifRevision?"replace":"add"),!Number.isSafeInteger(n.size)||n.size<0)throw d("invalid_request","Streamed file size must be a non-negative safe integer.");if(!$t.test(n.contentDigest))throw d("invalid_request","Streamed files require a lowercase SHA-256 content digest.");let o=new Un(n.stream,i.signal),r=new xe;return this.uploadKnownSource(e,n.size,n.contentDigest,i.mediaType??n.mediaType,i,1,async(s,a,c)=>{let l=await o.read(c);return r.update(l),l},async()=>{if(await o.expectEnd(),`sha256:${r.digestHex()}`!==n.contentDigest)throw d("invalid_request","Streamed file bytes do not match the declared SHA-256 digest.")},()=>o.close(),s=>o.setMaxSourceChunkBytes(s))}async uploadKnownSource(e,n,i,o,r,s,a,c,l,u){let f=r.transferId??crypto.randomUUID();if(!jo.test(f))throw d("invalid_request","File transfer ID must be a UUID.");let p=!1;try{let h=await this.request("POST","uploads",{protocol_version:1,type:"open_file_upload",transfer_id:f,path:e,size:n,content_digest:i,...o?{media_type:o}:{},...r.ifRevision?{if_revision:r.ifRevision}:{}},r.signal);if(ci(h,f,"upload"),h.total_size!==n||h.strategy.kind==="object_ranges")throw d("invalid_operation_response","The authority returned an incompatible upload strategy.");let m=h.strategy.kind==="framed_chunks";if(m&&!this.framed)throw d("invalid_operation_response","Encrypted file chunk delivery is unavailable.");let P=h.strategy.kind==="object_put"?Math.max(1,n):h.strategy.kind==="framed_chunks"?h.strategy.chunk_size:h.strategy.part_size,v=h.strategy.kind==="object_put"?1:Math.ceil(n/P),b=h.prepared_upload_part;if(b!==void 0){if(ui(b,f,0,0,n,"PUT"),h.strategy.kind!=="object_put"||pi(b.headers).get("if-none-match")!=="*")throw d("invalid_operation_response","Upload bootstrap must be a create-only single PUT.");Date.parse(b.expires_at)<=Date.now()+6e4&&(b=void 0)}let C=b?void 0:await this.request("GET",`transfers/${encodeURIComponent(f)}`,void 0,r.signal);if(C&&(li(C,h),C.state!=="open"&&C.state!=="committed"))throw d("invalid_operation_response",`The authority cannot resume a ${C.state} file transfer.`);if(u?.(P),!m&&C?.received.length===v){let M=await this.tryReplayUploadCommit(f,h.strategy.kind==="object_multipart"?C.uploaded_parts:void 0,r.signal);if(M)return p=!0,fe(M.file)}let y=new Set(C?.received??[]),A=new Map((C?.uploaded_parts??[]).map(M=>[M.part_number-1,M])),D=[...y].reduce((M,O)=>M+di(n,P,O),0),S=await Ho(v,s,async M=>{let O=M*P,U=Math.min(P,Math.max(0,n-O)),H=await a(M,O,U);if(Qo(H)!==U)throw d("invalid_request","Streamed file bytes ended before the declared size.");if(y.has(M))return A.get(M)??null;let B=m?await Jt(async()=>this.framed.uploadChunk(h,M,await Vo(H),r.signal),r.signal).then(()=>null):await this.uploadPart(f,M,O,H,U,h.strategy.kind==="object_multipart",r.signal,b?{session:h,part:b}:void 0);return D+=U,r.onProgress?.({phase:"uploading",transferredBytes:D,totalBytes:n}),B});await c?.();let T=await this.commitUpload(f,h.strategy.kind==="object_multipart"?S.filter(M=>M!==null):void 0,r.signal);if(T.protocol_version!==1||T.type!=="file_upload_committed"||T.transfer_id!==f||T.file.path!==e||T.file.size!==n||T.file.content_digest!==i)throw d("invalid_operation_response","The authority returned an invalid file receipt.");return p=!0,fe(T.file)}catch(h){throw _e(h)}finally{await l?.().catch(()=>{}),!p&&r.transferId===void 0&&await this.abort(f)}}async download(e,n={}){let i=await this.downloadBytes(e,n);return new Blob([i.buffer],{type:e.mediaType??""})}async downloadStream(e,n={}){return W(n,this.timeouts.requestMs,i=>this.openDownloadStream(e,n,i.signal))}async openDownloadStream(e,n,i){this.requireAction("read");let o=ai(n.concurrency),r=crypto.randomUUID(),s;try{if(s=await this.request("POST","downloads",{protocol_version:1,type:"open_file_download",transfer_id:r,file_id:e.fileId,revision:e.revision},i),ci(s,r,"download"),s.total_size!==e.size||s.strategy.kind!=="object_ranges"&&s.strategy.kind!=="framed_chunks")throw d("invalid_operation_response","The authority returned an incompatible download session.");if(s.strategy.kind==="framed_chunks"&&!this.framed)throw d("invalid_operation_response","Encrypted file chunk delivery is unavailable.");if(s.strategy.kind==="object_ranges"&&e.size>0&&!this.hosted)throw d("invalid_operation_response","Authenticated hosted file delivery is unavailable.")}catch(S){throw await this.abort(r),_e(S)}let a=s.strategy.kind==="framed_chunks"?s.strategy.chunk_size:s.strategy.part_size,c=Math.ceil(e.size/a),l=new xe,u=0,f=0,p=null,h=0,m=!1,P=new AbortController,v=n.signal?AbortSignal.any([n.signal,P.signal]):P.signal,b=new Map,C=0,y=()=>{if(s.strategy.kind==="framed_chunks")for(;C<c&&b.size<o;){let S=C;C+=1;let T=Jt(()=>this.framed.downloadChunk(s,S,v),v).then(M=>({ok:!0,chunk:M}),M=>({ok:!1,error:M}));b.set(S,T)}},A=async()=>{m||(m=!0,P.abort(),await p?.cancel().catch(()=>{}),p=null,await Promise.all(b.values()),b.clear(),await this.abort(r))},D=()=>{if(h!==e.size||`sha256:${l.digestHex()}`!==e.contentDigest)throw d("invalid_operation_response","Downloaded file bytes failed integrity verification.")};return new ReadableStream({pull:async S=>{try{if(ee(v),s.strategy.kind==="object_ranges")for(;;){if(!p){if(u>=c){D(),S.close(),A();return}let N=u*a;f=Math.min(a,e.size-N),p=(await Jt(()=>this.hosted.downloadPart(s,u,f,v),v)).getReader()}let B=await p.read();if(B.done){if(p.releaseLock(),p=null,f!==0)throw d("invalid_operation_response","A hosted file range ended before its declared byte length.");u+=1;continue}if(!(B.value instanceof Uint8Array))throw d("invalid_operation_response","A hosted file range returned a non-byte chunk.");if(B.value.byteLength!==0){if(B.value.byteLength>f)throw d("invalid_operation_response","A hosted file range exceeded its declared byte length.");f-=B.value.byteLength,l.update(B.value),h+=B.value.byteLength,n.onProgress?.({phase:"downloading",transferredBytes:h,totalBytes:e.size}),S.enqueue(B.value);return}}if(u>=c){D(),S.close(),A();return}let T=u*a,M=Math.min(a,e.size-T);y();let O=b.get(u);if(!O)throw d("invalid_operation_response","A file chunk was not scheduled.");let U=await O;if(b.delete(u),!U.ok)throw U.error;let H=U.chunk;if(H.byteLength!==M)throw d("invalid_operation_response","A file chunk had the wrong byte length.");l.update(H),h+=H.byteLength,u+=1,y(),n.onProgress?.({phase:"downloading",transferredBytes:h,totalBytes:e.size}),u===c&&D(),S.enqueue(H),u===c&&(S.close(),A())}catch(T){let M=n.signal?.aborted?d("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:n.signal.reason}):T;await A(),S.error(_e(M))}},cancel:A})}async downloadBytes(e,n={}){if(e.size>si)throw d("invalid_request",`download() buffers at most ${si} bytes; use downloadStream() for larger files.`);let i=await this.downloadStream(e,n),o=new Uint8Array(e.size),r=i.getReader(),s=0;try{for(;;){let a=await r.read();if(a.done)break;if(a.value.byteLength>o.byteLength-s)throw d("invalid_operation_response","Downloaded file bytes failed integrity verification.");o.set(a.value,s),s+=a.value.byteLength}if(s!==o.byteLength)throw d("invalid_operation_response","Downloaded file bytes failed integrity verification.");return o}catch(a){throw await r.cancel().catch(()=>{}),a}finally{r.releaseLock()}}async move(e,n,i={}){return W(i,this.timeouts.requestMs,o=>this.moveWithinBudget(e,n,{...i,signal:o.signal,timeoutMs:null}))}async moveWithinBudget(e,n,i){this.requireAction("move");let o=i.mutationId??crypto.randomUUID(),r;try{r=await this.request("POST",`${encodeURIComponent(e.fileId)}/move`,{protocol_version:1,type:"move_file",mutation_id:o,file_id:e.fileId,if_revision:i.ifRevision??e.revision,from_path:e.path,path:n,update_references:!1},i.signal)}catch(s){throw _e(s)}if(r.protocol_version!==1||r.type!=="file_moved"||r.mutation_id!==o||r.file.file_id!==e.fileId||r.file.path!==n)throw d("invalid_operation_response","The authority returned an invalid file move receipt.");return fe(r.file)}async delete(e,n={}){return W(n,this.timeouts.requestMs,i=>this.deleteWithinBudget(e,{...n,signal:i.signal,timeoutMs:null}))}async deleteWithinBudget(e,n){this.requireAction("delete");let i=n.mutationId??crypto.randomUUID(),o;try{o=await this.request("POST",`${encodeURIComponent(e.fileId)}/delete`,{protocol_version:1,type:"delete_file",mutation_id:i,file_id:e.fileId,if_revision:n.ifRevision??e.revision,path:e.path},n.signal)}catch(r){throw _e(r)}if(o.protocol_version!==1||o.type!=="file_deleted"||o.mutation_id!==i||o.file_id!==e.fileId||o.previous_path!==e.path)throw d("invalid_operation_response","The authority returned an invalid file delete receipt.");return{protocolVersion:o.protocol_version,type:o.type,mutationId:o.mutation_id,fileId:o.file_id,previousPath:o.previous_path,revision:o.revision}}async uploadPart(e,n,i,o,r,s,a,c){for(let l=1;l<=_t;l+=1){ee(a);try{let u=l===1&&c&&Date.parse(c.part.expires_at)>Date.now()+6e4;if(c&&!u){let v=await this.request("GET",`transfers/${encodeURIComponent(e)}`,void 0,a);if(li(v,c.session),v.state!=="open"&&v.state!=="committed")throw d("invalid_operation_response",`The authority cannot resume a ${v.state} file transfer.`);if(v.received.includes(n))return{part_number:n+1,etag:""}}let f=u?c.part:await this.request("POST",`uploads/${encodeURIComponent(e)}/parts`,{protocol_version:1,type:"prepare_file_upload_part",transfer_id:e,part_number:n+1,content_length:r},a);ui(f,e,n,i,r,"PUT");let p=pi(f.headers),h=await fetch(f.url,{method:f.method,headers:p,body:o,redirect:"error",signal:a});if(h.status===412&&!s&&p.get("if-none-match")==="*")return{part_number:n+1,etag:""};if(!h.ok)throw new Error(`Object upload failed with HTTP ${h.status}.`);let P=h.headers.get("etag");if(s&&!P)throw new Error("Multipart object upload did not return an ETag.");return{part_number:n+1,etag:P??""}}catch(u){if(a?.aborted||l===_t)throw u}}throw new Error("Unreachable upload retry state.")}async tryReplayUploadCommit(e,n,i){try{return await this.commitUpload(e,n,i)}catch(o){if(o instanceof _&&o.code==="file_upload_incomplete")return null;throw o}}async commitUpload(e,n,i){let o;for(let r=1;r<=_t;r+=1){ee(i);try{return await this.request("POST",`uploads/${encodeURIComponent(e)}/commit`,{protocol_version:1,type:"commit_file_upload",transfer_id:e,...n===void 0?{}:{parts:n}},i)}catch(s){if(o=s,i?.aborted||s instanceof _||r===_t)throw s}}throw o}requireAction(e){if(!this.capability()?.actions.includes(e))throw d("not_authorized",`This connection is not authorized to ${e} files.`)}async abort(e){await this.request("DELETE",`transfers/${encodeURIComponent(e)}`).catch(()=>{})}};var ut=class{constructor(e,n,i={}){this.adapter=n;this.record=e,this.baseBody=this.body=n.body(e),this.seen.add(n.revision(e)),this.idleMs=i.autosave===!1?void 0:i.autosave?.idleMs??1e3,this.current=this.compute()}adapter;record;baseBody;body;patch={};remote=null;problem=null;refreshProblem=null;deleted=!1;busy=!1;pending;incoming=[];seen=new Set;listeners=new Set;tail=Promise.resolve();queued=0;inFlight;timer;lastEdit=0;disposed=!1;idleMs;current;get snapshot(){return this.current}getSnapshot=()=>this.current;subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});setBody(e){e!==this.body&&(this.body=e,this.edited())}patchFrontmatter(e){this.patch={...this.patch,...e},this.edited()}restore(e){let n=this.adapter.body(this.record),i=this.adapter.frontmatter?.(this.record)??{},o=Object.fromEntries(Object.entries(e.patch??{}).filter(([r,s])=>JSON.stringify(i[r]??null)!==JSON.stringify(s)));e.body===n&&Object.keys(o).length===0||(this.body=e.body,this.patch=o,(e.body!==n&&e.baseBody!==n||Object.keys(o).some(r=>!e.baseFrontmatter||JSON.stringify(e.baseFrontmatter[r]??null)!==JSON.stringify(i[r]??null)))&&(this.remote=this.record),this.emit())}resumeRecovery(e){this.pending||this.busy||(this.pending={requestId:e,sent:"restored"},this.emit(),this.autosave())}dispose(){this.disposed=!0,clearTimeout(this.timer),this.listeners.clear()}autosave(){this.lastEdit=Date.now(),this.schedule()}receive(e){if(!this.seen.has(this.adapter.revision(e))){if(this.busy||this.pending){this.incoming.push(e);return}this.seen.add(this.adapter.revision(e)),this.classify(e),this.emit()}}refresh(e){return this.run(async()=>{let n=this.adapter.read;if(!n||this.pending)return R(this.record);let i=await n(this.record,e);return i.ok?(this.refreshProblem=null,this.seen.add(this.adapter.revision(i.value)),this.classify(i.value),this.emit(),R(this.record)):(i.problem.code==="file_not_found"?this.markDeleted():(this.refreshProblem=i.problem,this.emit()),i)})}accept(e){this.seen.add(this.adapter.revision(e));let n=this.adapter.body(e);this.body===this.baseBody&&(this.body=n),this.baseBody=n;let i=this.adapter.frontmatter?.(e)??{};for(let[o,r]of Object.entries(this.patch))Ue(i[o],r)&&delete this.patch[o];this.record=e,this.remote=null,this.problem=null,this.refreshProblem=null,this.emit()}markDeleted(){clearTimeout(this.timer),this.deleted=!0,this.emit()}save(e){if(clearTimeout(this.timer),this.inFlight)return this.inFlight;let n=this.run(()=>this.pending?this.recoverPending(e):this.write(e,!0));this.inFlight=n;let i=()=>{this.inFlight===n&&(this.inFlight=void 0)};return n.then(i,i),n}async flush(e){for(;;){if(this.deleted)return g($i());if(this.remote)return g(Wi());if(!this.inFlight&&!this.pending&&!this.dirtyLocally())return R(this.record);let n=await this.save(e);if(!n.ok)return n}}run(e){let n=this.queued===0?e():this.tail.then(e);this.queued+=1;let i=()=>{this.queued-=1};return this.tail=n.then(i,i),n}resolve(e){let n=this.remote;!n||this.busy||(this.record=n,this.remote=null,this.problem=null,this.baseBody=this.adapter.body(n),"body"in e?this.body=e.body:e.keep==="theirs"&&(this.body=this.baseBody,this.patch={}),this.emit(),this.dirtyLocally()&&this.autosave())}discard(){this.busy||(clearTimeout(this.timer),this.record=this.remote??this.record,this.remote=null,this.problem=null,this.baseBody=this.body=this.adapter.body(this.record),this.patch={},this.emit())}edited(){this.problem=null,this.lastEdit=Date.now(),this.emit(),this.schedule()}schedule(){if(clearTimeout(this.timer),this.disposed||this.idleMs===void 0||this.remote||this.deleted)return;let e=Math.max(0,this.lastEdit+this.idleMs-Date.now());this.timer=setTimeout(()=>{this.save()},e)}dirtyLocally(){return this.body!==this.baseBody||Object.keys(this.patch).length>0}async write(e,n){if(this.remote)return g(Wi());if(this.deleted)return g($i());if(!this.dirtyLocally())return R(this.record);let i={};this.body!==this.baseBody&&(i.body=this.body),Object.keys(this.patch).length&&(i.patch=structuredClone(this.patch)),this.busy=!0,this.emit();let o=await this.guard(()=>this.adapter.write(this.record,{...i},e));if(o.ok)return this.acknowledge(o.value,i),R(this.record);let r=ul(o.problem);if(r)return this.busy=!1,this.problem=o.problem,this.pending={requestId:r,sent:i},this.emit(),this.schedule(),o;let s=await this.classifyFailure(o.problem,e);return s==="resolved"?R(this.record):s==="rebased"&&n?this.write(e,!1):this.failure(o.problem)}async recoverPending(e){let n=this.pending,i=this.adapter.recover;if(!i)return g(w("pending_mutation_unresolved","Exact recovery of the interrupted write is unavailable. No new write was attempted."));this.busy=!0,this.emit();let o=await this.guard(()=>i(n.requestId,e));return o.ok?(n.sent==="restored"?(this.pending=void 0,this.busy=!1,this.accept(o.value),this.settle()):this.acknowledge(o.value,n.sent),R(this.record)):o.problem.operation_outcome!=="unknown"&&o.problem.code!=="operation_outcome_unknown"&&this.adapter.isPending?.(n.requestId)===!1?(this.pending=void 0,await this.classifyFailure(o.problem,e),this.failure(o.problem)):(this.busy=!1,this.problem=o.problem,this.emit(),o)}async guard(e){try{return await e()}catch(n){throw this.busy=!1,this.emit(),n}}failure(e){return this.deleted?g($i()):this.remote?g(Wi()):g(e)}acknowledge(e,n){this.seen.add(this.adapter.revision(e)),this.record=e,n.body!==void 0&&(this.baseBody=n.body);for(let[i,o]of Object.entries(n.patch??{}))i in this.patch&&Ue(this.patch[i],o)&&delete this.patch[i];this.problem=null,this.refreshProblem=null,this.pending=void 0,this.settle(),this.dirtyLocally()&&this.schedule()}async classifyFailure(e,n){let i=this.adapter.revision(this.record),o=this.adapter.read,r=o?await this.guard(()=>o(this.record,n)):void 0;return r&&!r.ok&&r.problem.code==="file_not_found"?(this.deleted=!0,this.settle(),"failed"):!r?.ok||this.adapter.revision(r.value)===i?(this.problem=e,this.settle(),"failed"):(this.seen.add(this.adapter.revision(r.value)),this.classify(r.value),this.settle(),this.remote?"failed":this.dirtyLocally()?"rebased":"resolved")}settle(){this.busy=!1;for(let e of this.incoming.splice(0))this.seen.has(this.adapter.revision(e))||(this.seen.add(this.adapter.revision(e)),this.classify(e));this.emit()}classify(e){if(this.adapter.revision(e)===this.adapter.revision(this.record))return;let n=this.adapter.body(this.record),i=this.adapter.body(e),o=i!==n,r=this.body!==this.baseBody,s=this.adapter.frontmatter?.(this.record)??{},a=this.adapter.frontmatter?.(e)??{};if(r&&o&&i!==this.body||Object.entries(this.patch).some(([l,u])=>!Ue(a[l],s[l])&&!Ue(a[l],u))){clearTimeout(this.timer),this.remote=e;return}this.remote=null,this.record=e,o&&(this.baseBody=this.body=i);for(let[l,u]of Object.entries(this.patch))Ue(a[l],u)&&delete this.patch[l];this.dirtyLocally()||(this.problem=null)}compute(){let e=this.busy||!!this.pending||this.dirtyLocally();return{state:this.deleted?"deleted":this.remote?"conflict":this.busy?"saving":this.pending?"recovery":this.problem||this.refreshProblem?"error":e?"unsaved":"saved",body:this.body,frontmatter:{...this.adapter.frontmatter?.(this.record)??{},...this.patch},record:this.record,remote:this.remote,dirty:e,problem:this.problem??this.refreshProblem,...this.pending?{pendingRequestId:this.pending.requestId}:{}}}emit(){this.current=this.compute(),this.listeners.forEach(e=>e())}};function Wi(){return w("concurrent_modification","This record changed elsewhere. Local changes are kept until the conflict is resolved.")}function $i(){return w("file_not_found","This record no longer exists. Local changes are kept.")}function ul(t){return t.code==="operation_outcome_unknown"?t.details.request_id:void 0}function Ue(t,e){if(t===e)return!0;if(typeof t!="object"||typeof e!="object"||t===null||e===null)return!1;if(Array.isArray(t)||Array.isArray(e))return Array.isArray(t)&&Array.isArray(e)&&t.length===e.length&&t.every((i,o)=>Ue(i,e[o]));let n=Object.keys(t);return n.length===Object.keys(e).length&&n.every(i=>i in e&&Ue(t[i],e[i]))}var pl=4,fl=4,pt=class{constructor(e,n=async()=>null){this.connection=e;this.pendingUpdate=n}connection;pendingUpdate;entries=new Map;opening=new Map;refreshes=new Map;refreshQueue=new Set;activeRefreshes=0;followers=0;async open(e,n={}){for(;;){let i=this.entries.get(e);if(i)return R(this.lease(i));let o=this.opening.get(e),r=o??this.load(e,n);o||(this.opening.set(e,r),r.then(()=>this.opening.delete(e)));let s=await r;if(s.ok)return R(this.lease(s.value));if(!(o&&(s.problem.code==="operation_cancelled"||s.problem.code==="timeout"))||n.signal?.aborted)return s}}follow(e){this.followers+=1;let n=e.subscribe(o=>this.apply(o),o=>{if(o.state==="reset_required")for(let r of this.entries.values())this.refresh(r)}),i=!1;return()=>{if(!i&&(i=!0,n(),--this.followers===0)){for(let o of this.refreshes.values())clearTimeout(o.timer),o.stopWaiting?.();this.refreshes.clear(),this.refreshQueue.clear()}}}refresh(e){let n=this.refreshes.get(e);if(n){n.dirty=!0;return}let i={entry:e,dirty:!1,attempts:0};this.refreshes.set(e,i),this.enqueueRefresh(i)}enqueueRefresh(e){e.entry.session.snapshot.pendingRequestId?e.stopWaiting=e.entry.session.subscribe(()=>{e.entry.session.snapshot.pendingRequestId||(e.stopWaiting?.(),e.stopWaiting=void 0,this.enqueueRefresh(e))}):(this.refreshQueue.add(e),this.pumpRefreshes())}pumpRefreshes(){for(;this.activeRefreshes<pl&&this.refreshQueue.size>0;){let e=this.refreshQueue.values().next().value;this.refreshQueue.delete(e),e.dirty=!1,this.activeRefreshes+=1,this.runRefresh(e)}}async runRefresh(e){try{e.attempts+=1;let n=await e.entry.session.refresh();if(this.refreshes.get(e.entry)!==e)return;if(e.entry.session.snapshot.pendingRequestId){e.attempts-=1,this.enqueueRefresh(e);return}!n.ok&&n.problem.code!=="operation_cancelled"&&(n.problem.recovery==="retry"||n.problem.operation_outcome==="not_sent"&&n.problem.category==="availability")&&e.attempts<fl?e.timer=setTimeout(()=>this.enqueueRefresh(e),100*2**(e.attempts-1)):e.dirty?(e.attempts=0,this.enqueueRefresh(e)):this.refreshes.delete(e.entry)}finally{this.activeRefreshes-=1,this.pumpRefreshes()}}async load(e,n){let{autosave:i,...o}=n,r=await this.connection.read({path:e},o);if(!r.ok)return r;let s=this.entries.get(r.value.path);if(s)return R(s);let a={path:r.value.path,leases:0};a.session=new ut(r.value,this.adapter(a),{autosave:i});let c=await this.pendingUpdate(a.path);return c&&a.session.resumeRecovery(c),this.entries.set(a.path,a),R(a)}adapter(e){return{revision:n=>n.revision,body:n=>n.body??"",frontmatter:n=>n.frontmatter,write:(n,i,o)=>this.connection.update({path:e.path,ifRevision:n.revision,patch:i.patch??{},...i.body===void 0?{}:{body:i.body}},o),read:(n,i)=>this.connection.read({path:e.path},i),recover:async(n,i)=>{let o=this.connection.pendingMutation(n);return o?o.recover(i):g(w("no_pending_mutation","The interrupted write is no longer pending."))},isPending:n=>this.connection.pendingMutation(n)!==null}}lease(e){e.leases+=1,e.stopRetiring?.(),e.stopRetiring=void 0;let n=!1;return{session:e.session,release:()=>{n||(n=!0,e.leases-=1,this.retire(e))}}}retire(e){if(e.leases>0)return;let n=()=>{let{state:i,dirty:o}=e.session.snapshot;if(i!=="saved"&&i!=="deleted"&&!(i==="error"&&!o))return!1;e.stopRetiring?.(),e.stopRetiring=void 0,this.entries.get(e.path)===e&&this.entries.delete(e.path);let r=this.refreshes.get(e);return r&&(clearTimeout(r.timer),r.stopWaiting?.(),this.refreshQueue.delete(r),this.refreshes.delete(e)),!0};n()||(e.stopRetiring=e.session.subscribe(()=>{n()}))}apply(e){let{payload:n}=e;if(e.type==="mdbase.record.renamed"){let o=typeof n.from=="string"?this.entries.get(n.from):void 0;if(!o||typeof n.to!="string")return;this.entries.delete(o.path),o.path=n.to,this.entries.set(o.path,o),this.refresh(o);return}if(e.type!=="mdbase.record.modified"&&e.type!=="mdbase.record.deleted")return;let i=typeof n.path=="string"?this.entries.get(n.path):void 0;!i||n.revision===i.session.snapshot.record.revision||this.refresh(i)}};var hl=4,xs=32,Nn=class{constructor(e,n,i={}){this.transport=e;this.requestTimeoutMs=n;this.foregroundCapacity=Ji(i.foregroundCapacity,hl),this.foregroundQueueCapacity=Ji(i.foregroundQueueCapacity,xs),this.mutationQueueCapacity=Ji(i.mutationQueueCapacity,xs)}transport;requestTimeoutMs;foregroundCapacity;foregroundQueueCapacity;mutationQueueCapacity;foregroundQueue=[];mutationQueue=[];identicalReads=new Map;latestFamilies=new Map;activeForeground=0;mutationActive=!1;operation(e,n,i={}){let o=!Z(e,n),r=ml(i.coordination,o),s=o&&r.coalesce!==!1&&!r.latestWins&&i.signal===void 0?yl(e,n,i.timeoutMs):void 0;if(s){let c=this.identicalReads.get(s);if(c)return c}let a=W(i,this.requestTimeoutMs,c=>this.schedule(e,n,i,r,o,c));return s&&(this.identicalReads.set(s,a),a.finally(()=>{this.identicalReads.get(s)===a&&this.identicalReads.delete(s)}).catch(()=>{})),a}schedule(e,n,i,o,r,s){let a=o.latestWins?this.replaceLatest(o.family):void 0,c=gl(s.signal,a?.signal),{coordination:l,...u}=i,f=de({...u,timeoutMs:null},s),p=()=>this.transport.operation(e,n,{...f,signal:c.signal}),h=r?this.foregroundQueue:this.mutationQueue,m=r?this.foregroundQueueCapacity:this.mutationQueueCapacity;return h.length>=m?(c.dispose(),this.releaseLatest(o.family,a),Promise.reject(d("connector_busy","The selected connection request queue is full.",{operationOutcome:"not_sent",status:503}))):new Promise((P,v)=>{let b={budget:s,run:p,resolve:A=>P(A),reject:v,started:!1,settled:!1},C=()=>{b.started||b.settled||(b.settled=!0,h.splice(h.indexOf(b),1),b.reject(te(c.signal)),c.dispose(),this.releaseLatest(o.family,a))};c.signal.addEventListener("abort",C,{once:!0});let y=b.run;b.run=async()=>{c.signal.removeEventListener("abort",C);try{if(c.signal.aborted)throw te(c.signal);return await y()}finally{c.dispose(),this.releaseLatest(o.family,a)}},h.push(b),this.pump()})}replaceLatest(e){let n=new AbortController;return this.latestFamilies.get(e)?.abort(d("operation_cancelled","A newer request replaced this read before it changed the collection.",{operationOutcome:"not_sent"})),this.latestFamilies.set(e,n),n}releaseLatest(e,n){e&&n&&this.latestFamilies.get(e)===n&&this.latestFamilies.delete(e)}pump(){for(;this.activeForeground<this.foregroundCapacity;){let e=Es(this.foregroundQueue);if(!e)break;this.activeForeground+=1,this.start(e,()=>{this.activeForeground-=1,this.pump()})}if(!this.mutationActive){let e=Es(this.mutationQueue);e&&(this.mutationActive=!0,this.start(e,()=>{this.mutationActive=!1,this.pump()}))}}start(e,n){e.started=!0,e.run().then(i=>{e.settled||(e.settled=!0,e.resolve(i))},i=>{e.settled||(e.settled=!0,e.reject(i))}).finally(n)}};function Es(t){for(;t.length>0;){let e=t.shift();if(!e.settled)return e}}function ml(t,e){let n=t??{};if(n.latestWins&&!e)throw new TypeError("latestWins coordination is available only for read operations.");if(n.latestWins&&!n.family?.trim())throw new TypeError("latestWins coordination requires a non-empty family.");return n}function yl(t,e,n){return`${t}:${n===void 0?"default":String(n)}:${Yi(e)}`}function Yi(t){return t===null||typeof t!="object"?JSON.stringify(t)??String(t):Array.isArray(t)?`[${t.map(Yi).join(",")}]`:`{${Object.entries(t).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>`${JSON.stringify(e)}:${Yi(n)}`).join(",")}}`}function gl(t,e){if(!e)return{signal:t,dispose:()=>{}};let n=new AbortController,i=()=>n.abort(t.reason),o=()=>n.abort(e.reason);return t.aborted?i():t.addEventListener("abort",i,{once:!0}),e.aborted?o():e.addEventListener("abort",o,{once:!0}),{signal:n.signal,dispose:()=>{t.removeEventListener("abort",i),e.removeEventListener("abort",o)}}}function Ji(t,e){let n=t??e;if(!Number.isSafeInteger(n)||n<=0)throw new TypeError("Request coordinator capacities must be positive safe integers.");return n}var ft=class{constructor(e,n){this.internals=e;this.collectionId=n;this.transport=new Ln({serverUrl:e.serverUrl,storage:e.storage,keyStore:e.keyStore,directAccessMode:e.directAccessMode,loopbackUrl:e.loopbackUrl,collectionId:n,internals:e,timeouts:e.timeouts,onChange:()=>{this.authorityFeatures.refreshLifetime(),this.emitConnection()}}),this.authorityFeatures=new yn({lifetime:()=>{let i=this.transport.currentToken();return JSON.stringify([i?.savedAt,i?.grantId,i?.keyHandle,i?.authority?.operationsUrl,i?.authority?.filesUrl,i?.authority?.replicaId,i?.authority?.proofPublicKey,i?.clientId,i?.applicationOrigin,i?.encryption,i?.scope,i?.operations,i?.fileCapability,this.transport.route])},operations:()=>this.operations,fileCapability:()=>this.fileCapability,describe:async i=>{let o=bn(await this.transport.performOperation("describe",{},i));if(o.collectionId.toLowerCase()!==this.collectionId.toLowerCase())throw d("invalid_operation_response","The authority described a different collection.");return R(o)},filesPage:async(i,o)=>{let r=await Ni((s,a,c,l)=>this.transport.files.control(s,a,c,l),new URLSearchParams({protocol_version:"1",limit:"1",...i?{folder:i}:{}}),o);return ze(r.authority_capabilities)}},e.timeouts.requestMs),this.people=new rt({request:(i,o)=>Vr(i,o??{},{serverUrl:e.serverUrl,collectionId:n,requestMs:e.timeouts.requestMs,authorizedToken:r=>this.transport.authorizedToken({signal:r,timeoutMs:null})}),describe:i=>this.describe(i),queryPages:(i,o)=>this.queryPages(i,o)}),this.files=new dt(()=>this.fileCapability,(i,o,r,s)=>this.transport.files.control(i,o,r,s),{uploadChunk:(i,o,r,s)=>this.transport.files.uploadChunk(i,o,r,s),downloadChunk:(i,o,r)=>this.transport.files.downloadChunk(i,o,r)},{downloadPart:(i,o,r,s)=>this.transport.files.downloadHostedPart(i,o,r,s)},e.timeouts,(i,o)=>this.supportsAuthorityFeature(i,o)),this.records=new pt(this,i=>this.transport.pendingUpdate(i)),this.collectionClient=new at(new Nn({operation:(i,o,r)=>this.transport.performOperation(i,o,r)},e.timeouts.requestMs),e.timeouts.requestMs,(i,o)=>this.supportsAuthorityFeature(i,o)),this.readMany=this.collectionClient.readMany.bind(this.collectionClient),this.notifications=new An({serverUrl:e.serverUrl,storage:e.storage,authorizedToken:i=>this.transport.authorizedToken({signal:i,timeoutMs:null}),register:i=>this.internals.register({signal:i,timeoutMs:null}),notificationKey:i=>e.notificationKey(n,i),requestTimeoutMs:e.timeouts.requestMs})}internals;collectionId;collectionClient;notifications;transport;authorityFeatures;files;records;people;readMany;connectionListeners=new Set;get displayName(){return this.transport.currentToken()?.collectionName??`Collection ${this.collectionId.slice(0,8)}`}get operations(){return[...this.transport.currentToken()?.operations??[]]}get scope(){return this.transport.currentToken()?.scope??null}get fileCapability(){return this.transport.currentToken()?.fileCapability??null}get directAccess(){return this.transport.directAccess}get route(){return this.transport.route}supportsAuthorityFeature(e,n){return this.authorityFeatures.supports(e,n)}get authorityCapabilities(){return this.authorityFeatures.capabilities}register(e){return I(()=>this.internals.register(e),qe)}info(){let e=this.transport.currentToken();return e?{collectionId:e.collectionId,displayName:e.collectionName,operations:[...e.operations],scope:e.scope,...e.fileCapability?{fileCapability:e.fileCapability}:{},authority:e.authority?{kind:"hosted",durability:"provider"}:{kind:"connector",durability:"computer"},route:this.transport.route,directAccess:this.transport.directAccess}:null}authorizationCapabilities(e=Ee){let n=this.operations,i=Pt(e).filter(o=>!n.includes(o));return{authorized:this.info()!==null,sufficient:this.info()!==null&&i.length===0,collectionId:this.collectionId,grantedOperations:n,missingOperations:i}}hasOperations(e){return this.authorizationCapabilities(e).sufficient}authorize(e={}){return I(()=>this.internals.authorize({...e,target:{kind:"collection",collectionId:this.collectionId}}),Ce)}async requestCapabilities(e,n={}){return I(async()=>{let i=await this.internals.register(n);if(re(i.requirements,{...n,capabilities:e}),this.info()!==null&&e.every(s=>(X(V(i.requirements),s)??[]).every(a=>this.operations.includes(a))))return{kind:"unchanged",connection:this};if(V(i.requirements)===1){let{capabilities:s,...a}=n;return this.internals.authorize({...a,target:{kind:"collection",collectionId:this.collectionId},operations:[...new Set([...this.operations,...e.flatMap(c=>X(1,c)??[])])]})}let r=Yt(i.requirements,this.operations);return this.internals.authorize({...n,target:{kind:"collection",collectionId:this.collectionId},capabilities:[...new Set([...r,...e])]})},Ce)}async requestOperations(e,n={}){return I(async()=>{let i=await this.internals.register(n);re(i.requirements,{...n,operations:e});let o=this.authorizationCapabilities(e);return o.sufficient?{kind:"unchanged",connection:this}:this.internals.authorize({...n,target:{kind:"collection",collectionId:this.collectionId},operations:[...new Set([...o.grantedOperations,...e])]})},Ce)}onConnectionChange(e){return this.connectionListeners.add(e),e(this.info()),()=>this.connectionListeners.delete(e)}notifyStorageChanged(){this.authorityFeatures.invalidate(),this.transport.notifyStorageChanged()}checkDirectAccess(e){return I(()=>this.transport.checkDirectAccess(e),Si)}requestDirectAccess(e){return I(()=>this.transport.requestDirectAccess(e),Si)}disableDirectAccess(){this.transport.disableDirectAccess()}sync(){let e=this.transport.currentToken();if(!e)return null;let n=e.collectionId;if(!e.authority){if(!e.grantId||!e.operations.includes("sync"))return null;let o=e.grantId;return{collectionId:n,replicaId:o,transport:{openSession:r=>this.transport.performOperation("sync",{action:"open_session"},jn(r,this.internals.timeouts.syncMs)),snapshot:(r,s,a)=>this.transport.performOperation("sync",{action:"snapshot",snapshot_id:r,...s?{page:s}:{}},jn(a,this.internals.timeouts.syncMs)),changes:(r,s=200,a)=>this.transport.performOperation("sync",{action:"changes",after:r,limit:s},jn(a,this.internals.timeouts.syncMs)),mutate:(r,s)=>this.transport.performOperation("sync",{action:"mutate",mutation:r},jn(s,this.internals.timeouts.syncMs))}}}let i=e.authority.replicaId;return{collectionId:n,replicaId:i,transport:{openSession:o=>this.transport.performAuthoritySyncRequest(n,i,"POST","sessions",void 0,o),snapshot:(o,r,s)=>{let a=new URLSearchParams({snapshot_id:o});return r&&a.set("page",r),this.transport.performAuthoritySyncRequest(n,i,"GET",`snapshot?${a}`,void 0,s)},changes:(o,r=200,s)=>this.transport.performAuthoritySyncRequest(n,i,"GET",`changes?${new URLSearchParams({after:String(o),limit:String(r)})}`,void 0,s),mutate:(o,r)=>this.transport.performAuthoritySyncRequest(n,i,"POST","mutations",o,r)}}}registerNotifications(e){return I(()=>this.notifications.registerNotifications(e),wt)}registerNativeNotifications(e){return I(()=>this.notifications.registerNativeNotifications(e),wt)}unregisterNativeNotifications(e){return I(()=>this.notifications.unregisterNativeNotifications(e),wt)}unregisterNotifications(e,n){return I(()=>this.notifications.unregisterNotifications(e,n),wt)}forget(){let e=this.transport.currentToken();this.internals.removeToken(this.collectionId,e?.keyHandle,"not_authorized",!0),this.transport.notifyStorageChanged()}get schemaGeneration(){return this.collectionClient.schemaGeneration}async describe(e){let n=await this.collectionClient.describe(e);return n.ok&&n.value.collectionId.toLowerCase()!==this.collectionId.toLowerCase()?g(w("invalid_operation_response","The authority described a different collection.")):n}changes(e={},n){return this.collectionClient.changes(e,n)}read(e,n){return this.collectionClient.read(e,n)}query(e={},n){return this.collectionClient.query(e,n)}queryPages(e={},n={}){return e.output==="metadata"?this.collectionClient.queryPages(e,n):this.collectionClient.queryPages(e,n)}queryAll(e={},n={}){return e.output==="metadata"?this.collectionClient.queryAll(e,n):this.collectionClient.queryAll(e,n)}listViews(e){return this.collectionClient.listViews(e)}executeView(e,n){return this.collectionClient.executeView(e,n)}executeViewPages(e,n={}){return this.collectionClient.executeViewPages(e,n)}readViewSource(e,n){return this.collectionClient.readViewSource(e,n)}createViewSource(e,n){return this.collectionClient.createViewSource(e,n)}updateViewSource(e,n){return this.collectionClient.updateViewSource(e,n)}deleteViewSource(e,n){return this.collectionClient.deleteViewSource(e,n)}create(e,n){return this.collectionClient.create(e,n)}update(e,n){return this.collectionClient.update(e,n)}delete(e,n){return this.collectionClient.delete(e,n)}preflightDelete(e,n){return this.collectionClient.preflightDelete(e,n)}rename(e,n){return this.collectionClient.rename(e,n)}preflightRename(e,n){return this.collectionClient.preflightRename(e,n)}async renameWithProgress(e,n={}){return W(n,this.internals.timeouts.requestMs,async i=>{let o=Date.now(),r=!1,s,a=(c,l,u=0)=>{n.onProgress?.({operation:"rename",state:c,elapsedMs:Date.now()-o,cancellable:l,resumed:r,completedUnits:u,...s?{estimate:s}:{}})};try{Fe(i.signal),a("preflighting",!0);let c=n.preflight?R(n.preflight):await this.preflightRename(e,{signal:i.signal,timeoutMs:null});if(!c.ok)return c;let l=c.value;try{br(e,l)}catch(p){if(p instanceof _)return g(p.problem);throw p}s=vr(e,l),a("ready",!0),Fe(i.signal);let u=this.transport.hasResumableMutationTransport();a("applying",u);let f=await this.rename(e,u?{signal:i.signal,timeoutMs:null}:{timeoutMs:qs(i.remainingMs())});return f.ok&&a("completed",!1,s.totalUnits),f}catch(c){if(Mi(c,i.signal)&&a("cancelled",!1),c instanceof _)return g(c.problem);throw c}})}async deleteWithProgress(e,n={}){return W(n,this.internals.timeouts.requestMs,async i=>{let o=Date.now(),r=!1,s,a=(c,l,u=0)=>{n.onProgress?.({operation:"delete",state:c,elapsedMs:Date.now()-o,cancellable:l,resumed:r,completedUnits:u,...s?{estimate:s}:{}})};try{Fe(i.signal),a("preflighting",!0);let c=n.preflight?R(n.preflight):await this.preflightDelete(e,{signal:i.signal,timeoutMs:null});if(!c.ok)return c;let l=c.value;try{_r(e,l)}catch(p){if(p instanceof _)return g(p.problem);throw p}s=Cr(l),a("ready",!0),Fe(i.signal);let u=this.transport.hasResumableMutationTransport();a("applying",u);let f=await this.delete(e,u?{signal:i.signal,timeoutMs:null}:{timeoutMs:qs(i.remainingMs())});return f.ok&&a("completed",!1,s.totalUnits),f}catch(c){if(Mi(c,i.signal)&&a("cancelled",!1),c instanceof _)return g(c.problem);throw c}})}pendingMutations(){return this.transport.pendingMutations().map(e=>({...e,recover:n=>I(()=>this.recoverPendingMutation(e.requestId,n),G)}))}pendingMutation(e){let n=this.transport.pendingMutation(e);return n?{...n,recover:i=>I(()=>this.recoverPendingMutation(e,i),G)}:null}async recoverPendingMutation(e,n){let i=await this.transport.recoverPendingMutation(e,n);if(i&&typeof i=="object"&&"valid"in i){let o=i;if(!o.valid)throw new _(je(o));return o.result}return i}validate(e={},n){return this.collectionClient.validate(e,n)}readType(e,n){return this.collectionClient.readType(e,n)}createType(e,n){return this.collectionClient.createType(e,n)}updateType(e,n){return this.collectionClient.updateType(e,n)}assessTypePack(e,n){return this.collectionClient.assessTypePack(e,n)}applyTypePack(e,n){return this.collectionClient.applyTypePack(e,n)}assessCollectionSetup(e,n){return this.collectionClient.assessCollectionSetup(e,n)}applyCollectionSetup(e,n){return this.collectionClient.applyCollectionSetup(e,n)}listTimers(e,n){return this.collectionClient.listTimers(e,n)}putTimer(e,n){return this.collectionClient.putTimer(e,n)}cancelTimer(e,n){return this.collectionClient.cancelTimer(e,n)}reconcileTimers(e,n){return this.collectionClient.reconcileTimers(e,n)}watch(e={},n={}){return I(()=>k(n,this.internals.timeouts.watchStartMs,async i=>{let o=await this.collectionClient.changes(e.cursor===void 0?{}:{after:e.cursor,limit:200},{signal:i.signal,timeoutMs:null});if(!o.ok)throw new _(o.problem);if(o.value.reset)throw new _(w("change_cursor_reset","The collection change cursor expired. Refresh collection state before subscribing again."));return new Rn(r=>this.collectionClient.watch(r),o.value.cursor,e,e.cursor===void 0?[]:o.value.events,this.internals.timeouts.watchStartMs)}),tn)}emitConnection(){let e=this.info();for(let n of this.connectionListeners)n(e)}};function jn(t,e){return{...t,timeoutMs:t?.timeoutMs===void 0?e:t.timeoutMs}}function qs(t){return t===null?null:Math.max(1,Math.ceil(t))}async function zs(t){if(typeof location>"u"&&!t.navigate&&!t.options.openVerification)throw d("browser_required","Authorization navigation requires a browser environment.");let n=(t.options.presentation==="popup"||t.portableDeclared)&&!t.options.openVerification&&!t.navigate&&typeof window<"u"?window.open("","mdbase-connect-authorization","popup,width=620,height=760"):null;try{return{application:await t.register(t.options.signal),popup:n}}catch(i){throw n?.close(),i}}async function Ls(t){let e=Ns(t.storagePrefix,t.state);try{for(;;){let n=F(t.storage.getItem(e));if(n?.version===1){if(t.storage.removeItem(e),n.status==="failed")throw L(n.code,n.message,{details:n.returnTo?{return_to:n.returnTo}:void 0});let i=t.connection(n.collectionId);if(!i)throw d("invalid_callback","Authorization completed without a usable saved connection.");return{kind:"connected",connection:i,...n.returnTo?{returnTo:n.returnTo}:{}}}await oe(200,t.signal)}}finally{t.popup.close(),t.storage.removeItem(e);let n=`${t.storagePrefix}:pending:${t.state}`;F(t.storage.getItem(n))?.state===t.state&&(t.storage.removeItem(n),t.pending.keyHandle&&await t.keyStore.delete(t.pending.keyHandle))}}function Us(t){return t.completion.then(e=>(t.popupAttempt&&Fs(t,{version:1,status:"connected",collectionId:e.connection.collectionId,...e.returnTo?{returnTo:e.returnTo}:{}}),t.popupAttempt&&Ds(),e)).catch(e=>{throw t.popupAttempt&&Fs(t,{version:1,status:"failed",code:e instanceof _?e.code:"invalid_callback",message:e instanceof Error?e.message:"Authorization could not be completed.",...t.pending?.returnTo?{returnTo:t.pending.returnTo}:{}}),t.popupAttempt&&Ds(),e})}function Fs(t,e){t.storage.setItem(Ns(t.storagePrefix,t.state),JSON.stringify(e))}function Ns(t,e){return`${t}:completion:${e}`}function Ds(){typeof window<"u"&&typeof window.close=="function"&&window.close()}function Xi(t,e,n,i){let o=`${e}:pending-mutation:`,r=new Set;for(let s=0;s<t.length;s+=1){let a=t.key(s);if(!a?.startsWith(o))continue;let c=F(t.getItem(a));if(!c||!n.includes(c.operation)||i&&c.collectionId!==i)continue;let l=c.envelope?.protocol_version??c.request?.protocol_version;l!==void 0&&l!==Y&&mt(l)&&r.add(l)}return[...r].sort((s,a)=>a-s)}function Zi(t,e,n){return eo(t,e).has(n)}function eo(t,e){let n=new Set;for(let i=0;i<t.length;i+=1){let o=t.key(i);if(o!==e&&!o?.startsWith(`${e}:`))continue;let r=F(t.getItem(o));r?.keyHandle&&n.add(r.keyHandle)}return n}function js(t,e,n){let i=[e];for(let o=0;o<t.length;o+=1){let r=t.key(o);r?.startsWith(`${e}:`)&&i.push(r)}for(let o of i){let r=F(t.getItem(o));r?.keyHandle&&n(r.keyHandle),t.removeItem(o)}}function Bs({body:t,clientId:e,keyHandle:n,previous:i,retiredKeyHandles:o,defaultApplicationOrigin:r,pinConnectorIdentity:s}){let a=t.collection_id;if(typeof a!="string")throw d("invalid_token_response","Authorization returned no collection ID.");let c=cn(t.scope);if(!c)throw d("invalid_token_response","Authorization returned no valid collection scope.");if(!ln(c))throw d("legacy_scope_reauthorization_required","Authorization returned a legacy contract-scoped grant. Reauthorize for the entire collection.");if(t.authority&&!Mt(t.authority,a))throw d("invalid_token_response","Authorization returned an invalid remote authority capability.");if(t.authority&&t.encryption)throw d("invalid_token_response","Authorization returned conflicting collection transports.");if(t.file_capability!==null&&t.file_capability!==void 0&&!an(t.file_capability))throw d("invalid_token_response","Authorization returned an invalid file capability.");if(t.encryption){try{ye(t.encryption)}catch{throw d("invalid_token_response","Authorization returned an invalid encrypted relay binding.")}if(s(t.encryption.connector_id,t.encryption.connector_agreement_public_key),t.encryption.collection_id!==a||typeof t.grant_id!="string"||t.grant_id.length===0)throw d("invalid_token_response","Authorization returned an encrypted relay binding for another grant.")}if(i?.encryption&&t.encryption&&i.keyHandle&&i.keyHandle===n&&(i.grantId!==t.grant_id||i.encryption.connector_id!==t.encryption.connector_id||i.encryption.connector_agreement_public_key!==t.encryption.connector_agreement_public_key||i.encryption.application_agreement_public_key!==t.encryption.application_agreement_public_key))throw d("connector_identity_changed","The connector identity changed during authorization renewal. Reauthorize before sending collection data.");return{version:1,accessToken:t.access_token,refreshToken:t.refresh_token,clientId:e,collectionId:a,collectionName:t.collection_name??`Collection ${a.slice(0,8)}`,operations:t.operations,scope:c,expiresAt:Date.now()+t.expires_in*1e3,refreshExpiresAt:t.refresh_expires_in?Date.now()+t.refresh_expires_in*1e3:void 0,grantId:t.grant_id,encryption:t.encryption??void 0,fileCapability:t.file_capability??void 0,applicationOrigin:t.application_origin??r,keyHandle:n,...o?.length?{retiredKeyHandles:o}:{},savedAt:Date.now(),authority:t.authority?{operationsUrl:t.authority.operations_url,syncUrl:t.authority.sync_url,filesUrl:t.authority.files_url,replicaId:t.authority.replica_id,accessToken:t.authority.access_token,proofPublicKey:t.authority.proof_public_key}:void 0}}function to(t,e){let n=new Set;if(e&&n.add(e),t?.keyHandle&&n.add(t.keyHandle),Array.isArray(t?.retiredKeyHandles))for(let i of t.retiredKeyHandles)typeof i=="string"&&i.length>0&&n.add(i);return n}function Ks(t,e,n,i,o=[],r=!1){let s=[],a=[],c=to(n);for(let u of eo(t,e))c.add(u);let l=new Set(o);for(let u of l)c.add(u);for(let u of c)u!==i&&(r||l.has(u)||Zi(t,e,u)?s:a).push(u);return{retained:s,disposable:a}}function bl(t,e,n){let i=F(t.getItem(e));if(!i||!Array.isArray(i.retiredKeyHandles))return;let o=i.retiredKeyHandles.filter(r=>r!==n);o.length!==i.retiredKeyHandles.length&&(o.length>0?i.retiredKeyHandles=o:delete i.retiredKeyHandles,t.setItem(e,JSON.stringify(i)))}async function Qs(t,e,n,i,o){F(t.getItem(i))?.keyHandle===o||Zi(t,n,o)||(await e.delete(o),bl(t,i,o))}var Bn=class{serverUrl;manifest;manifestSource;redirectUri;storage;relayEncryption;keyStore;identityStore;directAccessMode;loopbackUrl;navigate;timeouts;credentialStorage;application=null;manifestPromise=null;completionPromises=new Oe;grantKeyLeases;connectionCache=new Map;listeners=new Set;invalidatedConnections=new Map;constructor(e){this.serverUrl=xr(String(e.serverUrl));let n=Ar(e.manifest,e.redirectUri);this.manifest=n.manifest,this.manifestSource=n.manifestSource;let i=Dr(this.manifest);this.redirectUri=n.redirectUri,this.storage=e.storage??Fr(i),this.relayEncryption=e.relayEncryption??"required",this.keyStore=e.keyStore??(i?new We:new He),this.identityStore=e.identityStore??(i?new it:new nt),this.credentialStorage=e.storage||e.keyStore||e.identityStore?"custom":this.storage instanceof Ye?"memory":"persistent",this.directAccessMode=e.directAccess??"auto",this.loopbackUrl=Tr(String(e.loopbackUrl??`http://127.0.0.1:${Io}`)),this.navigate=e.navigate,this.timeouts=Ve(e.timeouts),this.grantKeyLeases=new Mn(this.storagePrefix(),(o,r)=>this.deleteGrantKeyWhenUnused(o,r)),typeof window<"u"&&this.storage===window.localStorage&&window.addEventListener("storage",o=>{o.storageArea!==this.storage||!o.key?.startsWith(this.storagePrefix())||(this.connectionCache.get(qr(o.key))?.notifyStorageChanged(),this.emitConnections())})}environment(){return{distribution:typeof this.manifest!="string"&&this.manifest.distribution==="portable"?"portable":this.application?.distribution??"web",applicationOrigin:this.defaultApplicationOrigin(),credentialStorage:this.credentialStorage}}register(e={}){return k(e,this.timeouts.requestMs,n=>this.registerWithinBudget(n.signal))}async registerWithinBudget(e){if(this.application)return this.application;let n=await ae(`${this.serverUrl}/v1/apps/register`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({manifest:await this.manifestDeclaration({signal:e,timeoutMs:null})}),signal:e},"temporarily_unavailable","Application registration is temporarily unavailable."),i=await E(n,"invalid_operation_response","Connect returned an invalid application registration response.");if(!n.ok)throw z(i,"discovery_failed","Application discovery failed.",n.status);return this.application=i.application,this.application}manifestDeclaration(e={}){if(this.manifestPromise)return this.manifestPromise;let i=k(e,this.timeouts.requestMs,o=>this.loadManifest(o.signal)).catch(o=>{throw this.manifestPromise===i&&(this.manifestPromise=null),o});return this.manifestPromise=i,this.manifestPromise}async loadManifest(e){if(typeof this.manifest!="string")return this.manifest;let n=this.manifest,i;try{i=await fetch(n,{headers:{accept:"application/json"},signal:e})}catch(o){throw d("manifest_load_failed","The bundled application declaration could not be loaded.",{cause:o})}if(!i.ok)throw d("manifest_load_failed",`The bundled application declaration returned HTTP ${i.status}.`,{status:i.status});try{return await E(i,"invalid_application_manifest","The bundled application declaration is not valid JSON.")}catch(o){throw d("invalid_application_manifest","The bundled application declaration is not valid JSON.",{cause:o,details:{issues:[{path:"/",keyword:"json",message:"must be valid JSON",params:{}}]}})}}async authorize(e={}){let n=e.presentation==="popup"?6e5:this.timeouts.requestMs;return k(e,n,i=>this.authorizeWithinBudget({...e,signal:i.signal,timeoutMs:null}))}async authorizeWithinBudget(e){let n=typeof this.manifest!="string"&&this.manifest.distribution==="portable",{application:i,popup:o}=await zs({options:e,portableDeclared:n,navigate:this.navigate,register:r=>this.registerWithinBudget(r)});try{re(i.requirements,e),i.requirements.capabilities?.contract_version===2&&await zr(this.serverUrl,e.signal)}catch(r){throw o?.close(),r}return i.distribution==="portable"?(e.openVerification&&o?.close(),this.authorizePortable(i,e,e.openVerification?null:o)):this.authorizeWeb(i,e,o)}async authorizeWeb(e,n,i){let{verifier:o,challenge:r}=await At(),s=se(24),a=crypto.randomUUID(),c=n.target?.kind==="collection"?n.target.collectionId:void 0,l=`grant:${e.id}:${s}`,u=await this.keyStore.create(l),f;try{f=await this.loadApplicationIdentity(e)}catch(b){throw await this.keyStore.delete(l),b}let p=_i(e,n),h=vi(e.requirements),m=new Date,P=await qt({protocol_version:ce,authorization_id:a,application_id:e.id,application_declaration_id:It(e.family_identity),application_manifest_digest:e.manifest_digest,application_installation_id:await ot(f),installation_signing_public_key:f.signingPublicKey,grant_agreement_public_key:u.agreementPublicKey,grant_signing_public_key:u.signingPublicKey,flow:"authorization_code",authorization_nonce:se(32),issued_at:m.toISOString(),expires_at:new Date(m.getTime()+600*1e3).toISOString(),redirect_uri:this.redirectUri,state:s,code_challenge:r,contracts:ni(p,h,Xi(this.storage,this.storagePrefix(),p,c),V(e.requirements)),requested_operations:p,...h?{requested_files:h}:{},...c?{collection_id:c}:{}},f),v={version:1,verifier:o,state:s,clientId:e.id,redirectUri:this.redirectUri,relayEncryption:this.relayEncryption,collectionId:c,returnTo:n.returnTo,keyHandle:l,authorizationId:a,applicationAgreementPublicKey:u.agreementPublicKey,applicationSigningPublicKey:u.signingPublicKey,...n.presentation==="popup"&&i?{presentation:"popup"}:{}};this.storage.setItem(this.pendingKey(s),JSON.stringify(v));try{let b=await fetch(`${this.serverUrl}/oauth/authorization_request`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e.id,redirect_uri:this.redirectUri,code_challenge:r,code_challenge_method:"S256",state:s,operations:p.join(","),...c?{collection_id:c}:{},application_authorization:JSON.stringify(P)}),signal:n.signal}),C=await E(b,"invalid_device_authorization_response","The authorization service returned an invalid authorization response.");if(!b.ok)throw z(C,"device_authorization_failed","Application authorization could not be started.",b.status);if(typeof C.authorization_uri!="string"||C.authorization_id!==a||!Number.isInteger(C.expires_in)||C.expires_in<=0)throw d("invalid_device_authorization_response","The authorization service returned an invalid authorization response.");if(n.presentation==="popup"&&i)return i.location.href=C.authorization_uri,await Ls({storage:this.storage,storagePrefix:this.storagePrefix(),state:s,pending:v,popup:i,signal:n.signal,keyStore:this.keyStore,connection:y=>this.connection(y)});if(i?.close(),this.navigate)await this.navigate(C.authorization_uri);else if(typeof location<"u")location.assign(C.authorization_uri);else throw d("browser_required","Authorization navigation requires a browser environment.");return{kind:"redirecting"}}catch(b){throw i?.close(),this.storage.removeItem(this.pendingKey(s)),await this.keyStore.delete(l),n.signal?.aborted?Xe(n.signal,"Application authorization was cancelled.",b):b}}async authorizePortable(e,n,i){if(this.relayEncryption!=="required")throw i?.close(),d("encryption_required","Downloaded applications require encrypted relay authorization.");let{verifier:o,challenge:r}=await At(),s=`grant:${e.id}:${se(24)}`,a=await this.keyStore.create(s),c;try{c=await this.loadApplicationIdentity(e)}catch(C){throw i?.close(),await this.keyStore.delete(s),C}let l=_i(e,n),u=vi(e.requirements),f=crypto.randomUUID(),p=new Date,h=await qt({protocol_version:ce,authorization_id:f,application_id:e.id,application_declaration_id:It(e.family_identity),application_manifest_digest:e.manifest_digest,application_installation_id:await ot(c),installation_signing_public_key:c.signingPublicKey,grant_agreement_public_key:a.agreementPublicKey,grant_signing_public_key:a.signingPublicKey,flow:"device_code",authorization_nonce:se(32),issued_at:p.toISOString(),expires_at:new Date(p.getTime()+600*1e3).toISOString(),code_challenge:r,contracts:ni(l,u,Xi(this.storage,this.storagePrefix(),l,n.target?.kind==="collection"?n.target.collectionId:void 0),V(e.requirements)),requested_operations:l,...u?{requested_files:u}:{},...n.target?.kind==="collection"?{collection_id:n.target.collectionId}:{}},c),m,P;try{m=await fetch(`${this.serverUrl}/oauth/device_authorization`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e.id,operations:l.join(","),...n.target?.kind==="collection"?{collection_id:n.target.collectionId}:{},code_challenge:r,code_challenge_method:"S256",application_authorization:JSON.stringify(h)}),signal:n.signal}),P=await E(m,"invalid_device_authorization_response","The authorization service returned an invalid device authorization response.")}catch(C){throw i?.close(),await this.keyStore.delete(s),d("device_authorization_failed","Downloaded application authorization could not be started.",{cause:C})}if(!m.ok)throw i?.close(),await this.keyStore.delete(s),z(P,"device_authorization_failed","Downloaded application authorization could not be started.",m.status);let v;try{v=kr(P)}catch(C){throw i?.close(),await this.keyStore.delete(s),n.signal?.aborted?Xe(n.signal,"Downloaded application authorization was cancelled.",C):C}if(n.onDeviceCode?.(v),n.openVerification)await n.openVerification(v);else if(i)try{i.location.href=v.verificationUriComplete}catch{}else throw await this.keyStore.delete(s),d("approval_window_blocked","The approval window was blocked. Show the provided verification link and code, then try again.",{details:{user_code:v.userCode,verification_uri:v.verificationUri,verification_uri_complete:v.verificationUriComplete,expires_at:v.expiresAt,interval_seconds:v.intervalSeconds}});let b=v.intervalSeconds;try{for(;Date.now()<v.expiresAt;){if(await oe(b*1e3,n.signal),n.signal?.aborted)throw Xe(n.signal,"Downloaded application authorization was cancelled.");let C;try{C=await fetch(`${this.serverUrl}/oauth/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:P.device_code,client_id:e.id,code_verifier:o}),signal:n.signal})}catch(T){if(n.signal?.aborted)throw Xe(n.signal,"Downloaded application authorization was cancelled.",T);continue}let y=await E(C,"invalid_token_response","The authorization service returned an invalid token response.");if(!C.ok){let T=Tt(y);if(T==="authorization_pending")continue;if(T==="slow_down"){b+=5;continue}throw z(y,"token_exchange_failed","Downloaded application authorization could not be completed.",C.status)}let A=Mt(y.authority,y.collection_id),D=y.encryption&&y.encryption.protocol_version===Vt&&y.encryption.suite===gt&&y.encryption.application_agreement_public_key===a.agreementPublicKey;if(y.application_origin!==this.defaultApplicationOrigin())throw d("invalid_token_response","Authorization did not bind the portable grant to its exact application origin.");if(y.authority&&(!A||y.encryption!=null||y.authority.proof_public_key!==a.signingPublicKey))throw d("invalid_token_response","Authorization returned a remote authority capability that is not bound to this portable grant key.");if(!y.authority&&!D)throw d("encryption_required","Authorization did not establish the expected key-bound local portable grant.");let S=this.storeTokenResponse(y,e.id,s);if(n.target?.kind==="collection"&&n.target.collectionId!==S.collectionId)throw this.removeToken(S.collectionId,S.keyHandle),d("collection_mismatch","The approved collection does not match the collection requested by this link.");return i?.close(),{kind:"connected",connection:this.connection(S.collectionId),...n.returnTo?{returnTo:n.returnTo}:{}}}throw d("expired_token","The downloaded application authorization code expired.")}catch(C){throw i?.close(),await this.keyStore.delete(s),n.signal?.aborted?Xe(n.signal,"Downloaded application authorization was cancelled.",C):C}}completeAuthorization(e,n={}){let i=pn(e);if(!i)return Promise.reject(d("invalid_callback","Authorization callback is missing its state."));let o=F(this.storage.getItem(this.pendingKey(i))),r=o?.presentation==="popup";return this.completionPromises.run(i,n,this.timeouts.requestMs,s=>Us({storage:this.storage,storagePrefix:this.storagePrefix(),state:i,pending:o,popupAttempt:r,completion:this.performAuthorizationCompletion(e,i,s)}))}async performAuthorizationCompletion(e,n,i){let o=new URL(e),r=o.searchParams.get("code"),s=this.pendingKey(n),a=F(this.storage.getItem(s));if(!a||a.version!==1||n!==a.state)throw d("invalid_callback","Authorization callback is missing or does not match this browser session.");if(o.searchParams.has("error"))throw a.keyHandle&&await this.keyStore.delete(a.keyHandle),this.storage.removeItem(s),L(o.searchParams.get("error")??"access_denied",o.searchParams.get("error_description")??"Collection access was not approved.",{details:a.returnTo?{return_to:a.returnTo}:void 0});if(!r)throw d("invalid_callback","Authorization callback is missing its code.");let c=await ae(`${this.serverUrl}/oauth/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:r,client_id:a.clientId,redirect_uri:a.redirectUri,code_verifier:a.verifier}),signal:i},"temporarily_unavailable","Authorization completion is temporarily unavailable."),l=await E(c,"invalid_token_response","The authorization service returned an invalid token response.");if(!c.ok)throw z(l,"token_exchange_failed","Authorization could not be completed.",c.status);if(a.relayEncryption==="required"&&!l.authority&&(!l.encryption||!a.keyHandle||l.encryption.application_agreement_public_key!==a.applicationAgreementPublicKey))throw a.keyHandle&&await this.keyStore.delete(a.keyHandle),this.storage.removeItem(s),d("encryption_required","Authorization did not establish the required encrypted relay grant.");if(l.authority?.proof_public_key){if(!a.keyHandle||!a.applicationSigningPublicKey||l.authority.proof_public_key!==a.applicationSigningPublicKey)throw a.keyHandle&&await this.keyStore.delete(a.keyHandle),this.storage.removeItem(s),d("invalid_token_response","Authorization returned a remote authority capability bound to another application key.")}else l.authority&&a.keyHandle&&await this.keyStore.delete(a.keyHandle);let u=this.storeTokenResponse(l,a.clientId,l.authority?.proof_public_key?a.keyHandle:l.authority?void 0:a.keyHandle);if(a.collectionId&&a.collectionId!==u.collectionId)throw this.removeToken(u.collectionId,u.keyHandle),this.storage.removeItem(s),d("collection_mismatch","The approved collection does not match the collection requested by this link.");return this.storage.removeItem(s),{connection:this.connection(u.collectionId),...a.returnTo?{returnTo:a.returnTo}:{}}}connections(){let e=[];for(let n of sn(this.storage,this.storagePrefix())){let i=this.connection(n)?.info();i&&e.push(i)}return e.sort((n,i)=>n.displayName.localeCompare(i.displayName)||n.collectionId.localeCompare(i.collectionId))}connection(e){if(!this.storage.getItem(this.tokenKey(e)))return null;let n=this.connectionCache.get(e);return n||(n=new ft(this,e),this.connectionCache.set(e,n)),n.info()?n:null}unavailableReason(e){return this.invalidatedConnections.get(e)??null}connectionApplicationId(e){if(!this.connection(e))return null;let n=F(this.storage.getItem(this.tokenKey(e)));return typeof n?.clientId=="string"&&n.clientId.length>0?n.clientId:null}onConnectionsChange(e){return this.listeners.add(e),e(this.connections()),()=>this.listeners.delete(e)}storeTokenResponse(e,n,i){let o=e.collection_id;if(typeof o!="string")throw d("invalid_token_response","Authorization returned no collection ID.");let r=F(this.storage.getItem(this.tokenKey(o))),s=Ks(this.storage,this.pendingMutationKey(o),r,i,this.grantKeyLeases.handles(o),this.grantKeyLeases.retainAutomaticallyRetiredKeys),a;try{a=Bs({body:e,clientId:n,keyHandle:i,previous:r,retiredKeyHandles:s.retained,defaultApplicationOrigin:this.defaultApplicationOrigin(),pinConnectorIdentity:(c,l)=>this.pinConnectorIdentity(c,l)})}catch(c){throw c instanceof _&&c.code==="legacy_scope_reauthorization_required"&&this.removeToken(o,i,c.code),c}this.storage.setItem(this.tokenKey(o),JSON.stringify(a));for(let c of s.disposable)this.deleteGrantKeyWhenUnused(o,c);return Sr(this.storage,this.storagePrefix(),o),this.invalidatedConnections.delete(o),this.connectionCache.delete(o),this.emitConnections(),a}forgetConnectorIdentity(e){this.storage.removeItem(this.connectorPinKey(e))}pinConnectorIdentity(e,n){let i=this.connectorPinKey(e),o=F(this.storage.getItem(i));if(o&&(o.version!==1||o.publicKey!==n))throw d("connector_identity_changed","The connector identity changed since this application first connected. Forget the saved connector identity only after verifying the computer, then authorize again.");o||this.storage.setItem(i,JSON.stringify({version:1,publicKey:n}))}connectorPinKey(e){return`mdbase-connect:${this.serverUrl}:connector-pin:${e}`}async loadApplicationIdentity(e){try{return await fn(this.identityStore,this.serverUrl,e)}catch(n){throw d("application_identity_unavailable",n instanceof De?n.message:"The application installation identity is unavailable.",{cause:n})}}removeToken(e,n,i="authorization_lost",o=!1){this.invalidatedConnections.set(e,i);let r=F(this.storage.getItem(this.tokenKey(e))),s=to(r,n);this.storage.removeItem(this.tokenKey(e)),o&&js(this.storage,this.pendingMutationKey(e),a=>s.add(a));for(let a of s)this.deleteGrantKeyWhenUnused(e,a);for(let a of["web_push","fcm"])this.storage.removeItem(this.notificationKey(e,a));Or(this.storage,this.storagePrefix(),e),this.connectionCache.delete(e),this.emitConnections()}acquireGrantKeyLease(e,n,i){return this.grantKeyLeases.acquire(e,n,i)}deleteGrantKeyWhenUnused(e,n){this.grantKeyLeases.deleteExclusive(e,n,()=>Qs(this.storage,this.keyStore,this.pendingMutationKey(e),this.tokenKey(e),n))}tokenKey(e){return`${this.storagePrefix()}:token:${e}`}pendingMutationKey(e){return`${this.storagePrefix()}:pending-mutation:${e}`}notificationKey(e,n="web_push"){return`${this.storagePrefix()}:notifications:${e}:${n}`}directPreferenceKey(){return`mdbase-connect:direct:${this.defaultApplicationOrigin()}`}defaultApplicationOrigin(){return Er(this.manifest,this.manifestSource,this.redirectUri,this.application?.distribution==="portable")}pendingKey(e){return`${this.storagePrefix()}:pending:${e}`}storagePrefix(){return`mdbase-connect:${this.serverUrl}:${this.manifestSource}`}emitConnections(){let e=this.connections();for(let n of this.listeners)n(e)}};var Kn=class{internals;constructor(e){this.internals=new Bn(e)}register(e){return I(()=>this.internals.register(e),qe)}authorize(e={}){return I(()=>this.internals.authorize(e),Ce)}application(e){return new et(this,e,this.internals.timeouts)}manifest(e){return I(()=>this.internals.manifestDeclaration(e),qe)}environment(){return this.internals.environment()}completeAuthorization(e,n){return I(()=>this.internals.completeAuthorization(e===void 0?dn():String(e),n),Ce)}connections(){return this.internals.connections()}connection(e){return this.internals.connection(e)}unavailableReason(e){return this.internals.unavailableReason(e)}connectionApplicationId(e){return this.internals.connectionApplicationId(e)}onConnectionsChange(e){return this.internals.onConnectionsChange(e)}forgetAll(){for(let e of this.connections())this.connection(e.collectionId)?.forget()}forgetConnectorIdentity(e){this.internals.forgetConnectorIdentity(e)}};function no(t){if(!t||typeof t!="object")throw d("invalid_push_payload","The push payload is not an object.");let e=t;if(e.type!=="mdbase.notification"||e.version!==1||typeof e.signal_id!="string"||typeof e.criterion_id!="string"||typeof e.cursor!="string"||!e.presentation||typeof e.presentation.title!="string")throw d("invalid_push_payload","The push payload is not an mdbase notification.");return e}function Vs(t){if(!t||typeof t!="object")throw d("invalid_push_payload","The native notification data is not an object.");let e=t;if(e.type!=="mdbase.notification"||e.version!==1&&e.version!=="1"||typeof e.signal_id!="string"||typeof e.criterion_id!="string"||typeof e.cursor!="string")throw d("invalid_push_payload","The native notification data is not an mdbase notification.");return{type:"mdbase.notification",version:1,signal_id:e.signal_id,criterion_id:e.criterion_id,cursor:e.cursor}}function Gs(t,e){let n=no(e);return t.showNotification(n.presentation.title,{...n.presentation.body?{body:n.presentation.body}:{},...n.presentation.tag?{tag:n.presentation.tag}:{},data:{type:n.type,signal_id:n.signal_id,criterion_id:n.criterion_id,cursor:n.cursor}})}function Hs(t,e,n={}){let i=JSON.stringify(t),o=`record[${i}]`,r=JSON.stringify(e),s=a=>`${a} != null && ${a}.asFile() != null && ${a}.asFile().file.path == ${r}`;return`${i} in record && ${n.multiple?`${o} != null && ${o}.exists(link, ${s("link")})`:s(o)}`}function Ws(t){return{subscribe:e=>t.subscribe(e),getSnapshot:()=>t.getSnapshot()}}var Qn=class{collectionParameter;fallbackPath;listeners=new Set;handlePopState=()=>this.emit();constructor(e={}){this.collectionParameter=e.collectionParameter??"collection",this.fallbackPath=e.fallbackPath??"/"}selectedCollectionId(){return this.currentUrl().searchParams.get(this.collectionParameter)}select(e,n={}){let i=kt(this.currentUrl());e?i.searchParams.set(this.collectionParameter,e):i.searchParams.delete(this.collectionParameter);let o=this.browserHistory();o[n.history==="push"?"pushState":"replaceState"](o.state,"",i),this.emit()}authorizationReturnTo(){let e=kt(this.currentUrl());return`${e.pathname}${e.search}${e.hash}`}authorizationCallback(){let e=this.currentUrl().href;return un(e)?e:null}finishAuthorization(e,n){let i=this.safeAppUrl(e??this.fallbackPath);kt(i),i.searchParams.set(this.collectionParameter,n),this.browserHistory().replaceState(null,"",i),this.emit()}clearAuthorizationCallback(e){let n=e?this.safeAppUrl(e):this.currentUrl(),i=this.browserHistory();i.replaceState(i.state,"",kt(n)),this.emit()}subscribe(e){let n=this.listeners.size===0;return this.listeners.add(e),n&&typeof window<"u"&&window.addEventListener("popstate",this.handlePopState),()=>{this.listeners.delete(e),this.listeners.size===0&&typeof window<"u"&&window.removeEventListener("popstate",this.handlePopState)}}emit(){for(let e of this.listeners)e()}safeAppUrl(e){let n=this.currentUrl(),i=new URL(e,n.origin);return i.origin===n.origin?i:new URL(this.fallbackPath,n.origin)}currentUrl(){if(typeof location>"u")throw d("browser_required","Browser selection requires a browser environment.");return new URL(location.href)}browserHistory(){if(typeof history>"u")throw d("browser_required","Browser selection requires a browser environment.");return history}},Vn=class{collectionId=null;listeners=new Set;selectedCollectionId(){return this.collectionId}select(e){if(e!==this.collectionId){this.collectionId=e;for(let n of this.listeners)n()}}authorizationReturnTo(){}authorizationCallback(){return null}finishAuthorization(e,n){this.select(n)}clearAuthorizationCallback(){}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}};return ea(_l);})();
|