@mdbase-dev/connect 0.1.0-beta.25 → 0.1.0-beta.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -254,17 +254,31 @@ Request `read_type`, `create_type`, and `update_type` during authorization.
254
254
  Contract-scoped applications cannot manage collection-wide type definitions.
255
255
 
256
256
  To install a complete catalog pack without exposing its individual collection
257
- paths, request `install_type_pack`, fetch and verify the published provision,
258
- then pass it to the atomic collection operation:
257
+ paths, request `assess_type_pack` and `apply_type_pack`, fetch and verify the
258
+ published provision, then review and apply the authority's exact plan:
259
259
 
260
260
  ```ts
261
261
  const response = await fetch(pack.provisionUrl);
262
262
  const provision = await response.json();
263
- await connection.installTypePack(provision);
263
+ const installedBy = "dev.example.catalog";
264
+ const assessment = await connection.assessTypePack({
265
+ provision,
266
+ installed_by: installedBy
267
+ });
268
+ if (!assessment.ok) return renderProblem(assessment.problem);
269
+
270
+ renderDefinitionChanges(assessment.value);
271
+ const applied = await connection.applyTypePack({
272
+ provision,
273
+ installed_by: installedBy,
274
+ expected_assessment_digest: assessment.value.assessment_digest
275
+ });
276
+ if (!applied.ok) return renderProblem(applied.problem);
264
277
  ```
265
278
 
266
279
  The caller remains responsible for verifying the catalog digest before sending
267
- the provision. Existing targets with different content are rejected.
280
+ the provision. Apply rechecks the reviewed assessment inside the transaction;
281
+ stale plans and locally modified targets fail without partial writes.
268
282
 
269
283
  For a local collection, ask for same-computer access from a user gesture:
270
284
 
@@ -333,6 +347,25 @@ implements:
333
347
  ---
334
348
  `;
335
349
 
350
+ const workItemPack = defineTypePack({
351
+ id: "example.work-items",
352
+ version: "1.0.0",
353
+ resources: [
354
+ {
355
+ kind: "contract",
356
+ mode: "managed",
357
+ source: "_contracts/example.work-item.md",
358
+ document: contract
359
+ },
360
+ {
361
+ kind: "type",
362
+ mode: "seed",
363
+ source: "_types/work-item.md",
364
+ document: type
365
+ }
366
+ ]
367
+ });
368
+
336
369
  export const manifest = {
337
370
  manifest_version: 1,
338
371
  id: "dev.mdbase.worklog",
@@ -340,18 +373,10 @@ export const manifest = {
340
373
  homepage: "https://worklog.example",
341
374
  redirect_uris: ["https://worklog.example/auth/mdbase/callback"],
342
375
  requirements: {
343
- contracts: [{ id: "example.work-item", version: "1.0.0" }]
376
+ contracts: workItemPack.provides
344
377
  },
345
378
  provisions: {
346
- type_packs: [defineTypePack({
347
- id: "example.work-items",
348
- version: "1.0.0",
349
- provides: [{ id: "example.work-item", version: "1.0.0" }],
350
- resources: [
351
- { kind: "contract", source: "_contracts/example.work-item.md", document: contract },
352
- { kind: "type", source: "_types/work-item.md", document: type }
353
- ]
354
- })]
379
+ type_packs: [workItemPack]
355
380
  }
356
381
  };
357
382
  ```
@@ -1,4 +1,4 @@
1
1
  {
2
2
  "file": "mdbase-connect.min.js",
3
- "integrity": "sha384-Rejwyx0zN9iv54K0UaKMWs09sQLXcxnOBtKT574KVKlC7aR4FZ7CqpPRMd7mKlNl"
3
+ "integrity": "sha384-DjJkmk65xgvpJONlTzVuGLRLNCDOhbOdcG4xoq+le2zjOf+cYDEiN4Ctdl+HyrCL"
4
4
  }
@@ -1,3 +1,3 @@
1
- "use strict";var MdbaseConnect=(()=>{var pt=Object.defineProperty;var ii=Object.getOwnPropertyDescriptor;var oi=Object.getOwnPropertyNames;var ri=Object.prototype.hasOwnProperty;var ai=(n,e)=>{for(var t in e)pt(n,t,{get:e[t],enumerable:!0})},si=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of oi(e))!ri.call(n,o)&&o!==t&&pt(n,o,{get:()=>e[o],enumerable:!(i=ii(e,o))||i.enumerable});return n};var ci=n=>si(pt({},"__esModule",{value:!0}),n);var zo={};ai(zo,{ALL_CONNECT_PROBLEM_CODES:()=>Ot,AUTHORIZATION_PROBLEM_CODES:()=>ee,COLLECTION_CHANGES_PROBLEM_CODES:()=>It,COLLECTION_DESCRIPTION_PROBLEM_CODES:()=>Ie,COLLECTION_MUTATION_PROBLEM_CODES:()=>I,COLLECTION_QUERY_PROBLEM_CODES:()=>Tt,COLLECTION_READ_PROBLEM_CODES:()=>q,COLLECTION_SETUP_PROBLEM_CODES:()=>vn,COLLECTION_TYPE_PROBLEM_CODES:()=>ye,COMMON_OPERATION_PROBLEM_CODES:()=>bn,ConnectOutcomeError:()=>Qe,DIRECT_ACCESS_PROBLEM_CODES:()=>Xe,FileTransferCryptoError:()=>H,FirstContactCryptoError:()=>U,GrantFileTransferCipher:()=>ue,IndexedDbGrantKeyStore:()=>ce,MdbaseBrowserSelection:()=>Kt,MdbaseCollectionClient:()=>Ee,MdbaseConnect:()=>Bt,MdbaseConnectError:()=>S,MdbaseConnection:()=>De,MdbaseFileClient:()=>Fe,MdbaseMemorySelection:()=>jt,MdbaseSession:()=>Ne,MemoryGrantKeyStore:()=>le,NOTIFICATION_PROBLEM_CODES:()=>fe,REGISTRATION_PROBLEM_CODES:()=>Z,RelayCryptoError:()=>C,SESSION_PROBLEM_CODES:()=>no,applicationInstallationId:()=>Y,authorizationSigningMessage:()=>$e,captureConnectOutcome:()=>A,connectError:()=>c,connectFailure:()=>T,connectProblem:()=>z,connectSuccess:()=>E,createPkce:()=>Ue,decryptRelayResponse:()=>de,deriveFirstContactSas:()=>Je,encryptRelayRequest:()=>X,isRetryableConnectError:()=>eo,operationProblem:()=>At,parseMdbaseNativeNotificationData:()=>Mo,parseMdbasePushPayload:()=>ti,serverConnectError:()=>D,showMdbasePushNotification:()=>Uo,signApplicationAuthorization:()=>Te,unknownConnectProblem:()=>kt,unwrapConnectOutcome:()=>io});var J={access_denied:{category:"authorization",recovery:"reauthorize"},access_paused:{category:"availability",recovery:"resume_connector_access"},approval_window_blocked:{category:"authorization",recovery:"reauthorize"},authority_authorization_changed:{category:"authorization",recovery:"reauthorize"},authorization_cancelled:{category:"cancellation",recovery:"none"},authorization_expired:{category:"authorization",recovery:"reauthorize"},browser_required:{category:"compatibility",recovery:"none"},callback_url_required:{category:"validation",recovery:"fix_request"},change_cursor_reset:{category:"conflict",recovery:"refresh"},collection_access_denied:{category:"authorization",recovery:"reauthorize"},collection_configuration_invalid:{category:"validation",recovery:"repair_collection"},collection_contracts_missing:{category:"compatibility",recovery:"choose_collection"},collection_incompatible:{category:"compatibility",recovery:"choose_collection"},collection_invalid:{category:"validation",recovery:"repair_collection"},collection_kind_unsupported:{category:"compatibility",recovery:"choose_collection"},collection_mismatch:{category:"selection",recovery:"choose_collection"},collection_not_found:{category:"selection",recovery:"choose_collection"},collection_not_ready:{category:"selection",recovery:"choose_collection"},collection_not_selected:{category:"selection",recovery:"choose_collection"},collection_type_registry_invalid:{category:"validation",recovery:"repair_collection"},collection_version_unsupported:{category:"compatibility",recovery:"upgrade_collection"},concurrent_modification:{category:"conflict",recovery:"refresh"},connector_identity_changed:{category:"integrity",recovery:"reauthorize"},connector_offline:{category:"availability",recovery:"retry"},connector_upgrade_required:{category:"compatibility",recovery:"upgrade_connector"},device_authorization_failed:{category:"authorization",recovery:"reauthorize"},direct_operation_rejected:{category:"authorization",recovery:"reauthorize"},discovery_failed:{category:"availability",recovery:"retry"},encrypted_relay_rejected:{category:"authorization",recovery:"reauthorize"},encryption_required:{category:"authorization",recovery:"reauthorize"},expired_token:{category:"authorization",recovery:"reauthorize"},file_changed_during_move:{category:"conflict",recovery:"refresh"},file_changed_during_read:{category:"conflict",recovery:"refresh"},file_move_failed:{category:"internal",recovery:"contact_support"},file_mutation_conflict:{category:"conflict",recovery:"resolve_conflict"},file_not_found:{category:"conflict",recovery:"refresh"},file_source_mismatch:{category:"conflict",recovery:"refresh"},file_upload_incomplete:{category:"conflict",recovery:"retry"},first_contact_handler_required:{category:"compatibility",recovery:"upgrade_application"},hosted_provider_unavailable:{category:"availability",recovery:"retry"},insufficient_access:{category:"authorization",recovery:"reauthorize"},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_first_contact:{category:"integrity",recovery:"contact_support"},invalid_loopback_url:{category:"validation",recovery:"fix_request"},invalid_mutation_id:{category:"validation",recovery:"fix_request"},invalid_operation_response:{category:"integrity",recovery:"contact_support"},invalid_path:{category:"validation",recovery:"fix_request"},invalid_preflight:{category:"conflict",recovery:"refresh"},invalid_push_payload:{category:"validation",recovery:"fix_request"},invalid_push_subscription:{category:"validation",recovery:"fix_request"},invalid_request:{category:"validation",recovery:"fix_request"},invalid_token_response:{category:"integrity",recovery:"contact_support"},managed_fcm_not_declared:{category:"compatibility",recovery:"fix_request"},manifest_load_failed:{category:"availability",recovery:"retry"},manifest_required:{category:"validation",recovery:"fix_request"},missing_grant_key:{category:"authorization",recovery:"reauthorize"},no_pending_mutation:{category:"conflict",recovery:"refresh"},not_authorized:{category:"authorization",recovery:"reauthorize"},not_remote_authority:{category:"compatibility",recovery:"choose_collection"},notification_criterion_not_declared:{category:"validation",recovery:"fix_request"},notification_reauthorization_required:{category:"authorization",recovery:"reauthorize"},notification_registration_failed:{category:"availability",recovery:"retry"},notification_unregistration_failed:{category:"availability",recovery:"retry"},notifications_not_declared:{category:"compatibility",recovery:"fix_request"},notifications_unavailable:{category:"availability",recovery:"retry"},operation_cancelled:{category:"cancellation",recovery:"none"},operation_failed:{category:"internal",recovery:"contact_support"},operation_invalid:{category:"validation",recovery:"fix_request"},operation_outcome_unknown:{category:"conflict",recovery:"resolve_outcome"},path_occupied:{category:"conflict",recovery:"resolve_conflict"},pending_mutation_unresolved:{category:"conflict",recovery:"resolve_outcome"},query_snapshot_changed:{category:"conflict",recovery:"refresh"},rate_limited:{category:"availability",recovery:"retry"},redirect_uri_required:{category:"validation",recovery:"fix_request"},reference_updates_unsupported:{category:"compatibility",recovery:"fix_request"},relay_authorization_expired:{category:"authorization",recovery:"reauthorize"},relay_unavailable:{category:"availability",recovery:"retry"},sandbox_unsupported:{category:"compatibility",recovery:"fix_request"},scope_denied:{category:"authorization",recovery:"reauthorize"},stale_file_revision:{category:"conflict",recovery:"refresh"},storage_required:{category:"compatibility",recovery:"none"},sync_failed:{category:"availability",recovery:"retry"},temporarily_unavailable:{category:"availability",recovery:"retry"},timeout:{category:"availability",recovery:"retry"},token_exchange_failed:{category:"availability",recovery:"retry"},type_pack_provision_failed:{category:"validation",recovery:"repair_collection"},unknown_collection:{category:"selection",recovery:"choose_collection"},unsafe_file_path:{category:"validation",recovery:"fix_request"},unsupported_encryption:{category:"compatibility",recovery:"upgrade_application"},unsupported_operation:{category:"compatibility",recovery:"fix_request"}},li={access_denied:{type:"object",required:[],properties:{return_to:{type:"string"}}},approval_window_blocked:{type:"object",required:["user_code","verification_uri","verification_uri_complete","expires_at","interval_seconds"],properties:{user_code:{type:"string"},verification_uri:{type:"string"},verification_uri_complete:{type:"string"},expires_at:{type:"integer"},interval_seconds:{type:"integer"}}},collection_configuration_invalid:{type:"object",required:["diagnostics"],properties:{diagnostics:{type:"array",items:{type:"object"}}}},collection_contracts_missing:{type:"object",required:["contracts"],properties:{contracts:{type:"array",items:{type:"object",required:["id","version"],properties:{id:{type:"string"},version:{type:"string"}}}}}},collection_invalid:{type:"object",required:["diagnostics"],properties:{diagnostics:{type:"array",items:{type:"object"}}}},collection_type_registry_invalid:{type:"object",required:["diagnostics"],properties:{diagnostics:{type:"array",items:{type:"object"}}}},collection_version_unsupported:{type:"object",required:["current_version","required_version"],properties:{current_version:{type:"string"},required_version:{type:"string"}}},connector_offline:{type:"object",required:[],properties:{connector_name:{type:"string"}}},insufficient_access:{type:"object",required:["required_operations","granted_operations","missing_operations"],properties:{required_operations:{type:"array",items:{type:"string"}},granted_operations:{type:"array",items:{type:"string"}},missing_operations:{type:"array",items:{type:"string"}}}},operation_invalid:{type:"object",required:["diagnostics"],properties:{diagnostics:{type:"array",items:{type:"object"}},partial_result:{}}},rate_limited:{type:"object",required:[],properties:{retry_after_ms:{type:"integer"}}}};function Ht(n){return Object.hasOwn(J,n)}function Ce(n){if(!$t(n))return!1;let e=n;if(e.problem_version!==1||typeof e.message!="string"||e.message.length===0||e.operation_outcome!==void 0&&e.operation_outcome!=="not_sent"&&e.operation_outcome!=="rejected"&&e.operation_outcome!=="unknown"||e.trace_id!==void 0&&(typeof e.trace_id!="string"||e.trace_id.length===0))return!1;if(e.code==="unknown")return typeof e.server_code=="string"&&e.server_code.length>0&&e.category==="unknown"&&e.recovery==="none";if(typeof e.code!="string"||!Ht(e.code)||e.server_code!==void 0)return!1;let t=J[e.code],i=li[e.code],o=i===void 0?e.details===void 0:e.details===void 0?(i.required?.length??0)===0:ht(e.details,i);return e.category===t.category&&e.recovery===t.recovery&&o}function ht(n,e){if(e.type===void 0)return!0;if(e.type==="string")return typeof n=="string";if(e.type==="integer")return typeof n=="number"&&Number.isInteger(n);if(e.type==="number")return typeof n=="number"&&Number.isFinite(n);if(e.type==="boolean")return typeof n=="boolean";if(e.type==="array")return Array.isArray(n)&&n.every(i=>ht(i,e.items??{}));if(!$t(n))return!1;if(!e.properties)return!0;let t=n;return!Object.keys(t).every(i=>Object.hasOwn(e.properties,i))||!(e.required??[]).every(i=>Object.hasOwn(t,i))?!1:Object.entries(t).every(([i,o])=>ht(o,e.properties[i]))}function $t(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function ft(n,e,t={}){if(Ht(n)){let i=J[n],o={problem_version:1,code:n,category:i.category,recovery:i.recovery,message:e,...t.details===void 0?{}:{details:t.details},...t.operation_outcome===void 0?{}:{operation_outcome:t.operation_outcome},...t.trace_id===void 0?{}:{trace_id:t.trace_id}};if(Ce(o))return o}return{problem_version:1,code:"unknown",server_code:n,category:"unknown",recovery:"none",message:e,...t.details===void 0?{}:{details:t.details},...t.operation_outcome===void 0?{}:{operation_outcome:t.operation_outcome},...t.trace_id===void 0?{}:{trace_id:t.trace_id}}}var Vt=new Uint8Array([77,68,66,70]),Gt=1,Yt=0,Lo=new Uint8Array([77,68,66,82]);var Jt=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,b=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name="FileFrameError"}};function di(n){return n==="upload_chunk"?1:2}function ui(n){if(n===1)return"upload_chunk";if(n===2)return"download_chunk";throw new b("invalid_kind",`Unknown file frame kind ${n}`)}function pi(n){if(!n||typeof n!="object"||Array.isArray(n))throw new b("invalid_header","File frame header must be a JSON object");return n}function Be(n,e){let t=n[e];if(typeof t!="string"||t.length===0)throw new b("invalid_header",`File frame header ${e} must be a non-empty string`);return t}function qe(n,e){let t=Be(n,e);if(!Jt.test(t))throw new b("invalid_header",`File frame header ${e} must be a UUID`);return t}function Q(n,e,t=Number.MAX_SAFE_INTEGER){let i=n[e];if(!Number.isSafeInteger(i)||i<0||i>t)throw new b("invalid_header",`File frame header ${e} is outside its allowed range`);return i}function yt(n){if(n.protocol_version!==1)throw new b("unsupported_version",`Unsupported file transfer protocol ${n.protocol_version}`);if(n.protection!=="grant_aead_v1"&&n.protection!=="transport_tls")throw new b("invalid_header","Unknown file transfer protection");if(n.direction!=="upload"&&n.direction!=="download")throw new b("invalid_header","Unknown file transfer direction");for(let[e,t]of[["grant_id",n.grant_id],["authority_id",n.authority_id],["collection_id",n.collection_id],["transfer_id",n.transfer_id]])if(!Jt.test(t))throw new b("invalid_header",`File frame header ${e} must be a UUID`);for(let[e,t,i]of[["chunk_size",n.chunk_size,4194304],["chunk_index",n.chunk_index,Number.MAX_SAFE_INTEGER],["offset",n.offset,Number.MAX_SAFE_INTEGER],["plaintext_length",n.plaintext_length,4194304],["total_size",n.total_size,Number.MAX_SAFE_INTEGER]])if(!Number.isSafeInteger(t)||t<0||t>i)throw new b("invalid_header",`File frame header ${e} is outside its allowed range`);if(n.chunk_size<64*1024)throw new b("invalid_header","File frame chunk_size is below the protocol minimum");if(!Number.isSafeInteger(n.scope_epoch)||n.scope_epoch<1)throw new b("invalid_header","File frame header scope_epoch must be a positive integer");if(n.protection==="grant_aead_v1"&&!n.key_id)throw new b("invalid_header","AEAD-protected file frames require key_id");return{protocol_version:1,protection:n.protection,grant_id:n.grant_id,authority_id:n.authority_id,collection_id:n.collection_id,transfer_id:n.transfer_id,direction:n.direction,chunk_size:n.chunk_size,chunk_index:n.chunk_index,offset:n.offset,plaintext_length:n.plaintext_length,total_size:n.total_size,scope_epoch:n.scope_epoch,...n.key_id===void 0?{}:{key_id:n.key_id}}}function hi(n){let e;try{e=new TextDecoder("utf-8",{fatal:!0}).decode(n)}catch{throw new b("invalid_header","File frame header is not valid UTF-8")}let t;try{t=pi(JSON.parse(e))}catch(d){throw d instanceof b?d:new b("invalid_header","File frame header is not valid JSON")}let i=new Set(["protocol_version","protection","grant_id","authority_id","collection_id","transfer_id","direction","chunk_size","chunk_index","offset","plaintext_length","total_size","scope_epoch","key_id"]);if(Object.keys(t).some(d=>!i.has(d)))throw new b("invalid_header","File frame header contains an unknown field");let o=Q(t,"protocol_version");if(o!==1)throw new b("unsupported_version",`Unsupported file transfer protocol ${o}`);let r=Be(t,"protection"),a=Be(t,"direction"),s=t.key_id===void 0?void 0:Be(t,"key_id"),l=yt({protocol_version:1,protection:r,grant_id:qe(t,"grant_id"),authority_id:qe(t,"authority_id"),collection_id:qe(t,"collection_id"),transfer_id:qe(t,"transfer_id"),direction:a,chunk_size:Q(t,"chunk_size",4194304),chunk_index:Q(t,"chunk_index"),offset:Q(t,"offset"),plaintext_length:Q(t,"plaintext_length",4194304),total_size:Q(t,"total_size"),scope_epoch:Q(t,"scope_epoch"),...s===void 0?{}:{key_id:s}});if(JSON.stringify(l)!==e)throw new b("invalid_header","File frame header must use the canonical field order without duplicate fields or whitespace");return l}function mt(n,e,t){let i=n==="upload_chunk"?"upload":"download";if(e.direction!==i)throw new b("invalid_header",`Frame kind ${n} requires direction ${i}`);let o=e.chunk_index*e.chunk_size;if(!Number.isSafeInteger(o)||e.offset!==o)throw new b("invalid_header","Chunk offset does not match its index and protocol chunk size");if(e.offset+e.plaintext_length>e.total_size)throw new b("invalid_header","Chunk extends past the declared transfer size");let r=e.protection==="grant_aead_v1"?e.plaintext_length+16:e.plaintext_length;if(t!==r)throw new b("invalid_length","Payload length does not match the protected plaintext length")}function fi(n){return n.plaintext_length+(n.protection==="grant_aead_v1"?16:0)}function Ke(n,e){let t=yt(e),i=fi(t);mt(n,t,i);let o=new TextEncoder().encode(JSON.stringify(t));if(o.byteLength>16384)throw new b("limit_exceeded","File frame header exceeds the protocol limit");let r=new Uint8Array(16+o.byteLength);r.set(Vt,0);let a=new DataView(r.buffer,r.byteOffset,r.byteLength);return a.setUint8(4,Gt),a.setUint8(5,di(n)),a.setUint16(6,Yt,!1),a.setUint32(8,o.byteLength,!1),a.setUint32(12,i,!1),r.set(o,16),r}function Qt(n){let e=yt(n.header);if(mt(n.kind,e,n.payload.byteLength),n.payload.byteLength>4194320)throw new b("limit_exceeded","File frame payload exceeds the protocol limit");let t=Ke(n.kind,e),i=new Uint8Array(t.byteLength+n.payload.byteLength);return i.set(t,0),i.set(n.payload,t.byteLength),i}function je(n,e={}){if(n.byteLength<16)throw new b("invalid_length","File frame is shorter than its fixed prefix");if(!Vt.every((y,h)=>n[h]===y))throw new b("invalid_magic","File frame magic is not MDBF");let t=new DataView(n.buffer,n.byteOffset,n.byteLength),i=t.getUint8(4);if(i!==Gt)throw new b("unsupported_version",`Unsupported file frame version ${i}`);let o=ui(t.getUint8(5));if(t.getUint16(6,!1)!==Yt)throw new b("unsupported_flags","File frame uses unsupported flags");let r=t.getUint32(8,!1),a=t.getUint32(12,!1),s=e.maxHeaderBytes??16384,l=e.maxPayloadBytes??4194320;if(r===0)throw new b("invalid_length","File frame header must not be empty");if(r>s||a>l)throw new b("limit_exceeded","File frame exceeds the configured decode limits");let d=16+r+a;if(!Number.isSafeInteger(d)||d!==n.byteLength)throw new b("invalid_length","File frame lengths do not match the supplied bytes");let p=16+r,u=hi(n.subarray(16,p));return mt(o,u,a),{kind:o,header:u,payload:n.slice(p)}}var yi=new TextEncoder().encode("mdbase-connect application installation id v1\0"),mi=new TextEncoder().encode("mdbase-connect application authorization proof\0");async function Wt(n,e){let t=re(n),i=re(e);if(en(t,i))throw new Error("Application installation agreement and signing keys must be distinct.");let r=new Uint8Array(await crypto.subtle.digest("SHA-256",ae([yi,O(t),O(i)]))).slice(0,16);return r[6]=r[6]&15|128,r[8]=r[8]&63|128,[Pe(r.slice(0,4)),Pe(r.slice(4,6)),Pe(r.slice(6,8)),Pe(r.slice(8,10)),Pe(r.slice(10,16))].join("-")}function $e(n){let e=[re(n.installation_agreement_public_key),re(n.installation_signing_public_key),re(n.grant_agreement_public_key),re(n.grant_signing_public_key)];if(e.some((r,a)=>e.slice(a+1).some(s=>en(r,s))))throw new Error("Application authorization keys must be distinct.");let t=_t(n.authorization_nonce),i=_t(n.code_challenge);if(n.protocol_version!==1||t.byteLength!==32||!/^[0-9a-f]{64}$/u.test(n.application_manifest_digest)||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/u.test(n.issued_at)||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/u.test(n.expires_at)||i.byteLength!==32||n.requested_operations.length===0&&n.requested_files===void 0||new Set(n.requested_operations).size!==n.requested_operations.length||n.requested_operations.some(r=>!r||r.includes("\0"))||(n.flow==="authorization_code"?n.redirect_uri===void 0||n.state===void 0:n.flow!=="device_code"||n.redirect_uri!==void 0||n.state!==void 0))throw new Error("Application authorization binding is invalid.");_i(n.requested_files);let o=n.requested_operations.map(r=>O(new TextEncoder().encode(r)));return ae([mi,Se(n.protocol_version),O(He(n.application_id)),O(He(n.authorization_id)),O(Zt(n.application_manifest_digest)),O(He(n.application_installation_id)),...e.map(O),O(new TextEncoder().encode(n.flow)),O(t),O(new TextEncoder().encode(n.issued_at)),O(new TextEncoder().encode(n.expires_at)),Xt(n.redirect_uri),Xt(n.state),O(new TextEncoder().encode(n.code_challenge)),Se(o.length),...o,gi(n.requested_files),bi(n.collection_id)])}function _i(n){if(n!==void 0&&(n.actions.length===0||new Set(n.actions).size!==n.actions.length||n.scope.kind==="selected_folders"&&(n.scope.folders.length===0||new Set(n.scope.folders).size!==n.scope.folders.length||n.scope.folders.some(e=>!e||e.includes("\0")))))throw new Error("Application authorization file request is invalid.")}function gi(n){if(n===void 0)return new Uint8Array([0]);let e=n.actions.map(t=>O(new TextEncoder().encode(t)));return ae([new Uint8Array([1]),Se(e.length),...e,O(new TextEncoder().encode(n.scope.kind)),...n.scope.kind==="selected_folders"?[Se(n.scope.folders.length),...n.scope.folders.map(t=>O(new TextEncoder().encode(t)))]:[]])}function Xt(n){return n===void 0?new Uint8Array([0]):ae([new Uint8Array([1]),O(new TextEncoder().encode(n))])}function bi(n){return n===void 0?new Uint8Array([0]):ae([new Uint8Array([1]),O(He(n))])}function re(n){let e=_t(n);if(e.byteLength!==65||e[0]!==4)throw new Error("Application authorization public key is invalid.");return e}function _t(n){if(!/^[A-Za-z0-9_-]+$/u.test(n))throw new Error("Invalid base64url value.");let e=n.replaceAll("-","+").replaceAll("_","/"),t=e.padEnd(Math.ceil(e.length/4)*4,"="),i=Uint8Array.from(atob(t),o=>o.charCodeAt(0));if(vi(i)!==n)throw new Error("Non-canonical base64url value.");return i}function He(n){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu.test(n))throw new Error("Invalid UUID value.");let e=n.replaceAll("-","");return Zt(e)}function Zt(n){if(!/^[0-9a-f]+$/u.test(n)||n.length%2!==0)throw new Error("Invalid hexadecimal value.");return Uint8Array.from({length:n.length/2},(e,t)=>Number.parseInt(n.slice(t*2,t*2+2),16))}function O(n){return ae([Se(n.byteLength),n])}function Se(n){let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,n,!1),e}function ae(n){let e=new Uint8Array(n.reduce((i,o)=>i+o.byteLength,0)),t=0;for(let i of n)e.set(i,t),t+=i.byteLength;return e}function vi(n){return btoa(String.fromCharCode(...n)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}function en(n,e){return n.byteLength===e.byteLength&&n.every((t,i)=>t===e[i])}function Pe(n){return[...n].map(e=>e.toString(16).padStart(2,"0")).join("")}var se=1,Re=1;var tn=28485,ke="P256-HKDF-SHA256-AES256GCM";var wi="contract-setup-v1",Ci="file-relay-v1",Pi=["application-trust-v1","authorization-activation","encrypted-relay","policy-ack"],Bo=[...Pi,wi,Ci],gt=1;var nn="mdbase-authority-request-proof-v1",Ae={version:"x-mdbase-proof-version",timestamp:"x-mdbase-proof-timestamp",nonce:"x-mdbase-proof-nonce",signature:"x-mdbase-proof-signature"};var Si="mdbase-connect-keys",G="grant-keys",vt=18446744073709551615n,Ri="mdbase-connect relay request key v1",ki="mdbase-connect relay response key v1",on=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,ce=class{database=null;async create(e){let t=await cn(e),i=await this.open();return await an(i,o=>o.add({...t,counter:"0"})),t}async get(e){let t=await this.open(),i=await Ei(t.transaction(G).objectStore(G).get(e));return i?{handle:i.handle,agreementPrivateKey:i.agreementPrivateKey,agreementPublicKey:i.agreementPublicKey,signingPrivateKey:i.signingPrivateKey,signingPublicKey:i.signingPublicKey}:null}async nextCounter(e){let t=await this.open();return new Promise((i,o)=>{let r=t.transaction(G,"readwrite"),a=r.objectStore(G),s=a.get(e),l=null;s.onerror=()=>o(s.error),s.onsuccess=()=>{let d=s.result;if(!d){r.abort(),o(new C("missing_grant_key","The encrypted grant key is unavailable."));return}let p=BigInt(d.counter)+1n;if(p>vt){r.abort(),o(new C("counter_exhausted","The encrypted grant must be authorized again."));return}l=p.toString(),a.put({...d,counter:l})},r.onerror=()=>o(r.error),r.onabort=()=>o(r.error??new Error("Key counter transaction aborted.")),r.oncomplete=()=>{l&&i(l)}})}async delete(e){let t=await this.open();await an(t,i=>i.delete(e))}open(){if(typeof indexedDB>"u")throw new C("key_storage_unavailable","Encrypted relay authorization requires browser IndexedDB or an injected grant key store.");return this.database||(this.database=new Promise((e,t)=>{let i=indexedDB.open(Si,1);i.onupgradeneeded=()=>{i.result.objectStoreNames.contains(G)||i.result.createObjectStore(G,{keyPath:"handle"})},i.onerror=()=>t(i.error),i.onsuccess=()=>e(i.result)})),this.database}},le=class{records=new Map;sequence=Promise.resolve();async create(e){if(this.records.has(e))throw new Error(`Grant key already exists: ${e}`);let t=await cn(e);return this.records.set(e,{...t,counter:"0"}),t}async get(e){let t=this.records.get(e);return t?{handle:t.handle,agreementPrivateKey:t.agreementPrivateKey,agreementPublicKey:t.agreementPublicKey,signingPrivateKey:t.signingPrivateKey,signingPublicKey:t.signingPublicKey}:null}nextCounter(e){let t,i,o=new Promise((r,a)=>{t=r,i=a});return this.sequence=this.sequence.then(()=>{let r=this.records.get(e);if(!r)throw new C("missing_grant_key","The encrypted grant key is unavailable.");let a=BigInt(r.counter)+1n;if(a>vt)throw new C("counter_exhausted","The encrypted grant must be authorized again.");r.counter=a.toString(),t(r.counter)}).catch(r=>{i(r)}),o}async delete(e){this.records.delete(e)}};async function sn(n,e,t,i){let o=await Oi(n,e,t),r=i.timestamp??Math.floor(Date.now()/1e3),a=i.nonce??crypto.randomUUID(),s=await Ai({...i,timestamp:r,nonce:a}),l=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},o.signingPrivateKey,new TextEncoder().encode(s));return{[Ae.version]:String(gt),[Ae.timestamp]:String(r),[Ae.nonce]:a,[Ae.signature]:Oe(new Uint8Array(l))}}async function Ai(n){let e=n.method.toUpperCase(),t=await rn(n.body??""),i=await rn(n.credential);for(let o of[e,n.target,String(n.timestamp),n.nonce])if(!o||o.includes(`
1
+ "use strict";var MdbaseConnect=(()=>{var pt=Object.defineProperty;var ii=Object.getOwnPropertyDescriptor;var oi=Object.getOwnPropertyNames;var ri=Object.prototype.hasOwnProperty;var ai=(n,e)=>{for(var t in e)pt(n,t,{get:e[t],enumerable:!0})},si=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of oi(e))!ri.call(n,o)&&o!==t&&pt(n,o,{get:()=>e[o],enumerable:!(i=ii(e,o))||i.enumerable});return n};var ci=n=>si(pt({},"__esModule",{value:!0}),n);var zo={};ai(zo,{ALL_CONNECT_PROBLEM_CODES:()=>Ot,AUTHORIZATION_PROBLEM_CODES:()=>ee,COLLECTION_CHANGES_PROBLEM_CODES:()=>It,COLLECTION_DESCRIPTION_PROBLEM_CODES:()=>Ie,COLLECTION_MUTATION_PROBLEM_CODES:()=>I,COLLECTION_QUERY_PROBLEM_CODES:()=>Tt,COLLECTION_READ_PROBLEM_CODES:()=>q,COLLECTION_SETUP_PROBLEM_CODES:()=>vn,COLLECTION_TYPE_PROBLEM_CODES:()=>te,COMMON_OPERATION_PROBLEM_CODES:()=>bn,ConnectOutcomeError:()=>Qe,DIRECT_ACCESS_PROBLEM_CODES:()=>Xe,FileTransferCryptoError:()=>H,FirstContactCryptoError:()=>U,GrantFileTransferCipher:()=>pe,IndexedDbGrantKeyStore:()=>le,MdbaseBrowserSelection:()=>Kt,MdbaseCollectionClient:()=>Ee,MdbaseConnect:()=>Bt,MdbaseConnectError:()=>S,MdbaseConnection:()=>De,MdbaseFileClient:()=>Fe,MdbaseMemorySelection:()=>jt,MdbaseSession:()=>Ne,MemoryGrantKeyStore:()=>de,NOTIFICATION_PROBLEM_CODES:()=>ye,REGISTRATION_PROBLEM_CODES:()=>Z,RelayCryptoError:()=>C,SESSION_PROBLEM_CODES:()=>no,applicationInstallationId:()=>Y,authorizationSigningMessage:()=>$e,captureConnectOutcome:()=>A,connectError:()=>c,connectFailure:()=>T,connectProblem:()=>z,connectSuccess:()=>E,createPkce:()=>Ue,decryptRelayResponse:()=>ue,deriveFirstContactSas:()=>Je,encryptRelayRequest:()=>X,isRetryableConnectError:()=>eo,operationProblem:()=>At,parseMdbaseNativeNotificationData:()=>Mo,parseMdbasePushPayload:()=>ti,serverConnectError:()=>D,showMdbasePushNotification:()=>Uo,signApplicationAuthorization:()=>Te,unknownConnectProblem:()=>Rt,unwrapConnectOutcome:()=>io});var J={access_denied:{category:"authorization",recovery:"reauthorize"},access_paused:{category:"availability",recovery:"resume_connector_access"},approval_window_blocked:{category:"authorization",recovery:"reauthorize"},authority_authorization_changed:{category:"authorization",recovery:"reauthorize"},authorization_cancelled:{category:"cancellation",recovery:"none"},authorization_expired:{category:"authorization",recovery:"reauthorize"},browser_required:{category:"compatibility",recovery:"none"},callback_url_required:{category:"validation",recovery:"fix_request"},change_cursor_reset:{category:"conflict",recovery:"refresh"},collection_access_denied:{category:"authorization",recovery:"reauthorize"},collection_configuration_invalid:{category:"validation",recovery:"repair_collection"},collection_contracts_missing:{category:"compatibility",recovery:"choose_collection"},collection_incompatible:{category:"compatibility",recovery:"choose_collection"},collection_invalid:{category:"validation",recovery:"repair_collection"},collection_kind_unsupported:{category:"compatibility",recovery:"choose_collection"},collection_mismatch:{category:"selection",recovery:"choose_collection"},collection_not_found:{category:"selection",recovery:"choose_collection"},collection_not_ready:{category:"selection",recovery:"choose_collection"},collection_not_selected:{category:"selection",recovery:"choose_collection"},collection_type_registry_invalid:{category:"validation",recovery:"repair_collection"},collection_version_unsupported:{category:"compatibility",recovery:"upgrade_collection"},concurrent_modification:{category:"conflict",recovery:"refresh"},connector_identity_changed:{category:"integrity",recovery:"reauthorize"},connector_offline:{category:"availability",recovery:"retry"},connector_upgrade_required:{category:"compatibility",recovery:"upgrade_connector"},device_authorization_failed:{category:"authorization",recovery:"reauthorize"},direct_operation_rejected:{category:"authorization",recovery:"reauthorize"},discovery_failed:{category:"availability",recovery:"retry"},encrypted_relay_rejected:{category:"authorization",recovery:"reauthorize"},encryption_required:{category:"authorization",recovery:"reauthorize"},expired_token:{category:"authorization",recovery:"reauthorize"},file_changed_during_move:{category:"conflict",recovery:"refresh"},file_changed_during_read:{category:"conflict",recovery:"refresh"},file_move_failed:{category:"internal",recovery:"contact_support"},file_mutation_conflict:{category:"conflict",recovery:"resolve_conflict"},file_not_found:{category:"conflict",recovery:"refresh"},file_source_mismatch:{category:"conflict",recovery:"refresh"},file_upload_incomplete:{category:"conflict",recovery:"retry"},first_contact_handler_required:{category:"compatibility",recovery:"upgrade_application"},hosted_provider_unavailable:{category:"availability",recovery:"retry"},insufficient_access:{category:"authorization",recovery:"reauthorize"},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_first_contact:{category:"integrity",recovery:"contact_support"},invalid_loopback_url:{category:"validation",recovery:"fix_request"},invalid_mutation_id:{category:"validation",recovery:"fix_request"},invalid_operation_response:{category:"integrity",recovery:"contact_support"},invalid_path:{category:"validation",recovery:"fix_request"},invalid_preflight:{category:"conflict",recovery:"refresh"},invalid_push_payload:{category:"validation",recovery:"fix_request"},invalid_push_subscription:{category:"validation",recovery:"fix_request"},invalid_request:{category:"validation",recovery:"fix_request"},invalid_token_response:{category:"integrity",recovery:"contact_support"},managed_fcm_not_declared:{category:"compatibility",recovery:"fix_request"},manifest_load_failed:{category:"availability",recovery:"retry"},manifest_required:{category:"validation",recovery:"fix_request"},missing_grant_key:{category:"authorization",recovery:"reauthorize"},no_pending_mutation:{category:"conflict",recovery:"refresh"},not_authorized:{category:"authorization",recovery:"reauthorize"},not_remote_authority:{category:"compatibility",recovery:"choose_collection"},notification_criterion_not_declared:{category:"validation",recovery:"fix_request"},notification_reauthorization_required:{category:"authorization",recovery:"reauthorize"},notification_registration_failed:{category:"availability",recovery:"retry"},notification_unregistration_failed:{category:"availability",recovery:"retry"},notifications_not_declared:{category:"compatibility",recovery:"fix_request"},notifications_unavailable:{category:"availability",recovery:"retry"},operation_cancelled:{category:"cancellation",recovery:"none"},operation_failed:{category:"internal",recovery:"contact_support"},operation_invalid:{category:"validation",recovery:"fix_request"},operation_outcome_unknown:{category:"conflict",recovery:"resolve_outcome"},path_occupied:{category:"conflict",recovery:"resolve_conflict"},pending_mutation_unresolved:{category:"conflict",recovery:"resolve_outcome"},query_snapshot_changed:{category:"conflict",recovery:"refresh"},rate_limited:{category:"availability",recovery:"retry"},redirect_uri_required:{category:"validation",recovery:"fix_request"},reference_updates_unsupported:{category:"compatibility",recovery:"fix_request"},relay_authorization_expired:{category:"authorization",recovery:"reauthorize"},relay_unavailable:{category:"availability",recovery:"retry"},sandbox_unsupported:{category:"compatibility",recovery:"fix_request"},scope_denied:{category:"authorization",recovery:"reauthorize"},stale_file_revision:{category:"conflict",recovery:"refresh"},storage_required:{category:"compatibility",recovery:"none"},sync_failed:{category:"availability",recovery:"retry"},temporarily_unavailable:{category:"availability",recovery:"retry"},timeout:{category:"availability",recovery:"retry"},token_exchange_failed:{category:"availability",recovery:"retry"},type_pack_provision_failed:{category:"validation",recovery:"repair_collection"},unknown_collection:{category:"selection",recovery:"choose_collection"},unsafe_file_path:{category:"validation",recovery:"fix_request"},unsupported_encryption:{category:"compatibility",recovery:"upgrade_application"},unsupported_operation:{category:"compatibility",recovery:"fix_request"}},li={access_denied:{type:"object",required:[],properties:{return_to:{type:"string"}}},approval_window_blocked:{type:"object",required:["user_code","verification_uri","verification_uri_complete","expires_at","interval_seconds"],properties:{user_code:{type:"string"},verification_uri:{type:"string"},verification_uri_complete:{type:"string"},expires_at:{type:"integer"},interval_seconds:{type:"integer"}}},collection_configuration_invalid:{type:"object",required:["diagnostics"],properties:{diagnostics:{type:"array",items:{type:"object"}}}},collection_contracts_missing:{type:"object",required:["contracts"],properties:{contracts:{type:"array",items:{type:"object",required:["id","version"],properties:{id:{type:"string"},version:{type:"string"}}}}}},collection_invalid:{type:"object",required:["diagnostics"],properties:{diagnostics:{type:"array",items:{type:"object"}}}},collection_type_registry_invalid:{type:"object",required:["diagnostics"],properties:{diagnostics:{type:"array",items:{type:"object"}}}},collection_version_unsupported:{type:"object",required:["current_version","required_version"],properties:{current_version:{type:"string"},required_version:{type:"string"}}},connector_offline:{type:"object",required:[],properties:{connector_name:{type:"string"}}},insufficient_access:{type:"object",required:["required_operations","granted_operations","missing_operations"],properties:{required_operations:{type:"array",items:{type:"string"}},granted_operations:{type:"array",items:{type:"string"}},missing_operations:{type:"array",items:{type:"string"}}}},operation_invalid:{type:"object",required:["diagnostics"],properties:{diagnostics:{type:"array",items:{type:"object"}},partial_result:{}}},rate_limited:{type:"object",required:[],properties:{retry_after_ms:{type:"integer"}}}};function Ht(n){return Object.hasOwn(J,n)}function Ce(n){if(!$t(n))return!1;let e=n;if(e.problem_version!==1||typeof e.message!="string"||e.message.length===0||e.operation_outcome!==void 0&&e.operation_outcome!=="not_sent"&&e.operation_outcome!=="rejected"&&e.operation_outcome!=="unknown"||e.trace_id!==void 0&&(typeof e.trace_id!="string"||e.trace_id.length===0))return!1;if(e.code==="unknown")return typeof e.server_code=="string"&&e.server_code.length>0&&e.category==="unknown"&&e.recovery==="none";if(typeof e.code!="string"||!Ht(e.code)||e.server_code!==void 0)return!1;let t=J[e.code],i=li[e.code],o=i===void 0?e.details===void 0:e.details===void 0?(i.required?.length??0)===0:ht(e.details,i);return e.category===t.category&&e.recovery===t.recovery&&o}function ht(n,e){if(e.type===void 0)return!0;if(e.type==="string")return typeof n=="string";if(e.type==="integer")return typeof n=="number"&&Number.isInteger(n);if(e.type==="number")return typeof n=="number"&&Number.isFinite(n);if(e.type==="boolean")return typeof n=="boolean";if(e.type==="array")return Array.isArray(n)&&n.every(i=>ht(i,e.items??{}));if(!$t(n))return!1;if(!e.properties)return!0;let t=n;return!Object.keys(t).every(i=>Object.hasOwn(e.properties,i))||!(e.required??[]).every(i=>Object.hasOwn(t,i))?!1:Object.entries(t).every(([i,o])=>ht(o,e.properties[i]))}function $t(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function ft(n,e,t={}){if(Ht(n)){let i=J[n],o={problem_version:1,code:n,category:i.category,recovery:i.recovery,message:e,...t.details===void 0?{}:{details:t.details},...t.operation_outcome===void 0?{}:{operation_outcome:t.operation_outcome},...t.trace_id===void 0?{}:{trace_id:t.trace_id}};if(Ce(o))return o}return{problem_version:1,code:"unknown",server_code:n,category:"unknown",recovery:"none",message:e,...t.details===void 0?{}:{details:t.details},...t.operation_outcome===void 0?{}:{operation_outcome:t.operation_outcome},...t.trace_id===void 0?{}:{trace_id:t.trace_id}}}var Vt=new Uint8Array([77,68,66,70]),Gt=1,Yt=0,Lo=new Uint8Array([77,68,66,82]);var Jt=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,b=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name="FileFrameError"}};function di(n){return n==="upload_chunk"?1:2}function ui(n){if(n===1)return"upload_chunk";if(n===2)return"download_chunk";throw new b("invalid_kind",`Unknown file frame kind ${n}`)}function pi(n){if(!n||typeof n!="object"||Array.isArray(n))throw new b("invalid_header","File frame header must be a JSON object");return n}function Be(n,e){let t=n[e];if(typeof t!="string"||t.length===0)throw new b("invalid_header",`File frame header ${e} must be a non-empty string`);return t}function qe(n,e){let t=Be(n,e);if(!Jt.test(t))throw new b("invalid_header",`File frame header ${e} must be a UUID`);return t}function Q(n,e,t=Number.MAX_SAFE_INTEGER){let i=n[e];if(!Number.isSafeInteger(i)||i<0||i>t)throw new b("invalid_header",`File frame header ${e} is outside its allowed range`);return i}function yt(n){if(n.protocol_version!==1)throw new b("unsupported_version",`Unsupported file transfer protocol ${n.protocol_version}`);if(n.protection!=="grant_aead_v1"&&n.protection!=="transport_tls")throw new b("invalid_header","Unknown file transfer protection");if(n.direction!=="upload"&&n.direction!=="download")throw new b("invalid_header","Unknown file transfer direction");for(let[e,t]of[["grant_id",n.grant_id],["authority_id",n.authority_id],["collection_id",n.collection_id],["transfer_id",n.transfer_id]])if(!Jt.test(t))throw new b("invalid_header",`File frame header ${e} must be a UUID`);for(let[e,t,i]of[["chunk_size",n.chunk_size,4194304],["chunk_index",n.chunk_index,Number.MAX_SAFE_INTEGER],["offset",n.offset,Number.MAX_SAFE_INTEGER],["plaintext_length",n.plaintext_length,4194304],["total_size",n.total_size,Number.MAX_SAFE_INTEGER]])if(!Number.isSafeInteger(t)||t<0||t>i)throw new b("invalid_header",`File frame header ${e} is outside its allowed range`);if(n.chunk_size<64*1024)throw new b("invalid_header","File frame chunk_size is below the protocol minimum");if(!Number.isSafeInteger(n.scope_epoch)||n.scope_epoch<1)throw new b("invalid_header","File frame header scope_epoch must be a positive integer");if(n.protection==="grant_aead_v1"&&!n.key_id)throw new b("invalid_header","AEAD-protected file frames require key_id");return{protocol_version:1,protection:n.protection,grant_id:n.grant_id,authority_id:n.authority_id,collection_id:n.collection_id,transfer_id:n.transfer_id,direction:n.direction,chunk_size:n.chunk_size,chunk_index:n.chunk_index,offset:n.offset,plaintext_length:n.plaintext_length,total_size:n.total_size,scope_epoch:n.scope_epoch,...n.key_id===void 0?{}:{key_id:n.key_id}}}function hi(n){let e;try{e=new TextDecoder("utf-8",{fatal:!0}).decode(n)}catch{throw new b("invalid_header","File frame header is not valid UTF-8")}let t;try{t=pi(JSON.parse(e))}catch(d){throw d instanceof b?d:new b("invalid_header","File frame header is not valid JSON")}let i=new Set(["protocol_version","protection","grant_id","authority_id","collection_id","transfer_id","direction","chunk_size","chunk_index","offset","plaintext_length","total_size","scope_epoch","key_id"]);if(Object.keys(t).some(d=>!i.has(d)))throw new b("invalid_header","File frame header contains an unknown field");let o=Q(t,"protocol_version");if(o!==1)throw new b("unsupported_version",`Unsupported file transfer protocol ${o}`);let r=Be(t,"protection"),a=Be(t,"direction"),s=t.key_id===void 0?void 0:Be(t,"key_id"),l=yt({protocol_version:1,protection:r,grant_id:qe(t,"grant_id"),authority_id:qe(t,"authority_id"),collection_id:qe(t,"collection_id"),transfer_id:qe(t,"transfer_id"),direction:a,chunk_size:Q(t,"chunk_size",4194304),chunk_index:Q(t,"chunk_index"),offset:Q(t,"offset"),plaintext_length:Q(t,"plaintext_length",4194304),total_size:Q(t,"total_size"),scope_epoch:Q(t,"scope_epoch"),...s===void 0?{}:{key_id:s}});if(JSON.stringify(l)!==e)throw new b("invalid_header","File frame header must use the canonical field order without duplicate fields or whitespace");return l}function mt(n,e,t){let i=n==="upload_chunk"?"upload":"download";if(e.direction!==i)throw new b("invalid_header",`Frame kind ${n} requires direction ${i}`);let o=e.chunk_index*e.chunk_size;if(!Number.isSafeInteger(o)||e.offset!==o)throw new b("invalid_header","Chunk offset does not match its index and protocol chunk size");if(e.offset+e.plaintext_length>e.total_size)throw new b("invalid_header","Chunk extends past the declared transfer size");let r=e.protection==="grant_aead_v1"?e.plaintext_length+16:e.plaintext_length;if(t!==r)throw new b("invalid_length","Payload length does not match the protected plaintext length")}function fi(n){return n.plaintext_length+(n.protection==="grant_aead_v1"?16:0)}function Ke(n,e){let t=yt(e),i=fi(t);mt(n,t,i);let o=new TextEncoder().encode(JSON.stringify(t));if(o.byteLength>16384)throw new b("limit_exceeded","File frame header exceeds the protocol limit");let r=new Uint8Array(16+o.byteLength);r.set(Vt,0);let a=new DataView(r.buffer,r.byteOffset,r.byteLength);return a.setUint8(4,Gt),a.setUint8(5,di(n)),a.setUint16(6,Yt,!1),a.setUint32(8,o.byteLength,!1),a.setUint32(12,i,!1),r.set(o,16),r}function Qt(n){let e=yt(n.header);if(mt(n.kind,e,n.payload.byteLength),n.payload.byteLength>4194320)throw new b("limit_exceeded","File frame payload exceeds the protocol limit");let t=Ke(n.kind,e),i=new Uint8Array(t.byteLength+n.payload.byteLength);return i.set(t,0),i.set(n.payload,t.byteLength),i}function je(n,e={}){if(n.byteLength<16)throw new b("invalid_length","File frame is shorter than its fixed prefix");if(!Vt.every((y,h)=>n[h]===y))throw new b("invalid_magic","File frame magic is not MDBF");let t=new DataView(n.buffer,n.byteOffset,n.byteLength),i=t.getUint8(4);if(i!==Gt)throw new b("unsupported_version",`Unsupported file frame version ${i}`);let o=ui(t.getUint8(5));if(t.getUint16(6,!1)!==Yt)throw new b("unsupported_flags","File frame uses unsupported flags");let r=t.getUint32(8,!1),a=t.getUint32(12,!1),s=e.maxHeaderBytes??16384,l=e.maxPayloadBytes??4194320;if(r===0)throw new b("invalid_length","File frame header must not be empty");if(r>s||a>l)throw new b("limit_exceeded","File frame exceeds the configured decode limits");let d=16+r+a;if(!Number.isSafeInteger(d)||d!==n.byteLength)throw new b("invalid_length","File frame lengths do not match the supplied bytes");let p=16+r,u=hi(n.subarray(16,p));return mt(o,u,a),{kind:o,header:u,payload:n.slice(p)}}var yi=new TextEncoder().encode("mdbase-connect application installation id v1\0"),mi=new TextEncoder().encode("mdbase-connect application authorization proof\0");async function Wt(n,e){let t=ae(n),i=ae(e);if(en(t,i))throw new Error("Application installation agreement and signing keys must be distinct.");let r=new Uint8Array(await crypto.subtle.digest("SHA-256",se([yi,O(t),O(i)]))).slice(0,16);return r[6]=r[6]&15|128,r[8]=r[8]&63|128,[Pe(r.slice(0,4)),Pe(r.slice(4,6)),Pe(r.slice(6,8)),Pe(r.slice(8,10)),Pe(r.slice(10,16))].join("-")}function $e(n){let e=[ae(n.installation_agreement_public_key),ae(n.installation_signing_public_key),ae(n.grant_agreement_public_key),ae(n.grant_signing_public_key)];if(e.some((r,a)=>e.slice(a+1).some(s=>en(r,s))))throw new Error("Application authorization keys must be distinct.");let t=_t(n.authorization_nonce),i=_t(n.code_challenge);if(n.protocol_version!==1||t.byteLength!==32||!/^[0-9a-f]{64}$/u.test(n.application_manifest_digest)||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/u.test(n.issued_at)||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/u.test(n.expires_at)||i.byteLength!==32||n.requested_operations.length===0&&n.requested_files===void 0||new Set(n.requested_operations).size!==n.requested_operations.length||n.requested_operations.some(r=>!r||r.includes("\0"))||(n.flow==="authorization_code"?n.redirect_uri===void 0||n.state===void 0:n.flow!=="device_code"||n.redirect_uri!==void 0||n.state!==void 0))throw new Error("Application authorization binding is invalid.");_i(n.requested_files);let o=n.requested_operations.map(r=>O(new TextEncoder().encode(r)));return se([mi,Se(n.protocol_version),O(He(n.application_id)),O(He(n.authorization_id)),O(Zt(n.application_manifest_digest)),O(He(n.application_installation_id)),...e.map(O),O(new TextEncoder().encode(n.flow)),O(t),O(new TextEncoder().encode(n.issued_at)),O(new TextEncoder().encode(n.expires_at)),Xt(n.redirect_uri),Xt(n.state),O(new TextEncoder().encode(n.code_challenge)),Se(o.length),...o,gi(n.requested_files),bi(n.collection_id)])}function _i(n){if(n!==void 0&&(n.actions.length===0||new Set(n.actions).size!==n.actions.length||n.scope.kind==="selected_folders"&&(n.scope.folders.length===0||new Set(n.scope.folders).size!==n.scope.folders.length||n.scope.folders.some(e=>!e||e.includes("\0")))))throw new Error("Application authorization file request is invalid.")}function gi(n){if(n===void 0)return new Uint8Array([0]);let e=n.actions.map(t=>O(new TextEncoder().encode(t)));return se([new Uint8Array([1]),Se(e.length),...e,O(new TextEncoder().encode(n.scope.kind)),...n.scope.kind==="selected_folders"?[Se(n.scope.folders.length),...n.scope.folders.map(t=>O(new TextEncoder().encode(t)))]:[]])}function Xt(n){return n===void 0?new Uint8Array([0]):se([new Uint8Array([1]),O(new TextEncoder().encode(n))])}function bi(n){return n===void 0?new Uint8Array([0]):se([new Uint8Array([1]),O(He(n))])}function ae(n){let e=_t(n);if(e.byteLength!==65||e[0]!==4)throw new Error("Application authorization public key is invalid.");return e}function _t(n){if(!/^[A-Za-z0-9_-]+$/u.test(n))throw new Error("Invalid base64url value.");let e=n.replaceAll("-","+").replaceAll("_","/"),t=e.padEnd(Math.ceil(e.length/4)*4,"="),i=Uint8Array.from(atob(t),o=>o.charCodeAt(0));if(vi(i)!==n)throw new Error("Non-canonical base64url value.");return i}function He(n){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu.test(n))throw new Error("Invalid UUID value.");let e=n.replaceAll("-","");return Zt(e)}function Zt(n){if(!/^[0-9a-f]+$/u.test(n)||n.length%2!==0)throw new Error("Invalid hexadecimal value.");return Uint8Array.from({length:n.length/2},(e,t)=>Number.parseInt(n.slice(t*2,t*2+2),16))}function O(n){return se([Se(n.byteLength),n])}function Se(n){let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,n,!1),e}function se(n){let e=new Uint8Array(n.reduce((i,o)=>i+o.byteLength,0)),t=0;for(let i of n)e.set(i,t),t+=i.byteLength;return e}function vi(n){return btoa(String.fromCharCode(...n)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}function en(n,e){return n.byteLength===e.byteLength&&n.every((t,i)=>t===e[i])}function Pe(n){return[...n].map(e=>e.toString(16).padStart(2,"0")).join("")}var ce=1,ke=1;var tn=28485,Re="P256-HKDF-SHA256-AES256GCM";var wi="contract-setup-v1",Ci="file-relay-v1",Pi=["application-trust-v1","authorization-activation","encrypted-relay","policy-ack"],Bo=[...Pi,wi,Ci],gt=1;var nn="mdbase-authority-request-proof-v1",Ae={version:"x-mdbase-proof-version",timestamp:"x-mdbase-proof-timestamp",nonce:"x-mdbase-proof-nonce",signature:"x-mdbase-proof-signature"};var Si="mdbase-connect-keys",G="grant-keys",vt=18446744073709551615n,ki="mdbase-connect relay request key v1",Ri="mdbase-connect relay response key v1",on=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,le=class{database=null;async create(e){let t=await cn(e),i=await this.open();return await an(i,o=>o.add({...t,counter:"0"})),t}async get(e){let t=await this.open(),i=await Ei(t.transaction(G).objectStore(G).get(e));return i?{handle:i.handle,agreementPrivateKey:i.agreementPrivateKey,agreementPublicKey:i.agreementPublicKey,signingPrivateKey:i.signingPrivateKey,signingPublicKey:i.signingPublicKey}:null}async nextCounter(e){let t=await this.open();return new Promise((i,o)=>{let r=t.transaction(G,"readwrite"),a=r.objectStore(G),s=a.get(e),l=null;s.onerror=()=>o(s.error),s.onsuccess=()=>{let d=s.result;if(!d){r.abort(),o(new C("missing_grant_key","The encrypted grant key is unavailable."));return}let p=BigInt(d.counter)+1n;if(p>vt){r.abort(),o(new C("counter_exhausted","The encrypted grant must be authorized again."));return}l=p.toString(),a.put({...d,counter:l})},r.onerror=()=>o(r.error),r.onabort=()=>o(r.error??new Error("Key counter transaction aborted.")),r.oncomplete=()=>{l&&i(l)}})}async delete(e){let t=await this.open();await an(t,i=>i.delete(e))}open(){if(typeof indexedDB>"u")throw new C("key_storage_unavailable","Encrypted relay authorization requires browser IndexedDB or an injected grant key store.");return this.database||(this.database=new Promise((e,t)=>{let i=indexedDB.open(Si,1);i.onupgradeneeded=()=>{i.result.objectStoreNames.contains(G)||i.result.createObjectStore(G,{keyPath:"handle"})},i.onerror=()=>t(i.error),i.onsuccess=()=>e(i.result)})),this.database}},de=class{records=new Map;sequence=Promise.resolve();async create(e){if(this.records.has(e))throw new Error(`Grant key already exists: ${e}`);let t=await cn(e);return this.records.set(e,{...t,counter:"0"}),t}async get(e){let t=this.records.get(e);return t?{handle:t.handle,agreementPrivateKey:t.agreementPrivateKey,agreementPublicKey:t.agreementPublicKey,signingPrivateKey:t.signingPrivateKey,signingPublicKey:t.signingPublicKey}:null}nextCounter(e){let t,i,o=new Promise((r,a)=>{t=r,i=a});return this.sequence=this.sequence.then(()=>{let r=this.records.get(e);if(!r)throw new C("missing_grant_key","The encrypted grant key is unavailable.");let a=BigInt(r.counter)+1n;if(a>vt)throw new C("counter_exhausted","The encrypted grant must be authorized again.");r.counter=a.toString(),t(r.counter)}).catch(r=>{i(r)}),o}async delete(e){this.records.delete(e)}};async function sn(n,e,t,i){let o=await Oi(n,e,t),r=i.timestamp??Math.floor(Date.now()/1e3),a=i.nonce??crypto.randomUUID(),s=await Ai({...i,timestamp:r,nonce:a}),l=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},o.signingPrivateKey,new TextEncoder().encode(s));return{[Ae.version]:String(gt),[Ae.timestamp]:String(r),[Ae.nonce]:a,[Ae.signature]:Oe(new Uint8Array(l))}}async function Ai(n){let e=n.method.toUpperCase(),t=await rn(n.body??""),i=await rn(n.credential);for(let o of[e,n.target,String(n.timestamp),n.nonce])if(!o||o.includes(`
2
2
  `)||o.includes("\r"))throw new C("invalid_proof_input","Authority request proof metadata is invalid.");return[nn,gt,e,n.target,t,i,n.timestamp,n.nonce].join(`
3
- `)}async function X(n,e,t,i,o,r=crypto.randomUUID()){W(t.encryption);let a=await ln(n,e,t.encryption.application_agreement_public_key),s=await n.nextCounter(e),l={binding:t,requestId:r,operation:i,counter:s},d=await dn(a.agreementPrivateKey,t,"request"),p=new TextEncoder().encode(JSON.stringify(o??{})),u=await crypto.subtle.encrypt({name:"AES-GCM",iv:hn(s),additionalData:new TextEncoder().encode(pn(l,"request")),tagLength:128},d,p);return{type:"encrypted_operation_request",...Ti(l),ciphertext:Oe(new Uint8Array(u))}}async function de(n,e,t,i,o){if(!Ii(i,o))throw new C("invalid_encrypted_response","Encrypted response metadata does not match its request.");let r=await ln(n,e,t.encryption.application_agreement_public_key),a={binding:t,requestId:i.request_id,operation:i.operation,counter:i.counter},s=await dn(r.agreementPrivateKey,t,"response");try{let l=await crypto.subtle.decrypt({name:"AES-GCM",iv:hn(i.counter),additionalData:new TextEncoder().encode(pn(a,"response")),tagLength:128},s,yn(fn(o.ciphertext))),d=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(l));if(d?.ok===!0&&"result"in d||d?.ok===!1&&Ce(d.problem))return d;throw new Error("invalid response body")}catch(l){throw l instanceof C?l:new C("encrypted_response_rejected","The encrypted connector response could not be authenticated.")}}var C=class extends Error{constructor(t,i){super(i);this.code=t}code};async function cn(n){let e=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"]),t=Oe(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=Oe(new Uint8Array(await crypto.subtle.exportKey("raw",r.publicKey))),s=await crypto.subtle.exportKey("pkcs8",r.privateKey),l=await crypto.subtle.importKey("pkcs8",s,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]);return{handle:n,agreementPrivateKey:o,agreementPublicKey:t,signingPrivateKey:l,signingPublicKey:a}}async function ln(n,e,t){let i=await n.get(e);if(!i||i.agreementPublicKey!==t)throw new C("missing_grant_key","The encrypted grant key is unavailable or does not match the grant.");return i}async function Oi(n,e,t){let i=await n.get(e);if(!i||i.signingPublicKey!==t)throw new C("missing_grant_key","The remote authority signing key is unavailable or does not match the grant.");return i}async function dn(n,e,t){let i=await wt(n,e.encryption.connector_agreement_public_key),o=await crypto.subtle.importKey("raw",i,"HKDF",!1,["deriveKey"]),r=new TextEncoder().encode(un(e)),a=await crypto.subtle.digest("SHA-256",r);return crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:a,info:new TextEncoder().encode(t==="request"?Ri:ki)},o,{name:"AES-GCM",length:256},!1,t==="request"?["encrypt"]:["decrypt"])}async function wt(n,e){try{let t=await crypto.subtle.importKey("raw",yn(bt(e)),{name:"ECDH",namedCurve:"P-256"},!1,[]);return await crypto.subtle.deriveBits({name:"ECDH",public:t},n,256)}catch{throw new C("invalid_public_key","The connector relay public key is invalid.")}}function un(n){let e=n.encryption;return["mdbase-connect",se,e.suite,n.grantId,n.applicationId,e.connector_id,e.collection_id,e.scope_epoch,e.key_id].join("|")}function pn(n,e){return[un(n.binding),n.requestId,e,n.operation,n.counter].join("|")}function Ti(n){let e=n.binding.encryption;return{protocol_version:se,suite:ke,request_id:n.requestId,grant_id:n.binding.grantId,application_id:n.binding.applicationId,connector_id:e.connector_id,collection_id:e.collection_id,operation:n.operation,scope_epoch:e.scope_epoch,key_id:e.key_id,counter:n.counter}}function Ii(n,e){return e.type==="encrypted_operation_response"&&typeof e.ciphertext=="string"&&n.protocol_version===e.protocol_version&&n.suite===e.suite&&n.request_id===e.request_id&&n.grant_id===e.grant_id&&n.application_id===e.application_id&&n.connector_id===e.connector_id&&n.collection_id===e.collection_id&&n.operation===e.operation&&n.scope_epoch===e.scope_epoch&&n.key_id===e.key_id&&n.counter===e.counter}function W(n){if(n.protocol_version!==se||n.suite!==ke||!Number.isSafeInteger(n.scope_epoch)||n.scope_epoch<=0||typeof n.key_id!="string"||n.key_id.length===0||n.key_id.length>200||n.key_id.includes("|"))throw new C("unsupported_encryption","The grant uses an unsupported relay encryption profile.");if(typeof n.connector_id!="string"||!on.test(n.connector_id)||typeof n.collection_id!="string"||!on.test(n.collection_id))throw new C("unsupported_encryption","The grant uses invalid encrypted relay identities.");bt(n.application_agreement_public_key),bt(n.connector_agreement_public_key)}function hn(n){let e=BigInt(n);if(e<=0n||e>vt||e.toString()!==n)throw new C("invalid_counter","The encrypted relay counter is invalid.");let t=new Uint8Array(new ArrayBuffer(12));return new DataView(t.buffer).setBigUint64(4,e,!1),t}function Oe(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}async function rn(n){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n));return Oe(new Uint8Array(e))}function fn(n){if(!/^[A-Za-z0-9_-]+$/.test(n))throw new C("invalid_base64","Encrypted relay data is malformed.");let e="=".repeat((4-n.length%4)%4),t=atob(n.replaceAll("-","+").replaceAll("_","/")+e);return Uint8Array.from(t,i=>i.charCodeAt(0))}function bt(n){let e=fn(n);if(e.length!==65||e[0]!==4)throw new C("invalid_public_key","Encrypted relay public keys must be uncompressed P-256 points.");return e}function yn(n){return Uint8Array.from(n).buffer}function Ei(n){return new Promise((e,t)=>{n.onerror=()=>t(n.error),n.onsuccess=()=>e(n.result)})}function an(n,e){return new Promise((t,i)=>{let o=n.transaction(G,"readwrite"),r=e(o.objectStore(G));r.onerror=()=>i(r.error),o.onerror=()=>i(o.error),o.onabort=()=>i(o.error??new Error("Grant key transaction aborted.")),o.oncomplete=()=>t()})}var xi="mdbase-connect file chunk key v1",Ve=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,H=class extends Error{constructor(t,i){super(i);this.code=t;this.name="FileTransferCryptoError"}code},ue=class n{constructor(e,t){this.binding=e;this.key=t}binding;key;static async open(e,t,i){mn(i);let o=await e.get(t);if(!o||o.agreementPublicKey!==i.encryption.application_agreement_public_key)throw new C("missing_grant_key","The encrypted grant key is unavailable or does not match the file transfer grant.");let r=await wt(o.agreementPrivateKey,i.encryption.connector_agreement_public_key);return n.fromSharedSecret(r,i)}static async fromSharedSecret(e,t){mn(t);let i=await Mi(e,t);return new n(t,i)}async encryptChunk(e,t,i){if(this.validateHeader(t),i.byteLength!==t.plaintext_length)throw new H("plaintext_length_mismatch","File chunk plaintext length does not match its authenticated header.");let o=Ke(e,t),r=await crypto.subtle.encrypt({name:"AES-GCM",iv:_n(t.chunk_index),additionalData:Ge(o),tagLength:128},this.key,Ge(i));return Qt({kind:e,header:t,payload:new Uint8Array(r)})}async decryptChunk(e){let t=je(e);this.validateHeader(t.header);let i=Ke(t.kind,t.header);try{let o=await crypto.subtle.decrypt({name:"AES-GCM",iv:_n(t.header.chunk_index),additionalData:Ge(i),tagLength:128},this.key,Ge(t.payload));return new Uint8Array(o)}catch{throw new H("authentication_failed","The encrypted file chunk could not be authenticated.")}}validateHeader(e){let t=this.binding.encryption;if(e.protocol_version!==1||e.protection!=="grant_aead_v1"||e.grant_id!==this.binding.grantId||e.authority_id!==this.binding.authorityId||e.collection_id!==t.collection_id||e.transfer_id!==this.binding.transferId||e.direction!==this.binding.direction||e.scope_epoch!==t.scope_epoch||e.key_id!==t.key_id)throw new H("header_binding_mismatch","The file frame does not match its transfer encryption binding.")}};async function Mi(n,e){let t=new TextEncoder().encode(Ui(e)),i=await crypto.subtle.digest("SHA-256",t),o=await crypto.subtle.importKey("raw",n,"HKDF",!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:i,info:new TextEncoder().encode(xi)},o,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}function mn(n){if(W(n.encryption),!Ve.test(n.grantId)||!Ve.test(n.applicationId)||!Ve.test(n.authorityId)||!Ve.test(n.transferId)||n.direction!=="upload"&&n.direction!=="download")throw new H("invalid_binding","The file transfer encryption binding is invalid.")}function Ui(n){let e=n.encryption;return["mdbase-connect","file-transfer",1,e.suite,n.grantId,n.applicationId,e.connector_id,n.authorityId,e.collection_id,e.scope_epoch,e.key_id,n.transferId,n.direction].join("|")}function _n(n){if(!Number.isSafeInteger(n)||n<0)throw new H("invalid_chunk_index","The file chunk index is invalid.");let e=new Uint8Array(new ArrayBuffer(12));return new DataView(e.buffer).setBigUint64(4,BigInt(n),!1),e}function Ge(n){return Uint8Array.from(n).buffer}var zi=new TextEncoder().encode("mdbase-connect first-contact transcript\0"),Fi=new TextEncoder().encode("mdbase-connect first-contact sas v1"),Di="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Li=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,U=class extends Error{constructor(t,i){super(i);this.code=t}code};async function Je(n,e,t){let i=await Ni(n),o=e==="application"?n.application_agreement_public_key:n.connector_agreement_public_key,r=e==="application"?i.connector:i.applicationAgreement;if(t.agreementPublicKey!==o)throw new U("identity_mismatch","The first-contact identity does not match the transcript.");let a;try{a=await crypto.subtle.importKey("raw",r,{name:"ECDH",namedCurve:"P-256"},!1,[])}catch{throw new U("invalid_public_key","The first-contact public key is invalid.")}let s=await crypto.subtle.deriveBits({name:"ECDH",public:a},t.agreementPrivateKey,256),l=qi(n,i),d=await crypto.subtle.digest("SHA-256",l),p=await crypto.subtle.importKey("raw",s,"HKDF",!1,["deriveBits"]),u=new Uint8Array(await crypto.subtle.deriveBits({name:"HKDF",hash:"SHA-256",salt:d,info:Fi},p,40));return Ki(u)}async function Ni(n){if(n.protocol_version!==Re)throw new U("unsupported_version","The first-contact protocol version is not supported.");let e=Pt(n.application_agreement_public_key),t=Pt(n.application_signing_public_key),i=Pt(n.connector_agreement_public_key);if(St(e,t)||St(e,i)||St(t,i))throw new U("invalid_public_key","First contact requires distinct endpoint agreement and signing keys.");try{await Promise.all([e,t,i].map(o=>crypto.subtle.importKey("raw",o,{name:"ECDH",namedCurve:"P-256"},!1,[])))}catch{throw new U("invalid_public_key","The first-contact public key is invalid.")}return{applicationAgreement:e,applicationSigning:t,connector:i}}function qi(n,e){let t=[zi,gn(n.protocol_version),pe(Ct(n.application_id)),pe(Ct(n.application_installation_id)),pe(e.applicationAgreement),pe(e.applicationSigning),pe(Ct(n.connector_id)),pe(e.connector)],i=t.reduce((a,s)=>a+s.byteLength,0),o=new Uint8Array(i),r=0;for(let a of t)o.set(a,r),r+=a.byteLength;return o}function pe(n){let e=new Uint8Array(4+n.byteLength);return e.set(gn(n.byteLength)),e.set(n,4),e}function gn(n){let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,n,!1),e}function Ct(n){if(!Li.test(n))throw new U("invalid_binding","The first-contact transcript contains an invalid identifier.");let e=n.replaceAll("-","");return Uint8Array.from({length:16},(t,i)=>Number.parseInt(e.slice(i*2,i*2+2),16))}function Pt(n){if(!/^[A-Za-z0-9_-]+$/.test(n))throw new U("invalid_public_key","The first-contact public key is invalid.");let e=n.replaceAll("-","+").replaceAll("_","/"),t=e.padEnd(Math.ceil(e.length/4)*4,"="),i;try{i=Uint8Array.from(atob(t),o=>o.charCodeAt(0))}catch{throw new U("invalid_public_key","The first-contact public key is invalid.")}if(i.byteLength!==65||i[0]!==4||Bi(i)!==n)throw new U("invalid_public_key","The first-contact public key is invalid.");return i}function Bi(n){return btoa(String.fromCharCode(...n)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}function St(n,e){return n.byteLength===e.byteLength&&n.every((t,i)=>t===e[i])}function Ki(n){let e=0n;for(let i of n)e=e<<8n|BigInt(i);let t="";for(let i=7;i>=0;i-=1)t+=Di[Number(e>>BigInt(i*5)&31n)],i===4&&(t+="-");return t}var Rt=BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),ji=Rt/2n;async function Y(n){return Wt(n.agreementPublicKey,n.signingPublicKey)}async function Te(n,e){if(n.installation_agreement_public_key!==e.agreementPublicKey||n.installation_signing_public_key!==e.signingPublicKey||n.application_installation_id!==await Y(e))throw new Error("Application authorization identity does not match its binding.");let t=Vi(new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},e.signingPrivateKey,$e(n))));return{binding:n,signature:$i(t)}}function Hi(n){let e=new Uint8Array(n.reduce((i,o)=>i+o.byteLength,0)),t=0;for(let i of n)e.set(i,t),t+=i.byteLength;return e}function $i(n){return btoa(String.fromCharCode(...n)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}function Vi(n){if(n.byteLength!==64)throw new Error("Application authorization signature is invalid.");let e=Gi(n.slice(32));if(e===0n||e>=Rt)throw new Error("Application authorization signature is invalid.");return e<=ji?n:Hi([n.slice(0,32),Yi(Rt-e,32)])}function Gi(n){return BigInt(`0x${Ji(n)}`)}function Yi(n,e){let t=n.toString(16).padStart(e*2,"0");return Uint8Array.from({length:e},(i,o)=>Number.parseInt(t.slice(o*2,o*2+2),16))}function Ji(n){return[...n].map(e=>e.toString(16).padStart(2,"0")).join("")}function he(n,e){return new Promise((t,i)=>{if(e?.aborted){i(e.reason??new DOMException("Aborted","AbortError"));return}let o=setTimeout(t,n);e?.addEventListener("abort",()=>{clearTimeout(o),i(e.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}var S=class extends Error{constructor(t,i={}){super(t.message,i.cause===void 0?void 0:{cause:i.cause});this.problem=t;this.name="MdbaseConnectError",this.code=t.code,this.status=i.status}problem;code;status;get retryable(){return this.problem.recovery==="retry"&&this.problem.operation_outcome!=="unknown"}get requiresAuthorization(){return this.problem.category==="authorization"}get outcomeUnknown(){return this.problem.operation_outcome==="unknown"}get recovery(){return this.problem.recovery}get details(){return this.problem.details}};function z(n,e,...[t={}]){let i=J[n];return{problem_version:1,code:n,category:i.category,recovery:i.recovery,message:e,...t.details===void 0?{}:{details:t.details},...t.operationOutcome===void 0?{}:{operation_outcome:t.operationOutcome},...t.traceId===void 0?{}:{trace_id:t.traceId}}}function kt(n,e,t={}){return ft(n,e,{details:t.details,operation_outcome:t.operationOutcome,trace_id:t.traceId})}function c(n,e,...t){let i=t[0];return new S(z(n,e,...t),{status:i?.status,cause:i?.cause})}function D(n,e,t={}){let{status:i,cause:o,...r}=t;return new S(ft(n,e,{details:r.details,operation_outcome:r.operationOutcome,trace_id:r.traceId}),{status:i,cause:o})}function At(n){let e=Xi(n.diagnostics),t=to(n.diagnostics);if(e==="collection_version_unsupported"){let i=Wi(n.diagnostics);return z(e,t,{operationOutcome:"rejected",details:i})}return e!=="operation_invalid"?z(e,t,{operationOutcome:"rejected",details:{diagnostics:n.diagnostics}}):z(e,t,{operationOutcome:"rejected",details:{diagnostics:n.diagnostics,partial_result:n.result}})}function Xi(n){let e=new Set(n.filter(t=>t.severity==="error").map(t=>t.code));return["migration_required","migration_lossy","unsupported_version"].some(t=>e.has(t))?"collection_version_unsupported":["invalid_config","invalid_configuration","missing_config","missing_spec_version"].some(t=>e.has(t))?"collection_configuration_invalid":["duplicate_type","invalid_contract_definition","invalid_data_contract","invalid_type_definition","invalid_type_path"].some(t=>e.has(t))?"collection_type_registry_invalid":["collection_invalid","collection_open_failed"].some(t=>e.has(t))?"collection_invalid":"operation_invalid"}function Wi(n){let e=n.map(t=>t.details).find(t=>Zi(t));return{current_version:typeof e?.current_version=="string"?e.current_version:"0.2.x",required_version:typeof e?.required_version=="string"?e.required_version:"0.3.0"}}function Zi(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function eo(n){return n instanceof S&&n.retryable}function to(n){return n.filter(e=>e.severity==="error").map(e=>e.message).join(" ")||n.map(e=>e.message).join(" ")||"The collection rejected this operation."}var bn=["access_denied","access_paused","authorization_expired","collection_access_denied","connector_identity_changed","connector_offline","connector_upgrade_required","direct_operation_rejected","operation_outcome_unknown","encryption_required","encrypted_relay_rejected","hosted_provider_unavailable","insufficient_access","invalid_encrypted_response","invalid_operation_response","invalid_request","missing_grant_key","not_authorized","operation_cancelled","operation_failed","rate_limited","relay_authorization_expired","relay_unavailable","temporarily_unavailable","timeout","unsupported_operation"],Ot=Object.keys(J),Z=["discovery_failed","invalid_application_manifest","invalid_request","manifest_load_failed","rate_limited","temporarily_unavailable","timeout"],ee=[...Z,"access_denied","approval_window_blocked","authorization_cancelled","browser_required","collection_access_denied","collection_configuration_invalid","collection_contracts_missing","collection_incompatible","collection_invalid","collection_kind_unsupported","collection_mismatch","collection_not_found","collection_type_registry_invalid","collection_version_unsupported","connector_identity_changed","connector_offline","connector_upgrade_required","device_authorization_failed","encryption_required","expired_token","first_contact_handler_required","invalid_callback","invalid_device_authorization_response","invalid_first_contact","invalid_token_response","scope_denied","token_exchange_failed"],fe=[...Z,"authorization_expired","invalid_push_subscription","managed_fcm_not_declared","not_authorized","notification_criterion_not_declared","notification_reauthorization_required","notification_registration_failed","notification_unregistration_failed","notifications_not_declared","notifications_unavailable"],Xe=["connector_offline","connector_upgrade_required","invalid_operation_response","not_authorized","operation_failed","temporarily_unavailable","timeout"],no=[...ee,"collection_not_ready","collection_not_selected","unknown_collection"],vn=["collection_configuration_invalid","collection_invalid","collection_type_registry_invalid","collection_version_unsupported"],Ie=[...bn,...vn],q=[...Ie,"invalid_path","operation_invalid"],Tt=[...q,"query_snapshot_changed","sandbox_unsupported"],I=[...q,"concurrent_modification","invalid_preflight","pending_mutation_unresolved"],It=[...Ie,"change_cursor_reset"],ye=[...I,"type_pack_provision_failed"];function E(n,e=[]){return{ok:!0,value:n,diagnostics:e}}function T(n){return{ok:!1,problem:n}}async function A(n,e){try{return E(await n())}catch(t){if(!(t instanceof S))throw t;let i=t.problem;return i.code==="unknown"||e.includes(i.code)?T(i):T(kt(i.code,i.message,{details:i.details,operationOutcome:i.operation_outcome,traceId:i.trace_id}))}}var Qe=class extends Error{constructor(t){super(t.message);this.problem=t;this.name="ConnectOutcomeError"}problem};function io(n){if(!n.ok)throw new Qe(n.problem);return n.value}var Ee=class{constructor(e){this.transport=e}transport;operation(e,t,i){return A(()=>this.transport.operation(e,t,i),Ot)}describe(){return this.rawOperation("describe",{},Ie)}changes(e={},t){return this.rawOperation("changes",e,It,t)}read(e){return this.envelopeOperation("read",e,q)}query(e={},t){return this.envelopeOperation("query",e,Tt,t)}async*queryPages(e={},t={}){let{offset:i,limit:o,snapshot:r,...a}=e,s=ro(i,0),l=wn(t.firstPageSize??o,200),d=wn(t.pageSize??o,1e3),p=r,u=0,y=0;for(;!t.signal?.aborted;){let h=await this.query({...a,offset:s,limit:y===0?l:d,...p?{snapshot:p}:{}},{signal:t.signal});if(!h.ok){yield h;return}let _=h.value,f=_.meta?.snapshot;if(p&&f&&p!==f){yield T(z("query_snapshot_changed","The collection query snapshot changed while paging. Refresh the query before continuing."));return}!p&&f&&(p=f),u+=_.results.length;let v=!_.meta?.has_more||_.results.length===0,m={results:_.results,..._.meta?{meta:_.meta}:{},page:y,offset:s,loaded:u,complete:v,...p?{snapshot:p}:{}};if(t.onProgress?.(m),yield E(m,h.diagnostics),v)return;s+=_.results.length,y+=1}}async queryAll(e={},t={}){let i=[],o,r=[];for await(let a of this.queryPages(e,t)){if(!a.ok)return a;let s=a.value;i.push(...s.results),o=s,r.push(...a.diagnostics)}return E({results:i,meta:{...o?.meta??{},total_count:o?.meta?.total_count??i.length,has_more:o?!o.complete:!1,...o?.snapshot?{snapshot:o.snapshot}:{}}},r)}listViews(){return this.envelopeOperation("list_views",{},q)}executeView(e){return this.envelopeOperation("execute_view",e,q)}readViewSource(e){return this.envelopeOperation("read_view_source",e,q)}createViewSource(e){return this.envelopeOperation("create_view_source",e,I)}updateViewSource(e){return this.envelopeOperation("update_view_source",e,I)}deleteViewSource(e){return this.envelopeOperation("delete_view_source",e,I)}create(e){return this.envelopeOperation("create",e,I)}update(e){return this.envelopeOperation("update",e,I)}delete(e,t){return this.envelopeOperation("delete",e,I,t)}preflightDelete(e,t){return this.envelopeOperation("delete",{...e,check_backlinks:!0,dry_run:!0},I,t)}rename(e,t){return this.envelopeOperation("rename",e,I,t)}preflightRename(e,t){return this.envelopeOperation("rename",{...e,dry_run:!0},I,t)}validate(e={}){return this.envelopeOperation("validate",e,q)}readType(e){return this.envelopeOperation("read_type",e,ye)}createType(e){return this.envelopeOperation("create_type",e,ye)}updateType(e){return this.envelopeOperation("update_type",e,ye)}installTypePack(e){return this.envelopeOperation("install_type_pack",e,ye)}listTimers(e){return this.rawOperation("list_timers",{namespace:e},q)}putTimer(e){return this.rawOperation("put_timer",e,I)}cancelTimer(e){return this.rawOperation("cancel_timer",e,I)}reconcileTimers(e){return this.rawOperation("reconcile_timers",e,I)}async*watch(e={}){let t=e.cursor,i=Math.max(100,e.pollIntervalMs??1e3),o=oo(e.retry),r=0,a=!1;for(e.onStatus?.({state:"connecting",...t===void 0?{}:{cursor:t}});!e.signal?.aborted;){let s=await this.changes(t===void 0?{}:{after:t,limit:200},{signal:e.signal});if(!s.ok){let p=s.problem;if(e.signal?.aborted)return;if(!o||p.recovery!=="retry"){yield s;return}if(a=!1,r+=1,o.maxAttempts!==void 0&&r>o.maxAttempts){yield s;return}let u=Math.min(o.maxDelayMs,Math.round(o.initialDelayMs*o.multiplier**(r-1)));e.onStatus?.({state:"reconnecting",...t===void 0?{}:{cursor:t},attempt:r,retryInMs:u,problem:p});try{await he(u,e.signal)}catch{if(!e.signal?.aborted)throw c("operation_failed","Watch retry delay failed unexpectedly.")}continue}let l=s.value;if(t===void 0){t=l.cursor;continue}if(l.reset){let p=z("change_cursor_reset","The collection change cursor expired. Refresh collection state before subscribing again.");e.onStatus?.({state:"reset_required",cursor:t,problem:p}),yield T(p);return}let d=r>0;r=0,(!a||d)&&e.onStatus?.({state:"connected",cursor:t,recovered:d}),a=!0;for(let p of l.events)yield E(p);if(t=l.cursor,!l.has_more)try{await he(i,e.signal)}catch{if(!e.signal?.aborted)throw c("operation_failed","Watch polling delay failed unexpectedly.")}}}rawOperation(e,t,i,o){return A(()=>this.transport.operation(e,t,o),i)}async envelopeOperation(e,t,i,o){let r=await A(()=>this.transport.operation(e,t,o),i);if(!r.ok)return r;let a=r.value;return a.valid?E(a.result,a.diagnostics):T(At(a))}};function oo(n){if(n!==!1)return{initialDelayMs:Math.max(0,n?.initialDelayMs??500),maxDelayMs:Math.max(0,n?.maxDelayMs??15e3),multiplier:Math.max(1,n?.multiplier??2),...n?.maxAttempts===void 0?{}:{maxAttempts:Math.max(0,n.maxAttempts)}}}function ro(n,e){return typeof n=="number"&&Number.isFinite(n)?Math.max(0,Math.floor(n)):e}function wn(n,e){return typeof n=="number"&&Number.isFinite(n)&&n>0?Math.floor(n):e}function N(n){let e=new Uint8Array(n);return crypto.getRandomValues(e),xe(e)}function xe(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function Cn(n){let e=n.replaceAll("-","+").replaceAll("_","/").padEnd(Math.ceil(n.length/4)*4,"="),t=atob(e),i=new Uint8Array(new ArrayBuffer(t.length));for(let o=0;o<t.length;o+=1)i[o]=t.charCodeAt(o);return i}function te(n){return{...n,credentials:"omit",targetAddressSpace:"loopback"}}async function Me(){if(typeof navigator>"u"||!navigator.permissions?.query)return null;try{return(await navigator.permissions.query({name:"local-network-access"})).state}catch{return null}}function me(n){return n===404||n===405||n===426||n>=500}function We(n,e){return e&&typeof e=="object"&&!Array.isArray(e)&&e.dry_run===!0?!1:n==="sync"&&e!==null&&typeof e=="object"&&!Array.isArray(e)&&e.action==="mutate"||n==="create"||n==="update"||n==="delete"||n==="rename"||n==="create_type"||n==="update_type"||n==="install_type_pack"||n==="put_timer"||n==="cancel_timer"||n==="reconcile_timers"}function B(n){return[...new Set(n)]}function Pn(n,e){return n.grantId||e.grantId?n.grantId===e.grantId&&n.keyHandle===e.keyHandle&&n.encryption?.key_id===e.encryption?.key_id:n.accessToken===e.accessToken}function ne(n){if(n?.aborted)throw c("operation_cancelled","The operation was cancelled before it changed the collection.",{operationOutcome:"not_sent",cause:n.reason})}function xt(n,e,t,i){return n instanceof S?n:e?.aborted?t?L(n):c("operation_cancelled","The operation was cancelled before it changed the collection.",{operationOutcome:"not_sent",cause:n}):t?L(n):n instanceof TypeError?c(i,i==="hosted_provider_unavailable"?"The hosted collection provider is unavailable.":"The Connect relay is unavailable.",{cause:n}):n instanceof Error?n:new Error(String(n))}function Mt(n,e){return e?.aborted===!0||n instanceof S&&n.code==="operation_cancelled"}function Sn(n,e){if(e.dry_run!==!0||e.would_rename!==!0||e.from!==n.from||e.to!==n.to)throw c("invalid_preflight","The rename preview does not match this mutation. Run the preview again.")}function Rn(n,e){if(e.dry_run!==!0||e.would_delete!==!0||e.path!==n.path)throw c("invalid_preflight","The delete preview does not match this mutation. Run the preview again.")}function kn(n,e){if(n.update_refs===!1)return{affectedRecords:0,totalUnits:1,warnings:0};let t=e.references_affected??[];return{affectedRecords:new Set(t.map(i=>i.path)).size,totalUnits:1+t.length,warnings:e.warnings?.length??0}}function An(n){return{affectedRecords:new Set((n.broken_links??[]).map(e=>e.path)).size,totalUnits:1,warnings:0}}async function On(n,e){let t=new TextEncoder().encode(`${n}\0${Ut(e??{})}`),i=await crypto.subtle.digest("SHA-256",t);return xe(new Uint8Array(i))}function Ut(n){return JSON.stringify(Et(n))}function Et(n){return Array.isArray(n)?n.map(e=>Et(e)):n&&typeof n=="object"?Object.fromEntries(Object.entries(n).filter(([,e])=>e!==void 0).sort(([e],[t])=>e<t?-1:e>t?1:0).map(([e,t])=>[e,Et(t)])):n}function L(n){return c("operation_outcome_unknown","The write may have completed, but mdbase could not recover its authoritative result. Retry the exact same write to recover safely.",{operationOutcome:"unknown",cause:n})}async function $(n,e,t,i){try{return await fetch(n,e)}catch(o){throw c(t,i,{cause:o})}}function Tn(n){let e=new URL(n);if(e.protocol!=="http:"||!["127.0.0.1","[::1]"].includes(e.hostname)||e.username||e.password||e.pathname!=="/"||e.search||e.hash)throw c("invalid_loopback_url","loopbackUrl must be an HTTP origin on 127.0.0.1 or ::1.");return e.origin}async function Ue(){let n=N(32),e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n));return{verifier:n,challenge:xe(new Uint8Array(e))}}function R(n,e,t,i){return D(ge(n)??n?.error?.code??e,n?.error_description??n?.error?.message??t,{status:i,details:n?.error?.details})}function ge(n){return typeof n?.error=="string"?n.error:void 0}function Ze(n,e){if(!n||typeof n!="object"||Array.isArray(n)||typeof e!="string")return!1;let t=n;if(typeof t.operations_url!="string"||typeof t.sync_url!="string"||typeof t.files_url!="string"||typeof t.replica_id!="string"||t.replica_id.length===0||typeof t.access_token!="string"||t.access_token.length===0||t.proof_public_key!==void 0&&(typeof t.proof_public_key!="string"||t.proof_public_key.length===0))return!1;try{let i=new URL(t.operations_url),o=new URL(t.sync_url),r=new URL(t.files_url);return[i,o,r].every(a=>(a.protocol==="https:"||a.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(a.hostname))&&!a.username&&!a.password&&!a.search&&!a.hash)&&/^\/v1\/authorities\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/operations$/i.test(i.pathname)&&/^\/v1\/authorities\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/sync$/i.test(o.pathname)&&/^\/v1\/authorities\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/files$/i.test(r.pathname)&&i.origin===o.origin&&i.origin===r.origin&&i.pathname.split("/")[3]===e&&o.pathname.split("/")[3]===e&&r.pathname.split("/")[3]===e}catch{return!1}}function In(n,e){return Ze({operations_url:n?.operationsUrl,sync_url:n?.syncUrl,files_url:n?.filesUrl,replica_id:n?.replicaId,access_token:n?.accessToken,proof_public_key:n?.proofPublicKey},e)}function et(n){if(!n||typeof n!="object"||Array.isArray(n))return!1;let e=n,t=e.actions;if(e.kind!=="files"||e.protocol_version!==1||!Array.isArray(t)||t.length===0||t.length>6||new Set(t).size!==t.length||t.some(o=>!["list","read","add","replace","move","delete"].includes(o)))return!1;let i=e.scope;return!i||typeof i!="object"||Array.isArray(i)?!1:i.kind==="collection"?Object.keys(i).length===1:i.kind==="selected_folders"&&Object.keys(i).length===2&&Array.isArray(i.folders)&&i.folders.length>0&&i.folders.length<=100&&new Set(i.folders).size===i.folders.length&&i.folders.every(o=>typeof o=="string"&&o.length>0&&o.length<=1024&&ao(o))}function ao(n){let e=new Set([".mdbase",".git","node_modules","_contracts","_schemas","_types","_views"]);return!n.startsWith("/")&&!n.endsWith("/")&&!n.includes("\\")&&n.split("/").every(t=>{let i=t.split(".")[0]?.toUpperCase()??"";return t!==""&&t!=="."&&t!==".."&&!t.startsWith(".")&&!t.endsWith(" ")&&!t.endsWith(".")&&!/[<>:"|?*]/.test(t)&&!e.has(t.toLowerCase())&&!["CON","PRN","AUX","NUL"].includes(i)&&!/^(COM|LPT)[1-9]$/.test(i)})}function En(n,e){if(!n||typeof n!="object"||Array.isArray(n)||n.collection_id!==e)return!1;try{return W(n),!0}catch{return!1}}function xn(n){if(typeof n?.device_code!="string"||typeof n?.user_code!="string"||typeof n?.verification_uri!="string"||typeof n?.verification_uri_complete!="string"||!Number.isFinite(n?.expires_in)||!Number.isFinite(n?.interval))throw c("invalid_device_authorization_response","Connect returned an invalid downloaded application authorization response.");return{userCode:n.user_code,verificationUri:n.verification_uri,verificationUriComplete:n.verification_uri_complete,expiresAt:Date.now()+Math.max(1,n.expires_in)*1e3,intervalSeconds:Math.max(1,n.interval)}}function M(n){if(!n)return null;try{return JSON.parse(n)}catch{return null}}function tt(n){if(!n||typeof n!="object"||Array.isArray(n))return null;let e=n;return e.access!=="contract"&&e.access!=="full_collection"||!Array.isArray(e.contracts)||e.contracts.some(t=>!t||typeof t!="object"||t.contract_type!=="record"||typeof t.id!="string"||typeof t.version!="string"||!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(t.version)||!/^sha256:[0-9a-f]{64}$/.test(t.digest)||!t.schema||typeof t.schema!="object"||Array.isArray(t.schema)||!Array.isArray(t.implementations)||t.implementations.some(i=>!i||typeof i!="object"||typeof i.type_name!="string"||!Number.isInteger(i.type_version)||!/^sha256:[0-9a-f]{64}$/.test(i.digest)||!i.fields||typeof i.fields!="object"||Array.isArray(i.fields)||Object.values(i.fields).some(o=>typeof o!="string")))?null:e}function Mn(n){return n.endsWith("/")?n.slice(0,-1):n}function Un(){if(typeof location>"u")throw c("manifest_required","manifest is required outside a browser environment.");if(location.origin==="null")throw c("manifest_required","Downloaded applications must provide their v1 portable manifest inline.");return new URL("/.well-known/mdbase-app.json",location.origin).href}function zn(){if(typeof location>"u")throw c("redirect_uri_required","redirectUri is required outside a browser environment.");return location.href.split(/[?#]/)[0]}function Fn(){if(typeof location>"u")throw c("callback_url_required","callbackUrl is required outside a browser environment.");return location.href}function Dn(n){if(n)return new _e;if(typeof localStorage>"u")throw c("storage_required","storage is required outside a browser environment.");try{let e=`mdbase-connect:probe:${N(8)}`;return localStorage.setItem(e,"1"),localStorage.removeItem(e),localStorage}catch{return new _e}}var _e=class{values=new Map;get length(){return this.values.size}clear(){this.values.clear()}getItem(e){return this.values.get(e)??null}key(e){return[...this.values.keys()][e]??null}removeItem(e){this.values.delete(e)}setItem(e,t){this.values.set(String(e),String(t))}};function Ln(n){return typeof n=="string"||n.distribution!=="portable"?!1:typeof location>"u"||location.origin==="null"||!["http:","https:"].includes(location.protocol)}function Nn(n){let e=Ut(n),t=2166136261,i=2654435769;for(let o=0;o<e.length;o+=1){let r=e.charCodeAt(o);t=Math.imul(t^r,16777619),i=Math.imul(i^r,2246822507)}return`${(t>>>0).toString(16).padStart(8,"0")}${(i>>>0).toString(16).padStart(8,"0")}`}var nt=class{constructor(e){this.context=e}context;async registerNotifications(e){let t=await this.context.authorizedToken();if(!t)throw c("not_authorized","Connect this application before enabling notifications.");let o=(await this.context.register()).notifications?.criteria.map(v=>v.id)??[],r=[...new Set(e.criteria??o)],a=r.find(v=>!o.includes(v));if(a)throw c("notification_criterion_not_declared",`The application manifest does not declare notification criterion ${a}.`);if(r.length===0)throw c("notifications_not_declared","This application manifest does not declare any notification criteria.");let s=await $(`${this.context.serverUrl}/v1/notifications/vapid-public-key`,void 0,"notifications_unavailable","Push notifications are unavailable."),l=await s.json();if(!s.ok)throw R(l,"notifications_unavailable","Push notifications are unavailable.",s.status);let d=await e.serviceWorker.pushManager.getSubscription();d||(d=await e.serviceWorker.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Cn(l.public_key)}));let p=d.toJSON();if(!p.endpoint||!p.keys?.p256dh||!p.keys.auth)throw c("invalid_push_subscription","The browser returned an incomplete push subscription.");let u=M(this.context.storage.getItem(this.context.notificationKey())),y=e.installationId??u?.installationId??N(24),h=await $(`${this.context.serverUrl}/v1/notifications/channels`,{method:"POST",headers:{authorization:`Bearer ${t.accessToken}`,"content-type":"application/json"},body:JSON.stringify({installation_id:y,criteria:r,subscription:{endpoint:p.endpoint,expirationTime:p.expirationTime??null,keys:p.keys}})},"notification_registration_failed","Could not register push notifications."),_=await h.json();if(!h.ok)throw R(_,"notification_registration_failed","Could not register push notifications.",h.status);u?.channelId&&u.channelId!==_.channel_id&&fetch(`${this.context.serverUrl}/v1/notifications/channels/${u.channelId}`,{method:"DELETE",headers:{authorization:`Bearer ${t.accessToken}`}}).catch(()=>{});let f={channelId:_.channel_id,installationId:y,criteria:r};return this.context.storage.setItem(this.context.notificationKey(),JSON.stringify(f)),f}async registerNativeNotifications(e){let t=await this.context.authorizedToken();if(!t)throw c("not_authorized","Connect this application before enabling notifications.");let i=await this.context.register();if(i.notifications?.native_delivery?.mode!=="managed_fcm")throw c("managed_fcm_not_declared","This application does not declare Connect-managed native notifications.");let o=i.notifications.criteria.map(h=>h.id),r=[...new Set(e.criteria??o)],a=r.find(h=>!o.includes(h));if(a)throw c("notification_criterion_not_declared",`The application manifest does not declare notification criterion ${a}.`);if(r.length===0)throw c("notifications_not_declared","This application manifest does not declare any notification criteria.");let s=this.context.notificationKey("fcm"),l=M(this.context.storage.getItem(s)),d=e.installationId??l?.installationId??N(24),p=await $(`${this.context.serverUrl}/v1/notifications/channels`,{method:"POST",headers:{authorization:`Bearer ${t.accessToken}`,"content-type":"application/json"},body:JSON.stringify({installation_id:d,criteria:r,transport:"fcm",token:e.token})},"notification_registration_failed","Could not register native notifications."),u=await p.json();if(!p.ok)throw R(u,"notification_registration_failed","Could not register native notifications.",p.status);l?.channelId&&l.channelId!==u.channel_id&&this.deleteNotificationChannel(l.channelId,t.accessToken).catch(()=>{});let y={channelId:u.channel_id,installationId:d,transport:"fcm",criteria:r};return this.context.storage.setItem(s,JSON.stringify(y)),y}async unregisterNativeNotifications(){let e=this.context.notificationKey("fcm"),t=M(this.context.storage.getItem(e)),i=await this.context.authorizedToken();if(t?.channelId&&!i)throw c("not_authorized","Reconnect this application before disabling native notifications.");t?.channelId&&i&&await this.deleteNotificationChannel(t.channelId,i.accessToken),this.context.storage.removeItem(e)}async unregisterNotifications(e){let t=M(this.context.storage.getItem(this.context.notificationKey())),i=await this.context.authorizedToken();if(t?.channelId&&!i)throw c("not_authorized","Reconnect this application before disabling push notifications.");if(t?.channelId&&i){let r=await $(`${this.context.serverUrl}/v1/notifications/channels/${t.channelId}`,{method:"DELETE",headers:{authorization:`Bearer ${i.accessToken}`}},"notification_unregistration_failed","Could not unregister push notifications.");if(!r.ok&&r.status!==404){let a=await r.json();throw R(a,"notification_unregistration_failed","Could not unregister push notifications.",r.status)}}this.context.storage.removeItem(this.context.notificationKey()),await(await e?.pushManager.getSubscription())?.unsubscribe()}async deleteNotificationChannel(e,t){let i=await $(`${this.context.serverUrl}/v1/notifications/channels/${e}`,{method:"DELETE",headers:{authorization:`Bearer ${t}`}},"notification_unregistration_failed","Could not unregister push notifications.");if(!i.ok&&i.status!==404){let o=await i.json();throw R(o,"notification_unregistration_failed","Could not unregister push notifications.",i.status)}}};async function it(n,e,t,i,o,r){if(!n.authority)throw c("not_remote_authority","This authorization has no remote authority endpoint.");let a=t===""||t.startsWith("?")?t:`/${t}`,s=`${n.authority.filesUrl}${a}`,l=i===void 0?void 0:JSON.stringify(i),d=await r(n,e,s,l,n.authority.accessToken);return fetch(s,{method:e,redirect:"error",headers:{authorization:`Bearer ${n.authority.accessToken}`,...l===void 0?{}:{"content-type":"application/json"},...d},...l===void 0?{}:{body:l},...o?{signal:o}:{}})}async function qn(n,e,t,i,o,r,a){let s=n,l=await it(s,e,t,i,o,a);if(l.status===401&&s.refreshToken){if(s=await r(),!s.authority||!s.fileCapability)throw c("authority_authorization_changed","Reconnect this collection before accessing its files.");l=await it(s,e,t,i,o,a)}let d=await l.json().catch(()=>({}));if(!l.ok)throw R(d,"operation_failed","Collection file request failed.",l.status);return d}async function Bn(n,e,t,i,o,r){let a=n,s=await it(a,"GET",e,void 0,i,r);if(s.status===401&&a.refreshToken){if(a=await o(),!a.authority||!a.fileCapability)throw c("authority_authorization_changed","Reconnect this collection before accessing its files.");s=await it(a,"GET",e,void 0,i,r)}if(!s.ok){let d=await s.json().catch(()=>({}));throw R(d,"operation_failed","Collection file range request failed.",s.status)}let l=s.headers.get("content-length");if(l===null||!/^(0|[1-9][0-9]*)$/u.test(l)||Number(l)!==t)throw await s.body?.cancel().catch(()=>{}),c("invalid_operation_response","The hosted file response declared an unexpected byte length.");if(!s.body)throw c("invalid_operation_response","The hosted file response did not contain a byte stream.");return s.body}var ot=class{constructor(e){this.options=e}options;async control(e,t,i,o,r){be(e);let a=ho(t,i,o),s=await this.encryptControl(e,a),l;if(await this.options.shouldAttemptDirect(e)){try{l=await fetch(`${this.options.loopbackUrl}/v1/files/control`,te({method:"POST",headers:{"content-type":"application/mdbase-connect+json"},body:JSON.stringify(s),signal:r}))}catch(d){if(r?.aborted)throw d;this.options.onDirectUnavailable()}if(l&&!me(l.status))return l.ok&&this.options.onDirectAvailable(),this.decryptControlResponse(e,s,l);l&&this.options.onDirectUnavailable()}return l=await this.sendRelayControl(e,s,r),await co(l,e)&&(e=await this.options.refreshAuthorization(),zt(e),s=await this.encryptControl(e,a),l=await this.sendRelayControl(e,s,r)),l.ok&&this.options.onRelayAvailable(),this.decryptControlResponse(e,s,l)}async decryptControlResponse(e,t,i){let o=await i.json().catch(()=>({}));if(!i.ok)throw R(o,"operation_failed","Collection file request failed.",i.status);let r=o?.envelope;if(!r)throw c("invalid_encrypted_response","The connector omitted its encrypted file response.");let a=await de(this.options.keyStore,e.keyHandle,Ft(e),t,r);return a.ok||po(a.problem),a.result}async uploadChunk(e,t,i,o){let a=await this.localFileToken(e,"upload"),s=await Kn(this.options.keyStore,a,e,t,i),l;if(await this.options.shouldAttemptDirect(a)){try{l=await fetch(`${this.options.loopbackUrl}/v1/files/upload`,te(jn(s,o)))}catch(d){if(o?.aborted)throw d;this.options.onDirectUnavailable()}if(l&&!me(l.status))return l.ok&&this.options.onDirectAvailable(),so(l,"Encrypted file chunk upload failed.");l&&this.options.onDirectUnavailable()}if(l=await this.sendRelayUpload(a,s,o),l.status===401&&a.refreshToken&&(a=await this.options.refreshAuthorization(),zt(a),s=await Kn(this.options.keyStore,a,e,t,i),l=await this.sendRelayUpload(a,s,o)),!l.ok){let d=await l.json().catch(()=>({}));throw R(d,"operation_failed","Encrypted file chunk upload failed.",l.status)}this.options.onRelayAvailable()}async downloadChunk(e,t,i){let o=await this.localFileToken(e,"download"),r;if(await this.options.shouldAttemptDirect(o)){try{r=await fetch(`${this.options.loopbackUrl}/v1/files/download/${encodeURIComponent(o.grantId)}/${encodeURIComponent(e.transfer_id)}/${t}`,te({method:"GET",signal:i}))}catch(a){if(i?.aborted)throw a;this.options.onDirectUnavailable()}if(r&&!me(r.status))return r.ok&&this.options.onDirectAvailable(),this.decryptDownloadResponse(o,e,t,r);r&&this.options.onDirectUnavailable()}return r=await this.sendRelayDownload(o,e,t,i),r.status===401&&o.refreshToken&&(o=await this.options.refreshAuthorization(),zt(o),r=await this.sendRelayDownload(o,e,t,i)),r.ok&&this.options.onRelayAvailable(),this.decryptDownloadResponse(o,e,t,r)}async decryptDownloadResponse(e,t,i,o){if(!o.ok){let s=await o.json().catch(()=>({}));throw R(s,"operation_failed","Encrypted file chunk download failed.",o.status)}if(o.headers.get("content-type")?.split(";",1)[0]!=="application/mdbase-connect-file")throw c("invalid_operation_response","The connector returned an invalid file response media type.");let r=new Uint8Array(await o.arrayBuffer()),a;try{uo(t,i,r),a=await(await $n(this.options.keyStore,e,t)).decryptChunk(r)}catch(s){throw s instanceof S?s:c("invalid_operation_response","The connector returned an invalid encrypted file frame.",{cause:s})}if(a.byteLength!==Dt(t,i))throw c("invalid_operation_response","The connector returned a truncated file chunk.");return a}encryptControl(e,t){return be(e),X(this.options.keyStore,e.keyHandle,Ft(e),"file_control",t)}sendRelayControl(e,t,i){return fetch(`${this.options.serverUrl}/v1/authorities/${encodeURIComponent(e.collectionId)}/files/control`,{method:"POST",headers:{authorization:`Bearer ${e.accessToken}`,"content-type":"application/json"},body:JSON.stringify(t),signal:i})}sendRelayUpload(e,t,i){return fetch(`${this.options.serverUrl}/v1/authorities/${encodeURIComponent(e.collectionId)}/files/upload`,{...jn(t,i),headers:{authorization:`Bearer ${e.accessToken}`,"content-type":"application/mdbase-connect-file"}})}sendRelayDownload(e,t,i,o){return fetch(`${this.options.serverUrl}/v1/authorities/${encodeURIComponent(e.collectionId)}/files/download/${encodeURIComponent(t.transfer_id)}/${i}`,{method:"GET",headers:{authorization:`Bearer ${e.accessToken}`},signal:o})}async localFileToken(e,t){let i=await this.options.authorizedToken();if(!i||i.authority||!i.fileCapability||!i.encryption||!i.grantId||!i.keyHandle||e.direction!==t||e.protection!=="grant_aead_v1")throw c("not_authorized","This connection cannot use encrypted local file delivery.");return rt(e),i}};function zt(n){if(n.authority||!n.fileCapability)throw c("not_authorized","This connection cannot use encrypted local file delivery.");be(n)}async function Kn(n,e,t,i,o){let r=lo(e,t,i,o.byteLength);return(await $n(n,e,t)).encryptChunk("upload_chunk",r,o)}function jn(n,e){return{method:"POST",headers:{"content-type":"application/mdbase-connect-file"},body:Uint8Array.from(n).buffer,signal:e}}async function so(n,e){if(n.ok)return;let t=await n.json().catch(()=>({}));throw R(t,"operation_failed",e,n.status)}async function co(n,e){return e.refreshToken?n.status===401?!0:n.status!==409?!1:(await n.clone().json().catch(()=>null))?.error?.code==="encryption_binding_stale":!1}function be(n){if(!n.encryption||!n.grantId||!n.keyHandle)throw c("missing_grant_key","Reconnect this application to restore encrypted file access.")}function Ft(n){return be(n),{grantId:n.grantId,applicationId:n.clientId,encryption:n.encryption}}function $n(n,e,t){return be(e),ue.open(n,e.keyHandle,{...Ft(e),authorityId:e.encryption.connector_id,transferId:t.transfer_id,direction:t.direction})}function lo(n,e,t,i){be(n);let o=rt(e),r=Dt(e,t);if(i!==r)throw c("invalid_request","The file chunk has the wrong byte length.");return{protocol_version:1,protection:"grant_aead_v1",grant_id:n.grantId,authority_id:n.encryption.connector_id,collection_id:n.collectionId,transfer_id:e.transfer_id,direction:e.direction,chunk_size:o,chunk_index:t,offset:t*o,plaintext_length:i,total_size:e.total_size,scope_epoch:n.encryption.scope_epoch,key_id:n.encryption.key_id}}function uo(n,e,t){let i=je(t),o=Dt(n,e),r=rt(n);if(i.kind!=="download_chunk"||i.header.chunk_index!==e||i.header.chunk_size!==r||i.header.offset!==e*r||i.header.plaintext_length!==o||i.header.total_size!==n.total_size)throw c("invalid_operation_response","The connector returned a file frame for a different chunk.")}function po(n){throw D(n.code==="unknown"?n.server_code:n.code,n.message,{details:n.details,operationOutcome:n.operation_outcome??"rejected",traceId:n.trace_id})}function ho(n,e,t){if(n==="GET"&&(e===""||e.startsWith("?"))){let o=new URLSearchParams(e.startsWith("?")?e.slice(1):e),r=o.get("limit");return{protocol_version:1,type:"list_files",...o.get("folder")?{folder:o.get("folder")}:{},...o.get("after")?{after:o.get("after")}:{},...r?{limit:Number(r)}:{}}}let i=e.split("/");if(n==="GET"&&i.length===2&&i[0]==="transfers")return Hn("get_file_transfer_status",i[1]);if(n==="DELETE"&&i.length===2&&i[0]==="transfers")return Hn("abort_file_transfer",i[1]);if(n==="POST"&&fo(t)){let o=e==="uploads"?"open_file_upload":e==="downloads"?"open_file_download":i.length===3&&i[0]==="uploads"&&i[2]==="commit"?"commit_file_upload":i.length===2&&i[1]==="move"&&t.file_id===decodeURIComponent(i[0])?"move_file":i.length===2&&i[1]==="delete"&&t.file_id===decodeURIComponent(i[0])?"delete_file":null;if(o&&t.type===o)return{...t}}throw c("invalid_request","The file control request path is invalid.")}function Hn(n,e){return{protocol_version:1,type:n,transfer_id:decodeURIComponent(e)}}function rt(n){if(n.strategy.kind!=="framed_chunks"||!Number.isSafeInteger(n.strategy.chunk_size)||n.strategy.chunk_size<=0)throw c("invalid_operation_response","The connector returned an invalid framed transfer strategy.");return n.strategy.chunk_size}function Dt(n,e){let t=rt(n);if(!Number.isSafeInteger(e)||e<0||!Number.isSafeInteger(n.total_size)||n.total_size<0)throw c("invalid_request","The file chunk index is invalid.");let i=e*t;if(!Number.isSafeInteger(i)||i>=n.total_size)throw c("invalid_request","The file chunk index is outside the transfer.");return Math.min(t,n.total_size-i)}function fo(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}var at=class{constructor(e){this.options=e;this.local=new ot(e)}options;local;async control(e,t="",i,o){let r=await this.requireFileToken();return r.authority?qn(r,e,t,i,o,this.options.refreshAuthorization,this.options.authorityProofHeaders):this.local.control(r,e,t,i,o)}uploadChunk(e,t,i,o){return this.local.uploadChunk(e,t,i,o)}downloadChunk(e,t,i){return this.local.downloadChunk(e,t,i)}async downloadHostedPart(e,t,i,o){let r=await this.requireFileToken();if(!r.authority)throw c("not_remote_authority","Hosted file delivery requires a remote authority endpoint.");return Bn(r,`downloads/${encodeURIComponent(e.transfer_id)}/parts/${t}`,i,o,this.options.refreshAuthorization,this.options.authorityProofHeaders)}async requireFileToken(){let e=await this.options.authorizedToken();if(!e?.fileCapability)throw c("not_authorized","This connection has no file capability.");return e}};var st=class{serverUrl;storage;keyStore;directAccessMode;loopbackUrl;collectionId;internals;onChange;files;refreshPromise=null;directStatus;currentRoute="relay";directFailures=0;directRetryAt=0;constructor(e){this.serverUrl=e.serverUrl,this.storage=e.storage,this.keyStore=e.keyStore,this.directAccessMode=e.directAccessMode,this.loopbackUrl=e.loopbackUrl,this.collectionId=e.collectionId,this.internals=e.internals,this.onChange=e.onChange,this.files=new at({keyStore:this.keyStore,serverUrl:this.serverUrl,loopbackUrl:this.loopbackUrl,authorizedToken:()=>this.authorizedToken(),refreshAuthorization:()=>this.refreshAuthorization(),shouldAttemptDirect:t=>this.shouldAttemptDirect(t),onDirectAvailable:()=>{this.markDirectAvailable(),this.setRoute("direct")},onDirectUnavailable:()=>this.markDirectUnavailable(),onRelayAvailable:()=>this.setRoute("relay"),authorityProofHeaders:(t,i,o,r,a)=>this.authorityProofHeaders(t,i,o,r,a)}),this.directStatus=this.directAccessMode==="disabled"?"disabled":"unavailable"}get directAccess(){return this.currentToken()?.authority?"disabled":this.directStatus}get route(){return this.currentToken()?.authority?"remote":this.currentRoute}notifyStorageChanged(){this.emitConnection()}async checkDirectAccess(){let e=this.currentToken();if(!this.directEligible(e))return this.setDirectStatus("disabled");let t=await Me();return t==="denied"?this.setDirectStatus("denied"):(t==="prompt"||t===null)&&this.storage.getItem(this.directPreferenceKey())!=="enabled"?this.setDirectStatus("permission_required"):this.probeDirectAccess()}async requestDirectAccess(){let e=this.currentToken();return this.directCapable(e)?(this.storage.setItem(this.directPreferenceKey(),"enabled"),this.directRetryAt=0,this.probeDirectAccess()):this.setDirectStatus("disabled")}disableDirectAccess(){this.storage.setItem(this.directPreferenceKey(),"disabled"),this.setDirectStatus("disabled"),this.setRoute("relay")}pendingMutation(){let e=M(this.storage.getItem(this.pendingMutationKey())),t=this.currentToken();return!e||!t||e.collectionId!==t.collectionId||e.grantId!==t.grantId||e.keyId!==t.encryption?.key_id?null:{operation:e.operation,createdAt:e.createdAt,resumable:!0}}async resumePendingMutation(e,t){let i=this.pendingMutation();if(!i)throw c("no_pending_mutation","There is no interrupted mutation to resume.");return this.performOperation(i.operation,e,t)}async performOperation(e,t,i={}){ne(i.signal);let o=this.currentToken();if(!o)throw c("not_authorized","Connect this application before accessing a collection.");if(!o.operations.includes(e))throw c("insufficient_access",`This connection does not allow ${e}.`,{details:{required_operations:[e],granted_operations:[...o.operations],missing_operations:[e]}});let r=await this.shouldAttemptDirect(o);if(!r&&(o=await this.authorizedToken(),!o))throw c("not_authorized","Reconnect this application to continue.");let a;try{a=await this.sendOperation(o,e,t,r,i)}catch(p){throw xt(p,i.signal,We(e,t)&&this.pendingMutation()!==null,o.authority?"hosted_provider_unavailable":"relay_unavailable")}let s=a.response,l=s.status===409&&(await s.clone().json().catch(()=>null))?.error?.code==="encryption_binding_stale";if((s.status===401||l)&&o.refreshToken){if(a.pendingMutation&&(a.directDeliveryUncertain||a.encryptedRequest&&a.resumingMutation))throw c("operation_outcome_unknown","The direct operation may have completed, but its encrypted grant changed before the response could be recovered. Refresh before making another change.",{operationOutcome:"unknown"});a.pendingMutation&&this.clearPendingMutation(),o=await this.refreshAuthorization(),r=await this.shouldAttemptDirect(o);try{a=await this.sendOperation(o,e,t,r,i)}catch(p){throw xt(p,i.signal,We(e,t)&&this.pendingMutation()!==null,o.authority?"hosted_provider_unavailable":"relay_unavailable")}s=a.response}let d;try{d=await s.json()}catch(p){throw a.pendingMutation?L(p):c("invalid_operation_response","The collection authority returned a response that is not valid JSON.",{cause:p})}if(!s.ok){let p=R(d,"operation_failed","Collection operation failed.",s.status);throw a.pendingMutation&&(a.directDeliveryUncertain||a.encryptedRequest&&a.resumingMutation)?L(p):(a.pendingMutation&&!a.directDeliveryUncertain&&this.clearPendingMutation(),p.code==="direct_operation_rejected"&&p.status===403&&this.invalidateRejectedAuthorization(o),p)}if(a.encryptedRequest){let p=d?.envelope;if(!p||!o.encryption||!o.grantId||!o.keyHandle)throw a.pendingMutation?L(new Error("Encrypted operation response was missing its envelope.")):c("invalid_encrypted_response","The relay did not return an encrypted connector response.");try{let u=await de(this.keyStore,o.keyHandle,{grantId:o.grantId,applicationId:o.clientId,encryption:o.encryption},a.encryptedRequest,p);if(a.pendingMutation&&this.clearPendingMutation(),!u.ok)throw D(u.problem.code==="unknown"?u.problem.server_code:u.problem.code,u.problem.message,{details:u.problem.details,operationOutcome:u.problem.operation_outcome??"rejected",traceId:u.problem.trace_id});return u.result}catch(u){throw u instanceof S?u:u instanceof C?a.pendingMutation?L(u):D(u.code,u.message):u}}if(d?.protocol_version!==1||d?.request_id!==a.requestId)throw a.pendingMutation?L(new Error("Operation response protocol or request ID did not match.")):c("invalid_operation_response","The collection authority returned a response for a different protocol request.");if(d.ok===!1)throw Ce(d.problem)?(a.pendingMutation&&this.clearPendingMutation(),new S(d.problem)):a.pendingMutation?L(new Error("Operation rejection did not contain a canonical problem.")):c("invalid_operation_response","The collection authority returned an invalid operation problem.");if(d.ok!==!0||!("result"in d))throw a.pendingMutation?L(new Error("Successful operation response did not contain a result.")):c("invalid_operation_response","The collection authority returned an incomplete operation response.");return a.pendingMutation&&this.clearPendingMutation(),d.result}async performAuthoritySyncRequest(e,t,i,o,r){let a=await this.authorizedToken();if(!a?.authority||a.collectionId!==e||a.authority.replicaId!==t)throw c("authority_authorization_changed","Reconnect this collection authority before synchronizing.");let s=await this.sendAuthoritySyncRequest(a,i,o,r);if(s.status===401&&a.refreshToken){if(a=await this.refreshAuthorization(),!a.authority||a.collectionId!==e||a.authority.replicaId!==t)throw c("authority_authorization_changed","Reconnect this collection authority before synchronizing.");s=await this.sendAuthoritySyncRequest(a,i,o,r)}let l=await s.json();if(!s.ok)throw R(l,"sync_failed","Collection synchronization failed.",s.status);return l}async sendAuthoritySyncRequest(e,t,i,o){if(!e.authority)throw c("not_remote_authority","This authorization has no remote authority endpoint.");let r=`${e.authority.syncUrl}/${i}`,a=o===void 0?void 0:JSON.stringify(o),s=await this.authorityProofHeaders(e,t,r,a,e.authority.accessToken);return fetch(r,{method:t,headers:{authorization:`Bearer ${e.authority.accessToken}`,...o===void 0?{}:{"content-type":"application/json"},...s},...a===void 0?{}:{body:a}})}async sendOperation(e,t,i,o,r={}){let a=i??{},s,l=!1,d=!1,p=crypto.randomUUID(),u=null,y;if(We(t,i)){if(y=await On(t,i),u=M(this.storage.getItem(this.pendingMutationKey())),u){if(u.collectionId!==e.collectionId||u.grantId!==e.grantId||u.keyId!==e.encryption?.key_id||u.operation!==t||u.inputFingerprint!==y)throw c("pending_mutation_unresolved","A previous write still has an unknown outcome. Retry that exact write before making another change.");p=u.requestId,d=!0}l=!0}if(e.encryption&&!e.authority){if(!e.grantId||!e.keyHandle)throw c("missing_grant_key","Reconnect this application to restore encrypted access.");try{if(l)if(u){if(!u.envelope)throw c("pending_mutation_unresolved","The pending write belongs to a different transport. Reconnect before retrying it.");s=u.envelope}else s=await X(this.keyStore,e.keyHandle,{grantId:e.grantId,applicationId:e.clientId,encryption:e.encryption},t,i,p),this.storage.setItem(this.pendingMutationKey(),JSON.stringify({collectionId:e.collectionId,...e.grantId?{grantId:e.grantId}:{},keyId:e.encryption.key_id,operation:t,inputFingerprint:y,requestId:p,envelope:s,createdAt:Date.now()}));else s=await X(this.keyStore,e.keyHandle,{grantId:e.grantId,applicationId:e.clientId,encryption:e.encryption},t,i)}catch(m){throw m instanceof C?D(m.code,m.message):m}a=s}else a={protocol_version:1,request_id:p,input:a},l&&!u&&this.storage.setItem(this.pendingMutationKey(),JSON.stringify({collectionId:e.collectionId,...e.grantId?{grantId:e.grantId}:{},operation:t,inputFingerprint:y,requestId:p,createdAt:Date.now()}));if(o&&s&&!e.authority){let m=!1;try{let k=await fetch(`${this.loopbackUrl}/v1/operations`,te({method:"POST",headers:{"content-type":"application/mdbase-connect+json"},body:JSON.stringify(s),signal:r.signal}));if(!me(k.status))return k.ok&&(this.markDirectAvailable(),this.setRoute("direct")),{response:k,requestId:p,encryptedRequest:s,pendingMutation:l,resumingMutation:d};m=k.status>=500,this.markDirectUnavailable()}catch(k){if(r.signal?.aborted)throw k;m=!0,await Me()==="denied"?this.setDirectStatus("denied"):this.markDirectUnavailable()}let P;try{P=e.expiresAt>Date.now()+3e4?e:await this.refreshAuthorization()}catch(k){throw l&&(m||d)?L(k):k}let g;try{g=await fetch(`${this.serverUrl}/v1/authorities/${encodeURIComponent(P.collectionId)}/operations/${t}`,{method:"POST",headers:{authorization:`Bearer ${P.accessToken}`,"content-type":"application/json"},body:JSON.stringify(s),signal:r.signal})}catch(k){throw l&&(m||d)?L(k):k}return g.ok&&this.setRoute("relay"),{response:g,requestId:p,encryptedRequest:s,directDeliveryUncertain:m,pendingMutation:l,resumingMutation:d}}let h=e.authority?`${e.authority.operationsUrl}/${t}`:`${this.serverUrl}/v1/authorities/${encodeURIComponent(e.collectionId)}/operations/${t}`,_=JSON.stringify(a),f=e.authority?await this.authorityProofHeaders(e,"POST",h,_,e.authority.accessToken):{},v=await fetch(h,{method:"POST",headers:{authorization:`Bearer ${e.authority?.accessToken??e.accessToken}`,"content-type":"application/json",...f},body:_,signal:r.signal});return v.ok&&this.setRoute(e.authority?"remote":"relay"),{response:v,requestId:p,encryptedRequest:s,pendingMutation:l,resumingMutation:d}}directCapable(e){return!(!e||e.authority||!e.encryption||!e.grantId||!e.keyHandle||this.directAccessMode==="disabled"||typeof location<"u"&&e.applicationOrigin&&e.applicationOrigin!==location.origin)}hasResumableMutationTransport(){return!!this.currentToken()}directEligible(e){return e!==null&&this.directCapable(e)&&this.storage.getItem(this.directPreferenceKey())!=="disabled"}async shouldAttemptDirect(e){if(!this.directEligible(e))return!1;if(this.directStatus==="available")return!0;if(this.directStatus==="unavailable"&&Date.now()<this.directRetryAt)return!1;let t=await Me();return t==="denied"?(this.setDirectStatus("denied"),!1):(t==="prompt"||t===null)&&this.storage.getItem(this.directPreferenceKey())!=="enabled"?(this.setDirectStatus("permission_required"),!1):(this.setDirectStatus("checking"),!0)}async probeDirectAccess(){this.setDirectStatus("checking");try{let e=await fetch(`${this.loopbackUrl}/v1/ready`,te({method:"GET",cache:"no-store"})),t=await e.json().catch(()=>null);if(e.ok&&t?.service==="mdbase-connect"&&t?.loopback_protocol_version===1&&t?.encrypted_protocol_version===1)return this.markDirectAvailable(),"available"}catch{}return await Me()==="denied"?this.setDirectStatus("denied"):(this.markDirectUnavailable(),"unavailable")}markDirectAvailable(){this.directFailures=0,this.directRetryAt=0,this.setDirectStatus("available")}markDirectUnavailable(){this.directFailures+=1,this.directRetryAt=Date.now()+Math.min(6e4,1e3*2**(this.directFailures-1)),this.setDirectStatus("unavailable")}setDirectStatus(e){return this.directStatus!==e&&(this.directStatus=e,this.emitConnection()),e}setRoute(e){this.currentRoute!==e&&(this.currentRoute=e,this.emitConnection())}emitConnection(){this.onChange()}invalidateRejectedAuthorization(e){let t=M(this.storage.getItem(this.tokenKey()));!t||!Pn(t,e)||(this.internals.removeToken(this.collectionId,t.keyHandle),this.currentRoute="relay",this.directStatus=this.directAccessMode==="disabled"?"disabled":"unavailable",this.emitConnection())}currentToken(){let e=this.storage.getItem(this.tokenKey()),t=M(e),i=o=>(this.internals.removeToken(this.collectionId,typeof o=="string"?o:void 0,"invalid_stored_grant"),null);if(!t)return e&&i(),null;if(t.version!==1||typeof t.accessToken!="string"||t.accessToken.length===0||typeof t.clientId!="string"||t.clientId.length===0||t.collectionId!==this.collectionId||typeof t.collectionName!="string"||t.collectionName.length===0||!Array.isArray(t.operations)||t.operations.some(o=>typeof o!="string")||typeof t.expiresAt!="number"||!Number.isFinite(t.expiresAt)||t.refreshToken!==void 0&&(typeof t.refreshToken!="string"||t.refreshToken.length===0)||t.refreshExpiresAt!==void 0&&(typeof t.refreshExpiresAt!="number"||!Number.isFinite(t.refreshExpiresAt))||!tt(t.scope)||t.fileCapability&&!et(t.fileCapability)||t.authority&&!In(t.authority,t.collectionId))return i(t.keyHandle);if(this.internals.relayEncryption==="required"){if(t.authority){if(!t.keyHandle||!t.authority.proofPublicKey)return i(t.keyHandle)}else if(!t.grantId||!t.keyHandle||!En(t.encryption,t.collectionId))return i(t.keyHandle)}return t.expiresAt<=Date.now()&&(!t.refreshToken||(t.refreshExpiresAt??0)<=Date.now())?this.directCapable(t)?t:(this.internals.removeToken(this.collectionId,t.keyHandle),null):t}async authorizedToken(){let e=this.currentToken();if(!e)return null;if(e.expiresAt>Date.now()+3e4)return e;if(!e.refreshToken||(e.refreshExpiresAt??0)<=Date.now()){if(this.directCapable(e))throw c("relay_authorization_expired","Direct access is still available on this computer, but using the relay requires reconnecting this application.");return this.internals.removeToken(this.collectionId,e.keyHandle),null}return this.refreshAuthorization()}refreshAuthorization(){return this.refreshPromise?this.refreshPromise:(this.refreshPromise=this.performRefresh().finally(()=>{this.refreshPromise=null}),this.refreshPromise)}async performRefresh(){let e=this.currentToken();if(!e?.refreshToken)throw c("not_authorized","Reconnect this application to continue.");if((e.refreshExpiresAt??0)<=Date.now())throw c("relay_authorization_expired","Direct access is still available on this computer, but using the relay requires reconnecting this application.");let t=e.refreshToken,i=`${this.serverUrl}/oauth/token`,o=new URLSearchParams({grant_type:"refresh_token",refresh_token:e.refreshToken,client_id:e.clientId}).toString(),r=e.authority?await this.authorityProofHeaders(e,"POST",i,o,e.refreshToken):{},a=await fetch(i,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",...r},body:o}),s=await a.json();if(!a.ok){let l=this.currentToken();if(l?.refreshToken&&l.refreshToken!==t)return l;throw this.directCapable(e)||this.internals.removeToken(this.collectionId,e.keyHandle),(ge(s)??s?.error?.code)==="invalid_grant"?c("authorization_expired",s?.error_description??s?.error?.message??"Reconnect this application to continue.",{status:a.status}):R(s,"authorization_expired","Reconnect this application to continue.",a.status)}return this.storeTokenResponse(s,e.clientId,e.keyHandle)}async authorityProofHeaders(e,t,i,o,r){if(!e.authority?.proofPublicKey)return{};if(!e.keyHandle)throw c("missing_grant_key","Reconnect this application to restore remote authority request signing.");try{let a=new URL(i);return await sn(this.keyStore,e.keyHandle,e.authority.proofPublicKey,{method:t,target:`${a.pathname}${a.search}`,body:o,credential:r})}catch(a){throw a instanceof C?D(a.code,a.message):a}}storeTokenResponse(e,t,i){if(e.collection_id!==this.collectionId)throw c("collection_mismatch","The refreshed authorization belongs to a different collection.");let o=this.internals.storeTokenResponse(e,t,i);return this.currentRoute=o.authority?"remote":"relay",this.directStatus=o.authority||this.directAccessMode==="disabled"?"disabled":"unavailable",this.emitConnection(),o}tokenKey(){return this.internals.tokenKey(this.collectionId)}notificationKey(e="web_push"){return this.internals.notificationKey(this.collectionId,e)}pendingMutationKey(){return this.internals.pendingMutationKey(this.collectionId)}clearPendingMutation(){this.storage.removeItem(this.pendingMutationKey())}directPreferenceKey(){return this.internals.directPreferenceKey()}};var yo=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]),mo=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ve=class{state=mo.slice();block=new Uint8Array(64);words=new Uint32Array(64);blockLength=0;byteLength=0;finished=!1;update(e){if(this.finished)throw new Error("SHA-256 digest is already finalized.");if(this.byteLength+=e.byteLength,!Number.isSafeInteger(this.byteLength))throw new Error("SHA-256 input exceeds the safe browser byte range.");let t=0;if(this.blockLength>0){let i=Math.min(64-this.blockLength,e.byteLength);this.block.set(e.subarray(0,i),this.blockLength),this.blockLength+=i,t+=i,this.blockLength===64&&(this.compress(this.block),this.blockLength=0)}for(;t+64<=e.byteLength;)this.compress(e.subarray(t,t+64)),t+=64;return t<e.byteLength&&(this.block.set(e.subarray(t),0),this.blockLength=e.byteLength-t),this}digestHex(){if(this.finished)throw new Error("SHA-256 digest is already finalized.");this.finished=!0,this.block[this.blockLength]=128,this.block.fill(0,this.blockLength+1),this.blockLength>=56&&(this.compress(this.block),this.block.fill(0));let e=this.byteLength*8,t=Math.floor(e/4294967296),i=e>>>0;return Vn(this.block,56,t),Vn(this.block,60,i),this.compress(this.block),[...this.state].map(o=>o.toString(16).padStart(8,"0")).join("")}compress(e){let t=this.words;for(let u=0;u<16;u+=1){let y=u*4;t[u]=(e[y]<<24|e[y+1]<<16|e[y+2]<<8|e[y+3])>>>0}for(let u=16;u<64;u+=1){let y=t[u-15],h=t[u-2],_=K(y,7)^K(y,18)^y>>>3,f=K(h,17)^K(h,19)^h>>>10;t[u]=t[u-16]+_+t[u-7]+f>>>0}let i=this.state[0],o=this.state[1],r=this.state[2],a=this.state[3],s=this.state[4],l=this.state[5],d=this.state[6],p=this.state[7];for(let u=0;u<64;u+=1){let y=K(s,6)^K(s,11)^K(s,25),h=s&l^~s&d,_=p+y+h+yo[u]+t[u]>>>0,f=K(i,2)^K(i,13)^K(i,22),v=i&o^i&r^o&r,m=f+v>>>0;p=d,d=l,l=s,s=a+_>>>0,a=r,r=o,o=i,i=_+m>>>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]+l>>>0,this.state[6]=this.state[6]+d>>>0,this.state[7]=this.state[7]+p>>>0}};function K(n,e){return n>>>e|n<<32-e}function Vn(n,e,t){n[e]=t>>>24,n[e+1]=t>>>16,n[e+2]=t>>>8,n[e+3]=t}var ct=class{constructor(e,t){this.signal=t;this.iterator=_o(e)}signal;iterator;remainder=new Uint8Array;remainderOffset=0;maxSourceChunkBytes=null;iteratorClosing=!1;ended=!1;setMaxSourceChunkBytes(e){this.maxSourceChunkBytes=e}async read(e){let t=new Uint8Array(e),i=0;for(;i<e;){if(this.remainderOffset===this.remainder.byteLength){let r=await this.nextSourceChunk();if(r.done)throw this.ended=!0,c("invalid_request","Streamed file bytes ended before the declared size.");if(!(r.value instanceof Uint8Array))throw c("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 c("invalid_request",`A streamed file chunk exceeded the negotiated ${this.maxSourceChunkBytes}-byte upload part size.`);if(this.remainder=r.value,this.remainderOffset=0,this.remainder.byteLength===0)continue}let o=Math.min(e-i,this.remainder.byteLength-this.remainderOffset);t.set(this.remainder.subarray(this.remainderOffset,this.remainderOffset+o),i),i+=o,this.remainderOffset+=o}return t}async expectEnd(){if(this.remainderOffset<this.remainder.byteLength)throw c("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 c("invalid_request","A streamed file chunk was not a Uint8Array.");if(e.value.byteLength>0)throw c("invalid_request","Streamed file bytes exceed the declared size.")}}async close(){this.ended=!0,this.closeIterator()}async nextSourceChunk(){Gn(this.signal);let e=this.iterator.next(),t=this.signal;if(!t)return e;let i=()=>{},o=new Promise((r,a)=>{let s=()=>{this.closeIterator(),a(Yn(t))};t.addEventListener("abort",s,{once:!0}),i=()=>t.removeEventListener("abort",s),t.aborted&&s()});try{let r=await Promise.race([e,o]);return Gn(t),r}finally{i()}}closeIterator(){if(!this.iteratorClosing){this.iteratorClosing=!0;try{this.iterator.return?.()?.catch(()=>{})}catch{}}}};function _o(n){if(typeof n.getReader=="function"){let t=n.getReader(),i=!1,o=()=>{i||(i=!0,t.releaseLock())};return{async next(){if(i)return{done:!0,value:void 0};let r=await t.read();return r.done&&o(),r},async return(){if(!i)try{await t.cancel()}finally{o()}return{done:!0,value:void 0}}}}let e=n;if(typeof e[Symbol.asyncIterator]!="function")throw c("invalid_request","Streamed files require a readable byte stream.");return e[Symbol.asyncIterator]()}function Gn(n){if(n?.aborted)throw Yn(n)}function Yn(n){return c("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:n?.reason})}var Jn=1024*1024,go=4,Qn=8,we=3,Xn=64*1024*1024,bo=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,vo=/^sha256:[0-9a-f]{64}$/u,Fe=class{constructor(e,t,i,o){this.capability=e;this.request=t;this.framed=i;this.hosted=o}capability;request;framed;hosted;async*list(e={}){this.requireAction("list");let t;do{ie(e.signal);let i=new URLSearchParams({protocol_version:String(1),...e.folder?{folder:e.folder}:{},...t?{after:t}:{},...e.pageSize?{limit:String(Ro(e.pageSize))}:{}}),o=await this.request("GET",`?${i.toString()}`,void 0,e.signal);if(o.protocol_version!==1||o.type!=="files_page"||!Array.isArray(o.files))throw c("invalid_operation_response","The authority returned an invalid file page.");for(let r of o.files)ie(e.signal),yield r;t=o.next}while(t)}async upload(e,t,i={}){this.requireAction(i.ifRevision?"replace":"add");let o=Co(t,i.mediaType),r=Wn(i.concurrency),a=await wo(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,l,d)=>o.slice(l,l+d))}async uploadStream(e,t,i={}){if(this.requireAction(i.ifRevision?"replace":"add"),!Number.isSafeInteger(t.size)||t.size<0)throw c("invalid_request","Streamed file size must be a non-negative safe integer.");if(!vo.test(t.contentDigest))throw c("invalid_request","Streamed files require a lowercase SHA-256 content digest.");let o=new ct(t.stream,i.signal),r=new ve;return this.uploadKnownSource(e,t.size,t.contentDigest,i.mediaType??t.mediaType,i,1,async(a,s,l)=>{let d=await o.read(l);return r.update(d),d},async()=>{if(await o.expectEnd(),`sha256:${r.digestHex()}`!==t.contentDigest)throw c("invalid_request","Streamed file bytes do not match the declared SHA-256 digest.")},()=>o.close(),a=>o.setMaxSourceChunkBytes(a))}async uploadKnownSource(e,t,i,o,r,a,s,l,d,p){let u=r.transferId??crypto.randomUUID();if(!bo.test(u))throw c("invalid_request","File transfer ID must be a UUID.");let y=!1;try{let h=await this.request("POST","uploads",{protocol_version:1,type:"open_file_upload",transfer_id:u,path:e,size:t,content_digest:i,...o?{media_type:o}:{},...r.ifRevision?{if_revision:r.ifRevision}:{}},r.signal);if(Zn(h,u,"upload"),h.total_size!==t||h.strategy.kind==="object_ranges")throw c("invalid_operation_response","The authority returned an incompatible upload strategy.");let _=h.strategy.kind==="framed_chunks";if(_&&!this.framed)throw c("invalid_operation_response","Encrypted file chunk delivery is unavailable.");let f=h.strategy.kind==="object_put"?Math.max(1,t):h.strategy.kind==="framed_chunks"?h.strategy.chunk_size:h.strategy.part_size,v=h.strategy.kind==="object_put"?1:Math.ceil(t/f);if(p?.(f),!_&&h.received.length===v){let w=await this.tryReplayUploadCommit(u,h.strategy.kind==="object_multipart"?h.uploaded_parts:void 0,r.signal);if(w)return y=!0,w.file}let m=new Set(h.received),P=new Map((h.uploaded_parts??[]).map(w=>[w.part_number-1,w])),g=[...m].reduce((w,F)=>w+Ao(t,f,F),0),k=await Io(v,a,async w=>{let F=w*f,j=Math.min(f,Math.max(0,t-F)),ut=await s(w,F,j);if(Po(ut)!==j)throw c("invalid_request","Streamed file bytes ended before the declared size.");if(m.has(w))return P.get(w)??null;let ni=_?await Lt(async()=>this.framed.uploadChunk(h,w,await So(ut),r.signal),r.signal).then(()=>null):await this.uploadPart(u,w,F,ut,j,h.strategy.kind==="object_multipart",r.signal);return g+=j,r.onProgress?.({phase:"uploading",transferredBytes:g,totalBytes:t}),ni});await l?.();let x=await this.commitUpload(u,h.strategy.kind==="object_multipart"?k.filter(w=>w!==null):void 0,r.signal);if(x.protocol_version!==1||x.type!=="file_upload_committed"||x.transfer_id!==u||x.file.path!==e||x.file.size!==t||x.file.content_digest!==i)throw c("invalid_operation_response","The authority returned an invalid file receipt.");return y=!0,x.file}catch(h){throw ze(h)}finally{await d?.().catch(()=>{}),!y&&r.transferId===void 0&&await this.abort(u)}}async download(e,t={}){if(e.size>Xn)throw c("invalid_request",`download() buffers at most ${Xn} bytes; use downloadStream() for larger files.`);let i=await this.downloadStream(e,t),o=[],r=i.getReader();for(;;){let a=await r.read();if(a.done)break;o.push(a.value)}return new Blob(o.map(a=>{let s=new Uint8Array(a.byteLength);return s.set(a),s.buffer}),{type:e.media_type??""})}async downloadStream(e,t={}){this.requireAction("read"),Wn(t.concurrency);let i=crypto.randomUUID(),o;try{if(o=await this.request("POST","downloads",{protocol_version:1,type:"open_file_download",transfer_id:i,file_id:e.file_id,revision:e.revision},t.signal),Zn(o,i,"download"),o.total_size!==e.size||o.strategy.kind!=="object_ranges"&&o.strategy.kind!=="framed_chunks")throw c("invalid_operation_response","The authority returned an incompatible download session.");if(o.strategy.kind==="framed_chunks"&&!this.framed)throw c("invalid_operation_response","Encrypted file chunk delivery is unavailable.");if(o.strategy.kind==="object_ranges"&&e.size>0&&!this.hosted)throw c("invalid_operation_response","Authenticated hosted file delivery is unavailable.")}catch(f){throw await this.abort(i),ze(f)}let r=o.strategy.kind==="framed_chunks"?o.strategy.chunk_size:o.strategy.part_size,a=Math.ceil(e.size/r),s=new ve,l=0,d=0,p=null,u=0,y=!1,h=async()=>{y||(y=!0,await p?.cancel().catch(()=>{}),p=null,await this.abort(i))},_=()=>{if(u!==e.size||`sha256:${s.digestHex()}`!==e.content_digest)throw c("invalid_operation_response","Downloaded file bytes failed integrity verification.")};return new ReadableStream({pull:async f=>{try{if(ie(t.signal),o.strategy.kind==="object_ranges")for(;;){if(!p){if(l>=a){_(),await h(),f.close();return}let k=l*r;d=Math.min(r,e.size-k),p=(await Lt(()=>this.hosted.downloadPart(o,l,d,t.signal),t.signal)).getReader()}let g=await p.read();if(g.done){if(p.releaseLock(),p=null,d!==0)throw c("invalid_operation_response","A hosted file range ended before its declared byte length.");l+=1;continue}if(!(g.value instanceof Uint8Array))throw c("invalid_operation_response","A hosted file range returned a non-byte chunk.");if(g.value.byteLength!==0){if(g.value.byteLength>d)throw c("invalid_operation_response","A hosted file range exceeded its declared byte length.");d-=g.value.byteLength,s.update(g.value),u+=g.value.byteLength,t.onProgress?.({phase:"downloading",transferredBytes:u,totalBytes:e.size}),f.enqueue(g.value);return}}if(l>=a){_(),await h(),f.close();return}let v=l*r,m=Math.min(r,e.size-v),P=await Lt(()=>this.framed.downloadChunk(o,l,t.signal),t.signal);if(P.byteLength!==m)throw c("invalid_operation_response","A file chunk had the wrong byte length.");s.update(P),u+=P.byteLength,l+=1,t.onProgress?.({phase:"downloading",transferredBytes:u,totalBytes:e.size}),l===a&&_(),f.enqueue(P),l===a&&(await h(),f.close())}catch(v){await h(),f.error(ze(v))}},cancel:h})}async downloadBytes(e,t={}){return new Uint8Array(await(await this.download(e,t)).arrayBuffer())}async move(e,t,i={}){this.requireAction("move");let o=i.mutationId??crypto.randomUUID(),r;try{r=await this.request("POST",`${encodeURIComponent(e.file_id)}/move`,{protocol_version:1,type:"move_file",mutation_id:o,file_id:e.file_id,if_revision:i.ifRevision??e.revision,from_path:e.path,path:t,update_references:!1},i.signal)}catch(a){throw ze(a)}if(r.protocol_version!==1||r.type!=="file_moved"||r.mutation_id!==o||r.file.file_id!==e.file_id||r.file.path!==t)throw c("invalid_operation_response","The authority returned an invalid file move receipt.");return r.file}async delete(e,t={}){this.requireAction("delete");let i=t.mutationId??crypto.randomUUID(),o;try{o=await this.request("POST",`${encodeURIComponent(e.file_id)}/delete`,{protocol_version:1,type:"delete_file",mutation_id:i,file_id:e.file_id,if_revision:t.ifRevision??e.revision,path:e.path},t.signal)}catch(r){throw ze(r)}if(o.protocol_version!==1||o.type!=="file_deleted"||o.mutation_id!==i||o.file_id!==e.file_id||o.previous_path!==e.path)throw c("invalid_operation_response","The authority returned an invalid file delete receipt.");return o}async uploadPart(e,t,i,o,r,a,s){for(let l=1;l<=we;l+=1){ie(s);try{let d=await this.request("POST",`uploads/${encodeURIComponent(e)}/parts`,{protocol_version:1,type:"prepare_file_upload_part",transfer_id:e,part_number:t+1,content_length:r},s);Oo(d,e,t,i,r,"PUT");let p=await fetch(d.url,{method:d.method,headers:To(d.headers),body:o,redirect:"error",signal:s});if(!p.ok)throw new Error(`Object upload failed with HTTP ${p.status}.`);let u=p.headers.get("etag");if(a&&!u)throw new Error("Multipart object upload did not return an ETag.");return{part_number:t+1,etag:u??""}}catch(d){if(s?.aborted||l===we)throw d}}throw new Error("Unreachable upload retry state.")}async tryReplayUploadCommit(e,t,i){try{return await this.commitUpload(e,t,i)}catch(o){if(o instanceof S&&o.code==="file_upload_incomplete")return null;throw o}}async commitUpload(e,t,i){let o;for(let r=1;r<=we;r+=1){ie(i);try{return await this.request("POST",`uploads/${encodeURIComponent(e)}/commit`,{protocol_version:1,type:"commit_file_upload",transfer_id:e,...t===void 0?{}:{parts:t}},i)}catch(a){if(o=a,i?.aborted||a instanceof S||r===we)throw a}}throw o}requireAction(e){if(!this.capability()?.actions.includes(e))throw c("not_authorized",`This connection is not authorized to ${e} files.`)}async abort(e){await this.request("DELETE",`transfers/${encodeURIComponent(e)}`).catch(()=>{})}};async function wo(n,e,t){let i=new ve;for(let o=0;o<n.size;o+=Jn){ie(e);let r=new Uint8Array(await n.slice(o,o+Jn).arrayBuffer());i.update(r),t(Math.min(n.size,o+r.byteLength))}return n.size===0&&t(0),i.digestHex()}function Co(n,e){if(n instanceof Blob)return e&&e!==n.type?n.slice(0,n.size,e):n;if(n instanceof ArrayBuffer)return new Blob([n],{type:e});let t=new Uint8Array(n.byteLength);return t.set(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)),new Blob([t.buffer],{type:e})}function Po(n){return n instanceof Blob?n.size:n.byteLength}async function So(n){return n instanceof Blob?new Uint8Array(await n.arrayBuffer()):n}function Wn(n=go){if(!Number.isInteger(n)||n<1||n>Qn)throw c("invalid_request",`File concurrency must be between 1 and ${Qn}.`);return n}function Ro(n){if(!Number.isInteger(n)||n<1||n>1e3)throw c("invalid_request","File page size must be between 1 and 1000.");return n}function Zn(n,e,t){if(n.protocol_version!==1||n.type!=="file_transfer"||n.transfer_id!==e||n.direction!==t||!Number.isSafeInteger(n.total_size)||n.total_size<0||!Array.isArray(n.received)||!ko(n))throw c("invalid_operation_response","The authority returned an invalid file transfer session.");let i=n.strategy.kind==="framed_chunks"?n.strategy.chunk_size:n.strategy.kind==="object_put"?Math.max(1,n.total_size):n.strategy.part_size,o=n.strategy.kind==="object_put"?1:Math.ceil(n.total_size/i);if(new Set(n.received).size!==n.received.length||n.received.some(a=>!Number.isSafeInteger(a)||a<0||a>=o))throw c("invalid_operation_response","The authority returned invalid transfer progress.");let r=n.uploaded_parts??[];if(!Array.isArray(r)||r.some((a,s)=>!Number.isSafeInteger(a?.part_number)||a.part_number<1||a.part_number>o||typeof a.etag!="string"||a.etag.length===0||a.etag.length>255||s>0&&r[s-1].part_number>=a.part_number)||(n.strategy.kind==="object_multipart"?r.length!==n.received.length||r.some((a,s)=>a.part_number-1!==n.received[s]):r.length!==0))throw c("invalid_operation_response","The authority returned invalid uploaded part receipts.")}function ko(n){return n.strategy.kind==="framed_chunks"?n.protection==="grant_aead_v1"&&Number.isSafeInteger(n.strategy.chunk_size)&&n.strategy.chunk_size>0:n.protection!=="transport_tls"?!1:n.strategy.kind==="object_put"?!0:Number.isSafeInteger(n.strategy.part_size)&&n.strategy.part_size>0}function Ao(n,e,t){return Math.min(e,Math.max(0,n-t*e))}async function Lt(n,e){for(let t=1;t<=we;t+=1){ie(e);try{return await n()}catch(i){if(e?.aborted||t===we)throw i}}throw new Error("Unreachable file chunk retry state.")}function Oo(n,e,t,i,o,r){let a;try{a=new URL(n.url)}catch{throw c("invalid_operation_response","The authority returned an invalid object URL.")}if(n.protocol_version!==1||n.type!=="file_part"||n.transfer_id!==e||n.part_index!==t||n.offset!==i||n.content_length!==o||n.method.toUpperCase()!==r||a.protocol!=="https:"&&!(a.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(a.hostname))||a.username||a.password)throw c("invalid_operation_response","The authority returned an invalid prepared file part.")}function To(n){let e=new Headers;for(let[t,i]of Object.entries(n))["host","content-length"].includes(t.toLowerCase())||e.set(t,i);return e}async function Io(n,e,t){let i=new Array(n),o=0;return await Promise.all(Array.from({length:Math.min(n,e)},async()=>{for(;o<n;){let r=o;o+=1,i[r]=await t(r)}})),i}function ie(n){if(n?.aborted)throw c("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:n.reason})}function ze(n){return n instanceof S?n:typeof DOMException<"u"&&n instanceof DOMException&&n.name==="AbortError"?c("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:n}):c("temporarily_unavailable","The file transfer could not be completed.",{cause:n})}var oe=["describe","changes","read","query"];var De=class{constructor(e,t){this.internals=e;this.collectionId=t;this.transport=new st({serverUrl:e.serverUrl,storage:e.storage,keyStore:e.keyStore,directAccessMode:e.directAccessMode,loopbackUrl:e.loopbackUrl,collectionId:t,internals:e,onChange:()=>this.emitConnection()}),this.files=new Fe(()=>this.fileCapability,(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)}),this.collectionClient=new Ee({operation:(i,o,r)=>this.transport.performOperation(i,o,r)}),this.notifications=new nt({serverUrl:e.serverUrl,storage:e.storage,authorizedToken:()=>this.transport.authorizedToken(),register:()=>this.internals.register(),notificationKey:i=>e.notificationKey(t,i)})}internals;collectionId;collectionClient;notifications;transport;files;connectionListeners=new Set;get displayName(){return this.transport.currentToken()?.collectionName??`Collection ${this.collectionId.slice(0,8)}`}get operations(){return[...this.transport.currentToken()?.operations??[]]}get scope(){return this.transport.currentToken()?.scope??null}get fileCapability(){return this.transport.currentToken()?.fileCapability??null}get directAccess(){return this.transport.directAccess}get route(){return this.transport.route}register(){return A(()=>this.internals.register(),Z)}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}:{},route:this.transport.route,directAccess:this.transport.directAccess}:null}authorizationCapabilities(e=oe){let t=this.operations,i=B(e).filter(o=>!t.includes(o));return{authorized:this.info()!==null,sufficient:this.info()!==null&&i.length===0,collectionId:this.collectionId,grantedOperations:t,missingOperations:i}}hasOperations(e){return this.authorizationCapabilities(e).sufficient}authorize(e={}){return A(()=>this.internals.authorize({...e,target:{kind:"collection",collectionId:this.collectionId}}),ee)}async requestOperations(e,t={}){let i=this.authorizationCapabilities(e);return i.sufficient?E({kind:"unchanged",connection:this}):this.authorize({...t,operations:B([...i.grantedOperations,...i.missingOperations])})}onConnectionChange(e){return this.connectionListeners.add(e),e(this.info()),()=>this.connectionListeners.delete(e)}notifyStorageChanged(){this.transport.notifyStorageChanged()}checkDirectAccess(){return A(()=>this.transport.checkDirectAccess(),Xe)}requestDirectAccess(){return A(()=>this.transport.requestDirectAccess(),Xe)}disableDirectAccess(){this.transport.disableDirectAccess()}sync(){let e=this.transport.currentToken();if(!e)return null;let t=e.collectionId;if(!e.authority){if(!e.grantId||!e.operations.includes("sync"))return null;let o=e.grantId;return{collectionId:t,replicaId:o,transport:{openSession:()=>this.transport.performOperation("sync",{action:"open_session"}),snapshot:(r,a)=>this.transport.performOperation("sync",{action:"snapshot",snapshot_id:r,...a?{page:a}:{}}),changes:(r,a=200)=>this.transport.performOperation("sync",{action:"changes",after:r,limit:a}),mutate:r=>this.transport.performOperation("sync",{action:"mutate",mutation:r})}}}let i=e.authority.replicaId;return{collectionId:t,replicaId:i,transport:{openSession:()=>this.transport.performAuthoritySyncRequest(t,i,"POST","sessions"),snapshot:(o,r)=>{let a=new URLSearchParams({snapshot_id:o});return r&&a.set("page",r),this.transport.performAuthoritySyncRequest(t,i,"GET",`snapshot?${a}`)},changes:(o,r=200)=>this.transport.performAuthoritySyncRequest(t,i,"GET",`changes?${new URLSearchParams({after:String(o),limit:String(r)})}`),mutate:o=>this.transport.performAuthoritySyncRequest(t,i,"POST","mutations",o)}}}registerNotifications(e){return A(()=>this.notifications.registerNotifications(e),fe)}registerNativeNotifications(e){return A(()=>this.notifications.registerNativeNotifications(e),fe)}unregisterNativeNotifications(){return A(()=>this.notifications.unregisterNativeNotifications(),fe)}unregisterNotifications(e){return A(()=>this.notifications.unregisterNotifications(e),fe)}forget(){let e=this.transport.currentToken();this.internals.removeToken(this.collectionId,e?.keyHandle,"not_authorized"),this.transport.notifyStorageChanged()}describe(){return this.collectionClient.describe()}changes(e={},t){return this.collectionClient.changes(e,t)}read(e){return this.collectionClient.read(e)}query(e={},t){return this.collectionClient.query(e,t)}queryPages(e={},t={}){return this.collectionClient.queryPages(e,t)}queryAll(e={},t={}){return this.collectionClient.queryAll(e,t)}listViews(){return this.collectionClient.listViews()}executeView(e){return this.collectionClient.executeView(e)}readViewSource(e){return this.collectionClient.readViewSource(e)}createViewSource(e){return this.collectionClient.createViewSource(e)}updateViewSource(e){return this.collectionClient.updateViewSource(e)}deleteViewSource(e){return this.collectionClient.deleteViewSource(e)}create(e){return this.collectionClient.create(e)}update(e){return this.collectionClient.update(e)}delete(e,t){return this.collectionClient.delete(e,t)}preflightDelete(e,t){return this.collectionClient.preflightDelete(e,t)}rename(e,t){return this.collectionClient.rename(e,t)}preflightRename(e,t){return this.collectionClient.preflightRename(e,t)}async renameWithProgress(e,t={}){let i=Date.now(),o=this.pendingMutation()?.operation==="rename",r,a=(s,l,d=0)=>{t.onProgress?.({operation:"rename",state:s,elapsedMs:Date.now()-i,cancellable:l,resumed:o,completedUnits:d,...r?{estimate:r}:{}})};try{ne(t.signal),a("preflighting",!0);let s=t.preflight?E(t.preflight):await this.preflightRename(e,{signal:t.signal});if(!s.ok)return s;let l=s.value;try{Sn(e,l)}catch(u){if(u instanceof S)return T(u.problem);throw u}r=kn(e,l),a("ready",!0),ne(t.signal);let d=this.transport.hasResumableMutationTransport();a("applying",d);let p=await this.rename(e,d?{signal:t.signal}:void 0);return p.ok&&a("completed",!1,r.totalUnits),p}catch(s){if(Mt(s,t.signal)&&a("cancelled",!1),s instanceof S)return T(s.problem);throw s}}async deleteWithProgress(e,t={}){let i=Date.now(),o=this.pendingMutation()?.operation==="delete",r,a=(s,l,d=0)=>{t.onProgress?.({operation:"delete",state:s,elapsedMs:Date.now()-i,cancellable:l,resumed:o,completedUnits:d,...r?{estimate:r}:{}})};try{ne(t.signal),a("preflighting",!0);let s=t.preflight?E(t.preflight):await this.preflightDelete(e,{signal:t.signal});if(!s.ok)return s;let l=s.value;try{Rn(e,l)}catch(u){if(u instanceof S)return T(u.problem);throw u}r=An(l),a("ready",!0),ne(t.signal);let d=this.transport.hasResumableMutationTransport();a("applying",d);let p=await this.delete(e,d?{signal:t.signal}:void 0);return p.ok&&a("completed",!1,r.totalUnits),p}catch(s){if(Mt(s,t.signal)&&a("cancelled",!1),s instanceof S)return T(s.problem);throw s}}pendingMutation(){return this.transport.pendingMutation()}resumePendingMutation(e,t){return A(()=>this.transport.resumePendingMutation(e,t),I)}validate(e={}){return this.collectionClient.validate(e)}readType(e){return this.collectionClient.readType(e)}createType(e){return this.collectionClient.createType(e)}updateType(e){return this.collectionClient.updateType(e)}installTypePack(e){return this.collectionClient.installTypePack(e)}listTimers(e){return this.collectionClient.listTimers(e)}putTimer(e){return this.collectionClient.putTimer(e)}cancelTimer(e){return this.collectionClient.cancelTimer(e)}reconcileTimers(e){return this.collectionClient.reconcileTimers(e)}watch(e={}){return this.collectionClient.watch(e)}operation(e,t,i){return this.collectionClient.operation(e,t,i)}emitConnection(){let e=this.info();for(let t of this.connectionListeners)t(e)}};async function Nt(n,e,t,i,o){if(!n||typeof n!="object"||Array.isArray(n))throw c("invalid_first_contact","The authorization service returned an invalid first-contact challenge.");let r=n,a=await Y(t);if(r.application_id!==e.id||r.application_installation_id!==a||r.application_agreement_public_key!==t.agreementPublicKey||r.application_signing_public_key!==t.signingPublicKey)throw c("invalid_first_contact","The first-contact challenge does not match this application installation.");let s=JSON.stringify(r);if(s===o)return o;if(!i.onFirstContact)throw c("first_contact_handler_required","Local access requires the application to display a first-contact comparison code.");let l;try{l=await Je(r,"application",t)}catch(d){throw c("invalid_first_contact","The authorization service returned an invalid first-contact challenge.",{cause:d})}return await i.onFirstContact({binding:r,authenticationString:l,applicationId:r.application_id,connectorId:r.connector_id}),s}async function qt(n,e,t){let i=`application-installation:${e}:${t.id}`,o=await n.get(i);if(o)return o;try{return await n.create(i)}catch(r){let a=await n.get(i);if(a)return a;throw r}}var lt=class{serverUrl;manifest;manifestSource;redirectUri;storage;relayEncryption;keyStore;directAccessMode;loopbackUrl;navigate;credentialStorage;application=null;completionPromises=new Map;connectionCache=new Map;listeners=new Set;invalidatedConnections=new Map;constructor(e){this.serverUrl=Mn(e.serverUrl),this.manifest=e.manifest??Un(),this.manifestSource=typeof this.manifest=="string"?this.manifest:this.manifest.distribution==="portable"?`bundle:${this.manifest.id}:${Nn(this.manifest)}`:`bundle:${this.manifest.id}`;let t=Ln(this.manifest);this.redirectUri=e.redirectUri??(typeof this.manifest!="string"&&this.manifest.distribution==="portable"?"":zn()),this.storage=e.storage??Dn(t),this.relayEncryption=e.relayEncryption??"required",this.keyStore=e.keyStore??(t?new le:new ce),this.credentialStorage=e.storage||e.keyStore?"custom":this.storage instanceof _e?"memory":"persistent",this.directAccessMode=e.directAccess??"auto",this.loopbackUrl=Tn(e.loopbackUrl??`http://127.0.0.1:${tn}`),this.navigate=e.navigate,typeof window<"u"&&this.storage===window.localStorage&&window.addEventListener("storage",i=>{i.storageArea!==this.storage||!i.key?.startsWith(this.storagePrefix())||(this.connectionCache.get(Eo(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}}async register(){if(this.application)return this.application;let e=await $(`${this.serverUrl}/v1/apps/register`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({manifest:await this.loadManifest()})},"temporarily_unavailable","Application registration is temporarily unavailable."),t=await e.json();if(!e.ok)throw R(t,"discovery_failed","Application discovery failed.",e.status);return this.application=t.application,this.application}async loadManifest(){if(typeof this.manifest!="string")return this.manifest;let e=this.manifest,t;try{t=await fetch(e,{headers:{accept:"application/json"}})}catch(i){throw c("manifest_load_failed","The bundled application declaration could not be loaded.",{cause:i})}if(!t.ok)throw c("manifest_load_failed",`The bundled application declaration returned HTTP ${t.status}.`,{status:t.status});try{return await t.json()}catch(i){throw c("invalid_application_manifest","The bundled application declaration is not valid JSON.",{cause:i})}}async authorize(e={}){if(typeof location>"u"&&!this.navigate&&!e.openVerification)throw c("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.register()}catch(r){throw i?.close(),r}return o.distribution==="portable"?(e.openVerification&&i?.close(),this.authorizePortable(o,e,e.openVerification?null:i)):this.authorizeWeb(o,e,i)}async authorizeWeb(e,t,i){let{verifier:o,challenge:r}=await Ue(),a=N(24),s=crypto.randomUUID(),l=t.target?.kind==="collection"?t.target.collectionId:void 0,d=`grant:${e.id}:${a}`,p=await this.keyStore.create(d),u=await qt(this.keyStore,this.serverUrl,e),y=B(t.operations??oe),h=new Date,_=await Te({protocol_version:Re,authorization_id:s,application_id:e.id,application_manifest_digest:e.manifest_digest,application_installation_id:await Y(u),installation_agreement_public_key:u.agreementPublicKey,installation_signing_public_key:u.signingPublicKey,grant_agreement_public_key:p.agreementPublicKey,grant_signing_public_key:p.signingPublicKey,flow:"authorization_code",authorization_nonce:N(32),issued_at:h.toISOString(),expires_at:new Date(h.getTime()+600*1e3).toISOString(),redirect_uri:this.redirectUri,state:a,code_challenge:r,requested_operations:y,...e.requirements?.files?{requested_files:e.requirements.files}:{},...l?{collection_id:l}:{}},u),f={version:1,verifier:o,state:a,clientId:e.id,redirectUri:this.redirectUri,relayEncryption:this.relayEncryption,collectionId:l,returnTo:t.returnTo,keyHandle:d,installationKeyHandle:u.handle,authorizationId:s,applicationAgreementPublicKey:p.agreementPublicKey,applicationSigningPublicKey:p.signingPublicKey};this.storage.setItem(this.pendingKey(a),JSON.stringify(f));try{let v=await fetch(`${this.serverUrl}/oauth/authorization_request`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e.id,redirect_uri:this.redirectUri,code_challenge:r,code_challenge_method:"S256",state:a,operations:y.join(","),...l?{collection_id:l}:{},application_authorization:JSON.stringify(_)}),signal:t.signal}),m=await v.json();if(!v.ok)throw R(m,"device_authorization_failed","Application authorization could not be started.",v.status);if(typeof m.authorization_uri!="string"||m.authorization_id!==s||!Number.isInteger(m.expires_in)||!Number.isInteger(m.interval)||m.expires_in<=0||m.interval<=0)throw c("invalid_device_authorization_response","The authorization service returned an invalid polling response.");if(this.navigate)await this.navigate(m.authorization_uri);else if(i)i.location.href=m.authorization_uri;else throw c("browser_required","The approval window was blocked. Allow popups for this application and try again.");let P=Date.now()+m.expires_in*1e3,g=m.interval,k="";for(;Date.now()<P;){if(await he(g*1e3,t.signal),t.signal?.aborted)throw c("authorization_cancelled","Application authorization was cancelled.");let x;try{x=await fetch(`${this.serverUrl}/oauth/authorization_status`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e.id,authorization_id:s,code_verifier:o}),signal:t.signal})}catch(j){if(t.signal?.aborted)throw c("authorization_cancelled","Application authorization was cancelled.",{cause:j});continue}let w=await x.json();if(!x.ok){let j=ge(w);if(j==="authorization_pending"){w.first_contact&&(k=await Nt(w.first_contact,e,u,t,k));continue}if(j==="slow_down"){g+=2;continue}throw R(w,"token_exchange_failed","Application authorization could not be completed.",x.status)}if(typeof w.authorization_redirect!="string")throw c("invalid_token_response","The authorization service returned an invalid completion response.");let F=await this.performAuthorizationCompletion(w.authorization_redirect,a);return i?.close(),{kind:"connected",...F}}throw c("expired_token","The application authorization expired.")}catch(v){throw i?.close(),this.storage.removeItem(this.pendingKey(a)),await this.keyStore.delete(d),t.signal?.aborted?c("authorization_cancelled","Application authorization was cancelled.",{cause:v}):v}}async authorizePortable(e,t,i){if(this.relayEncryption!=="required")throw i?.close(),c("encryption_required","Downloaded applications require encrypted relay authorization.");let{verifier:o,challenge:r}=await Ue(),a=`grant:${e.id}:${N(24)}`,s=await this.keyStore.create(a),l=await qt(this.keyStore,this.serverUrl,e),d=B(t.operations??oe),p=crypto.randomUUID(),u=new Date,y=await Te({protocol_version:Re,authorization_id:p,application_id:e.id,application_manifest_digest:e.manifest_digest,application_installation_id:await Y(l),installation_agreement_public_key:l.agreementPublicKey,installation_signing_public_key:l.signingPublicKey,grant_agreement_public_key:s.agreementPublicKey,grant_signing_public_key:s.signingPublicKey,flow:"device_code",authorization_nonce:N(32),issued_at:u.toISOString(),expires_at:new Date(u.getTime()+600*1e3).toISOString(),code_challenge:r,requested_operations:d,...e.requirements?.files?{requested_files:e.requirements.files}:{},...t.target?.kind==="collection"?{collection_id:t.target.collectionId}:{}},l),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(","),...t.target?.kind==="collection"?{collection_id:t.target.collectionId}:{},code_challenge:r,code_challenge_method:"S256",application_authorization:JSON.stringify(y)})}),_=await h.json()}catch(P){throw i?.close(),await this.keyStore.delete(a),c("device_authorization_failed","Downloaded application authorization could not be started.",{cause:P})}if(!h.ok)throw i?.close(),await this.keyStore.delete(a),R(_,"device_authorization_failed","Downloaded application authorization could not be started.",h.status);let f;try{f=xn(_)}catch(P){throw i?.close(),await this.keyStore.delete(a),t.signal?.aborted?c("authorization_cancelled","Downloaded application authorization was cancelled.",{cause:P}):P}if(t.onDeviceCode?.(f),t.openVerification)await t.openVerification(f);else if(i)try{i.location.href=f.verificationUriComplete}catch{}else throw await this.keyStore.delete(a),c("approval_window_blocked","The approval window was blocked. Show the provided verification link and code, then try again.",{details:{user_code:f.userCode,verification_uri:f.verificationUri,verification_uri_complete:f.verificationUriComplete,expires_at:f.expiresAt,interval_seconds:f.intervalSeconds}});let v=f.intervalSeconds,m="";try{for(;Date.now()<f.expiresAt;){if(await he(v*1e3,t.signal),t.signal?.aborted)throw c("authorization_cancelled","Downloaded application authorization was cancelled.");let P;try{P=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:t.signal})}catch(F){if(t.signal?.aborted)throw c("authorization_cancelled","Downloaded application authorization was cancelled.",{cause:F});continue}let g=await P.json();if(!P.ok){let F=ge(g);if(F==="authorization_pending"){g.first_contact&&(m=await Nt(g.first_contact,e,l,t,m));continue}if(F==="slow_down"){v+=5;continue}throw R(g,"token_exchange_failed","Downloaded application authorization could not be completed.",P.status)}let k=Ze(g.authority,g.collection_id),x=g.encryption&&g.encryption.protocol_version===se&&g.encryption.suite===ke&&g.encryption.application_agreement_public_key===s.agreementPublicKey;if(g.application_origin!=="null")throw c("invalid_token_response","Authorization did not bind the portable grant to its opaque application origin.");if(g.authority&&(!k||g.encryption!=null||g.authority.proof_public_key!==s.signingPublicKey))throw c("invalid_token_response","Authorization returned a remote authority capability that is not bound to this portable grant key.");if(!g.authority&&!x)throw c("encryption_required","Authorization did not establish the expected key-bound local portable grant.");let w=this.storeTokenResponse(g,e.id,a);if(t.target?.kind==="collection"&&t.target.collectionId!==w.collectionId)throw this.removeToken(w.collectionId,w.keyHandle),c("collection_mismatch","The approved collection does not match the collection requested by this link.");return i?.close(),{kind:"connected",connection:this.connection(w.collectionId),...t.returnTo?{returnTo:t.returnTo}:{}}}throw c("expired_token","The downloaded application authorization code expired.")}catch(P){throw i?.close(),await this.keyStore.delete(a),t.signal?.aborted?c("authorization_cancelled","Downloaded application authorization was cancelled.",{cause:P}):P}}completeAuthorization(e){let t=new URL(e).searchParams.get("state");if(!t)return Promise.reject(c("invalid_callback","Authorization callback is missing its state."));let i=this.completionPromises.get(t);if(i)return i;let r=this.performAuthorizationCompletion(e,t).finally(()=>{this.completionPromises.get(t)===r&&this.completionPromises.delete(t)});return this.completionPromises.set(t,r),r}async performAuthorizationCompletion(e,t){let i=new URL(e),o=i.searchParams.get("code"),r=this.pendingKey(t),a=M(this.storage.getItem(r));if(!a||a.version!==1||t!==a.state)throw c("invalid_callback","Authorization callback is missing or does not match this browser session.");if(i.searchParams.has("error"))throw a.keyHandle&&await this.keyStore.delete(a.keyHandle),this.storage.removeItem(r),D(i.searchParams.get("error")??"access_denied",i.searchParams.get("error_description")??"Collection access was not approved.",{details:a.returnTo?{return_to:a.returnTo}:void 0});if(!o)throw c("invalid_callback","Authorization callback is missing its code.");let s=await $(`${this.serverUrl}/oauth/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:o,client_id:a.clientId,redirect_uri:a.redirectUri,code_verifier:a.verifier})},"temporarily_unavailable","Authorization completion is temporarily unavailable."),l=await s.json();if(!s.ok)throw R(l,"token_exchange_failed","Authorization could not be completed.",s.status);if(a.relayEncryption==="required"&&!l.authority&&(!l.encryption||!a.keyHandle||l.encryption.application_agreement_public_key!==a.applicationAgreementPublicKey))throw a.keyHandle&&await this.keyStore.delete(a.keyHandle),this.storage.removeItem(r),c("encryption_required","Authorization did not establish the required encrypted relay grant.");if(l.authority?.proof_public_key){if(!a.keyHandle||!a.applicationSigningPublicKey||l.authority.proof_public_key!==a.applicationSigningPublicKey)throw a.keyHandle&&await this.keyStore.delete(a.keyHandle),this.storage.removeItem(r),c("invalid_token_response","Authorization returned a remote authority capability bound to another application key.")}else l.authority&&a.keyHandle&&await this.keyStore.delete(a.keyHandle);let d=this.storeTokenResponse(l,a.clientId,l.authority?.proof_public_key?a.keyHandle:l.authority?void 0:a.keyHandle);if(a.collectionId&&a.collectionId!==d.collectionId)throw this.removeToken(d.collectionId,d.keyHandle),this.storage.removeItem(r),c("collection_mismatch","The approved collection does not match the collection requested by this link.");return this.storage.removeItem(r),{connection:this.connection(d.collectionId),...a.returnTo?{returnTo:a.returnTo}:{}}}connections(){let e=[];for(let t of this.connectionIds()){let i=this.connection(t)?.info();i&&e.push(i)}return e.sort((t,i)=>t.displayName.localeCompare(i.displayName)||t.collectionId.localeCompare(i.collectionId))}connection(e){if(!this.storage.getItem(this.tokenKey(e)))return null;let t=this.connectionCache.get(e);return t||(t=new De(this,e),this.connectionCache.set(e,t)),t.info()?t:null}unavailableReason(e){return this.invalidatedConnections.get(e)??null}onConnectionsChange(e){return this.listeners.add(e),e(this.connections()),()=>this.listeners.delete(e)}storeTokenResponse(e,t,i){let o=e.collection_id;if(typeof o!="string")throw c("invalid_token_response","Authorization returned no collection ID.");let r=tt(e.scope);if(!r)throw c("invalid_token_response","Authorization returned no valid collection scope.");if(e.authority&&!Ze(e.authority,o))throw c("invalid_token_response","Authorization returned an invalid remote authority capability.");if(e.authority&&e.encryption)throw c("invalid_token_response","Authorization returned conflicting collection transports.");if(e.file_capability!==null&&e.file_capability!==void 0&&!et(e.file_capability))throw c("invalid_token_response","Authorization returned an invalid file capability.");if(e.encryption){try{W(e.encryption)}catch{throw c("invalid_token_response","Authorization returned an invalid encrypted relay binding.")}if(e.encryption.collection_id!==o||typeof e.grant_id!="string"||e.grant_id.length===0)throw c("invalid_token_response","Authorization returned an encrypted relay binding for another grant.")}let a=M(this.storage.getItem(this.tokenKey(o)));if(a?.encryption&&e.encryption&&a.keyHandle&&a.keyHandle===i&&(a.grantId!==e.grant_id||a.encryption.connector_id!==e.encryption.connector_id||a.encryption.connector_agreement_public_key!==e.encryption.connector_agreement_public_key||a.encryption.application_agreement_public_key!==e.encryption.application_agreement_public_key))throw c("connector_identity_changed","The connector identity changed during authorization renewal. Reauthorize before sending collection data.");a?.keyHandle&&a.keyHandle!==i&&this.keyStore.delete(a.keyHandle).catch(()=>{});let s={version:1,accessToken:e.access_token,refreshToken:e.refresh_token,clientId:t,collectionId:o,collectionName:e.collection_name??`Collection ${o.slice(0,8)}`,operations:e.operations,scope:r,expiresAt:Date.now()+e.expires_in*1e3,refreshExpiresAt:e.refresh_expires_in?Date.now()+e.refresh_expires_in*1e3:void 0,grantId:e.grant_id,encryption:e.encryption??void 0,fileCapability:e.file_capability??void 0,applicationOrigin:e.application_origin??this.defaultApplicationOrigin(),keyHandle:i,savedAt:Date.now(),authority:e.authority?{operationsUrl:e.authority.operations_url,syncUrl:e.authority.sync_url,filesUrl:e.authority.files_url,replicaId:e.authority.replica_id,accessToken:e.authority.access_token,proofPublicKey:e.authority.proof_public_key}:void 0};return this.storage.setItem(this.tokenKey(o),JSON.stringify(s)),this.addConnectionId(o),this.invalidatedConnections.delete(o),this.connectionCache.delete(o),this.emitConnections(),s}removeToken(e,t,i="authorization_lost"){this.invalidatedConnections.set(e,i),t&&this.keyStore.delete(t).catch(()=>{}),this.storage.removeItem(this.tokenKey(e)),this.storage.removeItem(this.pendingMutationKey(e));for(let o of["web_push","fcm"])this.storage.removeItem(this.notificationKey(e,o));this.storage.setItem(this.connectionsKey(),JSON.stringify({version:1,collectionIds:this.connectionIds().filter(o=>o!==e)})),this.connectionCache.delete(e),this.emitConnections()}tokenKey(e){return`${this.storagePrefix()}:token:${e}`}pendingMutationKey(e){return`${this.storagePrefix()}:pending-mutation:${e}`}notificationKey(e,t="web_push"){return`${this.storagePrefix()}:notifications:${e}:${t}`}directPreferenceKey(){return`mdbase-connect:direct:${this.defaultApplicationOrigin()}`}defaultApplicationOrigin(){if(typeof this.manifest!="string"&&this.manifest.distribution==="portable"||this.application?.distribution==="portable")return"null";let e=new URL(this.redirectUri);if(["http:","https:"].includes(e.protocol))return e.origin;if(typeof location<"u")return location.origin;if(this.manifest&&typeof this.manifest!="string")return new URL(this.manifest.homepage).origin;try{return new URL(this.manifestSource).origin}catch{return""}}pendingKey(e){return`${this.storagePrefix()}:pending:${e}`}storagePrefix(){return`mdbase-connect:${this.serverUrl}:${this.manifestSource}`}connectionsKey(){return`${this.storagePrefix()}:connections`}connectionIds(){let e=M(this.storage.getItem(this.connectionsKey()));return e?.version===1&&Array.isArray(e.collectionIds)&&e.collectionIds.every(t=>typeof t=="string")?e.collectionIds:[]}addConnectionId(e){this.storage.setItem(this.connectionsKey(),JSON.stringify({version:1,collectionIds:[...new Set([...this.connectionIds(),e])]}))}emitConnections(){let e=this.connections();for(let t of this.listeners)t(e)}};function Eo(n){let e=":token:",t=n.lastIndexOf(e);return t<0?"":n.slice(t+e.length)}function Le(n){for(let e of["code","state","error","error_description"])n.searchParams.delete(e);return n}function dt(n){let e;try{e=new URL(n)}catch{return!1}return e.searchParams.has("state")&&(e.searchParams.has("code")||e.searchParams.has("error"))}function ei(n){if(!n.details||typeof n.details!="object"||Array.isArray(n.details))return;let e=n.details.return_to;return typeof e=="string"?e:void 0}var Ne=class{constructor(e,t){this.connect=e;this.operations=B(t.operations??oe),this.selection=t.selection,this.autoSelect=t.autoSelect??"only",this.snapshot={status:"unselected",connections:[]},this.refresh()}connect;operations;selection;autoSelect;listeners=new Set;snapshot;snapshotKey="";stopConnections;stopSelection;stopActiveConnection;activeCollectionId=null;unavailableReason="not_authorized";started=!1;refreshing=!1;refreshQueued=!1;transactionDepth=0;callbackPromise=null;async start(){this.started||(this.started=!0,this.stopConnections=this.connect.onConnectionsChange(()=>this.refresh()),this.stopSelection=this.selection.subscribe(()=>{this.unavailableReason="not_authorized",this.refresh()}));let e=this.selection.authorizationCallback();if(e){let t=await this.handleAuthorizationCallback(e);if(!t.ok)return t}else this.autoSelectOnlyConnection();return this.refresh(),E(this.snapshot)}destroy(){this.stopConnections?.(),this.stopSelection?.(),this.stopActiveConnection?.(),this.stopConnections=void 0,this.stopSelection=void 0,this.stopActiveConnection=void 0,this.activeCollectionId=null,this.started=!1}getSnapshot(){return this.snapshot}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}select(e,t={}){let i=this.connect.connection(e);return i?(this.unavailableReason="not_authorized",this.selection.select(e,t),this.refresh(),E(i)):T(z("unknown_collection","This collection is not authorized for this application."))}clearSelection(e={}){this.unavailableReason="not_authorized",this.selection.select(null,e),this.refresh()}forget(e){this.transactionDepth+=1;try{let t=this.selection.selectedCollectionId()===e;this.connect.connection(e)?.forget(),t&&this.selection.select(null,{history:"replace"})}finally{this.transactionDepth-=1,this.refresh()}}async authorize(e,t={}){let i=this.selection.selectedCollectionId();if(e==="selected"&&!i)return T(z("collection_not_selected","Choose a collection before updating its access."));let o=typeof e=="object"?e.collectionId:e==="selected"?i:null;this.transactionDepth+=1;try{let r=await this.connect.authorize({...t,operations:this.operations,target:o===null?{kind:"choose"}:{kind:"collection",collectionId:o},returnTo:this.selection.authorizationReturnTo()});return r.ok&&r.value.kind==="connected"&&this.selection.finishAuthorization(r.value.returnTo,r.value.connection.collectionId),r}finally{this.transactionDepth-=1,this.refresh()}}async ensureOperations(e){let t=this.snapshot;if(t.status!=="ready")return T(z("collection_not_ready","Choose an authorized collection first."));let i=B(e),o=t.connection.authorizationCapabilities(i);if(o.sufficient)return E({kind:"unchanged",connection:t.connection});this.transactionDepth+=1;try{let r=await this.connect.authorize({operations:B([...o.grantedOperations,...o.missingOperations]),target:{kind:"collection",collectionId:t.collectionId},returnTo:this.selection.authorizationReturnTo()});return r.ok&&r.value.kind==="connected"&&this.selection.finishAuthorization(r.value.returnTo,r.value.connection.collectionId),r}finally{this.transactionDepth-=1,this.refresh()}}handleAuthorizationCallback(e){if(!dt(e))return Promise.resolve(T(z("invalid_callback","This URL is not an authorization callback.")));if(this.callbackPromise)return this.callbackPromise;this.transactionDepth+=1;let t=this.connect.completeAuthorization(e).then(i=>{if(!i.ok){let r=ei(i.problem);return this.selection.clearAuthorizationCallback(r),this.refresh(),i}let o=i.value;return this.unavailableReason="not_authorized",this.selection.finishAuthorization(o.returnTo,o.connection.collectionId),this.refresh(),E(o.connection,i.diagnostics)}).catch(i=>{throw this.selection.clearAuthorizationCallback(),this.refresh(),i}).finally(()=>{this.transactionDepth-=1,this.refresh(),this.callbackPromise===t&&(this.callbackPromise=null)});return this.callbackPromise=t,t}autoSelectOnlyConnection(){if(this.autoSelect!=="only"||this.selection.selectedCollectionId())return;let e=this.connect.connections();e.length===1&&this.selection.select(e[0].collectionId,{history:"replace"})}refresh(){if(this.transactionDepth>0){this.refreshQueued=!0;return}if(this.refreshing){this.refreshQueued=!0;return}this.refreshing=!0;try{do this.refreshQueued=!1,this.refreshOnce();while(this.refreshQueued)}finally{this.refreshing=!1}}refreshOnce(){let e=this.selection.selectedCollectionId(),t=this.connect.connections(),i=e?this.connect.connection(e):null;i?.collectionId!==this.activeCollectionId&&(this.stopActiveConnection?.(),this.activeCollectionId=i?.collectionId??null,this.stopActiveConnection=i?.onConnectionChange(a=>{!a&&this.selection.selectedCollectionId()===i.collectionId&&(this.unavailableReason="authorization_lost"),this.refresh()}));let o;if(!e)o={status:"unselected",connections:t};else if(!i||!i.info())o={status:"unavailable",collectionId:e,reason:this.connect.unavailableReason(e)??this.unavailableReason,connections:t};else{let a=i.info();o={status:"ready",collectionId:e,connection:i,info:a,access:i.authorizationCapabilities(this.operations),connections:t}}let r=xo(o);if(r!==this.snapshotKey){this.snapshot=o,this.snapshotKey=r;for(let a of this.listeners)a()}}};function xo(n){return n.status==="unselected"?JSON.stringify({status:n.status,connections:n.connections}):n.status==="unavailable"?JSON.stringify({status:n.status,collectionId:n.collectionId,reason:n.reason,connections:n.connections}):JSON.stringify({status:n.status,collectionId:n.collectionId,info:n.info,access:n.access,connections:n.connections})}var Bt=class{internals;constructor(e){this.internals=new lt(e)}register(){return A(()=>this.internals.register(),Z)}authorize(e={}){return A(()=>this.internals.authorize(e),ee)}createSession(e){return new Ne(this,e)}environment(){return this.internals.environment()}completeAuthorization(e){return A(()=>this.internals.completeAuthorization(e??Fn()),ee)}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()}};function ti(n){if(!n||typeof n!="object")throw c("invalid_push_payload","The push payload is not an object.");let e=n;if(e.type!=="mdbase.notification"||e.version!==1||typeof e.signal_id!="string"||typeof e.criterion_id!="string"||typeof e.cursor!="string"||!e.presentation||typeof e.presentation.title!="string")throw c("invalid_push_payload","The push payload is not an mdbase notification.");return e}function Mo(n){if(!n||typeof n!="object")throw c("invalid_push_payload","The native notification data is not an object.");let e=n;if(e.type!=="mdbase.notification"||e.version!==1&&e.version!=="1"||typeof e.signal_id!="string"||typeof e.criterion_id!="string"||typeof e.cursor!="string")throw c("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 Uo(n,e){let t=ti(e);return n.showNotification(t.presentation.title,{...t.presentation.body?{body:t.presentation.body}:{},...t.presentation.tag?{tag:t.presentation.tag}:{},data:{type:t.type,signal_id:t.signal_id,criterion_id:t.criterion_id,cursor:t.cursor}})}var Kt=class{collectionParameter;fallbackPath;listeners=new Set;handlePopState=()=>this.emit();constructor(e={}){this.collectionParameter=e.collectionParameter??"collection",this.fallbackPath=e.fallbackPath??"/"}selectedCollectionId(){return this.currentUrl().searchParams.get(this.collectionParameter)}select(e,t={}){let i=Le(this.currentUrl());e?i.searchParams.set(this.collectionParameter,e):i.searchParams.delete(this.collectionParameter);let o=this.browserHistory();o[t.history==="push"?"pushState":"replaceState"](o.state,"",i),this.emit()}authorizationReturnTo(){let e=Le(this.currentUrl());return`${e.pathname}${e.search}${e.hash}`}authorizationCallback(){let e=this.currentUrl().href;return dt(e)?e:null}finishAuthorization(e,t){let i=this.safeAppUrl(e??this.fallbackPath);Le(i),i.searchParams.set(this.collectionParameter,t),this.browserHistory().replaceState(null,"",i),this.emit()}clearAuthorizationCallback(e){let t=e?this.safeAppUrl(e):this.currentUrl(),i=this.browserHistory();i.replaceState(i.state,"",Le(t)),this.emit()}subscribe(e){let t=this.listeners.size===0;return this.listeners.add(e),t&&typeof window<"u"&&window.addEventListener("popstate",this.handlePopState),()=>{this.listeners.delete(e),this.listeners.size===0&&typeof window<"u"&&window.removeEventListener("popstate",this.handlePopState)}}emit(){for(let e of this.listeners)e()}safeAppUrl(e){let t=this.currentUrl(),i=new URL(e,t.origin);return i.origin===t.origin?i:new URL(this.fallbackPath,t.origin)}currentUrl(){if(typeof location>"u")throw c("browser_required","Browser selection requires a browser environment.");return new URL(location.href)}browserHistory(){if(typeof history>"u")throw c("browser_required","Browser selection requires a browser environment.");return history}},jt=class{collectionId=null;listeners=new Set;selectedCollectionId(){return this.collectionId}select(e){if(e!==this.collectionId){this.collectionId=e;for(let t of this.listeners)t()}}authorizationReturnTo(){}authorizationCallback(){return null}finishAuthorization(e,t){this.select(t)}clearAuthorizationCallback(){}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}};return ci(zo);})();
3
+ `)}async function X(n,e,t,i,o,r=crypto.randomUUID()){W(t.encryption);let a=await ln(n,e,t.encryption.application_agreement_public_key),s=await n.nextCounter(e),l={binding:t,requestId:r,operation:i,counter:s},d=await dn(a.agreementPrivateKey,t,"request"),p=new TextEncoder().encode(JSON.stringify(o??{})),u=await crypto.subtle.encrypt({name:"AES-GCM",iv:hn(s),additionalData:new TextEncoder().encode(pn(l,"request")),tagLength:128},d,p);return{type:"encrypted_operation_request",...Ti(l),ciphertext:Oe(new Uint8Array(u))}}async function ue(n,e,t,i,o){if(!Ii(i,o))throw new C("invalid_encrypted_response","Encrypted response metadata does not match its request.");let r=await ln(n,e,t.encryption.application_agreement_public_key),a={binding:t,requestId:i.request_id,operation:i.operation,counter:i.counter},s=await dn(r.agreementPrivateKey,t,"response");try{let l=await crypto.subtle.decrypt({name:"AES-GCM",iv:hn(i.counter),additionalData:new TextEncoder().encode(pn(a,"response")),tagLength:128},s,yn(fn(o.ciphertext))),d=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(l));if(d?.ok===!0&&"result"in d||d?.ok===!1&&Ce(d.problem))return d;throw new Error("invalid response body")}catch(l){throw l instanceof C?l:new C("encrypted_response_rejected","The encrypted connector response could not be authenticated.")}}var C=class extends Error{constructor(t,i){super(i);this.code=t}code};async function cn(n){let e=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"]),t=Oe(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=Oe(new Uint8Array(await crypto.subtle.exportKey("raw",r.publicKey))),s=await crypto.subtle.exportKey("pkcs8",r.privateKey),l=await crypto.subtle.importKey("pkcs8",s,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]);return{handle:n,agreementPrivateKey:o,agreementPublicKey:t,signingPrivateKey:l,signingPublicKey:a}}async function ln(n,e,t){let i=await n.get(e);if(!i||i.agreementPublicKey!==t)throw new C("missing_grant_key","The encrypted grant key is unavailable or does not match the grant.");return i}async function Oi(n,e,t){let i=await n.get(e);if(!i||i.signingPublicKey!==t)throw new C("missing_grant_key","The remote authority signing key is unavailable or does not match the grant.");return i}async function dn(n,e,t){let i=await wt(n,e.encryption.connector_agreement_public_key),o=await crypto.subtle.importKey("raw",i,"HKDF",!1,["deriveKey"]),r=new TextEncoder().encode(un(e)),a=await crypto.subtle.digest("SHA-256",r);return crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:a,info:new TextEncoder().encode(t==="request"?ki:Ri)},o,{name:"AES-GCM",length:256},!1,t==="request"?["encrypt"]:["decrypt"])}async function wt(n,e){try{let t=await crypto.subtle.importKey("raw",yn(bt(e)),{name:"ECDH",namedCurve:"P-256"},!1,[]);return await crypto.subtle.deriveBits({name:"ECDH",public:t},n,256)}catch{throw new C("invalid_public_key","The connector relay public key is invalid.")}}function un(n){let e=n.encryption;return["mdbase-connect",ce,e.suite,n.grantId,n.applicationId,e.connector_id,e.collection_id,e.scope_epoch,e.key_id].join("|")}function pn(n,e){return[un(n.binding),n.requestId,e,n.operation,n.counter].join("|")}function Ti(n){let e=n.binding.encryption;return{protocol_version:ce,suite:Re,request_id:n.requestId,grant_id:n.binding.grantId,application_id:n.binding.applicationId,connector_id:e.connector_id,collection_id:e.collection_id,operation:n.operation,scope_epoch:e.scope_epoch,key_id:e.key_id,counter:n.counter}}function Ii(n,e){return e.type==="encrypted_operation_response"&&typeof e.ciphertext=="string"&&n.protocol_version===e.protocol_version&&n.suite===e.suite&&n.request_id===e.request_id&&n.grant_id===e.grant_id&&n.application_id===e.application_id&&n.connector_id===e.connector_id&&n.collection_id===e.collection_id&&n.operation===e.operation&&n.scope_epoch===e.scope_epoch&&n.key_id===e.key_id&&n.counter===e.counter}function W(n){if(n.protocol_version!==ce||n.suite!==Re||!Number.isSafeInteger(n.scope_epoch)||n.scope_epoch<=0||typeof n.key_id!="string"||n.key_id.length===0||n.key_id.length>200||n.key_id.includes("|"))throw new C("unsupported_encryption","The grant uses an unsupported relay encryption profile.");if(typeof n.connector_id!="string"||!on.test(n.connector_id)||typeof n.collection_id!="string"||!on.test(n.collection_id))throw new C("unsupported_encryption","The grant uses invalid encrypted relay identities.");bt(n.application_agreement_public_key),bt(n.connector_agreement_public_key)}function hn(n){let e=BigInt(n);if(e<=0n||e>vt||e.toString()!==n)throw new C("invalid_counter","The encrypted relay counter is invalid.");let t=new Uint8Array(new ArrayBuffer(12));return new DataView(t.buffer).setBigUint64(4,e,!1),t}function Oe(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}async function rn(n){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n));return Oe(new Uint8Array(e))}function fn(n){if(!/^[A-Za-z0-9_-]+$/.test(n))throw new C("invalid_base64","Encrypted relay data is malformed.");let e="=".repeat((4-n.length%4)%4),t=atob(n.replaceAll("-","+").replaceAll("_","/")+e);return Uint8Array.from(t,i=>i.charCodeAt(0))}function bt(n){let e=fn(n);if(e.length!==65||e[0]!==4)throw new C("invalid_public_key","Encrypted relay public keys must be uncompressed P-256 points.");return e}function yn(n){return Uint8Array.from(n).buffer}function Ei(n){return new Promise((e,t)=>{n.onerror=()=>t(n.error),n.onsuccess=()=>e(n.result)})}function an(n,e){return new Promise((t,i)=>{let o=n.transaction(G,"readwrite"),r=e(o.objectStore(G));r.onerror=()=>i(r.error),o.onerror=()=>i(o.error),o.onabort=()=>i(o.error??new Error("Grant key transaction aborted.")),o.oncomplete=()=>t()})}var xi="mdbase-connect file chunk key v1",Ve=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,H=class extends Error{constructor(t,i){super(i);this.code=t;this.name="FileTransferCryptoError"}code},pe=class n{constructor(e,t){this.binding=e;this.key=t}binding;key;static async open(e,t,i){mn(i);let o=await e.get(t);if(!o||o.agreementPublicKey!==i.encryption.application_agreement_public_key)throw new C("missing_grant_key","The encrypted grant key is unavailable or does not match the file transfer grant.");let r=await wt(o.agreementPrivateKey,i.encryption.connector_agreement_public_key);return n.fromSharedSecret(r,i)}static async fromSharedSecret(e,t){mn(t);let i=await Mi(e,t);return new n(t,i)}async encryptChunk(e,t,i){if(this.validateHeader(t),i.byteLength!==t.plaintext_length)throw new H("plaintext_length_mismatch","File chunk plaintext length does not match its authenticated header.");let o=Ke(e,t),r=await crypto.subtle.encrypt({name:"AES-GCM",iv:_n(t.chunk_index),additionalData:Ge(o),tagLength:128},this.key,Ge(i));return Qt({kind:e,header:t,payload:new Uint8Array(r)})}async decryptChunk(e){let t=je(e);this.validateHeader(t.header);let i=Ke(t.kind,t.header);try{let o=await crypto.subtle.decrypt({name:"AES-GCM",iv:_n(t.header.chunk_index),additionalData:Ge(i),tagLength:128},this.key,Ge(t.payload));return new Uint8Array(o)}catch{throw new H("authentication_failed","The encrypted file chunk could not be authenticated.")}}validateHeader(e){let t=this.binding.encryption;if(e.protocol_version!==1||e.protection!=="grant_aead_v1"||e.grant_id!==this.binding.grantId||e.authority_id!==this.binding.authorityId||e.collection_id!==t.collection_id||e.transfer_id!==this.binding.transferId||e.direction!==this.binding.direction||e.scope_epoch!==t.scope_epoch||e.key_id!==t.key_id)throw new H("header_binding_mismatch","The file frame does not match its transfer encryption binding.")}};async function Mi(n,e){let t=new TextEncoder().encode(Ui(e)),i=await crypto.subtle.digest("SHA-256",t),o=await crypto.subtle.importKey("raw",n,"HKDF",!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:i,info:new TextEncoder().encode(xi)},o,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}function mn(n){if(W(n.encryption),!Ve.test(n.grantId)||!Ve.test(n.applicationId)||!Ve.test(n.authorityId)||!Ve.test(n.transferId)||n.direction!=="upload"&&n.direction!=="download")throw new H("invalid_binding","The file transfer encryption binding is invalid.")}function Ui(n){let e=n.encryption;return["mdbase-connect","file-transfer",1,e.suite,n.grantId,n.applicationId,e.connector_id,n.authorityId,e.collection_id,e.scope_epoch,e.key_id,n.transferId,n.direction].join("|")}function _n(n){if(!Number.isSafeInteger(n)||n<0)throw new H("invalid_chunk_index","The file chunk index is invalid.");let e=new Uint8Array(new ArrayBuffer(12));return new DataView(e.buffer).setBigUint64(4,BigInt(n),!1),e}function Ge(n){return Uint8Array.from(n).buffer}var zi=new TextEncoder().encode("mdbase-connect first-contact transcript\0"),Fi=new TextEncoder().encode("mdbase-connect first-contact sas v1"),Di="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Li=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,U=class extends Error{constructor(t,i){super(i);this.code=t}code};async function Je(n,e,t){let i=await Ni(n),o=e==="application"?n.application_agreement_public_key:n.connector_agreement_public_key,r=e==="application"?i.connector:i.applicationAgreement;if(t.agreementPublicKey!==o)throw new U("identity_mismatch","The first-contact identity does not match the transcript.");let a;try{a=await crypto.subtle.importKey("raw",r,{name:"ECDH",namedCurve:"P-256"},!1,[])}catch{throw new U("invalid_public_key","The first-contact public key is invalid.")}let s=await crypto.subtle.deriveBits({name:"ECDH",public:a},t.agreementPrivateKey,256),l=qi(n,i),d=await crypto.subtle.digest("SHA-256",l),p=await crypto.subtle.importKey("raw",s,"HKDF",!1,["deriveBits"]),u=new Uint8Array(await crypto.subtle.deriveBits({name:"HKDF",hash:"SHA-256",salt:d,info:Fi},p,40));return Ki(u)}async function Ni(n){if(n.protocol_version!==ke)throw new U("unsupported_version","The first-contact protocol version is not supported.");let e=Pt(n.application_agreement_public_key),t=Pt(n.application_signing_public_key),i=Pt(n.connector_agreement_public_key);if(St(e,t)||St(e,i)||St(t,i))throw new U("invalid_public_key","First contact requires distinct endpoint agreement and signing keys.");try{await Promise.all([e,t,i].map(o=>crypto.subtle.importKey("raw",o,{name:"ECDH",namedCurve:"P-256"},!1,[])))}catch{throw new U("invalid_public_key","The first-contact public key is invalid.")}return{applicationAgreement:e,applicationSigning:t,connector:i}}function qi(n,e){let t=[zi,gn(n.protocol_version),he(Ct(n.application_id)),he(Ct(n.application_installation_id)),he(e.applicationAgreement),he(e.applicationSigning),he(Ct(n.connector_id)),he(e.connector)],i=t.reduce((a,s)=>a+s.byteLength,0),o=new Uint8Array(i),r=0;for(let a of t)o.set(a,r),r+=a.byteLength;return o}function he(n){let e=new Uint8Array(4+n.byteLength);return e.set(gn(n.byteLength)),e.set(n,4),e}function gn(n){let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,n,!1),e}function Ct(n){if(!Li.test(n))throw new U("invalid_binding","The first-contact transcript contains an invalid identifier.");let e=n.replaceAll("-","");return Uint8Array.from({length:16},(t,i)=>Number.parseInt(e.slice(i*2,i*2+2),16))}function Pt(n){if(!/^[A-Za-z0-9_-]+$/.test(n))throw new U("invalid_public_key","The first-contact public key is invalid.");let e=n.replaceAll("-","+").replaceAll("_","/"),t=e.padEnd(Math.ceil(e.length/4)*4,"="),i;try{i=Uint8Array.from(atob(t),o=>o.charCodeAt(0))}catch{throw new U("invalid_public_key","The first-contact public key is invalid.")}if(i.byteLength!==65||i[0]!==4||Bi(i)!==n)throw new U("invalid_public_key","The first-contact public key is invalid.");return i}function Bi(n){return btoa(String.fromCharCode(...n)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}function St(n,e){return n.byteLength===e.byteLength&&n.every((t,i)=>t===e[i])}function Ki(n){let e=0n;for(let i of n)e=e<<8n|BigInt(i);let t="";for(let i=7;i>=0;i-=1)t+=Di[Number(e>>BigInt(i*5)&31n)],i===4&&(t+="-");return t}var kt=BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),ji=kt/2n;async function Y(n){return Wt(n.agreementPublicKey,n.signingPublicKey)}async function Te(n,e){if(n.installation_agreement_public_key!==e.agreementPublicKey||n.installation_signing_public_key!==e.signingPublicKey||n.application_installation_id!==await Y(e))throw new Error("Application authorization identity does not match its binding.");let t=Vi(new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},e.signingPrivateKey,$e(n))));return{binding:n,signature:$i(t)}}function Hi(n){let e=new Uint8Array(n.reduce((i,o)=>i+o.byteLength,0)),t=0;for(let i of n)e.set(i,t),t+=i.byteLength;return e}function $i(n){return btoa(String.fromCharCode(...n)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}function Vi(n){if(n.byteLength!==64)throw new Error("Application authorization signature is invalid.");let e=Gi(n.slice(32));if(e===0n||e>=kt)throw new Error("Application authorization signature is invalid.");return e<=ji?n:Hi([n.slice(0,32),Yi(kt-e,32)])}function Gi(n){return BigInt(`0x${Ji(n)}`)}function Yi(n,e){let t=n.toString(16).padStart(e*2,"0");return Uint8Array.from({length:e},(i,o)=>Number.parseInt(t.slice(o*2,o*2+2),16))}function Ji(n){return[...n].map(e=>e.toString(16).padStart(2,"0")).join("")}function fe(n,e){return new Promise((t,i)=>{if(e?.aborted){i(e.reason??new DOMException("Aborted","AbortError"));return}let o=setTimeout(t,n);e?.addEventListener("abort",()=>{clearTimeout(o),i(e.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}var S=class extends Error{constructor(t,i={}){super(t.message,i.cause===void 0?void 0:{cause:i.cause});this.problem=t;this.name="MdbaseConnectError",this.code=t.code,this.status=i.status}problem;code;status;get retryable(){return this.problem.recovery==="retry"&&this.problem.operation_outcome!=="unknown"}get requiresAuthorization(){return this.problem.category==="authorization"}get outcomeUnknown(){return this.problem.operation_outcome==="unknown"}get recovery(){return this.problem.recovery}get details(){return this.problem.details}};function z(n,e,...[t={}]){let i=J[n];return{problem_version:1,code:n,category:i.category,recovery:i.recovery,message:e,...t.details===void 0?{}:{details:t.details},...t.operationOutcome===void 0?{}:{operation_outcome:t.operationOutcome},...t.traceId===void 0?{}:{trace_id:t.traceId}}}function Rt(n,e,t={}){return ft(n,e,{details:t.details,operation_outcome:t.operationOutcome,trace_id:t.traceId})}function c(n,e,...t){let i=t[0];return new S(z(n,e,...t),{status:i?.status,cause:i?.cause})}function D(n,e,t={}){let{status:i,cause:o,...r}=t;return new S(ft(n,e,{details:r.details,operation_outcome:r.operationOutcome,trace_id:r.traceId}),{status:i,cause:o})}function At(n){let e=Xi(n.diagnostics),t=to(n.diagnostics);if(e==="collection_version_unsupported"){let i=Wi(n.diagnostics);return z(e,t,{operationOutcome:"rejected",details:i})}return e!=="operation_invalid"?z(e,t,{operationOutcome:"rejected",details:{diagnostics:n.diagnostics}}):z(e,t,{operationOutcome:"rejected",details:{diagnostics:n.diagnostics,partial_result:n.result}})}function Xi(n){let e=new Set(n.filter(t=>t.severity==="error").map(t=>t.code));return["migration_required","migration_lossy","unsupported_version"].some(t=>e.has(t))?"collection_version_unsupported":["invalid_config","invalid_configuration","missing_config","missing_spec_version"].some(t=>e.has(t))?"collection_configuration_invalid":["duplicate_type","invalid_contract_definition","invalid_data_contract","invalid_type_definition","invalid_type_path"].some(t=>e.has(t))?"collection_type_registry_invalid":["collection_invalid","collection_open_failed"].some(t=>e.has(t))?"collection_invalid":"operation_invalid"}function Wi(n){let e=n.map(t=>t.details).find(t=>Zi(t));return{current_version:typeof e?.current_version=="string"?e.current_version:"0.2.x",required_version:typeof e?.required_version=="string"?e.required_version:"0.3.0"}}function Zi(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function eo(n){return n instanceof S&&n.retryable}function to(n){return n.filter(e=>e.severity==="error").map(e=>e.message).join(" ")||n.map(e=>e.message).join(" ")||"The collection rejected this operation."}var bn=["access_denied","access_paused","authorization_expired","collection_access_denied","connector_identity_changed","connector_offline","connector_upgrade_required","direct_operation_rejected","operation_outcome_unknown","encryption_required","encrypted_relay_rejected","hosted_provider_unavailable","insufficient_access","invalid_encrypted_response","invalid_operation_response","invalid_request","missing_grant_key","not_authorized","operation_cancelled","operation_failed","rate_limited","relay_authorization_expired","relay_unavailable","temporarily_unavailable","timeout","unsupported_operation"],Ot=Object.keys(J),Z=["discovery_failed","invalid_application_manifest","invalid_request","manifest_load_failed","rate_limited","temporarily_unavailable","timeout"],ee=[...Z,"access_denied","approval_window_blocked","authorization_cancelled","browser_required","collection_access_denied","collection_configuration_invalid","collection_contracts_missing","collection_incompatible","collection_invalid","collection_kind_unsupported","collection_mismatch","collection_not_found","collection_type_registry_invalid","collection_version_unsupported","connector_identity_changed","connector_offline","connector_upgrade_required","device_authorization_failed","encryption_required","expired_token","first_contact_handler_required","invalid_callback","invalid_device_authorization_response","invalid_first_contact","invalid_token_response","scope_denied","token_exchange_failed"],ye=[...Z,"authorization_expired","invalid_push_subscription","managed_fcm_not_declared","not_authorized","notification_criterion_not_declared","notification_reauthorization_required","notification_registration_failed","notification_unregistration_failed","notifications_not_declared","notifications_unavailable"],Xe=["connector_offline","connector_upgrade_required","invalid_operation_response","not_authorized","operation_failed","temporarily_unavailable","timeout"],no=[...ee,"collection_not_ready","collection_not_selected","unknown_collection"],vn=["collection_configuration_invalid","collection_invalid","collection_type_registry_invalid","collection_version_unsupported"],Ie=[...bn,...vn],q=[...Ie,"invalid_path","operation_invalid"],Tt=[...q,"query_snapshot_changed","sandbox_unsupported"],I=[...q,"concurrent_modification","invalid_preflight","pending_mutation_unresolved"],It=[...Ie,"change_cursor_reset"],te=[...I,"type_pack_provision_failed"];function E(n,e=[]){return{ok:!0,value:n,diagnostics:e}}function T(n){return{ok:!1,problem:n}}async function A(n,e){try{return E(await n())}catch(t){if(!(t instanceof S))throw t;let i=t.problem;return i.code==="unknown"||e.includes(i.code)?T(i):T(Rt(i.code,i.message,{details:i.details,operationOutcome:i.operation_outcome,traceId:i.trace_id}))}}var Qe=class extends Error{constructor(t){super(t.message);this.problem=t;this.name="ConnectOutcomeError"}problem};function io(n){if(!n.ok)throw new Qe(n.problem);return n.value}var Ee=class{constructor(e){this.transport=e}transport;operation(e,t,i){return A(()=>this.transport.operation(e,t,i),Ot)}describe(){return this.rawOperation("describe",{},Ie)}changes(e={},t){return this.rawOperation("changes",e,It,t)}read(e){return this.envelopeOperation("read",e,q)}query(e={},t){return this.envelopeOperation("query",e,Tt,t)}async*queryPages(e={},t={}){let{offset:i,limit:o,snapshot:r,...a}=e,s=ro(i,0),l=wn(t.firstPageSize??o,200),d=wn(t.pageSize??o,1e3),p=r,u=0,y=0;for(;!t.signal?.aborted;){let h=await this.query({...a,offset:s,limit:y===0?l:d,...p?{snapshot:p}:{}},{signal:t.signal});if(!h.ok){yield h;return}let _=h.value,f=_.meta?.snapshot;if(p&&f&&p!==f){yield T(z("query_snapshot_changed","The collection query snapshot changed while paging. Refresh the query before continuing."));return}!p&&f&&(p=f),u+=_.results.length;let v=!_.meta?.has_more||_.results.length===0,m={results:_.results,..._.meta?{meta:_.meta}:{},page:y,offset:s,loaded:u,complete:v,...p?{snapshot:p}:{}};if(t.onProgress?.(m),yield E(m,h.diagnostics),v)return;s+=_.results.length,y+=1}}async queryAll(e={},t={}){let i=[],o,r=[];for await(let a of this.queryPages(e,t)){if(!a.ok)return a;let s=a.value;i.push(...s.results),o=s,r.push(...a.diagnostics)}return E({results:i,meta:{...o?.meta??{},total_count:o?.meta?.total_count??i.length,has_more:o?!o.complete:!1,...o?.snapshot?{snapshot:o.snapshot}:{}}},r)}listViews(){return this.envelopeOperation("list_views",{},q)}executeView(e){return this.envelopeOperation("execute_view",e,q)}readViewSource(e){return this.envelopeOperation("read_view_source",e,q)}createViewSource(e){return this.envelopeOperation("create_view_source",e,I)}updateViewSource(e){return this.envelopeOperation("update_view_source",e,I)}deleteViewSource(e){return this.envelopeOperation("delete_view_source",e,I)}create(e){return this.envelopeOperation("create",e,I)}update(e){return this.envelopeOperation("update",e,I)}delete(e,t){return this.envelopeOperation("delete",e,I,t)}preflightDelete(e,t){return this.envelopeOperation("delete",{...e,check_backlinks:!0,dry_run:!0},I,t)}rename(e,t){return this.envelopeOperation("rename",e,I,t)}preflightRename(e,t){return this.envelopeOperation("rename",{...e,dry_run:!0},I,t)}validate(e={}){return this.envelopeOperation("validate",e,q)}readType(e){return this.envelopeOperation("read_type",e,te)}createType(e){return this.envelopeOperation("create_type",e,te)}updateType(e){return this.envelopeOperation("update_type",e,te)}assessTypePack(e){return this.envelopeOperation("assess_type_pack",e,te)}applyTypePack(e){return this.envelopeOperation("apply_type_pack",e,te)}listTimers(e){return this.rawOperation("list_timers",{namespace:e},q)}putTimer(e){return this.rawOperation("put_timer",e,I)}cancelTimer(e){return this.rawOperation("cancel_timer",e,I)}reconcileTimers(e){return this.rawOperation("reconcile_timers",e,I)}async*watch(e={}){let t=e.cursor,i=Math.max(100,e.pollIntervalMs??1e3),o=oo(e.retry),r=0,a=!1;for(e.onStatus?.({state:"connecting",...t===void 0?{}:{cursor:t}});!e.signal?.aborted;){let s=await this.changes(t===void 0?{}:{after:t,limit:200},{signal:e.signal});if(!s.ok){let p=s.problem;if(e.signal?.aborted)return;if(!o||p.recovery!=="retry"){yield s;return}if(a=!1,r+=1,o.maxAttempts!==void 0&&r>o.maxAttempts){yield s;return}let u=Math.min(o.maxDelayMs,Math.round(o.initialDelayMs*o.multiplier**(r-1)));e.onStatus?.({state:"reconnecting",...t===void 0?{}:{cursor:t},attempt:r,retryInMs:u,problem:p});try{await fe(u,e.signal)}catch{if(!e.signal?.aborted)throw c("operation_failed","Watch retry delay failed unexpectedly.")}continue}let l=s.value;if(t===void 0){t=l.cursor;continue}if(l.reset){let p=z("change_cursor_reset","The collection change cursor expired. Refresh collection state before subscribing again.");e.onStatus?.({state:"reset_required",cursor:t,problem:p}),yield T(p);return}let d=r>0;r=0,(!a||d)&&e.onStatus?.({state:"connected",cursor:t,recovered:d}),a=!0;for(let p of l.events)yield E(p);if(t=l.cursor,!l.has_more)try{await fe(i,e.signal)}catch{if(!e.signal?.aborted)throw c("operation_failed","Watch polling delay failed unexpectedly.")}}}rawOperation(e,t,i,o){return A(()=>this.transport.operation(e,t,o),i)}async envelopeOperation(e,t,i,o){let r=await A(()=>this.transport.operation(e,t,o),i);if(!r.ok)return r;let a=r.value;return a.valid?E(a.result,a.diagnostics):T(At(a))}};function oo(n){if(n!==!1)return{initialDelayMs:Math.max(0,n?.initialDelayMs??500),maxDelayMs:Math.max(0,n?.maxDelayMs??15e3),multiplier:Math.max(1,n?.multiplier??2),...n?.maxAttempts===void 0?{}:{maxAttempts:Math.max(0,n.maxAttempts)}}}function ro(n,e){return typeof n=="number"&&Number.isFinite(n)?Math.max(0,Math.floor(n)):e}function wn(n,e){return typeof n=="number"&&Number.isFinite(n)&&n>0?Math.floor(n):e}function N(n){let e=new Uint8Array(n);return crypto.getRandomValues(e),xe(e)}function xe(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function Cn(n){let e=n.replaceAll("-","+").replaceAll("_","/").padEnd(Math.ceil(n.length/4)*4,"="),t=atob(e),i=new Uint8Array(new ArrayBuffer(t.length));for(let o=0;o<t.length;o+=1)i[o]=t.charCodeAt(o);return i}function ne(n){return{...n,credentials:"omit",targetAddressSpace:"loopback"}}async function Me(){if(typeof navigator>"u"||!navigator.permissions?.query)return null;try{return(await navigator.permissions.query({name:"local-network-access"})).state}catch{return null}}function me(n){return n===404||n===405||n===426||n>=500}function We(n,e){return e&&typeof e=="object"&&!Array.isArray(e)&&e.dry_run===!0?!1:n==="sync"&&e!==null&&typeof e=="object"&&!Array.isArray(e)&&e.action==="mutate"||n==="create"||n==="update"||n==="delete"||n==="rename"||n==="create_type"||n==="update_type"||n==="apply_type_pack"||n==="put_timer"||n==="cancel_timer"||n==="reconcile_timers"}function B(n){return[...new Set(n)]}function Pn(n,e){return n.grantId||e.grantId?n.grantId===e.grantId&&n.keyHandle===e.keyHandle&&n.encryption?.key_id===e.encryption?.key_id:n.accessToken===e.accessToken}function ie(n){if(n?.aborted)throw c("operation_cancelled","The operation was cancelled before it changed the collection.",{operationOutcome:"not_sent",cause:n.reason})}function xt(n,e,t,i){return n instanceof S?n:e?.aborted?t?L(n):c("operation_cancelled","The operation was cancelled before it changed the collection.",{operationOutcome:"not_sent",cause:n}):t?L(n):n instanceof TypeError?c(i,i==="hosted_provider_unavailable"?"The hosted collection provider is unavailable.":"The Connect relay is unavailable.",{cause:n}):n instanceof Error?n:new Error(String(n))}function Mt(n,e){return e?.aborted===!0||n instanceof S&&n.code==="operation_cancelled"}function Sn(n,e){if(e.dry_run!==!0||e.would_rename!==!0||e.from!==n.from||e.to!==n.to)throw c("invalid_preflight","The rename preview does not match this mutation. Run the preview again.")}function kn(n,e){if(e.dry_run!==!0||e.would_delete!==!0||e.path!==n.path)throw c("invalid_preflight","The delete preview does not match this mutation. Run the preview again.")}function Rn(n,e){if(n.update_refs===!1)return{affectedRecords:0,totalUnits:1,warnings:0};let t=e.references_affected??[];return{affectedRecords:new Set(t.map(i=>i.path)).size,totalUnits:1+t.length,warnings:e.warnings?.length??0}}function An(n){return{affectedRecords:new Set((n.broken_links??[]).map(e=>e.path)).size,totalUnits:1,warnings:0}}async function On(n,e){let t=new TextEncoder().encode(`${n}\0${Ut(e??{})}`),i=await crypto.subtle.digest("SHA-256",t);return xe(new Uint8Array(i))}function Ut(n){return JSON.stringify(Et(n))}function Et(n){return Array.isArray(n)?n.map(e=>Et(e)):n&&typeof n=="object"?Object.fromEntries(Object.entries(n).filter(([,e])=>e!==void 0).sort(([e],[t])=>e<t?-1:e>t?1:0).map(([e,t])=>[e,Et(t)])):n}function L(n){return c("operation_outcome_unknown","The write may have completed, but mdbase could not recover its authoritative result. Retry the exact same write to recover safely.",{operationOutcome:"unknown",cause:n})}async function $(n,e,t,i){try{return await fetch(n,e)}catch(o){throw c(t,i,{cause:o})}}function Tn(n){let e=new URL(n);if(e.protocol!=="http:"||!["127.0.0.1","[::1]"].includes(e.hostname)||e.username||e.password||e.pathname!=="/"||e.search||e.hash)throw c("invalid_loopback_url","loopbackUrl must be an HTTP origin on 127.0.0.1 or ::1.");return e.origin}async function Ue(){let n=N(32),e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n));return{verifier:n,challenge:xe(new Uint8Array(e))}}function k(n,e,t,i){return D(ge(n)??n?.error?.code??e,n?.error_description??n?.error?.message??t,{status:i,details:n?.error?.details})}function ge(n){return typeof n?.error=="string"?n.error:void 0}function Ze(n,e){if(!n||typeof n!="object"||Array.isArray(n)||typeof e!="string")return!1;let t=n;if(typeof t.operations_url!="string"||typeof t.sync_url!="string"||typeof t.files_url!="string"||typeof t.replica_id!="string"||t.replica_id.length===0||typeof t.access_token!="string"||t.access_token.length===0||t.proof_public_key!==void 0&&(typeof t.proof_public_key!="string"||t.proof_public_key.length===0))return!1;try{let i=new URL(t.operations_url),o=new URL(t.sync_url),r=new URL(t.files_url);return[i,o,r].every(a=>(a.protocol==="https:"||a.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(a.hostname))&&!a.username&&!a.password&&!a.search&&!a.hash)&&/^\/v1\/authorities\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/operations$/i.test(i.pathname)&&/^\/v1\/authorities\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/sync$/i.test(o.pathname)&&/^\/v1\/authorities\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/files$/i.test(r.pathname)&&i.origin===o.origin&&i.origin===r.origin&&i.pathname.split("/")[3]===e&&o.pathname.split("/")[3]===e&&r.pathname.split("/")[3]===e}catch{return!1}}function In(n,e){return Ze({operations_url:n?.operationsUrl,sync_url:n?.syncUrl,files_url:n?.filesUrl,replica_id:n?.replicaId,access_token:n?.accessToken,proof_public_key:n?.proofPublicKey},e)}function et(n){if(!n||typeof n!="object"||Array.isArray(n))return!1;let e=n,t=e.actions;if(e.kind!=="files"||e.protocol_version!==1||!Array.isArray(t)||t.length===0||t.length>6||new Set(t).size!==t.length||t.some(o=>!["list","read","add","replace","move","delete"].includes(o)))return!1;let i=e.scope;return!i||typeof i!="object"||Array.isArray(i)?!1:i.kind==="collection"?Object.keys(i).length===1:i.kind==="selected_folders"&&Object.keys(i).length===2&&Array.isArray(i.folders)&&i.folders.length>0&&i.folders.length<=100&&new Set(i.folders).size===i.folders.length&&i.folders.every(o=>typeof o=="string"&&o.length>0&&o.length<=1024&&ao(o))}function ao(n){let e=new Set([".mdbase",".git","node_modules","_contracts","_schemas","_types","_views"]);return!n.startsWith("/")&&!n.endsWith("/")&&!n.includes("\\")&&n.split("/").every(t=>{let i=t.split(".")[0]?.toUpperCase()??"";return t!==""&&t!=="."&&t!==".."&&!t.startsWith(".")&&!t.endsWith(" ")&&!t.endsWith(".")&&!/[<>:"|?*]/.test(t)&&!e.has(t.toLowerCase())&&!["CON","PRN","AUX","NUL"].includes(i)&&!/^(COM|LPT)[1-9]$/.test(i)})}function En(n,e){if(!n||typeof n!="object"||Array.isArray(n)||n.collection_id!==e)return!1;try{return W(n),!0}catch{return!1}}function xn(n){if(typeof n?.device_code!="string"||typeof n?.user_code!="string"||typeof n?.verification_uri!="string"||typeof n?.verification_uri_complete!="string"||!Number.isFinite(n?.expires_in)||!Number.isFinite(n?.interval))throw c("invalid_device_authorization_response","Connect returned an invalid downloaded application authorization response.");return{userCode:n.user_code,verificationUri:n.verification_uri,verificationUriComplete:n.verification_uri_complete,expiresAt:Date.now()+Math.max(1,n.expires_in)*1e3,intervalSeconds:Math.max(1,n.interval)}}function M(n){if(!n)return null;try{return JSON.parse(n)}catch{return null}}function tt(n){if(!n||typeof n!="object"||Array.isArray(n))return null;let e=n;return e.access!=="contract"&&e.access!=="full_collection"||!Array.isArray(e.contracts)||e.contracts.some(t=>!t||typeof t!="object"||t.contract_type!=="record"||typeof t.id!="string"||typeof t.version!="string"||!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(t.version)||!/^sha256:[0-9a-f]{64}$/.test(t.digest)||!t.schema||typeof t.schema!="object"||Array.isArray(t.schema)||!Array.isArray(t.implementations)||t.implementations.some(i=>!i||typeof i!="object"||typeof i.type_name!="string"||!Number.isInteger(i.type_version)||!/^sha256:[0-9a-f]{64}$/.test(i.digest)||!i.fields||typeof i.fields!="object"||Array.isArray(i.fields)||Object.values(i.fields).some(o=>typeof o!="string")))?null:e}function Mn(n){return n.endsWith("/")?n.slice(0,-1):n}function Un(){if(typeof location>"u")throw c("manifest_required","manifest is required outside a browser environment.");if(location.origin==="null")throw c("manifest_required","Downloaded applications must provide their v1 portable manifest inline.");return new URL("/.well-known/mdbase-app.json",location.origin).href}function zn(){if(typeof location>"u")throw c("redirect_uri_required","redirectUri is required outside a browser environment.");return location.href.split(/[?#]/)[0]}function Fn(){if(typeof location>"u")throw c("callback_url_required","callbackUrl is required outside a browser environment.");return location.href}function Dn(n){if(n)return new _e;if(typeof localStorage>"u")throw c("storage_required","storage is required outside a browser environment.");try{let e=`mdbase-connect:probe:${N(8)}`;return localStorage.setItem(e,"1"),localStorage.removeItem(e),localStorage}catch{return new _e}}var _e=class{values=new Map;get length(){return this.values.size}clear(){this.values.clear()}getItem(e){return this.values.get(e)??null}key(e){return[...this.values.keys()][e]??null}removeItem(e){this.values.delete(e)}setItem(e,t){this.values.set(String(e),String(t))}};function Ln(n){return typeof n=="string"||n.distribution!=="portable"?!1:typeof location>"u"||location.origin==="null"||!["http:","https:"].includes(location.protocol)}function Nn(n){let e=Ut(n),t=2166136261,i=2654435769;for(let o=0;o<e.length;o+=1){let r=e.charCodeAt(o);t=Math.imul(t^r,16777619),i=Math.imul(i^r,2246822507)}return`${(t>>>0).toString(16).padStart(8,"0")}${(i>>>0).toString(16).padStart(8,"0")}`}var nt=class{constructor(e){this.context=e}context;async registerNotifications(e){let t=await this.context.authorizedToken();if(!t)throw c("not_authorized","Connect this application before enabling notifications.");let o=(await this.context.register()).notifications?.criteria.map(v=>v.id)??[],r=[...new Set(e.criteria??o)],a=r.find(v=>!o.includes(v));if(a)throw c("notification_criterion_not_declared",`The application manifest does not declare notification criterion ${a}.`);if(r.length===0)throw c("notifications_not_declared","This application manifest does not declare any notification criteria.");let s=await $(`${this.context.serverUrl}/v1/notifications/vapid-public-key`,void 0,"notifications_unavailable","Push notifications are unavailable."),l=await s.json();if(!s.ok)throw k(l,"notifications_unavailable","Push notifications are unavailable.",s.status);let d=await e.serviceWorker.pushManager.getSubscription();d||(d=await e.serviceWorker.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:Cn(l.public_key)}));let p=d.toJSON();if(!p.endpoint||!p.keys?.p256dh||!p.keys.auth)throw c("invalid_push_subscription","The browser returned an incomplete push subscription.");let u=M(this.context.storage.getItem(this.context.notificationKey())),y=e.installationId??u?.installationId??N(24),h=await $(`${this.context.serverUrl}/v1/notifications/channels`,{method:"POST",headers:{authorization:`Bearer ${t.accessToken}`,"content-type":"application/json"},body:JSON.stringify({installation_id:y,criteria:r,subscription:{endpoint:p.endpoint,expirationTime:p.expirationTime??null,keys:p.keys}})},"notification_registration_failed","Could not register push notifications."),_=await h.json();if(!h.ok)throw k(_,"notification_registration_failed","Could not register push notifications.",h.status);u?.channelId&&u.channelId!==_.channel_id&&fetch(`${this.context.serverUrl}/v1/notifications/channels/${u.channelId}`,{method:"DELETE",headers:{authorization:`Bearer ${t.accessToken}`}}).catch(()=>{});let f={channelId:_.channel_id,installationId:y,criteria:r};return this.context.storage.setItem(this.context.notificationKey(),JSON.stringify(f)),f}async registerNativeNotifications(e){let t=await this.context.authorizedToken();if(!t)throw c("not_authorized","Connect this application before enabling notifications.");let i=await this.context.register();if(i.notifications?.native_delivery?.mode!=="managed_fcm")throw c("managed_fcm_not_declared","This application does not declare Connect-managed native notifications.");let o=i.notifications.criteria.map(h=>h.id),r=[...new Set(e.criteria??o)],a=r.find(h=>!o.includes(h));if(a)throw c("notification_criterion_not_declared",`The application manifest does not declare notification criterion ${a}.`);if(r.length===0)throw c("notifications_not_declared","This application manifest does not declare any notification criteria.");let s=this.context.notificationKey("fcm"),l=M(this.context.storage.getItem(s)),d=e.installationId??l?.installationId??N(24),p=await $(`${this.context.serverUrl}/v1/notifications/channels`,{method:"POST",headers:{authorization:`Bearer ${t.accessToken}`,"content-type":"application/json"},body:JSON.stringify({installation_id:d,criteria:r,transport:"fcm",token:e.token})},"notification_registration_failed","Could not register native notifications."),u=await p.json();if(!p.ok)throw k(u,"notification_registration_failed","Could not register native notifications.",p.status);l?.channelId&&l.channelId!==u.channel_id&&this.deleteNotificationChannel(l.channelId,t.accessToken).catch(()=>{});let y={channelId:u.channel_id,installationId:d,transport:"fcm",criteria:r};return this.context.storage.setItem(s,JSON.stringify(y)),y}async unregisterNativeNotifications(){let e=this.context.notificationKey("fcm"),t=M(this.context.storage.getItem(e)),i=await this.context.authorizedToken();if(t?.channelId&&!i)throw c("not_authorized","Reconnect this application before disabling native notifications.");t?.channelId&&i&&await this.deleteNotificationChannel(t.channelId,i.accessToken),this.context.storage.removeItem(e)}async unregisterNotifications(e){let t=M(this.context.storage.getItem(this.context.notificationKey())),i=await this.context.authorizedToken();if(t?.channelId&&!i)throw c("not_authorized","Reconnect this application before disabling push notifications.");if(t?.channelId&&i){let r=await $(`${this.context.serverUrl}/v1/notifications/channels/${t.channelId}`,{method:"DELETE",headers:{authorization:`Bearer ${i.accessToken}`}},"notification_unregistration_failed","Could not unregister push notifications.");if(!r.ok&&r.status!==404){let a=await r.json();throw k(a,"notification_unregistration_failed","Could not unregister push notifications.",r.status)}}this.context.storage.removeItem(this.context.notificationKey()),await(await e?.pushManager.getSubscription())?.unsubscribe()}async deleteNotificationChannel(e,t){let i=await $(`${this.context.serverUrl}/v1/notifications/channels/${e}`,{method:"DELETE",headers:{authorization:`Bearer ${t}`}},"notification_unregistration_failed","Could not unregister push notifications.");if(!i.ok&&i.status!==404){let o=await i.json();throw k(o,"notification_unregistration_failed","Could not unregister push notifications.",i.status)}}};async function it(n,e,t,i,o,r){if(!n.authority)throw c("not_remote_authority","This authorization has no remote authority endpoint.");let a=t===""||t.startsWith("?")?t:`/${t}`,s=`${n.authority.filesUrl}${a}`,l=i===void 0?void 0:JSON.stringify(i),d=await r(n,e,s,l,n.authority.accessToken);return fetch(s,{method:e,redirect:"error",headers:{authorization:`Bearer ${n.authority.accessToken}`,...l===void 0?{}:{"content-type":"application/json"},...d},...l===void 0?{}:{body:l},...o?{signal:o}:{}})}async function qn(n,e,t,i,o,r,a){let s=n,l=await it(s,e,t,i,o,a);if(l.status===401&&s.refreshToken){if(s=await r(),!s.authority||!s.fileCapability)throw c("authority_authorization_changed","Reconnect this collection before accessing its files.");l=await it(s,e,t,i,o,a)}let d=await l.json().catch(()=>({}));if(!l.ok)throw k(d,"operation_failed","Collection file request failed.",l.status);return d}async function Bn(n,e,t,i,o,r){let a=n,s=await it(a,"GET",e,void 0,i,r);if(s.status===401&&a.refreshToken){if(a=await o(),!a.authority||!a.fileCapability)throw c("authority_authorization_changed","Reconnect this collection before accessing its files.");s=await it(a,"GET",e,void 0,i,r)}if(!s.ok){let d=await s.json().catch(()=>({}));throw k(d,"operation_failed","Collection file range request failed.",s.status)}let l=s.headers.get("content-length");if(l===null||!/^(0|[1-9][0-9]*)$/u.test(l)||Number(l)!==t)throw await s.body?.cancel().catch(()=>{}),c("invalid_operation_response","The hosted file response declared an unexpected byte length.");if(!s.body)throw c("invalid_operation_response","The hosted file response did not contain a byte stream.");return s.body}var ot=class{constructor(e){this.options=e}options;async control(e,t,i,o,r){be(e);let a=ho(t,i,o),s=await this.encryptControl(e,a),l;if(await this.options.shouldAttemptDirect(e)){try{l=await fetch(`${this.options.loopbackUrl}/v1/files/control`,ne({method:"POST",headers:{"content-type":"application/mdbase-connect+json"},body:JSON.stringify(s),signal:r}))}catch(d){if(r?.aborted)throw d;this.options.onDirectUnavailable()}if(l&&!me(l.status))return l.ok&&this.options.onDirectAvailable(),this.decryptControlResponse(e,s,l);l&&this.options.onDirectUnavailable()}return l=await this.sendRelayControl(e,s,r),await co(l,e)&&(e=await this.options.refreshAuthorization(),zt(e),s=await this.encryptControl(e,a),l=await this.sendRelayControl(e,s,r)),l.ok&&this.options.onRelayAvailable(),this.decryptControlResponse(e,s,l)}async decryptControlResponse(e,t,i){let o=await i.json().catch(()=>({}));if(!i.ok)throw k(o,"operation_failed","Collection file request failed.",i.status);let r=o?.envelope;if(!r)throw c("invalid_encrypted_response","The connector omitted its encrypted file response.");let a=await ue(this.options.keyStore,e.keyHandle,Ft(e),t,r);return a.ok||po(a.problem),a.result}async uploadChunk(e,t,i,o){let a=await this.localFileToken(e,"upload"),s=await Kn(this.options.keyStore,a,e,t,i),l;if(await this.options.shouldAttemptDirect(a)){try{l=await fetch(`${this.options.loopbackUrl}/v1/files/upload`,ne(jn(s,o)))}catch(d){if(o?.aborted)throw d;this.options.onDirectUnavailable()}if(l&&!me(l.status))return l.ok&&this.options.onDirectAvailable(),so(l,"Encrypted file chunk upload failed.");l&&this.options.onDirectUnavailable()}if(l=await this.sendRelayUpload(a,s,o),l.status===401&&a.refreshToken&&(a=await this.options.refreshAuthorization(),zt(a),s=await Kn(this.options.keyStore,a,e,t,i),l=await this.sendRelayUpload(a,s,o)),!l.ok){let d=await l.json().catch(()=>({}));throw k(d,"operation_failed","Encrypted file chunk upload failed.",l.status)}this.options.onRelayAvailable()}async downloadChunk(e,t,i){let o=await this.localFileToken(e,"download"),r;if(await this.options.shouldAttemptDirect(o)){try{r=await fetch(`${this.options.loopbackUrl}/v1/files/download/${encodeURIComponent(o.grantId)}/${encodeURIComponent(e.transfer_id)}/${t}`,ne({method:"GET",signal:i}))}catch(a){if(i?.aborted)throw a;this.options.onDirectUnavailable()}if(r&&!me(r.status))return r.ok&&this.options.onDirectAvailable(),this.decryptDownloadResponse(o,e,t,r);r&&this.options.onDirectUnavailable()}return r=await this.sendRelayDownload(o,e,t,i),r.status===401&&o.refreshToken&&(o=await this.options.refreshAuthorization(),zt(o),r=await this.sendRelayDownload(o,e,t,i)),r.ok&&this.options.onRelayAvailable(),this.decryptDownloadResponse(o,e,t,r)}async decryptDownloadResponse(e,t,i,o){if(!o.ok){let s=await o.json().catch(()=>({}));throw k(s,"operation_failed","Encrypted file chunk download failed.",o.status)}if(o.headers.get("content-type")?.split(";",1)[0]!=="application/mdbase-connect-file")throw c("invalid_operation_response","The connector returned an invalid file response media type.");let r=new Uint8Array(await o.arrayBuffer()),a;try{uo(t,i,r),a=await(await $n(this.options.keyStore,e,t)).decryptChunk(r)}catch(s){throw s instanceof S?s:c("invalid_operation_response","The connector returned an invalid encrypted file frame.",{cause:s})}if(a.byteLength!==Dt(t,i))throw c("invalid_operation_response","The connector returned a truncated file chunk.");return a}encryptControl(e,t){return be(e),X(this.options.keyStore,e.keyHandle,Ft(e),"file_control",t)}sendRelayControl(e,t,i){return fetch(`${this.options.serverUrl}/v1/authorities/${encodeURIComponent(e.collectionId)}/files/control`,{method:"POST",headers:{authorization:`Bearer ${e.accessToken}`,"content-type":"application/json"},body:JSON.stringify(t),signal:i})}sendRelayUpload(e,t,i){return fetch(`${this.options.serverUrl}/v1/authorities/${encodeURIComponent(e.collectionId)}/files/upload`,{...jn(t,i),headers:{authorization:`Bearer ${e.accessToken}`,"content-type":"application/mdbase-connect-file"}})}sendRelayDownload(e,t,i,o){return fetch(`${this.options.serverUrl}/v1/authorities/${encodeURIComponent(e.collectionId)}/files/download/${encodeURIComponent(t.transfer_id)}/${i}`,{method:"GET",headers:{authorization:`Bearer ${e.accessToken}`},signal:o})}async localFileToken(e,t){let i=await this.options.authorizedToken();if(!i||i.authority||!i.fileCapability||!i.encryption||!i.grantId||!i.keyHandle||e.direction!==t||e.protection!=="grant_aead_v1")throw c("not_authorized","This connection cannot use encrypted local file delivery.");return rt(e),i}};function zt(n){if(n.authority||!n.fileCapability)throw c("not_authorized","This connection cannot use encrypted local file delivery.");be(n)}async function Kn(n,e,t,i,o){let r=lo(e,t,i,o.byteLength);return(await $n(n,e,t)).encryptChunk("upload_chunk",r,o)}function jn(n,e){return{method:"POST",headers:{"content-type":"application/mdbase-connect-file"},body:Uint8Array.from(n).buffer,signal:e}}async function so(n,e){if(n.ok)return;let t=await n.json().catch(()=>({}));throw k(t,"operation_failed",e,n.status)}async function co(n,e){return e.refreshToken?n.status===401?!0:n.status!==409?!1:(await n.clone().json().catch(()=>null))?.error?.code==="encryption_binding_stale":!1}function be(n){if(!n.encryption||!n.grantId||!n.keyHandle)throw c("missing_grant_key","Reconnect this application to restore encrypted file access.")}function Ft(n){return be(n),{grantId:n.grantId,applicationId:n.clientId,encryption:n.encryption}}function $n(n,e,t){return be(e),pe.open(n,e.keyHandle,{...Ft(e),authorityId:e.encryption.connector_id,transferId:t.transfer_id,direction:t.direction})}function lo(n,e,t,i){be(n);let o=rt(e),r=Dt(e,t);if(i!==r)throw c("invalid_request","The file chunk has the wrong byte length.");return{protocol_version:1,protection:"grant_aead_v1",grant_id:n.grantId,authority_id:n.encryption.connector_id,collection_id:n.collectionId,transfer_id:e.transfer_id,direction:e.direction,chunk_size:o,chunk_index:t,offset:t*o,plaintext_length:i,total_size:e.total_size,scope_epoch:n.encryption.scope_epoch,key_id:n.encryption.key_id}}function uo(n,e,t){let i=je(t),o=Dt(n,e),r=rt(n);if(i.kind!=="download_chunk"||i.header.chunk_index!==e||i.header.chunk_size!==r||i.header.offset!==e*r||i.header.plaintext_length!==o||i.header.total_size!==n.total_size)throw c("invalid_operation_response","The connector returned a file frame for a different chunk.")}function po(n){throw D(n.code==="unknown"?n.server_code:n.code,n.message,{details:n.details,operationOutcome:n.operation_outcome??"rejected",traceId:n.trace_id})}function ho(n,e,t){if(n==="GET"&&(e===""||e.startsWith("?"))){let o=new URLSearchParams(e.startsWith("?")?e.slice(1):e),r=o.get("limit");return{protocol_version:1,type:"list_files",...o.get("folder")?{folder:o.get("folder")}:{},...o.get("after")?{after:o.get("after")}:{},...r?{limit:Number(r)}:{}}}let i=e.split("/");if(n==="GET"&&i.length===2&&i[0]==="transfers")return Hn("get_file_transfer_status",i[1]);if(n==="DELETE"&&i.length===2&&i[0]==="transfers")return Hn("abort_file_transfer",i[1]);if(n==="POST"&&fo(t)){let o=e==="uploads"?"open_file_upload":e==="downloads"?"open_file_download":i.length===3&&i[0]==="uploads"&&i[2]==="commit"?"commit_file_upload":i.length===2&&i[1]==="move"&&t.file_id===decodeURIComponent(i[0])?"move_file":i.length===2&&i[1]==="delete"&&t.file_id===decodeURIComponent(i[0])?"delete_file":null;if(o&&t.type===o)return{...t}}throw c("invalid_request","The file control request path is invalid.")}function Hn(n,e){return{protocol_version:1,type:n,transfer_id:decodeURIComponent(e)}}function rt(n){if(n.strategy.kind!=="framed_chunks"||!Number.isSafeInteger(n.strategy.chunk_size)||n.strategy.chunk_size<=0)throw c("invalid_operation_response","The connector returned an invalid framed transfer strategy.");return n.strategy.chunk_size}function Dt(n,e){let t=rt(n);if(!Number.isSafeInteger(e)||e<0||!Number.isSafeInteger(n.total_size)||n.total_size<0)throw c("invalid_request","The file chunk index is invalid.");let i=e*t;if(!Number.isSafeInteger(i)||i>=n.total_size)throw c("invalid_request","The file chunk index is outside the transfer.");return Math.min(t,n.total_size-i)}function fo(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}var at=class{constructor(e){this.options=e;this.local=new ot(e)}options;local;async control(e,t="",i,o){let r=await this.requireFileToken();return r.authority?qn(r,e,t,i,o,this.options.refreshAuthorization,this.options.authorityProofHeaders):this.local.control(r,e,t,i,o)}uploadChunk(e,t,i,o){return this.local.uploadChunk(e,t,i,o)}downloadChunk(e,t,i){return this.local.downloadChunk(e,t,i)}async downloadHostedPart(e,t,i,o){let r=await this.requireFileToken();if(!r.authority)throw c("not_remote_authority","Hosted file delivery requires a remote authority endpoint.");return Bn(r,`downloads/${encodeURIComponent(e.transfer_id)}/parts/${t}`,i,o,this.options.refreshAuthorization,this.options.authorityProofHeaders)}async requireFileToken(){let e=await this.options.authorizedToken();if(!e?.fileCapability)throw c("not_authorized","This connection has no file capability.");return e}};var st=class{serverUrl;storage;keyStore;directAccessMode;loopbackUrl;collectionId;internals;onChange;files;refreshPromise=null;directStatus;currentRoute="relay";directFailures=0;directRetryAt=0;constructor(e){this.serverUrl=e.serverUrl,this.storage=e.storage,this.keyStore=e.keyStore,this.directAccessMode=e.directAccessMode,this.loopbackUrl=e.loopbackUrl,this.collectionId=e.collectionId,this.internals=e.internals,this.onChange=e.onChange,this.files=new at({keyStore:this.keyStore,serverUrl:this.serverUrl,loopbackUrl:this.loopbackUrl,authorizedToken:()=>this.authorizedToken(),refreshAuthorization:()=>this.refreshAuthorization(),shouldAttemptDirect:t=>this.shouldAttemptDirect(t),onDirectAvailable:()=>{this.markDirectAvailable(),this.setRoute("direct")},onDirectUnavailable:()=>this.markDirectUnavailable(),onRelayAvailable:()=>this.setRoute("relay"),authorityProofHeaders:(t,i,o,r,a)=>this.authorityProofHeaders(t,i,o,r,a)}),this.directStatus=this.directAccessMode==="disabled"?"disabled":"unavailable"}get directAccess(){return this.currentToken()?.authority?"disabled":this.directStatus}get route(){return this.currentToken()?.authority?"remote":this.currentRoute}notifyStorageChanged(){this.emitConnection()}async checkDirectAccess(){let e=this.currentToken();if(!this.directEligible(e))return this.setDirectStatus("disabled");let t=await Me();return t==="denied"?this.setDirectStatus("denied"):(t==="prompt"||t===null)&&this.storage.getItem(this.directPreferenceKey())!=="enabled"?this.setDirectStatus("permission_required"):this.probeDirectAccess()}async requestDirectAccess(){let e=this.currentToken();return this.directCapable(e)?(this.storage.setItem(this.directPreferenceKey(),"enabled"),this.directRetryAt=0,this.probeDirectAccess()):this.setDirectStatus("disabled")}disableDirectAccess(){this.storage.setItem(this.directPreferenceKey(),"disabled"),this.setDirectStatus("disabled"),this.setRoute("relay")}pendingMutation(){let e=M(this.storage.getItem(this.pendingMutationKey())),t=this.currentToken();return!e||!t||e.collectionId!==t.collectionId||e.grantId!==t.grantId||e.keyId!==t.encryption?.key_id?null:{operation:e.operation,createdAt:e.createdAt,resumable:!0}}async resumePendingMutation(e,t){let i=this.pendingMutation();if(!i)throw c("no_pending_mutation","There is no interrupted mutation to resume.");return this.performOperation(i.operation,e,t)}async performOperation(e,t,i={}){ie(i.signal);let o=this.currentToken();if(!o)throw c("not_authorized","Connect this application before accessing a collection.");if(!o.operations.includes(e))throw c("insufficient_access",`This connection does not allow ${e}.`,{details:{required_operations:[e],granted_operations:[...o.operations],missing_operations:[e]}});let r=await this.shouldAttemptDirect(o);if(!r&&(o=await this.authorizedToken(),!o))throw c("not_authorized","Reconnect this application to continue.");let a;try{a=await this.sendOperation(o,e,t,r,i)}catch(p){throw xt(p,i.signal,We(e,t)&&this.pendingMutation()!==null,o.authority?"hosted_provider_unavailable":"relay_unavailable")}let s=a.response,l=s.status===409&&(await s.clone().json().catch(()=>null))?.error?.code==="encryption_binding_stale";if((s.status===401||l)&&o.refreshToken){if(a.pendingMutation&&(a.directDeliveryUncertain||a.encryptedRequest&&a.resumingMutation))throw c("operation_outcome_unknown","The direct operation may have completed, but its encrypted grant changed before the response could be recovered. Refresh before making another change.",{operationOutcome:"unknown"});a.pendingMutation&&this.clearPendingMutation(),o=await this.refreshAuthorization(),r=await this.shouldAttemptDirect(o);try{a=await this.sendOperation(o,e,t,r,i)}catch(p){throw xt(p,i.signal,We(e,t)&&this.pendingMutation()!==null,o.authority?"hosted_provider_unavailable":"relay_unavailable")}s=a.response}let d;try{d=await s.json()}catch(p){throw a.pendingMutation?L(p):c("invalid_operation_response","The collection authority returned a response that is not valid JSON.",{cause:p})}if(!s.ok){let p=k(d,"operation_failed","Collection operation failed.",s.status);throw a.pendingMutation&&(a.directDeliveryUncertain||a.encryptedRequest&&a.resumingMutation)?L(p):(a.pendingMutation&&!a.directDeliveryUncertain&&this.clearPendingMutation(),p.code==="direct_operation_rejected"&&p.status===403&&this.invalidateRejectedAuthorization(o),p)}if(a.encryptedRequest){let p=d?.envelope;if(!p||!o.encryption||!o.grantId||!o.keyHandle)throw a.pendingMutation?L(new Error("Encrypted operation response was missing its envelope.")):c("invalid_encrypted_response","The relay did not return an encrypted connector response.");try{let u=await ue(this.keyStore,o.keyHandle,{grantId:o.grantId,applicationId:o.clientId,encryption:o.encryption},a.encryptedRequest,p);if(a.pendingMutation&&this.clearPendingMutation(),!u.ok)throw D(u.problem.code==="unknown"?u.problem.server_code:u.problem.code,u.problem.message,{details:u.problem.details,operationOutcome:u.problem.operation_outcome??"rejected",traceId:u.problem.trace_id});return u.result}catch(u){throw u instanceof S?u:u instanceof C?a.pendingMutation?L(u):D(u.code,u.message):u}}if(d?.protocol_version!==1||d?.request_id!==a.requestId)throw a.pendingMutation?L(new Error("Operation response protocol or request ID did not match.")):c("invalid_operation_response","The collection authority returned a response for a different protocol request.");if(d.ok===!1)throw Ce(d.problem)?(a.pendingMutation&&this.clearPendingMutation(),new S(d.problem)):a.pendingMutation?L(new Error("Operation rejection did not contain a canonical problem.")):c("invalid_operation_response","The collection authority returned an invalid operation problem.");if(d.ok!==!0||!("result"in d))throw a.pendingMutation?L(new Error("Successful operation response did not contain a result.")):c("invalid_operation_response","The collection authority returned an incomplete operation response.");return a.pendingMutation&&this.clearPendingMutation(),d.result}async performAuthoritySyncRequest(e,t,i,o,r){let a=await this.authorizedToken();if(!a?.authority||a.collectionId!==e||a.authority.replicaId!==t)throw c("authority_authorization_changed","Reconnect this collection authority before synchronizing.");let s=await this.sendAuthoritySyncRequest(a,i,o,r);if(s.status===401&&a.refreshToken){if(a=await this.refreshAuthorization(),!a.authority||a.collectionId!==e||a.authority.replicaId!==t)throw c("authority_authorization_changed","Reconnect this collection authority before synchronizing.");s=await this.sendAuthoritySyncRequest(a,i,o,r)}let l=await s.json();if(!s.ok)throw k(l,"sync_failed","Collection synchronization failed.",s.status);return l}async sendAuthoritySyncRequest(e,t,i,o){if(!e.authority)throw c("not_remote_authority","This authorization has no remote authority endpoint.");let r=`${e.authority.syncUrl}/${i}`,a=o===void 0?void 0:JSON.stringify(o),s=await this.authorityProofHeaders(e,t,r,a,e.authority.accessToken);return fetch(r,{method:t,headers:{authorization:`Bearer ${e.authority.accessToken}`,...o===void 0?{}:{"content-type":"application/json"},...s},...a===void 0?{}:{body:a}})}async sendOperation(e,t,i,o,r={}){let a=i??{},s,l=!1,d=!1,p=crypto.randomUUID(),u=null,y;if(We(t,i)){if(y=await On(t,i),u=M(this.storage.getItem(this.pendingMutationKey())),u){if(u.collectionId!==e.collectionId||u.grantId!==e.grantId||u.keyId!==e.encryption?.key_id||u.operation!==t||u.inputFingerprint!==y)throw c("pending_mutation_unresolved","A previous write still has an unknown outcome. Retry that exact write before making another change.");p=u.requestId,d=!0}l=!0}if(e.encryption&&!e.authority){if(!e.grantId||!e.keyHandle)throw c("missing_grant_key","Reconnect this application to restore encrypted access.");try{if(l)if(u){if(!u.envelope)throw c("pending_mutation_unresolved","The pending write belongs to a different transport. Reconnect before retrying it.");s=u.envelope}else s=await X(this.keyStore,e.keyHandle,{grantId:e.grantId,applicationId:e.clientId,encryption:e.encryption},t,i,p),this.storage.setItem(this.pendingMutationKey(),JSON.stringify({collectionId:e.collectionId,...e.grantId?{grantId:e.grantId}:{},keyId:e.encryption.key_id,operation:t,inputFingerprint:y,requestId:p,envelope:s,createdAt:Date.now()}));else s=await X(this.keyStore,e.keyHandle,{grantId:e.grantId,applicationId:e.clientId,encryption:e.encryption},t,i)}catch(m){throw m instanceof C?D(m.code,m.message):m}a=s}else a={protocol_version:1,request_id:p,input:a},l&&!u&&this.storage.setItem(this.pendingMutationKey(),JSON.stringify({collectionId:e.collectionId,...e.grantId?{grantId:e.grantId}:{},operation:t,inputFingerprint:y,requestId:p,createdAt:Date.now()}));if(o&&s&&!e.authority){let m=!1;try{let R=await fetch(`${this.loopbackUrl}/v1/operations`,ne({method:"POST",headers:{"content-type":"application/mdbase-connect+json"},body:JSON.stringify(s),signal:r.signal}));if(!me(R.status))return R.ok&&(this.markDirectAvailable(),this.setRoute("direct")),{response:R,requestId:p,encryptedRequest:s,pendingMutation:l,resumingMutation:d};m=R.status>=500,this.markDirectUnavailable()}catch(R){if(r.signal?.aborted)throw R;m=!0,await Me()==="denied"?this.setDirectStatus("denied"):this.markDirectUnavailable()}let P;try{P=e.expiresAt>Date.now()+3e4?e:await this.refreshAuthorization()}catch(R){throw l&&(m||d)?L(R):R}let g;try{g=await fetch(`${this.serverUrl}/v1/authorities/${encodeURIComponent(P.collectionId)}/operations/${t}`,{method:"POST",headers:{authorization:`Bearer ${P.accessToken}`,"content-type":"application/json"},body:JSON.stringify(s),signal:r.signal})}catch(R){throw l&&(m||d)?L(R):R}return g.ok&&this.setRoute("relay"),{response:g,requestId:p,encryptedRequest:s,directDeliveryUncertain:m,pendingMutation:l,resumingMutation:d}}let h=e.authority?`${e.authority.operationsUrl}/${t}`:`${this.serverUrl}/v1/authorities/${encodeURIComponent(e.collectionId)}/operations/${t}`,_=JSON.stringify(a),f=e.authority?await this.authorityProofHeaders(e,"POST",h,_,e.authority.accessToken):{},v=await fetch(h,{method:"POST",headers:{authorization:`Bearer ${e.authority?.accessToken??e.accessToken}`,"content-type":"application/json",...f},body:_,signal:r.signal});return v.ok&&this.setRoute(e.authority?"remote":"relay"),{response:v,requestId:p,encryptedRequest:s,pendingMutation:l,resumingMutation:d}}directCapable(e){return!(!e||e.authority||!e.encryption||!e.grantId||!e.keyHandle||this.directAccessMode==="disabled"||typeof location<"u"&&e.applicationOrigin&&e.applicationOrigin!==location.origin)}hasResumableMutationTransport(){return!!this.currentToken()}directEligible(e){return e!==null&&this.directCapable(e)&&this.storage.getItem(this.directPreferenceKey())!=="disabled"}async shouldAttemptDirect(e){if(!this.directEligible(e))return!1;if(this.directStatus==="available")return!0;if(this.directStatus==="unavailable"&&Date.now()<this.directRetryAt)return!1;let t=await Me();return t==="denied"?(this.setDirectStatus("denied"),!1):(t==="prompt"||t===null)&&this.storage.getItem(this.directPreferenceKey())!=="enabled"?(this.setDirectStatus("permission_required"),!1):(this.setDirectStatus("checking"),!0)}async probeDirectAccess(){this.setDirectStatus("checking");try{let e=await fetch(`${this.loopbackUrl}/v1/ready`,ne({method:"GET",cache:"no-store"})),t=await e.json().catch(()=>null);if(e.ok&&t?.service==="mdbase-connect"&&t?.loopback_protocol_version===1&&t?.encrypted_protocol_version===1)return this.markDirectAvailable(),"available"}catch{}return await Me()==="denied"?this.setDirectStatus("denied"):(this.markDirectUnavailable(),"unavailable")}markDirectAvailable(){this.directFailures=0,this.directRetryAt=0,this.setDirectStatus("available")}markDirectUnavailable(){this.directFailures+=1,this.directRetryAt=Date.now()+Math.min(6e4,1e3*2**(this.directFailures-1)),this.setDirectStatus("unavailable")}setDirectStatus(e){return this.directStatus!==e&&(this.directStatus=e,this.emitConnection()),e}setRoute(e){this.currentRoute!==e&&(this.currentRoute=e,this.emitConnection())}emitConnection(){this.onChange()}invalidateRejectedAuthorization(e){let t=M(this.storage.getItem(this.tokenKey()));!t||!Pn(t,e)||(this.internals.removeToken(this.collectionId,t.keyHandle),this.currentRoute="relay",this.directStatus=this.directAccessMode==="disabled"?"disabled":"unavailable",this.emitConnection())}currentToken(){let e=this.storage.getItem(this.tokenKey()),t=M(e),i=o=>(this.internals.removeToken(this.collectionId,typeof o=="string"?o:void 0,"invalid_stored_grant"),null);if(!t)return e&&i(),null;if(t.version!==1||typeof t.accessToken!="string"||t.accessToken.length===0||typeof t.clientId!="string"||t.clientId.length===0||t.collectionId!==this.collectionId||typeof t.collectionName!="string"||t.collectionName.length===0||!Array.isArray(t.operations)||t.operations.some(o=>typeof o!="string")||typeof t.expiresAt!="number"||!Number.isFinite(t.expiresAt)||t.refreshToken!==void 0&&(typeof t.refreshToken!="string"||t.refreshToken.length===0)||t.refreshExpiresAt!==void 0&&(typeof t.refreshExpiresAt!="number"||!Number.isFinite(t.refreshExpiresAt))||!tt(t.scope)||t.fileCapability&&!et(t.fileCapability)||t.authority&&!In(t.authority,t.collectionId))return i(t.keyHandle);if(this.internals.relayEncryption==="required"){if(t.authority){if(!t.keyHandle||!t.authority.proofPublicKey)return i(t.keyHandle)}else if(!t.grantId||!t.keyHandle||!En(t.encryption,t.collectionId))return i(t.keyHandle)}return t.expiresAt<=Date.now()&&(!t.refreshToken||(t.refreshExpiresAt??0)<=Date.now())?this.directCapable(t)?t:(this.internals.removeToken(this.collectionId,t.keyHandle),null):t}async authorizedToken(){let e=this.currentToken();if(!e)return null;if(e.expiresAt>Date.now()+3e4)return e;if(!e.refreshToken||(e.refreshExpiresAt??0)<=Date.now()){if(this.directCapable(e))throw c("relay_authorization_expired","Direct access is still available on this computer, but using the relay requires reconnecting this application.");return this.internals.removeToken(this.collectionId,e.keyHandle),null}return this.refreshAuthorization()}refreshAuthorization(){return this.refreshPromise?this.refreshPromise:(this.refreshPromise=this.performRefresh().finally(()=>{this.refreshPromise=null}),this.refreshPromise)}async performRefresh(){let e=this.currentToken();if(!e?.refreshToken)throw c("not_authorized","Reconnect this application to continue.");if((e.refreshExpiresAt??0)<=Date.now())throw c("relay_authorization_expired","Direct access is still available on this computer, but using the relay requires reconnecting this application.");let t=e.refreshToken,i=`${this.serverUrl}/oauth/token`,o=new URLSearchParams({grant_type:"refresh_token",refresh_token:e.refreshToken,client_id:e.clientId}).toString(),r=e.authority?await this.authorityProofHeaders(e,"POST",i,o,e.refreshToken):{},a=await fetch(i,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",...r},body:o}),s=await a.json();if(!a.ok){let l=this.currentToken();if(l?.refreshToken&&l.refreshToken!==t)return l;throw this.directCapable(e)||this.internals.removeToken(this.collectionId,e.keyHandle),(ge(s)??s?.error?.code)==="invalid_grant"?c("authorization_expired",s?.error_description??s?.error?.message??"Reconnect this application to continue.",{status:a.status}):k(s,"authorization_expired","Reconnect this application to continue.",a.status)}return this.storeTokenResponse(s,e.clientId,e.keyHandle)}async authorityProofHeaders(e,t,i,o,r){if(!e.authority?.proofPublicKey)return{};if(!e.keyHandle)throw c("missing_grant_key","Reconnect this application to restore remote authority request signing.");try{let a=new URL(i);return await sn(this.keyStore,e.keyHandle,e.authority.proofPublicKey,{method:t,target:`${a.pathname}${a.search}`,body:o,credential:r})}catch(a){throw a instanceof C?D(a.code,a.message):a}}storeTokenResponse(e,t,i){if(e.collection_id!==this.collectionId)throw c("collection_mismatch","The refreshed authorization belongs to a different collection.");let o=this.internals.storeTokenResponse(e,t,i);return this.currentRoute=o.authority?"remote":"relay",this.directStatus=o.authority||this.directAccessMode==="disabled"?"disabled":"unavailable",this.emitConnection(),o}tokenKey(){return this.internals.tokenKey(this.collectionId)}notificationKey(e="web_push"){return this.internals.notificationKey(this.collectionId,e)}pendingMutationKey(){return this.internals.pendingMutationKey(this.collectionId)}clearPendingMutation(){this.storage.removeItem(this.pendingMutationKey())}directPreferenceKey(){return this.internals.directPreferenceKey()}};var yo=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]),mo=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ve=class{state=mo.slice();block=new Uint8Array(64);words=new Uint32Array(64);blockLength=0;byteLength=0;finished=!1;update(e){if(this.finished)throw new Error("SHA-256 digest is already finalized.");if(this.byteLength+=e.byteLength,!Number.isSafeInteger(this.byteLength))throw new Error("SHA-256 input exceeds the safe browser byte range.");let t=0;if(this.blockLength>0){let i=Math.min(64-this.blockLength,e.byteLength);this.block.set(e.subarray(0,i),this.blockLength),this.blockLength+=i,t+=i,this.blockLength===64&&(this.compress(this.block),this.blockLength=0)}for(;t+64<=e.byteLength;)this.compress(e.subarray(t,t+64)),t+=64;return t<e.byteLength&&(this.block.set(e.subarray(t),0),this.blockLength=e.byteLength-t),this}digestHex(){if(this.finished)throw new Error("SHA-256 digest is already finalized.");this.finished=!0,this.block[this.blockLength]=128,this.block.fill(0,this.blockLength+1),this.blockLength>=56&&(this.compress(this.block),this.block.fill(0));let e=this.byteLength*8,t=Math.floor(e/4294967296),i=e>>>0;return Vn(this.block,56,t),Vn(this.block,60,i),this.compress(this.block),[...this.state].map(o=>o.toString(16).padStart(8,"0")).join("")}compress(e){let t=this.words;for(let u=0;u<16;u+=1){let y=u*4;t[u]=(e[y]<<24|e[y+1]<<16|e[y+2]<<8|e[y+3])>>>0}for(let u=16;u<64;u+=1){let y=t[u-15],h=t[u-2],_=K(y,7)^K(y,18)^y>>>3,f=K(h,17)^K(h,19)^h>>>10;t[u]=t[u-16]+_+t[u-7]+f>>>0}let i=this.state[0],o=this.state[1],r=this.state[2],a=this.state[3],s=this.state[4],l=this.state[5],d=this.state[6],p=this.state[7];for(let u=0;u<64;u+=1){let y=K(s,6)^K(s,11)^K(s,25),h=s&l^~s&d,_=p+y+h+yo[u]+t[u]>>>0,f=K(i,2)^K(i,13)^K(i,22),v=i&o^i&r^o&r,m=f+v>>>0;p=d,d=l,l=s,s=a+_>>>0,a=r,r=o,o=i,i=_+m>>>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]+l>>>0,this.state[6]=this.state[6]+d>>>0,this.state[7]=this.state[7]+p>>>0}};function K(n,e){return n>>>e|n<<32-e}function Vn(n,e,t){n[e]=t>>>24,n[e+1]=t>>>16,n[e+2]=t>>>8,n[e+3]=t}var ct=class{constructor(e,t){this.signal=t;this.iterator=_o(e)}signal;iterator;remainder=new Uint8Array;remainderOffset=0;maxSourceChunkBytes=null;iteratorClosing=!1;ended=!1;setMaxSourceChunkBytes(e){this.maxSourceChunkBytes=e}async read(e){let t=new Uint8Array(e),i=0;for(;i<e;){if(this.remainderOffset===this.remainder.byteLength){let r=await this.nextSourceChunk();if(r.done)throw this.ended=!0,c("invalid_request","Streamed file bytes ended before the declared size.");if(!(r.value instanceof Uint8Array))throw c("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 c("invalid_request",`A streamed file chunk exceeded the negotiated ${this.maxSourceChunkBytes}-byte upload part size.`);if(this.remainder=r.value,this.remainderOffset=0,this.remainder.byteLength===0)continue}let o=Math.min(e-i,this.remainder.byteLength-this.remainderOffset);t.set(this.remainder.subarray(this.remainderOffset,this.remainderOffset+o),i),i+=o,this.remainderOffset+=o}return t}async expectEnd(){if(this.remainderOffset<this.remainder.byteLength)throw c("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 c("invalid_request","A streamed file chunk was not a Uint8Array.");if(e.value.byteLength>0)throw c("invalid_request","Streamed file bytes exceed the declared size.")}}async close(){this.ended=!0,this.closeIterator()}async nextSourceChunk(){Gn(this.signal);let e=this.iterator.next(),t=this.signal;if(!t)return e;let i=()=>{},o=new Promise((r,a)=>{let s=()=>{this.closeIterator(),a(Yn(t))};t.addEventListener("abort",s,{once:!0}),i=()=>t.removeEventListener("abort",s),t.aborted&&s()});try{let r=await Promise.race([e,o]);return Gn(t),r}finally{i()}}closeIterator(){if(!this.iteratorClosing){this.iteratorClosing=!0;try{this.iterator.return?.()?.catch(()=>{})}catch{}}}};function _o(n){if(typeof n.getReader=="function"){let t=n.getReader(),i=!1,o=()=>{i||(i=!0,t.releaseLock())};return{async next(){if(i)return{done:!0,value:void 0};let r=await t.read();return r.done&&o(),r},async return(){if(!i)try{await t.cancel()}finally{o()}return{done:!0,value:void 0}}}}let e=n;if(typeof e[Symbol.asyncIterator]!="function")throw c("invalid_request","Streamed files require a readable byte stream.");return e[Symbol.asyncIterator]()}function Gn(n){if(n?.aborted)throw Yn(n)}function Yn(n){return c("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:n?.reason})}var Jn=1024*1024,go=4,Qn=8,we=3,Xn=64*1024*1024,bo=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,vo=/^sha256:[0-9a-f]{64}$/u,Fe=class{constructor(e,t,i,o){this.capability=e;this.request=t;this.framed=i;this.hosted=o}capability;request;framed;hosted;async*list(e={}){this.requireAction("list");let t;do{oe(e.signal);let i=new URLSearchParams({protocol_version:String(1),...e.folder?{folder:e.folder}:{},...t?{after:t}:{},...e.pageSize?{limit:String(ko(e.pageSize))}:{}}),o=await this.request("GET",`?${i.toString()}`,void 0,e.signal);if(o.protocol_version!==1||o.type!=="files_page"||!Array.isArray(o.files))throw c("invalid_operation_response","The authority returned an invalid file page.");for(let r of o.files)oe(e.signal),yield r;t=o.next}while(t)}async upload(e,t,i={}){this.requireAction(i.ifRevision?"replace":"add");let o=Co(t,i.mediaType),r=Wn(i.concurrency),a=await wo(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,l,d)=>o.slice(l,l+d))}async uploadStream(e,t,i={}){if(this.requireAction(i.ifRevision?"replace":"add"),!Number.isSafeInteger(t.size)||t.size<0)throw c("invalid_request","Streamed file size must be a non-negative safe integer.");if(!vo.test(t.contentDigest))throw c("invalid_request","Streamed files require a lowercase SHA-256 content digest.");let o=new ct(t.stream,i.signal),r=new ve;return this.uploadKnownSource(e,t.size,t.contentDigest,i.mediaType??t.mediaType,i,1,async(a,s,l)=>{let d=await o.read(l);return r.update(d),d},async()=>{if(await o.expectEnd(),`sha256:${r.digestHex()}`!==t.contentDigest)throw c("invalid_request","Streamed file bytes do not match the declared SHA-256 digest.")},()=>o.close(),a=>o.setMaxSourceChunkBytes(a))}async uploadKnownSource(e,t,i,o,r,a,s,l,d,p){let u=r.transferId??crypto.randomUUID();if(!bo.test(u))throw c("invalid_request","File transfer ID must be a UUID.");let y=!1;try{let h=await this.request("POST","uploads",{protocol_version:1,type:"open_file_upload",transfer_id:u,path:e,size:t,content_digest:i,...o?{media_type:o}:{},...r.ifRevision?{if_revision:r.ifRevision}:{}},r.signal);if(Zn(h,u,"upload"),h.total_size!==t||h.strategy.kind==="object_ranges")throw c("invalid_operation_response","The authority returned an incompatible upload strategy.");let _=h.strategy.kind==="framed_chunks";if(_&&!this.framed)throw c("invalid_operation_response","Encrypted file chunk delivery is unavailable.");let f=h.strategy.kind==="object_put"?Math.max(1,t):h.strategy.kind==="framed_chunks"?h.strategy.chunk_size:h.strategy.part_size,v=h.strategy.kind==="object_put"?1:Math.ceil(t/f);if(p?.(f),!_&&h.received.length===v){let w=await this.tryReplayUploadCommit(u,h.strategy.kind==="object_multipart"?h.uploaded_parts:void 0,r.signal);if(w)return y=!0,w.file}let m=new Set(h.received),P=new Map((h.uploaded_parts??[]).map(w=>[w.part_number-1,w])),g=[...m].reduce((w,F)=>w+Ao(t,f,F),0),R=await Io(v,a,async w=>{let F=w*f,j=Math.min(f,Math.max(0,t-F)),ut=await s(w,F,j);if(Po(ut)!==j)throw c("invalid_request","Streamed file bytes ended before the declared size.");if(m.has(w))return P.get(w)??null;let ni=_?await Lt(async()=>this.framed.uploadChunk(h,w,await So(ut),r.signal),r.signal).then(()=>null):await this.uploadPart(u,w,F,ut,j,h.strategy.kind==="object_multipart",r.signal);return g+=j,r.onProgress?.({phase:"uploading",transferredBytes:g,totalBytes:t}),ni});await l?.();let x=await this.commitUpload(u,h.strategy.kind==="object_multipart"?R.filter(w=>w!==null):void 0,r.signal);if(x.protocol_version!==1||x.type!=="file_upload_committed"||x.transfer_id!==u||x.file.path!==e||x.file.size!==t||x.file.content_digest!==i)throw c("invalid_operation_response","The authority returned an invalid file receipt.");return y=!0,x.file}catch(h){throw ze(h)}finally{await d?.().catch(()=>{}),!y&&r.transferId===void 0&&await this.abort(u)}}async download(e,t={}){if(e.size>Xn)throw c("invalid_request",`download() buffers at most ${Xn} bytes; use downloadStream() for larger files.`);let i=await this.downloadStream(e,t),o=[],r=i.getReader();for(;;){let a=await r.read();if(a.done)break;o.push(a.value)}return new Blob(o.map(a=>{let s=new Uint8Array(a.byteLength);return s.set(a),s.buffer}),{type:e.media_type??""})}async downloadStream(e,t={}){this.requireAction("read"),Wn(t.concurrency);let i=crypto.randomUUID(),o;try{if(o=await this.request("POST","downloads",{protocol_version:1,type:"open_file_download",transfer_id:i,file_id:e.file_id,revision:e.revision},t.signal),Zn(o,i,"download"),o.total_size!==e.size||o.strategy.kind!=="object_ranges"&&o.strategy.kind!=="framed_chunks")throw c("invalid_operation_response","The authority returned an incompatible download session.");if(o.strategy.kind==="framed_chunks"&&!this.framed)throw c("invalid_operation_response","Encrypted file chunk delivery is unavailable.");if(o.strategy.kind==="object_ranges"&&e.size>0&&!this.hosted)throw c("invalid_operation_response","Authenticated hosted file delivery is unavailable.")}catch(f){throw await this.abort(i),ze(f)}let r=o.strategy.kind==="framed_chunks"?o.strategy.chunk_size:o.strategy.part_size,a=Math.ceil(e.size/r),s=new ve,l=0,d=0,p=null,u=0,y=!1,h=async()=>{y||(y=!0,await p?.cancel().catch(()=>{}),p=null,await this.abort(i))},_=()=>{if(u!==e.size||`sha256:${s.digestHex()}`!==e.content_digest)throw c("invalid_operation_response","Downloaded file bytes failed integrity verification.")};return new ReadableStream({pull:async f=>{try{if(oe(t.signal),o.strategy.kind==="object_ranges")for(;;){if(!p){if(l>=a){_(),await h(),f.close();return}let R=l*r;d=Math.min(r,e.size-R),p=(await Lt(()=>this.hosted.downloadPart(o,l,d,t.signal),t.signal)).getReader()}let g=await p.read();if(g.done){if(p.releaseLock(),p=null,d!==0)throw c("invalid_operation_response","A hosted file range ended before its declared byte length.");l+=1;continue}if(!(g.value instanceof Uint8Array))throw c("invalid_operation_response","A hosted file range returned a non-byte chunk.");if(g.value.byteLength!==0){if(g.value.byteLength>d)throw c("invalid_operation_response","A hosted file range exceeded its declared byte length.");d-=g.value.byteLength,s.update(g.value),u+=g.value.byteLength,t.onProgress?.({phase:"downloading",transferredBytes:u,totalBytes:e.size}),f.enqueue(g.value);return}}if(l>=a){_(),await h(),f.close();return}let v=l*r,m=Math.min(r,e.size-v),P=await Lt(()=>this.framed.downloadChunk(o,l,t.signal),t.signal);if(P.byteLength!==m)throw c("invalid_operation_response","A file chunk had the wrong byte length.");s.update(P),u+=P.byteLength,l+=1,t.onProgress?.({phase:"downloading",transferredBytes:u,totalBytes:e.size}),l===a&&_(),f.enqueue(P),l===a&&(await h(),f.close())}catch(v){await h(),f.error(ze(v))}},cancel:h})}async downloadBytes(e,t={}){return new Uint8Array(await(await this.download(e,t)).arrayBuffer())}async move(e,t,i={}){this.requireAction("move");let o=i.mutationId??crypto.randomUUID(),r;try{r=await this.request("POST",`${encodeURIComponent(e.file_id)}/move`,{protocol_version:1,type:"move_file",mutation_id:o,file_id:e.file_id,if_revision:i.ifRevision??e.revision,from_path:e.path,path:t,update_references:!1},i.signal)}catch(a){throw ze(a)}if(r.protocol_version!==1||r.type!=="file_moved"||r.mutation_id!==o||r.file.file_id!==e.file_id||r.file.path!==t)throw c("invalid_operation_response","The authority returned an invalid file move receipt.");return r.file}async delete(e,t={}){this.requireAction("delete");let i=t.mutationId??crypto.randomUUID(),o;try{o=await this.request("POST",`${encodeURIComponent(e.file_id)}/delete`,{protocol_version:1,type:"delete_file",mutation_id:i,file_id:e.file_id,if_revision:t.ifRevision??e.revision,path:e.path},t.signal)}catch(r){throw ze(r)}if(o.protocol_version!==1||o.type!=="file_deleted"||o.mutation_id!==i||o.file_id!==e.file_id||o.previous_path!==e.path)throw c("invalid_operation_response","The authority returned an invalid file delete receipt.");return o}async uploadPart(e,t,i,o,r,a,s){for(let l=1;l<=we;l+=1){oe(s);try{let d=await this.request("POST",`uploads/${encodeURIComponent(e)}/parts`,{protocol_version:1,type:"prepare_file_upload_part",transfer_id:e,part_number:t+1,content_length:r},s);Oo(d,e,t,i,r,"PUT");let p=await fetch(d.url,{method:d.method,headers:To(d.headers),body:o,redirect:"error",signal:s});if(!p.ok)throw new Error(`Object upload failed with HTTP ${p.status}.`);let u=p.headers.get("etag");if(a&&!u)throw new Error("Multipart object upload did not return an ETag.");return{part_number:t+1,etag:u??""}}catch(d){if(s?.aborted||l===we)throw d}}throw new Error("Unreachable upload retry state.")}async tryReplayUploadCommit(e,t,i){try{return await this.commitUpload(e,t,i)}catch(o){if(o instanceof S&&o.code==="file_upload_incomplete")return null;throw o}}async commitUpload(e,t,i){let o;for(let r=1;r<=we;r+=1){oe(i);try{return await this.request("POST",`uploads/${encodeURIComponent(e)}/commit`,{protocol_version:1,type:"commit_file_upload",transfer_id:e,...t===void 0?{}:{parts:t}},i)}catch(a){if(o=a,i?.aborted||a instanceof S||r===we)throw a}}throw o}requireAction(e){if(!this.capability()?.actions.includes(e))throw c("not_authorized",`This connection is not authorized to ${e} files.`)}async abort(e){await this.request("DELETE",`transfers/${encodeURIComponent(e)}`).catch(()=>{})}};async function wo(n,e,t){let i=new ve;for(let o=0;o<n.size;o+=Jn){oe(e);let r=new Uint8Array(await n.slice(o,o+Jn).arrayBuffer());i.update(r),t(Math.min(n.size,o+r.byteLength))}return n.size===0&&t(0),i.digestHex()}function Co(n,e){if(n instanceof Blob)return e&&e!==n.type?n.slice(0,n.size,e):n;if(n instanceof ArrayBuffer)return new Blob([n],{type:e});let t=new Uint8Array(n.byteLength);return t.set(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)),new Blob([t.buffer],{type:e})}function Po(n){return n instanceof Blob?n.size:n.byteLength}async function So(n){return n instanceof Blob?new Uint8Array(await n.arrayBuffer()):n}function Wn(n=go){if(!Number.isInteger(n)||n<1||n>Qn)throw c("invalid_request",`File concurrency must be between 1 and ${Qn}.`);return n}function ko(n){if(!Number.isInteger(n)||n<1||n>1e3)throw c("invalid_request","File page size must be between 1 and 1000.");return n}function Zn(n,e,t){if(n.protocol_version!==1||n.type!=="file_transfer"||n.transfer_id!==e||n.direction!==t||!Number.isSafeInteger(n.total_size)||n.total_size<0||!Array.isArray(n.received)||!Ro(n))throw c("invalid_operation_response","The authority returned an invalid file transfer session.");let i=n.strategy.kind==="framed_chunks"?n.strategy.chunk_size:n.strategy.kind==="object_put"?Math.max(1,n.total_size):n.strategy.part_size,o=n.strategy.kind==="object_put"?1:Math.ceil(n.total_size/i);if(new Set(n.received).size!==n.received.length||n.received.some(a=>!Number.isSafeInteger(a)||a<0||a>=o))throw c("invalid_operation_response","The authority returned invalid transfer progress.");let r=n.uploaded_parts??[];if(!Array.isArray(r)||r.some((a,s)=>!Number.isSafeInteger(a?.part_number)||a.part_number<1||a.part_number>o||typeof a.etag!="string"||a.etag.length===0||a.etag.length>255||s>0&&r[s-1].part_number>=a.part_number)||(n.strategy.kind==="object_multipart"?r.length!==n.received.length||r.some((a,s)=>a.part_number-1!==n.received[s]):r.length!==0))throw c("invalid_operation_response","The authority returned invalid uploaded part receipts.")}function Ro(n){return n.strategy.kind==="framed_chunks"?n.protection==="grant_aead_v1"&&Number.isSafeInteger(n.strategy.chunk_size)&&n.strategy.chunk_size>0:n.protection!=="transport_tls"?!1:n.strategy.kind==="object_put"?!0:Number.isSafeInteger(n.strategy.part_size)&&n.strategy.part_size>0}function Ao(n,e,t){return Math.min(e,Math.max(0,n-t*e))}async function Lt(n,e){for(let t=1;t<=we;t+=1){oe(e);try{return await n()}catch(i){if(e?.aborted||t===we)throw i}}throw new Error("Unreachable file chunk retry state.")}function Oo(n,e,t,i,o,r){let a;try{a=new URL(n.url)}catch{throw c("invalid_operation_response","The authority returned an invalid object URL.")}if(n.protocol_version!==1||n.type!=="file_part"||n.transfer_id!==e||n.part_index!==t||n.offset!==i||n.content_length!==o||n.method.toUpperCase()!==r||a.protocol!=="https:"&&!(a.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(a.hostname))||a.username||a.password)throw c("invalid_operation_response","The authority returned an invalid prepared file part.")}function To(n){let e=new Headers;for(let[t,i]of Object.entries(n))["host","content-length"].includes(t.toLowerCase())||e.set(t,i);return e}async function Io(n,e,t){let i=new Array(n),o=0;return await Promise.all(Array.from({length:Math.min(n,e)},async()=>{for(;o<n;){let r=o;o+=1,i[r]=await t(r)}})),i}function oe(n){if(n?.aborted)throw c("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:n.reason})}function ze(n){return n instanceof S?n:typeof DOMException<"u"&&n instanceof DOMException&&n.name==="AbortError"?c("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:n}):c("temporarily_unavailable","The file transfer could not be completed.",{cause:n})}var re=["describe","changes","read","query"];var De=class{constructor(e,t){this.internals=e;this.collectionId=t;this.transport=new st({serverUrl:e.serverUrl,storage:e.storage,keyStore:e.keyStore,directAccessMode:e.directAccessMode,loopbackUrl:e.loopbackUrl,collectionId:t,internals:e,onChange:()=>this.emitConnection()}),this.files=new Fe(()=>this.fileCapability,(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)}),this.collectionClient=new Ee({operation:(i,o,r)=>this.transport.performOperation(i,o,r)}),this.notifications=new nt({serverUrl:e.serverUrl,storage:e.storage,authorizedToken:()=>this.transport.authorizedToken(),register:()=>this.internals.register(),notificationKey:i=>e.notificationKey(t,i)})}internals;collectionId;collectionClient;notifications;transport;files;connectionListeners=new Set;get displayName(){return this.transport.currentToken()?.collectionName??`Collection ${this.collectionId.slice(0,8)}`}get operations(){return[...this.transport.currentToken()?.operations??[]]}get scope(){return this.transport.currentToken()?.scope??null}get fileCapability(){return this.transport.currentToken()?.fileCapability??null}get directAccess(){return this.transport.directAccess}get route(){return this.transport.route}register(){return A(()=>this.internals.register(),Z)}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}:{},route:this.transport.route,directAccess:this.transport.directAccess}:null}authorizationCapabilities(e=re){let t=this.operations,i=B(e).filter(o=>!t.includes(o));return{authorized:this.info()!==null,sufficient:this.info()!==null&&i.length===0,collectionId:this.collectionId,grantedOperations:t,missingOperations:i}}hasOperations(e){return this.authorizationCapabilities(e).sufficient}authorize(e={}){return A(()=>this.internals.authorize({...e,target:{kind:"collection",collectionId:this.collectionId}}),ee)}async requestOperations(e,t={}){let i=this.authorizationCapabilities(e);return i.sufficient?E({kind:"unchanged",connection:this}):this.authorize({...t,operations:B([...i.grantedOperations,...i.missingOperations])})}onConnectionChange(e){return this.connectionListeners.add(e),e(this.info()),()=>this.connectionListeners.delete(e)}notifyStorageChanged(){this.transport.notifyStorageChanged()}checkDirectAccess(){return A(()=>this.transport.checkDirectAccess(),Xe)}requestDirectAccess(){return A(()=>this.transport.requestDirectAccess(),Xe)}disableDirectAccess(){this.transport.disableDirectAccess()}sync(){let e=this.transport.currentToken();if(!e)return null;let t=e.collectionId;if(!e.authority){if(!e.grantId||!e.operations.includes("sync"))return null;let o=e.grantId;return{collectionId:t,replicaId:o,transport:{openSession:()=>this.transport.performOperation("sync",{action:"open_session"}),snapshot:(r,a)=>this.transport.performOperation("sync",{action:"snapshot",snapshot_id:r,...a?{page:a}:{}}),changes:(r,a=200)=>this.transport.performOperation("sync",{action:"changes",after:r,limit:a}),mutate:r=>this.transport.performOperation("sync",{action:"mutate",mutation:r})}}}let i=e.authority.replicaId;return{collectionId:t,replicaId:i,transport:{openSession:()=>this.transport.performAuthoritySyncRequest(t,i,"POST","sessions"),snapshot:(o,r)=>{let a=new URLSearchParams({snapshot_id:o});return r&&a.set("page",r),this.transport.performAuthoritySyncRequest(t,i,"GET",`snapshot?${a}`)},changes:(o,r=200)=>this.transport.performAuthoritySyncRequest(t,i,"GET",`changes?${new URLSearchParams({after:String(o),limit:String(r)})}`),mutate:o=>this.transport.performAuthoritySyncRequest(t,i,"POST","mutations",o)}}}registerNotifications(e){return A(()=>this.notifications.registerNotifications(e),ye)}registerNativeNotifications(e){return A(()=>this.notifications.registerNativeNotifications(e),ye)}unregisterNativeNotifications(){return A(()=>this.notifications.unregisterNativeNotifications(),ye)}unregisterNotifications(e){return A(()=>this.notifications.unregisterNotifications(e),ye)}forget(){let e=this.transport.currentToken();this.internals.removeToken(this.collectionId,e?.keyHandle,"not_authorized"),this.transport.notifyStorageChanged()}describe(){return this.collectionClient.describe()}changes(e={},t){return this.collectionClient.changes(e,t)}read(e){return this.collectionClient.read(e)}query(e={},t){return this.collectionClient.query(e,t)}queryPages(e={},t={}){return this.collectionClient.queryPages(e,t)}queryAll(e={},t={}){return this.collectionClient.queryAll(e,t)}listViews(){return this.collectionClient.listViews()}executeView(e){return this.collectionClient.executeView(e)}readViewSource(e){return this.collectionClient.readViewSource(e)}createViewSource(e){return this.collectionClient.createViewSource(e)}updateViewSource(e){return this.collectionClient.updateViewSource(e)}deleteViewSource(e){return this.collectionClient.deleteViewSource(e)}create(e){return this.collectionClient.create(e)}update(e){return this.collectionClient.update(e)}delete(e,t){return this.collectionClient.delete(e,t)}preflightDelete(e,t){return this.collectionClient.preflightDelete(e,t)}rename(e,t){return this.collectionClient.rename(e,t)}preflightRename(e,t){return this.collectionClient.preflightRename(e,t)}async renameWithProgress(e,t={}){let i=Date.now(),o=this.pendingMutation()?.operation==="rename",r,a=(s,l,d=0)=>{t.onProgress?.({operation:"rename",state:s,elapsedMs:Date.now()-i,cancellable:l,resumed:o,completedUnits:d,...r?{estimate:r}:{}})};try{ie(t.signal),a("preflighting",!0);let s=t.preflight?E(t.preflight):await this.preflightRename(e,{signal:t.signal});if(!s.ok)return s;let l=s.value;try{Sn(e,l)}catch(u){if(u instanceof S)return T(u.problem);throw u}r=Rn(e,l),a("ready",!0),ie(t.signal);let d=this.transport.hasResumableMutationTransport();a("applying",d);let p=await this.rename(e,d?{signal:t.signal}:void 0);return p.ok&&a("completed",!1,r.totalUnits),p}catch(s){if(Mt(s,t.signal)&&a("cancelled",!1),s instanceof S)return T(s.problem);throw s}}async deleteWithProgress(e,t={}){let i=Date.now(),o=this.pendingMutation()?.operation==="delete",r,a=(s,l,d=0)=>{t.onProgress?.({operation:"delete",state:s,elapsedMs:Date.now()-i,cancellable:l,resumed:o,completedUnits:d,...r?{estimate:r}:{}})};try{ie(t.signal),a("preflighting",!0);let s=t.preflight?E(t.preflight):await this.preflightDelete(e,{signal:t.signal});if(!s.ok)return s;let l=s.value;try{kn(e,l)}catch(u){if(u instanceof S)return T(u.problem);throw u}r=An(l),a("ready",!0),ie(t.signal);let d=this.transport.hasResumableMutationTransport();a("applying",d);let p=await this.delete(e,d?{signal:t.signal}:void 0);return p.ok&&a("completed",!1,r.totalUnits),p}catch(s){if(Mt(s,t.signal)&&a("cancelled",!1),s instanceof S)return T(s.problem);throw s}}pendingMutation(){return this.transport.pendingMutation()}resumePendingMutation(e,t){return A(()=>this.transport.resumePendingMutation(e,t),I)}validate(e={}){return this.collectionClient.validate(e)}readType(e){return this.collectionClient.readType(e)}createType(e){return this.collectionClient.createType(e)}updateType(e){return this.collectionClient.updateType(e)}assessTypePack(e){return this.collectionClient.assessTypePack(e)}applyTypePack(e){return this.collectionClient.applyTypePack(e)}listTimers(e){return this.collectionClient.listTimers(e)}putTimer(e){return this.collectionClient.putTimer(e)}cancelTimer(e){return this.collectionClient.cancelTimer(e)}reconcileTimers(e){return this.collectionClient.reconcileTimers(e)}watch(e={}){return this.collectionClient.watch(e)}operation(e,t,i){return this.collectionClient.operation(e,t,i)}emitConnection(){let e=this.info();for(let t of this.connectionListeners)t(e)}};async function Nt(n,e,t,i,o){if(!n||typeof n!="object"||Array.isArray(n))throw c("invalid_first_contact","The authorization service returned an invalid first-contact challenge.");let r=n,a=await Y(t);if(r.application_id!==e.id||r.application_installation_id!==a||r.application_agreement_public_key!==t.agreementPublicKey||r.application_signing_public_key!==t.signingPublicKey)throw c("invalid_first_contact","The first-contact challenge does not match this application installation.");let s=JSON.stringify(r);if(s===o)return o;if(!i.onFirstContact)throw c("first_contact_handler_required","Local access requires the application to display a first-contact comparison code.");let l;try{l=await Je(r,"application",t)}catch(d){throw c("invalid_first_contact","The authorization service returned an invalid first-contact challenge.",{cause:d})}return await i.onFirstContact({binding:r,authenticationString:l,applicationId:r.application_id,connectorId:r.connector_id}),s}async function qt(n,e,t){let i=`application-installation:${e}:${t.id}`,o=await n.get(i);if(o)return o;try{return await n.create(i)}catch(r){let a=await n.get(i);if(a)return a;throw r}}var lt=class{serverUrl;manifest;manifestSource;redirectUri;storage;relayEncryption;keyStore;directAccessMode;loopbackUrl;navigate;credentialStorage;application=null;completionPromises=new Map;connectionCache=new Map;listeners=new Set;invalidatedConnections=new Map;constructor(e){this.serverUrl=Mn(e.serverUrl),this.manifest=e.manifest??Un(),this.manifestSource=typeof this.manifest=="string"?this.manifest:this.manifest.distribution==="portable"?`bundle:${this.manifest.id}:${Nn(this.manifest)}`:`bundle:${this.manifest.id}`;let t=Ln(this.manifest);this.redirectUri=e.redirectUri??(typeof this.manifest!="string"&&this.manifest.distribution==="portable"?"":zn()),this.storage=e.storage??Dn(t),this.relayEncryption=e.relayEncryption??"required",this.keyStore=e.keyStore??(t?new de:new le),this.credentialStorage=e.storage||e.keyStore?"custom":this.storage instanceof _e?"memory":"persistent",this.directAccessMode=e.directAccess??"auto",this.loopbackUrl=Tn(e.loopbackUrl??`http://127.0.0.1:${tn}`),this.navigate=e.navigate,typeof window<"u"&&this.storage===window.localStorage&&window.addEventListener("storage",i=>{i.storageArea!==this.storage||!i.key?.startsWith(this.storagePrefix())||(this.connectionCache.get(Eo(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}}async register(){if(this.application)return this.application;let e=await $(`${this.serverUrl}/v1/apps/register`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({manifest:await this.loadManifest()})},"temporarily_unavailable","Application registration is temporarily unavailable."),t=await e.json();if(!e.ok)throw k(t,"discovery_failed","Application discovery failed.",e.status);return this.application=t.application,this.application}async loadManifest(){if(typeof this.manifest!="string")return this.manifest;let e=this.manifest,t;try{t=await fetch(e,{headers:{accept:"application/json"}})}catch(i){throw c("manifest_load_failed","The bundled application declaration could not be loaded.",{cause:i})}if(!t.ok)throw c("manifest_load_failed",`The bundled application declaration returned HTTP ${t.status}.`,{status:t.status});try{return await t.json()}catch(i){throw c("invalid_application_manifest","The bundled application declaration is not valid JSON.",{cause:i})}}async authorize(e={}){if(typeof location>"u"&&!this.navigate&&!e.openVerification)throw c("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.register()}catch(r){throw i?.close(),r}return o.distribution==="portable"?(e.openVerification&&i?.close(),this.authorizePortable(o,e,e.openVerification?null:i)):this.authorizeWeb(o,e,i)}async authorizeWeb(e,t,i){let{verifier:o,challenge:r}=await Ue(),a=N(24),s=crypto.randomUUID(),l=t.target?.kind==="collection"?t.target.collectionId:void 0,d=`grant:${e.id}:${a}`,p=await this.keyStore.create(d),u=await qt(this.keyStore,this.serverUrl,e),y=B(t.operations??re),h=new Date,_=await Te({protocol_version:ke,authorization_id:s,application_id:e.id,application_manifest_digest:e.manifest_digest,application_installation_id:await Y(u),installation_agreement_public_key:u.agreementPublicKey,installation_signing_public_key:u.signingPublicKey,grant_agreement_public_key:p.agreementPublicKey,grant_signing_public_key:p.signingPublicKey,flow:"authorization_code",authorization_nonce:N(32),issued_at:h.toISOString(),expires_at:new Date(h.getTime()+600*1e3).toISOString(),redirect_uri:this.redirectUri,state:a,code_challenge:r,requested_operations:y,...e.requirements?.files?{requested_files:e.requirements.files}:{},...l?{collection_id:l}:{}},u),f={version:1,verifier:o,state:a,clientId:e.id,redirectUri:this.redirectUri,relayEncryption:this.relayEncryption,collectionId:l,returnTo:t.returnTo,keyHandle:d,installationKeyHandle:u.handle,authorizationId:s,applicationAgreementPublicKey:p.agreementPublicKey,applicationSigningPublicKey:p.signingPublicKey};this.storage.setItem(this.pendingKey(a),JSON.stringify(f));try{let v=await fetch(`${this.serverUrl}/oauth/authorization_request`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e.id,redirect_uri:this.redirectUri,code_challenge:r,code_challenge_method:"S256",state:a,operations:y.join(","),...l?{collection_id:l}:{},application_authorization:JSON.stringify(_)}),signal:t.signal}),m=await v.json();if(!v.ok)throw k(m,"device_authorization_failed","Application authorization could not be started.",v.status);if(typeof m.authorization_uri!="string"||m.authorization_id!==s||!Number.isInteger(m.expires_in)||!Number.isInteger(m.interval)||m.expires_in<=0||m.interval<=0)throw c("invalid_device_authorization_response","The authorization service returned an invalid polling response.");if(this.navigate)await this.navigate(m.authorization_uri);else if(i)i.location.href=m.authorization_uri;else throw c("browser_required","The approval window was blocked. Allow popups for this application and try again.");let P=Date.now()+m.expires_in*1e3,g=m.interval,R="";for(;Date.now()<P;){if(await fe(g*1e3,t.signal),t.signal?.aborted)throw c("authorization_cancelled","Application authorization was cancelled.");let x;try{x=await fetch(`${this.serverUrl}/oauth/authorization_status`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e.id,authorization_id:s,code_verifier:o}),signal:t.signal})}catch(j){if(t.signal?.aborted)throw c("authorization_cancelled","Application authorization was cancelled.",{cause:j});continue}let w=await x.json();if(!x.ok){let j=ge(w);if(j==="authorization_pending"){w.first_contact&&(R=await Nt(w.first_contact,e,u,t,R));continue}if(j==="slow_down"){g+=2;continue}throw k(w,"token_exchange_failed","Application authorization could not be completed.",x.status)}if(typeof w.authorization_redirect!="string")throw c("invalid_token_response","The authorization service returned an invalid completion response.");let F=await this.performAuthorizationCompletion(w.authorization_redirect,a);return i?.close(),{kind:"connected",...F}}throw c("expired_token","The application authorization expired.")}catch(v){throw i?.close(),this.storage.removeItem(this.pendingKey(a)),await this.keyStore.delete(d),t.signal?.aborted?c("authorization_cancelled","Application authorization was cancelled.",{cause:v}):v}}async authorizePortable(e,t,i){if(this.relayEncryption!=="required")throw i?.close(),c("encryption_required","Downloaded applications require encrypted relay authorization.");let{verifier:o,challenge:r}=await Ue(),a=`grant:${e.id}:${N(24)}`,s=await this.keyStore.create(a),l=await qt(this.keyStore,this.serverUrl,e),d=B(t.operations??re),p=crypto.randomUUID(),u=new Date,y=await Te({protocol_version:ke,authorization_id:p,application_id:e.id,application_manifest_digest:e.manifest_digest,application_installation_id:await Y(l),installation_agreement_public_key:l.agreementPublicKey,installation_signing_public_key:l.signingPublicKey,grant_agreement_public_key:s.agreementPublicKey,grant_signing_public_key:s.signingPublicKey,flow:"device_code",authorization_nonce:N(32),issued_at:u.toISOString(),expires_at:new Date(u.getTime()+600*1e3).toISOString(),code_challenge:r,requested_operations:d,...e.requirements?.files?{requested_files:e.requirements.files}:{},...t.target?.kind==="collection"?{collection_id:t.target.collectionId}:{}},l),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(","),...t.target?.kind==="collection"?{collection_id:t.target.collectionId}:{},code_challenge:r,code_challenge_method:"S256",application_authorization:JSON.stringify(y)})}),_=await h.json()}catch(P){throw i?.close(),await this.keyStore.delete(a),c("device_authorization_failed","Downloaded application authorization could not be started.",{cause:P})}if(!h.ok)throw i?.close(),await this.keyStore.delete(a),k(_,"device_authorization_failed","Downloaded application authorization could not be started.",h.status);let f;try{f=xn(_)}catch(P){throw i?.close(),await this.keyStore.delete(a),t.signal?.aborted?c("authorization_cancelled","Downloaded application authorization was cancelled.",{cause:P}):P}if(t.onDeviceCode?.(f),t.openVerification)await t.openVerification(f);else if(i)try{i.location.href=f.verificationUriComplete}catch{}else throw await this.keyStore.delete(a),c("approval_window_blocked","The approval window was blocked. Show the provided verification link and code, then try again.",{details:{user_code:f.userCode,verification_uri:f.verificationUri,verification_uri_complete:f.verificationUriComplete,expires_at:f.expiresAt,interval_seconds:f.intervalSeconds}});let v=f.intervalSeconds,m="";try{for(;Date.now()<f.expiresAt;){if(await fe(v*1e3,t.signal),t.signal?.aborted)throw c("authorization_cancelled","Downloaded application authorization was cancelled.");let P;try{P=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:t.signal})}catch(F){if(t.signal?.aborted)throw c("authorization_cancelled","Downloaded application authorization was cancelled.",{cause:F});continue}let g=await P.json();if(!P.ok){let F=ge(g);if(F==="authorization_pending"){g.first_contact&&(m=await Nt(g.first_contact,e,l,t,m));continue}if(F==="slow_down"){v+=5;continue}throw k(g,"token_exchange_failed","Downloaded application authorization could not be completed.",P.status)}let R=Ze(g.authority,g.collection_id),x=g.encryption&&g.encryption.protocol_version===ce&&g.encryption.suite===Re&&g.encryption.application_agreement_public_key===s.agreementPublicKey;if(g.application_origin!=="null")throw c("invalid_token_response","Authorization did not bind the portable grant to its opaque application origin.");if(g.authority&&(!R||g.encryption!=null||g.authority.proof_public_key!==s.signingPublicKey))throw c("invalid_token_response","Authorization returned a remote authority capability that is not bound to this portable grant key.");if(!g.authority&&!x)throw c("encryption_required","Authorization did not establish the expected key-bound local portable grant.");let w=this.storeTokenResponse(g,e.id,a);if(t.target?.kind==="collection"&&t.target.collectionId!==w.collectionId)throw this.removeToken(w.collectionId,w.keyHandle),c("collection_mismatch","The approved collection does not match the collection requested by this link.");return i?.close(),{kind:"connected",connection:this.connection(w.collectionId),...t.returnTo?{returnTo:t.returnTo}:{}}}throw c("expired_token","The downloaded application authorization code expired.")}catch(P){throw i?.close(),await this.keyStore.delete(a),t.signal?.aborted?c("authorization_cancelled","Downloaded application authorization was cancelled.",{cause:P}):P}}completeAuthorization(e){let t=new URL(e).searchParams.get("state");if(!t)return Promise.reject(c("invalid_callback","Authorization callback is missing its state."));let i=this.completionPromises.get(t);if(i)return i;let r=this.performAuthorizationCompletion(e,t).finally(()=>{this.completionPromises.get(t)===r&&this.completionPromises.delete(t)});return this.completionPromises.set(t,r),r}async performAuthorizationCompletion(e,t){let i=new URL(e),o=i.searchParams.get("code"),r=this.pendingKey(t),a=M(this.storage.getItem(r));if(!a||a.version!==1||t!==a.state)throw c("invalid_callback","Authorization callback is missing or does not match this browser session.");if(i.searchParams.has("error"))throw a.keyHandle&&await this.keyStore.delete(a.keyHandle),this.storage.removeItem(r),D(i.searchParams.get("error")??"access_denied",i.searchParams.get("error_description")??"Collection access was not approved.",{details:a.returnTo?{return_to:a.returnTo}:void 0});if(!o)throw c("invalid_callback","Authorization callback is missing its code.");let s=await $(`${this.serverUrl}/oauth/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:o,client_id:a.clientId,redirect_uri:a.redirectUri,code_verifier:a.verifier})},"temporarily_unavailable","Authorization completion is temporarily unavailable."),l=await s.json();if(!s.ok)throw k(l,"token_exchange_failed","Authorization could not be completed.",s.status);if(a.relayEncryption==="required"&&!l.authority&&(!l.encryption||!a.keyHandle||l.encryption.application_agreement_public_key!==a.applicationAgreementPublicKey))throw a.keyHandle&&await this.keyStore.delete(a.keyHandle),this.storage.removeItem(r),c("encryption_required","Authorization did not establish the required encrypted relay grant.");if(l.authority?.proof_public_key){if(!a.keyHandle||!a.applicationSigningPublicKey||l.authority.proof_public_key!==a.applicationSigningPublicKey)throw a.keyHandle&&await this.keyStore.delete(a.keyHandle),this.storage.removeItem(r),c("invalid_token_response","Authorization returned a remote authority capability bound to another application key.")}else l.authority&&a.keyHandle&&await this.keyStore.delete(a.keyHandle);let d=this.storeTokenResponse(l,a.clientId,l.authority?.proof_public_key?a.keyHandle:l.authority?void 0:a.keyHandle);if(a.collectionId&&a.collectionId!==d.collectionId)throw this.removeToken(d.collectionId,d.keyHandle),this.storage.removeItem(r),c("collection_mismatch","The approved collection does not match the collection requested by this link.");return this.storage.removeItem(r),{connection:this.connection(d.collectionId),...a.returnTo?{returnTo:a.returnTo}:{}}}connections(){let e=[];for(let t of this.connectionIds()){let i=this.connection(t)?.info();i&&e.push(i)}return e.sort((t,i)=>t.displayName.localeCompare(i.displayName)||t.collectionId.localeCompare(i.collectionId))}connection(e){if(!this.storage.getItem(this.tokenKey(e)))return null;let t=this.connectionCache.get(e);return t||(t=new De(this,e),this.connectionCache.set(e,t)),t.info()?t:null}unavailableReason(e){return this.invalidatedConnections.get(e)??null}onConnectionsChange(e){return this.listeners.add(e),e(this.connections()),()=>this.listeners.delete(e)}storeTokenResponse(e,t,i){let o=e.collection_id;if(typeof o!="string")throw c("invalid_token_response","Authorization returned no collection ID.");let r=tt(e.scope);if(!r)throw c("invalid_token_response","Authorization returned no valid collection scope.");if(e.authority&&!Ze(e.authority,o))throw c("invalid_token_response","Authorization returned an invalid remote authority capability.");if(e.authority&&e.encryption)throw c("invalid_token_response","Authorization returned conflicting collection transports.");if(e.file_capability!==null&&e.file_capability!==void 0&&!et(e.file_capability))throw c("invalid_token_response","Authorization returned an invalid file capability.");if(e.encryption){try{W(e.encryption)}catch{throw c("invalid_token_response","Authorization returned an invalid encrypted relay binding.")}if(e.encryption.collection_id!==o||typeof e.grant_id!="string"||e.grant_id.length===0)throw c("invalid_token_response","Authorization returned an encrypted relay binding for another grant.")}let a=M(this.storage.getItem(this.tokenKey(o)));if(a?.encryption&&e.encryption&&a.keyHandle&&a.keyHandle===i&&(a.grantId!==e.grant_id||a.encryption.connector_id!==e.encryption.connector_id||a.encryption.connector_agreement_public_key!==e.encryption.connector_agreement_public_key||a.encryption.application_agreement_public_key!==e.encryption.application_agreement_public_key))throw c("connector_identity_changed","The connector identity changed during authorization renewal. Reauthorize before sending collection data.");a?.keyHandle&&a.keyHandle!==i&&this.keyStore.delete(a.keyHandle).catch(()=>{});let s={version:1,accessToken:e.access_token,refreshToken:e.refresh_token,clientId:t,collectionId:o,collectionName:e.collection_name??`Collection ${o.slice(0,8)}`,operations:e.operations,scope:r,expiresAt:Date.now()+e.expires_in*1e3,refreshExpiresAt:e.refresh_expires_in?Date.now()+e.refresh_expires_in*1e3:void 0,grantId:e.grant_id,encryption:e.encryption??void 0,fileCapability:e.file_capability??void 0,applicationOrigin:e.application_origin??this.defaultApplicationOrigin(),keyHandle:i,savedAt:Date.now(),authority:e.authority?{operationsUrl:e.authority.operations_url,syncUrl:e.authority.sync_url,filesUrl:e.authority.files_url,replicaId:e.authority.replica_id,accessToken:e.authority.access_token,proofPublicKey:e.authority.proof_public_key}:void 0};return this.storage.setItem(this.tokenKey(o),JSON.stringify(s)),this.addConnectionId(o),this.invalidatedConnections.delete(o),this.connectionCache.delete(o),this.emitConnections(),s}removeToken(e,t,i="authorization_lost"){this.invalidatedConnections.set(e,i),t&&this.keyStore.delete(t).catch(()=>{}),this.storage.removeItem(this.tokenKey(e)),this.storage.removeItem(this.pendingMutationKey(e));for(let o of["web_push","fcm"])this.storage.removeItem(this.notificationKey(e,o));this.storage.setItem(this.connectionsKey(),JSON.stringify({version:1,collectionIds:this.connectionIds().filter(o=>o!==e)})),this.connectionCache.delete(e),this.emitConnections()}tokenKey(e){return`${this.storagePrefix()}:token:${e}`}pendingMutationKey(e){return`${this.storagePrefix()}:pending-mutation:${e}`}notificationKey(e,t="web_push"){return`${this.storagePrefix()}:notifications:${e}:${t}`}directPreferenceKey(){return`mdbase-connect:direct:${this.defaultApplicationOrigin()}`}defaultApplicationOrigin(){if(typeof this.manifest!="string"&&this.manifest.distribution==="portable"||this.application?.distribution==="portable")return"null";let e=new URL(this.redirectUri);if(["http:","https:"].includes(e.protocol))return e.origin;if(typeof location<"u")return location.origin;if(this.manifest&&typeof this.manifest!="string")return new URL(this.manifest.homepage).origin;try{return new URL(this.manifestSource).origin}catch{return""}}pendingKey(e){return`${this.storagePrefix()}:pending:${e}`}storagePrefix(){return`mdbase-connect:${this.serverUrl}:${this.manifestSource}`}connectionsKey(){return`${this.storagePrefix()}:connections`}connectionIds(){let e=M(this.storage.getItem(this.connectionsKey()));return e?.version===1&&Array.isArray(e.collectionIds)&&e.collectionIds.every(t=>typeof t=="string")?e.collectionIds:[]}addConnectionId(e){this.storage.setItem(this.connectionsKey(),JSON.stringify({version:1,collectionIds:[...new Set([...this.connectionIds(),e])]}))}emitConnections(){let e=this.connections();for(let t of this.listeners)t(e)}};function Eo(n){let e=":token:",t=n.lastIndexOf(e);return t<0?"":n.slice(t+e.length)}function Le(n){for(let e of["code","state","error","error_description"])n.searchParams.delete(e);return n}function dt(n){let e;try{e=new URL(n)}catch{return!1}return e.searchParams.has("state")&&(e.searchParams.has("code")||e.searchParams.has("error"))}function ei(n){if(!n.details||typeof n.details!="object"||Array.isArray(n.details))return;let e=n.details.return_to;return typeof e=="string"?e:void 0}var Ne=class{constructor(e,t){this.connect=e;this.operations=B(t.operations??re),this.selection=t.selection,this.autoSelect=t.autoSelect??"only",this.snapshot={status:"unselected",connections:[]},this.refresh()}connect;operations;selection;autoSelect;listeners=new Set;snapshot;snapshotKey="";stopConnections;stopSelection;stopActiveConnection;activeCollectionId=null;unavailableReason="not_authorized";started=!1;refreshing=!1;refreshQueued=!1;transactionDepth=0;callbackPromise=null;async start(){this.started||(this.started=!0,this.stopConnections=this.connect.onConnectionsChange(()=>this.refresh()),this.stopSelection=this.selection.subscribe(()=>{this.unavailableReason="not_authorized",this.refresh()}));let e=this.selection.authorizationCallback();if(e){let t=await this.handleAuthorizationCallback(e);if(!t.ok)return t}else this.autoSelectOnlyConnection();return this.refresh(),E(this.snapshot)}destroy(){this.stopConnections?.(),this.stopSelection?.(),this.stopActiveConnection?.(),this.stopConnections=void 0,this.stopSelection=void 0,this.stopActiveConnection=void 0,this.activeCollectionId=null,this.started=!1}getSnapshot(){return this.snapshot}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}select(e,t={}){let i=this.connect.connection(e);return i?(this.unavailableReason="not_authorized",this.selection.select(e,t),this.refresh(),E(i)):T(z("unknown_collection","This collection is not authorized for this application."))}clearSelection(e={}){this.unavailableReason="not_authorized",this.selection.select(null,e),this.refresh()}forget(e){this.transactionDepth+=1;try{let t=this.selection.selectedCollectionId()===e;this.connect.connection(e)?.forget(),t&&this.selection.select(null,{history:"replace"})}finally{this.transactionDepth-=1,this.refresh()}}async authorize(e,t={}){let i=this.selection.selectedCollectionId();if(e==="selected"&&!i)return T(z("collection_not_selected","Choose a collection before updating its access."));let o=typeof e=="object"?e.collectionId:e==="selected"?i:null;this.transactionDepth+=1;try{let r=await this.connect.authorize({...t,operations:this.operations,target:o===null?{kind:"choose"}:{kind:"collection",collectionId:o},returnTo:this.selection.authorizationReturnTo()});return r.ok&&r.value.kind==="connected"&&this.selection.finishAuthorization(r.value.returnTo,r.value.connection.collectionId),r}finally{this.transactionDepth-=1,this.refresh()}}async ensureOperations(e){let t=this.snapshot;if(t.status!=="ready")return T(z("collection_not_ready","Choose an authorized collection first."));let i=B(e),o=t.connection.authorizationCapabilities(i);if(o.sufficient)return E({kind:"unchanged",connection:t.connection});this.transactionDepth+=1;try{let r=await this.connect.authorize({operations:B([...o.grantedOperations,...o.missingOperations]),target:{kind:"collection",collectionId:t.collectionId},returnTo:this.selection.authorizationReturnTo()});return r.ok&&r.value.kind==="connected"&&this.selection.finishAuthorization(r.value.returnTo,r.value.connection.collectionId),r}finally{this.transactionDepth-=1,this.refresh()}}handleAuthorizationCallback(e){if(!dt(e))return Promise.resolve(T(z("invalid_callback","This URL is not an authorization callback.")));if(this.callbackPromise)return this.callbackPromise;this.transactionDepth+=1;let t=this.connect.completeAuthorization(e).then(i=>{if(!i.ok){let r=ei(i.problem);return this.selection.clearAuthorizationCallback(r),this.refresh(),i}let o=i.value;return this.unavailableReason="not_authorized",this.selection.finishAuthorization(o.returnTo,o.connection.collectionId),this.refresh(),E(o.connection,i.diagnostics)}).catch(i=>{throw this.selection.clearAuthorizationCallback(),this.refresh(),i}).finally(()=>{this.transactionDepth-=1,this.refresh(),this.callbackPromise===t&&(this.callbackPromise=null)});return this.callbackPromise=t,t}autoSelectOnlyConnection(){if(this.autoSelect!=="only"||this.selection.selectedCollectionId())return;let e=this.connect.connections();e.length===1&&this.selection.select(e[0].collectionId,{history:"replace"})}refresh(){if(this.transactionDepth>0){this.refreshQueued=!0;return}if(this.refreshing){this.refreshQueued=!0;return}this.refreshing=!0;try{do this.refreshQueued=!1,this.refreshOnce();while(this.refreshQueued)}finally{this.refreshing=!1}}refreshOnce(){let e=this.selection.selectedCollectionId(),t=this.connect.connections(),i=e?this.connect.connection(e):null;i?.collectionId!==this.activeCollectionId&&(this.stopActiveConnection?.(),this.activeCollectionId=i?.collectionId??null,this.stopActiveConnection=i?.onConnectionChange(a=>{!a&&this.selection.selectedCollectionId()===i.collectionId&&(this.unavailableReason="authorization_lost"),this.refresh()}));let o;if(!e)o={status:"unselected",connections:t};else if(!i||!i.info())o={status:"unavailable",collectionId:e,reason:this.connect.unavailableReason(e)??this.unavailableReason,connections:t};else{let a=i.info();o={status:"ready",collectionId:e,connection:i,info:a,access:i.authorizationCapabilities(this.operations),connections:t}}let r=xo(o);if(r!==this.snapshotKey){this.snapshot=o,this.snapshotKey=r;for(let a of this.listeners)a()}}};function xo(n){return n.status==="unselected"?JSON.stringify({status:n.status,connections:n.connections}):n.status==="unavailable"?JSON.stringify({status:n.status,collectionId:n.collectionId,reason:n.reason,connections:n.connections}):JSON.stringify({status:n.status,collectionId:n.collectionId,info:n.info,access:n.access,connections:n.connections})}var Bt=class{internals;constructor(e){this.internals=new lt(e)}register(){return A(()=>this.internals.register(),Z)}authorize(e={}){return A(()=>this.internals.authorize(e),ee)}createSession(e){return new Ne(this,e)}environment(){return this.internals.environment()}completeAuthorization(e){return A(()=>this.internals.completeAuthorization(e??Fn()),ee)}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()}};function ti(n){if(!n||typeof n!="object")throw c("invalid_push_payload","The push payload is not an object.");let e=n;if(e.type!=="mdbase.notification"||e.version!==1||typeof e.signal_id!="string"||typeof e.criterion_id!="string"||typeof e.cursor!="string"||!e.presentation||typeof e.presentation.title!="string")throw c("invalid_push_payload","The push payload is not an mdbase notification.");return e}function Mo(n){if(!n||typeof n!="object")throw c("invalid_push_payload","The native notification data is not an object.");let e=n;if(e.type!=="mdbase.notification"||e.version!==1&&e.version!=="1"||typeof e.signal_id!="string"||typeof e.criterion_id!="string"||typeof e.cursor!="string")throw c("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 Uo(n,e){let t=ti(e);return n.showNotification(t.presentation.title,{...t.presentation.body?{body:t.presentation.body}:{},...t.presentation.tag?{tag:t.presentation.tag}:{},data:{type:t.type,signal_id:t.signal_id,criterion_id:t.criterion_id,cursor:t.cursor}})}var Kt=class{collectionParameter;fallbackPath;listeners=new Set;handlePopState=()=>this.emit();constructor(e={}){this.collectionParameter=e.collectionParameter??"collection",this.fallbackPath=e.fallbackPath??"/"}selectedCollectionId(){return this.currentUrl().searchParams.get(this.collectionParameter)}select(e,t={}){let i=Le(this.currentUrl());e?i.searchParams.set(this.collectionParameter,e):i.searchParams.delete(this.collectionParameter);let o=this.browserHistory();o[t.history==="push"?"pushState":"replaceState"](o.state,"",i),this.emit()}authorizationReturnTo(){let e=Le(this.currentUrl());return`${e.pathname}${e.search}${e.hash}`}authorizationCallback(){let e=this.currentUrl().href;return dt(e)?e:null}finishAuthorization(e,t){let i=this.safeAppUrl(e??this.fallbackPath);Le(i),i.searchParams.set(this.collectionParameter,t),this.browserHistory().replaceState(null,"",i),this.emit()}clearAuthorizationCallback(e){let t=e?this.safeAppUrl(e):this.currentUrl(),i=this.browserHistory();i.replaceState(i.state,"",Le(t)),this.emit()}subscribe(e){let t=this.listeners.size===0;return this.listeners.add(e),t&&typeof window<"u"&&window.addEventListener("popstate",this.handlePopState),()=>{this.listeners.delete(e),this.listeners.size===0&&typeof window<"u"&&window.removeEventListener("popstate",this.handlePopState)}}emit(){for(let e of this.listeners)e()}safeAppUrl(e){let t=this.currentUrl(),i=new URL(e,t.origin);return i.origin===t.origin?i:new URL(this.fallbackPath,t.origin)}currentUrl(){if(typeof location>"u")throw c("browser_required","Browser selection requires a browser environment.");return new URL(location.href)}browserHistory(){if(typeof history>"u")throw c("browser_required","Browser selection requires a browser environment.");return history}},jt=class{collectionId=null;listeners=new Set;selectedCollectionId(){return this.collectionId}select(e){if(e!==this.collectionId){this.collectionId=e;for(let t of this.listeners)t()}}authorizationReturnTo(){}authorizationCallback(){return null}finishAuthorization(e,t){this.select(t)}clearAuthorizationCallback(){}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}};return ci(zo);})();
@@ -1 +1 @@
1
- sha384-Rejwyx0zN9iv54K0UaKMWs09sQLXcxnOBtKT574KVKlC7aR4FZ7CqpPRMd7mKlNl
1
+ sha384-DjJkmk65xgvpJONlTzVuGLRLNCDOhbOdcG4xoq+le2zjOf+cYDEiN4Ctdl+HyrCL
@@ -1,4 +1,4 @@
1
- import type { CollectionChange, CollectionChangesPage, CollectionDescription, CollectionOperation, CollectionTypeDocument, CreateViewSourceInput, DeleteViewSourceInput, DeleteViewSourceResult, ExecuteViewInput, JsonObject, ReadViewSourceInput, RecordDocument, SavedViewExecution, SavedViewList, SavedViewSourceDocument, TypePackInstallResult, TypePackProvision, UpdateViewSourceInput } from "@mdbase-dev/connect-protocol";
1
+ import type { CollectionChange, CollectionChangesPage, CollectionDescription, CollectionOperation, CollectionTypeDocument, ApplyTypePackInput, AssessTypePackInput, CreateViewSourceInput, DeleteViewSourceInput, DeleteViewSourceResult, ExecuteViewInput, JsonObject, ReadViewSourceInput, RecordDocument, SavedViewExecution, SavedViewList, SavedViewSourceDocument, TypePackApplyResult, TypePackAssessment, UpdateViewSourceInput } from "@mdbase-dev/connect-protocol";
2
2
  import { type CollectionChangesProblemCode, type CollectionDescriptionProblemCode, type CollectionMutationProblemCode, type CollectionQueryProblemCode, type CollectionReadProblemCode, type CollectionTypeProblemCode, type ConnectOutcome } from "./outcomes.js";
3
3
  import type { ChangesInput, CreateInput, CreateTypeInput, DeleteInput, DeletePreflightResult, DeleteResult, MdbaseCollectionTransport, MdbaseDesiredTimer, MdbaseTimer, MdbaseTimerList, MdbaseTimerReconciliation, OperationRequestOptions, QueryInput, QueryPage, QueryPagesOptions, QueryResult, ReadInput, ReadTypeInput, RenameInput, RenamePreflightResult, RenameResult, UpdateInput, UpdateTypeInput, WatchOptions } from "./operation-types.js";
4
4
  /**
@@ -33,7 +33,8 @@ export declare class MdbaseCollectionClient<Frontmatter extends JsonObject = Jso
33
33
  readType(input: ReadTypeInput): Promise<ConnectOutcome<CollectionTypeDocument, CollectionTypeProblemCode>>;
34
34
  createType(input: CreateTypeInput): Promise<ConnectOutcome<CollectionTypeDocument, CollectionTypeProblemCode>>;
35
35
  updateType(input: UpdateTypeInput): Promise<ConnectOutcome<CollectionTypeDocument, CollectionTypeProblemCode>>;
36
- installTypePack(input: TypePackProvision): Promise<ConnectOutcome<TypePackInstallResult, CollectionTypeProblemCode>>;
36
+ assessTypePack(input: AssessTypePackInput): Promise<ConnectOutcome<TypePackAssessment, CollectionTypeProblemCode>>;
37
+ applyTypePack(input: ApplyTypePackInput): Promise<ConnectOutcome<TypePackApplyResult, CollectionTypeProblemCode>>;
37
38
  listTimers(namespace: string): Promise<ConnectOutcome<MdbaseTimerList, CollectionReadProblemCode>>;
38
39
  putTimer(input: {
39
40
  namespace: string;
@@ -143,8 +143,11 @@ export class MdbaseCollectionClient {
143
143
  updateType(input) {
144
144
  return this.envelopeOperation("update_type", input, COLLECTION_TYPE_PROBLEM_CODES);
145
145
  }
146
- installTypePack(input) {
147
- return this.envelopeOperation("install_type_pack", input, COLLECTION_TYPE_PROBLEM_CODES);
146
+ assessTypePack(input) {
147
+ return this.envelopeOperation("assess_type_pack", input, COLLECTION_TYPE_PROBLEM_CODES);
148
+ }
149
+ applyTypePack(input) {
150
+ return this.envelopeOperation("apply_type_pack", input, COLLECTION_TYPE_PROBLEM_CODES);
148
151
  }
149
152
  listTimers(namespace) {
150
153
  return this.rawOperation("list_timers", { namespace }, COLLECTION_READ_PROBLEM_CODES);
@@ -1,4 +1,4 @@
1
- import type { CollectionChange, CollectionChangesPage, CollectionDescription, CollectionOperation, FirstContactBinding, CollectionTypeDocument, CreateViewSourceInput, DeleteViewSourceInput, DeleteViewSourceResult, ExecuteViewInput, FileCapability, GrantScope, JsonObject, ReadViewSourceInput, RecordDocument, SavedViewExecution, SavedViewList, SavedViewSourceDocument, TypePackInstallResult, TypePackProvision, UpdateViewSourceInput } from "@mdbase-dev/connect-protocol";
1
+ import type { CollectionChange, CollectionChangesPage, CollectionDescription, CollectionOperation, FirstContactBinding, CollectionTypeDocument, CreateViewSourceInput, DeleteViewSourceInput, DeleteViewSourceResult, ExecuteViewInput, FileCapability, GrantScope, JsonObject, ReadViewSourceInput, RecordDocument, SavedViewExecution, SavedViewList, SavedViewSourceDocument, ApplyTypePackInput, AssessTypePackInput, TypePackApplyResult, TypePackAssessment, UpdateViewSourceInput } from "@mdbase-dev/connect-protocol";
2
2
  import { type ConnectionTransportInternals } from "./connection-transport.js";
3
3
  import type { DirectAccessStatus, MdbaseAuthorizationCapabilities, MdbaseConnectionInfo, MdbaseConnectionRoute, MdbaseSyncConnection } from "./connection-types.js";
4
4
  import type { GrantKeyStore } from "./crypto.js";
@@ -143,7 +143,8 @@ export declare class MdbaseConnection<Frontmatter extends JsonObject = JsonObjec
143
143
  readType(input: ReadTypeInput): Promise<ConnectOutcome<CollectionTypeDocument, CollectionTypeProblemCode>>;
144
144
  createType(input: CreateTypeInput): Promise<ConnectOutcome<CollectionTypeDocument, CollectionTypeProblemCode>>;
145
145
  updateType(input: UpdateTypeInput): Promise<ConnectOutcome<CollectionTypeDocument, CollectionTypeProblemCode>>;
146
- installTypePack(input: TypePackProvision): Promise<ConnectOutcome<TypePackInstallResult, CollectionTypeProblemCode>>;
146
+ assessTypePack(input: AssessTypePackInput): Promise<ConnectOutcome<TypePackAssessment, CollectionTypeProblemCode>>;
147
+ applyTypePack(input: ApplyTypePackInput): Promise<ConnectOutcome<TypePackApplyResult, CollectionTypeProblemCode>>;
147
148
  listTimers(namespace: string): Promise<ConnectOutcome<MdbaseTimerList, CollectionReadProblemCode>>;
148
149
  putTimer(input: {
149
150
  namespace: string;
@@ -382,8 +382,11 @@ export class MdbaseConnection {
382
382
  updateType(input) {
383
383
  return this.collectionClient.updateType(input);
384
384
  }
385
- installTypePack(input) {
386
- return this.collectionClient.installTypePack(input);
385
+ assessTypePack(input) {
386
+ return this.collectionClient.assessTypePack(input);
387
+ }
388
+ applyTypePack(input) {
389
+ return this.collectionClient.applyTypePack(input);
387
390
  }
388
391
  listTimers(namespace) {
389
392
  return this.collectionClient.listTimers(namespace);
package/dist/index.d.ts CHANGED
@@ -16,4 +16,4 @@ export * from "./operation-types.js";
16
16
  export * from "./selection.js";
17
17
  export * from "./session.js";
18
18
  export { createPkce } from "./runtime-utils.js";
19
- export type { ApplicationProvisions, ApplicationRequirements, ApplicationNotifications, ApplicationAuthorizationBinding, ApplicationAuthorizationProof, CollectionChange, CollectionChangesPage, CollectionContractDescriptor, CollectionDescription, CollectionFileMetadata, CollectionOperation as MdbaseOperation, CollectionTypeDescriptor, CollectionTypeDocument, ConnectOperationOutcome, ConnectProblem, ConnectProblemCategory, ConnectProblemCode, ConnectProblemDetailsByCode, ConnectRecoveryAction, ContractRequirement, DataContractViewIdentity, GrantScope, FirstContactBinding, JsonObject, MdbaseAppManifest, NotificationCriterion, MdbaseDiagnostic, MdbaseOperationEnvelope, KnownConnectProblem, RecordDocument, QueryRecord, SavedNamedView, SavedViewDocument, SavedViewExecution, SavedViewList, SavedViewPresentation, SavedViewProperty, SavedViewSource, SavedViewSourceDocument, ReadViewSourceInput, CreateViewSourceInput, UpdateViewSourceInput, DeleteViewSourceInput, DeleteViewSourceResult, ExecuteViewInput, TypePackManifest, TypePackManifestResource, TypePackInstallResult, TypePackProvision, TypePackResourceDiff, TypePackSourceResource, UnknownConnectProblem } from "@mdbase-dev/connect-protocol";
19
+ export type { ApplicationProvisions, ApplicationRequirements, ApplicationNotifications, ApplicationAuthorizationBinding, ApplicationAuthorizationProof, CollectionChange, CollectionChangesPage, CollectionContractDescriptor, CollectionDescription, CollectionFileMetadata, CollectionOperation as MdbaseOperation, CollectionTypeDescriptor, CollectionTypeDocument, ConnectOperationOutcome, ConnectProblem, ConnectProblemCategory, ConnectProblemCode, ConnectProblemDetailsByCode, ConnectRecoveryAction, ContractRequirement, DataContractViewIdentity, GrantScope, FirstContactBinding, JsonObject, MdbaseAppManifest, NotificationCriterion, MdbaseDiagnostic, MdbaseOperationEnvelope, KnownConnectProblem, RecordDocument, QueryRecord, SavedNamedView, SavedViewDocument, SavedViewExecution, SavedViewList, SavedViewPresentation, SavedViewProperty, SavedViewSource, SavedViewSourceDocument, ReadViewSourceInput, CreateViewSourceInput, UpdateViewSourceInput, DeleteViewSourceInput, DeleteViewSourceResult, ExecuteViewInput, TypePackManifest, TypePackManifestResource, TypePackApplyResult, TypePackAssessment, TypePackReceipt, AssessTypePackInput, ApplyTypePackInput, TypePackProvision, TypePackResourceDiff, TypePackSourceResource, UnknownConnectProblem } from "@mdbase-dev/connect-protocol";
@@ -34,7 +34,7 @@ export function isMutation(operation, input) {
34
34
  || operation === "rename"
35
35
  || operation === "create_type"
36
36
  || operation === "update_type"
37
- || operation === "install_type_pack"
37
+ || operation === "apply_type_pack"
38
38
  || operation === "put_timer"
39
39
  || operation === "cancel_timer"
40
40
  || operation === "reconcile_timers";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mdbase-dev/connect",
3
- "version": "0.1.0-beta.25",
3
+ "version": "0.1.0-beta.27",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -25,7 +25,7 @@
25
25
  "README.md"
26
26
  ],
27
27
  "dependencies": {
28
- "@mdbase-dev/connect-protocol": "0.1.0-beta.25"
28
+ "@mdbase-dev/connect-protocol": "0.1.0-beta.27"
29
29
  },
30
30
  "devDependencies": {
31
31
  "esbuild": "^0.28.1",