@mdbase-dev/connect 0.1.0-beta.61 → 0.1.0-beta.62
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/dist/browser/integrity.json +1 -1
- package/dist/browser/mdbase-connect.min.js +2 -2
- package/dist/browser/mdbase-connect.min.js.sha384 +1 -1
- package/dist/connection-transport.js +5 -8
- package/dist/crypto.d.ts +1 -1
- package/dist/crypto.js +6 -1
- package/dist/fresh-encrypted-request.d.ts +1 -1
- package/dist/fresh-encrypted-request.js +2 -2
- package/dist/request-budget.d.ts +5 -0
- package/dist/request-budget.js +7 -0
- package/package.json +2 -2
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";var MdbaseConnect=(()=>{var Xt=Object.defineProperty;var Wo=Object.getOwnPropertyDescriptor;var Yo=Object.getOwnPropertyNames;var Jo=Object.prototype.hasOwnProperty;var Qo=(t,e)=>{for(var n in e)Xt(t,n,{get:e[n],enumerable:!0})},Xo=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Yo(e))!Jo.call(t,o)&&o!==n&&Xt(t,o,{get:()=>e[o],enumerable:!(i=Wo(e,o))||i.enumerable});return t};var Zo=t=>Xo(Xt({},"__esModule",{value:!0}),t);var Xa={};Qo(Xa,{ApplicationIdentityStoreError:()=>_e,FileTransferCryptoError:()=>te,GrantFileTransferCipher:()=>Ue,IndexedDbApplicationIdentityStore:()=>De,IndexedDbGrantKeyStore:()=>Pe,MDBASE_RECORD_CREATED_CONTRACT:()=>ni,MDBASE_TIMER_FIRED_CONTRACT:()=>ii,MdbaseApplicationSession:()=>xe,MdbaseBrowserSelection:()=>Jt,MdbaseCollectionClient:()=>ze,MdbaseConnect:()=>Yt,MdbaseConnectError:()=>b,MdbaseConnection:()=>Ke,MdbaseFileClient:()=>je,MdbaseMemorySelection:()=>Qt,MdbaseMemoryVerificationStore:()=>rt,MdbaseSession:()=>Me,MemoryApplicationIdentityStore:()=>qe,MemoryGrantKeyStore:()=>Oe,RelayCryptoError:()=>R,applicationIdentity:()=>Ot,applicationInstallationId:()=>Fe,authorityProofMessage:()=>fn,connectError:()=>l,connectFailure:()=>O,connectProblem:()=>k,connectSuccess:()=>I,createPkce:()=>tt,decryptRelayResponse:()=>Te,deriveFileTransferKey:()=>wn,deriveP256SharedSecret:()=>Ze,effectiveCapabilities:()=>gt,encryptRelayRequest:()=>Q,externalStore:()=>$o,isRetryableConnectError:()=>si,operationProblem:()=>Se,operationsForApplicationCapabilities:()=>pt,parseMdbaseNativeNotificationData:()=>Ho,parseMdbasePushPayload:()=>Dn,showMdbasePushNotification:()=>Vo,signApplicationAuthorization:()=>at,signAuthorityRequest:()=>Ct,validateGrantEncryption:()=>X});var pe={access_denied:{category:"authorization",recovery:"reauthorize"},access_paused:{category:"availability",recovery:"resume_connector_access"},application_identity_unavailable:{category:"compatibility",recovery:"upgrade_application"},approval_window_blocked:{category:"authorization",recovery:"reauthorize"},authority_authorization_changed:{category:"authorization",recovery:"reauthorize"},authorization_binding_incompatible:{category:"compatibility",recovery:"upgrade_application"},authorization_cancelled:{category:"cancellation",recovery:"none"},authorization_expired:{category:"authorization",recovery:"reauthorize"},authorization_replayed:{category:"integrity",recovery:"reauthorize"},browser_required:{category:"compatibility",recovery:"none"},callback_url_required:{category:"validation",recovery:"fix_request"},capability_contract_incompatible:{category:"compatibility",recovery:"upgrade_application"},change_cursor_reset:{category:"conflict",recovery:"refresh"},collection_access_denied:{category:"authorization",recovery:"reauthorize"},collection_configuration_invalid:{category:"validation",recovery:"repair_collection"},collection_contracts_missing:{category:"compatibility",recovery:"choose_collection"},collection_incompatible:{category:"compatibility",recovery:"choose_collection"},collection_invalid:{category:"validation",recovery:"repair_collection"},collection_kind_unsupported:{category:"compatibility",recovery:"choose_collection"},collection_mismatch:{category:"selection",recovery:"choose_collection"},collection_not_found:{category:"selection",recovery:"choose_collection"},collection_not_ready:{category:"selection",recovery:"choose_collection"},collection_not_selected:{category:"selection",recovery:"choose_collection"},collection_type_registry_invalid:{category:"validation",recovery:"repair_collection"},collection_version_unsupported:{category:"compatibility",recovery:"upgrade_collection"},concurrent_modification:{category:"conflict",recovery:"refresh"},connector_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"},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"},hosted_provider_unavailable:{category:"availability",recovery:"retry"},insufficient_access:{category:"authorization",recovery:"reauthorize"},invalid_application_authorization:{category:"validation",recovery:"fix_request"},invalid_application_manifest:{category:"validation",recovery:"fix_request"},invalid_callback:{category:"validation",recovery:"fix_request"},invalid_device_authorization_response:{category:"integrity",recovery:"contact_support"},invalid_encrypted_response:{category:"integrity",recovery:"contact_support"},invalid_loopback_url:{category:"validation",recovery:"fix_request"},invalid_mutation_id:{category:"validation",recovery:"fix_request"},invalid_operation_response:{category:"integrity",recovery:"contact_support"},invalid_path:{category:"validation",recovery:"fix_request"},invalid_preflight:{category:"conflict",recovery:"refresh"},invalid_push_payload:{category:"validation",recovery:"fix_request"},invalid_push_subscription:{category:"validation",recovery:"fix_request"},invalid_request:{category:"validation",recovery:"fix_request"},invalid_token_response:{category:"integrity",recovery:"contact_support"},managed_fcm_not_declared:{category:"compatibility",recovery:"fix_request"},manifest_load_failed:{category:"availability",recovery:"retry"},manifest_required:{category:"validation",recovery:"fix_request"},missing_grant_key:{category:"authorization",recovery:"reauthorize"},mutation_recovery_expired:{category:"compatibility",recovery:"none"},mutation_request_conflict:{category:"conflict",recovery:"resolve_conflict"},no_pending_mutation:{category:"conflict",recovery:"refresh"},not_authorized:{category:"authorization",recovery:"reauthorize"},not_remote_authority:{category:"compatibility",recovery:"choose_collection"},notification_criterion_not_declared:{category:"validation",recovery:"fix_request"},notification_reauthorization_required:{category:"authorization",recovery:"reauthorize"},notification_registration_failed:{category:"availability",recovery:"retry"},notification_unregistration_failed:{category:"availability",recovery:"retry"},notifications_not_declared:{category:"compatibility",recovery:"fix_request"},notifications_unavailable:{category:"availability",recovery:"retry"},operation_cancelled:{category:"cancellation",recovery:"none"},operation_failed:{category:"internal",recovery:"contact_support"},operation_invalid:{category:"validation",recovery:"fix_request"},operation_outcome_unknown:{category:"conflict",recovery:"resolve_outcome"},path_occupied:{category:"conflict",recovery:"resolve_conflict"},pending_mutation_unresolved:{category:"conflict",recovery:"resolve_outcome"},query_snapshot_changed:{category:"conflict",recovery:"refresh"},rate_limited:{category:"availability",recovery:"retry"},reconnect_required:{category:"authorization",recovery:"reauthorize"},redirect_uri_required:{category:"validation",recovery:"fix_request"},reference_updates_unsupported:{category:"compatibility",recovery:"fix_request"},registry_backup_invalid:{category:"integrity",recovery:"contact_support"},registry_busy:{category:"availability",recovery:"retry"},registry_corrupt:{category:"integrity",recovery:"repair_collection"},registry_migration_failed:{category:"internal",recovery:"contact_support"},registry_schema_incompatible:{category:"compatibility",recovery:"upgrade_connector"},relay_authorization_expired:{category:"authorization",recovery:"reauthorize"},relay_unavailable:{category:"availability",recovery:"retry"},sandbox_unsupported:{category:"compatibility",recovery:"fix_request"},scope_denied:{category:"authorization",recovery:"reauthorize"},stale_file_revision:{category:"conflict",recovery:"refresh"},storage_required:{category:"compatibility",recovery:"none"},sync_failed:{category:"availability",recovery:"retry"},temporarily_unavailable:{category:"availability",recovery:"retry"},timeout:{category:"availability",recovery:"retry"},token_exchange_failed:{category:"availability",recovery:"retry"},transport_protocol_incompatible:{category:"compatibility",recovery:"upgrade_connector"},type_pack_provision_failed:{category:"validation",recovery:"repair_collection"},unknown_collection:{category:"selection",recovery:"choose_collection"},unsafe_file_path:{category:"validation",recovery:"fix_request"},unsupported_encryption:{category:"compatibility",recovery:"upgrade_application"},unsupported_operation:{category:"compatibility",recovery:"fix_request"}},er={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 qn(t){return Object.hasOwn(pe,t)}function Ve(t){if(!Fn(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"||!qn(e.code)||e.server_code!==void 0)return!1;let n=pe[e.code],i=er[e.code],o=i===void 0?e.details===void 0:e.details===void 0?(i.required?.length??0)===0:Zt(e.details,i);return e.category===n.category&&e.recovery===n.recovery&&o}function Zt(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=>Zt(i,e.items??{}));if(!Fn(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])=>Zt(o,e.properties[i]))}function Fn(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function en(t,e,n={}){if(qn(t)){let i=pe[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(Ve(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 zn=new Uint8Array([77,68,66,70]),Un=1,Nn=0,ns=new Uint8Array([77,68,66,82]);var Ln=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,C=class extends Error{code;constructor(e,n){super(n),this.code=e,this.name="FileFrameError"}};function tr(t){return t==="upload_chunk"?1:2}function nr(t){if(t===1)return"upload_chunk";if(t===2)return"download_chunk";throw new C("invalid_kind",`Unknown file frame kind ${t}`)}function ir(t){if(!t||typeof t!="object"||Array.isArray(t))throw new C("invalid_header","File frame header must be a JSON object");return t}function lt(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new C("invalid_header",`File frame header ${e} must be a non-empty string`);return n}function ct(t,e){let n=lt(t,e);if(!Ln.test(n))throw new C("invalid_header",`File frame header ${e} must be a UUID`);return n}function fe(t,e,n=Number.MAX_SAFE_INTEGER){let i=t[e];if(!Number.isSafeInteger(i)||i<0||i>n)throw new C("invalid_header",`File frame header ${e} is outside its allowed range`);return i}function tn(t){if(t.protocol_version!==1)throw new C("unsupported_version",`Unsupported file transfer protocol ${t.protocol_version}`);if(t.protection!=="grant_aead_v1"&&t.protection!=="transport_tls")throw new C("invalid_header","Unknown file transfer protection");if(t.direction!=="upload"&&t.direction!=="download")throw new C("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(!Ln.test(n))throw new C("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 C("invalid_header",`File frame header ${e} is outside its allowed range`);if(t.chunk_size<64*1024)throw new C("invalid_header","File frame chunk_size is below the protocol minimum");if(!Number.isSafeInteger(t.scope_epoch)||t.scope_epoch<1)throw new C("invalid_header","File frame header scope_epoch must be a positive integer");if(t.protection==="grant_aead_v1"&&!t.key_id)throw new C("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 or(t){let e;try{e=new TextDecoder("utf-8",{fatal:!0}).decode(t)}catch{throw new C("invalid_header","File frame header is not valid UTF-8")}let n;try{n=ir(JSON.parse(e))}catch(d){throw d instanceof C?d:new C("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(d=>!i.has(d)))throw new C("invalid_header","File frame header contains an unknown field");let o=fe(n,"protocol_version");if(o!==1)throw new C("unsupported_version",`Unsupported file transfer protocol ${o}`);let r=lt(n,"protection"),a=lt(n,"direction"),s=n.key_id===void 0?void 0:lt(n,"key_id"),c=tn({protocol_version:1,protection:r,grant_id:ct(n,"grant_id"),authority_id:ct(n,"authority_id"),collection_id:ct(n,"collection_id"),transfer_id:ct(n,"transfer_id"),direction:a,chunk_size:fe(n,"chunk_size",4194304),chunk_index:fe(n,"chunk_index"),offset:fe(n,"offset"),plaintext_length:fe(n,"plaintext_length",4194304),total_size:fe(n,"total_size"),scope_epoch:fe(n,"scope_epoch"),...s===void 0?{}:{key_id:s}});if(JSON.stringify(c)!==e)throw new C("invalid_header","File frame header must use the canonical field order without duplicate fields or whitespace");return c}function nn(t,e,n){let i=t==="upload_chunk"?"upload":"download";if(e.direction!==i)throw new C("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 C("invalid_header","Chunk offset does not match its index and protocol chunk size");if(e.offset+e.plaintext_length>e.total_size)throw new C("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 C("invalid_length","Payload length does not match the protected plaintext length")}function rr(t){return t.plaintext_length+(t.protection==="grant_aead_v1"?16:0)}function dt(t,e){let n=tn(e),i=rr(n);nn(t,n,i);let o=new TextEncoder().encode(JSON.stringify(n));if(o.byteLength>16384)throw new C("limit_exceeded","File frame header exceeds the protocol limit");let r=new Uint8Array(16+o.byteLength);r.set(zn,0);let a=new DataView(r.buffer,r.byteOffset,r.byteLength);return a.setUint8(4,Un),a.setUint8(5,tr(t)),a.setUint16(6,Nn,!1),a.setUint32(8,o.byteLength,!1),a.setUint32(12,i,!1),r.set(o,16),r}function Bn(t){let e=tn(t.header);if(nn(t.kind,e,t.payload.byteLength),t.payload.byteLength>4194320)throw new C("limit_exceeded","File frame payload exceeds the protocol limit");let n=dt(t.kind,e),i=new Uint8Array(n.byteLength+t.payload.byteLength);return i.set(n,0),i.set(t.payload,n.byteLength),i}function ut(t,e={}){if(t.byteLength<16)throw new C("invalid_length","File frame is shorter than its fixed prefix");if(!zn.every((f,h)=>t[h]===f))throw new C("invalid_magic","File frame magic is not MDBF");let n=new DataView(t.buffer,t.byteOffset,t.byteLength),i=n.getUint8(4);if(i!==Un)throw new C("unsupported_version",`Unsupported file frame version ${i}`);let o=nr(n.getUint8(5));if(n.getUint16(6,!1)!==Nn)throw new C("unsupported_flags","File frame uses unsupported flags");let r=n.getUint32(8,!1),a=n.getUint32(12,!1),s=e.maxHeaderBytes??16384,c=e.maxPayloadBytes??4194320;if(r===0)throw new C("invalid_length","File frame header must not be empty");if(r>s||a>c)throw new C("limit_exceeded","File frame exceeds the configured decode limits");let d=16+r+a;if(!Number.isSafeInteger(d)||d!==t.byteLength)throw new C("invalid_length","File frame lengths do not match the supplied bytes");let p=16+r,u=or(t.subarray(16,p));return nn(o,u,a),{kind:o,header:u,payload:t.slice(p)}}var ar=["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"],sr=["list_files","open_file_upload","open_file_download","move_file","delete_file","get_file_transfer_status","commit_file_upload","abort_file_transfer"],cr={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"},lr={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},dr={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},ur=new Set(["open_file_upload","move_file","delete_file","commit_file_upload","abort_file_transfer"]);var pr=new Set(ar),fr=new Set(sr);function jn(t){return pr.has(t)}function hr(t){return fr.has(t)}function Kn(t,e){if(t==="file_control"){let n=Hn(e)&&typeof e.type=="string"?e.type:"";if(!hr(n))throw new Error(`Unknown file-control message: ${n}`);return dr[n]}return lr[t]}function oe(t,e){let n=Hn(e)?e:{};if(n.dry_run===!0)return null;if(t==="file_control"){let o=typeof n.type=="string"?n.type:"";return ur.has(o)?`file_control:${o}`:null}let i=cr[t];return i==="always"?t:i==="sync_action"&&n.action==="mutate"?"sync:mutate":null}function we(t,e){return oe(t,e)!==null}function Hn(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var yr=1,mr="mdbase-connect mutation fingerprint v1\0",on=new TextEncoder;function gr(t){return rn(t,new Set)}function _r(t,e){let n=oe(t,e);if(n===null)throw new TypeError("The operation is not a canonical mutation.");let i=on.encode(n),o=on.encode(gr(e)),r=on.encode(mr),a=new Uint8Array(r.length+4+8+i.length+4+8+o.length),s=new DataView(a.buffer),c=0;return a.set(r,c),c+=r.length,s.setUint32(c,yr,!1),c+=4,c=$n(a,s,c,i),s.setUint32(c,Kn(t,e),!1),c+=4,$n(a,s,c,o),a}async function Gn(t,e){let n=new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",_r(t,e).buffer));return br(n)}function rn(t,e){if(t===null)return"null";if(t===!0)return"true";if(t===!1)return"false";if(typeof t=="string")return Vn(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(rn(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)Vn(o);return i.sort(([o],[r])=>o<r?-1:o>r?1:0),`{${i.map(([o,r])=>{let a=Object.getOwnPropertyDescriptor(t,o);if(!a||a.get||a.set)throw new TypeError("Mutation input must not contain accessor properties.");return`${JSON.stringify(o)}:${rn(r,e)}`}).join(",")}}`}finally{e.delete(t)}}function Vn(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 $n(t,e,n,i){return e.setBigUint64(n,BigInt(i.length),!1),n+=8,t.set(i,n),n+i.length}function br(t){return btoa(String.fromCharCode(...t)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}var L=3,vr=2,Wn=[L,vr],$=5,an=4,Yn=[$,an],Cr=1,wr=1,cs={operation_transport:[...Wn],authorization_binding:[...Yn],semantic_capabilities:[Cr],durable_mutation:[wr]};function sn(t,e,n=[]){let i={operation_transport:L,authorization_binding:$,semantic_capabilities:1},o=[...new Set(n)].filter(r=>r!==L).sort((r,a)=>a-r);return o.length>0&&(i.operation_transport_recovery=o),(t.some(r=>we(r,{action:"mutate"}))||e?.actions.some(r=>r!=="list"&&r!=="read")===!0)&&(i.durable_mutation=1),i}function $e(t){return Wn.includes(t)}function Jn(t){return Yn.includes(t)}var Qn={"collection.inspect":["describe"],"records.watch":["changes"],"records.read":["read"],"records.query":["query"],"records.validate":["validate"],"records.create":["create"],"records.update":["update"],"records.delete":["delete"],"records.rename":["rename"],"views.list":["list_views"],"views.execute":["execute_view"],"views.source.read":["read_view_source"],"views.source.create":["create_view_source"],"views.source.update":["update_view_source"],"views.source.delete":["delete_view_source"],"definitions.contracts.current":[],"definitions.read":["read_type"],"definitions.create":["create_type"],"definitions.update":["update_type"],"definitions.type-pack.inspect":["assess_type_pack"],"definitions.type-pack.apply":["assess_type_pack","apply_type_pack"],"collection.setup.apply":["assess_collection_setup","apply_collection_setup"],"timers.list":["list_timers"],"timers.put":["put_timer"],"timers.cancel":["cancel_timer"],"timers.reconcile":["reconcile_timers"],"sync.offline-replica":["sync"],"notifications.background-delivery":[],"files.list":[],"files.read":[],"files.add":[],"files.replace":[],"files.move":[],"files.delete":[]};function pt(t,e={}){let n=e.includeOptional===!1?t.required:[...t.required,...t.optional??[]];return[...new Set(n.flatMap(i=>Qn[i]))]}function ft(t){return[...Qn[t]]}var Sr=new TextEncoder().encode("mdbase-connect application installation id v2\0"),Rr=new TextEncoder().encode("mdbase-connect application authorization proof v4\0"),Ar=new TextEncoder().encode("mdbase-connect application authorization proof v5\0");async function Zn(t){let e=ht(t),i=new Uint8Array(await crypto.subtle.digest("SHA-256",he([Sr,D(e)]))).slice(0,16);return i[6]=i[6]&15|128,i[8]=i[8]&63|128,[Ge(i.slice(0,4)),Ge(i.slice(4,6)),Ge(i.slice(6,8)),Ge(i.slice(8,10)),Ge(i.slice(10,16))].join("-")}function ei(t){let e=[ht(t.installation_signing_public_key),ht(t.grant_agreement_public_key),ht(t.grant_signing_public_key)];if(e.some((c,d)=>e.slice(d+1).some(p=>Mr(c,p))))throw new Error("Application authorization keys must be distinct.");let n=cn(t.authorization_nonce),i=cn(t.code_challenge),o=t.contracts,r=o.operation_transport_recovery??[],a=t.requested_operations.some(c=>we(c,{action:"mutate"}))||t.requested_files?.actions.some(c=>!["list","read"].includes(c))===!0;if(!Jn(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||!$e(o.operation_transport)||t.protocol_version===$&&o.operation_transport!==L||r.some(c=>!$e(c)||c===o.operation_transport)||new Set(r).size!==r.length||t.protocol_version===an&&r.length>0||r.length>0&&!a||(a?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.");Or(t.requested_files);let s=t.requested_operations.map(c=>D(new TextEncoder().encode(c)));return he([t.protocol_version===$?Ar:Rr,H(t.protocol_version),D(yt(t.application_id)),D(yt(t.authorization_id)),D(new TextEncoder().encode(t.application_declaration_id)),D(ti(t.application_manifest_digest)),D(yt(t.application_installation_id)),...e.map(D),D(new TextEncoder().encode(t.flow)),D(n),D(new TextEncoder().encode(t.issued_at)),D(new TextEncoder().encode(t.expires_at)),Xn(t.redirect_uri),Xn(t.state),D(new TextEncoder().encode(t.code_challenge)),H(o.operation_transport),...t.protocol_version===$?[H(r.length),...r.map(H)]:[],H(o.authorization_binding),H(o.semantic_capabilities),Pr(o.durable_mutation),H(s.length),...s,Tr(t.requested_files),kr(t.collection_id)])}function Pr(t){return t===void 0?new Uint8Array(1):he([new Uint8Array([1]),H(t)])}function Or(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 Tr(t){if(t===void 0)return new Uint8Array(1);let e=t.actions.map(n=>D(new TextEncoder().encode(n)));return he([new Uint8Array([1]),H(e.length),...e,D(new TextEncoder().encode(t.scope.kind)),...t.scope.kind==="selected_folders"?[H(t.scope.folders.length),...t.scope.folders.map(n=>D(new TextEncoder().encode(n)))]:[]])}function Xn(t){return t===void 0?new Uint8Array(1):he([new Uint8Array([1]),D(new TextEncoder().encode(t))])}function kr(t){return t===void 0?new Uint8Array(1):he([new Uint8Array([1]),D(yt(t))])}function ht(t){let e=cn(t);if(e.byteLength!==65||e[0]!==4)throw new Error("Application authorization public key is invalid.");return e}function cn(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(Ir(i)!==t)throw new Error("Non-canonical base64url value.");return i}function yt(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 ti(e)}function ti(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 D(t){return he([H(t.byteLength),t])}function H(t){let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t,!1),e}function he(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 Ir(t){return btoa(String.fromCharCode(...t)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}function Mr(t,e){return t.byteLength===e.byteLength&&t.every((n,i)=>n===e[i])}function Ge(t){return[...t].map(e=>e.toString(16).padStart(2,"0")).join("")}var ni={id:"mdbase.record.created",version:"1.0.0",digest:"sha256:7f3bed6baa356ee9389e977ae7b77a102e2bee871a7c1d9f2026fc21cacdbfc9"};var ii={id:"mdbase.runtime.timer.fired",version:"1.0.0",digest:"sha256:41105be7a7abf33b31ced47e1e1965242236e40ccaea286b959b0a8c591f5642"};var oi=28485,We="P256-HKDF-SHA256-AES256GCM",mt=1;var xr="contract-setup-v1",Er="file-relay-v1",Dr="protocol-usage-report-v1",qr=["application-authorization-v4","authorization-activation","encrypted-relay","policy-ack"];var Fr=["durable-mutation-journal-v1","durable-file-lifecycle-v1"],ys=[...Fr,"mutation-replay-after-credential-retirement-v1"],ms=[...qr,"application-authorization-v5",xr,Er,Dr],ln=1;var ri="mdbase-authority-request-proof-v1",Ye={version:"x-mdbase-proof-version",timestamp:"x-mdbase-proof-timestamp",nonce:"x-mdbase-proof-nonce",signature:"x-mdbase-proof-signature"};function gt(t,e,n){let i=new Set(t.required),o=[...new Set([...t.required,...t.optional??[]])],r={};for(let a of o)r[a]=zr(a,i.has(a),e,n);return{contractVersion:1,values:r,requiredAvailable:t.required.every(a=>r[a]?.state==="available")}}function zr(t,e,n,i){let o=ft(t),r=o.filter(s=>!i.operations.includes(s)),a={id:t,requirement:e?"required":"optional",operations:o,missingOperations:r,evidence:[{source:"application",fact:`${e?"Required":"Optional"} in capability contract v1.`}]};if(r.length>0)return{...a,state:"requires_authorization",evidence:[...a.evidence,{source:"authorization",fact:`Missing ${r.join(", ")}.`}],reason:"The current grant does not include every operation for this capability."};if(t==="definitions.contracts.current"&&i.scope.access!=="full_collection"){let s=new Set(i.scope.contracts.map(({id:d,version:p,digest:u})=>`${d}@${p}:${u}`)),c=(n.requirements?.contracts??[]).filter(({id:d,version:p,digest:u})=>!s.has(`${d}@${p}:${u}`));if(c.length>0)return{...a,state:"requires_authorization",reason:"The current grant does not approve the exact required contract definitions.",evidence:[...a.evidence,{source:"authorization",fact:`Missing ${c.map(({id:d,version:p})=>`${d}@${p}`).join(", ")}.`}],details:{missingContracts:c}}}if(t.startsWith("files.")){let s=t.slice(6);if(!i.fileCapability?.actions.includes(s))return{...a,state:i.fileCapability?"requires_authorization":"unsupported",reason:i.fileCapability?`The current file grant does not include ${s}.`:"This connection has no file capability.",evidence:[...a.evidence,{source:"authorization",fact:i.fileCapability?`Granted file actions: ${i.fileCapability.actions.join(", ")}.`:"No file capability was granted."}]}}return t==="notifications.background-delivery"&&(n.notifications?.criteria.length??0)===0?{...a,state:"requires_setup",reason:"The application manifest declares no notification criteria.",evidence:[...a.evidence,{source:"application",fact:"No authority notification criteria are declared."}]}:{...a,state:"available",evidence:[...a.evidence,{source:"authorization",fact:o.length>0?`Granted operations: ${o.join(", ")}.`:"No record operation is required."},{source:"authority",fact:i.authority.kind==="hosted"?"Backed by a durable hosted mdbase authority.":"Backed by a user-operated mdbase connector."}],...t==="sync.offline-replica"?{details:{durability:"device",writes:"queued",authority:i.authority.kind}}:{},...t==="notifications.background-delivery"?{details:{delivery:"authority",payload:"opaque"}}:{}}}var b=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 k(t,e,...[n={}]){let i=pe[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 ai(t,e,n={}){return en(t,e,{details:n.details,operation_outcome:n.operationOutcome,trace_id:n.traceId})}function l(t,e,...n){let i=n[0];return new b(k(t,e,...n),{status:i?.status,cause:i?.cause})}function F(t,e,n={}){let{status:i,cause:o,...r}=n;return new b(en(t,e,{details:r.details,operation_outcome:r.operationOutcome,trace_id:r.traceId}),{status:i,cause:o})}function Se(t){let e=Nr(t.diagnostics),n=jr(t.diagnostics);if(e==="collection_version_unsupported"){let i=Lr(t.diagnostics);return k(e,n,{operationOutcome:"rejected",details:i})}return e!=="operation_invalid"?k(e,n,{operationOutcome:"rejected",details:{diagnostics:t.diagnostics}}):k(e,n,{operationOutcome:"rejected",details:{diagnostics:t.diagnostics,partial_result:t.result}})}function Nr(t){let e=new Set(t.filter(n=>n.severity==="error").map(n=>n.code));return["migration_required","migration_lossy","unsupported_version"].some(n=>e.has(n))?"collection_version_unsupported":["invalid_config","invalid_configuration","missing_config","missing_spec_version"].some(n=>e.has(n))?"collection_configuration_invalid":["duplicate_type","invalid_contract_definition","invalid_data_contract","invalid_type_definition","invalid_type_path"].some(n=>e.has(n))?"collection_type_registry_invalid":["collection_invalid","collection_open_failed"].some(n=>e.has(n))?"collection_invalid":"operation_invalid"}function Lr(t){let e=t.map(n=>n.details).find(n=>Br(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 Br(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function si(t){return t instanceof b&&t.retryable}function jr(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 Kr=["access_denied","access_paused","authorization_binding_incompatible","authorization_expired","capability_contract_incompatible","collection_access_denied","connector_identity_changed","connector_offline","connector_upgrade_required","direct_operation_rejected","durable_mutation_unsupported","operation_outcome_unknown","encryption_required","encrypted_relay_rejected","hosted_provider_unavailable","insufficient_access","invalid_encrypted_response","invalid_operation_response","invalid_request","missing_grant_key","mutation_recovery_expired","mutation_request_conflict","not_authorized","operation_cancelled","operation_failed","rate_limited","relay_authorization_expired","relay_unavailable","temporarily_unavailable","timeout","transport_protocol_incompatible","unsupported_operation"],ci=Object.keys(pe),ye=["discovery_failed","invalid_operation_response","invalid_application_manifest","invalid_request","manifest_load_failed","rate_limited","temporarily_unavailable","timeout"],Re=[...ye,"access_denied","application_identity_unavailable","approval_window_blocked","authorization_binding_incompatible","authorization_cancelled","authorization_replayed","browser_required","capability_contract_incompatible","collection_access_denied","collection_configuration_invalid","collection_contracts_missing","collection_incompatible","collection_invalid","collection_kind_unsupported","collection_mismatch","collection_not_found","collection_type_registry_invalid","collection_version_unsupported","connector_identity_changed","connector_offline","connector_upgrade_required","device_authorization_failed","durable_mutation_unsupported","encryption_required","expired_token","invalid_application_authorization","invalid_callback","invalid_device_authorization_response","invalid_token_response","scope_denied","reconnect_required","token_exchange_failed","transport_protocol_incompatible"],Je=[...ye,"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"],dn=["connector_offline","connector_upgrade_required","invalid_operation_response","not_authorized","operation_failed","temporarily_unavailable","timeout"],Ds=[...Re,"collection_not_ready","collection_not_selected","unknown_collection"],Hr=["collection_configuration_invalid","collection_invalid","collection_type_registry_invalid","collection_version_unsupported"],_t=[...Kr,...Hr],Y=[..._t,"invalid_path","operation_invalid"],li=[...Y,"query_snapshot_changed","sandbox_unsupported"],z=[...Y,"concurrent_modification","invalid_preflight","pending_mutation_unresolved"],bt=[..._t,"change_cursor_reset"],re=[...z,"type_pack_provision_failed"];function I(t,e=[]){return{ok:!0,value:t,diagnostics:e}}function O(t){return{ok:!1,problem:t}}async function x(t,e){try{return I(await t())}catch(n){if(!(n instanceof b))throw n;let i=n.problem;return i.code==="unknown"||e.includes(i.code)?O(i):O(ai(i.code,i.message,{details:i.details,operationOutcome:i.operation_outcome,traceId:i.trace_id}))}}var vt=3e4,Vr=1e4,$r=10*6e4,Gr=12e4,Wr=6e4;function Ae(t={}){return{requestMs:Qe(t.requestMs,vt,"requestMs"),watchStartMs:Qe(t.watchStartMs,Vr,"watchStartMs"),fileIndexMs:Qe(t.fileIndexMs,$r,"fileIndexMs"),uploadMs:Qe(t.uploadMs,Gr,"uploadMs"),syncMs:Qe(t.syncMs,Wr,"syncMs")}}function ae(t={},e=vt,n=Date.now){let i=t.timeoutMs===void 0?e:t.timeoutMs,o=i===null?null:Yr(i),r=new AbortController,a=o===null?null:n()+o,s=()=>r.abort(t.signal?.reason);t.signal?.aborted?s():t.signal?.addEventListener("abort",s,{once:!0});let c=o===null?void 0:setTimeout(()=>r.abort(l("timeout","The operation exceeded its request deadline.",{operationOutcome:"not_sent"})),o),d=!1;return{signal:r.signal,deadline:a,remainingMs:()=>a===null?null:Math.max(0,a-n()),dispose:()=>{d||(d=!0,c!==void 0&&clearTimeout(c),t.signal?.removeEventListener("abort",s))}}}async function U(t,e,n){let i=ae(t,e),o,r=new Promise((s,c)=>{o=c}),a=()=>o?.(J(i.signal));i.signal.addEventListener("abort",a,{once:!0});try{if(i.signal.aborted)throw J(i.signal);return await Promise.race([n(i),r])}finally{i.signal.removeEventListener("abort",a),i.dispose()}}async function B(t,e,n){let i=ae(t,e);try{if(i.signal.aborted)throw J(i.signal);return await n(i)}finally{i.dispose()}}function J(t){return t.reason instanceof b?t.reason:l("operation_cancelled","The operation was cancelled before it changed the collection.",{operationOutcome:"not_sent",cause:t.reason})}function Yr(t){if(!Number.isSafeInteger(t)||t<=0)throw new TypeError("timeoutMs must be a positive safe integer or null.");return t}function Qe(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}var Jr="mdbase-connect-keys",se="grant-keys",pn=18446744073709551615n,Qr="mdbase-connect relay request key v1",Xr="mdbase-connect relay response key v1",di=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Pe=class{database=null;async create(e){let n=await fi(e),i=await this.open();return await pi(i,o=>o.add({...n,counter:"0"})),n}async get(e){let n=await this.open(),i=await na(n.transaction(se).objectStore(se).get(e));return i?{handle:i.handle,agreementPrivateKey:i.agreementPrivateKey,agreementPublicKey:i.agreementPublicKey,signingPrivateKey:i.signingPrivateKey,signingPublicKey:i.signingPublicKey}:null}async nextCounter(e){let n=await this.open();return new Promise((i,o)=>{let r=n.transaction(se,"readwrite"),a=r.objectStore(se),s=a.get(e),c=null;s.onerror=()=>o(s.error),s.onsuccess=()=>{let d=s.result;if(!d){r.abort(),o(new R("missing_grant_key","The encrypted grant key is unavailable."));return}let p=BigInt(d.counter)+1n;if(p>pn){r.abort(),o(new R("counter_exhausted","The encrypted grant must be authorized again."));return}c=p.toString(),a.put({...d,counter:c})},r.onerror=()=>o(r.error),r.onabort=()=>o(r.error??new Error("Key counter transaction aborted.")),r.oncomplete=()=>{c&&i(c)}})}async delete(e){let n=await this.open();await pi(n,i=>i.delete(e))}open(){if(typeof indexedDB>"u")throw new R("key_storage_unavailable","Encrypted relay authorization requires browser IndexedDB or an injected grant key store.");return this.database||(this.database=new Promise((e,n)=>{let i=indexedDB.open(Jr,1);i.onupgradeneeded=()=>{i.result.objectStoreNames.contains(se)||i.result.createObjectStore(se,{keyPath:"handle"})},i.onerror=()=>n(i.error),i.onsuccess=()=>e(i.result)})),this.database}},Oe=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 fi(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,a)=>{n=r,i=a});return this.sequence=this.sequence.then(()=>{let r=this.records.get(e);if(!r)throw new R("missing_grant_key","The encrypted grant key is unavailable.");let a=BigInt(r.counter)+1n;if(a>pn)throw new R("counter_exhausted","The encrypted grant must be authorized again.");r.counter=a.toString(),n(r.counter)}).catch(r=>{i(r)}),o}async delete(e){this.records.delete(e)}};async function Ct(t,e,n,i){let o=await Zr(t,e,n),r=i.timestamp??Math.floor(Date.now()/1e3),a=i.nonce??crypto.randomUUID(),s=await fn({...i,timestamp:r,nonce:a}),c=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},o.signingPrivateKey,new TextEncoder().encode(s));return{[Ye.version]:String(ln),[Ye.timestamp]:String(r),[Ye.nonce]:a,[Ye.signature]:Xe(new Uint8Array(c))}}async function fn(t){let e=t.method.toUpperCase(),n=await ui(t.body??""),i=await ui(t.credential);for(let o of[e,t.target,String(t.timestamp),t.nonce])if(!o||o.includes(`
|
|
1
|
+
"use strict";var MdbaseConnect=(()=>{var Xt=Object.defineProperty;var Yo=Object.getOwnPropertyDescriptor;var Jo=Object.getOwnPropertyNames;var Qo=Object.prototype.hasOwnProperty;var Xo=(t,e)=>{for(var n in e)Xt(t,n,{get:e[n],enumerable:!0})},Zo=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Jo(e))!Qo.call(t,o)&&o!==n&&Xt(t,o,{get:()=>e[o],enumerable:!(i=Yo(e,o))||i.enumerable});return t};var er=t=>Zo(Xt({},"__esModule",{value:!0}),t);var Za={};Xo(Za,{ApplicationIdentityStoreError:()=>_e,FileTransferCryptoError:()=>te,GrantFileTransferCipher:()=>Ue,IndexedDbApplicationIdentityStore:()=>De,IndexedDbGrantKeyStore:()=>Pe,MDBASE_RECORD_CREATED_CONTRACT:()=>ni,MDBASE_TIMER_FIRED_CONTRACT:()=>ii,MdbaseApplicationSession:()=>xe,MdbaseBrowserSelection:()=>Jt,MdbaseCollectionClient:()=>ze,MdbaseConnect:()=>Yt,MdbaseConnectError:()=>b,MdbaseConnection:()=>Ke,MdbaseFileClient:()=>je,MdbaseMemorySelection:()=>Qt,MdbaseMemoryVerificationStore:()=>rt,MdbaseSession:()=>Me,MemoryApplicationIdentityStore:()=>qe,MemoryGrantKeyStore:()=>Oe,RelayCryptoError:()=>R,applicationIdentity:()=>Ot,applicationInstallationId:()=>Fe,authorityProofMessage:()=>fn,connectError:()=>l,connectFailure:()=>O,connectProblem:()=>k,connectSuccess:()=>I,createPkce:()=>tt,decryptRelayResponse:()=>Te,deriveFileTransferKey:()=>wn,deriveP256SharedSecret:()=>Ze,effectiveCapabilities:()=>gt,encryptRelayRequest:()=>Q,externalStore:()=>Go,isRetryableConnectError:()=>si,operationProblem:()=>Se,operationsForApplicationCapabilities:()=>pt,parseMdbaseNativeNotificationData:()=>Vo,parseMdbasePushPayload:()=>Dn,showMdbasePushNotification:()=>$o,signApplicationAuthorization:()=>at,signAuthorityRequest:()=>Ct,validateGrantEncryption:()=>X});var pe={access_denied:{category:"authorization",recovery:"reauthorize"},access_paused:{category:"availability",recovery:"resume_connector_access"},application_identity_unavailable:{category:"compatibility",recovery:"upgrade_application"},approval_window_blocked:{category:"authorization",recovery:"reauthorize"},authority_authorization_changed:{category:"authorization",recovery:"reauthorize"},authorization_binding_incompatible:{category:"compatibility",recovery:"upgrade_application"},authorization_cancelled:{category:"cancellation",recovery:"none"},authorization_expired:{category:"authorization",recovery:"reauthorize"},authorization_replayed:{category:"integrity",recovery:"reauthorize"},browser_required:{category:"compatibility",recovery:"none"},callback_url_required:{category:"validation",recovery:"fix_request"},capability_contract_incompatible:{category:"compatibility",recovery:"upgrade_application"},change_cursor_reset:{category:"conflict",recovery:"refresh"},collection_access_denied:{category:"authorization",recovery:"reauthorize"},collection_configuration_invalid:{category:"validation",recovery:"repair_collection"},collection_contracts_missing:{category:"compatibility",recovery:"choose_collection"},collection_incompatible:{category:"compatibility",recovery:"choose_collection"},collection_invalid:{category:"validation",recovery:"repair_collection"},collection_kind_unsupported:{category:"compatibility",recovery:"choose_collection"},collection_mismatch:{category:"selection",recovery:"choose_collection"},collection_not_found:{category:"selection",recovery:"choose_collection"},collection_not_ready:{category:"selection",recovery:"choose_collection"},collection_not_selected:{category:"selection",recovery:"choose_collection"},collection_type_registry_invalid:{category:"validation",recovery:"repair_collection"},collection_version_unsupported:{category:"compatibility",recovery:"upgrade_collection"},concurrent_modification:{category:"conflict",recovery:"refresh"},connector_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"},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"},hosted_provider_unavailable:{category:"availability",recovery:"retry"},insufficient_access:{category:"authorization",recovery:"reauthorize"},invalid_application_authorization:{category:"validation",recovery:"fix_request"},invalid_application_manifest:{category:"validation",recovery:"fix_request"},invalid_callback:{category:"validation",recovery:"fix_request"},invalid_device_authorization_response:{category:"integrity",recovery:"contact_support"},invalid_encrypted_response:{category:"integrity",recovery:"contact_support"},invalid_loopback_url:{category:"validation",recovery:"fix_request"},invalid_mutation_id:{category:"validation",recovery:"fix_request"},invalid_operation_response:{category:"integrity",recovery:"contact_support"},invalid_path:{category:"validation",recovery:"fix_request"},invalid_preflight:{category:"conflict",recovery:"refresh"},invalid_push_payload:{category:"validation",recovery:"fix_request"},invalid_push_subscription:{category:"validation",recovery:"fix_request"},invalid_request:{category:"validation",recovery:"fix_request"},invalid_token_response:{category:"integrity",recovery:"contact_support"},managed_fcm_not_declared:{category:"compatibility",recovery:"fix_request"},manifest_load_failed:{category:"availability",recovery:"retry"},manifest_required:{category:"validation",recovery:"fix_request"},missing_grant_key:{category:"authorization",recovery:"reauthorize"},mutation_recovery_expired:{category:"compatibility",recovery:"none"},mutation_request_conflict:{category:"conflict",recovery:"resolve_conflict"},no_pending_mutation:{category:"conflict",recovery:"refresh"},not_authorized:{category:"authorization",recovery:"reauthorize"},not_remote_authority:{category:"compatibility",recovery:"choose_collection"},notification_criterion_not_declared:{category:"validation",recovery:"fix_request"},notification_reauthorization_required:{category:"authorization",recovery:"reauthorize"},notification_registration_failed:{category:"availability",recovery:"retry"},notification_unregistration_failed:{category:"availability",recovery:"retry"},notifications_not_declared:{category:"compatibility",recovery:"fix_request"},notifications_unavailable:{category:"availability",recovery:"retry"},operation_cancelled:{category:"cancellation",recovery:"none"},operation_failed:{category:"internal",recovery:"contact_support"},operation_invalid:{category:"validation",recovery:"fix_request"},operation_outcome_unknown:{category:"conflict",recovery:"resolve_outcome"},path_occupied:{category:"conflict",recovery:"resolve_conflict"},pending_mutation_unresolved:{category:"conflict",recovery:"resolve_outcome"},query_snapshot_changed:{category:"conflict",recovery:"refresh"},rate_limited:{category:"availability",recovery:"retry"},reconnect_required:{category:"authorization",recovery:"reauthorize"},redirect_uri_required:{category:"validation",recovery:"fix_request"},reference_updates_unsupported:{category:"compatibility",recovery:"fix_request"},registry_backup_invalid:{category:"integrity",recovery:"contact_support"},registry_busy:{category:"availability",recovery:"retry"},registry_corrupt:{category:"integrity",recovery:"repair_collection"},registry_migration_failed:{category:"internal",recovery:"contact_support"},registry_schema_incompatible:{category:"compatibility",recovery:"upgrade_connector"},relay_authorization_expired:{category:"authorization",recovery:"reauthorize"},relay_unavailable:{category:"availability",recovery:"retry"},sandbox_unsupported:{category:"compatibility",recovery:"fix_request"},scope_denied:{category:"authorization",recovery:"reauthorize"},stale_file_revision:{category:"conflict",recovery:"refresh"},storage_required:{category:"compatibility",recovery:"none"},sync_failed:{category:"availability",recovery:"retry"},temporarily_unavailable:{category:"availability",recovery:"retry"},timeout:{category:"availability",recovery:"retry"},token_exchange_failed:{category:"availability",recovery:"retry"},transport_protocol_incompatible:{category:"compatibility",recovery:"upgrade_connector"},type_pack_provision_failed:{category:"validation",recovery:"repair_collection"},unknown_collection:{category:"selection",recovery:"choose_collection"},unsafe_file_path:{category:"validation",recovery:"fix_request"},unsupported_encryption:{category:"compatibility",recovery:"upgrade_application"},unsupported_operation:{category:"compatibility",recovery:"fix_request"}},tr={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 qn(t){return Object.hasOwn(pe,t)}function Ve(t){if(!Fn(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"||!qn(e.code)||e.server_code!==void 0)return!1;let n=pe[e.code],i=tr[e.code],o=i===void 0?e.details===void 0:e.details===void 0?(i.required?.length??0)===0:Zt(e.details,i);return e.category===n.category&&e.recovery===n.recovery&&o}function Zt(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=>Zt(i,e.items??{}));if(!Fn(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])=>Zt(o,e.properties[i]))}function Fn(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function en(t,e,n={}){if(qn(t)){let i=pe[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(Ve(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 zn=new Uint8Array([77,68,66,70]),Un=1,Nn=0,is=new Uint8Array([77,68,66,82]);var Ln=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,C=class extends Error{code;constructor(e,n){super(n),this.code=e,this.name="FileFrameError"}};function nr(t){return t==="upload_chunk"?1:2}function ir(t){if(t===1)return"upload_chunk";if(t===2)return"download_chunk";throw new C("invalid_kind",`Unknown file frame kind ${t}`)}function or(t){if(!t||typeof t!="object"||Array.isArray(t))throw new C("invalid_header","File frame header must be a JSON object");return t}function lt(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new C("invalid_header",`File frame header ${e} must be a non-empty string`);return n}function ct(t,e){let n=lt(t,e);if(!Ln.test(n))throw new C("invalid_header",`File frame header ${e} must be a UUID`);return n}function fe(t,e,n=Number.MAX_SAFE_INTEGER){let i=t[e];if(!Number.isSafeInteger(i)||i<0||i>n)throw new C("invalid_header",`File frame header ${e} is outside its allowed range`);return i}function tn(t){if(t.protocol_version!==1)throw new C("unsupported_version",`Unsupported file transfer protocol ${t.protocol_version}`);if(t.protection!=="grant_aead_v1"&&t.protection!=="transport_tls")throw new C("invalid_header","Unknown file transfer protection");if(t.direction!=="upload"&&t.direction!=="download")throw new C("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(!Ln.test(n))throw new C("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 C("invalid_header",`File frame header ${e} is outside its allowed range`);if(t.chunk_size<64*1024)throw new C("invalid_header","File frame chunk_size is below the protocol minimum");if(!Number.isSafeInteger(t.scope_epoch)||t.scope_epoch<1)throw new C("invalid_header","File frame header scope_epoch must be a positive integer");if(t.protection==="grant_aead_v1"&&!t.key_id)throw new C("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 rr(t){let e;try{e=new TextDecoder("utf-8",{fatal:!0}).decode(t)}catch{throw new C("invalid_header","File frame header is not valid UTF-8")}let n;try{n=or(JSON.parse(e))}catch(d){throw d instanceof C?d:new C("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(d=>!i.has(d)))throw new C("invalid_header","File frame header contains an unknown field");let o=fe(n,"protocol_version");if(o!==1)throw new C("unsupported_version",`Unsupported file transfer protocol ${o}`);let r=lt(n,"protection"),a=lt(n,"direction"),s=n.key_id===void 0?void 0:lt(n,"key_id"),c=tn({protocol_version:1,protection:r,grant_id:ct(n,"grant_id"),authority_id:ct(n,"authority_id"),collection_id:ct(n,"collection_id"),transfer_id:ct(n,"transfer_id"),direction:a,chunk_size:fe(n,"chunk_size",4194304),chunk_index:fe(n,"chunk_index"),offset:fe(n,"offset"),plaintext_length:fe(n,"plaintext_length",4194304),total_size:fe(n,"total_size"),scope_epoch:fe(n,"scope_epoch"),...s===void 0?{}:{key_id:s}});if(JSON.stringify(c)!==e)throw new C("invalid_header","File frame header must use the canonical field order without duplicate fields or whitespace");return c}function nn(t,e,n){let i=t==="upload_chunk"?"upload":"download";if(e.direction!==i)throw new C("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 C("invalid_header","Chunk offset does not match its index and protocol chunk size");if(e.offset+e.plaintext_length>e.total_size)throw new C("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 C("invalid_length","Payload length does not match the protected plaintext length")}function ar(t){return t.plaintext_length+(t.protection==="grant_aead_v1"?16:0)}function dt(t,e){let n=tn(e),i=ar(n);nn(t,n,i);let o=new TextEncoder().encode(JSON.stringify(n));if(o.byteLength>16384)throw new C("limit_exceeded","File frame header exceeds the protocol limit");let r=new Uint8Array(16+o.byteLength);r.set(zn,0);let a=new DataView(r.buffer,r.byteOffset,r.byteLength);return a.setUint8(4,Un),a.setUint8(5,nr(t)),a.setUint16(6,Nn,!1),a.setUint32(8,o.byteLength,!1),a.setUint32(12,i,!1),r.set(o,16),r}function Bn(t){let e=tn(t.header);if(nn(t.kind,e,t.payload.byteLength),t.payload.byteLength>4194320)throw new C("limit_exceeded","File frame payload exceeds the protocol limit");let n=dt(t.kind,e),i=new Uint8Array(n.byteLength+t.payload.byteLength);return i.set(n,0),i.set(t.payload,n.byteLength),i}function ut(t,e={}){if(t.byteLength<16)throw new C("invalid_length","File frame is shorter than its fixed prefix");if(!zn.every((f,h)=>t[h]===f))throw new C("invalid_magic","File frame magic is not MDBF");let n=new DataView(t.buffer,t.byteOffset,t.byteLength),i=n.getUint8(4);if(i!==Un)throw new C("unsupported_version",`Unsupported file frame version ${i}`);let o=ir(n.getUint8(5));if(n.getUint16(6,!1)!==Nn)throw new C("unsupported_flags","File frame uses unsupported flags");let r=n.getUint32(8,!1),a=n.getUint32(12,!1),s=e.maxHeaderBytes??16384,c=e.maxPayloadBytes??4194320;if(r===0)throw new C("invalid_length","File frame header must not be empty");if(r>s||a>c)throw new C("limit_exceeded","File frame exceeds the configured decode limits");let d=16+r+a;if(!Number.isSafeInteger(d)||d!==t.byteLength)throw new C("invalid_length","File frame lengths do not match the supplied bytes");let p=16+r,u=rr(t.subarray(16,p));return nn(o,u,a),{kind:o,header:u,payload:t.slice(p)}}var sr=["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"],cr=["list_files","open_file_upload","open_file_download","move_file","delete_file","get_file_transfer_status","commit_file_upload","abort_file_transfer"],lr={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"},dr={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},ur={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},pr=new Set(["open_file_upload","move_file","delete_file","commit_file_upload","abort_file_transfer"]);var fr=new Set(sr),hr=new Set(cr);function jn(t){return fr.has(t)}function yr(t){return hr.has(t)}function Kn(t,e){if(t==="file_control"){let n=Hn(e)&&typeof e.type=="string"?e.type:"";if(!yr(n))throw new Error(`Unknown file-control message: ${n}`);return ur[n]}return dr[t]}function oe(t,e){let n=Hn(e)?e:{};if(n.dry_run===!0)return null;if(t==="file_control"){let o=typeof n.type=="string"?n.type:"";return pr.has(o)?`file_control:${o}`:null}let i=lr[t];return i==="always"?t:i==="sync_action"&&n.action==="mutate"?"sync:mutate":null}function we(t,e){return oe(t,e)!==null}function Hn(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var mr=1,gr="mdbase-connect mutation fingerprint v1\0",on=new TextEncoder;function _r(t){return rn(t,new Set)}function br(t,e){let n=oe(t,e);if(n===null)throw new TypeError("The operation is not a canonical mutation.");let i=on.encode(n),o=on.encode(_r(e)),r=on.encode(gr),a=new Uint8Array(r.length+4+8+i.length+4+8+o.length),s=new DataView(a.buffer),c=0;return a.set(r,c),c+=r.length,s.setUint32(c,mr,!1),c+=4,c=$n(a,s,c,i),s.setUint32(c,Kn(t,e),!1),c+=4,$n(a,s,c,o),a}async function Gn(t,e){let n=new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",br(t,e).buffer));return vr(n)}function rn(t,e){if(t===null)return"null";if(t===!0)return"true";if(t===!1)return"false";if(typeof t=="string")return Vn(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(rn(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)Vn(o);return i.sort(([o],[r])=>o<r?-1:o>r?1:0),`{${i.map(([o,r])=>{let a=Object.getOwnPropertyDescriptor(t,o);if(!a||a.get||a.set)throw new TypeError("Mutation input must not contain accessor properties.");return`${JSON.stringify(o)}:${rn(r,e)}`}).join(",")}}`}finally{e.delete(t)}}function Vn(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 $n(t,e,n,i){return e.setBigUint64(n,BigInt(i.length),!1),n+=8,t.set(i,n),n+i.length}function vr(t){return btoa(String.fromCharCode(...t)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}var L=3,Cr=2,Wn=[L,Cr],$=5,an=4,Yn=[$,an],wr=1,Sr=1,ls={operation_transport:[...Wn],authorization_binding:[...Yn],semantic_capabilities:[wr],durable_mutation:[Sr]};function sn(t,e,n=[]){let i={operation_transport:L,authorization_binding:$,semantic_capabilities:1},o=[...new Set(n)].filter(r=>r!==L).sort((r,a)=>a-r);return o.length>0&&(i.operation_transport_recovery=o),(t.some(r=>we(r,{action:"mutate"}))||e?.actions.some(r=>r!=="list"&&r!=="read")===!0)&&(i.durable_mutation=1),i}function $e(t){return Wn.includes(t)}function Jn(t){return Yn.includes(t)}var Qn={"collection.inspect":["describe"],"records.watch":["changes"],"records.read":["read"],"records.query":["query"],"records.validate":["validate"],"records.create":["create"],"records.update":["update"],"records.delete":["delete"],"records.rename":["rename"],"views.list":["list_views"],"views.execute":["execute_view"],"views.source.read":["read_view_source"],"views.source.create":["create_view_source"],"views.source.update":["update_view_source"],"views.source.delete":["delete_view_source"],"definitions.contracts.current":[],"definitions.read":["read_type"],"definitions.create":["create_type"],"definitions.update":["update_type"],"definitions.type-pack.inspect":["assess_type_pack"],"definitions.type-pack.apply":["assess_type_pack","apply_type_pack"],"collection.setup.apply":["assess_collection_setup","apply_collection_setup"],"timers.list":["list_timers"],"timers.put":["put_timer"],"timers.cancel":["cancel_timer"],"timers.reconcile":["reconcile_timers"],"sync.offline-replica":["sync"],"notifications.background-delivery":[],"files.list":[],"files.read":[],"files.add":[],"files.replace":[],"files.move":[],"files.delete":[]};function pt(t,e={}){let n=e.includeOptional===!1?t.required:[...t.required,...t.optional??[]];return[...new Set(n.flatMap(i=>Qn[i]))]}function ft(t){return[...Qn[t]]}var Rr=new TextEncoder().encode("mdbase-connect application installation id v2\0"),Ar=new TextEncoder().encode("mdbase-connect application authorization proof v4\0"),Pr=new TextEncoder().encode("mdbase-connect application authorization proof v5\0");async function Zn(t){let e=ht(t),i=new Uint8Array(await crypto.subtle.digest("SHA-256",he([Rr,D(e)]))).slice(0,16);return i[6]=i[6]&15|128,i[8]=i[8]&63|128,[Ge(i.slice(0,4)),Ge(i.slice(4,6)),Ge(i.slice(6,8)),Ge(i.slice(8,10)),Ge(i.slice(10,16))].join("-")}function ei(t){let e=[ht(t.installation_signing_public_key),ht(t.grant_agreement_public_key),ht(t.grant_signing_public_key)];if(e.some((c,d)=>e.slice(d+1).some(p=>xr(c,p))))throw new Error("Application authorization keys must be distinct.");let n=cn(t.authorization_nonce),i=cn(t.code_challenge),o=t.contracts,r=o.operation_transport_recovery??[],a=t.requested_operations.some(c=>we(c,{action:"mutate"}))||t.requested_files?.actions.some(c=>!["list","read"].includes(c))===!0;if(!Jn(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||!$e(o.operation_transport)||t.protocol_version===$&&o.operation_transport!==L||r.some(c=>!$e(c)||c===o.operation_transport)||new Set(r).size!==r.length||t.protocol_version===an&&r.length>0||r.length>0&&!a||(a?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.");Tr(t.requested_files);let s=t.requested_operations.map(c=>D(new TextEncoder().encode(c)));return he([t.protocol_version===$?Pr:Ar,H(t.protocol_version),D(yt(t.application_id)),D(yt(t.authorization_id)),D(new TextEncoder().encode(t.application_declaration_id)),D(ti(t.application_manifest_digest)),D(yt(t.application_installation_id)),...e.map(D),D(new TextEncoder().encode(t.flow)),D(n),D(new TextEncoder().encode(t.issued_at)),D(new TextEncoder().encode(t.expires_at)),Xn(t.redirect_uri),Xn(t.state),D(new TextEncoder().encode(t.code_challenge)),H(o.operation_transport),...t.protocol_version===$?[H(r.length),...r.map(H)]:[],H(o.authorization_binding),H(o.semantic_capabilities),Or(o.durable_mutation),H(s.length),...s,kr(t.requested_files),Ir(t.collection_id)])}function Or(t){return t===void 0?new Uint8Array(1):he([new Uint8Array([1]),H(t)])}function Tr(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 kr(t){if(t===void 0)return new Uint8Array(1);let e=t.actions.map(n=>D(new TextEncoder().encode(n)));return he([new Uint8Array([1]),H(e.length),...e,D(new TextEncoder().encode(t.scope.kind)),...t.scope.kind==="selected_folders"?[H(t.scope.folders.length),...t.scope.folders.map(n=>D(new TextEncoder().encode(n)))]:[]])}function Xn(t){return t===void 0?new Uint8Array(1):he([new Uint8Array([1]),D(new TextEncoder().encode(t))])}function Ir(t){return t===void 0?new Uint8Array(1):he([new Uint8Array([1]),D(yt(t))])}function ht(t){let e=cn(t);if(e.byteLength!==65||e[0]!==4)throw new Error("Application authorization public key is invalid.");return e}function cn(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(Mr(i)!==t)throw new Error("Non-canonical base64url value.");return i}function yt(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 ti(e)}function ti(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 D(t){return he([H(t.byteLength),t])}function H(t){let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t,!1),e}function he(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 Mr(t){return btoa(String.fromCharCode(...t)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}function xr(t,e){return t.byteLength===e.byteLength&&t.every((n,i)=>n===e[i])}function Ge(t){return[...t].map(e=>e.toString(16).padStart(2,"0")).join("")}var ni={id:"mdbase.record.created",version:"1.0.0",digest:"sha256:7f3bed6baa356ee9389e977ae7b77a102e2bee871a7c1d9f2026fc21cacdbfc9"};var ii={id:"mdbase.runtime.timer.fired",version:"1.0.0",digest:"sha256:41105be7a7abf33b31ced47e1e1965242236e40ccaea286b959b0a8c591f5642"};var oi=28485,We="P256-HKDF-SHA256-AES256GCM",mt=1;var Er="contract-setup-v1",Dr="file-relay-v1",qr="protocol-usage-report-v1",Fr=["application-authorization-v4","authorization-activation","encrypted-relay","policy-ack"];var zr=["durable-mutation-journal-v1","durable-file-lifecycle-v1"],ms=[...zr,"mutation-replay-after-credential-retirement-v1"],gs=[...Fr,"application-authorization-v5",Er,Dr,qr],ln=1;var ri="mdbase-authority-request-proof-v1",Ye={version:"x-mdbase-proof-version",timestamp:"x-mdbase-proof-timestamp",nonce:"x-mdbase-proof-nonce",signature:"x-mdbase-proof-signature"};function gt(t,e,n){let i=new Set(t.required),o=[...new Set([...t.required,...t.optional??[]])],r={};for(let a of o)r[a]=Ur(a,i.has(a),e,n);return{contractVersion:1,values:r,requiredAvailable:t.required.every(a=>r[a]?.state==="available")}}function Ur(t,e,n,i){let o=ft(t),r=o.filter(s=>!i.operations.includes(s)),a={id:t,requirement:e?"required":"optional",operations:o,missingOperations:r,evidence:[{source:"application",fact:`${e?"Required":"Optional"} in capability contract v1.`}]};if(r.length>0)return{...a,state:"requires_authorization",evidence:[...a.evidence,{source:"authorization",fact:`Missing ${r.join(", ")}.`}],reason:"The current grant does not include every operation for this capability."};if(t==="definitions.contracts.current"&&i.scope.access!=="full_collection"){let s=new Set(i.scope.contracts.map(({id:d,version:p,digest:u})=>`${d}@${p}:${u}`)),c=(n.requirements?.contracts??[]).filter(({id:d,version:p,digest:u})=>!s.has(`${d}@${p}:${u}`));if(c.length>0)return{...a,state:"requires_authorization",reason:"The current grant does not approve the exact required contract definitions.",evidence:[...a.evidence,{source:"authorization",fact:`Missing ${c.map(({id:d,version:p})=>`${d}@${p}`).join(", ")}.`}],details:{missingContracts:c}}}if(t.startsWith("files.")){let s=t.slice(6);if(!i.fileCapability?.actions.includes(s))return{...a,state:i.fileCapability?"requires_authorization":"unsupported",reason:i.fileCapability?`The current file grant does not include ${s}.`:"This connection has no file capability.",evidence:[...a.evidence,{source:"authorization",fact:i.fileCapability?`Granted file actions: ${i.fileCapability.actions.join(", ")}.`:"No file capability was granted."}]}}return t==="notifications.background-delivery"&&(n.notifications?.criteria.length??0)===0?{...a,state:"requires_setup",reason:"The application manifest declares no notification criteria.",evidence:[...a.evidence,{source:"application",fact:"No authority notification criteria are declared."}]}:{...a,state:"available",evidence:[...a.evidence,{source:"authorization",fact:o.length>0?`Granted operations: ${o.join(", ")}.`:"No record operation is required."},{source:"authority",fact:i.authority.kind==="hosted"?"Backed by a durable hosted mdbase authority.":"Backed by a user-operated mdbase connector."}],...t==="sync.offline-replica"?{details:{durability:"device",writes:"queued",authority:i.authority.kind}}:{},...t==="notifications.background-delivery"?{details:{delivery:"authority",payload:"opaque"}}:{}}}var b=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 k(t,e,...[n={}]){let i=pe[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 ai(t,e,n={}){return en(t,e,{details:n.details,operation_outcome:n.operationOutcome,trace_id:n.traceId})}function l(t,e,...n){let i=n[0];return new b(k(t,e,...n),{status:i?.status,cause:i?.cause})}function F(t,e,n={}){let{status:i,cause:o,...r}=n;return new b(en(t,e,{details:r.details,operation_outcome:r.operationOutcome,trace_id:r.traceId}),{status:i,cause:o})}function Se(t){let e=Lr(t.diagnostics),n=Kr(t.diagnostics);if(e==="collection_version_unsupported"){let i=Br(t.diagnostics);return k(e,n,{operationOutcome:"rejected",details:i})}return e!=="operation_invalid"?k(e,n,{operationOutcome:"rejected",details:{diagnostics:t.diagnostics}}):k(e,n,{operationOutcome:"rejected",details:{diagnostics:t.diagnostics,partial_result:t.result}})}function Lr(t){let e=new Set(t.filter(n=>n.severity==="error").map(n=>n.code));return["migration_required","migration_lossy","unsupported_version"].some(n=>e.has(n))?"collection_version_unsupported":["invalid_config","invalid_configuration","missing_config","missing_spec_version"].some(n=>e.has(n))?"collection_configuration_invalid":["duplicate_type","invalid_contract_definition","invalid_data_contract","invalid_type_definition","invalid_type_path"].some(n=>e.has(n))?"collection_type_registry_invalid":["collection_invalid","collection_open_failed"].some(n=>e.has(n))?"collection_invalid":"operation_invalid"}function Br(t){let e=t.map(n=>n.details).find(n=>jr(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 jr(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function si(t){return t instanceof b&&t.retryable}function Kr(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 Hr=["access_denied","access_paused","authorization_binding_incompatible","authorization_expired","capability_contract_incompatible","collection_access_denied","connector_identity_changed","connector_offline","connector_upgrade_required","direct_operation_rejected","durable_mutation_unsupported","operation_outcome_unknown","encryption_required","encrypted_relay_rejected","hosted_provider_unavailable","insufficient_access","invalid_encrypted_response","invalid_operation_response","invalid_request","missing_grant_key","mutation_recovery_expired","mutation_request_conflict","not_authorized","operation_cancelled","operation_failed","rate_limited","relay_authorization_expired","relay_unavailable","temporarily_unavailable","timeout","transport_protocol_incompatible","unsupported_operation"],ci=Object.keys(pe),ye=["discovery_failed","invalid_operation_response","invalid_application_manifest","invalid_request","manifest_load_failed","rate_limited","temporarily_unavailable","timeout"],Re=[...ye,"access_denied","application_identity_unavailable","approval_window_blocked","authorization_binding_incompatible","authorization_cancelled","authorization_replayed","browser_required","capability_contract_incompatible","collection_access_denied","collection_configuration_invalid","collection_contracts_missing","collection_incompatible","collection_invalid","collection_kind_unsupported","collection_mismatch","collection_not_found","collection_type_registry_invalid","collection_version_unsupported","connector_identity_changed","connector_offline","connector_upgrade_required","device_authorization_failed","durable_mutation_unsupported","encryption_required","expired_token","invalid_application_authorization","invalid_callback","invalid_device_authorization_response","invalid_token_response","scope_denied","reconnect_required","token_exchange_failed","transport_protocol_incompatible"],Je=[...ye,"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"],dn=["connector_offline","connector_upgrade_required","invalid_operation_response","not_authorized","operation_failed","temporarily_unavailable","timeout"],qs=[...Re,"collection_not_ready","collection_not_selected","unknown_collection"],Vr=["collection_configuration_invalid","collection_invalid","collection_type_registry_invalid","collection_version_unsupported"],_t=[...Hr,...Vr],Y=[..._t,"invalid_path","operation_invalid"],li=[...Y,"query_snapshot_changed","sandbox_unsupported"],z=[...Y,"concurrent_modification","invalid_preflight","pending_mutation_unresolved"],bt=[..._t,"change_cursor_reset"],re=[...z,"type_pack_provision_failed"];function I(t,e=[]){return{ok:!0,value:t,diagnostics:e}}function O(t){return{ok:!1,problem:t}}async function x(t,e){try{return I(await t())}catch(n){if(!(n instanceof b))throw n;let i=n.problem;return i.code==="unknown"||e.includes(i.code)?O(i):O(ai(i.code,i.message,{details:i.details,operationOutcome:i.operation_outcome,traceId:i.trace_id}))}}var vt=3e4,$r=1e4,Gr=10*6e4,Wr=12e4,Yr=6e4;function Ae(t={}){return{requestMs:Qe(t.requestMs,vt,"requestMs"),watchStartMs:Qe(t.watchStartMs,$r,"watchStartMs"),fileIndexMs:Qe(t.fileIndexMs,Gr,"fileIndexMs"),uploadMs:Qe(t.uploadMs,Wr,"uploadMs"),syncMs:Qe(t.syncMs,Yr,"syncMs")}}function di(t,e){return{...t,signal:e.signal,...e.deadline===null?{}:{deadlineUnixMs:e.deadline}}}function ae(t={},e=vt,n=Date.now){let i=t.timeoutMs===void 0?e:t.timeoutMs,o=i===null?null:Jr(i),r=new AbortController,a=o===null?null:n()+o,s=()=>r.abort(t.signal?.reason);t.signal?.aborted?s():t.signal?.addEventListener("abort",s,{once:!0});let c=o===null?void 0:setTimeout(()=>r.abort(l("timeout","The operation exceeded its request deadline.",{operationOutcome:"not_sent"})),o),d=!1;return{signal:r.signal,deadline:a,remainingMs:()=>a===null?null:Math.max(0,a-n()),dispose:()=>{d||(d=!0,c!==void 0&&clearTimeout(c),t.signal?.removeEventListener("abort",s))}}}async function U(t,e,n){let i=ae(t,e),o,r=new Promise((s,c)=>{o=c}),a=()=>o?.(J(i.signal));i.signal.addEventListener("abort",a,{once:!0});try{if(i.signal.aborted)throw J(i.signal);return await Promise.race([n(i),r])}finally{i.signal.removeEventListener("abort",a),i.dispose()}}async function B(t,e,n){let i=ae(t,e);try{if(i.signal.aborted)throw J(i.signal);return await n(i)}finally{i.dispose()}}function J(t){return t.reason instanceof b?t.reason:l("operation_cancelled","The operation was cancelled before it changed the collection.",{operationOutcome:"not_sent",cause:t.reason})}function Jr(t){if(!Number.isSafeInteger(t)||t<=0)throw new TypeError("timeoutMs must be a positive safe integer or null.");return t}function Qe(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}var Qr="mdbase-connect-keys",se="grant-keys",pn=18446744073709551615n,Xr="mdbase-connect relay request key v1",Zr="mdbase-connect relay response key v1",ui=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Pe=class{database=null;async create(e){let n=await hi(e),i=await this.open();return await fi(i,o=>o.add({...n,counter:"0"})),n}async get(e){let n=await this.open(),i=await ia(n.transaction(se).objectStore(se).get(e));return i?{handle:i.handle,agreementPrivateKey:i.agreementPrivateKey,agreementPublicKey:i.agreementPublicKey,signingPrivateKey:i.signingPrivateKey,signingPublicKey:i.signingPublicKey}:null}async nextCounter(e){let n=await this.open();return new Promise((i,o)=>{let r=n.transaction(se,"readwrite"),a=r.objectStore(se),s=a.get(e),c=null;s.onerror=()=>o(s.error),s.onsuccess=()=>{let d=s.result;if(!d){r.abort(),o(new R("missing_grant_key","The encrypted grant key is unavailable."));return}let p=BigInt(d.counter)+1n;if(p>pn){r.abort(),o(new R("counter_exhausted","The encrypted grant must be authorized again."));return}c=p.toString(),a.put({...d,counter:c})},r.onerror=()=>o(r.error),r.onabort=()=>o(r.error??new Error("Key counter transaction aborted.")),r.oncomplete=()=>{c&&i(c)}})}async delete(e){let n=await this.open();await fi(n,i=>i.delete(e))}open(){if(typeof indexedDB>"u")throw new R("key_storage_unavailable","Encrypted relay authorization requires browser IndexedDB or an injected grant key store.");return this.database||(this.database=new Promise((e,n)=>{let i=indexedDB.open(Qr,1);i.onupgradeneeded=()=>{i.result.objectStoreNames.contains(se)||i.result.createObjectStore(se,{keyPath:"handle"})},i.onerror=()=>n(i.error),i.onsuccess=()=>e(i.result)})),this.database}},Oe=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 hi(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,a)=>{n=r,i=a});return this.sequence=this.sequence.then(()=>{let r=this.records.get(e);if(!r)throw new R("missing_grant_key","The encrypted grant key is unavailable.");let a=BigInt(r.counter)+1n;if(a>pn)throw new R("counter_exhausted","The encrypted grant must be authorized again.");r.counter=a.toString(),n(r.counter)}).catch(r=>{i(r)}),o}async delete(e){this.records.delete(e)}};async function Ct(t,e,n,i){let o=await ea(t,e,n),r=i.timestamp??Math.floor(Date.now()/1e3),a=i.nonce??crypto.randomUUID(),s=await fn({...i,timestamp:r,nonce:a}),c=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},o.signingPrivateKey,new TextEncoder().encode(s));return{[Ye.version]:String(ln),[Ye.timestamp]:String(r),[Ye.nonce]:a,[Ye.signature]:Xe(new Uint8Array(c))}}async function fn(t){let e=t.method.toUpperCase(),n=await pi(t.body??""),i=await pi(t.credential);for(let o of[e,t.target,String(t.timestamp),t.nonce])if(!o||o.includes(`
|
|
2
2
|
`)||o.includes("\r"))throw new R("invalid_proof_input","Authority request proof metadata is invalid.");return[ri,ln,e,t.target,n,i,t.timestamp,t.nonce].join(`
|
|
3
|
-
`)}async function Q(t,e,n,i,o,r=crypto.randomUUID()){X(n.encryption);let a=await hi(t,e,n.encryption.application_agreement_public_key),s=await t.nextCounter(e),c={binding:n,protocolVersion:L,requestId:r,operation:i,counter:s},d=await yi(a.agreementPrivateKey,n,c.protocolVersion,"request"),p=new TextEncoder().encode(JSON.stringify(o??{})),u=await crypto.subtle.encrypt({name:"AES-GCM",iv:_i(s),additionalData:new TextEncoder().encode(gi(c,"request")),tagLength:128},d,p);return{type:"encrypted_operation_request",...ea(c),ciphertext:Xe(new Uint8Array(u))}}async function Te(t,e,n,i,o){if(!ta(i,o))throw new R("invalid_encrypted_response","Encrypted response metadata does not match its request.");let r=await hi(t,e,n.encryption.application_agreement_public_key),a={binding:n,protocolVersion:i.protocol_version,requestId:i.request_id,operation:i.operation,counter:i.counter},s=await yi(r.agreementPrivateKey,n,i.protocol_version,"response");try{let c=await crypto.subtle.decrypt({name:"AES-GCM",iv:_i(i.counter),additionalData:new TextEncoder().encode(gi(a,"response")),tagLength:128},s,vi(bi(o.ciphertext))),d=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(c));if(d?.ok===!0&&"result"in d||d?.ok===!1&&Ve(d.problem))return d;throw new Error("invalid response body")}catch(c){throw c instanceof R?c:new R("encrypted_response_rejected","The encrypted connector response could not be authenticated.")}}var R=class extends Error{constructor(n,i){super(i);this.code=n}code};async function fi(t){let e=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"]),n=Xe(new Uint8Array(await crypto.subtle.exportKey("raw",e.publicKey))),i=await crypto.subtle.exportKey("pkcs8",e.privateKey),o=await crypto.subtle.importKey("pkcs8",i,{name:"ECDH",namedCurve:"P-256"},!1,["deriveBits"]),r=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign","verify"]),a=Xe(new Uint8Array(await crypto.subtle.exportKey("raw",r.publicKey))),s=await crypto.subtle.exportKey("pkcs8",r.privateKey),c=await crypto.subtle.importKey("pkcs8",s,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]);return{handle:t,agreementPrivateKey:o,agreementPublicKey:n,signingPrivateKey:c,signingPublicKey:a}}async function hi(t,e,n){let i=await t.get(e);if(!i||i.agreementPublicKey!==n)throw new R("missing_grant_key","The encrypted grant key is unavailable or does not match the grant.");return i}async function Zr(t,e,n){let i=await t.get(e);if(!i||i.signingPublicKey!==n)throw new R("missing_grant_key","The remote authority signing key is unavailable or does not match the grant.");return i}async function yi(t,e,n,i){let o=await Ze(t,e.encryption.connector_agreement_public_key),r=await crypto.subtle.importKey("raw",o,"HKDF",!1,["deriveKey"]),a=new TextEncoder().encode(mi(e,n)),s=await crypto.subtle.digest("SHA-256",a);return crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:s,info:new TextEncoder().encode(i==="request"?Qr:Xr)},r,{name:"AES-GCM",length:256},!1,i==="request"?["encrypt"]:["decrypt"])}async function Ze(t,e){try{let n=await crypto.subtle.importKey("raw",vi(un(e)),{name:"ECDH",namedCurve:"P-256"},!1,[]);return await crypto.subtle.deriveBits({name:"ECDH",public:n},t,256)}catch{throw new R("invalid_public_key","The connector relay public key is invalid.")}}function mi(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 gi(t,e){return[mi(t.binding,t.protocolVersion),t.requestId,e,t.operation,t.counter].join("|")}function ea(t){let e=t.binding.encryption;return{protocol_version:t.protocolVersion,suite:We,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 ta(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 X(t){if(t.protocol_version!==mt||t.suite!==We||!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 R("unsupported_encryption","The grant uses an unsupported relay encryption profile.");if(typeof t.connector_id!="string"||!di.test(t.connector_id)||typeof t.collection_id!="string"||!di.test(t.collection_id))throw new R("unsupported_encryption","The grant uses invalid encrypted relay identities.");un(t.application_agreement_public_key),un(t.connector_agreement_public_key)}function _i(t){let e=BigInt(t);if(e<=0n||e>pn||e.toString()!==t)throw new R("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}function Xe(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}async function ui(t){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return Xe(new Uint8Array(e))}function bi(t){if(!/^[A-Za-z0-9_-]+$/.test(t))throw new R("invalid_base64","Encrypted relay data is malformed.");let e="=".repeat((4-t.length%4)%4),n=atob(t.replaceAll("-","+").replaceAll("_","/")+e);return Uint8Array.from(n,i=>i.charCodeAt(0))}function un(t){let e=bi(t);if(e.length!==65||e[0]!==4)throw new R("invalid_public_key","Encrypted relay public keys must be uncompressed P-256 points.");return e}function vi(t){return Uint8Array.from(t).buffer}function na(t){return new Promise((e,n)=>{t.onerror=()=>n(t.error),t.onsuccess=()=>e(t.result)})}function pi(t,e){return new Promise((n,i)=>{let o=t.transaction(se,"readwrite"),r=e(o.objectStore(se));r.onerror=()=>i(r.error),o.onerror=()=>i(o.error),o.onabort=()=>i(o.error??new Error("Grant key transaction aborted.")),o.oncomplete=()=>n()})}function ce(t){return{...t,credentials:"omit",targetAddressSpace:"loopback"}}async function et(){if(typeof navigator>"u"||!navigator.permissions?.query)return null;try{return(await navigator.permissions.query({name:"local-network-access"})).state}catch{return null}}function ke(t){return t===404||t===405||t===426||t>=500}function Ci(t,e){return we(t,e)}function G(t){return[...new Set(t)]}function wi(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 me(t){if(t?.aborted)throw l("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 b?t:e?.aborted?n?j(n,t):e.reason instanceof b?e.reason:l("operation_cancelled","The operation was cancelled before it changed the collection.",{operationOutcome:"not_sent",cause:t}):n?j(n,t):t instanceof TypeError?l(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 yn(t,e){return e?.aborted===!0||t instanceof b&&t.code==="operation_cancelled"}function Si(t,e){if(e.dryRun!==!0||e.wouldRename!==!0||e.from!==t.from||e.to!==t.to)throw l("invalid_preflight","The rename preview does not match this mutation. Run the preview again.")}function Ri(t,e){if(e.dryRun!==!0||e.wouldDelete!==!0||e.path!==t.path)throw l("invalid_preflight","The delete preview does not match this mutation. Run the preview again.")}function Ai(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 Pi(t){return{affectedRecords:new Set((t.brokenLinks??[]).map(e=>e.path)).size,totalUnits:1,warnings:0}}async function Oi(t,e){return Gn(t,e??{})}function Ti(t){return JSON.stringify(hn(t))}function hn(t){return Array.isArray(t)?t.map(e=>hn(e)):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[n])=>e<n?-1:e>n?1:0).map(([e,n])=>[e,hn(n)])):t}function j(t,e){return l("operation_outcome_unknown","The write may have completed, but mdbase could not recover its authoritative result. Retry the exact same write to recover safely.",{operationOutcome:"unknown",details:{request_id:t},cause:e})}function V(t){let e=new Uint8Array(t);return crypto.getRandomValues(e),mn(e)}function mn(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function ki(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}async function Z(t,e,n,i){try{return await fetch(t,e)}catch(o){throw l(n,i,{cause:o})}}async function A(t,e,n){let i;try{i=await t.text()}catch(o){throw F(e,n,{status:t.status,cause:o})}if(i.trim()==="")throw F(e,n,{status:t.status});try{return JSON.parse(i)}catch(o){throw F(e,n,{status:t.status,cause:o})}}function Ii(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 l("invalid_loopback_url","loopbackUrl must be an HTTP origin on 127.0.0.1 or ::1.");return e.origin}async function tt(){let t=V(32),e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return{verifier:t,challenge:mn(new Uint8Array(e))}}function T(t,e,n,i){return F(nt(t)??t?.error?.code??e,t?.error_description??t?.error?.message??n,{status:i,details:t?.error?.details})}function nt(t){return typeof t?.error=="string"?t.error:void 0}function it(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(a=>(a.protocol==="https:"||a.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(a.hostname))&&!a.username&&!a.password&&!a.search&&!a.hash)&&/^\/v1\/authorities\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/operations$/i.test(i.pathname)&&/^\/v1\/authorities\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/sync$/i.test(o.pathname)&&/^\/v1\/authorities\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/files$/i.test(r.pathname)&&i.origin===o.origin&&i.origin===r.origin&&i.pathname.split("/")[3]===e&&o.pathname.split("/")[3]===e&&r.pathname.split("/")[3]===e}catch{return!1}}function Mi(t,e){return it({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 St(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&&ia(o))}function ia(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 xi(t,e){if(!t||typeof t!="object"||Array.isArray(t)||t.collection_id!==e)return!1;try{return X(t),!0}catch{return!1}}function Ei(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 l("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 M(t){if(!t)return null;try{return JSON.parse(t)}catch{return null}}function Rt(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 Di(t){return t.endsWith("/")?t.slice(0,-1):t}function qi(){if(typeof location>"u")throw l("manifest_required","manifest is required outside a browser environment.");if(location.origin==="null")throw l("manifest_required","Downloaded applications must provide their v1 portable manifest inline.");return new URL("/.well-known/mdbase-app.json",location.origin).href}function Fi(){if(typeof location>"u")throw l("redirect_uri_required","redirectUri is required outside a browser environment.");return location.href.split(/[?#]/)[0]}function zi(t,e,n,i){if(typeof t!="string"&&t.distribution==="portable"||i)return"null";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 Ui(t){let e=":token:",n=t.lastIndexOf(e);return n<0?"":t.slice(n+e.length)}function At(){if(typeof location>"u")throw l("callback_url_required","callbackUrl is required outside a browser environment.");return location.href}function Ni(t){if(t)return new Ie;if(typeof localStorage>"u")throw l("storage_required","storage is required outside a browser environment.");try{let e=`mdbase-connect:probe:${V(8)}`;return localStorage.setItem(e,"1"),localStorage.removeItem(e),localStorage}catch{return new Ie}}var Ie=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 Li(t){return typeof t=="string"||t.distribution!=="portable"?!1:typeof location>"u"||location.origin==="null"||!["http:","https:"].includes(location.protocol)}function Bi(t){let e=Ti(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")}`}function ot(t){for(let e of["code","state","error","error_description"])t.searchParams.delete(e);return t}function Pt(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 ji(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 ge=["describe","changes","read","query"];var Me=class{constructor(e,n){this.connect=e;this.operations=G(n.operations??ge),this.selection=n.selection,this.autoSelect=n.autoSelect??"only",this.snapshot={status:"unselected",connections:[]},this.refresh()}connect;operations;selection;autoSelect;listeners=new Set;snapshot;snapshotKey="";stopConnections;stopSelection;stopActiveConnection;activeCollectionId=null;unavailableReason="not_authorized";started=!1;refreshing=!1;refreshQueued=!1;transactionDepth=0;callbackPromise=null;async start(e){this.started||(this.started=!0,this.stopConnections=this.connect.onConnectionsChange(()=>this.refresh()),this.stopSelection=this.selection.subscribe(()=>{this.unavailableReason="not_authorized",this.refresh()}));let n=this.selection.authorizationCallback();if(n){let i=await this.handleAuthorizationCallback(n,e);if(!i.ok)return i}else this.autoSelectOnlyConnection();return this.refresh(),I(this.snapshot)}destroy(){this.stopConnections?.(),this.stopSelection?.(),this.stopActiveConnection?.(),this.stopConnections=void 0,this.stopSelection=void 0,this.stopActiveConnection=void 0,this.activeCollectionId=null,this.started=!1}getSnapshot(){return this.snapshot}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}select(e,n={}){let i=this.connect.connection(e);return i?(this.unavailableReason="not_authorized",this.selection.select(e,n),this.refresh(),I(i)):O(k("unknown_collection","This collection is not authorized for this application."))}clearSelection(e={}){this.unavailableReason="not_authorized",this.selection.select(null,e),this.refresh()}forget(e){this.transactionDepth+=1;try{let n=this.selection.selectedCollectionId()===e;this.connect.connection(e)?.forget(),n&&this.selection.select(null,{history:"replace"})}finally{this.transactionDepth-=1,this.refresh()}}async authorize(e,n={}){let i=this.selection.selectedCollectionId();if(e==="selected"&&!i)return O(k("collection_not_selected","Choose a collection before updating its access."));let o=typeof e=="object"?e.collectionId:e==="selected"?i:null;this.transactionDepth+=1;try{let r=await this.connect.authorize({...n,operations:this.operations,target:o===null?{kind:"choose"}:{kind:"collection",collectionId:o},returnTo:this.selection.authorizationReturnTo()});return r.ok&&r.value.kind==="connected"&&this.selection.finishAuthorization(r.value.returnTo,r.value.connection.collectionId),r}finally{this.transactionDepth-=1,this.refresh()}}async ensureOperations(e,n){let i=this.snapshot;if(i.status!=="ready")return O(k("collection_not_ready","Choose an authorized collection first."));let o=G(e),r=i.connection.authorizationCapabilities(o);if(r.sufficient)return I({kind:"unchanged",connection:i.connection});this.transactionDepth+=1;try{let a=await this.connect.authorize({...n,operations:G([...r.grantedOperations,...r.missingOperations]),target:{kind:"collection",collectionId:i.collectionId},returnTo:this.selection.authorizationReturnTo()});return a.ok&&a.value.kind==="connected"&&this.selection.finishAuthorization(a.value.returnTo,a.value.connection.collectionId),a}finally{this.transactionDepth-=1,this.refresh()}}handleAuthorizationCallback(e,n){if(!Pt(e))return Promise.resolve(O(k("invalid_callback","This URL is not an authorization callback.")));if(this.callbackPromise)return this.callbackPromise;this.transactionDepth+=1;let i=this.connect.completeAuthorization(e,n).then(o=>{if(!o.ok){let a=ji(o.problem);return this.selection.clearAuthorizationCallback(a),this.refresh(),o}let r=o.value;return this.unavailableReason="not_authorized",this.selection.finishAuthorization(r.returnTo,r.connection.collectionId),this.refresh(),I(r.connection,o.diagnostics)}).catch(o=>{throw this.selection.clearAuthorizationCallback(),this.refresh(),o}).finally(()=>{this.transactionDepth-=1,this.refresh(),this.callbackPromise===i&&(this.callbackPromise=null)});return this.callbackPromise=i,i}autoSelectOnlyConnection(){if(this.autoSelect!=="only"||this.selection.selectedCollectionId())return;let e=this.connect.connections();e.length===1&&this.selection.select(e[0].collectionId,{history:"replace"})}refresh(){if(this.transactionDepth>0){this.refreshQueued=!0;return}if(this.refreshing){this.refreshQueued=!0;return}this.refreshing=!0;try{do this.refreshQueued=!1,this.refreshOnce();while(this.refreshQueued)}finally{this.refreshing=!1}}refreshOnce(){let e=this.selection.selectedCollectionId(),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(a=>{!a&&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 a=i.info();o={status:"ready",collectionId:e,connection:i,info:a,access:i.authorizationCapabilities(this.operations),connections:n}}let r=oa(o);if(r!==this.snapshotKey){this.snapshot=o,this.snapshotKey=r;for(let a of this.listeners)a()}}};function oa(t){return 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 rt=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)}},xe=class{constructor(e,n,i=Ae()){this.connect=e;this.options=n;this.timeouts=i;this.verificationStore=n.verificationStore??pa()}connect;options;timeouts;listeners=new Set;verificationStore;snapshot={status:"opening",connections:[]};manifest=null;application=null;base=null;stopBase;setupAssessment=null;setupTypePackAdoptions=null;verificationGeneration=0;lifecycleGeneration=0;startOperation=null;start(e){if(this.base&&!this.startOperation)return Promise.resolve(I(this.snapshot));let n=this.startOperation??this.beginStart();return n.waiters+=1,U(e,this.timeouts.watchStartMs,()=>n.promise).finally(()=>{n.waiters-=1,n.waiters===0&&this.startOperation===n&&(n.controller.abort(),this.startOperation=null,this.lifecycleGeneration+=1)})}beginStart(){this.snapshot={status:"opening",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){let i=await this.connect.register(e);if(!i.ok)return i;let o=await this.connect.manifest(e);if(!o.ok)return o;let r=o.value.requirements?.capabilities;if(!r)return O(k("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:{}}]}}));if(n!==this.lifecycleGeneration||e.signal?.aborted)throw J(e.signal??new AbortController().signal);this.application=i.value,this.manifest=o.value;let a=new Me(this.connect,{selection:this.options.selection,autoSelect:this.options.autoSelect,operations:ra(r)});this.base=a;try{let s=await a.start(e);if(!s.ok)return this.cleanupBase(a),s;if(n!==this.lifecycleGeneration||e.signal?.aborted)throw J(e.signal??new AbortController().signal);if(this.stopBase=a.subscribe(()=>{this.base===a&&this.refresh()}),await this.refresh(!0,e),n!==this.lifecycleGeneration||e.signal?.aborted)throw J(e.signal??new AbortController().signal);return I(this.snapshot)}catch(s){throw this.cleanupBase(a),s}}destroy(){this.lifecycleGeneration+=1,this.verificationGeneration+=1,this.startOperation?.controller.abort(),this.startOperation=null,this.base&&this.cleanupBase(this.base),this.application=null,this.manifest=null,this.setupAssessment=null,this.setupTypePackAdoptions=null,this.snapshot={status:"opening",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={}){return this.requireBase().select(e,n)}clearSelection(e={}){this.requireBase().clearSelection(e)}forget(e){this.requireBase().forget(e)}authorize(e,n={}){return this.requireBase().authorize(e,n)}handleAuthorizationCallback(e,n){return this.requireBase().handleAuthorizationCallback(String(e),n)}completeAuthorization(e,n){return this.requireBase().handleAuthorizationCallback(e===void 0?At():String(e),n)}ensureCapabilities(e,n){let i=this.requireManifest().requirements?.capabilities,o=new Set([...i?.required??[],...i?.optional??[]]);return e.some(r=>!o.has(r))?Promise.resolve(O(k("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:[...o]}}]}}))):this.requireBase().ensureOperations(aa(e),n)}async applyCollectionSetup(e){if(this.snapshot.status!=="setup_review_required"||!this.setupAssessment)return O(k("collection_not_ready","There is no reviewed collection setup to apply."));if(!this.setupAssessment.applicable)return O(k("collection_not_ready","Resolve the collection setup conflicts before applying this update."));let n=this.connection();if(!n)return O(k("collection_not_ready","The collection is not ready."));let i=this.setupAssessment,o={...this.collectionSetupInput(this.setupTypePackAdoptions??void 0),expectedAssessmentDigest:i.assessmentDigest,expectedCollectionRevision:i.collectionRevision,expectedProvisionDigest:i.provisionDigest,allowTypePackDowngrades:i.typePacks.filter(s=>s.status==="downgrade").map(s=>s.desired.id)},r=ae(e,this.timeouts.requestMs),a={signal:r.signal,timeoutMs:null};try{let s=await n.applyCollectionSetup(o,a);return s.ok?(this.setupAssessment=null,this.setupTypePackAdoptions=null,await this.verifySetup(this.context(n),++this.verificationGeneration,a),I(this.snapshot)):s}finally{r.dispose()}}async refresh(e=!1,n){if(!this.base||!this.manifest)return;let i=this.base.getSnapshot();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}let r=this.context(i.connection);if(!r.capabilities.requiredAvailable||!da(this.manifest,r.info)){this.publish({status:"authorization_required",...r});return}if(!(this.manifest.requirements?.capabilities?.required.includes("collection.setup.apply")??!1)){this.publish({status:"ready",verification:"verified",...r});return}let s=gn(this.manifest,i.collectionId);this.verificationStore.read(s)===Ki(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 a=this.collectionSetupInput(),s=i?await o.assessCollectionSetup(a,i):await o.assessCollectionSetup(a);if(n===this.verificationGeneration){if(!s.ok){this.publish({status:"blocked",problem:s.problem,...e});return}if(!s.value.applicable){let c=la(s.value);if(Object.keys(c).length>0){if(s=i?await o.assessCollectionSetup(this.collectionSetupInput(c),i):await o.assessCollectionSetup(this.collectionSetupInput(c)),n!==this.verificationGeneration)return;if(!s.ok){this.publish({status:"blocked",problem:s.problem,...e});return}this.setupTypePackAdoptions=c}}if(n===this.verificationGeneration){if(s.value.status!=="current"){this.setupAssessment=s.value,this.verificationStore.remove(gn(r,e.collectionId)),this.publish({status:"setup_review_required",update:ca(s.value,r.provisions?.type_packs??[]),...e});return}this.verificationStore.write(gn(r,e.collectionId),Ki(r)),this.publish({status:"ready",verification:"verified",...e})}}}collectionSetupInput(e){let n=this.requireManifest(),i=this.requireApplication();return{applicationId:ua(i.family_identity),declarationDigest:`sha256:${i.manifest_digest}`,requirements:{configuration:n.requirements?.configuration??[]},provisions:{configuration:n.provisions?.configuration??[],typePacks:n.provisions?.type_packs??[]},...e?{typePackAdoptions:e}:{}}}context(e){let n=e.info();return{collectionId:e.collectionId,info:n,capabilities:gt(this.requireManifest().requirements.capabilities,this.requireManifest(),n),connections:this.connect.connections()}}publish(e){if(JSON.stringify(this.snapshot)!==JSON.stringify(e)){this.snapshot=e;for(let n of this.listeners)n()}}requireBase(){if(!this.base)throw new Error("Start the application session before using it.");return this.base}requireManifest(){if(!this.manifest)throw new Error("Start the application session before using it.");return this.manifest}requireApplication(){if(!this.application)throw new Error("Start the application session before using it.");return this.application}};function ra(t){return pt(t)}function aa(t){let e=t.flatMap(n=>ft(n));return[...new Set(e)]}function sa(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 ca(t,e){let n=t.typePacks.map(r=>{let a=e.find(s=>s.manifest.id===r.desired.id);if(!a)throw new Error(`Collection setup returned undeclared type pack '${r.desired.id}'.`);return sa(a,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 la(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 gn(t,e){return`mdbase-application-session:v1:${t.id}:${e}`}function Ki(t){return JSON.stringify({capabilities:t.requirements?.capabilities,requirements:t.requirements?.configuration??[],provisions:t.provisions??{}})}function da(t,e){return t.requirements?.access!=="full_collection"||e.scope.access==="full_collection"}function ua(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 pa(){return typeof localStorage<"u"?{read:t=>localStorage.getItem(t),write:(t,e)=>localStorage.setItem(t,e),remove:t=>localStorage.removeItem(t)}:new rt}function ee(t,e){return new Promise((n,i)=>{if(e?.aborted){i(e?.reason??new DOMException("Aborted","AbortError"));return}let o=()=>e?.removeEventListener("abort",a),r=setTimeout(()=>{o(),n()},t),a=()=>{clearTimeout(r),o(),i(e?.reason??new DOMException("Aborted","AbortError"))};e?.addEventListener("abort",a,{once:!0})})}var fa="mdbase-connect-identities",Ee="application-identities",_n=BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),ha=_n/2n,De=class{database=null;async create(e){let n=await Vi(e),i=await this.open();return await Hi(i,o=>o.add(n)),n}async get(e){let n=await this.open();return await ya(n.transaction(Ee).objectStore(Ee).get(e))??null}async delete(e){let n=await this.open();await Hi(n,i=>i.delete(e))}open(){if(typeof indexedDB>"u")throw new _e("Persistent application identity requires browser IndexedDB or an injected identity store.");return this.database||(this.database=new Promise((e,n)=>{let i=indexedDB.open(fa,1);i.onupgradeneeded=()=>{i.result.objectStoreNames.contains(Ee)||i.result.createObjectStore(Ee,{keyPath:"handle"})},i.onerror=()=>n(i.error),i.onsuccess=()=>e(i.result)})),this.database}},qe=class{records=new Map;async create(e){if(this.records.has(e))throw new Error(`Application identity already exists: ${e}`);let n=await Vi(e);return this.records.set(e,n),n}async get(e){return this.records.get(e)??null}async delete(e){this.records.delete(e)}},_e=class extends Error{constructor(e){super(e),this.name="ApplicationIdentityStoreError"}};async function Fe(t){return Zn(t.signingPublicKey)}async function at(t,e){if(t.installation_signing_public_key!==e.signingPublicKey||t.application_installation_id!==await Fe(e))throw new Error("Application authorization identity does not match its binding.");let n=ga(new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},e.signingPrivateKey,ei(t))));return{binding:t,signature:$i(n)}}async function Ot(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 a=await t.get(i);if(a)return a;throw r}}async function Vi(t){let e=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign","verify"]),n=$i(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 ya(t){return new Promise((e,n)=>{t.onerror=()=>n(t.error),t.onsuccess=()=>e(t.result)})}function Hi(t,e){return new Promise((n,i)=>{let o=t.transaction(Ee,"readwrite");e(o.objectStore(Ee)).onerror=()=>i(o.error),o.onerror=()=>i(o.error),o.onabort=()=>i(o.error??new Error("Identity transaction aborted.")),o.oncomplete=()=>n()})}function ma(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 $i(t){return btoa(String.fromCharCode(...t)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}function ga(t){if(t.byteLength!==64)throw new Error("Application authorization signature is invalid.");let e=_a(t.slice(32));if(e===0n||e>=_n)throw new Error("Application authorization signature is invalid.");return e<=ha?t:ma([t.slice(0,32),ba(_n-e,32)])}function _a(t){return BigInt(`0x${va(t)}`)}function ba(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 va(t){return[...t].map(e=>e.toString(16).padStart(2,"0")).join("")}function Gi(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 ze=class{constructor(e,n=vt){this.transport=e;this.requestTimeoutMs=n}transport;requestTimeoutMs;operation(e,n,i){return x(()=>this.transport.operation(e,n,i),ci)}async describe(e){let n=await this.rawOperation("describe",{},_t,e);return E(n,Fa)}async changes(e={},n){let i=await this.rawOperation("changes",e,bt,n);return E(i,qa)}async read(e,n){let i=await this.envelopeOperation("read",Ca(e),Y,n);return E(i,Tt)}async query(e={},n){let i=await this.envelopeOperation("query",wa(e),li,n);return E(i,({results:o,meta:r})=>({results:o.map(ro),...r?{meta:{totalCount:r.total_count,hasMore:r.has_more,...r.snapshot?{snapshot:r.snapshot}:{}}}:{}}))}async*queryPages(e={},n={}){let{offset:i,limit:o,snapshot:r,...a}=e,s=za(i,0),c=Zi(n.firstPageSize??o,200),d=Zi(n.pageSize??o,1e3),p=r,u=0,f=0;for(;!n.signal?.aborted;){let h=await this.query({...a,offset:s,limit:f===0?c:d,...p?{snapshot:p}:{}},{signal:n.signal,timeoutMs:n.pageTimeoutMs});if(!h.ok){yield h;return}let _=h.value,m=_.meta?.snapshot;if(p&&m&&p!==m){yield O(k("query_snapshot_changed","The collection query snapshot changed while paging. Refresh the query before continuing."));return}!p&&m&&(p=m),u+=_.results.length;let w=!_.meta?.hasMore||_.results.length===0,y={results:_.results,..._.meta?{meta:_.meta}:{},page:f,offset:s,loaded:u,complete:w,...p?{snapshot:p}:{}};if(n.onProgress?.(y),yield I(y,h.diagnostics),w)return;s+=_.results.length,f+=1}}async queryAll(e={},n={}){let i=ae(n,this.requestTimeoutMs),o=[],r,a=[];try{for await(let s of this.queryPages(e,{firstPageSize:n.firstPageSize,pageSize:n.pageSize,signal:i.signal,pageTimeoutMs:null,onProgress:n.onProgress})){if(!s.ok)return s;let c=s.value;o.push(...c.results),r=c,a.push(...s.diagnostics)}if(i.signal.aborted)throw J(i.signal);return I({results:o,meta:{...r?.meta??{},totalCount:r?.meta?.totalCount??o.length,hasMore:r?!r.complete:!1,...r?.snapshot?{snapshot:r.snapshot}:{}}},a)}catch(s){if(s instanceof b)return O(s.problem);throw s}finally{i.dispose()}}async listViews(e){let n=await this.envelopeOperation("list_views",{},Y,e);return E(n,i=>({views:i.views,meta:{totalCount:i.meta.total_count}}))}async executeView(e,n){let i=await this.envelopeOperation("execute_view",e,Y,n);return E(i,Ia)}readViewSource(e,n){return this.envelopeOperation("read_view_source",e,Y,n)}createViewSource(e,n){return this.envelopeOperation("create_view_source",e,z,n)}updateViewSource(e,n){return this.envelopeOperation("update_view_source",bn(e),z,n)}deleteViewSource(e,n){return this.envelopeOperation("delete_view_source",bn(e),z,n)}async create(e,n){let i=await this.envelopeOperation("create",Sa(e),z,n);return E(i,Tt)}async update(e,n){let i=await this.envelopeOperation("update",Ra(e),z,n);return E(i,Tt)}async delete(e,n){let i=await this.envelopeOperation("delete",Wi(e),z,n);return E(i,no)}async preflightDelete(e,n){let i=await this.envelopeOperation("delete",{...Wi(e),check_backlinks:!0,dry_run:!0},z,n);return E(i,Oa)}async rename(e,n){let i=await this.envelopeOperation("rename",Yi(e),z,n);return E(i,Ta)}async preflightRename(e,n){let i=await this.envelopeOperation("rename",{...Yi(e),dry_run:!0},z,n);return E(i,ka)}validate(e={},n){return this.envelopeOperation("validate",e,Y,n)}readType(e,n){return this.envelopeOperation("read_type",e,re,n)}createType(e,n){return this.envelopeOperation("create_type",e,re,n)}updateType(e,n){return this.envelopeOperation("update_type",bn(e),re,n)}async assessTypePack(e,n){let i=await this.envelopeOperation("assess_type_pack",eo(e),re,n);return E(i,Cn)}async applyTypePack(e,n){let i=await this.envelopeOperation("apply_type_pack",Aa(e),re,n);return E(i,xa)}async assessCollectionSetup(e,n){let i=await this.envelopeOperation("assess_collection_setup",to(e),re,n);return E(i,Xi)}async applyCollectionSetup(e,n){let i=await this.envelopeOperation("apply_collection_setup",Pa(e),re,n);return E(i,o=>({assessment:Xi(o.assessment),receipt:Ea(o.receipt)}))}async listTimers(e,n){let i=await this.rawOperation("list_timers",{namespace:e},Y,n);return E(i,o=>({namespace:o.namespace,timers:o.timers.map(vn)}))}async putTimer(e,n){let i=await this.rawOperation("put_timer",{namespace:e.namespace,criterion_id:e.criterionId,timer:Ji(e.timer)},z,n);return E(i,vn)}cancelTimer(e,n){return this.rawOperation("cancel_timer",e,z,n)}async reconcileTimers(e,n){let i=await this.rawOperation("reconcile_timers",{namespace:e.namespace,criterion_id:e.criterionId,timers:e.timers.map(Ji)},z,n);return E(i,o=>({namespace:o.namespace,timers:o.timers.map(vn),cancelledIds:o.cancelled_ids}))}async*watch(e={}){let n=e.cursor,i=Math.max(100,e.pollIntervalMs??1e3),o=Gi(e.retry),r=0,a=!1;for(e.onStatus?.({state:"connecting",...n===void 0?{}:{cursor:n}});!e.signal?.aborted;){let s=await this.changes(n===void 0?{}:{after:n,limit:200},{signal:e.signal,timeoutMs:e.timeoutMs});if(!s.ok){let p=s.problem;if(e.signal?.aborted)return;if(!o||p.recovery!=="retry"){yield s;return}if(a=!1,r+=1,o.maxAttempts!==void 0&&r>o.maxAttempts){yield s;return}let u=Math.min(o.maxDelayMs,Math.round(o.initialDelayMs*o.multiplier**(r-1)));e.onStatus?.({state:"reconnecting",...n===void 0?{}:{cursor:n},attempt:r,retryInMs:u,problem:p});try{await ee(u,e.signal)}catch{if(!e.signal?.aborted)throw l("operation_failed","Watch retry delay failed unexpectedly.")}continue}let c=s.value;if(n===void 0){n=c.cursor;continue}if(c.reset){let p=k("change_cursor_reset","The collection change cursor expired. Refresh collection state before subscribing again.");e.onStatus?.({state:"reset_required",cursor:n,problem:p}),yield O(p);return}let d=r>0;r=0,(!a||d)&&e.onStatus?.({state:"connected",cursor:n,recovered:d}),a=!0;for(let p of c.events)yield I(p);if(n=c.cursor,!c.hasMore)try{await ee(i,e.signal)}catch{if(!e.signal?.aborted)throw l("operation_failed","Watch polling delay failed unexpectedly.")}}}rawOperation(e,n,i,o){return x(()=>this.transport.operation(e,n,o),i)}async envelopeOperation(e,n,i,o){let r=await x(()=>this.transport.operation(e,n,o),i);if(!r.ok)return r;let a=r.value;return a.valid?I(a.result,a.diagnostics):O(Se(a))}};function E(t,e){return t.ok?I(e(t.value),t.diagnostics):t}function Ca(t){return{path:t.path,...t.contract?{contract:t.contract}:{},...t.includeDocument===void 0?{}:{include_document:t.includeDocument}}}function wa(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.snapshot?{snapshot:t.snapshot}:{},...t.includeBody===void 0?{}:{include_body:t.includeBody},...t.frontmatterMode?{frontmatter_mode:t.frontmatterMode}:{},...t.contract?{contract:t.contract}:{}}}function Sa(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 Ra(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 Wi(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 Yi(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 bn(t){let{ifRevision:e,...n}=t;return{...n,...e?{if_revision:e}:{}}}function eo(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(io)}:{}}}function Aa(t){return{...eo(t),expected_assessment_digest:t.expectedAssessmentDigest,...t.allowDowngrade===void 0?{}:{allow_downgrade:t.allowDowngrade}}}function to(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(io)}:{},...t.typePackAdoptions?{type_pack_adoptions:t.typePackAdoptions}:{}}}function Pa(t){return{...to(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 no(t){return{path:t.path,deleted:t.deleted,...t.broken_links?{brokenLinks:t.broken_links}:{}}}function Oa(t){return{...no(t),deleted:!1,dryRun:!0,wouldDelete:!0}}function Ta(t){let{references_updated:e,...n}=t;return{...Tt(n),from:t.from,to:t.to,...e?{referencesUpdated:e}:{}}}function ka(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 Ji(t){return{id:t.id,fire_at:t.fireAt,...t.data===void 0?{}:{data:t.data}}}function vn(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 io(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 oo(t){return{id:t.id,version:t.version,digest:t.digest,type:t.type,implementationDigest:t.implementation_digest}}function ro(t){let{effective_frontmatter:e,contract:n,...i}=t;return{...i,...e===void 0?{}:{effectiveFrontmatter:e},...n?{contract:oo(n)}:{}}}function Tt(t){let{effective_frontmatter:e,contract:n,...i}=t;return{...i,effectiveFrontmatter:e,...n?{contract:oo(n)}:{}}}function Ia(t){return{results:t.results.map(e=>{let n=ro(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,view:t.meta.view,...t.meta.context?{context:t.meta.context}:{},...t.meta.groups?{groups:t.meta.groups}:{}}}}function Qi(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 kt(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 Ma(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 Cn(t){return{status:t.status,applicable:t.applicable,assessmentDigest:t.assessment_digest,...t.current?{current:kt(t.current)}:{},desired:kt(t.desired),resources:t.resources.map(Qi),lock:t.lock,contractSetups:{choices:t.contract_setups.choices.map(Ma),resources:t.contract_setups.resources.map(Qi)}}}function xa(t){return{...Cn(t),receipt:kt(t.receipt),cleanupDeferred:t.cleanup_deferred}}function Xi(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,baselineDiagnosticCount:t.baseline_diagnostic_count,finalDiagnosticCount:t.final_diagnostic_count,resolvedDiagnosticCount:t.resolved_diagnostic_count,introducedDiagnosticCount:t.introduced_diagnostic_count,baselineDiagnosticDigest:t.baseline_diagnostic_digest,configuration:t.configuration,typePacks:t.type_packs.map(Cn),finalResourceRevisions:t.final_resource_revisions,assessmentDigest:t.assessment_digest}}function Ea(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(kt),cleanupDeferred:t.cleanup_deferred}}function Da(t){return{cursor:t.cursor,type:t.type,occurredAt:t.occurred_at,payload:t.payload}}function qa(t){return{events:t.events.map(Da),cursor:t.cursor,hasMore:t.has_more,reset:t.reset}}function Fa(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 za(t,e){return typeof t=="number"&&Number.isFinite(t)?Math.max(0,Math.floor(t)):e}function Zi(t,e){return typeof t=="number"&&Number.isFinite(t)&&t>0?Math.floor(t):e}var It=class{constructor(e){this.context=e}context;async registerNotifications(e){return U(e,this.context.requestTimeoutMs,n=>this.registerNotificationsWithinBudget(e,n.signal))}async registerNotificationsWithinBudget(e,n){let i=await this.context.authorizedToken(n);if(!i)throw l("not_authorized","Connect this application before enabling notifications.");let r=(await this.context.register(n)).notifications?.criteria.map(y=>y.id)??[],a=[...new Set(e.criteria??r)],s=a.find(y=>!r.includes(y));if(s)throw l("notification_criterion_not_declared",`The application manifest does not declare notification criterion ${s}.`);if(a.length===0)throw l("notifications_not_declared","This application manifest does not declare any notification criteria.");let c=await Z(`${this.context.serverUrl}/v1/notifications/vapid-public-key`,{signal:n},"notifications_unavailable","Push notifications are unavailable."),d=await A(c,"invalid_operation_response","Connect returned an invalid notification key response.");if(!c.ok)throw T(d,"notifications_unavailable","Push notifications are unavailable.",c.status);let p=await e.serviceWorker.pushManager.getSubscription();p||(p=await e.serviceWorker.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:ki(d.public_key)}));let u=p.toJSON();if(!u.endpoint||!u.keys?.p256dh||!u.keys.auth)throw l("invalid_push_subscription","The browser returned an incomplete push subscription.");let f=M(this.context.storage.getItem(this.context.notificationKey())),h=e.installationId??f?.installationId??V(24),_=await Z(`${this.context.serverUrl}/v1/notifications/channels`,{method:"POST",headers:{authorization:`Bearer ${i.accessToken}`,"content-type":"application/json"},body:JSON.stringify({installation_id:h,criteria:a,subscription:{endpoint:u.endpoint,expirationTime:u.expirationTime??null,keys:u.keys}}),signal:n},"notification_registration_failed","Could not register push notifications."),m=await A(_,"invalid_operation_response","Connect returned an invalid notification registration response.");if(!_.ok)throw T(m,"notification_registration_failed","Could not register push notifications.",_.status);f?.channelId&&f.channelId!==m.channel_id&&fetch(`${this.context.serverUrl}/v1/notifications/channels/${f.channelId}`,{method:"DELETE",headers:{authorization:`Bearer ${i.accessToken}`},signal:n}).catch(()=>{});let w={channelId:m.channel_id,installationId:h,criteria:a};return this.context.storage.setItem(this.context.notificationKey(),JSON.stringify(w)),w}async registerNativeNotifications(e){return U(e,this.context.requestTimeoutMs,n=>this.registerNativeNotificationsWithinBudget(e,n.signal))}async registerNativeNotificationsWithinBudget(e,n){let i=await this.context.authorizedToken(n);if(!i)throw l("not_authorized","Connect this application before enabling notifications.");let o=await this.context.register(n);if(o.notifications?.native_delivery?.mode!=="managed_fcm")throw l("managed_fcm_not_declared","This application does not declare Connect-managed native notifications.");let r=o.notifications.criteria.map(_=>_.id),a=[...new Set(e.criteria??r)],s=a.find(_=>!r.includes(_));if(s)throw l("notification_criterion_not_declared",`The application manifest does not declare notification criterion ${s}.`);if(a.length===0)throw l("notifications_not_declared","This application manifest does not declare any notification criteria.");let c=this.context.notificationKey("fcm"),d=M(this.context.storage.getItem(c)),p=e.installationId??d?.installationId??V(24),u=await Z(`${this.context.serverUrl}/v1/notifications/channels`,{method:"POST",headers:{authorization:`Bearer ${i.accessToken}`,"content-type":"application/json"},body:JSON.stringify({installation_id:p,criteria:a,transport:"fcm",token:e.token}),signal:n},"notification_registration_failed","Could not register native notifications."),f=await A(u,"invalid_operation_response","Connect returned an invalid native notification response.");if(!u.ok)throw T(f,"notification_registration_failed","Could not register native notifications.",u.status);d?.channelId&&d.channelId!==f.channel_id&&this.deleteNotificationChannel(d.channelId,i.accessToken,n).catch(()=>{});let h={channelId:f.channel_id,installationId:p,transport:"fcm",criteria:a};return this.context.storage.setItem(c,JSON.stringify(h)),h}async unregisterNativeNotifications(e={}){return U(e,this.context.requestTimeoutMs,n=>this.unregisterNativeNotificationsWithinBudget(n.signal))}async unregisterNativeNotificationsWithinBudget(e){let n=this.context.notificationKey("fcm"),i=M(this.context.storage.getItem(n)),o=await this.context.authorizedToken(e);if(i?.channelId&&!o)throw l("not_authorized","Reconnect this application before disabling native notifications.");i?.channelId&&o&&await this.deleteNotificationChannel(i.channelId,o.accessToken,e),this.context.storage.removeItem(n)}async unregisterNotifications(e,n={}){return U(n,this.context.requestTimeoutMs,i=>this.unregisterNotificationsWithinBudget(e,i.signal))}async unregisterNotificationsWithinBudget(e,n){let i=M(this.context.storage.getItem(this.context.notificationKey())),o=await this.context.authorizedToken(n);if(i?.channelId&&!o)throw l("not_authorized","Reconnect this application before disabling push notifications.");if(i?.channelId&&o){let a=await Z(`${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(!a.ok&&a.status!==404){let s=await A(a,"invalid_operation_response","Connect returned an invalid notification response.");throw T(s,"notification_unregistration_failed","Could not unregister push notifications.",a.status)}}this.context.storage.removeItem(this.context.notificationKey()),await(await e?.pushManager.getSubscription())?.unsubscribe()}async deleteNotificationChannel(e,n,i){let o=await Z(`${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 A(o,"invalid_operation_response","Connect returned an invalid notification response.");throw T(r,"notification_unregistration_failed","Could not unregister push notifications.",o.status)}}};async function Mt(t,e,n,i,o,r){if(!t.authority)throw l("not_remote_authority","This authorization has no remote authority endpoint.");let a=n===""||n.startsWith("?")?n:`/${n}`,s=`${t.authority.filesUrl}${a}`,c=i===void 0?void 0:JSON.stringify(i),d=await r(t,e,s,c,t.authority.accessToken);return fetch(s,{method:e,redirect:"error",headers:{authorization:`Bearer ${t.authority.accessToken}`,...c===void 0?{}:{"content-type":"application/json"},...d},...c===void 0?{}:{body:c},...o?{signal:o}:{}})}async function ao(t,e,n,i,o,r,a){let s=t,c=await Mt(s,e,n,i,o,a);if(c.status===401&&s.refreshToken){if(s=await r(),!s.authority||!s.fileCapability)throw l("authority_authorization_changed","Reconnect this collection before accessing its files.");c=await Mt(s,e,n,i,o,a)}let d=await A(c,"invalid_operation_response","The hosted authority returned an invalid file response.");if(!c.ok)throw T(d,"operation_failed","Collection file request failed.",c.status);return d}async function so(t,e,n,i,o,r){let a=t,s=await Mt(a,"GET",e,void 0,i,r);if(s.status===401&&a.refreshToken){if(a=await o(),!a.authority||!a.fileCapability)throw l("authority_authorization_changed","Reconnect this collection before accessing its files.");s=await Mt(a,"GET",e,void 0,i,r)}if(!s.ok){let d=await A(s,"invalid_operation_response","The hosted authority returned an invalid file range error response.");throw T(d,"operation_failed","Collection file range request failed.",s.status)}let c=s.headers.get("content-length");if(c===null||!/^(0|[1-9][0-9]*)$/u.test(c)||Number(c)!==n)throw await s.body?.cancel().catch(()=>{}),l("invalid_operation_response","The hosted file response declared an unexpected byte length.");if(!s.body)throw l("invalid_operation_response","The hosted file response did not contain a byte stream.");return s.body}var Ua="mdbase-connect file chunk key v1",xt=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,te=class extends Error{constructor(n,i){super(i);this.code=n;this.name="FileTransferCryptoError"}code},Ue=class t{constructor(e,n){this.binding=e;this.key=n}binding;key;static async open(e,n,i){co(i);let o=await e.get(n);if(!o||o.agreementPublicKey!==i.encryption.application_agreement_public_key)throw new R("missing_grant_key","The encrypted grant key is unavailable or does not match the file transfer grant.");let r=await Ze(o.agreementPrivateKey,i.encryption.connector_agreement_public_key);return t.fromSharedSecret(r,i)}static async fromSharedSecret(e,n){co(n);let i=await wn(e,n);return new t(n,i)}async encryptChunk(e,n,i){if(this.validateHeader(n),i.byteLength!==n.plaintext_length)throw new te("plaintext_length_mismatch","File chunk plaintext length does not match its authenticated header.");let o=dt(e,n),r=await crypto.subtle.encrypt({name:"AES-GCM",iv:lo(n.chunk_index),additionalData:Et(o),tagLength:128},this.key,Et(i));return Bn({kind:e,header:n,payload:new Uint8Array(r)})}async decryptChunk(e){let n=ut(e);this.validateHeader(n.header);let i=dt(n.kind,n.header);try{let o=await crypto.subtle.decrypt({name:"AES-GCM",iv:lo(n.header.chunk_index),additionalData:Et(i),tagLength:128},this.key,Et(n.payload));return new Uint8Array(o)}catch{throw new te("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 te("header_binding_mismatch","The file frame does not match its transfer encryption binding.")}};async function wn(t,e){let n=new TextEncoder().encode(Na(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(Ua)},o,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}function co(t){if(X(t.encryption),!xt.test(t.grantId)||!xt.test(t.applicationId)||!xt.test(t.authorityId)||!xt.test(t.transferId)||t.direction!=="upload"&&t.direction!=="download")throw new te("invalid_binding","The file transfer encryption binding is invalid.")}function Na(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 lo(t){if(!Number.isSafeInteger(t)||t<0)throw new te("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 Et(t){return Uint8Array.from(t).buffer}var qt=8,Sn=10;function Ft(t){return t instanceof b&&t.code==="connector_busy"}async function uo(t){if(!Ft(t.error)||t.completedRetries>=qt)return{retried:!1};try{await zt(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 Ne(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 zt(t,e){return fo(ho(50,800,t),e)}function po(t,e){return fo(ho(100,1e3,t-1),e)}async function fo(t,e){try{await ee(t,e)}catch(n){throw e?.aborted?e.reason instanceof b?e.reason:l("operation_cancelled","The operation was cancelled while waiting for connector capacity.",{operationOutcome:"not_sent",cause:n}):n}}function ho(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 Nt=class{constructor(e){this.options=e}options;async control(e,n,i,o,r){return this.controlAttempt(e,n,i,o,r,!1,0)}async controlAttempt(e,n,i,o,r,a,s){Le(e);let c=Va(n,i,o),d=await this.encryptControl(e,c),p,u=await this.options.shouldAttemptDirect(e);if(u){try{p=await fetch(`${this.options.loopbackUrl}/v1/files/control`,ce({method:"POST",headers:{"content-type":"application/mdbase-connect+json"},body:JSON.stringify(d),signal:r}))}catch(f){if(r?.aborted)throw f;this.options.onDirectUnavailable()}if(p&&(!ke(p.status)||await Ne(p)))return p.ok&&this.options.onDirectAvailable(),this.decryptControlResponse(e,n,i,o,r,d,p,a,s);p&&this.options.onDirectUnavailable()}return u&&n==="GET"&&(e=e.expiresAt>Date.now()+3e4?e:await this.options.refreshAuthorization(r),Ut(e),d=await this.encryptControl(e,c)),p=await this.sendRelayControl(e,d,r),await Ba(p,e)&&(e=await this.options.refreshAuthorization(r),Ut(e),d=await this.encryptControl(e,c),p=await this.sendRelayControl(e,d,r)),p.ok&&this.options.onRelayAvailable(),this.decryptControlResponse(e,n,i,o,r,d,p,a,s)}async decryptControlResponse(e,n,i,o,r,a,s,c,d){let p=await A(s,"invalid_operation_response","The collection authority returned an invalid file control response.");if(!s.ok){let h=T(p,"operation_failed","Collection file request failed.",s.status);if(Ft(h)&&d<qt)return await zt(d,r),this.controlAttempt(e,n,i,o,r,c,d+1);if(h.code==="fresh_request_required"&&n==="GET"&&!c)return this.controlAttempt(e,n,i,o,r,!0,d);throw h}let u=p?.envelope;if(!u)throw l("invalid_encrypted_response","The connector omitted its encrypted file response.");let f=await Te(this.options.keyStore,e.keyHandle,Rn(e),a,u);if(!f.ok&&f.problem.code==="fresh_request_required"&&n==="GET"&&!c)return this.controlAttempt(e,n,i,o,r,!0,d);if(!f.ok){let h=Ha(f.problem);if(Ft(h)&&d<qt)return await zt(d,r),this.controlAttempt(e,n,i,o,r,c,d+1);throw h}return f.result}async uploadChunk(e,n,i,o){let a=await this.localFileToken(e,"upload",o),s=await yo(this.options.keyStore,a,e,n,i),c;if(await this.options.shouldAttemptDirect(a)){try{c=await fetch(`${this.options.loopbackUrl}/v1/files/upload`,ce(mo(s,o)))}catch(d){if(o?.aborted)throw d;this.options.onDirectUnavailable()}if(c&&(!ke(c.status)||await Ne(c)))return c.ok&&this.options.onDirectAvailable(),La(c,"Encrypted file chunk upload failed.");c&&this.options.onDirectUnavailable()}if(c=await this.sendRelayUpload(a,s,o),c.status===401&&a.refreshToken&&(a=await this.options.refreshAuthorization(o),Ut(a),s=await yo(this.options.keyStore,a,e,n,i),c=await this.sendRelayUpload(a,s,o)),!c.ok){let d=await A(c,"invalid_operation_response","The collection authority returned an invalid file upload response.");throw T(d,"operation_failed","Encrypted file chunk upload failed.",c.status)}this.options.onRelayAvailable()}async downloadChunk(e,n,i){let o=await this.localFileToken(e,"download",i),r;if(await this.options.shouldAttemptDirect(o)){try{r=await fetch(`${this.options.loopbackUrl}/v1/files/download/${encodeURIComponent(o.grantId)}/${encodeURIComponent(e.transfer_id)}/${n}`,ce({method:"GET",signal:i}))}catch(a){if(i?.aborted)throw a;this.options.onDirectUnavailable()}if(r&&(!ke(r.status)||await Ne(r)))return r.ok&&this.options.onDirectAvailable(),this.decryptDownloadResponse(o,e,n,r);r&&this.options.onDirectUnavailable()}return r=await this.sendRelayDownload(o,e,n,i),r.status===401&&o.refreshToken&&(o=await this.options.refreshAuthorization(i),Ut(o),r=await this.sendRelayDownload(o,e,n,i)),r.ok&&this.options.onRelayAvailable(),this.decryptDownloadResponse(o,e,n,r)}async decryptDownloadResponse(e,n,i,o){if(!o.ok){let s=await A(o,"invalid_operation_response","The collection authority returned an invalid file download response.");throw T(s,"operation_failed","Encrypted file chunk download failed.",o.status)}if(o.headers.get("content-type")?.split(";",1)[0]!=="application/mdbase-connect-file")throw l("invalid_operation_response","The connector returned an invalid file response media type.");let r=new Uint8Array(await o.arrayBuffer()),a;try{Ka(n,i,r),a=await(await _o(this.options.keyStore,e,n)).decryptChunk(r)}catch(s){throw s instanceof b?s:l("invalid_operation_response","The connector returned an invalid encrypted file frame.",{cause:s})}if(a.byteLength!==An(n,i))throw l("invalid_operation_response","The connector returned a truncated file chunk.");return a}encryptControl(e,n){return Le(e),Q(this.options.keyStore,e.keyHandle,Rn(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`,{...mo(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);if(!o||o.authority||!o.fileCapability||!o.encryption||!o.grantId||!o.keyHandle||e.direction!==n||e.protection!=="grant_aead_v1")throw l("not_authorized","This connection cannot use encrypted local file delivery.");return Lt(e),o}};function Ut(t){if(t.authority||!t.fileCapability)throw l("not_authorized","This connection cannot use encrypted local file delivery.");Le(t)}async function yo(t,e,n,i,o){let r=ja(e,n,i,o.byteLength);return(await _o(t,e,n)).encryptChunk("upload_chunk",r,o)}function mo(t,e){return{method:"POST",headers:{"content-type":"application/mdbase-connect-file"},body:Uint8Array.from(t).buffer,signal:e}}async function La(t,e){if(t.ok)return;let n=await A(t,"invalid_operation_response","The collection authority returned an invalid file transfer response.");throw T(n,"operation_failed",e,t.status)}async function Ba(t,e){return e.refreshToken?t.status===401?!0:t.status!==409?!1:(await A(t.clone(),"invalid_operation_response","The collection authority returned an invalid file response.").catch(()=>null))?.error?.code==="encryption_binding_stale":!1}function Le(t){if(!t.encryption||!t.grantId||!t.keyHandle)throw l("missing_grant_key","Reconnect this application to restore encrypted file access.")}function Rn(t){return Le(t),{grantId:t.grantId,applicationId:t.clientId,encryption:t.encryption}}function _o(t,e,n){return Le(e),Ue.open(t,e.keyHandle,{...Rn(e),authorityId:e.encryption.connector_id,transferId:n.transfer_id,direction:n.direction})}function ja(t,e,n,i){Le(t);let o=Lt(e),r=An(e,n);if(i!==r)throw l("invalid_request","The file chunk has the wrong byte length.");return{protocol_version:1,protection:"grant_aead_v1",grant_id: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 Ka(t,e,n){let i=ut(n),o=An(t,e),r=Lt(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 l("invalid_operation_response","The connector returned a file frame for a different chunk.")}function Ha(t){return F(t.code==="unknown"?t.server_code:t.code,t.message,{details:t.details,operationOutcome:t.operation_outcome??"rejected",traceId:t.trace_id})}function Va(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 go("get_file_transfer_status",i[1]);if(t==="DELETE"&&i.length===2&&i[0]==="transfers")return go("abort_file_transfer",i[1]);if(t==="POST"&&$a(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 l("invalid_request","The file control request path is invalid.")}function go(t,e){return{protocol_version:1,type:t,transfer_id:decodeURIComponent(e)}}function Lt(t){if(t.strategy.kind!=="framed_chunks"||!Number.isSafeInteger(t.strategy.chunk_size)||t.strategy.chunk_size<=0)throw l("invalid_operation_response","The connector returned an invalid framed transfer strategy.");return t.strategy.chunk_size}function An(t,e){let n=Lt(t);if(!Number.isSafeInteger(e)||e<0||!Number.isSafeInteger(t.total_size)||t.total_size<0)throw l("invalid_request","The file chunk index is invalid.");let i=e*n;if(!Number.isSafeInteger(i)||i>=t.total_size)throw l("invalid_request","The file chunk index is outside the transfer.");return Math.min(n,t.total_size-i)}function $a(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var Bt=class{constructor(e){this.options=e;this.local=new Nt(e)}options;local;async control(e,n="",i,o){let r=await this.requireFileToken(o);return r.authority?ao(r,e,n,i,o,this.options.refreshAuthorization,this.options.authorityProofHeaders):this.local.control(r,e,n,i,o)}uploadChunk(e,n,i,o){return this.local.uploadChunk(e,n,i,o)}downloadChunk(e,n,i){return this.local.downloadChunk(e,n,i)}async downloadHostedPart(e,n,i,o){let r=await this.requireFileToken(o);if(!r.authority)throw l("not_remote_authority","Hosted file delivery requires a remote authority endpoint.");return so(r,`downloads/${encodeURIComponent(e.transfer_id)}/parts/${n}`,i,o,this.options.refreshAuthorization,this.options.authorityProofHeaders)}async requireFileToken(e){let n=await this.options.authorizedToken(e);if(!n?.fileCapability)throw l("not_authorized","This connection has no file capability.");return n}};async function Be(t,e,n,i,o,r){if(!e.authority?.proofPublicKey)return{};if(!e.keyHandle)throw l("missing_grant_key","Reconnect this application to restore remote authority request signing.");try{let a=new URL(i);return await Ct(t,e.keyHandle,e.authority.proofPublicKey,{method:n,target:`${a.pathname}${a.search}`,body:o,credential:r})}catch(a){throw a instanceof R?F(a.code,a.message):a}}var jt=class{constructor(e,n){this.storage=e;this.baseKey=n}storage;baseKey;list(e){if(!e)return[];let n=M(this.storage.getItem(this.baseKey));if(bo(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=>M(this.storage.getItem(o))).filter(o=>bo(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??oe(e.operation,e.request?.input??(e.operation==="sync"?{action:"mutate"}:{}))??(e.operation==="sync"?"sync:mutate":e.operation)}store(e){this.storage.setItem(this.key(e.requestId),JSON.stringify(e))}take(e){let n=this.key(e),i=M(this.storage.getItem(n));return this.storage.removeItem(n),i}key(e){return`${this.baseKey}:${encodeURIComponent(e)}`}};function bo(t){return!!(t&&typeof t.collectionId=="string"&&typeof t.requestId=="string"&&t.requestId.length>0&&jn(t.operation)&&typeof t.inputFingerprint=="string"&&Number.isFinite(t.createdAt)&&t.createdAt>0&&(t.envelope||t.request)&&(t.operation==="sync"||oe(t.operation,t.request?.input??{})!==null))}function vo({stored:t,collectionId:e,relayEncryption:n,invalidate:i,directCapable:o}){let r=M(t),a=s=>(i(typeof s=="string"?s:void 0),null);if(!r)return t&&a(),null;if(r.version!==1||typeof r.accessToken!="string"||r.accessToken.length===0||typeof r.clientId!="string"||r.clientId.length===0||r.collectionId!==e||typeof r.collectionName!="string"||r.collectionName.length===0||!Array.isArray(r.operations)||r.operations.some(s=>typeof s!="string")||typeof r.expiresAt!="number"||!Number.isFinite(r.expiresAt)||r.refreshToken!==void 0&&(typeof r.refreshToken!="string"||r.refreshToken.length===0)||r.refreshExpiresAt!==void 0&&(typeof r.refreshExpiresAt!="number"||!Number.isFinite(r.refreshExpiresAt))||!Rt(r.scope)||r.fileCapability&&!St(r.fileCapability)||r.authority&&!Mi(r.authority,r.collectionId))return a(r.keyHandle);if(n==="required"){if(r.authority){if(!r.keyHandle||!r.authority.proofPublicKey)return a(r.keyHandle)}else if(!r.grantId||!r.keyHandle||!xi(r.encryption,r.collectionId))return a(r.keyHandle)}return r.expiresAt<=Date.now()&&(!r.refreshToken||(r.refreshExpiresAt??0)<=Date.now())?o(r)?r:(i(r.keyHandle),null):r}async function Pn(t,e,n,i,o,r){if(!e.authority)throw l("not_remote_authority","This authorization has no remote authority endpoint.");let a=`${e.authority.syncUrl}/${i}`,s=o===void 0?void 0:JSON.stringify(o),c=await Be(t,e,n,a,s,e.authority.accessToken);return fetch(a,{method:n,headers:{authorization:`Bearer ${e.authority.accessToken}`,...o===void 0?{}:{"content-type":"application/json"},...c},...s===void 0?{}:{body:s},signal:r})}async function Co(t,e,n,i){if(!e.encryption||!e.grantId||!e.keyHandle)throw l("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 Q(t,e.keyHandle,{grantId:e.grantId,applicationId:e.clientId,encryption:e.encryption},n,i)}catch(o){throw o instanceof R?F(o.code,o.message):o}}function wo(t,e){return!t||t.authority||!t.encryption||!t.grantId||!t.keyHandle||e==="disabled"?!1:typeof location>"u"||!t.applicationOrigin||t.applicationOrigin===location.origin}async function So(t,e,n){try{let i=await fetch(`${t}/v1/ready`,ce({method:"GET",cache:"no-store",signal:n})),o=await A(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}catch{return!1}}var Kt=class{serverUrl;storage;keyStore;directAccessMode;loopbackUrl;collectionId;internals;onChange;timeouts;pendingMutationStore;files;refreshPromise=null;directStatus;currentRoute="relay";directFailures=0;directRetryAt=0;constructor(e){this.serverUrl=e.serverUrl,this.storage=e.storage,this.keyStore=e.keyStore,this.directAccessMode=e.directAccessMode,this.loopbackUrl=e.loopbackUrl,this.collectionId=e.collectionId,this.internals=e.internals,this.onChange=e.onChange,this.timeouts=e.timeouts,this.pendingMutationStore=new jt(this.storage,this.internals.pendingMutationKey(this.collectionId)),this.files=new Bt({keyStore:this.keyStore,serverUrl:this.serverUrl,loopbackUrl:this.loopbackUrl,authorizedToken:n=>this.authorizedToken({signal:n,timeoutMs:null}),refreshAuthorization:n=>this.refreshAuthorization(n),shouldAttemptDirect:n=>this.shouldAttemptDirect(n),onDirectAvailable:()=>{this.markDirectAvailable(),this.setRoute("direct")},onDirectUnavailable:()=>this.markDirectUnavailable(),onRelayAvailable:()=>this.setRoute("relay"),authorityProofHeaders:(n,i,o,r,a)=>Be(this.keyStore,n,i,o,r,a)}),this.directStatus=this.directAccessMode==="disabled"?"disabled":"unavailable"}get directAccess(){return this.currentToken()?.authority?"disabled":this.directStatus}get route(){return this.currentToken()?.authority?"remote":this.currentRoute}notifyStorageChanged(){this.emitConnection()}async checkDirectAccess(e={}){return U(e,this.timeouts.watchStartMs,n=>this.checkDirectAccessWithinBudget(n.signal))}async checkDirectAccessWithinBudget(e){let n=this.currentToken();if(!this.directEligible(n))return this.setDirectStatus("disabled");let i=await et();return i==="denied"?this.setDirectStatus("denied"):(i==="prompt"||i===null)&&this.storage.getItem(this.internals.directPreferenceKey())!=="enabled"?this.setDirectStatus("permission_required"):this.probeDirectAccess(e)}async requestDirectAccess(e={}){return U(e,this.timeouts.watchStartMs,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=>({requestId:e.requestId,operation:this.pendingMutationStore.identifier(e),fingerprint:e.inputFingerprint,status:"outcome_unknown",createdAt:new Date(e.createdAt).toISOString()}))}pendingMutation(e){let n=this.storedPendingMutation(e);return n?{requestId:n.requestId,operation:this.pendingMutationStore.identifier(n),fingerprint:n.inputFingerprint,status:"outcome_unknown",createdAt:new Date(n.createdAt).toISOString()}:null}async recoverPendingMutation(e,n){let i=this.storedPendingMutation(e);if(!i)throw l("no_pending_mutation","There is no interrupted mutation to resume.");return B(n,this.timeouts.requestMs,o=>this.performOperationWithinBudget(i.operation,i.request?.input??{},{...n,signal:o.signal},i))}async performOperation(e,n,i={}){return B(i,this.timeouts.requestMs,o=>this.performOperationWithinBudget(e,n,{...i,signal:o.signal}))}async performOperationWithinBudget(e,n,i,o,r=!1,a=0,s=!1){me(i.signal);let c=this.currentToken();if(!c)throw l("not_authorized","Connect this application before accessing a collection.");if(!c.operations.includes(e))throw l("insufficient_access",`This connection does not allow ${e}.`,{details:{required_operations:[e],granted_operations:[...c.operations],missing_operations:[e]}});let d=await this.shouldAttemptDirect(c);if(!d&&(c=await this.authorizedToken({signal:i.signal,timeoutMs:null}),!c))throw l("not_authorized","Reconnect this application to continue.");let p=o?.requestId??(Ci(e,n)?crypto.randomUUID():void 0),u;try{u=await this.sendOperation(c,e,n,d,i,p,s)}catch(y){throw wt(y,i.signal,p!==void 0&&this.storedPendingMutation(p)!==null?p:void 0,c.authority?"hosted_provider_unavailable":"relay_unavailable")}let f=u.response,h=f.status===409&&(await A(f.clone(),"invalid_operation_response","The collection authority returned an invalid operation response.").catch(()=>null))?.error?.code==="encryption_binding_stale";if((f.status===401||h)&&c.refreshToken){if(u.pendingMutation&&(u.directDeliveryUncertain||u.encryptedRequest&&u.resumingMutation))throw l("operation_outcome_unknown","The direct operation may have completed, but its encrypted grant changed before the response could be recovered. Refresh before making another change.",{operationOutcome:"unknown",details:{request_id:u.requestId}});u.pendingMutation&&this.clearPendingMutation(u.requestId),c=await this.refreshAuthorization(i.signal),d=await this.shouldAttemptDirect(c);try{u=await this.sendOperation(c,e,n,d,i,p,s)}catch(y){throw wt(y,i.signal,p!==void 0&&this.storedPendingMutation(p)!==null?p:void 0,c.authority?"hosted_provider_unavailable":"relay_unavailable")}f=u.response}let _=y=>uo({error:y,attempt:u,completedRetries:a,signal:i.signal,knownRejectedMutationRetry:s,clearPending:v=>this.clearPendingMutation(v),retry:(v,N)=>this.performOperationWithinBudget(e,n,i,v,r,a+1,N)}),m;try{m=await A(f,"invalid_operation_response","The collection authority returned a response that is not valid JSON.")}catch(y){throw u.pendingMutation?j(u.requestId,y):l("invalid_operation_response","The collection authority returned a response that is not valid JSON.",{cause:y})}if(!f.ok){let y=T(m,"operation_failed","Collection operation failed.",f.status),v=await _(y);if(v.retried)return v.result;if(y.code==="fresh_request_required"&&!u.pendingMutation&&!r)return this.performOperationWithinBudget(e,n,i,void 0,!0);throw u.pendingMutation&&(u.directDeliveryUncertain||u.encryptedRequest&&u.resumingMutation)?j(u.requestId,y):(u.pendingMutation&&!u.directDeliveryUncertain&&this.clearPendingMutation(u.requestId),y.code==="direct_operation_rejected"&&y.status===403&&this.invalidateRejectedAuthorization(c),y)}if(u.encryptedRequest){let y=m?.envelope,v=u.pendingMutationRecord,N=v?.encryption??c.encryption,P=v?.grantId??c.grantId,q=v?.applicationId??c.clientId,S=v?.keyHandle??c.keyHandle;if(!y||!N||!P||!S)throw u.pendingMutation?j(u.requestId,new Error("Encrypted operation response was missing its envelope.")):l("invalid_encrypted_response","The relay did not return an encrypted connector response.");try{let g=await Te(this.keyStore,S,{grantId:P,applicationId:q,encryption:N},u.encryptedRequest,y);if(!g.ok&&g.problem.code==="fresh_request_required"&&!u.pendingMutation&&!r)return this.performOperationWithinBudget(e,n,i,void 0,!0);if(u.pendingMutation&&this.clearPendingMutation(u.requestId),!g.ok)throw F(g.problem.code==="unknown"?g.problem.server_code:g.problem.code,g.problem.message,{details:g.problem.details,operationOutcome:g.problem.operation_outcome??"rejected",traceId:g.problem.trace_id});return g.result}catch(g){throw g instanceof b?g:g instanceof R?u.pendingMutation?j(u.requestId,g):F(g.code,g.message):g}}let w=u.pendingMutationRecord?.request?.protocol_version??L;if(m?.protocol_version!==w||m?.request_id!==u.requestId)throw u.pendingMutation?j(u.requestId,new Error("Operation response protocol or request ID did not match.")):l("invalid_operation_response","The collection authority returned a response for a different protocol request.");if(m.ok===!1){if(!Ve(m.problem))throw u.pendingMutation?j(u.requestId,new Error("Operation rejection did not contain a canonical problem.")):l("invalid_operation_response","The collection authority returned an invalid operation problem.");let y=new b(m.problem),v=await _(y);if(v.retried)return v.result;throw u.pendingMutation&&this.clearPendingMutation(u.requestId),y}if(m.ok!==!0||!("result"in m))throw u.pendingMutation?j(u.requestId,new Error("Successful operation response did not contain a result.")):l("invalid_operation_response","The collection authority returned an incomplete operation response.");return u.pendingMutation&&this.clearPendingMutation(u.requestId),m.result}async performAuthoritySyncRequest(e,n,i,o,r,a={}){return B(a,this.timeouts.syncMs,async s=>{let c=await this.authorizedToken({signal:s.signal,timeoutMs:null});if(!c?.authority||c.collectionId!==e||c.authority.replicaId!==n)throw l("authority_authorization_changed","Reconnect this collection authority before synchronizing.");try{let d=await Pn(this.keyStore,c,i,o,r,s.signal);if(d.status===401&&c.refreshToken){if(c=await this.refreshAuthorization(s.signal),!c.authority||c.collectionId!==e||c.authority.replicaId!==n)throw l("authority_authorization_changed","Reconnect this collection authority before synchronizing.");d=await Pn(this.keyStore,c,i,o,r,s.signal)}let p=await A(d,"invalid_operation_response","The collection authority returned an invalid synchronization response.");if(!d.ok)throw T(p,"sync_failed","Collection synchronization failed.",d.status);return p}catch(d){let p=i==="POST"&&o==="mutations"&&r&&typeof r=="object"&&typeof r.mutation_id=="string"?r.mutation_id:void 0;throw wt(d,s.signal,p,"hosted_provider_unavailable")}})}async sendOperation(e,n,i,o,r={},a,s=!1){let c=i??{},d,p=!1,u=!1,f=a??crypto.randomUUID(),h=null,_;if(a!==void 0){if(h=this.storedPendingMutation(a),_=h?.inputFingerprint??await Oi(n,i),h){if(h.collectionId!==e.collectionId||h.operation!==n||h.inputFingerprint!==_)throw l("pending_mutation_unresolved","A previous write still has an unknown outcome. Retry that exact write before making another change.");f=h.requestId,u=!s}p=!0}let m=h?.mutation??oe(n,i);if(h?.envelope&&(e.authority||!e.encryption))throw l("pending_mutation_unresolved","The pending write requires its encrypted relay authority. Reconnect that authority before recovery.");if(h?.request&&e.encryption&&!e.authority)throw l("pending_mutation_unresolved","The pending write belongs to a different authority transport. Reconnect that authority before recovery.");if(e.encryption&&!e.authority){if(!e.grantId||!e.keyHandle)throw l("missing_grant_key","Reconnect this application to restore encrypted access.");try{if(p)if(h){if(!h.envelope)throw l("pending_mutation_unresolved","The pending write belongs to a different transport. Reconnect before retrying it.");d=h.envelope}else d=await Q(this.keyStore,e.keyHandle,{grantId:e.grantId,applicationId:e.clientId,encryption:e.encryption},n,i,f),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:m,inputFingerprint:_,requestId:f,envelope:d,createdAt:Date.now()});else d=await Q(this.keyStore,e.keyHandle,{grantId:e.grantId,applicationId:e.clientId,encryption:e.encryption},n,i)}catch(P){throw P instanceof R?F(P.code,P.message):P}f=d.request_id,c=d}else{let P=h?.request??{protocol_version:L,request_id:f,input:c};c=P,p&&!h&&this.pendingMutationStore.store({collectionId:e.collectionId,...e.grantId?{grantId:e.grantId}:{},operation:n,mutation:m,inputFingerprint:_,requestId:f,request:P,createdAt:Date.now()})}if(o&&d&&!e.authority){let P=!1;try{let g=await fetch(`${this.loopbackUrl}/v1/operations`,ce({method:"POST",headers:{"content-type":"application/mdbase-connect+json"},body:JSON.stringify(d),signal:r.signal}));if(!ke(g.status)||await Ne(g))return g.ok&&(this.markDirectAvailable(),this.setRoute("direct")),{response:g,requestId:f,encryptedRequest:d,pendingMutation:p,...p?{pendingMutationRecord:h??this.storedPendingMutation(f)??void 0}:{},resumingMutation:u};P=g.status>=500,this.markDirectUnavailable()}catch(g){if(r.signal?.aborted)throw g;P=!0,await et()==="denied"?this.setDirectStatus("denied"):this.markDirectUnavailable()}let q;try{q=e.expiresAt>Date.now()+3e4?e:await this.refreshAuthorization(r.signal)}catch(g){throw p&&(P||u)?j(f,g):g}let S;p||(d=await Co(this.keyStore,q,n,i),f=d.request_id);try{S=await fetch(`${this.serverUrl}/v1/authorities/${encodeURIComponent(q.collectionId)}/operations/${n}`,{method:"POST",headers:{authorization:`Bearer ${q.accessToken}`,"content-type":"application/json"},body:JSON.stringify(d),signal:r.signal})}catch(g){throw p&&(P||u)?j(f,g):g}return S.ok&&this.setRoute("relay"),{response:S,requestId:f,encryptedRequest:d,directDeliveryUncertain:P,pendingMutation:p,...p?{pendingMutationRecord:h??this.storedPendingMutation(f)??void 0}:{},resumingMutation:u}}let w=e.authority?`${e.authority.operationsUrl}/${n}`:`${this.serverUrl}/v1/authorities/${encodeURIComponent(e.collectionId)}/operations/${n}`,y=JSON.stringify(c),v=e.authority?await Be(this.keyStore,e,"POST",w,y,e.authority.accessToken):{},N=await fetch(w,{method:"POST",headers:{authorization:`Bearer ${e.authority?.accessToken??e.accessToken}`,"content-type":"application/json",...v},body:y,signal:r.signal});return N.ok&&this.setRoute(e.authority?"remote":"relay"),{response:N,requestId:f,encryptedRequest:d,pendingMutation:p,...p?{pendingMutationRecord:h??this.storedPendingMutation(f)??void 0}:{},resumingMutation:u}}directCapable(e){return wo(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 et();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){return this.setDirectStatus("checking"),await So(this.loopbackUrl,L,e)?(this.markDirectAvailable(),"available"):await et()==="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=M(this.storage.getItem(this.internals.tokenKey(this.collectionId)));!n||!wi(n,e)||(this.internals.removeToken(this.collectionId,n.keyHandle),this.currentRoute="relay",this.directStatus=this.directAccessMode==="disabled"?"disabled":"unavailable",this.emitConnection())}currentToken(){return vo({stored:this.storage.getItem(this.internals.tokenKey(this.collectionId)),collectionId:this.collectionId,relayEncryption:this.internals.relayEncryption,invalidate:e=>this.internals.removeToken(this.collectionId,e,"invalid_stored_grant"),directCapable:e=>this.directCapable(e)})}async authorizedToken(e={}){let 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 l("relay_authorization_expired","Direct access is still available on this computer, but using the relay requires reconnecting this application.");return this.internals.removeToken(this.collectionId,n.keyHandle),null}return this.refreshAuthorization(e.signal)}refreshAuthorization(e){return this.refreshPromise?this.refreshPromise:(this.refreshPromise=this.performRefresh(e).finally(()=>{this.refreshPromise=null}),this.refreshPromise)}async performRefresh(e){let n=this.currentToken();if(!n?.refreshToken)throw l("not_authorized","Reconnect this application to continue.");if((n.refreshExpiresAt??0)<=Date.now())throw l("relay_authorization_expired","Direct access is still available on this computer, but using the relay requires reconnecting this application.");let i=n.refreshToken,o=`${this.serverUrl}/oauth/token`,r=new URLSearchParams({grant_type:"refresh_token",refresh_token:n.refreshToken,client_id:n.clientId}).toString(),a=n.authority?await Be(this.keyStore,n,"POST",o,r,n.refreshToken):{},s=await fetch(o,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",...a},body:r,signal:e}),c=await A(s,"invalid_token_response","The authorization service returned an invalid token response.");if(!s.ok){let d=this.currentToken();if(d?.refreshToken&&d.refreshToken!==i)return d;throw this.directCapable(n)||this.internals.removeToken(this.collectionId,n.keyHandle),(nt(c)??c?.error?.code)==="invalid_grant"?l("authorization_expired",c?.error_description??c?.error?.message??"Reconnect this application to continue.",{status:s.status}):T(c,"authorization_expired","Reconnect this application to continue.",s.status)}return this.storeTokenResponse(c,n.clientId,n.keyHandle)}storeTokenResponse(e,n,i){if(e.collection_id!==this.collectionId)throw l("collection_mismatch","The refreshed authorization belongs to a different collection.");let o=this.internals.storeTokenResponse(e,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),i=this.currentToken()?.keyHandle;n?.keyHandle&&n.keyHandle!==i&&this.keyStore.delete(n.keyHandle).catch(()=>{})}};var Ga=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]),Wa=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),be=class{state=Wa.slice();block=new Uint8Array(64);words=new Uint32Array(64);blockLength=0;byteLength=0;finished=!1;update(e){if(this.finished)throw new Error("SHA-256 digest is already finalized.");if(this.byteLength+=e.byteLength,!Number.isSafeInteger(this.byteLength))throw new Error("SHA-256 input exceeds the safe browser byte range.");let n=0;if(this.blockLength>0){let i=Math.min(64-this.blockLength,e.byteLength);this.block.set(e.subarray(0,i),this.blockLength),this.blockLength+=i,n+=i,this.blockLength===64&&(this.compress(this.block),this.blockLength=0)}for(;n+64<=e.byteLength;)this.compress(e.subarray(n,n+64)),n+=64;return n<e.byteLength&&(this.block.set(e.subarray(n),0),this.blockLength=e.byteLength-n),this}digestHex(){if(this.finished)throw new Error("SHA-256 digest is already finalized.");this.finished=!0,this.block[this.blockLength]=128,this.block.fill(0,this.blockLength+1),this.blockLength>=56&&(this.compress(this.block),this.block.fill(0));let e=this.byteLength*8,n=Math.floor(e/4294967296),i=e>>>0;return Ro(this.block,56,n),Ro(this.block,60,i),this.compress(this.block),[...this.state].map(o=>o.toString(16).padStart(8,"0")).join("")}compress(e){let n=this.words;for(let u=0;u<16;u+=1){let f=u*4;n[u]=(e[f]<<24|e[f+1]<<16|e[f+2]<<8|e[f+3])>>>0}for(let u=16;u<64;u+=1){let f=n[u-15],h=n[u-2],_=W(f,7)^W(f,18)^f>>>3,m=W(h,17)^W(h,19)^h>>>10;n[u]=n[u-16]+_+n[u-7]+m>>>0}let i=this.state[0],o=this.state[1],r=this.state[2],a=this.state[3],s=this.state[4],c=this.state[5],d=this.state[6],p=this.state[7];for(let u=0;u<64;u+=1){let f=W(s,6)^W(s,11)^W(s,25),h=s&c^~s&d,_=p+f+h+Ga[u]+n[u]>>>0,m=W(i,2)^W(i,13)^W(i,22),w=i&o^i&r^o&r,y=m+w>>>0;p=d,d=c,c=s,s=a+_>>>0,a=r,r=o,o=i,i=_+y>>>0}this.state[0]=this.state[0]+i>>>0,this.state[1]=this.state[1]+o>>>0,this.state[2]=this.state[2]+r>>>0,this.state[3]=this.state[3]+a>>>0,this.state[4]=this.state[4]+s>>>0,this.state[5]=this.state[5]+c>>>0,this.state[6]=this.state[6]+d>>>0,this.state[7]=this.state[7]+p>>>0}};function W(t,e){return t>>>e|t<<32-e}function Ro(t,e,n){t[e]=n>>>24,t[e+1]=n>>>16,t[e+2]=n>>>8,t[e+3]=n}var Ht=class{constructor(e,n){this.signal=n;this.iterator=Ya(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,l("invalid_request","Streamed file bytes ended before the declared size.");if(!(r.value instanceof Uint8Array))throw l("invalid_request","A streamed file chunk was not a Uint8Array.");if(this.maxSourceChunkBytes===null)throw new Error("Stream source was read before upload negotiation completed.");if(r.value.byteLength>this.maxSourceChunkBytes)throw l("invalid_request",`A streamed file chunk exceeded the negotiated ${this.maxSourceChunkBytes}-byte upload part size.`);if(this.remainder=r.value,this.remainderOffset=0,this.remainder.byteLength===0)continue}let o=Math.min(e-i,this.remainder.byteLength-this.remainderOffset);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 l("invalid_request","Streamed file bytes exceed the declared size.");for(;!this.ended;){let e=await this.nextSourceChunk();if(e.done){this.ended=!0;return}if(!(e.value instanceof Uint8Array))throw l("invalid_request","A streamed file chunk was not a Uint8Array.");if(e.value.byteLength>0)throw l("invalid_request","Streamed file bytes exceed the declared size.")}}async close(){this.ended=!0,this.closeIterator()}async nextSourceChunk(){Ao(this.signal);let e=this.iterator.next(),n=this.signal;if(!n)return e;let i=()=>{},o=new Promise((r,a)=>{let s=()=>{this.closeIterator(),a(Po(n))};n.addEventListener("abort",s,{once:!0}),i=()=>n.removeEventListener("abort",s),n.aborted&&s()});try{let r=await Promise.race([e,o]);return Ao(n),r}finally{i()}}closeIterator(){if(!this.iteratorClosing){this.iteratorClosing=!0;try{this.iterator.return?.()?.catch(()=>{})}catch{}}}};function Ya(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 l("invalid_request","Streamed files require a readable byte stream.");return e[Symbol.asyncIterator]()}function Ao(t){if(t?.aborted)throw Po(t)}function Po(t){return l("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:t?.reason})}var Oo=1024*1024,Ja=4,To=8,st=3,On=64*1024*1024,ko=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Io=/^sha256:[0-9a-f]{64}$/u;async function Mo(t,e,n){let i=new be;for(let o=0;o<t.size;o+=Oo){le(e);let r=new Uint8Array(await t.slice(o,o+Oo).arrayBuffer());i.update(r),n(Math.min(t.size,o+r.byteLength))}return t.size===0&&n(0),i.digestHex()}function xo(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 Eo(t){return t instanceof Blob?t.size:t.byteLength}async function Do(t){return t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t}function Tn(t=Ja){if(!Number.isInteger(t)||t<1||t>To)throw l("invalid_request",`File concurrency must be between 1 and ${To}.`);return t}function qo(t){if(!Number.isInteger(t)||t<1||t>1e3)throw l("invalid_request","File page size must be between 1 and 1000.");return t}function kn(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)||!Qa(t))throw l("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(a=>!Number.isSafeInteger(a)||a<0||a>=o))throw l("invalid_operation_response","The authority returned invalid transfer progress.");let r=t.uploaded_parts??[];if(!Array.isArray(r)||r.some((a,s)=>!Number.isSafeInteger(a?.part_number)||a.part_number<1||a.part_number>o||typeof a.etag!="string"||a.etag.length===0||a.etag.length>255||s>0&&r[s-1].part_number>=a.part_number)||(t.strategy.kind==="object_multipart"?r.length!==t.received.length||r.some((a,s)=>a.part_number-1!==t.received[s]):r.length!==0))throw l("invalid_operation_response","The authority returned invalid uploaded part receipts.")}function Fo(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,a)=>r+In(e.total_size,n,a),0)!==t.received_bytes)throw l("invalid_operation_response","The authority returned invalid transfer status.");let o=t.uploaded_parts;if(!Array.isArray(o)||o.some((r,a)=>!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||a>0&&o[a-1].part_number>=r.part_number)||(e.strategy.kind==="object_multipart"?o.length!==t.received.length||o.some((r,a)=>r.part_number-1!==t.received[a]):o.length!==0))throw l("invalid_operation_response","The authority returned invalid uploaded part status.")}function Qa(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 In(t,e,n){return Math.min(e,Math.max(0,t-n*e))}async function Vt(t,e){for(let n=1;n<=Sn;n+=1){le(e);try{return await t()}catch(i){if(e?.aborted||n===Sn||i instanceof b&&!i.retryable)throw i;await po(n,e)}}throw new Error("Unreachable file chunk retry state.")}function zo(t,e,n,i,o,r){let a;try{a=new URL(t.url)}catch{throw l("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||t.method.toUpperCase()!==r||a.protocol!=="https:"&&!(a.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(a.hostname))||a.username||a.password)throw l("invalid_operation_response","The authority returned an invalid prepared file part.")}function Uo(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 No(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 le(t){if(t?.aborted)throw l("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:t.reason})}function ve(t){return t instanceof b?t:typeof DOMException<"u"&&t instanceof DOMException&&t.name==="AbortError"?l("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:t}):l("temporarily_unavailable","The file transfer could not be completed.",{cause:t})}var je=class{constructor(e,n,i,o,r=Ae()){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=ae(e,this.timeouts.fileIndexMs),i=n.signal;try{this.requireAction("list");let o;do{le(i);let r=new URLSearchParams({protocol_version:String(1),...e.folder?{folder:e.folder}:{},...o?{after:o}:{},...e.pageSize?{limit:String(qo(e.pageSize))}:{}}),a;for(;;)try{a=await this.request("GET",`?${r.toString()}`,void 0,i);break}catch(s){let c=ve(s);if(c.code!=="file_index_warming")throw c;e.onIndexing?.(),await ee(500,i)}if(a.protocol_version!==1||a.type!=="files_page"||!Array.isArray(a.files))throw l("invalid_operation_response","The authority returned an invalid file page.");for(let s of a.files)le(i),yield $t(s);o=a.next}while(o)}finally{n.dispose()}}async upload(e,n,i={}){return B(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=xo(n,i.mediaType),r=Tn(i.concurrency),a=await Mo(o,i.signal,s=>{i.onProgress?.({phase:"hashing",transferredBytes:s,totalBytes:o.size})});return this.uploadKnownSource(e,o.size,`sha256:${a}`,(i.mediaType??o.type)||void 0,i,r,async(s,c,d)=>o.slice(c,c+d))}async uploadStream(e,n,i={}){return B(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 l("invalid_request","Streamed file size must be a non-negative safe integer.");if(!Io.test(n.contentDigest))throw l("invalid_request","Streamed files require a lowercase SHA-256 content digest.");let o=new Ht(n.stream,i.signal),r=new be;return this.uploadKnownSource(e,n.size,n.contentDigest,i.mediaType??n.mediaType,i,1,async(a,s,c)=>{let d=await o.read(c);return r.update(d),d},async()=>{if(await o.expectEnd(),`sha256:${r.digestHex()}`!==n.contentDigest)throw l("invalid_request","Streamed file bytes do not match the declared SHA-256 digest.")},()=>o.close(),a=>o.setMaxSourceChunkBytes(a))}async uploadKnownSource(e,n,i,o,r,a,s,c,d,p){let u=r.transferId??crypto.randomUUID();if(!ko.test(u))throw l("invalid_request","File transfer ID must be a UUID.");let f=!1;try{let h=await this.request("POST","uploads",{protocol_version:1,type:"open_file_upload",transfer_id:u,path:e,size:n,content_digest:i,...o?{media_type:o}:{},...r.ifRevision?{if_revision:r.ifRevision}:{}},r.signal);if(kn(h,u,"upload"),h.total_size!==n||h.strategy.kind==="object_ranges")throw l("invalid_operation_response","The authority returned an incompatible upload strategy.");let _=h.strategy.kind==="framed_chunks";if(_&&!this.framed)throw l("invalid_operation_response","Encrypted file chunk delivery is unavailable.");let m=h.strategy.kind==="object_put"?Math.max(1,n):h.strategy.kind==="framed_chunks"?h.strategy.chunk_size:h.strategy.part_size,w=h.strategy.kind==="object_put"?1:Math.ceil(n/m),y=await this.request("GET",`transfers/${encodeURIComponent(u)}`,void 0,r.signal);if(Fo(y,h),y.state!=="open"&&y.state!=="committed")throw l("invalid_operation_response",`The authority cannot resume a ${y.state} file transfer.`);if(p?.(m),!_&&y.received.length===w){let g=await this.tryReplayUploadCommit(u,h.strategy.kind==="object_multipart"?y.uploaded_parts:void 0,r.signal);if(g)return f=!0,$t(g.file)}let v=new Set(y.received),N=new Map(y.uploaded_parts.map(g=>[g.part_number-1,g])),P=[...v].reduce((g,K)=>g+In(n,m,K),0),q=await No(w,a,async g=>{let K=g*m,de=Math.min(m,Math.max(0,n-K)),ue=await s(g,K,de);if(Eo(ue)!==de)throw l("invalid_request","Streamed file bytes ended before the declared size.");if(v.has(g))return N.get(g)??null;let Ce=_?await Vt(async()=>this.framed.uploadChunk(h,g,await Do(ue),r.signal),r.signal).then(()=>null):await this.uploadPart(u,g,K,ue,de,h.strategy.kind==="object_multipart",r.signal);return P+=de,r.onProgress?.({phase:"uploading",transferredBytes:P,totalBytes:n}),Ce});await c?.();let S=await this.commitUpload(u,h.strategy.kind==="object_multipart"?q.filter(g=>g!==null):void 0,r.signal);if(S.protocol_version!==1||S.type!=="file_upload_committed"||S.transfer_id!==u||S.file.path!==e||S.file.size!==n||S.file.content_digest!==i)throw l("invalid_operation_response","The authority returned an invalid file receipt.");return f=!0,$t(S.file)}catch(h){throw ve(h)}finally{await d?.().catch(()=>{}),!f&&r.transferId===void 0&&await this.abort(u)}}async download(e,n={}){if(e.size>On)throw l("invalid_request",`download() buffers at most ${On} bytes; use downloadStream() for larger files.`);let i=await this.downloadStream(e,n),o=[],r=i.getReader();for(;;){let a=await r.read();if(a.done)break;o.push(a.value)}return new Blob(o.map(a=>{let s=new Uint8Array(a.byteLength);return s.set(a),s.buffer}),{type:e.mediaType??""})}async downloadStream(e,n={}){return B(n,this.timeouts.requestMs,i=>this.openDownloadStream(e,n,i.signal))}async openDownloadStream(e,n,i){this.requireAction("read");let o=Tn(n.concurrency),r=crypto.randomUUID(),a;try{if(a=await this.request("POST","downloads",{protocol_version:1,type:"open_file_download",transfer_id:r,file_id:e.fileId,revision:e.revision},i),kn(a,r,"download"),a.total_size!==e.size||a.strategy.kind!=="object_ranges"&&a.strategy.kind!=="framed_chunks")throw l("invalid_operation_response","The authority returned an incompatible download session.");if(a.strategy.kind==="framed_chunks"&&!this.framed)throw l("invalid_operation_response","Encrypted file chunk delivery is unavailable.");if(a.strategy.kind==="object_ranges"&&e.size>0&&!this.hosted)throw l("invalid_operation_response","Authenticated hosted file delivery is unavailable.")}catch(S){throw await this.abort(r),ve(S)}let s=a.strategy.kind==="framed_chunks"?a.strategy.chunk_size:a.strategy.part_size,c=Math.ceil(e.size/s),d=new be,p=0,u=0,f=null,h=0,_=!1,m=new AbortController,w=n.signal?AbortSignal.any([n.signal,m.signal]):m.signal,y=new Map,v=0,N=()=>{if(a.strategy.kind==="framed_chunks")for(;v<c&&y.size<o;){let S=v;v+=1;let g=Vt(()=>this.framed.downloadChunk(a,S,w),w).then(K=>({ok:!0,chunk:K}),K=>({ok:!1,error:K}));y.set(S,g)}},P=async()=>{_||(_=!0,m.abort(),await f?.cancel().catch(()=>{}),f=null,await Promise.all(y.values()),y.clear(),await this.abort(r))},q=()=>{if(h!==e.size||`sha256:${d.digestHex()}`!==e.contentDigest)throw l("invalid_operation_response","Downloaded file bytes failed integrity verification.")};return new ReadableStream({pull:async S=>{try{if(le(w),a.strategy.kind==="object_ranges")for(;;){if(!f){if(p>=c){q(),S.close(),P();return}let Go=p*s;u=Math.min(s,e.size-Go),f=(await Vt(()=>this.hosted.downloadPart(a,p,u,w),w)).getReader()}let ie=await f.read();if(ie.done){if(f.releaseLock(),f=null,u!==0)throw l("invalid_operation_response","A hosted file range ended before its declared byte length.");p+=1;continue}if(!(ie.value instanceof Uint8Array))throw l("invalid_operation_response","A hosted file range returned a non-byte chunk.");if(ie.value.byteLength!==0){if(ie.value.byteLength>u)throw l("invalid_operation_response","A hosted file range exceeded its declared byte length.");u-=ie.value.byteLength,d.update(ie.value),h+=ie.value.byteLength,n.onProgress?.({phase:"downloading",transferredBytes:h,totalBytes:e.size}),S.enqueue(ie.value);return}}if(p>=c){q(),S.close(),P();return}let g=p*s,K=Math.min(s,e.size-g);N();let de=y.get(p);if(!de)throw l("invalid_operation_response","A file chunk was not scheduled.");let ue=await de;if(y.delete(p),!ue.ok)throw ue.error;let Ce=ue.chunk;if(Ce.byteLength!==K)throw l("invalid_operation_response","A file chunk had the wrong byte length.");d.update(Ce),h+=Ce.byteLength,p+=1,N(),n.onProgress?.({phase:"downloading",transferredBytes:h,totalBytes:e.size}),p===c&&q(),S.enqueue(Ce),p===c&&(S.close(),P())}catch(g){await P(),S.error(ve(g))}},cancel:P})}async downloadBytes(e,n={}){return new Uint8Array(await(await this.download(e,n)).arrayBuffer())}async move(e,n,i={}){return B(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(a){throw ve(a)}if(r.protocol_version!==1||r.type!=="file_moved"||r.mutation_id!==o||r.file.file_id!==e.fileId||r.file.path!==n)throw l("invalid_operation_response","The authority returned an invalid file move receipt.");return $t(r.file)}async delete(e,n={}){return B(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 ve(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 l("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,a,s){for(let c=1;c<=st;c+=1){le(s);try{let d=await this.request("POST",`uploads/${encodeURIComponent(e)}/parts`,{protocol_version:1,type:"prepare_file_upload_part",transfer_id:e,part_number:n+1,content_length:r},s);zo(d,e,n,i,r,"PUT");let p=await fetch(d.url,{method:d.method,headers:Uo(d.headers),body:o,redirect:"error",signal:s});if(!p.ok)throw new Error(`Object upload failed with HTTP ${p.status}.`);let u=p.headers.get("etag");if(a&&!u)throw new Error("Multipart object upload did not return an ETag.");return{part_number:n+1,etag:u??""}}catch(d){if(s?.aborted||c===st)throw d}}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 b&&o.code==="file_upload_incomplete")return null;throw o}}async commitUpload(e,n,i){let o;for(let r=1;r<=st;r+=1){le(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(a){if(o=a,i?.aborted||a instanceof b||r===st)throw a}}throw o}requireAction(e){if(!this.capability()?.actions.includes(e))throw l("not_authorized",`This connection is not authorized to ${e} files.`)}async abort(e){await this.request("DELETE",`transfers/${encodeURIComponent(e)}`).catch(()=>{})}};function $t(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 Ke=class{constructor(e,n){this.internals=e;this.collectionId=n;this.transport=new Kt({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.files=new je(()=>this.fileCapability,(i,o,r,a)=>this.transport.files.control(i,o,r,a),{uploadChunk:(i,o,r,a)=>this.transport.files.uploadChunk(i,o,r,a),downloadChunk:(i,o,r)=>this.transport.files.downloadChunk(i,o,r)},{downloadPart:(i,o,r,a)=>this.transport.files.downloadHostedPart(i,o,r,a)},e.timeouts),this.collectionClient=new ze({operation:(i,o,r)=>this.transport.performOperation(i,o,r)},e.timeouts.requestMs),this.notifications=new It({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;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 x(()=>this.internals.register(e),ye)}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=ge){let n=this.operations,i=G(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 x(()=>this.internals.authorize({...e,target:{kind:"collection",collectionId:this.collectionId}}),Re)}async requestOperations(e,n={}){let i=this.authorizationCapabilities(e);return i.sufficient?I({kind:"unchanged",connection:this}):this.authorize({...n,operations:G([...i.grantedOperations,...i.missingOperations])})}onConnectionChange(e){return this.connectionListeners.add(e),e(this.info()),()=>this.connectionListeners.delete(e)}notifyStorageChanged(){this.transport.notifyStorageChanged()}checkDirectAccess(e){return x(()=>this.transport.checkDirectAccess(e),dn)}requestDirectAccess(e){return x(()=>this.transport.requestDirectAccess(e),dn)}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"},Gt(r,this.internals.timeouts.syncMs)),snapshot:(r,a,s)=>this.transport.performOperation("sync",{action:"snapshot",snapshot_id:r,...a?{page:a}:{}},Gt(s,this.internals.timeouts.syncMs)),changes:(r,a=200,s)=>this.transport.performOperation("sync",{action:"changes",after:r,limit:a},Gt(s,this.internals.timeouts.syncMs)),mutate:(r,a)=>this.transport.performOperation("sync",{action:"mutate",mutation:r},Gt(a,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,a)=>{let s=new URLSearchParams({snapshot_id:o});return r&&s.set("page",r),this.transport.performAuthoritySyncRequest(n,i,"GET",`snapshot?${s}`,void 0,a)},changes:(o,r=200,a)=>this.transport.performAuthoritySyncRequest(n,i,"GET",`changes?${new URLSearchParams({after:String(o),limit:String(r)})}`,void 0,a),mutate:(o,r)=>this.transport.performAuthoritySyncRequest(n,i,"POST","mutations",o,r)}}}registerNotifications(e){return x(()=>this.notifications.registerNotifications(e),Je)}registerNativeNotifications(e){return x(()=>this.notifications.registerNativeNotifications(e),Je)}unregisterNativeNotifications(e){return x(()=>this.notifications.unregisterNativeNotifications(e),Je)}unregisterNotifications(e,n){return x(()=>this.notifications.unregisterNotifications(e,n),Je)}forget(){let e=this.transport.currentToken();this.internals.removeToken(this.collectionId,e?.keyHandle,"not_authorized",!0),this.transport.notifyStorageChanged()}describe(e){return this.collectionClient.describe(e)}changes(e={},n){return this.collectionClient.changes(e,n)}read(e,n){return this.collectionClient.read(e,n)}query(e={},n){return this.collectionClient.query(e,n)}queryPages(e={},n={}){return this.collectionClient.queryPages(e,n)}queryAll(e={},n={}){return this.collectionClient.queryAll(e,n)}listViews(e){return this.collectionClient.listViews(e)}executeView(e,n){return this.collectionClient.executeView(e,n)}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 B(n,this.internals.timeouts.requestMs,async i=>{let o=Date.now(),r=!1,a,s=(c,d,p=0)=>{n.onProgress?.({operation:"rename",state:c,elapsedMs:Date.now()-o,cancellable:d,resumed:r,completedUnits:p,...a?{estimate:a}:{}})};try{me(i.signal),s("preflighting",!0);let c=n.preflight?I(n.preflight):await this.preflightRename(e,{signal:i.signal,timeoutMs:null});if(!c.ok)return c;let d=c.value;try{Si(e,d)}catch(f){if(f instanceof b)return O(f.problem);throw f}a=Ai(e,d),s("ready",!0),me(i.signal);let p=this.transport.hasResumableMutationTransport();s("applying",p);let u=await this.rename(e,p?{signal:i.signal,timeoutMs:null}:{timeoutMs:Lo(i.remainingMs())});return u.ok&&s("completed",!1,a.totalUnits),u}catch(c){if(yn(c,i.signal)&&s("cancelled",!1),c instanceof b)return O(c.problem);throw c}})}async deleteWithProgress(e,n={}){return B(n,this.internals.timeouts.requestMs,async i=>{let o=Date.now(),r=!1,a,s=(c,d,p=0)=>{n.onProgress?.({operation:"delete",state:c,elapsedMs:Date.now()-o,cancellable:d,resumed:r,completedUnits:p,...a?{estimate:a}:{}})};try{me(i.signal),s("preflighting",!0);let c=n.preflight?I(n.preflight):await this.preflightDelete(e,{signal:i.signal,timeoutMs:null});if(!c.ok)return c;let d=c.value;try{Ri(e,d)}catch(f){if(f instanceof b)return O(f.problem);throw f}a=Pi(d),s("ready",!0),me(i.signal);let p=this.transport.hasResumableMutationTransport();s("applying",p);let u=await this.delete(e,p?{signal:i.signal,timeoutMs:null}:{timeoutMs:Lo(i.remainingMs())});return u.ok&&s("completed",!1,a.totalUnits),u}catch(c){if(yn(c,i.signal)&&s("cancelled",!1),c instanceof b)return O(c.problem);throw c}})}pendingMutations(){return this.transport.pendingMutations().map(e=>({...e,recover:n=>x(()=>this.recoverPendingMutation(e.requestId,n),z)}))}pendingMutation(e){let n=this.transport.pendingMutation(e);return n?{...n,recover:i=>x(()=>this.recoverPendingMutation(e,i),z)}: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 b(Se(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 x(()=>U(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 b(o.problem);if(o.value.reset)throw new b(k("change_cursor_reset","The collection change cursor expired. Refresh collection state before subscribing again."));return new Mn(this.collectionClient,o.value.cursor,e,e.cursor===void 0?[]:o.value.events,this.internals.timeouts.watchStartMs)}),bt)}emitConnection(){let e=this.info();for(let n of this.connectionListeners)n(e)}},Mn=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 a=i.lifetimeSignal;if(a?.aborted)this.close();else if(a){let s=()=>this.close();a.addEventListener("abort",s,{once:!0}),this.removeLifetimeAbort=()=>a.removeEventListener("abort",s)}this.controller.signal.aborted||this.run(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 Gt(t,e){return{...t,timeoutMs:t?.timeoutMs===void 0?e:t.timeoutMs}}function Lo(t){return t===null?null:Math.max(1,Math.ceil(t))}function xn(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 He(t,e,n){return t.reason instanceof b?t.reason:l("authorization_cancelled",e,{cause:n})}function En(t,e,n,i){let o=`${e}:pending-mutation:`,r=new Set;for(let a=0;a<t.length;a+=1){let s=t.key(a);if(!s?.startsWith(o))continue;let c=M(t.getItem(s));if(!c||!n.includes(c.operation)||i&&c.collectionId!==i)continue;let d=c.envelope?.protocol_version??c.request?.protocol_version;d!==void 0&&d!==L&&$e(d)&&r.add(d)}return[...r].sort((a,s)=>s-a)}function Bo(t,e,n){for(let i=0;i<t.length;i+=1){let o=t.key(i);if(o!==e&&!o?.startsWith(`${e}:`))continue;if(M(t.getItem(o))?.keyHandle===n)return!0}return!1}function jo(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=M(t.getItem(o));r?.keyHandle&&n(r.keyHandle),t.removeItem(o)}}function Ko({body:t,clientId:e,keyHandle:n,previous:i,defaultApplicationOrigin:o,pinConnectorIdentity:r}){let a=t.collection_id;if(typeof a!="string")throw l("invalid_token_response","Authorization returned no collection ID.");let s=Rt(t.scope);if(!s)throw l("invalid_token_response","Authorization returned no valid collection scope.");if(t.authority&&!it(t.authority,a))throw l("invalid_token_response","Authorization returned an invalid remote authority capability.");if(t.authority&&t.encryption)throw l("invalid_token_response","Authorization returned conflicting collection transports.");if(t.file_capability!==null&&t.file_capability!==void 0&&!St(t.file_capability))throw l("invalid_token_response","Authorization returned an invalid file capability.");if(t.encryption){try{X(t.encryption)}catch{throw l("invalid_token_response","Authorization returned an invalid encrypted relay binding.")}if(r(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 l("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 l("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:s,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??o,keyHandle:n,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}}var Wt=class{serverUrl;manifest;manifestSource;redirectUri;storage;relayEncryption;keyStore;identityStore;directAccessMode;loopbackUrl;navigate;timeouts;credentialStorage;application=null;manifestPromise=null;completionPromises=new Map;connectionCache=new Map;listeners=new Set;invalidatedConnections=new Map;constructor(e){this.serverUrl=Di(String(e.serverUrl)),this.manifest=e.manifest instanceof URL?e.manifest.href:e.manifest??qi(),this.manifestSource=typeof this.manifest=="string"?this.manifest:this.manifest.distribution==="portable"?`bundle:${this.manifest.id}:${Bi(this.manifest)}`:`bundle:${this.manifest.id}`;let n=Li(this.manifest);this.redirectUri=e.redirectUri===void 0?typeof this.manifest!="string"&&this.manifest.distribution==="portable"?"":Fi():String(e.redirectUri),this.storage=e.storage??Ni(n),this.relayEncryption=e.relayEncryption??"required",this.keyStore=e.keyStore??(n?new Oe:new Pe),this.identityStore=e.identityStore??(n?new qe:new De),this.credentialStorage=e.storage||e.keyStore||e.identityStore?"custom":this.storage instanceof Ie?"memory":"persistent",this.directAccessMode=e.directAccess??"auto",this.loopbackUrl=Ii(String(e.loopbackUrl??`http://127.0.0.1:${oi}`)),this.navigate=e.navigate,this.timeouts=Ae(e.timeouts),typeof window<"u"&&this.storage===window.localStorage&&window.addEventListener("storage",i=>{i.storageArea!==this.storage||!i.key?.startsWith(this.storagePrefix())||(this.connectionCache.get(Ui(i.key))?.notifyStorageChanged(),this.emitConnections())})}environment(){let e=typeof this.manifest!="string"&&this.manifest.distribution==="portable"?"portable":this.application?.distribution??"web";return{distribution:e,applicationOrigin:e==="portable"?"null":this.defaultApplicationOrigin(),credentialStorage:this.credentialStorage}}register(e={}){return U(e,this.timeouts.requestMs,n=>this.registerWithinBudget(n.signal))}async registerWithinBudget(e){if(this.application)return this.application;let n=await Z(`${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 A(n,"invalid_operation_response","Connect returned an invalid application registration response.");if(!n.ok)throw T(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=U(e,this.timeouts.requestMs,o=>this.loadManifest(o.signal)).catch(o=>{throw this.manifestPromise===i&&(this.manifestPromise=null),o});return this.manifestPromise=i,this.manifestPromise}async loadManifest(e){if(typeof this.manifest!="string")return this.manifest;let n=this.manifest,i;try{i=await fetch(n,{headers:{accept:"application/json"},signal:e})}catch(o){throw l("manifest_load_failed","The bundled application declaration could not be loaded.",{cause:o})}if(!i.ok)throw l("manifest_load_failed",`The bundled application declaration returned HTTP ${i.status}.`,{status:i.status});try{return await A(i,"invalid_application_manifest","The bundled application declaration is not valid JSON.")}catch(o){throw l("invalid_application_manifest","The bundled application declaration is not valid JSON.",{cause:o,details:{issues:[{path:"/",keyword:"json",message:"must be valid JSON",params:{}}]}})}}async authorize(e={}){return U(e,this.timeouts.requestMs,n=>this.authorizeWithinBudget({...e,signal:n.signal,timeoutMs:null}))}async authorizeWithinBudget(e){if(typeof location>"u"&&!this.navigate&&!e.openVerification)throw l("browser_required","Authorization navigation requires a browser environment.");let i=typeof this.manifest!="string"&&this.manifest.distribution==="portable"&&!e.openVerification&&!this.navigate&&typeof window<"u"?window.open("","mdbase-connect-authorization","popup,width=620,height=760"):null,o;try{o=await this.registerWithinBudget(e.signal)}catch(r){throw i?.close(),r}return o.distribution==="portable"?(e.openVerification&&i?.close(),this.authorizePortable(o,e,e.openVerification?null:i)):(i?.close(),this.authorizeWeb(o,e))}async authorizeWeb(e,n){let{verifier:i,challenge:o}=await tt(),r=V(24),a=crypto.randomUUID(),s=n.target?.kind==="collection"?n.target.collectionId:void 0,c=`grant:${e.id}:${r}`,d=await this.keyStore.create(c),p;try{p=await this.loadApplicationIdentity(e)}catch(m){throw await this.keyStore.delete(c),m}let u=G(n.operations??ge),f=new Date,h=await at({protocol_version:$,authorization_id:a,application_id:e.id,application_declaration_id:xn(e.family_identity),application_manifest_digest:e.manifest_digest,application_installation_id:await Fe(p),installation_signing_public_key:p.signingPublicKey,grant_agreement_public_key:d.agreementPublicKey,grant_signing_public_key:d.signingPublicKey,flow:"authorization_code",authorization_nonce:V(32),issued_at:f.toISOString(),expires_at:new Date(f.getTime()+600*1e3).toISOString(),redirect_uri:this.redirectUri,state:r,code_challenge:o,contracts:sn(u,e.requirements?.files,En(this.storage,this.storagePrefix(),u,s)),requested_operations:u,...e.requirements?.files?{requested_files:e.requirements.files}:{},...s?{collection_id:s}:{}},p),_={version:1,verifier:i,state:r,clientId:e.id,redirectUri:this.redirectUri,relayEncryption:this.relayEncryption,collectionId:s,returnTo:n.returnTo,keyHandle:c,authorizationId:a,applicationAgreementPublicKey:d.agreementPublicKey,applicationSigningPublicKey:d.signingPublicKey};this.storage.setItem(this.pendingKey(r),JSON.stringify(_));try{let m=await fetch(`${this.serverUrl}/oauth/authorization_request`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e.id,redirect_uri:this.redirectUri,code_challenge:o,code_challenge_method:"S256",state:r,operations:u.join(","),...s?{collection_id:s}:{},application_authorization:JSON.stringify(h)}),signal:n.signal}),w=await A(m,"invalid_device_authorization_response","The authorization service returned an invalid authorization response.");if(!m.ok)throw T(w,"device_authorization_failed","Application authorization could not be started.",m.status);if(typeof w.authorization_uri!="string"||w.authorization_id!==a||!Number.isInteger(w.expires_in)||w.expires_in<=0)throw l("invalid_device_authorization_response","The authorization service returned an invalid authorization response.");if(this.navigate)await this.navigate(w.authorization_uri);else if(typeof location<"u")location.assign(w.authorization_uri);else throw l("browser_required","Authorization navigation requires a browser environment.");return{kind:"redirecting"}}catch(m){throw this.storage.removeItem(this.pendingKey(r)),await this.keyStore.delete(c),n.signal?.aborted?He(n.signal,"Application authorization was cancelled.",m):m}}async authorizePortable(e,n,i){if(this.relayEncryption!=="required")throw i?.close(),l("encryption_required","Downloaded applications require encrypted relay authorization.");let{verifier:o,challenge:r}=await tt(),a=`grant:${e.id}:${V(24)}`,s=await this.keyStore.create(a),c;try{c=await this.loadApplicationIdentity(e)}catch(y){throw i?.close(),await this.keyStore.delete(a),y}let d=G(n.operations??ge),p=crypto.randomUUID(),u=new Date,f=await at({protocol_version:$,authorization_id:p,application_id:e.id,application_declaration_id:xn(e.family_identity),application_manifest_digest:e.manifest_digest,application_installation_id:await Fe(c),installation_signing_public_key:c.signingPublicKey,grant_agreement_public_key:s.agreementPublicKey,grant_signing_public_key:s.signingPublicKey,flow:"device_code",authorization_nonce:V(32),issued_at:u.toISOString(),expires_at:new Date(u.getTime()+600*1e3).toISOString(),code_challenge:r,contracts:sn(d,e.requirements?.files,En(this.storage,this.storagePrefix(),d,n.target?.kind==="collection"?n.target.collectionId:void 0)),requested_operations:d,...e.requirements?.files?{requested_files:e.requirements.files}:{},...n.target?.kind==="collection"?{collection_id:n.target.collectionId}:{}},c),h,_;try{h=await fetch(`${this.serverUrl}/oauth/device_authorization`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e.id,operations:d.join(","),...n.target?.kind==="collection"?{collection_id:n.target.collectionId}:{},code_challenge:r,code_challenge_method:"S256",application_authorization:JSON.stringify(f)}),signal:n.signal}),_=await A(h,"invalid_device_authorization_response","The authorization service returned an invalid device authorization response.")}catch(y){throw i?.close(),await this.keyStore.delete(a),l("device_authorization_failed","Downloaded application authorization could not be started.",{cause:y})}if(!h.ok)throw i?.close(),await this.keyStore.delete(a),T(_,"device_authorization_failed","Downloaded application authorization could not be started.",h.status);let m;try{m=Ei(_)}catch(y){throw i?.close(),await this.keyStore.delete(a),n.signal?.aborted?He(n.signal,"Downloaded application authorization was cancelled.",y):y}if(n.onDeviceCode?.(m),n.openVerification)await n.openVerification(m);else if(i)try{i.location.href=m.verificationUriComplete}catch{}else throw await this.keyStore.delete(a),l("approval_window_blocked","The approval window was blocked. Show the provided verification link and code, then try again.",{details:{user_code:m.userCode,verification_uri:m.verificationUri,verification_uri_complete:m.verificationUriComplete,expires_at:m.expiresAt,interval_seconds:m.intervalSeconds}});let w=m.intervalSeconds;try{for(;Date.now()<m.expiresAt;){if(await ee(w*1e3,n.signal),n.signal?.aborted)throw He(n.signal,"Downloaded application authorization was cancelled.");let y;try{y=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(S){if(n.signal?.aborted)throw He(n.signal,"Downloaded application authorization was cancelled.",S);continue}let v=await A(y,"invalid_token_response","The authorization service returned an invalid token response.");if(!y.ok){let S=nt(v);if(S==="authorization_pending")continue;if(S==="slow_down"){w+=5;continue}throw T(v,"token_exchange_failed","Downloaded application authorization could not be completed.",y.status)}let N=it(v.authority,v.collection_id),P=v.encryption&&v.encryption.protocol_version===mt&&v.encryption.suite===We&&v.encryption.application_agreement_public_key===s.agreementPublicKey;if(v.application_origin!=="null")throw l("invalid_token_response","Authorization did not bind the portable grant to its opaque application origin.");if(v.authority&&(!N||v.encryption!=null||v.authority.proof_public_key!==s.signingPublicKey))throw l("invalid_token_response","Authorization returned a remote authority capability that is not bound to this portable grant key.");if(!v.authority&&!P)throw l("encryption_required","Authorization did not establish the expected key-bound local portable grant.");let q=this.storeTokenResponse(v,e.id,a);if(n.target?.kind==="collection"&&n.target.collectionId!==q.collectionId)throw this.removeToken(q.collectionId,q.keyHandle),l("collection_mismatch","The approved collection does not match the collection requested by this link.");return i?.close(),{kind:"connected",connection:this.connection(q.collectionId),...n.returnTo?{returnTo:n.returnTo}:{}}}throw l("expired_token","The downloaded application authorization code expired.")}catch(y){throw i?.close(),await this.keyStore.delete(a),n.signal?.aborted?He(n.signal,"Downloaded application authorization was cancelled.",y):y}}completeAuthorization(e,n={}){return U(n,this.timeouts.requestMs,i=>this.completeAuthorizationWithinBudget(e,i.signal))}completeAuthorizationWithinBudget(e,n){let i=new URL(e).searchParams.get("state");if(!i)return Promise.reject(l("invalid_callback","Authorization callback is missing its state."));let o=this.completionPromises.get(i);if(o)return o;let a=this.performAuthorizationCompletion(e,i,n).finally(()=>{this.completionPromises.get(i)===a&&this.completionPromises.delete(i)});return this.completionPromises.set(i,a),a}async performAuthorizationCompletion(e,n,i){let o=new URL(e),r=o.searchParams.get("code"),a=this.pendingKey(n),s=M(this.storage.getItem(a));if(!s||s.version!==1||n!==s.state)throw l("invalid_callback","Authorization callback is missing or does not match this browser session.");if(o.searchParams.has("error"))throw s.keyHandle&&await this.keyStore.delete(s.keyHandle),this.storage.removeItem(a),F(o.searchParams.get("error")??"access_denied",o.searchParams.get("error_description")??"Collection access was not approved.",{details:s.returnTo?{return_to:s.returnTo}:void 0});if(!r)throw l("invalid_callback","Authorization callback is missing its code.");let c=await Z(`${this.serverUrl}/oauth/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:r,client_id:s.clientId,redirect_uri:s.redirectUri,code_verifier:s.verifier}),signal:i},"temporarily_unavailable","Authorization completion is temporarily unavailable."),d=await A(c,"invalid_token_response","The authorization service returned an invalid token response.");if(!c.ok)throw T(d,"token_exchange_failed","Authorization could not be completed.",c.status);if(s.relayEncryption==="required"&&!d.authority&&(!d.encryption||!s.keyHandle||d.encryption.application_agreement_public_key!==s.applicationAgreementPublicKey))throw s.keyHandle&&await this.keyStore.delete(s.keyHandle),this.storage.removeItem(a),l("encryption_required","Authorization did not establish the required encrypted relay grant.");if(d.authority?.proof_public_key){if(!s.keyHandle||!s.applicationSigningPublicKey||d.authority.proof_public_key!==s.applicationSigningPublicKey)throw s.keyHandle&&await this.keyStore.delete(s.keyHandle),this.storage.removeItem(a),l("invalid_token_response","Authorization returned a remote authority capability bound to another application key.")}else d.authority&&s.keyHandle&&await this.keyStore.delete(s.keyHandle);let p=this.storeTokenResponse(d,s.clientId,d.authority?.proof_public_key?s.keyHandle:d.authority?void 0:s.keyHandle);if(s.collectionId&&s.collectionId!==p.collectionId)throw this.removeToken(p.collectionId,p.keyHandle),this.storage.removeItem(a),l("collection_mismatch","The approved collection does not match the collection requested by this link.");return this.storage.removeItem(a),{connection:this.connection(p.collectionId),...s.returnTo?{returnTo:s.returnTo}:{}}}connections(){let e=[];for(let n of this.connectionIds()){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 Ke(this,e),this.connectionCache.set(e,n)),n.info()?n:null}unavailableReason(e){return this.invalidatedConnections.get(e)??null}onConnectionsChange(e){return this.listeners.add(e),e(this.connections()),()=>this.listeners.delete(e)}storeTokenResponse(e,n,i){let o=e.collection_id;if(typeof o!="string")throw l("invalid_token_response","Authorization returned no collection ID.");let r=M(this.storage.getItem(this.tokenKey(o))),a=Ko({body:e,clientId:n,keyHandle:i,previous:r,defaultApplicationOrigin:this.defaultApplicationOrigin(),pinConnectorIdentity:(s,c)=>this.pinConnectorIdentity(s,c)});return r?.keyHandle&&r.keyHandle!==i&&this.keyStore.delete(r.keyHandle).catch(()=>{}),this.storage.setItem(this.tokenKey(o),JSON.stringify(a)),this.addConnectionId(o),this.invalidatedConnections.delete(o),this.connectionCache.delete(o),this.emitConnections(),a}forgetConnectorIdentity(e){this.storage.removeItem(this.connectorPinKey(e))}pinConnectorIdentity(e,n){let i=this.connectorPinKey(e),o=M(this.storage.getItem(i));if(o&&(o.version!==1||o.publicKey!==n))throw l("connector_identity_changed","The connector identity changed since this application first connected. Forget the saved connector identity only after verifying the computer, then authorize again.");o||this.storage.setItem(i,JSON.stringify({version:1,publicKey:n}))}connectorPinKey(e){return`mdbase-connect:${this.serverUrl}:connector-pin:${e}`}async loadApplicationIdentity(e){try{return await Ot(this.identityStore,this.serverUrl,e)}catch(n){throw l("application_identity_unavailable",n instanceof _e?n.message:"The application installation identity is unavailable.",{cause:n})}}removeToken(e,n,i="authorization_lost",o=!1){this.invalidatedConnections.set(e,i),n&&(o||!Bo(this.storage,this.pendingMutationKey(e),n))&&this.keyStore.delete(n).catch(()=>{}),this.storage.removeItem(this.tokenKey(e)),o&&jo(this.storage,this.pendingMutationKey(e),r=>{this.keyStore.delete(r).catch(()=>{})});for(let r of["web_push","fcm"])this.storage.removeItem(this.notificationKey(e,r));this.storage.setItem(this.connectionsKey(),JSON.stringify({version:1,collectionIds:this.connectionIds().filter(r=>r!==e)})),this.connectionCache.delete(e),this.emitConnections()}tokenKey(e){return`${this.storagePrefix()}:token:${e}`}pendingMutationKey(e){return`${this.storagePrefix()}:pending-mutation:${e}`}notificationKey(e,n="web_push"){return`${this.storagePrefix()}:notifications:${e}:${n}`}directPreferenceKey(){return`mdbase-connect:direct:${this.defaultApplicationOrigin()}`}defaultApplicationOrigin(){return zi(this.manifest,this.manifestSource,this.redirectUri,this.application?.distribution==="portable")}pendingKey(e){return`${this.storagePrefix()}:pending:${e}`}storagePrefix(){return`mdbase-connect:${this.serverUrl}:${this.manifestSource}`}connectionsKey(){return`${this.storagePrefix()}:connections`}connectionIds(){let e=M(this.storage.getItem(this.connectionsKey()));return e?.version===1&&Array.isArray(e.collectionIds)&&e.collectionIds.every(n=>typeof n=="string")?e.collectionIds:[]}addConnectionId(e){this.storage.setItem(this.connectionsKey(),JSON.stringify({version:1,collectionIds:[...new Set([...this.connectionIds(),e])]}))}emitConnections(){let e=this.connections();for(let n of this.listeners)n(e)}};var Yt=class{internals;constructor(e){this.internals=new Wt(e)}register(e){return x(()=>this.internals.register(e),ye)}authorize(e={}){return x(()=>this.internals.authorize(e),Re)}application(e){return new xe(this,e,this.internals.timeouts)}manifest(e){return x(()=>this.internals.manifestDeclaration(e),ye)}environment(){return this.internals.environment()}completeAuthorization(e,n){return x(()=>this.internals.completeAuthorization(e===void 0?At():String(e),n),Re)}connections(){return this.internals.connections()}connection(e){return this.internals.connection(e)}unavailableReason(e){return this.internals.unavailableReason(e)}onConnectionsChange(e){return this.internals.onConnectionsChange(e)}forgetAll(){for(let e of this.connections())this.connection(e.collectionId)?.forget()}forgetConnectorIdentity(e){this.internals.forgetConnectorIdentity(e)}};function Dn(t){if(!t||typeof t!="object")throw l("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 l("invalid_push_payload","The push payload is not an mdbase notification.");return e}function Ho(t){if(!t||typeof t!="object")throw l("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 l("invalid_push_payload","The native notification data is not an mdbase notification.");return{type:"mdbase.notification",version:1,signal_id:e.signal_id,criterion_id:e.criterion_id,cursor:e.cursor}}function Vo(t,e){let n=Dn(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 $o(t){return{subscribe:e=>t.subscribe(e),getSnapshot:()=>t.getSnapshot()}}var Jt=class{collectionParameter;fallbackPath;listeners=new Set;handlePopState=()=>this.emit();constructor(e={}){this.collectionParameter=e.collectionParameter??"collection",this.fallbackPath=e.fallbackPath??"/"}selectedCollectionId(){return this.currentUrl().searchParams.get(this.collectionParameter)}select(e,n={}){let i=ot(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=ot(this.currentUrl());return`${e.pathname}${e.search}${e.hash}`}authorizationCallback(){let e=this.currentUrl().href;return Pt(e)?e:null}finishAuthorization(e,n){let i=this.safeAppUrl(e??this.fallbackPath);ot(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,"",ot(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 l("browser_required","Browser selection requires a browser environment.");return new URL(location.href)}browserHistory(){if(typeof history>"u")throw l("browser_required","Browser selection requires a browser environment.");return history}},Qt=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 Zo(Xa);})();
|
|
3
|
+
`)}async function Q(t,e,n,i,o,r=crypto.randomUUID(),a){if(X(n.encryption),a!==void 0&&(!Number.isSafeInteger(a)||a<=0))throw new R("invalid_deadline","The operation deadline is invalid.");let s=await yi(t,e,n.encryption.application_agreement_public_key),c=await t.nextCounter(e),d={binding:n,protocolVersion:L,requestId:r,operation:i,counter:c},p=await mi(s.agreementPrivateKey,n,d.protocolVersion,"request"),u=new TextEncoder().encode(JSON.stringify(o??{})),f=await crypto.subtle.encrypt({name:"AES-GCM",iv:bi(c),additionalData:new TextEncoder().encode(_i(d,"request")),tagLength:128},p,u);return{type:"encrypted_operation_request",...ta(d),...a===void 0?{}:{deadline_unix_ms:a},ciphertext:Xe(new Uint8Array(f))}}async function Te(t,e,n,i,o){if(!na(i,o))throw new R("invalid_encrypted_response","Encrypted response metadata does not match its request.");let r=await yi(t,e,n.encryption.application_agreement_public_key),a={binding:n,protocolVersion:i.protocol_version,requestId:i.request_id,operation:i.operation,counter:i.counter},s=await mi(r.agreementPrivateKey,n,i.protocol_version,"response");try{let c=await crypto.subtle.decrypt({name:"AES-GCM",iv:bi(i.counter),additionalData:new TextEncoder().encode(_i(a,"response")),tagLength:128},s,Ci(vi(o.ciphertext))),d=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(c));if(d?.ok===!0&&"result"in d||d?.ok===!1&&Ve(d.problem))return d;throw new Error("invalid response body")}catch(c){throw c instanceof R?c:new R("encrypted_response_rejected","The encrypted connector response could not be authenticated.")}}var R=class extends Error{constructor(n,i){super(i);this.code=n}code};async function hi(t){let e=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"]),n=Xe(new Uint8Array(await crypto.subtle.exportKey("raw",e.publicKey))),i=await crypto.subtle.exportKey("pkcs8",e.privateKey),o=await crypto.subtle.importKey("pkcs8",i,{name:"ECDH",namedCurve:"P-256"},!1,["deriveBits"]),r=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign","verify"]),a=Xe(new Uint8Array(await crypto.subtle.exportKey("raw",r.publicKey))),s=await crypto.subtle.exportKey("pkcs8",r.privateKey),c=await crypto.subtle.importKey("pkcs8",s,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]);return{handle:t,agreementPrivateKey:o,agreementPublicKey:n,signingPrivateKey:c,signingPublicKey:a}}async function yi(t,e,n){let i=await t.get(e);if(!i||i.agreementPublicKey!==n)throw new R("missing_grant_key","The encrypted grant key is unavailable or does not match the grant.");return i}async function ea(t,e,n){let i=await t.get(e);if(!i||i.signingPublicKey!==n)throw new R("missing_grant_key","The remote authority signing key is unavailable or does not match the grant.");return i}async function mi(t,e,n,i){let o=await Ze(t,e.encryption.connector_agreement_public_key),r=await crypto.subtle.importKey("raw",o,"HKDF",!1,["deriveKey"]),a=new TextEncoder().encode(gi(e,n)),s=await crypto.subtle.digest("SHA-256",a);return crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:s,info:new TextEncoder().encode(i==="request"?Xr:Zr)},r,{name:"AES-GCM",length:256},!1,i==="request"?["encrypt"]:["decrypt"])}async function Ze(t,e){try{let n=await crypto.subtle.importKey("raw",Ci(un(e)),{name:"ECDH",namedCurve:"P-256"},!1,[]);return await crypto.subtle.deriveBits({name:"ECDH",public:n},t,256)}catch{throw new R("invalid_public_key","The connector relay public key is invalid.")}}function gi(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 _i(t,e){return[gi(t.binding,t.protocolVersion),t.requestId,e,t.operation,t.counter].join("|")}function ta(t){let e=t.binding.encryption;return{protocol_version:t.protocolVersion,suite:We,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 na(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 X(t){if(t.protocol_version!==mt||t.suite!==We||!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 R("unsupported_encryption","The grant uses an unsupported relay encryption profile.");if(typeof t.connector_id!="string"||!ui.test(t.connector_id)||typeof t.collection_id!="string"||!ui.test(t.collection_id))throw new R("unsupported_encryption","The grant uses invalid encrypted relay identities.");un(t.application_agreement_public_key),un(t.connector_agreement_public_key)}function bi(t){let e=BigInt(t);if(e<=0n||e>pn||e.toString()!==t)throw new R("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}function Xe(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}async function pi(t){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return Xe(new Uint8Array(e))}function vi(t){if(!/^[A-Za-z0-9_-]+$/.test(t))throw new R("invalid_base64","Encrypted relay data is malformed.");let e="=".repeat((4-t.length%4)%4),n=atob(t.replaceAll("-","+").replaceAll("_","/")+e);return Uint8Array.from(n,i=>i.charCodeAt(0))}function un(t){let e=vi(t);if(e.length!==65||e[0]!==4)throw new R("invalid_public_key","Encrypted relay public keys must be uncompressed P-256 points.");return e}function Ci(t){return Uint8Array.from(t).buffer}function ia(t){return new Promise((e,n)=>{t.onerror=()=>n(t.error),t.onsuccess=()=>e(t.result)})}function fi(t,e){return new Promise((n,i)=>{let o=t.transaction(se,"readwrite"),r=e(o.objectStore(se));r.onerror=()=>i(r.error),o.onerror=()=>i(o.error),o.onabort=()=>i(o.error??new Error("Grant key transaction aborted.")),o.oncomplete=()=>n()})}function ce(t){return{...t,credentials:"omit",targetAddressSpace:"loopback"}}async function et(){if(typeof navigator>"u"||!navigator.permissions?.query)return null;try{return(await navigator.permissions.query({name:"local-network-access"})).state}catch{return null}}function ke(t){return t===404||t===405||t===426||t>=500}function wi(t,e){return we(t,e)}function G(t){return[...new Set(t)]}function Si(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 me(t){if(t?.aborted)throw l("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 b?t:e?.aborted?n?j(n,t):e.reason instanceof b?e.reason:l("operation_cancelled","The operation was cancelled before it changed the collection.",{operationOutcome:"not_sent",cause:t}):n?j(n,t):t instanceof TypeError?l(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 yn(t,e){return e?.aborted===!0||t instanceof b&&t.code==="operation_cancelled"}function Ri(t,e){if(e.dryRun!==!0||e.wouldRename!==!0||e.from!==t.from||e.to!==t.to)throw l("invalid_preflight","The rename preview does not match this mutation. Run the preview again.")}function Ai(t,e){if(e.dryRun!==!0||e.wouldDelete!==!0||e.path!==t.path)throw l("invalid_preflight","The delete preview does not match this mutation. Run the preview again.")}function Pi(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 Oi(t){return{affectedRecords:new Set((t.brokenLinks??[]).map(e=>e.path)).size,totalUnits:1,warnings:0}}async function Ti(t,e){return Gn(t,e??{})}function ki(t){return JSON.stringify(hn(t))}function hn(t){return Array.isArray(t)?t.map(e=>hn(e)):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[n])=>e<n?-1:e>n?1:0).map(([e,n])=>[e,hn(n)])):t}function j(t,e){return l("operation_outcome_unknown","The write may have completed, but mdbase could not recover its authoritative result. Retry the exact same write to recover safely.",{operationOutcome:"unknown",details:{request_id:t},cause:e})}function V(t){let e=new Uint8Array(t);return crypto.getRandomValues(e),mn(e)}function mn(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function Ii(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}async function Z(t,e,n,i){try{return await fetch(t,e)}catch(o){throw l(n,i,{cause:o})}}async function A(t,e,n){let i;try{i=await t.text()}catch(o){throw F(e,n,{status:t.status,cause:o})}if(i.trim()==="")throw F(e,n,{status:t.status});try{return JSON.parse(i)}catch(o){throw F(e,n,{status:t.status,cause:o})}}function Mi(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 l("invalid_loopback_url","loopbackUrl must be an HTTP origin on 127.0.0.1 or ::1.");return e.origin}async function tt(){let t=V(32),e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return{verifier:t,challenge:mn(new Uint8Array(e))}}function T(t,e,n,i){return F(nt(t)??t?.error?.code??e,t?.error_description??t?.error?.message??n,{status:i,details:t?.error?.details})}function nt(t){return typeof t?.error=="string"?t.error:void 0}function it(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(a=>(a.protocol==="https:"||a.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(a.hostname))&&!a.username&&!a.password&&!a.search&&!a.hash)&&/^\/v1\/authorities\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/operations$/i.test(i.pathname)&&/^\/v1\/authorities\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/sync$/i.test(o.pathname)&&/^\/v1\/authorities\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/files$/i.test(r.pathname)&&i.origin===o.origin&&i.origin===r.origin&&i.pathname.split("/")[3]===e&&o.pathname.split("/")[3]===e&&r.pathname.split("/")[3]===e}catch{return!1}}function xi(t,e){return it({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 St(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&&oa(o))}function oa(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 Ei(t,e){if(!t||typeof t!="object"||Array.isArray(t)||t.collection_id!==e)return!1;try{return X(t),!0}catch{return!1}}function Di(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 l("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 M(t){if(!t)return null;try{return JSON.parse(t)}catch{return null}}function Rt(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 qi(t){return t.endsWith("/")?t.slice(0,-1):t}function Fi(){if(typeof location>"u")throw l("manifest_required","manifest is required outside a browser environment.");if(location.origin==="null")throw l("manifest_required","Downloaded applications must provide their v1 portable manifest inline.");return new URL("/.well-known/mdbase-app.json",location.origin).href}function zi(){if(typeof location>"u")throw l("redirect_uri_required","redirectUri is required outside a browser environment.");return location.href.split(/[?#]/)[0]}function Ui(t,e,n,i){if(typeof t!="string"&&t.distribution==="portable"||i)return"null";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 Ni(t){let e=":token:",n=t.lastIndexOf(e);return n<0?"":t.slice(n+e.length)}function At(){if(typeof location>"u")throw l("callback_url_required","callbackUrl is required outside a browser environment.");return location.href}function Li(t){if(t)return new Ie;if(typeof localStorage>"u")throw l("storage_required","storage is required outside a browser environment.");try{let e=`mdbase-connect:probe:${V(8)}`;return localStorage.setItem(e,"1"),localStorage.removeItem(e),localStorage}catch{return new Ie}}var Ie=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 Bi(t){return typeof t=="string"||t.distribution!=="portable"?!1:typeof location>"u"||location.origin==="null"||!["http:","https:"].includes(location.protocol)}function ji(t){let e=ki(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")}`}function ot(t){for(let e of["code","state","error","error_description"])t.searchParams.delete(e);return t}function Pt(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 Ki(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 ge=["describe","changes","read","query"];var Me=class{constructor(e,n){this.connect=e;this.operations=G(n.operations??ge),this.selection=n.selection,this.autoSelect=n.autoSelect??"only",this.snapshot={status:"unselected",connections:[]},this.refresh()}connect;operations;selection;autoSelect;listeners=new Set;snapshot;snapshotKey="";stopConnections;stopSelection;stopActiveConnection;activeCollectionId=null;unavailableReason="not_authorized";started=!1;refreshing=!1;refreshQueued=!1;transactionDepth=0;callbackPromise=null;async start(e){this.started||(this.started=!0,this.stopConnections=this.connect.onConnectionsChange(()=>this.refresh()),this.stopSelection=this.selection.subscribe(()=>{this.unavailableReason="not_authorized",this.refresh()}));let n=this.selection.authorizationCallback();if(n){let i=await this.handleAuthorizationCallback(n,e);if(!i.ok)return i}else this.autoSelectOnlyConnection();return this.refresh(),I(this.snapshot)}destroy(){this.stopConnections?.(),this.stopSelection?.(),this.stopActiveConnection?.(),this.stopConnections=void 0,this.stopSelection=void 0,this.stopActiveConnection=void 0,this.activeCollectionId=null,this.started=!1}getSnapshot(){return this.snapshot}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}select(e,n={}){let i=this.connect.connection(e);return i?(this.unavailableReason="not_authorized",this.selection.select(e,n),this.refresh(),I(i)):O(k("unknown_collection","This collection is not authorized for this application."))}clearSelection(e={}){this.unavailableReason="not_authorized",this.selection.select(null,e),this.refresh()}forget(e){this.transactionDepth+=1;try{let n=this.selection.selectedCollectionId()===e;this.connect.connection(e)?.forget(),n&&this.selection.select(null,{history:"replace"})}finally{this.transactionDepth-=1,this.refresh()}}async authorize(e,n={}){let i=this.selection.selectedCollectionId();if(e==="selected"&&!i)return O(k("collection_not_selected","Choose a collection before updating its access."));let o=typeof e=="object"?e.collectionId:e==="selected"?i:null;this.transactionDepth+=1;try{let r=await this.connect.authorize({...n,operations:this.operations,target:o===null?{kind:"choose"}:{kind:"collection",collectionId:o},returnTo:this.selection.authorizationReturnTo()});return r.ok&&r.value.kind==="connected"&&this.selection.finishAuthorization(r.value.returnTo,r.value.connection.collectionId),r}finally{this.transactionDepth-=1,this.refresh()}}async ensureOperations(e,n){let i=this.snapshot;if(i.status!=="ready")return O(k("collection_not_ready","Choose an authorized collection first."));let o=G(e),r=i.connection.authorizationCapabilities(o);if(r.sufficient)return I({kind:"unchanged",connection:i.connection});this.transactionDepth+=1;try{let a=await this.connect.authorize({...n,operations:G([...r.grantedOperations,...r.missingOperations]),target:{kind:"collection",collectionId:i.collectionId},returnTo:this.selection.authorizationReturnTo()});return a.ok&&a.value.kind==="connected"&&this.selection.finishAuthorization(a.value.returnTo,a.value.connection.collectionId),a}finally{this.transactionDepth-=1,this.refresh()}}handleAuthorizationCallback(e,n){if(!Pt(e))return Promise.resolve(O(k("invalid_callback","This URL is not an authorization callback.")));if(this.callbackPromise)return this.callbackPromise;this.transactionDepth+=1;let i=this.connect.completeAuthorization(e,n).then(o=>{if(!o.ok){let a=Ki(o.problem);return this.selection.clearAuthorizationCallback(a),this.refresh(),o}let r=o.value;return this.unavailableReason="not_authorized",this.selection.finishAuthorization(r.returnTo,r.connection.collectionId),this.refresh(),I(r.connection,o.diagnostics)}).catch(o=>{throw this.selection.clearAuthorizationCallback(),this.refresh(),o}).finally(()=>{this.transactionDepth-=1,this.refresh(),this.callbackPromise===i&&(this.callbackPromise=null)});return this.callbackPromise=i,i}autoSelectOnlyConnection(){if(this.autoSelect!=="only"||this.selection.selectedCollectionId())return;let e=this.connect.connections();e.length===1&&this.selection.select(e[0].collectionId,{history:"replace"})}refresh(){if(this.transactionDepth>0){this.refreshQueued=!0;return}if(this.refreshing){this.refreshQueued=!0;return}this.refreshing=!0;try{do this.refreshQueued=!1,this.refreshOnce();while(this.refreshQueued)}finally{this.refreshing=!1}}refreshOnce(){let e=this.selection.selectedCollectionId(),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(a=>{!a&&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 a=i.info();o={status:"ready",collectionId:e,connection:i,info:a,access:i.authorizationCapabilities(this.operations),connections:n}}let r=ra(o);if(r!==this.snapshotKey){this.snapshot=o,this.snapshotKey=r;for(let a of this.listeners)a()}}};function ra(t){return 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 rt=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)}},xe=class{constructor(e,n,i=Ae()){this.connect=e;this.options=n;this.timeouts=i;this.verificationStore=n.verificationStore??fa()}connect;options;timeouts;listeners=new Set;verificationStore;snapshot={status:"opening",connections:[]};manifest=null;application=null;base=null;stopBase;setupAssessment=null;setupTypePackAdoptions=null;verificationGeneration=0;lifecycleGeneration=0;startOperation=null;start(e){if(this.base&&!this.startOperation)return Promise.resolve(I(this.snapshot));let n=this.startOperation??this.beginStart();return n.waiters+=1,U(e,this.timeouts.watchStartMs,()=>n.promise).finally(()=>{n.waiters-=1,n.waiters===0&&this.startOperation===n&&(n.controller.abort(),this.startOperation=null,this.lifecycleGeneration+=1)})}beginStart(){this.snapshot={status:"opening",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){let i=await this.connect.register(e);if(!i.ok)return i;let o=await this.connect.manifest(e);if(!o.ok)return o;let r=o.value.requirements?.capabilities;if(!r)return O(k("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:{}}]}}));if(n!==this.lifecycleGeneration||e.signal?.aborted)throw J(e.signal??new AbortController().signal);this.application=i.value,this.manifest=o.value;let a=new Me(this.connect,{selection:this.options.selection,autoSelect:this.options.autoSelect,operations:aa(r)});this.base=a;try{let s=await a.start(e);if(!s.ok)return this.cleanupBase(a),s;if(n!==this.lifecycleGeneration||e.signal?.aborted)throw J(e.signal??new AbortController().signal);if(this.stopBase=a.subscribe(()=>{this.base===a&&this.refresh()}),await this.refresh(!0,e),n!==this.lifecycleGeneration||e.signal?.aborted)throw J(e.signal??new AbortController().signal);return I(this.snapshot)}catch(s){throw this.cleanupBase(a),s}}destroy(){this.lifecycleGeneration+=1,this.verificationGeneration+=1,this.startOperation?.controller.abort(),this.startOperation=null,this.base&&this.cleanupBase(this.base),this.application=null,this.manifest=null,this.setupAssessment=null,this.setupTypePackAdoptions=null,this.snapshot={status:"opening",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={}){return this.requireBase().select(e,n)}clearSelection(e={}){this.requireBase().clearSelection(e)}forget(e){this.requireBase().forget(e)}authorize(e,n={}){return this.requireBase().authorize(e,n)}handleAuthorizationCallback(e,n){return this.requireBase().handleAuthorizationCallback(String(e),n)}completeAuthorization(e,n){return this.requireBase().handleAuthorizationCallback(e===void 0?At():String(e),n)}ensureCapabilities(e,n){let i=this.requireManifest().requirements?.capabilities,o=new Set([...i?.required??[],...i?.optional??[]]);return e.some(r=>!o.has(r))?Promise.resolve(O(k("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:[...o]}}]}}))):this.requireBase().ensureOperations(sa(e),n)}async applyCollectionSetup(e){if(this.snapshot.status!=="setup_review_required"||!this.setupAssessment)return O(k("collection_not_ready","There is no reviewed collection setup to apply."));if(!this.setupAssessment.applicable)return O(k("collection_not_ready","Resolve the collection setup conflicts before applying this update."));let n=this.connection();if(!n)return O(k("collection_not_ready","The collection is not ready."));let i=this.setupAssessment,o={...this.collectionSetupInput(this.setupTypePackAdoptions??void 0),expectedAssessmentDigest:i.assessmentDigest,expectedCollectionRevision:i.collectionRevision,expectedProvisionDigest:i.provisionDigest,allowTypePackDowngrades:i.typePacks.filter(s=>s.status==="downgrade").map(s=>s.desired.id)},r=ae(e,this.timeouts.requestMs),a={signal:r.signal,timeoutMs:null};try{let s=await n.applyCollectionSetup(o,a);return s.ok?(this.setupAssessment=null,this.setupTypePackAdoptions=null,await this.verifySetup(this.context(n),++this.verificationGeneration,a),I(this.snapshot)):s}finally{r.dispose()}}async refresh(e=!1,n){if(!this.base||!this.manifest)return;let i=this.base.getSnapshot();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}let r=this.context(i.connection);if(!r.capabilities.requiredAvailable||!ua(this.manifest,r.info)){this.publish({status:"authorization_required",...r});return}if(!(this.manifest.requirements?.capabilities?.required.includes("collection.setup.apply")??!1)){this.publish({status:"ready",verification:"verified",...r});return}let s=gn(this.manifest,i.collectionId);this.verificationStore.read(s)===Hi(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 a=this.collectionSetupInput(),s=i?await o.assessCollectionSetup(a,i):await o.assessCollectionSetup(a);if(n===this.verificationGeneration){if(!s.ok){this.publish({status:"blocked",problem:s.problem,...e});return}if(!s.value.applicable){let c=da(s.value);if(Object.keys(c).length>0){if(s=i?await o.assessCollectionSetup(this.collectionSetupInput(c),i):await o.assessCollectionSetup(this.collectionSetupInput(c)),n!==this.verificationGeneration)return;if(!s.ok){this.publish({status:"blocked",problem:s.problem,...e});return}this.setupTypePackAdoptions=c}}if(n===this.verificationGeneration){if(s.value.status!=="current"){this.setupAssessment=s.value,this.verificationStore.remove(gn(r,e.collectionId)),this.publish({status:"setup_review_required",update:la(s.value,r.provisions?.type_packs??[]),...e});return}this.verificationStore.write(gn(r,e.collectionId),Hi(r)),this.publish({status:"ready",verification:"verified",...e})}}}collectionSetupInput(e){let n=this.requireManifest(),i=this.requireApplication();return{applicationId:pa(i.family_identity),declarationDigest:`sha256:${i.manifest_digest}`,requirements:{configuration:n.requirements?.configuration??[]},provisions:{configuration:n.provisions?.configuration??[],typePacks:n.provisions?.type_packs??[]},...e?{typePackAdoptions:e}:{}}}context(e){let n=e.info();return{collectionId:e.collectionId,info:n,capabilities:gt(this.requireManifest().requirements.capabilities,this.requireManifest(),n),connections:this.connect.connections()}}publish(e){if(JSON.stringify(this.snapshot)!==JSON.stringify(e)){this.snapshot=e;for(let n of this.listeners)n()}}requireBase(){if(!this.base)throw new Error("Start the application session before using it.");return this.base}requireManifest(){if(!this.manifest)throw new Error("Start the application session before using it.");return this.manifest}requireApplication(){if(!this.application)throw new Error("Start the application session before using it.");return this.application}};function aa(t){return pt(t)}function sa(t){let e=t.flatMap(n=>ft(n));return[...new Set(e)]}function ca(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 la(t,e){let n=t.typePacks.map(r=>{let a=e.find(s=>s.manifest.id===r.desired.id);if(!a)throw new Error(`Collection setup returned undeclared type pack '${r.desired.id}'.`);return ca(a,r)}),i=t.configuration.filter(r=>r.action!=="current").length,o=t.status==="conflict"?"Existing collection policy conflicts with this application's required setup.":`This application requires ${i} configuration change${i===1?"":"s"} and ${n.length} definition update${n.length===1?"":"s"}.`;return{status:t.status,applicable:t.applicable,assessmentDigest:t.assessmentDigest,collectionRevision:t.collectionRevision,provisionDigest:t.provisionDigest,configuration:t.configuration,typePacks:n,canApply:t.applicable,reason:o}}function da(t){let e={};for(let n of t.typePacks){let i=Object.fromEntries(n.resources.filter(o=>o.action==="conflict"&&o.mode==="managed"&&o.currentDigest!==void 0&&o.installedDigest===void 0).map(o=>[o.target,o.currentDigest]));Object.keys(i).length>0&&(e[n.desired.id]=i)}return e}function gn(t,e){return`mdbase-application-session:v1:${t.id}:${e}`}function Hi(t){return JSON.stringify({capabilities:t.requirements?.capabilities,requirements:t.requirements?.configuration??[],provisions:t.provisions??{}})}function ua(t,e){return t.requirements?.access!=="full_collection"||e.scope.access==="full_collection"}function pa(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 fa(){return typeof localStorage<"u"?{read:t=>localStorage.getItem(t),write:(t,e)=>localStorage.setItem(t,e),remove:t=>localStorage.removeItem(t)}:new rt}function ee(t,e){return new Promise((n,i)=>{if(e?.aborted){i(e?.reason??new DOMException("Aborted","AbortError"));return}let o=()=>e?.removeEventListener("abort",a),r=setTimeout(()=>{o(),n()},t),a=()=>{clearTimeout(r),o(),i(e?.reason??new DOMException("Aborted","AbortError"))};e?.addEventListener("abort",a,{once:!0})})}var ha="mdbase-connect-identities",Ee="application-identities",_n=BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),ya=_n/2n,De=class{database=null;async create(e){let n=await $i(e),i=await this.open();return await Vi(i,o=>o.add(n)),n}async get(e){let n=await this.open();return await ma(n.transaction(Ee).objectStore(Ee).get(e))??null}async delete(e){let n=await this.open();await Vi(n,i=>i.delete(e))}open(){if(typeof indexedDB>"u")throw new _e("Persistent application identity requires browser IndexedDB or an injected identity store.");return this.database||(this.database=new Promise((e,n)=>{let i=indexedDB.open(ha,1);i.onupgradeneeded=()=>{i.result.objectStoreNames.contains(Ee)||i.result.createObjectStore(Ee,{keyPath:"handle"})},i.onerror=()=>n(i.error),i.onsuccess=()=>e(i.result)})),this.database}},qe=class{records=new Map;async create(e){if(this.records.has(e))throw new Error(`Application identity already exists: ${e}`);let n=await $i(e);return this.records.set(e,n),n}async get(e){return this.records.get(e)??null}async delete(e){this.records.delete(e)}},_e=class extends Error{constructor(e){super(e),this.name="ApplicationIdentityStoreError"}};async function Fe(t){return Zn(t.signingPublicKey)}async function at(t,e){if(t.installation_signing_public_key!==e.signingPublicKey||t.application_installation_id!==await Fe(e))throw new Error("Application authorization identity does not match its binding.");let n=_a(new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},e.signingPrivateKey,ei(t))));return{binding:t,signature:Gi(n)}}async function Ot(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 a=await t.get(i);if(a)return a;throw r}}async function $i(t){let e=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign","verify"]),n=Gi(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 ma(t){return new Promise((e,n)=>{t.onerror=()=>n(t.error),t.onsuccess=()=>e(t.result)})}function Vi(t,e){return new Promise((n,i)=>{let o=t.transaction(Ee,"readwrite");e(o.objectStore(Ee)).onerror=()=>i(o.error),o.onerror=()=>i(o.error),o.onabort=()=>i(o.error??new Error("Identity transaction aborted.")),o.oncomplete=()=>n()})}function ga(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 Gi(t){return btoa(String.fromCharCode(...t)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}function _a(t){if(t.byteLength!==64)throw new Error("Application authorization signature is invalid.");let e=ba(t.slice(32));if(e===0n||e>=_n)throw new Error("Application authorization signature is invalid.");return e<=ya?t:ga([t.slice(0,32),va(_n-e,32)])}function ba(t){return BigInt(`0x${Ca(t)}`)}function va(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 Ca(t){return[...t].map(e=>e.toString(16).padStart(2,"0")).join("")}function Wi(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 ze=class{constructor(e,n=vt){this.transport=e;this.requestTimeoutMs=n}transport;requestTimeoutMs;operation(e,n,i){return x(()=>this.transport.operation(e,n,i),ci)}async describe(e){let n=await this.rawOperation("describe",{},_t,e);return E(n,za)}async changes(e={},n){let i=await this.rawOperation("changes",e,bt,n);return E(i,Fa)}async read(e,n){let i=await this.envelopeOperation("read",wa(e),Y,n);return E(i,Tt)}async query(e={},n){let i=await this.envelopeOperation("query",Sa(e),li,n);return E(i,({results:o,meta:r})=>({results:o.map(ao),...r?{meta:{totalCount:r.total_count,hasMore:r.has_more,...r.snapshot?{snapshot:r.snapshot}:{}}}:{}}))}async*queryPages(e={},n={}){let{offset:i,limit:o,snapshot:r,...a}=e,s=Ua(i,0),c=eo(n.firstPageSize??o,200),d=eo(n.pageSize??o,1e3),p=r,u=0,f=0;for(;!n.signal?.aborted;){let h=await this.query({...a,offset:s,limit:f===0?c:d,...p?{snapshot:p}:{}},{signal:n.signal,timeoutMs:n.pageTimeoutMs});if(!h.ok){yield h;return}let _=h.value,m=_.meta?.snapshot;if(p&&m&&p!==m){yield O(k("query_snapshot_changed","The collection query snapshot changed while paging. Refresh the query before continuing."));return}!p&&m&&(p=m),u+=_.results.length;let w=!_.meta?.hasMore||_.results.length===0,y={results:_.results,..._.meta?{meta:_.meta}:{},page:f,offset:s,loaded:u,complete:w,...p?{snapshot:p}:{}};if(n.onProgress?.(y),yield I(y,h.diagnostics),w)return;s+=_.results.length,f+=1}}async queryAll(e={},n={}){let i=ae(n,this.requestTimeoutMs),o=[],r,a=[];try{for await(let s of this.queryPages(e,{firstPageSize:n.firstPageSize,pageSize:n.pageSize,signal:i.signal,pageTimeoutMs:null,onProgress:n.onProgress})){if(!s.ok)return s;let c=s.value;o.push(...c.results),r=c,a.push(...s.diagnostics)}if(i.signal.aborted)throw J(i.signal);return I({results:o,meta:{...r?.meta??{},totalCount:r?.meta?.totalCount??o.length,hasMore:r?!r.complete:!1,...r?.snapshot?{snapshot:r.snapshot}:{}}},a)}catch(s){if(s instanceof b)return O(s.problem);throw s}finally{i.dispose()}}async listViews(e){let n=await this.envelopeOperation("list_views",{},Y,e);return E(n,i=>({views:i.views,meta:{totalCount:i.meta.total_count}}))}async executeView(e,n){let i=await this.envelopeOperation("execute_view",e,Y,n);return E(i,Ma)}readViewSource(e,n){return this.envelopeOperation("read_view_source",e,Y,n)}createViewSource(e,n){return this.envelopeOperation("create_view_source",e,z,n)}updateViewSource(e,n){return this.envelopeOperation("update_view_source",bn(e),z,n)}deleteViewSource(e,n){return this.envelopeOperation("delete_view_source",bn(e),z,n)}async create(e,n){let i=await this.envelopeOperation("create",Ra(e),z,n);return E(i,Tt)}async update(e,n){let i=await this.envelopeOperation("update",Aa(e),z,n);return E(i,Tt)}async delete(e,n){let i=await this.envelopeOperation("delete",Yi(e),z,n);return E(i,io)}async preflightDelete(e,n){let i=await this.envelopeOperation("delete",{...Yi(e),check_backlinks:!0,dry_run:!0},z,n);return E(i,Ta)}async rename(e,n){let i=await this.envelopeOperation("rename",Ji(e),z,n);return E(i,ka)}async preflightRename(e,n){let i=await this.envelopeOperation("rename",{...Ji(e),dry_run:!0},z,n);return E(i,Ia)}validate(e={},n){return this.envelopeOperation("validate",e,Y,n)}readType(e,n){return this.envelopeOperation("read_type",e,re,n)}createType(e,n){return this.envelopeOperation("create_type",e,re,n)}updateType(e,n){return this.envelopeOperation("update_type",bn(e),re,n)}async assessTypePack(e,n){let i=await this.envelopeOperation("assess_type_pack",to(e),re,n);return E(i,Cn)}async applyTypePack(e,n){let i=await this.envelopeOperation("apply_type_pack",Pa(e),re,n);return E(i,Ea)}async assessCollectionSetup(e,n){let i=await this.envelopeOperation("assess_collection_setup",no(e),re,n);return E(i,Zi)}async applyCollectionSetup(e,n){let i=await this.envelopeOperation("apply_collection_setup",Oa(e),re,n);return E(i,o=>({assessment:Zi(o.assessment),receipt:Da(o.receipt)}))}async listTimers(e,n){let i=await this.rawOperation("list_timers",{namespace:e},Y,n);return E(i,o=>({namespace:o.namespace,timers:o.timers.map(vn)}))}async putTimer(e,n){let i=await this.rawOperation("put_timer",{namespace:e.namespace,criterion_id:e.criterionId,timer:Qi(e.timer)},z,n);return E(i,vn)}cancelTimer(e,n){return this.rawOperation("cancel_timer",e,z,n)}async reconcileTimers(e,n){let i=await this.rawOperation("reconcile_timers",{namespace:e.namespace,criterion_id:e.criterionId,timers:e.timers.map(Qi)},z,n);return E(i,o=>({namespace:o.namespace,timers:o.timers.map(vn),cancelledIds:o.cancelled_ids}))}async*watch(e={}){let n=e.cursor,i=Math.max(100,e.pollIntervalMs??1e3),o=Wi(e.retry),r=0,a=!1;for(e.onStatus?.({state:"connecting",...n===void 0?{}:{cursor:n}});!e.signal?.aborted;){let s=await this.changes(n===void 0?{}:{after:n,limit:200},{signal:e.signal,timeoutMs:e.timeoutMs});if(!s.ok){let p=s.problem;if(e.signal?.aborted)return;if(!o||p.recovery!=="retry"){yield s;return}if(a=!1,r+=1,o.maxAttempts!==void 0&&r>o.maxAttempts){yield s;return}let u=Math.min(o.maxDelayMs,Math.round(o.initialDelayMs*o.multiplier**(r-1)));e.onStatus?.({state:"reconnecting",...n===void 0?{}:{cursor:n},attempt:r,retryInMs:u,problem:p});try{await ee(u,e.signal)}catch{if(!e.signal?.aborted)throw l("operation_failed","Watch retry delay failed unexpectedly.")}continue}let c=s.value;if(n===void 0){n=c.cursor;continue}if(c.reset){let p=k("change_cursor_reset","The collection change cursor expired. Refresh collection state before subscribing again.");e.onStatus?.({state:"reset_required",cursor:n,problem:p}),yield O(p);return}let d=r>0;r=0,(!a||d)&&e.onStatus?.({state:"connected",cursor:n,recovered:d}),a=!0;for(let p of c.events)yield I(p);if(n=c.cursor,!c.hasMore)try{await ee(i,e.signal)}catch{if(!e.signal?.aborted)throw l("operation_failed","Watch polling delay failed unexpectedly.")}}}rawOperation(e,n,i,o){return x(()=>this.transport.operation(e,n,o),i)}async envelopeOperation(e,n,i,o){let r=await x(()=>this.transport.operation(e,n,o),i);if(!r.ok)return r;let a=r.value;return a.valid?I(a.result,a.diagnostics):O(Se(a))}};function E(t,e){return t.ok?I(e(t.value),t.diagnostics):t}function wa(t){return{path:t.path,...t.contract?{contract:t.contract}:{},...t.includeDocument===void 0?{}:{include_document:t.includeDocument}}}function Sa(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.snapshot?{snapshot:t.snapshot}:{},...t.includeBody===void 0?{}:{include_body:t.includeBody},...t.frontmatterMode?{frontmatter_mode:t.frontmatterMode}:{},...t.contract?{contract:t.contract}:{}}}function Ra(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 Aa(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 Yi(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 Ji(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 bn(t){let{ifRevision:e,...n}=t;return{...n,...e?{if_revision:e}:{}}}function to(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(oo)}:{}}}function Pa(t){return{...to(t),expected_assessment_digest:t.expectedAssessmentDigest,...t.allowDowngrade===void 0?{}:{allow_downgrade:t.allowDowngrade}}}function no(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(oo)}:{},...t.typePackAdoptions?{type_pack_adoptions:t.typePackAdoptions}:{}}}function Oa(t){return{...no(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 io(t){return{path:t.path,deleted:t.deleted,...t.broken_links?{brokenLinks:t.broken_links}:{}}}function Ta(t){return{...io(t),deleted:!1,dryRun:!0,wouldDelete:!0}}function ka(t){let{references_updated:e,...n}=t;return{...Tt(n),from:t.from,to:t.to,...e?{referencesUpdated:e}:{}}}function Ia(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 Qi(t){return{id:t.id,fire_at:t.fireAt,...t.data===void 0?{}:{data:t.data}}}function vn(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 oo(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 ro(t){return{id:t.id,version:t.version,digest:t.digest,type:t.type,implementationDigest:t.implementation_digest}}function ao(t){let{effective_frontmatter:e,contract:n,...i}=t;return{...i,...e===void 0?{}:{effectiveFrontmatter:e},...n?{contract:ro(n)}:{}}}function Tt(t){let{effective_frontmatter:e,contract:n,...i}=t;return{...i,effectiveFrontmatter:e,...n?{contract:ro(n)}:{}}}function Ma(t){return{results:t.results.map(e=>{let n=ao(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,view:t.meta.view,...t.meta.context?{context:t.meta.context}:{},...t.meta.groups?{groups:t.meta.groups}:{}}}}function Xi(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 kt(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 xa(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 Cn(t){return{status:t.status,applicable:t.applicable,assessmentDigest:t.assessment_digest,...t.current?{current:kt(t.current)}:{},desired:kt(t.desired),resources:t.resources.map(Xi),lock:t.lock,contractSetups:{choices:t.contract_setups.choices.map(xa),resources:t.contract_setups.resources.map(Xi)}}}function Ea(t){return{...Cn(t),receipt:kt(t.receipt),cleanupDeferred:t.cleanup_deferred}}function Zi(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,baselineDiagnosticCount:t.baseline_diagnostic_count,finalDiagnosticCount:t.final_diagnostic_count,resolvedDiagnosticCount:t.resolved_diagnostic_count,introducedDiagnosticCount:t.introduced_diagnostic_count,baselineDiagnosticDigest:t.baseline_diagnostic_digest,configuration:t.configuration,typePacks:t.type_packs.map(Cn),finalResourceRevisions:t.final_resource_revisions,assessmentDigest:t.assessment_digest}}function Da(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(kt),cleanupDeferred:t.cleanup_deferred}}function qa(t){return{cursor:t.cursor,type:t.type,occurredAt:t.occurred_at,payload:t.payload}}function Fa(t){return{events:t.events.map(qa),cursor:t.cursor,hasMore:t.has_more,reset:t.reset}}function za(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 Ua(t,e){return typeof t=="number"&&Number.isFinite(t)?Math.max(0,Math.floor(t)):e}function eo(t,e){return typeof t=="number"&&Number.isFinite(t)&&t>0?Math.floor(t):e}var It=class{constructor(e){this.context=e}context;async registerNotifications(e){return U(e,this.context.requestTimeoutMs,n=>this.registerNotificationsWithinBudget(e,n.signal))}async registerNotificationsWithinBudget(e,n){let i=await this.context.authorizedToken(n);if(!i)throw l("not_authorized","Connect this application before enabling notifications.");let r=(await this.context.register(n)).notifications?.criteria.map(y=>y.id)??[],a=[...new Set(e.criteria??r)],s=a.find(y=>!r.includes(y));if(s)throw l("notification_criterion_not_declared",`The application manifest does not declare notification criterion ${s}.`);if(a.length===0)throw l("notifications_not_declared","This application manifest does not declare any notification criteria.");let c=await Z(`${this.context.serverUrl}/v1/notifications/vapid-public-key`,{signal:n},"notifications_unavailable","Push notifications are unavailable."),d=await A(c,"invalid_operation_response","Connect returned an invalid notification key response.");if(!c.ok)throw T(d,"notifications_unavailable","Push notifications are unavailable.",c.status);let p=await e.serviceWorker.pushManager.getSubscription();p||(p=await e.serviceWorker.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Ii(d.public_key)}));let u=p.toJSON();if(!u.endpoint||!u.keys?.p256dh||!u.keys.auth)throw l("invalid_push_subscription","The browser returned an incomplete push subscription.");let f=M(this.context.storage.getItem(this.context.notificationKey())),h=e.installationId??f?.installationId??V(24),_=await Z(`${this.context.serverUrl}/v1/notifications/channels`,{method:"POST",headers:{authorization:`Bearer ${i.accessToken}`,"content-type":"application/json"},body:JSON.stringify({installation_id:h,criteria:a,subscription:{endpoint:u.endpoint,expirationTime:u.expirationTime??null,keys:u.keys}}),signal:n},"notification_registration_failed","Could not register push notifications."),m=await A(_,"invalid_operation_response","Connect returned an invalid notification registration response.");if(!_.ok)throw T(m,"notification_registration_failed","Could not register push notifications.",_.status);f?.channelId&&f.channelId!==m.channel_id&&fetch(`${this.context.serverUrl}/v1/notifications/channels/${f.channelId}`,{method:"DELETE",headers:{authorization:`Bearer ${i.accessToken}`},signal:n}).catch(()=>{});let w={channelId:m.channel_id,installationId:h,criteria:a};return this.context.storage.setItem(this.context.notificationKey(),JSON.stringify(w)),w}async registerNativeNotifications(e){return U(e,this.context.requestTimeoutMs,n=>this.registerNativeNotificationsWithinBudget(e,n.signal))}async registerNativeNotificationsWithinBudget(e,n){let i=await this.context.authorizedToken(n);if(!i)throw l("not_authorized","Connect this application before enabling notifications.");let o=await this.context.register(n);if(o.notifications?.native_delivery?.mode!=="managed_fcm")throw l("managed_fcm_not_declared","This application does not declare Connect-managed native notifications.");let r=o.notifications.criteria.map(_=>_.id),a=[...new Set(e.criteria??r)],s=a.find(_=>!r.includes(_));if(s)throw l("notification_criterion_not_declared",`The application manifest does not declare notification criterion ${s}.`);if(a.length===0)throw l("notifications_not_declared","This application manifest does not declare any notification criteria.");let c=this.context.notificationKey("fcm"),d=M(this.context.storage.getItem(c)),p=e.installationId??d?.installationId??V(24),u=await Z(`${this.context.serverUrl}/v1/notifications/channels`,{method:"POST",headers:{authorization:`Bearer ${i.accessToken}`,"content-type":"application/json"},body:JSON.stringify({installation_id:p,criteria:a,transport:"fcm",token:e.token}),signal:n},"notification_registration_failed","Could not register native notifications."),f=await A(u,"invalid_operation_response","Connect returned an invalid native notification response.");if(!u.ok)throw T(f,"notification_registration_failed","Could not register native notifications.",u.status);d?.channelId&&d.channelId!==f.channel_id&&this.deleteNotificationChannel(d.channelId,i.accessToken,n).catch(()=>{});let h={channelId:f.channel_id,installationId:p,transport:"fcm",criteria:a};return this.context.storage.setItem(c,JSON.stringify(h)),h}async unregisterNativeNotifications(e={}){return U(e,this.context.requestTimeoutMs,n=>this.unregisterNativeNotificationsWithinBudget(n.signal))}async unregisterNativeNotificationsWithinBudget(e){let n=this.context.notificationKey("fcm"),i=M(this.context.storage.getItem(n)),o=await this.context.authorizedToken(e);if(i?.channelId&&!o)throw l("not_authorized","Reconnect this application before disabling native notifications.");i?.channelId&&o&&await this.deleteNotificationChannel(i.channelId,o.accessToken,e),this.context.storage.removeItem(n)}async unregisterNotifications(e,n={}){return U(n,this.context.requestTimeoutMs,i=>this.unregisterNotificationsWithinBudget(e,i.signal))}async unregisterNotificationsWithinBudget(e,n){let i=M(this.context.storage.getItem(this.context.notificationKey())),o=await this.context.authorizedToken(n);if(i?.channelId&&!o)throw l("not_authorized","Reconnect this application before disabling push notifications.");if(i?.channelId&&o){let a=await Z(`${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(!a.ok&&a.status!==404){let s=await A(a,"invalid_operation_response","Connect returned an invalid notification response.");throw T(s,"notification_unregistration_failed","Could not unregister push notifications.",a.status)}}this.context.storage.removeItem(this.context.notificationKey()),await(await e?.pushManager.getSubscription())?.unsubscribe()}async deleteNotificationChannel(e,n,i){let o=await Z(`${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 A(o,"invalid_operation_response","Connect returned an invalid notification response.");throw T(r,"notification_unregistration_failed","Could not unregister push notifications.",o.status)}}};async function Mt(t,e,n,i,o,r){if(!t.authority)throw l("not_remote_authority","This authorization has no remote authority endpoint.");let a=n===""||n.startsWith("?")?n:`/${n}`,s=`${t.authority.filesUrl}${a}`,c=i===void 0?void 0:JSON.stringify(i),d=await r(t,e,s,c,t.authority.accessToken);return fetch(s,{method:e,redirect:"error",headers:{authorization:`Bearer ${t.authority.accessToken}`,...c===void 0?{}:{"content-type":"application/json"},...d},...c===void 0?{}:{body:c},...o?{signal:o}:{}})}async function so(t,e,n,i,o,r,a){let s=t,c=await Mt(s,e,n,i,o,a);if(c.status===401&&s.refreshToken){if(s=await r(),!s.authority||!s.fileCapability)throw l("authority_authorization_changed","Reconnect this collection before accessing its files.");c=await Mt(s,e,n,i,o,a)}let d=await A(c,"invalid_operation_response","The hosted authority returned an invalid file response.");if(!c.ok)throw T(d,"operation_failed","Collection file request failed.",c.status);return d}async function co(t,e,n,i,o,r){let a=t,s=await Mt(a,"GET",e,void 0,i,r);if(s.status===401&&a.refreshToken){if(a=await o(),!a.authority||!a.fileCapability)throw l("authority_authorization_changed","Reconnect this collection before accessing its files.");s=await Mt(a,"GET",e,void 0,i,r)}if(!s.ok){let d=await A(s,"invalid_operation_response","The hosted authority returned an invalid file range error response.");throw T(d,"operation_failed","Collection file range request failed.",s.status)}let c=s.headers.get("content-length");if(c===null||!/^(0|[1-9][0-9]*)$/u.test(c)||Number(c)!==n)throw await s.body?.cancel().catch(()=>{}),l("invalid_operation_response","The hosted file response declared an unexpected byte length.");if(!s.body)throw l("invalid_operation_response","The hosted file response did not contain a byte stream.");return s.body}var Na="mdbase-connect file chunk key v1",xt=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,te=class extends Error{constructor(n,i){super(i);this.code=n;this.name="FileTransferCryptoError"}code},Ue=class t{constructor(e,n){this.binding=e;this.key=n}binding;key;static async open(e,n,i){lo(i);let o=await e.get(n);if(!o||o.agreementPublicKey!==i.encryption.application_agreement_public_key)throw new R("missing_grant_key","The encrypted grant key is unavailable or does not match the file transfer grant.");let r=await Ze(o.agreementPrivateKey,i.encryption.connector_agreement_public_key);return t.fromSharedSecret(r,i)}static async fromSharedSecret(e,n){lo(n);let i=await wn(e,n);return new t(n,i)}async encryptChunk(e,n,i){if(this.validateHeader(n),i.byteLength!==n.plaintext_length)throw new te("plaintext_length_mismatch","File chunk plaintext length does not match its authenticated header.");let o=dt(e,n),r=await crypto.subtle.encrypt({name:"AES-GCM",iv:uo(n.chunk_index),additionalData:Et(o),tagLength:128},this.key,Et(i));return Bn({kind:e,header:n,payload:new Uint8Array(r)})}async decryptChunk(e){let n=ut(e);this.validateHeader(n.header);let i=dt(n.kind,n.header);try{let o=await crypto.subtle.decrypt({name:"AES-GCM",iv:uo(n.header.chunk_index),additionalData:Et(i),tagLength:128},this.key,Et(n.payload));return new Uint8Array(o)}catch{throw new te("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 te("header_binding_mismatch","The file frame does not match its transfer encryption binding.")}};async function wn(t,e){let n=new TextEncoder().encode(La(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(Na)},o,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}function lo(t){if(X(t.encryption),!xt.test(t.grantId)||!xt.test(t.applicationId)||!xt.test(t.authorityId)||!xt.test(t.transferId)||t.direction!=="upload"&&t.direction!=="download")throw new te("invalid_binding","The file transfer encryption binding is invalid.")}function La(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 uo(t){if(!Number.isSafeInteger(t)||t<0)throw new te("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 Et(t){return Uint8Array.from(t).buffer}var qt=8,Sn=10;function Ft(t){return t instanceof b&&t.code==="connector_busy"}async function po(t){if(!Ft(t.error)||t.completedRetries>=qt)return{retried:!1};try{await zt(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 Ne(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 zt(t,e){return ho(yo(50,800,t),e)}function fo(t,e){return ho(yo(100,1e3,t-1),e)}async function ho(t,e){try{await ee(t,e)}catch(n){throw e?.aborted?e.reason instanceof b?e.reason:l("operation_cancelled","The operation was cancelled while waiting for connector capacity.",{operationOutcome:"not_sent",cause:n}):n}}function yo(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 Nt=class{constructor(e){this.options=e}options;async control(e,n,i,o,r){return this.controlAttempt(e,n,i,o,r,!1,0)}async controlAttempt(e,n,i,o,r,a,s){Le(e);let c=$a(n,i,o),d=await this.encryptControl(e,c),p,u=await this.options.shouldAttemptDirect(e);if(u){try{p=await fetch(`${this.options.loopbackUrl}/v1/files/control`,ce({method:"POST",headers:{"content-type":"application/mdbase-connect+json"},body:JSON.stringify(d),signal:r}))}catch(f){if(r?.aborted)throw f;this.options.onDirectUnavailable()}if(p&&(!ke(p.status)||await Ne(p)))return p.ok&&this.options.onDirectAvailable(),this.decryptControlResponse(e,n,i,o,r,d,p,a,s);p&&this.options.onDirectUnavailable()}return u&&n==="GET"&&(e=e.expiresAt>Date.now()+3e4?e:await this.options.refreshAuthorization(r),Ut(e),d=await this.encryptControl(e,c)),p=await this.sendRelayControl(e,d,r),await ja(p,e)&&(e=await this.options.refreshAuthorization(r),Ut(e),d=await this.encryptControl(e,c),p=await this.sendRelayControl(e,d,r)),p.ok&&this.options.onRelayAvailable(),this.decryptControlResponse(e,n,i,o,r,d,p,a,s)}async decryptControlResponse(e,n,i,o,r,a,s,c,d){let p=await A(s,"invalid_operation_response","The collection authority returned an invalid file control response.");if(!s.ok){let h=T(p,"operation_failed","Collection file request failed.",s.status);if(Ft(h)&&d<qt)return await zt(d,r),this.controlAttempt(e,n,i,o,r,c,d+1);if(h.code==="fresh_request_required"&&n==="GET"&&!c)return this.controlAttempt(e,n,i,o,r,!0,d);throw h}let u=p?.envelope;if(!u)throw l("invalid_encrypted_response","The connector omitted its encrypted file response.");let f=await Te(this.options.keyStore,e.keyHandle,Rn(e),a,u);if(!f.ok&&f.problem.code==="fresh_request_required"&&n==="GET"&&!c)return this.controlAttempt(e,n,i,o,r,!0,d);if(!f.ok){let h=Va(f.problem);if(Ft(h)&&d<qt)return await zt(d,r),this.controlAttempt(e,n,i,o,r,c,d+1);throw h}return f.result}async uploadChunk(e,n,i,o){let a=await this.localFileToken(e,"upload",o),s=await mo(this.options.keyStore,a,e,n,i),c;if(await this.options.shouldAttemptDirect(a)){try{c=await fetch(`${this.options.loopbackUrl}/v1/files/upload`,ce(go(s,o)))}catch(d){if(o?.aborted)throw d;this.options.onDirectUnavailable()}if(c&&(!ke(c.status)||await Ne(c)))return c.ok&&this.options.onDirectAvailable(),Ba(c,"Encrypted file chunk upload failed.");c&&this.options.onDirectUnavailable()}if(c=await this.sendRelayUpload(a,s,o),c.status===401&&a.refreshToken&&(a=await this.options.refreshAuthorization(o),Ut(a),s=await mo(this.options.keyStore,a,e,n,i),c=await this.sendRelayUpload(a,s,o)),!c.ok){let d=await A(c,"invalid_operation_response","The collection authority returned an invalid file upload response.");throw T(d,"operation_failed","Encrypted file chunk upload failed.",c.status)}this.options.onRelayAvailable()}async downloadChunk(e,n,i){let o=await this.localFileToken(e,"download",i),r;if(await this.options.shouldAttemptDirect(o)){try{r=await fetch(`${this.options.loopbackUrl}/v1/files/download/${encodeURIComponent(o.grantId)}/${encodeURIComponent(e.transfer_id)}/${n}`,ce({method:"GET",signal:i}))}catch(a){if(i?.aborted)throw a;this.options.onDirectUnavailable()}if(r&&(!ke(r.status)||await Ne(r)))return r.ok&&this.options.onDirectAvailable(),this.decryptDownloadResponse(o,e,n,r);r&&this.options.onDirectUnavailable()}return r=await this.sendRelayDownload(o,e,n,i),r.status===401&&o.refreshToken&&(o=await this.options.refreshAuthorization(i),Ut(o),r=await this.sendRelayDownload(o,e,n,i)),r.ok&&this.options.onRelayAvailable(),this.decryptDownloadResponse(o,e,n,r)}async decryptDownloadResponse(e,n,i,o){if(!o.ok){let s=await A(o,"invalid_operation_response","The collection authority returned an invalid file download response.");throw T(s,"operation_failed","Encrypted file chunk download failed.",o.status)}if(o.headers.get("content-type")?.split(";",1)[0]!=="application/mdbase-connect-file")throw l("invalid_operation_response","The connector returned an invalid file response media type.");let r=new Uint8Array(await o.arrayBuffer()),a;try{Ha(n,i,r),a=await(await bo(this.options.keyStore,e,n)).decryptChunk(r)}catch(s){throw s instanceof b?s:l("invalid_operation_response","The connector returned an invalid encrypted file frame.",{cause:s})}if(a.byteLength!==An(n,i))throw l("invalid_operation_response","The connector returned a truncated file chunk.");return a}encryptControl(e,n){return Le(e),Q(this.options.keyStore,e.keyHandle,Rn(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`,{...go(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);if(!o||o.authority||!o.fileCapability||!o.encryption||!o.grantId||!o.keyHandle||e.direction!==n||e.protection!=="grant_aead_v1")throw l("not_authorized","This connection cannot use encrypted local file delivery.");return Lt(e),o}};function Ut(t){if(t.authority||!t.fileCapability)throw l("not_authorized","This connection cannot use encrypted local file delivery.");Le(t)}async function mo(t,e,n,i,o){let r=Ka(e,n,i,o.byteLength);return(await bo(t,e,n)).encryptChunk("upload_chunk",r,o)}function go(t,e){return{method:"POST",headers:{"content-type":"application/mdbase-connect-file"},body:Uint8Array.from(t).buffer,signal:e}}async function Ba(t,e){if(t.ok)return;let n=await A(t,"invalid_operation_response","The collection authority returned an invalid file transfer response.");throw T(n,"operation_failed",e,t.status)}async function ja(t,e){return e.refreshToken?t.status===401?!0:t.status!==409?!1:(await A(t.clone(),"invalid_operation_response","The collection authority returned an invalid file response.").catch(()=>null))?.error?.code==="encryption_binding_stale":!1}function Le(t){if(!t.encryption||!t.grantId||!t.keyHandle)throw l("missing_grant_key","Reconnect this application to restore encrypted file access.")}function Rn(t){return Le(t),{grantId:t.grantId,applicationId:t.clientId,encryption:t.encryption}}function bo(t,e,n){return Le(e),Ue.open(t,e.keyHandle,{...Rn(e),authorityId:e.encryption.connector_id,transferId:n.transfer_id,direction:n.direction})}function Ka(t,e,n,i){Le(t);let o=Lt(e),r=An(e,n);if(i!==r)throw l("invalid_request","The file chunk has the wrong byte length.");return{protocol_version:1,protection:"grant_aead_v1",grant_id: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 Ha(t,e,n){let i=ut(n),o=An(t,e),r=Lt(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 l("invalid_operation_response","The connector returned a file frame for a different chunk.")}function Va(t){return F(t.code==="unknown"?t.server_code:t.code,t.message,{details:t.details,operationOutcome:t.operation_outcome??"rejected",traceId:t.trace_id})}function $a(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 _o("get_file_transfer_status",i[1]);if(t==="DELETE"&&i.length===2&&i[0]==="transfers")return _o("abort_file_transfer",i[1]);if(t==="POST"&&Ga(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 l("invalid_request","The file control request path is invalid.")}function _o(t,e){return{protocol_version:1,type:t,transfer_id:decodeURIComponent(e)}}function Lt(t){if(t.strategy.kind!=="framed_chunks"||!Number.isSafeInteger(t.strategy.chunk_size)||t.strategy.chunk_size<=0)throw l("invalid_operation_response","The connector returned an invalid framed transfer strategy.");return t.strategy.chunk_size}function An(t,e){let n=Lt(t);if(!Number.isSafeInteger(e)||e<0||!Number.isSafeInteger(t.total_size)||t.total_size<0)throw l("invalid_request","The file chunk index is invalid.");let i=e*n;if(!Number.isSafeInteger(i)||i>=t.total_size)throw l("invalid_request","The file chunk index is outside the transfer.");return Math.min(n,t.total_size-i)}function Ga(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var Bt=class{constructor(e){this.options=e;this.local=new Nt(e)}options;local;async control(e,n="",i,o){let r=await this.requireFileToken(o);return r.authority?so(r,e,n,i,o,this.options.refreshAuthorization,this.options.authorityProofHeaders):this.local.control(r,e,n,i,o)}uploadChunk(e,n,i,o){return this.local.uploadChunk(e,n,i,o)}downloadChunk(e,n,i){return this.local.downloadChunk(e,n,i)}async downloadHostedPart(e,n,i,o){let r=await this.requireFileToken(o);if(!r.authority)throw l("not_remote_authority","Hosted file delivery requires a remote authority endpoint.");return co(r,`downloads/${encodeURIComponent(e.transfer_id)}/parts/${n}`,i,o,this.options.refreshAuthorization,this.options.authorityProofHeaders)}async requireFileToken(e){let n=await this.options.authorizedToken(e);if(!n?.fileCapability)throw l("not_authorized","This connection has no file capability.");return n}};async function Be(t,e,n,i,o,r){if(!e.authority?.proofPublicKey)return{};if(!e.keyHandle)throw l("missing_grant_key","Reconnect this application to restore remote authority request signing.");try{let a=new URL(i);return await Ct(t,e.keyHandle,e.authority.proofPublicKey,{method:n,target:`${a.pathname}${a.search}`,body:o,credential:r})}catch(a){throw a instanceof R?F(a.code,a.message):a}}var jt=class{constructor(e,n){this.storage=e;this.baseKey=n}storage;baseKey;list(e){if(!e)return[];let n=M(this.storage.getItem(this.baseKey));if(vo(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=>M(this.storage.getItem(o))).filter(o=>vo(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??oe(e.operation,e.request?.input??(e.operation==="sync"?{action:"mutate"}:{}))??(e.operation==="sync"?"sync:mutate":e.operation)}store(e){this.storage.setItem(this.key(e.requestId),JSON.stringify(e))}take(e){let n=this.key(e),i=M(this.storage.getItem(n));return this.storage.removeItem(n),i}key(e){return`${this.baseKey}:${encodeURIComponent(e)}`}};function vo(t){return!!(t&&typeof t.collectionId=="string"&&typeof t.requestId=="string"&&t.requestId.length>0&&jn(t.operation)&&typeof t.inputFingerprint=="string"&&Number.isFinite(t.createdAt)&&t.createdAt>0&&(t.envelope||t.request)&&(t.operation==="sync"||oe(t.operation,t.request?.input??{})!==null))}function Co({stored:t,collectionId:e,relayEncryption:n,invalidate:i,directCapable:o}){let r=M(t),a=s=>(i(typeof s=="string"?s:void 0),null);if(!r)return t&&a(),null;if(r.version!==1||typeof r.accessToken!="string"||r.accessToken.length===0||typeof r.clientId!="string"||r.clientId.length===0||r.collectionId!==e||typeof r.collectionName!="string"||r.collectionName.length===0||!Array.isArray(r.operations)||r.operations.some(s=>typeof s!="string")||typeof r.expiresAt!="number"||!Number.isFinite(r.expiresAt)||r.refreshToken!==void 0&&(typeof r.refreshToken!="string"||r.refreshToken.length===0)||r.refreshExpiresAt!==void 0&&(typeof r.refreshExpiresAt!="number"||!Number.isFinite(r.refreshExpiresAt))||!Rt(r.scope)||r.fileCapability&&!St(r.fileCapability)||r.authority&&!xi(r.authority,r.collectionId))return a(r.keyHandle);if(n==="required"){if(r.authority){if(!r.keyHandle||!r.authority.proofPublicKey)return a(r.keyHandle)}else if(!r.grantId||!r.keyHandle||!Ei(r.encryption,r.collectionId))return a(r.keyHandle)}return r.expiresAt<=Date.now()&&(!r.refreshToken||(r.refreshExpiresAt??0)<=Date.now())?o(r)?r:(i(r.keyHandle),null):r}async function Pn(t,e,n,i,o,r){if(!e.authority)throw l("not_remote_authority","This authorization has no remote authority endpoint.");let a=`${e.authority.syncUrl}/${i}`,s=o===void 0?void 0:JSON.stringify(o),c=await Be(t,e,n,a,s,e.authority.accessToken);return fetch(a,{method:n,headers:{authorization:`Bearer ${e.authority.accessToken}`,...o===void 0?{}:{"content-type":"application/json"},...c},...s===void 0?{}:{body:s},signal:r})}async function wo(t,e,n,i,o){if(!e.encryption||!e.grantId||!e.keyHandle)throw l("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 Q(t,e.keyHandle,{grantId:e.grantId,applicationId:e.clientId,encryption:e.encryption},n,i,void 0,o)}catch(r){throw r instanceof R?F(r.code,r.message):r}}function So(t,e){return!t||t.authority||!t.encryption||!t.grantId||!t.keyHandle||e==="disabled"?!1:typeof location>"u"||!t.applicationOrigin||t.applicationOrigin===location.origin}async function Ro(t,e,n){try{let i=await fetch(`${t}/v1/ready`,ce({method:"GET",cache:"no-store",signal:n})),o=await A(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}catch{return!1}}var Kt=class{serverUrl;storage;keyStore;directAccessMode;loopbackUrl;collectionId;internals;onChange;timeouts;pendingMutationStore;files;refreshPromise=null;directStatus;currentRoute="relay";directFailures=0;directRetryAt=0;constructor(e){this.serverUrl=e.serverUrl,this.storage=e.storage,this.keyStore=e.keyStore,this.directAccessMode=e.directAccessMode,this.loopbackUrl=e.loopbackUrl,this.collectionId=e.collectionId,this.internals=e.internals,this.onChange=e.onChange,this.timeouts=e.timeouts,this.pendingMutationStore=new jt(this.storage,this.internals.pendingMutationKey(this.collectionId)),this.files=new Bt({keyStore:this.keyStore,serverUrl:this.serverUrl,loopbackUrl:this.loopbackUrl,authorizedToken:n=>this.authorizedToken({signal:n,timeoutMs:null}),refreshAuthorization:n=>this.refreshAuthorization(n),shouldAttemptDirect:n=>this.shouldAttemptDirect(n),onDirectAvailable:()=>{this.markDirectAvailable(),this.setRoute("direct")},onDirectUnavailable:()=>this.markDirectUnavailable(),onRelayAvailable:()=>this.setRoute("relay"),authorityProofHeaders:(n,i,o,r,a)=>Be(this.keyStore,n,i,o,r,a)}),this.directStatus=this.directAccessMode==="disabled"?"disabled":"unavailable"}get directAccess(){return this.currentToken()?.authority?"disabled":this.directStatus}get route(){return this.currentToken()?.authority?"remote":this.currentRoute}notifyStorageChanged(){this.emitConnection()}async checkDirectAccess(e={}){return U(e,this.timeouts.watchStartMs,n=>this.checkDirectAccessWithinBudget(n.signal))}async checkDirectAccessWithinBudget(e){let n=this.currentToken();if(!this.directEligible(n))return this.setDirectStatus("disabled");let i=await et();return i==="denied"?this.setDirectStatus("denied"):(i==="prompt"||i===null)&&this.storage.getItem(this.internals.directPreferenceKey())!=="enabled"?this.setDirectStatus("permission_required"):this.probeDirectAccess(e)}async requestDirectAccess(e={}){return U(e,this.timeouts.watchStartMs,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=>({requestId:e.requestId,operation:this.pendingMutationStore.identifier(e),fingerprint:e.inputFingerprint,status:"outcome_unknown",createdAt:new Date(e.createdAt).toISOString()}))}pendingMutation(e){let n=this.storedPendingMutation(e);return n?{requestId:n.requestId,operation:this.pendingMutationStore.identifier(n),fingerprint:n.inputFingerprint,status:"outcome_unknown",createdAt:new Date(n.createdAt).toISOString()}:null}async recoverPendingMutation(e,n){let i=this.storedPendingMutation(e);if(!i)throw l("no_pending_mutation","There is no interrupted mutation to resume.");return B(n,this.timeouts.requestMs,o=>this.performOperationWithinBudget(i.operation,i.request?.input??{},{...n,signal:o.signal},i))}async performOperation(e,n,i={}){return B(i,this.timeouts.requestMs,o=>this.performOperationWithinBudget(e,n,di(i,o)))}async performOperationWithinBudget(e,n,i,o,r=!1,a=0,s=!1){me(i.signal);let c=this.currentToken();if(!c)throw l("not_authorized","Connect this application before accessing a collection.");if(!c.operations.includes(e))throw l("insufficient_access",`This connection does not allow ${e}.`,{details:{required_operations:[e],granted_operations:[...c.operations],missing_operations:[e]}});let d=await this.shouldAttemptDirect(c);if(!d&&(c=await this.authorizedToken({signal:i.signal,timeoutMs:null}),!c))throw l("not_authorized","Reconnect this application to continue.");let p=o?.requestId??(wi(e,n)?crypto.randomUUID():void 0),u;try{u=await this.sendOperation(c,e,n,d,i,p,s)}catch(y){throw wt(y,i.signal,p!==void 0&&this.storedPendingMutation(p)!==null?p:void 0,c.authority?"hosted_provider_unavailable":"relay_unavailable")}let f=u.response,h=f.status===409&&(await A(f.clone(),"invalid_operation_response","The collection authority returned an invalid operation response.").catch(()=>null))?.error?.code==="encryption_binding_stale";if((f.status===401||h)&&c.refreshToken){if(u.pendingMutation&&(u.directDeliveryUncertain||u.encryptedRequest&&u.resumingMutation))throw l("operation_outcome_unknown","The direct operation may have completed, but its encrypted grant changed before the response could be recovered. Refresh before making another change.",{operationOutcome:"unknown",details:{request_id:u.requestId}});u.pendingMutation&&this.clearPendingMutation(u.requestId),c=await this.refreshAuthorization(i.signal),d=await this.shouldAttemptDirect(c);try{u=await this.sendOperation(c,e,n,d,i,p,s)}catch(y){throw wt(y,i.signal,p!==void 0&&this.storedPendingMutation(p)!==null?p:void 0,c.authority?"hosted_provider_unavailable":"relay_unavailable")}f=u.response}let _=y=>po({error:y,attempt:u,completedRetries:a,signal:i.signal,knownRejectedMutationRetry:s,clearPending:v=>this.clearPendingMutation(v),retry:(v,N)=>this.performOperationWithinBudget(e,n,i,v,r,a+1,N)}),m;try{m=await A(f,"invalid_operation_response","The collection authority returned a response that is not valid JSON.")}catch(y){throw u.pendingMutation?j(u.requestId,y):l("invalid_operation_response","The collection authority returned a response that is not valid JSON.",{cause:y})}if(!f.ok){let y=T(m,"operation_failed","Collection operation failed.",f.status),v=await _(y);if(v.retried)return v.result;if(y.code==="fresh_request_required"&&!u.pendingMutation&&!r)return this.performOperationWithinBudget(e,n,i,void 0,!0);throw u.pendingMutation&&(u.directDeliveryUncertain||u.encryptedRequest&&u.resumingMutation)?j(u.requestId,y):(u.pendingMutation&&!u.directDeliveryUncertain&&this.clearPendingMutation(u.requestId),y.code==="direct_operation_rejected"&&y.status===403&&this.invalidateRejectedAuthorization(c),y)}if(u.encryptedRequest){let y=m?.envelope,v=u.pendingMutationRecord,N=v?.encryption??c.encryption,P=v?.grantId??c.grantId,q=v?.applicationId??c.clientId,S=v?.keyHandle??c.keyHandle;if(!y||!N||!P||!S)throw u.pendingMutation?j(u.requestId,new Error("Encrypted operation response was missing its envelope.")):l("invalid_encrypted_response","The relay did not return an encrypted connector response.");try{let g=await Te(this.keyStore,S,{grantId:P,applicationId:q,encryption:N},u.encryptedRequest,y);if(!g.ok&&g.problem.code==="fresh_request_required"&&!u.pendingMutation&&!r)return this.performOperationWithinBudget(e,n,i,void 0,!0);if(u.pendingMutation&&this.clearPendingMutation(u.requestId),!g.ok)throw F(g.problem.code==="unknown"?g.problem.server_code:g.problem.code,g.problem.message,{details:g.problem.details,operationOutcome:g.problem.operation_outcome??"rejected",traceId:g.problem.trace_id});return g.result}catch(g){throw g instanceof b?g:g instanceof R?u.pendingMutation?j(u.requestId,g):F(g.code,g.message):g}}let w=u.pendingMutationRecord?.request?.protocol_version??L;if(m?.protocol_version!==w||m?.request_id!==u.requestId)throw u.pendingMutation?j(u.requestId,new Error("Operation response protocol or request ID did not match.")):l("invalid_operation_response","The collection authority returned a response for a different protocol request.");if(m.ok===!1){if(!Ve(m.problem))throw u.pendingMutation?j(u.requestId,new Error("Operation rejection did not contain a canonical problem.")):l("invalid_operation_response","The collection authority returned an invalid operation problem.");let y=new b(m.problem),v=await _(y);if(v.retried)return v.result;throw u.pendingMutation&&this.clearPendingMutation(u.requestId),y}if(m.ok!==!0||!("result"in m))throw u.pendingMutation?j(u.requestId,new Error("Successful operation response did not contain a result.")):l("invalid_operation_response","The collection authority returned an incomplete operation response.");return u.pendingMutation&&this.clearPendingMutation(u.requestId),m.result}async performAuthoritySyncRequest(e,n,i,o,r,a={}){return B(a,this.timeouts.syncMs,async s=>{let c=await this.authorizedToken({signal:s.signal,timeoutMs:null});if(!c?.authority||c.collectionId!==e||c.authority.replicaId!==n)throw l("authority_authorization_changed","Reconnect this collection authority before synchronizing.");try{let d=await Pn(this.keyStore,c,i,o,r,s.signal);if(d.status===401&&c.refreshToken){if(c=await this.refreshAuthorization(s.signal),!c.authority||c.collectionId!==e||c.authority.replicaId!==n)throw l("authority_authorization_changed","Reconnect this collection authority before synchronizing.");d=await Pn(this.keyStore,c,i,o,r,s.signal)}let p=await A(d,"invalid_operation_response","The collection authority returned an invalid synchronization response.");if(!d.ok)throw T(p,"sync_failed","Collection synchronization failed.",d.status);return p}catch(d){let p=i==="POST"&&o==="mutations"&&r&&typeof r=="object"&&typeof r.mutation_id=="string"?r.mutation_id:void 0;throw wt(d,s.signal,p,"hosted_provider_unavailable")}})}async sendOperation(e,n,i,o,r={},a,s=!1){let c=i??{},d,p=!1,u=!1,f=a??crypto.randomUUID(),h=null,_;if(a!==void 0){if(h=this.storedPendingMutation(a),_=h?.inputFingerprint??await Ti(n,i),h){if(h.collectionId!==e.collectionId||h.operation!==n||h.inputFingerprint!==_)throw l("pending_mutation_unresolved","A previous write still has an unknown outcome. Retry that exact write before making another change.");f=h.requestId,u=!s}p=!0}let m=h?.mutation??oe(n,i);if(h?.envelope&&(e.authority||!e.encryption))throw l("pending_mutation_unresolved","The pending write requires its encrypted relay authority. Reconnect that authority before recovery.");if(h?.request&&e.encryption&&!e.authority)throw l("pending_mutation_unresolved","The pending write belongs to a different authority transport. Reconnect that authority before recovery.");if(e.encryption&&!e.authority){if(!e.grantId||!e.keyHandle)throw l("missing_grant_key","Reconnect this application to restore encrypted access.");try{if(p)if(h){if(!h.envelope)throw l("pending_mutation_unresolved","The pending write belongs to a different transport. Reconnect before retrying it.");d=h.envelope}else d=await Q(this.keyStore,e.keyHandle,{grantId:e.grantId,applicationId:e.clientId,encryption:e.encryption},n,i,f,r.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:m,inputFingerprint:_,requestId:f,envelope:d,createdAt:Date.now()});else d=await Q(this.keyStore,e.keyHandle,{grantId:e.grantId,applicationId:e.clientId,encryption:e.encryption},n,i,void 0,r.deadlineUnixMs)}catch(P){throw P instanceof R?F(P.code,P.message):P}f=d.request_id,c=d}else{let P=h?.request??{protocol_version:L,request_id:f,input:c};c=P,p&&!h&&this.pendingMutationStore.store({collectionId:e.collectionId,...e.grantId?{grantId:e.grantId}:{},operation:n,mutation:m,inputFingerprint:_,requestId:f,request:P,createdAt:Date.now()})}if(o&&d&&!e.authority){let P=!1;try{let g=await fetch(`${this.loopbackUrl}/v1/operations`,ce({method:"POST",headers:{"content-type":"application/mdbase-connect+json"},body:JSON.stringify(d),signal:r.signal}));if(!ke(g.status)||await Ne(g))return g.ok&&(this.markDirectAvailable(),this.setRoute("direct")),{response:g,requestId:f,encryptedRequest:d,pendingMutation:p,...p?{pendingMutationRecord:h??this.storedPendingMutation(f)??void 0}:{},resumingMutation:u};P=g.status>=500,this.markDirectUnavailable()}catch(g){if(r.signal?.aborted)throw g;P=!0,await et()==="denied"?this.setDirectStatus("denied"):this.markDirectUnavailable()}let q;try{q=e.expiresAt>Date.now()+3e4?e:await this.refreshAuthorization(r.signal)}catch(g){throw p&&(P||u)?j(f,g):g}let S;p||(d=await wo(this.keyStore,q,n,i,r.deadlineUnixMs),f=d.request_id);try{S=await fetch(`${this.serverUrl}/v1/authorities/${encodeURIComponent(q.collectionId)}/operations/${n}`,{method:"POST",headers:{authorization:`Bearer ${q.accessToken}`,"content-type":"application/json"},body:JSON.stringify(d),signal:r.signal})}catch(g){throw p&&(P||u)?j(f,g):g}return S.ok&&this.setRoute("relay"),{response:S,requestId:f,encryptedRequest:d,directDeliveryUncertain:P,pendingMutation:p,...p?{pendingMutationRecord:h??this.storedPendingMutation(f)??void 0}:{},resumingMutation:u}}let w=e.authority?`${e.authority.operationsUrl}/${n}`:`${this.serverUrl}/v1/authorities/${encodeURIComponent(e.collectionId)}/operations/${n}`,y=JSON.stringify(c),v=e.authority?await Be(this.keyStore,e,"POST",w,y,e.authority.accessToken):{},N=await fetch(w,{method:"POST",headers:{authorization:`Bearer ${e.authority?.accessToken??e.accessToken}`,"content-type":"application/json",...v},body:y,signal:r.signal});return N.ok&&this.setRoute(e.authority?"remote":"relay"),{response:N,requestId:f,encryptedRequest:d,pendingMutation:p,...p?{pendingMutationRecord:h??this.storedPendingMutation(f)??void 0}:{},resumingMutation:u}}directCapable(e){return So(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 et();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){return this.setDirectStatus("checking"),await Ro(this.loopbackUrl,L,e)?(this.markDirectAvailable(),"available"):await et()==="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=M(this.storage.getItem(this.internals.tokenKey(this.collectionId)));!n||!Si(n,e)||(this.internals.removeToken(this.collectionId,n.keyHandle),this.currentRoute="relay",this.directStatus=this.directAccessMode==="disabled"?"disabled":"unavailable",this.emitConnection())}currentToken(){return Co({stored:this.storage.getItem(this.internals.tokenKey(this.collectionId)),collectionId:this.collectionId,relayEncryption:this.internals.relayEncryption,invalidate:e=>this.internals.removeToken(this.collectionId,e,"invalid_stored_grant"),directCapable:e=>this.directCapable(e)})}async authorizedToken(e={}){let 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 l("relay_authorization_expired","Direct access is still available on this computer, but using the relay requires reconnecting this application.");return this.internals.removeToken(this.collectionId,n.keyHandle),null}return this.refreshAuthorization(e.signal)}refreshAuthorization(e){return this.refreshPromise?this.refreshPromise:(this.refreshPromise=this.performRefresh(e).finally(()=>{this.refreshPromise=null}),this.refreshPromise)}async performRefresh(e){let n=this.currentToken();if(!n?.refreshToken)throw l("not_authorized","Reconnect this application to continue.");if((n.refreshExpiresAt??0)<=Date.now())throw l("relay_authorization_expired","Direct access is still available on this computer, but using the relay requires reconnecting this application.");let i=n.refreshToken,o=`${this.serverUrl}/oauth/token`,r=new URLSearchParams({grant_type:"refresh_token",refresh_token:n.refreshToken,client_id:n.clientId}).toString(),a=n.authority?await Be(this.keyStore,n,"POST",o,r,n.refreshToken):{},s=await fetch(o,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",...a},body:r,signal:e}),c=await A(s,"invalid_token_response","The authorization service returned an invalid token response.");if(!s.ok){let d=this.currentToken();if(d?.refreshToken&&d.refreshToken!==i)return d;throw this.directCapable(n)||this.internals.removeToken(this.collectionId,n.keyHandle),(nt(c)??c?.error?.code)==="invalid_grant"?l("authorization_expired",c?.error_description??c?.error?.message??"Reconnect this application to continue.",{status:s.status}):T(c,"authorization_expired","Reconnect this application to continue.",s.status)}return this.storeTokenResponse(c,n.clientId,n.keyHandle)}storeTokenResponse(e,n,i){if(e.collection_id!==this.collectionId)throw l("collection_mismatch","The refreshed authorization belongs to a different collection.");let o=this.internals.storeTokenResponse(e,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),i=this.currentToken()?.keyHandle;n?.keyHandle&&n.keyHandle!==i&&this.keyStore.delete(n.keyHandle).catch(()=>{})}};var Wa=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]),Ya=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),be=class{state=Ya.slice();block=new Uint8Array(64);words=new Uint32Array(64);blockLength=0;byteLength=0;finished=!1;update(e){if(this.finished)throw new Error("SHA-256 digest is already finalized.");if(this.byteLength+=e.byteLength,!Number.isSafeInteger(this.byteLength))throw new Error("SHA-256 input exceeds the safe browser byte range.");let n=0;if(this.blockLength>0){let i=Math.min(64-this.blockLength,e.byteLength);this.block.set(e.subarray(0,i),this.blockLength),this.blockLength+=i,n+=i,this.blockLength===64&&(this.compress(this.block),this.blockLength=0)}for(;n+64<=e.byteLength;)this.compress(e.subarray(n,n+64)),n+=64;return n<e.byteLength&&(this.block.set(e.subarray(n),0),this.blockLength=e.byteLength-n),this}digestHex(){if(this.finished)throw new Error("SHA-256 digest is already finalized.");this.finished=!0,this.block[this.blockLength]=128,this.block.fill(0,this.blockLength+1),this.blockLength>=56&&(this.compress(this.block),this.block.fill(0));let e=this.byteLength*8,n=Math.floor(e/4294967296),i=e>>>0;return Ao(this.block,56,n),Ao(this.block,60,i),this.compress(this.block),[...this.state].map(o=>o.toString(16).padStart(8,"0")).join("")}compress(e){let n=this.words;for(let u=0;u<16;u+=1){let f=u*4;n[u]=(e[f]<<24|e[f+1]<<16|e[f+2]<<8|e[f+3])>>>0}for(let u=16;u<64;u+=1){let f=n[u-15],h=n[u-2],_=W(f,7)^W(f,18)^f>>>3,m=W(h,17)^W(h,19)^h>>>10;n[u]=n[u-16]+_+n[u-7]+m>>>0}let i=this.state[0],o=this.state[1],r=this.state[2],a=this.state[3],s=this.state[4],c=this.state[5],d=this.state[6],p=this.state[7];for(let u=0;u<64;u+=1){let f=W(s,6)^W(s,11)^W(s,25),h=s&c^~s&d,_=p+f+h+Wa[u]+n[u]>>>0,m=W(i,2)^W(i,13)^W(i,22),w=i&o^i&r^o&r,y=m+w>>>0;p=d,d=c,c=s,s=a+_>>>0,a=r,r=o,o=i,i=_+y>>>0}this.state[0]=this.state[0]+i>>>0,this.state[1]=this.state[1]+o>>>0,this.state[2]=this.state[2]+r>>>0,this.state[3]=this.state[3]+a>>>0,this.state[4]=this.state[4]+s>>>0,this.state[5]=this.state[5]+c>>>0,this.state[6]=this.state[6]+d>>>0,this.state[7]=this.state[7]+p>>>0}};function W(t,e){return t>>>e|t<<32-e}function Ao(t,e,n){t[e]=n>>>24,t[e+1]=n>>>16,t[e+2]=n>>>8,t[e+3]=n}var Ht=class{constructor(e,n){this.signal=n;this.iterator=Ja(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,l("invalid_request","Streamed file bytes ended before the declared size.");if(!(r.value instanceof Uint8Array))throw l("invalid_request","A streamed file chunk was not a Uint8Array.");if(this.maxSourceChunkBytes===null)throw new Error("Stream source was read before upload negotiation completed.");if(r.value.byteLength>this.maxSourceChunkBytes)throw l("invalid_request",`A streamed file chunk exceeded the negotiated ${this.maxSourceChunkBytes}-byte upload part size.`);if(this.remainder=r.value,this.remainderOffset=0,this.remainder.byteLength===0)continue}let o=Math.min(e-i,this.remainder.byteLength-this.remainderOffset);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 l("invalid_request","Streamed file bytes exceed the declared size.");for(;!this.ended;){let e=await this.nextSourceChunk();if(e.done){this.ended=!0;return}if(!(e.value instanceof Uint8Array))throw l("invalid_request","A streamed file chunk was not a Uint8Array.");if(e.value.byteLength>0)throw l("invalid_request","Streamed file bytes exceed the declared size.")}}async close(){this.ended=!0,this.closeIterator()}async nextSourceChunk(){Po(this.signal);let e=this.iterator.next(),n=this.signal;if(!n)return e;let i=()=>{},o=new Promise((r,a)=>{let s=()=>{this.closeIterator(),a(Oo(n))};n.addEventListener("abort",s,{once:!0}),i=()=>n.removeEventListener("abort",s),n.aborted&&s()});try{let r=await Promise.race([e,o]);return Po(n),r}finally{i()}}closeIterator(){if(!this.iteratorClosing){this.iteratorClosing=!0;try{this.iterator.return?.()?.catch(()=>{})}catch{}}}};function Ja(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 l("invalid_request","Streamed files require a readable byte stream.");return e[Symbol.asyncIterator]()}function Po(t){if(t?.aborted)throw Oo(t)}function Oo(t){return l("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:t?.reason})}var To=1024*1024,Qa=4,ko=8,st=3,On=64*1024*1024,Io=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Mo=/^sha256:[0-9a-f]{64}$/u;async function xo(t,e,n){let i=new be;for(let o=0;o<t.size;o+=To){le(e);let r=new Uint8Array(await t.slice(o,o+To).arrayBuffer());i.update(r),n(Math.min(t.size,o+r.byteLength))}return t.size===0&&n(0),i.digestHex()}function Eo(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 Do(t){return t instanceof Blob?t.size:t.byteLength}async function qo(t){return t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t}function Tn(t=Qa){if(!Number.isInteger(t)||t<1||t>ko)throw l("invalid_request",`File concurrency must be between 1 and ${ko}.`);return t}function Fo(t){if(!Number.isInteger(t)||t<1||t>1e3)throw l("invalid_request","File page size must be between 1 and 1000.");return t}function kn(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 l("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(a=>!Number.isSafeInteger(a)||a<0||a>=o))throw l("invalid_operation_response","The authority returned invalid transfer progress.");let r=t.uploaded_parts??[];if(!Array.isArray(r)||r.some((a,s)=>!Number.isSafeInteger(a?.part_number)||a.part_number<1||a.part_number>o||typeof a.etag!="string"||a.etag.length===0||a.etag.length>255||s>0&&r[s-1].part_number>=a.part_number)||(t.strategy.kind==="object_multipart"?r.length!==t.received.length||r.some((a,s)=>a.part_number-1!==t.received[s]):r.length!==0))throw l("invalid_operation_response","The authority returned invalid uploaded part receipts.")}function zo(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,a)=>r+In(e.total_size,n,a),0)!==t.received_bytes)throw l("invalid_operation_response","The authority returned invalid transfer status.");let o=t.uploaded_parts;if(!Array.isArray(o)||o.some((r,a)=>!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||a>0&&o[a-1].part_number>=r.part_number)||(e.strategy.kind==="object_multipart"?o.length!==t.received.length||o.some((r,a)=>r.part_number-1!==t.received[a]):o.length!==0))throw l("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 In(t,e,n){return Math.min(e,Math.max(0,t-n*e))}async function Vt(t,e){for(let n=1;n<=Sn;n+=1){le(e);try{return await t()}catch(i){if(e?.aborted||n===Sn||i instanceof b&&!i.retryable)throw i;await fo(n,e)}}throw new Error("Unreachable file chunk retry state.")}function Uo(t,e,n,i,o,r){let a;try{a=new URL(t.url)}catch{throw l("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||t.method.toUpperCase()!==r||a.protocol!=="https:"&&!(a.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(a.hostname))||a.username||a.password)throw l("invalid_operation_response","The authority returned an invalid prepared file part.")}function No(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 Lo(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 le(t){if(t?.aborted)throw l("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:t.reason})}function ve(t){return t instanceof b?t:typeof DOMException<"u"&&t instanceof DOMException&&t.name==="AbortError"?l("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:t}):l("temporarily_unavailable","The file transfer could not be completed.",{cause:t})}var je=class{constructor(e,n,i,o,r=Ae()){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=ae(e,this.timeouts.fileIndexMs),i=n.signal;try{this.requireAction("list");let o;do{le(i);let r=new URLSearchParams({protocol_version:String(1),...e.folder?{folder:e.folder}:{},...o?{after:o}:{},...e.pageSize?{limit:String(Fo(e.pageSize))}:{}}),a;for(;;)try{a=await this.request("GET",`?${r.toString()}`,void 0,i);break}catch(s){let c=ve(s);if(c.code!=="file_index_warming")throw c;e.onIndexing?.(),await ee(500,i)}if(a.protocol_version!==1||a.type!=="files_page"||!Array.isArray(a.files))throw l("invalid_operation_response","The authority returned an invalid file page.");for(let s of a.files)le(i),yield $t(s);o=a.next}while(o)}finally{n.dispose()}}async upload(e,n,i={}){return B(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=Eo(n,i.mediaType),r=Tn(i.concurrency),a=await xo(o,i.signal,s=>{i.onProgress?.({phase:"hashing",transferredBytes:s,totalBytes:o.size})});return this.uploadKnownSource(e,o.size,`sha256:${a}`,(i.mediaType??o.type)||void 0,i,r,async(s,c,d)=>o.slice(c,c+d))}async uploadStream(e,n,i={}){return B(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 l("invalid_request","Streamed file size must be a non-negative safe integer.");if(!Mo.test(n.contentDigest))throw l("invalid_request","Streamed files require a lowercase SHA-256 content digest.");let o=new Ht(n.stream,i.signal),r=new be;return this.uploadKnownSource(e,n.size,n.contentDigest,i.mediaType??n.mediaType,i,1,async(a,s,c)=>{let d=await o.read(c);return r.update(d),d},async()=>{if(await o.expectEnd(),`sha256:${r.digestHex()}`!==n.contentDigest)throw l("invalid_request","Streamed file bytes do not match the declared SHA-256 digest.")},()=>o.close(),a=>o.setMaxSourceChunkBytes(a))}async uploadKnownSource(e,n,i,o,r,a,s,c,d,p){let u=r.transferId??crypto.randomUUID();if(!Io.test(u))throw l("invalid_request","File transfer ID must be a UUID.");let f=!1;try{let h=await this.request("POST","uploads",{protocol_version:1,type:"open_file_upload",transfer_id:u,path:e,size:n,content_digest:i,...o?{media_type:o}:{},...r.ifRevision?{if_revision:r.ifRevision}:{}},r.signal);if(kn(h,u,"upload"),h.total_size!==n||h.strategy.kind==="object_ranges")throw l("invalid_operation_response","The authority returned an incompatible upload strategy.");let _=h.strategy.kind==="framed_chunks";if(_&&!this.framed)throw l("invalid_operation_response","Encrypted file chunk delivery is unavailable.");let m=h.strategy.kind==="object_put"?Math.max(1,n):h.strategy.kind==="framed_chunks"?h.strategy.chunk_size:h.strategy.part_size,w=h.strategy.kind==="object_put"?1:Math.ceil(n/m),y=await this.request("GET",`transfers/${encodeURIComponent(u)}`,void 0,r.signal);if(zo(y,h),y.state!=="open"&&y.state!=="committed")throw l("invalid_operation_response",`The authority cannot resume a ${y.state} file transfer.`);if(p?.(m),!_&&y.received.length===w){let g=await this.tryReplayUploadCommit(u,h.strategy.kind==="object_multipart"?y.uploaded_parts:void 0,r.signal);if(g)return f=!0,$t(g.file)}let v=new Set(y.received),N=new Map(y.uploaded_parts.map(g=>[g.part_number-1,g])),P=[...v].reduce((g,K)=>g+In(n,m,K),0),q=await Lo(w,a,async g=>{let K=g*m,de=Math.min(m,Math.max(0,n-K)),ue=await s(g,K,de);if(Do(ue)!==de)throw l("invalid_request","Streamed file bytes ended before the declared size.");if(v.has(g))return N.get(g)??null;let Ce=_?await Vt(async()=>this.framed.uploadChunk(h,g,await qo(ue),r.signal),r.signal).then(()=>null):await this.uploadPart(u,g,K,ue,de,h.strategy.kind==="object_multipart",r.signal);return P+=de,r.onProgress?.({phase:"uploading",transferredBytes:P,totalBytes:n}),Ce});await c?.();let S=await this.commitUpload(u,h.strategy.kind==="object_multipart"?q.filter(g=>g!==null):void 0,r.signal);if(S.protocol_version!==1||S.type!=="file_upload_committed"||S.transfer_id!==u||S.file.path!==e||S.file.size!==n||S.file.content_digest!==i)throw l("invalid_operation_response","The authority returned an invalid file receipt.");return f=!0,$t(S.file)}catch(h){throw ve(h)}finally{await d?.().catch(()=>{}),!f&&r.transferId===void 0&&await this.abort(u)}}async download(e,n={}){if(e.size>On)throw l("invalid_request",`download() buffers at most ${On} bytes; use downloadStream() for larger files.`);let i=await this.downloadStream(e,n),o=[],r=i.getReader();for(;;){let a=await r.read();if(a.done)break;o.push(a.value)}return new Blob(o.map(a=>{let s=new Uint8Array(a.byteLength);return s.set(a),s.buffer}),{type:e.mediaType??""})}async downloadStream(e,n={}){return B(n,this.timeouts.requestMs,i=>this.openDownloadStream(e,n,i.signal))}async openDownloadStream(e,n,i){this.requireAction("read");let o=Tn(n.concurrency),r=crypto.randomUUID(),a;try{if(a=await this.request("POST","downloads",{protocol_version:1,type:"open_file_download",transfer_id:r,file_id:e.fileId,revision:e.revision},i),kn(a,r,"download"),a.total_size!==e.size||a.strategy.kind!=="object_ranges"&&a.strategy.kind!=="framed_chunks")throw l("invalid_operation_response","The authority returned an incompatible download session.");if(a.strategy.kind==="framed_chunks"&&!this.framed)throw l("invalid_operation_response","Encrypted file chunk delivery is unavailable.");if(a.strategy.kind==="object_ranges"&&e.size>0&&!this.hosted)throw l("invalid_operation_response","Authenticated hosted file delivery is unavailable.")}catch(S){throw await this.abort(r),ve(S)}let s=a.strategy.kind==="framed_chunks"?a.strategy.chunk_size:a.strategy.part_size,c=Math.ceil(e.size/s),d=new be,p=0,u=0,f=null,h=0,_=!1,m=new AbortController,w=n.signal?AbortSignal.any([n.signal,m.signal]):m.signal,y=new Map,v=0,N=()=>{if(a.strategy.kind==="framed_chunks")for(;v<c&&y.size<o;){let S=v;v+=1;let g=Vt(()=>this.framed.downloadChunk(a,S,w),w).then(K=>({ok:!0,chunk:K}),K=>({ok:!1,error:K}));y.set(S,g)}},P=async()=>{_||(_=!0,m.abort(),await f?.cancel().catch(()=>{}),f=null,await Promise.all(y.values()),y.clear(),await this.abort(r))},q=()=>{if(h!==e.size||`sha256:${d.digestHex()}`!==e.contentDigest)throw l("invalid_operation_response","Downloaded file bytes failed integrity verification.")};return new ReadableStream({pull:async S=>{try{if(le(w),a.strategy.kind==="object_ranges")for(;;){if(!f){if(p>=c){q(),S.close(),P();return}let Wo=p*s;u=Math.min(s,e.size-Wo),f=(await Vt(()=>this.hosted.downloadPart(a,p,u,w),w)).getReader()}let ie=await f.read();if(ie.done){if(f.releaseLock(),f=null,u!==0)throw l("invalid_operation_response","A hosted file range ended before its declared byte length.");p+=1;continue}if(!(ie.value instanceof Uint8Array))throw l("invalid_operation_response","A hosted file range returned a non-byte chunk.");if(ie.value.byteLength!==0){if(ie.value.byteLength>u)throw l("invalid_operation_response","A hosted file range exceeded its declared byte length.");u-=ie.value.byteLength,d.update(ie.value),h+=ie.value.byteLength,n.onProgress?.({phase:"downloading",transferredBytes:h,totalBytes:e.size}),S.enqueue(ie.value);return}}if(p>=c){q(),S.close(),P();return}let g=p*s,K=Math.min(s,e.size-g);N();let de=y.get(p);if(!de)throw l("invalid_operation_response","A file chunk was not scheduled.");let ue=await de;if(y.delete(p),!ue.ok)throw ue.error;let Ce=ue.chunk;if(Ce.byteLength!==K)throw l("invalid_operation_response","A file chunk had the wrong byte length.");d.update(Ce),h+=Ce.byteLength,p+=1,N(),n.onProgress?.({phase:"downloading",transferredBytes:h,totalBytes:e.size}),p===c&&q(),S.enqueue(Ce),p===c&&(S.close(),P())}catch(g){await P(),S.error(ve(g))}},cancel:P})}async downloadBytes(e,n={}){return new Uint8Array(await(await this.download(e,n)).arrayBuffer())}async move(e,n,i={}){return B(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(a){throw ve(a)}if(r.protocol_version!==1||r.type!=="file_moved"||r.mutation_id!==o||r.file.file_id!==e.fileId||r.file.path!==n)throw l("invalid_operation_response","The authority returned an invalid file move receipt.");return $t(r.file)}async delete(e,n={}){return B(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 ve(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 l("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,a,s){for(let c=1;c<=st;c+=1){le(s);try{let d=await this.request("POST",`uploads/${encodeURIComponent(e)}/parts`,{protocol_version:1,type:"prepare_file_upload_part",transfer_id:e,part_number:n+1,content_length:r},s);Uo(d,e,n,i,r,"PUT");let p=await fetch(d.url,{method:d.method,headers:No(d.headers),body:o,redirect:"error",signal:s});if(!p.ok)throw new Error(`Object upload failed with HTTP ${p.status}.`);let u=p.headers.get("etag");if(a&&!u)throw new Error("Multipart object upload did not return an ETag.");return{part_number:n+1,etag:u??""}}catch(d){if(s?.aborted||c===st)throw d}}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 b&&o.code==="file_upload_incomplete")return null;throw o}}async commitUpload(e,n,i){let o;for(let r=1;r<=st;r+=1){le(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(a){if(o=a,i?.aborted||a instanceof b||r===st)throw a}}throw o}requireAction(e){if(!this.capability()?.actions.includes(e))throw l("not_authorized",`This connection is not authorized to ${e} files.`)}async abort(e){await this.request("DELETE",`transfers/${encodeURIComponent(e)}`).catch(()=>{})}};function $t(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 Ke=class{constructor(e,n){this.internals=e;this.collectionId=n;this.transport=new Kt({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.files=new je(()=>this.fileCapability,(i,o,r,a)=>this.transport.files.control(i,o,r,a),{uploadChunk:(i,o,r,a)=>this.transport.files.uploadChunk(i,o,r,a),downloadChunk:(i,o,r)=>this.transport.files.downloadChunk(i,o,r)},{downloadPart:(i,o,r,a)=>this.transport.files.downloadHostedPart(i,o,r,a)},e.timeouts),this.collectionClient=new ze({operation:(i,o,r)=>this.transport.performOperation(i,o,r)},e.timeouts.requestMs),this.notifications=new It({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;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 x(()=>this.internals.register(e),ye)}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=ge){let n=this.operations,i=G(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 x(()=>this.internals.authorize({...e,target:{kind:"collection",collectionId:this.collectionId}}),Re)}async requestOperations(e,n={}){let i=this.authorizationCapabilities(e);return i.sufficient?I({kind:"unchanged",connection:this}):this.authorize({...n,operations:G([...i.grantedOperations,...i.missingOperations])})}onConnectionChange(e){return this.connectionListeners.add(e),e(this.info()),()=>this.connectionListeners.delete(e)}notifyStorageChanged(){this.transport.notifyStorageChanged()}checkDirectAccess(e){return x(()=>this.transport.checkDirectAccess(e),dn)}requestDirectAccess(e){return x(()=>this.transport.requestDirectAccess(e),dn)}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"},Gt(r,this.internals.timeouts.syncMs)),snapshot:(r,a,s)=>this.transport.performOperation("sync",{action:"snapshot",snapshot_id:r,...a?{page:a}:{}},Gt(s,this.internals.timeouts.syncMs)),changes:(r,a=200,s)=>this.transport.performOperation("sync",{action:"changes",after:r,limit:a},Gt(s,this.internals.timeouts.syncMs)),mutate:(r,a)=>this.transport.performOperation("sync",{action:"mutate",mutation:r},Gt(a,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,a)=>{let s=new URLSearchParams({snapshot_id:o});return r&&s.set("page",r),this.transport.performAuthoritySyncRequest(n,i,"GET",`snapshot?${s}`,void 0,a)},changes:(o,r=200,a)=>this.transport.performAuthoritySyncRequest(n,i,"GET",`changes?${new URLSearchParams({after:String(o),limit:String(r)})}`,void 0,a),mutate:(o,r)=>this.transport.performAuthoritySyncRequest(n,i,"POST","mutations",o,r)}}}registerNotifications(e){return x(()=>this.notifications.registerNotifications(e),Je)}registerNativeNotifications(e){return x(()=>this.notifications.registerNativeNotifications(e),Je)}unregisterNativeNotifications(e){return x(()=>this.notifications.unregisterNativeNotifications(e),Je)}unregisterNotifications(e,n){return x(()=>this.notifications.unregisterNotifications(e,n),Je)}forget(){let e=this.transport.currentToken();this.internals.removeToken(this.collectionId,e?.keyHandle,"not_authorized",!0),this.transport.notifyStorageChanged()}describe(e){return this.collectionClient.describe(e)}changes(e={},n){return this.collectionClient.changes(e,n)}read(e,n){return this.collectionClient.read(e,n)}query(e={},n){return this.collectionClient.query(e,n)}queryPages(e={},n={}){return this.collectionClient.queryPages(e,n)}queryAll(e={},n={}){return this.collectionClient.queryAll(e,n)}listViews(e){return this.collectionClient.listViews(e)}executeView(e,n){return this.collectionClient.executeView(e,n)}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 B(n,this.internals.timeouts.requestMs,async i=>{let o=Date.now(),r=!1,a,s=(c,d,p=0)=>{n.onProgress?.({operation:"rename",state:c,elapsedMs:Date.now()-o,cancellable:d,resumed:r,completedUnits:p,...a?{estimate:a}:{}})};try{me(i.signal),s("preflighting",!0);let c=n.preflight?I(n.preflight):await this.preflightRename(e,{signal:i.signal,timeoutMs:null});if(!c.ok)return c;let d=c.value;try{Ri(e,d)}catch(f){if(f instanceof b)return O(f.problem);throw f}a=Pi(e,d),s("ready",!0),me(i.signal);let p=this.transport.hasResumableMutationTransport();s("applying",p);let u=await this.rename(e,p?{signal:i.signal,timeoutMs:null}:{timeoutMs:Bo(i.remainingMs())});return u.ok&&s("completed",!1,a.totalUnits),u}catch(c){if(yn(c,i.signal)&&s("cancelled",!1),c instanceof b)return O(c.problem);throw c}})}async deleteWithProgress(e,n={}){return B(n,this.internals.timeouts.requestMs,async i=>{let o=Date.now(),r=!1,a,s=(c,d,p=0)=>{n.onProgress?.({operation:"delete",state:c,elapsedMs:Date.now()-o,cancellable:d,resumed:r,completedUnits:p,...a?{estimate:a}:{}})};try{me(i.signal),s("preflighting",!0);let c=n.preflight?I(n.preflight):await this.preflightDelete(e,{signal:i.signal,timeoutMs:null});if(!c.ok)return c;let d=c.value;try{Ai(e,d)}catch(f){if(f instanceof b)return O(f.problem);throw f}a=Oi(d),s("ready",!0),me(i.signal);let p=this.transport.hasResumableMutationTransport();s("applying",p);let u=await this.delete(e,p?{signal:i.signal,timeoutMs:null}:{timeoutMs:Bo(i.remainingMs())});return u.ok&&s("completed",!1,a.totalUnits),u}catch(c){if(yn(c,i.signal)&&s("cancelled",!1),c instanceof b)return O(c.problem);throw c}})}pendingMutations(){return this.transport.pendingMutations().map(e=>({...e,recover:n=>x(()=>this.recoverPendingMutation(e.requestId,n),z)}))}pendingMutation(e){let n=this.transport.pendingMutation(e);return n?{...n,recover:i=>x(()=>this.recoverPendingMutation(e,i),z)}: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 b(Se(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 x(()=>U(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 b(o.problem);if(o.value.reset)throw new b(k("change_cursor_reset","The collection change cursor expired. Refresh collection state before subscribing again."));return new Mn(this.collectionClient,o.value.cursor,e,e.cursor===void 0?[]:o.value.events,this.internals.timeouts.watchStartMs)}),bt)}emitConnection(){let e=this.info();for(let n of this.connectionListeners)n(e)}},Mn=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 a=i.lifetimeSignal;if(a?.aborted)this.close();else if(a){let s=()=>this.close();a.addEventListener("abort",s,{once:!0}),this.removeLifetimeAbort=()=>a.removeEventListener("abort",s)}this.controller.signal.aborted||this.run(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 Gt(t,e){return{...t,timeoutMs:t?.timeoutMs===void 0?e:t.timeoutMs}}function Bo(t){return t===null?null:Math.max(1,Math.ceil(t))}function xn(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 He(t,e,n){return t.reason instanceof b?t.reason:l("authorization_cancelled",e,{cause:n})}function En(t,e,n,i){let o=`${e}:pending-mutation:`,r=new Set;for(let a=0;a<t.length;a+=1){let s=t.key(a);if(!s?.startsWith(o))continue;let c=M(t.getItem(s));if(!c||!n.includes(c.operation)||i&&c.collectionId!==i)continue;let d=c.envelope?.protocol_version??c.request?.protocol_version;d!==void 0&&d!==L&&$e(d)&&r.add(d)}return[...r].sort((a,s)=>s-a)}function jo(t,e,n){for(let i=0;i<t.length;i+=1){let o=t.key(i);if(o!==e&&!o?.startsWith(`${e}:`))continue;if(M(t.getItem(o))?.keyHandle===n)return!0}return!1}function Ko(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=M(t.getItem(o));r?.keyHandle&&n(r.keyHandle),t.removeItem(o)}}function Ho({body:t,clientId:e,keyHandle:n,previous:i,defaultApplicationOrigin:o,pinConnectorIdentity:r}){let a=t.collection_id;if(typeof a!="string")throw l("invalid_token_response","Authorization returned no collection ID.");let s=Rt(t.scope);if(!s)throw l("invalid_token_response","Authorization returned no valid collection scope.");if(t.authority&&!it(t.authority,a))throw l("invalid_token_response","Authorization returned an invalid remote authority capability.");if(t.authority&&t.encryption)throw l("invalid_token_response","Authorization returned conflicting collection transports.");if(t.file_capability!==null&&t.file_capability!==void 0&&!St(t.file_capability))throw l("invalid_token_response","Authorization returned an invalid file capability.");if(t.encryption){try{X(t.encryption)}catch{throw l("invalid_token_response","Authorization returned an invalid encrypted relay binding.")}if(r(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 l("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 l("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:s,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??o,keyHandle:n,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}}var Wt=class{serverUrl;manifest;manifestSource;redirectUri;storage;relayEncryption;keyStore;identityStore;directAccessMode;loopbackUrl;navigate;timeouts;credentialStorage;application=null;manifestPromise=null;completionPromises=new Map;connectionCache=new Map;listeners=new Set;invalidatedConnections=new Map;constructor(e){this.serverUrl=qi(String(e.serverUrl)),this.manifest=e.manifest instanceof URL?e.manifest.href:e.manifest??Fi(),this.manifestSource=typeof this.manifest=="string"?this.manifest:this.manifest.distribution==="portable"?`bundle:${this.manifest.id}:${ji(this.manifest)}`:`bundle:${this.manifest.id}`;let n=Bi(this.manifest);this.redirectUri=e.redirectUri===void 0?typeof this.manifest!="string"&&this.manifest.distribution==="portable"?"":zi():String(e.redirectUri),this.storage=e.storage??Li(n),this.relayEncryption=e.relayEncryption??"required",this.keyStore=e.keyStore??(n?new Oe:new Pe),this.identityStore=e.identityStore??(n?new qe:new De),this.credentialStorage=e.storage||e.keyStore||e.identityStore?"custom":this.storage instanceof Ie?"memory":"persistent",this.directAccessMode=e.directAccess??"auto",this.loopbackUrl=Mi(String(e.loopbackUrl??`http://127.0.0.1:${oi}`)),this.navigate=e.navigate,this.timeouts=Ae(e.timeouts),typeof window<"u"&&this.storage===window.localStorage&&window.addEventListener("storage",i=>{i.storageArea!==this.storage||!i.key?.startsWith(this.storagePrefix())||(this.connectionCache.get(Ni(i.key))?.notifyStorageChanged(),this.emitConnections())})}environment(){let e=typeof this.manifest!="string"&&this.manifest.distribution==="portable"?"portable":this.application?.distribution??"web";return{distribution:e,applicationOrigin:e==="portable"?"null":this.defaultApplicationOrigin(),credentialStorage:this.credentialStorage}}register(e={}){return U(e,this.timeouts.requestMs,n=>this.registerWithinBudget(n.signal))}async registerWithinBudget(e){if(this.application)return this.application;let n=await Z(`${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 A(n,"invalid_operation_response","Connect returned an invalid application registration response.");if(!n.ok)throw T(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=U(e,this.timeouts.requestMs,o=>this.loadManifest(o.signal)).catch(o=>{throw this.manifestPromise===i&&(this.manifestPromise=null),o});return this.manifestPromise=i,this.manifestPromise}async loadManifest(e){if(typeof this.manifest!="string")return this.manifest;let n=this.manifest,i;try{i=await fetch(n,{headers:{accept:"application/json"},signal:e})}catch(o){throw l("manifest_load_failed","The bundled application declaration could not be loaded.",{cause:o})}if(!i.ok)throw l("manifest_load_failed",`The bundled application declaration returned HTTP ${i.status}.`,{status:i.status});try{return await A(i,"invalid_application_manifest","The bundled application declaration is not valid JSON.")}catch(o){throw l("invalid_application_manifest","The bundled application declaration is not valid JSON.",{cause:o,details:{issues:[{path:"/",keyword:"json",message:"must be valid JSON",params:{}}]}})}}async authorize(e={}){return U(e,this.timeouts.requestMs,n=>this.authorizeWithinBudget({...e,signal:n.signal,timeoutMs:null}))}async authorizeWithinBudget(e){if(typeof location>"u"&&!this.navigate&&!e.openVerification)throw l("browser_required","Authorization navigation requires a browser environment.");let i=typeof this.manifest!="string"&&this.manifest.distribution==="portable"&&!e.openVerification&&!this.navigate&&typeof window<"u"?window.open("","mdbase-connect-authorization","popup,width=620,height=760"):null,o;try{o=await this.registerWithinBudget(e.signal)}catch(r){throw i?.close(),r}return o.distribution==="portable"?(e.openVerification&&i?.close(),this.authorizePortable(o,e,e.openVerification?null:i)):(i?.close(),this.authorizeWeb(o,e))}async authorizeWeb(e,n){let{verifier:i,challenge:o}=await tt(),r=V(24),a=crypto.randomUUID(),s=n.target?.kind==="collection"?n.target.collectionId:void 0,c=`grant:${e.id}:${r}`,d=await this.keyStore.create(c),p;try{p=await this.loadApplicationIdentity(e)}catch(m){throw await this.keyStore.delete(c),m}let u=G(n.operations??ge),f=new Date,h=await at({protocol_version:$,authorization_id:a,application_id:e.id,application_declaration_id:xn(e.family_identity),application_manifest_digest:e.manifest_digest,application_installation_id:await Fe(p),installation_signing_public_key:p.signingPublicKey,grant_agreement_public_key:d.agreementPublicKey,grant_signing_public_key:d.signingPublicKey,flow:"authorization_code",authorization_nonce:V(32),issued_at:f.toISOString(),expires_at:new Date(f.getTime()+600*1e3).toISOString(),redirect_uri:this.redirectUri,state:r,code_challenge:o,contracts:sn(u,e.requirements?.files,En(this.storage,this.storagePrefix(),u,s)),requested_operations:u,...e.requirements?.files?{requested_files:e.requirements.files}:{},...s?{collection_id:s}:{}},p),_={version:1,verifier:i,state:r,clientId:e.id,redirectUri:this.redirectUri,relayEncryption:this.relayEncryption,collectionId:s,returnTo:n.returnTo,keyHandle:c,authorizationId:a,applicationAgreementPublicKey:d.agreementPublicKey,applicationSigningPublicKey:d.signingPublicKey};this.storage.setItem(this.pendingKey(r),JSON.stringify(_));try{let m=await fetch(`${this.serverUrl}/oauth/authorization_request`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e.id,redirect_uri:this.redirectUri,code_challenge:o,code_challenge_method:"S256",state:r,operations:u.join(","),...s?{collection_id:s}:{},application_authorization:JSON.stringify(h)}),signal:n.signal}),w=await A(m,"invalid_device_authorization_response","The authorization service returned an invalid authorization response.");if(!m.ok)throw T(w,"device_authorization_failed","Application authorization could not be started.",m.status);if(typeof w.authorization_uri!="string"||w.authorization_id!==a||!Number.isInteger(w.expires_in)||w.expires_in<=0)throw l("invalid_device_authorization_response","The authorization service returned an invalid authorization response.");if(this.navigate)await this.navigate(w.authorization_uri);else if(typeof location<"u")location.assign(w.authorization_uri);else throw l("browser_required","Authorization navigation requires a browser environment.");return{kind:"redirecting"}}catch(m){throw this.storage.removeItem(this.pendingKey(r)),await this.keyStore.delete(c),n.signal?.aborted?He(n.signal,"Application authorization was cancelled.",m):m}}async authorizePortable(e,n,i){if(this.relayEncryption!=="required")throw i?.close(),l("encryption_required","Downloaded applications require encrypted relay authorization.");let{verifier:o,challenge:r}=await tt(),a=`grant:${e.id}:${V(24)}`,s=await this.keyStore.create(a),c;try{c=await this.loadApplicationIdentity(e)}catch(y){throw i?.close(),await this.keyStore.delete(a),y}let d=G(n.operations??ge),p=crypto.randomUUID(),u=new Date,f=await at({protocol_version:$,authorization_id:p,application_id:e.id,application_declaration_id:xn(e.family_identity),application_manifest_digest:e.manifest_digest,application_installation_id:await Fe(c),installation_signing_public_key:c.signingPublicKey,grant_agreement_public_key:s.agreementPublicKey,grant_signing_public_key:s.signingPublicKey,flow:"device_code",authorization_nonce:V(32),issued_at:u.toISOString(),expires_at:new Date(u.getTime()+600*1e3).toISOString(),code_challenge:r,contracts:sn(d,e.requirements?.files,En(this.storage,this.storagePrefix(),d,n.target?.kind==="collection"?n.target.collectionId:void 0)),requested_operations:d,...e.requirements?.files?{requested_files:e.requirements.files}:{},...n.target?.kind==="collection"?{collection_id:n.target.collectionId}:{}},c),h,_;try{h=await fetch(`${this.serverUrl}/oauth/device_authorization`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e.id,operations:d.join(","),...n.target?.kind==="collection"?{collection_id:n.target.collectionId}:{},code_challenge:r,code_challenge_method:"S256",application_authorization:JSON.stringify(f)}),signal:n.signal}),_=await A(h,"invalid_device_authorization_response","The authorization service returned an invalid device authorization response.")}catch(y){throw i?.close(),await this.keyStore.delete(a),l("device_authorization_failed","Downloaded application authorization could not be started.",{cause:y})}if(!h.ok)throw i?.close(),await this.keyStore.delete(a),T(_,"device_authorization_failed","Downloaded application authorization could not be started.",h.status);let m;try{m=Di(_)}catch(y){throw i?.close(),await this.keyStore.delete(a),n.signal?.aborted?He(n.signal,"Downloaded application authorization was cancelled.",y):y}if(n.onDeviceCode?.(m),n.openVerification)await n.openVerification(m);else if(i)try{i.location.href=m.verificationUriComplete}catch{}else throw await this.keyStore.delete(a),l("approval_window_blocked","The approval window was blocked. Show the provided verification link and code, then try again.",{details:{user_code:m.userCode,verification_uri:m.verificationUri,verification_uri_complete:m.verificationUriComplete,expires_at:m.expiresAt,interval_seconds:m.intervalSeconds}});let w=m.intervalSeconds;try{for(;Date.now()<m.expiresAt;){if(await ee(w*1e3,n.signal),n.signal?.aborted)throw He(n.signal,"Downloaded application authorization was cancelled.");let y;try{y=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(S){if(n.signal?.aborted)throw He(n.signal,"Downloaded application authorization was cancelled.",S);continue}let v=await A(y,"invalid_token_response","The authorization service returned an invalid token response.");if(!y.ok){let S=nt(v);if(S==="authorization_pending")continue;if(S==="slow_down"){w+=5;continue}throw T(v,"token_exchange_failed","Downloaded application authorization could not be completed.",y.status)}let N=it(v.authority,v.collection_id),P=v.encryption&&v.encryption.protocol_version===mt&&v.encryption.suite===We&&v.encryption.application_agreement_public_key===s.agreementPublicKey;if(v.application_origin!=="null")throw l("invalid_token_response","Authorization did not bind the portable grant to its opaque application origin.");if(v.authority&&(!N||v.encryption!=null||v.authority.proof_public_key!==s.signingPublicKey))throw l("invalid_token_response","Authorization returned a remote authority capability that is not bound to this portable grant key.");if(!v.authority&&!P)throw l("encryption_required","Authorization did not establish the expected key-bound local portable grant.");let q=this.storeTokenResponse(v,e.id,a);if(n.target?.kind==="collection"&&n.target.collectionId!==q.collectionId)throw this.removeToken(q.collectionId,q.keyHandle),l("collection_mismatch","The approved collection does not match the collection requested by this link.");return i?.close(),{kind:"connected",connection:this.connection(q.collectionId),...n.returnTo?{returnTo:n.returnTo}:{}}}throw l("expired_token","The downloaded application authorization code expired.")}catch(y){throw i?.close(),await this.keyStore.delete(a),n.signal?.aborted?He(n.signal,"Downloaded application authorization was cancelled.",y):y}}completeAuthorization(e,n={}){return U(n,this.timeouts.requestMs,i=>this.completeAuthorizationWithinBudget(e,i.signal))}completeAuthorizationWithinBudget(e,n){let i=new URL(e).searchParams.get("state");if(!i)return Promise.reject(l("invalid_callback","Authorization callback is missing its state."));let o=this.completionPromises.get(i);if(o)return o;let a=this.performAuthorizationCompletion(e,i,n).finally(()=>{this.completionPromises.get(i)===a&&this.completionPromises.delete(i)});return this.completionPromises.set(i,a),a}async performAuthorizationCompletion(e,n,i){let o=new URL(e),r=o.searchParams.get("code"),a=this.pendingKey(n),s=M(this.storage.getItem(a));if(!s||s.version!==1||n!==s.state)throw l("invalid_callback","Authorization callback is missing or does not match this browser session.");if(o.searchParams.has("error"))throw s.keyHandle&&await this.keyStore.delete(s.keyHandle),this.storage.removeItem(a),F(o.searchParams.get("error")??"access_denied",o.searchParams.get("error_description")??"Collection access was not approved.",{details:s.returnTo?{return_to:s.returnTo}:void 0});if(!r)throw l("invalid_callback","Authorization callback is missing its code.");let c=await Z(`${this.serverUrl}/oauth/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:r,client_id:s.clientId,redirect_uri:s.redirectUri,code_verifier:s.verifier}),signal:i},"temporarily_unavailable","Authorization completion is temporarily unavailable."),d=await A(c,"invalid_token_response","The authorization service returned an invalid token response.");if(!c.ok)throw T(d,"token_exchange_failed","Authorization could not be completed.",c.status);if(s.relayEncryption==="required"&&!d.authority&&(!d.encryption||!s.keyHandle||d.encryption.application_agreement_public_key!==s.applicationAgreementPublicKey))throw s.keyHandle&&await this.keyStore.delete(s.keyHandle),this.storage.removeItem(a),l("encryption_required","Authorization did not establish the required encrypted relay grant.");if(d.authority?.proof_public_key){if(!s.keyHandle||!s.applicationSigningPublicKey||d.authority.proof_public_key!==s.applicationSigningPublicKey)throw s.keyHandle&&await this.keyStore.delete(s.keyHandle),this.storage.removeItem(a),l("invalid_token_response","Authorization returned a remote authority capability bound to another application key.")}else d.authority&&s.keyHandle&&await this.keyStore.delete(s.keyHandle);let p=this.storeTokenResponse(d,s.clientId,d.authority?.proof_public_key?s.keyHandle:d.authority?void 0:s.keyHandle);if(s.collectionId&&s.collectionId!==p.collectionId)throw this.removeToken(p.collectionId,p.keyHandle),this.storage.removeItem(a),l("collection_mismatch","The approved collection does not match the collection requested by this link.");return this.storage.removeItem(a),{connection:this.connection(p.collectionId),...s.returnTo?{returnTo:s.returnTo}:{}}}connections(){let e=[];for(let n of this.connectionIds()){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 Ke(this,e),this.connectionCache.set(e,n)),n.info()?n:null}unavailableReason(e){return this.invalidatedConnections.get(e)??null}onConnectionsChange(e){return this.listeners.add(e),e(this.connections()),()=>this.listeners.delete(e)}storeTokenResponse(e,n,i){let o=e.collection_id;if(typeof o!="string")throw l("invalid_token_response","Authorization returned no collection ID.");let r=M(this.storage.getItem(this.tokenKey(o))),a=Ho({body:e,clientId:n,keyHandle:i,previous:r,defaultApplicationOrigin:this.defaultApplicationOrigin(),pinConnectorIdentity:(s,c)=>this.pinConnectorIdentity(s,c)});return r?.keyHandle&&r.keyHandle!==i&&this.keyStore.delete(r.keyHandle).catch(()=>{}),this.storage.setItem(this.tokenKey(o),JSON.stringify(a)),this.addConnectionId(o),this.invalidatedConnections.delete(o),this.connectionCache.delete(o),this.emitConnections(),a}forgetConnectorIdentity(e){this.storage.removeItem(this.connectorPinKey(e))}pinConnectorIdentity(e,n){let i=this.connectorPinKey(e),o=M(this.storage.getItem(i));if(o&&(o.version!==1||o.publicKey!==n))throw l("connector_identity_changed","The connector identity changed since this application first connected. Forget the saved connector identity only after verifying the computer, then authorize again.");o||this.storage.setItem(i,JSON.stringify({version:1,publicKey:n}))}connectorPinKey(e){return`mdbase-connect:${this.serverUrl}:connector-pin:${e}`}async loadApplicationIdentity(e){try{return await Ot(this.identityStore,this.serverUrl,e)}catch(n){throw l("application_identity_unavailable",n instanceof _e?n.message:"The application installation identity is unavailable.",{cause:n})}}removeToken(e,n,i="authorization_lost",o=!1){this.invalidatedConnections.set(e,i),n&&(o||!jo(this.storage,this.pendingMutationKey(e),n))&&this.keyStore.delete(n).catch(()=>{}),this.storage.removeItem(this.tokenKey(e)),o&&Ko(this.storage,this.pendingMutationKey(e),r=>{this.keyStore.delete(r).catch(()=>{})});for(let r of["web_push","fcm"])this.storage.removeItem(this.notificationKey(e,r));this.storage.setItem(this.connectionsKey(),JSON.stringify({version:1,collectionIds:this.connectionIds().filter(r=>r!==e)})),this.connectionCache.delete(e),this.emitConnections()}tokenKey(e){return`${this.storagePrefix()}:token:${e}`}pendingMutationKey(e){return`${this.storagePrefix()}:pending-mutation:${e}`}notificationKey(e,n="web_push"){return`${this.storagePrefix()}:notifications:${e}:${n}`}directPreferenceKey(){return`mdbase-connect:direct:${this.defaultApplicationOrigin()}`}defaultApplicationOrigin(){return Ui(this.manifest,this.manifestSource,this.redirectUri,this.application?.distribution==="portable")}pendingKey(e){return`${this.storagePrefix()}:pending:${e}`}storagePrefix(){return`mdbase-connect:${this.serverUrl}:${this.manifestSource}`}connectionsKey(){return`${this.storagePrefix()}:connections`}connectionIds(){let e=M(this.storage.getItem(this.connectionsKey()));return e?.version===1&&Array.isArray(e.collectionIds)&&e.collectionIds.every(n=>typeof n=="string")?e.collectionIds:[]}addConnectionId(e){this.storage.setItem(this.connectionsKey(),JSON.stringify({version:1,collectionIds:[...new Set([...this.connectionIds(),e])]}))}emitConnections(){let e=this.connections();for(let n of this.listeners)n(e)}};var Yt=class{internals;constructor(e){this.internals=new Wt(e)}register(e){return x(()=>this.internals.register(e),ye)}authorize(e={}){return x(()=>this.internals.authorize(e),Re)}application(e){return new xe(this,e,this.internals.timeouts)}manifest(e){return x(()=>this.internals.manifestDeclaration(e),ye)}environment(){return this.internals.environment()}completeAuthorization(e,n){return x(()=>this.internals.completeAuthorization(e===void 0?At():String(e),n),Re)}connections(){return this.internals.connections()}connection(e){return this.internals.connection(e)}unavailableReason(e){return this.internals.unavailableReason(e)}onConnectionsChange(e){return this.internals.onConnectionsChange(e)}forgetAll(){for(let e of this.connections())this.connection(e.collectionId)?.forget()}forgetConnectorIdentity(e){this.internals.forgetConnectorIdentity(e)}};function Dn(t){if(!t||typeof t!="object")throw l("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 l("invalid_push_payload","The push payload is not an mdbase notification.");return e}function Vo(t){if(!t||typeof t!="object")throw l("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 l("invalid_push_payload","The native notification data is not an mdbase notification.");return{type:"mdbase.notification",version:1,signal_id:e.signal_id,criterion_id:e.criterion_id,cursor:e.cursor}}function $o(t,e){let n=Dn(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 Go(t){return{subscribe:e=>t.subscribe(e),getSnapshot:()=>t.getSnapshot()}}var Jt=class{collectionParameter;fallbackPath;listeners=new Set;handlePopState=()=>this.emit();constructor(e={}){this.collectionParameter=e.collectionParameter??"collection",this.fallbackPath=e.fallbackPath??"/"}selectedCollectionId(){return this.currentUrl().searchParams.get(this.collectionParameter)}select(e,n={}){let i=ot(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=ot(this.currentUrl());return`${e.pathname}${e.search}${e.hash}`}authorizationCallback(){let e=this.currentUrl().href;return Pt(e)?e:null}finishAuthorization(e,n){let i=this.safeAppUrl(e??this.fallbackPath);ot(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,"",ot(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 l("browser_required","Browser selection requires a browser environment.");return new URL(location.href)}browserHistory(){if(typeof history>"u")throw l("browser_required","Browser selection requires a browser environment.");return history}},Qt=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 er(Za);})();
|