@mdbase-dev/sdk 0.4.0 → 0.4.1
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.
|
@@ -127,4 +127,4 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
|
|
|
127
127
|
`,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){let i="end"in t.value?t.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let o=e.items[e.items.length-2]?.value?.end;if(Array.isArray(o)){Gh(o,t.start),o.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let i=!this.onKeyLine&&this.indent===e.indent,o=i&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",s=[];if(o&&t.sep&&!t.value){let r=[];for(let a=0;a<t.sep.length;++a){let c=t.sep[a];switch(c.type){case"newline":r.push(a);break;case"space":break;case"comment":c.indent>e.indent&&(r.length=0);break;default:r.length=0}}r.length>=2&&(s=t.sep.splice(r[1]))}switch(this.type){case"anchor":case"tag":o||t.value?(s.push(this.sourceToken),e.items.push({start:s}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):o||t.value?(s.push(this.sourceToken),e.items.push({start:s,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Zo(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]});else if(YI(t.key)&&!Zo(t.sep,"newline")){let r=fl(t.start),a=t.key,c=t.sep;c.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:a,sep:c}]})}else s.length>0?t.sep=t.sep.concat(s,this.sourceToken):t.sep.push(this.sourceToken);else if(Zo(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let r=fl(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||o?e.items.push({start:s,key:null,sep:[this.sourceToken]}):Zo(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let r=this.flowScalar(this.type);o||t.value?(e.items.push({start:s,key:r,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(r):(Object.assign(t,{key:r,sep:[]}),this.onKeyLine=!0);return}default:{let r=this.startBlockValue(e);if(r){if(r.type==="block-seq"){if(!t.explicitKey&&t.sep&&!Zo(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else i&&e.items.push({start:s});this.stack.push(r);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){let i="end"in t.value?t.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let o=e.items[e.items.length-2]?.value?.end;if(Array.isArray(o)){Gh(o,t.start),o.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;t.value||Zo(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let i=this.startBlockValue(e);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let i;do yield*this.pop(),i=this.peek(1);while(i?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case"map-value-ind":!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:o,sep:[]}):t.sep?this.stack.push(o):Object.assign(t,{key:o,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let i=this.startBlockValue(e);i?this.stack.push(i):(yield*this.pop(),yield*this.step())}else{let i=this.peek(2);if(i.type==="block-map"&&(this.type==="map-value-ind"&&i.indent===e.indent||this.type==="newline"&&!i.items[i.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&i.type!=="flow-collection"){let o=Hh(i),s=fl(o);GI(e);let r=e.end.splice(1,e.end.length);r.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:s,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(`
|
|
128
128
|
`)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
|
129
129
|
`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=Hh(e),i=fl(t);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let t=Hh(e),i=fl(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!=="comment"||this.indent<=t?!1:e.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}}});function iL(n){let e=n.prettyErrors!==!1;return{lineCounter:n.lineCounter||e&&new ld||null,prettyErrors:e}}function Ev(n,e={}){let{lineCounter:t,prettyErrors:i}=iL(e),o=new cd(t?.addNewLine),s=new sd(e),r=null;for(let a of s.compose(o.parse(n),!0,n.length))if(!r)r=a;else if(r.options.logLevel!=="silent"){r.errors.push(new Qi(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&t&&(r.errors.forEach(pv(n,t)),r.warnings.forEach(pv(n,t))),r}var JI=C(()=>{Av();Qp();nd();Vw();Ne();Rv();Ov()});var qv=C(()=>{Av();Qp();cv();nd();jp();Ne();Ko();Mt();Ho();Go();Kh();Cv();Rv();Ov();JI();Lp()});var XI=C(()=>{qv();qv()});function Si(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,c=Si.evaluated;if(c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){for(let l in n)if(!(l==="app-runtime"||l==="mobile")){let p={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};r===null?r=[p]:r.push(p),a++}if(n["app-runtime"]!==void 0){let l=n["app-runtime"];if(Array.isArray(l)){if(l.length>16){let f={instancePath:e+"/app-runtime",schemaPath:"#/$defs/installationOrigins/maxItems",keyword:"maxItems",params:{limit:16},message:"must NOT have more than 16 items"};r===null?r=[f]:r.push(f),a++}let p=l.length;for(let f=0;f<p;f++){let h=l[f];if(typeof h=="string"){if(W(h)>255){let m={instancePath:e+"/app-runtime/"+f,schemaPath:"#/$defs/installationOrigins/items/maxLength",keyword:"maxLength",params:{limit:255},message:"must NOT have more than 255 characters"};r===null?r=[m]:r.push(m),a++}if(W(h)<1){let m={instancePath:e+"/app-runtime/"+f,schemaPath:"#/$defs/installationOrigins/items/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[m]:r.push(m),a++}if(!Wn(h)){let m={instancePath:e+"/app-runtime/"+f,schemaPath:"#/$defs/installationOrigins/items/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'};r===null?r=[m]:r.push(m),a++}}else{let m={instancePath:e+"/app-runtime/"+f,schemaPath:"#/$defs/installationOrigins/items/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[m]:r.push(m),a++}}let d=l.length,u;if(d>1){let f={};for(;d--;){let h=l[d];if(typeof h=="string"){if(typeof f[h]=="number"){u=f[h];let m={instancePath:e+"/app-runtime",schemaPath:"#/$defs/installationOrigins/uniqueItems",keyword:"uniqueItems",params:{i:d,j:u},message:"must NOT have duplicate items (items ## "+u+" and "+d+" are identical)"};r===null?r=[m]:r.push(m),a++;break}f[h]=d}}}}else{let p={instancePath:e+"/app-runtime",schemaPath:"#/$defs/installationOrigins/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[p]:r.push(p),a++}}if(n.mobile!==void 0){let l=n.mobile;if(Array.isArray(l)){if(l.length>16){let f={instancePath:e+"/mobile",schemaPath:"#/$defs/installationOrigins/maxItems",keyword:"maxItems",params:{limit:16},message:"must NOT have more than 16 items"};r===null?r=[f]:r.push(f),a++}let p=l.length;for(let f=0;f<p;f++){let h=l[f];if(typeof h=="string"){if(W(h)>255){let m={instancePath:e+"/mobile/"+f,schemaPath:"#/$defs/installationOrigins/items/maxLength",keyword:"maxLength",params:{limit:255},message:"must NOT have more than 255 characters"};r===null?r=[m]:r.push(m),a++}if(W(h)<1){let m={instancePath:e+"/mobile/"+f,schemaPath:"#/$defs/installationOrigins/items/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[m]:r.push(m),a++}if(!Wn(h)){let m={instancePath:e+"/mobile/"+f,schemaPath:"#/$defs/installationOrigins/items/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'};r===null?r=[m]:r.push(m),a++}}else{let m={instancePath:e+"/mobile/"+f,schemaPath:"#/$defs/installationOrigins/items/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[m]:r.push(m),a++}}let d=l.length,u;if(d>1){let f={};for(;d--;){let h=l[d];if(typeof h=="string"){if(typeof f[h]=="number"){u=f[h];let m={instancePath:e+"/mobile",schemaPath:"#/$defs/installationOrigins/uniqueItems",keyword:"uniqueItems",params:{i:d,j:u},message:"must NOT have duplicate items (items ## "+u+" and "+d+" are identical)"};r===null?r=[m]:r.push(m),a++;break}f[h]=d}}}}else{let p={instancePath:e+"/mobile",schemaPath:"#/$defs/installationOrigins/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[p]:r.push(p),a++}}}else{let l={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[l]:r.push(l),a++}return Si.errors=r,a===0}function hl(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,c=hl.evaluated;if(c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.contract_version===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"contract_version"},message:"must have required property 'contract_version'"};r===null?r=[l]:r.push(l),a++}if(n.required===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"required"},message:"must have required property 'required'"};r===null?r=[l]:r.push(l),a++}for(let l in n)if(!(l==="contract_version"||l==="required"||l==="optional")){let p={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};r===null?r=[p]:r.push(p),a++}if(n.contract_version!==void 0&&n.contract_version!==2){let l={instancePath:e+"/contract_version",schemaPath:"#/properties/contract_version/const",keyword:"const",params:{allowedValue:2},message:"must be equal to constant"};r===null?r=[l]:r.push(l),a++}if(n.required!==void 0){let l=n.required;if(Array.isArray(l)){if(l.length>32){let f={instancePath:e+"/required",schemaPath:"#/properties/required/maxItems",keyword:"maxItems",params:{limit:32},message:"must NOT have more than 32 items"};r===null?r=[f]:r.push(f),a++}let p=l.length;for(let f=0;f<p;f++){let h=l[f];if(!(h==="collection.read"||h==="records.create"||h==="records.edit"||h==="records.delete"||h==="views.manage"||h==="definitions.manage"||h==="background.schedule"||h==="offline.replica"||h==="history.read")){let m={instancePath:e+"/required/"+f,schemaPath:"#/$defs/applicationCapability/enum",keyword:"enum",params:{allowedValues:eC.enum},message:"must be equal to one of the allowed values"};r===null?r=[m]:r.push(m),a++}}let d=l.length,u;if(d>1){e:for(;d--;)for(u=d;u--;)if(ai(l[d],l[u])){let f={instancePath:e+"/required",schemaPath:"#/properties/required/uniqueItems",keyword:"uniqueItems",params:{i:d,j:u},message:"must NOT have duplicate items (items ## "+u+" and "+d+" are identical)"};r===null?r=[f]:r.push(f),a++;break e}}}else{let p={instancePath:e+"/required",schemaPath:"#/properties/required/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[p]:r.push(p),a++}}if(n.optional!==void 0){let l=n.optional;if(Array.isArray(l)){if(l.length>32){let f={instancePath:e+"/optional",schemaPath:"#/properties/optional/maxItems",keyword:"maxItems",params:{limit:32},message:"must NOT have more than 32 items"};r===null?r=[f]:r.push(f),a++}let p=l.length;for(let f=0;f<p;f++){let h=l[f];if(!(h==="collection.read"||h==="records.create"||h==="records.edit"||h==="records.delete"||h==="views.manage"||h==="definitions.manage"||h==="background.schedule"||h==="offline.replica"||h==="history.read")){let m={instancePath:e+"/optional/"+f,schemaPath:"#/$defs/applicationCapability/enum",keyword:"enum",params:{allowedValues:eC.enum},message:"must be equal to one of the allowed values"};r===null?r=[m]:r.push(m),a++}}let d=l.length,u;if(d>1){e:for(;d--;)for(u=d;u--;)if(ai(l[d],l[u])){let f={instancePath:e+"/optional",schemaPath:"#/properties/optional/uniqueItems",keyword:"uniqueItems",params:{i:d,j:u},message:"must NOT have duplicate items (items ## "+u+" and "+d+" are identical)"};r===null?r=[f]:r.push(f),a++;break e}}}else{let p={instancePath:e+"/optional",schemaPath:"#/properties/optional/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[p]:r.push(p),a++}}}else{let l={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[l]:r.push(l),a++}return hl.errors=r,a===0}function ml(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,c=ml.evaluated;if(c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.required===void 0){let d={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"required"},message:"must have required property 'required'"};r===null?r=[d]:r.push(d),a++}if(n.scope===void 0){let d={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"scope"},message:"must have required property 'scope'"};r===null?r=[d]:r.push(d),a++}for(let d in n)if(!(d==="required"||d==="optional"||d==="scope")){let u={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:d},message:"must NOT have additional properties"};r===null?r=[u]:r.push(u),a++}if(n.required!==void 0){let d=n.required;if(Array.isArray(d)){if(d.length>6){let m={instancePath:e+"/required",schemaPath:"#/$defs/fileActions/maxItems",keyword:"maxItems",params:{limit:6},message:"must NOT have more than 6 items"};r===null?r=[m]:r.push(m),a++}if(d.length<1){let m={instancePath:e+"/required",schemaPath:"#/$defs/fileActions/minItems",keyword:"minItems",params:{limit:1},message:"must NOT have fewer than 1 items"};r===null?r=[m]:r.push(m),a++}let u=d.length;for(let m=0;m<u;m++){let w=d[m];if(!(w==="list"||w==="read"||w==="add"||w==="replace"||w==="move"||w==="delete")){let b={instancePath:e+"/required/"+m,schemaPath:"#/$defs/fileActions/items/enum",keyword:"enum",params:{allowedValues:tC.items.enum},message:"must be equal to one of the allowed values"};r===null?r=[b]:r.push(b),a++}}let f=d.length,h;if(f>1){e:for(;f--;)for(h=f;h--;)if(ai(d[f],d[h])){let m={instancePath:e+"/required",schemaPath:"#/$defs/fileActions/uniqueItems",keyword:"uniqueItems",params:{i:f,j:h},message:"must NOT have duplicate items (items ## "+h+" and "+f+" are identical)"};r===null?r=[m]:r.push(m),a++;break e}}}else{let u={instancePath:e+"/required",schemaPath:"#/$defs/fileActions/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[u]:r.push(u),a++}}if(n.optional!==void 0){let d=n.optional;if(Array.isArray(d)){if(d.length>6){let m={instancePath:e+"/optional",schemaPath:"#/$defs/fileActions/maxItems",keyword:"maxItems",params:{limit:6},message:"must NOT have more than 6 items"};r===null?r=[m]:r.push(m),a++}if(d.length<1){let m={instancePath:e+"/optional",schemaPath:"#/$defs/fileActions/minItems",keyword:"minItems",params:{limit:1},message:"must NOT have fewer than 1 items"};r===null?r=[m]:r.push(m),a++}let u=d.length;for(let m=0;m<u;m++){let w=d[m];if(!(w==="list"||w==="read"||w==="add"||w==="replace"||w==="move"||w==="delete")){let b={instancePath:e+"/optional/"+m,schemaPath:"#/$defs/fileActions/items/enum",keyword:"enum",params:{allowedValues:tC.items.enum},message:"must be equal to one of the allowed values"};r===null?r=[b]:r.push(b),a++}}let f=d.length,h;if(f>1){e:for(;f--;)for(h=f;h--;)if(ai(d[f],d[h])){let m={instancePath:e+"/optional",schemaPath:"#/$defs/fileActions/uniqueItems",keyword:"uniqueItems",params:{i:f,j:h},message:"must NOT have duplicate items (items ## "+h+" and "+f+" are identical)"};r===null?r=[m]:r.push(m),a++;break e}}}else{let u={instancePath:e+"/optional",schemaPath:"#/$defs/fileActions/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[u]:r.push(u),a++}}if(n.scope!==void 0){let d=n.scope,u=a,f=!1,h=null,m=a;if(d&&typeof d=="object"&&!Array.isArray(d)){if(d.kind===void 0){let b={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf/0/required",keyword:"required",params:{missingProperty:"kind"},message:"must have required property 'kind'"};r===null?r=[b]:r.push(b),a++}if(d.folders===void 0){let b={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf/0/required",keyword:"required",params:{missingProperty:"folders"},message:"must have required property 'folders'"};r===null?r=[b]:r.push(b),a++}for(let b in d)if(!(b==="kind"||b==="folders")){let g={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf/0/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:b},message:"must NOT have additional properties"};r===null?r=[g]:r.push(g),a++}if(d.kind!==void 0&&d.kind!=="selected_folders"){let b={instancePath:e+"/scope/kind",schemaPath:"#/$defs/fileScope/oneOf/0/properties/kind/const",keyword:"const",params:{allowedValue:"selected_folders"},message:"must be equal to constant"};r===null?r=[b]:r.push(b),a++}if(d.folders!==void 0){let b=d.folders;if(Array.isArray(b)){if(b.length>100){let _={instancePath:e+"/scope/folders",schemaPath:"#/$defs/fileScope/oneOf/0/properties/folders/maxItems",keyword:"maxItems",params:{limit:100},message:"must NOT have more than 100 items"};r===null?r=[_]:r.push(_),a++}if(b.length<1){let _={instancePath:e+"/scope/folders",schemaPath:"#/$defs/fileScope/oneOf/0/properties/folders/minItems",keyword:"minItems",params:{limit:1},message:"must NOT have fewer than 1 items"};r===null?r=[_]:r.push(_),a++}let g=b.length;for(let _=0;_<g;_++){let k=b[_];if(typeof k=="string"){if(W(k)>1024){let S={instancePath:e+"/scope/folders/"+_,schemaPath:"#/$defs/fileScope/oneOf/0/properties/folders/items/maxLength",keyword:"maxLength",params:{limit:1024},message:"must NOT have more than 1024 characters"};r===null?r=[S]:r.push(S),a++}if(W(k)<1){let S={instancePath:e+"/scope/folders/"+_,schemaPath:"#/$defs/fileScope/oneOf/0/properties/folders/items/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[S]:r.push(S),a++}if(!pC.test(k)){let S={instancePath:e+"/scope/folders/"+_,schemaPath:"#/$defs/fileScope/oneOf/0/properties/folders/items/pattern",keyword:"pattern",params:{pattern:"^(?!/)(?!\\.)(?!.*//)(?!.*\\\\)(?!.*/\\.)(?!(?:_contracts|_schemas|_types|_views|node_modules)(?:/|$))(?!.*\\/(?:_contracts|_schemas|_types|_views|node_modules)(?:/|$))(?!.*/$).+$"},message:'must match pattern "^(?!/)(?!\\.)(?!.*//)(?!.*\\\\)(?!.*/\\.)(?!(?:_contracts|_schemas|_types|_views|node_modules)(?:/|$))(?!.*\\/(?:_contracts|_schemas|_types|_views|node_modules)(?:/|$))(?!.*/$).+$"'};r===null?r=[S]:r.push(S),a++}}else{let S={instancePath:e+"/scope/folders/"+_,schemaPath:"#/$defs/fileScope/oneOf/0/properties/folders/items/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[S]:r.push(S),a++}}let y=b.length,v;if(y>1){let _={};for(;y--;){let k=b[y];if(typeof k=="string"){if(typeof _[k]=="number"){v=_[k];let S={instancePath:e+"/scope/folders",schemaPath:"#/$defs/fileScope/oneOf/0/properties/folders/uniqueItems",keyword:"uniqueItems",params:{i:y,j:v},message:"must NOT have duplicate items (items ## "+v+" and "+y+" are identical)"};r===null?r=[S]:r.push(S),a++;break}_[k]=y}}}}else{let g={instancePath:e+"/scope/folders",schemaPath:"#/$defs/fileScope/oneOf/0/properties/folders/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[g]:r.push(g),a++}}}else{let b={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf/0/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[b]:r.push(b),a++}var p=m===a;if(p){f=!0,h=0;var l=!0}let w=a;if(d&&typeof d=="object"&&!Array.isArray(d)){if(d.kind===void 0){let b={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf/1/required",keyword:"required",params:{missingProperty:"kind"},message:"must have required property 'kind'"};r===null?r=[b]:r.push(b),a++}for(let b in d)if(b!=="kind"){let g={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf/1/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:b},message:"must NOT have additional properties"};r===null?r=[g]:r.push(g),a++}if(d.kind!==void 0&&d.kind!=="collection"){let b={instancePath:e+"/scope/kind",schemaPath:"#/$defs/fileScope/oneOf/1/properties/kind/const",keyword:"const",params:{allowedValue:"collection"},message:"must be equal to constant"};r===null?r=[b]:r.push(b),a++}}else{let b={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf/1/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[b]:r.push(b),a++}var p=w===a;if(p&&f?(f=!1,h=[h,1]):p&&(f=!0,h=1,l!==!0&&(l=!0)),f)a=u,r!==null&&(u?r.length=u:r=null);else{let b={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf",keyword:"oneOf",params:{passingSchemas:h},message:"must match exactly one schema in oneOf"};r===null?r=[b]:r.push(b),a++}}}else{let d={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[d]:r.push(d),a++}return ml.errors=r,a===0}function yl(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,c=yl.evaluated;if(c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.id===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"id"},message:"must have required property 'id'"};r===null?r=[p]:r.push(p),a++}if(n.path===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"path"},message:"must have required property 'path'"};r===null?r=[p]:r.push(p),a++}if(n.predicate===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"predicate"},message:"must have required property 'predicate'"};r===null?r=[p]:r.push(p),a++}if(n.value===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"value"},message:"must have required property 'value'"};r===null?r=[p]:r.push(p),a++}for(let p in n)if(!(p==="id"||p==="path"||p==="predicate"||p==="value")){let d={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:p},message:"must NOT have additional properties"};r===null?r=[d]:r.push(d),a++}if(n.id!==void 0){let p=n.id;if(typeof p=="string"){if(W(p)>100){let d={instancePath:e+"/id",schemaPath:"#/properties/id/maxLength",keyword:"maxLength",params:{limit:100},message:"must NOT have more than 100 characters"};r===null?r=[d]:r.push(d),a++}if(W(p)<1){let d={instancePath:e+"/id",schemaPath:"#/properties/id/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[d]:r.push(d),a++}if(!Zh.test(p)){let d={instancePath:e+"/id",schemaPath:"#/properties/id/pattern",keyword:"pattern",params:{pattern:"^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$"},message:'must match pattern "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$"'};r===null?r=[d]:r.push(d),a++}}else{let d={instancePath:e+"/id",schemaPath:"#/properties/id/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[d]:r.push(d),a++}}if(n.path!==void 0){let p=n.path;if(typeof p=="string"){if(W(p)>1024){let d={instancePath:e+"/path",schemaPath:"#/properties/path/maxLength",keyword:"maxLength",params:{limit:1024},message:"must NOT have more than 1024 characters"};r===null?r=[d]:r.push(d),a++}if(W(p)<1){let d={instancePath:e+"/path",schemaPath:"#/properties/path/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[d]:r.push(d),a++}}else{let d={instancePath:e+"/path",schemaPath:"#/properties/path/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[d]:r.push(d),a++}}if(n.predicate!==void 0&&n.predicate!=="contains"){let p={instancePath:e+"/predicate",schemaPath:"#/properties/predicate/const",keyword:"const",params:{allowedValue:"contains"},message:"must be equal to constant"};r===null?r=[p]:r.push(p),a++}if(n.value!==void 0){let p=n.value,d=a,u=!1,f=a;if(typeof p!="string"){let b={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/0/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[b]:r.push(b),a++}var l=f===a;u=u||l;let h=a;if(!(typeof p=="number"&&isFinite(p))){let b={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/1/type",keyword:"type",params:{type:"number"},message:"must be number"};r===null?r=[b]:r.push(b),a++}var l=h===a;u=u||l;let m=a;if(typeof p!="boolean"){let b={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/2/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"};r===null?r=[b]:r.push(b),a++}var l=m===a;u=u||l;let w=a;if(p!==null){let b={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/3/type",keyword:"type",params:{type:"null"},message:"must be null"};r===null?r=[b]:r.push(b),a++}var l=w===a;if(u=u||l,u)a=d,r!==null&&(d?r.length=d:r=null);else{let b={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};r===null?r=[b]:r.push(b),a++}}}else{let p={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[p]:r.push(p),a++}return yl.errors=r,a===0}function xi(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,c=xi.evaluated;if(c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.id===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"id"},message:"must have required property 'id'"};r===null?r=[l]:r.push(l),a++}if(n.version===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"version"},message:"must have required property 'version'"};r===null?r=[l]:r.push(l),a++}if(n.digest===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"digest"},message:"must have required property 'digest'"};r===null?r=[l]:r.push(l),a++}for(let l in n)if(!(l==="id"||l==="version"||l==="digest")){let p={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};r===null?r=[p]:r.push(p),a++}if(n.id!==void 0){let l=n.id;if(typeof l=="string"){if(W(l)>100){let p={instancePath:e+"/id",schemaPath:"#/$defs/identifier/maxLength",keyword:"maxLength",params:{limit:100},message:"must NOT have more than 100 characters"};r===null?r=[p]:r.push(p),a++}if(W(l)<1){let p={instancePath:e+"/id",schemaPath:"#/$defs/identifier/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[p]:r.push(p),a++}if(!ql.test(l)){let p={instancePath:e+"/id",schemaPath:"#/$defs/identifier/pattern",keyword:"pattern",params:{pattern:"^[a-z0-9]+(?:[._-][a-z0-9]+)*$"},message:'must match pattern "^[a-z0-9]+(?:[._-][a-z0-9]+)*$"'};r===null?r=[p]:r.push(p),a++}}else{let p={instancePath:e+"/id",schemaPath:"#/$defs/identifier/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[p]:r.push(p),a++}}if(n.version!==void 0){let l=n.version;if(typeof l=="string"){if(!Qh.test(l)){let p={instancePath:e+"/version",schemaPath:"#/properties/version/pattern",keyword:"pattern",params:{pattern:"^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$"},message:'must match pattern "^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$"'};r===null?r=[p]:r.push(p),a++}}else{let p={instancePath:e+"/version",schemaPath:"#/properties/version/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[p]:r.push(p),a++}}if(n.digest!==void 0){let l=n.digest;if(typeof l=="string"){if(!gl.test(l)){let p={instancePath:e+"/digest",schemaPath:"#/properties/digest/pattern",keyword:"pattern",params:{pattern:"^sha256:[0-9a-f]{64}$"},message:'must match pattern "^sha256:[0-9a-f]{64}$"'};r===null?r=[p]:r.push(p),a++}}else{let p={instancePath:e+"/digest",schemaPath:"#/properties/digest/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[p]:r.push(p),a++}}}else{let l={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[l]:r.push(l),a++}return xi.errors=r,a===0}function bl(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,c=bl.evaluated;if(c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.access===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"access"},message:"must have required property 'access'"};r===null?r=[p]:r.push(p),a++}if(n.contracts===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"contracts"},message:"must have required property 'contracts'"};r===null?r=[p]:r.push(p),a++}for(let p in n)if(!(p==="capabilities"||p==="access"||p==="collection_kind"||p==="people"||p==="files"||p==="configuration"||p==="contracts")){let d={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:p},message:"must NOT have additional properties"};r===null?r=[d]:r.push(d),a++}if(n.capabilities!==void 0&&(hl(n.capabilities,{instancePath:e+"/capabilities",parentData:n,parentDataProperty:"capabilities",rootData:o,dynamicAnchors:s})||(r=r===null?hl.errors:r.concat(hl.errors),a=r.length)),n.access!==void 0&&n.access!=="full_collection"){let p={instancePath:e+"/access",schemaPath:"#/properties/access/const",keyword:"const",params:{allowedValue:"full_collection"},message:"must be equal to constant"};r===null?r=[p]:r.push(p),a++}if(n.collection_kind!==void 0&&n.collection_kind!=="hosted"){let p={instancePath:e+"/collection_kind",schemaPath:"#/properties/collection_kind/const",keyword:"const",params:{allowedValue:"hosted"},message:"must be equal to constant"};r===null?r=[p]:r.push(p),a++}if(n.people!==void 0){let p=n.people,d=a,u=!1,f=a;if(p&&typeof p=="object"&&!Array.isArray(p)&&p.required===void 0){let m={instancePath:e+"/people",schemaPath:"#/properties/people/anyOf/0/required",keyword:"required",params:{missingProperty:"required"},message:"must have required property 'required'"};r===null?r=[m]:r.push(m),a++}var l=f===a;u=u||l;let h=a;if(p&&typeof p=="object"&&!Array.isArray(p)&&p.optional===void 0){let m={instancePath:e+"/people",schemaPath:"#/properties/people/anyOf/1/required",keyword:"required",params:{missingProperty:"optional"},message:"must have required property 'optional'"};r===null?r=[m]:r.push(m),a++}var l=h===a;if(u=u||l,u)a=d,r!==null&&(d?r.length=d:r=null);else{let m={instancePath:e+"/people",schemaPath:"#/properties/people/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};r===null?r=[m]:r.push(m),a++}if(p&&typeof p=="object"&&!Array.isArray(p)){if(p.version===void 0){let m={instancePath:e+"/people",schemaPath:"#/properties/people/required",keyword:"required",params:{missingProperty:"version"},message:"must have required property 'version'"};r===null?r=[m]:r.push(m),a++}for(let m in p)if(!(m==="version"||m==="required"||m==="optional")){let w={instancePath:e+"/people",schemaPath:"#/properties/people/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:m},message:"must NOT have additional properties"};r===null?r=[w]:r.push(w),a++}if(p.version!==void 0&&p.version!==1){let m={instancePath:e+"/people/version",schemaPath:"#/properties/people/properties/version/const",keyword:"const",params:{allowedValue:1},message:"must be equal to constant"};r===null?r=[m]:r.push(m),a++}if(p.required!==void 0){let m=p.required;if(Array.isArray(m)){if(m.length<1){let y={instancePath:e+"/people/required",schemaPath:"#/$defs/peoplePermissions/minItems",keyword:"minItems",params:{limit:1},message:"must NOT have fewer than 1 items"};r===null?r=[y]:r.push(y),a++}let w=m.length;for(let y=0;y<w;y++){let v=m[y];if(!(v==="identity"||v==="members")){let _={instancePath:e+"/people/required/"+y,schemaPath:"#/$defs/peoplePermissions/items/enum",keyword:"enum",params:{allowedValues:QI.items.enum},message:"must be equal to one of the allowed values"};r===null?r=[_]:r.push(_),a++}}let b=m.length,g;if(b>1){e:for(;b--;)for(g=b;g--;)if(ai(m[b],m[g])){let y={instancePath:e+"/people/required",schemaPath:"#/$defs/peoplePermissions/uniqueItems",keyword:"uniqueItems",params:{i:b,j:g},message:"must NOT have duplicate items (items ## "+g+" and "+b+" are identical)"};r===null?r=[y]:r.push(y),a++;break e}}}else{let w={instancePath:e+"/people/required",schemaPath:"#/$defs/peoplePermissions/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[w]:r.push(w),a++}}if(p.optional!==void 0){let m=p.optional;if(Array.isArray(m)){if(m.length<1){let y={instancePath:e+"/people/optional",schemaPath:"#/$defs/peoplePermissions/minItems",keyword:"minItems",params:{limit:1},message:"must NOT have fewer than 1 items"};r===null?r=[y]:r.push(y),a++}let w=m.length;for(let y=0;y<w;y++){let v=m[y];if(!(v==="identity"||v==="members")){let _={instancePath:e+"/people/optional/"+y,schemaPath:"#/$defs/peoplePermissions/items/enum",keyword:"enum",params:{allowedValues:QI.items.enum},message:"must be equal to one of the allowed values"};r===null?r=[_]:r.push(_),a++}}let b=m.length,g;if(b>1){e:for(;b--;)for(g=b;g--;)if(ai(m[b],m[g])){let y={instancePath:e+"/people/optional",schemaPath:"#/$defs/peoplePermissions/uniqueItems",keyword:"uniqueItems",params:{i:b,j:g},message:"must NOT have duplicate items (items ## "+g+" and "+b+" are identical)"};r===null?r=[y]:r.push(y),a++;break e}}}else{let w={instancePath:e+"/people/optional",schemaPath:"#/$defs/peoplePermissions/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[w]:r.push(w),a++}}}else{let m={instancePath:e+"/people",schemaPath:"#/properties/people/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[m]:r.push(m),a++}}if(n.files!==void 0&&(ml(n.files,{instancePath:e+"/files",parentData:n,parentDataProperty:"files",rootData:o,dynamicAnchors:s})||(r=r===null?ml.errors:r.concat(ml.errors),a=r.length)),n.configuration!==void 0){let p=n.configuration;if(Array.isArray(p)){if(p.length>50){let u={instancePath:e+"/configuration",schemaPath:"#/properties/configuration/maxItems",keyword:"maxItems",params:{limit:50},message:"must NOT have more than 50 items"};r===null?r=[u]:r.push(u),a++}let d=p.length;for(let u=0;u<d;u++)yl(p[u],{instancePath:e+"/configuration/"+u,parentData:p,parentDataProperty:u,rootData:o,dynamicAnchors:s})||(r=r===null?yl.errors:r.concat(yl.errors),a=r.length)}else{let d={instancePath:e+"/configuration",schemaPath:"#/properties/configuration/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[d]:r.push(d),a++}}if(n.contracts!==void 0){let p=n.contracts;if(Array.isArray(p)){if(p.length>20){let h={instancePath:e+"/contracts",schemaPath:"#/properties/contracts/maxItems",keyword:"maxItems",params:{limit:20},message:"must NOT have more than 20 items"};r===null?r=[h]:r.push(h),a++}let d=p.length;for(let h=0;h<d;h++)xi(p[h],{instancePath:e+"/contracts/"+h,parentData:p,parentDataProperty:h,rootData:o,dynamicAnchors:s})||(r=r===null?xi.errors:r.concat(xi.errors),a=r.length);let u=p.length,f;if(u>1){e:for(;u--;)for(f=u;f--;)if(ai(p[u],p[f])){let h={instancePath:e+"/contracts",schemaPath:"#/properties/contracts/uniqueItems",keyword:"uniqueItems",params:{i:u,j:f},message:"must NOT have duplicate items (items ## "+f+" and "+u+" are identical)"};r===null?r=[h]:r.push(h),a++;break e}}}else{let d={instancePath:e+"/contracts",schemaPath:"#/properties/contracts/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[d]:r.push(d),a++}}}else{let p={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[p]:r.push(p),a++}return bl.errors=r,a===0}function wl(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,c=wl.evaluated;if(c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.requirement===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"requirement"},message:"must have required property 'requirement'"};r===null?r=[p]:r.push(p),a++}if(n.operation===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"operation"},message:"must have required property 'operation'"};r===null?r=[p]:r.push(p),a++}if(n.path===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"path"},message:"must have required property 'path'"};r===null?r=[p]:r.push(p),a++}if(n.value===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"value"},message:"must have required property 'value'"};r===null?r=[p]:r.push(p),a++}for(let p in n)if(!(p==="requirement"||p==="operation"||p==="path"||p==="value")){let d={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:p},message:"must NOT have additional properties"};r===null?r=[d]:r.push(d),a++}if(n.requirement!==void 0){let p=n.requirement;if(typeof p=="string"){if(W(p)>100){let d={instancePath:e+"/requirement",schemaPath:"#/properties/requirement/maxLength",keyword:"maxLength",params:{limit:100},message:"must NOT have more than 100 characters"};r===null?r=[d]:r.push(d),a++}if(W(p)<1){let d={instancePath:e+"/requirement",schemaPath:"#/properties/requirement/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[d]:r.push(d),a++}if(!Zh.test(p)){let d={instancePath:e+"/requirement",schemaPath:"#/properties/requirement/pattern",keyword:"pattern",params:{pattern:"^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$"},message:'must match pattern "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$"'};r===null?r=[d]:r.push(d),a++}}else{let d={instancePath:e+"/requirement",schemaPath:"#/properties/requirement/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[d]:r.push(d),a++}}if(n.operation!==void 0&&n.operation!=="set_add"){let p={instancePath:e+"/operation",schemaPath:"#/properties/operation/const",keyword:"const",params:{allowedValue:"set_add"},message:"must be equal to constant"};r===null?r=[p]:r.push(p),a++}if(n.path!==void 0){let p=n.path;if(typeof p=="string"){if(W(p)>1024){let d={instancePath:e+"/path",schemaPath:"#/properties/path/maxLength",keyword:"maxLength",params:{limit:1024},message:"must NOT have more than 1024 characters"};r===null?r=[d]:r.push(d),a++}if(W(p)<1){let d={instancePath:e+"/path",schemaPath:"#/properties/path/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[d]:r.push(d),a++}}else{let d={instancePath:e+"/path",schemaPath:"#/properties/path/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[d]:r.push(d),a++}}if(n.value!==void 0){let p=n.value,d=a,u=!1,f=a;if(typeof p!="string"){let b={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/0/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[b]:r.push(b),a++}var l=f===a;u=u||l;let h=a;if(!(typeof p=="number"&&isFinite(p))){let b={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/1/type",keyword:"type",params:{type:"number"},message:"must be number"};r===null?r=[b]:r.push(b),a++}var l=h===a;u=u||l;let m=a;if(typeof p!="boolean"){let b={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/2/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"};r===null?r=[b]:r.push(b),a++}var l=m===a;u=u||l;let w=a;if(p!==null){let b={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/3/type",keyword:"type",params:{type:"null"},message:"must be null"};r===null?r=[b]:r.push(b),a++}var l=w===a;if(u=u||l,u)a=d,r!==null&&(d?r.length=d:r=null);else{let b={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};r===null?r=[b]:r.push(b),a++}}}else{let p={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[p]:r.push(p),a++}return wl.errors=r,a===0}function vl(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,c=vl.evaluated;if(c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.kind===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"kind"},message:"must have required property 'kind'"};r===null?r=[p]:r.push(p),a++}if(n.mode===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"mode"},message:"must have required property 'mode'"};r===null?r=[p]:r.push(p),a++}if(n.source===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"source"},message:"must have required property 'source'"};r===null?r=[p]:r.push(p),a++}if(n.target===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"target"},message:"must have required property 'target'"};r===null?r=[p]:r.push(p),a++}if(n.digest===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"digest"},message:"must have required property 'digest'"};r===null?r=[p]:r.push(p),a++}for(let p in n)if(!(p==="kind"||p==="mode"||p==="upgrade_from"||p==="source"||p==="target"||p==="digest")){let d={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:p},message:"must NOT have additional properties"};r===null?r=[d]:r.push(d),a++}if(n.kind!==void 0){let p=n.kind;if(!(p==="contract"||p==="type"||p==="schema")){let d={instancePath:e+"/kind",schemaPath:"#/properties/kind/enum",keyword:"enum",params:{allowedValues:nC.properties.kind.enum},message:"must be equal to one of the allowed values"};r===null?r=[d]:r.push(d),a++}}if(n.mode!==void 0){let p=n.mode;if(!(p==="managed"||p==="seed")){let d={instancePath:e+"/mode",schemaPath:"#/properties/mode/enum",keyword:"enum",params:{allowedValues:nC.properties.mode.enum},message:"must be equal to one of the allowed values"};r===null?r=[d]:r.push(d),a++}}if(n.upgrade_from!==void 0){let p=n.upgrade_from,d=a,u=!1,f=null,h=a;if(p&&typeof p=="object"&&!Array.isArray(p)){if(p.digest===void 0){let w={instancePath:e+"/upgrade_from",schemaPath:"#/$defs/typePackUpgradeBaseline/required",keyword:"required",params:{missingProperty:"digest"},message:"must have required property 'digest'"};r===null?r=[w]:r.push(w),a++}if(p.document===void 0){let w={instancePath:e+"/upgrade_from",schemaPath:"#/$defs/typePackUpgradeBaseline/required",keyword:"required",params:{missingProperty:"document"},message:"must have required property 'document'"};r===null?r=[w]:r.push(w),a++}for(let w in p)if(!(w==="digest"||w==="document"||w==="version")){let b={instancePath:e+"/upgrade_from",schemaPath:"#/$defs/typePackUpgradeBaseline/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:w},message:"must NOT have additional properties"};r===null?r=[b]:r.push(b),a++}if(p.digest!==void 0){let w=p.digest;if(typeof w=="string"){if(!gl.test(w)){let b={instancePath:e+"/upgrade_from/digest",schemaPath:"#/$defs/typePackUpgradeBaseline/properties/digest/pattern",keyword:"pattern",params:{pattern:"^sha256:[0-9a-f]{64}$"},message:'must match pattern "^sha256:[0-9a-f]{64}$"'};r===null?r=[b]:r.push(b),a++}}else{let b={instancePath:e+"/upgrade_from/digest",schemaPath:"#/$defs/typePackUpgradeBaseline/properties/digest/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[b]:r.push(b),a++}}if(p.document!==void 0){let w=p.document;if(typeof w=="string"){if(W(w)>262144){let b={instancePath:e+"/upgrade_from/document",schemaPath:"#/$defs/typePackUpgradeBaseline/properties/document/maxLength",keyword:"maxLength",params:{limit:262144},message:"must NOT have more than 262144 characters"};r===null?r=[b]:r.push(b),a++}}else{let b={instancePath:e+"/upgrade_from/document",schemaPath:"#/$defs/typePackUpgradeBaseline/properties/document/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[b]:r.push(b),a++}}if(p.version!==void 0){let w=p.version;if(!(typeof w=="number"&&!(w%1)&&!isNaN(w)&&isFinite(w))){let b={instancePath:e+"/upgrade_from/version",schemaPath:"#/$defs/typePackUpgradeBaseline/properties/version/type",keyword:"type",params:{type:"integer"},message:"must be integer"};r===null?r=[b]:r.push(b),a++}if(typeof w=="number"&&isFinite(w)&&(w<1||isNaN(w))){let b={instancePath:e+"/upgrade_from/version",schemaPath:"#/$defs/typePackUpgradeBaseline/properties/version/minimum",keyword:"minimum",params:{comparison:">=",limit:1},message:"must be >= 1"};r===null?r=[b]:r.push(b),a++}}}else{let w={instancePath:e+"/upgrade_from",schemaPath:"#/$defs/typePackUpgradeBaseline/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[w]:r.push(w),a++}var l=h===a;l&&(u=!0,f=0);let m=a;if(Array.isArray(p)){if(p.length<1){let b={instancePath:e+"/upgrade_from",schemaPath:"#/properties/upgrade_from/oneOf/1/minItems",keyword:"minItems",params:{limit:1},message:"must NOT have fewer than 1 items"};r===null?r=[b]:r.push(b),a++}let w=p.length;for(let b=0;b<w;b++){let g=p[b];if(g&&typeof g=="object"&&!Array.isArray(g)){if(g.digest===void 0){let y={instancePath:e+"/upgrade_from/"+b,schemaPath:"#/$defs/typePackUpgradeBaseline/required",keyword:"required",params:{missingProperty:"digest"},message:"must have required property 'digest'"};r===null?r=[y]:r.push(y),a++}if(g.document===void 0){let y={instancePath:e+"/upgrade_from/"+b,schemaPath:"#/$defs/typePackUpgradeBaseline/required",keyword:"required",params:{missingProperty:"document"},message:"must have required property 'document'"};r===null?r=[y]:r.push(y),a++}for(let y in g)if(!(y==="digest"||y==="document"||y==="version")){let v={instancePath:e+"/upgrade_from/"+b,schemaPath:"#/$defs/typePackUpgradeBaseline/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:y},message:"must NOT have additional properties"};r===null?r=[v]:r.push(v),a++}if(g.digest!==void 0){let y=g.digest;if(typeof y=="string"){if(!gl.test(y)){let v={instancePath:e+"/upgrade_from/"+b+"/digest",schemaPath:"#/$defs/typePackUpgradeBaseline/properties/digest/pattern",keyword:"pattern",params:{pattern:"^sha256:[0-9a-f]{64}$"},message:'must match pattern "^sha256:[0-9a-f]{64}$"'};r===null?r=[v]:r.push(v),a++}}else{let v={instancePath:e+"/upgrade_from/"+b+"/digest",schemaPath:"#/$defs/typePackUpgradeBaseline/properties/digest/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[v]:r.push(v),a++}}if(g.document!==void 0){let y=g.document;if(typeof y=="string"){if(W(y)>262144){let v={instancePath:e+"/upgrade_from/"+b+"/document",schemaPath:"#/$defs/typePackUpgradeBaseline/properties/document/maxLength",keyword:"maxLength",params:{limit:262144},message:"must NOT have more than 262144 characters"};r===null?r=[v]:r.push(v),a++}}else{let v={instancePath:e+"/upgrade_from/"+b+"/document",schemaPath:"#/$defs/typePackUpgradeBaseline/properties/document/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[v]:r.push(v),a++}}if(g.version!==void 0){let y=g.version;if(!(typeof y=="number"&&!(y%1)&&!isNaN(y)&&isFinite(y))){let v={instancePath:e+"/upgrade_from/"+b+"/version",schemaPath:"#/$defs/typePackUpgradeBaseline/properties/version/type",keyword:"type",params:{type:"integer"},message:"must be integer"};r===null?r=[v]:r.push(v),a++}if(typeof y=="number"&&isFinite(y)&&(y<1||isNaN(y))){let v={instancePath:e+"/upgrade_from/"+b+"/version",schemaPath:"#/$defs/typePackUpgradeBaseline/properties/version/minimum",keyword:"minimum",params:{comparison:">=",limit:1},message:"must be >= 1"};r===null?r=[v]:r.push(v),a++}}}else{let y={instancePath:e+"/upgrade_from/"+b,schemaPath:"#/$defs/typePackUpgradeBaseline/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[y]:r.push(y),a++}}}else{let w={instancePath:e+"/upgrade_from",schemaPath:"#/properties/upgrade_from/oneOf/1/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[w]:r.push(w),a++}var l=m===a;if(l&&u?(u=!1,f=[f,1]):l&&(u=!0,f=1),u)a=d,r!==null&&(d?r.length=d:r=null);else{let w={instancePath:e+"/upgrade_from",schemaPath:"#/properties/upgrade_from/oneOf",keyword:"oneOf",params:{passingSchemas:f},message:"must match exactly one schema in oneOf"};r===null?r=[w]:r.push(w),a++}}if(n.source!==void 0){let p=n.source;if(typeof p=="string"){if(W(p)>240){let d={instancePath:e+"/source",schemaPath:"#/properties/source/maxLength",keyword:"maxLength",params:{limit:240},message:"must NOT have more than 240 characters"};r===null?r=[d]:r.push(d),a++}if(W(p)<1){let d={instancePath:e+"/source",schemaPath:"#/properties/source/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[d]:r.push(d),a++}}else{let d={instancePath:e+"/source",schemaPath:"#/properties/source/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[d]:r.push(d),a++}}if(n.target!==void 0){let p=n.target;if(typeof p=="string"){if(W(p)>240){let d={instancePath:e+"/target",schemaPath:"#/properties/target/maxLength",keyword:"maxLength",params:{limit:240},message:"must NOT have more than 240 characters"};r===null?r=[d]:r.push(d),a++}if(W(p)<1){let d={instancePath:e+"/target",schemaPath:"#/properties/target/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[d]:r.push(d),a++}}else{let d={instancePath:e+"/target",schemaPath:"#/properties/target/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[d]:r.push(d),a++}}if(n.digest!==void 0){let p=n.digest;if(typeof p=="string"){if(!gl.test(p)){let d={instancePath:e+"/digest",schemaPath:"#/properties/digest/pattern",keyword:"pattern",params:{pattern:"^sha256:[0-9a-f]{64}$"},message:'must match pattern "^sha256:[0-9a-f]{64}$"'};r===null?r=[d]:r.push(d),a++}}else{let d={instancePath:e+"/digest",schemaPath:"#/properties/digest/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[d]:r.push(d),a++}}}else{let p={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[p]:r.push(p),a++}return vl.errors=r,a===0}function _l(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,c=_l.evaluated;if(c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.kind===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"kind"},message:"must have required property 'kind'"};r===null?r=[l]:r.push(l),a++}if(n.id===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"id"},message:"must have required property 'id'"};r===null?r=[l]:r.push(l),a++}if(n.version===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"version"},message:"must have required property 'version'"};r===null?r=[l]:r.push(l),a++}if(n.resources===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"resources"},message:"must have required property 'resources'"};r===null?r=[l]:r.push(l),a++}for(let l in n)if(!(l==="kind"||l==="id"||l==="version"||l==="name"||l==="description"||l==="resources"||dC.test(l))){let p={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};r===null?r=[p]:r.push(p),a++}if(n.kind!==void 0&&n.kind!=="mdbase.type-pack"){let l={instancePath:e+"/kind",schemaPath:"#/properties/kind/const",keyword:"const",params:{allowedValue:"mdbase.type-pack"},message:"must be equal to constant"};r===null?r=[l]:r.push(l),a++}if(n.id!==void 0){let l=n.id;if(typeof l=="string"){if(W(l)>100){let p={instancePath:e+"/id",schemaPath:"#/$defs/identifier/maxLength",keyword:"maxLength",params:{limit:100},message:"must NOT have more than 100 characters"};r===null?r=[p]:r.push(p),a++}if(W(l)<1){let p={instancePath:e+"/id",schemaPath:"#/$defs/identifier/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[p]:r.push(p),a++}if(!ql.test(l)){let p={instancePath:e+"/id",schemaPath:"#/$defs/identifier/pattern",keyword:"pattern",params:{pattern:"^[a-z0-9]+(?:[._-][a-z0-9]+)*$"},message:'must match pattern "^[a-z0-9]+(?:[._-][a-z0-9]+)*$"'};r===null?r=[p]:r.push(p),a++}}else{let p={instancePath:e+"/id",schemaPath:"#/$defs/identifier/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[p]:r.push(p),a++}}if(n.version!==void 0){let l=n.version;if(typeof l=="string"){if(!Qh.test(l)){let p={instancePath:e+"/version",schemaPath:"#/$defs/contract/properties/version/pattern",keyword:"pattern",params:{pattern:"^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$"},message:'must match pattern "^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$"'};r===null?r=[p]:r.push(p),a++}}else{let p={instancePath:e+"/version",schemaPath:"#/$defs/contract/properties/version/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[p]:r.push(p),a++}}if(n.name!==void 0){let l=n.name;if(typeof l=="string"){if(W(l)>100){let p={instancePath:e+"/name",schemaPath:"#/properties/name/maxLength",keyword:"maxLength",params:{limit:100},message:"must NOT have more than 100 characters"};r===null?r=[p]:r.push(p),a++}if(W(l)<1){let p={instancePath:e+"/name",schemaPath:"#/properties/name/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[p]:r.push(p),a++}}else{let p={instancePath:e+"/name",schemaPath:"#/properties/name/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[p]:r.push(p),a++}}if(n.description!==void 0){let l=n.description;if(typeof l=="string"){if(W(l)>500){let p={instancePath:e+"/description",schemaPath:"#/properties/description/maxLength",keyword:"maxLength",params:{limit:500},message:"must NOT have more than 500 characters"};r===null?r=[p]:r.push(p),a++}}else{let p={instancePath:e+"/description",schemaPath:"#/properties/description/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[p]:r.push(p),a++}}if(n.resources!==void 0){let l=n.resources;if(Array.isArray(l)){if(l.length>100){let d={instancePath:e+"/resources",schemaPath:"#/properties/resources/maxItems",keyword:"maxItems",params:{limit:100},message:"must NOT have more than 100 items"};r===null?r=[d]:r.push(d),a++}if(l.length<1){let d={instancePath:e+"/resources",schemaPath:"#/properties/resources/minItems",keyword:"minItems",params:{limit:1},message:"must NOT have fewer than 1 items"};r===null?r=[d]:r.push(d),a++}let p=l.length;for(let d=0;d<p;d++)vl(l[d],{instancePath:e+"/resources/"+d,parentData:l,parentDataProperty:d,rootData:o,dynamicAnchors:s})||(r=r===null?vl.errors:r.concat(vl.errors),a=r.length)}else{let p={instancePath:e+"/resources",schemaPath:"#/properties/resources/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[p]:r.push(p),a++}}}else{let l={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[l]:r.push(l),a++}return _l.errors=r,a===0}function Al(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,c=Al.evaluated;if(c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.manifest===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"manifest"},message:"must have required property 'manifest'"};r===null?r=[l]:r.push(l),a++}if(n.resources===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"resources"},message:"must have required property 'resources'"};r===null?r=[l]:r.push(l),a++}if(n.provides===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"provides"},message:"must have required property 'provides'"};r===null?r=[l]:r.push(l),a++}for(let l in n)if(!(l==="manifest"||l==="resources"||l==="provides")){let p={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};r===null?r=[p]:r.push(p),a++}if(n.manifest!==void 0&&(_l(n.manifest,{instancePath:e+"/manifest",parentData:n,parentDataProperty:"manifest",rootData:o,dynamicAnchors:s})||(r=r===null?_l.errors:r.concat(_l.errors),a=r.length)),n.resources!==void 0){let l=n.resources;if(Array.isArray(l)){if(l.length>100){let d={instancePath:e+"/resources",schemaPath:"#/properties/resources/maxItems",keyword:"maxItems",params:{limit:100},message:"must NOT have more than 100 items"};r===null?r=[d]:r.push(d),a++}if(l.length<1){let d={instancePath:e+"/resources",schemaPath:"#/properties/resources/minItems",keyword:"minItems",params:{limit:1},message:"must NOT have fewer than 1 items"};r===null?r=[d]:r.push(d),a++}let p=l.length;for(let d=0;d<p;d++){let u=l[d];if(u&&typeof u=="object"&&!Array.isArray(u)){if(u.source===void 0){let f={instancePath:e+"/resources/"+d,schemaPath:"#/$defs/typePackSourceResource/required",keyword:"required",params:{missingProperty:"source"},message:"must have required property 'source'"};r===null?r=[f]:r.push(f),a++}if(u.document===void 0){let f={instancePath:e+"/resources/"+d,schemaPath:"#/$defs/typePackSourceResource/required",keyword:"required",params:{missingProperty:"document"},message:"must have required property 'document'"};r===null?r=[f]:r.push(f),a++}for(let f in u)if(!(f==="source"||f==="document")){let h={instancePath:e+"/resources/"+d,schemaPath:"#/$defs/typePackSourceResource/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:f},message:"must NOT have additional properties"};r===null?r=[h]:r.push(h),a++}if(u.source!==void 0){let f=u.source;if(typeof f=="string"){if(W(f)>240){let h={instancePath:e+"/resources/"+d+"/source",schemaPath:"#/$defs/typePackSourceResource/properties/source/maxLength",keyword:"maxLength",params:{limit:240},message:"must NOT have more than 240 characters"};r===null?r=[h]:r.push(h),a++}if(W(f)<1){let h={instancePath:e+"/resources/"+d+"/source",schemaPath:"#/$defs/typePackSourceResource/properties/source/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[h]:r.push(h),a++}}else{let h={instancePath:e+"/resources/"+d+"/source",schemaPath:"#/$defs/typePackSourceResource/properties/source/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[h]:r.push(h),a++}}if(u.document!==void 0){let f=u.document;if(typeof f=="string"){if(W(f)>262144){let h={instancePath:e+"/resources/"+d+"/document",schemaPath:"#/$defs/typePackSourceResource/properties/document/maxLength",keyword:"maxLength",params:{limit:262144},message:"must NOT have more than 262144 characters"};r===null?r=[h]:r.push(h),a++}}else{let h={instancePath:e+"/resources/"+d+"/document",schemaPath:"#/$defs/typePackSourceResource/properties/document/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[h]:r.push(h),a++}}}else{let f={instancePath:e+"/resources/"+d,schemaPath:"#/$defs/typePackSourceResource/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[f]:r.push(f),a++}}}else{let p={instancePath:e+"/resources",schemaPath:"#/properties/resources/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[p]:r.push(p),a++}}if(n.provides!==void 0){let l=n.provides;if(Array.isArray(l)){if(l.length>20){let f={instancePath:e+"/provides",schemaPath:"#/properties/provides/maxItems",keyword:"maxItems",params:{limit:20},message:"must NOT have more than 20 items"};r===null?r=[f]:r.push(f),a++}let p=l.length;for(let f=0;f<p;f++)xi(l[f],{instancePath:e+"/provides/"+f,parentData:l,parentDataProperty:f,rootData:o,dynamicAnchors:s})||(r=r===null?xi.errors:r.concat(xi.errors),a=r.length);let d=l.length,u;if(d>1){e:for(;d--;)for(u=d;u--;)if(ai(l[d],l[u])){let f={instancePath:e+"/provides",schemaPath:"#/properties/provides/uniqueItems",keyword:"uniqueItems",params:{i:d,j:u},message:"must NOT have duplicate items (items ## "+u+" and "+d+" are identical)"};r===null?r=[f]:r.push(f),a++;break e}}}else{let p={instancePath:e+"/provides",schemaPath:"#/properties/provides/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[p]:r.push(p),a++}}}else{let l={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[l]:r.push(l),a++}return Al.errors=r,a===0}function kl(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,c=kl.evaluated;if(c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.id===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"id"},message:"must have required property 'id'"};r===null?r=[l]:r.push(l),a++}if(n.event===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"event"},message:"must have required property 'event'"};r===null?r=[l]:r.push(l),a++}if(n.presentation===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"presentation"},message:"must have required property 'presentation'"};r===null?r=[l]:r.push(l),a++}for(let l in n)if(!(l==="id"||l==="event"||l==="if"||l==="debounce"||l==="minimum_interval"||l==="presentation")){let p={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};r===null?r=[p]:r.push(p),a++}if(n.id!==void 0){let l=n.id;if(typeof l=="string"){if(W(l)>100){let p={instancePath:e+"/id",schemaPath:"#/$defs/identifier/maxLength",keyword:"maxLength",params:{limit:100},message:"must NOT have more than 100 characters"};r===null?r=[p]:r.push(p),a++}if(W(l)<1){let p={instancePath:e+"/id",schemaPath:"#/$defs/identifier/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[p]:r.push(p),a++}if(!ql.test(l)){let p={instancePath:e+"/id",schemaPath:"#/$defs/identifier/pattern",keyword:"pattern",params:{pattern:"^[a-z0-9]+(?:[._-][a-z0-9]+)*$"},message:'must match pattern "^[a-z0-9]+(?:[._-][a-z0-9]+)*$"'};r===null?r=[p]:r.push(p),a++}}else{let p={instancePath:e+"/id",schemaPath:"#/$defs/identifier/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[p]:r.push(p),a++}}if(n.event!==void 0&&(xi(n.event,{instancePath:e+"/event",parentData:n,parentDataProperty:"event",rootData:o,dynamicAnchors:s})||(r=r===null?xi.errors:r.concat(xi.errors),a=r.length)),n.if!==void 0){let l=n.if;if(l&&typeof l=="object"&&!Array.isArray(l)){if(l.$expr===void 0){let p={instancePath:e+"/if",schemaPath:"#/properties/if/required",keyword:"required",params:{missingProperty:"$expr"},message:"must have required property '$expr'"};r===null?r=[p]:r.push(p),a++}for(let p in l)if(p!=="$expr"){let d={instancePath:e+"/if",schemaPath:"#/properties/if/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:p},message:"must NOT have additional properties"};r===null?r=[d]:r.push(d),a++}if(l.$expr!==void 0){let p=l.$expr;if(typeof p=="string"){if(W(p)>4096){let d={instancePath:e+"/if/$expr",schemaPath:"#/properties/if/properties/%24expr/maxLength",keyword:"maxLength",params:{limit:4096},message:"must NOT have more than 4096 characters"};r===null?r=[d]:r.push(d),a++}if(W(p)<1){let d={instancePath:e+"/if/$expr",schemaPath:"#/properties/if/properties/%24expr/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[d]:r.push(d),a++}}else{let d={instancePath:e+"/if/$expr",schemaPath:"#/properties/if/properties/%24expr/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[d]:r.push(d),a++}}}else{let p={instancePath:e+"/if",schemaPath:"#/properties/if/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[p]:r.push(p),a++}}if(n.debounce!==void 0){let l=n.debounce;if(typeof l=="string"){if(!Yh.test(l)){let p={instancePath:e+"/debounce",schemaPath:"#/$defs/duration/pattern",keyword:"pattern",params:{pattern:"^[0-9]+(ms|s|m|h|d)$"},message:'must match pattern "^[0-9]+(ms|s|m|h|d)$"'};r===null?r=[p]:r.push(p),a++}}else{let p={instancePath:e+"/debounce",schemaPath:"#/$defs/duration/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[p]:r.push(p),a++}}if(n.minimum_interval!==void 0){let l=n.minimum_interval;if(typeof l=="string"){if(!Yh.test(l)){let p={instancePath:e+"/minimum_interval",schemaPath:"#/$defs/duration/pattern",keyword:"pattern",params:{pattern:"^[0-9]+(ms|s|m|h|d)$"},message:'must match pattern "^[0-9]+(ms|s|m|h|d)$"'};r===null?r=[p]:r.push(p),a++}}else{let p={instancePath:e+"/minimum_interval",schemaPath:"#/$defs/duration/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[p]:r.push(p),a++}}if(n.presentation!==void 0){let l=n.presentation;if(l&&typeof l=="object"&&!Array.isArray(l)){if(l.title===void 0){let p={instancePath:e+"/presentation",schemaPath:"#/properties/presentation/required",keyword:"required",params:{missingProperty:"title"},message:"must have required property 'title'"};r===null?r=[p]:r.push(p),a++}for(let p in l)if(!(p==="title"||p==="body"||p==="tag")){let d={instancePath:e+"/presentation",schemaPath:"#/properties/presentation/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:p},message:"must NOT have additional properties"};r===null?r=[d]:r.push(d),a++}if(l.title!==void 0){let p=l.title;if(typeof p=="string"){if(W(p)>80){let d={instancePath:e+"/presentation/title",schemaPath:"#/properties/presentation/properties/title/maxLength",keyword:"maxLength",params:{limit:80},message:"must NOT have more than 80 characters"};r===null?r=[d]:r.push(d),a++}if(W(p)<1){let d={instancePath:e+"/presentation/title",schemaPath:"#/properties/presentation/properties/title/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[d]:r.push(d),a++}}else{let d={instancePath:e+"/presentation/title",schemaPath:"#/properties/presentation/properties/title/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[d]:r.push(d),a++}}if(l.body!==void 0){let p=l.body;if(typeof p=="string"){if(W(p)>160){let d={instancePath:e+"/presentation/body",schemaPath:"#/properties/presentation/properties/body/maxLength",keyword:"maxLength",params:{limit:160},message:"must NOT have more than 160 characters"};r===null?r=[d]:r.push(d),a++}}else{let d={instancePath:e+"/presentation/body",schemaPath:"#/properties/presentation/properties/body/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[d]:r.push(d),a++}}if(l.tag!==void 0){let p=l.tag;if(typeof p=="string"){if(W(p)>80){let d={instancePath:e+"/presentation/tag",schemaPath:"#/properties/presentation/properties/tag/maxLength",keyword:"maxLength",params:{limit:80},message:"must NOT have more than 80 characters"};r===null?r=[d]:r.push(d),a++}if(W(p)<1){let d={instancePath:e+"/presentation/tag",schemaPath:"#/properties/presentation/properties/tag/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[d]:r.push(d),a++}}else{let d={instancePath:e+"/presentation/tag",schemaPath:"#/properties/presentation/properties/tag/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[d]:r.push(d),a++}}}else{let p={instancePath:e+"/presentation",schemaPath:"#/properties/presentation/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[p]:r.push(p),a++}}}else{let l={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[l]:r.push(l),a++}return kl.errors=r,a===0}function Jh(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,c=Jh.evaluated;c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.items=void 0);let l=a,p=!1,d=null,u=a;if(n&&typeof n=="object"&&!Array.isArray(n)){if(n.homepage===void 0){let g={instancePath:e,schemaPath:"#/oneOf/0/required",keyword:"required",params:{missingProperty:"homepage"},message:"must have required property 'homepage'"};r===null?r=[g]:r.push(g),a++}if(n.redirect_uris===void 0){let g={instancePath:e,schemaPath:"#/oneOf/0/required",keyword:"required",params:{missingProperty:"redirect_uris"},message:"must have required property 'redirect_uris'"};r===null?r=[g]:r.push(g),a++}if(n.distribution!==void 0&&n.distribution!=="web"){let g={instancePath:e+"/distribution",schemaPath:"#/oneOf/0/properties/distribution/const",keyword:"const",params:{allowedValue:"web"},message:"must be equal to constant"};r===null?r=[g]:r.push(g),a++}if(n.project_url!==void 0){let g={instancePath:e+"/project_url",schemaPath:"#/oneOf/0/properties/project_url/false schema",keyword:"false schema",params:{},message:"boolean schema is false"};r===null?r=[g]:r.push(g),a++}}var m=u===a;if(m){p=!0,d=0;var f={};f.distribution=!0,f.homepage=!0,f.redirect_uris=!0,f.project_url=!0}let h=a;if(n&&typeof n=="object"&&!Array.isArray(n)){if(n.distribution===void 0){let g={instancePath:e,schemaPath:"#/oneOf/1/required",keyword:"required",params:{missingProperty:"distribution"},message:"must have required property 'distribution'"};r===null?r=[g]:r.push(g),a++}if(n.distribution!==void 0&&n.distribution!=="portable"){let g={instancePath:e+"/distribution",schemaPath:"#/oneOf/1/properties/distribution/const",keyword:"const",params:{allowedValue:"portable"},message:"must be equal to constant"};r===null?r=[g]:r.push(g),a++}if(n.platform!==void 0){let g={instancePath:e+"/platform",schemaPath:"#/oneOf/1/properties/platform/false schema",keyword:"false schema",params:{},message:"boolean schema is false"};r===null?r=[g]:r.push(g),a++}if(n.homepage!==void 0){let g={instancePath:e+"/homepage",schemaPath:"#/oneOf/1/properties/homepage/false schema",keyword:"false schema",params:{},message:"boolean schema is false"};r===null?r=[g]:r.push(g),a++}if(n.redirect_uris!==void 0){let g={instancePath:e+"/redirect_uris",schemaPath:"#/oneOf/1/properties/redirect_uris/false schema",keyword:"false schema",params:{},message:"boolean schema is false"};r===null?r=[g]:r.push(g),a++}}var m=h===a;if(m&&p?(p=!1,d=[d,1]):m&&(p=!0,d=1,f!==!0&&(f=f||{},f.distribution=!0,f.platform=!0,f.homepage=!0,f.redirect_uris=!0)),p)a=l,r!==null&&(l?r.length=l:r=null);else{let g={instancePath:e,schemaPath:"#/oneOf",keyword:"oneOf",params:{passingSchemas:d},message:"must match exactly one schema in oneOf"};r===null?r=[g]:r.push(g),a++}if(n&&typeof n=="object"&&!Array.isArray(n)){if(n.manifest_version===void 0){let g={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"manifest_version"},message:"must have required property 'manifest_version'"};r===null?r=[g]:r.push(g),a++}if(n.id===void 0){let g={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"id"},message:"must have required property 'id'"};r===null?r=[g]:r.push(g),a++}if(n.name===void 0){let g={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"name"},message:"must have required property 'name'"};r===null?r=[g]:r.push(g),a++}for(let g in n)if(!aC.call(ZI.properties,g)){let y={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:g},message:"must NOT have additional properties"};r===null?r=[y]:r.push(y),a++}if(n.manifest_version!==void 0&&n.manifest_version!==1){let g={instancePath:e+"/manifest_version",schemaPath:"#/properties/manifest_version/const",keyword:"const",params:{allowedValue:1},message:"must be equal to constant"};r===null?r=[g]:r.push(g),a++}if(n.distribution!==void 0){let g=n.distribution;if(!(g==="web"||g==="portable")){let y={instancePath:e+"/distribution",schemaPath:"#/properties/distribution/enum",keyword:"enum",params:{allowedValues:ZI.properties.distribution.enum},message:"must be equal to one of the allowed values"};r===null?r=[y]:r.push(y),a++}}if(n.id!==void 0){let g=n.id;if(typeof g=="string"){if(W(g)>150){let y={instancePath:e+"/id",schemaPath:"#/properties/id/maxLength",keyword:"maxLength",params:{limit:150},message:"must NOT have more than 150 characters"};r===null?r=[y]:r.push(y),a++}if(W(g)<5){let y={instancePath:e+"/id",schemaPath:"#/properties/id/minLength",keyword:"minLength",params:{limit:5},message:"must NOT have fewer than 5 characters"};r===null?r=[y]:r.push(y),a++}if(!lC.test(g)){let y={instancePath:e+"/id",schemaPath:"#/properties/id/pattern",keyword:"pattern",params:{pattern:"^[a-z][a-z0-9-]*(\\.[a-z][a-z0-9-]*){2,}$"},message:'must match pattern "^[a-z][a-z0-9-]*(\\.[a-z][a-z0-9-]*){2,}$"'};r===null?r=[y]:r.push(y),a++}}else{let y={instancePath:e+"/id",schemaPath:"#/properties/id/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[y]:r.push(y),a++}}if(n.name!==void 0){let g=n.name;if(typeof g=="string"){if(W(g)>100){let y={instancePath:e+"/name",schemaPath:"#/properties/name/maxLength",keyword:"maxLength",params:{limit:100},message:"must NOT have more than 100 characters"};r===null?r=[y]:r.push(y),a++}if(W(g)<1){let y={instancePath:e+"/name",schemaPath:"#/properties/name/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[y]:r.push(y),a++}}else{let y={instancePath:e+"/name",schemaPath:"#/properties/name/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[y]:r.push(y),a++}}if(n.platform!==void 0&&n.platform!=="native"){let g={instancePath:e+"/platform",schemaPath:"#/properties/platform/const",keyword:"const",params:{allowedValue:"native"},message:"must be equal to constant"};r===null?r=[g]:r.push(g),a++}if(n.homepage!==void 0){let g=n.homepage;if(typeof g=="string"){if(!Qo.test(g)){let y={instancePath:e+"/homepage",schemaPath:"#/properties/homepage/pattern",keyword:"pattern",params:{pattern:"^https://"},message:'must match pattern "^https://"'};r===null?r=[y]:r.push(y),a++}if(!Wn(g)){let y={instancePath:e+"/homepage",schemaPath:"#/properties/homepage/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'};r===null?r=[y]:r.push(y),a++}}else{let y={instancePath:e+"/homepage",schemaPath:"#/properties/homepage/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[y]:r.push(y),a++}}if(n.project_url!==void 0){let g=n.project_url;if(typeof g=="string"){if(!Qo.test(g)){let y={instancePath:e+"/project_url",schemaPath:"#/properties/project_url/pattern",keyword:"pattern",params:{pattern:"^https://"},message:'must match pattern "^https://"'};r===null?r=[y]:r.push(y),a++}if(!Wn(g)){let y={instancePath:e+"/project_url",schemaPath:"#/properties/project_url/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'};r===null?r=[y]:r.push(y),a++}}else{let y={instancePath:e+"/project_url",schemaPath:"#/properties/project_url/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[y]:r.push(y),a++}}if(n.icon!==void 0){let g=n.icon;if(typeof g=="string"){if(!Qo.test(g)){let y={instancePath:e+"/icon",schemaPath:"#/properties/icon/pattern",keyword:"pattern",params:{pattern:"^https://"},message:'must match pattern "^https://"'};r===null?r=[y]:r.push(y),a++}if(!Wn(g)){let y={instancePath:e+"/icon",schemaPath:"#/properties/icon/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'};r===null?r=[y]:r.push(y),a++}}else{let y={instancePath:e+"/icon",schemaPath:"#/properties/icon/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[y]:r.push(y),a++}}if(n.redirect_uris!==void 0){let g=n.redirect_uris;if(Array.isArray(g)){if(g.length>10){let k={instancePath:e+"/redirect_uris",schemaPath:"#/properties/redirect_uris/maxItems",keyword:"maxItems",params:{limit:10},message:"must NOT have more than 10 items"};r===null?r=[k]:r.push(k),a++}if(g.length<1){let k={instancePath:e+"/redirect_uris",schemaPath:"#/properties/redirect_uris/minItems",keyword:"minItems",params:{limit:1},message:"must NOT have fewer than 1 items"};r===null?r=[k]:r.push(k),a++}let y=g.length;for(let k=0;k<y;k++){let S=g[k];if(typeof S=="string"){if(!Wn(S)){let x={instancePath:e+"/redirect_uris/"+k,schemaPath:"#/properties/redirect_uris/items/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'};r===null?r=[x]:r.push(x),a++}}else{let x={instancePath:e+"/redirect_uris/"+k,schemaPath:"#/properties/redirect_uris/items/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[x]:r.push(x),a++}}let v=g.length,_;if(v>1){let k={};for(;v--;){let S=g[v];if(typeof S=="string"){if(typeof k[S]=="number"){_=k[S];let x={instancePath:e+"/redirect_uris",schemaPath:"#/properties/redirect_uris/uniqueItems",keyword:"uniqueItems",params:{i:v,j:_},message:"must NOT have duplicate items (items ## "+_+" and "+v+" are identical)"};r===null?r=[x]:r.push(x),a++;break}k[S]=v}}}}else{let y={instancePath:e+"/redirect_uris",schemaPath:"#/properties/redirect_uris/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[y]:r.push(y),a++}}if(n.installation_origins!==void 0){let g=n.installation_origins;if(g&&typeof g=="object"&&!Array.isArray(g)){for(let y in g)if(!(y==="lab"||y==="staging"||y==="production")){let v={instancePath:e+"/installation_origins",schemaPath:"#/properties/installation_origins/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:y},message:"must NOT have additional properties"};r===null?r=[v]:r.push(v),a++}g.lab!==void 0&&(Si(g.lab,{instancePath:e+"/installation_origins/lab",parentData:g,parentDataProperty:"lab",rootData:o,dynamicAnchors:s})||(r=r===null?Si.errors:r.concat(Si.errors),a=r.length)),g.staging!==void 0&&(Si(g.staging,{instancePath:e+"/installation_origins/staging",parentData:g,parentDataProperty:"staging",rootData:o,dynamicAnchors:s})||(r=r===null?Si.errors:r.concat(Si.errors),a=r.length)),g.production!==void 0&&(Si(g.production,{instancePath:e+"/installation_origins/production",parentData:g,parentDataProperty:"production",rootData:o,dynamicAnchors:s})||(r=r===null?Si.errors:r.concat(Si.errors),a=r.length))}else{let y={instancePath:e+"/installation_origins",schemaPath:"#/properties/installation_origins/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[y]:r.push(y),a++}}if(n.requirements!==void 0&&(bl(n.requirements,{instancePath:e+"/requirements",parentData:n,parentDataProperty:"requirements",rootData:o,dynamicAnchors:s})||(r=r===null?bl.errors:r.concat(bl.errors),a=r.length)),n.provisions!==void 0){let g=n.provisions;if(g&&typeof g=="object"&&!Array.isArray(g)){if(g.type_packs===void 0){let y={instancePath:e+"/provisions",schemaPath:"#/properties/provisions/required",keyword:"required",params:{missingProperty:"type_packs"},message:"must have required property 'type_packs'"};r===null?r=[y]:r.push(y),a++}for(let y in g)if(!(y==="configuration"||y==="type_packs")){let v={instancePath:e+"/provisions",schemaPath:"#/properties/provisions/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:y},message:"must NOT have additional properties"};r===null?r=[v]:r.push(v),a++}if(g.configuration!==void 0){let y=g.configuration;if(Array.isArray(y)){if(y.length>50){let _={instancePath:e+"/provisions/configuration",schemaPath:"#/properties/provisions/properties/configuration/maxItems",keyword:"maxItems",params:{limit:50},message:"must NOT have more than 50 items"};r===null?r=[_]:r.push(_),a++}let v=y.length;for(let _=0;_<v;_++)wl(y[_],{instancePath:e+"/provisions/configuration/"+_,parentData:y,parentDataProperty:_,rootData:o,dynamicAnchors:s})||(r=r===null?wl.errors:r.concat(wl.errors),a=r.length)}else{let v={instancePath:e+"/provisions/configuration",schemaPath:"#/properties/provisions/properties/configuration/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[v]:r.push(v),a++}}if(g.type_packs!==void 0){let y=g.type_packs;if(Array.isArray(y)){if(y.length>20){let _={instancePath:e+"/provisions/type_packs",schemaPath:"#/properties/provisions/properties/type_packs/maxItems",keyword:"maxItems",params:{limit:20},message:"must NOT have more than 20 items"};r===null?r=[_]:r.push(_),a++}let v=y.length;for(let _=0;_<v;_++)Al(y[_],{instancePath:e+"/provisions/type_packs/"+_,parentData:y,parentDataProperty:_,rootData:o,dynamicAnchors:s})||(r=r===null?Al.errors:r.concat(Al.errors),a=r.length)}else{let v={instancePath:e+"/provisions/type_packs",schemaPath:"#/properties/provisions/properties/type_packs/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[v]:r.push(v),a++}}}else{let y={instancePath:e+"/provisions",schemaPath:"#/properties/provisions/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[y]:r.push(y),a++}}if(n.notifications!==void 0){let g=n.notifications;if(g&&typeof g=="object"&&!Array.isArray(g)){if(g.criteria===void 0){let y={instancePath:e+"/notifications",schemaPath:"#/properties/notifications/required",keyword:"required",params:{missingProperty:"criteria"},message:"must have required property 'criteria'"};r===null?r=[y]:r.push(y),a++}for(let y in g)if(!(y==="criteria"||y==="native_delivery")){let v={instancePath:e+"/notifications",schemaPath:"#/properties/notifications/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:y},message:"must NOT have additional properties"};r===null?r=[v]:r.push(v),a++}if(g.criteria!==void 0){let y=g.criteria;if(Array.isArray(y)){if(y.length>50){let _={instancePath:e+"/notifications/criteria",schemaPath:"#/properties/notifications/properties/criteria/maxItems",keyword:"maxItems",params:{limit:50},message:"must NOT have more than 50 items"};r===null?r=[_]:r.push(_),a++}let v=y.length;for(let _=0;_<v;_++)kl(y[_],{instancePath:e+"/notifications/criteria/"+_,parentData:y,parentDataProperty:_,rootData:o,dynamicAnchors:s})||(r=r===null?kl.errors:r.concat(kl.errors),a=r.length)}else{let v={instancePath:e+"/notifications/criteria",schemaPath:"#/properties/notifications/properties/criteria/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[v]:r.push(v),a++}}if(g.native_delivery!==void 0){let y=g.native_delivery,v=a,_=!1,k=null,S=a;if(y&&typeof y=="object"&&!Array.isArray(y)){if(y.mode===void 0){let P={instancePath:e+"/notifications/native_delivery",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/0/required",keyword:"required",params:{missingProperty:"mode"},message:"must have required property 'mode'"};r===null?r=[P]:r.push(P),a++}if(y.firebase_project_id===void 0){let P={instancePath:e+"/notifications/native_delivery",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/0/required",keyword:"required",params:{missingProperty:"firebase_project_id"},message:"must have required property 'firebase_project_id'"};r===null?r=[P]:r.push(P),a++}for(let P in y)if(!(P==="mode"||P==="firebase_project_id")){let I={instancePath:e+"/notifications/native_delivery",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/0/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:P},message:"must NOT have additional properties"};r===null?r=[I]:r.push(I),a++}if(y.mode!==void 0&&y.mode!=="managed_fcm"){let P={instancePath:e+"/notifications/native_delivery/mode",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/0/properties/mode/const",keyword:"const",params:{allowedValue:"managed_fcm"},message:"must be equal to constant"};r===null?r=[P]:r.push(P),a++}if(y.firebase_project_id!==void 0){let P=y.firebase_project_id;if(typeof P=="string"){if(W(P)>63){let I={instancePath:e+"/notifications/native_delivery/firebase_project_id",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/0/properties/firebase_project_id/maxLength",keyword:"maxLength",params:{limit:63},message:"must NOT have more than 63 characters"};r===null?r=[I]:r.push(I),a++}if(W(P)<6){let I={instancePath:e+"/notifications/native_delivery/firebase_project_id",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/0/properties/firebase_project_id/minLength",keyword:"minLength",params:{limit:6},message:"must NOT have fewer than 6 characters"};r===null?r=[I]:r.push(I),a++}if(!cC.test(P)){let I={instancePath:e+"/notifications/native_delivery/firebase_project_id",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/0/properties/firebase_project_id/pattern",keyword:"pattern",params:{pattern:"^[a-z][a-z0-9-]*[a-z0-9]$"},message:'must match pattern "^[a-z][a-z0-9-]*[a-z0-9]$"'};r===null?r=[I]:r.push(I),a++}}else{let I={instancePath:e+"/notifications/native_delivery/firebase_project_id",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/0/properties/firebase_project_id/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[I]:r.push(I),a++}}}else{let P={instancePath:e+"/notifications/native_delivery",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/0/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[P]:r.push(P),a++}var b=S===a;if(b){_=!0,k=0;var w=!0}let x=a;if(y&&typeof y=="object"&&!Array.isArray(y)){if(y.mode===void 0){let P={instancePath:e+"/notifications/native_delivery",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/1/required",keyword:"required",params:{missingProperty:"mode"},message:"must have required property 'mode'"};r===null?r=[P]:r.push(P),a++}if(y.url===void 0){let P={instancePath:e+"/notifications/native_delivery",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/1/required",keyword:"required",params:{missingProperty:"url"},message:"must have required property 'url'"};r===null?r=[P]:r.push(P),a++}for(let P in y)if(!(P==="mode"||P==="url")){let I={instancePath:e+"/notifications/native_delivery",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/1/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:P},message:"must NOT have additional properties"};r===null?r=[I]:r.push(I),a++}if(y.mode!==void 0&&y.mode!=="webhook"){let P={instancePath:e+"/notifications/native_delivery/mode",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/1/properties/mode/const",keyword:"const",params:{allowedValue:"webhook"},message:"must be equal to constant"};r===null?r=[P]:r.push(P),a++}if(y.url!==void 0){let P=y.url;if(typeof P=="string"){if(!Qo.test(P)){let I={instancePath:e+"/notifications/native_delivery/url",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/1/properties/url/pattern",keyword:"pattern",params:{pattern:"^https://"},message:'must match pattern "^https://"'};r===null?r=[I]:r.push(I),a++}if(!Wn(P)){let I={instancePath:e+"/notifications/native_delivery/url",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/1/properties/url/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'};r===null?r=[I]:r.push(I),a++}}else{let I={instancePath:e+"/notifications/native_delivery/url",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/1/properties/url/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[I]:r.push(I),a++}}}else{let P={instancePath:e+"/notifications/native_delivery",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/1/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[P]:r.push(P),a++}var b=x===a;if(b&&_?(_=!1,k=[k,1]):b&&(_=!0,k=1,w!==!0&&(w=!0)),_)a=v,r!==null&&(v?r.length=v:r=null);else{let P={instancePath:e+"/notifications/native_delivery",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf",keyword:"oneOf",params:{passingSchemas:k},message:"must match exactly one schema in oneOf"};r===null?r=[P]:r.push(P),a++}}}else{let y={instancePath:e+"/notifications",schemaPath:"#/properties/notifications/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[y]:r.push(y),a++}}}else{let g={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[g]:r.push(g),a++}return Jh.errors=r,a===0}function Pi(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,c=Pi.evaluated;if(c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){for(let l in n)if(!(l==="app-runtime"||l==="mobile")){let p={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};r===null?r=[p]:r.push(p),a++}if(n["app-runtime"]!==void 0){let l=n["app-runtime"];if(Array.isArray(l)){if(l.length>16){let f={instancePath:e+"/app-runtime",schemaPath:"#/$defs/installationOrigins/maxItems",keyword:"maxItems",params:{limit:16},message:"must NOT have more than 16 items"};r===null?r=[f]:r.push(f),a++}let p=l.length;for(let f=0;f<p;f++){let h=l[f];if(typeof h=="string"){if(W(h)>255){let m={instancePath:e+"/app-runtime/"+f,schemaPath:"#/$defs/installationOrigins/items/maxLength",keyword:"maxLength",params:{limit:255},message:"must NOT have more than 255 characters"};r===null?r=[m]:r.push(m),a++}if(W(h)<1){let m={instancePath:e+"/app-runtime/"+f,schemaPath:"#/$defs/installationOrigins/items/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[m]:r.push(m),a++}if(!Wn(h)){let m={instancePath:e+"/app-runtime/"+f,schemaPath:"#/$defs/installationOrigins/items/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'};r===null?r=[m]:r.push(m),a++}}else{let m={instancePath:e+"/app-runtime/"+f,schemaPath:"#/$defs/installationOrigins/items/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[m]:r.push(m),a++}}let d=l.length,u;if(d>1){let f={};for(;d--;){let h=l[d];if(typeof h=="string"){if(typeof f[h]=="number"){u=f[h];let m={instancePath:e+"/app-runtime",schemaPath:"#/$defs/installationOrigins/uniqueItems",keyword:"uniqueItems",params:{i:d,j:u},message:"must NOT have duplicate items (items ## "+u+" and "+d+" are identical)"};r===null?r=[m]:r.push(m),a++;break}f[h]=d}}}}else{let p={instancePath:e+"/app-runtime",schemaPath:"#/$defs/installationOrigins/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[p]:r.push(p),a++}}if(n.mobile!==void 0){let l=n.mobile;if(Array.isArray(l)){if(l.length>16){let f={instancePath:e+"/mobile",schemaPath:"#/$defs/installationOrigins/maxItems",keyword:"maxItems",params:{limit:16},message:"must NOT have more than 16 items"};r===null?r=[f]:r.push(f),a++}let p=l.length;for(let f=0;f<p;f++){let h=l[f];if(typeof h=="string"){if(W(h)>255){let m={instancePath:e+"/mobile/"+f,schemaPath:"#/$defs/installationOrigins/items/maxLength",keyword:"maxLength",params:{limit:255},message:"must NOT have more than 255 characters"};r===null?r=[m]:r.push(m),a++}if(W(h)<1){let m={instancePath:e+"/mobile/"+f,schemaPath:"#/$defs/installationOrigins/items/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[m]:r.push(m),a++}if(!Wn(h)){let m={instancePath:e+"/mobile/"+f,schemaPath:"#/$defs/installationOrigins/items/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'};r===null?r=[m]:r.push(m),a++}}else{let m={instancePath:e+"/mobile/"+f,schemaPath:"#/$defs/installationOrigins/items/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[m]:r.push(m),a++}}let d=l.length,u;if(d>1){let f={};for(;d--;){let h=l[d];if(typeof h=="string"){if(typeof f[h]=="number"){u=f[h];let m={instancePath:e+"/mobile",schemaPath:"#/$defs/installationOrigins/uniqueItems",keyword:"uniqueItems",params:{i:d,j:u},message:"must NOT have duplicate items (items ## "+u+" and "+d+" are identical)"};r===null?r=[m]:r.push(m),a++;break}f[h]=d}}}}else{let p={instancePath:e+"/mobile",schemaPath:"#/$defs/installationOrigins/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[p]:r.push(p),a++}}}else{let l={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[l]:r.push(l),a++}return Pi.errors=r,a===0}function Sl(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,c=Sl.evaluated;if(c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.contract_version===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"contract_version"},message:"must have required property 'contract_version'"};r===null?r=[l]:r.push(l),a++}if(n.required===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"required"},message:"must have required property 'required'"};r===null?r=[l]:r.push(l),a++}for(let l in n)if(!(l==="contract_version"||l==="required"||l==="optional")){let p={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};r===null?r=[p]:r.push(p),a++}if(n.contract_version!==void 0&&n.contract_version!==1){let l={instancePath:e+"/contract_version",schemaPath:"#/properties/contract_version/const",keyword:"const",params:{allowedValue:1},message:"must be equal to constant"};r===null?r=[l]:r.push(l),a++}if(n.required!==void 0){let l=n.required;if(Array.isArray(l)){if(l.length>32){let f={instancePath:e+"/required",schemaPath:"#/properties/required/maxItems",keyword:"maxItems",params:{limit:32},message:"must NOT have more than 32 items"};r===null?r=[f]:r.push(f),a++}let p=l.length;for(let f=0;f<p;f++){let h=l[f];if(!(h==="collection.inspect"||h==="records.watch"||h==="records.read"||h==="records.query"||h==="records.validate"||h==="records.create"||h==="records.update"||h==="records.delete"||h==="records.rename"||h==="views.list"||h==="views.execute"||h==="views.source.read"||h==="views.source.create"||h==="views.source.update"||h==="views.source.delete"||h==="definitions.contracts.current"||h==="definitions.read"||h==="definitions.create"||h==="definitions.update"||h==="definitions.type-pack.inspect"||h==="definitions.type-pack.apply"||h==="collection.setup.apply"||h==="timers.list"||h==="timers.put"||h==="timers.cancel"||h==="timers.reconcile"||h==="sync.offline-replica"||h==="notifications.background-delivery"||h==="files.list"||h==="files.read"||h==="files.add"||h==="files.replace"||h==="files.move"||h==="files.delete")){let m={instancePath:e+"/required/"+f,schemaPath:"#/$defs/applicationCapability/enum",keyword:"enum",params:{allowedValues:rC.enum},message:"must be equal to one of the allowed values"};r===null?r=[m]:r.push(m),a++}}let d=l.length,u;if(d>1){e:for(;d--;)for(u=d;u--;)if(ai(l[d],l[u])){let f={instancePath:e+"/required",schemaPath:"#/properties/required/uniqueItems",keyword:"uniqueItems",params:{i:d,j:u},message:"must NOT have duplicate items (items ## "+u+" and "+d+" are identical)"};r===null?r=[f]:r.push(f),a++;break e}}}else{let p={instancePath:e+"/required",schemaPath:"#/properties/required/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[p]:r.push(p),a++}}if(n.optional!==void 0){let l=n.optional;if(Array.isArray(l)){if(l.length>32){let f={instancePath:e+"/optional",schemaPath:"#/properties/optional/maxItems",keyword:"maxItems",params:{limit:32},message:"must NOT have more than 32 items"};r===null?r=[f]:r.push(f),a++}let p=l.length;for(let f=0;f<p;f++){let h=l[f];if(!(h==="collection.inspect"||h==="records.watch"||h==="records.read"||h==="records.query"||h==="records.validate"||h==="records.create"||h==="records.update"||h==="records.delete"||h==="records.rename"||h==="views.list"||h==="views.execute"||h==="views.source.read"||h==="views.source.create"||h==="views.source.update"||h==="views.source.delete"||h==="definitions.contracts.current"||h==="definitions.read"||h==="definitions.create"||h==="definitions.update"||h==="definitions.type-pack.inspect"||h==="definitions.type-pack.apply"||h==="collection.setup.apply"||h==="timers.list"||h==="timers.put"||h==="timers.cancel"||h==="timers.reconcile"||h==="sync.offline-replica"||h==="notifications.background-delivery"||h==="files.list"||h==="files.read"||h==="files.add"||h==="files.replace"||h==="files.move"||h==="files.delete")){let m={instancePath:e+"/optional/"+f,schemaPath:"#/$defs/applicationCapability/enum",keyword:"enum",params:{allowedValues:rC.enum},message:"must be equal to one of the allowed values"};r===null?r=[m]:r.push(m),a++}}let d=l.length,u;if(d>1){e:for(;d--;)for(u=d;u--;)if(ai(l[d],l[u])){let f={instancePath:e+"/optional",schemaPath:"#/properties/optional/uniqueItems",keyword:"uniqueItems",params:{i:d,j:u},message:"must NOT have duplicate items (items ## "+u+" and "+d+" are identical)"};r===null?r=[f]:r.push(f),a++;break e}}}else{let p={instancePath:e+"/optional",schemaPath:"#/properties/optional/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[p]:r.push(p),a++}}}else{let l={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[l]:r.push(l),a++}return Sl.errors=r,a===0}function Pl(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,c=Pl.evaluated;if(c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.actions===void 0){let d={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"actions"},message:"must have required property 'actions'"};r===null?r=[d]:r.push(d),a++}if(n.scope===void 0){let d={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"scope"},message:"must have required property 'scope'"};r===null?r=[d]:r.push(d),a++}for(let d in n)if(!(d==="actions"||d==="scope")){let u={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:d},message:"must NOT have additional properties"};r===null?r=[u]:r.push(u),a++}if(n.actions!==void 0){let d=n.actions;if(Array.isArray(d)){if(d.length>6){let m={instancePath:e+"/actions",schemaPath:"#/properties/actions/maxItems",keyword:"maxItems",params:{limit:6},message:"must NOT have more than 6 items"};r===null?r=[m]:r.push(m),a++}if(d.length<1){let m={instancePath:e+"/actions",schemaPath:"#/properties/actions/minItems",keyword:"minItems",params:{limit:1},message:"must NOT have fewer than 1 items"};r===null?r=[m]:r.push(m),a++}let u=d.length;for(let m=0;m<u;m++){let w=d[m];if(!(w==="list"||w==="read"||w==="add"||w==="replace"||w==="move"||w==="delete")){let b={instancePath:e+"/actions/"+m,schemaPath:"#/properties/actions/items/enum",keyword:"enum",params:{allowedValues:oL.properties.actions.items.enum},message:"must be equal to one of the allowed values"};r===null?r=[b]:r.push(b),a++}}let f=d.length,h;if(f>1){e:for(;f--;)for(h=f;h--;)if(ai(d[f],d[h])){let m={instancePath:e+"/actions",schemaPath:"#/properties/actions/uniqueItems",keyword:"uniqueItems",params:{i:f,j:h},message:"must NOT have duplicate items (items ## "+h+" and "+f+" are identical)"};r===null?r=[m]:r.push(m),a++;break e}}}else{let u={instancePath:e+"/actions",schemaPath:"#/properties/actions/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[u]:r.push(u),a++}}if(n.scope!==void 0){let d=n.scope,u=a,f=!1,h=null,m=a;if(d&&typeof d=="object"&&!Array.isArray(d)){if(d.kind===void 0){let b={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf/0/required",keyword:"required",params:{missingProperty:"kind"},message:"must have required property 'kind'"};r===null?r=[b]:r.push(b),a++}if(d.folders===void 0){let b={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf/0/required",keyword:"required",params:{missingProperty:"folders"},message:"must have required property 'folders'"};r===null?r=[b]:r.push(b),a++}for(let b in d)if(!(b==="kind"||b==="folders")){let g={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf/0/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:b},message:"must NOT have additional properties"};r===null?r=[g]:r.push(g),a++}if(d.kind!==void 0&&d.kind!=="selected_folders"){let b={instancePath:e+"/scope/kind",schemaPath:"#/$defs/fileScope/oneOf/0/properties/kind/const",keyword:"const",params:{allowedValue:"selected_folders"},message:"must be equal to constant"};r===null?r=[b]:r.push(b),a++}if(d.folders!==void 0){let b=d.folders;if(Array.isArray(b)){if(b.length>100){let _={instancePath:e+"/scope/folders",schemaPath:"#/$defs/fileScope/oneOf/0/properties/folders/maxItems",keyword:"maxItems",params:{limit:100},message:"must NOT have more than 100 items"};r===null?r=[_]:r.push(_),a++}if(b.length<1){let _={instancePath:e+"/scope/folders",schemaPath:"#/$defs/fileScope/oneOf/0/properties/folders/minItems",keyword:"minItems",params:{limit:1},message:"must NOT have fewer than 1 items"};r===null?r=[_]:r.push(_),a++}let g=b.length;for(let _=0;_<g;_++){let k=b[_];if(typeof k=="string"){if(W(k)>1024){let S={instancePath:e+"/scope/folders/"+_,schemaPath:"#/$defs/fileScope/oneOf/0/properties/folders/items/maxLength",keyword:"maxLength",params:{limit:1024},message:"must NOT have more than 1024 characters"};r===null?r=[S]:r.push(S),a++}if(W(k)<1){let S={instancePath:e+"/scope/folders/"+_,schemaPath:"#/$defs/fileScope/oneOf/0/properties/folders/items/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[S]:r.push(S),a++}if(!pC.test(k)){let S={instancePath:e+"/scope/folders/"+_,schemaPath:"#/$defs/fileScope/oneOf/0/properties/folders/items/pattern",keyword:"pattern",params:{pattern:"^(?!/)(?!\\.)(?!.*//)(?!.*\\\\)(?!.*/\\.)(?!(?:_contracts|_schemas|_types|_views|node_modules)(?:/|$))(?!.*\\/(?:_contracts|_schemas|_types|_views|node_modules)(?:/|$))(?!.*/$).+$"},message:'must match pattern "^(?!/)(?!\\.)(?!.*//)(?!.*\\\\)(?!.*/\\.)(?!(?:_contracts|_schemas|_types|_views|node_modules)(?:/|$))(?!.*\\/(?:_contracts|_schemas|_types|_views|node_modules)(?:/|$))(?!.*/$).+$"'};r===null?r=[S]:r.push(S),a++}}else{let S={instancePath:e+"/scope/folders/"+_,schemaPath:"#/$defs/fileScope/oneOf/0/properties/folders/items/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[S]:r.push(S),a++}}let y=b.length,v;if(y>1){let _={};for(;y--;){let k=b[y];if(typeof k=="string"){if(typeof _[k]=="number"){v=_[k];let S={instancePath:e+"/scope/folders",schemaPath:"#/$defs/fileScope/oneOf/0/properties/folders/uniqueItems",keyword:"uniqueItems",params:{i:y,j:v},message:"must NOT have duplicate items (items ## "+v+" and "+y+" are identical)"};r===null?r=[S]:r.push(S),a++;break}_[k]=y}}}}else{let g={instancePath:e+"/scope/folders",schemaPath:"#/$defs/fileScope/oneOf/0/properties/folders/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[g]:r.push(g),a++}}}else{let b={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf/0/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[b]:r.push(b),a++}var p=m===a;if(p){f=!0,h=0;var l=!0}let w=a;if(d&&typeof d=="object"&&!Array.isArray(d)){if(d.kind===void 0){let b={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf/1/required",keyword:"required",params:{missingProperty:"kind"},message:"must have required property 'kind'"};r===null?r=[b]:r.push(b),a++}for(let b in d)if(b!=="kind"){let g={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf/1/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:b},message:"must NOT have additional properties"};r===null?r=[g]:r.push(g),a++}if(d.kind!==void 0&&d.kind!=="collection"){let b={instancePath:e+"/scope/kind",schemaPath:"#/$defs/fileScope/oneOf/1/properties/kind/const",keyword:"const",params:{allowedValue:"collection"},message:"must be equal to constant"};r===null?r=[b]:r.push(b),a++}}else{let b={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf/1/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[b]:r.push(b),a++}var p=w===a;if(p&&f?(f=!1,h=[h,1]):p&&(f=!0,h=1,l!==!0&&(l=!0)),f)a=u,r!==null&&(u?r.length=u:r=null);else{let b={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf",keyword:"oneOf",params:{passingSchemas:h},message:"must match exactly one schema in oneOf"};r===null?r=[b]:r.push(b),a++}}}else{let d={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[d]:r.push(d),a++}return Pl.errors=r,a===0}function xl(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,c=xl.evaluated;if(c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.id===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"id"},message:"must have required property 'id'"};r===null?r=[p]:r.push(p),a++}if(n.path===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"path"},message:"must have required property 'path'"};r===null?r=[p]:r.push(p),a++}if(n.predicate===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"predicate"},message:"must have required property 'predicate'"};r===null?r=[p]:r.push(p),a++}if(n.value===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"value"},message:"must have required property 'value'"};r===null?r=[p]:r.push(p),a++}for(let p in n)if(!(p==="id"||p==="path"||p==="predicate"||p==="value")){let d={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:p},message:"must NOT have additional properties"};r===null?r=[d]:r.push(d),a++}if(n.id!==void 0){let p=n.id;if(typeof p=="string"){if(W(p)>100){let d={instancePath:e+"/id",schemaPath:"#/properties/id/maxLength",keyword:"maxLength",params:{limit:100},message:"must NOT have more than 100 characters"};r===null?r=[d]:r.push(d),a++}if(W(p)<1){let d={instancePath:e+"/id",schemaPath:"#/properties/id/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[d]:r.push(d),a++}if(!Zh.test(p)){let d={instancePath:e+"/id",schemaPath:"#/properties/id/pattern",keyword:"pattern",params:{pattern:"^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$"},message:'must match pattern "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$"'};r===null?r=[d]:r.push(d),a++}}else{let d={instancePath:e+"/id",schemaPath:"#/properties/id/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[d]:r.push(d),a++}}if(n.path!==void 0){let p=n.path;if(typeof p=="string"){if(W(p)>1024){let d={instancePath:e+"/path",schemaPath:"#/properties/path/maxLength",keyword:"maxLength",params:{limit:1024},message:"must NOT have more than 1024 characters"};r===null?r=[d]:r.push(d),a++}if(W(p)<1){let d={instancePath:e+"/path",schemaPath:"#/properties/path/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[d]:r.push(d),a++}}else{let d={instancePath:e+"/path",schemaPath:"#/properties/path/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[d]:r.push(d),a++}}if(n.predicate!==void 0&&n.predicate!=="contains"){let p={instancePath:e+"/predicate",schemaPath:"#/properties/predicate/const",keyword:"const",params:{allowedValue:"contains"},message:"must be equal to constant"};r===null?r=[p]:r.push(p),a++}if(n.value!==void 0){let p=n.value,d=a,u=!1,f=a;if(typeof p!="string"){let b={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/0/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[b]:r.push(b),a++}var l=f===a;u=u||l;let h=a;if(!(typeof p=="number"&&isFinite(p))){let b={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/1/type",keyword:"type",params:{type:"number"},message:"must be number"};r===null?r=[b]:r.push(b),a++}var l=h===a;u=u||l;let m=a;if(typeof p!="boolean"){let b={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/2/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"};r===null?r=[b]:r.push(b),a++}var l=m===a;u=u||l;let w=a;if(p!==null){let b={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/3/type",keyword:"type",params:{type:"null"},message:"must be null"};r===null?r=[b]:r.push(b),a++}var l=w===a;if(u=u||l,u)a=d,r!==null&&(d?r.length=d:r=null);else{let b={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};r===null?r=[b]:r.push(b),a++}}}else{let p={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[p]:r.push(p),a++}return xl.errors=r,a===0}function Ii(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,c=Ii.evaluated;if(c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.id===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"id"},message:"must have required property 'id'"};r===null?r=[l]:r.push(l),a++}if(n.version===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"version"},message:"must have required property 'version'"};r===null?r=[l]:r.push(l),a++}if(n.digest===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"digest"},message:"must have required property 'digest'"};r===null?r=[l]:r.push(l),a++}for(let l in n)if(!(l==="id"||l==="version"||l==="digest")){let p={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};r===null?r=[p]:r.push(p),a++}if(n.id!==void 0){let l=n.id;if(typeof l=="string"){if(W(l)>100){let p={instancePath:e+"/id",schemaPath:"#/$defs/identifier/maxLength",keyword:"maxLength",params:{limit:100},message:"must NOT have more than 100 characters"};r===null?r=[p]:r.push(p),a++}if(W(l)<1){let p={instancePath:e+"/id",schemaPath:"#/$defs/identifier/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[p]:r.push(p),a++}if(!ql.test(l)){let p={instancePath:e+"/id",schemaPath:"#/$defs/identifier/pattern",keyword:"pattern",params:{pattern:"^[a-z0-9]+(?:[._-][a-z0-9]+)*$"},message:'must match pattern "^[a-z0-9]+(?:[._-][a-z0-9]+)*$"'};r===null?r=[p]:r.push(p),a++}}else{let p={instancePath:e+"/id",schemaPath:"#/$defs/identifier/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[p]:r.push(p),a++}}if(n.version!==void 0){let l=n.version;if(typeof l=="string"){if(!Qh.test(l)){let p={instancePath:e+"/version",schemaPath:"#/properties/version/pattern",keyword:"pattern",params:{pattern:"^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$"},message:'must match pattern "^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$"'};r===null?r=[p]:r.push(p),a++}}else{let p={instancePath:e+"/version",schemaPath:"#/properties/version/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[p]:r.push(p),a++}}if(n.digest!==void 0){let l=n.digest;if(typeof l=="string"){if(!gl.test(l)){let p={instancePath:e+"/digest",schemaPath:"#/properties/digest/pattern",keyword:"pattern",params:{pattern:"^sha256:[0-9a-f]{64}$"},message:'must match pattern "^sha256:[0-9a-f]{64}$"'};r===null?r=[p]:r.push(p),a++}}else{let p={instancePath:e+"/digest",schemaPath:"#/properties/digest/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[p]:r.push(p),a++}}}else{let l={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[l]:r.push(l),a++}return Ii.errors=r,a===0}function Il(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,c=Il.evaluated;if(c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.access===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"access"},message:"must have required property 'access'"};r===null?r=[l]:r.push(l),a++}if(n.contracts===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"contracts"},message:"must have required property 'contracts'"};r===null?r=[l]:r.push(l),a++}for(let l in n)if(!(l==="capabilities"||l==="access"||l==="collection_kind"||l==="files"||l==="configuration"||l==="contracts")){let p={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};r===null?r=[p]:r.push(p),a++}if(n.capabilities!==void 0&&(Sl(n.capabilities,{instancePath:e+"/capabilities",parentData:n,parentDataProperty:"capabilities",rootData:o,dynamicAnchors:s})||(r=r===null?Sl.errors:r.concat(Sl.errors),a=r.length)),n.access!==void 0&&n.access!=="full_collection"){let l={instancePath:e+"/access",schemaPath:"#/properties/access/const",keyword:"const",params:{allowedValue:"full_collection"},message:"must be equal to constant"};r===null?r=[l]:r.push(l),a++}if(n.collection_kind!==void 0&&n.collection_kind!=="hosted"){let l={instancePath:e+"/collection_kind",schemaPath:"#/properties/collection_kind/const",keyword:"const",params:{allowedValue:"hosted"},message:"must be equal to constant"};r===null?r=[l]:r.push(l),a++}if(n.files!==void 0&&(Pl(n.files,{instancePath:e+"/files",parentData:n,parentDataProperty:"files",rootData:o,dynamicAnchors:s})||(r=r===null?Pl.errors:r.concat(Pl.errors),a=r.length)),n.configuration!==void 0){let l=n.configuration;if(Array.isArray(l)){if(l.length>50){let d={instancePath:e+"/configuration",schemaPath:"#/properties/configuration/maxItems",keyword:"maxItems",params:{limit:50},message:"must NOT have more than 50 items"};r===null?r=[d]:r.push(d),a++}let p=l.length;for(let d=0;d<p;d++)xl(l[d],{instancePath:e+"/configuration/"+d,parentData:l,parentDataProperty:d,rootData:o,dynamicAnchors:s})||(r=r===null?xl.errors:r.concat(xl.errors),a=r.length)}else{let p={instancePath:e+"/configuration",schemaPath:"#/properties/configuration/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[p]:r.push(p),a++}}if(n.contracts!==void 0){let l=n.contracts;if(Array.isArray(l)){if(l.length>20){let f={instancePath:e+"/contracts",schemaPath:"#/properties/contracts/maxItems",keyword:"maxItems",params:{limit:20},message:"must NOT have more than 20 items"};r===null?r=[f]:r.push(f),a++}let p=l.length;for(let f=0;f<p;f++)Ii(l[f],{instancePath:e+"/contracts/"+f,parentData:l,parentDataProperty:f,rootData:o,dynamicAnchors:s})||(r=r===null?Ii.errors:r.concat(Ii.errors),a=r.length);let d=l.length,u;if(d>1){e:for(;d--;)for(u=d;u--;)if(ai(l[d],l[u])){let f={instancePath:e+"/contracts",schemaPath:"#/properties/contracts/uniqueItems",keyword:"uniqueItems",params:{i:d,j:u},message:"must NOT have duplicate items (items ## "+u+" and "+d+" are identical)"};r===null?r=[f]:r.push(f),a++;break e}}}else{let p={instancePath:e+"/contracts",schemaPath:"#/properties/contracts/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[p]:r.push(p),a++}}}else{let l={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[l]:r.push(l),a++}return Il.errors=r,a===0}function Cl(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,c=Cl.evaluated;if(c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.requirement===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"requirement"},message:"must have required property 'requirement'"};r===null?r=[p]:r.push(p),a++}if(n.operation===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"operation"},message:"must have required property 'operation'"};r===null?r=[p]:r.push(p),a++}if(n.path===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"path"},message:"must have required property 'path'"};r===null?r=[p]:r.push(p),a++}if(n.value===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"value"},message:"must have required property 'value'"};r===null?r=[p]:r.push(p),a++}for(let p in n)if(!(p==="requirement"||p==="operation"||p==="path"||p==="value")){let d={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:p},message:"must NOT have additional properties"};r===null?r=[d]:r.push(d),a++}if(n.requirement!==void 0){let p=n.requirement;if(typeof p=="string"){if(W(p)>100){let d={instancePath:e+"/requirement",schemaPath:"#/properties/requirement/maxLength",keyword:"maxLength",params:{limit:100},message:"must NOT have more than 100 characters"};r===null?r=[d]:r.push(d),a++}if(W(p)<1){let d={instancePath:e+"/requirement",schemaPath:"#/properties/requirement/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[d]:r.push(d),a++}if(!Zh.test(p)){let d={instancePath:e+"/requirement",schemaPath:"#/properties/requirement/pattern",keyword:"pattern",params:{pattern:"^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$"},message:'must match pattern "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$"'};r===null?r=[d]:r.push(d),a++}}else{let d={instancePath:e+"/requirement",schemaPath:"#/properties/requirement/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[d]:r.push(d),a++}}if(n.operation!==void 0&&n.operation!=="set_add"){let p={instancePath:e+"/operation",schemaPath:"#/properties/operation/const",keyword:"const",params:{allowedValue:"set_add"},message:"must be equal to constant"};r===null?r=[p]:r.push(p),a++}if(n.path!==void 0){let p=n.path;if(typeof p=="string"){if(W(p)>1024){let d={instancePath:e+"/path",schemaPath:"#/properties/path/maxLength",keyword:"maxLength",params:{limit:1024},message:"must NOT have more than 1024 characters"};r===null?r=[d]:r.push(d),a++}if(W(p)<1){let d={instancePath:e+"/path",schemaPath:"#/properties/path/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[d]:r.push(d),a++}}else{let d={instancePath:e+"/path",schemaPath:"#/properties/path/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[d]:r.push(d),a++}}if(n.value!==void 0){let p=n.value,d=a,u=!1,f=a;if(typeof p!="string"){let b={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/0/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[b]:r.push(b),a++}var l=f===a;u=u||l;let h=a;if(!(typeof p=="number"&&isFinite(p))){let b={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/1/type",keyword:"type",params:{type:"number"},message:"must be number"};r===null?r=[b]:r.push(b),a++}var l=h===a;u=u||l;let m=a;if(typeof p!="boolean"){let b={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/2/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"};r===null?r=[b]:r.push(b),a++}var l=m===a;u=u||l;let w=a;if(p!==null){let b={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/3/type",keyword:"type",params:{type:"null"},message:"must be null"};r===null?r=[b]:r.push(b),a++}var l=w===a;if(u=u||l,u)a=d,r!==null&&(d?r.length=d:r=null);else{let b={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};r===null?r=[b]:r.push(b),a++}}}else{let p={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[p]:r.push(p),a++}return Cl.errors=r,a===0}function Rl(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,c=Rl.evaluated;if(c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.kind===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"kind"},message:"must have required property 'kind'"};r===null?r=[l]:r.push(l),a++}if(n.id===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"id"},message:"must have required property 'id'"};r===null?r=[l]:r.push(l),a++}if(n.version===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"version"},message:"must have required property 'version'"};r===null?r=[l]:r.push(l),a++}if(n.resources===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"resources"},message:"must have required property 'resources'"};r===null?r=[l]:r.push(l),a++}for(let l in n)if(!(l==="kind"||l==="id"||l==="version"||l==="name"||l==="description"||l==="resources"||dC.test(l))){let p={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};r===null?r=[p]:r.push(p),a++}if(n.kind!==void 0&&n.kind!=="mdbase.type-pack"){let l={instancePath:e+"/kind",schemaPath:"#/properties/kind/const",keyword:"const",params:{allowedValue:"mdbase.type-pack"},message:"must be equal to constant"};r===null?r=[l]:r.push(l),a++}if(n.id!==void 0){let l=n.id;if(typeof l=="string"){if(W(l)>100){let p={instancePath:e+"/id",schemaPath:"#/$defs/identifier/maxLength",keyword:"maxLength",params:{limit:100},message:"must NOT have more than 100 characters"};r===null?r=[p]:r.push(p),a++}if(W(l)<1){let p={instancePath:e+"/id",schemaPath:"#/$defs/identifier/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[p]:r.push(p),a++}if(!ql.test(l)){let p={instancePath:e+"/id",schemaPath:"#/$defs/identifier/pattern",keyword:"pattern",params:{pattern:"^[a-z0-9]+(?:[._-][a-z0-9]+)*$"},message:'must match pattern "^[a-z0-9]+(?:[._-][a-z0-9]+)*$"'};r===null?r=[p]:r.push(p),a++}}else{let p={instancePath:e+"/id",schemaPath:"#/$defs/identifier/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[p]:r.push(p),a++}}if(n.version!==void 0){let l=n.version;if(typeof l=="string"){if(!Qh.test(l)){let p={instancePath:e+"/version",schemaPath:"#/$defs/contract/properties/version/pattern",keyword:"pattern",params:{pattern:"^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$"},message:'must match pattern "^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$"'};r===null?r=[p]:r.push(p),a++}}else{let p={instancePath:e+"/version",schemaPath:"#/$defs/contract/properties/version/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[p]:r.push(p),a++}}if(n.name!==void 0){let l=n.name;if(typeof l=="string"){if(W(l)>100){let p={instancePath:e+"/name",schemaPath:"#/properties/name/maxLength",keyword:"maxLength",params:{limit:100},message:"must NOT have more than 100 characters"};r===null?r=[p]:r.push(p),a++}if(W(l)<1){let p={instancePath:e+"/name",schemaPath:"#/properties/name/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[p]:r.push(p),a++}}else{let p={instancePath:e+"/name",schemaPath:"#/properties/name/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[p]:r.push(p),a++}}if(n.description!==void 0){let l=n.description;if(typeof l=="string"){if(W(l)>500){let p={instancePath:e+"/description",schemaPath:"#/properties/description/maxLength",keyword:"maxLength",params:{limit:500},message:"must NOT have more than 500 characters"};r===null?r=[p]:r.push(p),a++}}else{let p={instancePath:e+"/description",schemaPath:"#/properties/description/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[p]:r.push(p),a++}}if(n.resources!==void 0){let l=n.resources;if(Array.isArray(l)){if(l.length>100){let d={instancePath:e+"/resources",schemaPath:"#/properties/resources/maxItems",keyword:"maxItems",params:{limit:100},message:"must NOT have more than 100 items"};r===null?r=[d]:r.push(d),a++}if(l.length<1){let d={instancePath:e+"/resources",schemaPath:"#/properties/resources/minItems",keyword:"minItems",params:{limit:1},message:"must NOT have fewer than 1 items"};r===null?r=[d]:r.push(d),a++}let p=l.length;for(let d=0;d<p;d++){let u=l[d];if(u&&typeof u=="object"&&!Array.isArray(u)){if(u.kind===void 0){let f={instancePath:e+"/resources/"+d,schemaPath:"#/$defs/typePackManifestResource/required",keyword:"required",params:{missingProperty:"kind"},message:"must have required property 'kind'"};r===null?r=[f]:r.push(f),a++}if(u.mode===void 0){let f={instancePath:e+"/resources/"+d,schemaPath:"#/$defs/typePackManifestResource/required",keyword:"required",params:{missingProperty:"mode"},message:"must have required property 'mode'"};r===null?r=[f]:r.push(f),a++}if(u.source===void 0){let f={instancePath:e+"/resources/"+d,schemaPath:"#/$defs/typePackManifestResource/required",keyword:"required",params:{missingProperty:"source"},message:"must have required property 'source'"};r===null?r=[f]:r.push(f),a++}if(u.target===void 0){let f={instancePath:e+"/resources/"+d,schemaPath:"#/$defs/typePackManifestResource/required",keyword:"required",params:{missingProperty:"target"},message:"must have required property 'target'"};r===null?r=[f]:r.push(f),a++}if(u.digest===void 0){let f={instancePath:e+"/resources/"+d,schemaPath:"#/$defs/typePackManifestResource/required",keyword:"required",params:{missingProperty:"digest"},message:"must have required property 'digest'"};r===null?r=[f]:r.push(f),a++}for(let f in u)if(!(f==="kind"||f==="mode"||f==="source"||f==="target"||f==="digest")){let h={instancePath:e+"/resources/"+d,schemaPath:"#/$defs/typePackManifestResource/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:f},message:"must NOT have additional properties"};r===null?r=[h]:r.push(h),a++}if(u.kind!==void 0){let f=u.kind;if(!(f==="contract"||f==="type"||f==="schema")){let h={instancePath:e+"/resources/"+d+"/kind",schemaPath:"#/$defs/typePackManifestResource/properties/kind/enum",keyword:"enum",params:{allowedValues:oC.properties.kind.enum},message:"must be equal to one of the allowed values"};r===null?r=[h]:r.push(h),a++}}if(u.mode!==void 0){let f=u.mode;if(!(f==="managed"||f==="seed")){let h={instancePath:e+"/resources/"+d+"/mode",schemaPath:"#/$defs/typePackManifestResource/properties/mode/enum",keyword:"enum",params:{allowedValues:oC.properties.mode.enum},message:"must be equal to one of the allowed values"};r===null?r=[h]:r.push(h),a++}}if(u.source!==void 0){let f=u.source;if(typeof f=="string"){if(W(f)>240){let h={instancePath:e+"/resources/"+d+"/source",schemaPath:"#/$defs/typePackManifestResource/properties/source/maxLength",keyword:"maxLength",params:{limit:240},message:"must NOT have more than 240 characters"};r===null?r=[h]:r.push(h),a++}if(W(f)<1){let h={instancePath:e+"/resources/"+d+"/source",schemaPath:"#/$defs/typePackManifestResource/properties/source/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[h]:r.push(h),a++}}else{let h={instancePath:e+"/resources/"+d+"/source",schemaPath:"#/$defs/typePackManifestResource/properties/source/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[h]:r.push(h),a++}}if(u.target!==void 0){let f=u.target;if(typeof f=="string"){if(W(f)>240){let h={instancePath:e+"/resources/"+d+"/target",schemaPath:"#/$defs/typePackManifestResource/properties/target/maxLength",keyword:"maxLength",params:{limit:240},message:"must NOT have more than 240 characters"};r===null?r=[h]:r.push(h),a++}if(W(f)<1){let h={instancePath:e+"/resources/"+d+"/target",schemaPath:"#/$defs/typePackManifestResource/properties/target/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[h]:r.push(h),a++}}else{let h={instancePath:e+"/resources/"+d+"/target",schemaPath:"#/$defs/typePackManifestResource/properties/target/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[h]:r.push(h),a++}}if(u.digest!==void 0){let f=u.digest;if(typeof f=="string"){if(!gl.test(f)){let h={instancePath:e+"/resources/"+d+"/digest",schemaPath:"#/$defs/typePackManifestResource/properties/digest/pattern",keyword:"pattern",params:{pattern:"^sha256:[0-9a-f]{64}$"},message:'must match pattern "^sha256:[0-9a-f]{64}$"'};r===null?r=[h]:r.push(h),a++}}else{let h={instancePath:e+"/resources/"+d+"/digest",schemaPath:"#/$defs/typePackManifestResource/properties/digest/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[h]:r.push(h),a++}}}else{let f={instancePath:e+"/resources/"+d,schemaPath:"#/$defs/typePackManifestResource/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[f]:r.push(f),a++}}}else{let p={instancePath:e+"/resources",schemaPath:"#/properties/resources/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[p]:r.push(p),a++}}}else{let l={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[l]:r.push(l),a++}return Rl.errors=r,a===0}function Ol(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,c=Ol.evaluated;if(c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.manifest===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"manifest"},message:"must have required property 'manifest'"};r===null?r=[l]:r.push(l),a++}if(n.resources===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"resources"},message:"must have required property 'resources'"};r===null?r=[l]:r.push(l),a++}if(n.provides===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"provides"},message:"must have required property 'provides'"};r===null?r=[l]:r.push(l),a++}for(let l in n)if(!(l==="manifest"||l==="resources"||l==="provides")){let p={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};r===null?r=[p]:r.push(p),a++}if(n.manifest!==void 0&&(Rl(n.manifest,{instancePath:e+"/manifest",parentData:n,parentDataProperty:"manifest",rootData:o,dynamicAnchors:s})||(r=r===null?Rl.errors:r.concat(Rl.errors),a=r.length)),n.resources!==void 0){let l=n.resources;if(Array.isArray(l)){if(l.length>100){let d={instancePath:e+"/resources",schemaPath:"#/properties/resources/maxItems",keyword:"maxItems",params:{limit:100},message:"must NOT have more than 100 items"};r===null?r=[d]:r.push(d),a++}if(l.length<1){let d={instancePath:e+"/resources",schemaPath:"#/properties/resources/minItems",keyword:"minItems",params:{limit:1},message:"must NOT have fewer than 1 items"};r===null?r=[d]:r.push(d),a++}let p=l.length;for(let d=0;d<p;d++){let u=l[d];if(u&&typeof u=="object"&&!Array.isArray(u)){if(u.source===void 0){let f={instancePath:e+"/resources/"+d,schemaPath:"#/$defs/typePackSourceResource/required",keyword:"required",params:{missingProperty:"source"},message:"must have required property 'source'"};r===null?r=[f]:r.push(f),a++}if(u.document===void 0){let f={instancePath:e+"/resources/"+d,schemaPath:"#/$defs/typePackSourceResource/required",keyword:"required",params:{missingProperty:"document"},message:"must have required property 'document'"};r===null?r=[f]:r.push(f),a++}for(let f in u)if(!(f==="source"||f==="document")){let h={instancePath:e+"/resources/"+d,schemaPath:"#/$defs/typePackSourceResource/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:f},message:"must NOT have additional properties"};r===null?r=[h]:r.push(h),a++}if(u.source!==void 0){let f=u.source;if(typeof f=="string"){if(W(f)>240){let h={instancePath:e+"/resources/"+d+"/source",schemaPath:"#/$defs/typePackSourceResource/properties/source/maxLength",keyword:"maxLength",params:{limit:240},message:"must NOT have more than 240 characters"};r===null?r=[h]:r.push(h),a++}if(W(f)<1){let h={instancePath:e+"/resources/"+d+"/source",schemaPath:"#/$defs/typePackSourceResource/properties/source/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[h]:r.push(h),a++}}else{let h={instancePath:e+"/resources/"+d+"/source",schemaPath:"#/$defs/typePackSourceResource/properties/source/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[h]:r.push(h),a++}}if(u.document!==void 0){let f=u.document;if(typeof f=="string"){if(W(f)>262144){let h={instancePath:e+"/resources/"+d+"/document",schemaPath:"#/$defs/typePackSourceResource/properties/document/maxLength",keyword:"maxLength",params:{limit:262144},message:"must NOT have more than 262144 characters"};r===null?r=[h]:r.push(h),a++}}else{let h={instancePath:e+"/resources/"+d+"/document",schemaPath:"#/$defs/typePackSourceResource/properties/document/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[h]:r.push(h),a++}}}else{let f={instancePath:e+"/resources/"+d,schemaPath:"#/$defs/typePackSourceResource/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[f]:r.push(f),a++}}}else{let p={instancePath:e+"/resources",schemaPath:"#/properties/resources/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[p]:r.push(p),a++}}if(n.provides!==void 0){let l=n.provides;if(Array.isArray(l)){if(l.length>20){let f={instancePath:e+"/provides",schemaPath:"#/properties/provides/maxItems",keyword:"maxItems",params:{limit:20},message:"must NOT have more than 20 items"};r===null?r=[f]:r.push(f),a++}let p=l.length;for(let f=0;f<p;f++)Ii(l[f],{instancePath:e+"/provides/"+f,parentData:l,parentDataProperty:f,rootData:o,dynamicAnchors:s})||(r=r===null?Ii.errors:r.concat(Ii.errors),a=r.length);let d=l.length,u;if(d>1){e:for(;d--;)for(u=d;u--;)if(ai(l[d],l[u])){let f={instancePath:e+"/provides",schemaPath:"#/properties/provides/uniqueItems",keyword:"uniqueItems",params:{i:d,j:u},message:"must NOT have duplicate items (items ## "+u+" and "+d+" are identical)"};r===null?r=[f]:r.push(f),a++;break e}}}else{let p={instancePath:e+"/provides",schemaPath:"#/properties/provides/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[p]:r.push(p),a++}}}else{let l={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[l]:r.push(l),a++}return Ol.errors=r,a===0}function El(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,c=El.evaluated;if(c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.id===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"id"},message:"must have required property 'id'"};r===null?r=[l]:r.push(l),a++}if(n.event===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"event"},message:"must have required property 'event'"};r===null?r=[l]:r.push(l),a++}if(n.presentation===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"presentation"},message:"must have required property 'presentation'"};r===null?r=[l]:r.push(l),a++}for(let l in n)if(!(l==="id"||l==="event"||l==="if"||l==="debounce"||l==="minimum_interval"||l==="presentation")){let p={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};r===null?r=[p]:r.push(p),a++}if(n.id!==void 0){let l=n.id;if(typeof l=="string"){if(W(l)>100){let p={instancePath:e+"/id",schemaPath:"#/$defs/identifier/maxLength",keyword:"maxLength",params:{limit:100},message:"must NOT have more than 100 characters"};r===null?r=[p]:r.push(p),a++}if(W(l)<1){let p={instancePath:e+"/id",schemaPath:"#/$defs/identifier/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[p]:r.push(p),a++}if(!ql.test(l)){let p={instancePath:e+"/id",schemaPath:"#/$defs/identifier/pattern",keyword:"pattern",params:{pattern:"^[a-z0-9]+(?:[._-][a-z0-9]+)*$"},message:'must match pattern "^[a-z0-9]+(?:[._-][a-z0-9]+)*$"'};r===null?r=[p]:r.push(p),a++}}else{let p={instancePath:e+"/id",schemaPath:"#/$defs/identifier/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[p]:r.push(p),a++}}if(n.event!==void 0&&(Ii(n.event,{instancePath:e+"/event",parentData:n,parentDataProperty:"event",rootData:o,dynamicAnchors:s})||(r=r===null?Ii.errors:r.concat(Ii.errors),a=r.length)),n.if!==void 0){let l=n.if;if(l&&typeof l=="object"&&!Array.isArray(l)){if(l.$expr===void 0){let p={instancePath:e+"/if",schemaPath:"#/properties/if/required",keyword:"required",params:{missingProperty:"$expr"},message:"must have required property '$expr'"};r===null?r=[p]:r.push(p),a++}for(let p in l)if(p!=="$expr"){let d={instancePath:e+"/if",schemaPath:"#/properties/if/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:p},message:"must NOT have additional properties"};r===null?r=[d]:r.push(d),a++}if(l.$expr!==void 0){let p=l.$expr;if(typeof p=="string"){if(W(p)>4096){let d={instancePath:e+"/if/$expr",schemaPath:"#/properties/if/properties/%24expr/maxLength",keyword:"maxLength",params:{limit:4096},message:"must NOT have more than 4096 characters"};r===null?r=[d]:r.push(d),a++}if(W(p)<1){let d={instancePath:e+"/if/$expr",schemaPath:"#/properties/if/properties/%24expr/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[d]:r.push(d),a++}}else{let d={instancePath:e+"/if/$expr",schemaPath:"#/properties/if/properties/%24expr/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[d]:r.push(d),a++}}}else{let p={instancePath:e+"/if",schemaPath:"#/properties/if/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[p]:r.push(p),a++}}if(n.debounce!==void 0){let l=n.debounce;if(typeof l=="string"){if(!Yh.test(l)){let p={instancePath:e+"/debounce",schemaPath:"#/$defs/duration/pattern",keyword:"pattern",params:{pattern:"^[0-9]+(ms|s|m|h|d)$"},message:'must match pattern "^[0-9]+(ms|s|m|h|d)$"'};r===null?r=[p]:r.push(p),a++}}else{let p={instancePath:e+"/debounce",schemaPath:"#/$defs/duration/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[p]:r.push(p),a++}}if(n.minimum_interval!==void 0){let l=n.minimum_interval;if(typeof l=="string"){if(!Yh.test(l)){let p={instancePath:e+"/minimum_interval",schemaPath:"#/$defs/duration/pattern",keyword:"pattern",params:{pattern:"^[0-9]+(ms|s|m|h|d)$"},message:'must match pattern "^[0-9]+(ms|s|m|h|d)$"'};r===null?r=[p]:r.push(p),a++}}else{let p={instancePath:e+"/minimum_interval",schemaPath:"#/$defs/duration/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[p]:r.push(p),a++}}if(n.presentation!==void 0){let l=n.presentation;if(l&&typeof l=="object"&&!Array.isArray(l)){if(l.title===void 0){let p={instancePath:e+"/presentation",schemaPath:"#/properties/presentation/required",keyword:"required",params:{missingProperty:"title"},message:"must have required property 'title'"};r===null?r=[p]:r.push(p),a++}for(let p in l)if(!(p==="title"||p==="body"||p==="tag")){let d={instancePath:e+"/presentation",schemaPath:"#/properties/presentation/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:p},message:"must NOT have additional properties"};r===null?r=[d]:r.push(d),a++}if(l.title!==void 0){let p=l.title;if(typeof p=="string"){if(W(p)>80){let d={instancePath:e+"/presentation/title",schemaPath:"#/properties/presentation/properties/title/maxLength",keyword:"maxLength",params:{limit:80},message:"must NOT have more than 80 characters"};r===null?r=[d]:r.push(d),a++}if(W(p)<1){let d={instancePath:e+"/presentation/title",schemaPath:"#/properties/presentation/properties/title/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[d]:r.push(d),a++}}else{let d={instancePath:e+"/presentation/title",schemaPath:"#/properties/presentation/properties/title/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[d]:r.push(d),a++}}if(l.body!==void 0){let p=l.body;if(typeof p=="string"){if(W(p)>160){let d={instancePath:e+"/presentation/body",schemaPath:"#/properties/presentation/properties/body/maxLength",keyword:"maxLength",params:{limit:160},message:"must NOT have more than 160 characters"};r===null?r=[d]:r.push(d),a++}}else{let d={instancePath:e+"/presentation/body",schemaPath:"#/properties/presentation/properties/body/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[d]:r.push(d),a++}}if(l.tag!==void 0){let p=l.tag;if(typeof p=="string"){if(W(p)>80){let d={instancePath:e+"/presentation/tag",schemaPath:"#/properties/presentation/properties/tag/maxLength",keyword:"maxLength",params:{limit:80},message:"must NOT have more than 80 characters"};r===null?r=[d]:r.push(d),a++}if(W(p)<1){let d={instancePath:e+"/presentation/tag",schemaPath:"#/properties/presentation/properties/tag/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[d]:r.push(d),a++}}else{let d={instancePath:e+"/presentation/tag",schemaPath:"#/properties/presentation/properties/tag/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[d]:r.push(d),a++}}}else{let p={instancePath:e+"/presentation",schemaPath:"#/properties/presentation/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[p]:r.push(p),a++}}}else{let l={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[l]:r.push(l),a++}return El.errors=r,a===0}function Xh(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,c=Xh.evaluated;c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.items=void 0);let l=a,p=!1,d=null,u=a;if(n&&typeof n=="object"&&!Array.isArray(n)){if(n.homepage===void 0){let g={instancePath:e,schemaPath:"#/oneOf/0/required",keyword:"required",params:{missingProperty:"homepage"},message:"must have required property 'homepage'"};r===null?r=[g]:r.push(g),a++}if(n.redirect_uris===void 0){let g={instancePath:e,schemaPath:"#/oneOf/0/required",keyword:"required",params:{missingProperty:"redirect_uris"},message:"must have required property 'redirect_uris'"};r===null?r=[g]:r.push(g),a++}if(n.distribution!==void 0&&n.distribution!=="web"){let g={instancePath:e+"/distribution",schemaPath:"#/oneOf/0/properties/distribution/const",keyword:"const",params:{allowedValue:"web"},message:"must be equal to constant"};r===null?r=[g]:r.push(g),a++}if(n.project_url!==void 0){let g={instancePath:e+"/project_url",schemaPath:"#/oneOf/0/properties/project_url/false schema",keyword:"false schema",params:{},message:"boolean schema is false"};r===null?r=[g]:r.push(g),a++}}var m=u===a;if(m){p=!0,d=0;var f={};f.distribution=!0,f.homepage=!0,f.redirect_uris=!0,f.project_url=!0}let h=a;if(n&&typeof n=="object"&&!Array.isArray(n)){if(n.distribution===void 0){let g={instancePath:e,schemaPath:"#/oneOf/1/required",keyword:"required",params:{missingProperty:"distribution"},message:"must have required property 'distribution'"};r===null?r=[g]:r.push(g),a++}if(n.distribution!==void 0&&n.distribution!=="portable"){let g={instancePath:e+"/distribution",schemaPath:"#/oneOf/1/properties/distribution/const",keyword:"const",params:{allowedValue:"portable"},message:"must be equal to constant"};r===null?r=[g]:r.push(g),a++}if(n.platform!==void 0){let g={instancePath:e+"/platform",schemaPath:"#/oneOf/1/properties/platform/false schema",keyword:"false schema",params:{},message:"boolean schema is false"};r===null?r=[g]:r.push(g),a++}if(n.homepage!==void 0){let g={instancePath:e+"/homepage",schemaPath:"#/oneOf/1/properties/homepage/false schema",keyword:"false schema",params:{},message:"boolean schema is false"};r===null?r=[g]:r.push(g),a++}if(n.redirect_uris!==void 0){let g={instancePath:e+"/redirect_uris",schemaPath:"#/oneOf/1/properties/redirect_uris/false schema",keyword:"false schema",params:{},message:"boolean schema is false"};r===null?r=[g]:r.push(g),a++}}var m=h===a;if(m&&p?(p=!1,d=[d,1]):m&&(p=!0,d=1,f!==!0&&(f=f||{},f.distribution=!0,f.platform=!0,f.homepage=!0,f.redirect_uris=!0)),p)a=l,r!==null&&(l?r.length=l:r=null);else{let g={instancePath:e,schemaPath:"#/oneOf",keyword:"oneOf",params:{passingSchemas:d},message:"must match exactly one schema in oneOf"};r===null?r=[g]:r.push(g),a++}if(n&&typeof n=="object"&&!Array.isArray(n)){if(n.manifest_version===void 0){let g={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"manifest_version"},message:"must have required property 'manifest_version'"};r===null?r=[g]:r.push(g),a++}if(n.id===void 0){let g={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"id"},message:"must have required property 'id'"};r===null?r=[g]:r.push(g),a++}if(n.name===void 0){let g={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"name"},message:"must have required property 'name'"};r===null?r=[g]:r.push(g),a++}for(let g in n)if(!aC.call(iC.properties,g)){let y={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:g},message:"must NOT have additional properties"};r===null?r=[y]:r.push(y),a++}if(n.manifest_version!==void 0&&n.manifest_version!==1){let g={instancePath:e+"/manifest_version",schemaPath:"#/properties/manifest_version/const",keyword:"const",params:{allowedValue:1},message:"must be equal to constant"};r===null?r=[g]:r.push(g),a++}if(n.distribution!==void 0){let g=n.distribution;if(!(g==="web"||g==="portable")){let y={instancePath:e+"/distribution",schemaPath:"#/properties/distribution/enum",keyword:"enum",params:{allowedValues:iC.properties.distribution.enum},message:"must be equal to one of the allowed values"};r===null?r=[y]:r.push(y),a++}}if(n.id!==void 0){let g=n.id;if(typeof g=="string"){if(W(g)>150){let y={instancePath:e+"/id",schemaPath:"#/properties/id/maxLength",keyword:"maxLength",params:{limit:150},message:"must NOT have more than 150 characters"};r===null?r=[y]:r.push(y),a++}if(W(g)<5){let y={instancePath:e+"/id",schemaPath:"#/properties/id/minLength",keyword:"minLength",params:{limit:5},message:"must NOT have fewer than 5 characters"};r===null?r=[y]:r.push(y),a++}if(!lC.test(g)){let y={instancePath:e+"/id",schemaPath:"#/properties/id/pattern",keyword:"pattern",params:{pattern:"^[a-z][a-z0-9-]*(\\.[a-z][a-z0-9-]*){2,}$"},message:'must match pattern "^[a-z][a-z0-9-]*(\\.[a-z][a-z0-9-]*){2,}$"'};r===null?r=[y]:r.push(y),a++}}else{let y={instancePath:e+"/id",schemaPath:"#/properties/id/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[y]:r.push(y),a++}}if(n.name!==void 0){let g=n.name;if(typeof g=="string"){if(W(g)>100){let y={instancePath:e+"/name",schemaPath:"#/properties/name/maxLength",keyword:"maxLength",params:{limit:100},message:"must NOT have more than 100 characters"};r===null?r=[y]:r.push(y),a++}if(W(g)<1){let y={instancePath:e+"/name",schemaPath:"#/properties/name/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[y]:r.push(y),a++}}else{let y={instancePath:e+"/name",schemaPath:"#/properties/name/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[y]:r.push(y),a++}}if(n.platform!==void 0&&n.platform!=="native"){let g={instancePath:e+"/platform",schemaPath:"#/properties/platform/const",keyword:"const",params:{allowedValue:"native"},message:"must be equal to constant"};r===null?r=[g]:r.push(g),a++}if(n.homepage!==void 0){let g=n.homepage;if(typeof g=="string"){if(!Qo.test(g)){let y={instancePath:e+"/homepage",schemaPath:"#/properties/homepage/pattern",keyword:"pattern",params:{pattern:"^https://"},message:'must match pattern "^https://"'};r===null?r=[y]:r.push(y),a++}if(!Wn(g)){let y={instancePath:e+"/homepage",schemaPath:"#/properties/homepage/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'};r===null?r=[y]:r.push(y),a++}}else{let y={instancePath:e+"/homepage",schemaPath:"#/properties/homepage/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[y]:r.push(y),a++}}if(n.project_url!==void 0){let g=n.project_url;if(typeof g=="string"){if(!Qo.test(g)){let y={instancePath:e+"/project_url",schemaPath:"#/properties/project_url/pattern",keyword:"pattern",params:{pattern:"^https://"},message:'must match pattern "^https://"'};r===null?r=[y]:r.push(y),a++}if(!Wn(g)){let y={instancePath:e+"/project_url",schemaPath:"#/properties/project_url/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'};r===null?r=[y]:r.push(y),a++}}else{let y={instancePath:e+"/project_url",schemaPath:"#/properties/project_url/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[y]:r.push(y),a++}}if(n.icon!==void 0){let g=n.icon;if(typeof g=="string"){if(!Qo.test(g)){let y={instancePath:e+"/icon",schemaPath:"#/properties/icon/pattern",keyword:"pattern",params:{pattern:"^https://"},message:'must match pattern "^https://"'};r===null?r=[y]:r.push(y),a++}if(!Wn(g)){let y={instancePath:e+"/icon",schemaPath:"#/properties/icon/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'};r===null?r=[y]:r.push(y),a++}}else{let y={instancePath:e+"/icon",schemaPath:"#/properties/icon/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[y]:r.push(y),a++}}if(n.redirect_uris!==void 0){let g=n.redirect_uris;if(Array.isArray(g)){if(g.length>10){let k={instancePath:e+"/redirect_uris",schemaPath:"#/properties/redirect_uris/maxItems",keyword:"maxItems",params:{limit:10},message:"must NOT have more than 10 items"};r===null?r=[k]:r.push(k),a++}if(g.length<1){let k={instancePath:e+"/redirect_uris",schemaPath:"#/properties/redirect_uris/minItems",keyword:"minItems",params:{limit:1},message:"must NOT have fewer than 1 items"};r===null?r=[k]:r.push(k),a++}let y=g.length;for(let k=0;k<y;k++){let S=g[k];if(typeof S=="string"){if(!Wn(S)){let x={instancePath:e+"/redirect_uris/"+k,schemaPath:"#/properties/redirect_uris/items/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'};r===null?r=[x]:r.push(x),a++}}else{let x={instancePath:e+"/redirect_uris/"+k,schemaPath:"#/properties/redirect_uris/items/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[x]:r.push(x),a++}}let v=g.length,_;if(v>1){let k={};for(;v--;){let S=g[v];if(typeof S=="string"){if(typeof k[S]=="number"){_=k[S];let x={instancePath:e+"/redirect_uris",schemaPath:"#/properties/redirect_uris/uniqueItems",keyword:"uniqueItems",params:{i:v,j:_},message:"must NOT have duplicate items (items ## "+_+" and "+v+" are identical)"};r===null?r=[x]:r.push(x),a++;break}k[S]=v}}}}else{let y={instancePath:e+"/redirect_uris",schemaPath:"#/properties/redirect_uris/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[y]:r.push(y),a++}}if(n.installation_origins!==void 0){let g=n.installation_origins;if(g&&typeof g=="object"&&!Array.isArray(g)){for(let y in g)if(!(y==="lab"||y==="staging"||y==="production")){let v={instancePath:e+"/installation_origins",schemaPath:"#/properties/installation_origins/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:y},message:"must NOT have additional properties"};r===null?r=[v]:r.push(v),a++}g.lab!==void 0&&(Pi(g.lab,{instancePath:e+"/installation_origins/lab",parentData:g,parentDataProperty:"lab",rootData:o,dynamicAnchors:s})||(r=r===null?Pi.errors:r.concat(Pi.errors),a=r.length)),g.staging!==void 0&&(Pi(g.staging,{instancePath:e+"/installation_origins/staging",parentData:g,parentDataProperty:"staging",rootData:o,dynamicAnchors:s})||(r=r===null?Pi.errors:r.concat(Pi.errors),a=r.length)),g.production!==void 0&&(Pi(g.production,{instancePath:e+"/installation_origins/production",parentData:g,parentDataProperty:"production",rootData:o,dynamicAnchors:s})||(r=r===null?Pi.errors:r.concat(Pi.errors),a=r.length))}else{let y={instancePath:e+"/installation_origins",schemaPath:"#/properties/installation_origins/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[y]:r.push(y),a++}}if(n.requirements!==void 0&&(Il(n.requirements,{instancePath:e+"/requirements",parentData:n,parentDataProperty:"requirements",rootData:o,dynamicAnchors:s})||(r=r===null?Il.errors:r.concat(Il.errors),a=r.length)),n.provisions!==void 0){let g=n.provisions;if(g&&typeof g=="object"&&!Array.isArray(g)){if(g.type_packs===void 0){let y={instancePath:e+"/provisions",schemaPath:"#/properties/provisions/required",keyword:"required",params:{missingProperty:"type_packs"},message:"must have required property 'type_packs'"};r===null?r=[y]:r.push(y),a++}for(let y in g)if(!(y==="configuration"||y==="type_packs")){let v={instancePath:e+"/provisions",schemaPath:"#/properties/provisions/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:y},message:"must NOT have additional properties"};r===null?r=[v]:r.push(v),a++}if(g.configuration!==void 0){let y=g.configuration;if(Array.isArray(y)){if(y.length>50){let _={instancePath:e+"/provisions/configuration",schemaPath:"#/properties/provisions/properties/configuration/maxItems",keyword:"maxItems",params:{limit:50},message:"must NOT have more than 50 items"};r===null?r=[_]:r.push(_),a++}let v=y.length;for(let _=0;_<v;_++)Cl(y[_],{instancePath:e+"/provisions/configuration/"+_,parentData:y,parentDataProperty:_,rootData:o,dynamicAnchors:s})||(r=r===null?Cl.errors:r.concat(Cl.errors),a=r.length)}else{let v={instancePath:e+"/provisions/configuration",schemaPath:"#/properties/provisions/properties/configuration/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[v]:r.push(v),a++}}if(g.type_packs!==void 0){let y=g.type_packs;if(Array.isArray(y)){if(y.length>20){let _={instancePath:e+"/provisions/type_packs",schemaPath:"#/properties/provisions/properties/type_packs/maxItems",keyword:"maxItems",params:{limit:20},message:"must NOT have more than 20 items"};r===null?r=[_]:r.push(_),a++}let v=y.length;for(let _=0;_<v;_++)Ol(y[_],{instancePath:e+"/provisions/type_packs/"+_,parentData:y,parentDataProperty:_,rootData:o,dynamicAnchors:s})||(r=r===null?Ol.errors:r.concat(Ol.errors),a=r.length)}else{let v={instancePath:e+"/provisions/type_packs",schemaPath:"#/properties/provisions/properties/type_packs/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[v]:r.push(v),a++}}}else{let y={instancePath:e+"/provisions",schemaPath:"#/properties/provisions/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[y]:r.push(y),a++}}if(n.notifications!==void 0){let g=n.notifications;if(g&&typeof g=="object"&&!Array.isArray(g)){if(g.criteria===void 0){let y={instancePath:e+"/notifications",schemaPath:"#/properties/notifications/required",keyword:"required",params:{missingProperty:"criteria"},message:"must have required property 'criteria'"};r===null?r=[y]:r.push(y),a++}for(let y in g)if(!(y==="criteria"||y==="native_delivery")){let v={instancePath:e+"/notifications",schemaPath:"#/properties/notifications/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:y},message:"must NOT have additional properties"};r===null?r=[v]:r.push(v),a++}if(g.criteria!==void 0){let y=g.criteria;if(Array.isArray(y)){if(y.length>50){let _={instancePath:e+"/notifications/criteria",schemaPath:"#/properties/notifications/properties/criteria/maxItems",keyword:"maxItems",params:{limit:50},message:"must NOT have more than 50 items"};r===null?r=[_]:r.push(_),a++}let v=y.length;for(let _=0;_<v;_++)El(y[_],{instancePath:e+"/notifications/criteria/"+_,parentData:y,parentDataProperty:_,rootData:o,dynamicAnchors:s})||(r=r===null?El.errors:r.concat(El.errors),a=r.length)}else{let v={instancePath:e+"/notifications/criteria",schemaPath:"#/properties/notifications/properties/criteria/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[v]:r.push(v),a++}}if(g.native_delivery!==void 0){let y=g.native_delivery,v=a,_=!1,k=null,S=a;if(y&&typeof y=="object"&&!Array.isArray(y)){if(y.mode===void 0){let P={instancePath:e+"/notifications/native_delivery",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/0/required",keyword:"required",params:{missingProperty:"mode"},message:"must have required property 'mode'"};r===null?r=[P]:r.push(P),a++}if(y.firebase_project_id===void 0){let P={instancePath:e+"/notifications/native_delivery",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/0/required",keyword:"required",params:{missingProperty:"firebase_project_id"},message:"must have required property 'firebase_project_id'"};r===null?r=[P]:r.push(P),a++}for(let P in y)if(!(P==="mode"||P==="firebase_project_id")){let I={instancePath:e+"/notifications/native_delivery",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/0/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:P},message:"must NOT have additional properties"};r===null?r=[I]:r.push(I),a++}if(y.mode!==void 0&&y.mode!=="managed_fcm"){let P={instancePath:e+"/notifications/native_delivery/mode",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/0/properties/mode/const",keyword:"const",params:{allowedValue:"managed_fcm"},message:"must be equal to constant"};r===null?r=[P]:r.push(P),a++}if(y.firebase_project_id!==void 0){let P=y.firebase_project_id;if(typeof P=="string"){if(W(P)>63){let I={instancePath:e+"/notifications/native_delivery/firebase_project_id",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/0/properties/firebase_project_id/maxLength",keyword:"maxLength",params:{limit:63},message:"must NOT have more than 63 characters"};r===null?r=[I]:r.push(I),a++}if(W(P)<6){let I={instancePath:e+"/notifications/native_delivery/firebase_project_id",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/0/properties/firebase_project_id/minLength",keyword:"minLength",params:{limit:6},message:"must NOT have fewer than 6 characters"};r===null?r=[I]:r.push(I),a++}if(!cC.test(P)){let I={instancePath:e+"/notifications/native_delivery/firebase_project_id",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/0/properties/firebase_project_id/pattern",keyword:"pattern",params:{pattern:"^[a-z][a-z0-9-]*[a-z0-9]$"},message:'must match pattern "^[a-z][a-z0-9-]*[a-z0-9]$"'};r===null?r=[I]:r.push(I),a++}}else{let I={instancePath:e+"/notifications/native_delivery/firebase_project_id",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/0/properties/firebase_project_id/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[I]:r.push(I),a++}}}else{let P={instancePath:e+"/notifications/native_delivery",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/0/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[P]:r.push(P),a++}var b=S===a;if(b){_=!0,k=0;var w=!0}let x=a;if(y&&typeof y=="object"&&!Array.isArray(y)){if(y.mode===void 0){let P={instancePath:e+"/notifications/native_delivery",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/1/required",keyword:"required",params:{missingProperty:"mode"},message:"must have required property 'mode'"};r===null?r=[P]:r.push(P),a++}if(y.url===void 0){let P={instancePath:e+"/notifications/native_delivery",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/1/required",keyword:"required",params:{missingProperty:"url"},message:"must have required property 'url'"};r===null?r=[P]:r.push(P),a++}for(let P in y)if(!(P==="mode"||P==="url")){let I={instancePath:e+"/notifications/native_delivery",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/1/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:P},message:"must NOT have additional properties"};r===null?r=[I]:r.push(I),a++}if(y.mode!==void 0&&y.mode!=="webhook"){let P={instancePath:e+"/notifications/native_delivery/mode",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/1/properties/mode/const",keyword:"const",params:{allowedValue:"webhook"},message:"must be equal to constant"};r===null?r=[P]:r.push(P),a++}if(y.url!==void 0){let P=y.url;if(typeof P=="string"){if(!Qo.test(P)){let I={instancePath:e+"/notifications/native_delivery/url",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/1/properties/url/pattern",keyword:"pattern",params:{pattern:"^https://"},message:'must match pattern "^https://"'};r===null?r=[I]:r.push(I),a++}if(!Wn(P)){let I={instancePath:e+"/notifications/native_delivery/url",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/1/properties/url/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'};r===null?r=[I]:r.push(I),a++}}else{let I={instancePath:e+"/notifications/native_delivery/url",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/1/properties/url/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[I]:r.push(I),a++}}}else{let P={instancePath:e+"/notifications/native_delivery",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/1/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[P]:r.push(P),a++}var b=x===a;if(b&&_?(_=!1,k=[k,1]):b&&(_=!0,k=1,w!==!0&&(w=!0)),_)a=v,r!==null&&(v?r.length=v:r=null);else{let P={instancePath:e+"/notifications/native_delivery",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf",keyword:"oneOf",params:{passingSchemas:k},message:"must match exactly one schema in oneOf"};r===null?r=[P]:r.push(P),a++}}}else{let y={instancePath:e+"/notifications",schemaPath:"#/properties/notifications/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[y]:r.push(y),a++}}}else{let g={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[g]:r.push(g),a++}return Xh.errors=r,a===0}var sC,ZI,aC,W,lC,Qo,cC,Wn,QI,eC,ai,tC,pC,Zh,ql,Qh,gl,dC,nC,Yh,uC,iC,rC,oL,oC,fC=C(()=>{"use strict";sC=Jh,ZI={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/connect/schemas/mdbase-app.v1.json",title:"mdbase connect bundled application manifest v1",type:"object",additionalProperties:!1,required:["manifest_version","id","name"],properties:{manifest_version:{const:1},distribution:{enum:["web","portable"],description:"Portable declarations use device authorization and do not claim a browser origin."},id:{type:"string",minLength:5,maxLength:150,pattern:"^[a-z][a-z0-9-]*(\\.[a-z][a-z0-9-]*){2,}$",description:"Stable reverse-domain application identifier. This is presentation metadata, not publisher authentication."},name:{type:"string",minLength:1,maxLength:100},platform:{const:"native",description:"Unverified native app; permits literal IPv4 loopback HTTP on any port."},homepage:{type:"string",format:"uri",pattern:"^https://"},project_url:{type:"string",format:"uri",pattern:"^https://"},icon:{type:"string",format:"uri",pattern:"^https://"},redirect_uris:{type:"array",minItems:1,maxItems:10,uniqueItems:!0,items:{type:"string",format:"uri",description:"An HTTPS URI on the homepage origin or a private-use scheme derived from the application ID."}},installation_origins:{type:"object",additionalProperties:!1,properties:{lab:{$ref:"#/$defs/installationOriginPolicy"},staging:{$ref:"#/$defs/installationOriginPolicy"},production:{$ref:"#/$defs/installationOriginPolicy"}}},requirements:{$ref:"#/$defs/requirements"},provisions:{type:"object",additionalProperties:!1,required:["type_packs"],properties:{configuration:{type:"array",maxItems:50,items:{$ref:"#/$defs/configurationProvision"}},type_packs:{type:"array",maxItems:20,items:{$ref:"#/$defs/typePackProvision"}}}},notifications:{type:"object",additionalProperties:!1,required:["criteria"],properties:{criteria:{type:"array",maxItems:50,items:{$ref:"#/$defs/notificationCriterion"}},native_delivery:{$ref:"#/$defs/nativeNotificationDelivery"}}}},oneOf:[{required:["homepage","redirect_uris"],properties:{distribution:{const:"web"},homepage:!0,redirect_uris:!0,project_url:!1}},{required:["distribution"],properties:{distribution:{const:"portable"},platform:!1,homepage:!1,redirect_uris:!1}}],$defs:{installationOriginPolicy:{type:"object",additionalProperties:!1,properties:{"app-runtime":{$ref:"#/$defs/installationOrigins"},mobile:{$ref:"#/$defs/installationOrigins"}}},installationOrigins:{type:"array",maxItems:16,uniqueItems:!0,items:{type:"string",minLength:1,maxLength:255,format:"uri"}},identifier:{type:"string",minLength:1,maxLength:100,pattern:"^[a-z0-9]+(?:[._-][a-z0-9]+)*$"},duration:{type:"string",pattern:"^[0-9]+(ms|s|m|h|d)$"},contract:{type:"object",additionalProperties:!1,required:["id","version","digest"],properties:{id:{$ref:"#/$defs/identifier"},version:{type:"string",pattern:"^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$"},digest:{type:"string",pattern:"^sha256:[0-9a-f]{64}$"}}},requirements:{type:"object",additionalProperties:!1,required:["access","contracts"],properties:{capabilities:{$ref:"#/$defs/capabilityRequirements"},access:{const:"full_collection",description:"Compatibility declaration for collection-level application authorization."},collection_kind:{const:"hosted",description:"Require a durable provider-backed collection with direct sync support."},people:{type:"object",additionalProperties:!1,required:["version"],anyOf:[{required:["required"]},{required:["optional"]}],properties:{version:{const:1},required:{$ref:"#/$defs/peoplePermissions"},optional:{$ref:"#/$defs/peoplePermissions"}}},files:{$ref:"#/$defs/fileRequirement"},configuration:{type:"array",maxItems:50,items:{$ref:"#/$defs/configurationRequirement"}},contracts:{type:"array",maxItems:20,uniqueItems:!0,items:{$ref:"#/$defs/contract"}}}},capabilityRequirements:{type:"object",additionalProperties:!1,required:["contract_version","required"],properties:{contract_version:{const:2},required:{type:"array",maxItems:32,uniqueItems:!0,items:{$ref:"#/$defs/applicationCapability"}},optional:{type:"array",maxItems:32,uniqueItems:!0,items:{$ref:"#/$defs/applicationCapability"}}}},configurationValue:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"}]},configurationRequirement:{type:"object",additionalProperties:!1,required:["id","path","predicate","value"],properties:{id:{type:"string",minLength:1,maxLength:100,pattern:"^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$"},path:{type:"string",minLength:1,maxLength:1024},predicate:{const:"contains"},value:{$ref:"#/$defs/configurationValue"}}},configurationProvision:{type:"object",additionalProperties:!1,required:["requirement","operation","path","value"],properties:{requirement:{type:"string",minLength:1,maxLength:100,pattern:"^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$"},operation:{const:"set_add"},path:{type:"string",minLength:1,maxLength:1024},value:{$ref:"#/$defs/configurationValue"}}},applicationCapability:{enum:["collection.read","records.create","records.edit","records.delete","views.manage","definitions.manage","background.schedule","offline.replica","history.read"]},peoplePermissions:{type:"array",minItems:1,uniqueItems:!0,items:{enum:["identity","members"]}},fileRequirement:{type:"object",additionalProperties:!1,required:["required","scope"],properties:{required:{$ref:"#/$defs/fileActions"},optional:{$ref:"#/$defs/fileActions"},scope:{$ref:"#/$defs/fileScope"}}},fileActions:{type:"array",minItems:1,maxItems:6,uniqueItems:!0,items:{enum:["list","read","add","replace","move","delete"]}},fileScope:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","folders"],properties:{kind:{const:"selected_folders"},folders:{type:"array",minItems:1,maxItems:100,uniqueItems:!0,items:{type:"string",minLength:1,maxLength:1024,pattern:"^(?!/)(?!\\.)(?!.*//)(?!.*\\\\)(?!.*/\\.)(?!(?:_contracts|_schemas|_types|_views|node_modules)(?:/|$))(?!.*\\/(?:_contracts|_schemas|_types|_views|node_modules)(?:/|$))(?!.*/$).+$"}}}},{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:{const:"collection"}}}]},typePackProvision:{type:"object",additionalProperties:!1,required:["manifest","resources","provides"],properties:{manifest:{$ref:"#/$defs/typePackManifest"},resources:{type:"array",minItems:1,maxItems:100,items:{$ref:"#/$defs/typePackSourceResource"}},provides:{type:"array",maxItems:20,uniqueItems:!0,items:{$ref:"#/$defs/contract"}}}},typePackManifest:{type:"object",required:["kind","id","version","resources"],properties:{kind:{const:"mdbase.type-pack"},id:{$ref:"#/$defs/identifier"},version:{$ref:"#/$defs/contract/properties/version"},name:{type:"string",minLength:1,maxLength:100},description:{type:"string",maxLength:500},resources:{type:"array",minItems:1,maxItems:100,items:{$ref:"#/$defs/typePackManifestResource"}}},patternProperties:{"^x-[A-Za-z][A-Za-z0-9._:-]{0,127}$":!0},additionalProperties:!1},typePackManifestResource:{type:"object",additionalProperties:!1,required:["kind","mode","source","target","digest"],properties:{kind:{enum:["contract","type","schema"]},mode:{enum:["managed","seed"]},upgrade_from:{oneOf:[{$ref:"#/$defs/typePackUpgradeBaseline"},{type:"array",minItems:1,items:{$ref:"#/$defs/typePackUpgradeBaseline"}}]},source:{type:"string",minLength:1,maxLength:240},target:{type:"string",minLength:1,maxLength:240},digest:{type:"string",pattern:"^sha256:[0-9a-f]{64}$"}}},typePackUpgradeBaseline:{type:"object",additionalProperties:!1,required:["digest","document"],properties:{digest:{type:"string",pattern:"^sha256:[0-9a-f]{64}$"},document:{type:"string",maxLength:262144},version:{type:"integer",minimum:1}}},typePackSourceResource:{type:"object",additionalProperties:!1,required:["source","document"],properties:{source:{type:"string",minLength:1,maxLength:240},document:{type:"string",maxLength:262144}}},notificationCriterion:{type:"object",additionalProperties:!1,required:["id","event","presentation"],properties:{id:{$ref:"#/$defs/identifier"},event:{$ref:"#/$defs/contract"},if:{type:"object",additionalProperties:!1,required:["$expr"],properties:{$expr:{type:"string",minLength:1,maxLength:4096}}},debounce:{$ref:"#/$defs/duration"},minimum_interval:{$ref:"#/$defs/duration"},presentation:{type:"object",additionalProperties:!1,required:["title"],properties:{title:{type:"string",minLength:1,maxLength:80},body:{type:"string",maxLength:160},tag:{type:"string",minLength:1,maxLength:80}}}}},nativeNotificationDelivery:{oneOf:[{type:"object",additionalProperties:!1,required:["mode","firebase_project_id"],properties:{mode:{const:"managed_fcm"},firebase_project_id:{type:"string",minLength:6,maxLength:63,pattern:"^[a-z][a-z0-9-]*[a-z0-9]$"}}},{type:"object",additionalProperties:!1,required:["mode","url"],properties:{mode:{const:"webhook"},url:{type:"string",format:"uri",pattern:"^https://"}}}]}}},aC=Object.prototype.hasOwnProperty,W=(function(e){let t=e.length,i=0,o=0,s;for(;o<t;)i++,s=e.charCodeAt(o++),s>=55296&&s<=56319&&o<t&&(s=e.charCodeAt(o),(s&64512)===56320&&o++);return i}),lC=new RegExp("^[a-z][a-z0-9-]*(\\.[a-z][a-z0-9-]*){2,}$","u"),Qo=new RegExp("^https://","u"),cC=new RegExp("^[a-z][a-z0-9-]*[a-z0-9]$","u"),Wn=(()=>{let n=/\/|:/,e=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;return function(i){return n.test(i)&&e.test(i)}})();Si.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};QI={type:"array",minItems:1,uniqueItems:!0,items:{enum:["identity","members"]}},eC={enum:["collection.read","records.create","records.edit","records.delete","views.manage","definitions.manage","background.schedule","offline.replica","history.read"]},ai=(function n(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){if(e.constructor!==t.constructor)return!1;var i,o,s;if(Array.isArray(e)){if(i=e.length,i!=t.length)return!1;for(o=i;o--!==0;)if(!n(e[o],t[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();if(s=Object.keys(e),i=s.length,i!==Object.keys(t).length)return!1;for(o=i;o--!==0;)if(!Object.prototype.hasOwnProperty.call(t,s[o]))return!1;for(o=i;o--!==0;){var r=s[o];if(!n(e[r],t[r]))return!1}return!0}return e!==e&&t!==t});hl.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};tC={type:"array",minItems:1,maxItems:6,uniqueItems:!0,items:{enum:["list","read","add","replace","move","delete"]}},pC=new RegExp("^(?!/)(?!\\.)(?!.*//)(?!.*\\\\)(?!.*/\\.)(?!(?:_contracts|_schemas|_types|_views|node_modules)(?:/|$))(?!.*\\/(?:_contracts|_schemas|_types|_views|node_modules)(?:/|$))(?!.*/$).+$","u");ml.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};Zh=new RegExp("^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$","u");yl.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};ql=new RegExp("^[a-z0-9]+(?:[._-][a-z0-9]+)*$","u"),Qh=new RegExp("^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$","u"),gl=new RegExp("^sha256:[0-9a-f]{64}$","u");xi.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};bl.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};wl.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};dC=new RegExp("^x-[A-Za-z][A-Za-z0-9._:-]{0,127}$","u"),nC={type:"object",additionalProperties:!1,required:["kind","mode","source","target","digest"],properties:{kind:{enum:["contract","type","schema"]},mode:{enum:["managed","seed"]},upgrade_from:{oneOf:[{$ref:"#/$defs/typePackUpgradeBaseline"},{type:"array",minItems:1,items:{$ref:"#/$defs/typePackUpgradeBaseline"}}]},source:{type:"string",minLength:1,maxLength:240},target:{type:"string",minLength:1,maxLength:240},digest:{type:"string",pattern:"^sha256:[0-9a-f]{64}$"}}};vl.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};_l.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};Al.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};Yh=new RegExp("^[0-9]+(ms|s|m|h|d)$","u");kl.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};Jh.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};uC=Xh,iC={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/connect/schemas/mdbase-app.legacy-v1.json",title:"mdbase connect bundled application manifest v1",type:"object",additionalProperties:!1,required:["manifest_version","id","name"],properties:{manifest_version:{const:1},distribution:{enum:["web","portable"],description:"Portable declarations use device authorization and do not claim a browser origin."},id:{type:"string",minLength:5,maxLength:150,pattern:"^[a-z][a-z0-9-]*(\\.[a-z][a-z0-9-]*){2,}$",description:"Stable reverse-domain application identifier. This is presentation metadata, not publisher authentication."},name:{type:"string",minLength:1,maxLength:100},platform:{const:"native",description:"Unverified native app; permits literal IPv4 loopback HTTP on any port."},homepage:{type:"string",format:"uri",pattern:"^https://"},project_url:{type:"string",format:"uri",pattern:"^https://"},icon:{type:"string",format:"uri",pattern:"^https://"},redirect_uris:{type:"array",minItems:1,maxItems:10,uniqueItems:!0,items:{type:"string",format:"uri",description:"An HTTPS URI on the homepage origin or a private-use scheme derived from the application ID."}},installation_origins:{type:"object",additionalProperties:!1,properties:{lab:{$ref:"#/$defs/installationOriginPolicy"},staging:{$ref:"#/$defs/installationOriginPolicy"},production:{$ref:"#/$defs/installationOriginPolicy"}}},requirements:{$ref:"#/$defs/requirements"},provisions:{type:"object",additionalProperties:!1,required:["type_packs"],properties:{configuration:{type:"array",maxItems:50,items:{$ref:"#/$defs/configurationProvision"}},type_packs:{type:"array",maxItems:20,items:{$ref:"#/$defs/typePackProvision"}}}},notifications:{type:"object",additionalProperties:!1,required:["criteria"],properties:{criteria:{type:"array",maxItems:50,items:{$ref:"#/$defs/notificationCriterion"}},native_delivery:{$ref:"#/$defs/nativeNotificationDelivery"}}}},oneOf:[{required:["homepage","redirect_uris"],properties:{distribution:{const:"web"},homepage:!0,redirect_uris:!0,project_url:!1}},{required:["distribution"],properties:{distribution:{const:"portable"},platform:!1,homepage:!1,redirect_uris:!1}}],$defs:{installationOriginPolicy:{type:"object",additionalProperties:!1,properties:{"app-runtime":{$ref:"#/$defs/installationOrigins"},mobile:{$ref:"#/$defs/installationOrigins"}}},installationOrigins:{type:"array",maxItems:16,uniqueItems:!0,items:{type:"string",minLength:1,maxLength:255,format:"uri"}},identifier:{type:"string",minLength:1,maxLength:100,pattern:"^[a-z0-9]+(?:[._-][a-z0-9]+)*$"},duration:{type:"string",pattern:"^[0-9]+(ms|s|m|h|d)$"},contract:{type:"object",additionalProperties:!1,required:["id","version","digest"],properties:{id:{$ref:"#/$defs/identifier"},version:{type:"string",pattern:"^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$"},digest:{type:"string",pattern:"^sha256:[0-9a-f]{64}$"}}},requirements:{type:"object",additionalProperties:!1,required:["access","contracts"],properties:{capabilities:{$ref:"#/$defs/capabilityRequirements"},access:{const:"full_collection",description:"Compatibility declaration for collection-level application authorization."},collection_kind:{const:"hosted",description:"Require a durable provider-backed collection with direct sync support."},files:{$ref:"#/$defs/fileRequirement"},configuration:{type:"array",maxItems:50,items:{$ref:"#/$defs/configurationRequirement"}},contracts:{type:"array",maxItems:20,uniqueItems:!0,items:{$ref:"#/$defs/contract"}}}},capabilityRequirements:{type:"object",additionalProperties:!1,required:["contract_version","required"],properties:{contract_version:{const:1},required:{type:"array",maxItems:32,uniqueItems:!0,items:{$ref:"#/$defs/applicationCapability"}},optional:{type:"array",maxItems:32,uniqueItems:!0,items:{$ref:"#/$defs/applicationCapability"}}}},configurationValue:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"}]},configurationRequirement:{type:"object",additionalProperties:!1,required:["id","path","predicate","value"],properties:{id:{type:"string",minLength:1,maxLength:100,pattern:"^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$"},path:{type:"string",minLength:1,maxLength:1024},predicate:{const:"contains"},value:{$ref:"#/$defs/configurationValue"}}},configurationProvision:{type:"object",additionalProperties:!1,required:["requirement","operation","path","value"],properties:{requirement:{type:"string",minLength:1,maxLength:100,pattern:"^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$"},operation:{const:"set_add"},path:{type:"string",minLength:1,maxLength:1024},value:{$ref:"#/$defs/configurationValue"}}},applicationCapability:{enum:["collection.inspect","records.watch","records.read","records.query","records.validate","records.create","records.update","records.delete","records.rename","views.list","views.execute","views.source.read","views.source.create","views.source.update","views.source.delete","definitions.contracts.current","definitions.read","definitions.create","definitions.update","definitions.type-pack.inspect","definitions.type-pack.apply","collection.setup.apply","timers.list","timers.put","timers.cancel","timers.reconcile","sync.offline-replica","notifications.background-delivery","files.list","files.read","files.add","files.replace","files.move","files.delete"]},fileRequirement:{type:"object",additionalProperties:!1,required:["actions","scope"],properties:{actions:{type:"array",minItems:1,maxItems:6,uniqueItems:!0,items:{enum:["list","read","add","replace","move","delete"]}},scope:{$ref:"#/$defs/fileScope"}}},fileScope:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","folders"],properties:{kind:{const:"selected_folders"},folders:{type:"array",minItems:1,maxItems:100,uniqueItems:!0,items:{type:"string",minLength:1,maxLength:1024,pattern:"^(?!/)(?!\\.)(?!.*//)(?!.*\\\\)(?!.*/\\.)(?!(?:_contracts|_schemas|_types|_views|node_modules)(?:/|$))(?!.*\\/(?:_contracts|_schemas|_types|_views|node_modules)(?:/|$))(?!.*/$).+$"}}}},{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:{const:"collection"}}}]},typePackProvision:{type:"object",additionalProperties:!1,required:["manifest","resources","provides"],properties:{manifest:{$ref:"#/$defs/typePackManifest"},resources:{type:"array",minItems:1,maxItems:100,items:{$ref:"#/$defs/typePackSourceResource"}},provides:{type:"array",maxItems:20,uniqueItems:!0,items:{$ref:"#/$defs/contract"}}}},typePackManifest:{type:"object",required:["kind","id","version","resources"],properties:{kind:{const:"mdbase.type-pack"},id:{$ref:"#/$defs/identifier"},version:{$ref:"#/$defs/contract/properties/version"},name:{type:"string",minLength:1,maxLength:100},description:{type:"string",maxLength:500},resources:{type:"array",minItems:1,maxItems:100,items:{$ref:"#/$defs/typePackManifestResource"}}},patternProperties:{"^x-[A-Za-z][A-Za-z0-9._:-]{0,127}$":!0},additionalProperties:!1},typePackManifestResource:{type:"object",additionalProperties:!1,required:["kind","mode","source","target","digest"],properties:{kind:{enum:["contract","type","schema"]},mode:{enum:["managed","seed"]},source:{type:"string",minLength:1,maxLength:240},target:{type:"string",minLength:1,maxLength:240},digest:{type:"string",pattern:"^sha256:[0-9a-f]{64}$"}}},typePackSourceResource:{type:"object",additionalProperties:!1,required:["source","document"],properties:{source:{type:"string",minLength:1,maxLength:240},document:{type:"string",maxLength:262144}}},notificationCriterion:{type:"object",additionalProperties:!1,required:["id","event","presentation"],properties:{id:{$ref:"#/$defs/identifier"},event:{$ref:"#/$defs/contract"},if:{type:"object",additionalProperties:!1,required:["$expr"],properties:{$expr:{type:"string",minLength:1,maxLength:4096}}},debounce:{$ref:"#/$defs/duration"},minimum_interval:{$ref:"#/$defs/duration"},presentation:{type:"object",additionalProperties:!1,required:["title"],properties:{title:{type:"string",minLength:1,maxLength:80},body:{type:"string",maxLength:160},tag:{type:"string",minLength:1,maxLength:80}}}}},nativeNotificationDelivery:{oneOf:[{type:"object",additionalProperties:!1,required:["mode","firebase_project_id"],properties:{mode:{const:"managed_fcm"},firebase_project_id:{type:"string",minLength:6,maxLength:63,pattern:"^[a-z][a-z0-9-]*[a-z0-9]$"}}},{type:"object",additionalProperties:!1,required:["mode","url"],properties:{mode:{const:"webhook"},url:{type:"string",format:"uri",pattern:"^https://"}}}]}}};Pi.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};rC={enum:["collection.inspect","records.watch","records.read","records.query","records.validate","records.create","records.update","records.delete","records.rename","views.list","views.execute","views.source.read","views.source.create","views.source.update","views.source.delete","definitions.contracts.current","definitions.read","definitions.create","definitions.update","definitions.type-pack.inspect","definitions.type-pack.apply","collection.setup.apply","timers.list","timers.put","timers.cancel","timers.reconcile","sync.offline-replica","notifications.background-delivery","files.list","files.read","files.add","files.replace","files.move","files.delete"]};Sl.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};oL={type:"object",additionalProperties:!1,required:["actions","scope"],properties:{actions:{type:"array",minItems:1,maxItems:6,uniqueItems:!0,items:{enum:["list","read","add","replace","move","delete"]}},scope:{$ref:"#/$defs/fileScope"}}};Pl.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};xl.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};Ii.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};Il.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};Cl.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};oC={type:"object",additionalProperties:!1,required:["kind","mode","source","target","digest"],properties:{kind:{enum:["contract","type","schema"]},mode:{enum:["managed","seed"]},source:{type:"string",minLength:1,maxLength:240},target:{type:"string",minLength:1,maxLength:240},digest:{type:"string",pattern:"^sha256:[0-9a-f]{64}$"}}};Rl.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};Ol.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};El.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};Xh.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1}});function Tv(n,e){let t=n===1?aL:n===2?sL:void 0;if(!(!t||!Object.hasOwn(t,e)))return[...t[e]]}var sL,hC,aL,GK,Mv,em=C(()=>{sL={"collection.read":["describe","changes","read","query","list_views","execute_view","read_view_source","validate","read_type"],"records.create":["create"],"records.edit":["update","rename"],"records.delete":["delete"],"views.manage":["create_view_source","update_view_source","delete_view_source"],"definitions.manage":["create_type","update_type","assess_type_pack","apply_type_pack"],"background.schedule":["list_timers","put_timer","cancel_timer","reconcile_timers"],"offline.replica":["sync"],"history.read":["record_history","record_version"]},hC=["assess_collection_setup","apply_collection_setup"],aL=Object.freeze({"collection.inspect":Object.freeze(["describe"]),"records.watch":Object.freeze(["changes"]),"records.read":Object.freeze(["read"]),"records.query":Object.freeze(["query"]),"records.validate":Object.freeze(["validate"]),"records.create":Object.freeze(["create"]),"records.update":Object.freeze(["update"]),"records.delete":Object.freeze(["delete"]),"records.rename":Object.freeze(["rename"]),"views.list":Object.freeze(["list_views"]),"views.execute":Object.freeze(["execute_view"]),"views.source.read":Object.freeze(["read_view_source"]),"views.source.create":Object.freeze(["create_view_source"]),"views.source.update":Object.freeze(["update_view_source"]),"views.source.delete":Object.freeze(["delete_view_source"]),"definitions.contracts.current":Object.freeze([]),"definitions.read":Object.freeze(["read_type"]),"definitions.create":Object.freeze(["create_type"]),"definitions.update":Object.freeze(["update_type"]),"definitions.type-pack.inspect":Object.freeze(["assess_type_pack"]),"definitions.type-pack.apply":Object.freeze(["assess_type_pack","apply_type_pack"]),"collection.setup.apply":Object.freeze(["assess_collection_setup","apply_collection_setup"]),"timers.list":Object.freeze(["list_timers"]),"timers.put":Object.freeze(["put_timer"]),"timers.cancel":Object.freeze(["cancel_timer"]),"timers.reconcile":Object.freeze(["reconcile_timers"]),"sync.offline-replica":Object.freeze(["sync"]),"notifications.background-delivery":Object.freeze([]),"files.list":Object.freeze([]),"files.read":Object.freeze([]),"files.add":Object.freeze([]),"files.replace":Object.freeze([]),"files.move":Object.freeze([]),"files.delete":Object.freeze([])});GK=Object.freeze([1,2]),Mv=Object.freeze(["application-authorization-v2-issuance"])});function mC(n,e={}){return{actions:[...new Set([...n.required,...e.includeOptional===!1?[]:n.optional??[]])],scope:structuredClone(n.scope)}}var JK,XK,Lv=C(()=>{JK=new Uint8Array([77,68,66,70]),XK=new Uint8Array([77,68,66,82])});var yC,jv=C(()=>{yC={access_denied:{category:"authorization",recovery:"reauthorize"},access_paused:{category:"availability",recovery:"resume_connector_access"},application_authorization_issuance_disabled:{category:"authorization",recovery:"reauthorize"},application_declaration_mismatch:{category:"authorization",recovery:"reauthorize"},application_identity_unavailable:{category:"compatibility",recovery:"upgrade_application"},application_reauthorization_required:{category:"authorization",recovery:"reauthorize"},application_semantic_version_mismatch:{category:"authorization",recovery:"reauthorize"},approval_window_blocked:{category:"authorization",recovery:"reauthorize"},authority_authorization_changed:{category:"authorization",recovery:"reauthorize"},authorization_binding_incompatible:{category:"compatibility",recovery:"upgrade_application"},authorization_cancelled:{category:"cancellation",recovery:"none"},authorization_expired:{category:"authorization",recovery:"reauthorize"},authorization_replayed:{category:"integrity",recovery:"reauthorize"},browser_required:{category:"compatibility",recovery:"none"},callback_url_required:{category:"validation",recovery:"fix_request"},capability_contract_incompatible:{category:"compatibility",recovery:"upgrade_application"},change_cursor_reset:{category:"conflict",recovery:"refresh"},collection_access_denied:{category:"authorization",recovery:"reauthorize"},collection_claimed_by_newer_runtime:{category:"compatibility",recovery:"upgrade_connector"},collection_configuration_invalid:{category:"validation",recovery:"repair_collection"},collection_contracts_missing:{category:"compatibility",recovery:"choose_collection"},collection_incompatible:{category:"compatibility",recovery:"choose_collection"},collection_invalid:{category:"validation",recovery:"repair_collection"},collection_kind_unsupported:{category:"compatibility",recovery:"choose_collection"},collection_mismatch:{category:"selection",recovery:"choose_collection"},collection_not_found:{category:"selection",recovery:"choose_collection"},collection_not_ready:{category:"selection",recovery:"choose_collection"},collection_not_selected:{category:"selection",recovery:"choose_collection"},collection_type_registry_invalid:{category:"validation",recovery:"repair_collection"},collection_unavailable:{category:"availability",recovery:"choose_collection"},collection_version_unsupported:{category:"compatibility",recovery:"upgrade_collection"},concurrent_modification:{category:"conflict",recovery:"refresh"},connector_busy:{category:"availability",recovery:"retry"},connector_identity_changed:{category:"integrity",recovery:"reauthorize"},connector_offline:{category:"availability",recovery:"retry"},connector_upgrade_required:{category:"compatibility",recovery:"upgrade_connector"},cursor_capacity_exhausted:{category:"availability",recovery:"retry"},device_authorization_failed:{category:"authorization",recovery:"reauthorize"},direct_operation_rejected:{category:"authorization",recovery:"reauthorize"},discovery_failed:{category:"availability",recovery:"retry"},durable_mutation_unsupported:{category:"compatibility",recovery:"upgrade_connector"},encrypted_relay_rejected:{category:"authorization",recovery:"reauthorize"},encryption_required:{category:"authorization",recovery:"reauthorize"},expired_token:{category:"authorization",recovery:"reauthorize"},file_changed_during_move:{category:"conflict",recovery:"refresh"},file_changed_during_read:{category:"conflict",recovery:"refresh"},file_index_warming:{category:"availability",recovery:"retry"},file_list_changed:{category:"conflict",recovery:"refresh"},file_move_failed:{category:"internal",recovery:"contact_support"},file_mutation_conflict:{category:"conflict",recovery:"resolve_conflict"},file_not_found:{category:"conflict",recovery:"refresh"},file_source_mismatch:{category:"conflict",recovery:"refresh"},file_upload_incomplete:{category:"conflict",recovery:"retry"},fresh_request_required:{category:"availability",recovery:"retry"},generation_expired:{category:"conflict",recovery:"refresh"},hosted_provider_unavailable:{category:"availability",recovery:"retry"},insufficient_access:{category:"authorization",recovery:"reauthorize"},invalid_application_authorization:{category:"validation",recovery:"fix_request"},invalid_application_manifest:{category:"validation",recovery:"fix_request"},invalid_callback:{category:"validation",recovery:"fix_request"},invalid_device_authorization_response:{category:"integrity",recovery:"contact_support"},invalid_encrypted_response:{category:"integrity",recovery:"contact_support"},invalid_loopback_url:{category:"validation",recovery:"fix_request"},invalid_mutation_id:{category:"validation",recovery:"fix_request"},invalid_operation_response:{category:"integrity",recovery:"contact_support"},invalid_path:{category:"validation",recovery:"fix_request"},invalid_preflight:{category:"conflict",recovery:"refresh"},invalid_push_payload:{category:"validation",recovery:"fix_request"},invalid_push_subscription:{category:"validation",recovery:"fix_request"},invalid_read_cursor:{category:"validation",recovery:"fix_request"},invalid_replica:{category:"authorization",recovery:"reauthorize"},invalid_request:{category:"validation",recovery:"fix_request"},invalid_token_response:{category:"integrity",recovery:"contact_support"},legacy_scope_reauthorization_required:{category:"authorization",recovery:"reauthorize"},managed_fcm_not_declared:{category:"compatibility",recovery:"fix_request"},manifest_load_failed:{category:"availability",recovery:"retry"},manifest_required:{category:"validation",recovery:"fix_request"},missing_grant_key:{category:"authorization",recovery:"reauthorize"},mutation_abandoned:{category:"conflict",recovery:"none"},mutation_recovery_expired:{category:"compatibility",recovery:"none"},mutation_request_conflict:{category:"conflict",recovery:"resolve_conflict"},no_pending_mutation:{category:"conflict",recovery:"refresh"},not_authorized:{category:"authorization",recovery:"reauthorize"},not_remote_authority:{category:"compatibility",recovery:"choose_collection"},notification_criterion_not_declared:{category:"validation",recovery:"fix_request"},notification_grant_reauthorization_required:{category:"authorization",recovery:"reauthorize"},notification_reauthorization_required:{category:"authorization",recovery:"reauthorize"},notification_registration_failed:{category:"availability",recovery:"retry"},notification_unregistration_failed:{category:"availability",recovery:"retry"},notifications_not_declared:{category:"compatibility",recovery:"fix_request"},notifications_unavailable:{category:"availability",recovery:"retry"},operation_cancelled:{category:"cancellation",recovery:"none"},operation_failed:{category:"internal",recovery:"contact_support"},operation_invalid:{category:"validation",recovery:"fix_request"},operation_outcome_unknown:{category:"conflict",recovery:"resolve_outcome"},origin_denied:{category:"authorization",recovery:"reauthorize"},path_occupied:{category:"conflict",recovery:"resolve_conflict"},pending_mutation_unresolved:{category:"conflict",recovery:"resolve_outcome"},query_snapshot_changed:{category:"conflict",recovery:"refresh"},rate_limited:{category:"availability",recovery:"retry"},reconnect_required:{category:"authorization",recovery:"reauthorize"},redirect_uri_required:{category:"validation",recovery:"fix_request"},reference_updates_unsupported:{category:"compatibility",recovery:"fix_request"},registry_backup_invalid:{category:"integrity",recovery:"contact_support"},registry_busy:{category:"availability",recovery:"retry"},registry_corrupt:{category:"integrity",recovery:"repair_collection"},registry_migration_failed:{category:"internal",recovery:"contact_support"},registry_schema_incompatible:{category:"compatibility",recovery:"upgrade_connector"},relay_authorization_expired:{category:"authorization",recovery:"reauthorize"},relay_unavailable:{category:"availability",recovery:"retry"},replica_scope_denied:{category:"authorization",recovery:"reauthorize"},sandbox_unsupported:{category:"compatibility",recovery:"fix_request"},scope_changed:{category:"authorization",recovery:"reauthorize"},scope_denied:{category:"authorization",recovery:"reauthorize"},scope_epoch_stale:{category:"authorization",recovery:"reauthorize"},session_destroyed:{category:"cancellation",recovery:"none"},session_not_started:{category:"validation",recovery:"fix_request"},session_starting:{category:"availability",recovery:"retry"},stale_file_revision:{category:"conflict",recovery:"refresh"},storage_required:{category:"compatibility",recovery:"none"},sync_failed:{category:"availability",recovery:"retry"},temporarily_unavailable:{category:"availability",recovery:"retry"},timeout:{category:"availability",recovery:"retry"},timer_grant_unavailable:{category:"authorization",recovery:"reauthorize"},token_exchange_failed:{category:"availability",recovery:"retry"},transport_protocol_incompatible:{category:"compatibility",recovery:"upgrade_connector"},type_pack_provision_failed:{category:"validation",recovery:"repair_collection"},unknown_collection:{category:"selection",recovery:"choose_collection"},unsafe_file_path:{category:"validation",recovery:"fix_request"},unsupported_encryption:{category:"compatibility",recovery:"upgrade_application"},unsupported_operation:{category:"compatibility",recovery:"fix_request"}}});function cL(n,e,...[t={}]){let i=yC[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 gC(n,e,...t){let i=t[0];return new Uv(cL(n,e,...t),{status:i?.status,cause:i?.cause})}var Uv,bC=C(()=>{jv();Uv=class extends Error{problem;code;status;constructor(e,t={}){super(e.message,t.cause===void 0?void 0:{cause:t.cause}),this.problem=e,this.name="MdbaseConnectError",this.code=e.code,this.status=t.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 tm(n){let e=structuredClone(n);return{...e,requirements:{configuration:[],...e.requirements},provisions:{type_packs:[],configuration:[],...e.provisions},notifications:e.notifications??{criteria:[]}}}function ao(n){let e=n.capabilities===void 0?1:n.capabilities?.contract_version;return e!==1&&e!==2&&Tl("Unsupported declared capability contract version."),e}function Tl(n){throw gC("invalid_application_manifest",n,{details:{issues:[{path:"/requirements/capabilities",keyword:"authorizationSelection",message:n,params:{}}]}})}function vC(n,e){if(e.operations!==void 0&&e.capabilities!==void 0&&Tl("Specify operations or capabilities, not both."),e.operations!==void 0&&ao(n)!==1&&Tl("Exact operations authorization is only supported for legacy v1 declarations."),e.capabilities!==void 0){let t=new Set([...n.capabilities?.required??[],...n.capabilities?.optional??[]]);e.capabilities.some(i=>!t.has(i)||Tv(ao(n),i)===void 0)&&Tl("Authorization can only include capabilities declared by the application.")}}function Nv(n,e){let{requirements:t}=n;if(vC(t,e),ao(t)===1){if(e.operations!==void 0)return[...new Set(e.operations)];if(e.capabilities===void 0)return[...wC]}let i=t.capabilities,s=[...i?.required??[],...e.capabilities??i?.optional??[]].flatMap(a=>Tv(ao(t),a)??[]),r=(n.provisions?.type_packs.length??0)>0||(n.provisions?.configuration?.length??0)>0;return[...new Set([...s,...ao(t)===2&&r?hC:[]])]}function Dv(n){let e=n.files;if(e)return ao(n)===1?((!("actions"in e)||"required"in e||"optional"in e)&&Tl("Legacy file declarations must use exact files.actions."),{actions:[...e.actions],scope:structuredClone(e.scope)}):("actions"in e&&Tl("V2 file declarations must use required/optional file actions."),mC(e))}var wC,zv=C(()=>{em();Lv();bC();wC=["describe","changes","read","query"]});var _C,AC,nm=C(()=>{_C="/settings/record_extensions",AC="yaml-document-records-v1"});var kC=C(()=>{});function mL(n,e){let t=yL(e)?e:{};if(t.dry_run===!0&&hL.has(n))return null;if(n==="file_control"){let o=typeof t.type=="string"?t.type:"";return fL.has(o)?`file_control:${o}`:null}let i=uL[n];return i==="always"?n:i==="sync_action"&&t.action==="mutate"?"sync:mutate":null}function im(n,e){return mL(n,e)!==null}function yL(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}var pL,dL,uL,fL,hL,lW,cW,rm=C(()=>{pL=["describe","changes","read","query","list_views","execute_view","read_view_source","create_view_source","update_view_source","delete_view_source","validate","create","update","delete","rename","read_type","create_type","update_type","assess_type_pack","apply_type_pack","assess_collection_setup","apply_collection_setup","list_timers","put_timer","cancel_timer","reconcile_timers","sync","record_history","record_version"],dL=["list_files","stat_file","open_file_upload","open_file_download","move_file","delete_file","get_file_transfer_status","commit_file_upload","abort_file_transfer"],uL={describe:"never",changes:"never",read:"never",query:"never",list_views:"never",execute_view:"never",read_view_source:"never",create_view_source:"always",update_view_source:"always",delete_view_source:"always",validate:"never",create:"always",update:"always",delete:"always",rename:"always",read_type:"never",create_type:"always",update_type:"always",assess_type_pack:"never",apply_type_pack:"always",assess_collection_setup:"never",apply_collection_setup:"always",list_timers:"never",put_timer:"always",cancel_timer:"always",reconcile_timers:"always",sync:"sync_action",record_history:"never",record_version:"never"},fL=new Set(["open_file_upload","move_file","delete_file","commit_file_upload","abort_file_transfer"]),hL=new Set(["delete","rename"]),lW=new Set(pL),cW=new Set(dL)});var SC=C(()=>{});var uW,fW,PC=C(()=>{uW=new TextEncoder,{isWellFormed:fW}=String.prototype});function CC(n,e,t=[],i=2){let o={operation_transport:pd,authorization_binding:lo,semantic_capabilities:i},s=[...new Set(t)].filter(r=>r!==pd).sort((r,a)=>a-r);return s.length>0&&(o.operation_transport_recovery=s),(n.some(r=>im(r,{action:"mutate"}))||e?.actions.some(r=>r!=="list"&&r!=="read")===!0)&&(o.durable_mutation=1),o}function Bv(n){return xC.includes(n)}function RC(n){return IC.includes(n)}var pd,bL,xC,lo,$v,IC,wL,vL,yW,om=C(()=>{rm();pd=3,bL=2,xC=[pd,bL],lo=5,$v=4,IC=[lo,$v],wL=2,vL=1,yW={operation_transport:[...xC],authorization_binding:[...IC],semantic_capabilities:[wL,1],durable_mutation:[vL]}});async function EC(n){let e=sm(n),i=new Uint8Array(await crypto.subtle.digest("SHA-256",Vs([_L,Yt(e)]))).slice(0,16);return i[6]=i[6]&15|128,i[8]=i[8]&63|128,[dd(i.slice(0,4)),dd(i.slice(4,6)),dd(i.slice(6,8)),dd(i.slice(8,10)),dd(i.slice(10,16))].join("-")}function qC(n){let e=[sm(n.installation_signing_public_key),sm(n.grant_agreement_public_key),sm(n.grant_signing_public_key)];if(e.some((c,l)=>e.slice(l+1).some(p=>CL(c,p))))throw new Error("Application authorization keys must be distinct.");let t=Vv(n.authorization_nonce),i=Vv(n.code_challenge),o=n.contracts,s=o.operation_transport_recovery??[],r=n.requested_operations.some(c=>im(c,{action:"mutate"}))||n.requested_files?.actions.some(c=>!["list","read"].includes(c))===!0;if(!RC(n.protocol_version)||t.byteLength!==32||!/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)+$/u.test(n.application_declaration_id)||!/^[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||![o.operation_transport,o.authorization_binding,o.semantic_capabilities,o.durable_mutation??1].every(c=>Number.isInteger(c)&&c>0)||o.authorization_binding!==n.protocol_version||!Bv(o.operation_transport)||n.protocol_version===lo&&o.operation_transport!==pd||s.some(c=>!Bv(c)||c===o.operation_transport)||new Set(s).size!==s.length||n.protocol_version===$v&&s.length>0||s.length>0&&!r||(r?o.durable_mutation!==1:o.durable_mutation!==void 0)||n.requested_operations.length===0&&n.requested_files===void 0||new Set(n.requested_operations).size!==n.requested_operations.length||n.requested_operations.some(c=>!c||c.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.");PL(n.requested_files);let a=n.requested_operations.map(c=>Yt(new TextEncoder().encode(c)));return Vs([n.protocol_version===lo?kL:AL,tr(n.protocol_version),Yt(am(n.application_id)),Yt(am(n.authorization_id)),Yt(new TextEncoder().encode(n.application_declaration_id)),Yt(TC(n.application_manifest_digest)),Yt(am(n.application_installation_id)),...e.map(Yt),Yt(new TextEncoder().encode(n.flow)),Yt(t),Yt(new TextEncoder().encode(n.issued_at)),Yt(new TextEncoder().encode(n.expires_at)),OC(n.redirect_uri),OC(n.state),Yt(new TextEncoder().encode(n.code_challenge)),tr(o.operation_transport),...n.protocol_version===lo?[tr(s.length),...s.map(tr)]:[],tr(o.authorization_binding),tr(o.semantic_capabilities),SL(o.durable_mutation),tr(a.length),...a,xL(n.requested_files),IL(n.collection_id)])}function SL(n){return n===void 0?new Uint8Array(1):Vs([new Uint8Array([1]),tr(n)])}function PL(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 xL(n){if(n===void 0)return new Uint8Array(1);let e=n.actions.map(t=>Yt(new TextEncoder().encode(t)));return Vs([new Uint8Array([1]),tr(e.length),...e,Yt(new TextEncoder().encode(n.scope.kind)),...n.scope.kind==="selected_folders"?[tr(n.scope.folders.length),...n.scope.folders.map(t=>Yt(new TextEncoder().encode(t)))]:[]])}function OC(n){return n===void 0?new Uint8Array(1):Vs([new Uint8Array([1]),Yt(new TextEncoder().encode(n))])}function IL(n){return n===void 0?new Uint8Array(1):Vs([new Uint8Array([1]),Yt(am(n))])}function sm(n){let e=Vv(n);if(e.byteLength!==65||e[0]!==4)throw new Error("Application authorization public key is invalid.");return e}function Vv(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=atob(t);if(btoa(i)!==t)throw new Error("Non-canonical base64url value.");let o=new Uint8Array(i.length);for(let s=0;s<i.length;s++)o[s]=i.charCodeAt(s);return o}function am(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 TC(e)}function TC(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 Yt(n){return Vs([tr(n.byteLength),n])}function tr(n){let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,n,!1),e}function Vs(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 CL(n,e){return n.byteLength===e.byteLength&&n.every((t,i)=>t===e[i])}function dd(n){return[...n].map(e=>e.toString(16).padStart(2,"0")).join("")}var _L,AL,kL,MC=C(()=>{rm();om();_L=new TextEncoder().encode("mdbase-connect application installation id v2\0"),AL=new TextEncoder().encode("mdbase-connect application authorization proof v4\0"),kL=new TextEncoder().encode("mdbase-connect application authorization proof v5\0")});var lm,LC=C(()=>{lm={id:"mdbase.runtime.timer.fired",version:"1.0.0",digest:"sha256:41105be7a7abf33b31ced47e1e1965242236e40ccaea286b959b0a8c591f5642"}});function UC(n,e){let t=n.protocol.slice(0,-1),i=e?.toLowerCase().split(".").reverse().join(".");return t.includes(".")&&/^[a-z][a-z0-9+.-]*$/.test(t)&&!["http","https","file","javascript","data"].includes(t)&&(!i||t===i||t.startsWith(`${i}.`))&&n.username===""&&n.password===""&&n.hostname.length>0&&n.hash===""}var RL,OL,EL,qL,TL,ML,LL,xW,jL,IW,Fv,jC,ud,fd=C(()=>{em();kC();nm();jv();zv();Lv();rm();SC();PC();om();em();MC();LC();nm();om();RL="contract-setup-v1",OL="file-relay-v1",EL="protocol-usage-report-v1",qL="policy-freshness-lease-v1",TL=["application-authorization-v4","authorization-activation","encrypted-relay","policy-ack"],ML=["durable-mutation-journal-v1","durable-file-lifecycle-v1","contract-metadata-read-v1"],LL="candidate-b-activation-v1",xW=[...Mv,...ML,"mutation-replay-after-credential-retirement-v1",LL],jL="application-declaration-evidence-v1",IW=[...Mv,jL,...TL,qL,"application-authorization-v5",RL,OL,EL,AC],Fv=1,jC="mdbase-authority-request-proof-v1",ud={version:"x-mdbase-proof-version",timestamp:"x-mdbase-proof-timestamp",nonce:"x-mdbase-proof-nonce",signature:"x-mdbase-proof-signature"}});function DL(n,e={}){return zL(n,e,!0)}function $C(n){let e=Re(Re(n).requirements);return e.capabilities===void 0?1:Re(e.capabilities).contract_version}function zL(n,e,t){let i=FL(n,e.maxBytes??dm);if(i)return pm([i]);let o=t?$C(n):2;if(o!==1&&o!==2)return pm([me("/requirements/capabilities/contract_version","contractVersion","must declare supported contract version 1 or 2")]);let s=Re(n).platform==="native",r=e.allowLocal||s?ej(n,!e.allowLocal):n,a=BL(o===1?NL:UL,r);if(!a.valid)return a;let c=[...KL(n,e.allowLocal===!0),...o===1?QL(n):ZL(n),...HL(n),...JL(n)];return c.length===0?{valid:!0,issues:[]}:pm(c)}function hd(n,e={}){let t=DL(n,e);if(!t.valid)throw new Wv(t.issues);return $C(n)===1?{contractVersion:1,manifest:tm(n)}:{contractVersion:2,manifest:tm(n)}}function $L(n){return n.map(e=>`${e.path||"/"} ${e.message}`).join("; ")}function BL(n,e){if(n(e))return{valid:!0,issues:[]};let t=(n.errors??[]).map(VL),i=t.filter(o=>o.keyword!=="oneOf");return pm(i.length>0?i:t)}function VL(n){let e=n.params;return n.keyword==="required"&&typeof e.missingProperty=="string"?{path:Hv(n.instancePath,e.missingProperty),keyword:n.keyword,message:"is required",params:e}:n.keyword==="additionalProperties"&&typeof e.additionalProperty=="string"?{path:Hv(n.instancePath,e.additionalProperty),keyword:n.keyword,message:"is not allowed",params:e}:{path:n.instancePath,keyword:n.keyword,message:n.message??"is invalid",params:e}}function Hv(n,e){let t=e.replaceAll("~","~0").replaceAll("/","~1");return`${n}/${t}`}function FL(n,e){let t=BC(n,new WeakSet);if(t)return{...t,path:t.path||"/"};try{let i=JSON.stringify(n);if(i.length*3<=e)return;let o=new TextEncoder().encode(i).byteLength;return o<=e?void 0:me("/","maxBytes",`must not exceed ${e} UTF-8 bytes`,{maxBytes:e,actualBytes:o})}catch{return me("/","json","must be serializable as JSON")}}function BC(n,e){if(n===null||typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n))return;if(typeof n!="object")return me("","json","must be a JSON value");if(e.has(n))return me("","json","must not contain circular references");let t=Object.getPrototypeOf(n);if(!Array.isArray(n)&&t!==Object.prototype&&t!==null)return me("","json","must be a plain JSON object");e.add(n);let i=Array.isArray(n)?Array.prototype.entries.call(n):Object.entries(n);for(let[o,s]of i){let r=BC(s,e);if(r)return r.path=Hv("",String(o))+r.path,r}e.delete(n)}function KL(n,e){let t=Re(n),i=t.platform==="native";for(let[o,s]of Object.entries(Re(t.installation_origins)))for(let[r,a]of Object.entries(Re(s)))for(let[c,l]of a.entries()){let p=`/installation_origins/${o}/${r}/${c}`;try{if(i&&(r!=="app-runtime"||!Fs(l)))return[me(p,"origin","native applications require canonical IPv4 loopback HTTP app-runtime origins")];let d=new URL(l),u=(Kv(d,o==="lab")||i&&Fs(l))&&d.origin===l,f=r==="mobile"&&d.protocol==="capacitor:"&&/^[a-z0-9.-]+$/u.test(d.hostname)&&`${d.protocol}//${d.host}`===l,h=r==="app-runtime"&&/^chrome-extension:\/\/[a-p]{32}$/u.test(l);if(!u&&!f&&!h||l.includes("*")||d.username||d.password||d.search||d.hash)return[me(p,"origin","must be an exact HTTPS, loopback HTTP, mobile capacitor or Chrome extension origin without wildcards")]}catch{return[me(p,"origin","must be an exact installation origin")]}}if(t.distribution==="portable"){if(t.project_url===void 0)return t.icon===void 0?[]:[me("/icon","origin","requires a project_url on the same origin")];try{let o=new URL(String(t.project_url));return o.protocol!=="https:"?[me("/project_url","protocol","must use HTTPS")]:t.icon!==void 0&&new URL(String(t.icon)).origin!==o.origin?[me("/icon","origin","must use the project_url origin")]:[]}catch{return[me("/","url","contains an invalid URL")]}}try{let o=new URL(String(t.homepage));if(i?!cm(String(t.homepage)):!Kv(o,e))return[me("/homepage","protocol",i?"native applications require canonical IPv4 loopback HTTP":"must use HTTPS (or loopback HTTP in local mode)")];for(let[s,r]of t.redirect_uris.entries()){if(String(r).includes("*"))return[me(`/redirect_uris/${s}`,"url","must be an exact URI without wildcards")];let a=new URL(String(r));if(i&&["http:","https:"].includes(a.protocol)&&!cm(String(r)))return[me(`/redirect_uris/${s}`,"origin","native HTTP(S) redirects require canonical IPv4 loopback HTTP")];if(a.origin===o.origin&&!Kv(a,e)&&!(i&&cm(String(r))))return[me(`/redirect_uris/${s}`,"protocol","must use HTTPS (or loopback HTTP in local mode)")];let c=WL(a,String(t.id)),l=!i&&a.protocol==="capacitor:"&&!a.username&&!a.password&&!a.port&&!a.search&&!a.hash&&a.href===r&&Object.values(Re(t.installation_origins)).some(p=>{let d=Re(p).mobile;return Array.isArray(d)&&d.includes(`capacitor://${a.hostname}`)});if(a.origin!==o.origin&&!c&&!l)return[me(`/redirect_uris/${s}`,"origin","must use the homepage origin or a private-use scheme matching the application ID")]}return t.icon!==void 0&&new URL(String(t.icon)).origin!==o.origin?[me("/icon","origin","must use the homepage origin")]:[]}catch{return[me("/","url","contains an invalid URL")]}}function WL(n,e){let t=n.protocol.slice(0,-1);return UC(n)&&(t===e||t.startsWith(`${e}.`))}function HL(n){let e=Re(n),t=Re(e.requirements),i=Array.isArray(t.contracts)?t.contracts:[],o=new Set(i.map(c=>{let l=Re(c);return`${l.id}@${l.version}`})),s=Re(e.provisions),r=Array.isArray(s.type_packs)?s.type_packs:[],a=[];for(let[c,l]of r.entries()){let p=Re(l),d=Array.isArray(p.provides)?p.provides:[];for(let u of d){let f=Re(u);o.has(`${f.id}@${f.version}`)||a.push(me(`/provisions/type_packs/${c}/provides`,"contractRequirement","may only contain contracts required by the application"))}a.push(...GL(p,`/provisions/type_packs/${c}`))}return a}function GL(n,e=""){let t=Re(n),i=Re(t.manifest),o=Array.isArray(i.resources)?i.resources.map(Re):[],s=Array.isArray(t.resources)?t.resources.map(Re):[],r=new Map(s.map(c=>[String(c.source),c.document]));if(r.size!==s.length||new Set(o.map(c=>String(c.source))).size!==o.length||o.length!==s.length)return[me(`${e}/resources`,"resourceSet","must match manifest source paths exactly")];let a=[];for(let[c,l]of o.entries()){let p=`${e}/manifest/resources/${c}`,d=String(l.source),u=r.get(d);if(typeof u!="string"){a.push(me(`${e}/resources`,"resourceSet",`is missing manifest source ${d}`));continue}VC(u)!==l.digest&&a.push(me(`${p}/digest`,"digest","does not match the embedded document")),l.upgrade_from!==void 0&&a.push(...YL(l,u,`${p}/upgrade_from`))}return a}function YL(n,e,t){if(n.kind!=="type"||n.mode!=="seed")return[me(t,"seedUpgrade","is only allowed for seed types")];let i=NC(e),o=Array.isArray(n.upgrade_from),s=(o?n.upgrade_from:[n.upgrade_from]).map(Re),r=new Set,a=[];for(let[c,l]of s.entries()){let p=o?`${t}/${c}`:t,d=String(l.document);l.digest!==VC(d)?a.push(me(`${p}/digest`,"digest","does not match the baseline document")):r.has(l.digest)?a.push(me(`${p}/digest`,"uniqueBaseline","duplicates another upgrade baseline")):l.digest===n.digest&&a.push(me(`${p}/digest`,"seedUpgrade","must not be the resource's own document")),r.add(l.digest);let u=NC(d);!i||!u||u.kind!==i.kind||u.name!==i.name?a.push(me(`${p}/document`,"seedUpgrade","must be a type document with the same kind and name as the resource")):l.version!==void 0&&u.version!==l.version&&a.push(me(`${p}/version`,"seedUpgrade","must equal the version the baseline document declares"))}return a}function NC(n){let e=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u.exec(n)?.[1];if(e===void 0)return;let t=Ev(e,{uniqueKeys:!0});if(!(t.errors.length>0||!si(t.contents)))return{kind:t.get("kind"),name:t.get("name"),version:t.get("version")}}function VC(n){return`sha256:${Ua(Ze(Mb(n)))}`}function JL(n){let e=Re(n),t=Re(e.requirements),i=Re(e.provisions),o=Array.isArray(t.configuration)?t.configuration:[],s=Array.isArray(i.configuration)?i.configuration:[],r=[],a=new Map;for(let[p,d]of o.entries()){let u=Re(d),f=String(u.id),h=String(u.path),m=DC(h,u.value);m&&r.push(me(`/requirements/configuration/${p}/path`,"configurationPointer",m)),a.has(f)?r.push(me(`/requirements/configuration/${p}/id`,"uniqueRequirement",`duplicates configuration requirement ${f}`)):a.set(f,{path:h,value:u.value,index:p})}let c=new Set,l=new Set;for(let[p,d]of s.entries()){let u=Re(d),f=String(u.requirement),h=String(u.path),m=DC(h,u.value);m&&r.push(me(`/provisions/configuration/${p}/path`,"configurationPointer",m));let w=a.get(f);if(!w){r.push(me(`/provisions/configuration/${p}/requirement`,"configurationRequirement",`references unknown configuration requirement ${f}`));continue}c.has(f)&&r.push(me(`/provisions/configuration/${p}/requirement`,"uniqueProvision",`configuration requirement ${f} may have exactly one provision`)),c.add(f),h!==w.path&&r.push(me(`/provisions/configuration/${p}/path`,"configurationRequirement",`must equal /requirements/configuration/${w.index}/path`)),JSON.stringify(u.value)!==JSON.stringify(w.value)&&r.push(me(`/provisions/configuration/${p}/value`,"configurationRequirement",`must equal /requirements/configuration/${w.index}/value`));let b=`${h}\0${JSON.stringify(u.value)}`;l.has(b)&&r.push(me(`/provisions/configuration/${p}`,"uniqueContribution","duplicates another configuration path and value contribution")),l.add(b)}for(let[p,d]of a)c.has(p)||r.push(me(`/requirements/configuration/${d.index}`,"configurationProvision",`requires one provision linked by id ${p}`));return r}function DC(n,e){if(n===_C)return XL.includes(e)?void 0:"accepts only the record extensions md and base";if(!n.startsWith("/")||n.length*3>1024&&new TextEncoder().encode(n).byteLength>1024)return"must be a bounded RFC 6901 JSON pointer";let t=n.slice(1).split("/");if(t.length<2||t.length>16)return"must address a value below an x-* extension namespace";for(let i of t){if(/~(?:[^01]|$)/u.test(i))return"contains an invalid RFC 6901 escape";if(i.length===0||i==="-"||/^\d+$/u.test(i)||/\p{Cc}/u.test(i))return"contains a disallowed object-key segment"}return/^x-[a-z0-9][a-z0-9-]*$/u.test(t[0])?void 0:"must be inside a top-level x-* extension namespace"}function ZL(n){let e=Re(n),t=Re(e.requirements),i=Re(t.capabilities),o=[];t.access!=="full_collection"&&o.push(me("/requirements/access","collectionAccess","must explicitly request full_collection; legacy or omitted access is not widened"));let s=Array.isArray(i.required)?i.required.map(String):[],a=(Array.isArray(i.optional)?i.optional.map(String):[]).find(w=>s.includes(w));a&&o.push(me("/requirements/capabilities/optional","disjoint",`must not repeat required capability ${a}`));let c=Re(t.files),l=Array.isArray(c.required)?c.required.map(String):[],d=(Array.isArray(c.optional)?c.optional.map(String):[]).find(w=>l.includes(w));d&&o.push(me("/requirements/files/optional","disjoint",`must not repeat required file action ${d}`));let u=Re(t.people),f=Array.isArray(u.required)?u.required.map(String):[],m=(Array.isArray(u.optional)?u.optional.map(String):[]).find(w=>f.includes(w));return m&&o.push(me("/requirements/people/optional","disjoint",`must not repeat required people permission ${m}`)),o}function QL(n){let e=Re(n),t=Re(e.requirements),i=Re(t.capabilities),o=[];if(t.access!=="full_collection"&&o.push(me("/requirements/access","collectionAccess","must explicitly request full_collection; legacy or omitted access is not widened")),Object.keys(i).length===0)return o;let s=Array.isArray(i.required)?i.required.map(String):[],r=Array.isArray(i.optional)?i.optional.map(String):[],a=r.find(h=>s.includes(h));a&&o.push(me("/requirements/capabilities/optional","disjoint",`must not repeat required capability ${a}`));let c=new Set([...s,...r]),l=Re(e.provisions);c.has("definitions.type-pack.apply")&&t.access!=="full_collection"&&o.push(me("/requirements/access","typePackAccess","must be full_collection for definitions.type-pack.apply")),Array.isArray(l.type_packs)&&l.type_packs.length>0&&!s.includes("collection.setup.apply")&&o.push(me("/requirements/capabilities/required","collectionSetupCapability","must require collection.setup.apply when bundled type packs are declared"));let p=Array.isArray(l.configuration)&&l.configuration.length>0,d=p||Array.isArray(l.type_packs)&&l.type_packs.length>0;p&&!s.includes("collection.setup.apply")&&o.push(me("/requirements/capabilities/required","collectionSetupCapability","must require collection.setup.apply when configuration provisions are declared")),c.has("collection.setup.apply")&&(t.access!=="full_collection"&&o.push(me("/requirements/access","collectionSetupAccess","must be full_collection for collection.setup.apply")),d||o.push(me("/provisions","collectionSetupProvision","must declare a configuration provision or type pack for collection.setup.apply"))),c.has("notifications.background-delivery")&&!Array.isArray(Re(e.notifications).criteria)&&o.push(me("/notifications/criteria","notificationCapability","must be declared for notifications.background-delivery"));let u=Re(t.files),f=Array.isArray(u.actions)?new Set(u.actions.map(String)):new Set;for(let h of["list","read","add","replace","move","delete"]){let m=`files.${h}`;c.has(m)!==f.has(h)&&o.push(me("/requirements/capabilities","fileCapability",`${m} and requirements.files.actions.${h} must be declared together`))}return o}function ej(n,e=!1){let t=Re(n);if(t.distribution==="portable")return n;let i={...t};for(let o of["homepage","icon"])typeof i[o]=="string"&&(i[o]=zC(i[o],e));return Array.isArray(i.redirect_uris)&&(i.redirect_uris=i.redirect_uris.map(o=>typeof o=="string"?zC(o,e):o)),i}function zC(n,e){try{let t=new URL(n);return t.protocol==="http:"&&(e?cm(n):FC(t.hostname))&&(t.protocol="https:"),t.href}catch{return n}}function Fs(n){if(typeof n!="string"||!/^http:\/\/127\.0\.0\.1(?::[1-9][0-9]{0,4})?$/.test(n))return!1;try{return new URL(n).origin===n}catch{return!1}}function cm(n){let e=/^http:\/\/[^/?#]+/.exec(n)?.[0];return Fs(e)}function Kv(n,e){return n.protocol==="https:"||e&&n.protocol==="http:"&&FC(n.hostname)}function FC(n){return n==="localhost"||n==="127.0.0.1"||n==="[::1]"||n==="::1"}function pm(n){return{valid:!1,issues:n}}function me(n,e,t,i={}){return{path:n,keyword:e,message:t,params:i}}function Re(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)?n:{}}var dm,Wv,UL,NL,XL,md=C(()=>{gr();yr();XI();fC();zv();nm();fd();dm=524288,Wv=class extends Error{issues;constructor(e){super(`Invalid application manifest: ${$L(e)}`),this.issues=e,this.name="AppManifestValidationError"}},UL=sC,NL=uC;XL=["md","base"]});function es(n){return!1}function Qe(n){try{let e=new URL(n);return e.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(e.hostname)}catch{return!1}}function Gv(n){return!1}var um=C(()=>{"use strict"});function Cr(n){return!1}function ts(n){return n==="lab"||n==="staging"||n==="production"}function Ml(n){return n==="lab"}function ns(n){try{let e=new URL(n);return e.protocol==="http:"&&e.hostname==="127.0.0.1"&&Number(e.port)>0&&e.origin===n&&!e.username&&!e.password}catch{return!1}}var St=C(()=>{"use strict";um()});function dt(n){return n.protocol==="https:"||n.protocol==="http:"?n.origin:`${n.protocol}//${n.host}`}function Yv(n,e){if(typeof n!="string"||n.length>512)return null;let t;try{t=new URL(n)}catch{return null}if(t.username||t.password||t.search||t.hash||!["","/"].includes(t.pathname)||dt(t)!==n)return null;switch(t.protocol){case"https:":return"web";case"http:":return e==="native"?Fs(n)?"native":null:Qe(n)?"web":null;case"capacitor:":return!t.port&&/^[a-z0-9.-]{1,253}$/.test(t.hostname)?"mobile":null;case"chrome-extension:":return/^[a-p]{32}$/.test(t.host)?"extension":null;case"moz-extension:":return tj.test(t.host)?"extension":null;default:return null}}function Et(){let n=globalThis.location;if(!n)return null;if(typeof n.origin=="string"&&n.origin!=="null")return n.origin;try{let e=new URL(n.href);if(e.protocol==="blob:"){let t=dt(new URL(e.pathname));return ut(t)?t:null}return dt(e)}catch{return null}}var tj,ut,Jt=C(()=>{"use strict";md();St();tj=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;ut=n=>Yv(n)!==null});function WC(n,e){let t=KC.get(n);return(!t||!/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(e.id)||e.id==="00000000-0000-0000-0000-000000000000")&&on(),e.supersededDeclaredId!==void 0&&e.supersededDeclaredId!==n.id&&on(),co({...n,id:e.id,name:e.name,storage:e.supersededDeclaredId===void 0?t:{...n.storage}})}function on(){throw A("invalid_request","invalid application declaration","application_declaration")}function Jv(n,e=new Set,t=0,i={nodes:0,chars:0}){if((++i.nodes>524288||t>64)&&on(),typeof n=="string")return i.chars+=n.length,i.chars>524288&&on(),n;if(n===null||typeof n=="boolean")return n;if(typeof n=="number")return Number.isFinite(n)||on(),n;(typeof n!="object"||e.has(n)||Object.getOwnPropertySymbols(n).length)&&on(),e.add(n);try{if(Array.isArray(n))return(n.length>524288||Object.keys(n).length!==n.length)&&on(),Object.freeze(Array.from({length:n.length},(s,r)=>{let a=Object.getOwnPropertyDescriptor(n,String(r));return(!a||!("value"in a))&&on(),Jv(a.value,e,t+1,i)}));Object.getPrototypeOf(n)!==Object.prototype&&Object.getPrototypeOf(n)!==null&&on();let o=Object.create(null);for(let s of Object.keys(n)){i.chars+=s.length;let r=Object.getOwnPropertyDescriptor(n,s);(i.chars>524288||!r||!("value"in r))&&on(),o[s]=Jv(r.value,e,t+1,i)}return Object.freeze(o)}finally{e.delete(n)}}function fm(n){return JSON.parse(JSON.stringify(n.manifest))}function co(n){let e=Jv(n);(!e||Array.isArray(e)||Object.keys(e).some(m=>!["id","name","origin","environment","manifest","storage","installationKind"].includes(m)))&&on();let{id:t,name:i,origin:o,environment:s,manifest:r}=e;(typeof t!="string"||!t||t.length>256||!/^[a-z0-9][a-z0-9._-]*$/.test(t)||t==="00000000-0000-0000-0000-000000000000"||typeof i!="string"||!i.trim()||new TextEncoder().encode(i).length>100||/[\u0000-\u001f\u007f]/.test(i)||typeof o!="string"||typeof s!="string"||!ts(s)||!r||Array.isArray(r)||typeof r!="object")&&on(),Cr(s)&&!ns(o)&&on();let a=Yv(o,r.platform==="native"?"native":void 0),c=e.installationKind??(a==="mobile"?"mobile":"app-runtime");(a===null||c!=="app-runtime"&&c!=="mobile"||a==="mobile"&&c!=="mobile"||(a==="extension"||a==="native")&&c!=="app-runtime")&&on();let l=e.storage;l!==void 0&&(!l||Array.isArray(l)||typeof l!="object"||Object.keys(l).some(m=>!["joinDatabaseName","setupDatabaseName","unsyncedDatabaseName","applicationNamespace"].includes(m)))&&on();let p=l,d=p?.applicationNamespace??t,u=typeof d=="string"&&d!==t?`namespace.${Tw(JSON.stringify([t,d]))}`:t,f={joinDatabaseName:p?.joinDatabaseName??`mdbase.${u}.native-collection-join.v1`,setupDatabaseName:p?.setupDatabaseName??`mdbase.${u}.native-model-setup.v1`,unsyncedDatabaseName:p?.unsyncedDatabaseName??`mdbase.${u}.unsynced.v1`,applicationNamespace:d};for(let m of Object.values(f))(typeof m!="string"||!m||m.length>256||/[\u0000-\u001f\u007f]/.test(m))&&on();new Set([f.joinDatabaseName,f.setupDatabaseName,f.unsyncedDatabaseName]).size!==3&&on();let h=Object.freeze({id:t,name:i,origin:o,environment:s,installationKind:c,manifest:r,storage:Object.freeze(f)});return KC.set(h,Object.freeze({...p})),h}var KC,Ll=C(()=>{"use strict";oh();Jt();re();St();KC=new WeakMap});function yd(n){if(n!==null&&typeof n=="object"){for(let e of Object.values(n))yd(e);Object.freeze(n)}return n}function is(n){let e=hd(fm(n),{allowLocal:!0}),t=yd(e.manifest),i=t.requirements,o=ao(i),s=yd(Nv(t,{})),r=Dv(i),a=yd(CC(s,r,void 0,o)),c=i.capabilities,l=c?.contract_version===2?Object.freeze({capabilityContractVersion:2,requiredNativeCapabilities:Object.freeze([...c.required])}):null,p=c?.contract_version===2&&[...c.required,...c.optional??[]].includes("offline.replica");return Object.freeze({contractVersion:e.contractVersion,manifest:t,semanticVersion:o,operations:s,...r?{files:yd(r)}:{},contracts:a,nativeCapabilities:l,privateDeviceDeclared:p})}var hm=C(()=>{"use strict";fd();md();Ll()});function mm(n,e){if(typeof n!="string"||!n||n.length>2048||n.includes("*"))return!1;let t=e&&typeof e=="object"?e.redirect_uris:void 0;if(!Array.isArray(t)||!t.includes(n))return!1;let{id:i,homepage:o}=e,s;try{s=new URL(n)}catch{return!1}if(s.username||s.password||s.hash)return!1;if(s.protocol==="https:"||s.protocol==="http:"){let a;try{a=new URL(String(o))}catch{return!1}return s.origin===a.origin&&(s.protocol==="https:"||Qe(s.origin))}let r=s.protocol.slice(0,-1);return typeof i=="string"&&r.includes(".")&&/^[a-z][a-z0-9+.-]*$/.test(r)&&!nj.includes(r)&&(r===i||r.startsWith(`${i}.`))&&s.hostname.length>0}function jl(n,e,t){if(!e.startsWith("capacitor://"))return!1;let i=t?.redirect_uris;if(!Array.isArray(i)||!i.includes(n)||n.includes("*"))return!1;let o;try{o=new URL(n)}catch{return!1}return o.href!==n||o.username||o.password||o.search||o.hash?!1:o.protocol==="capacitor:"?`capacitor://${o.host}`===e:o.protocol!=="http:"&&o.protocol!=="https:"&&mm(n,t)}var nj,ym=C(()=>{"use strict";St();nj=["http","https","file","javascript","data","blob","about","capacitor","chrome-extension","moz-extension"]});function HC(n,e){if(typeof n!="string"||!n.length)throw gd();let t=new URL(n),i=e&&Qe(n);if(t.origin!==n||t.username||t.password||t.protocol!=="https:"&&!i)throw gd();return n}function Ci(n){let{environment:e,release:t}=n;if(!ts(e)||!t||t.schema!=="mdbn-app-trust/release/1"||t.environment!==e||!/^[0-9a-f]{64}$/.test(t.assetSha256)||!t.source||t.source.repository!=="mdbase-dev/mdbase-connect"||!/^[0-9a-f]{40}$/.test(t.source.commit)||!/^[A-Za-z0-9.+-]{1,64}$/.test(t.source.version)||!Array.isArray(t.trustedRoots)||!t.trustedRoots.length||t.trustedRoots.length>64||t.trustedRoots.some(c=>!(c instanceof Uint8Array)||c.length!==32||c.every(l=>l===0))||!(t.policyPins instanceof Uint8Array)||!t.policyPins.length||t.policyPins.length>65536)throw gd();let i=Cr(e),o=HC(t.cpOrigin,i),s=HC(t.logOrigin,i),r=n.appOrigin;if(i&&![o,s,r].every(ns)||!ut(r))throw gd();let a=Object.freeze({environment:e,appOrigin:r,cpOrigin:o,logOrigin:s,assetSha256:t.assetSha256,allowLoopbackHttp:Ml(e)&&new URL(r).protocol==="http:"});return GC.add(a),a}function YC(n){return!!n&&typeof n=="object"&&GC.has(n)}var GC,gd,rs=C(()=>{"use strict";Jt();St();GC=new WeakSet,gd=()=>new Error("app environment: explicit authenticated build context required")});function Ks(){return Object.freeze({...Xv,trustedRoots:Object.freeze(ij.map(JC)),policyPins:JC(rj)})}var Xv,ij,rj,JC,gm=C(()=>{Xv={schema:"mdbn-app-trust/release/1",environment:"production",cpOrigin:"https://connect.mdbase.dev",logOrigin:"https://log.mdbase.dev",assetSha256:"7912e40838213e60b65848350d319a48019021317b112e3326429b250f0133d7",source:{commit:"36abd4b065be9495a7f5ae0808865a1f2279af04",repository:"mdbase-dev/mdbase-connect",version:"0.1.0-beta.141"}};Object.freeze(Xv.source);Object.freeze(Xv);ij=Object.freeze(["d9f6e481aa47ae9e0373c8994fe6edb3131d8ac3cf3cbc1be58672a8543c932d"]),rj="8281825070a2bd532b5544dfb77617d4040ca6a25820d9f6e481aa47ae9e0373c8994fe6edb3131d8ac3cf3cbc1be58672a8543c932d818350c580fb092af10eb030605bd6e478e6f158206b587b1b32ba84b3d630868fe8e5396339f0c0ed2c59324a67824c1a2028040c5070a2bd532b5544dfb77617d4040ca6a2",JC=n=>{let e=new Uint8Array(n.length/2);for(let t=0;t<e.length;t++)e[t]=parseInt(n.slice(t*2,t*2+2),16);return e}});function Qv(n){if(!n||typeof n!="object"||Array.isArray(n))throw po();return n}function e_(n){return n===null||typeof n=="string"||typeof n=="boolean"||typeof n=="number"?JSON.stringify(n):Array.isArray(n)?`[${n.map(e_).join(",")}]`:`{${Object.entries(n).filter(([,t])=>t!==void 0).sort(([t],[i])=>t<i?-1:t>i?1:0).map(([t,i])=>`${JSON.stringify(t)}:${e_(i)}`).join(",")}}`}async function wm(n){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e_(n))));return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function sj(n,e){let t=[[n,e]],i=0;for(;t.length;){if(++i>524288)return!1;let[o,s]=t.pop();if(o===s)continue;if(!o||!s||typeof o!="object"||typeof s!="object"||Array.isArray(o)!==Array.isArray(s))return!1;let r=Object.keys(o);if(r.length!==Object.keys(s).length)return!1;for(let a of r){if(!Object.hasOwn(s,a))return!1;t.push([o[a],s[a]])}}return!0}async function vm(n){let e=n.declaration,t=n.signal,i=n.isCurrent,o=n.fetch??globalThis.fetch,s=e.manifest,r=co(e);function a(){try{if(!t.aborted&&n.signal===t&&n.declaration===e&&n.isCurrent===i&&e.id===r.id&&e.name===r.name&&e.origin===r.origin&&e.environment===r.environment&&e.manifest===s&&i.call(n)===!0&&!t.aborted)return}catch{}throw A("cancelled","Application registration fenced","application_registration_fenced")}a();let c,l;try{c=Ci({environment:r.environment,appOrigin:r.origin,release:Ks()})}catch{throw a(),A("unavailable","SDK registration environment unavailable","application_registration_unavailable")}try{l=hd(fm(r),{allowLocal:!0}).manifest}catch{throw bd()}let p=r.environment==="local"?[]:l.installation_origins?.[r.environment]?.[r.installationKind]??[];if(l.name!==r.name||l.distribution==="portable"||new URL(l.homepage).origin!==r.origin&&!p.includes(r.origin)&&!("platform"in l&&l.platform==="native"&&r.installationKind==="app-runtime"&&Fs(r.origin)))throw bd();let d=JSON.stringify({manifest:l}),u=`${c.cpOrigin}/v1/apps/register`,f=`mdbase.app.registration.v1.${encodeURIComponent(c.cpOrigin)}.${encodeURIComponent(l.id)}`,h=()=>{try{return globalThis.localStorage??null}catch{return null}},m=h()?await wm(l).catch(()=>null):null;a();let w=x=>{if(m)try{h()?.setItem(f,JSON.stringify({v:1,digest:m,declaredId:r.id,...x}))}catch{}};{let x=null;try{let P=h()?.getItem(f);x=P?Qv(JSON.parse(P)):null}catch{x=null}if(x&&m&&x.v===1&&x.digest===m&&x.declaredId===r.id&&typeof x.id=="string"&&Zv.test(x.id)&&x.id!==ZC&&x.name===l.name&&typeof x.manifestDigest=="string"&&/^[0-9a-f]{64}$/.test(x.manifestDigest)&&(x.supersededDeclaredId===void 0||x.supersededDeclaredId===r.id))return Object.freeze({id:x.id,name:l.name,manifestDigest:x.manifestDigest,...x.supersededDeclaredId!==void 0?{supersededDeclaredId:r.id}:{}})}if(new TextEncoder().encode(d).length>dm+32||typeof o!="function")throw bd();let b=new AbortController,g=()=>b.abort(),y=setTimeout(g,15e3);y.unref?.(),t.addEventListener("abort",g,{once:!0});function v(){if(a(),b.signal.aborted)throw bm()}async function _(x){let P=x.headers.get("content-length");if(!x.body||P!==null&&(!/^(0|[1-9][0-9]*)$/.test(P)||Number(P)>8192))return x.body?.cancel().catch(()=>{}),null;let I=x.body.getReader(),O=new Uint8Array(8192),R=0;try{for(;;){let q=await I.read();if(v(),q.done)break;if(R+q.value.length>O.length)return null;O.set(q.value,R),R+=q.value.length}return js(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(O.subarray(0,R))))}catch(q){if(q instanceof ne)throw q;return null}finally{I.cancel().catch(()=>{})}}async function k(x){let P=new Uint8Array(2*dm+8192),I=0,O=x.headers.get("content-length");if(O!==null&&/^(0|[1-9][0-9]*)$/.test(O)&&Number(O)>P.length)throw x.body?.cancel().catch(()=>{}),po();if(!x.body)throw po();let R=x.body.getReader();try{for(;;){let q=await R.read();try{if(v(),q.done)break;if(I+q.value.length>P.length)throw po();P.set(q.value,I),I+=q.value.length}finally{q.value?.fill(0)}}try{return Qv(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(P.subarray(0,I))))}catch{throw po()}}finally{P.fill(0),R.cancel().catch(()=>{}),R.releaseLock()}}async function S(x){let P=Qv(x.application),I=P.id,O=P.manifest_digest;if(typeof I!="string"||!Zv.test(I)||I===ZC)throw po();let R=Zv.test(r.id)&&I!==r.id,q=R?bd:po;if(R&&O!==await wm(l).catch(()=>null))throw bd();if(v(),typeof O!="string"||!/^[0-9a-f]{64}$/.test(O)||P.name!==l.name||P.canonical_identity!==`bundle:${l.id}:sha256:${O}`||P.family_identity!==`bundle:${l.id}`||P.distribution!=="web")throw q();if(!P.application_declaration)throw A("upgrade_required","Canonical registration evidence unavailable","application_registration_unsupported");let j;try{j=hd(P.application_declaration,{allowLocal:!0}).manifest}catch{throw po()}if(!sj(l,j))throw q();return v(),Object.freeze({id:I,name:l.name,manifestDigest:O,...R?{supersededDeclaredId:r.id}:{}})}try{v();try{n.onRequest?.()}catch{}for(let x=0;x<3;x++){v();let P;try{if(P=await o(u,{method:"POST",headers:{"content-type":"application/json"},body:d,signal:b.signal,credentials:"omit",redirect:"error",cache:"default",referrerPolicy:"no-referrer"}),v(),P.redirected||P.url&&P.url!==u)throw po();if(!P.ok){if(oj.has(P.status))throw await P.body?.cancel().catch(()=>{}),bm();let O=await _(P);throw A("forbidden","Application registration refused",O?{reason:"application_registration_refused",details:{code:O.code,paths:[...O.paths]}}:"application_registration_refused")}let I=await S(await k(P));return w(I),I}catch(I){if(P?.body?.cancel().catch(()=>{}),v(),I instanceof ne&&I.reason!=="application_registration_unknown")throw I;if(x===2)throw bm();await new Promise((O,R)=>{let q=()=>{clearTimeout(j),b.signal.removeEventListener("abort",q);try{v(),O()}catch(B){R(B)}},j=setTimeout(q,x===0?250:1e3);j.unref?.(),b.signal.addEventListener("abort",q,{once:!0}),b.signal.aborted&&q()})}}throw bm()}finally{clearTimeout(y),t.removeEventListener("abort",g),b.abort()}}var Zv,ZC,oj,bd,po,bm,_m=C(()=>{"use strict";md();md();rs();re();Ll();gm();Gf();Zv=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,ZC="00000000-0000-0000-0000-000000000000",oj=new Set([408,429,500,502,503,504]),bd=()=>A("invalid_request","Application registration binding mismatch","application_registration_binding"),po=()=>A("unavailable","Application registration evidence invalid","application_registration_response"),bm=()=>A("outcome_unknown","Original application registration outcome unknown","application_registration_unknown")});function Dl(n,e={}){return{description:"in-process",open(t,i){return new Promise((o,s)=>{let r;try{r=n.connect(e)}catch(c){s(A("unavailable",`runtime refused to connect: ${String(c)}`));return}let a=()=>{r.close(),s(A("cancelled","connect aborted"))};i?.addEventListener("abort",a,{once:!0}),r.onframe=c=>{i?.removeEventListener("abort",a),r.onframe=null,r.onclose=null,o({port:r,helloResponse:c})},r.onclose=c=>{i?.removeEventListener("abort",a),s(c??A("unavailable","runtime closed the session"))},r.send(t)})}}}var xm=C(()=>{"use strict";re()});function Im(n){return typeof n=="string"&&n.length<=100&&/^(?:UTC|[A-Z][A-Za-z0-9_+-]*(?:\/[A-Z][A-Za-z0-9_+-]*)+)$/.test(n)}var t_=C(()=>{"use strict"});function s1(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)?n:null}function a1(n,e,t){if(!/^[A-Za-z0-9_-]+$/.test(n))return!1;try{let i=atob(n.replaceAll("-","+").replaceAll("_","/"));return i.length===e&&(t===void 0||i.charCodeAt(0)===t)&&btoa(i).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")===n}catch{return!1}}function Cm(n,e){let t=s1(n),i=s1(t?.native_completion);if(!i||!Object.hasOwn(i,"version")||i.version!==1||Object.keys(i).length!==o1.length+1||o1.some(r=>!Object.hasOwn(i,r)||typeof i[r]!="string"))throw zl();let o=i;for(let r of["account_id","authorization_request_id","application_id","application_installation_id","collection_id","grant_id"])if(!gj.test(o[r]))throw zl();if(!o.application_declaration_id||!/^[0-9a-f]{64}$/.test(o.application_manifest_digest)||!a1(o.grant_signing_public_key,65,4)||!a1(o.client_noise_public_key,32))throw zl();try{if(!ut(o.application_origin)||dt(new URL(o.application_origin))!==o.application_origin)throw zl()}catch{throw zl()}let s={account_id:e.accountId,authorization_request_id:e.authorizationRequestId,application_id:e.applicationId,application_declaration_id:e.declarationId,application_manifest_digest:e.manifestDigest,application_installation_id:e.applicationInstallationId,application_origin:e.applicationOrigin,collection_id:e.collectionId,grant_signing_public_key:e.grantSigningPublicKey,client_noise_public_key:e.clientNoisePublicKey};if(Object.entries(s).some(([r,a])=>o[r]!==a)||e.grantId!==void 0&&o.grant_id!==e.grantId||t.collection_id!==o.collection_id||t.grant_id!==o.grant_id||t.application_origin!==o.application_origin)throw zl();return Object.freeze({...o})}var o1,gj,zl,n_=C(()=>{"use strict";Jt();re();o1=["account_id","authorization_request_id","application_id","application_declaration_id","application_manifest_digest","application_installation_id","application_origin","collection_id","grant_id","grant_signing_public_key","client_noise_public_key"],gj=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,zl=()=>A("unauthenticated","native completion does not match the original approved preparation")});function i_(n,e,t,i,o,s){return Cm({native_completion:n,collection_id:e.collectionId,grant_id:n?.grant_id,application_origin:o},{accountId:t,authorizationRequestId:e.authorizationRequestId,applicationId:i,applicationOrigin:o,collectionId:e.collectionId,manifestDigest:s,declarationId:n?.application_declaration_id,applicationInstallationId:n?.application_installation_id,grantSigningPublicKey:n?.grant_signing_public_key,clientNoisePublicKey:n?.client_noise_public_key})}var l1=C(()=>{"use strict";n_()});function li(n){let e=()=>new TypeError("invalid collection display name");if(typeof n!="string"||/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/.test(n))throw e();for(let i=0;i<n.length;i++){let o=n.charCodeAt(i);if(o>=55296&&o<=56319){let s=n.charCodeAt(++i);if(!(s>=56320&&s<=57343))throw e()}else if(o>=56320&&o<=57343)throw e()}let t=n.trim();if(!t.length||t.length>200)throw e();return t}var Ws=C(()=>{"use strict"});function Rm(n){let e=[n.account,n.installation,n.collection];if(e.some(t=>typeof t!="string"||!c1.test(t)))throw new rt("invalid_scope");return`mdbase-app-${e.map(t=>t.toLowerCase()).join("-")}`}function r_(n){let e=[n.account,n.installation];if(e.some(t=>typeof t!="string"||!c1.test(t)))throw new rt("invalid_scope");return`mdbase-app-installation-${e.map(t=>t.toLowerCase()).join("-")}`}function Ad(n,e,t){return _d(n,Rm(e),t)}function kd(n,e,t){return _d(n,r_(e),t)}function Sd(n){return typeof n=="string"&&n.length>0&&n.length<=64&&!/[^A-Za-z0-9_-]/.test(n)}function Hs(n){return typeof n=="string"&&n.length>0&&n.length<=256&&!/[\u0000-\u001f\u007f]/.test(n)}function p1(n){let e=d1({cpOrigin:n.cpOrigin,appId:n.appId});if(n.storageNamespace===void 0)return e;if(!Hs(n.storageNamespace))throw new rt("invalid_scope");return`mdbase-app-sign-in-namespace-v1-${JSON.stringify([n.cpOrigin,n.appId,n.storageNamespace])}`}function d1(n){let e=new URL(n.cpOrigin);if(e.origin!==n.cpOrigin||e.username||e.password||!["https:","http:"].includes(e.protocol)||!Sd(n.appId))throw new rt("invalid_scope");if(n.owner===void 0)return`mdbase-app-sign-in-v1-${n.appId}-${n.cpOrigin}`;if(!Hs(n.owner))throw new rt("invalid_scope");return`mdbase-app-sign-in-v2-${JSON.stringify([n.cpOrigin,n.owner,n.appId])}`}function u1(n,e,t){if(e.storageNamespace!==void 0&&(!Hs(e.owner)||e.owner.startsWith("bundle:")))throw new rt("invalid_scope");let i=d1(e),o=p1(e);return e.owner===void 0?_d(n,o,t):(async()=>{let s=await _d(n,o,t);try{let r=await _d(n,i,t);return{release:async()=>{await r.release(),await s.release()}}}catch(r){throw await s.release(),r}})()}function f1(n,e,t){try{return n.request(p1(e),{mode:"shared",signal:t},async()=>{})}catch(i){return Promise.reject(i)}}function _d(n,e,t){if(!n)return Promise.reject(new rt("unavailable"));if(t?.aborted)return Promise.reject(new rt("aborted"));let i,o=new Promise(d=>{i=d}),s,r,a=new Promise((d,u)=>{s=d,r=u}),c=!1,l=()=>{c=!0,r(new rt("aborted"))};t?.addEventListener("abort",l,{once:!0});let p=Promise.resolve().then(()=>n.request(e,{mode:"exclusive",ifAvailable:!0},async d=>{if(t?.removeEventListener("abort",l),c||t?.aborted){r(new rt("aborted"));return}if(!d){r(new rt("busy"));return}s({release:()=>(i(),p)}),await o}));return p.catch(()=>{t?.removeEventListener("abort",l),r(new rt("unavailable"))}),a}async function h1(n){let e=n.closeTimeoutMs??5e3;if(!Number.isSafeInteger(e)||e<1||e>3e4)throw new RangeError("invalid Worker close timeout");let t=n.signal,i=Object.freeze({account:n.scope.account,installation:n.scope.installation,collection:n.scope.collection});Rm(i);let o=await kd(n.locks,i,t),s;try{s=await Ad(n.locks,i,t)}catch(h){throw await o.release(),h}let r={release:async()=>{await s.release(),await o.release()}},a;try{if(t?.aborted)throw new rt("aborted");a=n.create(i)}catch{throw await r.release(),new rt(t?.aborted?"aborted":"initialization_failed")}let c,l=Object.freeze({scope:Object.freeze({account:i.account,installation:i.installation}),isCurrent:()=>!c&&!t?.aborted}),p,d=new Promise((h,m)=>{p=()=>m(new rt("aborted"))}),u=()=>c??=(async()=>{t?.removeEventListener("abort",f);let h;try{await Promise.race([Promise.resolve().then(()=>a.stop()),new Promise(m=>{h=setTimeout(m,e)})])}catch{}finally{h&&clearTimeout(h)}try{a.terminate()}catch{throw new rt("shutdown_failed")}await r.release()})(),f=()=>{p(),u().catch(()=>{})};t?.addEventListener("abort",f,{once:!0});try{if(t?.aborted)throw new rt("aborted");if(await Promise.race([Promise.resolve().then(()=>n.initialize(a,t,i,l)),d]),t?.aborted||c)throw new rt("aborted");return{worker:a,scope:i,close:u}}catch{throw await u(),new rt(t?.aborted?"aborted":"initialization_failed")}}var rt,c1,os=C(()=>{"use strict";rt=class extends Error{constructor(t){super(`app replica owner: ${t}`);this.reason=t;this.name="AppReplicaOwnerError"}reason},c1=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i});function g1(n){if(typeof CryptoKey!="function"||!(n instanceof CryptoKey)||n.type!=="secret"||n.extractable||n.algorithm.name!=="AES-GCM"||n.algorithm.length!==256||n.usages.length!==2||!n.usages.includes("encrypt")||!n.usages.includes("decrypt"))throw lt();return n}function m1(n){if(!n||typeof n!="object"||Array.isArray(n)||Object.keys(n).sort().join()!=="encrypted,key,revision,version")throw lt();let e=n;if(e.version!==1||!Number.isSafeInteger(e.revision)||e.revision<0||!(e.encrypted instanceof Uint8Array)||e.encrypted.length<29||e.encrypted.length>y1+28)throw lt();return{version:1,revision:e.revision,key:g1(e.key),encrypted:new Uint8Array(e.encrypted)}}var $l,Om,y1,Pd,lt,bj,Em,b1=C(()=>{"use strict";St();Jt();os();$l="installation-sign-in",Om="original",y1=128*1024,Pd=class extends Error{constructor(t){super(`app installation storage ${t}; preserve storage and reopen`);this.reason=t}reason},lt=(n="unavailable")=>new Pd(n),bj=(n,e)=>n.length===e.length&&n.every((t,i)=>t===e[i]);Em=class n{constructor(e,t){this.options=e;this.lease=t;this.namespace=JSON.stringify(e.owner===void 0?["mdbase.app-installation.v1",e.origin,e.cpOrigin,e.appId]:["mdbase.app-installation.v2",e.origin,e.cpOrigin,e.owner,e.appId])}options;lease;db=null;record=null;closing=!1;closeResult=null;namespace;static async open(e,t){let i=Object.freeze({origin:e.origin,cpOrigin:e.cpOrigin,appId:e.appId,...e.owner===void 0?{}:{owner:e.owner},...e.storageNamespace===void 0?{}:{storageNamespace:e.storageNamespace},mode:e.mode,signal:e.signal,locks:e.locks,allowLoopbackHttp:e.allowLoopbackHttp===!0}),o=null,s=null,r=null;try{if(!ut(i.origin))throw lt();{let l=i.cpOrigin,p=new URL(l),d=i.allowLoopbackHttp&&Qe(l);if(p.origin!==l||p.username||p.password||p.protocol!=="https:"&&!d)throw lt()}if(i.owner!==void 0&&!Hs(i.owner)||!["fresh","existing","open"].includes(i.mode)||!Sd(i.appId)||i.signal.aborted||Et()!==i.origin||!globalThis.indexedDB||!globalThis.crypto?.subtle||typeof CryptoKey!="function")throw lt();let a=await u1(i.locks,i,i.signal);if(o=new n(i,a),o.check(),i.mode!=="existing"){s=t(),o.check(),o.bound(s);let l=g1(await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]));o.check(),r={version:1,revision:0,key:l,encrypted:await o.encrypt(l,0,s)},s.fill(0),s=null}o.db=await o.openDatabase(r),o.check(),o.db.onversionchange=()=>{o.close()},o.record=await o.readRecord(),o.check(),s=await o.decrypt(o.record),o.check(),o.bound(s);let c={store:o,plaintext:s};return s=null,c}catch(a){throw await o?.close(),lt(a instanceof rt&&a.reason==="busy"?"busy":"unavailable")}finally{s?.fill(0),r?.encrypted.fill(0)}}isCurrent(){try{return this.check(),!0}catch{return!1}}check(){if(this.closing||this.options.signal.aborted||Et()!==this.options.origin)throw lt()}bound(e){if(!(e instanceof Uint8Array)||!e.length||e.length>y1)throw lt()}aad(e){return new TextEncoder().encode(`${this.namespace}:${e}`)}async encrypt(e,t,i){this.check(),this.bound(i);let o=crypto.getRandomValues(new Uint8Array(12)),s=this.aad(t),r=new Uint8Array(i),a=null;try{a=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:o,additionalData:s},e,r)),this.check();let c=new Uint8Array(12+a.length);return c.set(o),c.set(a,12),c}finally{r.fill(0),a?.fill(0),o.fill(0),s.fill(0)}}async decrypt(e){this.check();let t=this.aad(e.revision),i=new Uint8Array(e.encrypted.subarray(0,12)),o=new Uint8Array(e.encrypted.subarray(12));try{let s=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:i,additionalData:t},e.key,o));try{return this.check(),this.bound(s),s}catch{throw s.fill(0),lt()}}finally{i.fill(0),o.fill(0),t.fill(0)}}openDatabase(e){return new Promise((t,i)=>{this.check();let o=this.options,s=o.owner===void 0?`mdbase.app.installation.v1.${encodeURIComponent(o.cpOrigin)}.${o.appId}`:`mdbase.app.installation.v2.${encodeURIComponent(o.cpOrigin)}.${encodeURIComponent(o.owner)}.${o.appId}`,r=indexedDB.open(s,1),a=!1,c=!1,l=()=>{a=!0;try{r.transaction?.abort()}catch{}i(lt())},p=()=>this.options.signal.removeEventListener("abort",l);this.options.signal.addEventListener("abort",l,{once:!0}),r.onblocked=l,r.onupgradeneeded=()=>{try{if(this.check(),a||!e||r.result.objectStoreNames.length)throw lt();r.result.createObjectStore($l).add(e,Om),c=!0}catch{r.transaction?.abort()}},r.onerror=()=>{p(),i(lt())},r.onsuccess=()=>{p();try{if(this.check(),a||this.options.mode==="fresh"&&!c||r.result.objectStoreNames.length!==1||!r.result.objectStoreNames.contains($l))throw lt();t(r.result)}catch{r.result.close(),i(lt())}}})}readRecord(){return new Promise((e,t)=>{if(this.check(),!this.db)throw lt();let i=this.db.transaction($l,"readonly",{durability:"strict"}),o=null,s=()=>{try{i.abort()}catch{}},r=()=>this.options.signal.removeEventListener("abort",s);this.options.signal.addEventListener("abort",s,{once:!0}),i.onerror=i.onabort=()=>{r(),o?.encrypted.fill(0),t(lt())},i.oncomplete=()=>{r();try{if(this.check(),!o)throw lt();e(o)}catch{o?.encrypted.fill(0),t(lt())}};let a=i.objectStore($l).get(Om);a.onsuccess=()=>{try{this.check(),o=m1(a.result)}catch{s()}}})}async commit(e){let t=null;try{if(this.check(),!this.record||this.record.revision>=Number.MAX_SAFE_INTEGER)throw lt();let i=this.record;t={version:1,revision:i.revision+1,key:i.key,encrypted:await this.encrypt(i.key,i.revision+1,e)},this.check(),await new Promise((o,s)=>{if(this.check(),!this.db)throw lt();let r=this.db.transaction($l,"readwrite",{durability:"strict"}),a=()=>{try{r.abort()}catch{}},c=()=>this.options.signal.removeEventListener("abort",a);this.options.signal.addEventListener("abort",a,{once:!0}),r.onerror=r.onabort=()=>{c(),s(lt())},r.oncomplete=()=>{c();try{this.check(),o()}catch{s(lt())}};let l=r.objectStore($l),p=l.get(Om);p.onsuccess=()=>{let d=null;try{if(this.check(),d=m1(p.result),d.revision!==i.revision||!bj(d.encrypted,i.encrypted))throw lt();l.put(t,Om)}catch{a()}finally{d?.encrypted.fill(0)}}}),this.check(),i.encrypted.fill(0),this.record=t,t=null}catch{throw await this.close(),lt()}finally{t?.encrypted.fill(0)}}close(){return this.closeResult??=(async()=>{this.closing=!0,this.db?.close(),this.db=null,this.record?.encrypted.fill(0),this.record=null,await this.lease.release()})()}}});function w1(){return new Promise(n=>{let e;try{e=indexedDB.open(s_,1)}catch{n(null);return}e.onupgradeneeded=()=>{try{e.result.createObjectStore(Bl)}catch{}},e.onsuccess=()=>{let t=e.result;t.onversionchange=()=>t.close(),n(t.objectStoreNames.contains(Bl)?t:(t.close(),null))},e.onerror=e.onblocked=()=>n(null)})}function o_(n,e){return w1().then(t=>new Promise(i=>{if(!t){i(null);return}let o=null;try{let s=t.transaction(Bl,n),r=e(s.objectStore(Bl));r&&(r.onsuccess=()=>{o=r.result??null}),s.oncomplete=()=>{t.close(),i(o)},s.onerror=s.onabort=()=>{t.close(),i(null)}}catch{t.close(),i(null)}}))}function v1(){return typeof indexedDB>"u"?null:Object.freeze({async read(n,e){let t=await o_("readonly",i=>i.get(n)).catch(()=>null);return!t||typeof t.value!="string"||!t.value||t.value.length>16*1024||/[^\x21-\x7e]/.test(t.value)||typeof t.expires!="number"||!Number.isSafeInteger(t.expires)||t.expires-e<6e4||t.expires-e>16*6e4?null:Object.freeze({value:t.value,expires:t.expires})},async write(n,e){await o_("readwrite",t=>t.put({value:e.value,expires:e.expires},n)).catch(()=>null)},async drop(n){await o_("readwrite",e=>e.delete(n)).catch(()=>null)}})}async function _1(n){let{cpOrigin:e,connectorId:t,deviceId:i}=n;if(!t||!i)return!0;let o=await w1();return o?new Promise(s=>{try{let r=o.transaction(Bl,"readwrite"),a=r.objectStore(Bl).openCursor();a.onsuccess=()=>{let c=a.result;if(c){if(typeof c.key=="string"){let l=c.key.split(" ");l.length===5&&l[0]===e&&l[2]===t&&l[3]===i&&c.delete()}c.continue()}},r.oncomplete=()=>{o.close(),s(!0)},r.onerror=r.onabort=()=>{o.close(),s(!1)}}catch{o.close(),s(!1)}}):!1}var s_,Bl,a_=C(()=>{"use strict";s_="mdbase.app.log-token.v1",Bl="tokens"});function qm(n,e,t=wj){let i;return Promise.race([n.catch(()=>e),new Promise(o=>{i=setTimeout(()=>o(e),t)})]).finally(()=>clearTimeout(i))}function xd(n){return qm(new Promise(e=>{let t=indexedDB.deleteDatabase(n);t.onsuccess=()=>e(!0),t.onerror=()=>e(!1)}),!1)}function A1(n){let{accountId:e,connectorId:t,deviceId:i,installationId:o}=n,s=[e,t,i,o].map(vj).join(".");return[`mdbase.app.device-key-kek.v1.${s}`,`mdbase.app.device-keys.v1.${s}`,`mdbase.app.noise.v1.${nr(o)}.${nr(t)}.${nr(i)}`]}async function k1(n){try{return globalThis.indexedDB?(await Promise.all(A1(n).map(xd))).every(Boolean):!1}catch{return!1}}function _j(n){let e=encodeURIComponent(n.cpOrigin),t=`mdbase.app.installation.v1.${e}.${n.appId}`;return[n.owner===void 0?t:`mdbase.app.installation.v2.${e}.${encodeURIComponent(n.owner)}.${n.appId}`,t]}async function Aj(n){let e=new Set,{accountId:t,connectorId:i,deviceId:o,installationId:s}=n;if(t&&i&&o&&s){for(let l of A1({accountId:t,connectorId:i,deviceId:o,installationId:s}))e.add(l);let r=[t,i,o,s].map(nr).join("."),a=[`mdbase.app.cloud-copy-outcome.v1.${r}.`,`mdbase.app.private-bootstrap.v1.${r}.`];for(let l of n.collectionIds){let p=nr(l);for(let d of["create","join"])e.add(`${a[0]}${p}.${d}`);for(let d of["create","enrol"])e.add(`${a[1]}${p}.${d}`)}let c=indexedDB.databases;if(typeof c=="function"){let l=await qm(c.call(indexedDB),[]);for(let{name:p}of l)p&&a.some(d=>p.startsWith(d))&&e.add(p)}}return[...e]}async function kj(n,e){let t=globalThis.navigator?.storage;return typeof t?.getDirectory!="function"?!0:qm((async()=>{let i=await t.getDirectory(),o=`.mdbase-app-${nr(n)}-${nr(e)}-`,s=[];for await(let a of i.keys())a.startsWith(o)&&s.push(a);let r=!0;for(let a of s)try{await i.removeEntry(a,{recursive:!0})}catch{r=!1}return r})(),!1)}async function S1(n,e){try{if(!globalThis.indexedDB||!n.accountId||!n.connectorId||!n.deviceId||!n.installationId)return!1;let t=nr(e),i=[n.accountId,n.connectorId,n.deviceId,n.installationId].map(nr).join("."),o=["create","join"].map(a=>`mdbase.app.cloud-copy-outcome.v1.${i}.${t}.${a}`);o.push(...["create","enrol"].map(a=>`mdbase.app.private-bootstrap.v1.${i}.${t}.${a}`));let s=await Promise.all(o.map(xd)),r=globalThis.navigator?.storage;if(typeof r?.getDirectory=="function"){let a=await r.getDirectory();try{await a.removeEntry(`.mdbase-app-${nr(n.accountId)}-${nr(n.installationId)}-${t}`,{recursive:!0})}catch(c){if(!(c instanceof DOMException&&c.name==="NotFoundError"))return!1}}return s.every(Boolean)}catch{return!1}}async function P1(n){if(!globalThis.indexedDB)return Object.freeze({ledger:!1,complete:!1});let[e,t]=_j(n),i=await xd(e),o=new Set(n.isolated?[]:n.databases);!n.isolated&&n.storageNamespace===void 0&&o.add(t),o.delete(e),!n.isolated&&n.storageNamespace===void 0&&o.add(s_);let[s,r]=await Promise.all([Promise.all([...o].map(xd)),l_(n,n.storageNamespace!==void 0)]);return Object.freeze({ledger:i,complete:i&&r&&s.every(Boolean)})}async function l_(n,e=!0){if(!globalThis.indexedDB)return!1;let t=Aj(n).then(s=>Promise.all(s.map(xd))).then(s=>s.every(Boolean),()=>!1),i=e?qm(_1(n),!1):!0,o=n.accountId&&n.installationId?kj(n.accountId,n.installationId).catch(()=>!1):!0;return(await Promise.all([t,i,o])).every(Boolean)}var wj,vj,nr,Tm=C(()=>{"use strict";a_();ve();wj=5e3,vj=n=>Array.from(N(n),e=>e.toString(16).padStart(2,"0")).join(""),nr=n=>(N(n),n.toLowerCase())});function Sj(n,e){if(n!==400||!e||typeof e!="object"||Array.isArray(e))return!1;let{code:t,message:i}=e;return t==="invalid_request"&&typeof i=="string"&&i.length<=512&&/unrecognized key/i.test(i)&&i.includes("requested_private_device")}function _e(n){if(typeof n!="string"||!Pj.test(n)||N(n).every(e=>e===0))throw E("response");return n}function gn(n,e){if(typeof n!="string"||!e.test(n))throw E("response");return n}function Me(n,e){if(!n||typeof n!="object"||Array.isArray(n)||Object.keys(n).sort().join()!==e.split(",").sort().join())throw E("response");return n}function xj(n){if(typeof n!="string"||n.length>320||!/^[^\s@\u0000-\u001f\u007f]+@[^\s@\u0000-\u001f\u007f]+$/.test(n))throw E("response");return n}function Vl(n,e=!1){let[t,i,o,s]=e?["accountEmail","portalConfirmed","accountProvider","accountLogin"]:["account_email","account_selection_confirmed","account_provider","account_login"];return[t,i,o,s].some(r=>Object.hasOwn(n,r))?`,${t},${i}${Object.hasOwn(n,o)||Object.hasOwn(n,s)?`,${o},${s}`:""}`:""}function Mm(n,e=!1){let t=Vl(n,e);if(!t)return{};let i=e?n.accountEmail:n.account_email,o=e?n.portalConfirmed:n.account_selection_confirmed,s=e?n.accountProvider:n.account_provider,r=e?n.accountLogin:n.account_login;if(o!==!0)throw E("response");if(t.includes(e?"accountProvider":"account_provider")){if(i!==null||s!=="github"||typeof r!="string"||!r.length||new TextEncoder().encode(r).byteLength>100||/[\s\u0000-\u001f\u007f]/.test(r))throw E("response");return{accountEmail:null,portalConfirmed:!0,accountProvider:"github",accountLogin:r}}return{accountEmail:xj(i),portalConfirmed:!0}}function Ij(n){let{accountEmail:e,portalConfirmed:t,accountProvider:i,accountLogin:o,...s}=n;return s}function x1(n,e){if(n.portalConfirmed&&(e.portalConfirmed!==!0||n.accountEmail!==e.accountEmail||n.accountProvider!==e.accountProvider||n.accountLogin!==e.accountLogin))throw E("binding")}function m_(n){return Object.hasOwn(n,"timer_consent")||Object.hasOwn(n,"timer_grants")?",timer_consent,timer_grants":""}function d_(n,e,t,i,o){if(!m_(n))return;if(![!0,!1,null].includes(n.timer_consent)||!Array.isArray(n.timer_grants)||n.timer_grants.length>1e3)throw E("response");let s=n.timer_grants.map(r=>{let a=Me(r,"grant_id,collection_id,declaration_digest"),c=_e(a.collection_id);if(!t.includes(c))throw E("response");return Object.freeze({grantId:_e(a.grant_id),collectionId:c,declarationDigest:gn(a.declaration_digest,/^[0-9a-f]{64}$/)})});if(new Set(s.map(r=>r.grantId)).size!==s.length||new Set(s.map(r=>r.collectionId)).size!==s.length||(n.timer_consent===!0?!i||!o||!s.some(r=>r.collectionId===o):s.length!==0)||new Set(s.map(r=>r.declarationDigest)).size>1)throw E("response");return n.timer_consent===null?void 0:Object.freeze({requestId:e,approved:n.timer_consent===!0,grants:Object.freeze(s.filter(r=>r.collectionId===o))})}function u_(n){let e=Me(n,"grantId,kind,targetDigest,channelId,pending");if(!["web_push","fcm"].includes(e.kind)||![null,"register","delete"].includes(e.pending)||e.channelId===null&&e.pending!=="register")throw E("response");return Object.freeze({grantId:_e(e.grantId),kind:e.kind,targetDigest:gn(e.targetDigest,/^[0-9a-f]{64}$/),channelId:e.channelId===null?null:_e(e.channelId),pending:e.pending})}function Cj(n){let e=n&&typeof n=="object"&&!Array.isArray(n)?n.collections:void 0;return Array.isArray(e)&&e.length>0&&e.every(t=>!t||typeof t!="object"||!("mode"in t))}function f_(n){if(!Array.isArray(n)||n.length>1e3)throw E("response");let e=new Set;return Object.freeze(n.map(t=>{let i=c=>t&&typeof t=="object"&&c in t?`,${c}`:"",o=Me(t,`collection_id,display_name,role${i("availability")}${i("file_actions")}${i("mode")}`),s=_e(o.collection_id);if("mode"in o&&o.mode!=="cloud_copy"&&o.mode!=="private"||e.has(s)||typeof o.display_name!="string"||!o.display_name.length||o.display_name.length>1024||o.role!=="owner"&&o.role!=="editor"&&o.role!=="viewer")throw E("response");let r=wi(o.availability),a="file_actions"in o?y_(o.file_actions):null;return e.add(s),Object.freeze({collectionId:s,displayName:o.display_name,role:o.role,...r?{availability:r}:{},...a?{fileActions:a}:{},...o.mode==="private"?{mode:"private"}:{}})}))}function y_(n,e=Lm,t=!0){if(!Array.isArray(n)||n.length>Lm.length||!t&&!n.length||new Set(n).size!==n.length||n.some(i=>!e.includes(i)))throw E("response");return Object.freeze(Lm.filter(i=>n.includes(i)))}function I1(n){let e=n.collectionHint??null;if(e!==null&&(typeof e!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(e)||e==="00000000-0000-0000-0000-000000000000"))throw E("binding");return e}function C1(n,e,t){return n===e||t!==null&&n===`${e}?collection_hint=${t}`?n:null}var et,E,c_,p_,ci,Pj,h_,Lm,g_,uo,Fl,Id=C(()=>{"use strict";l1();No();ve();St();Ws();rs();b1();os();ri();Tm();et=class extends Error{constructor(t,i){super(`app installation sign-in: ${t}`);this.reason=t;this.server=i;this.name="AppInstallationSignInError"}reason;server},E=n=>new et(n),c_=new WeakSet,p_=new WeakSet;ci=n=>Array.from(n,e=>e.toString(16).padStart(2,"0")).join(""),Pj=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;h_=1e3,Lm=["list","read","add","replace","move","delete"];Fl=class n{constructor(e,t,i){this.store=e;this.state=t;this.options=i;this.request=i.fetch??((o,s)=>globalThis.fetch(o,s)),this.parent=i.signal,this.parent.addEventListener("abort",this.onAbort,{once:!0}),this.check()}store;state;options;static{g_=(e,t,i)=>e.replaceRefusedInstallation(t,i),uo={replacementPending:e=>e.replacementPending(),references:e=>e.scopedInstallationReferences(),replaceRetained:(e,t,i,o)=>e.replaceRetainedCollectionInstallation(t,i,o)}}closed=!1;busy=!1;nativeAcknowledged=!1;credentialRefused=!1;closedPairing=null;wrongAccountRequestId=null;lifetime=new AbortController;request;parent;onAbort=()=>{this.close()};static async open(e){let t=Object.freeze({...e,...e.recoveryFor?{recoveryFor:Object.freeze({...e.recoveryFor})}:{}}),i=null;try{if(!["lab","staging","production"].includes(t.environment)||!Sd(t.appId)||typeof t.appName!="string"||!t.appName.length||t.appName.length>100||t.appName.trim()!==t.appName||t.installationKind!==void 0&&t.installationKind!=="app-runtime"&&t.installationKind!=="mobile")throw E("binding");let o=t.environmentSelection;if(t.requestedCreateCollections!==void 0&&typeof t.requestedCreateCollections!="boolean"||t.freshRequestedCreateCollections!==void 0&&typeof t.freshRequestedCreateCollections!="boolean"||t.freshRequestedPrivateDevice!==void 0&&typeof t.freshRequestedPrivateDevice!="boolean")throw E("binding");if(t.recoveryFor!==void 0){let r=Me(t.recoveryFor,"accountId,collectionId");if(_e(r.accountId),_e(r.collectionId),!t.owner||t.requestedCreateCollections===!0||t.freshRequestedCreateCollections===!0)throw E("binding")}if(o!==void 0&&(!YC(o)||o.environment!==t.environment||o.appOrigin!==t.origin||o.cpOrigin!==t.cpOrigin||t.allowLoopbackHttp===!0&&!o.allowLoopbackHttp))throw E("binding");i=await Em.open({...t,allowLoopbackHttp:o?.allowLoopbackHttp??t.allowLoopbackHttp},()=>new TextEncoder().encode(JSON.stringify(this.freshState(t))));let s=this.decode(i.plaintext,t);return new n(i.store,s,t)}catch(o){throw await i?.store.close(),o instanceof et?o:o instanceof Pd&&o.reason==="busy"?E("open_in_another_tab"):E("recovery_required")}finally{i?.plaintext.fill(0)}}static freshState(e){let t=crypto.getRandomValues(new Uint8Array(32));try{let i=`pair_${btoa(String.fromCharCode(...t)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}`;return{version:3,renewal:null,requestedCreateCollections:e.requestedCreateCollections??e.freshRequestedCreateCollections??!1,collectionIds:[],createCollections:!1,consentRequest:null,...e.freshRequestedPrivateDevice===!0?{requestedPrivateDevice:!0}:{},requestId:crypto.randomUUID(),installationId:crypto.randomUUID(),deviceId:crypto.randomUUID(),secret:i,appId:e.appId,...e.owner===void 0?{}:{owner:e.owner},kind:e.installationKind??"app-runtime",origin:e.origin,cpOrigin:e.cpOrigin,environment:e.environment,selection:null,confirmed:!1,nativeStarted:!1,proof:null,token:null,...e.recoveryFor?{recoveryFor:e.recoveryFor}:{}}}finally{t.fill(0)}}static decode(e,t){let i=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e)),o="version,requestId,installationId,deviceId,secret,appId,kind,origin,cpOrigin,environment,selection,confirmed,nativeStarted,proof,token",s=i?.version===1,r=`${o},requestedCreateCollections,collectionIds,createCollections,consentRequest`,a=s?{...Me(i,o),version:3,renewal:null,requestedCreateCollections:!1,collectionIds:[],createCollections:!1,consentRequest:null}:i?.version===2?{...Me(i,r),version:3,renewal:null}:Me(i,`${r},renewal${Object.hasOwn(i,"collectionSelection")?",collectionSelection":""}${Object.hasOwn(i,"timerConsent")?",timerConsent":""}${Object.hasOwn(i,"timerChannel")?",timerChannel":""}${Object.hasOwn(i,"owner")?",owner":""}${Object.hasOwn(i,"collectionListing")?",collectionListing":""}${Object.hasOwn(i,"collectionRecoveries")?",collectionRecoveries":""}${Object.hasOwn(i,"retainedCollectionRecoveries")?",retainedCollectionRecoveries":""}${Object.hasOwn(i,"replacementPending")?",replacementPending":""}${Object.hasOwn(i,"recoveryFor")?",recoveryFor":""}${Object.hasOwn(i,"nativeAuthorization")?",nativeAuthorization":""}${Object.hasOwn(i,"nativeSelection")?",nativeSelection":""}${Object.hasOwn(i,"nativeGrants")?",nativeGrants":""}${Object.hasOwn(i,"requestedPrivateDevice")?",requestedPrivateDevice":""}${Object.hasOwn(i,"privateDeviceCollectionIds")?",privateDeviceCollectionIds":""}${Object.hasOwn(i,"requestSent")?",requestSent":""}`);if(a.version!==3||a.appId!==t.appId||a.owner!==t.owner||a.kind!==(t.installationKind??"app-runtime")||a.origin!==t.origin||a.cpOrigin!==t.cpOrigin||a.environment!==t.environment||typeof a.confirmed!="boolean"||typeof a.nativeStarted!="boolean")throw E("recovery_required");let c=a;if(typeof c.requestedCreateCollections!="boolean"||typeof c.createCollections!="boolean"||t.requestedCreateCollections!==void 0&&t.requestedCreateCollections!==c.requestedCreateCollections)throw E("binding");if(c.collectionIds=this.collectionIds(c.collectionIds),c.requestedPrivateDevice!==void 0&&c.requestedPrivateDevice!==!0)throw E("recovery_required");if(c.privateDeviceCollectionIds!==void 0){let l=this.collectionIds(c.privateDeviceCollectionIds);if(!l.length||!c.token||l.some(p=>!c.collectionIds.includes(p)))throw E("recovery_required");c.privateDeviceCollectionIds=l}if(c.recoveryFor!==void 0){let l=Me(c.recoveryFor,"accountId,collectionId");_e(l.accountId),_e(l.collectionId)}if(c.recoveryFor===void 0!=(t.recoveryFor===void 0)||c.recoveryFor?.accountId!==t.recoveryFor?.accountId||c.recoveryFor?.collectionId!==t.recoveryFor?.collectionId||c.recoveryFor&&(c.requestedCreateCollections||c.createCollections||c.selection&&c.selection.accountId!==c.recoveryFor.accountId||c.token&&(c.nativeSelection?c.collectionIds.length!==0||c.nativeSelection.collectionId!==c.recoveryFor.collectionId:!n.recovered(c.recoveryFor.collectionId,c.collectionIds,c.privateDeviceCollectionIds??[],c.collectionSelection))))throw E("recovery_required");if(c.consentRequest!==null){let l=Me(c.consentRequest,`requestId,secret,requestedCreateCollections,challenge,completed,addedCollectionIds,approvedCreateCollections${Object.hasOwn(c.consentRequest,"requestedPrivateDevice")?",requestedPrivateDevice":""}${Vl(c.consentRequest,!0)}`);if(l.requestedPrivateDevice!==void 0&&l.requestedPrivateDevice!==!0||(Mm(l,!0),_e(l.requestId),gn(l.secret,/^pair_[A-Za-z0-9_-]{43}$/),l.requestId===c.requestId||l.secret===c.secret||typeof l.requestedCreateCollections!="boolean"||typeof l.completed!="boolean"||typeof l.approvedCreateCollections!="boolean"||l.approvedCreateCollections&&!l.requestedCreateCollections)||(l.challenge!==null&&gn(l.challenge,/^[0-9a-f]{64}$/),this.collectionIds(l.addedCollectionIds),!c.token||!c.selection||l.completed&&l.challenge===null))throw E("recovery_required")}if(c.createCollections&&!c.token||c.collectionIds.length&&!c.token)throw E("recovery_required");if(c.collectionSelection!==void 0){let l=Me(c.collectionSelection,"requestId,selectedCollectionId,createdCollectionIds");if(_e(l.requestId),!c.token||!c.collectionIds.includes(_e(l.selectedCollectionId))||this.collectionIds(l.createdCollectionIds).some(p=>!c.collectionIds.includes(p)))throw E("recovery_required")}if(_e(c.requestId),_e(c.installationId),_e(c.deviceId),gn(c.secret,/^pair_[A-Za-z0-9_-]{43}$/),c.renewal!==null){let l=Me(c.renewal,"requestId,secret");if(_e(l.requestId),gn(l.secret,/^pair_[A-Za-z0-9_-]{43}$/),l.requestId===c.requestId||l.secret===c.secret)throw E("recovery_required")}if(c.requestSent!==void 0&&c.requestSent!==c.requestId)throw E("recovery_required");if(c.timerChannel!==void 0){if(!c.token||!c.selection)throw E("recovery_required");try{c.timerChannel=u_(c.timerChannel)}catch{throw E("recovery_required")}}if(c.timerConsent!==void 0){let l=Me(c.timerConsent,"requestId,approved,grants");if(_e(l.requestId),!c.token||!c.selection||typeof l.approved!="boolean"||!Array.isArray(l.grants)||l.grants.length>1)throw E("recovery_required");let p=l.grants.map(u=>{let f=Me(u,"grantId,collectionId,declarationDigest");return{grant_id:f.grantId,collection_id:f.collectionId,declaration_digest:f.declarationDigest}}),d=c.selection.portalConfirmed===!0||c.consentRequest?.portalConfirmed===!0;c.timerConsent=d_({timer_consent:l.approved,timer_grants:p},_e(l.requestId),c.collectionIds,d,p[0]?.collection_id)}if(c.selection!==null){let l=Me(c.selection,`accountId,connectorId,challenge,approvalMode${Vl(c.selection,!0)}`);if(_e(l.accountId),_e(l.connectorId),gn(l.challenge,/^[0-9a-f]{64}$/),l.approvalMode!=="password-ak1")throw E("response");Mm(l,!0)}if(c.proof!==null&&this.proof(c.proof),c.token!==null&&gn(c.token,/^idev_[A-Za-z0-9_-]{43}$/),c.confirmed&&!c.selection||c.nativeStarted&&!c.confirmed||c.proof&&!c.nativeStarted||c.token&&!c.proof||c.collectionListing!==void 0&&(!c.token||!c.confirmed||!c.selection||!c.proof||f_(c.collectionListing).some(l=>!c.collectionIds.includes(l.collectionId))))throw E("recovery_required");if(c.collectionRecoveries!==void 0){if(!c.token||!c.confirmed||!c.selection||!c.proof||!c.collectionRecoveries||typeof c.collectionRecoveries!="object"||Array.isArray(c.collectionRecoveries))throw E("recovery_required");let l=Object.entries(c.collectionRecoveries);if(l.length>h_||l.some(([p,d])=>!(c.collectionIds.includes(_e(p))||c.nativeGrants?.some(u=>u.collection_id===p))||d!==null&&!_e(d)))throw E("recovery_required")}if(c.replacementPending!==void 0&&(c.replacementPending!==!0||!c.token||!c.confirmed))throw E("recovery_required");if(c.retainedCollectionRecoveries!==void 0){let l=c.retainedCollectionRecoveries;if(c.recoveryFor||!l||typeof l!="object"||Array.isArray(l))throw E("recovery_required");let p=Object.values(c.collectionRecoveries??{}).filter(u=>u!==null),d=new Set(p);if(d.size!==p.length)throw E("recovery_required");for(let[u,f]of Object.entries(l)){if(_e(u),!f||typeof f!="object"||Array.isArray(f))throw E("recovery_required");let h=Object.entries(f);if(!h.length||d.size+h.length>h_)throw E("recovery_required");for(let[m,w]of h){if(_e(m),_e(w),d.has(w)||u===c.selection?.accountId&&Object.hasOwn(c.collectionRecoveries??{},m))throw E("recovery_required");d.add(w)}}}if(c.nativeAuthorization){let l=Me(c.nativeAuthorization,"requestId,authorizationId,applicationId,manifestDigest");if(_e(l.requestId),_e(l.authorizationId),l.applicationId!==c.appId||!c.proof||!c.confirmed)throw E("recovery_required");gn(l.manifestDigest,/^[0-9a-f]{64}$/)}if(c.nativeSelection){let l=Me(c.nativeSelection,"requestId,authorizationRequestId,collectionId");if(_e(l.requestId),_e(l.authorizationRequestId),_e(l.collectionId),!c.token||!c.nativeAuthorization||l.requestId!==c.nativeAuthorization.requestId||l.authorizationRequestId!==c.nativeAuthorization.authorizationId)throw E("recovery_required")}if(c.nativeGrants&&(!c.token||!c.selection||!Array.isArray(c.nativeGrants)||c.nativeGrants.length>1e3||(c.nativeGrants=c.nativeGrants.map(l=>i_(l,{requestId:c.requestId,authorizationRequestId:l.authorization_request_id,collectionId:l.collection_id},c.selection.accountId,c.appId,c.origin,l.application_manifest_digest)),new Set(c.nativeGrants.map(l=>l.collection_id)).size!==c.nativeGrants.length)))throw E("recovery_required");return c}modeConsented(e){return e.mode==="private"==(this.state.privateDeviceCollectionIds?.includes(e.collectionId)===!0)}static collectionIds(e){if(!Array.isArray(e)||e.length>1e3)throw E("response");let t=e.map(_e);if(new Set(t).size!==t.length)throw E("response");return t}static proof(e){let t=Me(e,"sign_pk,kem_pk,noise_pk,sig");return{sign_pk:gn(t.sign_pk,/^[0-9a-f]{64}$/),kem_pk:gn(t.kem_pk,/^[0-9a-f]{64}$/),noise_pk:gn(t.noise_pk,/^[0-9a-f]{64}$/),sig:gn(t.sig,/^[0-9a-f]{128}$/)}}isCurrent(){return!this.closed&&!this.parent.aborted&&!this.lifetime.signal.aborted&&this.store.isCurrent()}check(){if(!this.isCurrent())throw E("fenced")}view(){this.check();let e=this.state,t=e.consentRequest?.portalConfirmed?e.consentRequest:e.selection;return Object.freeze({requestId:e.requestId,installationId:e.installationId,deviceId:e.deviceId,appId:e.appId,kind:e.kind,verificationUri:`${e.cpOrigin}/pair/${e.requestId}`,state:e.token?"paired":e.proof?"awaiting_approval":e.confirmed?"account_confirmed":e.selection?"account_selected":"pending",accountId:e.selection?.accountId??null,accountEmail:t?.accountEmail??null,...t?.accountProvider?{accountProvider:t.accountProvider,accountLogin:t.accountLogin}:{},collectionSelection:e.collectionSelection?Object.freeze({...e.collectionSelection,createdCollectionIds:Object.freeze([...e.collectionSelection.createdCollectionIds])}):null,nativeSelection:e.nativeSelection&&e.nativeGrants?.some(i=>i.authorization_request_id===e.nativeSelection.authorizationRequestId&&i.collection_id===e.nativeSelection.collectionId)?Object.freeze({...e.nativeSelection}):null,nativeGrants:Object.freeze([...e.nativeGrants??[]]),...e.timerConsent?{timerConsent:e.timerConsent}:{},collectionIds:Object.freeze([...e.collectionIds]),createCollections:e.createCollections,requestedCreateCollections:e.requestedCreateCollections,...e.privateDeviceCollectionIds?.length?{privateDeviceCollectionIds:Object.freeze([...e.privateDeviceCollectionIds])}:{}})}async save(e){this.check();let t=new TextEncoder().encode(JSON.stringify(e));try{await this.store.commit(t),this.check(),this.state=e}catch{throw await this.close(),E("recovery_required")}finally{t.fill(0)}}async exclusive(e){if(this.check(),this.busy)throw E("busy");this.busy=!0;try{return await e()}finally{this.busy=!1}}async json(e,t,i,o){this.check(),this.wrongAccountRequestId=null;let s=new AbortController,r=()=>s.abort(),a=setTimeout(r,15e3);this.lifetime.signal.addEventListener("abort",r,{once:!0});let c=null,l=null,p=!1,d=!1,u=new Uint8Array(o?.get||e.endsWith("/exchange")?1024*1024:64*1024),f=0;try{if(c=await this.request(`${this.state.cpOrigin}${e}`,{method:o?.get?"GET":o?.patch?"PATCH":o?.delete?"DELETE":"POST",headers:{...o?{authorization:`Bearer ${o.bearer}`}:t?{authorization:`Bearer ${this.state.secret}`}:{},...i===void 0?{}:{"content-type":"application/json"}},body:i===void 0?void 0:JSON.stringify(i),credentials:"omit",redirect:"error",cache:"default",referrerPolicy:"no-referrer",signal:s.signal}),this.check(),s.signal.aborted)throw E("outcome_unknown");let h=c.headers.get("content-length");if(h!==null&&/^(0|[1-9][0-9]*)$/.test(h)&&Number(h)>u.length)throw s.abort(),E("response");if(!c.body)throw E("response");for(l=c.body.getReader();;){let{done:w,value:b}=await l.read();try{if(this.check(),s.signal.aborted)throw E("outcome_unknown");if(w){p=!0;break}if(f+b.length>u.length)throw s.abort(),E("response");u.set(b,f),f+=b.length}finally{b?.fill(0)}}d=!0;let m=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(u.subarray(0,f)));if(!m||typeof m!="object"||Array.isArray(m))throw E("response");if(!c.ok){let w=m.error;if(!o&&c.status===404&&(e==="/v1/pairing-requests"||e===`/v1/pairing-requests/${this.state.requestId}/exchange`||e===`/v1/pairing-requests/${this.state.requestId}/attest`)&&w&&typeof w=="object"&&!Array.isArray(w)&&(w.code==="installation_pairing_expired"||w.code==="installation_pairing_denied")){let y=w.code==="installation_pairing_expired"?"expired":"refused";throw this.closedPairing={requestId:this.state.requestId,reason:y},E(y)}let b=vi(c.status,m,c.headers);this.state.token&&o?.bearer===this.state.token&&b.status===401&&b.code==="invalid_connector"&&(this.credentialRefused=!0);let g=new et(Rt(b)??"refused",b);throw e==="/v1/pairing-requests"&&Sj(c.status,w)&&p_.add(g),g}return{status:c.status,value:m}}catch(h){this.check();let m=h instanceof et?h:E(o?.get&&!s.signal.aborted&&!(h instanceof DOMException&&h.name==="AbortError")?d?"response":!c||c.ok?"unavailable":"refused":"outcome_unknown");throw c&&!c.ok&&c_.add(m),m}finally{u.fill(0),p||(l?.cancel()??c?.body?.cancel())?.catch(()=>{}),l?.releaseLock(),clearTimeout(a),this.lifetime.signal.removeEventListener("abort",r)}}start(e={}){let t;try{t=I1(e)}catch(i){return Promise.reject(i)}return this.exclusive(()=>this.startRequest(t))}replaceRefusedInstallation(e,t){return this.exclusive(async()=>{let i=this.state;if(!(this.credentialRefused||i.replacementPending)||!i.token)throw E("recovery_required");let o=this.scopedInstallationReferences();if(o.some(c=>!t?.(c)))throw E("recovery_required");let s=this.confirmedSelection(),r=[...i.collectionIds,...(i.nativeGrants??[]).map(c=>c.collection_id)];if(i.replacementPending||await this.saveWithRecoveryMetadata({...i,replacementPending:!0}),await e(),!await l_({...s,collectionIds:r})||o.some(c=>!t?.(c)))throw E("recovery_required");let a=n.freshState(this.options);if(o.length){let c={};for(let{accountId:l,collectionId:p,reference:d}of o)(c[l]??={})[p]=d;a.retainedCollectionRecoveries=c}await this.save(a),this.credentialRefused=!1,this.nativeAcknowledged=!1,this.closedPairing=null})}replacementPending(){return this.check(),this.state.replacementPending===!0}renewExpiredPairing(){return this.exclusive(async()=>{let e=this.state;if(e.token||this.closedPairing?.requestId!==e.requestId)throw E("recovery_required");let t=crypto.getRandomValues(new Uint8Array(32));try{let i=crypto.randomUUID(),o=`pair_${btoa(String.fromCharCode(...t)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}`;if(i===e.requestId||i===e.renewal?.requestId||o===e.secret)throw E("binding");let{requestSent:s,...r}=e,a=e.selection?Ij(e.selection):e.selection;return await this.save({...r,selection:a,requestId:i,secret:o,renewal:{requestId:e.requestId,secret:e.secret}}),this.closedPairing=null,await this.startRequest()}finally{t.fill(0)}})}async startRequest(e=null){if(this.state.token)return this.view();let t=this.state;if(t.recoveryFor&&e!==null&&e!==t.recoveryFor.collectionId)throw E("binding");if(this.closedPairing?.requestId===t.requestId)throw E(this.closedPairing.reason);let i;try{i=await this.json("/v1/pairing-requests",!1,{installation:{app_id:t.appId,request_id:t.requestId,pairing_secret:t.secret,installation_id:t.installationId,device_id:t.deviceId,kind:t.kind,requested_create_collections:t.requestedCreateCollections,...t.requestedPrivateDevice===!0?{requested_private_device:!0}:{},...t.recoveryFor?{recovery_collection_id:t.recoveryFor.collectionId}:{},...t.renewal?{renewal:{request_id:t.renewal.requestId,pairing_secret:t.renewal.secret}}:{}},...e?{collection_hint:e}:{}})}catch(a){if(t.requestedPrivateDevice!==!0||!(a instanceof et)||!p_.has(a))throw a;let{requestedPrivateDevice:c,...l}=t;return await this.save(l),await this.startRequest(e)}let{status:o,value:s}=i;if(o!==200&&o!==201)throw E("response");Me(s,`pairing_id,pairing_secret,verification_uri,expires_in,installation_device,app_id,app_origin,app_name${this.recoveryTargetKeys()}`),this.assertRecoveryTarget(s);let r=C1(s.verification_uri,`${t.cpOrigin}/pair/${t.requestId}`,e);if(s.pairing_id!==t.requestId||s.pairing_secret!==t.secret||r===null||s.installation_device!==!0||s.app_id!==t.appId||s.app_origin!==t.origin||s.app_name!==this.options.appName||!Number.isSafeInteger(s.expires_in)||s.expires_in<0||s.expires_in>600)throw E("response");return this.state.requestSent!==t.requestId&&await this.save({...this.state,requestSent:t.requestId}),Object.freeze({...this.view(),verificationUri:r})}recoveryTargetKeys(){return this.state.recoveryFor?",recovery_collection_id":""}assertRecoveryTarget(e){if(this.state.recoveryFor&&_e(e.recovery_collection_id)!==this.state.recoveryFor.collectionId)throw E("binding")}selected(e){let t=this.state;if(this.assertRecoveryTarget(e),e.request_id!==t.requestId||e.installation_id!==t.installationId||e.device_id!==t.deviceId||e.kind!==t.kind||e.app_id!==t.appId||e.app_origin!==t.origin||e.approval_mode!=="password-ak1"||!Number.isSafeInteger(e.expires_at)||e.expires_at<0)throw E("response");let i={accountId:_e(e.account_id),connectorId:_e(e.connector_id),challenge:gn(e.challenge,/^[0-9a-f]{64}$/),approvalMode:"password-ak1"};if(t.selection&&(i.accountId!==t.selection.accountId||i.connectorId!==t.selection.connectorId||i.challenge!==t.selection.challenge||i.approvalMode!==t.selection.approvalMode))throw E("binding");if(Object.assign(i,Mm(e)),t.selection&&x1(t.selection,i),t.recoveryFor&&i.accountId!==t.recoveryFor.accountId)throw e.status==="account_selected"&&!t.selection&&!t.confirmed&&!t.nativeStarted&&!t.proof&&!t.token?(this.wrongAccountRequestId=t.requestId,E("recovery_account_mismatch")):E("binding");return this.wrongAccountRequestId=null,i}canAbandonWrongAccount(){let e=this.state;return this.isCurrent()&&e.recoveryFor!==void 0&&this.wrongAccountRequestId===e.requestId&&!e.selection&&!e.confirmed&&!e.nativeStarted&&!e.proof&&!e.token&&!e.consentRequest}exchange(){return this.exclusive(async()=>{if(this.state.token)return this.view();let{status:e,value:t}=await this.json(`/v1/pairing-requests/${this.state.requestId}/exchange`,!0);if(t.status==="pending"){if(Me(t,"status"),e!==202||this.state.selection&&!this.state.renewal)throw E("response");return this.view()}let i=`status,request_id,account_id,connector_id,device_id,installation_id,kind,challenge,approval_mode,app_id,app_origin,expires_at${Vl(t)}${this.recoveryTargetKeys()}`;if(t.status==="account_selected"||t.status==="awaiting_approval"){if(Me(t,i),e!==202||t.status==="awaiting_approval"&&!this.state.proof)throw E("response");let v=this.selected(t);return JSON.stringify(v)!==JSON.stringify(this.state.selection)&&await this.save({...this.state,selection:v}),this.view()}let o=Object.hasOwn(t,"collection_ids")||Object.hasOwn(t,"create_collections"),s=Object.hasOwn(t,"selected_collection_id")||Object.hasOwn(t,"created_collection_ids"),r=Object.hasOwn(t,"native_selection"),a=Object.hasOwn(t,"private_device_collection_ids");if(Me(t,`${i},connector,token,registration${o?",collection_ids,create_collections":""}${a?",private_device_collection_ids":""}${s?",selected_collection_id,created_collection_ids":""}${r?",native_selection":""}${m_(t)}`),e!==200||t.status!=="paired"||!this.state.confirmed||!this.state.proof)throw E("response");let c=this.selected(t),l=Me(t.connector,"id,name"),p=Me(t.registration,"device_id,sign_pk,kem_pk,noise_pk");if(l.id!==c.connectorId||l.name!==this.options.appName||p.device_id!==this.state.deviceId||p.sign_pk!==this.state.proof.sign_pk||p.kem_pk!==this.state.proof.kem_pk||p.noise_pk!==this.state.proof.noise_pk)throw E("binding");let d=o?n.collectionIds(t.collection_ids):[],u=a?n.collectionIds(t.private_device_collection_ids):[];if(u.length&&(!o||this.state.requestedPrivateDevice!==!0||u.some(v=>d.includes(v))))throw E("response");let f=n.collectionIds([...d,...u]),h=o?t.create_collections:!1;if(typeof h!="boolean"||h&&!this.state.requestedCreateCollections)throw E("response");let m=s?this.collectionSelection(t,f,this.state.requestId):void 0,w=r?this.parseNativeSelection(t.native_selection,this.state.requestId):void 0;if(r&&(!o||s||h||f.length!==0||t.timer_consent===!0))throw E("response");if(this.state.recoveryFor&&w&&w.collectionId!==this.state.recoveryFor.collectionId||this.state.recoveryFor&&!w&&(h||!n.recovered(this.state.recoveryFor.collectionId,f,u,m)))throw E("binding");if(t.timer_consent===!0&&!m)throw E("response");let b=!m&&u.length>0,g=d_(t,this.state.requestId,f,c.portalConfirmed===!0,m?.selectedCollectionId),y=gn(t.token,/^idev_[A-Za-z0-9_-]{43}$/);return await this.save({...this.state,selection:c,token:y,collectionIds:f,createCollections:h,privateDeviceCollectionIds:u.length?u:void 0,nativeSelection:w,...w||b?{collectionSelection:void 0}:m?{collectionSelection:m}:{},...g?{timerConsent:g}:{}}),this.view()})}static recovered(e,t,i,o){return t.length!==1||t[0]!==e?!1:i.length?i.length===1&&i[0]===e&&o===void 0:o?.selectedCollectionId===e&&o.createdCollectionIds.length===0}parseNativeSelection(e,t){let i=Me(e,"authorization_request_id,collection_id"),o=this.state.nativeAuthorization;if(!o||o.requestId!==t||_e(i.authorization_request_id)!==o.authorizationId)throw E("binding");return Object.freeze({requestId:t,authorizationRequestId:o.authorizationId,collectionId:_e(i.collection_id)})}pendingNativeSelection(){return this.check(),this.state.nativeSelection??null}nativeAuthorizationContext(e){this.check(),this.owned(e);let t=this.state,i=t.consentRequest&&!t.consentRequest.completed?t.consentRequest:null,o=i?.challenge??t.selection?.challenge,s=i?i.portalConfirmed:t.selection?.portalConfirmed;if(!t.proof||!t.confirmed||!s||!o||t.token&&!i)return null;let r=i?.requestId??t.requestId,a=t.nativeAuthorization;return Object.freeze({requestId:r,accountId:t.selection.accountId,appId:t.appId,challenge:o,...a?.requestId===r?{authorizationId:a.authorizationId}:{}})}attachNativeAuthorization(e,t,i){let o=Object.freeze({...t}),s=Object.freeze({...i}),r=e.isCurrent;return this.exclusive(async()=>{this.owned(e);let a=this.nativeAuthorizationContext(e);if(!a||e.isCurrent!==r||a.requestId!==o.requestId||a.challenge!==o.challenge||a.accountId!==o.accountId||s.applicationId!==a.appId||!/^[0-9a-f]{64}$/.test(s.manifestDigest)||(_e(s.authorizationId),a.authorizationId&&a.authorizationId!==s.authorizationId))throw E("binding");await this.save({...this.state,nativeAuthorization:{...s,requestId:a.requestId}});let c=a.requestId===this.state.requestId?this.state.secret:this.state.consentRequest.secret,{status:l,value:p}=await this.json(`/v1/pairing-requests/${a.requestId}/native-authorization`,!1,{authorization_request_id:s.authorizationId},{bearer:c});if(this.owned(e),e.isCurrent!==r)throw E("fenced");if(Me(p,"request_id,authorization_request_id,account_id"),l!==200||p.request_id!==a.requestId||p.authorization_request_id!==s.authorizationId||p.account_id!==a.accountId)throw E("binding")})}completeNativeAuthorization(e,t){let i=this.consentGuard(e);return this.exclusive(async()=>{i();let o=this.state,s=o.nativeSelection,r=o.nativeAuthorization;if(!this.nativeAcknowledged||!s||!r)throw E("binding");let a=i_(t,s,o.selection.accountId,o.appId,o.origin,r.manifestDigest);await this.save({...o,nativeGrants:[...(o.nativeGrants??[]).filter(c=>c.collection_id!==s.collectionId),a]}),i()})}abandonNativeSelection(e){let t=e.isCurrent;return this.exclusive(async()=>{this.owned(e);let i=this.state,o=i.nativeSelection;if(!o||i.nativeGrants?.some(c=>c.authorization_request_id===o.authorizationRequestId&&c.collection_id===o.collectionId))return!1;if(i.recoveryFor)throw E("recovery_required");let{nativeSelection:s,nativeAuthorization:r,...a}=i;if(await this.save(a),this.owned(e),e.isCurrent!==t)throw E("fenced");return!0})}collectionSelection(e,t,i){let o=_e(e.selected_collection_id),s=n.collectionIds(e.created_collection_ids);if(!t.includes(o)||s.some(r=>!t.includes(r)))throw E("response");return Object.freeze({requestId:i,selectedCollectionId:o,createdCollectionIds:Object.freeze(s)})}collectionConsentView(){this.check();let e=this.state.consentRequest;return e?Object.freeze({requestId:e.requestId,verificationUri:`${this.state.cpOrigin}/pair/${e.requestId}`,state:e.completed?"scope_updated":"pending",requestedCreateCollections:e.requestedCreateCollections,addedCollectionIds:Object.freeze([...e.addedCollectionIds]),approvedCreateCollections:e.approvedCreateCollections,...e.requestedPrivateDevice===!0?{requestedPrivateDevice:!0}:{},accountEmail:e.accountEmail??null,...e.accountProvider?{accountProvider:e.accountProvider,accountLogin:e.accountLogin}:{},accountSelectionConfirmed:e.portalConfirmed===!0}):null}consentGuard(e){let t=e.isCurrent;return()=>{if(this.check(),this.owned(e),this.receipt(),e.isCurrent!==t)throw E("fenced")}}async consentWindow(e,t){try{return await t()}catch(i){let o=i instanceof et?i.server?.code:null;if((o==="installation_pairing_denied"||o==="installation_pairing_expired")&&i instanceof et&&i.server?.status===404){let s=this.state.consentRequest;throw s&&!s.completed&&s.requestId===e&&await this.save({...this.state,consentRequest:null}),E(o==="installation_pairing_expired"?"expired":"refused")}throw i}}startCollectionConsent(e,t=!1,i={},o=!1){let s=this.consentGuard(e),r;try{r=I1(i)}catch(c){return Promise.reject(c)}let a=async()=>{if(s(),typeof t!="boolean"||typeof o!="boolean")throw E("binding");let c=this.state.recoveryFor;if(c&&(r!==c.collectionId||t||o&&!(this.state.requestedPrivateDevice===!0&&this.state.privateDeviceCollectionIds?.includes(c.collectionId)===!0)))throw E("binding");let l=this.state.consentRequest;if(!l||l.completed){let b=crypto.getRandomValues(new Uint8Array(32));try{let g=`pair_${btoa(String.fromCharCode(...b)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}`;l={requestId:crypto.randomUUID(),secret:g,requestedCreateCollections:t,challenge:null,completed:!1,addedCollectionIds:[],approvedCreateCollections:!1,...o?{requestedPrivateDevice:!0}:{}},await this.save({...this.state,consentRequest:l}),s()}finally{b.fill(0)}}else if(l.requestedCreateCollections!==t)throw E("binding");let p=this.state,d=p.token,u=l,f;try{f=await this.consentWindow(u.requestId,()=>this.json("/v1/pairing-requests",!1,{installation:{app_id:p.appId,request_id:u.requestId,pairing_secret:u.secret,installation_id:p.installationId,device_id:p.deviceId,kind:p.kind,requested_create_collections:u.requestedCreateCollections,...u.requestedPrivateDevice===!0?{requested_private_device:!0}:{},...p.recoveryFor?{recovery_collection_id:p.recoveryFor.collectionId}:{},reconsent:!0},...r?{collection_hint:r}:{}},{bearer:d}))}catch(b){if(u.requestedPrivateDevice!==!0||!(b instanceof et)||!p_.has(b))throw b;s();let{requestedPrivateDevice:g,...y}=u;return await this.save({...this.state,consentRequest:y}),s(),await a()}s();let{status:h,value:m}=f;Me(m,`pairing_id,pairing_secret,verification_uri,expires_in,installation_device,app_id,app_origin,app_name${this.recoveryTargetKeys()}`),this.assertRecoveryTarget(m);let w=null;if(h!==200&&h!==201||m.pairing_id!==l.requestId||m.pairing_secret!==l.secret||(w=C1(m.verification_uri,`${p.cpOrigin}/pair/${l.requestId}`,r))===null||m.installation_device!==!0||m.app_id!==p.appId||m.app_origin!==p.origin||m.app_name!==this.options.appName||!Number.isSafeInteger(m.expires_in)||m.expires_in<0||m.expires_in>600||d!==this.state.token)throw E("response");return Object.freeze({...this.collectionConsentView(),verificationUri:w})};return this.exclusive(async()=>{let c=this.state.consentRequest,l=c!==null&&!c.completed;try{return await a()}catch(p){if(l&&this.state.consentRequest===null&&p instanceof et&&(p.reason==="refused"||p.reason==="expired"))return await a();throw p}})}exchangeCollectionConsent(e){let t=this.consentGuard(e);return this.exclusive(async()=>{t();let i=this.state.consentRequest,o=this.state;if(!i)throw E("binding");if(i.completed)return this.collectionConsentView();let{status:s,value:r}=await this.consentWindow(i.requestId,()=>this.json(`/v1/pairing-requests/${i.requestId}/exchange`,!1,void 0,{bearer:i.secret}));t();let a=Vl(r),c=`status,request_id,account_id,connector_id,device_id,installation_id,kind,challenge,approval_mode,app_id,app_origin,expires_at${a}${this.recoveryTargetKeys()}`,l=r.status==="scope_updated",p=l&&(Object.hasOwn(r,"selected_collection_id")||Object.hasOwn(r,"created_collection_ids")),d=l&&Object.hasOwn(r,"native_selection"),u=l?Object.hasOwn(r,"added_private_device_collection_ids")?"added_private_device_collection_ids":Object.hasOwn(r,"private_device_collection_ids")?"private_device_collection_ids":null:null;if(Me(r,`${c}${l?",added_collection_ids,approved_create_collections":""}${u?`,${u}`:""}${p?",selected_collection_id,created_collection_ids":""}${d?",native_selection":""}${l?m_(r):""}`),this.assertRecoveryTarget(r),!l&&(s!==202||r.status!=="awaiting_approval")||l&&s!==200||r.request_id!==i.requestId||r.account_id!==o.selection.accountId||r.connector_id!==o.selection.connectorId||r.device_id!==o.deviceId||r.installation_id!==o.installationId||r.kind!==o.kind||r.app_id!==o.appId||r.app_origin!==o.origin||r.approval_mode!==o.selection.approvalMode||!Number.isSafeInteger(r.expires_at)||r.expires_at<0)throw E("binding");let f=Mm(r);if(i.portalConfirmed&&!a)throw E("response");x1(i,f);let h=gn(r.challenge,/^[0-9a-f]{64}$/);if(i.challenge!==null&&i.challenge!==h)throw E("binding");if(!l)return(i.challenge===null||a&&!i.portalConfirmed)&&await this.save({...o,consentRequest:{...i,...f,challenge:h}}),t(),this.collectionConsentView();let m=n.collectionIds(r.added_collection_ids),w=u?n.collectionIds(r[u]):[];if(w.length&&(i.requestedPrivateDevice!==!0||w.some(P=>m.includes(P)||o.collectionIds.includes(P)&&!o.privateDeviceCollectionIds?.includes(P)))||m.some(P=>o.privateDeviceCollectionIds?.includes(P)))throw E("response");let b=n.collectionIds([...m,...w]),g=[...new Set([...o.privateDeviceCollectionIds??[],...w])];if(typeof r.approved_create_collections!="boolean"||r.approved_create_collections&&!i.requestedCreateCollections)throw E("response");let y=n.collectionIds([...new Set([...o.collectionIds,...b])]),v=p?this.collectionSelection(r,y,i.requestId):void 0,_=d?this.parseNativeSelection(r.native_selection,i.requestId):void 0;if(d&&(p||b.length!==0||r.approved_create_collections!==!1||r.timer_consent===!0)||r.timer_consent===!0&&!v)throw E("response");let k=v?[...new Set([...b,v.selectedCollectionId])]:b,S=d_(r,i.requestId,k,f.portalConfirmed===!0,v?.selectedCollectionId),x=_||!v&&w.length>0?void 0:v??o.collectionSelection;if(o.recoveryFor&&(d||r.approved_create_collections||!n.recovered(o.recoveryFor.collectionId,y,g,x)))throw E("binding");return await this.save({...o,collectionIds:y,privateDeviceCollectionIds:g.length?g:void 0,nativeSelection:_,collectionSelection:x,...S?{timerConsent:S}:{},createCollections:o.createCollections||r.approved_create_collections,consentRequest:{...i,...f,challenge:h,completed:!0,addedCollectionIds:b,approvedCreateCollections:r.approved_create_collections}}),t(),this.collectionConsentView()})}keptCollections(){return this.state.collectionListing===void 0?null:Object.freeze(f_(this.state.collectionListing).filter(e=>this.state.collectionIds.includes(e.collectionId)&&this.modeConsented(e)).map(e=>Object.freeze({...e,fileActions:Object.freeze([])})))}cachedApprovedCollections(e){this.consentGuard(e)();try{return this.keptCollections()}catch{return null}}listApprovedCollections(e){let t=this.consentGuard(e);return this.exclusive(async()=>{t();let i,o=this.options.freshRequestedPrivateDevice===!0&&(this.state.privateDeviceCollectionIds?.length??0)>0,s="/v1/next/collections?include=file_actions",r=f=>this.json(f,!1,void 0,{bearer:this.state.token,get:!0});try{i=await r(o?`${s},mode`:s),o&&i.status===200&&Cj(i.value)&&(t(),i=await r(s))}catch(f){if(t(),f instanceof et&&f.reason==="unavailable"&&!f.server&&!c_.has(f)&&this.state.collectionListing!==void 0)return this.keptCollections();if(f instanceof et&&(f.server||c_.has(f))&&this.state.collectionListing!==void 0){let h={...this.state};delete h.collectionListing,await this.save(h),t()}throw f}t();let{status:a,value:c}=i;if(Me(c,"collections"),a!==200)throw E("response");let l=Object.freeze(f_(c.collections).filter(f=>this.modeConsented(f))),p=c.collections.filter(f=>this.state.collectionIds.includes(f.collection_id)).map(f=>{let h={...f};return delete h.file_actions,h}),d={...this.state};delete d.collectionListing;let u={...d,collectionListing:p};return await this.save(new TextEncoder().encode(JSON.stringify(u)).length<=128*1024?u:d),t(),l})}collectionRecoveries(){return this.check(),Object.freeze({...this.retainedRecoveriesForAccount(),...this.state.collectionRecoveries})}scopedInstallationReferences(){this.check();let e=[];for(let[i,o]of Object.entries(this.state.retainedCollectionRecoveries??{}))for(let[s,r]of Object.entries(o))e.push({accountId:i,collectionId:s,reference:r});let t=this.state.selection?.accountId;if(t)for(let[i,o]of Object.entries(this.state.collectionRecoveries??{}))o!==null&&e.push({accountId:t,collectionId:i,reference:o});return e}retainedRecoveriesForAccount(){let{token:e,selection:t,retainedCollectionRecoveries:i}=this.state;return e&&t?i?.[t.accountId]:void 0}replaceRetainedCollectionInstallation(e,t,i){let o=this.consentGuard(e);return this.exclusive(async()=>{o(),_e(t),_e(i);let s=this.retainedRecoveriesForAccount();if(!s?.[t])return null;if(s[t]!==i)throw E("fenced");let r=crypto.randomUUID();return await this.saveWithRecoveryMetadata({...this.state,retainedCollectionRecoveries:{...this.state.retainedCollectionRecoveries,[e.scope.account]:{...s,[t]:r}}}),o(),r})}retireCollectionScope(e,t,i=null){let o=this.consentGuard(e);return this.exclusive(async()=>{if(o(),_e(t),!(this.state.collectionIds.includes(t)||this.state.nativeGrants?.some(s=>s.collection_id===t)))throw E("binding");if(i!==null){if(_e(i),this.state.collectionRecoveries?.[t]!==i)throw E("fenced")}else if(Object.hasOwn(this.state.collectionRecoveries??{},t))return;await this.saveRecovery(t,null),o()})}freshCollectionInstallation(e,t){let i=this.consentGuard(e);return this.exclusive(async()=>{if(i(),_e(t),!Object.hasOwn(this.state.collectionRecoveries??{},t))throw E("binding");let o=this.state.collectionRecoveries[t];if(o!==null)return o;if(this.scopedInstallationReferences().length>=h_)throw E("recovery_required");let s=crypto.randomUUID();return await this.saveRecovery(t,s),i(),s})}saveRecovery(e,t){return this.saveWithRecoveryMetadata({...this.state,collectionRecoveries:{...this.state.collectionRecoveries,[e]:t}})}async saveWithRecoveryMetadata(e){new TextEncoder().encode(JSON.stringify(e)).length>128*1024&&delete e.collectionListing,await this.save(e)}startFileAccess(e,t,i,o){let s=this.consentGuard(e),r;try{if(_e(t),r=y_([...i],Lm,!1),r.length!==i.length)throw E("binding")}catch{return Promise.reject(E("binding"))}return this.exclusive(async()=>{s();let a=crypto.getRandomValues(new Uint8Array(32));try{let c=crypto.randomUUID(),l=`pair_${btoa(String.fromCharCode(...a)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}`,p=this.state,d=p.token,{status:u,value:f}=await this.json("/v1/pairing-requests",!1,{installation:{app_id:p.appId,request_id:c,pairing_secret:l,installation_id:p.installationId,device_id:p.deviceId,kind:p.kind,requested_create_collections:!1,reconsent:!0,file_access:{collection_id:t,actions:[...r],reason:o}}},{bearer:d});s(),Me(f,"pairing_id,pairing_secret,verification_uri,expires_in,installation_device,app_id,app_origin,app_name");let h=`${p.cpOrigin}/pair/${c}`;if(u!==200&&u!==201||f.pairing_id!==c||f.pairing_secret!==l||f.verification_uri!==h||f.installation_device!==!0||f.app_id!==p.appId||f.app_origin!==p.origin||f.app_name!==this.options.appName||!Number.isSafeInteger(f.expires_in)||f.expires_in<0||f.expires_in>600||d!==this.state.token)throw E("response");return Object.freeze({requestId:c,secret:l,collectionId:t,actions:r,verificationUri:h,expiresAt:Date.now()+f.expires_in*1e3})}finally{a.fill(0)}})}exchangeFileAccess(e,t){let i=this.consentGuard(e);return this.exclusive(async()=>{i();let o=this.state,{status:s,value:r}=await this.json(`/v1/pairing-requests/${t.requestId}/exchange`,!1,void 0,{bearer:t.secret});if(i(),r.status==="pending"){if(Me(r,"status"),s!==202)throw E("response");return Object.freeze({state:"pending"})}if(r.status==="account_selected"||r.status==="awaiting_approval"){if(Me(r,`status,request_id,account_id,connector_id,device_id,installation_id,kind,challenge,approval_mode,app_id,app_origin,expires_at${Vl(r)}`),s!==202||r.request_id!==t.requestId||r.account_id!==o.selection?.accountId||r.installation_id!==o.installationId||r.device_id!==o.deviceId||r.app_id!==o.appId)throw E("binding");return Object.freeze({state:"pending"})}if(r.status==="declined"){if(Me(r,"status,request_id"),s!==200||r.request_id!==t.requestId)throw E("response");return Object.freeze({state:"declined"})}if(Me(r,"status,request_id,collection_id,file_actions"),s!==200||r.status!=="file_access_updated"||r.request_id!==t.requestId||r.collection_id!==t.collectionId)throw E("response");return Object.freeze({state:"granted",actions:y_(r.file_actions,t.actions,!1)})})}renameApprovedCollection(e,t,i){let o;try{_e(t),o=li(i)}catch{return Promise.reject(E("binding"))}let s=this.consentGuard(e);return this.exclusive(async()=>{if(s(),!this.state.collectionIds.includes(t))throw E("refused");let{status:r,value:a}=await this.json(`/v1/next/collections/${t}/name`,!1,{display_name:o},{bearer:this.state.token,patch:!0});s();let c=Me(a,"collection_id,display_name");if(r!==200||c.collection_id!==t||c.display_name!==o)throw E("response");return Object.freeze({collectionId:t,displayName:o})})}deleteApprovedCollection(e,t,i){let o;try{_e(t),o=li(i)}catch{return Promise.reject(E("binding"))}let s=this.consentGuard(e);return this.exclusive(async()=>{if(s(),!this.state.collectionIds.includes(t))throw E("refused");let{status:r,value:a}=await this.json(`/v1/next/collections/${t}`,!1,{confirm_name:o},{bearer:this.state.token,delete:!0});s();let c=Me(a,"collection_id,deleted");if(r!==200||c.collection_id!==t||c.deleted!==!0)throw E("response");return Object.freeze({collectionId:t,deleted:!0})})}signOutInstallation(){return this.exclusive(async()=>{let e=this.state.token;if(!e)throw E("binding");try{let{status:t,value:i}=await this.json("/v1/next/installation",!1,void 0,{bearer:e,delete:!0});if(t!==200||i.ok!==!0||i.revoked!==!0||!Number.isSafeInteger(i.collections)||i.collections<0||i.fence!=="closed"&&i.fence!=="committed_with_degraded_fence")throw E("response");return"revoked"}catch(t){if(t instanceof et&&t.server?.status===401&&t.server.code==="invalid_connector")return"already_signed_out";throw t}})}requestSent(){return this.check(),!this.state.token&&this.state.requestSent===this.state.requestId}forgetSentRequest(){return this.exclusive(async()=>{if(this.state.token||this.state.requestSent===void 0)return;let{requestSent:e,...t}=this.state;await this.save(t)})}hasWebPushChannel(){return this.check(),this.state.timerChannel?.kind==="web_push"}confirmPortalSelectedAccount(){return this.exclusive(async()=>{let e=this.state.selection;if(!e?.portalConfirmed)throw E("account_confirmation_required");if(this.state.confirmed||await this.save({...this.state,confirmed:!0}),this.check(),this.state.selection!==e)throw E("binding");return this.view()})}confirmSelectedAccount(e){return this.exclusive(async()=>{if(!this.state.selection||e!==this.state.selection.accountId)throw E("binding");return this.state.confirmed||await this.save({...this.state,confirmed:!0}),this.view()})}confirmedSelection(){if(this.check(),!this.state.confirmed||!this.state.selection)throw E("account_confirmation_required");let e=this.state,t=e.selection;return Object.freeze({accountId:t.accountId,connectorId:t.connectorId,installationId:e.installationId,deviceId:e.deviceId,kind:e.kind,cpOrigin:e.cpOrigin,approvalMode:t.approvalMode,isCurrent:()=>this.isCurrent()})}owned(e){let t=this.confirmedSelection();if(e.isCurrent()!==!0||e.scope.account!==t.accountId||e.scope.installation!==t.installationId)throw E("fenced")}prepareOriginalDevice(e){let t=e.isCurrent,i=()=>{try{return this.check(),this.owned(e),e.isCurrent===t}catch{return!1}};return this.exclusive(async()=>{if(!i())throw E("fenced");let o=this.state.proof?"existing":"fresh";if(this.state.nativeStarted||await this.save({...this.state,nativeStarted:!0}),!i())throw E("fenced");return Object.freeze({mode:o,pin:Object.freeze({...this.confirmedSelection(),isCurrent:i,installationOwned:i})})})}attest(e){let{runtime:t,custody:i,persistence:o,installation:s}=e,r=s.isCurrent,a=()=>{if(this.check(),this.owned(s),s.isCurrent!==r||!t.deviceCustodyCurrent(this.confirmedSelection(),i))throw E("fenced")};return this.exclusive(async()=>{if(a(),!this.state.nativeStarted)throw E("recovery_required");if(this.state.token)return this.view();if(!this.state.proof){await o.pending(new Uint8Array(i.envelope),{signal:this.lifetime.signal}),a();let d=Uint8Array.from(this.state.selection.challenge.match(/../g),f=>parseInt(f,16)),u=null;try{let f=t.signCpEnrol(d);u=f.signature,a(),await this.save({...this.state,proof:n.proof({sign_pk:ci(f.signPublicKey),kem_pk:ci(f.kemPublicKey),noise_pk:ci(f.noisePublicKey),sig:ci(u)})}),a()}finally{d.fill(0),u?.fill(0)}}let c=this.state.proof;if(c.sign_pk!==ci(i.signPublicKey)||c.kem_pk!==ci(i.kemPublicKey)||c.noise_pk!==ci(i.noisePublicKey))throw E("binding");let{status:l,value:p}=await this.json(`/v1/pairing-requests/${this.state.requestId}/attest`,!0,c);if(a(),Me(p,"ok"),l!==200||p.ok!==!0)throw E("response");return this.view()})}receipt(){let e=this.state,t=e.proof;if(this.check(),!e.token||!t||!e.selection)throw E("binding");let i=o=>Uint8Array.from(o.match(/../g),s=>parseInt(s,16));return Object.freeze({connectorId:e.selection.connectorId,deviceId:e.deviceId,installationId:e.installationId,signPublicKey:i(t.sign_pk),kemPublicKey:i(t.kem_pk),noisePublicKey:i(t.noise_pk)})}acknowledge(e){let{runtime:t,custody:i,persistence:o,installation:s}=e,r=s.isCurrent,a=()=>{if(this.check(),this.owned(s),s.isCurrent!==r||!t.deviceCustodyCurrent(this.confirmedSelection(),i))throw E("fenced")};return this.exclusive(async()=>{a();let c=this.receipt();if(ci(c.signPublicKey)!==ci(i.signPublicKey)||ci(c.kemPublicKey)!==ci(i.kemPublicKey)||ci(c.noisePublicKey)!==ci(i.noisePublicKey))throw E("binding");return await o.registered(c,{signal:this.lifetime.signal}),a(),t.acknowledgeDeviceRegistration(c),a(),this.nativeAcknowledged=!0,c})}originalTimerChannel(e){if(this.check(),this.receipt(),!this.state.timerConsent?.approved||!this.state.timerConsent.grants.some(i=>i.grantId===e))throw E("fenced");let t=this.state.timerChannel;return t?.grantId===e?t:null}retainTimerChannel(e,t){return this.exclusive(async()=>{if(this.originalTimerChannel(e),t!==null&&u_(t).grantId!==e)throw E("binding");await this.save({...this.state,timerChannel:t===null?void 0:u_(t)}),this.originalTimerChannel(e)})}session(e){return this.receipt(),this.confirmedHostSession(e,this.state.environment)}confirmedHostSession(e,t){let i=this.confirmedSelection();if(t!==this.state.environment)throw E("binding");let o=new URL(e);if(o.origin!==e||o.protocol!=="https:"&&!!1||o.username||o.password)throw E("binding");return Object.freeze({...i,logOrigin:e,timerConsent:()=>(this.check(),this.state.timerConsent??null),connectorBearer:async({signal:s})=>{if(this.check(),s.aborted||!this.state.token)throw E("fenced");return this.state.token}})}async close(){this.closed||(this.closed=!0,this.lifetime.abort(),this.parent.removeEventListener("abort",this.onAbort),this.state.secret="",this.state.token=null,this.state.consentRequest&&(this.state.consentRequest.secret=""),this.state.renewal&&(this.state.renewal.secret=""),this.state.renewal=null),await this.store.close()}}});function b_(n){return/^[0-9a-f]{64}$/.test(n)?Uint8Array.from(n.match(/../g).map(e=>parseInt(e,16))):null}function R1(n){if(!(n instanceof Map))return!1;let e=n.get(3);return e instanceof Map?e.get(0)==="unauthenticated"&&(e.get(1)==="nonce"||e.get(1)==="replay"):!1}var Rj,jm,O1=C(()=>{"use strict";Rj="x-mdbase-next-nonce";jm=class{constructor(e=Date.now){this.now=e}now;spares=[];take(){for(let e=this.spares.pop();e;e=this.spares.pop()){let t=this.now()-e.at;if(t>=0&&t<4e4)return e.nonce;e.nonce.fill(0)}return null}keep(e){let t=b_(e.get(Rj)??"");if(t)for(this.spares.push({nonce:t,at:this.now()});this.spares.length>6;)this.spares.shift().nonce.fill(0)}}});function Kl(n){if((typeof n!="number"||!Number.isSafeInteger(n))&&typeof n!="bigint")throw he("shape");let e=BigInt(n);if(e<0n||e>(1n<<64n)-1n)throw he("shape");return e}function Nm(n,e){let t=Kl(n);if(t>BigInt(e))throw he("shape");return Number(t)}function Gs(n){if(!(n instanceof Map))throw he("shape");return n}function Dm(n){let e=[];for(let[t,i]of n){if(typeof t!="number"||!Number.isSafeInteger(t)||t<0)throw he("shape");e.push([t,i])}return new Map(e.sort(([t],[i])=>t-i))}function Ys(n,e){if(!(n instanceof Uint8Array)||e!==void 0&&n.length!==e)throw he("shape");return n}function zm(n,e){return n.length===e.length&&n.every((t,i)=>t===e[i])}function E1(n){return[...n].map(e=>e.toString(16).padStart(2,"0")).join("")}function q1(n){return btoa(String.fromCharCode(...n))}function v_(n,e){let t;try{t=new URL(n)}catch{throw he("binding")}if(t.username||t.password||t.pathname!=="/"||t.search||t.hash||t.protocol!=="https:"&&!(e&&Qe(n)))throw he("binding");return t.origin}function T1(n,e){let t=n.headers.get("content-length");return t!==null&&/^(0|[1-9][0-9]*)$/.test(t)&&Number(t)>e}function Tj(n,e,t,i,o,s,r){let a=Um.encode("mdbase/v1/ls-http"),c=Um.encode(t),l=Um.encode("/v1/rpc"),p=Um.encode(o),d=Ze(p),u=Ze(s);p.fill(0);let f=new Uint8Array(1+a.length+c.length+1+l.length+1+16+96),h=0;for(let w of[Uint8Array.of(a.length),a,c,Uint8Array.of(0),l,Uint8Array.of(0),N(i),d,u,r])f.set(w,h),h+=w.length;let m=Ze(f);return f.fill(0),Object.freeze({endpoint:n,originalCallId:e,frame:s.slice(),token:o,method:t,path:"/v1/rpc",collection:i,nonce:r.slice(),bodyHash:u,tokenHash:d,digest:m})}var w_,Cd,Oj,Ej,qj,Um,En,he,Wl,Rd=C(()=>{"use strict";St();gr();Je();ve();ri();O1();w_=16*1024*1024,Cd=9*1024*1024,Oj=new Set(["append","read","head","subscribe","unsubscribe","put_object","get_object","has_objects","put_snapshot","get_snapshot","endorse_snapshot","stream_join","stream_leave","stream_send"]),Ej=new Set(["stream_join","stream_leave","stream_send"]),qj=new Set(["host","content-length","transfer-encoding","connection","keep-alive","upgrade","te","trailer","expect","range","cookie","authorization","proxy-authorization","origin","referer","accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","date","dnt","permissions-policy","set-cookie","via"]),Um=new TextEncoder,En=class extends Error{constructor(t,i){super(`app log transport: ${t}`);this.reason=t;this.server=i;this.name="AppHttpLogError"}reason;server},he=n=>new En(n);Wl=class{constructor(e,t={}){this.authority=e;try{if(this.endpointId=Kl(e.endpoint),this.endpoint=this.endpointId,this.collection=e.collection,this.collectionBytes=N(this.collection),this.loopback=t.allowLoopbackHttp===!0,this.base=v_(e.origin,this.loopback),!Array.isArray(e.directOrigins)||e.directOrigins.length>32)throw he("binding");this.approved=new Set([this.base,...e.directOrigins.map(i=>v_(i,this.loopback))]),this.fetchImpl=t.fetch??globalThis.fetch,this.now=t.now??Date.now,this.spares=new jm(this.now)}catch{throw he("binding")}}authority;endpoint;collection;endpointId;collectionBytes;base;approved;fetchImpl;now;loopback;commitId=(1n<<64n)-1n;spares;responseId=0;receiving=new Map;streams=null;setStreamRoute(e){this.streams=e}responseProgress(){return[...this.receiving].map(([e,t])=>({id:e,bytes:t}))}isCurrent(){try{return this.authority.isCurrent()===!0&&Kl(this.authority.endpoint)===this.endpointId&&this.authority.collection===this.collection&&v_(this.authority.origin,this.loopback)===this.base}catch{return!1}}check(e){if(e.aborted||!this.isCurrent())throw he("fenced")}request(e){if(e.length>w_)throw he("shape");let t=Gs(we(e));if(t.get(0)!==0||typeof t.get(2)!="string")throw he("shape");let i=t.get(2),o=Gs(t.get(3));if(!Oj.has(i)||!zm(Ys(o.get(0),16),this.collectionBytes))throw he("shape");return{id:Kl(t.get(1)),method:i,params:o}}response(e,t){let i=Gs(we(e));if(i.get(0)!==1||Kl(i.get(1))!==t||i.has(2)===i.has(3))throw he("shape");return i}async fetch(e,t,i,o){this.check(i);let s=new AbortController,r=()=>s.abort();i.addEventListener("abort",r,{once:!0});let a=setTimeout(r,o);a.unref?.();try{let c=this.fetchImpl,l=(t.method??"GET")==="GET"?"no-store":"default",p=await c(e,{...t,signal:s.signal,redirect:"error",credentials:"omit",cache:l,referrerPolicy:"no-referrer"});if(!this.isCurrent()||i.aborted)throw p.body?.cancel().catch(()=>{}),he("fenced");return this.withCleanup(p,()=>{clearTimeout(a),i.removeEventListener("abort",r)})}catch{throw clearTimeout(a),i.removeEventListener("abort",r),he(i.aborted||!this.isCurrent()?"fenced":"unavailable")}}cleanups=new WeakMap;withCleanup(e,t){return this.cleanups.set(e,t),e}release(e){this.cleanups.get(e)?.(),this.cleanups.delete(e)}async read(e,t,i,o){let s=new Uint8Array(Math.min(1024,t)),r=0,a=null;try{if(this.check(i),T1(e,t))throw he("integrity");if(!e.body)return s.subarray(0,0);for(a=e.body.getReader();;){let{done:c,value:l}=await a.read();try{if(this.check(i),c)break;if(r+l.length>t)throw he("integrity");if(r+l.length>s.length){let p=new Uint8Array(Math.min(t,Math.max(s.length*2,r+l.length)));p.set(s.subarray(0,r)),s.fill(0),s=p}s.set(l,r),r+=l.length,o(l.length)}finally{l?.fill(0)}}return s.subarray(0,r)}catch(c){throw s.fill(0),(a?.cancel()??e.body?.cancel())?.catch(()=>{}),c}finally{a?.releaseLock(),this.release(e)}}async refusal(e,t,i){let o;try{let r=await this.read(e,8192,t,i);try{o=$o(r)}finally{r.fill(0)}}catch(r){if(r instanceof En&&r.reason==="fenced")return r;o=void 0}let s=vi(e.status,o,e.headers);return new En(Rt(s)??"unavailable",s)}async freshNonce(e,t){let i=await this.fetch(`${this.base}/v1/nonce`,{},e,15e3);if(!i.ok)throw await this.refusal(i,e,t);let o=await this.read(i,128,e,t);try{this.check(e);let s=b_(new TextDecoder("utf-8",{fatal:!0}).decode(o).trim());if(!s)throw he("shape");return s}finally{o.fill(0)}}async rpc(e,t,i,o,s,r=i,a=!0){this.check(o);let c=await this.authority.accessToken({signal:o});if(this.check(o),typeof c!="string"||!c||c.length>16*1024||/[\r\n]/.test(c))throw he("shape");let l=a?this.spares.take():null,p=l??await this.freshNonce(o,s);this.check(o);let d=Tj(this.endpoint,r,t,this.collection,c,e,p);p.fill(0);let u=null;try{if(u=await this.authority.signLogProof(d,{signal:o}),this.check(o),!(u instanceof Uint8Array)||u.length!==64)throw he("shape");let f=await this.fetch(`${this.base}/v1/rpc`,{method:"POST",headers:{authorization:`Bearer ${c}`,"content-type":"application/cbor","x-mdbase-nonce":E1(d.nonce),"x-mdbase-sig":E1(u)},body:e},o,15e3);if(this.spares.keep(f.headers),f.status===401&&this.authority.invalidateToken?.(c),!f.ok)throw await this.refusal(f,o,s);let h=await this.read(f,t==="append"?64*1024:w_,o,s),m;try{this.check(o),m=R1(this.response(h,i))}catch(w){throw h.fill(0),w}return l&&m?(h.fill(0),await this.rpc(e,t,i,o,s,r,!1)):h}finally{u?.fill(0),d.frame.fill(0),d.nonce.fill(0),d.bodyHash.fill(0),d.tokenHash.fill(0),d.digest.fill(0)}}direct(e,t){let i=Gs(e),o=i.get(0),s=Gs(i.get(1)),r=i.get(2);if(typeof o!="string"||o.length>16*1024||typeof r!="number"||!Number.isSafeInteger(r))throw he("shape");let a;try{a=new URL(o)}catch{throw he("shape")}if(a.username||a.password||a.hash||!this.approved.has(a.origin))throw he("binding");let c=new Headers,l=new Set;if(s.size>32)throw he("shape");for(let[p,d]of s){if(typeof p!="string"||typeof d!="string")throw he("shape");let u=p.toLowerCase();if(!/^[a-z0-9!#$%&'*+.^_`|~-]+$/.test(u)||qj.has(u)||u.startsWith("proxy-")||u.startsWith("sec-")||u.startsWith("x-mdbase-")||u.startsWith("x-http-method")||l.has(u)||d.length>8*1024||/[\r\n]/.test(d))throw he("shape");if(u==="x-amz-checksum-sha256"&&d!==q1(t))throw he("integrity");l.add(u),c.set(u,d)}if(r-this.now()<=5e3)throw he("unavailable");return{url:a.href,headers:c,expires:r}}timeout(e,t){let i=e.expires-this.now();if(i<=5e3)throw he("unavailable");return Math.min(i,3e4+Math.ceil(t/(128*1024))*1e3)}async upload(e,t,i){this.check(i);let o;try{o=await this.fetch(e.url,{method:"PUT",headers:e.headers,body:t},i,this.timeout(e,t.length))}catch(s){if(this.check(i),s instanceof En&&s.reason==="unavailable")return;throw s}try{if(this.check(i),o.ok||o.status===408||o.status===425||o.status===429||o.status>=500)return;throw he("unavailable")}finally{o.body?.cancel().catch(()=>{}),this.release(o)}}async download(e,t,i,o,s){let r=new Uint8Array(t),a=0,c=0;try{for(let l=0;l<32&&c<5;l++){this.check(o);let p=a,d=new Headers(e.headers);p>0&&d.set("range",`bytes=${p}-${t-1}`);let u;try{u=await this.fetch(e.url,{headers:d},o,this.timeout(e,t-p))}catch{this.check(o),c++;continue}let f=null;try{if(this.check(o),[401,403,404,410].includes(u.status))throw he("unavailable");if([408,425,429].includes(u.status)||u.status>=500){c++;continue}if(u.status!==(p===0?200:206)||T1(u,t-p)||(p>0?u.headers.get("content-range")!==`bytes ${p}-${t-1}/${t}`:u.headers.has("content-range"))||u.headers.has("content-encoding")&&u.headers.get("content-encoding")!=="identity")throw he("integrity");let h=u.headers.get("x-amz-checksum-sha256");if(h!==null&&h!==q1(i)||!u.body)throw he("integrity");for(f=u.body.getReader();;){let m;try{m=await f.read()}catch{this.check(o);break}try{if(this.check(o),m.done)break;if(m.value.length>t-a)throw he("integrity");r.set(m.value,a),a+=m.value.length,s(m.value.length)}finally{m.value?.fill(0)}}}finally{(f?.cancel()??u.body?.cancel())?.catch(()=>{}),f?.releaseLock(),this.release(u)}if(a===t){if(!zm(Ze(r),i))throw he("integrity");return r}c=a>p?0:c+1}throw he("unavailable")}catch(l){throw r.fill(0),l}}async send(e,t){let i=null,o=null,s=null,r=null,a=null,c=++this.responseId,l=0;this.receiving.set(c,l);let p=d=>{l+=d,this.receiving.set(c,l)};try{if(this.check(t.signal),Kl(e.endpoint)!==this.endpointId||!(e.frame instanceof Uint8Array)||e.frame.length>w_||e.sidecar!==void 0&&(!(e.sidecar instanceof Uint8Array)||e.sidecar.length>Cd))throw he("shape");i=e.frame.slice(),o=e.sidecar?.slice()??null;let d=this.request(i);if(o&&d.method!=="put_object")throw he("shape");if(Ej.has(d.method)){let h=this.streams;if(!h)throw he("no_stream");try{s=await h(i,t)}catch{throw he(t.signal.aborted||!this.isCurrent()?"fenced":"no_stream")}this.check(t.signal),this.response(s,d.id);let m=s;return s=null,m}if(d.method==="put_object"){let h=Nm(d.params.get(3),Cd),m=Ys(d.params.get(4),32),w=d.params.get(5);if(h===0||o!==null&&(w!==void 0||o.length<=1024*1024)||o===null&&h>1024*1024)throw he("shape");let b=o??Ys(w);if(b.length!==h||!zm(Ze(b),m))throw he("integrity")}s=await this.rpc(i,d.method,d.id,t.signal,p),this.check(t.signal);let u=this.response(s,d.id);if(u.has(3)){let h=s;return s=null,h}if(d.method==="put_object"){let h=Gs(u.get(2)),m=h.get(0);if(m===0||m===2){if(h.has(1))throw he("shape");let _=s;return s=null,_}if(m!==1||!o)throw he("shape");let w=Ys(d.params.get(4),32),b=Ys(d.params.get(1),32);if(await this.upload(this.direct(h.get(1),w),o,t.signal),this.check(t.signal),this.commitId===d.id||this.commitId===0n)throw he("unavailable");let g=this.commitId--;a=fe(new Map([[0,0],[1,g],[2,"commit_object"],[3,new Map([[0,this.collectionBytes],[1,b]])]]));let y=await this.rpc(a,"commit_object",g,t.signal,p,d.id);try{this.check(t.signal);let _=this.response(y,g),k=_.get(2);if(_.has(3)||!(k instanceof Map)||k.size!==1||k.get(0)!==!0)throw he("unavailable")}finally{y.fill(0)}let v=new Map(h);return v.delete(1),v.set(0,0),u.set(2,Dm(v)),fe(Dm(u))}if(d.method==="get_object"){let h=Gs(u.get(2)),m=Nm(h.get(2),Cd),w=Ys(h.get(3),32);if(m===0||h.has(0)===h.has(1))throw he("shape");let b=d.params.get(2),g=0,y=m;if(b!==void 0&&(!Array.isArray(b)||b.length!==2||(g=Nm(b[0],Cd),y=Nm(b[1],Cd),g>m||y>m-g)))throw he("shape");if(h.has(0)){let _=Ys(h.get(0));if(_.length!==y||y===m&&!zm(Ze(_),w))throw he("integrity");let k=s;return s=null,k}r=await this.download(this.direct(h.get(1),w),m,w,t.signal,p),this.check(t.signal);let v=new Map(h);return v.delete(1),v.set(0,r.subarray(g,g+y)),u.set(2,Dm(v)),fe(Dm(u))}let f=s;return s=null,f}catch(d){if(d instanceof En)throw d;if(t.signal.aborted||!this.isCurrent())throw he("fenced");let u=null;try{u=d.server}catch{}let f=rn(u)?Rt(u):null;throw f&&rn(u)?new En(f,u):he("unavailable")}finally{this.receiving.delete(c),i?.fill(0),o?.fill(0),s?.fill(0),r?.fill(0),a?.fill(0)}}}});function M1(n,e){let t;try{t=new URL(n)}catch{throw gt("binding")}if(t.username||t.password||t.pathname!=="/"||t.search||t.hash||t.protocol!=="https:"&&!(e&&Qe(n)))throw gt("binding");return t.origin}function L1(n){if(typeof n=="number"&&!Number.isSafeInteger(n))throw gt("binding");let e=BigInt(n);if(e<0n||e>(1n<<64n)-1n)throw gt("binding");return e}function Mj(n){return[...n].map(e=>e.toString(16).padStart(2,"0")).join("")}function Lj(n){if(!n||typeof n!="object"||Array.isArray(n))throw gt("response");return n}var pi,gt,__,Hl,Od=C(()=>{"use strict";St();ve();Rd();ri();pi=class extends Error{constructor(t,i){super(`app CP authority: ${t}`);this.reason=t;this.server=i;this.name="AppCpAuthorityError"}reason;server},gt=n=>new pi(n),__=n=>new pi(Rt(n)??"unavailable",n);Hl=class{constructor(e,t,i={}){this.runtime=e;this.session=t;this.tokenCache=i.tokenCache??null;try{this.endpoint=L1(t.endpoint),this.collection=t.collection,this.connectorId=t.connectorId,this.deviceId=t.deviceId;for(let o of[this.collection,this.connectorId,this.deviceId])if(N(o).every(r=>r===0))throw gt("binding");if(this.rawCpOrigin=t.cpOrigin,this.rawLogOrigin=t.logOrigin,this.cpOrigin=M1(this.rawCpOrigin,i.allowLoopbackHttp===!0),this.origin=M1(this.rawLogOrigin,i.allowLoopbackHttp===!0),this.directOrigins=Object.freeze([...t.directOrigins]),this.now=i.now??Date.now,this.fetchImpl=i.fetch??globalThis.fetch,this.transport=new Wl(this,i),!this.scopeCurrent())throw gt("binding");e.bindCpConnector(t)}catch{throw gt("binding")}}runtime;session;endpoint;collection;origin;directOrigins;cpOrigin;connectorId;deviceId;rawCpOrigin;rawLogOrigin;now;fetchImpl;lifetime=new AbortController;authenticated=!1;token=null;tokenCache;cacheTried=!1;transport;scopeCurrent(){try{return!this.lifetime.signal.aborted&&this.session.isCurrent()===!0&&L1(this.session.endpoint)===this.endpoint&&this.session.collection===this.collection&&this.session.connectorId===this.connectorId&&this.session.deviceId===this.deviceId&&this.session.cpOrigin===this.rawCpOrigin&&this.session.logOrigin===this.rawLogOrigin}catch{return!1}}isCurrent(){return this.authenticated&&this.scopeCurrent()}check(e){if(!this.scopeCurrent())throw this.close(),gt("fenced");if(e.aborted)throw gt("fenced")}logTransport(){if(!this.isCurrent())throw gt("fenced");return this.transport}async signLogProof(e,t){if(this.check(t.signal),!this.authenticated)throw gt("fenced");return this.runtime.signLogHttp(e)}async json(e,t,i,o){this.check(o);let s=new AbortController,r=()=>s.abort();o.addEventListener("abort",r,{once:!0}),this.lifetime.signal.addEventListener("abort",r,{once:!0});let a=setTimeout(r,15e3);a.unref?.();let c=null,l=null,p=new Uint8Array(32*1024),d=0;try{let u=this.fetchImpl;if(c=await u(`${this.cpOrigin}${e}`,{method:"POST",headers:{authorization:`Bearer ${t}`,...i===void 0?{}:{"content-type":"application/json"}},body:i,signal:s.signal,redirect:"error",credentials:"omit",cache:"default",referrerPolicy:"no-referrer"}),this.check(o),s.signal.aborted)throw gt("unavailable");let f=c.headers.get("content-length");if(f!==null&&/^(0|[1-9][0-9]*)$/.test(f)&&Number(f)>p.length)throw s.abort(),c.ok?gt("unavailable"):__(vi(c.status,void 0,c.headers));if(!c.body)throw c.ok?gt("response"):__(vi(c.status,void 0,c.headers));for(l=c.body.getReader();;){let{done:h,value:m}=await l.read();try{if(this.check(o),s.signal.aborted)throw gt("unavailable");if(h)break;if(d+m.length>p.length)throw s.abort(),gt("response");p.set(m,d),d+=m.length}finally{m?.fill(0)}}if(!c.ok)throw __(vi(c.status,$o(p.subarray(0,d)),c.headers));return Lj(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(p.subarray(0,d))))}catch(u){throw this.check(o),u instanceof pi?u:gt("unavailable")}finally{p.fill(0),(l?.cancel()??c?.body?.cancel())?.catch(()=>{}),l?.releaseLock(),clearTimeout(a),o.removeEventListener("abort",r),this.lifetime.signal.removeEventListener("abort",r)}}async accessToken(e){let t=null,i=null;try{if(this.check(e.signal),this.token&&this.token.expires-this.now()>5e3)return this.token.value;if(!this.token&&this.tokenCache&&!this.cacheTried){this.cacheTried=!0;let c=await this.tokenCache.read(this.cacheKey(),this.now());if(this.check(e.signal),c)return this.token={value:c.value,expires:c.expires},this.authenticated=!0,c.value}let o=await this.session.connectorBearer(e);if(this.check(e.signal),typeof o!="string"||!o||o.length>16*1024||/[^\x21-\x7e]/.test(o))throw gt("binding");let s=await this.json("/v1/next/devices/challenge",o,void 0,e.signal);if(this.check(e.signal),typeof s.challenge!="string"||!/^[0-9a-f]{64}$/.test(s.challenge)||typeof s.expires_at!="number"||!Number.isSafeInteger(s.expires_at)||s.expires_at-this.now()<=5e3||(t=Uint8Array.from(s.challenge.match(/../g).map(c=>parseInt(c,16))),i=this.runtime.signCpLogToken(t),this.check(e.signal),!(i instanceof Uint8Array)||i.length!==64))throw gt("response");let r=JSON.stringify({device_id:this.deviceId,challenge:s.challenge,sig:Mj(i),capabilities:["collection_mode_switch_v2"]}),a=await this.json(`/v1/next/collections/${this.collection}/log-token`,o,r,e.signal);if(this.check(e.signal),typeof a.token!="string"||!a.token||a.token.length>16*1024||/[^\x21-\x7e]/.test(a.token)||typeof a.expires_at!="number"||!Number.isSafeInteger(a.expires_at)||a.expires_at-this.now()<=5e3||a.expires_at-this.now()>16*6e4)throw gt("response");return this.token={value:a.token,expires:a.expires_at},this.authenticated=!0,this.tokenCache?.write(this.cacheKey(),this.token).catch(()=>{}),a.token}catch(o){throw o instanceof pi?o:gt(this.scopeCurrent()?"unavailable":"fenced")}finally{t?.fill(0),i?.fill(0)}}cacheKey(){return[this.rawCpOrigin,this.rawLogOrigin,this.connectorId,this.deviceId,this.collection].join(" ")}invalidateToken(e){this.token?.value===e&&(this.token=null,this.tokenCache?.drop(this.cacheKey()).catch(()=>{}))}close(){this.lifetime.signal.aborted||(this.lifetime.abort(),this.token=null,this.authenticated=!1,this.runtime.retireLog())}}});function A_(n,e){if(typeof n!="string"||!n.length||n.length%2||n.length>e*2||!/^[0-9a-f]+$/.test(n))throw Pe("response");return Uint8Array.from(n.match(/../g),t=>parseInt(t,16))}function k_(n){if(!n||typeof n!="object"||Array.isArray(n))throw Pe("response");return n}var qn,Pe,jj,$m,j1,Gl,Ed=C(()=>{"use strict";ve();St();Ws();ri();qn=class extends Error{constructor(t,i=!1,o){super(`app cloud copy bootstrap: ${t}`);this.reason=t;this.retryable=i;this.server=o;this.name="AppCloudCopyBootstrapError"}reason;retryable;server},Pe=(n,e=!1)=>new qn(n,e),jj=new Set([408,429,500,502,503,504]),$m=(n,e)=>n.length===e.length&&n.every((t,i)=>t===e[i]),j1=n=>Array.from(n,e=>e.toString(16).padStart(2,"0")).join("");Gl=class{constructor(e,t,i,o,s={}){this.runtime=e;this.session=t;this.trust=i;this.persistence=o;try{if(this.storageCallbacks=Object.freeze({restore:o.restore,pending:o.pending,completed:o.completed}),this.scope=Object.freeze({accountId:t.accountId,connectorId:t.connectorId,deviceId:t.deviceId,installationId:t.installationId,collection:t.collection,purpose:t.purpose,cpOrigin:t.cpOrigin,logOrigin:t.logOrigin}),this.callbacks=Object.freeze({current:t.isCurrent,owned:t.installationOwned,bearer:t.connectorBearer}),this.local=Cr(i.environment),!1)throw Pe("binding");this.loopback=s.allowLoopbackHttp===!0||this.local;for(let c of[this.scope.accountId,this.scope.connectorId,this.scope.deviceId,this.scope.installationId,this.scope.collection])if(N(c).every(l=>l===0))throw Pe("binding");if(this.origin(this.scope.cpOrigin),this.origin(this.scope.logOrigin),i.schema!=="mdbn-app-trust/release/1"||!(["lab","staging","production"].includes(i.environment)||this.loopback&&i.environment==="test"||this.local)||i.cpOrigin!==this.scope.cpOrigin||i.logOrigin!==this.scope.logOrigin||!/^[0-9a-f]{64}$/.test(i.assetSha256)||i.source.repository!=="mdbase-dev/mdbase-connect"||!/^[0-9a-f]{40}$/.test(i.source.commit)||!i.source.version||i.source.version.length>64||!Array.isArray(i.trustedRoots)||i.trustedRoots.length<1||i.trustedRoots.length>64||!(i.policyPins instanceof Uint8Array)||!i.policyPins.length||i.policyPins.length>65536)throw Pe("binding");this.trustFields=Object.freeze({schema:i.schema,environment:i.environment,assetSha256:i.assetSha256,...i.source}),this.roots=Object.freeze(i.trustedRoots.map(c=>{if(!(c instanceof Uint8Array)||c.length!==32||c.every(l=>l===0))throw Pe("binding");return new Uint8Array(c)})),this.pins=new Uint8Array(i.policyPins);let r=s.displayName,a=r===void 0?void 0:li(r);if(a!==void 0&&this.scope.purpose!=="create"||(this.operation=Object.freeze({...e.registeredDeviceReceipt(),...a===void 0?{}:{displayName:a},accountId:this.scope.accountId,collection:this.scope.collection,purpose:this.scope.purpose,assetSha256:i.assetSha256,cpOrigin:this.scope.cpOrigin,logOrigin:this.scope.logOrigin}),this.request=s.fetch??globalThis.fetch,this.now=s.now??Date.now,!this.current()))throw Pe("binding")}catch{throw e.retireLog(),Pe("binding")}}runtime;session;trust;persistence;attempted=!1;adopted=!1;originalSignal=null;completion=null;lifetime=new AbortController;scope;callbacks;trustFields;roots;pins;operation;storageCallbacks;request;now;loopback;local;origin(e){if(this.local&&!ns(e))throw Pe("binding");let t=new URL(e);if(t.origin!==e||t.username||t.password||t.protocol!=="https:"&&!(this.loopback&&Qe(e)))throw Pe("binding");return t.origin}current(){try{let e=this.session,t=this.trust,i=this.trustFields;return!this.lifetime.signal.aborted&&!this.originalSignal?.aborted&&(this.adopted||this.runtime.cloudCopyCollectionCurrent(e))&&this.persistence.restore===this.storageCallbacks.restore&&this.persistence.pending===this.storageCallbacks.pending&&this.persistence.completed===this.storageCallbacks.completed&&e.isCurrent===this.callbacks.current&&e.installationOwned===this.callbacks.owned&&e.connectorBearer===this.callbacks.bearer&&this.callbacks.current.call(e)===!0&&this.callbacks.owned.call(e)===!0&&Object.entries(this.scope).every(([o,s])=>e[o]===s)&&t.cpOrigin===this.scope.cpOrigin&&t.logOrigin===this.scope.logOrigin&&t.schema===i.schema&&t.environment===i.environment&&t.assetSha256===i.assetSha256&&t.source.repository===i.repository&&t.source.commit===i.commit&&t.source.version===i.version&&t.trustedRoots.length===this.roots.length&&t.trustedRoots.every((o,s)=>$m(o,this.roots[s]))&&$m(t.policyPins,this.pins)}catch{return!1}}check(e){if(e.aborted||!this.current())throw this.close(),Pe("fenced")}operationCopy(e){for(let t of["accountId","connectorId","deviceId","installationId","collection","purpose","cpOrigin","logOrigin","assetSha256","displayName"])if(e[t]!==this.operation[t])throw Pe("response");for(let t of["signPublicKey","kemPublicKey","noisePublicKey"])if(!(e[t]instanceof Uint8Array)||!$m(e[t],this.operation[t]))throw Pe("response");return Object.freeze({...this.operation,signPublicKey:new Uint8Array(this.operation.signPublicKey),kemPublicKey:new Uint8Array(this.operation.kemPublicKey),noisePublicKey:new Uint8Array(this.operation.noisePublicKey)})}copy(e){if(!(e.genesisItem instanceof Uint8Array)||!e.genesisItem.length||e.genesisItem.length>256*1024||!/^sha256:[0-9a-f]{64}$/.test(e.expectedGenesis))throw Pe("response");return Object.freeze({operation:this.operationCopy(e.operation),genesisItem:new Uint8Array(e.genesisItem),expectedGenesis:e.expectedGenesis})}async hash(e,t){let i=new TextEncoder().encode("mdbase/v1/chain"),o=new Uint8Array(1+i.length+e.length);o[0]=i.length,o.set(i,1),o.set(e,1+i.length);let s=new Uint8Array(await crypto.subtle.digest("SHA-256",o));return this.check(t),`sha256:${j1(s)}`}async json(e,t,i,o){this.check(o);let s=new AbortController,r=()=>s.abort(),a=setTimeout(r,15e3);a.unref?.(),o.addEventListener("abort",r,{once:!0}),this.lifetime.signal.addEventListener("abort",r,{once:!0});let c=new Uint8Array(1024*1024),l=0,p=null,d=null;try{let u=this.request;if(p=await u(`${this.scope.cpOrigin}${e}`,{method:"POST",headers:{authorization:`Bearer ${t}`,...i===void 0?{}:{"content-type":"application/json"}},body:i,signal:s.signal,redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer"}),this.check(o),s.signal.aborted)throw Pe("unavailable",!0);if(!p.ok){let h=await this.problem(p,o),m=Rt(h),w=!m&&jj.has(p.status);throw new qn(m??(w?"unavailable":"refused"),w,h)}let f=p.headers.get("content-length");if(f!==null&&/^(0|[1-9][0-9]*)$/.test(f)&&Number(f)>c.length)throw s.abort(),Pe("response");if(!p.body)throw Pe("response");for(d=p.body.getReader();;){let{done:h,value:m}=await d.read();try{if(this.check(o),s.signal.aborted)throw Pe("unavailable",!0);if(h)break;if(l+m.length>c.length)throw s.abort(),Pe("response");c.set(m,l),l+=m.length}finally{m?.fill(0)}}try{return k_(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(c.subarray(0,l))))}catch{throw Pe("response")}}catch(u){throw this.check(o),u instanceof qn?u:Pe("unavailable",!0)}finally{c.fill(0),(d?.cancel()??p?.body?.cancel())?.catch(()=>{}),d?.releaseLock(),clearTimeout(a),o.removeEventListener("abort",r),this.lifetime.signal.removeEventListener("abort",r)}}async problem(e,t){let i=new Uint8Array(8192),o=0,s=e.body?.getReader();try{for(;s;){let{done:r,value:a}=await s.read();try{if(this.check(t),r)break;if(o+a.length>i.length){o=0;break}i.set(a,o),o+=a.length}finally{a?.fill(0)}}}catch{this.check(t),o=0}finally{s?.cancel().catch(()=>{}),s?.releaseLock()}try{return vi(e.status,o?$o(i.subarray(0,o)):void 0,e.headers)}finally{i.fill(0)}}async challenge(e,t){for(let i=0;i<3;i++)try{return await this.json("/v1/next/devices/challenge",e,void 0,t)}catch(o){if(!(o instanceof qn)||o.reason!=="unavailable"||!o.retryable||i===2)throw o;this.check(t),await new Promise((s,r)=>{let a=()=>{clearTimeout(l),t.removeEventListener("abort",c),this.lifetime.signal.removeEventListener("abort",c);try{this.check(t),s()}catch(p){r(p)}},c=()=>a(),l=setTimeout(a,i===0?250:1e3);l.unref?.(),t.addEventListener("abort",c,{once:!0}),this.lifetime.signal.addEventListener("abort",c,{once:!0}),(t.aborted||this.lifetime.signal.aborted)&&a()})}throw Pe("unavailable",!0)}async bootstrap(e){let{signal:t,reconcile:i}=e,o=Object.freeze({signal:t}),s=null,r=null;try{if(this.originalSignal??=t,t!==this.originalSignal||(this.check(t),this.attempted))throw Pe("fenced");this.attempted=!0;let a=await this.storageCallbacks.restore.call(this.persistence,o);if(this.check(t),a.state==="completed"){let w=this.copy(a.metadata);if(await this.hash(w.genesisItem,t)!==w.expectedGenesis)throw Pe("response");return this.completion=this.copy(w),w}if(a.state==="pending"){if(this.operationCopy(a.operation),i!=="explicit-unknown-outcome")throw Pe("outcome_unknown")}else if(a.state!=="none")throw Pe("response");await this.storageCallbacks.pending.call(this.persistence,this.operationCopy(this.operation),o),this.check(t);let c=await this.callbacks.bearer.call(this.session,o);if(this.check(t),typeof c!="string"||!c||c.length>16384||/[^\x21-\x7e]/.test(c))throw Pe("binding");let l=await this.challenge(c,t);if(s=A_(l.challenge,32),s.length!==32||typeof l.expires_at!="number"||!Number.isSafeInteger(l.expires_at)||l.expires_at-this.now()<=5e3||l.expires_at-this.now()>16*6e4)throw Pe("response");let p=this.scope.purpose==="create";if(r=p?this.runtime.signCloudCopyCreate(s):this.runtime.signCloudCopyJoin(s),this.check(t),r.length!==64)throw Pe("response");let d;try{d=await this.json(p?"/v1/next/collections/cloud-copy":`/v1/next/collections/${this.scope.collection}/devices`,c,JSON.stringify({device_id:this.scope.deviceId,capabilities:["collection_mode_switch_v2"],challenge:l.challenge,sig:j1(r),...p?{collection_id:this.scope.collection,...this.operation.displayName===void 0?{}:{display_name:this.operation.displayName}}:{}}),t)}catch(w){throw w instanceof qn&&w.reason==="unavailable"?Pe("outcome_unknown"):w}if(d.collection_id!==this.scope.collection||d.log_url!==this.scope.logOrigin)throw Pe("response");if(p){let w=A_(d.root_public_key,32);if(d.state!=="cloud-copy"||d.owner_account!==this.scope.accountId||!this.roots.some(b=>$m(b,w)))throw Pe("response")}else if(typeof d.enrolled_at!="number"||!Number.isSafeInteger(d.enrolled_at)||d.enrolled_at<1)throw Pe("response");let u=k_(d.device);if(u.device_id!==this.scope.deviceId||typeof u.token!="string"||!u.token||u.token.length>16384||/[^\x21-\x7e]/.test(u.token)||typeof u.expires_at!="number"||!Number.isSafeInteger(u.expires_at)||u.expires_at-this.now()<=5e3||u.expires_at-this.now()>16*6e4)throw Pe("response");let f=k_(d.genesis);if(f.seq!==1)throw Pe("response");let h=A_(f.item,256*1024),m=this.copy({operation:this.operation,genesisItem:h,expectedGenesis:await this.hash(h,t)});return await this.storageCallbacks.completed.call(this.persistence,this.copy(m),o),this.check(t),this.completion=this.copy(m),m}catch(a){throw this.close(),a instanceof qn?a:Pe("unavailable")}finally{s?.fill(0),r?.fill(0)}}adoptCollection(e,t){let{signal:i,replicaId:o,endpoint:s,opened:r,sqliteVersion:a,cloudCopyOptIn:c}=e;try{if(this.check(i),this.adopted||!this.completion||i!==this.originalSignal||c!==!0)throw Pe("binding");let l={replicaId:o,endpoint:s,opened:r,sqliteVersion:a,collection:this.scope.collection,deviceId:this.scope.deviceId,state:"cloud_copy",cloudCopyOptIn:!0,trustedRoots:this.roots.map(p=>new Uint8Array(p)),policyPins:new Uint8Array(this.pins),trustedSigners:[],expectedGenesis:this.completion.expectedGenesis};this.runtime.adoptDevice(l,t),this.adopted=!0,this.check(i)}catch(l){throw this.close(),l instanceof qn?l:Pe("unavailable")}}close(){this.completion=null,this.lifetime.abort(),this.runtime.retireLog()}}});function N1(n){try{if(n instanceof ir)return n;if(n instanceof et){if(n.reason==="outcome_unknown")return new ir("collection_delete_outcome_unknown");if(n.reason==="binding")return new ir("collection_delete_invalid");let e=zo(n.server)?.code;if(e&&Object.hasOwn(U1,e))return new ir(U1[e]);if(n.reason==="refused"&&!n.server)return new ir("collection_delete_not_approved")}}catch{}return new ir("collection_delete_failed")}var ir,U1,D1=C(()=>{"use strict";Id();ri();ir=class extends Error{constructor(t){super(`collection delete: ${t}`);this.code=t;this.name="AppCollectionDeleteError"}code},U1=Object.assign(Object.create(null),{collection_name_mismatch:"collection_delete_name_mismatch",not_owner:"collection_delete_not_owner",not_found:"collection_delete_not_found",migration_frozen:"collection_delete_frozen",busy:"collection_delete_busy",not_member:"collection_delete_not_approved",device_not_enrolled:"collection_delete_not_approved",installation_collection_not_approved:"collection_delete_not_approved",installation_not_current:"collection_delete_sign_in",identity_not_current:"collection_delete_sign_in",device_revoked:"collection_delete_sign_in",invalid_request:"collection_delete_invalid"})});function z1(n){return typeof n=="string"&&/^[a-zA-Z0-9_-]{16,128}$/.test(n)}function P_(n,e){let t=()=>{throw new xe("application_worker_binding")};if(!Array.isArray(n)||n.length!==5||n[0]!==di||n[1]!==e||!Number.isInteger(n[2])||n[2]<0||n[2]>Bm||n[2]===0&&n[3]!=="foreground"&&n[3]!=="approvalClosed"||n[2]!==0&&n[3]==="approvalClosed")return t();let i=n[3],o=n[4];["start","authorize","renewExpiredPairing","select","clearSelection","forget","refreshCollections","signOut","deleteCollection","requestFileAccess","pollFileAccess","openUnsynced","attachUnsynced","detachUnsynced","retireUnsynced","discardUnsynced","foreground","approvalClosed","cancelAuthorization","close","unlock"].includes(i)||t();let s=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;if(i==="requestFileAccess")return(!Array.isArray(o)||o.length!==3||typeof o[0]!="string"||!s.test(o[0])||!Array.isArray(o[1])||!o[1].length||o[1].length>6||o[1].some(r=>typeof r!="string"||!["list","read","add","replace","move","delete"].includes(r))||typeof o[2]!="string"||!o[2]||o[2].length>140)&&t(),Object.freeze([n[0],n[1],n[2],i,Object.freeze([o[0],Object.freeze([...o[1]]),o[2]])]);if(i==="unlock")return(!Array.isArray(o)||o.length!==3||typeof o[0]!="string"||!s.test(o[0])||o[0]==="00000000-0000-0000-0000-000000000000"||o[1]!=="password"&&o[1]!=="recoveryKey"||!(o[2]instanceof Uint8Array)||!o[2].length||o[2].length>S_)&&t(),Object.freeze([n[0],n[1],n[2],i,Object.freeze([o[0],o[1],o[2]])]);if(i==="pollFileAccess")(typeof o!="string"||!s.test(o))&&t();else if(i==="select"||i==="forget")(typeof o!="string"||!o||o.length>256||/[\u0000-\u001f\u007f]/.test(o))&&t();else{if(i==="deleteCollection")return(!Array.isArray(o)||o.length!==2||typeof o[0]!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(o[0])||typeof o[1]!="string"||!o[1]||o[1].length>1024)&&t(),Object.freeze([n[0],n[1],n[2],i,Object.freeze([o[0],o[1]])]);if(i==="retireUnsynced")return(!Array.isArray(o)||o.length!==2||o.some(r=>typeof r!="string"||!s.test(r))||o[0]===o[1])&&t(),Object.freeze([n[0],n[1],n[2],i,Object.freeze([o[0],o[1]])]);i==="authorize"?o!==null&&(typeof o!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(o)||o==="00000000-0000-0000-0000-000000000000")&&t():i==="openUnsynced"?o!==null&&!Im(o)&&t():i==="foreground"?typeof o!="boolean"&&t():i==="approvalClosed"?o!==!0&&t():o!==null&&t()}return Object.freeze([...n])}var di,Bm,S_,xe,qd=C(()=>{"use strict";t_();di="mdbn-application-worker/1",Bm=4294967295,S_=4096,xe=class extends Error{constructor(t){super("SDK application Worker unavailable");this.code=t;this.name="ApplicationWorkerError"}code}});function Vm(n){let e=n.cpOrigin,t=n.signal,i=n.isCurrent,o=n.open,s=()=>{let f=!1;try{f=!t.aborted&&i()===!0}catch{}if(!f)throw new sn("application_popup_fenced")};s();let r;try{r=new URL(e)}catch{throw new sn("application_popup_binding")}let a=n.allowLoopbackHttp===!0&&Qe(e);if(r.origin!==e||r.username||r.password||r.search||r.hash||r.pathname!=="/"||r.protocol!=="https:"&&!a)throw new sn("application_popup_binding");let c;try{c=o()}catch{throw new sn("application_popup_unavailable")}if(c===null)throw new sn("application_popup_blocked");if($1.has(c))throw new sn("application_popup_binding");$1.add(c);let l=!1,p=null,d=()=>{if(l){if(p)throw p;return}l=!0,t.removeEventListener("abort",u);try{c.close()}catch{throw p=new sn("application_popup_stop_failed"),p}},u=()=>{try{d()}catch{}};t.addEventListener("abort",u,{once:!0});try{s()}catch(f){throw d(),f}return Object.freeze({close:d,get closed(){try{return l||c.closed?.()===!0}catch{return!1}},focus(){if(s(),!l){try{c.focus?.()}catch{throw new sn("application_popup_unavailable")}s()}},navigate(f){if(s(),l)throw new sn("application_popup_fenced");let h;try{h=new URL(f)}catch{throw new sn("application_popup_binding")}if(h.origin!==e||h.username||h.password)throw new sn("application_popup_binding");try{c.navigate(h.href)}catch(m){throw m instanceof sn?m:new sn("application_popup_unavailable")}if(s(),l)throw new sn("application_popup_fenced")}})}function Uj(){let n=0,e=0;try{let t=globalThis.window;n=Math.max(0,Math.round(t.screenX+(t.outerWidth-V1)/2)),e=Math.max(0,Math.round(t.screenY+(t.outerHeight-F1)/2))}catch{}return`popup,width=${V1},height=${F1},left=${Number.isFinite(n)?n:0},top=${Number.isFinite(e)?e:0}`}function Fm(n,e,t,i=!1){return{cpOrigin:n,signal:e,isCurrent:t,allowLoopbackHttp:i,open(){let o=globalThis.window.open("about:blank","_blank",Uj());if(!o)return null;let s=B1.get(o);if(s)return s;let r={navigate(a){if(o.closed)throw new sn("application_popup_fenced");o.location.href=a},close(){let a=!o.closed;if(o.close(),a)try{globalThis.window.focus()}catch{}},focus(){try{o.focus()}catch{}},closed:()=>o.closed};return B1.set(o,r),r}}}function K1(n,e,t,i,o=!1){return{cpOrigin:n,signal:e,isCurrent:t,allowLoopbackHttp:o,open(){let s=null,r=a=>{Promise.resolve().then(()=>i.open(a)).catch(()=>{})};return{navigate(a){let c=new URL(a);i.returnUrl!==void 0&&c.searchParams.set("return_url",i.returnUrl),s=c.href,r(s)},focus(){s!==null&&r(s)},close(){s&&i.close&&Promise.resolve().then(()=>i.close()).catch(()=>{})}}}}}var sn,$1,B1,V1,F1,x_=C(()=>{"use strict";St();sn=class extends Error{constructor(t){super("application authorization popup unavailable");this.reason=t;this.name="ApplicationPortalError"}reason},$1=new WeakSet;B1=new WeakMap,V1=620,F1=760});function Js(n,e=null){if(n instanceof $e)return n;let t=n?.name??"",i=n instanceof Error?n.message:String(n),o=n?.resultCode,s=typeof o=="number"?o&255:null;return t==="QuotaExceededError"||/quota/i.test(i)||s===13?new $e("Full",i,e):s===11||s===26||/malformed|not a database|SQLITE_CORRUPT|SQLITE_NOTADB/i.test(i)?new $e("Corrupt",i,e):t==="NoModificationAllowedError"||s===5||s===6||/SQLITE_BUSY|SQLITE_LOCKED|NoModificationAllowed/i.test(i)?new $e("Busy",i,e):s===1||s===19||s===20||s===25||/SQLITE_ERROR|SQLITE_CONSTRAINT|syntax/i.test(i)?new $e("Sql",i,e):new $e("Other",i,e)}function I_(n){if(typeof n=="bigint")return n;if(typeof n=="number"&&Number.isSafeInteger(n))return BigInt(n);throw new $e("Other","SQLite integer is not losslessly represented")}var C_,R_,$e,Nj,Dj,zj,$j,Bj,Vj,Fj,Kj,Wj,Km,O_=C(()=>{"use strict";C_=new WeakMap,R_=new WeakMap,$e=class extends Error{constructor(t,i,o=null){super(`${t}${o===null?"":`@${o}`}(${i})`);this.kind=t;this.detail=i;this.stmt=o;this.name="IndexError"}kind;detail;stmt},Nj=new TextEncoder,Dj=1,zj=2,$j=3,Bj=4,Vj=5,Fj=100,Kj=101;Wj="CREATE TABLE IF NOT EXISTS _mdbn_host(k TEXT PRIMARY KEY, v) WITHOUT ROWID",Km=class n{constructor(e,t,i){this.sqlite3=e;this.db=t;this.info=i}sqlite3;db;info;cache=new Map;closed=!1;static open(e,t,i={}){try{let o=i.synchronous??"NORMAL";if(o!=="NORMAL"&&o!=="FULL")throw new $e("Other","unsupported synchronous profile");if(i.pragmas!==!1&&(t.exec(o==="FULL"?"PRAGMA page_size=65536":"PRAGMA page_size=32768"),t.exec("PRAGMA locking_mode=EXCLUSIVE"),t.exec("PRAGMA journal_mode=WAL"),t.exec(`PRAGMA synchronous=${o}`),o==="FULL")){t.exec("PRAGMA cache_size=-65536");let c=t.selectValue("PRAGMA page_size")===65536?2048:4096;t.exec(`PRAGMA wal_autocheckpoint=${c}`)}if(i.verifyPragmas&&(String(t.selectValue("PRAGMA locking_mode")).toLowerCase()!=="exclusive"||String(t.selectValue("PRAGMA journal_mode")).toLowerCase()!=="wal"||t.selectValue("PRAGMA synchronous")!==(o==="FULL"?2:1)))throw new $e("Other","SQLite did not apply the requested storage profile");let s=t.selectValue("SELECT count(*) FROM sqlite_master WHERE name='_mdbn_host'")>0,r=t.selectValue("SELECT count(*) FROM sqlite_master");t.exec(Wj);let a="Fresh";return s?a=t.selectValue("SELECT v FROM _mdbn_host WHERE k='clean'")===1?"Existing":"Unclean":r>0&&(a="Unclean"),t.exec("INSERT OR REPLACE INTO _mdbn_host(k, v) VALUES ('clean', 0)"),new n(e,t,{durability:"Disposable",opened:a,sqliteVersion:e.capi.sqlite3_libversion_number(),quotaSuspect:i.quotaSuspect??!1})}catch(o){throw Js(o)}}prepare(e){let t=this.cache.get(e);return t||(t=this.db.prepare(e),this.cache.set(e,t)),t}statementBuffer(e){let t=0;for(let i of e)i.kind==="Blob"&&(t+=Math.max(1,i.value.byteLength)),i.kind==="Text"&&(t+=Math.max(1,i.value.length*3));return t?this.sqlite3.wasm.alloc(t):0}bind(e,t,i){let o=e.pointer,s=this.sqlite3.wasm,r=i;for(let a=0;a<t.length;a++){let c=t[a],l=a+1,p;switch(c.kind){case"Null":p=s.exports.sqlite3_bind_null(o,l);break;case"Integer":if(BigInt.asIntN(64,c.value)!==c.value){e.bind(l,c.value);continue}p=s.exports.sqlite3_bind_int64(o,l,c.value);break;case"Real":e.bind(l,c.value);continue;case"Text":{let d=s.heap8u().subarray(r,r+c.value.length*3),{written:u}=Nj.encodeInto(c.value,d);p=s.exports.sqlite3_bind_text(o,l,r,u,0),r+=Math.max(1,u);break}case"Blob":s.heap8u().set(c.value,r),p=s.exports.sqlite3_bind_blob(o,l,r,c.value.length,0),r+=Math.max(1,c.value.length);break}p&&this.db.checkRc(p)}}bindPacket(e,t,i,o){let s=this.sqlite3.wasm.exports,r=e.pointer,a=t.view,c=t.offsets[i],l=a.getUint32(c-4,!0);for(let p=1;p<=l;p++){let d=a.getUint8(c++),u;switch(d){case 0:u=s.sqlite3_bind_null(r,p);break;case 1:u=s.sqlite3_bind_int64(r,p,a.getBigInt64(c,!0)),c+=8;break;case 2:e.bind(p,a.getFloat64(c,!0)),c+=8;continue;case 3:case 4:{let f=a.getUint32(c,!0);c+=4,u=d===3?s.sqlite3_bind_text(r,p,o+c,f,0):s.sqlite3_bind_blob(r,p,o+c,f,0),c+=f;break}default:throw new $e("Other","invalid tag in validated packet")}u&&this.db.checkRc(u)}}column(e,t,i,o){let s=this.sqlite3.wasm.exports;switch(i){case Vj:return o(1),{kind:"Null"};case Dj:return o(9),{kind:"Integer",value:I_(s.sqlite3_column_int64(e,t))};case zj:return o(9),{kind:"Real",value:s.sqlite3_column_double(e,t)};case $j:return o(5+s.sqlite3_column_bytes(e,t)),{kind:"Text",value:this.sqlite3.capi.sqlite3_column_text(e,t)};case Bj:{let r=s.sqlite3_column_bytes(e,t);o(5+r);let a=s.sqlite3_column_blob(e,t);if(r&&!a)throw new $e("Other","SQLite blob unavailable");return{kind:"Blob",value:this.sqlite3.wasm.heap8u().slice(a,a+r)}}default:throw new $e("Other","unknown SQLite value type")}}run(e,t){if(this.closed)throw new $e("Other","index closed");let i=C_.get(e);if(!i?.hasPayload)return this.runBatch(e,t,i);let o=this.sqlite3.wasm,s=i.view,r=o.alloc(s.byteLength+1);try{return o.heap8u().set(new Uint8Array(s.buffer,s.byteOffset,s.byteLength),r),this.runBatch(e,t,i,r)}finally{o.dealloc(r)}}runBatch(e,t,i,o=0){let s=this.sqlite3.wasm.exports,r=e.mode==="Transaction",a=[],c=0,l=0,p=13,d=u=>{if(t){if(!Number.isSafeInteger(u)||u<0||u>t.maxBytes-p)throw new $e("Full","index reply byte budget exceeded");p+=u}};if(t&&([t.maxBytes,t.maxRows,t.maxValues,t.maxColumns].some(u=>!Number.isSafeInteger(u)||u<0)||t.maxBytes<p))throw new $e("Full","invalid index reply budget");if(r)try{this.db.exec("BEGIN IMMEDIATE")}catch(u){throw Js(u)}for(let u=0;u<(i?.offsets.length??e.stmts.length);u++){let f=e.stmts[u];try{let h=this.prepare(f.sql),m=h.pointer,w=0;try{if(i)this.bindPacket(h,i,u,o);else{let v=f.params;w=this.statementBuffer(v),this.bind(h,v,w)}let b=s.sqlite3_column_count(m);if(t&&(!Number.isSafeInteger(b)||b<0||b>t.maxColumns))throw new $e("Full","index reply column budget exceeded");d(24);let g=[],y;for(;(y=s.sqlite3_step(m))===Fj;){if(t&&++c>t.maxRows)throw new $e("Full","index reply row budget exceeded");for(let v=0;v<b;v++){if(t&&++l>t.maxValues)throw new $e("Full","index reply value budget exceeded");let _=s.sqlite3_column_type(m,v);g.push(this.column(m,v,_,d))}}y!==Kj&&this.db.checkRc(y),a.push({columns:b,values:g,changes:I_(s.sqlite3_changes(this.db.pointer)),lastInsertRowid:I_(s.sqlite3_last_insert_rowid(this.db.pointer))})}finally{try{let b=s.sqlite3_clear_bindings(m),g=s.sqlite3_reset(m);(b||g)&&this.db.checkRc(b||g)}finally{w&&this.sqlite3.wasm.dealloc(w)}}}catch(h){if(r)try{this.db.exec("ROLLBACK")}catch{}throw Js(h,u)}}if(r)try{this.db.exec("COMMIT")}catch(u){try{this.db.exec("ROLLBACK")}catch{}throw Js(u)}return t&&R_.set(a,p),a}close(e={}){if(!this.closed){this.closed=!0;for(let t of this.cache.values())try{t.finalize()}catch{}if(this.cache.clear(),e.markClean!==!1)try{this.db.exec("INSERT OR REPLACE INTO _mdbn_host(k, v) VALUES ('clean', 1)")}catch{}this.db.close()}}}});function Jj(n,e,t,i){for(;t+4<=i&&!(e.getUint32(t)&2155905152);)t+=4;for(;t<i&&n[t]<128;)t++;t<i&&E_.decode(n.subarray(t,i))}function Xj(n){let e=new q_(n);if(!e.take(8).every((l,p)=>l===H1[p]))throw Xt();let t=e.byte();if(t===1)throw e.done(),new $e("Other","app database reset requires explicit recovery; automatic wipe refused");if(t!==0)throw Xt();let i=e.byte();if(i>1)throw Xt();let o=e.count(Tn.maxStatements,8),s=[],r=new Uint32Array(o),a=0;for(let l=0;l<o;l++){let p=e.text(Tn.maxSqlBytes),d=e.count(Tn.maxParameters,1);if(a+=d,a>Tn.maxValues)throw fo();r[l]=e.pos,e.params(d);let u;s.push({sql:p,get params(){if(u)return u;e.pos=r[l];let f=[];return e.params(d,f),u=f}})}e.done();let c={mode:i===0?"Transaction":"Autocommit",stmts:s};return C_.set(c,{view:e.view,offsets:r,hasPayload:e.hasPayload}),c}function Zj(n,e){if(!Array.isArray(n)||n.length!==e)throw Xt();let t=new Wm(2,R_.get(n));t.u32(n.length);let i=0;for(let o of n){if(!Number.isSafeInteger(o.columns)||o.columns<0||o.columns>Tn.maxColumns)throw fo();if(!Array.isArray(o.values)||(o.columns===0?o.values.length!==0:o.values.length%o.columns!==0))throw Xt();if(i+=o.columns===0?0:o.values.length/o.columns,i>Tn.maxRows||o.values.length>Tn.maxValues)throw fo();t.u32(o.columns),t.int(o.changes,!1),t.int(o.lastInsertRowid,!0),t.u32(o.values.length);for(let s of o.values)t.value(s)}return t.done()}function Qj(n,e){let t=n instanceof $e?n.kind:"Other",i={Sql:0,Corrupt:1,Full:2,Busy:3,Other:4},o=new Wm(3);o.byte(i[t]);let s=n instanceof $e?n.stmt:null;return e!==null&&s!==null&&Number.isSafeInteger(s)&&s>=0&&s<e?(o.byte(1),o.u32(s)):o.byte(0),o.data(G1.encode("app index operation failed; reopen and reconcile")),o.done()}function W1(n,e,t){if(!Number.isSafeInteger(e)||!Number.isSafeInteger(t)||e<0||t<0||e>4294967295||t>4294967295||e>n.buffer.byteLength||t>n.buffer.byteLength-e)throw Xt()}function Y1(n,e){let t=!1,i=!1;return(o,s)=>{if(t)throw i=!0,n.fence(),Xt();t=!0,i=!1;try{let r=e();if(W1(r.memory,o,s),s>Tn.maxBytes)throw n.fence(),fo();let a=n.run(new Uint8Array(r.memory.buffer,o,s)),c=r.alloc(a.length);if(W1(r.memory,c,a.length),i||c===0||c<o+s&&o<c+a.length)throw Xt();return new Uint8Array(r.memory.buffer,c,a.length).set(a),BigInt(c)<<32n|BigInt(a.length)}catch(r){throw n.fence(),r}finally{t=!1}}}var H1,Tn,Hj,Gj,Yj,Xt,fo,E_,G1,q_,Wm,Hm,J1=C(()=>{"use strict";O_();H1=Uint8Array.of(77,68,66,73,68,88,0,1),Tn=Object.freeze({maxBytes:4*1024*1024,maxStatements:16384,maxValues:131072,maxRows:4096,maxColumns:100,maxSqlBytes:100*1024,maxParameters:100}),Hj=-(1n<<63n),Gj=(1n<<63n)-1n,Yj=(1n<<64n)-1n,Xt=()=>new $e("Other","invalid app index ABI"),fo=()=>new $e("Full","app index ABI budget exceeded"),E_=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),G1=new TextEncoder;q_=class{constructor(e){this.bytes=e;this.view=new DataView(e.buffer,e.byteOffset,e.byteLength)}bytes;pos=0;hasPayload=!1;view;advance(e){if(!Number.isSafeInteger(e)||e<0||e>this.bytes.length-this.pos)throw Xt();let t=this.pos;return this.pos+=e,t}take(e){let t=this.advance(e);return this.bytes.subarray(t,this.pos)}byte(){return this.bytes[this.advance(1)]}u32(){return this.view.getUint32(this.advance(4),!0)}count(e,t){let i=this.u32();if(i>e)throw fo();if(i>Math.floor((this.bytes.length-this.pos)/t))throw Xt();return i}data(e){return this.take(this.count(e,1))}text(e){return E_.decode(this.data(e))}params(e,t){for(let i=0;i<e;i++){let o=this.byte();switch(o){case 0:t?.push({kind:"Null"});break;case 1:{let s=this.advance(8);t?.push({kind:"Integer",value:this.view.getBigInt64(s,!0)});break}case 2:{let s=this.view.getFloat64(this.advance(8),!0);if(!Number.isFinite(s))throw Xt();t?.push({kind:"Real",value:s});break}case 3:case 4:{let s=this.advance(this.count(Tn.maxBytes,1));if(this.hasPayload=!0,t){let r=this.bytes.subarray(s,this.pos);t.push(o===3?{kind:"Text",value:E_.decode(r)}:{kind:"Blob",value:r.slice()})}else o===3&&Jj(this.bytes,this.view,s,this.pos);break}default:throw Xt()}}}done(){if(this.pos!==this.bytes.length)throw Xt()}};Wm=class{bytes;view;length=0;values=0;constructor(e,t=128){if(t>Tn.maxBytes)throw fo();this.bytes=new Uint8Array(t),this.view=new DataView(this.bytes.buffer),this.put(H1),this.byte(e)}reserve(e){let t=this.length,i=t+e;if(i>Tn.maxBytes)throw fo();if(i>this.bytes.length){let o=Math.min(Tn.maxBytes,Math.max(i,this.bytes.length*2)),s=new Uint8Array(o);s.set(this.bytes.subarray(0,t)),this.bytes=s,this.view=new DataView(s.buffer)}return this.length=i,t}put(e){let t=this.reserve(e.length);this.bytes.set(e,t)}byte(e){let t=this.reserve(1);this.bytes[t]=e}u32(e){if(!Number.isSafeInteger(e)||e<0||e>4294967295)throw Xt();let t=this.reserve(4);this.view.setUint32(t,e,!0)}int(e,t){if(typeof e!="bigint"||e<(t?Hj:0n)||e>(t?Gj:Yj))throw Xt();let i=this.reserve(8);t?this.view.setBigInt64(i,e,!0):this.view.setBigUint64(i,e,!0)}data(e){let t=this.reserve(4+e.length);this.view.setUint32(t,e.length,!0),this.bytes.set(e,t+4)}value(e){if(++this.values>Tn.maxValues)throw fo();switch(e.kind){case"Null":this.byte(0);return;case"Integer":this.byte(1),this.int(e.value,!0);return;case"Real":{if(!Number.isFinite(e.value))throw Xt();this.byte(2);let t=this.reserve(8);this.view.setFloat64(t,e.value,!0);return}case"Text":this.byte(3),this.data(G1.encode(e.value));return;case"Blob":this.byte(4),this.data(e.value);return;default:throw Xt()}}done(){return this.bytes.subarray(0,this.length)}};Hm=class{constructor(e){this.index=e}index;fenced=!1;get needsRecovery(){return this.fenced||this.index.needsRecovery}fence(){this.fenced=!0,this.index.fence()}run(e){let t=null;try{if(this.needsRecovery)throw Xt();if(e.byteLength>Tn.maxBytes)throw fo();let i=Xj(new Uint8Array(e));t=i.stmts.length;let o=Tn;return Zj(this.index.run(i,o),t)}catch(i){return this.fence(),Qj(i,t)}}}});function M_(n){let e=[n.account,n.installation,n.collection];if(e.some(i=>!eU.test(i)))throw new $e("Other","invalid app storage scope");let t=`mdbase-app-${e.map(i=>i.toLowerCase()).join("-")}`;return{vfs:t,directory:`.${t}`}}async function X1(n,e){let t=M_(e),i,o,s;try{i=await n.installOpfsSAHPoolVfs({name:t.vfs,directory:t.directory,initialCapacity:6}),i.isPaused?.()&&await i.unpauseVfs(),o=new i.OpfsSAHPoolDb("/app.db");let r=Km.open(n,o,{synchronous:"FULL",verifyPragmas:!0});if(s=new T_(r),r.info.opened==="Unclean"){let a=s.run({mode:"Autocommit",stmts:[{sql:"PRAGMA quick_check",params:[]}]}),c=a[0]?.values;if(a.length!==1||c?.length!==1||c[0]?.kind!=="Text"||c[0].value!=="ok")throw s=void 0,r.close({markClean:!1}),o=void 0,new $e("Corrupt","app database integrity check failed; recovery required")}return{index:s,pool:i}}catch(r){let a=!1;try{s?s.close():o?.close()}catch{a=!0}try{i?.pauseVfs?.()}catch{a=!0}let c=Js(r);throw new $e(a?"Other":c.kind,"app SQLite open failed; recovery required",c.stmt)}}var eU,T_,Z1=C(()=>{"use strict";O_();eU=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;T_=class{constructor(e){this.inner=e}inner;fenced=!1;closed=!1;get info(){return this.inner.info}get needsRecovery(){return this.fenced}fence(){this.fenced=!0}run(e,t){if(this.closed||this.fenced)throw new $e("Other","app database fenced or closed; reopen and reconcile");try{return t?this.inner.run(e,t):this.inner.run(e)}catch(i){this.fenced=!0;let o=Js(i);throw new $e(o.kind,"app SQLite operation failed; reopen and reconcile",o.stmt)}}reset(){throw new $e("Other","app database reset requires explicit recovery; automatic wipe refused")}close(){this.closed||(this.closed=!0,this.inner.close({markClean:!this.fenced}))}}});function Q1(n){let e=Object.freeze({...n});if(!/^[0-9a-f]{64}$/.test(e.wasmSha256)||!Number.isSafeInteger(e.maxWasmBytes)||e.maxWasmBytes<1||e.maxWasmBytes>4*1024*1024||typeof e.loadWasm!="function"||typeof e.initialize!="function")throw Yl("binding");return async({scope:t,signal:i})=>{let o=Object.freeze({account:t.account,installation:t.installation,collection:t.collection});M_(o);let s=()=>{if(i.aborted||Object.entries(o).some(([y,v])=>t[y]!==v))throw Yl("fenced")};s();let r=globalThis.WorkerGlobalScope;if(typeof r!="function"||!(globalThis instanceof r))throw Yl("unsupported");let a=await e.loadWasm({signal:i});if(s(),!(a instanceof Uint8Array)||a.byteLength<1||a.byteLength>e.maxWasmBytes)throw Yl("binding");let c=new Uint8Array(a),l=new Uint8Array(await crypto.subtle.digest("SHA-256",c));if(s(),Array.from(l,y=>y.toString(16).padStart(2,"0")).join("")!==e.wasmSha256)throw Yl("binding");let p=await e.initialize({wasmBinary:c,print(){},printErr(){}});s();let d=await X1(p,o),u=d.index,f=new Hm(u),h={import:y=>Y1(f,y),fence:()=>f.fence(),get needsRecovery(){return f.needsRecovery}},m=y=>({kind:"Text",value:y}),w=Object.freeze({list(y){let[v]=u.run({mode:"Autocommit",stmts:[{sql:"SELECT v FROM _mdbn_host WHERE k >= 'w:' AND k < 'w;' ORDER BY k LIMIT 1024",params:[]}]}),_=[],k=0;for(let S of v?.values??[])if(S.kind==="Text"){if(k+=S.value.length,k>y)break;_.push(S.value)}return _},put(y,v){u.run({mode:"Autocommit",stmts:[{sql:"INSERT OR REPLACE INTO _mdbn_host(k, v) VALUES (?, ?)",params:[m(`w:${y}`),m(v)]}]})},remove(y){u.run({mode:"Autocommit",stmts:[{sql:"DELETE FROM _mdbn_host WHERE k = ?",params:[m(`w:${y}`)]}]})}}),b=null,g=()=>b??=Promise.resolve().then(async()=>{try{u.close(),await d.pool.pauseVfs()}catch{throw f.fence(),Yl("unavailable")}});return(i.aborted||Object.entries(o).some(([y,v])=>t[y]!==v))&&f.fence(),Object.freeze({sql:h,opened:{Fresh:"fresh",Existing:"existing",Unclean:"unclean"}[u.info.opened],sqliteVersion:u.info.sqliteVersion,ledger:w,close:g})}}var L_,Yl,eR=C(()=>{"use strict";Z1();J1();L_=class extends Error{constructor(t){super(`app collection SQL: ${t}`);this.reason=t;this.name="AppCollectionSqlError"}reason},Yl=n=>new L_(n)});var ho,j_=C(()=>{"use strict";ho=Object.freeze({plaintextBytes:524288,operations:64,readbacks:128,pathCodeUnits:1024})});function se(n){throw new Ln(n)}function Mn(n,e){return Object.keys(n).sort().join()===e}function U_(n){return(!n||!Mn(n,"account,collection,installation")||Object.values(n).some(e=>typeof e!="string"||!N_.test(e)||e==="00000000-0000-0000-0000-000000000000"))&&se("binding"),Object.freeze({account:n.account,installation:n.installation,collection:n.collection})}function tR(n){for(let e of n){let t=e.charCodeAt(0);if(t<32||t===127)return!0}return n.includes("\\")}function tU(n){(!Array.isArray(n)||n.length!==2)&&se("binding");let e=n.map(t=>((!t||typeof t!="object"||!Mn(t,"doc,kind,mustNotExist,path")||t.kind!=="resource_put"||t.mustNotExist!==!0||typeof t.path!="string"||typeof t.doc!="string"||!t.doc.length||t.path.length>1024||!t.path.endsWith(".md")||t.path.startsWith("/")||tR(t.path)||t.path.split("/").some(i=>!i||i==="."||i===".."))&&se("binding"),Object.freeze({kind:"resource_put",path:t.path,doc:t.doc,mustNotExist:!0})));return(e[0].path===e[1].path||qr.encode(JSON.stringify(e)).byteLength>rr)&&se("binding"),Object.freeze(e)}function Md(n){return typeof n=="string"&&n.length>0&&n.length<=ho.pathCodeUnits&&!n.startsWith("/")&&!tR(n)&&!n.split("/").some(e=>!e||e==="."||e==="..")}function Zs(n){let e=n;(!e||typeof e!="object"||!Mn(e,"assessmentDigest,ops,pack,readback")||!e.pack||typeof e.pack!="object"||!Mn(e.pack,"digest,id,version")||typeof e.pack.id!="string"||!e.pack.id.length||typeof e.pack.version!="string"||!e.pack.version.length||typeof e.pack.digest!="string"||!Xs.test(e.pack.digest)||typeof e.assessmentDigest!="string"||!Xs.test(e.assessmentDigest)||!Array.isArray(e.ops)||!e.ops.length||e.ops.length>ho.operations||!Array.isArray(e.readback)||!e.readback.length||e.readback.length>ho.readbacks)&&se("binding");let t=e.ops.map(r=>{(!r||typeof r!="object"||!Md(r.path)||"baseRevision"in r&&(typeof r.baseRevision!="string"||!Xs.test(r.baseRevision)))&&se("binding");let a="baseRevision"in r?{baseRevision:r.baseRevision}:{};return r.kind==="resource_put"?((!Mn(r,"baseRevision"in r?"baseRevision,doc,kind,mustNotExist,path":"doc,kind,mustNotExist,path")||typeof r.doc!="string"||typeof r.mustNotExist!="boolean")&&se("binding"),Object.freeze({kind:r.kind,path:r.path,doc:r.doc,...a,mustNotExist:r.mustNotExist})):((r.kind!=="resource_delete"||!Mn(r,"baseRevision"in r?"baseRevision,kind,path":"kind,path"))&&se("binding"),Object.freeze({kind:r.kind,path:r.path,...a}))}),i=new Set,o=e.readback.map(r=>((!r||typeof r!="object"||!Mn(r,"doc,path")||!Md(r.path)||r.doc!==null&&typeof r.doc!="string"||i.has(r.path))&&se("binding"),i.add(r.path),Object.freeze({path:r.path,doc:r.doc})));for(let r of t){let a=o.find(c=>c.path===r.path);(!a||a.doc!==(r.kind==="resource_put"?r.doc:null))&&se("binding")}let s=Object.freeze({pack:Object.freeze({id:e.pack.id,version:e.pack.version,digest:e.pack.digest}),assessmentDigest:e.assessmentDigest,ops:Object.freeze(t),readback:Object.freeze(o)});return qr.encode(JSON.stringify(s)).byteLength>rr&&se("binding"),s}function $t(n){let e=n;(!e||typeof e!="object"||!Mn(e,Object.hasOwn(e,"planKind")?"assessmentDigest,packs,planKind,provisionDigest,resourceOps,resourceReadback,sources":Object.hasOwn(e,"sourcePolicy")?"assessmentDigest,packs,provisionDigest,resourceOps,resourceReadback,sourcePolicy,sources":"assessmentDigest,packs,provisionDigest,resourceOps,resourceReadback,sources")||Object.hasOwn(e,"sourcePolicy")&&(e.sourcePolicy!=="current-only"||e.sources?.length!==0)||typeof e.assessmentDigest!="string"||!Xs.test(e.assessmentDigest)||typeof e.provisionDigest!="string"||!Xs.test(e.provisionDigest)||!Array.isArray(e.packs)||!e.packs.length&&e.planKind!=="configuration-only"||e.packs.length>16||!Array.isArray(e.resourceOps)||!Array.isArray(e.sources)||!e.resourceOps.length&&!e.sources.length||e.resourceOps.length+e.sources.length>ho.operations||!Array.isArray(e.resourceReadback)||!e.resourceReadback.length||e.resourceReadback.length+e.sources.length>ho.readbacks)&&se("binding"),Object.hasOwn(e,"planKind")&&(e.planKind!=="configuration-only"||e.packs.length!==0||!e.resourceOps.length||e.resourceOps.some(p=>!p||p.kind!=="resource_put"||!["mdbase.yaml","mdbase.provisions.yaml"].includes(p.path)))&&se("binding");let t=new Set,i=e.packs.map(p=>((!p||typeof p!="object"||!Mn(p,"digest,id,version")||typeof p.id!="string"||!p.id.length||p.id.length>150||t.has(p.id)||typeof p.version!="string"||!p.version.length||p.version.length>256||typeof p.digest!="string"||!Xs.test(p.digest))&&se("binding"),t.add(p.id),Object.freeze({...p}))),o=new Set,s=e.resourceReadback.map(p=>((!p||typeof p!="object"||!Mn(p,"doc,path")||!Md(p.path)||o.has(p.path)||p.doc!==null&&typeof p.doc!="string")&&se("binding"),o.add(p.path),Object.freeze({...p}))),r=e.resourceOps.map(p=>{(!p||typeof p!="object"||!Md(p.path))&&se("binding");let d=Object.hasOwn(p,"baseRevision");d&&(typeof p.baseRevision!="string"||!Xs.test(p.baseRevision))&&se("binding"),p.kind==="resource_put"?(!Mn(p,d?"baseRevision,doc,kind,mustNotExist,path":"doc,kind,mustNotExist,path")||typeof p.doc!="string"||typeof p.mustNotExist!="boolean"||(p.mustNotExist?d:!d))&&se("binding"):(p.kind!=="resource_delete"||!d||!Mn(p,"baseRevision,kind,path"))&&se("binding");let u=s.find(f=>f.path===p.path);return(!u||u.doc!==(p.kind==="resource_put"?p.doc:null))&&se("binding"),Object.freeze({...p})}),a=new Set,c=e.sources.map(p=>((!p||typeof p!="object"||!Mn(p,"document,id,path")||!Md(p.path)||o.has(p.path)||typeof p.id!="string"||!N_.test(p.id)||p.id==="00000000-0000-0000-0000-000000000000"||a.has(p.id)||typeof p.document!="string"||!p.document.length)&&se("binding"),o.add(p.path),a.add(p.id),Object.freeze({...p}))),l=Object.freeze({...e.planKind==="configuration-only"?{planKind:e.planKind}:{},...e.sourcePolicy==="current-only"?{sourcePolicy:e.sourcePolicy}:{},assessmentDigest:e.assessmentDigest,provisionDigest:e.provisionDigest,packs:Object.freeze(i),resourceOps:Object.freeze(r),resourceReadback:Object.freeze(s),sources:Object.freeze(c)});return qr.encode(JSON.stringify(l)).byteLength>rr&&se("binding"),l}function Zt(n,e,t=0){t>8&&se("binding");let i=n;(!i||typeof i!="object"||i.version!==1&&i.version!==2&&i.version!==3&&i.version!==4||!Mn(i,i.version===1?"mutationId,ops,phase,scope,version":i.version===4?"mutationId,phase,plan,previous,scope,version":"mutationId,phase,plan,scope,version")||typeof i.mutationId!="string"||!N_.test(i.mutationId)||i.mutationId==="00000000-0000-0000-0000-000000000000"||!(Td.includes(i.phase)||i.phase==="rejected"&&(i.version===3||i.version===4)))&&se("recovery_required");let o=U_(i.scope);if(JSON.stringify(o)!==JSON.stringify(e)&&se("binding"),i.version===1)return Object.freeze({version:1,scope:o,mutationId:i.mutationId,ops:tU(i.ops),phase:i.phase});if(i.version===4){let r=Zt(i.previous,e,t+1);r.phase!=="verified"&&se("recovery_required");for(let c=r;c.mutationId===i.mutationId&&se("binding"),c.version===4;)c=c.previous;let a=Object.freeze({version:4,scope:o,mutationId:i.mutationId,plan:$t(i.plan),phase:i.phase,previous:r});return qr.encode(JSON.stringify({...a,phase:"confirmed"})).byteLength>rr&&se("binding"),a}if(i.version===3){$t(i.plan).sourcePolicy!==void 0&&se("binding");let r=Object.freeze({version:3,scope:o,mutationId:i.mutationId,plan:$t(i.plan),phase:i.phase});return qr.encode(JSON.stringify({...r,phase:"confirmed"})).byteLength>rr&&se("binding"),r}let s=Object.freeze({version:2,scope:o,mutationId:i.mutationId,plan:Zs(i.plan),phase:i.phase});return qr.encode(JSON.stringify({...s,phase:"confirmed"})).byteLength>rr&&se("binding"),s}function Gm(n){return n.version!==2&&se("recovery_required"),n}function nU(n,e,t){return t(),globalThis.indexedDB||se("recovery_required"),new Promise((i,o)=>{let s=indexedDB.open(n,1),r=!1,a=()=>{r=!0,e.removeEventListener("abort",a);try{s.transaction?.abort()}catch{}o(new Ln("recovery_required"))};e.addEventListener("abort",a,{once:!0}),s.onupgradeneeded=()=>{try{t(),(r||s.result.objectStoreNames.length)&&se("recovery_required"),s.result.createObjectStore(Jl)}catch{a()}},s.onerror=s.onblocked=a,s.onsuccess=()=>{e.removeEventListener("abort",a);try{t(),(r||s.result.objectStoreNames.length!==1||!s.result.objectStoreNames.contains(Jl))&&se("recovery_required"),i(s.result)}catch{s.result.close(),o(new Ln("recovery_required"))}}})}var Jl,Td,N_,rr,Xs,qr,Ln,Xl,Qs=C(()=>{"use strict";St();Jt();j_();Jl="original-model-operation",Td=["prepared","attempted","confirmed","verified"],N_=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,rr=ho.plaintextBytes,Xs=/^sha256:[0-9a-f]{64}$/,qr=new TextEncoder,Ln=class extends Error{constructor(t){super("Preserve the original collection setup operation.");this.reason=t}reason};Xl=class{constructor(e){this.owner=e;this.scope=U_(e.scope),(typeof e.isCurrent!="function"||[e.databaseName,e.applicationNamespace].some(o=>typeof o!="string"||!o.length||o.length>256||/[\u0000-\u001f\u007f]/.test(o)))&&se("binding"),this.current=e.isCurrent,this.pins=JSON.stringify([e.databaseName,e.applicationNamespace,e.appOrigin,e.cpOrigin]);let t=new URL(e.appOrigin),i=new URL(e.cpOrigin);(!ut(e.appOrigin)||dt(t)!==e.appOrigin||i.origin!==e.cpOrigin||i.protocol!=="https:"&&!!1)&&se("binding"),this.namespace=JSON.stringify([e.appOrigin,e.cpOrigin,e.applicationNamespace,this.scope.account,this.scope.installation,this.scope.collection]),this.binding=JSON.stringify(this.scope)}owner;scope;namespace;binding;stopped=!1;turn=Promise.resolve();pins;current;close(){this.stopped=!0}check(e){e.throwIfAborted();let t=!1;try{t=!this.stopped&&this.owner.isCurrent===this.current&&this.current.call(this.owner)===!0&&JSON.stringify([this.owner.databaseName,this.owner.applicationNamespace,this.owner.appOrigin,this.owner.cpOrigin])===this.pins&&JSON.stringify(U_(this.owner.scope))===this.binding}catch{}t||(this.stopped=!0,se("fenced"))}async exclusive(e,t){this.check(e);let i=this.turn,o,s=new Promise(a=>{o=a});this.turn=i.then(()=>s);let r;try{await new Promise((c,l)=>{let p=()=>l(e.reason);e.addEventListener("abort",p,{once:!0}),i.then(()=>{e.removeEventListener("abort",p),c()})}),this.check(e),r=await nU(this.owner.databaseName,e,()=>this.check(e)),this.check(e);let a=await t(r);return this.check(e),a}finally{r?.close(),o()}}read(e,t){return this.check(t),new Promise((i,o)=>{let s=e.transaction(Jl,"readonly"),r=s.objectStore(Jl).get(this.namespace),a=()=>s.abort();t.addEventListener("abort",a,{once:!0}),s.onabort=s.onerror=()=>{t.removeEventListener("abort",a),o(new Ln("recovery_required"))},s.oncomplete=()=>{t.removeEventListener("abort",a),i(r.result)}})}aad(e){return qr.encode(JSON.stringify([this.namespace,1,e]))}async unwrap(e,t){if(this.check(t),e===void 0)return null;(!e||!Mn(e,"ciphertext,iv,key,revision,version")||e.version!==1||!Number.isSafeInteger(e.revision)||e.revision<1||!(e.key instanceof CryptoKey)||e.key.extractable||e.key.type!=="secret"||e.key.algorithm.name!=="AES-GCM"||!e.key.usages.includes("encrypt")||!e.key.usages.includes("decrypt")||!(e.iv instanceof Uint8Array)||e.iv.byteLength!==12||!(e.ciphertext instanceof ArrayBuffer)||e.ciphertext.byteLength>rr+2048)&&se("recovery_required");let i;try{i=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:e.iv,additionalData:this.aad(e.revision)},e.key,e.ciphertext)),this.check(t);let o=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(i));return(o?.version===2||o?.version===3||o?.version===4)&&i.byteLength>rr&&se("recovery_required"),Zt(o,this.scope)}catch(o){throw o instanceof Ln||t.aborted?o:new Ln("recovery_required")}finally{i?.fill(0)}}async commit(e,t,i,o){this.check(o);let s=(t?.revision??0)+1;Number.isSafeInteger(s)||se("fenced");let r=t?.key??await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),a=crypto.getRandomValues(new Uint8Array(12)),c=qr.encode(JSON.stringify(i));c.byteLength>rr&&(c.fill(0),se("binding"));let l;try{l=await crypto.subtle.encrypt({name:"AES-GCM",iv:a,additionalData:this.aad(s)},r,c)}finally{c.fill(0)}this.check(o);try{await new Promise((p,d)=>{let u=e.transaction(Jl,"readwrite",{durability:"strict"}),f=()=>u.abort();o.addEventListener("abort",f,{once:!0}),u.onerror=u.onabort=()=>{o.removeEventListener("abort",f),d(new Ln("outcome_unknown"))},u.oncomplete=()=>{o.removeEventListener("abort",f),p()};let h=u.objectStore(Jl),m=h.get(this.namespace);m.onsuccess=()=>{try{this.check(o);let w=m.result;if(w===void 0!=(t===void 0)||w&&w.revision!==t?.revision){u.abort();return}h.put({version:1,revision:s,key:r,iv:a,ciphertext:l},this.namespace)}catch{u.abort()}}})}catch(p){throw this.stopped=!0,p}return this.check(o),i}load(e){return this.exclusive(e,async t=>this.unwrap(await this.read(t,e),e))}prepare(e,t){let i=Zs(e);return qr.encode(JSON.stringify({version:2,scope:this.scope,mutationId:this.scope.collection,plan:i,phase:"confirmed"})).byteLength>rr&&se("binding"),this.exclusive(t,async o=>{let s=await this.read(o,t),r=await this.unwrap(s,t);if(r){let c=Gm(r);return JSON.stringify(c.plan)!==JSON.stringify(i)&&se("binding"),c}let a=Gm(Zt({version:2,scope:this.scope,mutationId:crypto.randomUUID(),plan:i,phase:"prepared"},this.scope));return this.commit(o,s,a,t)})}prepareResources(e,t){let i=$t(e);return i.sourcePolicy!==void 0&&se("binding"),qr.encode(JSON.stringify({version:3,scope:this.scope,mutationId:this.scope.collection,plan:i,phase:"confirmed"})).byteLength>rr&&se("binding"),this.exclusive(t,async o=>{let s=await this.read(o,t),r=await this.unwrap(s,t);if(r&&!(r.version===3&&r.phase==="rejected"))return r.version!==3&&se("recovery_required"),JSON.stringify(r.plan)!==JSON.stringify(i)&&se("binding"),r;let a=Zt({version:3,scope:this.scope,mutationId:crypto.randomUUID(),plan:i,phase:"prepared"},this.scope);return a.version!==3&&se("binding"),this.commit(o,s,a,t)})}prepareResourceRound(e,t,i){let o=$t(e);return this.exclusive(i,async s=>{let r=await this.read(s,i),a=await this.unwrap(r,i);a?.version===4&&a.phase==="rejected"&&(a=a.previous),(!a||a.mutationId!==t)&&se("binding"),a.phase!=="verified"&&se("recovery_required");let c=Zt({version:4,scope:this.scope,mutationId:crypto.randomUUID(),plan:o,phase:"prepared",previous:a},this.scope);return c.version!==4&&se("binding"),this.commit(s,r,c,i)})}advanceResource(e,t,i){return this.exclusive(i,async o=>{let s=await this.read(o,i),r=await this.unwrap(s,i);(!r||r.version!==3&&r.version!==4)&&se("recovery_required"),r.mutationId!==e&&se("binding"),r.phase==="rejected"&&se("recovery_required");let a=Td.indexOf(r.phase),c=Td.indexOf(t);if((c<a||c>a+1)&&se("recovery_required"),c===a)return r;let l=Zt({...r,phase:t},this.scope);return l.version!==3&&l.version!==4&&se("binding"),this.commit(o,s,l,i)})}recordResourceAttempt(e,t){return this.advanceResource(e,"attempted",t)}recordResourceConfirmed(e,t){return this.advanceResource(e,"confirmed",t)}recordResourceVerified(e,t){return this.advanceResource(e,"verified",t)}recordResourceRejected(e,t){return this.exclusive(t,async i=>{let o=await this.read(i,t),s=await this.unwrap(o,t);if((!s||s.version!==3&&s.version!==4)&&se("recovery_required"),s.mutationId!==e&&se("binding"),s.phase==="rejected")return s;s.phase!=="attempted"&&se("recovery_required");let r=Zt({...s,phase:"rejected"},this.scope);return r.version!==3&&r.version!==4&&se("binding"),this.commit(i,o,r,t)})}advance(e,t,i){return this.exclusive(i,async o=>{let s=await this.read(o,i),r=await this.unwrap(s,i);r||se("recovery_required");let a=Gm(r);a.mutationId!==e&&se("binding"),a.phase==="rejected"&&se("recovery_required");let c=Td.indexOf(a.phase),l=Td.indexOf(t);return(l<c||l>c+1)&&se("recovery_required"),l===c?a:this.commit(o,s,Gm(Zt({...a,phase:t},this.scope)),i)})}recordAttempt(e,t){return this.advance(e,"attempted",t)}recordConfirmed(e,t){return this.advance(e,"confirmed",t)}recordVerified(e,t){return this.advance(e,"verified",t)}}});function nR(n){if(!n||typeof n!="object")return null;let e=n;if(typeof e.mutationId!="string"||!iU.test(e.mutationId)||!Array.isArray(e.records)||!e.records.every(i=>typeof i=="string")||typeof e.createdAt!="number"||e.state!=="pending"&&e.state!=="rejected")return null;let t=e.problem;return t!==void 0&&(!t||typeof t.code!="string"||typeof t.message!="string"||typeof t.recovery!="string")?null:{mutationId:e.mutationId,records:[...e.records],createdAt:e.createdAt,state:e.state,...t?{problem:{code:t.code,recovery:t.recovery,message:t.message,...t.reason?{reason:t.reason}:{}}}:{}}}var iU,iR=C(()=>{"use strict";iU=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/});function Ym(n){if(!n||typeof n!="object"||Array.isArray(n))throw Gn();let e=Object.getPrototypeOf(n);if(e!==Object.prototype&&e!==null)throw Gn();let t=Object.create(null);for(let i of Reflect.ownKeys(n)){if(typeof i!="string")throw Gn();let o=Object.getOwnPropertyDescriptor(n,i);if(!o||!("value"in o))throw Gn();o.enumerable&&(t[i]=o.value)}return t}function D_(n){if(typeof n!="string"||!n.trim()||rU.encode(n).byteLength>4096)throw Gn();return n}function oR(n){let e=D_(n),t=new URL(e);if(!["http:","https:"].includes(t.protocol)||t.username||t.password)throw Gn();return e}function rR(n){let e=Ym(n),t={issuer:oR(e.issuer),subject:D_(e.subject),name:D_(e.name)};if(e.account_id!==void 0){if(typeof e.account_id!="string"||!oU.test(e.account_id)||e.account_id==="00000000-0000-0000-0000-000000000000")throw Gn();t.account_id=e.account_id}return t}function sU(n){if(!Array.isArray(n)||Object.getPrototypeOf(n)!==Array.prototype||n.length>1e3)throw Gn();for(let t of Reflect.ownKeys(n)){let i=Object.getOwnPropertyDescriptor(n,t);if(typeof t!="string"||!i||!("value"in i))throw Gn()}let e=[];for(let t=0;t<n.length;t++){let i=Object.getOwnPropertyDescriptor(n,String(t));if(!i||!("value"in i))throw Gn();e.push(i.value)}return e}function Zl(n,e){try{let t=Ym(e);if(n==="identity"){let o=rR(t);return t.person_settings_url!==void 0&&(o.person_settings_url=oR(t.person_settings_url)),o}if(n!=="members")throw Gn();return{members:sU(t.members).map(o=>{let s=Ym(o),r=rR(s),a=s.role;if(a!=="owner"&&a!=="editor"&&a!=="viewer")throw Gn();return{...r,role:a}})}}catch{throw Gn()}}function sR(n,e){try{if(e instanceof ne)switch(e.code){case"forbidden":return{code:"forbidden",reason:n==="members"&&e.reason==="people_permission_declined"?"people_permission_declined":"people_access"};case"unauthenticated":case"cancelled":return{code:"unauthenticated",reason:"people_fenced"};case"upgrade_required":return{code:"upgrade_required",reason:"people_unsupported"}}}catch{}return{code:"unavailable",reason:"people_response"}}function aR(n){let e=Ym(n);if(!(e.code==="forbidden"&&["people_permission_declined","people_access"].includes(e.reason)||e.code==="unauthenticated"&&e.reason==="people_fenced"||e.code==="upgrade_required"&&e.reason==="people_unsupported"||e.code==="unavailable"&&["people_response","people_busy"].includes(e.reason))||Object.keys(e).length!==2)throw Gn();return A(e.code,"people metadata request failed",e.reason)}function Jm(n,e){if(!e.peopleAuthority)throw A("upgrade_required","people metadata is unsupported","people_unsupported");return new vr(n,e.peopleAuthority)}var Gn,rU,oU,Ld=C(()=>{"use strict";re();xp();Gn=()=>A("unavailable","invalid people response","people_response"),rU=new TextEncoder,oU=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/});function Oi(n){if(!ea(n)||Object.keys(n).some(i=>i!=="adopt"))throw ye("binding");if(n.adopt===void 0)return Object.freeze({});let e=n.adopt;if(!ea(e)||Object.keys(e).length>256)throw ye("binding");let t={};for(let[i,o]of Object.entries(e)){if(!Tr(i)||typeof o!="string"||!Ud.test(o))throw ye("binding");t[i]=o}return Object.freeze({adopt:Object.freeze(t)})}function aU(n){if(!ea(n)||!jd(n,"configuration,packs,staged")||!Array.isArray(n.packs)||n.packs.length>16||!Array.isArray(n.configuration)||n.configuration.length>64||!Array.isArray(n.staged)||n.staged.length>1024)throw ye("binding");let e=n.packs.map(o=>{if(!ea(o)||!jd(o,"id,installedVersion,resources,status,version")||!Tr(o.id,150)||!Tr(o.version,128)||!["current","install","upgrade","downgrade","reconfigure","conflict"].includes(o.status)||!(o.installedVersion===null||Tr(o.installedVersion,128))||!Array.isArray(o.resources)||o.resources.length>1024)throw ye("binding");let s=o.resources.map(r=>{if(!ea(r)||!jd(r,"action,installed,kind,mode,target",["currentDigest","reason"])||!Tr(r.target)||!Tr(r.kind,64)||r.mode!=="managed"&&r.mode!=="seed"||typeof r.installed!="boolean"||!["create","update","delete","adopt","preserve","conflict"].includes(r.action)||r.currentDigest!==void 0&&(typeof r.currentDigest!="string"||!Ud.test(r.currentDigest))||r.reason!==void 0&&!Tr(r.reason,8192))throw ye("binding");return Object.freeze({...r})});return Object.freeze({id:o.id,version:o.version,status:o.status,installedVersion:o.installedVersion,resources:Object.freeze(s)})}),t=n.configuration.map(o=>{if(!ea(o)||!jd(o,"action,path,requirement",["value"])||!Tr(o.requirement,256)||!Tr(o.path,1024)||o.action!=="add"&&o.action!=="conflict"||!(o.value===void 0||o.value===null||["string","number","boolean"].includes(typeof o.value)))throw ye("binding");return Object.freeze({...o})}),i=n.staged.map(o=>{if(!ea(o)||!jd(o,"document,path")||!Tr(o.path)||typeof o.document!="string"||o.document.length>512*1024)throw ye("binding");return Object.freeze({path:o.path,document:o.document})});return Object.freeze({packs:Object.freeze(e),configuration:Object.freeze(t),staged:Object.freeze(i)})}function ta(n,e=!1){let t=n;if(!t||typeof t!="object"||Object.keys(t).sort().join(",")!==(e?"assessmentDigest,review,status":"assessmentDigest,status")||!["current","provision","conflict"].includes(t.status)||typeof t.assessmentDigest!="string"||!Ud.test(t.assessmentDigest))throw ye("binding");return Object.freeze({status:t.status,assessmentDigest:t.assessmentDigest,...e?{review:aU(t.review)}:{}})}function lR(n){let e=Object.freeze({account:n.scope.account,installation:n.scope.installation,collection:n.scope.collection});if(Object.values(e).some(t=>!Ql.test(t)||/^0{8}-0{4}-0{4}-0{4}-0{12}$/.test(t))||!Ql.test(n.generation))throw ye("binding");return{scope:e,generation:n.generation,binding:JSON.stringify([e.account,e.installation,e.collection])}}function ec(n){try{return new TextEncoder().encode(JSON.stringify(n)).byteLength<=lU}catch{return!1}}function cR(n,e,t){t=Object.freeze({...t});let i=lR(e),o=!1,s=null,r=null,a=0,c={},l=t.setupTurn,p=()=>{l?.owner===c&&(l.owner=null)},d=()=>{if(o||t.signal.aborted||t.isCurrent()!==!0)throw ye()},u=(m,w,b)=>{d();let g=[1,i.binding,i.generation,m,w,b];if(!ec(g))throw ye("binding");n.postMessage(g)},f=()=>{if(!o){o=!0,p(),n.onmessage=n.onmessageerror=null;try{n.postMessage([1,i.binding,i.generation,0,"closed",null])}catch{}n.close()}},h=()=>{try{f()}finally{t.onProtocolFailure()}};return n.onmessageerror=h,n.onmessage=m=>{let w=m.data;try{if(d(),Array.isArray(w)&&w.length===6&&w[0]===1&&w[1]===i.binding&&w[2]===i.generation&&w[3]===0&&w[4]==="detach"&&w[5]===null){h();return}if(!Array.isArray(w)||w.length!==6||w[0]!==1||w[1]!==i.binding||w[2]!==i.generation||!Number.isInteger(w[3])||w[3]<1||w[3]>4294967295||!uU.includes(w[4])||!ec(w))throw ye("binding");let b=w[3],g=w[4],y=w[5];if(b<=a)throw ye("binding");if(a=b,cU(g)){let k=null;try{let S=t.ledger?.()??null;if(!S)throw ye("recovery_required");if(g==="ledgerList"){if(y!==null)throw ye("binding");k=S.list(dU)}else if(g==="ledgerRemove"){if(typeof y!="string"||!Ql.test(y))throw ye("binding");S.remove(y)}else{if(!Array.isArray(y)||y.length!==2||typeof y[0]!="string"||!Ql.test(y[0])||typeof y[1]!="string"||y[1].length>pU)throw ye("binding");S.put(y[0],y[1])}}catch(S){u(b,"error",S instanceof Ei?S.reason:"recovery_required");return}u(b,"result",k);return}if(s){u(b,"error","busy");return}if(l&&fU(g)&&l.owner!==null&&l.owner!==c){u(b,"error","busy");return}let v=async()=>{d();let k=null;switch(g){case"resourcesAssess":case"resourcesApply":{let S=t.resourceSetup;if(!S)throw ye("recovery_required");if(g==="resourcesAssess"){let x=Array.isArray(y);if(x&&y.length!==2)throw ye("binding");k=x?ta(await S.assess(y[0],t.signal,Oi(y[1])),!0):ta(await S.assess(y,t.signal))}else{if(!Array.isArray(y)||y.length!==2&&y.length!==3||typeof y[1]!="string"||!Ud.test(y[1]))throw ye("binding");k=$t(y.length===3?await S.apply(y[0],y[1],t.signal,Oi(y[2])):await S.apply(y[0],y[1],t.signal))}d();break}case"peopleIdentity":case"peopleMembers":{if(y!==null)throw ye("binding");let S=t.peopleAuthority;if(!S)throw A("upgrade_required","people metadata is unsupported","people_unsupported");let x=()=>{if(d(),S.collection!==i.scope.collection||S.isCurrent()!==!0)throw A("unauthenticated","people scope changed","people_fenced")};x();let P=Xm(g),I=await S.request(P,{signal:t.signal});if(x(),k=Zl(P,I),x(),!ec([1,i.binding,i.generation,b,"result",k]))throw A("unavailable","invalid people response","people_response");break}case"load":if(y!==null)throw ye("binding");p(),k=await t.journal.load(t.signal);break;case"prepare":k=await t.journal.prepare(Zs(y),t.signal),d(),l&&(l.owner=c);break;case"prepareResources":k=await t.journal.prepareResources($t(y),t.signal),d(),l&&(l.owner=c);break;case"prepareResourceRound":if(!Array.isArray(y)||y.length!==2||typeof y[1]!="string")throw ye("binding");k=await t.journal.prepareResourceRound($t(y[0]),y[1],t.signal),d(),l&&(l.owner=c);break;case"assess":if(y!=="ready"&&y!=="setup_required")throw ye("binding");t.assess(y);break;case"foreground":if(typeof y!="boolean")throw ye("binding");t.foreground(y);break;case"recordResourceRejected":{if(typeof y!="string"||!Ql.test(y))throw ye("binding");let S=t.resourceSetup?.rejected;if(!S||await S(y,t.signal)!==!0)throw ye("recovery_required");d(),k=await t.journal.recordResourceRejected(y,t.signal),p();break}default:if(typeof y!="string"||!Ql.test(y))throw ye("binding");k=await t.journal[g](y,t.signal),(g==="recordVerified"||g==="recordResourceVerified")&&p()}d(),u(b,"result",k)},_=s=Promise.resolve().then(v).catch(k=>{if(!(o||t.signal.aborted))try{let S=Xm(g);u(b,"error",S?sR(S,k):k instanceof Ln||k instanceof Ei?k.reason:"recovery_required")}catch{h()}});_.finally(()=>{s===_&&(s=null)}).catch(()=>{})}catch{h()}},n.start(),{close(){return r||(r=Promise.resolve().then(async()=>{f(),await s}),r)}}}function Zm(n,e,t){t=Object.freeze({...t});let i=lR(e),o=!1,s=1,r=null,a=new Map,c=()=>{if(o||t.signal.aborted||t.isCurrent()!==!0)throw ye()},l=()=>{if(o)return;o=!0,t.signal.removeEventListener("abort",l),n.onmessage=n.onmessageerror=null;let v=r;r=null,v?.finish(void 0,ye(z_(v.action)?"fenced":"outcome_unknown"));for(let _ of a.values())_(void 0,ye("fenced"));a.clear();try{n.postMessage([1,i.binding,i.generation,0,"detach",null])}catch{}try{n.close()}finally{t.onClose()}};t.signal.addEventListener("abort",l,{once:!0}),n.onmessageerror=l,n.onmessage=v=>{try{c();let _=v.data;if(!Array.isArray(_)||_.length!==6||_[0]!==1||_[1]!==i.binding||_[2]!==i.generation||!ec(_))throw ye();if(_[3]===0&&_[4]==="closed"&&_[5]===null){l();return}let k=a.get(_[3]);if(k&&["result","error"].includes(_[4])){a.delete(_[3]),k(_[4]==="result"?_[5]:void 0,_[4]==="error"?ye(_[5]==="binding"?"binding":"recovery_required"):void 0);return}if(!r||_[3]!==r.id||!["result","error"].includes(_[4]))throw ye();let S=r,x=_[4]==="error"?Xm(S.action)&&_[5]!=="busy"?aR(_[5]):_[5]==="busy"?ye("busy"):ye(["binding","fenced","recovery_required","outcome_unknown"].includes(_[5])?_[5]:"recovery_required"):void 0;r=null,S.finish(_[4]==="result"?_[5]:void 0,x)}catch{l()}},n.start();let p=(v,_,k)=>{try{if(c(),k.aborted)throw ye();if(r)throw ye("busy");if(s>4294967295)throw l(),ye()}catch(x){return Promise.reject(x)}let S=s++;return new Promise((x,P)=>{let I=!1,O=()=>R(void 0,ye(z_(v)?"fenced":"outcome_unknown")),R=(q,j)=>{I||(I=!0,k.removeEventListener("abort",O),j?P(j):x(q))};r={id:S,action:v,finish:R},k.addEventListener("abort",O,{once:!0});try{let q=[1,i.binding,i.generation,S,v,_];if(!ec(q))throw ye("binding");n.postMessage(q)}catch(q){r=null,R(void 0,q),l()}})},d=(v,_)=>{try{if(c(),s>4294967295)throw l(),ye()}catch(S){return Promise.reject(S)}let k=s++;return new Promise((S,x)=>{a.set(k,(P,I)=>I?x(I):S(P));try{let P=[1,i.binding,i.generation,k,v,_];if(!ec(P))throw ye("binding");n.postMessage(P)}catch(P){a.delete(k),x(P)}})},u=Object.freeze({async list(){let v=await d("ledgerList",null);if(!Array.isArray(v))throw ye("recovery_required");return v.flatMap(_=>{try{let k=nR(JSON.parse(String(_)));return k?[k]:[]}catch{return[]}})},async put(v){await d("ledgerPut",[v.mutationId,JSON.stringify(v)])},async remove(v){await d("ledgerRemove",v)}}),f=(v,_)=>{let k=z_(v)?"fenced":"outcome_unknown";try{if(c(),_.aborted)throw ye()}catch{throw ye(k)}},h=async(v,_,k)=>{let S=await p(v,_,k);f(v,k);let x=Zt(S,i.scope);return f(v,k),x},m=async(v,_,k)=>{let S=await h(v,_,k);if(f(v,k),S.version!==2)throw ye("recovery_required");return S},w=async(v,_,k)=>{let S=await h(v,_,k);if(f(v,k),S.version!==3&&S.version!==4)throw ye("recovery_required");return S},b=Object.freeze({scope:i.scope,async load(v){let _=await p("load",null,v);f("load",v);let k=_===null?null:Zt(_,i.scope);return f("load",v),k},prepare:(v,_)=>m("prepare",Zs(v),_),recordAttempt:(v,_)=>m("recordAttempt",v,_),recordConfirmed:(v,_)=>m("recordConfirmed",v,_),recordVerified:(v,_)=>m("recordVerified",v,_),async prepareResources(v,_){let k=await w("prepareResources",$t(v),_);if(f("prepareResources",_),k.version!==3)throw ye("recovery_required");return k},async prepareResourceRound(v,_,k){let S=await w("prepareResourceRound",[$t(v),_],k);if(f("prepareResourceRound",k),S.version!==4)throw ye("recovery_required");return S},recordResourceAttempt:(v,_)=>w("recordResourceAttempt",v,_),recordResourceConfirmed:(v,_)=>w("recordResourceConfirmed",v,_),recordResourceVerified:(v,_)=>w("recordResourceVerified",v,_),recordResourceRejected:(v,_)=>w("recordResourceRejected",v,_)}),g=t.people===!0?Object.freeze({collection:i.scope.collection,isCurrent(){try{return c(),!0}catch{return!1}},async request(v,_={}){if(v!=="identity"&&v!=="members")throw A("invalid_request","invalid people resource");let k=v==="identity"?"peopleIdentity":"peopleMembers",S=_.signal??t.signal;try{let x=await p(k,null,S);f(k,S);let P=Zl(v,x);return f(k,S),P}catch(x){try{f(k,S)}catch{throw A("unauthenticated","people scope changed","people_fenced")}throw x instanceof Ei?A(x.reason==="busy"?"unavailable":"unauthenticated","people metadata request failed",x.reason==="busy"?"people_busy":"people_fenced"):x}}}):void 0,y=Object.freeze({async assess(v,_,k){let S=k!==void 0,x=await p("resourcesAssess",S?[v,Oi(k)]:v,_);f("resourcesAssess",_);let P=ta(x,S);return f("resourcesAssess",_),P},async apply(v,_,k,S){if(!Ud.test(_))throw ye("binding");let x=await p("resourcesApply",S===void 0?[v,_]:[v,_,Oi(S)],k);f("resourcesApply",k);let P=$t(x);return f("resourcesApply",k),P}});return Object.freeze({journal:b,close:l,resourceSetup:y,ledger:u,...g?{peopleAuthority:g}:{},async assess(v,_){await p("assess",v,_),f("assess",_)},async setForeground(v,_){await p("foreground",v,_),f("foreground",_)}})}var Ud,ea,Tr,jd,lU,Ql,Ei,ye,cU,pU,dU,uU,Xm,z_,fU,ss=C(()=>{"use strict";Qs();re();iR();Ld();Ud=/^sha256:[0-9a-f]{64}$/,ea=n=>!!n&&typeof n=="object"&&!Array.isArray(n)&&Object.getPrototypeOf(n)===Object.prototype,Tr=(n,e=4096)=>typeof n=="string"&&n.length>0&&n.length<=e;jd=(n,e,t=[])=>{let i=e.split(",");return i.every(o=>Object.hasOwn(n,o))&&Object.keys(n).every(o=>i.includes(o)||t.includes(o))};lU=512*1024+8192,Ql=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,Ei=class extends Error{constructor(t){super(`app collection control: ${t}`);this.reason=t;this.name="AppCollectionControlError"}reason},ye=(n="fenced")=>new Ei(n);cU=n=>n==="ledgerList"||n==="ledgerPut"||n==="ledgerRemove",pU=16*1024,dU=448*1024,uU=["load","prepare","prepareResources","prepareResourceRound","recordAttempt","recordConfirmed","recordVerified","recordResourceAttempt","recordResourceConfirmed","recordResourceVerified","recordResourceRejected","assess","foreground","peopleIdentity","peopleMembers","resourcesAssess","resourcesApply","ledgerList","ledgerPut","ledgerRemove"],Xm=n=>n==="peopleIdentity"?"identity":n==="peopleMembers"?"members":null,z_=n=>n==="load"||n==="assess"||n==="foreground"||n==="resourcesAssess"||n==="resourcesApply"||Xm(n)!==null,fU=n=>n==="load"||n==="prepare"||n==="prepareResources"||n==="prepareResourceRound"||n.startsWith("record")});function $_(n){let e=[n.account,n.installation,n.collection];if(e.some(o=>typeof o!="string"||!hU.test(o))||typeof n.isCurrent!="function")throw Pt();let t=JSON.stringify(e.map(o=>o.toLowerCase())),i=n.isCurrent.bind(n);return{binding:t,current:()=>{try{return i()===!0&&JSON.stringify([n.account,n.installation,n.collection].map(o=>o.toLowerCase()))===t}catch{return!1}}}}function uR(n,e,t,i,o){let s=$_(e),r=!1,a=()=>{if(!r){r=!0,n.onmessage=null,n.onmessageerror=null;try{n.postMessage([1,s.binding,"close"])}catch{}n.close(),i()}},c=()=>{if(r||!s.current())throw a(),Pt()};return n.onmessageerror=a,n.onmessage=l=>{try{c();let p=l.data;if(!Array.isArray(p)||p[0]!==1||p[1]!==s.binding)throw Pt();if(p.length===3&&p[2]==="close"){a();return}if(p.length===5&&mU.includes(p[2])){let u=p[2],f=p[3],h=p[4],m=pR(u);if(!o||!Number.isInteger(f)||f<1||f>4294967295||!(h instanceof Uint8Array)||!h.length||h.length>m)throw Pt();c(),o(u,f,h);return}if(p.length!==4||p[2]!=="frame"||!(p[3]instanceof Uint8Array)||p[3].length===0||p[3].length>Lo)throw Pt();let d=we(new Uint8Array(p[3]));c(),t(d)}catch{a()}},n.start(),{close:a,send(l){try{c();let p=fe(l);if(!p.length||p.length>Lo)throw Pt();c(),n.postMessage([1,s.binding,"frame",p],[p.buffer])}catch{throw a(),Pt()}},control(l,p,d){try{c();let u=pR(l);if(!Number.isInteger(p)||p<1||p>4294967295||!(d instanceof Uint8Array)||!d.length||d.length>u||!(d.buffer instanceof ArrayBuffer)||d.byteOffset!==0||d.byteLength!==d.buffer.byteLength)throw Pt();c(),n.postMessage([1,s.binding,l,p,d],[d.buffer])}catch{throw a(),Pt()}},current:c}}function gU(n){if(!(n instanceof Map))return!1;let e=n;return e.get(0)===0&&yU.has(e.get(2))}function Qm(n,e,t,i){if(!$_(t).current())throw Pt();let s;try{s=n.connect({collection:t.collection})}catch{throw e.close(),Pt()}let r;try{r=uR(e,t,c=>{if(s.send(c),i&&gU(c))try{i(c.get(2))}catch{}},()=>s.close(),(c,l,p)=>{let d;try{if(c==="bases-request"&&typeof n.executeBases=="function")d=n.executeBases(s,p);else if((c==="bases-list-views-request"||c==="bases-read-view-source-request")&&typeof n.discoverBases=="function")d=n.discoverBases(s,c==="bases-list-views-request"?"list-views":"read-view-source",p);else throw Pt()}finally{p.fill(0)}try{r.current(),r.control(dR(c),l,d)}catch(u){throw d.byteLength&&d.fill(0),u}}),s.onframe=c=>{try{r.send(c)}catch{}},s.onclose=()=>r.close()}catch{throw s.close(),e.close(),Pt()}let a=Object.freeze({async assess(c,l,p){if(l.throwIfAborted(),r.current(),!n.setupResources)throw Pt();let d=p===void 0?n.setupResources(s,"assess",c):n.setupResources(s,"assess",c,void 0,p);return r.current(),l.throwIfAborted(),d},async apply(c,l,p,d){if(p.throwIfAborted(),r.current(),!n.setupResources)throw Pt();let u=d===void 0?n.setupResources(s,"apply",c,l):n.setupResources(s,"apply",c,l,d);return r.current(),p.throwIfAborted(),u},async rejected(c,l){if(l.throwIfAborted(),r.current(),!n.resourceRejected)return!1;let p=n.resourceRejected(s,c);return r.current(),l.throwIfAborted(),p}});return{close:()=>r.close(),resourceSetup:a}}function ey(n,e){let t=$_(e),i=!1,o=!1,s,r=null,a=[],c=()=>A("cancelled","Bases read cancelled"),l=1;return{description:"app-local",close(){o=!0,s?s.close():n.close()},async open(p,d){if(i)throw Pt();if(!t.current()||d?.aborted||o)throw n.close(),Pt();i=!0;let u,f=s=uR(n,e,w=>u?.onframe?.(w),()=>{let w=r;r=null;let b=a.splice(0);w?.finish(void 0,c());for(let g of b)g.finish(void 0,c());u?.onclose?.(Pt())},(w,b,g)=>{if(!r||w!==r.response||b!==r.id)throw g.fill(0),Pt();let y=r;r=null,y.finish(g),h()});function h(){if(r||a.length===0)return;let w=a.shift();r=w;try{if(f.current(),r!==w){h();return}if(l>4294967295)throw f.close(),Pt();w.id=l++,f.control(w.kind,w.id,w.request)}catch(b){r===w&&(r=null),w.finish(void 0,b),h()}}let m=(w,b,g)=>{try{if(f.current(),g?.aborted)throw c();if(!(b instanceof Uint8Array)||!b.length||b.length>128*1024)throw A("invalid_request","Bases request bytes exceed bound");if(a.length>=32)throw A("unavailable","Bases read queue is full","bases_read_backpressure")}catch(v){return Promise.reject(v)}let y=new Uint8Array(b);return new Promise((v,_)=>{let k=!1,S=(I,O)=>{if(r!==x&&y.byteLength&&y.fill(0),k){I?.byteLength&&I.fill(0);return}k=!0,g?.removeEventListener("abort",P),O!==void 0?_(O):v(I)},x={kind:w,request:y,response:dR(w),finish:S},P=()=>{let I=a.indexOf(x);I!==-1&&a.splice(I,1),r===x&&x.id===void 0&&(r=null),S(void 0,c())};a.push(x),g?.addEventListener("abort",P,{once:!0}),h()})};u={onframe:null,onclose:null,send:w=>f.send(w),close:()=>f.close(),readAppBases:(w,b)=>m("bases-request",w,b),readAppBasesDiscovery(w,b,g){return w!=="list-views"&&w!=="read-view-source"?Promise.reject(A("invalid_request","unknown native Bases read")):m(w==="list-views"?"bases-list-views-request":"bases-read-view-source-request",b,g)}};try{if(d?.aborted||o)throw Pt();return await Dl({connect:()=>u}).open(p,d)}catch{throw f.close(),Pt()}}}}var hU,Pt,mU,dR,pR,yU,ty=C(()=>{"use strict";Je();re();xm();mp();hU=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/iu,Pt=()=>A("unavailable","app local facade unavailable; reopen and reconcile");mU=["bases-request","bases-response","bases-list-views-request","bases-list-views-response","bases-read-view-source-request","bases-read-view-source-response"],dR=n=>n==="bases-request"?"bases-response":n==="bases-list-views-request"?"bases-list-views-response":"bases-read-view-source-response",pR=n=>n.endsWith("request")?128*1024:n==="bases-response"?Lo:1024*1024;yU=new Set(["submit","resolve_hold","open_upload","upload_chunk","commit_upload","abort_upload","fetch_file","read_file","ack_chunks","presence_join","presence_update","presence_leave","subscribe_presence","unsubscribe_presence"])});var tc,B_=C(()=>{"use strict";Je();re();ve();tc=class n{constructor(e){this.instance=e}instance;ports=new Map;timer=null;opened=!1;get x(){if(!this.instance)throw A("unavailable","runtime instance was discarded after an ABI failure");return this.instance}discard(){this.instance=null,this.timer&&clearInterval(this.timer),this.timer=null;for(let e of[...this.ports.values()])e.end();this.ports.clear()}static async instantiate(e){return new n(await this.load(e))}static async load(e,t){let i=null,o=null,s=t?.(()=>{if(!o)throw A("unavailable","runtime imports called before initialization");return o})??{},r=new TextDecoder,a={host_app_sql:(p,d)=>0n,host_now_ms:()=>Date.now(),host_local_date:(p,d,u,f)=>{try{let h=r.decode(new Uint8Array(i.buffer,d,u)),m=new Intl.DateTimeFormat("en-CA",{timeZone:h,year:"numeric",month:"2-digit",day:"2-digit"}).format(p);return/^\d{4}-\d{2}-\d{2}$/.test(m)?(new Uint8Array(i.buffer,f,10).set(new TextEncoder().encode(m)),10):0}catch{return 0}},host_default_zone:(p,d)=>{let u=new TextEncoder().encode(Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"),f=Math.min(u.length,d);return new Uint8Array(i.buffer,p,f).set(u.subarray(0,f)),f},host_random:(p,d)=>{let u=new Uint8Array(i.buffer,p,d);for(let f=0;f<d;f+=65536)globalThis.crypto.getRandomValues(u.subarray(f,f+65536))}},{instance:c}=await WebAssembly.instantiate(e,{env:{...a,...s}}),l=c.exports;return o=l,i=l.memory,l}put(e){if(e.length===0)return[0,0];let t=this.x.alloc(e.length);return new Uint8Array(this.x.memory.buffer,t,e.length).set(e),[t,e.length]}takeOut(e){let t=Number(e>>32n),i=Number(e&0xffffffffn);if(i===0)return new Uint8Array(0);let o=new Uint8Array(this.x.memory.buffer,t,i).slice();return this.x.dealloc(t,i),o}info(){let e=we(this.takeOut(this.x.rt_info())),t=i=>{let[o,s]=i;return{major:o,minor:s}};return{abiMajor:e.get(0),runtimeVersion:e.get(1),sem:t(e.get(2)),serves:e.get(3).map(t)}}open(e){let t=this.x;if(this.opened)throw A("unavailable","runtime is already open");let i=e.queryExecutionProfile,o;if(i!==void 0){if(i!=="memory_constrained"&&i!=="desktop")throw A("invalid_request","unknown query execution profile");if(typeof t.rt_open_profile!="function")throw A("unavailable","runtime does not support explicit query profile initialization");o=i==="memory_constrained"?0:1}let s=zn(new Map([[0,N(e.collection)],[1,N(e.replicaId)],[2,N(e.deviceId)],[3,e.mode==="local_only"?0:1],[4,e.signSecretKey],[5,e.kemSecretKey],[6,e.e2e??!1]])),r;try{let a=this.put(s);r=this.takeOut(o===void 0?t.rt_open(...a):t.rt_open_profile(...a,o))}catch(a){throw this.discard(),a}finally{s.fill(0)}if(r.length)throw A("unavailable",`runtime failed to open: ${new TextDecoder().decode(r)}`);this.markOpened()}markOpened(){this.opened=!0,this.timer??=setInterval(()=>this.tick(),1e3),this.timer.unref?.()}tick(){this.x.rt_tick(Date.now()),this.flush()}connect(e={}){let t=null,i=!1,o=[],s={onframe:null,onclose:null,send:r=>{if(i)throw A("unavailable","port closed");let a=fe(r);if(t===null){let c=e.grant&&e.clientKey?new Uint8Array([...N(e.grant),...e.clientKey]):new Uint8Array(0),l=we(this.takeOut(this.x.rt_hello(...this.put(c),...this.put(a)))),p=BigInt(l[0]),d=we(l[1]);queueMicrotask(()=>{s.onframe?.(d),p===0n&&s.end()}),p!==0n&&(t=p,this.ports.set(p,s),this.flush());return}this.x.rt_frame(t,...this.put(a)),this.flush()},close:()=>{i||(i=!0,t!==null&&(this.ports.delete(t),this.x.rt_close(t)),s.onclose?.())},deliver:r=>s.onframe?s.onframe(r):o.push(r),end:()=>{i||(i=!0,t!==null&&this.ports.delete(t),s.onclose?.())}};return s}sessionForPort(e){for(let[t,i]of this.ports)if(i===e)return t;return null}flush(){let e=this.takeOut(this.x.rt_poll());if(!e.length)return;let t=we(e),i=new Set(t.filter(o=>o[1]===null).map(o=>BigInt(o[0])));for(let o of t){let[s,r]=o,a=this.ports.get(BigInt(s));if(a)if(r===null)a.end();else{let c=we(r);if(i.has(BigInt(s))){if(c instanceof Map){let l=c;l.get(0)===2&&l.get(1)==="closed"&&a.deliver(c)}}else queueMicrotask(()=>a.deliver(c))}}}dispose(){this.timer&&clearInterval(this.timer);for(let e of[...this.ports.values()])e.close()}}});function na(n){if((typeof n!="number"||!Number.isSafeInteger(n))&&typeof n!="bigint")throw new xt("invalid_call");let e=BigInt(n);if(e<0n||e>(1n<<64n)-1n)throw new xt("invalid_call");return e}function ny(n,e){return n.length===e.length&&n.every((t,i)=>t===e[i])}function hR(n){try{return n.server}catch{return null}}function PU(n){try{return n.reason}catch{return null}}function Nd(n,e=globalThis.navigator?.onLine){let t=hR(n);if(rn(t)){let i=t.retryAfterMs;return t.status===429?{kind:"rate_limited",retryAfterMs:i}:t.status>=500?{kind:"server_busy",retryAfterMs:i}:t.status===401||t.status===403?{kind:"auth"}:null}return PU(n)!=="unavailable"?null:e===!1?{kind:"offline"}:{kind:"unreachable"}}var fR,bU,wU,vU,_U,xt,AU,kU,SU,ia,iy=C(()=>{"use strict";gr();Je();ve();ri();fR=16*1024*1024,bU=9*1024*1024,wU=64,vU=64*1024*1024,_U=new Set(["append","read","head","subscribe","unsubscribe","put_object","get_object","has_objects","put_snapshot","get_snapshot","endorse_snapshot","stream_join","stream_leave","stream_send"]),xt=class extends Error{constructor(t){super(`app log host: ${t}`);this.reason=t;this.name="AppLogHostError"}reason};AU=new Set(["read","head","subscribe","get_object","has_objects","put_object","get_snapshot"]),kU=6,SU=new Set(["stream_join","stream_leave","stream_send"]);ia=class{constructor(e,t,i){this.runtime=e;this.transport=t;try{if(this.endpoint=na(i.endpoint),this.collection=N(i.collection),na(t.endpoint)!==this.endpoint||!ny(N(t.collection),this.collection))throw new Error}catch{throw new xt("invalid_binding")}if(this.rounds=i.maxRounds??64,!Number.isSafeInteger(this.rounds)||this.rounds<1||this.rounds>64)throw new RangeError("invalid app log pump rounds")}runtime;transport;abort=new AbortController;endpoint;collection;rounds;work=null;closed=!1;failed=!1;retired=!1;problem=null;terminal=null;health=null;sent=0;readAfter=[-1n,-1n];readAdvances=0;get fenced(){return this.failed}get callsSent(){return this.sent}get readProgress(){return this.readAdvances}responseProgress(){return this.transport.responseProgress?.()??[]}get serverProblem(){return this.problem}get terminalProblem(){return this.terminal}get transportHealth(){return this.health}current(){if(this.closed||this.failed)return!1;if(na(this.transport.endpoint)!==this.endpoint||!ny(N(this.transport.collection),this.collection))throw new xt("invalid_binding");return this.transport.isCurrent()===!0?!0:(this.retire(),!1)}retire(){if(this.closed=!0,this.abort.abort(),!this.retired){this.retired=!0;try{this.runtime.retireLog()}catch{throw this.failed=!0,new xt("fenced")}}}capture(e){if(!Array.isArray(e)||e.length>wU)throw new xt("invalid_call");let t=0,i=new Set,o=[];try{for(let s of e){if(na(s.endpoint)!==this.endpoint||!(s.frame instanceof Uint8Array)||s.frame.length>fR||s.sidecar!==void 0&&(!(s.sidecar instanceof Uint8Array)||s.sidecar.length>bU))throw new xt("invalid_call");if(t+=s.frame.length+(s.sidecar?.length??0),t>vU)throw new xt("invalid_call");let r=we(s.frame);if(!(r instanceof Map))throw new xt("invalid_call");let a=r;if(a.size!==4||a.get(0)!==0||!_U.has(a.get(2)))throw new xt("invalid_call");let c=na(a.get(1));if(i.has(c))throw new xt("invalid_call");i.add(c);let l=a.get(3),p=l instanceof Map?l.get(0):void 0;if(!(p instanceof Uint8Array)||!ny(p,this.collection)||s.sidecar!==void 0&&a.get(2)!=="put_object")throw new xt("invalid_call");if(s.sidecar!==void 0){let u=l,f=u.get(4);if(s.sidecar.length<=1024*1024||na(u.get(3))!==BigInt(s.sidecar.length)||u.has(5)||!(f instanceof Uint8Array)||!ny(f,Ze(s.sidecar)))throw new xt("invalid_call")}let d=a.get(2)==="read"?{after:na(l.get(1)),control:l.get(3)===1}:void 0;o.push({id:c,method:a.get(2),...d?{read:d}:{},call:{endpoint:this.endpoint,frame:s.frame.slice(),...s.sidecar?{sidecar:s.sidecar.slice()}:{}}})}return o}catch{for(let s of o)this.wipe(s);throw new xt("invalid_call")}}wipe(e){e.call.frame.fill(0),e.call.sidecar?.fill(0)}pump(){return this.work?this.work:this.failed?Promise.reject(new xt("fenced")):this.closed?Promise.resolve({quiet:!0}):(this.work=Promise.resolve().then(()=>this.drive()).finally(()=>{this.work=null}),this.work)}async drive(){try{for(let e=0;e<this.rounds;e++){if(!this.current())return{quiet:!0};let t=this.capture(this.runtime.takeLogCalls());if(!t.length)return{quiet:!0};this.sent+=t.length;let i=[];try{for(let o=0;o<t.length;){if(!this.current())return{quiet:!0};let s=o+1,r=l=>AU.has(t[l].method);if(r(o))for(;s<t.length&&s-o<kU&&r(s);)s++;let a=t.slice(o,s);o=s;let c=a.map(l=>this.transport.send(l.call,{signal:this.abort.signal}).then(p=>({reply:p,error:null}),p=>({reply:null,error:p})));i.push(...c);for(let[l,p]of a.entries()){let{reply:d,error:u}=await c[l];if(d===null){if(!this.current())return{quiet:!0};let f=hR(u);if(rn(f)){let m=Rt(f);m&&(this.problem=f),(m||f.status===403&&f.code==="forbidden")&&(this.terminal??=f)}let h=Nd(u);h&&(this.health=h),this.runtime.logNoResponse(p.id);continue}try{if(!this.current())return{quiet:!0};if(!(d instanceof Uint8Array)||d.length>fR){this.runtime.logNoResponse(p.id);continue}if(this.runtime.acceptLogReply(p.id,d)!==!0)this.runtime.logNoResponse(p.id);else if(!SU.has(p.method)&&(this.problem=null,this.health=null,p.read)){let f=p.read.control?1:0;p.read.after>this.readAfter[f]&&(this.readAfter[f]=p.read.after,this.readAdvances++)}}finally{d instanceof Uint8Array&&d.fill(0)}}}}finally{for(let o of await Promise.all(i))o.reply instanceof Uint8Array&&o.reply.fill(0);for(let o of t)this.wipe(o)}}return{quiet:!1}}catch{throw this.failed=!0,this.retire(),new xt("fenced")}}async drainForAuthenticatedReconnect(){if(this.closed||this.failed||this.retired)throw new xt("fenced");if(this.closed=!0,this.abort.abort(),this.retired=!0,await this.work?.catch(()=>{}),this.failed)throw new xt("fenced")}async close(){this.retire(),await this.work?.catch(()=>{})}}});function Dd(n,e,t=0,i={nodes:0}){if(t>32||++i.nodes>65536)throw A("invalid_request","resource DATA exceeds bound");if(n===null||typeof n=="boolean"||typeof n=="string"||typeof n=="number"&&Number.isFinite(n))return n;if(Array.isArray(n))return n.map(r=>Dd(r,e,t+1,i));let o=e?n!==null&&typeof n=="object"&&Object.getPrototypeOf(n)===Object.prototype?Object.entries(n):null:n instanceof Map?[...n]:null;if(!o)throw A("invalid_request","invalid resource DATA");let s=new Map;for(let[r,a]of o){if(typeof r!="string"||s.has(r))throw A("invalid_request","invalid resource DATA");s.set(r,Dd(a,e,t+1,i))}return e?s:Object.fromEntries(s)}function mR(n){if(!(n instanceof Uint8Array)||n.length===0||n.length>64*1024)throw L();return new Uint8Array(n)}function Yn(n){if((typeof n!="number"||!Number.isSafeInteger(n))&&typeof n!="bigint")throw L();let e=BigInt(n);if(e<0n||e>(1n<<64n)-1n)throw L();return e}function an(n){if(!(n instanceof Uint8Array)||n.length!==32)throw L();return n}var as,Lt,L,yR,nc,ry=C(()=>{"use strict";Je();ve();re();B_();tn();iy();ss();Qs();as=class extends Error{reason="account_key_proof_unavailable";constructor(){super("this app runtime cannot prove an account-key request"),this.name="AppAccountKeyProofUnavailableError"}},Lt=class extends Error{reason="strict_device_approval";constructor(){super("this account uses strict device approval; add this device from your desktop"),this.name="AppStrictDeviceApprovalError"}},L=()=>A("unavailable","app runtime unavailable; reopen and reconcile");yR=(n,e)=>n.length===e.length&&n.every((t,i)=>t===e[i]);nc=class n extends tc{constructor(t,i){super(t);this.sqlBinding=i}sqlBinding;attempted=!1;active=!1;retired=!1;collection=null;deviceId=null;connectorId=null;cpPin=null;deviceAttempted=!1;deviceActive=!1;deviceRegistered=!1;devicePin=null;installationId=null;publicIdentity=null;noiseEnvelope=null;cloudSource=null;cloudCallback=null;cloudCollection=null;cloudPurpose=null;cloudIssued=!1;privateAttempted=!1;privateSource=null;prospectiveCollection=null;privatePurpose=null;sasCommitment=null;privateEnrolAcknowledged=!1;endpoint=null;logGeneration=0n;pump=null;transport=null;get sql(){return this.sqlBinding.sql}get app(){return this.x}static async create(t,i){if(i.needsRecovery)throw L();return this.instantiateApp(t,i)}static async createDevice(t){return this.instantiateApp(t,null)}static async instantiateApp(t,i){let o={sql:i,exports:null,run:null},s=await this.load(t,a=>(o.exports=a,o.run=i?.import(a)??null,{host_app_sql:(c,l)=>o.run?.(c,l)??0n})),r=["rt_app_account_key_unlock","rt_app_account_key_status","rt_app_account_key_device_setup","rt_app_private_collection_pin","rt_app_private_enrol_restore","rt_app_private_enrol_commitment","rt_app_private_create_sign","rt_app_private_device_enrol_sign","rt_app_device_open","rt_app_device_registered","rt_app_device_adopt","rt_app_device_retire","rt_app_cp_enrol_sign","rt_app_verify_handover","rt_app_cp_bind_connector","rt_app_cp_log_token_sign","rt_app_open","rt_app_log_bind","rt_app_log_generation","rt_app_log_reconnect","rt_app_log_http_sign","rt_app_log_calls","rt_app_log_reply","rt_app_log_no_response","rt_app_log_retire","rt_app_log_push","rt_app_observations","rt_app_shutdown"];if(!(s.memory instanceof WebAssembly.Memory)||r.some(a=>typeof s[a]!="function"))throw L();return new n(s,o)}open(t){throw L()}fail(){try{(this.active||this.attempted)&&this.sql?.fence()}finally{this.active=!1,this.deviceActive=!1,this.discard()}}guard(t){try{return t()}catch{throw this.fail(),L()}}openAppConsuming(t){let i=null;try{if(this.attempted||this.deviceAttempted||!this.sql||this.sql.needsRecovery)throw L();this.attempted=!0;let o=Yn(t.endpoint);if(!Array.isArray(t.trustedRoots)||t.trustedRoots.length<1||t.trustedRoots.length>64||!Array.isArray(t.trustedSigners)||t.trustedSigners.length>1024||!Number.isSafeInteger(t.sqliteVersion)||t.sqliteVersion<0||t.sqliteVersion>4294967295)throw L();let s=t.state==="e2e"?0:t.state==="cloud_copy"?1:-1,r=t.opened==="fresh"?0:t.opened==="existing"?1:t.opened==="unclean"?2:-1;if(s<0||r<0||typeof t.cloudCopyOptIn!="boolean"||s===1!==t.cloudCopyOptIn||(i=zn(new Map([[0,3],[1,N(t.collection)],[2,N(t.replicaId)],[3,N(t.deviceId)],[4,o],[5,t.trustedRoots.map(an)],[6,t.trustedSigners.map(N)],[7,Ru(t.expectedGenesis)],[8,s],[9,t.cloudCopyOptIn],[10,an(t.signSecretKey)],[11,an(t.kemSecretKey)],[12,r],[13,t.sqliteVersion],[16,mR(t.policyPins)]])),i.length>64*1024)||this.guard(()=>this.takeOut(this.app.rt_app_open(...this.put(i)))).length)throw L();this.collection=t.collection,this.deviceId=t.deviceId,this.endpoint=o,this.active=!0,this.markOpened()}catch{throw this.retireLog(),this.fail(),L()}finally{i?.fill(0),t.signSecretKey?.fill(0),t.kemSecretKey?.fill(0)}}openUnsyncedConsuming(t){let i=null;try{if(this.attempted||this.deviceAttempted||!this.sql||this.sql.needsRecovery||typeof this.app.rt_app_open_local!="function"||(this.attempted=!0,!Number.isSafeInteger(t.sqliteVersion)||t.sqliteVersion<0||t.sqliteVersion>4294967295))throw L();let o=t.opened==="fresh"?0:t.opened==="existing"?1:t.opened==="unclean"?2:-1;if(o<0||(i=zn(new Map([[0,1],[1,N(t.collection)],[2,N(t.replicaId)],[3,N(t.deviceId)],[12,o],[13,t.sqliteVersion]])),this.guard(()=>this.takeOut(this.app.rt_app_open_local(...this.put(i)))).length))throw L();this.collection=t.collection,this.deviceId=t.deviceId,this.active=!0,this.markOpened()}catch{throw this.fail(),L()}finally{i?.fill(0)}}tick(){this.active&&!this.retired&&this.guard(()=>super.tick())}connect(t={}){if(!this.active||this.retired||t.collection!==void 0&&(typeof t.collection!="string"||t.collection.toLowerCase()!==this.collection?.toLowerCase()))throw L();let i=super.connect(t),o=i.send.bind(i),s=i.close.bind(i);return i.send=r=>this.guard(()=>o(r)),i.close=()=>this.guard(()=>s()),i}executeBases(t,i){return this.readBases(t,i,"execute")}discoverBases(t,i,o){if(i!=="list-views"&&i!=="read-view-source")throw L();return this.readBases(t,o,i)}readBases(t,i,o){let s=this.sessionForPort(t),r=o==="execute"?this.app.rt_app_bases_execute:o==="list-views"?this.app.rt_app_bases_list_views:this.app.rt_app_bases_read_view_source;if(!this.active||this.retired||!this.sql||this.sql.needsRecovery||s===null||typeof r!="function")throw L();if(!(i instanceof Uint8Array)||!i.length||i.length>128*1024)throw A("invalid_request","Bases request bytes exceed bound");let a=new Uint8Array(i);try{let c=this.guard(()=>{let l=Yn(r.call(this.app,s,...this.put(a))),p=Number(l&0xffffffffn);if(!p||p>(o==="execute"?16:1)*1024*1024)throw L();return this.takeOut(l)});if(!this.active||this.retired||this.sql.needsRecovery||this.sessionForPort(t)!==s)throw c.fill(0),L();return c}finally{a.fill(0)}}setupResources(t,i,o,s,r){let a=this.sessionForPort(t),c=this.app.rt_app_resources;if(!this.active||this.retired||!this.sql||this.sql.needsRecovery||a===null||typeof c!="function")throw A("unavailable","resource setup unsupported","resource_setup_unsupported");if(i!=="assess"&&i!=="apply"||i==="apply"&&(typeof s!="string"||!/^sha256:[0-9a-f]{64}$/.test(s)))throw L();let l=r!==void 0,p=[1,i==="apply"?1:0,Dd(o,!0),s??null];l&&p.push(Dd(Oi(r),!0));let d=fe(p);if(!d.length||d.length>512*1024)throw d.fill(0),A("invalid_request","resource DATA exceeds bound");let u;try{if(u=this.guard(()=>{let m=Yn(c.call(this.app,a,...this.put(d))),w=Number(m&0xffffffffn);if(!w||w>512*1024)throw L();return this.takeOut(m)}),!this.active||this.retired||this.sql.needsRecovery||this.sessionForPort(t)!==a)throw L();let f=this.guard(()=>we(u));if(!Array.isArray(f)||f.length!==3||f[0]!==1||typeof f[1]!="boolean")throw L();if(f[1]===!1)throw A("unavailable","resource setup unavailable","resource_setup_unavailable");let h=Dd(f[2],!1);return i==="assess"?ta(h,l):$t(h)}finally{d.fill(0),u?.fill(0)}}resourceRejected(t,i){let o=null;try{let s=this.sessionForPort(t),r=this.app.rt_app_receipt_rejected;return!this.active||this.retired||s===null||typeof r!="function"||!/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(i)?!1:(o=N(i),this.guard(()=>r.call(this.app,s,...this.put(o)))===1&&this.active&&!this.retired&&this.sessionForPort(t)===s)}catch{return!1}finally{o?.fill(0)}}verifyHandover(t,i,o){let s=null,r=null;try{let a=this.sessionForPort(t),c=i.collection,l=i.deviceId;if(!this.active||this.retired||a===null||c!==this.collection||i.isCurrent()!==!0||!(o instanceof Uint8Array)||o.length>64*1024)return null;s=new Uint8Array(o),r=N(l);let p=this.guard(()=>this.takeOut(this.app.rt_app_verify_handover(a,...this.put(r),...this.put(s))));if(p.length===0||this.sessionForPort(t)!==a||i.isCurrent()!==!0||i.collection!==c||i.deviceId!==l)return null;let d=this.guard(()=>$u.dec(we(p)));return d.seq===0||[d.chain,d.policyGeneration,d.catalogGeneration].some(u=>u===`sha256:${"00".repeat(32)}`)?null:d}catch{return null}finally{s?.fill(0),r?.fill(0)}}bindCpConnector(t){let i=null;try{if(!this.active||this.retired||this.pump||this.cpPin||t.isCurrent()!==!0||t.deviceId!==this.deviceId||t.collection!==this.collection)throw L();let o=t.connectorId;if(i=N(o),i.every(s=>s===0)||this.guard(()=>this.app.rt_app_cp_bind_connector(...this.put(i)))!==1)throw L();this.connectorId=o,this.cpPin=t}catch{throw L()}finally{i?.fill(0)}}deviceCurrent(){try{let t=this.devicePin;return this.deviceActive&&!this.retired&&t!==null&&t.isCurrent()===!0&&t.connectorId===this.connectorId&&t.deviceId===this.deviceId&&t.installationId===this.installationId}catch{return!1}}publicResult(t){if(t.length>1024)throw L();let i=we(t);if(!(i instanceof Map))throw L();let o=i;if(o.size!==4||[0,1,2,3].some(r=>!o.has(r)))throw L();let s=r=>{let a=o.get(r);if(!(a instanceof Uint8Array)||a.length!==32||a.every(c=>c===0))throw L();return new Uint8Array(a)};return{m:o,identity:Object.freeze({signPublicKey:s(0),kemPublicKey:s(1),noisePublicKey:s(2)})}}openDeviceConsuming(t){let i=null;try{if(this.deviceAttempted||this.attempted||this.retired)throw L();this.deviceAttempted=!0;let o=t.pin;if(this.devicePin=o,this.connectorId=o.connectorId,this.deviceId=o.deviceId,this.installationId=o.installationId,this.deviceActive=!0,!this.deviceCurrent())throw L();let s=[this.connectorId,this.deviceId,this.installationId].map(N);if(s.some(l=>l.every(p=>p===0)))throw L();let r=t.opened;if(r.mode!=="fresh"&&r.mode!=="existing"||r.mode==="existing"&&(!(r.envelope instanceof Uint8Array)||!r.envelope.length||r.envelope.length>1024))throw L();i=zn(new Map([[0,1],[1,s[0]],[2,s[1]],[3,s[2]],[4,r.mode==="fresh"?0:1],[5,an(t.signSecretKey)],[6,an(t.kemSecretKey)],[7,r.mode==="fresh"?new Uint8Array:new Uint8Array(r.envelope)]]));let a=this.guard(()=>this.takeOut(this.app.rt_app_device_open(...this.put(i))));if(!a.length||!this.deviceCurrent())throw L();let c=this.guard(()=>{let{m:l,identity:p}=this.publicResult(a),d=l.get(3);if(!(d instanceof Uint8Array)||!d.length||d.length>1024)throw L();return{...p,envelope:new Uint8Array(d)}});return this.publicIdentity={signPublicKey:new Uint8Array(c.signPublicKey),kemPublicKey:new Uint8Array(c.kemPublicKey),noisePublicKey:new Uint8Array(c.noisePublicKey)},this.noiseEnvelope=new Uint8Array(c.envelope),Object.freeze(c)}catch{throw this.retireLog(),L()}finally{i?.fill(0),t.signSecretKey?.fill(0),t.kemSecretKey?.fill(0)}}deviceCustodyCurrent(t,i){try{return this.deviceCurrent()&&!this.active&&this.publicIdentity!==null&&this.noiseEnvelope!==null&&t.isCurrent()===!0&&t.connectorId===this.connectorId&&t.deviceId===this.deviceId&&t.installationId===this.installationId&&i.envelope instanceof Uint8Array&&i.envelope.length===this.noiseEnvelope.length&&i.envelope.every((o,s)=>o===this.noiseEnvelope[s])&&["signPublicKey","kemPublicKey","noisePublicKey"].every(o=>i[o]instanceof Uint8Array&&i[o].length===32&&i[o].every((s,r)=>s===this.publicIdentity[o][r]))}catch{return!1}}acknowledgeDeviceRegistration(t){let i=null;try{if(!this.deviceCurrent()||this.active||this.deviceRegistered||!this.publicIdentity||t.connectorId!==this.connectorId||t.deviceId!==this.deviceId||t.installationId!==this.installationId)throw L();for(let o of["signPublicKey","kemPublicKey","noisePublicKey"])if(an(t[o]).some((s,r)=>s!==this.publicIdentity[o][r]))throw L();if(i=zn(new Map([[0,N(t.connectorId)],[1,N(t.deviceId)],[2,N(t.installationId)],[3,new Uint8Array(t.signPublicKey)],[4,new Uint8Array(t.kemPublicKey)],[5,new Uint8Array(t.noisePublicKey)]])),this.guard(()=>this.app.rt_app_device_registered(...this.put(i)))!==1||!this.deviceCurrent())throw L();this.deviceRegistered=!0}catch{throw this.retireLog(),L()}finally{i?.fill(0)}}prepareCloudCopyCollection(t){let i=null;try{if(t.approvalMode==="strict")throw new Lt;if(this.cloudSource||this.privateAttempted||!this.deviceCurrent()||!this.deviceRegistered||this.active||t.approvalMode!=="password-ak1"||!["create","join"].includes(t.purpose)||(this.cloudSource=t,this.cloudCallback=t.isCurrent,this.cloudCollection=t.collection,this.cloudPurpose=t.purpose,!this.cloudCopyCollectionCurrent(t)))throw L();let o=N(t.collection);if(o.every(s=>s===0)||(i=zn(new Map([[0,o],[1,t.purpose==="create"?0:1]])),this.guard(()=>this.app.rt_app_cloud_copy_pin(...this.put(i)))!==1||!this.cloudCopyCollectionCurrent(t)))throw L()}catch(o){throw this.retireLog(),o instanceof Lt?o:L()}finally{i?.fill(0)}}cloudCopyCollectionCurrent(t){try{let i=this.cloudSource;return this.deviceCurrent()&&!this.active&&this.deviceRegistered&&i!==null&&(!t||t===i)&&i.isCurrent===this.cloudCallback&&i.isCurrent()===!0&&i.connectorId===this.connectorId&&i.deviceId===this.deviceId&&i.installationId===this.installationId&&i.collection===this.cloudCollection&&i.purpose===this.cloudPurpose&&i.approvalMode==="password-ak1"}catch{return!1}}signCloudCopyCreate(t){return this.signCloudCopy(t,"create")}signCloudCopyJoin(t){return this.signCloudCopy(t,"join")}signCloudCopy(t,i){let o=null,s=null;try{if(this.cloudIssued||!this.cloudCopyCollectionCurrent()||this.cloudPurpose!==i||(this.cloudIssued=!0,o=new Uint8Array(an(t)),s=this.guard(()=>this.takeOut(i==="create"?this.app.rt_app_cloud_copy_create_sign(...this.put(o)):this.app.rt_app_cloud_copy_join_sign(...this.put(o)))),s.length!==64||!this.cloudCopyCollectionCurrent()))throw L();return s}catch{throw s?.fill(0),this.retireLog(),L()}finally{o?.fill(0)}}preparePrivateCollection(t,i){let o=null,s=null;try{if(t.approvalMode==="strict")throw new Lt;if(this.cloudSource||this.privateAttempted||!this.deviceCurrent()||!this.deviceRegistered||this.active||t.approvalMode!=="password-ak1"||!["create","enrol"].includes(t.purpose)||(this.privateAttempted=!0,this.privateSource=t,this.prospectiveCollection=t.collection,this.privatePurpose=t.purpose,!this.privateCollectionCurrent()))throw L();let r=N(t.collection);if(r.every(a=>a===0))throw L();if(i.mode==="fresh"){if(o=zn(new Map([[0,r],[1,t.purpose==="create"?0:1]])),this.guard(()=>this.app.rt_app_private_collection_pin(...this.put(o)))!==1)throw L()}else if(i.mode==="existing"){let a=i.marker,c=this.publicIdentity;if(t.purpose!=="enrol"||!c||a.collection!==t.collection||a.connectorId!==this.connectorId||a.deviceId!==this.deviceId||a.installationId!==this.installationId||typeof a.acknowledged!="boolean")throw L();for(let p of["signPublicKey","kemPublicKey","noisePublicKey"])if(!yR(an(a[p]),c[p]))throw L();let l=new Uint8Array(an(a.sasCommitment));if(l.every(p=>p===0)||(s=l,o=zn(new Map([[0,1],[1,r],[2,N(a.connectorId)],[3,N(a.deviceId)],[4,N(a.installationId)],[5,new Uint8Array(a.signPublicKey)],[6,new Uint8Array(a.kemPublicKey)],[7,new Uint8Array(a.noisePublicKey)],[8,l],[9,a.acknowledged]])),this.privateEnrolAcknowledged=a.acknowledged,this.guard(()=>this.app.rt_app_private_enrol_restore(...this.put(o)))!==1))throw L()}else throw L();if(!this.privateCollectionCurrent())throw L();if(t.purpose==="enrol"){let a=this.guard(()=>this.takeOut(this.app.rt_app_private_enrol_commitment()));if(a.length!==32||a.every(c=>c===0)||s!==null&&!yR(a,s))throw L();this.sasCommitment=new Uint8Array(a)}}catch(r){throw this.retireLog(),r instanceof Lt?r:L()}finally{o?.fill(0)}}registeredDeviceReceipt(){if(!this.deviceCurrent()||!this.deviceRegistered||!this.publicIdentity)throw L();let t=this.publicIdentity;return Object.freeze({connectorId:this.connectorId,deviceId:this.deviceId,installationId:this.installationId,signPublicKey:new Uint8Array(t.signPublicKey),kemPublicKey:new Uint8Array(t.kemPublicKey),noisePublicKey:new Uint8Array(t.noisePublicKey)})}privateEnrolMarker(){if(!this.privateCollectionCurrent()||this.privatePurpose!=="enrol"||!this.sasCommitment||!this.publicIdentity)throw L();let t=this.publicIdentity;return Object.freeze({connectorId:this.connectorId,deviceId:this.deviceId,installationId:this.installationId,collection:this.prospectiveCollection,sasCommitment:new Uint8Array(this.sasCommitment),acknowledged:this.privateEnrolAcknowledged,signPublicKey:new Uint8Array(t.signPublicKey),kemPublicKey:new Uint8Array(t.kemPublicKey),noisePublicKey:new Uint8Array(t.noisePublicKey)})}privateCollectionCurrent(t){try{if(t&&(t.isCurrent()!==!0||t.connectorId!==this.connectorId||t.deviceId!==this.deviceId||t.installationId!==this.installationId||t.collection!==this.prospectiveCollection||t.purpose!==this.privatePurpose||t.approvalMode!=="password-ak1"))return!1;let i=this.privateSource;return this.deviceCurrent()&&!this.active&&this.deviceRegistered&&i!==null&&i.isCurrent()===!0&&i.connectorId===this.connectorId&&i.deviceId===this.deviceId&&i.installationId===this.installationId&&i.collection===this.prospectiveCollection&&i.purpose===this.privatePurpose&&i.approvalMode==="password-ak1"}catch{return!1}}signPrivateCreate(t){let i=null;try{if(!this.privateCollectionCurrent()||this.privatePurpose!=="create")throw L();i=new Uint8Array(an(t));let o=this.guard(()=>this.takeOut(this.app.rt_app_private_create_sign(...this.put(i))));if(o.length!==64||!this.privateCollectionCurrent())throw L();return o}catch{throw this.retireLog(),L()}finally{i?.fill(0)}}signPrivateDeviceEnrol(t){let i=null;try{if(!this.privateCollectionCurrent()||this.privatePurpose!=="enrol"||!this.sasCommitment||this.privateEnrolAcknowledged)throw L();i=new Uint8Array(an(t));let o=this.guard(()=>this.takeOut(this.app.rt_app_private_device_enrol_sign(...this.put(i))));if(o.length!==64||!this.privateCollectionCurrent())throw L();return Object.freeze({signature:o,sasCommitment:new Uint8Array(this.sasCommitment)})}catch{throw this.retireLog(),L()}finally{i?.fill(0)}}adoptDevice(t,i){let o=null;try{if(!this.deviceCurrent()||!this.deviceRegistered||this.attempted||this.active||t.deviceId!==this.deviceId||this.privateSource&&(!this.privateCollectionCurrent()||t.collection!==this.prospectiveCollection)||this.cloudSource&&(!this.cloudCopyCollectionCurrent()||t.collection!==this.cloudCollection||t.state!=="cloud_copy"||t.cloudCopyOptIn!==!0))throw L();let s=mR(t.policyPins);if(i){if(this.sql||i.needsRecovery||!this.sqlBinding.exports)throw L();this.sqlBinding.sql=i,this.sqlBinding.run=i.import(this.sqlBinding.exports)}if(!this.sql||this.sql.needsRecovery)throw L();this.attempted=!0;let r=Yn(t.endpoint),a=t.state==="e2e"?0:t.state==="cloud_copy"?1:-1,c=t.opened==="fresh"?0:t.opened==="existing"?1:t.opened==="unclean"?2:-1;if(a<0||c<0||typeof t.cloudCopyOptIn!="boolean"||a===1!==t.cloudCopyOptIn||!Array.isArray(t.trustedRoots)||t.trustedRoots.length<1||t.trustedRoots.length>64||!Array.isArray(t.trustedSigners)||t.trustedSigners.length>1024||!Number.isSafeInteger(t.sqliteVersion)||t.sqliteVersion<0||t.sqliteVersion>4294967295||(o=zn(new Map([[0,4],[1,N(t.collection)],[2,N(t.replicaId)],[3,N(t.deviceId)],[4,r],[5,t.trustedRoots.map(an)],[6,t.trustedSigners.map(N)],[7,Ru(t.expectedGenesis)],[8,a],[9,t.cloudCopyOptIn],[10,null],[11,null],[12,c],[13,t.sqliteVersion],[14,N(this.connectorId)],[15,N(this.installationId)],[16,s]])),o.length>64*1024)||this.guard(()=>this.takeOut(this.app.rt_app_device_adopt(...this.put(o)))).length||!this.deviceCurrent())throw L();this.collection=t.collection,this.endpoint=r,this.active=!0,this.markOpened()}catch{throw this.retireLog(),this.fail(),L()}finally{o?.fill(0)}}signCpEnrol(t){let i=null;try{if(!this.deviceCurrent()||!this.publicIdentity||this.active||this.pump)throw this.retireLog(),L();i=new Uint8Array(an(t));let o=this.guard(()=>this.takeOut(this.app.rt_app_cp_enrol_sign(...this.put(i))));if(!this.deviceCurrent())throw this.retireLog(),L();if(!o.length)throw L();let{m:s,identity:r}=this.guard(()=>this.publicResult(o)),a=s.get(3);if(!(a instanceof Uint8Array)||a.length!==64||["signPublicKey","kemPublicKey","noisePublicKey"].some(c=>r[c].some((l,p)=>l!==this.publicIdentity[c][p])))throw L();return Object.freeze({...r,signature:new Uint8Array(a)})}catch{throw this.retireLog(),L()}finally{i?.fill(0)}}signCpLogToken(t){let i=null;try{if(!this.active||this.retired||!this.cpPin)throw L();let o=this.cpPin,s=!1;try{s=o.isCurrent()===!0&&o.connectorId===this.connectorId&&o.deviceId===this.deviceId&&o.collection===this.collection}catch{}if(!s)throw this.retireLog(),L();i=new Uint8Array(an(t));let r=this.guard(()=>this.takeOut(this.app.rt_app_cp_log_token_sign(...this.put(i))));if(r.length!==64)throw r.fill(0),L();return r}catch{throw L()}finally{i?.fill(0)}}bindLogTransport(t){try{if(!this.active||this.retired||this.pump||this.endpoint===null||this.collection===null||t.isCurrent()!==!0||Yn(t.endpoint)!==this.endpoint||t.collection!==this.collection)throw L()}catch{throw L()}let i=N(this.collection);if(this.guard(()=>this.app.rt_app_log_bind(this.endpoint,...this.put(i)))!==1)throw L();if(this.logGeneration=this.guard(()=>Yn(this.app.rt_app_log_generation())),this.logGeneration===0n)throw this.retireLog(),L();return this.pump=new ia(this,t,{endpoint:this.endpoint,collection:this.collection}),this.transport=t,this.pump}requestLogHead(){return!this.active||this.retired||this.pump===null||typeof this.app.rt_app_log_head!="function"?!1:this.guard(()=>this.app.rt_app_log_head())===1}get supportsLogPush(){return typeof this.app.rt_app_log_hello_sign=="function"}signLogHello(t,i){let o=null;try{if(!this.supportsLogPush||!this.active||this.retired||!this.pump||!this.transport||this.logGeneration===0n||!this.transport.isCurrent()||!(t instanceof Uint8Array)||t.length!==32||typeof i!="string"||i.length===0||i.length>16*1024||/[^\x21-\x7e]/.test(i))return null;let s=new TextEncoder().encode(i);o=new Uint8Array(32+s.length),o.set(t,0),o.set(s,32),s.fill(0);let r=this.logGeneration,a=this.guard(()=>this.takeOut(this.app.rt_app_log_hello_sign(r,...this.put(o))));return a.length!==64?(a.fill(0),null):a}catch{return null}finally{o?.fill(0)}}setLogStreamLink(t){return!this.active||this.retired||!this.pump||typeof this.app.rt_app_log_stream_link!="function"?!1:this.guard(()=>this.app.rt_app_log_stream_link(t?1:0))===1}async reconnectLogTransport(t){let i=this.pump,o=this.logGeneration,s=()=>this.active&&!this.retired&&this.pump===i&&i!==null&&this.transport===t&&t.isCurrent()===!0&&Yn(t.endpoint)===this.endpoint&&t.collection===this.collection;try{if(!s()||(await i.drainForAuthenticatedReconnect(),!s()))throw L();this.pump=null,this.transport=null;let r=N(this.collection);try{if(this.guard(()=>this.app.rt_app_log_reconnect(this.endpoint,...this.put(r)))!==1)throw L()}finally{r.fill(0)}if(this.logGeneration=this.guard(()=>Yn(this.app.rt_app_log_generation())),this.logGeneration<=o||!t.isCurrent()||this.retired||!this.active)throw L();return this.pump=new ia(this,t,{endpoint:this.endpoint,collection:this.collection}),this.transport=t,this.pump}catch{throw this.retireLog(),L()}}signLogHttp(t){let i=null;try{if(!this.active||!this.pump||!this.transport||this.logGeneration===0n||this.endpoint===null||t.path!=="/v1/rpc"||t.collection!==this.collection||Yn(t.endpoint)!==this.endpoint||!this.transport.isCurrent()||!(t.frame instanceof Uint8Array)||t.frame.length===0||t.frame.length>16*1024*1024||!(t.nonce instanceof Uint8Array)||t.nonce.length!==32||typeof t.token!="string"||t.token.length===0||t.token.length>16*1024||/[^\x21-\x7e]/.test(t.token))throw L();i=zn(new Map([[0,t.frame],[1,t.token],[2,t.nonce]]));let o=this.guard(()=>this.takeOut(this.app.rt_app_log_http_sign(this.endpoint,this.logGeneration,Yn(t.originalCallId),...this.put(i))));if(o.length!==64)throw o.fill(0),L();return o}catch{throw L()}finally{i?.fill(0)}}takeLogCalls(){return!this.active||this.retired?[]:this.guard(()=>{let t=this.takeOut(this.app.rt_app_log_calls());if(!t.length)return[];let i=we(t);if(!Array.isArray(i)||i.length>64)throw L();return i.map(o=>{if(!(o instanceof Map))throw L();let s=o,r=s.get(0),a=s.get(1),c=s.get(2);if(Yn(r)!==this.endpoint||!(a instanceof Uint8Array)||c!==void 0&&!(c instanceof Uint8Array))throw L();return{endpoint:r,frame:a,...c!==void 0?{sidecar:c}:{}}})})}acceptLogReply(t,i){return!this.active||this.retired?!1:this.guard(()=>this.app.rt_app_log_reply(Yn(t),...this.put(i))===1)}logNoResponse(t){this.active&&!this.retired&&this.guard(()=>this.app.rt_app_log_no_response(Yn(t)))}retireLog(){this.logGeneration=0n,!this.retired&&(this.retired=!0,this.cpPin=null,this.connectorId=null,this.devicePin=null,this.installationId=null,this.privateSource=null,this.prospectiveCollection=null,this.privatePurpose=null,this.sasCommitment?.fill(0),this.sasCommitment=null,this.publicIdentity=null,this.noiseEnvelope?.fill(0),this.noiseEnvelope=null,this.deviceActive=!1,this.deviceRegistered=!1,this.active?this.guard(()=>{super.dispose(),this.app.rt_app_log_retire()}):this.deviceAttempted&&this.guard(()=>this.app.rt_app_device_retire()))}pushLog(t){return!this.active||this.retired||!this.pump||!this.transport?!1:this.guard(()=>{let i=this.transport;return i.isCurrent()!==!0||Yn(i.endpoint)!==this.endpoint||i.collection!==this.collection?(this.retireLog(),!1):this.app.rt_app_log_push(...this.put(t))===1})}accountKeyCurrent(t){try{return this.active&&!this.retired&&t.isCurrent()===!0&&t.approvalMode==="password-ak1"&&t.collection===this.collection&&t.deviceId===this.deviceId&&t.connectorId===this.connectorId&&t.installationId===this.installationId&&this.devicePin!==null&&this.devicePin.isCurrent()===!0&&this.devicePin.connectorId===this.connectorId&&this.devicePin.deviceId===this.deviceId&&this.devicePin.installationId===this.installationId}catch{return!1}}accountKeyState(t){let i=we(t);if(!(i instanceof Map))throw L();let o=i;if(o.size!==2||!o.has(0)||!o.has(1))throw L();let s=o.get(0),r=o.get(1);if(s===0||s===1){if(r!==null)throw L();return Object.freeze({state:s===0?"pending":"keyed"})}if(s!==2||typeof r!="string"||!["not_private","not_ready","not_enrolled","not_authorized","device_missing","enrolment_mismatch","not_keyed","no_wrap","inconsistent","failed","outcome_unknown"].includes(r))throw L();return Object.freeze({state:"refused",reason:r})}unlockAccountKeyConsuming(t,i){try{if(t.approvalMode==="strict")throw new Lt;if(!this.accountKeyCurrent(t))throw L();an(i);let o=this.guard(()=>this.accountKeyState(this.takeOut(this.app.rt_app_account_key_unlock(...this.put(i)))));if(!this.accountKeyCurrent(t))throw L();return o}catch(o){throw this.retireLog(),o instanceof Lt?o:L()}finally{i instanceof Uint8Array&&i.fill(0)}}setupAccountKeyDeviceConsuming(t,i){try{if(t.approvalMode==="strict")throw new Lt;if(!this.accountKeyCurrent(t))throw L();an(i);let o=this.guard(()=>this.accountKeyState(this.takeOut(this.app.rt_app_account_key_device_setup(...this.put(i)))));if(!this.accountKeyCurrent(t))throw L();return o.state==="refused"?o:Object.freeze({state:o.state==="keyed"?"recovery_keyed":"recovery_pending"})}catch(o){throw this.retireLog(),o instanceof Lt?o:L()}finally{i instanceof Uint8Array&&i.fill(0)}}get supportsAccountKeyFetchProof(){return typeof this.app.rt_app_account_key_fetch_sign=="function"}signAccountKeyFetch(t,i,o){let s=this.app.rt_app_account_key_fetch_sign;if(typeof s!="function")throw new as;let r=null,a=null;try{if(t.approvalMode==="strict")throw new Lt;if(!this.accountKeyCurrent(t)||(a=N(i),a.every(l=>l===0)))throw L();r=zn(new Map([[0,new Uint8Array(an(o))],[1,a]]));let c=this.guard(()=>this.takeOut(s(...this.put(r))));if(c.length!==64||!this.accountKeyCurrent(t))throw c.fill(0),L();return c}catch(c){throw this.retireLog(),c instanceof Lt?c:L()}finally{r?.fill(0),a?.fill(0)}}accountKeyStatus(t){try{if(!this.accountKeyCurrent(t))throw L();let i=this.guard(()=>this.accountKeyState(this.takeOut(this.app.rt_app_account_key_status())));if(!this.accountKeyCurrent(t))throw L();return i}catch{throw this.retireLog(),L()}}observations(){if(!this.active||this.retired)throw L();return this.guard(()=>{let t=we(this.takeOut(this.app.rt_app_observations()));if(!(t instanceof Map))throw L();let i=t;for(let o of[1,2,3,4])if(typeof i.get(o)!="boolean")throw L();return{status:Jr.dec(i.get(0)),keyringRebuilding:i.get(1),keyringRebuildFailed:i.get(2),snapshotInstallAvailable:i.get(3),requiresReopen:i.get(4)}})}async close(){return this.pump&&(await this.pump.close(),this.pump=null,this.transport=null),this.shutdown()}shutdown(){if(!this.active)return this.deviceAttempted&&!this.retired&&this.retireLog(),this.discard(),!1;if(this.pump)return this.pump.close().catch(()=>{}),this.fail(),!1;try{return this.retireLog(),super.dispose(),this.guard(()=>this.app.rt_app_shutdown()===1)&&this.sql!==null&&!this.sql.needsRecovery}finally{this.active=!1,this.discard()}}dispose(){this.shutdown()}}});function ay(n){let e=n.manifest.requirements.files;if(!e)return null;let t=e.optional??[];return Object.freeze({required:Object.freeze((n.files?.actions??[]).filter(i=>!t.includes(i))),optional:Object.freeze([...t])})}function ly(n,e){return n.collections.find(t=>t.collectionId===e)?.fileActions??[]}function PR(n,e){let t=i=>n.required.includes(i)||n.optional.includes(i)&&e().includes(i);return Object.freeze({allows:t,check(i){if(!t(i))throw SR(i,n.optional.includes(i))}})}function xR(n,e,t,i){let o=e?.files,s=t?.reason;if(!Array.isArray(o)||!o.length||o.some(a=>!Y_.includes(a))||new Set(o).size!==o.length)throw A("invalid_request","Invalid file actions","access_invalid");if(typeof s!="string"||!s.trim()||s.length>140||/[\u0000-\u001f\u007f\u2028\u2029]/.test(s))throw A("invalid_request","Reason must be one line, 1-140 characters","access_invalid");let r=[];for(let a of o)if(!n?.required.includes(a)){if(!n?.optional.includes(a))throw SR(a,!1);i.includes(a)||r.push(a)}return Object.freeze(r)}function IR(n,e,t){let i=n.grant?.actions??[...new Set([...e?.required??[],...t])];return Object.freeze({status:"granted",actions:Object.freeze([...i])})}function jU(n,e){return new Promise(t=>{let i=0,o=a=>{clearInterval(r),n.removeEventListener("abort",s),t(a)},s=()=>o(!1),r=setInterval(()=>{e.closed?o(!0):++i>=3&&o(!1)},500);n.addEventListener("abort",s,{once:!0})})}async function CR(n,e,t,i=t){let o=p=>{try{e.close()}catch{}return p},s=p=>i?.aborted?H_("aborted"):G_(p),r;try{r=await n.start()}catch(p){if(t.aborted)return o(s(null));throw p}let a=r.fileAccess?.requestId??null,c=0,l=!1;for(;;){let p=n.native().fileAccess;if(!a||p?.requestId!==a)return o(t.aborted?s(a):G_(a));if(p.state==="granted")return o(n.granted());if(p.state==="declined")return o(LU);if(p.state==="expired")return o(H_("expired"));if(t.aborted)return o(s(a));if(l)return o(H_("closed"));let d=await jU(t,e);if(t.aborted)return o(s(a));try{await n.poll(a),l=d}catch{if(t.aborted)return o(s(a));if(d&&++c===3)return o(G_(a))}}}var Y_,SR,H_,G_,LU,zd=C(()=>{"use strict";re();Y_=["list","read","add","replace","move","delete"];SR=(n,e)=>e?A("forbidden",`File action ${n} needs requestAccess first`,"access_required"):A("forbidden",`File action ${n} is not declared`,"access_undeclared");H_=n=>Object.freeze({status:"cancelled",reason:n}),G_=n=>Object.freeze({status:"outcome_unknown",requestId:n}),LU=Object.freeze({status:"declined"})});async function MR(n,e){try{return Object.freeze({outcome:"applied",snapshot:await n})}catch(t){if(J(t,"conflict")&&t.reason==="setup_changed")return Object.freeze({outcome:"changed",snapshot:e()});if(J(t,"outcome_unknown"))return Object.freeze({outcome:"unknown",snapshot:e()});throw t}}function BU(n){return n==="contract"?{key:"contract",the:"the shared format for this app's notes",bare:"shared format for this app's notes",many:"shared formats for this app's notes"}:n==="type"?{key:"type",the:"the note type for this app",bare:"note type for this app",many:"note types for this app"}:n==="schema"?{key:"schema",the:"the set of checks for this app's note properties",bare:"set of checks for this app's note properties",many:"sets of checks for this app's note properties"}:{key:"other",the:"the setup item this app needs",bare:"setup item this app needs",many:"setup items this app needs"}}function fy(n){if(n===void 0)return Object.freeze([]);if(!Array.isArray(n)||n.length>DU)throw new TypeError("setup records: at most 32 { path, document } entries");let e=new Set,t=new TextEncoder,i=0;return Object.freeze(n.map(o=>{let s=o?.path,r=o?.document;if(typeof s!="string"||!/\.md$/i.test(s)||s.length>1024||s.startsWith("/")||s.split("/").some(a=>!a||a==="."||a==="..")||e.has(s.toLowerCase())||typeof r!="string"||!r.length||(i+=t.encode(r).length+t.encode(s).length)>zU)throw new TypeError("setup records: each needs a unique relative .md path and a document (256 KiB in total)");return e.add(s.toLowerCase()),Object.freeze({path:s,document:r})}))}function LR(n,e){return n.status!=="current"||n.refusal||e.facets.contracts.assessment?.status!=="setup_required"?n:Object.freeze({...n,status:"conflict",summary:TR,refusal:Object.freeze({code:"setup_unresolved",message:TR})})}function Bd(n,e){let t=n.review,i=n.status==="current"?"current":n.status==="conflict"?"conflict":"setup",o=[],s={},r=new Set(t.staged.map(w=>w.path)),a=new Map,c=0,l=!1,p=(w,b,g,y,v,_=1)=>{c+=_,v&&(l=!0);let k=a.get(w);k?(k.count+=_,k.targets.includes(g)||k.targets.push(g)):a.set(w,{kind:b,targets:[g],count:_,message:y})};for(let w of t.packs)for(let b of w.resources){let g=BU(b.kind),y=`T${g.the.slice(1)}`,v=b.kind==="contract"?", so other apps can work with them":"",_=k=>k===1?g.the:`${k} ${g.many}`;switch(b.action){case"create":p(`resource:create:${g.key}`,"create",b.target,k=>`Add ${_(k)}${v}.`,!1);break;case"update":p(`resource:update:${g.key}`,"update",b.target,k=>`Update ${_(k)}.`,!0);break;case"delete":p(`resource:delete:${g.key}`,"delete",b.target,k=>`Remove ${_(k)}, which this app no longer uses.`,!0);break;case"adopt":r.has(b.target)?p(`resource:adopt-replace:${g.key}`,"adopt",b.target,k=>k===1?`Replace ${g.the} with this app's version.`:`Replace ${k} ${g.many} with this app's versions.`,!0):p(`resource:adopt-match:${g.key}`,"adopt",b.target,k=>k===1?`Use your existing ${g.bare}, which already matches this app's.`:`Use your ${k} existing ${g.many}, which already match this app's.`,!1);break;case"preserve":case"conflict":{if(b.action==="preserve"&&b.reason===void 0)break;let k=b.mode==="seed",S=b.currentDigest!==void 0;S&&(s[b.target]=b.currentDigest),o.push({target:b.target,...S?{adoptable:{digest:b.currentDigest}}:{},message:k&&b.kind==="type"&&!b.installed?`The existing note type at "${b.target}" differs from the one this app needs. ${S?"You can replace it with this app's version.":"Existing notes use this type, so setup won't replace it automatically. Change the existing type to support this app, or rename it and update the notes that use it. Then run setup again."}`:k&&b.kind==="type"&&!S?`Your ${g.bare} has changes that can't be updated automatically while existing notes use it. Update "${b.target}" to support this app (for example, in the app or editor that manages it), then try setup again.`:S&&k?`Your ${g.bare} has changes that can't be combined with the version this app needs. You can replace it with this app's version.`:S&&b.installed?`${y} was changed after this app set it up. You can replace it with this app's version.`:S?`This collection already has a ${g.bare} that differs from the one this app needs. You can replace it with this app's version.`:b.installed?`${y} was changed after this app set it up, so it can't be updated automatically.`:`${y} can't be set up automatically.`});break}default:break}}for(let w of t.configuration){let b=FU(w.path);if(w.action==="add")if(b==="include")p("setting:include","setting",b,()=>"Include this app's files when reading the collection.",!0);else if(b==="record extensions"&&typeof w.value=="string"){let g=w.value.replace(/^\./,"");p(`setting:ext:${g}`,"setting",b,()=>`Read .${g} files as notes in this collection.`,!0)}else p("setting:other","setting",b,g=>g===1?"Adjust a collection setting this app needs.":`Adjust ${g} collection settings this app needs.`,!0);else o.push({target:b,message:"A collection setting differs from what this app needs, so it can't be changed automatically."})}let d=i==="current"?[]:e.records.map(w=>Object.freeze({path:w.path,action:w.free?"create":"skip"}));for(let w of d)w.action==="create"&&p(`record:${w.path}`,"record",w.path,()=>`Create the starter note "${$U(w.path)}".`,!1);if(e.promoted){let w=e.promoted;p("record:existing-files","record","Existing files",()=>`Recognize ${w} existing ${w===1?"file":"files"} as notes, preserving their contents.`,!0,1)}i==="setup"&&a.size===0&&o.length===0&&p("update:setup-record","update","Setup record",()=>"Update this collection's record of this app's setup. Your notes and note types stay as they are.",!0);let u=[...a.values()].map(w=>({kind:w.kind,target:w.targets.join(", "),message:w.message(w.count)}));i==="current"&&o.length&&(i="conflict");let f=(e.newer?.major.length??0)>0||t.packs.some(w=>w.installedVersion&&Ns(w.installedVersion,w.version)==="installed_newer_major"),h;i!=="current"&&!e.canManage?h={code:"setup_forbidden",message:"This app doesn't have permission to set up this collection."}:f?h={code:"installed_newer",message:"A newer version of this app set up this collection. Update the app to continue."}:o.length?h={code:"setup_conflict",message:o.length===Object.keys(s).length?`${o.length===1?"One item differs":`${o.length} items differ`} from what this app needs. Choose whether to use this app's version to continue.`:"Some items can't be set up automatically. Resolve them, then try again."}:d.some(w=>w.action==="create")&&!e.canCreateRecords&&(h={code:"setup_records_forbidden",message:"This app doesn't have permission to create notes in this collection."});let m=i==="current"?"Everything this app needs is already set up.":h?h.message:`This app will make ${VU(c,"change")} to this collection.${l?"":" Nothing already in it is changed."}`;return Object.freeze({status:i,canApply:i==="setup"&&h===void 0,digest:n.assessmentDigest,summary:m,changes:Object.freeze(u.map(w=>Object.freeze(w))),conflicts:Object.freeze(o.map(w=>Object.freeze(w))),adoptable:Object.freeze(s),packs:Object.freeze([...t.packs.map(w=>Object.freeze({id:w.id,version:w.version,status:w.status,...w.installedVersion?{installedVersion:w.installedVersion,relation:Ns(w.installedVersion,w.version)}:{}})),...(e.newer?.kept??[]).map(w=>Object.freeze({id:w.id,version:w.version,status:"current",installedVersion:w.installedVersion,relation:"installed_newer"}))]),staged:t.staged,records:Object.freeze(d),...h?{refusal:Object.freeze(h)}:{}})}var DU,zU,$U,VU,FU,TR,hy=C(()=>{"use strict";re();th();DU=32,zU=256*1024,$U=n=>(n.split("/").pop()??n).replace(/\.(md|ya?ml|json)$/i,"");VU=(n,e,t=`${e}s`)=>`${n} ${n===1?e:t}`,FU=n=>(n.split("/").filter(Boolean).pop()??n).replace(/[_-]+/g," ");TR="This collection is missing a note format this app needs. Add or update a note type that supports that format, then try setup again."});function eA(n){let e=typeof n=="number"&&Number.isInteger(n)&&n>=1e3&&n<=4999?n:null;return Object.freeze({closeCode:e,closeClass:e===null?"unknown":HU[e]??"other"})}function $R(n){try{let e=de(n,"relayCloseCode");if(e!==void 0)return eA(e)}catch{}}var HU,tA=C(()=>{"use strict";un();HU={1e3:"normal",1001:"going_away",1002:"protocol_error",1003:"unsupported_data",1005:"no_status",1006:"abnormal",1007:"invalid_payload",1008:"policy_violation",1009:"message_too_big",1010:"extension_required",1011:"internal_error",1012:"service_restart",1013:"try_again_later",1014:"bad_gateway",1015:"tls_failure",4e3:"pipe_closed",4401:"unauthenticated",4403:"grant_inactive",4404:"connector_offline",4429:"connector_busy"}});function BR(){throw A("unavailable","SDK release trust unavailable: package authenticated LAB or production inputs","application_release_trust_unavailable")}var VR=C(()=>{"use strict";re()});function nA(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in n&&n.BYTES_PER_ELEMENT===1}function yy(n,e=""){if(typeof n!="boolean")throw new TypeError(my(e)+"expected boolean, got type="+typeof n);return n}function ra(n,e=""){if(typeof n!="number")throw new TypeError(my(e)+"expected number, got "+typeof n);if(!Number.isSafeInteger(n)||n<0)throw new RangeError(my(e)+"expected integer >= 0, got "+n);return n}function qt(n,e,t=""){if(nA(n)&&(e===void 0||n.length===e))return n;e!==void 0&&ra(e,"length");let i=nA(n),o=e!==void 0?` of length ${e}`:"",s=i?`length=${n.length}`:`type=${typeof n}`,r=my(t)+"expected Uint8Array"+o+", got "+s;throw i?new RangeError(r):new TypeError(r)}function iA(n,e=!0){if(n.destroyed)throw new Error("hash was destroyed");if(e&&n.finished)throw new Error("digest() was already called")}function KR(n,e){qt(n,void 0,"output");let t=e.outputLen;if(!(n.length>=t))throw new RangeError('"output" expected length >= '+t)}function Lr(n){return new Uint32Array(n.buffer,n.byteOffset,Math.floor(n.byteLength/4))}function ui(...n){for(let e=0;e<n.length;e++)n[e].fill(0)}function GU(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function YU(n){return n<<24&4278190080|n<<8&16711680|n>>>8&65280|n>>>24&255}function JU(n){for(let e=0;e<n.length;e++)n[e]=YU(n[e]);return n}function XU(n,e){return!n.byteLength||!e.byteLength?!1:n.buffer===e.buffer&&n.byteOffset<e.byteOffset+e.byteLength&&e.byteOffset<n.byteOffset+n.byteLength}function WR(n,e){if(XU(n,e)&&n.byteOffset<e.byteOffset)throw new Error("complex overlap of input and output is not supported")}function HR(n,e){return FR(n,"defaults"),FR(e,"opts"),Object.assign(n,e)}function GR(n,e){if(n=qt(n),e=qt(e),n.length!==e.length)return!1;let t=0;for(let i=0;i<n.length;i++)t|=n[i]^e[i];return t===0}function YR(n,e,t){let i=e,o=t||(()=>[]),s=(a,c)=>i(c,...o(a)).update(a).digest(),r=i(new Uint8Array(n),...o(new Uint8Array(0)));return s.outputLen=r.outputLen,s.blockLen=r.blockLen,s.create=(a,...c)=>i(a,...c),s}function Vd(n,e,t=!0){if(e===void 0)return new Uint8Array(n);if(qt(e,n,"output"),t&&!Fd(e))throw new Error("invalid output, must be aligned");return e}function JR(n,e,t){ra(n),ra(e),yy(t);let i=new Uint8Array(16),o=GU(i);return o.setBigUint64(0,BigInt(e),t),o.setBigUint64(8,BigInt(n),t),i}function Fd(n){return n.byteOffset%4===0}function rc(n){return Uint8Array.from(qt(n))}var my,FR,qi,fi,rA,gy=C(()=>{/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */my=n=>n?`"${n}" `:"";FR=(n,e)=>{if(n===null||typeof n!="object"||Array.isArray(n))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof n}`)};qi=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;fi=qi?n=>n:JU;rA=(n,e)=>{function t(i,...o){if(qt(i,void 0,"key"),n.nonceLength!==void 0){let d=o[0];qt(d,n.varSizeNonce?void 0:n.nonceLength,"nonce")}let s=n.tagLength,r=n.nonceLength!==void 0?1:0;if(!n.withAAD){for(let d=r;d<o.length;d++)if(nA(o[d]))throw new Error("AAD not supported")}n.withAAD&&o[r]!==void 0&&qt(o[r],void 0,"AAD");let a=e(i,...o),c=(d,u)=>{if(u!==void 0){if(d!==2)throw new Error("cipher output not supported");qt(u,void 0,"output")}},l=!1;return{encrypt(d,u){if(l)throw new Error("cannot encrypt() twice with same key + nonce");return l=!0,qt(d,void 0,"data"),c(a.encrypt.length,u),a.encrypt(d,u)},decrypt(d,u){if(qt(d,void 0,"data"),s&&d.length<s)throw new Error('"ciphertext" expected length >= tagLength='+s);return c(a.decrypt.length,u),a.decrypt(d,u)}}}return Object.assign(t,n),t}});function Be(n,e){return n<<e|n>>>32-e}function tN(n,e,t,i,o,s,r,a){let c=o.length,l=new Uint8Array(Kd),p=Lr(l),d=qi&&Fd(o)&&Fd(s),u=d?Lr(o):XR,f=d?Lr(s):XR;if(!qi){for(let h=0;h<c;r++){if(n(e,t,i,p,r,a),fi(p),r>=oA)throw new Error("arx: counter overflow");let m=Math.min(Kd,c-h);for(let w=0,b;w<m;w++)b=h+w,s[b]=o[b]^l[w];h+=m}return}for(let h=0;h<c;r++){if(n(e,t,i,p,r,a),r>=oA)throw new Error("arx: counter overflow");let m=Math.min(Kd,c-h);if(d&&m===Kd){let w=h/4;if(h%4!==0)throw new Error("arx: invalid block position");for(let b=0,g;b<eN;b++)g=w+b,f[g]=u[g]^p[b];h+=Kd;continue}for(let w=0,b;w<m;w++)b=h+w,s[b]=o[b]^l[w];h+=m}}function sA(n,e){let{allowShortKeys:t,extendNonceFn:i,counterLength:o,counterRight:s,rounds:r}=HR({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof n!="function")throw new Error("core must be a function");return ra(o),ra(r),yy(s),yy(t),(a,c,l,p,d=0)=>{qt(a,void 0,"key"),qt(c,void 0,"nonce"),qt(l,void 0,"data");let u=l.length,f=p!==void 0;if(p=Vd(u,p,!1),f&&WR(l,p),ra(d),d<0||d>=oA)throw new Error("arx: counter overflow");let h=[],m=a.length,w,b;if(m===32)h.push(w=rc(a)),b=QU;else if(m===16&&t)w=new Uint8Array(32),w.set(a),w.set(a,16),b=ZU,h.push(w);else throw qt(a,32,"arx key"),new Error("invalid key size");(!qi||!Fd(c))&&h.push(c=rc(c));let g=Lr(w);if(i){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");let _=c.subarray(0,16);if(qi)i(b,g,Lr(_),g);else{let k=fi(Uint32Array.from(b));i(k,g,Lr(_),g),ui(k),fi(g)}c=c.subarray(16)}else qi||fi(g);let y=16-o;if(y!==c.length)throw new Error(`arx: nonce must be ${y} or 16 bytes`);if(y!==12){let _=new Uint8Array(12);_.set(c,s?0:12-c.length),c=_,h.push(c)}let v=fi(Lr(c));try{return tN(n,b,g,v,l,p,d,r),p}finally{ui(...h)}}}var ZR,ZU,QU,Kd,eN,oA,XR,QR=C(()=>{gy();ZR=n=>Uint8Array.from(n.split(""),e=>e.charCodeAt(0)),ZU=fi(Lr(ZR("expand 16-byte k"))),QU=fi(Lr(ZR("expand 32-byte k")));Kd=64,eN=16,oA=2**32-1,XR=Uint32Array.of()});function ln(n,e){return n[e++]&255|(n[e++]&255)<<8}var aA,eO,tO=C(()=>{gy();aA=class{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){e=rc(qt(e,32,"key"));let t=ln(e,0),i=ln(e,2),o=ln(e,4),s=ln(e,6),r=ln(e,8),a=ln(e,10),c=ln(e,12),l=ln(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|i<<3)&8191,this.r[2]=(i>>>10|o<<6)&7939,this.r[3]=(o>>>7|s<<9)&8191,this.r[4]=(s>>>4|r<<12)&255,this.r[5]=r>>>1&8190,this.r[6]=(r>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let p=0;p<8;p++)this.pad[p]=ln(e,16+2*p)}process(e,t,i=!1){let o=i?0:2048,{h:s,r}=this,a=r[0],c=r[1],l=r[2],p=r[3],d=r[4],u=r[5],f=r[6],h=r[7],m=r[8],w=r[9],b=ln(e,t+0),g=ln(e,t+2),y=ln(e,t+4),v=ln(e,t+6),_=ln(e,t+8),k=ln(e,t+10),S=ln(e,t+12),x=ln(e,t+14),P=s[0]+(b&8191),I=s[1]+((b>>>13|g<<3)&8191),O=s[2]+((g>>>10|y<<6)&8191),R=s[3]+((y>>>7|v<<9)&8191),q=s[4]+((v>>>4|_<<12)&8191),j=s[5]+(_>>>1&8191),B=s[6]+((_>>>14|k<<2)&8191),D=s[7]+((k>>>11|S<<5)&8191),X=s[8]+((S>>>8|x<<8)&8191),V=s[9]+(x>>>5|o),U=0,ce=U+P*a+I*(5*w)+O*(5*m)+R*(5*h)+q*(5*f);U=ce>>>13,ce&=8191,ce+=j*(5*u)+B*(5*d)+D*(5*p)+X*(5*l)+V*(5*c),U+=ce>>>13,ce&=8191;let ee=U+P*c+I*a+O*(5*w)+R*(5*m)+q*(5*h);U=ee>>>13,ee&=8191,ee+=j*(5*f)+B*(5*u)+D*(5*d)+X*(5*p)+V*(5*l),U+=ee>>>13,ee&=8191;let te=U+P*l+I*c+O*a+R*(5*w)+q*(5*m);U=te>>>13,te&=8191,te+=j*(5*h)+B*(5*f)+D*(5*u)+X*(5*d)+V*(5*p),U+=te>>>13,te&=8191;let Ie=U+P*p+I*l+O*c+R*a+q*(5*w);U=Ie>>>13,Ie&=8191,Ie+=j*(5*m)+B*(5*h)+D*(5*f)+X*(5*u)+V*(5*d),U+=Ie>>>13,Ie&=8191;let tt=U+P*d+I*p+O*l+R*c+q*a;U=tt>>>13,tt&=8191,tt+=j*(5*w)+B*(5*m)+D*(5*h)+X*(5*f)+V*(5*u),U+=tt>>>13,tt&=8191;let $=U+P*u+I*d+O*p+R*l+q*c;U=$>>>13,$&=8191,$+=j*a+B*(5*w)+D*(5*m)+X*(5*h)+V*(5*f),U+=$>>>13,$&=8191;let Y=U+P*f+I*u+O*d+R*p+q*l;U=Y>>>13,Y&=8191,Y+=j*c+B*a+D*(5*w)+X*(5*m)+V*(5*h),U+=Y>>>13,Y&=8191;let K=U+P*h+I*f+O*u+R*d+q*p;U=K>>>13,K&=8191,K+=j*l+B*c+D*a+X*(5*w)+V*(5*m),U+=K>>>13,K&=8191;let Q=U+P*m+I*h+O*f+R*u+q*d;U=Q>>>13,Q&=8191,Q+=j*p+B*l+D*c+X*a+V*(5*w),U+=Q>>>13,Q&=8191;let Ae=U+P*w+I*m+O*h+R*f+q*u;U=Ae>>>13,Ae&=8191,Ae+=j*d+B*p+D*l+X*c+V*a,U+=Ae>>>13,Ae&=8191,U=(U<<2)+U|0,U=U+ce|0,ce=U&8191,U=U>>>13,ee+=U,s[0]=ce,s[1]=ee,s[2]=te,s[3]=Ie,s[4]=tt,s[5]=$,s[6]=Y,s[7]=K,s[8]=Q,s[9]=Ae}finalize(){let{h:e,pad:t}=this,i=new Uint16Array(10),o=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=o,o=e[a]>>>13,e[a]&=8191;e[0]+=o*5,o=e[0]>>>13,e[0]&=8191,e[1]+=o,o=e[1]>>>13,e[1]&=8191,e[2]+=o,i[0]=e[0]+5,o=i[0]>>>13,i[0]&=8191;for(let a=1;a<10;a++)i[a]=e[a]+o,o=i[a]>>>13,i[a]&=8191;i[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)i[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|i[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let r=e[0]+t[0];e[0]=r&65535;for(let a=1;a<8;a++)r=(e[a]+t[a]|0)+(r>>>16)|0,e[a]=r&65535;ui(i)}update(e){iA(this),qt(e),e=rc(e);let{buffer:t,blockLen:i}=this,o=e.length;for(let s=0;s<o;){let r=Math.min(i-this.pos,o-s);if(r===i){for(;i<=o-s;s+=i)this.process(e,s);continue}t.set(e.subarray(s,s+r),this.pos),this.pos+=r,s+=r,this.pos===i&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,ui(this.h,this.r,this.buffer,this.pad)}digestInto(e){iA(this),KR(e,this),this.finished=!0;let{buffer:t,h:i}=this,{pos:o}=this;if(o){for(t[o++]=1;o<16;o++)t[o]=0;this.process(t,0,!0)}this.finalize();let s=0;for(let r=0;r<8;r++)e[s++]=i[r]>>>0,e[s++]=i[r]>>>8}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let i=e.slice(0,t);return this.destroy(),i}},eO=YR(32,n=>new aA(n))});function lA(n,e,t,i,o,s=20){let r=n[0],a=n[1],c=n[2],l=n[3],p=e[0],d=e[1],u=e[2],f=e[3],h=e[4],m=e[5],w=e[6],b=e[7],g=o,y=t[0],v=t[1],_=t[2],k=r,S=a,x=c,P=l,I=p,O=d,R=u,q=f,j=h,B=m,D=w,X=b,V=g,U=y,ce=v,ee=_;for(let Ie=0;Ie<s;Ie+=2)k=k+I|0,V=Be(V^k,16),j=j+V|0,I=Be(I^j,12),k=k+I|0,V=Be(V^k,8),j=j+V|0,I=Be(I^j,7),S=S+O|0,U=Be(U^S,16),B=B+U|0,O=Be(O^B,12),S=S+O|0,U=Be(U^S,8),B=B+U|0,O=Be(O^B,7),x=x+R|0,ce=Be(ce^x,16),D=D+ce|0,R=Be(R^D,12),x=x+R|0,ce=Be(ce^x,8),D=D+ce|0,R=Be(R^D,7),P=P+q|0,ee=Be(ee^P,16),X=X+ee|0,q=Be(q^X,12),P=P+q|0,ee=Be(ee^P,8),X=X+ee|0,q=Be(q^X,7),k=k+O|0,ee=Be(ee^k,16),D=D+ee|0,O=Be(O^D,12),k=k+O|0,ee=Be(ee^k,8),D=D+ee|0,O=Be(O^D,7),S=S+R|0,V=Be(V^S,16),X=X+V|0,R=Be(R^X,12),S=S+R|0,V=Be(V^S,8),X=X+V|0,R=Be(R^X,7),x=x+q|0,U=Be(U^x,16),j=j+U|0,q=Be(q^j,12),x=x+q|0,U=Be(U^x,8),j=j+U|0,q=Be(q^j,7),P=P+I|0,ce=Be(ce^P,16),B=B+ce|0,I=Be(I^B,12),P=P+I|0,ce=Be(ce^P,8),B=B+ce|0,I=Be(I^B,7);let te=0;i[te++]=r+k|0,i[te++]=a+S|0,i[te++]=c+x|0,i[te++]=l+P|0,i[te++]=p+I|0,i[te++]=d+O|0,i[te++]=u+R|0,i[te++]=f+q|0,i[te++]=h+j|0,i[te++]=m+B|0,i[te++]=w+D|0,i[te++]=b+X|0,i[te++]=g+V|0,i[te++]=y+U|0,i[te++]=v+ce|0,i[te++]=_+ee|0}function nN(n,e,t,i){let o=qi?n:fi(n.slice(0,4)),s=qi?e:fi(e.slice(0,8)),r=qi?t:fi(t.slice(0,4)),a=new Uint32Array(16);lA(o,s,r.subarray(1),a,r[0]);let c=0;i[c++]=a[0]-o[0]|0,i[c++]=a[1]-o[1]|0,i[c++]=a[2]-o[2]|0,i[c++]=a[3]-o[3]|0,i[c++]=a[12]-r[0]|0,i[c++]=a[13]-r[1]|0,i[c++]=a[14]-r[2]|0,i[c++]=a[15]-r[3]|0,fi(i),qi||ui(o,s,r),ui(a)}function iO(n,e,t,i,o){o!==void 0&&qt(o,void 0,"AAD");let s=n(e,t,sN),r=JR(i.length,o?o.length:0,!0),a=eO.create(s);o&&nO(a,o),nO(a,i),a.update(r);let c=a.digest();return ui(s,r),c}var iN,rN,oN,nO,sN,rO,cA,pA,dA=C(()=>{QR();tO();gy();iN=sA(lA,{counterRight:!1,counterLength:4,allowShortKeys:!1}),rN=sA(lA,{counterRight:!1,counterLength:8,extendNonceFn:nN,allowShortKeys:!1}),oN=new Uint8Array(16),nO=(n,e)=>{n.update(e);let t=e.length%16;t&&n.update(oN.subarray(t))},sN=new Uint8Array(32);rO=n=>(e,t,i)=>({encrypt(s,r){let a=s.length;r=Vd(a+16,r,!1),r.set(s);let c=r.subarray(0,-16);n(e,t,c,c,1);let l=iO(n,e,t,c,i);return r.set(l,a),ui(l),r},decrypt(s,r){r=Vd(s.length-16,r,!1);let a=s.subarray(0,-16),c=s.subarray(-16),l=iO(n,e,t,a,i);if(!GR(c,l))throw ui(l),new Error("invalid tag");return r.set(s.subarray(0,-16)),n(e,t,r,r,1),ui(l),r}}),cA=rA({blockSize:64,nonceLength:12,tagLength:16,withAAD:!0},rO(iN)),pA=rA({blockSize:64,nonceLength:24,tagLength:16,withAAD:!0},rO(rN))});function wy(n,e,t=()=>{}){if(!Array.isArray(n))throw new TypeError(`"${e}" expected array, got type=${typeof n}`);for(let i=0;i<n.length;i++)t(n[i],`${e}[${i}]`);return n}function cs(n,e="object"){if(n===null||typeof n!="object"||Array.isArray(n))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof n}`);return n}function oa(n,e){if(typeof n!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof n}`);return n}function mo(n,e=""){if(typeof n!="boolean")throw new TypeError(aN(e)+"expected boolean, got type="+typeof n);return n}function lN(n){if(typeof n=="bigint"){if(!ps(n))throw new RangeError("positive bigint expected, got "+n)}else uA(n);return n}function oc(n,e=""){if(typeof n!="number"){let t=e&&`"${e}" `;throw new TypeError(t+"expected number, got type="+typeof n)}if(!Number.isSafeInteger(n)){let t=e&&`"${e}" `;throw new RangeError(t+"expected safe integer, got "+n)}}function lO(n){if(typeof n!="string")throw new TypeError("hex string expected, got "+typeof n);return n===""?by:BigInt("0x"+n)}function vy(n){return lO(Ua(n))}function yo(n){return lO(Ua(ds(mt(n)).reverse()))}function hA(n,e){if(xn(e),e===0)throw new Error("zero output length is invalid");n=lN(n);let t=e*2,i=n.toString(16);if(i.length>t)throw new RangeError("number is too large");return tf(i.padStart(t,"0"))}function _y(n,e){return hA(n,e).reverse()}function ds(n){return Uint8Array.from(Qt(n))}function ps(n){return typeof n=="bigint"&&by<=n}function mA(n,e,t){return ps(n)&&ps(e)&&ps(t)&&e<=n&&n<t}function sa(n,e,t,i){if(!mA(e,t,i))throw new RangeError("expected valid "+n+": "+t+" <= n < "+i+", got "+e)}function yA(n){if(n<by)throw new Error("expected non-negative bigint, got "+n);return n===by?0:n.toString(2).length}function jr(n,e={},t={},i="object"){cs(n,i),cs(e,"fields"),cs(t,"optFields");function o(r,a,c){let l=i==="object"?`param "${String(r)}"`:`"${i}.${String(r)}"`,p=n[r];if(!Object.hasOwn(n,r)&&(c?p!==void 0:a!=="function"))throw new TypeError(`${l} is invalid: expected own property`);if(c&&p===void 0)return;let d=typeof p;if(d!==a||p===null)throw new TypeError(`${l} is invalid: expected ${a}, got ${d}`)}let s=(r,a)=>Object.entries(r).forEach(([c,l])=>o(c,l,a));s(e,!1),s(t,!0)}var Qt,uA,sO,fA,aO,Wd,Hd,by,oO,aN,cO,Gd=C(()=>{yr();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */Qt=(n,e,t)=>mt(n,e,t),uA=xn;sO=Ua,fA=(...n)=>Lb(...n),aO=n=>tf(n),Wd=Qu,Hd=n=>fS(n),by=BigInt(0),oO=BigInt(1),aN=n=>n?`"${n}" `:"";cO=n=>(oc(n,"n"),(oO<<BigInt(n))-oO)});function ct(n,e){if(e<=en)throw new Error("mod: expected positive modulus, got "+e);let t=n%e;return t>=en?t:e+t}function fN(n,e,t){if(t<=yt)throw new Error("pow: expected modulus > 1, got "+t);if(typeof e!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof e);if(e<en)throw new Error("invalid exponent, negatives unsupported");if(e===en)return yt;if(e===yt)return n;let i=n%t;if(i<en&&(i+=t),e<uN){let a=yt;for(;e>en;)e&yt&&(a=a*i%t),i=i*i%t,e>>=yt;return a}let o=[];for(;e>en;)o.push(Number(e&dN)),e>>=gA;let s=new Array(16);s[0]=yt,s[1]=i;for(let a=2;a<16;a++)s[a]=s[a-1]*i%t;let r=s[o[o.length-1]];for(let a=o.length-2;a>=0;a--){r=r*r%t,r=r*r%t,r=r*r%t,r=r*r%t;let c=o[a];c!==0&&(r=r*s[c]%t)}return r}function Ti(n,e,t){if(t<=yt)throw new Error("pow2: expected modulus > 1, got "+t);if(e<en)throw new Error("pow2: expected non-negative exponent, got "+e);let i=n;for(;e-- >en;)i*=i,i%=t;return i}function pO(n,e){if(n===en)throw new Error("invert: expected non-zero number");if(e<=yt)throw new Error("invert: expected modulus > 1, got "+e);let t=ct(n,e),i=e,o=en,s=yt;for(;t!==en;){let a=i/t,c=i-t*a,l=o-s*a;i=t,t=c,o=s,s=l}if(i!==yt)throw new Error("invert: does not exist");return ct(o,e)}function bA(n,e,t){let i=n;if(!i.eql(i.sqr(e),t))throw new Error("Cannot find square root")}function wA(n,e){if((n&yt)===en)throw new Error(e+": expected odd modulus, got "+n)}function yO(n,e){let t=n,i=(t.ORDER+yt)/gA,o=t.pow(e,i);return bA(t,o,e),o}function hN(n,e){let t=n,i=(t.ORDER-fO)/hO,o=t.mul(e,aa),s=t.pow(o,i),r=t.mul(e,s),a=t.mul(t.mul(r,aa),s),c=t.mul(r,t.sub(a,t.ONE));return bA(t,c,e),c}function mN(n){let e=Sy(n),t=gO(n),i=t(e,e.neg(e.ONE)),o=t(e,i),s=t(e,e.neg(i)),r=(n+cN)/mO;return((a,c)=>{let l=a,p=l.pow(c,r),d=l.mul(p,i),u=l.mul(p,o),f=l.mul(p,s),h=l.eql(l.sqr(d),c),m=l.eql(l.sqr(u),c);p=l.cmov(p,d,h),d=l.cmov(f,u,m);let w=l.eql(l.sqr(d),c),b=l.cmov(p,d,w);return bA(l,b,c),b})}function gO(n){if(n<uO)throw new Error("sqrt is not defined for small field");wA(n,"tonelliShanks");let e=n-yt,t=0;for(;e%aa===en;)e/=aa,t++;let i=aa,o=Sy(n);for(;Yd(o,i)===1;)if(i++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return yO;let s=o.pow(i,e),r=(e+yt)/aa;return function(c,l){let p=c;if(p.is0(l))return l;if(Yd(p,l)!==1)throw new Error("Cannot find square root");let d=t,u=p.mul(p.ONE,s),f=p.pow(l,e),h=p.pow(l,r);for(;!p.eql(f,p.ONE);){if(p.is0(f))throw new Error("Cannot find square root: probably non-prime P");let m=1,w=p.sqr(f);for(;!p.eql(w,p.ONE);)if(m++,w=p.sqr(w),m===d)throw new Error("Cannot find square root");let b=yt<<BigInt(d-m-1),g=p.pow(u,b);d=m,u=p.sqr(g),f=p.mul(f,u),h=p.mul(h,g)}return h}}function yN(n){return wA(n,"Fp.sqrt"),n%gA===uO?yO:n%hO===fO?hN:n%mO===pN?mN(n):gO(n)}function sc(n){if(cs(n,"field"),typeof n.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof n.ORDER);oc(n.BYTES,"BYTES"),oc(n.BITS,"BITS");for(let e of gN)oa(n[e],"field."+e);if(n.BYTES<1||n.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(n.ORDER<=yt)throw new Error("invalid field: expected ORDER > 1, got "+n.ORDER);return n}function ky(n,e,t=!1){sc(n),wy(e,"nums"),mo(t,"passZero");let i=n,o=new Array(e.length).fill(t?i.ZERO:void 0),s=e.reduce((a,c,l)=>i.is0(c)?a:(o[l]=a,i.mul(a,c)),i.ONE),r=i.inv(s);return e.reduceRight((a,c,l)=>i.is0(c)?a:(o[l]=i.mul(a,o[l]),i.mul(a,c)),r),o}function Yd(n,e){sc(n);let t=n;wA(t.ORDER,"FpLegendre");let i=(t.ORDER-yt)/aa,o=t.pow(e,i),s=t.eql(o,t.ONE),r=t.eql(o,t.ZERO),a=t.eql(o,t.neg(t.ONE));if(!s&&!r&&!a)throw new Error("invalid Legendre symbol result");return s?1:r?0:-1}function bN(n,e){if(e!==void 0&&uA(e),n<=en)throw new Error("invalid n length: expected positive n, got "+n);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=yA(n);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected nBitLength (${e}) >= bitLen(n) (${t})`);let i=e!==void 0?e:t,o=Math.ceil(i/8);return{nBitLength:i,nByteLength:o}}function Sy(n,e={}){return Object.freeze(Ay.prototype),new Ay(n,e)}var en,yt,aa,uO,gA,fO,cN,hO,pN,dN,mO,uN,bO,gN,dO,Ay,Jd=C(()=>{Gd();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */en=BigInt(0),yt=BigInt(1),aa=BigInt(2),uO=BigInt(3),gA=BigInt(4),fO=BigInt(5),cN=BigInt(7),hO=BigInt(8),pN=BigInt(9),dN=BigInt(15),mO=BigInt(16),uN=BigInt("0x10000000000000000");bO=(n,e)=>(ct(n,e)&yt)===yt,gN=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];dO=new WeakMap,Ay=class{ORDER;BITS;BYTES;isLE;ZERO=en;ONE=yt;_lengths;_mod;constructor(e,t={}){if(e<=yt)throw new Error("invalid field: expected ORDER > 1, got "+e);let i;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(i=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:o,nByteLength:s}=bN(e,i);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(e){return ct(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return en<=e&&e<this.ORDER}is0(e){return e===en}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&yt)===yt}neg(e){return ct(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return ct(e*e,this.ORDER)}add(e,t){return ct(e+t,this.ORDER)}sub(e,t){return ct(e-t,this.ORDER)}mul(e,t){return ct(e*t,this.ORDER)}pow(e,t){return fN(e,t,this.ORDER)}div(e,t){return ct(e*pO(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return pO(e,this.ORDER)}sqrt(e){let t=dO.get(this);return t||dO.set(this,t=yN(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?_y(e,this.BYTES):hA(e,this.BYTES)}fromBytes(e,t=!1){Qt(e);let{_lengths:i,BYTES:o,isLE:s,ORDER:r,_mod:a}=this;if(i){if(e.length<1||!i.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+i+" bytes, got "+e.length);let l=new Uint8Array(o);l.set(e,s?0:l.length-e.length),e=l}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?yo(e):vy(e);if(a&&(c=ct(c,r)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return ky(this,e,!0)}cmov(e,t,i){return mo(i,"condition"),i?t:e}}});function Zd(n){let e=n;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof n);oa(e.fromAffine,"Point.fromAffine"),oa(e.fromBytes,"Point.fromBytes"),oa(e.fromHex,"Point.fromHex"),cs(e.BASE,"Point.BASE"),cs(e.ZERO,"Point.ZERO"),sc(e.Fp),sc(e.Fn)}function AO(n,e){Zd(n),kO(e,n);let t=ky(n.Fp,e.map(i=>i.Z));return e.map((i,o)=>n.fromAffine(i.toAffine(t[o])))}function _N(n,e,t=1){if(!Number.isSafeInteger(n)||n<t||n>e)throw new Error("invalid window size, expected ["+t+".."+e+"], got W="+n)}function AN(n,e){let t=n*(4*e+128);if(t>vO)throw new Error("invalid window size: table would need ~"+Math.ceil(t/2**20)+" MiB, max "+vO/2**20+" MiB")}function kN(n,e){if(n!==void 0){oa(n,"randomBytes");try{let t=n(e);if(!Wd(t)||t.length!==e)return}catch{return}return n}}function kO(n,e){wy(n,"points"),n.forEach((t,i)=>{if(!(t instanceof e))throw new Error("invalid point at index "+i)})}function SN(n,e,t){if(!Array.isArray(n))throw new Error("array of scalars expected");n.forEach((i,o)=>{if(!(t===void 0?e.isValid(i):ps(i)&&i<t))throw new Error("invalid scalar at index "+o)})}function _A(n){return SO.get(n)||1}function PN(n,e){let t=n.double(),i=[n];for(let o=1;o<e;o++)i.push(i[o-1].add(t));return i}function xN(n,e){let t=2**e,i=t/2,o=BigInt(t-1),s=[];for(;n>AA;){let r=0;n&Xd&&(r=Number(n&o),r>=i&&(r-=t),n-=BigInt(r)),s.push(r),n>>=Xd}return s}function IN(n,e,t){let i=2**e,o=i/2,s=BigInt(i-1),r=BigInt(e),a=[];for(let c=0;c<t;c++){let l=Number(n&s);n>>=r,l>o&&(l-=i,n+=Xd),a.push(l)}if(n!==AA)throw new Error("invalid wnaf");return a}function CN(n,e,t){let i=0;for(let s of t)i=Math.max(i,s.length);let o=n;for(let s=i-1;s>=0;s--){s!==i-1&&(o=o.double());for(let r=0;r<t.length;r++){let a=t[r][s];if(a){let c=e[r][Math.abs(a)-1>>1];o=o.add(a<0?c.negate():c)}}}return o}function RN(n,e,t,i=!1){if(Zd(n),kO(e,n),mo(i,"allowOversized"),SN(t,n.Fn,i?n.Fn.ORDER**wN:void 0),e.length!==t.length)throw new Error("arrays of points and scalars must have equal length");let o=e.map(r=>PN(r,4)),s=t.map(r=>xN(r,4));return CN(n.ZERO,o,s)}function _O(n,e,t){if(e){if(e.ORDER!==n)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return sc(e),e}else return Sy(n,{isLE:t})}function PO(n,e,t={},i){if(n!=="weierstrass"&&n!=="edwards")throw new Error('expected curve type "weierstrass" or "edwards"');if(i===void 0&&(i=n==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${n} CURVE object`);jr(t);for(let c of["p","n","h"]){let l=e[c];if(!(ps(l)&&l!==AA))throw new Error(`CURVE.${c} must be positive bigint`)}let o=_O(e.p,t.Fp,i),s=_O(e.n,t.Fn,i),a=["Gx","Gy","a",n==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function xy(n,e){return function(i){let o=n(i);return{secretKey:o,publicKey:e(o)}}}var AA,Xd,wN,vA,wO,vN,vO,SO,Py,kA=C(()=>{Gd();Jd();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */AA=BigInt(0),Xd=BigInt(1),wN=BigInt(4),vA=16,wO=128,vN=5,vO=2**31;SO=new WeakMap;Py=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,t){Zd(e),this.randomBytes=kN(t,vA),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,t,i){let o=Math.ceil(i/t)+1,s=2**(t-1),r=[],a=e;for(let c=0;c<o;c++){let l=a;for(let p=0;p<s;p++)r.push(l),l=l.add(a);a=r[r.length-1].double()}return{W:t,bits:i,windows:o,comp:r}}wnafCachedCT(e,t){let{W:i,windows:o,comp:s}=e,r=2**(i-1),a=IN(t,i,o),c=this.ZERO,l=this.BASE;for(let p=0;p<o;p++){let d=a[p],u=p*r,f=Math.abs(d)-1,h=s[u];for(let w=1;w<r;w++)h=w===f?s[u+w]:h;let m=h.negate();d===0?l=l.add(s[u]):c=c.add(d<0?m:h)}return{p:c,f:l}}getWnafPrecomputes(e,t,i,o){let s=this.wnafPrecomputes.get(t),r=s?.find(a=>a.W===e&&a.bits===i);return r||(r=this.buildWnafTable(t,e,i),typeof o=="function"&&(r={...r,comp:o(r.comp)}),s||(s=[],this.wnafPrecomputes.set(t,s)),s.push(r)),r}assertPoint(e){if(!(e instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof e)}validateMulInput(e,t){if(this.assertPoint(e),!mA(t,Xd,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,t,i,o){let s=_A(e);return s===1?this.fixedWindowCT(e,t,i):this.wnafCachedCT(this.getWnafPrecomputes(s,e,i,o),t)}mulCT(e,t,i){return this.validateMulInput(e,t),this.runCT(e,t,this.bits,i)}mulCTBlinded(e,t,i){if(this.validateMulInput(e,t),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");let o=this.Point.Fn.BITS+wO,s=this.randomBytes(vA);if(!Wd(s)||s.length!==vA)throw new Error("randomBytes returned invalid byte array");s[0]=s[0]&63|128;let r=t+vy(s)*this.Point.Fn.ORDER;return this.runCT(e,r,o,i)}fixedWindowCT(e,t,i){let o=vN,s=1<<o,r=cO(o),a=new Array(s);a[0]=this.ZERO;for(let p=1;p<s;p++)a[p]=a[p-1].add(e);let c=Math.ceil(i/o),l=this.ZERO;for(let p=c-1;p>=0;p--){if(p!==c-1)for(let f=0;f<o;f++)l=l.double();let d=Number(t>>BigInt(p*o)&r),u=a[0];for(let f=1;f<s;f++)u=f===d?a[f]:u;l=l.add(u)}return{p:l,f:l}}shouldBlind(e,t){return this.randomBytes===void 0?!1:t===Xd?!0:e!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(e,t,i,o){return this.shouldBlind(e,i)?this.mulCTBlinded(e,t,o):this.mulCT(e,t,o)}mulUnsafe(e,t,i){if(this.assertPoint(e),!ps(t))throw new Error("invalid scalar");let o=_A(e);if(o===1||t>=this.Point.Fn.ORDER)return RN(this.Point,[e],[t],!0);let s=this.getWnafPrecomputes(o,e,this.bits,i);return this.wnafCachedCT(s,t).p}setWindowSize(e,t){this.assertPoint(e),_N(t,this.bits);let i=Math.ceil((this.bits+wO)/t)+1;AN(i*2**(t-1),this.Point.Fp.BYTES),SO.set(e,t),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return _A(e)!==1}}});function EN(n,e,t,i){let o=n.sqr(t),s=n.sqr(i),r=n.add(n.mul(e.a,o),s),a=n.add(n.ONE,n.mul(e.d,n.mul(o,s)));return n.eql(r,a)}function IO(n,e={}){jr(e,{},{},"extraOpts");let t=e,i=PO("edwards",n,t,t.FpFnLE),{Fp:o,Fn:s}=i,r=i.CURVE,{h:a}=r;if(Yd(o,r.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(Yd(o,r.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");jr(t,{},{uvRatio:"function",randomBytes:"function"});let c=t.randomBytes===void 0?Hd:t.randomBytes,l=Ry<<BigInt(o.BYTES*8)-Cy;function p(g){if(!o.isOdd)throw new Error("Field does not have .isOdd()");return o.isOdd(g)}let d=t.uvRatio===void 0?(g,y)=>{try{return{isValid:!0,value:o.sqrt(o.div(g,y))}}catch{return{isValid:!1,value:Iy}}}:t.uvRatio;if(!EN(o,r,r.Gx,r.Gy))throw new Error("bad curve params: generator point");let u=o.eql(r.a,o.neg(o.ONE))?g=>o.neg(g):o.eql(r.a,o.ONE)?g=>g:g=>o.mul(r.a,g);function f(g,y,v=!1){let _=v?Cy:Iy;return sa("coordinate "+g,y,_,l),y}function h(g){if(!(g instanceof m))throw new Error("EdwardsPoint expected")}class m{static BASE=new m(r.Gx,r.Gy,o.ONE,o.mul(r.Gx,r.Gy));static ZERO=new m(o.ZERO,o.ONE,o.ONE,o.ZERO);static Fp=o;static Fn=s;X;Y;Z;T;constructor(y,v,_,k){this.X=f("x",y),this.Y=f("y",v),this.Z=f("z",_,!0),this.T=f("t",k),Object.freeze(this)}static CURVE(){return r}static fromAffine(y){if(y instanceof m)throw new Error("extended point not allowed");let{x:v,y:_}=y||{};return f("x",v),f("y",_),new m(v,_,o.ONE,o.mul(v,_))}static fromBytes(y,v=!1){let _=o.BYTES,{a:k,d:S}=r;y=ds(Qt(y,_,"point")),mo(v,"zip215");let x=ds(y),P=y[_-1];x[_-1]=P&-129;let I=yo(x),O=v?l:o.ORDER;sa("point.y",I,Iy,O);let R=o.sqr(I),q=o.sub(R,o.ONE),j=o.sub(o.mulN(S,R),k),{isValid:B,value:D}=d(q,j);if(!B)throw new Error("bad point: invalid y coordinate");let X=p(D),V=(P&128)!==0;if(!v&&o.is0(D)&&V)throw new Error("bad point: x=0 and x_0=1");return V!==X&&(D=o.neg(D)),m.fromAffine({x:D,y:I})}static fromHex(y,v=!1){return m.fromBytes(aO(y),v)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=6,v=!0){return b.setWindowSize(this,y),v||this.multiply(Ry),this}assertValidity(){let y=this,{a:v,d:_}=r;if(y.is0())throw new Error("bad point: ZERO");let{X:k,Y:S,Z:x,T:P}=y,I=o.sqr(k),O=o.sqr(S),R=o.sqr(x),q=o.sqr(R),j=o.mul(I,v),B=o.mul(o.add(j,O),R),D=o.add(q,o.mul(_,o.mul(I,O)));if(!o.eql(B,D))throw new Error("bad point: equation left != right (1)");let X=o.mul(k,S),V=o.mul(x,P);if(!o.eql(X,V))throw new Error("bad point: equation left != right (2)")}equals(y){h(y);let{X:v,Y:_,Z:k}=this,{X:S,Y:x,Z:P}=y,I=o.mul(v,P),O=o.mul(S,k),R=o.mul(_,P),q=o.mul(x,k);return o.eql(I,O)&&o.eql(R,q)}is0(){return this.equals(m.ZERO)}negate(){return new m(o.neg(this.X),this.Y,this.Z,o.neg(this.T))}double(){let{X:y,Y:v,Z:_}=this,k=o.sqr(y),S=o.sqr(v),x=o.mul(o.sqr(_),Ry),P=u(k),I=o.addN(y,v),O=o.sub(o.subN(o.sqr(I),k),S),R=o.addN(P,S),q=o.subN(R,x),j=o.subN(P,S),B=o.mul(O,q),D=o.mul(R,j),X=o.mul(O,j),V=o.mul(q,R);return new m(B,D,V,X)}add(y){h(y);let{d:v}=r,{X:_,Y:k,Z:S,T:x}=this,{X:P,Y:I,Z:O,T:R}=y,q=o.mul(_,P),j=o.mul(k,I),B=o.mul(o.mulN(x,v),R),D=o.mul(S,O),X=o.sub(o.subN(o.mulN(o.addN(_,k),o.addN(P,I)),q),j),V=o.subN(D,B),U=o.addN(D,B),ce=o.sub(j,u(q)),ee=o.mul(X,V),te=o.mul(U,ce),Ie=o.mul(X,ce),tt=o.mul(V,U);return new m(ee,te,tt,Ie)}subtract(y){return h(y),this.add(y.negate())}multiply(y){if(!s.isValidNot0(y))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:v,f:_}=b.mulSecret(this,y,a,w);return w([v,_])[0]}multiplyUnsafe(y){if(!s.isValid(y))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return y===Iy?m.ZERO:this.is0()||y===Cy?this:b.mulUnsafe(this,y,w)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return b.mulUnsafe(this,r.n).is0()}toAffine(y){let v=this,_=y;if(_!=null&&typeof _!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof _);let{X:k,Y:S,Z:x}=v,P=v.is0();_==null&&(_=P?o.create(xO):o.inv(x));let I=o.mul(k,_),O=o.mul(S,_),R=o.mul(x,_);if(P)return{x:o.ZERO,y:o.ONE};if(!o.eql(R,o.ONE))throw new Error("invZ was invalid");return{x:I,y:O}}clearCofactor(){return a===Cy?this:a===Ry?this.double():a===ON?this.double().double():a===xO?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){let{x:y,y:v}=this.toAffine(),_=o.toBytes(v);return _[_.length-1]|=p(y)?128:0,_}toHex(){return sO(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let w=g=>AO(m,g),b=new Py(m,c);return b.bits>=6&&m.BASE.precompute(6),Object.freeze(m.prototype),Object.freeze(m),m}function CO(n,e,t={}){if(Zd(n),typeof e!="function")throw new Error('"hash" function param is required');let i=e,o=t;jr(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function",toMontgomery:"function",toMontgomerySecret:"function"});let{prehash:s}=o,{BASE:r,Fp:a,Fn:c}=n,l=i.outputLen,p=2*a.BYTES;if(l!==void 0&&(oc(l,"hash.outputLen"),l!==p))throw new Error(`hash.outputLen must be ${p}, got ${l}`);let d=o.randomBytes===void 0?Hd:o.randomBytes,u=o.toMontgomery,f=o.toMontgomerySecret,h=o.adjustScalarBytes===void 0?j=>j:o.adjustScalarBytes,m=o.domain===void 0?(j,B,D)=>{if(mo(D,"phflag"),B.length||D)throw new Error("Contexts/pre-hash are not supported");return j}:o.domain;function w(j){return c.create(yo(j))}function b(j){let B=P.secretKey;Qt(j,P.secretKey,"secretKey");let D=Qt(i(j),2*B,"hashedSecretKey"),X=h(D.slice(0,B)),V=D.slice(B,2*B),U=w(X);return{head:X,prefix:V,scalar:U}}function g(j){let{head:B,prefix:D,scalar:X}=b(j),V=r.multiply(X),U=V.toBytes();return{head:B,prefix:D,scalar:X,point:V,pointBytes:U}}function y(j){return g(j).pointBytes}function v(j=Uint8Array.of(),...B){let D=fA(...B);return w(i(m(D,Qt(j,void 0,"context"),!!s)))}function _(j,B,D={}){jr(D,{},{},"options"),j=ds(Qt(j,void 0,"message")),s&&(j=s(j));let{prefix:X,scalar:V,pointBytes:U}=g(B),ce=v(D.context,X,j),ee=r.multiply(ce).toBytes(),te=v(D.context,ee,U,j),Ie=c.create(ce+te*V);if(!c.isValid(Ie))throw new Error("sign failed: invalid s");let tt=fA(ee,c.toBytes(Ie));return Qt(tt,P.signature,"result")}let k={zip215:o.zip215};function S(j,B,D,X=k){jr(X);let{context:V}=X,U=X.zip215===void 0?!!k.zip215:X.zip215,ce=P.signature;j=Qt(j,ce,"signature"),B=Qt(B,void 0,"message"),D=Qt(D,P.publicKey,"publicKey"),U!==void 0&&mo(U,"zip215"),s&&(B=s(B));let ee=ce/2,te=j.subarray(0,ee),Ie=yo(j.subarray(ee,ce)),tt,$,Y;try{tt=n.fromBytes(D,U),$=n.fromBytes(te,U),Y=r.multiplyUnsafe(Ie)}catch{return!1}if(!U&&tt.isSmallOrder())return!1;let K=v(V,te,D,B);return $.add(tt.multiplyUnsafe(K)).subtract(Y).clearCofactor().is0()}let x=a.BYTES,P={secretKey:x,publicKey:x,signature:2*x,seed:x};function I(j){return j=j===void 0?d(P.seed):j,Qt(j,P.seed,"seed")}function O(j){return Wd(j)&&j.length===P.secretKey}function R(j,B){try{return!!n.fromBytes(j,B===void 0?k.zip215:B)}catch{return!1}}let q={getExtendedPublicKey:g,randomSecretKey:I,isValidSecretKey:O,isValidPublicKey:R,toMontgomery(j){if(u===void 0)throw new Error("Montgomery conversion is not supported for this curve");return u(n.fromBytes(j))},toMontgomerySecret(j){if(f===void 0)throw new Error("Montgomery conversion is not supported for this curve");return f(j)}};return Object.freeze(P),Object.freeze(q),Object.freeze({keygen:xy(I,y),getPublicKey:y,sign:_,verify:S,utils:q,Point:n,lengths:P})}var Iy,Cy,Ry,ON,xO,RO=C(()=>{Gd();kA();Jd();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */Iy=BigInt(0),Cy=BigInt(1),Ry=BigInt(2),ON=BigInt(4),xO=BigInt(8)});function OO(n,e){return n+e-(e>>Mi<<Mi)}function qN(n){let e=BigInt(6)*n;return(t,i,o)=>{let s=i+o,a=((e+o-i)*t+i)%n;return{x_2:a,x_3:s-a}}}function TN(n){return jr(n,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function",scalarMultBase:"function"}),Object.freeze({...n})}function EO(n){let e=TN(n),{P:t,type:i,adjustScalarBytes:o,powPminus2:s,randomBytes:r}=e,a=e.scalarMultBase,c=i==="x25519";if(!c&&i!=="x448")throw new Error("invalid type");let l=r===void 0?Hd:r,p=c?255:448,d=qN(t),u=c?32:56,f=BigInt(c?9:5),h=BigInt(c?121665:39081),m=c?Oy**BigInt(254):Oy**BigInt(447),w=c?BigInt(8)*(Oy**BigInt(251)-Mi):BigInt(4)*(Oy**BigInt(445)-Mi),b=m+w+Mi,g=D=>ct(D,t),y=v(f);function v(D){return _y(g(D),u)}function _(D){let X=ds(Qt(D,u,"uCoordinate"));return c&&(X[31]&=127),g(yo(X))}function k(D){return yo(o(ds(Qt(D,u,"scalar"))))}let S=new Set(c?[la,Mi,t-Mi,BigInt("325606250916557431795983626356110631294008115727848805560023387167927233504"),BigInt("39382357235489614581723060781553021112529911719440698176882885853963445705823")]:[la,Mi,t-Mi]);function x(D,X){let V=_(X);if(S.has(V))throw new Error("invalid private or public key received");let U=R(V,k(D));if(U===la)throw new Error("invalid private or public key received");return v(U)}function P(D){if(a===void 0)return x(D,y);let X=k(D);sa("scalar",X,m,b);let V=g(a(X));if(V===la)throw new Error("invalid private or public key received");return v(V)}let I=P,O=x;function R(D,X){sa("u",D,la,t),sa("scalar",X,m,b);let V=X,U=D,ce=Mi,ee=la,te=D,Ie=Mi,tt=V^V>>Mi;for(let K=BigInt(p-1);K>=la;K--){let Q=OO(t,tt>>K);({x_2:ce,x_3:te}=d(Q,ce,te)),{x_2:ee,x_3:Ie}=d(Q,ee,Ie);let Ae=ce+ee,oe=g(Ae*Ae),ie=ce-ee,He=g(ie*ie),Fe=oe-He,Ft=te+Ie,Ee=te-Ie,nt=g(Ee*Ae),dr=g(Ft*ie),_o=nt+dr,Ao=nt-dr;te=g(_o*_o),Ie=g(U*g(Ao*Ao)),ce=g(oe*He),ee=g(Fe*(oe+g(h*Fe)))}let $=OO(t,V);({x_2:ce,x_3:te}=d($,ce,te)),{x_2:ee,x_3:Ie}=d($,ee,Ie);let Y=s(ee);return g(ce*Y)}let q={secretKey:u,publicKey:u,seed:u},j=D=>(D=D===void 0?l(u):D,Qt(D,q.seed,"seed"),D),B={randomSecretKey:j};return Object.freeze(q),Object.freeze(B),Object.freeze({keygen:xy(j,I),getSharedSecret:O,getPublicKey:I,scalarMult:x,scalarMultBase:P,utils:B,GuBytes:y.slice(),lengths:q})}var la,Mi,Oy,qO=C(()=>{Gd();kA();Jd();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */la=BigInt(0),Mi=BigInt(1),Oy=BigInt(2)});function UO(n){let e=BigInt(10),t=BigInt(20),i=BigInt(40),o=BigInt(80),s=Ey,a=n*n%s*n%s,c=Ti(a,MO,s)*a%s,l=Ti(c,SA,s)*n%s,p=Ti(l,LN,s)*l%s,d=Ti(p,e,s)*p%s,u=Ti(d,t,s)*d%s,f=Ti(u,i,s)*u%s,h=Ti(f,o,s)*f%s,m=Ti(h,o,s)*f%s,w=Ti(m,e,s)*p%s;return{pow_p_5_8:Ti(w,MO,s)*n%s,b2:a}}function PA(n){return n[0]&=248,n[31]&=127,n[31]|=64,n}function NN(n,e){let t=Ey,i=ct(e*e*e,t),o=ct(i*i*e,t),s=UO(n*o).pow_p_5_8,r=ct(n*i*s,t),a=ct(e*r*r,t),c=r,l=ct(r*LO,t),p=a===n,d=a===ct(-n,t),u=a===ct(-n*LO,t);return p&&(r=c),(d||u)&&(r=l),bO(r,t)&&(r=ct(-r,t)),{isValid:p||d,value:r}}function DN(n){let{y:e}=n;return jO.toBytes(jO.div(SA+e,SA-e))}function zN(n){let e=Qd.Fp.BYTES;return mt(n,e),PA($b(n.subarray(0,e))).subarray(0,e)}function $N(n){return CO(Qd,$b,Object.assign({adjustScalarBytes:PA,toMontgomery:DN,toMontgomerySecret:zN,zip215:!0},n))}var TO,SA,MO,MN,LN,jN,Ey,UN,LO,Qd,jO,eu,or,qy=C(()=>{gr();yr();RO();Jd();qO();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */TO=BigInt(0),SA=BigInt(1),MO=BigInt(2),MN=BigInt(3),LN=BigInt(5),jN=BigInt(8),Ey=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),UN={p:Ey,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:jN,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};LO=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");Qd=IO(UN,{uvRatio:NN}),jO=Qd.Fp;eu=$N({}),or=(()=>{let n=Ey,e=t=>{let{pow_p_5_8:i,b2:o}=UO(t);return ct(Ti(i,MN,n)*o,n)};return EO({P:n,type:"x25519",powPminus2:e,adjustScalarBytes:PA,scalarMultBase:t=>{let i=ct(t,Qd.Fn.ORDER);if(i===TO)return TO;let o=Qd.BASE.multiply(i);return ct((o.Z+o.Y)*e(ct(o.Z-o.Y,n)),n)}})})()});var Ty,ca,xA=C(()=>{yr();Ty=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(ap(e),mt(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let i=this.blockLen,o=new Uint8Array(i);o.set(t.length>i?e.create().update(t).digest():t);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),at(o)}update(e){return Xr(this),this.iHash.update(e),this}digestInto(e){Xr(this),ja(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:i,finished:o,destroyed:s,blockLen:r,outputLen:a,canXOF:c}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=r,e.outputLen=a,e.canXOF=c,e.oHash=t._cloneInto(e.oHash),e.iHash=i._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},ca=(()=>{let n=((e,t,i)=>new Ty(e,t).update(i).digest());return n.create=(e,t)=>new Ty(e,t),n})()});function Ly(n){return"dh"in n?n:{publicKey:n.publicKey,dh:e=>pa(n.secretKey,e)}}async function DO(n,e){let t;try{t=await n.dh(e)}catch(i){throw i instanceof bt?i:new bt("invalid public key")}return KO(t)}function pc(){let n=or.utils.randomSecretKey();return{secretKey:n,publicKey:or.getPublicKey(n)}}function FO(n){return{secretKey:n,publicKey:or.getPublicKey(n)}}function tu(...n){let e=0;for(let o of n)e+=o.length;let t=new Uint8Array(e),i=0;for(let o of n)t.set(o,i),i+=o.length;return t}function KO(n){let e=0;for(let t of n)e|=t;if(e===0)throw new bt("invalid public key (all-zero shared secret)");return n}function pa(n,e){let t;try{t=or.getSharedSecret(n,e)}catch{throw new bt("invalid public key")}return KO(t)}function zO(n,e){let t=ca(Ze,n,e),i=ca(Ze,t,Uint8Array.of(1)),o=ca(Ze,t,tu(i,Uint8Array.of(2)));return[i,o]}function $O(n){let e=new Uint8Array(12),t=new DataView(e.buffer);return t.setUint32(4,n>>>0,!0),t.setUint32(8,Math.floor(n/2**32),!0),e}function Ur(n,e,t){for(let[i,o]of[["collection",n],["target device",t]])if(o.length!==16)throw new bt(`${i} ID must be 16 bytes`);if(e&&e.length!==16)throw new bt("grant ID must be 16 bytes");return tu(BN,n,e??VN,t)}var BO,Li,NO,VO,ac,IA,My,bt,lc,jy,cc,Uy,BN,VN,da=C(()=>{"use strict";dA();qy();xA();gr();BO="Noise_IK_25519_ChaChaPoly_SHA256",Li=32,NO=32,VO=65535,ac=16,IA=VO-ac,My=2**30;bt=class extends Error{constructor(e){super(e),this.name="NoiseError"}},lc=class{constructor(e=null){this.k=e}k;n=0;hasKey(){return this.k!==null}get count(){return this.n}encrypt(e,t){if(!this.k)return t;if(this.n>=My)throw new bt("session message limit reached");let i=cA(this.k,$O(this.n),e).encrypt(t);return this.n++,i}decrypt(e,t){if(!this.k)return t;if(this.n>=My)throw new bt("session message limit reached");let i;try{i=cA(this.k,$O(this.n),e).decrypt(t)}catch{throw new bt("decryption failed")}return this.n++,i}},jy=class{ck;h;cs=new lc;constructor(e){let t=new TextEncoder().encode(e);t.length<=NO?(this.h=new Uint8Array(NO),this.h.set(t)):this.h=Ze(t),this.ck=this.h}mixKey(e){let[t,i]=zO(this.ck,e);this.ck=t,this.cs=new lc(i)}mixHash(e){this.h=Ze(tu(this.h,e))}encryptAndHash(e){let t=this.cs.encrypt(this.h,e);return this.mixHash(t),t}decryptAndHash(e){let t=this.cs.decrypt(this.h,e);return this.mixHash(e),t}split(){let[e,t]=zO(this.ck,new Uint8Array(0));return[new lc(e),new lc(t)]}},cc=class{constructor(e){this.opts=e;if(e.remoteStatic.length!==Li)throw new bt("remote static key must be 32 bytes");this.e=e.ephemeral??pc(),this.ss.mixHash(e.prologue),this.ss.mixHash(e.remoteStatic)}opts;ss=new jy(BO);e;state="start";async writeMessage1(e){if(this.state!=="start")throw new bt("handshake out of order");this.state="sent";let t=Ly(this.opts.staticKey),i=this.ss;i.mixHash(this.e.publicKey),i.mixKey(pa(this.e.secretKey,this.opts.remoteStatic));let o=i.encryptAndHash(t.publicKey);i.mixKey(await DO(t,this.opts.remoteStatic));let s=i.encryptAndHash(e),r=tu(this.e.publicKey,o,s);if(r.length>VO)throw new bt("handshake message too large");return r}async readMessage2(e){if(this.state!=="sent")throw new bt("handshake out of order");if(e.length<Li+ac)throw new bt("handshake message too short");this.state="done";let t=this.ss,i=e.subarray(0,Li);t.mixHash(i),t.mixKey(pa(this.e.secretKey,i)),t.mixKey(await DO(Ly(this.opts.staticKey),i));let o=t.decryptAndHash(e.subarray(Li)),[s,r]=t.split();return{payload:o,transport:{send:s,recv:r,handshakeHash:t.h,remoteStatic:this.opts.remoteStatic}}}},Uy=class{constructor(e){this.opts=e;this.e=e.ephemeral??pc(),this.ss.mixHash(e.prologue),this.ss.mixHash(e.staticKey.publicKey)}opts;ss=new jy(BO);e;rs=null;re=null;state="start";readMessage1(e){if(this.state!=="start")throw new bt("handshake out of order");if(this.state="done",e.length<Li+Li+ac+ac)throw new bt("handshake message too short");let t=this.ss,i=e.subarray(0,Li).slice();t.mixHash(i),t.mixKey(pa(this.opts.staticKey.secretKey,i));let o=t.decryptAndHash(e.subarray(Li,Li+Li+ac));t.mixKey(pa(this.opts.staticKey.secretKey,o));let s=t.decryptAndHash(e.subarray(Li+Li+ac));return this.re=i,this.rs=o,this.state="read",{remoteStatic:o,payload:s}}writeMessage2(e){if(this.state!=="read"||!this.re||!this.rs)throw new bt("handshake out of order");this.state="done";let t=this.ss;t.mixHash(this.e.publicKey),t.mixKey(pa(this.e.secretKey,this.re)),t.mixKey(pa(this.e.secretKey,this.rs));let i=t.encryptAndHash(e),[o,s]=t.split();return{message:tu(this.e.publicKey,i),transport:{send:s,recv:o,handshakeHash:t.h,remoteStatic:this.rs}}}},BN=new TextEncoder().encode("mdbase/v1/client"),VN=new Uint8Array(16)});function FN(n,e,t){return new Promise((i,o)=>{let s=()=>o(A("cancelled","connect aborted"));t?.addEventListener("abort",s,{once:!0}),n.onmessage=r=>{t?.removeEventListener("abort",s),n.onmessage=a=>{e.push(a)},i(r)},n.onclose=r=>{t?.removeEventListener("abort",s),o(r??A("unavailable","connection closed during the handshake"))}})}function RA(n,e,t=CA,i=[]){let o=new Uint8Array(0),s=!1,r=setTimeout(()=>l(),t);r.unref?.();let a={ondata:null,onclose:null,write(p){if(s)throw A("unavailable","connection closed");for(let d=0;d<p.length;d+=IA){if(e.send.count>=My-1)throw l(),A("unavailable","session message limit reached; reconnecting");n.send(e.send.encrypt(o,p.subarray(d,d+IA)))}},close(){s||(s=!0,clearTimeout(r),n.close())}},c=p=>{if(s)return;let d;try{d=e.recv.decrypt(o,p)}catch{l(A("unavailable","transport message failed authentication","noise"));return}a.ondata?.(d)};if(n.onmessage=c,n.onclose=p=>l(p),i.length){let p=i.splice(0);queueMicrotask(()=>p.forEach(c))}function l(p){s||(s=!0,clearTimeout(r),n.close(),a.onclose?.(p))}return a}function Nr(n){return{description:n.description,async open(e,t){let i=()=>A("cancelled","connect aborted");if(t?.aborted)throw i();let o=await n.target(t);if(t?.aborted)throw i();let s=await o.openCarrier(t);if(t?.aborted)throw s.close(),i();try{let r=new cc({prologue:o.prologue,staticKey:n.staticKey,remoteStatic:o.remoteStatic}),a=[],c=FN(s,a,t);c.catch(()=>{}),o.preamble&&s.send(o.preamble);let l=await r.writeMessage1(n.firstPayload?n.firstPayload(e):fe(e));if(t?.aborted)throw i();s.send(l);let{payload:p,transport:d}=await r.readMessage2(await c),u=we(p);return{port:df(RA(s,d,n.lifetimeMs,a)),helloResponse:u,...o.device?{device:o.device}:{}}}catch(r){throw s.close(),J(r)?r:r instanceof bt?A("unauthenticated",`handshake failed: ${r.message}`,"noise"):A("unavailable",`handshake failed: ${String(r)}`)}}}}function dc(n,e=KN,t){return new Promise((i,o)=>{let s;try{s=e(n)}catch(d){o(J(d)?d:A("unavailable",`cannot open ${n}: ${String(d)}`));return}s.binaryType="arraybuffer";let r=!1,a=null,c=null,l={get onmessage(){return a},set onmessage(d){a=d},get onclose(){return c},set onclose(d){c=d},send(d){s.send(d)},close(){try{s.close(1e3)}catch{}}},p=()=>{s.close(),o(A("cancelled","connect aborted"))};t?.addEventListener("abort",p,{once:!0}),s.onopen=()=>{r=!0,t?.removeEventListener("abort",p),i(l)},s.onmessage=d=>{let u=d.data;u instanceof ArrayBuffer?a?.(new Uint8Array(u)):ArrayBuffer.isView(u)&&a?.(new Uint8Array(u.buffer,u.byteOffset,u.byteLength))},s.onerror=()=>{},s.onclose=d=>{let u=WN(d.code,d.reason);r?c?.(u):(t?.removeEventListener("abort",p),o(u??A("unavailable",`cannot connect to ${n}`)))}})}function WN(n,e){switch(n){case 4404:return A("unavailable",e||"no device of this collection is online","no_device_online");case 4401:return A("unauthenticated",e||"relay refused the session");case 4403:return A("forbidden",e||"relay refused the session");case 4429:return A("rate_limited",e||"rate limited");default:return}}function WO(n){let e=new Uint8Array(0),t={onmessage:null,onclose:null,send(i){if(i.length>65535)throw A("too_large","Noise message over 65535 bytes");let o=new Uint8Array(2+i.length);o[0]=i.length>>8,o[1]=i.length&255,o.set(i,2),n.write(o)},close(){n.close()}};return n.ondata=i=>{let o=new Uint8Array(e.length+i.length);o.set(e),o.set(i,e.length);let s=0;for(;o.length-s>=2;){let r=o[s]<<8|o[s+1];if(o.length-s-2<r)break;t.onmessage?.(o.slice(s+2,s+2+r)),s+=2+r}e=o.slice(s)},n.onclose=i=>t.onclose?.(i?A("unavailable",i.message):void 0),t}var CA,KN,uc=C(()=>{"use strict";Je();re();da();mp();CA=1440*60*1e3;KN=n=>{let e=globalThis.WebSocket;if(!e)throw A("unavailable","no WebSocket implementation; pass webSocket");return new e(n)}});function YN(n){return typeof n=="string"&&Object.hasOwn(HO,n)?HO[n]:4e3}function ua(n,e){let t=typeof e=="string"&&GN.has(e)?e:void 0,i=eA(n),o={relayCloseCode:i.closeCode,relayCloseClass:i.closeClass},s=(r,a,c,l)=>A(r,a,{reason:c,details:o,...l===void 0?{}:{retryAfterMs:l}});switch(i.closeCode){case 4401:return s("unauthenticated",t??"relay: unauthenticated","relay_unauthenticated");case 4403:return s("forbidden",t??"relay: grant inactive",t??"grant_inactive");case 4404:return t&&(o.relay=t),s("unavailable","no device of this collection is online","no_device_online");case 4429:return s("rate_limited",t??"relay: busy",t??"connector_busy",5e3);case 4e3:return t==="grant_lease_expired"?s("unavailable","grant lease expired",t,1e3):t==="device_key_mismatch"?s("unauthenticated","relay: the routed key is not the device's",t):s("unavailable",`relay closed the pipe: ${t??"unknown"}`,t??"pipe_closed");default:return s("unavailable",`relay connection closed${i.closeCode===null?"":` (${i.closeCode})`}`,"relay_closed")}}function JN(n){let e=globalThis.WebSocket;if(!e)throw A("unavailable","no WebSocket implementation; pass webSocket");return new e(n)}function fc(n,e,t=JN,i){let o="";try{o=new URL(n).protocol}catch{return Promise.reject(A("invalid_request",`invalid relay URL ${n}`,"relay_url"))}return o!=="wss:"&&!!1?Promise.reject(A("invalid_request","relay pipes require wss:","relay_insecure")):e.grant?new Promise((s,r)=>{let a;try{a=t(n)}catch(w){r(A("unavailable",`cannot open ${n}: ${String(w)}`));return}a.binaryType="arraybuffer";let c=!1,l,p=new Uint8Array(0),d=null,u=null,f={get onmessage(){return d},set onmessage(w){d=w},get onclose(){return u},set onclose(w){u=w,w&&l&&w(l)},send(w){if(l)throw l;if(w.length>65535)throw A("too_large","Noise message over 65535 bytes");let b=new Uint8Array(4+w.length);new DataView(b.buffer).setUint32(0,w.length),b.set(w,4),a.send(b)},close(){try{a.close(1e3)}catch{}}},h=w=>{l||(l=w,c?u?.(w):(i?.removeEventListener("abort",m),r(w)))},m=()=>{a.close(),h(A("cancelled","connect aborted"))};i?.addEventListener("abort",m,{once:!0}),a.onopen=()=>{a.send(JSON.stringify({type:"pipe_auth",access_token:e.accessToken,collection:e.collection,grant:e.grant,device:e.device,device_noise_pk:ht(e.devicePublicKey)}))},a.onmessage=w=>{if(l)return;let b=w.data;if(typeof b=="string"){let _;try{_=JSON.parse(b)}catch{return}_.type==="pipe_opened"&&!c?(c=!0,i?.removeEventListener("abort",m),s(f)):_.type==="pipe_close"&&(h(ua(YN(_.reason),_.reason)),a.close());return}if(!c)return;let g=b instanceof ArrayBuffer?new Uint8Array(b):ArrayBuffer.isView(b)?new Uint8Array(b.buffer,b.byteOffset,b.byteLength):null;if(!g)return;if(g.length>HN){a.close(),h(A("too_large","relay frame over the limit"));return}let y=new Uint8Array(p.length+g.length);y.set(p),y.set(g,p.length);let v=0;for(;y.length-v>=4;){let _=new DataView(y.buffer,y.byteOffset+v,4).getUint32(0);if(_>65535){a.close(),h(A("internal","relay sent an oversized Noise message"));return}if(y.length-v-4<_)break;d?.(y.slice(v+4,v+4+_)),v+=4+_}p=y.slice(v)},a.onerror=()=>{},a.onclose=w=>h(ua(w.code,w.reason))}):Promise.reject(A("invalid_request","relay pipes require a grant","grant_required"))}var HN,GN,HO,nu=C(()=>{"use strict";um();re();tA();Je();HN=65539,GN=new Set("unauthenticated grant_inactive connector_offline connector_busy device_mismatch device_key_mismatch closed client_closed handshake_timeout idle lifetime frame_too_large invalid_frame not_served relay_closing authorization_unavailable grant_revoked grant_lease_expired grant_pending_approval grant_revoked_on_device unknown_grant".split(" ")),HO=Object.assign(Object.create(null),{unauthenticated:4401,grant_inactive:4403,grant_revoked_on_device:4403,grant_pending_approval:4403,unknown_grant:4403,connector_offline:4404,connector_busy:4429})});function EA(n){let e=new Uint8Array(0),t=!1,i,o=null,s=null,r=[],a=0,c={get onmessage(){return o},set onmessage(d){for(o=d;d&&!t&&r.length&&o===d;){let u=r.shift();a-=u.length,d(u)}},get onclose(){return s},set onclose(d){s=d,d&&t&&i&&d(i)},send(d){if(t)throw A("unavailable","relay pipe closed");if(d.length>OA)throw A("too_large","Noise message over 65535 bytes");let u=new Uint8Array(4+d.length);new DataView(u.buffer).setUint32(0,d.length),u.set(d,4),n.send(u)},close(){t||(t=!0,r.length=0,a=0,n.close())}},l=(d,u)=>{t||(t=!0,e=new Uint8Array(0),r.length=0,a=0,i=ua(d,u),n.close(),s?.(i))},p=d=>{if(!t){if(o)return o(d);if(r.length>=XN||a+d.length>ZN)return l(4e3,"invalid_frame");r.push(d),a+=d.length}};return n.onmessage=d=>{if(t)return;if(d.length>GO)return l(4e3,"invalid_frame");let u=new Uint8Array(e.length+d.length);u.set(e),u.set(d,e.length);let f=0;for(;u.length-f>=4;){let h=new DataView(u.buffer,u.byteOffset+f,4).getUint32(0);if(h>OA)return l(4e3,"invalid_frame");if(u.length-f-4<h)break;let m=u.slice(f+4,f+4+h);if(f+=4+h,p(m),t)return}e=u.slice(f),e.length>GO&&l(4e3,"invalid_frame")},n.onclose=d=>l(d?.code,d?.reason),c}async function YO(n){try{return await n()}catch(e){if(J(e))throw e;if(e?.code==="not_authorized")throw A("unauthenticated","Connect authorization is missing","not_authorized");let i=e?.cause;throw typeof i?.code=="number"?ua(i.code,typeof i.reason=="string"?i.reason:void 0):A("unavailable","the relay pipe could not be opened","relay_unavailable")}}function iu(n,e){let t=n.targets.filter(o=>Ny.test(o.device)&&/^[0-9a-f]{64}$/.test(o.noise_pk)&&!!o.relay_collection&&Ny.test(o.relay_collection)),i=o=>(o.online===!0?0:o.online===void 0?1:2)*2+(o.device===e?0:1);return t.map((o,s)=>({target:o,index:s,rank:i(o)})).sort((o,s)=>o.rank-s.rank||o.index-s.index).map(({target:o})=>o)}function qA(n,e){let t=iu(n,e),i=t.filter(o=>o.online===!0);return i.length?i:t.slice(0,1)}function TA(n,e){return!e?.aborted&&J(n)&&(n.code==="unavailable"||n.code==="rate_limited")}function JO(n){let e=n.collection,t=n.next,i=n.staticKey;if(!Ny.test(e))throw A("invalid_request","collection must be a UUID");let o=t.route.bind(t),s=t.openPipe.bind(t),r=`next-relay:${e}`,a=null;return hf({description:r,open:async(c,l)=>{if(l?.aborted)throw A("cancelled","connect aborted");let p=await YO(()=>o(e,l?{signal:l}:{}));if(l?.aborted)throw A("cancelled","connect aborted");if(p.collection.toLowerCase()!==e.toLowerCase()||!Ny.test(p.grant))throw A("unauthenticated","the route does not match this collection's grant","route_mismatch");let d=wi(p.availability);if(d?.state==="unavailable")throw Fn(d.reason);let u=qA(p,a);if(!u.length)throw A("unavailable",p.reason==="no_device_registered"?"this collection has no device set up to serve it":"no device of this collection is online",p.reason??"no_device_online");let f;for(let h of u){let m=Object.freeze({...h}),w=m.noise_pk,b=new Uint8Array(32);for(let y=0;y<32;y++)b[y]=parseInt(w.slice(2*y,2*y+2),16);let g=Nr({description:r,staticKey:i,target:async()=>({prologue:Ur(N(m.relay_collection),N(p.grant),N(m.device)),remoteStatic:b,device:m.device,openCarrier:async y=>{let v=await YO(()=>s(e,m,y?{signal:y}:{}));return EA(v)}})});try{let y=await g.open(c,l);return a=y.device??null,y}catch(y){if(!TA(y,l))throw y;a===m.device&&(a=null),f??=y}}throw f},get target(){return a}})}var OA,GO,XN,ZN,Ny,MA=C(()=>{"use strict";ve();No();re();da();uc();nu();gp();OA=65535,GO=4+OA,XN=16,ZN=1<<20,Ny=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i});function XO(n,e){let t=()=>A("unauthenticated","people scope changed","people_fenced"),i={collection:n,isCurrent:()=>e.holds(n),async request(o,s={}){if(o!=="identity"&&o!=="members")throw A("invalid_request","invalid people resource");for(let r=0;;r++){if(s.signal?.throwIfAborted(),!i.isCurrent())throw t();let a=await e.accessToken(n,r>0),{status:c,body:l}=await t8(e,`/v1/authorities/${n}/${o}`,a,s.signal);if(!i.isCurrent())throw t();if(!(c===401&&r===0)){if(c===401)throw A("unauthenticated","people credential is no longer current","people_fenced");if(c===403){let p=l?.error?.code;throw p==="approval_required"?Fn("approval_required"):A("forbidden","people access was refused",o==="members"&&p==="insufficient_access"?"people_permission_declined":"people_access")}if(c===404)throw A("upgrade_required","people metadata is unsupported","people_unsupported");if(c!==200||!l)throw LA();return l}}}};return i}async function t8(n,e,t,i){let o=new AbortController,s=()=>o.abort();i?.addEventListener("abort",s,{once:!0});let r=setTimeout(s,e8);r.unref?.();try{let a=await n.fetch(`${n.cpOrigin}${e}`,{method:"GET",headers:{authorization:`Bearer ${t}`},signal:o.signal,redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer"}),c=await a.text();if(c.length>QN)throw LA();let l=null;try{let p=JSON.parse(c);p&&typeof p=="object"&&!Array.isArray(p)&&(l=p)}catch{l=null}return{status:a.status,body:l}}catch(a){throw i?.aborted?A("cancelled","request cancelled"):a instanceof ne?a:LA()}finally{clearTimeout(r),i?.removeEventListener("abort",s)}}var QN,e8,LA,ZO=C(()=>{"use strict";No();re();QN=1024*1024,e8=15e3,LA=()=>A("unavailable","people metadata is unavailable","people_response")});function NA(n){if(!/^sha256:[a-f0-9]{64}$/.test(n))throw Dr();return Uint8Array.from(n.slice(7).match(/../g),e=>parseInt(e,16))}function jA(n){if(!(n instanceof Map)||[...n.keys()].some(e=>typeof e!="number"))throw Dr();return n}function Dy(n,e){if(!(n instanceof Uint8Array)||n.length!==e)throw Dr();return n.slice()}function UA(n){if(n instanceof _t)return n.value;if(n instanceof Map){if([...n.keys()].some(e=>typeof e!="string"))throw Dr();return Object.fromEntries([...n].map(([e,t])=>[e,UA(t)]))}if(Array.isArray(n))return n.map(UA);if(n===null||["string","boolean","number"].includes(typeof n))return n;throw Dr()}async function ru(n,e,t,i){let o=fe(new Map([[0,1],[1,e],...t].sort(([r],[a])=>Number(r)-Number(a)))),s;try{s=await n.declaredSetup(o,i);let r=jA(we(s));if(r.get(0)!==1)throw Dr();let a=r.get(1),c=a==="review"?[0,1,2,3,4,5,6,7,8,9,10]:a==="pending"?[0,1,2]:a==="receipt"?[0,1,3]:a==="cancelled"?[0,1]:[];if(r.size!==c.length||c.some(f=>!r.has(f)))throw Dr();if(a==="cancelled")return{kind:a};if(a==="receipt")return{kind:a,receipt:Pn.dec(r.get(3))};let l=Dy(r.get(2),16);if(a==="pending")return{kind:a,ticket:l};if(a!=="review"||!["ready","setup_required","incompatible"].includes(r.get(3))||typeof r.get(8)!="string")throw Dr();let p=jA(r.get(9)),d=r.get(10);if(!(p instanceof Map)||p.size!==2||![p.get(0),p.get(1)].every(f=>Number.isSafeInteger(f)&&Number(f)>=0&&Number(f)<=256)||!Array.isArray(d)||d.length>32)throw Dr();let u=d.map(f=>{let h=jA(f);if(h.size!==2||typeof h.get(0)!="string"||!["create","skip"].includes(h.get(1)))throw Dr();return Object.freeze({path:h.get(0),action:h.get(1)})});return{kind:a,ticket:l,revision:Dy(r.get(4),32),declaration:QO(Dy(r.get(7),32)),application:r.get(8),promoted:p.get(0),retained:p.get(1),records:Object.freeze(u),assessment:ta({status:r.get(3)==="ready"?"current":r.get(3)==="incompatible"?"conflict":"provision",assessmentDigest:"sha256:"+QO(Dy(r.get(5),32)),review:UA(r.get(6))},!0)}}finally{o.fill(0),s?.fill(0)}}var Dr,QO,eE=C(()=>{"use strict";Je();re();ss();tn();Dr=()=>A("internal","Invalid Native setup reply.","declared_setup_codec"),QO=n=>Array.from(n,e=>e.toString(16).padStart(2,"0")).join("")});function n8(n){return new Promise((e,t)=>{if(n?.aborted)return t(A("cancelled","Setup cancelled."));let i=()=>{clearTimeout(o),t(A("cancelled","Setup cancelled."))},o=setTimeout(()=>{n?.removeEventListener("abort",i),e()},100);n?.addEventListener("abort",i,{once:!0})})}function tE(n){let{client:e,journal:t}=n,i=n.operations.includes("assess_collection_setup")&&n.operations.includes("apply_collection_setup"),o=new WeakMap,s=new WeakSet,r=!1,a;async function c(b){if(r)throw A("rate_limited","A setup operation is already running.");r=!0;try{return a&&(await a,a=void 0),await b()}finally{r=!1}}async function l(b,g){if(b||await e.readyForRead(g),await n.assertCurrent(),g?.aborted)throw A("cancelled","Setup cancelled.");if(b&&(b.closed||e.currentSession()!==b))throw us()}async function p(b,g){try{await ru(b,"cancel",[[2,g]],AbortSignal.timeout(1e3))}catch{}}async function d(b={}){await l(void 0,b.signal);let g=await e.readyForRead(b.signal);await l(g,b.signal);let y=await wm(n.manifest);await l(g,b.signal);let v=Oi(b.adopt===void 0?{}:{adopt:b.adopt}),_=fy(b.records),k=[];v.adopt&&Object.keys(v.adopt).length&&k.push([3,new Map(Object.entries(v.adopt).map(([x,P])=>[x,NA(P)]))]),_.length&&k.push([4,_.map(x=>new Map([[0,x.path],[1,x.document]]))]);let S;try{let x=await ru(g,"assess",k,b.signal);await l(g,b.signal);for(let P=0;x.kind==="pending";P++){if(S=x.ticket,P>=512)throw ou();await n8(b.signal),await l(g,b.signal),x=await ru(g,"poll",[[2,S]],b.signal),await l(g,b.signal)}if(x.kind!=="review")throw ou();if(S=x.ticket,x.declaration!==y||x.application!==n.manifest?.id)throw us();if(x.records.length!==_.length||x.records.some((P,I)=>P.path!==_[I].path))throw ou();return{s:g,review:x,options:{records:_,...v.adopt?{adopt:Object.freeze({...v.adopt})}:{}}}}catch(x){throw S&&await p(g,S),x}}async function u(b){await l(void 0,b);let g=await t.load();if(await l(void 0,b),!g)return;let y;try{y=await e.receipt(g,{signal:b})}catch(v){throw fa(g,v)}if(await l(void 0,b),y.mutation!==g||y.state!=="confirmed"&&y.state!=="rejected")throw fa(g);await t.clear(g)}function f(b,g){return Bd(g.assessment,{canManage:!0,canCreateRecords:b.hello.grant.capabilities.includes("records.create"),records:g.records.map(y=>({path:y.path,free:y.action==="create"})),...g.promoted?{promoted:g.promoted}:{}})}let h=(b,g)=>JSON.stringify([b.status,b.canApply,b.summary,b.changes,b.conflicts,b.adoptable,b.packs,b.staged,b.records,b.refusal??null,g.promoted,g.retained]);async function m(b){if(await l(void 0,b.signal),!i){if(n.operations.includes("apply_collection_setup")||n.operations.includes("assess_collection_setup"))throw ou();let k=Bd({status:"current",assessmentDigest:`sha256:${"0".repeat(64)}`,review:{configuration:[],packs:[],staged:[]}},{canManage:!1,canCreateRecords:!1,records:[]});return s.add(k),k}await u(b.signal);let{s:g,review:y,options:v}=await d(b),_=f(g,y);return o.set(_,{session:g,review:y,options:v,consumed:!1}),_}return Object.freeze({assess(b={}){return c(async()=>{let g=await m(b),y=o.get(g);return y&&(a=p(y.session,y.review.ticket),await l(y.session,b.signal)),g.status==="current"?"ready":g.refusal?.code==="installed_newer"?"incompatible":"setup_required"})},plan(b={}){return c(()=>m(b))},async apply(b,g={}){return c(async()=>{if(s.has(b))return await l(void 0,g.signal),"ready";let y=o.get(b);if(!y)throw new TypeError("setup.apply needs the original plan returned by setup.plan");if(y.consumed)throw us();if(b.refusal)throw A(b.refusal.code==="setup_conflict"?"conflict":b.refusal.code==="installed_newer"?"upgrade_required":"forbidden",b.refusal.message,b.refusal.code);if(b.status==="current"){await l(y.session,g.signal);let v=await d({signal:g.signal});if(await p(v.s,v.review.ticket),v.review.assessment.status!=="current")throw us();return"ready"}y.consumed=!0;for(let v=0;;v++){let _=crypto.randomUUID(),k;try{k=await t.begin(_)}catch(P){throw fa(_,P)}if(k!==_)throw fa(k);let S=!1,x=!1;try{await l(y.session,g.signal),S=!0;let P=await ru(y.session,"apply",[[2,y.review.ticket],[3,N(_)],[4,y.review.revision],[5,NA(y.review.assessment.assessmentDigest)]],g.signal);if(await n.assertCurrent(),P.kind!=="receipt"||P.receipt.mutation!==_)throw fa(_);let I=P.receipt.state==="pending"?await e.awaitReceipt(_,{timeoutMs:3e4,signal:g.signal}):P.receipt;if(await n.assertCurrent(),I.mutation!==_||I.state!=="confirmed"&&I.state!=="rejected")throw fa(_);if(x=!0,await t.clear(_),I.state==="rejected"||(I.conflicts?.length??0)>0||I.status!==void 0&&I.status!=="applied")throw us(_,I.problem);let O=await d({signal:g.signal});if(O.review.assessment.status!=="current")throw ou();return await p(O.s,O.review.ticket),"ready"}catch(P){if(!S||x||Da(P)&&P.code!=="outcome_unknown"){if(await t.clear(_),!x&&(Da(P)?P.code==="not_found"||P.code==="conflict":!S&&J(P,"conflict")&&P.reason==="setup_changed")){if(v)throw us(_,P);let O=await d({...y.options,signal:g.signal});try{if(await l(O.s,g.signal),O.review.assessment.status!=="provision"||h(f(O.s,O.review),O.review)!==h(b,y.review))throw us(_,P)}catch(R){throw await p(O.s,O.review.ticket),R}y={...y,session:O.s,review:O.review};continue}throw new ne((J(P)?P:us()).toProblem(),{mutationId:_,cause:P})}throw fa(_,P)}}})}})}var us,fa,ou,nE=C(()=>{"use strict";re();ve();qs();ss();hy();_m();eE();us=(n,e)=>new ne(A("conflict","This collection changed since setup was reviewed. Review it again.","setup_changed").toProblem(),{...n?{mutationId:n}:{},...e?{cause:e}:{}}),fa=(n,e)=>new ne(A("outcome_unknown","Reconcile the original setup before trying again.","setup_outcome_unknown").toProblem(),{mutationId:n,...e?{cause:e}:{}}),ou=()=>A("unavailable","Native setup is unavailable.","resource_setup_unavailable")});function rE(n){let e=new Uint8Array([...n.aad,...new TextEncoder().encode("\0declared-setup-attempt-v1")]),t=()=>A("unavailable","Protected Native setup attempt storage is unavailable.","grant_storage");async function i(){let s=await n.grant();await n.assertCurrent(s);let r=await n.store();if(!r.getSetupAttempt||!r.putSetupAttemptIfAbsent||!r.deleteSetupAttempt)throw t();return{grant:s,store:r}}async function o(s,r){let a;try{if(s.length<29||s.length>2048)throw t();a=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:s.slice(0,12),additionalData:e},r.refreshKey,s.slice(12)));let c=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(a)),l=Array.from(r.noisePublicKey,p=>p.toString(16).padStart(2,"0")).join("");if(c.version!==1||!iE.test(c.mid)||c.noise!==l||Object.keys(c).sort().join(",")!=="mid,noise,version")throw t();return await n.assertCurrent(r),c.mid}catch{throw t()}finally{a?.fill(0)}}return{async load(){let{grant:s,store:r}=await i(),a=await r.getSetupAttempt(s.collection);return await n.assertCurrent(s),a?o(a,s):void 0},async begin(s){if(!iE.test(s))throw t();let{grant:r,store:a}=await i(),c=crypto.getRandomValues(new Uint8Array(12)),l=new TextEncoder().encode(JSON.stringify({version:1,mid:s,noise:Array.from(r.noisePublicKey,u=>u.toString(16).padStart(2,"0")).join("")})),p;try{p=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:c,additionalData:e},r.refreshKey,l))}finally{l.fill(0)}await n.assertCurrent(r);let d=await a.putSetupAttemptIfAbsent(r.collection,new Uint8Array([...c,...p]));return o(d,r)},async clear(s){let{grant:r,store:a}=await i(),c=await a.getSetupAttempt(r.collection);c&&await o(c,r)===s&&(await n.assertCurrent(r),await a.deleteSetupAttempt(r.collection,c))}}}var iE,oE=C(()=>{"use strict";re();iE=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/});function su(){throw A("unauthenticated","the stored grant belongs to another app","grant_storage")}function sE(n,e,t={}){let i=globalThis.indexedDB;if(!i)throw A("unavailable","IndexedDB is not available here","grant_storage");let o=t.owner;if(o!==void 0&&!Hs(o))throw A("invalid_request","invalid grant store owner","grant_storage");let s=o===void 0?`mdbase.app-grants.v1.${encodeURIComponent(n)}.${e}`:`mdbase.app-grants.v2.${encodeURIComponent(n)}.${encodeURIComponent(o)}.${e}`,r=h=>h===void 0||o===void 0||h.owner===o?h:su(),a=h=>o===void 0||h===void 0||h.owner===o,c=h=>o===void 0?h:{...h,owner:o},l=null,p=()=>l??=new Promise((h,m)=>{let w=i.open(s,2);w.onupgradeneeded=()=>{for(let b of[DA,ha,hc])w.result.objectStoreNames.contains(b)||w.result.createObjectStore(b)},w.onsuccess=()=>{w.result.onversionchange=()=>{w.result.close(),l=null},h(w.result)},w.onerror=()=>{l=null,m(A("unavailable","grant storage could not be opened","grant_storage"))}}),d=async(h,m,w)=>{let b=await p();return new Promise((g,y)=>{let v=b.transaction([...h],m,{durability:"strict"}),_,k=!1;v.oncomplete=()=>k?g(_):y(A("unavailable","grant storage returned no result","grant_storage")),v.onabort=v.onerror=()=>y(A("unavailable","grant storage transaction failed","grant_storage"));try{w(v,S=>{_=S,k=!0})}catch{try{v.abort()}catch{}}})},u=(h,m,w)=>d([h],m,(b,g)=>w(b.objectStore(h),g)),f=(h,m)=>u(h,"readonly",(w,b)=>{let g=w.get(m);g.onsuccess=()=>b(g.result)});return{getSetupAttempt:async h=>r(await f(hc,h))?.bytes,putSetupAttemptIfAbsent:async(h,m)=>r(await u(hc,"readwrite",(w,b)=>{let g=w.get(h);g.onsuccess=()=>{if(g.result!==void 0)return b(g.result);let y=c({bytes:m.slice()});w.add(y,h).onsuccess=()=>b(y)}})).bytes,deleteSetupAttempt:async(h,m)=>{await u(hc,"readwrite",(b,g)=>{let y=b.get(h);y.onsuccess=()=>{if(!a(y.result))return g("refused");let v=y.result?.bytes;if(!v||v.length!==m.length||!v.every((_,k)=>_===m[k]))return g("done");b.delete(h).onsuccess=()=>g("done")}})==="refused"&&su()},getIdentity:async()=>r(await f(DA,"installation")),putIdentityIfAbsent:async h=>r(await u(DA,"readwrite",(m,w)=>{let b=m.get("installation");b.onsuccess=()=>{if(b.result!==void 0)return w(b.result);let g=c(h);m.add(g,"installation").onsuccess=()=>w(g)}})),getGrant:async h=>r(await f(ha,h)),listGrants:async()=>(await u(ha,"readonly",(h,m)=>{let w=h.getAll();w.onsuccess=()=>m(w.result)})).map(h=>r(h)),putGrant:async h=>{await u(ha,"readwrite",(w,b)=>{let g=w.get(h.collection);g.onsuccess=()=>{if(!a(g.result))return b("refused");w.put(c(h),h.collection).onsuccess=()=>b("done")}})==="refused"&&su()},deleteGrant:async h=>{await u(ha,"readwrite",(w,b)=>{let g=w.get(h);g.onsuccess=()=>{if(!a(g.result))return b("refused");w.delete(h).onsuccess=()=>b("done")}})==="refused"&&su()},clearGrants:async()=>{await d([ha,hc],"readwrite",(m,w)=>{let b=!1,g=2,y=()=>{--g===0&&w(b?"refused":"done")};for(let v of[ha,hc]){let _=m.objectStore(v);if(o===void 0){_.clear().onsuccess=y;continue}let k=_.openCursor();k.onsuccess=()=>{let S=k.result;if(!S)return y();a(S.value)?S.delete():b=!0,S.continue()}}})==="refused"&&su()}}}var DA,ha,hc,aE=C(()=>{"use strict";os();re();DA="identity",ha="grants",hc="native-setup-attempts"});var fE={};Ea(fE,{MdbaseAppGrants:()=>VA,deliverAppGrantCallback:()=>a8,mergeCollectionEntries:()=>c8});function o8(n){try{let e=Uint8Array.from(atob(n.replaceAll("-","+").replaceAll("_","/")),t=>t.charCodeAt(0));return e.length===32&&bn(e)===n}catch{return!1}}function a8(n){let e=globalThis.BroadcastChannel;if(!e)throw A("unavailable","BroadcastChannel is not available","authorization_callback");let t=new e(uE);t.postMessage({type:"callback",url:String(n)}),t.close()}function l8(){return{subscribe(n){let e=globalThis.BroadcastChannel;if(!e)throw A("unavailable","BroadcastChannel is not available","authorization_callback");let t=new e(uE);return t.onmessage=i=>{let o=i.data;o?.type==="callback"&&typeof o.url=="string"&&n(o.url)},()=>t.close()}}}function c8(n,e){let t=new Map;for(let i of n)t.set(i.collectionId,Object.freeze({collectionId:i.collectionId,displayName:i.displayName,kind:"cloud_copy",availability:i.availability??Object.freeze({state:"available"}),role:i.role}));for(let i of e)t.has(i.collectionId)||t.set(i.collectionId,Object.freeze({collectionId:i.collectionId,displayName:i.displayName,kind:"private",availability:i.availability,role:i.role}));return[...t.values()].sort((i,o)=>i.displayName.localeCompare(o.displayName)||i.collectionId.localeCompare(o.collectionId))}async function BA(n,e){let t=new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},n,e));if(t.length!==64)throw A("internal","unexpected signature length","authorization_signature");let i=0n;for(let s of t.subarray(32))i=i<<8n|BigInt(s);if(i<=lE/2n)return t;let o=lE-i;for(let s=63;s>=32;s--)t[s]=Number(o&0xffn),o>>=8n;return t}async function p8(n,e,t,i){let o=Math.floor(Date.now()/1e3),s=crypto.randomUUID(),r=[jC,Fv,"POST",e,await dE(t),await dE(i),o,s].join(`
|
|
130
|
-
`);return{[ud.version]:String(Fv),[ud.timestamp]:String(o),[ud.nonce]:s,[ud.signature]:bn(await BA(n,new TextEncoder().encode(r)))}}async function zA(n,e){let t=await crypto.subtle.generateKey({name:e,namedCurve:"P-256"},!1,n);return{privateKey:t.privateKey,publicKey:bn(new Uint8Array(await crypto.subtle.exportKey("raw",t.publicKey)))}}async function d8(){let n;try{n=await crypto.subtle.generateKey({name:"X25519"},!1,["deriveBits"])}catch{throw A("unavailable","this browser cannot keep a non-extractable X25519 key","browser_unsupported")}if(n.privateKey.extractable)throw A("unavailable","the Noise key must be non-extractable","browser_unsupported");return{privateKey:n.privateKey,publicKey:new Uint8Array(await crypto.subtle.exportKey("raw",n.publicKey))}}function u8(n){return{publicKey:n.noisePublicKey.slice(),dh:async e=>{let t=await crypto.subtle.importKey("raw",e,{name:"X25519"},!1,[]);return new Uint8Array(await crypto.subtle.deriveBits({name:"X25519",public:t},n.noisePrivateKey,256))}}}function f8(n,e){let t=new AbortController,i=()=>t.abort(),o=setTimeout(i,e);return o.unref?.(),n?.addEventListener("abort",i,{once:!0}),n?.aborted&&t.abort(),{signal:t.signal,done:()=>{clearTimeout(o),n?.removeEventListener("abort",i)}}}async function h8(n,e){let t=globalThis.navigator?.locks;if(t)return t.request(n,{mode:"exclusive"},e);let i=$y.get(n)??Promise.resolve(),o,s=new Promise(r=>{o=r});$y.set(n,s),await i;try{return await e()}finally{o(),$y.get(n)===s&&$y.delete(n)}}var i8,uE,fs,r8,lE,s8,bn,zy,cE,pE,dE,By,ma,$A,zr,$y,VA,hE=C(()=>{"use strict";fd();zd();ym();Jt();rs();Ll();oh();hm();VR();_m();ve();No();re();un();MA();da();uc();gp();nu();xp();ZO();nE();oE();Wb();aE();n_();i8=new Set(["owner","editor","viewer"]),uE="mdbase.app-grant.v1",fs=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,r8=15e3;lE=BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),s8=new TextEncoder().encode("mdbase-next client noise key v1\0");bn=n=>{let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")},zy=n=>crypto.getRandomValues(new Uint8Array(n)),cE=n=>{let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,n),e},pE=(...n)=>{let e=new Uint8Array(n.reduce((i,o)=>i+o.length,0)),t=0;for(let i of n)e.set(i,t),t+=i.length;return e};dE=async n=>bn(new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n))));By=(n,e)=>n.length===e.length&&n.every((t,i)=>t===e[i]),ma=(n,e)=>!!e&&n.collection===e.collection&&n.owner===e.owner&&By(n.noisePublicKey,e.noisePublicKey),$A=(n,e)=>ma(n,e)&&By(n.refresh,e.refresh),zr=()=>A("cancelled","the stored grant changed during this operation"),$y=new Map;VA=class{constructor(e){this.options=e;this.declaration=co(e.declaration),this.cpOrigin=Ci({environment:this.declaration.environment,appOrigin:this.declaration.origin,release:BR()}).cpOrigin;try{this.redirect=new URL(e.redirectUri)}catch{throw A("invalid_request","redirectUri must be an absolute URL","redirect_uri")}if(!(this.declaration.origin.startsWith("capacitor://")?jl(e.redirectUri,this.declaration.origin,this.declaration.manifest):this.redirect.protocol===new URL(this.declaration.origin).protocol&&this.redirect.origin===this.declaration.origin&&!this.redirect.hash))throw A("invalid_request","redirectUri must be a valid callback for this app","redirect_uri");this.fetcher=e.fetch??globalThis.fetch.bind(globalThis),this.callbacks=e.callbacks??l8(),this.storeValue=e.store??null}options;declaration;cpOrigin;redirect;fetcher;callbacks;storeValue;registration=null;tokens=new Map;routeProbe;refreshing=new Map;forgotten=new Set;epoch=0;register(){let e=this.registration??=vm({declaration:this.options.declaration,signal:new AbortController().signal,isCurrent:()=>!0,fetch:this.fetcher});return e.catch(()=>{this.registration===e&&(this.registration=null)}),e}ownerValue=null;owner(){return this.ownerValue??=Dx(is(this.declaration).manifest.id,rh(this.declaration))}async store(){if(this.storeValue)return this.storeValue;let e=this.owner();return this.storeValue=sE(this.cpOrigin,(await this.register()).id,{owner:e})}async identity(){let e=await this.store(),t=await e.getIdentity();if(t)return t;let i=await zA(["sign"],"ECDSA");return e.putIdentityIfAbsent({version:1,privateKey:i.privateKey,publicKey:i.publicKey})}async request(e,t,i){let o=f8(i,r8);try{let s;try{s=await this.fetcher(`${this.cpOrigin}${e}`,{...t,redirect:"error",credentials:"omit",signal:o.signal})}catch{throw i?.aborted?A("cancelled","request cancelled"):A("unavailable","cannot reach the control plane","control_unreachable")}let r=null;try{let a=await s.json();a&&typeof a=="object"&&!Array.isArray(a)&&(r=a)}catch{r=null}return{status:s.status,body:r}}finally{o.done()}}async authorize(e){e=Object.freeze({...e});let t=await this.prepareAuthorization(e).catch(i=>{throw e.popup.close(),i});try{e.popup.navigate(t.authorizationUri);let{collectionId:i}=await t.finish(e);return{collectionId:i}}finally{t.cancel();try{e.popup.close()}catch{}}}async prepareAuthorization(e={}){if(e=Object.freeze({...e}),e.collection!==void 0&&!fs.test(e.collection))throw A("invalid_request","collection must be a UUID");if(e.expectedAccountId!==void 0&&(!fs.test(e.expectedAccountId)||!e.authorizationNonce))throw A("invalid_request","original account and challenge required","authorization_binding");if(e.authorizationNonce!==void 0&&(!/^[A-Za-z0-9_-]{43}$/.test(e.authorizationNonce)||!o8(e.authorizationNonce)))throw A("invalid_request","invalid original challenge","authorization_binding");let t=new AbortController,i=e.signal?AbortSignal.any([e.signal,t.signal]):t.signal,o=this.epoch,s=()=>{if(i.aborted)throw A("cancelled","authorization fenced","authorization_cancelled");if(o!==this.epoch)throw zr()};s();let r=await this.register(),a=is(this.declaration),c=await this.identity(),l=await zA(["deriveBits"],"ECDH"),p=await zA(["sign"],"ECDSA"),d=await d8(),u=bn(zy(32)),f=bn(new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(u)))),h=bn(zy(24)),m=crypto.randomUUID(),w=new Date,b={protocol_version:lo,authorization_id:m,application_id:r.id,application_declaration_id:String(a.manifest.id),application_manifest_digest:r.manifestDigest,application_installation_id:await EC(c.publicKey),installation_signing_public_key:c.publicKey,grant_agreement_public_key:l.publicKey,grant_signing_public_key:p.publicKey,flow:"authorization_code",authorization_nonce:e.authorizationNonce??bn(zy(32)),issued_at:w.toISOString(),expires_at:new Date(w.getTime()+10*6e4).toISOString(),redirect_uri:this.redirect.href,state:h,code_challenge:f,contracts:a.contracts,requested_operations:[...a.operations],...a.files?{requested_files:a.files}:{},...e.collection?{collection_id:e.collection}:{}},g={binding:b,signature:bn(await BA(c.privateKey,qC(b)))},y=pE(s8,cE(16),N(m),cE(32),d.publicKey),v={public_key:bn(d.publicKey),signature:bn(await BA(p.privateKey,y))};s();let _=await this.request("/oauth/authorization_request",{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:r.id,redirect_uri:this.redirect.href,code_challenge:f,code_challenge_method:"S256",state:h,operations:a.operations.join(","),...e.collection?{collection_id:e.collection}:{},application_authorization:JSON.stringify(g),client_noise_key:JSON.stringify(v)})},i);s();let k=_.body?.authorization_uri;if(_.status!==200||_.body?.authorization_id!==m||typeof k!="string"||!k.startsWith(`${this.cpOrigin}/oauth/authorize?`))throw A("unavailable",`authorization could not be started (${_.status})`,"authorization_start");let S=null,x=this.awaitCallback(h,{navigate(){},close(){},get closed(){return S?.closed===!0}},{popup:{navigate(){},close(){}},signal:i,timeoutMs:e.timeoutMs});x.catch(()=>{});let P=!1;return Object.freeze({applicationId:r.id,manifestDigest:r.manifestDigest,authorizationId:m,authorizationUri:k,cancel:()=>t.abort(),finish:async I=>{if(I=Object.freeze({...I}),P)throw A("invalid_request","original authorization already consumed","authorization_binding");P=!0,S=I.popup;let O=()=>t.abort();I.signal?.addEventListener("abort",O,{once:!0}),I.signal?.aborted&&t.abort();try{s();let R=I.collection??e.collection;if(R!==void 0&&!fs.test(R))throw A("invalid_request","invalid approved collection","authorization_binding");if(e.collection&&R!==e.collection)throw A("forbidden","a different collection was approved","collection_mismatch");if(e.expectedAccountId&&!R)throw A("invalid_request","original Private choice required","authorization_binding");let q=await x;s();let j=await this.request("/oauth/token",{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:q,client_id:r.id,redirect_uri:this.redirect.href,code_verifier:u})},i);s();let B=e.expectedAccountId?Cm(j.body,{accountId:e.expectedAccountId,authorizationRequestId:m,applicationId:r.id,declarationId:b.application_declaration_id,manifestDigest:r.manifestDigest,applicationInstallationId:b.application_installation_id,applicationOrigin:this.declaration.origin,collectionId:R,grantSigningPublicKey:p.publicKey,clientNoisePublicKey:bn(d.publicKey)}):void 0,D=await this.saveTokens(j,{noise:d,signing:p.privateKey,collection:R,check:s});return s(),{collectionId:D,...B?{nativeCompletion:B}:{}}}finally{I.signal?.removeEventListener("abort",O),t.abort()}}})}awaitCallback(e,t,i){let o=Math.min(Math.max(i.timeoutMs??6e5,1e3),18e5);return new Promise((s,r)=>{let a=null,c=f=>{p(),clearTimeout(d),clearInterval(u),i.signal?.removeEventListener("abort",l),f()},l=()=>c(()=>r(A("cancelled","authorization cancelled","authorization_cancelled"))),p=this.callbacks.subscribe(f=>{let h;try{h=new URL(f)}catch{return}if(dt(h)!==dt(this.redirect)||h.username||h.password||h.hash||h.pathname!==this.redirect.pathname||h.searchParams.get("state")!==e)return;if(h.searchParams.get("error"))return c(()=>r(A("forbidden","access was not approved","authorization_denied")));let w=h.searchParams.get("code");if(!w)return c(()=>r(A("unavailable","the authorization callback has no code","authorization_callback")));c(()=>s(w))}),d=setTimeout(()=>c(()=>r(A("cancelled","authorization timed out","authorization_timed_out"))),o),u=setInterval(()=>{let f=!1;try{f=t.closed===!0}catch{f=!1}if(!f){a=null;return}a??=Date.now(),Date.now()-a>=3e3&&c(()=>r(A("cancelled","the authorization window was closed","authorization_cancelled")))},500);i.signal?.addEventListener("abort",l,{once:!0}),i.signal?.aborted&&l()})}async saveTokens(e,t){let i=e.body;if(e.status!==200||!i)throw e.status===400&&i&&(i.error==="invalid_grant"||de(i.error,"code")==="invalid_grant")?A("unauthenticated","the grant is no longer valid","grant_invalid"):e.status===400?Fn("sync_required"):A("unavailable",`token request failed (${e.status})`,"token_error");let o=i.access_token,s=i.refresh_token,r=i.collection_id,a=i.expires_in,c=i.refresh_expires_in;if(typeof o!="string"||typeof s!="string"||typeof r!="string"||!fs.test(r)||typeof a!="number"||!(a>0)||typeof c!="number"||!(c>0))throw A("unavailable","invalid token response","token_response");let l=r.toLowerCase();if(t.collection&&t.collection.toLowerCase()!==l)throw A("forbidden","a different collection was approved","collection_mismatch");if(t.previous&&t.previous.collection!==l)throw A("unavailable","the token names another collection","token_response");let p=t.previous?.refreshKey??await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),d=zy(12),u=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:d,additionalData:this.aad(l)},p,new TextEncoder().encode(s))),f=t.noise??{privateKey:t.previous.noisePrivateKey,publicKey:t.previous.noisePublicKey},h=t.signing??t.previous?.signingPrivateKey,m={version:1,collection:l,noisePrivateKey:f.privateKey,noisePublicKey:f.publicKey,refreshKey:p,refresh:pE(d,u),refreshExpiresAt:Date.now()+c*1e3,...h?{signingPrivateKey:h}:{},...t.previous?.owner?{owner:t.previous.owner}:{}},w=this.epoch;return await this.withLock(l,"commit",async()=>{let b=await this.store();if(w!==this.epoch||t.previous&&!$A(t.previous,await b.getGrant(l)))throw zr();t.check?.(),await b.putGrant(m);let g=await b.getGrant(l);if(!g||!By(m.noisePublicKey,g.noisePublicKey)||!By(m.refresh,g.refresh))throw zr();t.check?.(),this.tokens.set(l,{access:o,expiresAt:Date.now()+a*1e3,collection:l,owner:g.owner,noisePublicKey:g.noisePublicKey.slice()}),this.forgotten.delete(l)}),l}aad(e){return new TextEncoder().encode(`mdbase.app-grant.v2\0${this.cpOrigin}\0${this.owner()}\0${e}`)}async accessToken(e,t=!1){let i=await this.heldGrant(e),o=this.tokens.get(e);if(!t&&o&&ma(i,o)&&o.expiresAt-Date.now()>6e4)return o.access;let s=this.refreshing.get(e);if(s&&$A(i,s.grant)){let c=await s.work;return await this.assertCurrent(i),c}let r=this.withLock(e,"refresh",async()=>{let c=await this.assertCurrent(i);return this.refresh(e,c)}),a={grant:i,work:r};this.refreshing.set(e,a);try{let c=await r;return await this.assertCurrent(i),c}finally{this.refreshing.get(e)===a&&this.refreshing.delete(e)}}withLock(e,t,i){return h8(`mdbase.app-grant.${t}:${JSON.stringify([this.cpOrigin,this.owner(),e])}`,i)}async heldGrant(e){let t=await(await this.store()).getGrant(e);if(!t)throw Fn("sync_required");return{...t,noisePublicKey:t.noisePublicKey.slice(),refresh:t.refresh.slice()}}async assertCurrent(e){let t=await(await this.store()).getGrant(e.collection);if(!ma(e,t))throw zr();return t}async refresh(e,t){if(t.refreshExpiresAt<=Date.now())throw Fn("sync_required");let i;try{let c=await crypto.subtle.decrypt({name:"AES-GCM",iv:t.refresh.slice(0,12),additionalData:this.aad(e)},t.refreshKey,t.refresh.slice(12));i=new TextDecoder().decode(c)}catch{throw A("unauthenticated","the stored grant could not be read","grant_storage")}let o=await this.register(),s=new URLSearchParams({grant_type:"refresh_token",refresh_token:i,client_id:o.id}),r=t.signingPrivateKey?await p8(t.signingPrivateKey,"/oauth/token",s.toString(),i):{},a=await this.request("/oauth/token",{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",...r},body:s});try{await this.saveTokens(a,{previous:t})}catch(c){throw J(c,"unauthenticated")&&c.reason==="grant_invalid"&&await this.withLock(e,"commit",async()=>{let l=await this.store();if(!$A(t,await l.getGrant(e)))throw zr();await l.deleteGrant(e),this.forgotten.add(e);let p=this.tokens.get(e);p&&ma(t,p)&&this.tokens.delete(e)}),c}return a.body.access_token}async route(e,t){for(let i=0;;i++){let o=await this.accessToken(e,i>0),s=await this.request(`/v1/next/collections/${encodeURIComponent(e)}/route`,{headers:{authorization:`Bearer ${o}`}},t);if(s.status===401&&i===0)continue;if(s.status===401)throw A("unauthenticated","the control plane refused the access token");if(s.status===409)throw A("unauthenticated","this app's key is not registered with its grant","client_key_required");if(s.status!==200||!s.body)throw A("unavailable",`control plane answered ${s.status}`,"control_error");let r=s.body;if(typeof r.collection!="string"||r.collection.toLowerCase()!==e||!Array.isArray(r.targets))throw A("unauthenticated","the route does not match this collection's grant","route_mismatch");let c=wi(r.availability)??(iu(r,null).length?{state:"available"}:{state:"unavailable",reason:r.reason==="no_device_registered"?"no_device_registered":"device_offline"});return{token:o,route:r,availability:c}}}async verifiedStoredNativeGrant(e){let t=await this.register(),i=await(await this.store()).getGrant(e.collection_id);return!!i&&e.application_id===t.id&&e.application_origin===this.declaration.origin&&i.owner===this.owner()&&bn(i.noisePublicKey)===e.client_noise_public_key}async collections(e={}){let t=await(await this.store()).listGrants(),i=[];for(let r of t)(e.bindings===void 0||e.bindings.some(a=>a.collection_id===r.collection&&a.application_origin===this.declaration.origin&&bn(r.noisePublicKey)===a.client_noise_public_key))&&i.push(r);let o=new Set(i.map(r=>r.collection)),s=new Set;e:for(let r of i){let a;for(let l=0;;l++){let p;try{p=await this.accessToken(r.collection)}catch(d){if(J(d,"unauthenticated")&&d.reason==="grant_invalid"){s.add(r.collection);continue e}if(J(d,"forbidden")&&d.reason==="sync_required")continue e;throw d}if(await this.assertCurrent(r),a=await this.request("/v1/next/apps/collections",{headers:{authorization:`Bearer ${p}`}},e.signal),await this.assertCurrent(r),a.status===403){s.add(r.collection);continue e}if(a.status!==401)break;if(await this.withLock(r.collection,"commit",async()=>{await this.assertCurrent(r);let d=this.tokens.get(r.collection);if(d?.access!==p||!ma(r,d))throw zr();this.tokens.delete(r.collection)}),l>0)throw A("unauthenticated","the control plane refused the collection listing token")}if(a.status!==200||!Array.isArray(a.body?.collections))throw A("unavailable",`control plane answered ${a.status}`,"control_error");let c=[];for(let l of a.body.collections){let p=typeof l.collection=="string"?l.collection.toLowerCase():"";if(!fs.test(p)||s.has(p)||c.some(b=>b.collectionId===p))continue;let d=wi(l.availability);if(l.state!=="synced_e2e"&&!d)continue;let u=o.has(p)?d??{state:"opening"}:{state:"unavailable",reason:"sync_required"},f=l.authorization_grant??l.grant,h=i.find(b=>b.collection===p),m=l.reviewed_file_actions,w=h&&e.bindings?.some(b=>b.collection_id===p&&b.grant_id===f&&b.application_origin===this.declaration.origin&&b.client_noise_public_key===bn(h.noisePublicKey));c.push(Object.freeze({...w&&Array.isArray(m)?{fileActions:Object.freeze(Y_.filter(b=>m.includes(b)))}:{},collectionId:p,displayName:typeof l.name=="string"?l.name:"Collection",operations:Object.freeze(Array.isArray(l.operations)?l.operations.filter(b=>typeof b=="string"):[]),availability:Object.freeze(u),role:i8.has(l.role)?l.role:null}))}return c}return[]}async availability(e,t={}){let i=e.toLowerCase(),o=this.routeProbe={};try{let{token:s,route:r,availability:a}=await this.route(i,t.signal),c=this.tokens.get(i);return a.state==="available"&&!t.signal?.aborted&&c?.access===s&&(o.ready={credentials:c,route:r,until:performance.now()+3e3,signal:t.signal}),a}catch(s){let r=J(s)?de(s.details,"availability"):void 0;if(typeof r=="string")return wi({state:"unavailable",reason:r});throw s}}async waitForAvailable(e,t={}){let i=Date.now()+Math.min(Math.max(t.timeoutMs??6e4,0),6e5),o=Math.max(t.intervalMs??3e3,1e3),s=null;for(;;){if(t.signal?.aborted)throw A("cancelled","wait cancelled");let r=await this.availability(e,t.signal?{signal:t.signal}:{});if((!s||r.state!==s.state||r.state==="unavailable"&&s.state==="unavailable"&&r.reason!==s.reason)&&t.onAvailability?.(r),s=r,r.state==="available"||r.state==="unavailable"&&(r.reason==="sync_required"||r.reason==="access_removed"))return r;let a=i-Date.now();if(a<=0)return r;await new Promise(c=>{let l=setTimeout(p,Math.min(o,a));function p(){clearTimeout(l),t.signal?.removeEventListener("abort",p),c()}t.signal?.addEventListener("abort",p,{once:!0})})}}connector(e){let t=e.toLowerCase();if(!fs.test(t))throw A("invalid_request","collection must be a UUID");let i=null,o=this.options.webSocket,s;return hf({description:`app-grant:${t}`,open:async(r,a)=>{let c=s===void 0?this.routeProbe?.ready:void 0;this.routeProbe=void 0;let l=await(s??=this.heldGrant(t));if(await this.assertCurrent(l),a?.aborted)throw A("cancelled","connect aborted");let{token:p,route:d,availability:u}=c&&!c.signal?.aborted&&performance.now()<c.until&&c.credentials===this.tokens.get(t)&&ma(l,c.credentials)&&c.credentials.expiresAt>Date.now()?{token:c.credentials.access,route:c.route,availability:{state:"available"}}:await this.route(t,a);if(await this.assertCurrent(l),a?.aborted)throw A("cancelled","connect aborted");if(u.state==="unavailable")throw Fn(u.reason);if(!fs.test(d.grant))throw A("unauthenticated","the route names no grant","route_mismatch");let f=qA(d,i);if(!f.length)throw Fn("device_offline");let h;for(let m of f){await this.assertCurrent(l);let w=new Uint8Array(32);for(let y=0;y<32;y++)w[y]=parseInt(m.noise_pk.slice(2*y,2*y+2),16);let b=Nr({description:`app-grant:${t}`,staticKey:u8(l),target:async()=>({prologue:Ur(N(m.relay_collection),N(d.grant),N(m.device)),remoteStatic:w,device:m.device,openCarrier:async y=>{await this.assertCurrent(l);let v=await fc(m.url,{accessToken:p,collection:m.relay_collection,grant:d.grant,device:m.device,devicePublicKey:w},o,y);try{return await this.assertCurrent(l),v}catch(_){throw v.close(),_}}})}),g;try{g=await b.open(r,a)}catch(y){if(!TA(y,a))throw y;i===m.device&&(i=null),h??=y;continue}try{await this.assertCurrent(l)}catch(y){throw g.port.close(),y}return $S(g.port,l),i=g.device??null,g}throw h},get target(){return i}})}people(e,t){let i=e.toLowerCase();if(!fs.test(i))throw A("invalid_request","collection must be a UUID");return new vr(t,XO(i,{cpOrigin:this.cpOrigin,fetch:this.fetcher,accessToken:(o,s)=>this.accessToken(o,s),holds:o=>!this.forgotten.has(o)}))}setup(e){let t=is(this.declaration),i,o=async()=>{let r=e.currentSession(),a=r&&VS(r);if(!a||a.collection!==e.collection||(i??=a,!ma(i,a)))throw zr();return i};return tE({assertCurrent:async()=>this.assertCurrent(await o()),journal:rE({store:()=>this.store(),grant:o,assertCurrent:r=>this.assertCurrent(r),aad:this.aad(e.collection)}),client:e,manifest:t.manifest,operations:t.operations})}async forget(e,t={}){let i=e.toLowerCase(),o=t.expectedNoisePublicKey;await this.withLock(i,"commit",async()=>{let s=await this.store(),r=await s.getGrant(i);if(o!==void 0&&r&&bn(r.noisePublicKey)!==o)throw zr();await s.deleteGrant(i),this.forgotten.add(i),this.tokens.delete(i),this.routeProbe=void 0})}async forgetAllGrants(){this.routeProbe=void 0,this.epoch++;let e=await this.store(),t=[];try{t=(await e.listGrants()).map(o=>o.collection).sort()}catch{}for(let o of t)this.forgotten.add(o);let i=async(o,s)=>o.length?this.withLock(o[0],"commit",()=>i(o.slice(1),s)):s();await i(t,async()=>{if(this.tokens.clear(),typeof e.clearGrants=="function"){await e.clearGrants();return}for(let o of await e.listGrants())await e.deleteGrant(o.collection),this.forgotten.add(o.collection);if((await e.listGrants()).length)throw A("unavailable","grant storage could not be cleared","grant_storage")}),this.tokens.clear()}}});function Ky(n){return typeof n=="string"&&_8.includes(n)}var _8,WA=C(()=>{"use strict";_8=["joining","opening_store","connecting_log","syncing","loading_snapshot","replaying","waiting_for_key","verifying_read","checking_setup"]});function yE(n){let e=0,t=0;try{let i=n?.records.status.pending;e=typeof i=="number"&&i>0?i:0}catch{e=0}try{t=n?.records.ledger?.getSnapshot().pending.length??0}catch{t=0}return Math.max(e,t)}function gE(n=0){let e=n===1?"1 change hasn't":n>1?`${n} changes haven't`:"Some changes haven't";return A("conflict",`${e} reached mdbase yet. Wait for them to finish, or sign out anyway and lose them on this device.`,{reason:"sign_out_pending_writes",details:n})}var bE=C(()=>{"use strict";re()});function ya(n,e){return new Promise((t,i)=>{if(e.aborted){i(e.reason);return}let o=()=>{clearTimeout(s),i(e.reason)},s=setTimeout(()=>{e.removeEventListener("abort",o),t()},n);e.addEventListener("abort",o,{once:!0})})}var Wy=C(()=>{"use strict"});function U8(n,e){let t=new URL(n);if(t.protocol==="https:")return`wss://${t.host}`;if(e&&Qe(n))return`ws://${t.host}`;throw new Error("app log push: origin")}function vE(n){if(typeof n=="bigint"?n<0n:typeof n!="number"||!Number.isSafeInteger(n)||n<0)throw new Error("app log push: id");return BigInt(n).toString()}function D8(n){let e=n.get(3);if(!(e instanceof Map))return null;let t=e.get(0),i=e.get(1);return{code:typeof t=="string"?t:"unavailable",reason:typeof i=="string"?i:""}}var A8,k8,S8,P8,x8,I8,C8,R8,O8,E8,q8,T8,M8,L8,j8,N8,wE,Hy,_E=C(()=>{"use strict";St();Je();ve();A8=4401,k8=4403,S8=4410,P8=3e4,x8=1e4,I8=6e4,C8=6e4,R8=15e3,O8=4,E8=64*1024,q8=1024*1024,T8=new Set(["stream_join","stream_leave","stream_send"]),M8=1e4,L8=64,j8=32*1024;N8=n=>[...n].map(e=>e.toString(16).padStart(2,"0")).join(""),wE=(n,e,t)=>fe(new Map([[0,0],[1,n],[2,e],[3,t]]));Hy=class{constructor(e,t,i={}){this.source=e;this.events=t;this.base=U8(e.origin,i.allowLoopbackHttp===!0),this.collectionBytes=N(e.collection);let o=i.WebSocket??globalThis.WebSocket;if(typeof o!="function")throw new Error("app log push: no WebSocket");this.Ws=o,this.random=i.random??Math.random,this.now=i.now??Date.now}source;events;base;collectionBytes;Ws;random;now;socket=null;connecting=!1;closed=!1;finished=null;unsupported=!1;paused=!1;isLive=!1;attempts=0;liveSince=0;retry=null;ping=null;pongDue=null;opening=null;unsigned=0;life=new AbortController;token=null;phase="hello";calls=new Map;get live(){return this.isLive}get available(){return!this.unsupported&&this.finished===null&&!this.closed}get suspended(){return this.paused}start(){this.connect()}nudge(){this.unsupported=!1,this.unsigned=0,!(this.paused||this.socket||this.connecting||!this.available)&&(this.attempts=0,this.clearRetry(),this.connect())}suspend(){this.paused||!this.available||(this.paused=!0,this.clearRetry(),this.drop(1e3,"hidden"))}resume(){if(!this.paused){this.nudge();return}this.paused=!1,this.nudge()}close(){this.closed||(this.closed=!0,this.life.abort(),this.clearRetry(),this.drop(1e3,"closed"))}request(e,t){return new Promise((i,o)=>{let s=p=>o(new Error(`app log push: ${p}`)),r=this.socket;if(!r||!this.isLive){s("not live");return}if(!(e instanceof Uint8Array)||e.length>j8||this.calls.size>=L8){s("call");return}let a;try{let p=we(e);if(!(p instanceof Map))throw new Error;let d=p;if(d.get(0)!==0||!T8.has(d.get(2)))throw new Error;a=vE(d.get(1))}catch{s("call");return}if(this.calls.has(a)||t.signal.aborted){s("call");return}let c=()=>{clearTimeout(l.timer),t.signal.removeEventListener("abort",l.stop),this.calls.delete(a)},l={resolve:p=>{c(),i(p)},reject:p=>{c(),o(p)},timer:setTimeout(()=>l.reject(new Error("app log push: no reply")),M8),stop:()=>l.reject(new Error("app log push: aborted"))};t.signal.addEventListener("abort",l.stop,{once:!0}),this.calls.set(a,l);try{r.send(e)}catch{l.reject(new Error("app log push: send")),this.lost(r,1006)}})}clearRetry(){this.retry!==null&&clearTimeout(this.retry),this.retry=null}clearPing(){this.ping!==null&&clearInterval(this.ping),this.ping=null,this.pongDue!==null&&clearTimeout(this.pongDue),this.pongDue=null,this.opening!==null&&clearTimeout(this.opening),this.opening=null}setLive(e){if(this.isLive!==e){this.isLive=e,e&&(this.liveSince=this.now());try{this.events.live(e)}catch{}}}end(e){if(!(this.finished||this.closed)){this.finished=e,this.clearRetry(),this.drop(1e3,e);try{this.events.ended(e)}catch{}}}drop(e,t){this.clearPing();let i=this.socket;if(this.socket=null,i){i.onopen=i.onmessage=i.onclose=i.onerror=null;try{i.close(e,t)}catch{}}for(let o of[...this.calls.values()])o.reject(new Error("app log push: lost"));this.setLive(!1)}schedule(e=!1){if(this.paused||!this.available||this.retry!==null)return;let t=e?0:Math.floor(this.random()*Math.min(C8,1e3*2**Math.min(this.attempts,6)));this.attempts++,this.retry=setTimeout(()=>{this.retry=null,this.connect()},t)}async connect(){if(this.paused||this.socket||this.connecting||!this.available)return;if(!this.source.isCurrent()){this.close();return}this.connecting=!0;let e,t,i;try{let r=this.life.signal;if(e=await this.source.accessToken({signal:r}),t=await this.source.nonce({signal:r}),this.paused||!this.available||!this.source.isCurrent())return;if(i=this.source.signHello(t,e),!i){++this.unsigned>=O8?this.unsupported=!0:this.schedule();return}this.unsigned=0}catch{this.connecting=!1,this.schedule();return}finally{this.connecting=!1}this.token=e;let o;try{o=new this.Ws(`${this.base}/v1/ws?c=${this.source.collection}&n=${N8(t)}`)}catch{this.schedule();return}o.binaryType="arraybuffer",this.socket=o,this.phase="hello";let s=wE(1,"hello",new Map([[0,[1,0]],[1,e],[2,N(this.source.deviceId)],[3,i]]));i.fill(0),t.fill(0),o.onopen=()=>{try{o.send(s)}catch{this.lost(o,1006)}},o.onmessage=r=>this.message(o,r.data),o.onclose=r=>this.lost(o,r.code),o.onerror=()=>{},this.opening=setTimeout(()=>{this.opening=null,this.lost(o,1006)},R8)}message(e,t){if(e!==this.socket)return;if(typeof t=="string"){t==="pong"&&this.pongDue!==null&&(clearTimeout(this.pongDue),this.pongDue=null);return}if(!(t instanceof ArrayBuffer)||t.byteLength>q8){this.lost(e,1009);return}let i=new Uint8Array(t),o;try{let a=we(i);if(!(a instanceof Map))throw new Error;o=a}catch{this.lost(e,1007);return}if(o.get(0)===2){if(!this.isLive)return;if(this.deliver(i),o.get(1)==="closed"){let a=o.get(2),c=a instanceof Map?a.get(1):null;this.end(c==="gone"?"gone":c==="revoked"?"revoked":"forbidden")}return}if(o.get(0)!==1)return;let s=o.get(1),r=D8(o);if(this.phase==="live"){let a;try{a=vE(s)}catch{return}this.calls.get(a)?.resolve(i.slice());return}if(this.phase==="hello"){if(s!==1)return;if(r){this.refused(e,r);return}this.phase="subscribe";try{e.send(wE(2,"subscribe",new Map([[0,this.collectionBytes],[1,0],[2,E8]])))}catch{this.lost(e,1006)}return}if(s===2){if(r){this.refused(e,r);return}let a=o.get(2);if(!(a instanceof Map)){this.lost(e,1007);return}let c=a.get(0),l=a.get(1);this.phase="live",this.startPing(e),this.setLive(!0),(typeof c=="number"||typeof c=="bigint")&&l instanceof Uint8Array&&l.length===32&&this.deliver(fe(new Map([[0,2],[1,"head"],[2,new Map([[0,this.collectionBytes],[1,c],[2,l]])]])))}}deliver(e){try{this.events.push(e)}catch{}}refused(e,t){if(t.code==="forbidden"&&t.reason==="credentials_revoked"){this.end("revoked");return}if(t.code==="forbidden"||t.code==="not_found"){this.end(t.code==="not_found"?"gone":"forbidden");return}if(t.code==="gone"){this.end("gone");return}t.code==="unauthenticated"&&this.token&&(this.source.invalidateToken?.(this.token),this.token=null),this.lost(e,1008)}startPing(e){this.clearPing(),this.ping=setInterval(()=>{if(!(e!==this.socket||this.pongDue!==null)){try{e.send("ping")}catch{this.lost(e,1006);return}this.pongDue=setTimeout(()=>{this.pongDue=null,this.lost(e,1006)},x8)}},P8)}lost(e,t){if(e!==this.socket)return;let i=this.isLive&&this.now()-this.liveSince>=I8;if(this.drop(1e3,"lost"),t===k8){this.end("forbidden");return}if(t===S8){this.end("gone");return}if(i&&(this.attempts=0),t===A8){this.token&&this.source.invalidateToken?.(this.token),this.token=null,this.attempts=0,this.schedule(!0);return}this.schedule()}}});function AE(n){if(!n||typeof n!="object"||Array.isArray(n))throw sr();return n}function kE(n){if(typeof n=="number"&&!Number.isSafeInteger(n))throw sr();let e=BigInt(n);if(e<0n||e>(1n<<64n)-1n)throw sr();return e}var sr,yc,HA=C(()=>{"use strict";St();ve();re();sr=()=>A("unavailable","people metadata is unavailable","people_response");yc=class{constructor(e,t={}){this.session=e;this.rawOrigin=e.cpOrigin;let i=new URL(this.rawOrigin);if(i.username||i.password||i.pathname!=="/"||i.search||i.hash||i.protocol!=="https:"&&!(t.allowLoopbackHttp===!0&&Qe(e.cpOrigin)))throw A("invalid_request","invalid people CP origin","people_binding");this.cpOrigin=i.origin,this.collection=e.collection,this.connector=e.connectorId,this.device=e.deviceId,this.ep=kE(e.endpoint);for(let o of[this.collection,this.connector,this.device])if(N(o).every(s=>s===0))throw A("invalid_request","nil people binding","people_binding");if(this.fetchImpl=t.fetch??globalThis.fetch,!this.isCurrent())throw A("unauthenticated","people scope is not current","people_fenced")}session;cpOrigin;rawOrigin;collection;connector;device;ep;fetchImpl;lifetime=new AbortController;isCurrent(){try{return!this.lifetime.signal.aborted&&this.session.isCurrent()===!0&&this.session.cpOrigin===this.rawOrigin&&this.session.collection===this.collection&&this.session.connectorId===this.connector&&this.session.deviceId===this.device&&kE(this.session.endpoint)===this.ep}catch{return!1}}check(e){if(e?.throwIfAborted(),!this.isCurrent())throw A("unauthenticated","people scope changed","people_fenced")}async request(e,t={}){if(e!=="identity"&&e!=="members")throw A("invalid_request","invalid people resource");this.check(t.signal);let i=new AbortController,o=()=>i.abort();t.signal?.addEventListener("abort",o,{once:!0}),this.lifetime.signal.addEventListener("abort",o,{once:!0});let s=setTimeout(o,15e3);s.unref?.();let r=new Uint8Array(1024*1024),a=0,c,l;try{let p=await this.session.connectorBearer({signal:i.signal});if(this.check(t.signal),i.signal.aborted)throw sr();if(typeof p!="string"||!/^(idev_|ct_)/.test(p)||p.length>16*1024||/[^\x21-\x7e]/.test(p))throw A("unauthenticated","invalid people credential","people_binding");let d=this.fetchImpl;if(c=await d(`${this.cpOrigin}/v1/authorities/${this.collection}/${e}?device_id=${this.device}`,{method:"GET",headers:{authorization:`Bearer ${p}`},signal:i.signal,redirect:"error",credentials:"omit",cache:"default",referrerPolicy:"no-referrer"}),this.check(t.signal),i.signal.aborted)throw sr();let u=c.headers.get("content-length");if(u!==null&&/^(0|[1-9][0-9]*)$/.test(u)&&Number(u)>r.length||!c.body)throw sr();for(l=c.body.getReader();;){let{done:h,value:m}=await l.read();try{if(this.check(t.signal),i.signal.aborted)throw sr();if(h)break;if(a+m.length>r.length)throw sr();r.set(m,a),a+=m.length}finally{m?.fill(0)}}let f=AE(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r.subarray(0,a))));if(this.check(t.signal),c.status===401)throw A("unauthenticated","people credential is no longer current","people_fenced");if(c.status===403){let h=AE(f.error);throw A("forbidden","people access was refused",e==="members"&&h.code==="people_permission_declined"?"people_permission_declined":"people_access")}if(c.status===404)throw A("upgrade_required","people metadata is unsupported","people_unsupported");if(!c.ok)throw sr();return f}catch(p){throw this.check(t.signal),p instanceof ne?p:sr()}finally{i.abort(),r.fill(0),(l?.cancel()??c?.body?.cancel())?.catch(()=>{}),l?.releaseLock(),clearTimeout(s),t.signal?.removeEventListener("abort",o),this.lifetime.signal.removeEventListener("abort",o)}}close(){this.lifetime.abort()}}});function Gy(n,e){if(typeof n!="string"||!e.test(n))throw ge("invalid_request","timer_input");return encodeURIComponent(n)}function hs(n,e){if(!n||typeof n!="object"||Array.isArray(n)||Object.keys(n).sort().join()!==e.split(",").sort().join())throw ge("invalid_request","timer_input");return n}function SE(n){let e=hs(n,"id,fire_at");if(Gy(e.id,GA),typeof e.fire_at!="string"||!/^\d{4}-\d{2}-\d{2}T/.test(e.fire_at)||!Number.isFinite(Date.parse(e.fire_at)))throw ge("invalid_request","timer_input");return{id:e.id,fire_at:e.fire_at}}function YA(n){if(typeof n!="string"||!n.length||n.length>100)throw ge("invalid_request","timer_input")}function $8(n,e,t){let i=`${n}/${Gy(t[0],z8)}`;if(e==="list"&&t.length===1)return{path:i,method:"GET",write:!1};if(e==="put"&&t.length===3){let o=hs(t[2],"criterion_id,fire_at");return YA(o.criterion_id),SE({id:t[1],fire_at:o.fire_at}),{path:`${i}/${Gy(t[1],GA)}`,method:"PUT",body:o,write:!0}}if(e==="cancel"&&t.length===3){let o=t[2];if(o!==void 0&&(!Number.isSafeInteger(o)||o<1))throw ge("invalid_request","timer_input");return{path:`${i}/${Gy(t[1],GA)}${o===void 0?"":`?generation=${o}`}`,method:"DELETE",write:!0}}if((e==="reconcile"||e==="reconcileWithReceipt")&&t.length===2){let o=hs(t[1],`criterion_id,timers${e==="reconcileWithReceipt"?",recovery":""}`);if(YA(o.criterion_id),!Array.isArray(o.timers)||o.timers.length>1e4)throw ge("invalid_request","timer_input");let s=o.timers.map(SE);if(new Set(s.map(r=>r.id)).size!==s.length)throw ge("invalid_request","timer_input");if(e==="reconcileWithReceipt"){let r=hs(o.recovery,"protocol_version,operation_id,expected_revision");if(r.protocol_version!==1||typeof r.operation_id!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(r.operation_id)||!Number.isSafeInteger(r.expected_revision)||r.expected_revision<0||r.expected_revision>=Number.MAX_SAFE_INTEGER)throw ge("invalid_request","timer_input")}return{path:`${i}/reconcile`,method:"POST",body:{...o,timers:s},write:!0}}if(e==="lookupOperation"&&t.length===2&&typeof t[1]=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(t[1]))return{path:`${i}/operations/${t[1]}`,method:"GET",write:!1};throw ge("invalid_request","timer_input")}function xE(n,e){let t=PE(e.scope),i=e.generation,o=`/v1/next/collections/${e.scope.collection}/background-grants/${e.grantId}/timers`,s=!1,r=0,a=null,c=null,l=()=>{if(s||e.signal.aborted||!e.isCurrent())throw ge("unauthenticated","timer_fenced")},p=()=>{if(c)return c;s=!0,e.signal.removeEventListener("abort",d),a?.ctrl.abort();try{n.postMessage([1,t,i,"close"])}finally{n.removeEventListener("message",u),n.close()}return c=Promise.resolve().then(async()=>{await a?.work})},d=()=>{p()},u=f=>{let h=f.data;if(!Array.isArray(h)||h[0]!==1||h[1]!==t||h[2]!==i){p();return}if(h.length===4&&h[3]==="close"){p();return}if(h.length===5&&h[4]==="cancel"&&Number.isSafeInteger(h[3])&&h[3]>0){a&&a.id===h[3]&&a.ctrl.abort();return}if(h.length!==6||!Number.isSafeInteger(h[3])||h[3]<=r||a||typeof h[4]!="string"||!Array.isArray(h[5])){p();return}let m=h[3],w=h[4],b=h[5],g=new AbortController;r=m;let y=!1,v=w!=="list"&&w!=="lookupOperation",_=Promise.resolve().then(async()=>{let k=setTimeout(()=>g.abort(),1e4),S,x,P=new Uint8Array(au),I=0,O=()=>{x?.cancel().catch(()=>{})};g.signal.addEventListener("abort",O,{once:!0});try{l(),g.signal.throwIfAborted();let R=o.slice(0,-7)+"/notifications/channels",q,j,B=null;if(w==="vapid"&&b.length===0){if(!e.journal)throw ge("upgrade_required","native_timer_channel_journal_unavailable");e.journal.read(),q={path:"/v1/notifications/vapid-public-key",method:"GET",write:!1}}else if(w==="registerChannel"&&b.length===1){if(!e.journal)throw ge("upgrade_required","native_timer_channel_journal_unavailable");let ee=b[0],te=hs(ee,`kind,criteria,${ee?.kind==="web_push"?"subscription":"token"}`);if(!["web_push","fcm"].includes(te.kind)||!Array.isArray(te.criteria)||!te.criteria.length||te.criteria.length>100||(te.criteria.forEach(YA),new Set(te.criteria).size!==te.criteria.length))throw ge("invalid_request","timer_input");let Ie;if(te.kind==="fcm"){if(typeof te.token!="string"||te.token.length<16||te.token.length>4096||/[\s\u0000-\u001f\u007f]/.test(te.token))throw ge("invalid_request","timer_input");Ie={transport:"fcm",token:te.token}}else{let K=hs(te.subscription,"endpoint,expirationTime,keys"),Q=hs(K.keys,"p256dh,auth");if(typeof K.endpoint!="string"||K.endpoint.length>2048||typeof Q.p256dh!="string"||typeof Q.auth!="string"||!/^[A-Za-z0-9_-]{87}$/.test(Q.p256dh)||!/^[A-Za-z0-9_-]{22}$/.test(Q.auth))throw ge("invalid_request","timer_input");let Ae;try{Ae=new URL(K.endpoint)}catch{throw ge("invalid_request","timer_input")}if(Ae.protocol!=="https:"||Ae.username||Ae.password||Ae.hash||Ae.href!==K.endpoint||K.expirationTime!==null&&(!Number.isFinite(K.expirationTime)||K.expirationTime<0))throw ge("invalid_request","timer_input");Ie={subscription:K}}q={path:R,method:"POST",write:!0,body:{installation_id:e.scope.installation,criteria:[...te.criteria].sort(),...Ie}};let tt=new TextEncoder().encode(JSON.stringify(q.body)),$;try{$=[...new Uint8Array(await crypto.subtle.digest("SHA-256",tt))].map(K=>K.toString(16).padStart(2,"0")).join("")}finally{tt.fill(0)}l(),g.signal.throwIfAborted();let Y=e.journal.read();if(B=Y,Y?.pending)throw ge("outcome_unknown","timer_channel_reapproval_required");j={grantId:e.grantId,kind:te.kind,targetDigest:$,channelId:Y?.channelId??null,pending:"register"}}else if(w==="unregisterChannel"&&b.length===1&&["web_push","fcm"].includes(b[0])){if(!e.journal)throw ge("upgrade_required","native_timer_channel_journal_unavailable");let ee=e.journal.read();if(B=ee,!ee){n.postMessage([1,t,i,m,!0,void 0]);return}if(ee.pending==="register")throw ge("outcome_unknown","timer_channel_reapproval_required");if(ee.kind!==b[0]||!ee.channelId)throw ge("invalid_request","timer_channel_kind");j={...ee,pending:"delete"},q={path:`${R}/${ee.channelId}`,method:"DELETE",write:!0}}else q=$8(o,w,b);v=q.write;let D=q.body===void 0?void 0:JSON.stringify(q.body);if(D&&new TextEncoder().encode(D).length>au)throw ge("invalid_request","timer_input");let X=await e.bearer();if(l(),g.signal.throwIfAborted(),typeof X!="string"||!/^(idev_|ct_)[A-Za-z0-9_-]{43}$/.test(X))throw ge("unauthenticated","timer_credential");j&&(await e.journal.write(j),l(),g.signal.throwIfAborted()),y=v;let V=e.fetch;if(S=await V(`${e.cpOrigin}${q.path}`,{method:q.method,body:D,headers:{authorization:`Bearer ${X}`,...D===void 0?{}:{"content-type":"application/json"}},credentials:"omit",redirect:"error",cache:q.method==="GET"?"no-store":"default",referrerPolicy:"no-referrer",signal:g.signal}),l(),g.signal.throwIfAborted(),S.redirected)throw ge("unavailable","timer_response");if(w==="unregisterChannel"&&S.status===204){await e.journal.write(null),l(),g.signal.throwIfAborted(),n.postMessage([1,t,i,m,!0,void 0]);return}if(S.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase()!=="application/json"||!S.body)throw ge("unavailable","timer_response");let U=S.headers.get("content-length");if(U&&/^\d+$/.test(U)&&Number(U)>au)throw ge("unavailable","timer_response");for(x=S.body.getReader();;){let ee=await x.read();try{if(l(),g.signal.throwIfAborted(),ee.done)break;if(I+ee.value.length>au)throw ge("unavailable","timer_response");P.set(ee.value,I),I+=ee.value.length}finally{ee.value?.fill(0)}}let ce=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(P.subarray(0,I)));if(w==="unregisterChannel"&&S.status===404&&ce?.error?.code==="channel_not_found"){await e.journal.write(null),l(),g.signal.throwIfAborted(),n.postMessage([1,t,i,m,!0,void 0]);return}if(!S.ok){let ee=!!j&&S.status===503&&typeof ce?.error?.code=="string";throw S.status>=500&&!ee?ge("unavailable","timer_http"):ce?.error?.operation_outcome==="unknown"?ge("outcome_unknown","timer_write_unknown"):(j&&(await e.journal.write(B),l(),g.signal.throwIfAborted()),y=!1,ee?ge("unavailable","timer_http"):A(S.status===401||S.status===403?"unauthenticated":S.status===409?"conflict":S.status===404?"upgrade_required":S.status===429?"rate_limited":"invalid_request","Timer request was refused.","timer_refused"))}if(l(),g.signal.throwIfAborted(),w==="registerChannel"){if(typeof ce?.channel_id!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(ce.channel_id))throw ge("unavailable","timer_channel_response");await e.journal.write({...j,channelId:ce.channel_id,pending:null}),l(),g.signal.throwIfAborted(),n.postMessage([1,t,i,m,!0,{channelId:ce.channel_id,installationId:e.scope.installation,criteria:q.body.criteria}])}else n.postMessage([1,t,i,m,!0,ce])}catch(R){let q=y?ge("outcome_unknown","timer_write_unknown"):R instanceof ne?R:ge(g.signal.aborted?"cancelled":"unavailable","timer_request");s||n.postMessage([1,t,i,m,!1,q.code,q.reason])}finally{clearTimeout(k),g.signal.removeEventListener("abort",O),P.fill(0),(x?.cancel()??S?.body?.cancel())?.catch(()=>{}),x?.releaseLock(),a?.id===m&&(a=null)}});a={id:m,ctrl:g,work:_}};n.addEventListener("message",u),n.start(),e.signal.addEventListener("abort",d,{once:!0});try{l()}catch(f){throw p(),f}return Object.freeze({close:p})}function IE(n,e,t){let i=PE(e.scope),o=e.generation,s=!1,r=0,a=null,c=()=>{if(s)return;s=!0,t.signal.removeEventListener("abort",c);let y=a;a=null,y?.signal?.removeEventListener("abort",y.abort),y?.reject(ge(y.write?"outcome_unknown":"cancelled","timer_port_closed"));try{n.postMessage([1,i,o,"close"])}finally{n.removeEventListener("message",l),n.close(),t.onClose()}},l=y=>{let v=y.data;if(!Array.isArray(v)||v[0]!==1||v[1]!==i||v[2]!==o){c();return}if(v.length===4&&v[3]==="close"){c();return}let _=a;if(!_||v[3]!==_.id||!(v.length===6&&v[4]===!0||v.length===7&&v[4]===!1&&typeof v[5]=="string"&&Po(v[5]))){c();return}a=null,_.signal?.removeEventListener("abort",_.abort),v[4]?_.resolve(v[5]):_.reject(A(v[5],"Timer request could not complete.",typeof v[6]=="string"?v[6]:void 0))},p=(y,v,_,k=!1)=>{if(s||t.signal.aborted||_.signal?.aborted)return Promise.reject(ge("cancelled","timer_port_closed"));if(a||d&&!k)return Promise.reject(ge("unavailable","timer_port_busy"));if(r>=Number.MAX_SAFE_INTEGER)return c(),Promise.reject(ge("unavailable","timer_port_closed"));let S=++r,x=y!=="list"&&y!=="lookupOperation"&&y!=="vapid";return new Promise((P,I)=>{let O=()=>{try{n.postMessage([1,i,o,S,"cancel"])}catch{c()}I(ge(x?"outcome_unknown":"cancelled","timer_request_cancelled"))};a={id:S,write:x,resolve:P,reject:I,abort:O,signal:_.signal},_.signal?.addEventListener("abort",O,{once:!0});try{if(new TextEncoder().encode(JSON.stringify(v)).length>au)throw ge("invalid_request","timer_input");n.postMessage([1,i,o,S,y,v])}catch(R){a=null,_.signal?.removeEventListener("abort",O),I(R)}})},d=!1,u=()=>{if(s||t.signal.aborted)throw ge("cancelled","timer_port_closed")},f=y=>{if(!y?.length||y.length>100||y.some(v=>typeof v!="string"||!v.length||v.length>100)||new Set(y).size!==y.length)throw ge("invalid_request","timer_channel_criteria_required");return[...y].sort()},h=(y,v)=>{let _=hs(y,"channelId,installationId,criteria");if(typeof _.channelId!="string"||_.installationId!==e.scope.installation||JSON.stringify(_.criteria)!==JSON.stringify(v))throw ge("outcome_unknown","timer_channel_response");return{channelId:_.channelId,installationId:e.scope.installation,criteria:[...v]}},m=async(y,v)=>{if(u(),y.signal?.throwIfAborted(),d||a)throw ge("unavailable","timer_port_busy");d=!0;try{return await v()}finally{d=!1}},w=y=>m(y,async()=>{let v=f(y.criteria);if(y.installationId!==void 0&&y.installationId!==e.scope.installation)throw ge("invalid_request","timer_channel_installation");let _=y.serviceWorker;if(!_?.pushManager||typeof _.pushManager.getSubscription!="function"||typeof _.pushManager.subscribe!="function")throw ge("invalid_request","timer_push_platform");let k=await p("vapid",[],y,!0);if(u(),y.signal?.throwIfAborted(),typeof k.public_key!="string"||!/^[A-Za-z0-9_-]{87}$/.test(k.public_key))throw ge("unavailable","timer_vapid_response");let S=atob(k.public_key.replace(/-/g,"+").replace(/_/g,"/")),x=Uint8Array.from(S,O=>O.charCodeAt(0));if(x.length!==65||x[0]!==4||btoa(S).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")!==k.public_key)throw ge("unavailable","timer_vapid_response");let P=await _.pushManager.getSubscription();if(u(),y.signal?.throwIfAborted(),P){let O=P.options.applicationServerKey;if(!O||O.byteLength!==x.length||new Uint8Array(O).some((R,q)=>R!==x[q]))throw ge("invalid_request","timer_push_key_changed")}if(!P&&(P=await _.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:x}),s||t.signal.aborted||y.signal?.aborted))throw await P.unsubscribe(),ge("cancelled","timer_port_closed");let I=P.toJSON();return h(await p("registerChannel",[{kind:"web_push",criteria:v,subscription:{endpoint:I.endpoint,expirationTime:I.expirationTime??null,keys:I.keys}}],y,!0),v)}),b=y=>m(y,async()=>{let v=f(y.criteria);if(y.installationId!==void 0&&y.installationId!==e.scope.installation)throw ge("invalid_request","timer_channel_installation");return{...h(await p("registerChannel",[{kind:"fcm",criteria:v,token:y.token}],y,!0),v),transport:"fcm"}}),g=(y,v)=>m(v,async()=>{if(await p("unregisterChannel",["web_push"],v,!0),u(),v.signal?.throwIfAborted(),y){let _=await y.pushManager.getSubscription();u(),v.signal?.throwIfAborted(),_&&await _.unsubscribe(),u(),v.signal?.throwIfAborted()}});return n.addEventListener("message",l),n.start(),t.signal.addEventListener("abort",c,{once:!0}),t.signal.aborted&&c(),Object.freeze({list:(y,v)=>p("list",[y],v),put:(y,v,_,k)=>p("put",[y,v,_],k),cancel:(y,v,_,k)=>p("cancel",[y,v,_],k),reconcile:(y,v,_)=>p("reconcile",[y,v],_),reconcileWithReceipt:(y,v,_)=>p("reconcileWithReceipt",[y,v],_),lookupOperation:(y,v,_)=>p("lookupOperation",[y,v],_),registerWebPush:w,unregisterWebPush:g,registerFcm:b,unregisterFcm:y=>m(y,async()=>{await p("unregisterChannel",["fcm"],y,!0)}),close:c})}var z8,GA,au,ge,PE,JA=C(()=>{"use strict";re();z8=/^[A-Za-z0-9._-]{1,64}$/,GA=/^[A-Za-z0-9._:-]{1,128}$/,au=2*1024*1024,ge=(n,e)=>A(n,"Timer request could not complete.",e),PE=n=>JSON.stringify([n.account,n.installation,n.collection])});function gc(n){return n.mode==="local_only"?null:n.incidents.some(e=>e.kind==="waiting_for_key")?"waiting_for_key":n.installing?"installing":n.resyncing?"resyncing":n.connection==="offline"?"offline":n.headKnown===0?"head_unknown":n.confirmedThrough<n.headKnown?"behind":null}function Yy(n){let e=n.incidents.find(s=>s.kind==="waiting_for_key");if(!e)return null;let t={through:n.confirmedThrough,head:n.headKnown},i=s=>de(e.details,s),o=i("reason");typeof o=="string"&&/^[a-z_]{1,32}$/.test(o)&&(t.key=o);for(let s of["position","at"]){let r=i(s);typeof r=="number"&&(t[s]=r)}return t}function RE(n){if(gc(n)!=="waiting_for_key")return!1;let e=Yy(n)?.key;return e==="reading"||e==="no_grant"}var CE,OE=C(()=>{"use strict";un();CE=15e4});var Jy,XA,Ye,ZA,B8,Xy,QA=C(()=>{"use strict";Je();ve();Ws();Jy=264*1024+256,XA=264*1024,Ye=()=>new Error("app cloud copy outcome unavailable; preserve storage and reopen"),ZA=(n,e)=>n.length===e.length&&n.every((t,i)=>t===e[i]),B8=n=>Array.from(n,e=>e.toString(16).padStart(2,"0")).join(""),Xy=class{constructor(e,t,i,o,s){this.source=e;this.store=o;this.key=i;try{this.mode=s.mode,this.lifetime=s.signal,this.fields=Object.freeze({accountId:e.accountId,connectorId:e.connectorId,deviceId:e.deviceId,installationId:e.installationId,collection:e.collection,purpose:e.purpose,cpOrigin:e.cpOrigin,logOrigin:e.logOrigin,assetSha256:e.assetSha256});let r=e.displayName;if(this.displayName=r===void 0?void 0:li(r),this.displayName!==void 0&&e.purpose!=="create"||r!==this.displayName)throw Ye();this.current=e.isCurrent,this.owned=e.installationOwned,this.io=Object.freeze({read:o.read,cas:o.compareAndSet});let a=[e.accountId,e.connectorId,e.deviceId,e.installationId,e.collection].map(N);if(a.some(c=>c.every(l=>l===0))||!["create","join"].includes(e.purpose)||!["fresh","existing"].includes(this.mode)||!/^[0-9a-f]{64}$/.test(e.assetSha256)||(this.keys=Object.freeze([t.signPublicKey,t.kemPublicKey,t.noisePublicKey].map(c=>{if(!(c instanceof Uint8Array)||c.length!==32||c.every(l=>l===0))throw Ye();return new Uint8Array(c)})),t.connectorId!==e.connectorId||t.deviceId!==e.deviceId||t.installationId!==e.installationId)||typeof globalThis.CryptoKey!="function"||!(i instanceof CryptoKey)||i.type!=="secret"||i.extractable||i.algorithm.name!=="AES-GCM"||i.algorithm.length!==256||i.usages.length!==2||!i.usages.includes("encrypt")||!i.usages.includes("decrypt"))throw Ye();this.aad=fe(["mdbase/v1/app-cloud-copy-outcome-platform",...a,e.purpose,e.cpOrigin,e.logOrigin,e.assetSha256,...this.keys]),this.check(this.lifetime)}catch{throw Ye()}}source;store;closed=!1;key;fields;displayName;current;owned;io;keys;aad;mode;lifetime;check(e){try{if(this.closed||!this.key||e!==this.lifetime||e.aborted||this.source.displayName!==this.displayName||this.source.isCurrent!==this.current||this.source.installationOwned!==this.owned||this.current.call(this.source)!==!0||this.owned.call(this.source)!==!0||this.store.read!==this.io.read||this.store.compareAndSet!==this.io.cas||Object.entries(this.fields).some(([t,i])=>this.source[t]!==i))throw Ye()}catch{throw Ye()}}operation(e){if(e){if(e.displayName!==this.displayName)throw Ye();for(let t of Object.keys(this.fields))if(e[t]!==this.fields[t])throw Ye();for(let[t,i]of["signPublicKey","kemPublicKey","noisePublicKey"].entries())if(!(e[i]instanceof Uint8Array)||!ZA(e[i],this.keys[t]))throw Ye()}return Object.freeze({...this.fields,...this.displayName===void 0?{}:{displayName:this.displayName},signPublicKey:new Uint8Array(this.keys[0]),kemPublicKey:new Uint8Array(this.keys[1]),noisePublicKey:new Uint8Array(this.keys[2])})}metadata(e){let t=this.operation(e.operation);if(!(e.genesisItem instanceof Uint8Array)||!e.genesisItem.length||e.genesisItem.length>256*1024||typeof e.expectedGenesis!="string"||!/^sha256:[0-9a-f]{64}$/.test(e.expectedGenesis))throw Ye();return Object.freeze({operation:t,genesisItem:new Uint8Array(e.genesisItem),expectedGenesis:e.expectedGenesis})}async hashChecked(e,t){let i=new TextEncoder().encode("mdbase/v1/chain"),o=new Uint8Array(1+i.length+e.genesisItem.length);o[0]=i.length,o.set(i,1),o.set(e.genesisItem,1+i.length);let s=new Uint8Array(await crypto.subtle.digest("SHA-256",o));if(this.check(t),e.expectedGenesis!==`sha256:${B8(s)}`)throw Ye()}async read(e){let t=null;try{this.check(e);let i=await this.io.read.call(this.store,Object.freeze({signal:e}));if(this.check(e),i===null){if(this.mode!=="fresh")throw Ye();return null}if(!(i instanceof Uint8Array)||!i.length||i.length>Jy)throw Ye();let o=new Uint8Array(i),s=we(o);if(!(s instanceof Map))throw Ye();let r=s;if(r.size!==3||r.get(0)!==1)throw Ye();let a=r.get(1),c=r.get(2);if(!(a instanceof Uint8Array)||a.length!==12||!(c instanceof Uint8Array)||c.length<16||c.length>XA+16||(t=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:new Uint8Array(a),additionalData:new Uint8Array(this.aad),tagLength:128},this.key,new Uint8Array(c))),this.check(e),t.length>XA))throw Ye();let l=we(t);if(!(l instanceof Map))throw Ye();let p=l,d=p.get(0)===1&&p.size===3;if(!d&&!(p.get(0)===2&&p.size===4)||(d?null:p.get(3))!==(this.displayName??null))throw Ye();let u=p.get(1);if(!Array.isArray(u)||u.length!==3||u.some((m,w)=>!(m instanceof Uint8Array)||!ZA(m,this.keys[w])))throw Ye();let f=p.get(2),h=null;if(f!==null){if(!Array.isArray(f)||f.length!==2||!(f[0]instanceof Uint8Array)||typeof f[1]!="string")throw Ye();h=this.metadata({operation:this.operation(),genesisItem:f[0],expectedGenesis:f[1]}),await this.hashChecked(h,e)}return{encrypted:o,metadata:h}}catch{throw Ye()}finally{t?.fill(0)}}async write(e,t,i){let o=null,s=null;try{if(this.check(i),o=fe(new Map([[0,2],[1,this.keys.map(l=>new Uint8Array(l))],[2,e===null?null:[e.genesisItem,e.expectedGenesis]],[3,this.displayName??null]])),o.length>XA)throw Ye();let r=crypto.getRandomValues(new Uint8Array(12)),a=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:r,additionalData:new Uint8Array(this.aad),tagLength:128},this.key,new Uint8Array(o)));if(this.check(i),s=fe(new Map([[0,1],[1,r],[2,a]])),s.length>Jy)throw Ye();let c=await this.io.cas.call(this.store,t,s,Object.freeze({signal:i}));if(this.check(i),c!==!0)throw Ye()}catch{throw Ye()}finally{o?.fill(0),s?.fill(0)}}async restore(e){let{signal:t}=e,i=await this.read(t);return this.check(t),i===null?Object.freeze({state:"none"}):i.metadata===null?Object.freeze({state:"pending",operation:this.operation()}):Object.freeze({state:"completed",metadata:this.metadata(i.metadata)})}async pending(e,t){let{signal:i}=t;this.check(i),this.operation(e);let o=await this.read(i);this.check(i),!o&&await this.write(null,null,i)}async completed(e,t){let{signal:i}=t;this.check(i);let o=this.metadata(e);await this.hashChecked(o,i);let s=await this.read(i);if(this.check(i),!s)throw Ye();if(s.metadata){if(!ZA(s.metadata.genesisItem,o.genesisItem)||s.metadata.expectedGenesis!==o.expectedGenesis)throw Ye();return}await this.write(o,s.encrypted,i)}close(){this.closed=!0,this.key=null}}});function t0(n){if(!(n instanceof Uint8Array)||!n.length||n.length>Jy)throw wn();return new Uint8Array(n)}var Zy,e0,wn,V8,Qy,EE=C(()=>{"use strict";Jt();ve();QA();Zy="public-outcome",e0="operation",wn=()=>new Error("app cloud copy outcome store unavailable; preserve storage and reopen"),V8=(n,e)=>n===null||e===null?n===e:n.length===e.length&&n.every((t,i)=>t===e[i]);Qy=class n{constructor(e,t,i){this.source=e;this.origin=t;this.lifetime=i;this.fields=Object.freeze({accountId:e.accountId,connectorId:e.connectorId,deviceId:e.deviceId,installationId:e.installationId,collection:e.collection,purpose:e.purpose,cpOrigin:e.cpOrigin,logOrigin:e.logOrigin,assetSha256:e.assetSha256}),this.current=e.isCurrent,this.owned=e.installationOwned}source;origin;lifetime;db=null;closed=!1;fields;current;owned;get fenced(){return this.closed||this.lifetime.aborted}check(e){try{if(this.fenced||e!==this.lifetime||e.aborted||Et()!==this.origin||this.source.isCurrent!==this.current||this.source.installationOwned!==this.owned||this.current.call(this.source)!==!0||this.owned.call(this.source)!==!0||Object.entries(this.fields).some(([t,i])=>this.source[t]!==i))throw wn()}catch{throw wn()}}static async open(e){let{source:t,origin:i,mode:o,signal:s}=e,r=null;try{r=new n(t,i,s);let a=[r.fields.accountId,r.fields.connectorId,r.fields.deviceId,r.fields.installationId,r.fields.collection].map(l=>{if(N(l).every(p=>p===0))throw wn();return l.toLowerCase()});if(!ut(i)||!["fresh","existing"].includes(o)||!["create","join"].includes(r.fields.purpose)||!/^[0-9a-f]{64}$/.test(r.fields.assetSha256)||!globalThis.indexedDB)throw wn();r.check(s),r.db=await r.openDatabase(`mdbase.app.cloud-copy-outcome.v1.${a.join(".")}.${r.fields.purpose}`,o),r.db.onversionchange=()=>r.close(),r.check(s);let c=await r.read(Object.freeze({signal:s}));try{if(o==="fresh"!=(c===null))throw wn();r.check(s)}finally{c?.fill(0)}return r}catch{throw r?.close(),wn()}}openDatabase(e,t){return new Promise((i,o)=>{this.check(this.lifetime);let s=indexedDB.open(e,1),r=!1,a=!1,c=()=>{r=!0,o(wn())},l=()=>this.lifetime.removeEventListener("abort",c);this.lifetime.addEventListener("abort",c,{once:!0}),s.onblocked=c,s.onupgradeneeded=()=>{try{if(this.check(this.lifetime),r||t!=="fresh"||s.result.objectStoreNames.length!==0)throw wn();s.result.createObjectStore(Zy),a=!0}catch{s.transaction?.abort()}},s.onerror=()=>{l(),o(wn())},s.onsuccess=()=>{l();try{if(this.check(this.lifetime),r||t==="fresh"&&!a||s.result.objectStoreNames.length!==1||!s.result.objectStoreNames.contains(Zy))throw wn();i(s.result)}catch{s.result.close(),o(wn())}}})}async read(e){let{signal:t}=e;this.check(t);let i=await this.transaction("readonly",t,null,null);return this.check(t),i}async compareAndSet(e,t,i){let{signal:o}=i;this.check(o);let s=e===null?null:t0(e),r=t0(t);try{let a=await this.transaction("readwrite",o,s,r);return this.check(o),a===!0}finally{s?.fill(0),r.fill(0)}}transaction(e,t,i,o){return new Promise((s,r)=>{if(this.check(t),!this.db)throw wn();let a=this.db.transaction(Zy,e,{durability:"strict"}),c=a.objectStore(Zy),l=null,p=!1,d=()=>{p=!0;try{a.abort()}catch{}},u=()=>t.removeEventListener("abort",d);t.addEventListener("abort",d,{once:!0}),a.onabort=a.onerror=()=>{u(),l instanceof Uint8Array&&l.fill(0),r(wn())},a.oncomplete=()=>{u();try{if(this.check(t),p)throw wn();s(l)}catch{l instanceof Uint8Array&&l.fill(0),r(wn())}};let f=c.get(e0);f.onsuccess=()=>{let h=null;try{this.check(t),h=f.result===void 0?null:t0(f.result),e==="readonly"?(l=h,h=null):(l=V8(h,i),l===!0&&o!==null&&(i===null?c.add(new Uint8Array(o),e0):c.put(new Uint8Array(o),e0)))}catch{d()}finally{h?.fill(0)}}})}close(){this.closed||(this.closed=!0,this.db?.close(),this.db=null)}}});function r0(n,e){if(typeof n!="string"||!n.length||n.length>e*2||n.length%2||!/^[0-9a-f]+$/.test(n))throw ot("response");return Uint8Array.from(n.match(/../g).map(t=>parseInt(t,16)))}function o0(n){if(!n||typeof n!="object"||Array.isArray(n))throw ot("response");return n}var ga,ot,n0,i0,eg,s0=C(()=>{"use strict";St();ve();Ws();ga=class extends Error{constructor(t){super(`app private bootstrap: ${t}`);this.reason=t;this.name="AppPrivateBootstrapError"}reason},ot=n=>new ga(n),n0=n=>Array.from(n,e=>e.toString(16).padStart(2,"0")).join(""),i0=(n,e)=>n.length===e.length&&n.every((t,i)=>t===e[i]);eg=class{constructor(e,t,i,o={}){this.runtime=e;this.session=t;this.persistence=i;this.options=o;try{let s=o.displayName;if(this.displayName=s===void 0?void 0:li(s),this.displayName!==void 0&&t.purpose!=="create")throw ot("binding");this.scope=Object.freeze({connectorId:t.connectorId,deviceId:t.deviceId,installationId:t.installationId,collection:t.collection,purpose:t.purpose,accountId:t.accountId,cpOrigin:t.cpOrigin,logOrigin:t.logOrigin});for(let r of[this.scope.connectorId,this.scope.deviceId,this.scope.installationId,this.scope.collection,this.scope.accountId])if(N(r).every(a=>a===0))throw ot("binding");if(this.origin(this.scope.cpOrigin),this.origin(this.scope.logOrigin),!(t.rootPublicKey instanceof Uint8Array)||t.rootPublicKey.length!==32||t.rootPublicKey.every(r=>r===0)||(this.root=new Uint8Array(t.rootPublicKey),this.fetchImpl=o.fetch??globalThis.fetch,this.now=o.now??Date.now,this.marker=this.scope.purpose==="enrol"?e.privateEnrolMarker():null,!this.current()))throw ot("binding")}catch{throw e.retireLog(),ot("binding")}}runtime;session;persistence;options;attempted=!1;lifetime=new AbortController;scope;root;marker;fetchImpl;now;displayName;origin(e){let t=new URL(e);if(t.username||t.password||t.pathname!=="/"||t.search||t.hash||t.protocol!=="https:"&&!(this.options.allowLoopbackHttp===!0&&Qe(e)))throw ot("binding");return t.origin}current(){try{return!this.lifetime.signal.aborted&&this.runtime.privateCollectionCurrent(this.session)&&this.session.isCurrent()===!0&&this.session.approvalMode==="password-ak1"&&i0(this.session.rootPublicKey,this.root)&&Object.entries(this.scope).every(([e,t])=>this.session[e]===t)}catch{return!1}}markerCopy(){let e=this.marker;if(!e)throw ot("binding");return Object.freeze({...e,sasCommitment:new Uint8Array(e.sasCommitment),signPublicKey:new Uint8Array(e.signPublicKey),kemPublicKey:new Uint8Array(e.kemPublicKey),noisePublicKey:new Uint8Array(e.noisePublicKey)})}check(e){if(!this.current()||e.aborted)throw this.close(),ot("fenced")}async json(e,t,i,o){this.check(o);let s=new AbortController,r=()=>s.abort(),a=setTimeout(r,15e3);a.unref?.(),o.addEventListener("abort",r,{once:!0}),this.lifetime.signal.addEventListener("abort",r,{once:!0});let c=new Uint8Array(1024*1024),l=0,p=null,d=null;try{let u=this.fetchImpl;if(d=await u(`${this.origin(this.scope.cpOrigin)}${e}`,{method:"POST",headers:{authorization:`Bearer ${t}`,...i===void 0?{}:{"content-type":"application/json"}},body:i,signal:s.signal,redirect:"error",credentials:"omit",cache:"default",referrerPolicy:"no-referrer"}),this.check(o),s.signal.aborted||!d.ok)throw ot("unavailable");let f=d.headers.get("content-length");if(f!==null&&/^(0|[1-9][0-9]*)$/.test(f)&&Number(f)>c.length)throw s.abort(),ot("response");if(!d.body)throw ot("response");for(p=d.body.getReader();;){let{done:h,value:m}=await p.read();try{if(this.check(o),s.signal.aborted)throw ot("unavailable");if(h)break;if(l+m.length>c.length)throw s.abort(),ot("response");c.set(m,l),l+=m.length}finally{m?.fill(0)}}return o0(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(c.subarray(0,l))))}catch(u){throw this.check(o),u instanceof ga?u:ot("unavailable")}finally{c.fill(0),(p?.cancel()??d?.body?.cancel())?.catch(()=>{}),p?.releaseLock(),clearTimeout(a),o.removeEventListener("abort",r),this.lifetime.signal.removeEventListener("abort",r)}}copy(e){if(e.displayName!==this.displayName||e.collection!==this.scope.collection||e.deviceId!==this.scope.deviceId||e.logOrigin!==this.scope.logOrigin||!i0(e.rootPublicKey,this.root)||!(e.genesisItem instanceof Uint8Array)||!e.genesisItem.length||e.genesisItem.length>256*1024||e.expectedGenesis.length!==71||!/^sha256:[0-9a-f]{64}$/.test(e.expectedGenesis)||e.approval!==(this.scope.purpose==="create"?"creator":"pending"))throw ot("response");return Object.freeze({collection:e.collection,deviceId:e.deviceId,logOrigin:e.logOrigin,expectedGenesis:e.expectedGenesis,approval:e.approval,...this.displayName===void 0?{}:{displayName:this.displayName},rootPublicKey:new Uint8Array(e.rootPublicKey),genesisItem:new Uint8Array(e.genesisItem)})}async bootstrap(e){let t=null,i=null;try{if(this.check(e.signal),this.attempted)throw ot("fenced");this.attempted=!0;let o=await this.persistence.restoredCompletion(e);if(this.check(e.signal),o){let w=this.copy(o);return this.marker&&!this.marker.acknowledged&&(await this.persistence.privateEnrolAcknowledged(this.markerCopy(),e),this.check(e.signal)),w}if(this.marker?.acknowledged)throw ot("response");this.marker?await this.persistence.privateEnrolPending(this.markerCopy(),e):await this.persistence.pendingCreate({...this.runtime.registeredDeviceReceipt(),collection:this.scope.collection,...this.displayName===void 0?{}:{displayName:this.displayName}},e),this.check(e.signal);let s=await this.session.connectorBearer(e);if(this.check(e.signal),typeof s!="string"||!s||s.length>16384||/[^\x21-\x7e]/.test(s))throw ot("binding");let r=await this.json("/v1/next/devices/challenge",s,void 0,e.signal);if(this.check(e.signal),t=r0(r.challenge,32),t.length!==32||typeof r.expires_at!="number"||!Number.isSafeInteger(r.expires_at)||r.expires_at-this.now()<=5e3||r.expires_at-this.now()>16*6e4)throw ot("response");let a=this.scope.purpose==="enrol";i=a?this.runtime.signPrivateDeviceEnrol(t).signature:this.runtime.signPrivateCreate(t),this.check(e.signal);let c=await this.json(a?`/v1/next/collections/${this.scope.collection}/private/devices`:"/v1/next/collections/private",s,JSON.stringify({device_id:this.scope.deviceId,capabilities:["collection_mode_switch_v2"],challenge:r.challenge,sig:n0(i),...a?{sas_commit:n0(this.marker.sasCommitment)}:{collection_id:this.scope.collection,...this.displayName===void 0?{}:{display_name:this.displayName}}}),e.signal);if(this.check(e.signal),c.collection_id!==this.scope.collection||this.origin(c.log_url)!==this.origin(this.scope.logOrigin))throw ot("response");if(a){if(c.approval!=="pending"||typeof c.enrolled_at!="number"||!Number.isSafeInteger(c.enrolled_at)||c.enrolled_at<1)throw ot("response")}else if(c.state!=="private"||c.owner_account!==this.scope.accountId||!i0(r0(c.root_public_key,32),this.root))throw ot("response");let l=o0(c.device);if(l.device_id!==this.scope.deviceId||typeof l.token!="string"||!l.token.length||l.token.length>16384||/[^\x21-\x7e]/.test(l.token)||typeof l.expires_at!="number"||!Number.isSafeInteger(l.expires_at)||l.expires_at-this.now()<=5e3||l.expires_at-this.now()>16*6e4)throw ot("response");let p=o0(c.genesis);if(p.seq!==1)throw ot("response");let d=r0(p.item,256*1024),u=new TextEncoder().encode("mdbase/v1/chain"),f=new Uint8Array(1+u.length+d.length);f[0]=u.length,f.set(u,1),f.set(d,1+u.length);let h=new Uint8Array(await crypto.subtle.digest("SHA-256",f));this.check(e.signal);let m=this.copy({collection:this.scope.collection,deviceId:this.scope.deviceId,logOrigin:this.scope.logOrigin,rootPublicKey:this.root,genesisItem:d,expectedGenesis:`sha256:${n0(h)}`,approval:a?"pending":"creator",...this.displayName===void 0?{}:{displayName:this.displayName}});return await this.persistence.completed(this.copy(m),e),this.check(e.signal),this.marker&&(await this.persistence.privateEnrolAcknowledged(this.markerCopy(),e),this.check(e.signal)),m}catch(o){throw this.close(),o instanceof ga?o:ot("unavailable")}finally{t?.fill(0),i?.fill(0)}}close(){this.lifetime.abort(),this.runtime.retireLog()}}});var tg,a0,Oe,ba,F8,ng,l0=C(()=>{"use strict";St();Je();ve();Ws();tg=264*1024,a0=tg+256,Oe=()=>new Error("app private bootstrap custody unavailable; preserve storage and reopen"),ba=(n,e)=>n.length===e.length&&n.every((t,i)=>t===e[i]),F8=n=>Array.from(n,e=>e.toString(16).padStart(2,"0")).join(""),ng=class{constructor(e,t,i,o,s,r={}){this.source=e;this.key=i;this.store=o;this.noise=s;try{let a=r.displayName;if(this.displayName=a===void 0?void 0:li(a),this.displayName!==void 0&&e.purpose!=="create")throw Oe();this.pins=Object.freeze({accountId:e.accountId,connectorId:e.connectorId,deviceId:e.deviceId,installationId:e.installationId,collection:e.collection,purpose:e.purpose,cpOrigin:e.cpOrigin,logOrigin:e.logOrigin});let c=[this.pins.accountId,this.pins.connectorId,this.pins.deviceId,this.pins.installationId,this.pins.collection].map(N);if(c.some(l=>l.every(p=>p===0))||!["create","enrol"].includes(this.pins.purpose))throw Oe();for(let l of[e.cpOrigin,e.logOrigin]){let p=new URL(l);if(!(r.allowLoopbackHttp===!0&&Qe(l))&&p.protocol!=="https:"||p.origin!==l||p.username||p.password)throw Oe()}if(!(e.rootPublicKey instanceof Uint8Array)||e.rootPublicKey.length!==32||e.rootPublicKey.every(l=>l===0)||(this.root=new Uint8Array(e.rootPublicKey),this.keys=[t.signPublicKey,t.kemPublicKey,t.noisePublicKey].map(l=>{if(!(l instanceof Uint8Array)||l.length!==32||l.every(p=>p===0))throw Oe();return new Uint8Array(l)}),this.checkReceipt(t),i.type!=="secret"||i.extractable||i.algorithm.name!=="AES-GCM"||i.algorithm.length!==256||!i.usages.includes("encrypt")||!i.usages.includes("decrypt")))throw Oe();this.aad=fe(["mdbase/v1/app-private-bootstrap-platform",...c,this.pins.purpose,e.cpOrigin,e.logOrigin,this.root]),this.check(new AbortController().signal)}catch{throw Oe()}}source;key;store;noise;pins;root;keys;aad;displayName;check(e){try{if(e.aborted||this.source.isCurrent()!==!0||this.source.approvalMode!=="password-ak1"||!ba(this.source.rootPublicKey,this.root)||Object.entries(this.pins).some(([t,i])=>this.source[t]!==i))throw Oe()}catch{throw Oe()}}checkReceipt(e){if(e.connectorId!==this.pins.connectorId||e.deviceId!==this.pins.deviceId||e.installationId!==this.pins.installationId||[e.signPublicKey,e.kemPublicKey,e.noisePublicKey].some((i,o)=>!(i instanceof Uint8Array)||i.length!==32||i.every(s=>s===0)||!ba(i,this.keys[o])))throw Oe()}commit(e){if(this.checkReceipt(e),this.pins.purpose!=="enrol"||e.collection!==this.pins.collection||typeof e.acknowledged!="boolean"||!(e.sasCommitment instanceof Uint8Array)||e.sasCommitment.length!==32||e.sasCommitment.every(t=>t===0))throw Oe();return new Uint8Array(e.sasCommitment)}markerCopy(e,t){return Object.freeze({connectorId:this.pins.connectorId,deviceId:this.pins.deviceId,installationId:this.pins.installationId,collection:this.pins.collection,signPublicKey:new Uint8Array(this.keys[0]),kemPublicKey:new Uint8Array(this.keys[1]),noisePublicKey:new Uint8Array(this.keys[2]),sasCommitment:new Uint8Array(t),acknowledged:e.acknowledged})}copy(e){if(e.displayName!==this.displayName||e.collection!==this.pins.collection||e.deviceId!==this.pins.deviceId||e.logOrigin!==this.pins.logOrigin||!(e.rootPublicKey instanceof Uint8Array)||!ba(e.rootPublicKey,this.root)||!(e.genesisItem instanceof Uint8Array)||!e.genesisItem.length||e.genesisItem.length>256*1024||!/^sha256:[0-9a-f]{64}$/.test(e.expectedGenesis)||e.approval!==(this.pins.purpose==="create"?"creator":"pending"))throw Oe();return Object.freeze({collection:this.pins.collection,deviceId:this.pins.deviceId,logOrigin:this.pins.logOrigin,rootPublicKey:new Uint8Array(this.root),genesisItem:new Uint8Array(e.genesisItem),expectedGenesis:e.expectedGenesis,approval:e.approval,...this.displayName===void 0?{}:{displayName:this.displayName}})}async hashChecked(e,t){let i=new TextEncoder().encode("mdbase/v1/chain"),o=new Uint8Array(1+i.length+e.genesisItem.length);o[0]=i.length,o.set(i,1),o.set(e.genesisItem,1+i.length);let s=new Uint8Array(await crypto.subtle.digest("SHA-256",o));if(this.check(t),e.expectedGenesis!==`sha256:${F8(s)}`)throw Oe()}async read(e){let t=null;try{this.check(e.signal);let i=await this.store.read(e);if(this.check(e.signal),i===null)return null;if(!(i instanceof Uint8Array)||!i.length||i.length>a0)throw Oe();let o=new Uint8Array(i),s=we(o);if(!(s instanceof Map))throw Oe();let r=s;if(r.size!==3||r.get(0)!==1)throw Oe();let a=r.get(1),c=r.get(2);if(!(a instanceof Uint8Array)||a.length!==12||!(c instanceof Uint8Array)||c.length<16||c.length>tg+16||(t=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:new Uint8Array(a),additionalData:new Uint8Array(this.aad),tagLength:128},this.key,new Uint8Array(c))),this.check(e.signal),t.length>tg))throw Oe();let l=we(t);if(!(l instanceof Map))throw Oe();let p=l,d=p.get(0)===1&&p.size===4;if(!d&&!(p.get(0)===2&&p.size===5)||(d?null:p.get(4))!==(this.displayName??null))throw Oe();let u=p.get(1);if(!Array.isArray(u)||u.length!==3||u.some((w,b)=>!(w instanceof Uint8Array)||!ba(w,this.keys[b])))throw Oe();let f=p.get(2);if(this.pins.purpose==="create"?f!==null:!(f instanceof Uint8Array)||f.length!==32||f.every(w=>w===0))throw Oe();let h=p.get(3),m=null;if(h!==null){if(!Array.isArray(h)||h.length!==2||!(h[0]instanceof Uint8Array)||typeof h[1]!="string")throw Oe();m=this.copy({...this.pins,rootPublicKey:this.root,genesisItem:h[0],expectedGenesis:h[1],approval:this.pins.purpose==="create"?"creator":"pending",...this.displayName===void 0?{}:{displayName:this.displayName}}),await this.hashChecked(m,e.signal)}return{encrypted:o,value:{commit:f===null?null:new Uint8Array(f),metadata:m}}}catch{throw Oe()}finally{t?.fill(0)}}async write(e,t,i){let o=null,s=null;try{if(this.check(i.signal),o=fe(new Map([[0,2],[1,this.keys.map(l=>new Uint8Array(l))],[2,e.commit],[3,e.metadata===null?null:[e.metadata.genesisItem,e.metadata.expectedGenesis]],[4,this.displayName??null]])),o.length>tg)throw Oe();let r=crypto.getRandomValues(new Uint8Array(12)),a=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:r,additionalData:new Uint8Array(this.aad),tagLength:128},this.key,new Uint8Array(o)));this.check(i.signal),s=fe(new Map([[0,1],[1,r],[2,a]]));let c=await this.store.compareAndSet(t,s,i);if(this.check(i.signal),c!==!0)throw Oe()}catch{throw Oe()}finally{o?.fill(0),s?.fill(0)}}async pendingCreate(e,t){if(this.check(t.signal),this.checkReceipt(e),this.pins.purpose!=="create"||e.collection!==this.pins.collection||e.displayName!==this.displayName)throw Oe();let i=await this.read(t);this.check(t.signal),!i&&await this.write({commit:null,metadata:null},null,t)}async privateEnrolPending(e,t){this.check(t.signal);let i=this.commit(e),o=this.markerCopy(e,i);if(o.acknowledged)throw Oe();let s=await this.read(t);if(this.check(t.signal),s&&!ba(s.value.commit,i))throw Oe();try{await this.noise.privateEnrolPending(o,t),this.check(t.signal)}catch{throw Oe()}s||await this.write({commit:i,metadata:null},null,t)}async completed(e,t){this.check(t.signal);let i=this.copy(e);await this.hashChecked(i,t.signal);let o=await this.read(t);if(this.check(t.signal),!o)throw Oe();if(o.value.metadata){if(!ba(o.value.metadata.genesisItem,i.genesisItem)||o.value.metadata.expectedGenesis!==i.expectedGenesis)throw Oe();return}await this.write({...o.value,metadata:i},o.encrypted,t)}async privateEnrolAcknowledged(e,t){this.check(t.signal);let i=this.commit(e),o=this.markerCopy(e,i),s=await this.read(t);if(this.check(t.signal),!s?.value.metadata||!ba(s.value.commit,i))throw Oe();try{await this.noise.privateEnrolAcknowledged(o,t),this.check(t.signal)}catch{throw Oe()}}async restoredCompletion(e){let t=await this.read(e);return this.check(e.signal),t?.value.metadata?this.copy(t.value.metadata):null}}});function p0(n){if(!(n instanceof Uint8Array)||!n.length||n.length>a0)throw vn();return new Uint8Array(n)}var ig,qE,vn,c0,rg,TE=C(()=>{"use strict";Jt();ve();l0();ig="public-outcome",qE="operation",vn=()=>new Error("app private bootstrap store unavailable"),c0=(n,e)=>n===null||e===null?n===e:n.length===e.length&&n.every((t,i)=>t===e[i]);rg=class n{constructor(e,t,i,o,s){this.db=e;this.source=t;this.pins=i;this.root=o;this.origin=s;e.onversionchange=()=>this.close()}db;source;pins;root;origin;closed=!1;static async open(e){try{return await this.openChecked(e)}catch{throw vn()}}static async openChecked(e){let{source:t,signal:i}=e,o=Object.freeze({accountId:t.accountId,connectorId:t.connectorId,deviceId:t.deviceId,installationId:t.installationId,collection:t.collection,purpose:t.purpose,cpOrigin:t.cpOrigin,logOrigin:t.logOrigin}),s=[o.accountId,o.connectorId,o.deviceId,o.installationId,o.collection];for(let d of s)if(N(d).every(u=>u===0))throw vn();if(!(t.rootPublicKey instanceof Uint8Array)||t.rootPublicKey.length!==32||t.rootPublicKey.every(d=>d===0))throw vn();let r=new Uint8Array(t.rootPublicKey);if(!ut(e.origin)||Et()!==e.origin||!["fresh","existing"].includes(e.mode)||!["create","enrol"].includes(o.purpose)||!globalThis.indexedDB)throw vn();let a=()=>{try{return!i.aborted&&t.isCurrent()===!0&&t.approvalMode==="password-ak1"&&t.rootPublicKey instanceof Uint8Array&&c0(t.rootPublicKey,r)&&Object.entries(o).every(([d,u])=>t[d]===u)}catch{return!1}};if(!a())throw vn();let c=`mdbase.app.private-bootstrap.v1.${s.map(d=>d.toLowerCase()).join(".")}.${o.purpose}`,l=await new Promise((d,u)=>{let f=indexedDB.open(c,1),h=!1,m=()=>{h=!0,u(vn())},w=()=>i.removeEventListener("abort",m);i.addEventListener("abort",m,{once:!0}),f.onblocked=m,f.onupgradeneeded=()=>{if(h||!a()||e.mode!=="fresh"||f.result.objectStoreNames.length!==0){f.transaction?.abort();return}f.result.createObjectStore(ig)},f.onerror=()=>{w(),u(vn())},f.onsuccess=()=>{if(w(),h||!a()||f.result.objectStoreNames.length!==1||!f.result.objectStoreNames.contains(ig)){f.result.close(),u(vn());return}d(f.result)}}),p=new n(l,t,o,r,e.origin);try{let d=await p.read({signal:i});if(e.mode==="fresh"!=(d===null))throw vn();return d?.fill(0),p.check(i),p}catch{throw p.close(),vn()}}check(e){try{if(this.closed||e.aborted||Et()!==this.origin||this.source.isCurrent()!==!0||this.source.approvalMode!=="password-ak1"||!(this.source.rootPublicKey instanceof Uint8Array)||!c0(this.source.rootPublicKey,this.root)||Object.entries(this.pins).some(([t,i])=>this.source[t]!==i))throw vn()}catch{throw vn()}}async read(e){this.check(e.signal);let t=await this.transaction("readonly",e.signal,null,null);return this.check(e.signal),t}async compareAndSet(e,t,i){this.check(i.signal);let o=null,s=null;try{o=e===null?null:p0(e),s=p0(t);let r=await this.transaction("readwrite",i.signal,o,s);return this.check(i.signal),r===!0}finally{o?.fill(0),s?.fill(0)}}transaction(e,t,i,o){return new Promise((s,r)=>{this.check(t);let a=this.db.transaction(ig,e,{durability:"strict"}),c=a.objectStore(ig),l=null,p=!1,d=()=>{p=!0;try{a.abort()}catch{}},u=()=>t.removeEventListener("abort",d);t.addEventListener("abort",d,{once:!0}),a.onabort=a.onerror=()=>{u(),l instanceof Uint8Array&&l.fill(0),r(vn())},a.oncomplete=()=>{u();try{if(this.check(t),p)throw vn();s(l)}catch{l instanceof Uint8Array&&l.fill(0),r(vn())}};let f=c.get(qE);f.onsuccess=()=>{let h=null;try{this.check(t),h=f.result===void 0?null:p0(f.result),e==="readonly"?(l=h,h=null):(l=c0(h,i),l===!0&&o!==null&&c.put(new Uint8Array(o),qE))}catch{d()}finally{h?.fill(0)}}})}close(){this.closed||(this.closed=!0,this.db.close())}}});var ME,LE=C(()=>{ME=Uint8Array.from([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9])});function ms(n,e,t,i,o,s){let r=o[s],a=o[s+1],c=H[2*n],l=H[2*n+1],p=H[2*e],d=H[2*e+1],u=H[2*t],f=H[2*t+1],h=H[2*i],m=H[2*i+1],w=op(c,p,r);l=sp(w,l,d,a),c=w|0;let b=m^l,g=h^c;m=eS(b,g),h=tS(b,g),{h:f,l:u}=ni(f,u,m,h),b=d^f,g=p^u,d=hr(b,g,24),p=mr(b,g,24),H[2*n]=c,H[2*n+1]=l,H[2*e]=p,H[2*e+1]=d,H[2*t]=u,H[2*t+1]=f,H[2*i]=h,H[2*i+1]=m}function ys(n,e,t,i,o,s){let r=o[s],a=o[s+1],c=H[2*n],l=H[2*n+1],p=H[2*e],d=H[2*e+1],u=H[2*t],f=H[2*t+1],h=H[2*i],m=H[2*i+1],w=op(c,p,r);l=sp(w,l,d,a),c=w|0;let b=m^l,g=h^c;m=hr(b,g,16),h=mr(b,g,16),{h:f,l:u}=ni(f,u,m,h),b=d^f,g=p^u,d=xs(b,g,63),p=Is(b,g,63),H[2*n]=c,H[2*n+1]=l,H[2*e]=p,H[2*e+1]=d,H[2*t]=u,H[2*t+1]=f,H[2*i]=h,H[2*i+1]=m}function K8(n,e={},t,i,o){if(xn(t),n<=0||n>t)throw new Error('"dkLen" must be 1..'+t+", got "+n);let{key:s,salt:r,personalization:a}=e;if(s!==void 0&&(s.length<1||s.length>t))throw new Error('"key" expected to be undefined or of length=1..'+t);r!==void 0&&mt(r,i,"salt"),a!==void 0&&mt(a,o,"personalization")}var Bt,H,d0,u0,bc,jE=C(()=>{LE();Zu();yr();Bt=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),H=new Uint32Array(32);d0=class{buffer;buffer32;finished=!1;destroyed=!1;length=0;pos=0;blockLen;outputLen;canXOF=!1;constructor(e,t){xn(e),xn(t),this.blockLen=e,this.outputLen=t,this.buffer=new Uint8Array(e),this.buffer32=Ro(this.buffer)}update(e){Xr(this),mt(e);let{blockLen:t,buffer:i,buffer32:o}=this,s=e.length,r=e.byteOffset,a=e.buffer;for(let c=0;c<s;){this.pos===t&&(Di(o),this.compress(o,0,!1),Di(o),this.pos=0);let l=Math.min(t-this.pos,s-c),p=r+c;if(l===t&&!(p%4)&&c+l<s){let d=new Uint32Array(a,p,Math.floor((s-c)/4));Di(d);for(let u=0;c+t<s;u+=o.length,c+=t)this.length+=t,this.compress(d,u,!1);Di(d);continue}i.set(c===0&&l===s?e:e.subarray(c,c+l),this.pos),this.pos+=l,this.length+=l,c+=l}return this}digestInto(e){if(Xr(this),ja(e,this),e.byteOffset&3)throw new RangeError('"output" expected 4-byte aligned byteOffset, got '+e.byteOffset);let{pos:t,buffer32:i}=this;this.finished=!0,this.buffer.fill(0,t),Di(i),this.compress(i,0,!0),Di(i);let o=this.get(),s=e===this.buffer?i:Ro(e),r=Math.floor(this.outputLen/4);for(let p=0;p<r;p++)s[p]=nn(o[p]);let a=this.outputLen%4;if(!a)return;let c=r*4,l=o[r];for(let p=0;p<a;p++)e[c+p]=l>>>8*p}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let i=e.slice(0,t);return this.destroy(),i}_cloneInto(e){let{buffer:t,length:i,finished:o,destroyed:s,outputLen:r,pos:a}=this;return e||=new this.constructor({dkLen:r}),e.set(...this.get()),e.buffer.set(t),e.destroyed=s,e.finished=o,e.length=i,e.pos=a,e.outputLen=r,e}clone(){return this._cloneInto()}},u0=class extends d0{v0l=Bt[0]|0;v0h=Bt[1]|0;v1l=Bt[2]|0;v1h=Bt[3]|0;v2l=Bt[4]|0;v2h=Bt[5]|0;v3l=Bt[6]|0;v3h=Bt[7]|0;v4l=Bt[8]|0;v4h=Bt[9]|0;v5l=Bt[10]|0;v5h=Bt[11]|0;v6l=Bt[12]|0;v6h=Bt[13]|0;v7l=Bt[14]|0;v7h=Bt[15]|0;constructor(e={}){e=cp({},e);let t=e.dkLen===void 0?64:e.dkLen;super(128,t),K8(t,e,64,16,16);let{key:i,personalization:o,salt:s}=e,r=0;if(i!==void 0&&(mt(i,void 0,"key"),r=i.length),this.v0l^=this.outputLen|r<<8|65536|1<<24,s!==void 0){mt(s,void 0,"salt");let a=Ro(Tb(s));this.v4l^=nn(a[0]),this.v4h^=nn(a[1]),this.v5l^=nn(a[2]),this.v5h^=nn(a[3])}if(o!==void 0){mt(o,void 0,"personalization");let a=Ro(Tb(o));this.v6l^=nn(a[0]),this.v6h^=nn(a[1]),this.v7l^=nn(a[2]),this.v7h^=nn(a[3])}if(i!==void 0){let a=new Uint8Array(this.blockLen);a.set(i),this.update(a),at(a)}}get(){let{v0l:e,v0h:t,v1l:i,v1h:o,v2l:s,v2h:r,v3l:a,v3h:c,v4l:l,v4h:p,v5l:d,v5h:u,v6l:f,v6h:h,v7l:m,v7h:w}=this;return[e,t,i,o,s,r,a,c,l,p,d,u,f,h,m,w]}set(e,t,i,o,s,r,a,c,l,p,d,u,f,h,m,w){this.v0l=e|0,this.v0h=t|0,this.v1l=i|0,this.v1h=o|0,this.v2l=s|0,this.v2h=r|0,this.v3l=a|0,this.v3h=c|0,this.v4l=l|0,this.v4h=p|0,this.v5l=d|0,this.v5h=u|0,this.v6l=f|0,this.v6h=h|0,this.v7l=m|0,this.v7h=w|0}compress(e,t,i){let{v0l:o,v0h:s,v1l:r,v1h:a,v2l:c,v2h:l,v3l:p,v3h:d,v4l:u,v4h:f,v5l:h,v5h:m,v6l:w,v6h:b,v7l:g,v7h:y}=this;H[0]=o,H[1]=s,H[2]=r,H[3]=a,H[4]=c,H[5]=l,H[6]=p,H[7]=d,H[8]=u,H[9]=f,H[10]=h,H[11]=m,H[12]=w,H[13]=b,H[14]=g,H[15]=y,H.set(Bt,16);let v=Rb(this.length),_=Cb(this.length);H[24]=Bt[8]^v,H[25]=Bt[9]^_,i&&(H[28]=~H[28],H[29]=~H[29]);let k=0,S=ME;for(let x=0;x<12;x++)ms(0,4,8,12,e,t+2*S[k++]),ys(0,4,8,12,e,t+2*S[k++]),ms(1,5,9,13,e,t+2*S[k++]),ys(1,5,9,13,e,t+2*S[k++]),ms(2,6,10,14,e,t+2*S[k++]),ys(2,6,10,14,e,t+2*S[k++]),ms(3,7,11,15,e,t+2*S[k++]),ys(3,7,11,15,e,t+2*S[k++]),ms(0,5,10,15,e,t+2*S[k++]),ys(0,5,10,15,e,t+2*S[k++]),ms(1,6,11,12,e,t+2*S[k++]),ys(1,6,11,12,e,t+2*S[k++]),ms(2,7,8,13,e,t+2*S[k++]),ys(2,7,8,13,e,t+2*S[k++]),ms(3,4,9,14,e,t+2*S[k++]),ys(3,4,9,14,e,t+2*S[k++]);this.v0l^=H[0]^H[16],this.v0h^=H[1]^H[17],this.v1l^=H[2]^H[18],this.v1h^=H[3]^H[19],this.v2l^=H[4]^H[20],this.v2h^=H[5]^H[21],this.v3l^=H[6]^H[22],this.v3h^=H[7]^H[23],this.v4l^=H[8]^H[24],this.v4h^=H[9]^H[25],this.v5l^=H[10]^H[26],this.v5h^=H[11]^H[27],this.v6l^=H[12]^H[28],this.v6h^=H[13]^H[29],this.v7l^=H[14]^H[30],this.v7h^=H[15]^H[31],at(H)}destroy(){this.destroyed=!0,at(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},bc=pp(n=>new u0(n))});function gs(n,e,t,i){let o=jt[2*n],s=jt[2*n+1],r=jt[2*e],a=jt[2*e+1],c=jt[2*t],l=jt[2*t+1],p=jt[2*i],d=jt[2*i+1],u=0,f=0,h=0,m=0,w=0;u=Math.imul(o,r),f=((o>>>0)*(r>>>0)-(u>>>0))/4294967296+.5|0,h=(o>>>0)+(r>>>0)+(u<<1>>>0),s=s+a+(f<<1|u>>>31)+(h/4294967296|0)|0,o=h|0,m=d^s,w=p^o,d=w,p=m,u=Math.imul(c,p),f=((c>>>0)*(p>>>0)-(u>>>0))/4294967296+.5|0,h=(c>>>0)+(p>>>0)+(u<<1>>>0),l=l+d+(f<<1|u>>>31)+(h/4294967296|0)|0,c=h|0,m=a^l,w=r^c,a=m>>>24|w<<8,r=m<<8|w>>>24,u=Math.imul(o,r),f=((o>>>0)*(r>>>0)-(u>>>0))/4294967296+.5|0,h=(o>>>0)+(r>>>0)+(u<<1>>>0),s=s+a+(f<<1|u>>>31)+(h/4294967296|0)|0,o=h|0,m=d^s,w=p^o,d=m>>>16|w<<16,p=m<<16|w>>>16,u=Math.imul(c,p),f=((c>>>0)*(p>>>0)-(u>>>0))/4294967296+.5|0,h=(c>>>0)+(p>>>0)+(u<<1>>>0),l=l+d+(f<<1|u>>>31)+(h/4294967296|0)|0,c=h|0,m=a^l,w=r^c,a=m<<1|w>>>31,r=m>>>31|w<<1,jt[2*n]=o,jt[2*n+1]=s,jt[2*e]=r,jt[2*e+1]=a,jt[2*t]=c,jt[2*t+1]=l,jt[2*i]=p,jt[2*i+1]=d}function NE(n,e,t,i,o,s,r,a,c,l,p,d,u,f,h,m){gs(n,o,c,u),gs(e,s,l,f),gs(t,r,p,h),gs(i,a,d,m),gs(n,s,p,m),gs(e,r,d,u),gs(t,a,c,f),gs(i,o,l,h)}function lu(n,e,t,i,o){if(o)for(let s=0;s<256;s++){let r=n[e+s]^n[t+s];jt[s]=r,n[i+s]^=r}else for(let s=0;s<256;s++){let r=n[e+s]^n[t+s];jt[s]=r,n[i+s]=r}for(let s=0;s<128;s+=16)NE(s,s+1,s+2,s+3,s+4,s+5,s+6,s+7,s+8,s+9,s+10,s+11,s+12,s+13,s+14,s+15);for(let s=0;s<16;s+=2)NE(s,s+1,s+16,s+17,s+32,s+33,s+48,s+49,s+64,s+65,s+80,s+81,s+96,s+97,s+112,s+113);for(let s=0;s<256;s++)n[i+s]^=jt[s];at(jt)}function f0(n,e){let t=lp(n),i=new Uint32Array(1),o=lp(i);if(i[0]=nn(e),e<=64)return bc.create({dkLen:e}).update(o).update(t).digest();let s=new Uint8Array(e),r=bc.create({}).update(o).update(t).digest(),a=0;for(s.set(r.subarray(0,32)),a+=32;e-a>64;a+=32){let c=bc.create({}).update(r);c.digestInto(r),c.destroy(),s.set(r.subarray(0,32),a)}return s.set(bc(r,{dkLen:e-a}),a),at(r,i),s}function W8(n,e,t,i,o,s,r=!1){let a;n===0?e===0?a=o-1:r?a=e*i+o-1:a=e*i+(o==0?-1:0):r?a=t-i+o-1:a=t-i+(o==0?-1:0);let c=n!==0&&e!==cu-1?(e+1)*i:0,l=Math.imul(s,s),p=((s>>>0)*(s>>>0)-(l>>>0))/4294967296+.5|0,d=Math.imul(a,p),u=((a>>>0)*(p>>>0)-(d>>>0))/4294967296+.5|0,f=a-1-u;return(c+f)%t}function bs(n){return Number.isSafeInteger(n)&&n>=0&&n<H8}function Y8(n={}){n=cp({},n);let e={t:3,m:DE,p:1,version:19,dkLen:32,maxmem:G8,asyncTick:10};for(let[l,p]of Object.entries(n))p!==void 0&&(e[l]=p);let{dkLen:t,p:i,m:o,t:s,version:r,onProgress:a,asyncTick:c}=e;if(!bs(t)||t<4)throw new Error('"dkLen" must be 4..');if(!bs(i)||i<1||i>=Math.pow(2,24))throw new Error('"p" must be 1..2^24');if(!bs(o))throw new Error('"m" must be 0..2^32');if(!bs(s)||s<1)throw new Error('"t" (iterations) must be 1..2^32');if(a!==void 0&&typeof a!="function")throw new Error('"onProgress" must be a function');if(xn(c,"asyncTick"),!bs(o)||o<8*i)throw new Error('"m" (memory) must be at least 8*p bytes');if(r!==16&&r!==19)throw new Error('"version" must be 0x10 or 0x13, got '+r);return e}function J8(n,e,t,i){let o=[],s=new Uint32Array(1),r=lp(s),a,c,l=!1,p=(d,u)=>(typeof d=="string"&&o.push(u),u);try{let d=p(n,nf(n,"password")),u=p(e,nf(e,"salt"));if(!bs(d.length))throw new Error('"password" must be less of length 1..4Gb');if(!bs(u.length)||u.length<8)throw new Error('"salt" must be of length 8..4Gb');if(!Object.values(og).includes(t))throw new Error('"type" was invalid');let{p:f,dkLen:h,m,t:w,version:b,key:g,personalization:y,maxmem:v,onProgress:_,asyncTick:k}=Y8(i),S=g;g=p(S,UE(S,"key"));let x=y;y=p(x,UE(x,"personalization")),a=bc.create();for(let P of[f,h,m,w,b,t])s[0]=nn(P),a.update(r);for(let P of[d,u,g,y])s[0]=nn(P.length),a.update(r).update(P);return c=new Uint32Array(18),a.digestInto(lp(c)),l=!0,{H0:c,p:f,dkLen:h,m,t:w,version:b,maxmem:v,onProgress:_,asyncTick:k}}finally{a&&a.destroy(),at(s,...o),!l&&c&&at(c)}}function X8(n,e,t,i){let{H0:o,p:s,dkLen:r,m:a,t:c,version:l,maxmem:p,onProgress:d,asyncTick:u}=J8(n,e,t,i);try{let f=s,h=4*s*Math.floor(a/(cu*s)),m=Math.floor(h/s),w=Math.floor(m/cu),b=h*1024;if(!bs(p))throw new Error('"maxmem" expected <2**32, got '+p);if(b>p)throw new Error('"maxmem" limit was hit: memUsed(mP*1024)='+b+", maxmem="+p);let g=new Uint32Array(b/4);for(let v=0;v<s;v++){let _=256*m*v;o[17]=nn(v),o[16]=nn(0),g.set(Di(Ro(f0(o,1024))),_),o[16]=nn(1),g.set(Di(Ro(f0(o,1024))),_+256)}let y=()=>{};if(d){let v=c*cu*s*w-2*s,_=Math.max(Math.floor(v/1e4),1),k=0;y=()=>{k++,d&&(!(k%_)||k===v)&&d(k/v)}}return{type:t,mP:h,p:s,t:c,version:l,B:g,laneLen:m,lanes:f,segmentLen:w,dkLen:r,perBlock:y,asyncTick:u}}finally{at(o)}}function Z8(n,e,t,i){let o=new Uint32Array(256);for(let r=0;r<e;r++)for(let a=0;a<256;a++)o[a]^=n[256*(t*r+t-1)+a];let s=f0(Di(o),i);return at(n,o),s}function*Q8(n,e){let{type:t,mP:i,p:o,t:s,version:r,B:a,laneLen:c,lanes:l,segmentLen:p,perBlock:d}=n;e[262]=i,e[264]=s,e[266]=t;for(let u=0;u<s;u++){let f=u!==0&&r===19;e[256]=u;for(let h=0;h<cu;h++){e[260]=h;let m=t==og.Argon2i||t==og.Argon2id&&u===0&&h<2;for(let w=0;w<o;w++){e[258]=w,e[268]=0;let b=0;u===0&&h===0&&(b=2,m&&(e[268]++,lu(e,256,2*256,0,!1),lu(e,0,2*256,0,!1)));let g=w*c+h*p+b;for(let y=b;y<p;y++,g++){d();let v=g%c?g-1:g+c-1,_,k;if(m){let I=y%128;I===0&&(e[268]++,lu(e,256,2*256,0,!1),lu(e,0,2*256,0,!1)),_=e[2*I],k=e[2*I+1]}else{let I=256*v;_=a[I],k=a[I+1]}let S=u===0&&h===0?w:k%l,x=W8(u,h,c,p,y,_,S==w),P=c*S+x;lu(a,256*v,256*P,g*256,f),yield}}}}at(e)}async function eD(n,e,t,i){let o=X8(e,t,n,i),s=new Uint32Array(3*256),r=Q8(o,s),a=()=>at(s,o.B),c=Date.now();for(;!r.next().done;){let l=Date.now()-c;l>=0&&l<o.asyncTick||(await uS(a),c=Date.now())}return Z8(o.B,o.p,o.laneLen,o.dkLen)}var og,cu,UE,jt,H8,DE,G8,zE,$E=C(()=>{jE();yr();og={Argon2d:0,Argon2i:1,Argon2id:2},cu=4,UE=(n,e="")=>n===void 0?Uint8Array.of():nf(n,e),jt=new Uint32Array(256);H8=Math.pow(2,32),DE=1024**2,G8=DE*1024;zE=(n,e,t={})=>eD(og.Argon2id,n,e,t)});function nD(n,e,t,i=32,o){ap(n),xn(i,"length"),mt(e,void 0,"prk");let s=n.outputLen;if(e.length<s)throw new Error('"prk" must be at least HashLen octets');if(i>255*s)throw new Error("Length must be <= 255*HashLen");let r=Math.ceil(i/s);if(t===void 0?t=tD:mt(t,void 0,"info"),!r)return o&&at(e),new Uint8Array;let a=o&&r===1?e:new Uint8Array(r*s),{iHash:c,oHash:l}=ca.create(n,e),p=o?e:new Uint8Array(s),d=r>1?o?.iHash||n.create():void 0;for(let f=0;f<r-1;f++){pu[0]=f+1;let h=c._cloneInto(d);f&&h.update(p),h.update(t).update(pu).digestInto(p),l._cloneInto(d).update(p).digestInto(p),a.set(p,s*f)}if(pu[0]=r,r>1&&c.update(p),c.update(t).update(pu).digestInto(p),l.update(p).digestInto(p),a.set(p,s*(r-1)),c.destroy(),l.destroy(),d?.destroy(),p!==a&&at(p),at(pu),i===a.length)return a;let u=a.slice(0,i);return at(a),u}var pu,tD,sg,BE=C(()=>{xA();yr();pu=Uint8Array.of(0),tD=Uint8Array.of();sg=(n,e,t,i,o)=>{ap(n),t===void 0&&(t=new Uint8Array(n.outputLen));let s=ca.create(n,t).update(e);return nD(n,s.digest(),i,o,s)}});function va(n,e){let t=wc.encode(n);if(t.length>255)throw De("internal","domain tag longer than 255 bytes");return Ze(y0(Uint8Array.of(t.length),t,e))}function y0(...n){let e=0;for(let o of n)e+=o.length;let t=new Uint8Array(e),i=0;for(let o of n)t.set(o,i),i+=o.length;return t}function g0(n,e){if(n.length!==e.length)return!1;let t=0;for(let i=0;i<n.length;i++)t|=n[i]^e[i];return t===0}function wt(...n){for(let e of n)e.fill(0)}function Xn(n){if(!iD.test(n))throw De("internal","not a UUID");let e=n.replace(/-/g,"").toLowerCase(),t=new Uint8Array(16);for(let i=0;i<16;i++)t[i]=parseInt(e.slice(i*2,i*2+2),16);return t}function rD(n){let e="";for(let t of n)e+=t.toString(16).padStart(2,"0");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function FE(n=ag){let e=n(ar);if(e.length!==ar)throw De("internal","entropy returned the wrong length");return e}function KE(n){return va("mdbase/v1/recovery-key-check",n).subarray(0,VE)}function WE(n){if(n.length!==ar)throw De("internal","recovery secret is 32 bytes");let e=y0(n,KE(n)),t="",i=0,o=0;for(let s of e){for(i=i<<8|s,o+=8;o>=5;)t+=h0[i>>>o-5&31],o-=5;i&=(1<<o)-1}return o>0&&(t+=h0[i<<5-o&31]),wt(e),[m0,...t.match(/.{1,5}/g)].join("-")}function uu(n){if(typeof n!="string"||n.length>4096)throw De("invalid_recovery_key","Not a recovery key.","wrong_length");let e=n.toUpperCase().replace(/[\s-]/g,"").replace(/O/g,"0").replace(/[IL]/g,"1");if(!e.startsWith(m0))throw De("invalid_recovery_key","A recovery key starts with MDB1.","wrong_prefix");if(e=e.slice(m0.length),e.length!==oD)throw De("invalid_recovery_key","A recovery key has 55 characters after MDB1.","wrong_length");let t=new Uint8Array(ar+VE),i=0,o=0,s=0;for(let c of e){let l=h0.indexOf(c);if(l<0)throw De("invalid_recovery_key","A recovery key uses only Crockford base32 characters.","bad_character");i=i<<5|l,o+=5,o>=8&&(s<t.length&&(t[s++]=i>>>o-8&255),o-=8),i&=(1<<o)-1}if(s!==t.length||i!==0)throw De("invalid_recovery_key","Not a recovery key.","bad_character");let r=t.slice(0,ar),a=g0(KE(r),t.subarray(ar));if(wt(t),!a)throw wt(r),De("invalid_recovery_key","The recovery key has a typo (check failed).","checksum");return r}function HE(n,e){if(n.length!==ar)throw De("internal","recovery secret is 32 bytes");let t=Xn(e),i=sg(Ze,n,t,wc.encode("mdbase/v1/recovery-sign"),32),o=sg(Ze,n,t,wc.encode("mdbase/v1/recovery-kem"),32),s=eu.getPublicKey(i),r=or.getPublicKey(o);return{device:rD(va("mdbase/v1/recovery-id",y0(t,s)).subarray(0,16)),signSeed:i,signPk:s,kemSk:o,kemPk:r,noisePk:new Uint8Array(32)}}function GE(n,e){return eu.sign(e,n.signSeed)}function YE(n){wt(n.signSeed,n.kemSk)}function JE(n,e){if(n.length!==ar)throw De("internal","recovery secret is 32 bytes");let t=sg(Ze,n,Xn(e),wc.encode("mdbase/v1/account-key-proof"),32);return{seed:t,pk:eu.getPublicKey(t)}}function sD(n,e,t){if(!Number.isSafeInteger(t)||t<0)throw De("internal","expected_version");return va("mdbase/v1/account-key-rewrap",fe([Xn(n),Ze(e),t]))}function XE(n,e,t,i){return eu.sign(sD(e,t,i),n.seed)}function fu(n){return va("mdbase/v1/account-key-id",n)}function fD(n){if(!(wa(n.mKib)&&wa(n.t)&&wa(n.p)&&n.mKib>=cD&&n.mKib<=QE&&n.t>=pD&&n.t<=dD&&n.p>=1&&n.p<=uD&&n.mKib>=8*n.p&&n.salt instanceof Uint8Array&&n.salt.length===16))throw De("params","Unsupported key derivation parameters.")}function e2(n){return[ZE,n.mKib,n.t,n.p,n.salt]}function hD(n){if(!Array.isArray(n)||n.length!==5)throw De("encoding","Not an account key bundle.");let[e,t,i,o,s]=n;if(!wa(e)||!wa(t)||!wa(i)||!wa(o)||!(s instanceof Uint8Array)||s.length!==16)throw De("encoding","Not an account key bundle.");if(e!==ZE||t>4294967295||i>4294967295||o>4294967295)throw De("params","Unsupported key derivation parameters.");return{mKib:t,t:i,p:o,salt:s}}function w0(n){return fe($g([[0,b0],[1,e2(n.kdf)],[2,n.nonce],[3,n.ct],[4,n.keyId]]))}function t2(n){if(!(n instanceof Uint8Array)||n.length>aD)throw De("encoding","Not an account key bundle.");let e;try{e=we(n)}catch{throw De("encoding","Not an account key bundle.")}if(!(e instanceof Map)||e.size!==5||[...e.keys()].join()!=="0,1,2,3,4")throw De("encoding","Not an account key bundle.");let t=e,i=t.get(2),o=t.get(3),s=t.get(4);if(t.get(0)!==b0||!(i instanceof Uint8Array)||i.length!==24||!(o instanceof Uint8Array)||o.length!==48||!(s instanceof Uint8Array)||s.length!==32)throw De("encoding","Not an account key bundle.");let r={kdf:hD(t.get(1)),nonce:i,ct:o,keyId:s};if(!Bg(w0(r),n))throw De("encoding","Not an account key bundle.");return r}function n2(n){if(typeof n!="string")throw De("weak_password","The password is required.","too_short");if(wc.encode(n).length>du)throw De("weak_password","The password is too long.","too_long");let e=n.normalize("NFKC"),t=wc.encode(e);if(t.length>du)throw De("weak_password","The password is too long.","too_long");if([...e].length<vc)throw wt(t),De("weak_password",`The password needs at least ${vc} characters.`,"too_short");return t}function _a(n){wt(n2(n))}async function i2(n,e,t,i){fD(e);let o=n2(n);try{let s=await t(o,e.salt,{mKib:e.mKib,t:e.t,p:e.p},i);if(!(s instanceof Uint8Array)||s.length!==32)throw De("internal","The KDF runner returned the wrong length.");return s}finally{wt(o)}}function r2(n,e,t){return va("mdbase/v1/account-key-bundle",fe([b0,Xn(n),e,e2(t)]))}async function cg(n,e,t,i={}){if(n.length!==ar)throw De("internal","recovery secret is 32 bytes");_a(e);let o=i.entropy??ag,s=i.kdf??{...lD,salt:o(16)},r=i.nonce??o(24);if(r.length!==24)throw De("internal","nonce is 24 bytes");let a=fu(n),c=await i2(e,s,i.argon2id??lg,i.signal);try{let l=pA(c,r,r2(t,a,s)).encrypt(n);return{kdf:s,nonce:r,ct:l,keyId:a}}finally{wt(c)}}async function o2(n,e,t,i={}){let o=await i2(e,n.kdf,i.argon2id??lg,i.signal),s;try{s=pA(o,n.nonce,r2(t,n.keyId,n.kdf)).decrypt(n.ct)}catch{throw De("wrong_secret","Wrong password.")}finally{wt(o)}if(s.length!==ar||!g0(fu(s),n.keyId))throw wt(s),De("wrong_secret","Wrong password.");return s}function hu(n,e){if(n.length!==ar||!g0(fu(n),e.keyId))throw De("wrong_secret","This recovery key belongs to a different account key.")}var Ve,De,wc,ag,iD,h0,m0,ar,VE,oD,b0,ZE,aD,vc,du,lD,cD,QE,pD,dD,uD,wa,lg,pg=C(()=>{"use strict";dA();qy();$E();BE();gr();Je();Ve=class extends Error{code;reason;retryAfterMs;constructor(e,t,i={}){super(t),this.name="AccountKeyError",this.code=e,i.reason!==void 0&&(this.reason=i.reason),i.retryAfterMs!==void 0&&(this.retryAfterMs=i.retryAfterMs)}},De=(n,e,t)=>new Ve(n,e,t===void 0?{}:{reason:t}),wc=new TextEncoder;ag=n=>crypto.getRandomValues(new Uint8Array(n)),iD=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;h0="0123456789ABCDEFGHJKMNPQRSTVWXYZ",m0="MDB1",ar=32,VE=2,oD=55;b0=1,ZE=1,aD=512,vc=12,du=1024,lD={mKib:19456,t:3,p:1},cD=19456,QE=24576,pD=2,dD=10,uD=4;wa=n=>typeof n=="number"&&Number.isSafeInteger(n)&&n>=0;lg=async(n,e,t,i)=>{let o=()=>De("cancelled","Key derivation cancelled.");if(i?.aborted)throw o();try{return await zE(n,e,{t:t.t,m:t.mKib,p:t.p,dkLen:32,version:19,maxmem:QE*1024+(1<<20),asyncTick:20,onProgress:()=>{if(i?.aborted)throw o()}})}catch(s){throw s instanceof Ve?s:De("params","Key derivation failed.")}}});function s2(n){if(n.length<3)return!1;let e=[...n].reverse().join("");return[l2,...yD].some(t=>t.includes(n)||t.includes(e))}function gD(n){for(let e=1;e<=n.length/2;e++)if(n.length%e===0&&n.slice(0,e).repeat(n.length/e)===n)return n.slice(0,e);return null}function bD(n){let e=[];for(let t of n){let i=/\p{L}/u.test(t)?"letter":/\p{Nd}/u.test(t)?"digit":t.charCodeAt(0)<128?"symbol":"other",o=e[e.length-1];o&&o.kind===i?o.text+=t:e.push({kind:i,text:t})}return e}function c2(n,e,t,i){let o=e.toLowerCase();if(t.has(o))return i.add("repeat"),1;t.add(o);let s=gD(o);if(s&&s.length<o.length)return i.add("repeat"),c2(n,s,new Set,i)+lr(o.length/s.length);if(n==="letter"){let r=[...o].map(c=>a2[c]??c).join("");if(mu.has(o)||mu.has(r))return i.add("common"),lr(mu.size)+1;if(s2(o))return i.add("sequence"),lr(l2.length)+lr(o.length)+1;let a=2.5*[...o].length;return o!==e&&e.toUpperCase()!==e?a+=1+lr([...e].length):e.toUpperCase()===e&&e.length>1&&(a+=1),a}return n==="digit"?mD.has(o)||s2(o)?(i.add("sequence"),4):/^(19|20)\d\d$/.test(o)||/^\d{6}$/.test(o)||/^\d{8}$/.test(o)?(i.add("date"),6):3.32*o.length:n==="symbol"?[...e].reduce((r,a)=>r+(a===" "?1:"!?.,*#-_".includes(a)?2:5),0):7*[...e].length}function wD(n){let e=[...n],t=e.map(r=>a2[r.toLowerCase()]??r.toLowerCase()),i=[],o="",s=0;for(;s<e.length;){let r=null;for(let a=Math.min(24,e.length-s);a>=4;a--){let c=t.slice(s,s+a).join("");if(mu.has(c)){r=c;break}}r?(o&&i.push({word:null,text:o}),o="",i.push({word:r,text:e.slice(s,s+[...r].length).join("")}),s+=[...r].length):(o+=e[s],s++)}return o&&i.push({word:null,text:o}),i}function yu(n){typeof n!="string"&&(n="");let e=new TextEncoder().encode(n).length,t=n.normalize("NFKC"),i=[...t].length,o=new TextEncoder().encode(t).length,s=new Set,r=new Set,a=0,c=0,l=new Set;for(let h of wD(t)){if(h.word){s.add("common"),c++,l.add("word");let m=h.text.toLowerCase();a+=r.has(h.word)?1:lr(mu.size)+1+(m!==h.text?1:0)+(m!==h.word?1:0),r.add(h.word);continue}for(let m of bD(h.text))c++,l.add(m.kind),a+=c2(m.kind,m.text,r,s)}a+=Math.max(0,l.size-1)+lr(Math.max(1,c));let p=a<lr(1e3)?0:a<lr(1e6)?1:a<lr(1e8)?2:a<lr(1e10)?3:4,d=[],u=e>du||o>du;i<vc&&d.push(`Use at least ${vc} characters.`),u&&d.push("The password is too long."),s.has("common")&&d.push("Avoid common words and passwords."),s.has("sequence")&&d.push("Avoid sequences like abcd, 1234 or qwerty."),s.has("repeat")&&d.push("Avoid repeated characters or words."),s.has("date")&&d.push("Avoid years and dates."),p<3&&d.length===0&&d.push("Add another word or two; uncommon words are best.");let f=p>=3&&i>=vc&&!u;return{score:p,acceptable:f,feedback:f?[]:d,bits:Math.round(a*10)/10}}var mu,mD,a2,l2,yD,lr,p2=C(()=>{"use strict";pg();mu=new Set(["password","passwort","passw0rd","letmein","welcome","admin","administrator","login","master","monkey","dragon","football","baseball","soccer","hockey","qwerty","qwertyuiop","asdfgh","asdfghjkl","zxcvbn","zxcvbnm","azerty","iloveyou","sunshine","princess","shadow","superman","batman","michael","jennifer","jessica","charlie","thomas","trustno1","abc","abcd","abcdef","abcdefg","abcdefgh","secret","freedom","whatever","starwars","pokemon","computer","internet","hello","mustang","ginger","cheese","summer","winter","spring","autumn","flower","killer","hunter","ranger","buster","soccer","tigger","pepper","jordan","harley","robert","matthew","daniel","andrew","joshua","ashley","nicole","chelsea","amanda","orange","purple","yellow","silver","golden","cookie","chocolate","mdbase","task","note","notes","obsidian","recovery","private","encryption","unlock","account","default","changeme","temp","test","testing","guest","root","user","system","server","database","oracle","google","apple","facebook","twitter","github","linkedin","amazon","netflix","spotify","windows","android","iphone","samsung","nokia","sony","january","february","march","april","june","july","august","september","october","november","december","monday","tuesday","wednesday","thursday","friday","saturday","sunday","spider","lovely","liverpool","arsenal","chelsea","manchester","barcelona","madrid","america","london","paris","berlin","sydney","melbourne","canada"]),mD=new Set(["123","1234","12345","123456","1234567","12345678","123456789","1234567890","111111","000000","123123","654321","696969","112233","121212","131313","007","666","777","888","999","420","69"]),a2={0:"o",1:"i",3:"e",4:"a",5:"s",7:"t",8:"b","@":"a",$:"s","!":"i","+":"t"},l2="abcdefghijklmnopqrstuvwxyz0123456789",yD=["qwertyuiop","asdfghjkl","zxcvbnm","1234567890"],lr=n=>Math.log2(Math.max(1,n))});function u2(){let n=null;return{get:async()=>n?n.slice():null,set:async e=>{n&&wt(n),n=e.slice()},clear:async()=>{n&&wt(n),n=null}}}function Aa(n){if(!n||typeof n!="object"||Array.isArray(n))throw cn("not_object");return n}function d2(n){if(typeof n.complete!="boolean"||!Array.isArray(n.pending)||n.pending.length>1024)throw cn("strict_completion");let e=new Set,t=n.pending.map(i=>{let o=Aa(i);if(typeof o.collection_id!="string"||typeof o.device_id!="string"||o.revoked_at!==null&&(!Number.isSafeInteger(o.revoked_at)||o.revoked_at<0))throw cn("strict_pending");Xn(o.collection_id),Xn(o.device_id);let s=`${o.collection_id.toLowerCase()}/${o.device_id.toLowerCase()}`;if(e.has(s))throw cn("strict_pending");return e.add(s),{collectionId:o.collection_id,deviceId:o.device_id,revokedAt:o.revoked_at}});if(n.complete&&t.length!==0)throw cn("strict_completion");return{complete:n.complete,pending:t}}function go(n){if(n instanceof Ve)return n;let e=n&&typeof n=="object"?n:{},t=e.problem&&typeof e.problem=="object"?e.problem:{},i=typeof t.code=="string"?t.code:typeof e.code=="string"?e.code:"",o=typeof e.status=="number"?e.status:void 0,s=e.retryAfterMs??t.retryAfterMs??(typeof e.retry_after=="number"?e.retry_after*1e3:void 0),r=typeof s=="number"&&Number.isFinite(s)&&s>=0?s:void 0;return i==="rate_limited"||o===429?new Ve("rate_limited","Too many account key requests; try again later.",r===void 0?{}:{retryAfterMs:r}):i==="version_conflict"||i==="rotate_requires_strict"?new Ve("conflict","The account key changed; fetch the current state and retry.",{reason:i}):i==="strict_mode"?new Ve("strict_mode","The account is in strict mode."):i==="account_key_proof_required"?new Ve("wrong_secret","The account key held here is not the one registered for this bundle.",{reason:i}):i==="no_account_key"?new Ve("no_account_key","The account has no account key."):i==="cancelled"||e.name==="AbortError"?new Ve("cancelled","Account key request cancelled."):_D(i||(o===void 0?"port_failure":`http_${o}`),r)}var v0,vD,cn,_D,dg,ug,f2=C(()=>{"use strict";pg();Je();p2();v0=/^[0-9a-f]{64}$/,vD=/^([0-9a-f]{2}){1,512}$/,cn=n=>new Ve("internal","Invalid control-plane account-key response.",{reason:n}),_D=(n,e)=>new Ve("unavailable","The account key service refused or was unreachable.",e===void 0?{reason:n}:{reason:n,retryAfterMs:e});dg=n=>{if(!Number.isSafeInteger(n)||n<0)throw cn("version");return n};ug=class{lifetime=new AbortController;control;replica;secrets;argon2id;entropy;busy=Promise.resolve();last=null;constructor(e){if(this.control=e.control,this.replica=e.replica,!e.secrets)throw new Ve("internal","PrivateAccount needs a secret store (the platform keychain).");this.secrets=e.secrets,this.argon2id=e.argon2id??lg,this.entropy=e.entropy??ag,Xn(this.control.accountId)}close(){this.lifetime.signal.aborted||(this.lifetime.abort(),this.control.close?.())}passwordStrength(e){return yu(e)}async status(e={}){return this.serial(e,t=>this.readStatus(t))}get lastStatus(){return this.last}async setup(e,t){return this.serial({signal:t},async i=>{let o=yu(e);if(_a(e),!o.acceptable)throw new Ve("weak_password","The password is too weak.",{reason:"strength"});let s=await this.fetchState(i);if(s.mode==="password")throw new Ve("already_set_up","This account already has an account key; unlock it instead.");let r=FE(this.entropy);try{let a=await cg(r,e,this.control.accountId,{entropy:this.entropy,argon2id:this.argon2id,signal:i});this.check(i),await this.putBundle(r,s.version,a,i),await this.secrets.set(r);let c=WE(r),l=await this.keyAll(r,i);return l.length?{recoveryKey:c,incomplete:l}:{recoveryKey:c}}finally{wt(r)}})}async unlock(e,t){return this.serial({signal:t},async i=>{let o="recoveryKey"in e?uu(e.recoveryKey):null;try{let s=await this.requirePassword(i);o?hu(o,s.bundle):o=await o2(s.bundle,e.password,this.control.accountId,{argon2id:this.argon2id,signal:i}),this.check(i),await this.secrets.set(o);let r=await this.grantAll(o,i);return r.length?{incomplete:r}:{}}finally{o&&wt(o)}})}async changePassword(e,t){return this.serial({signal:t},async i=>{let o=yu(e);if(_a(e),!o.acceptable)throw new Ve("weak_password","The password is too weak.",{reason:"strength"});let s=await this.secrets.get();if(!s)throw new Ve("locked","Unlock the account key on this device first.");try{let r=await this.requirePassword(i);try{hu(s,r.bundle)}catch{throw new Ve("conflict","The account key on the server is not the one unlocked here; unlock again.",{reason:"key_id_changed"})}let a=await cg(s,e,this.control.accountId,{entropy:this.entropy,argon2id:this.argon2id,signal:i});this.check(i),await this.putBundle(s,r.version,a,i)}finally{wt(s)}})}async recover(e,t,i){return this.serial({signal:i},async o=>{let s=yu(t);if(_a(t),!s.acceptable)throw new Ve("weak_password","The password is too weak.",{reason:"strength"});let r=uu(e);try{let a=await this.requirePassword(o);hu(r,a.bundle);let c=await cg(r,t,this.control.accountId,{entropy:this.entropy,argon2id:this.argon2id,signal:o});this.check(o),await this.putBundle(r,a.version,c,o),await this.secrets.set(r);let l=await this.grantAll(r,o);return l.length?{incomplete:l}:{}}finally{wt(r)}})}async enableStrict(e){return this.serial({signal:e},async t=>{let i=await this.readStatus(t);if(i.mode==="strict"){i.strictComplete===!0&&await this.secrets.clear();let p=i.strictComplete===!0?!1:i.accountKeyKept;return this.last={...i,accountKeyKept:p},{version:i.version,complete:i.strictComplete,pending:i.pending,accountKeyKept:p,revocations:[],alreadyStrict:!0}}let o;try{o=await this.control.strict({expected_version:i.version},{signal:t})}catch(p){throw go(p)}let s=Aa(o);if(s.mode!=="strict"||dg(s.version)!==i.version+1||!Array.isArray(s.revocations))throw cn("strict");let r=d2(s),a=s.revocations.map(p=>{let d=Aa(p);if(typeof d.collection_id!="string"||typeof d.device_id!="string")throw cn("strict");return Xn(d.collection_id),Xn(d.device_id),{collectionId:d.collection_id,deviceId:d.device_id}});r.complete===!0&&await this.secrets.clear();let c=await this.secrets.get(),l=c!==null;return c&&wt(c),this.last={mode:"strict",version:s.version,unlocked:!1,strictComplete:r.complete,pending:r.pending,accountKeyKept:l},{version:s.version,...r,accountKeyKept:l,revocations:a,alreadyStrict:!1}})}async keyCollections(e){return this.serial({signal:e},async t=>{let i=await this.secrets.get();if(!i)throw new Ve("locked","Unlock the account key on this device first.");try{let o=await this.requirePassword(t);return hu(i,o.bundle),await this.keyAll(i,t)}finally{wt(i)}})}async lock(){await this.secrets.clear()}serial(e,t){let i=e.signal?AbortSignal.any([this.lifetime.signal,e.signal]):this.lifetime.signal,o=this.busy.then(()=>(this.check(i),t(i)),()=>(this.check(i),t(i)));return this.busy=o.catch(()=>{}),o}check(e){if(e.aborted)throw new Ve("cancelled","Account key request cancelled.")}async readStatus(e){let t;try{t=await this.control.status({signal:e})}catch(l){throw go(l)}this.check(e);let i=Aa(t),o=dg(i.version),s,r=null;if(i.mode==="none"&&o===0)s="none";else if(i.mode==="strict")s="strict";else if(i.mode==="password"&&typeof i.key_id=="string"&&v0.test(i.key_id))s="password",r=i.key_id;else throw cn("status");let a=s==="strict"?d2(i):void 0,c=await this.secrets.get();try{let l=r!==null&&c!==null&&c.length===32&&ht(fu(c))===r;return this.last={mode:s,unlocked:l,version:o,...a?{strictComplete:a.complete,pending:a.pending,accountKeyKept:c!==null}:{}}}finally{c&&wt(c)}}async fetchState(e){let t;try{t=await this.control.fetch({signal:e})}catch(r){throw go(r)}this.check(e);let i=Aa(t),o=dg(i.version);if(i.mode==="none"){if(o!==0)throw cn("mode");return{mode:"none",version:0}}if(i.mode==="strict")return{mode:"strict",version:o};if(i.mode!=="password")throw cn("mode");if(typeof i.key_id!="string"||!v0.test(i.key_id)||typeof i.bundle!="string"||!vD.test(i.bundle))throw cn("bundle");let s=t2(Wr(i.bundle));if(ht(s.keyId)!==i.key_id)throw cn("key_id");return{mode:"password",version:o,bundle:s}}async requirePassword(e){let t=await this.fetchState(e);if(t.mode==="none")throw new Ve("no_account_key","The account has no account key yet; set one up on a device that holds the keys.");if(t.mode==="strict")throw new Ve("strict_mode","The account is in strict mode; approve this device from an existing device.");return t}async putBundle(e,t,i,o){let s=ht(i.keyId),r=w0(i),a=JE(e,this.control.accountId),c;try{let p=ht(XE(a,this.control.accountId,r,t));c=await this.control.put({expected_version:t,key_id:s,bundle:ht(r),proof_pk:ht(a.pk),proof_sig:p},{signal:o})}catch(p){throw go(p)}finally{wt(a.seed)}let l=Aa(c);if(l.mode!=="password"||dg(l.version)!==t+1||l.key_id!==s)throw cn("put")}async collections(e){let t;try{t=await this.replica.privateCollections({signal:e})}catch(i){throw go(i)}if(this.check(e),!Array.isArray(t)||t.some(i=>typeof i!="string")||new Set(t).size!==t.length)throw cn("collections");for(let i of t)Xn(i);return t}async keyAll(e,t){let i=[];for(let o of await this.collections(t)){this.check(t);try{await this.enrol(e,o,t),await this.replica.keyAccountKeyDevice(o,e,{signal:t})}catch(s){if(s instanceof Ve&&s.code==="cancelled")throw s;i.push(o)}}return i}async grantAll(e,t){let i=[];for(let o of await this.collections(t)){this.check(t);try{await this.replica.selfGrantWithAccountKey(o,e,{signal:t})}catch(s){if(s instanceof Ve&&s.code==="cancelled")throw s;i.push(o)}}return i}async enrol(e,t,i){let o;try{o=await this.control.challenge({signal:i})}catch(a){throw go(a)}let s=typeof o=="string"?o.toLowerCase():typeof o?.challenge=="string"?o.challenge.toLowerCase():"";if(!v0.test(s))throw cn("challenge");this.check(i);let r=HE(e,t);try{let a=va("mdbase/v1/account-key-enrol",fe([Wr(s),Xn(t),Xn(r.device),Xn(this.control.accountId),r.signPk,r.kemPk,r.noisePk])),c=ht(GE(r,a)),l;try{l=await this.control.enrolRecoveryDevice(t,{challenge:s,recovery_device:r.device,sign_pk:ht(r.signPk),kem_pk:ht(r.kemPk),pop:c},{signal:i})}catch(d){throw go(d)}let p=Aa(l);if(p.collection_id!==t||p.device_id!==r.device||!Number.isSafeInteger(p.enrolled_at))throw cn("enrol")}finally{YE(r)}}}});function _0(n){if(n instanceof pt)return n;if(n instanceof Lt)return new pt("unlock_strict");if(n instanceof as)return new pt("unlock_unavailable");if(!(n instanceof Ve))return null;switch(n.code){case"wrong_secret":return new pt("wrong_secret");case"invalid_recovery_key":return new pt("invalid_recovery_key",n.reason);case"no_account_key":return new pt("no_account_key");case"strict_mode":return new pt("unlock_strict");case"rate_limited":return new pt("rate_limited",void 0,n.retryAfterMs);case"cancelled":return null;default:return n.reason==="account_key_proof_unavailable"?new pt("unlock_unavailable"):new pt("unavailable",n.reason??n.code,n.retryAfterMs)}}async function xD(n,e){return(await m2(n,e)).mode}async function m2(n,e){let t;try{t=await n.status({signal:e})}catch(s){throw go(s)}if(e.aborted)throw A0();let i=t&&typeof t=="object"&&!Array.isArray(t)?t:{},o=i.mode;if(o!=="password"&&o!=="strict"&&o!=="none")throw It("response");return{mode:o,version:Number.isSafeInteger(i.version)&&i.version>=1?i.version:null,keyId:typeof i.key_id=="string"&&h2.test(i.key_id)?i.key_id:null}}async function hg(n,e){let t=new Ac(n,()=>{throw It("proof")},e);try{return await xD(t,e.signal)}catch(i){throw e.signal.aborted?i:_0(i)??i}finally{t.close()}}async function mg(n,e,t,i){let o=i.signal,s=i.settleMs??SD,r=i.sealed,a="password"in t,c="recoveryKey"in t;if(a===c||typeof(a?t.password:t.recoveryKey)!="string"||!Number.isSafeInteger(s)||s<1)throw new pt("unavailable","binding");let l=()=>{if(o.aborted)throw A0();if(n.isCurrent()!==!0)throw It("fenced")};if(l(),e.status().state==="keyed"){r?.clear();return}if(c)try{wt(uu(t.recoveryKey))}catch(g){throw _0(g)??g}else try{_a(t.password)}catch{throw new pt("wrong_secret")}let p,d=null,u={privateCollections:async()=>[n.collection],keyAccountKeyDevice:()=>Promise.reject(fg()),async selfGrantWithAccountKey(g,y,v){let _=v.signal??o;try{if(l(),g!==n.collection||!(y instanceof Uint8Array)||y.length!==32)throw It("binding");let k=new Uint8Array(y),S;try{S=e.unlockConsuming(k)}finally{k.fill(0)}let x=Date.now()+s,P=100;for(;S.state==="pending";){if(Date.now()>=x)throw p="grant_pending",It("grant_pending");if(await e.drive({signal:_}),l(),S=e.status(),S.state!=="pending")break;await ya(P,_),l(),P=Math.min(1e3,P*2)}if(S.state==="refused")throw p=S.reason,It(S.reason)}catch(k){throw p===void 0&&(d={error:k}),k}}},f=new Ac(n,g=>e.signFetch(g),i),h=null,m=r?{accountId:f.accountId,status:g=>f.status(g),challenge:g=>f.challenge(g),async fetch(g){let y=r.take(n,h?.version??null,h?.keyId??null);if(y)return y;let v=await f.fetch(g);return r.keep(n,v),v},put:()=>f.put(),strict:()=>f.strict(),enrolRecoveryDevice:()=>f.enrolRecoveryDevice(),close:()=>f.close()}:f,w=u2(),b=new ug({control:m,replica:u,secrets:w,...i.argon2id?{argon2id:i.argon2id}:{}});try{h=await m2(f,o),l();let g=h.mode;try{i.onMode?.(g)}catch{}if(g==="none")throw new pt("no_account_key");if(g==="strict")throw new pt("unlock_strict");if(!e.supportsFetchProof())throw new pt("unlock_unavailable");if(e.headKnown()<=0&&(await e.drive({signal:o}),l()),e.headKnown()<=0)throw new pt("unavailable","log_head_unknown");let y=await b.unlock(t,o),v=d;if(v)throw v.error;if(l(),y.incomplete?.length)throw new pt(p==="grant_pending"?"unavailable":"unlock_failed",p??"incomplete");if(e.status().state!=="keyed")throw new pt("unlock_failed","not_keyed");r?.clear()}catch(g){throw(!(g instanceof Ve&&g.code==="wrong_secret")||o.aborted||n.isCurrent()!==!0)&&r?.clear(),o.aborted||n.isCurrent()!==!0?g:_0(g)??g}finally{try{await w.clear()}finally{b.close()}}}var pt,_c,AD,kD,SD,It,A0,fg,PD,h2,Ac,gu=C(()=>{"use strict";St();pg();ve();f2();ri();Wy();ry();pt=class extends Error{constructor(t,i,o){super(`app account key unlock: ${t}`);this.reason=t;this.detail=i;this.retryAfterMs=o;this.name="AppAccountKeyUnlockError"}reason;detail;retryAfterMs},_c=class{held=null;get holding(){return this.held!==null}take(e,t,i){let o=this.held;return o&&t!==null&&i!==null&&o.accountId===e.accountId&&o.connectorId===e.connectorId&&o.deviceId===e.deviceId&&o.version===t&&o.keyId===i?{mode:"password",version:o.version,key_id:o.keyId,bundle:o.bundle}:(this.held=null,null)}keep(e,t){this.held=null;let i=t&&typeof t=="object"&&!Array.isArray(t)?t:{};i.mode!=="password"||!Number.isSafeInteger(i.version)||i.version<1||typeof i.key_id!="string"||!h2.test(i.key_id)||typeof i.bundle!="string"||!/^([0-9a-f]{2}){1,512}$/.test(i.bundle)||(this.held=Object.freeze({accountId:e.accountId,connectorId:e.connectorId,deviceId:e.deviceId,version:i.version,keyId:i.key_id,bundle:i.bundle}))}clear(){this.held=null}},AD=64*1024,kD=15e3,SD=45e3,It=n=>new Ve("unavailable","The account key service refused or was unreachable.",{reason:n}),A0=()=>new Ve("cancelled","Account key request cancelled."),fg=()=>It("not_supported"),PD=n=>Array.from(n,e=>e.toString(16).padStart(2,"0")).join(""),h2=/^[0-9a-f]{64}$/,Ac=class{constructor(e,t,i={}){this.session=e;this.sign=t;for(let s of[e.accountId,e.connectorId,e.deviceId,e.collection])if(N(s).every(r=>r===0))throw It("binding");let o=new URL(e.cpOrigin);if(o.origin!==e.cpOrigin||o.username||o.password||o.protocol!=="https:"&&!(i.allowLoopbackHttp===!0&&Qe(e.cpOrigin)))throw It("binding");if(this.accountId=e.accountId,this.deviceId=e.deviceId,this.origin=o.origin,this.fetchImpl=i.fetch??globalThis.fetch,this.now=i.now??Date.now,e.isCurrent()!==!0)throw It("fenced")}session;sign;accountId;lifetime=new AbortController;origin;deviceId;fetchImpl;now;check(e){if(e.aborted||this.lifetime.signal.aborted)throw A0();let t=!1;try{t=this.session.isCurrent()===!0&&this.session.accountId===this.accountId&&this.session.deviceId===this.deviceId&&this.session.cpOrigin===this.origin}catch{t=!1}if(!t)throw It("fenced")}async request(e,t,i,o){let s=o.signal??this.lifetime.signal;this.check(s);let r=await this.session.connectorBearer({signal:s});if(this.check(s),typeof r!="string"||!r||r.length>16384||/[^\x21-\x7e]/.test(r))throw It("binding");let a=new AbortController,c=()=>a.abort(),l=setTimeout(c,kD);l.unref?.(),s.addEventListener("abort",c,{once:!0}),this.lifetime.signal.addEventListener("abort",c,{once:!0});let p=new Uint8Array(AD),d=0,u=null,f=null;try{let h=this.fetchImpl;try{u=await h(`${this.origin}${t}`,{method:e,headers:{authorization:`Bearer ${r}`,...i},signal:a.signal,redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer"})}catch{throw this.check(s),It("network")}if(this.check(s),a.signal.aborted)throw It("timeout");if(u.body)for(f=u.body.getReader();;){let w;try{w=await f.read()}catch{throw this.check(s),It("network")}try{if(this.check(s),a.signal.aborted)throw It("timeout");if(w.done)break;if(d+w.value.length>p.length)throw a.abort(),It("response");p.set(w.value,d),d+=w.value.length}finally{w.value?.fill(0)}}let m=$o(p.subarray(0,d));if(!u.ok)throw vi(u.status,m,u.headers);if(!m||typeof m!="object"||Array.isArray(m))throw It("response");return m}finally{p.fill(0),(f?.cancel()??u?.body?.cancel())?.catch(()=>{});try{f?.releaseLock()}catch{}clearTimeout(l),s.removeEventListener("abort",c),this.lifetime.signal.removeEventListener("abort",c)}}status(e){return this.request("GET","/v1/next/account-key/status",{},e)}challenge(e){return this.request("POST","/v1/next/devices/challenge",{},e)}async fetch(e){let t=null,i=null;try{let o=await this.request("POST","/v1/next/devices/challenge",{},e),s=o.challenge,r=o.expires_at;if(typeof s!="string"||!/^[0-9a-f]{64}$/.test(s)||typeof r!="number"||!Number.isSafeInteger(r)||r-this.now()<=5e3||r-this.now()>16*6e4)throw It("response");t=Uint8Array.from(s.match(/../g).map(a=>parseInt(a,16)));try{i=this.sign(t)}catch(a){throw a instanceof as?It(a.reason):a instanceof Lt?new Ve("strict_mode","The account is in strict mode."):It("proof")}if(!(i instanceof Uint8Array)||i.length!==64)throw It("proof");return await this.request("GET","/v1/next/account-key",{"x-mdbase-device-id":this.deviceId,"x-mdbase-challenge":s,"x-mdbase-signature":PD(i)},e)}finally{t?.fill(0),i?.fill(0)}}put(){return Promise.reject(fg())}strict(){return Promise.reject(fg())}enrolRecoveryDevice(){return Promise.reject(fg())}close(){this.lifetime.abort()}}});var ji,kc=C(()=>{"use strict";ji=class extends Error{reason="device_keys_unavailable";constructor(e){super(e),this.name="AppDeviceCustodyError"}}});function gg(n){if(typeof globalThis.CryptoKey!="function"||!(n instanceof CryptoKey)||n.type!=="secret"||n.extractable||n.algorithm.name!=="AES-GCM"||n.algorithm.length!==256||n.usages.length!==2||!n.usages.includes("encrypt")||!n.usages.includes("decrypt"))throw Ut();return n}function ID(n){if(n===void 0)return null;if(!n||typeof n!="object"||Array.isArray(n)||Object.keys(n).length!==2||!Object.hasOwn(n,"version")||!Object.hasOwn(n,"key")||n.version!==1)throw Ut();return gg(n.key)}var yg,y2,Ut,Sc,k0=C(()=>{"use strict";Jt();ve();kc();yg="device-key-kek",y2="original-device-kek",Ut=()=>new ji("app device key provider unavailable; preserve storage and reopen");Sc=class n{constructor(e,t,i){this.source=e;this.origin=t;this.lifetime=i;this.scope=Object.freeze({accountId:e.accountId,connectorId:e.connectorId,deviceId:e.deviceId,installationId:e.installationId}),this.current=e.isCurrent,this.owned=e.installationOwned}source;origin;lifetime;db=null;value=null;closed=!1;loaned=!1;scope;current;owned;static async open(e){let t=null;try{let{source:i,origin:o,mode:s,signal:r}=e;t=new n(i,o,r);let a=Object.values(t.scope).map(u=>{let f=N(u);if(f.every(h=>h===0))throw Ut();return Array.from(f,h=>h.toString(16).padStart(2,"0")).join("")});if(!ut(o)||!["fresh","existing"].includes(s)||!globalThis.indexedDB||!globalThis.crypto?.subtle||typeof globalThis.CryptoKey!="function")throw Ut();t.check(r);let c=crypto.subtle.generateKey.bind(crypto.subtle),l=`mdbase.app.device-key-kek.v1.${a.join(".")}`,p=await t.openDatabase(l,s);t.db=p,p.onversionchange=()=>t.close(),t.check(r);let d=await t.transaction("readonly",r,null);if(t.check(r),s==="existing"){if(d===null||typeof d=="boolean")throw Ut();t.value=d}else{if(d!==null)throw Ut();let u=gg(await c({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]));if(t.check(r),await t.transaction("readwrite",r,u)!==!0)throw Ut();t.check(r),t.value=u}return t.check(r),t}catch{throw t?.close(),Ut()}}check(e){try{if(this.closed||this.lifetime.aborted||e.aborted||Et()!==this.origin||this.source.isCurrent!==this.current||this.source.installationOwned!==this.owned||this.current.call(this.source)!==!0||this.owned.call(this.source)!==!0||Object.entries(this.scope).some(([t,i])=>this.source[t]!==i))throw Ut()}catch{throw Ut()}}openDatabase(e,t){return new Promise((i,o)=>{this.check(this.lifetime);let s=indexedDB.open(e,1),r=!1,a=!1,c=()=>{r=!0,o(Ut())};this.lifetime.addEventListener("abort",c,{once:!0});let l=()=>this.lifetime.removeEventListener("abort",c);s.onblocked=c,s.onupgradeneeded=()=>{try{if(this.check(this.lifetime),r||t!=="fresh"||s.result.objectStoreNames.length!==0)throw Ut();s.result.createObjectStore(yg),a=!0}catch{s.transaction?.abort()}},s.onerror=()=>{l(),o(Ut())},s.onsuccess=()=>{l();try{if(this.check(this.lifetime),r||t==="fresh"&&!a||s.result.objectStoreNames.length!==1||!s.result.objectStoreNames.contains(yg))throw Ut();i(s.result)}catch{s.result.close(),o(Ut())}}})}transaction(e,t,i){return new Promise((o,s)=>{if(this.check(t),!this.db)throw Ut();let r=this.db.transaction(yg,e,{durability:"strict"}),a=r.objectStore(yg),c=null,l=!1,p=()=>{l=!0;try{r.abort()}catch{}};t.addEventListener("abort",p,{once:!0}),this.lifetime.addEventListener("abort",p,{once:!0});let d=()=>{t.removeEventListener("abort",p),this.lifetime.removeEventListener("abort",p)};r.onerror=r.onabort=()=>{d(),c=null,s(Ut())},r.oncomplete=()=>{d();try{if(this.check(t),l)throw Ut();o(c)}catch{c=null,s(Ut())}};let u=a.get(y2);u.onsuccess=()=>{try{this.check(t);let f=ID(u.result);e==="readonly"?c=f:(c=f===null,c===!0&&i!==null&&a.add({version:1,key:gg(i)},y2))}catch{p()}}})}deviceCustodyKek(e){if(this.check(e.signal),this.loaned||!this.value)throw Ut();return this.loaned=!0,gg(this.value)}close(){this.closed||(this.closed=!0,this.value=null,this.db?.close(),this.db=null)}}});function b2(n){if(!(n instanceof Uint8Array)||!n.length||n.length>CD)throw jn();return new Uint8Array(n)}var bg,g2,CD,jn,Pc,S0=C(()=>{"use strict";Jt();ve();kc();bg="original-device-keys",g2="custody",CD=256,jn=()=>new ji("app device key custody store unavailable");Pc=class n{constructor(e,t,i,o,s){this.db=e;this.source=t;this.scope=i;this.namespace=o;this.origin=s;this.current=t.isCurrent,this.owned=t.installationOwned,e.onversionchange=()=>this.close()}db;source;scope;namespace;origin;closed=!1;current;owned;static async open(e){try{return await this.openChecked(e)}catch{throw jn()}}static async openChecked(e){let{source:t,signal:i,mode:o,origin:s}=e,r=Object.freeze({accountId:t.accountId,connectorId:t.connectorId,deviceId:t.deviceId,installationId:t.installationId}),a=t.isCurrent,c=t.installationOwned,l=()=>{try{return!i.aborted&&t.isCurrent===a&&t.installationOwned===c&&a.call(t)===!0&&c.call(t)===!0&&Object.keys(r).every(m=>t[m]===r[m])}catch{return!1}},p=[r.accountId,r.connectorId,r.deviceId,r.installationId].map(m=>{let w=N(m);if(w.every(b=>b===0))throw jn();return Array.from(w,b=>b.toString(16).padStart(2,"0")).join("")});if(!ut(s)||Et()!==s||!["fresh","existing"].includes(o)||!l()||!globalThis.indexedDB)throw jn();let d=`mdbase.app-device-keys.v1:${p.join(":")}`,u=`mdbase.app.device-keys.v1.${p.join(".")}`,f=await new Promise((m,w)=>{let b=indexedDB.open(u,1),g=!1,y=()=>{g=!0,w(jn())};i.addEventListener("abort",y,{once:!0});let v=()=>i.removeEventListener("abort",y);b.onblocked=y,b.onupgradeneeded=()=>{if(g||o!=="fresh"||!l()||b.result.objectStoreNames.length!==0){b.transaction?.abort();return}b.result.createObjectStore(bg)},b.onerror=()=>{v(),w(jn())},b.onsuccess=()=>{if(v(),g||!l()||b.result.objectStoreNames.length!==1||!b.result.objectStoreNames.contains(bg)){b.result.close(),w(jn());return}m(b.result)}}),h=new n(f,t,r,d,s);try{h.check(i);let m=await h.read(d,{signal:i});try{if(o==="fresh"!=(m===null))throw jn();return h.check(i),h}finally{m?.fill(0)}}catch{throw h.close(),jn()}}check(e,t=this.namespace){try{if(this.closed||e.aborted||t!==this.namespace||Et()!==this.origin||this.source.isCurrent!==this.current||this.source.installationOwned!==this.owned||this.current.call(this.source)!==!0||this.owned.call(this.source)!==!0||Object.keys(this.scope).some(i=>this.source[i]!==this.scope[i]))throw jn()}catch{throw jn()}}async read(e,t){let i=await this.transaction("readonly",e,t.signal,null);try{return this.check(t.signal,e),i}catch{throw i instanceof Uint8Array&&i.fill(0),jn()}}async create(e,t,i){this.check(i.signal,e);let o=b2(t);try{let s=await this.transaction("readwrite",e,i.signal,o);return this.check(i.signal,e),s===!0}finally{o.fill(0)}}transaction(e,t,i,o){return new Promise((s,r)=>{this.check(i,t);let a=this.db.transaction(bg,e,{durability:"strict"}),c=a.objectStore(bg),l=null,p=!1,d=()=>{p=!0;try{a.abort()}catch{}},u=()=>i.removeEventListener("abort",d);i.addEventListener("abort",d,{once:!0}),a.onabort=a.onerror=()=>{u(),l instanceof Uint8Array&&l.fill(0),r(jn())},a.oncomplete=()=>{u();try{if(this.check(i,t),p)throw jn();s(l)}catch{l instanceof Uint8Array&&l.fill(0),r(jn())}};let f=c.get(g2);f.onsuccess=()=>{let h=null;try{this.check(i,t),h=f.result===void 0?null:b2(f.result),e==="readonly"?(l=h,h=null):(l=h===null,l===!0&&o!==null&&c.add(new Uint8Array(o),g2))}catch{d()}finally{h?.fill(0)}}})}close(){this.closed||(this.closed=!0,this.db.close())}}});var _n,xc,P0=C(()=>{"use strict";Je();ve();_n=()=>new Error("app device key custody unavailable; preserve storage and reopen"),xc=class{constructor(e,t,i){this.pin=e;this.key=t;this.store=i;try{this.scope=Object.freeze({accountId:e.accountId,connectorId:e.connectorId,deviceId:e.deviceId,installationId:e.installationId}),this.current=e.isCurrent,this.owned=e.installationOwned;let o=[this.scope.accountId,this.scope.connectorId,this.scope.deviceId,this.scope.installationId].map(N);if(o.some(s=>s.every(r=>r===0))||t.type!=="secret"||t.extractable||t.algorithm.name!=="AES-GCM"||t.algorithm.length!==256||!t.usages.includes("encrypt")||!t.usages.includes("decrypt"))throw _n();this.namespace=`mdbase.app-device-keys.v1:${o.map(s=>Array.from(s,r=>r.toString(16).padStart(2,"0")).join("")).join(":")}`,this.aad=fe(["mdbase/v1/app-device-keys-platform",...o]),this.check(new AbortController().signal)}catch{throw _n()}}pin;key;store;scope;namespace;aad;current;owned;attempted=!1;check(e){try{if(e.aborted||this.pin.isCurrent!==this.current||this.pin.installationOwned!==this.owned||this.current.call(this.pin)!==!0||this.owned.call(this.pin)!==!0||this.pin.accountId!==this.scope.accountId||this.pin.connectorId!==this.scope.connectorId||this.pin.deviceId!==this.scope.deviceId||this.pin.installationId!==this.scope.installationId)throw _n()}catch{throw _n()}}async openNativeDevice(e,t){let i=null,o=null,s=!1;try{if(this.attempted)throw _n();this.attempted=!0;let r=t.signal,a=t.mode;if(this.check(r),!["fresh","existing"].includes(a)||t.noise.mode!==a||t.noise.mode==="existing"&&!(t.noise.envelope instanceof Uint8Array))throw _n();let c=t.noise.mode==="fresh"?{mode:"fresh"}:{mode:"existing",envelope:new Uint8Array(t.noise.envelope)};if(c.mode==="existing"&&(!c.envelope.length||c.envelope.length>1024))throw _n();let l=await this.store.read(this.namespace,{signal:r});if(this.check(r),a==="fresh"){if(l!==null)throw _n();i=globalThis.crypto.getRandomValues(new Uint8Array(64));let u=globalThis.crypto.getRandomValues(new Uint8Array(12)),f=new Uint8Array(await globalThis.crypto.subtle.encrypt({name:"AES-GCM",iv:u,additionalData:new Uint8Array(this.aad),tagLength:128},this.key,i));if(this.check(r),o=fe(new Map([[0,1],[1,u],[2,f]])),await this.store.create(this.namespace,o,{signal:r})!==!0)throw _n();this.check(r)}else{if(!(l instanceof Uint8Array)||l.length===0||l.length>256)throw _n();o=new Uint8Array(l);let u=we(o);if(!(u instanceof Map))throw _n();let f=u;if(f.size!==3||f.get(0)!==1)throw _n();let h=f.get(1),m=f.get(2);if(!(h instanceof Uint8Array)||h.length!==12||!(m instanceof Uint8Array)||m.length!==80||(i=new Uint8Array(await globalThis.crypto.subtle.decrypt({name:"AES-GCM",iv:new Uint8Array(h),additionalData:new Uint8Array(this.aad),tagLength:128},this.key,new Uint8Array(m))),this.check(r),i.length!==64))throw _n()}this.check(r);let p=Object.freeze({connectorId:this.scope.connectorId,deviceId:this.scope.deviceId,installationId:this.scope.installationId,isCurrent:()=>{try{return this.check(r),!0}catch{return!1}}});s=!0;let d=e.openDeviceConsuming({pin:p,signSecretKey:i.subarray(0,32),kemSecretKey:i.subarray(32),opened:c});return this.check(r),d}catch{if(s)try{e.retireLog()}catch{}throw _n()}finally{i?.fill(0),o?.fill(0)}}}});function x0(n){if(!(n instanceof Uint8Array)||n.byteLength<1||n.byteLength>RD)throw Zn();return new Uint8Array(n)}function OD(n,e){return n===null||e===null?n===e:n.length===e.length&&n.every((t,i)=>t===e[i])}function I0(n){if(N(n).every(t=>t===0))throw Zn();return n.toLowerCase()}function C0(n,e){try{return n.isCurrent()===!0&&n.connectorId===e[0]&&n.deviceId===e[1]&&n.installationId===e[2]}catch{return!1}}var wg,w2,RD,Zn,Ic,R0=C(()=>{"use strict";Jt();ve();kc();wg="opaque-noise",w2="custody",RD=4096,Zn=()=>new ji("app noise custody store unavailable");Ic=class n{constructor(e,t,i,o){this.db=e;this.source=t;this.pins=i;this.origin=o;e.onversionchange=()=>this.close()}db;source;pins;origin;closed=!1;static async open(e){try{return await this.openChecked(e)}catch{throw Zn()}}static async openChecked(e){let{source:t,signal:i}=e,o=[t.connectorId,t.deviceId,t.installationId];if(!ut(e.origin)||Et()!==e.origin||!["fresh","existing"].includes(e.mode)||i.aborted||!C0(t,o)||typeof globalThis.indexedDB>"u")throw Zn();let s=`mdbase.app.noise.v1.${I0(o[2])}.${I0(o[0])}.${I0(o[1])}`,r=await new Promise((c,l)=>{let p=indexedDB.open(s,1),d=!1,u=()=>{d=!0,l(Zn())};i.addEventListener("abort",u,{once:!0});let f=()=>i.removeEventListener("abort",u);p.onblocked=u,p.onupgradeneeded=()=>{if(d||i.aborted||e.mode!=="fresh"||!C0(t,o)||p.result.objectStoreNames.length!==0){p.transaction?.abort();return}p.result.createObjectStore(wg)},p.onerror=()=>{f(),l(Zn())},p.onsuccess=()=>{if(f(),d||i.aborted||p.result.objectStoreNames.length!==1||!p.result.objectStoreNames.contains(wg)){p.result.close(),l(Zn());return}c(p.result)}}),a=new n(r,t,o,e.origin);try{let c=await a.read(a.namespace,{signal:i});if(e.mode==="fresh"!=(c===null))throw Zn();return c?.fill(0),a.check(i),a}catch{throw a.close(),Zn()}}get namespace(){return`mdbase.app-noise.v1:${this.pins[0]}:${this.pins[1]}:${this.pins[2]}`}check(e,t=this.namespace){if(this.closed||e.aborted||t!==this.namespace||Et()!==this.origin||!C0(this.source,this.pins))throw Zn()}async read(e,t){this.check(t.signal,e);let i=await this.transaction("readonly",t.signal,null,null);try{return this.check(t.signal),i}catch{throw i instanceof Uint8Array&&i.fill(0),Zn()}}async compareAndSet(e,t,i,o){this.check(o.signal,e);let s=null,r=null;try{s=t===null?null:x0(t),r=x0(i);let a=await this.transaction("readwrite",o.signal,s,r);return this.check(o.signal),a===!0}finally{s?.fill(0),r?.fill(0)}}transaction(e,t,i,o){return new Promise((s,r)=>{this.check(t);let a=this.db.transaction(wg,e,{durability:"strict"}),c=a.objectStore(wg),l=null,p=!1,d=()=>{p=!0;try{a.abort()}catch{}},u=()=>t.removeEventListener("abort",d);t.addEventListener("abort",d,{once:!0}),a.onabort=a.onerror=()=>{u(),l instanceof Uint8Array&&l.fill(0),r(Zn())},a.oncomplete=()=>{u();try{if(this.check(t),p)throw Zn();s(l)}catch{l instanceof Uint8Array&&l.fill(0),r(Zn())}};let f=c.get(w2);f.onsuccess=()=>{let h=null;try{this.check(t),h=f.result===void 0?null:x0(f.result),e==="readonly"?(l=h,h=null):(l=OD(h,i),l===!0&&o!==null&&c.put(new Uint8Array(o),w2))}catch{d()}finally{h?.fill(0)}}})}close(){this.closed||(this.closed=!0,this.db.close())}}});var ze,bu,Cc,O0=C(()=>{"use strict";Je();ve();ze=()=>new Error("app Noise custody unavailable; preserve storage and reopen"),bu=(n,e)=>n.length===e.length&&n.every((t,i)=>t===e[i]),Cc=class{constructor(e,t,i){this.pin=e;this.key=t;this.store=i;try{this.scope=Object.freeze({connectorId:e.connectorId,deviceId:e.deviceId,installationId:e.installationId});let o=[this.scope.connectorId,this.scope.deviceId,this.scope.installationId].map(N);if(o.some(s=>s.every(r=>r===0))||t.type!=="secret"||t.extractable||t.algorithm.name!=="AES-GCM"||t.algorithm.length!==256||!t.usages.includes("encrypt")||!t.usages.includes("decrypt"))throw ze();this.namespace=`mdbase.app-noise.v1:${this.scope.connectorId}:${this.scope.deviceId}:${this.scope.installationId}`,this.aad=fe(["mdbase/v1/app-noise-platform",...o]),this.check(new AbortController().signal)}catch{throw ze()}}pin;key;store;scope;namespace;aad;check(e){try{if(e.aborted||this.pin.isCurrent()!==!0||this.pin.connectorId!==this.scope.connectorId||this.pin.deviceId!==this.scope.deviceId||this.pin.installationId!==this.scope.installationId)throw ze()}catch{throw ze()}}receiptValue(e){if(e.connectorId!==this.scope.connectorId||e.deviceId!==this.scope.deviceId||e.installationId!==this.scope.installationId)throw ze();let t=[e.signPublicKey,e.kemPublicKey,e.noisePublicKey];if(t.some(i=>!(i instanceof Uint8Array)||i.length!==32||i.every(o=>o===0)))throw ze();return t.map(i=>new Uint8Array(i))}receipt(e){if(e===null)return null;if(!Array.isArray(e)||e.length!==3||e.some(t=>!(t instanceof Uint8Array)||t.length!==32||t.every(i=>i===0)))throw ze();return Object.freeze({...this.scope,signPublicKey:new Uint8Array(e[0]),kemPublicKey:new Uint8Array(e[1]),noisePublicKey:new Uint8Array(e[2])})}markerValue(e){let t=N(e.collection);if(t.every(i=>i===0)||typeof e.acknowledged!="boolean"||!(e.sasCommitment instanceof Uint8Array)||e.sasCommitment.length!==32||e.sasCommitment.every(i=>i===0))throw ze();return[t,...this.receiptValue(e),new Uint8Array(e.sasCommitment),e.acknowledged]}marker(e,t){if(e===null)return null;if(!t||!Array.isArray(e)||e.length!==6||!(e[0]instanceof Uint8Array)||e[0].length!==16||e[0].every(r=>r===0)||typeof e[5]!="boolean")throw ze();let i=this.receipt(e.slice(1,4));for(let r of["signPublicKey","kemPublicKey","noisePublicKey"])if(!bu(i[r],t[r]))throw ze();let o=e[4];if(!(o instanceof Uint8Array)||o.length!==32||o.every(r=>r===0))throw ze();let s=Array.from(e[0],r=>r.toString(16).padStart(2,"0")).join("");return Object.freeze({...i,collection:`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`,sasCommitment:new Uint8Array(o),acknowledged:e[5]})}async restore(e){let t=await this.read(e);return this.check(e.signal),t?.value??null}async read(e){let t=null,i=null;try{this.check(e.signal);let o=await this.store.read(this.namespace,e);if(this.check(e.signal),o===null)return null;if(!(o instanceof Uint8Array)||o.length===0||o.length>4096)throw ze();t=new Uint8Array(o);let s=we(t);if(!(s instanceof Map))throw ze();let r=s,a=r.get(1),c=r.get(2);if(r.size!==3||r.get(0)!==1||!(a instanceof Uint8Array)||a.length!==12||!(c instanceof Uint8Array)||c.length<16||c.length>2064||(i=new Uint8Array(await globalThis.crypto.subtle.decrypt({name:"AES-GCM",iv:new Uint8Array(a),additionalData:new Uint8Array(this.aad),tagLength:128},this.key,new Uint8Array(c))),this.check(e.signal),i.length>2048))throw ze();let l=we(i);if(!(l instanceof Map))throw ze();let p=l,d=p.get(1);if(!(p.get(0)===1&&p.size===3||p.get(0)===2&&p.size===4&&p.has(3))||!(d instanceof Uint8Array)||d.length===0||d.length>1024||!p.has(2))throw ze();let u=this.receipt(p.get(2)),f=p.get(0)===2?this.marker(p.get(3),u):null;return{value:Object.freeze({envelope:new Uint8Array(d),receipt:u,privateEnrolMarker:f}),encrypted:new Uint8Array(t)}}catch{throw ze()}finally{t?.fill(0),i?.fill(0)}}async write(e,t,i,o,s=null){let r=null,a=null;try{if(this.check(o.signal),!(e instanceof Uint8Array)||!e.length||e.length>1024)throw ze();let c=new Map([[0,s===null?1:2],[1,new Uint8Array(e)],[2,t===null?null:this.receiptValue(t)]]);if(s!==null){let u=this.markerValue(s);this.marker(u,t),c.set(3,u)}if(r=fe(c),r.length>2048)throw ze();let l=globalThis.crypto.getRandomValues(new Uint8Array(12)),p=new Uint8Array(await globalThis.crypto.subtle.encrypt({name:"AES-GCM",iv:l,additionalData:new Uint8Array(this.aad),tagLength:128},this.key,new Uint8Array(r)));this.check(o.signal),a=fe(new Map([[0,1],[1,l],[2,p]]));let d=await this.store.compareAndSet(this.namespace,i,a,o);if(this.check(o.signal),d!==!0)throw ze()}catch{throw ze()}finally{r?.fill(0),a?.fill(0)}}async pending(e,t){let i=await this.read(t);if(this.check(t.signal),i){if(!bu(i.value.envelope,e))throw ze();return}await this.write(e,null,null,t),this.check(t.signal)}async privateEnrolPending(e,t){try{if(e.acknowledged!==!1)throw ze();await this.writePrivateMarker(e,!1,t)}catch{throw ze()}}async privateEnrolAcknowledged(e,t){try{await this.writePrivateMarker(e,!0,t)}catch{throw ze()}}async writePrivateMarker(e,t,i){this.check(i.signal);let o=this.marker(this.markerValue(e),e),s=await this.read(i);if(this.check(i.signal),!s?.value.receipt)throw ze();for(let a of["signPublicKey","kemPublicKey","noisePublicKey"])if(!bu(o[a],s.value.receipt[a]))throw ze();let r=s.value.privateEnrolMarker;if(r){if(r.collection!==o.collection||!bu(r.sasCommitment,o.sasCommitment))throw ze();if(r.acknowledged){if(!t)throw ze();return}if(!t)return}else if(t)throw ze();await this.write(s.value.envelope,s.value.receipt,s.encrypted,i,Object.freeze({...o,acknowledged:t})),this.check(i.signal)}async registered(e,t){let i=await this.read(t);if(this.check(t.signal),!i)throw ze();if(i.value.receipt){for(let o of["signPublicKey","kemPublicKey","noisePublicKey"])if(!bu(i.value.receipt[o],e[o]))throw ze();this.receiptValue(e);return}await this.write(i.value.envelope,e,i.encrypted,t),this.check(t.signal)}}});var ka,Nt,vg,Rc,E0=C(()=>{"use strict";St();ve();ka=class extends Error{constructor(t){super(`app device registration: ${t}`);this.reason=t;this.name="AppDeviceRegistrationError"}reason},Nt=n=>new ka(n),vg=n=>Array.from(n,e=>e.toString(16).padStart(2,"0")).join(""),Rc=class{constructor(e,t,i,o,s={}){this.runtime=e;this.session=t;this.persistence=o;try{this.scope=Object.freeze({connectorId:t.connectorId,deviceId:t.deviceId,installationId:t.installationId,kind:t.kind});for(let a of[this.scope.connectorId,this.scope.deviceId,this.scope.installationId])if(N(a).every(c=>c===0))throw Nt("binding");if(t.kind!=="mobile"&&t.kind!=="app-runtime")throw Nt("binding");this.rawOrigin=t.cpOrigin;let r=new URL(this.rawOrigin);if(r.username||r.password||r.pathname!=="/"||r.search||r.hash||r.protocol!=="https:"&&!(s.allowLoopbackHttp===!0&&Qe(this.rawOrigin))||(this.origin=r.origin,this.now=s.now??Date.now,this.fetchImpl=s.fetch??globalThis.fetch,!(i.envelope instanceof Uint8Array)||!i.envelope.length||i.envelope.length>1024)||!e.deviceCustodyCurrent(t,i)||(this.custody=Object.freeze({signPublicKey:new Uint8Array(i.signPublicKey),kemPublicKey:new Uint8Array(i.kemPublicKey),noisePublicKey:new Uint8Array(i.noisePublicKey),envelope:new Uint8Array(i.envelope)}),!this.current()))throw Nt("binding")}catch{throw e.retireLog(),Nt("binding")}}runtime;session;persistence;attempted=!1;lifetime=new AbortController;origin;rawOrigin;scope;custody;now;fetchImpl;current(){try{return!this.lifetime.signal.aborted&&this.runtime.deviceCustodyCurrent(this.session,this.custody)&&this.session.isCurrent()===!0&&this.session.cpOrigin===this.rawOrigin&&this.session.connectorId===this.scope.connectorId&&this.session.deviceId===this.scope.deviceId&&this.session.installationId===this.scope.installationId&&this.session.kind===this.scope.kind}catch{return!1}}check(e){if(!this.current()||e.aborted)throw this.close(),Nt("fenced")}async json(e,t,i,o){this.check(o);let s=new AbortController,r=()=>s.abort(),a=setTimeout(r,15e3);a.unref?.(),o.addEventListener("abort",r,{once:!0}),this.lifetime.signal.addEventListener("abort",r,{once:!0});let c=new Uint8Array(32*1024),l=0,p=null,d=null;try{let u=this.fetchImpl;if(p=await u(`${this.origin}${e}`,{method:"POST",headers:{authorization:`Bearer ${t}`,...i===void 0?{}:{"content-type":"application/json"}},body:i,signal:s.signal,redirect:"error",credentials:"omit",cache:"default",referrerPolicy:"no-referrer"}),this.check(o),s.signal.aborted||!p.ok)throw Nt("unavailable");let f=p.headers.get("content-length");if(f!==null&&/^(0|[1-9][0-9]*)$/.test(f)&&Number(f)>c.length)throw s.abort(),Nt("response");if(!p.body)throw Nt("response");for(d=p.body.getReader();;){let{done:m,value:w}=await d.read();try{if(this.check(o),s.signal.aborted)throw Nt("unavailable");if(m)break;if(l+w.length>c.length)throw s.abort(),Nt("response");c.set(w,l),l+=w.length}finally{w?.fill(0)}}let h=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(c.subarray(0,l)));if(!h||typeof h!="object"||Array.isArray(h))throw Nt("response");return h}catch(u){throw this.check(o),u instanceof ka?u:Nt("unavailable")}finally{c.fill(0),(d?.cancel()??p?.body?.cancel())?.catch(()=>{}),d?.releaseLock(),clearTimeout(a),o.removeEventListener("abort",r),this.lifetime.signal.removeEventListener("abort",r)}}async register(e){let t=null,i=null;try{if(this.check(e.signal),this.attempted)throw Nt("fenced");this.attempted=!0,await this.persistence.pending(new Uint8Array(this.custody.envelope),e),this.check(e.signal);let o=await this.session.connectorBearer(e);if(this.check(e.signal),typeof o!="string"||!o||o.length>16*1024||/[^\x21-\x7e]/.test(o))throw Nt("binding");let s=await this.json("/v1/next/devices/challenge",o,void 0,e.signal);if(this.check(e.signal),typeof s.challenge!="string"||!/^[0-9a-f]{64}$/.test(s.challenge)||typeof s.expires_at!="number"||!Number.isSafeInteger(s.expires_at)||s.expires_at-this.now()<=5e3||s.expires_at-this.now()>16*6e4)throw Nt("response");t=Uint8Array.from(s.challenge.match(/../g).map(l=>parseInt(l,16)));let r=this.runtime.signCpEnrol(t);this.check(e.signal),i=r.signature;let a=await this.json("/v1/next/devices",o,JSON.stringify({device_id:this.scope.deviceId,kind:this.scope.kind,capabilities:["collection_mode_switch_v2"],challenge:s.challenge,sign_pk:vg(r.signPublicKey),kem_pk:vg(r.kemPublicKey),noise_pk:vg(r.noisePublicKey),sig:vg(i)}),e.signal);if(this.check(e.signal),a.device_id!==this.scope.deviceId)throw Nt("response");let c=Object.freeze({connectorId:this.scope.connectorId,deviceId:this.scope.deviceId,installationId:this.scope.installationId,signPublicKey:new Uint8Array(r.signPublicKey),kemPublicKey:new Uint8Array(r.kemPublicKey),noisePublicKey:new Uint8Array(r.noisePublicKey)});return await this.persistence.registered(c,e),this.check(e.signal),this.runtime.acknowledgeDeviceRegistration(c),c}catch(o){throw this.close(),o instanceof ka?o:Nt("unavailable")}finally{t?.fill(0),i?.fill(0)}}close(){this.lifetime.signal.aborted||(this.lifetime.abort(),this.custody.envelope.fill(0),this.runtime.retireLog())}}});var hi,ED,qD,be,v2,Oc,wu=C(()=>{"use strict";a_();Wy();Jt();ve();Ws();Ls();re();xm();Od();_E();HA();JA();ri();Rd();OE();ty();Ed();QA();EE();s0();l0();TE();gu();k0();S0();P0();R0();kc();Tm();O0();E0();ry();hi=class extends Error{constructor(t,i,o){super(`app cloud copy host: ${t}`,o);this.reason=t;this.stage=i;this.name="AppCloudCopyHostError"}reason;stage},ED=32,qD=8,be=(n,e)=>new hi(n,e),v2=(n,e)=>n.length===e.length&&n.every((t,i)=>t===e[i]),Oc=class n{constructor(e,t,i,o,s){this.source=e;this.installation=t;this.originalRelease=i;this.origin=o;this.lifetime=s;this.selected=Object.freeze({accountId:e.accountId,connectorId:e.connectorId,deviceId:e.deviceId,installationId:e.installationId,kind:e.kind,cpOrigin:e.cpOrigin,logOrigin:e.logOrigin,approvalMode:e.approvalMode}),this.currentCallback=e.isCurrent,this.bearerCallback=e.connectorBearer,this.ownershipCallback=t.isCurrent;for(let r of[e.accountId,e.connectorId,e.deviceId,e.installationId])if(N(r).every(a=>a===0))throw be("binding");if(e.kind!=="app-runtime"&&e.kind!=="mobile"||i.schema!=="mdbn-app-trust/release/1"||i.cpOrigin!==e.cpOrigin||i.logOrigin!==e.logOrigin||!/^[0-9a-f]{64}$/.test(i.assetSha256)||!i.trustedRoots.length||i.trustedRoots.length>64||!i.policyPins.length||i.policyPins.length>65536)throw be("binding");if(this.trust=Object.freeze({...i,source:Object.freeze({...i.source}),trustedRoots:Object.freeze(i.trustedRoots.map(r=>{if(!(r instanceof Uint8Array)||r.length!==32||r.every(a=>a===0))throw be("binding");return new Uint8Array(r)})),policyPins:new Uint8Array(i.policyPins)}),this.pin=Object.freeze({...this.selected,isCurrent:()=>this.current(),installationOwned:()=>this.current(),connectorBearer:async({signal:r})=>{this.check(r);let a=await this.bearerCallback.call(this.source,Object.freeze({signal:r}));return this.check(r),a}}),e.approvalMode==="strict")throw new Lt;this.check(s)}source;installation;originalRelease;origin;lifetime;closing=!1;closeResult=null;provider=null;keys=null;noiseStore=null;key=null;noise=null;native=null;publicReceipt=null;signIn=null;originalCustody=null;collectionAttempted=!1;collectionSignal=null;collectionCurrent=null;outcomeStore=null;outcome=null;bootstrap=null;bootstrapConfirmed=!1;collectionScope=null;collectionSession=null;restoredPrivateMarker=null;privateStore=null;privateBootstrap=null;privateMetadata=null;accountKeyPin=null;accountKeyWork=!1;accountKeySealed=new _c;adoptedEndpoint=null;sqlAttempted=!1;sqlClose=null;collectionSql=null;logRequest=null;logLoopback=!1;logWork=null;authority=null;peopleMetadata=null;pump=null;timerPorts=new Set;readWork=null;readAbort=null;readWake=null;readClient=null;readVerified=!1;facades=new Map;logWorkListener=null;selected;currentCallback;bearerCallback;ownershipCallback;trust;pin;current(){try{let e=this.originalRelease,t=this.trust;return!this.closing&&!this.lifetime.aborted&&Et()===this.origin&&this.source.isCurrent===this.currentCallback&&this.source.connectorBearer===this.bearerCallback&&this.installation.isCurrent===this.ownershipCallback&&this.currentCallback.call(this.source)===!0&&this.ownershipCallback.call(this.installation)===!0&&this.installation.scope.account===this.selected.accountId&&this.installation.scope.installation===this.selected.installationId&&Object.entries(this.selected).every(([i,o])=>this.source[i]===o)&&e.schema===t.schema&&e.environment===t.environment&&e.cpOrigin===t.cpOrigin&&e.logOrigin===t.logOrigin&&e.assetSha256===t.assetSha256&&e.source.repository===t.source.repository&&e.source.commit===t.source.commit&&e.source.version===t.source.version&&e.trustedRoots.length===t.trustedRoots.length&&e.trustedRoots.every((i,o)=>v2(i,t.trustedRoots[o]))&&v2(e.policyPins,t.policyPins)}catch{return!1}}check(e){if(e.aborted||!this.current())throw be("fenced")}operationSignal(e){let t=AbortSignal.any([this.lifetime,...this.collectionSignal?[this.collectionSignal]:[],e]);return this.check(t),t}static async openOriginalDevice(e){let{session:t,installation:i,release:o,origin:s,mode:r,signal:a,loadRuntime:c,fetch:l,allowLoopbackHttp:p}=e,d=null;try{if(!["fresh","existing"].includes(r))throw be("binding");d=new n(t,i,o,s,a);let{custody:u,restored:f}=await d.openOwnedDevice({mode:r,signal:a,loadRuntime:c,requireReceipt:!0});if(r==="existing")d.native.acknowledgeDeviceRegistration(f.receipt),d.check(a),d.publicReceipt=d.native.registeredDeviceReceipt();else{let h=await new Rc(d.native,d.pin,u,d.noise,{fetch:l,allowLoopbackHttp:p}).register(Object.freeze({signal:a}));d.check(a),d.publicReceipt=h}return d}catch(u){throw await d?.close(),u instanceof hi||u instanceof Lt?u:new hi("unavailable","device_open",{cause:u})}}static async openInstallationDevice(e){let{signIn:t,installation:i,release:o,origin:s,signal:r,loadRuntime:a,allowLoopbackHttp:c}=e,l=null;try{let p=t.confirmedHostSession(o.logOrigin,o.environment);l=new n(p,i,o,s,r),l.signIn=t;let d=await t.prepareOriginalDevice(i);if(l.check(r),d.mode==="fresh"&&!await k1(d.pin))throw new ji("an unfinished device creation could not be cleared");l.check(r);let{custody:u,restored:f}=await l.openOwnedDevice({mode:d.mode,signal:r,loadRuntime:a,requireReceipt:!1});if(l.originalCustody=u,f?.receipt&&t.view().state!=="paired")throw be("recovery_required");return await l.noise.pending(new Uint8Array(u.envelope),{signal:r}),l.check(r),t.view().state==="paired"&&await l.completeInstallationSignIn(),l}catch(p){throw await l?.close(),p}}async attestInstallation(){if(this.check(this.lifetime),!this.signIn||!this.native||!this.originalCustody||!this.noise)throw be("binding");let e=await this.signIn.attest({runtime:this.native,custody:this.originalCustody,persistence:this.noise,installation:this.installation});return this.check(this.lifetime),e}async completeInstallationSignIn(){if(this.check(this.lifetime),!this.signIn||!this.native||!this.originalCustody||!this.noise)throw be("binding");return await this.signIn.acknowledge({runtime:this.native,custody:this.originalCustody,persistence:this.noise,installation:this.installation}),this.check(this.lifetime),this.publicReceipt=this.native.registeredDeviceReceipt(),this.registeredReceipt()}async openOwnedDevice(e){let{mode:t,signal:i,loadRuntime:o,requireReceipt:s}=e;this.check(i),this.provider=await Sc.open({source:this.pin,origin:this.origin,mode:t,signal:i}),this.check(i),this.key=this.provider.deviceCustodyKek({signal:i}),this.check(i),this.keys=await Pc.open({source:this.pin,origin:this.origin,mode:t,signal:i}),this.check(i),this.noiseStore=await Ic.open({source:this.pin,origin:this.origin,mode:t,signal:i}),this.check(i),this.noise=new Cc(this.pin,this.key,this.noiseStore);let r=await this.noise.restore({signal:i});if(this.check(i),t==="existing"?!r||s&&!r.receipt:r!==null)throw be("recovery_required");this.restoredPrivateMarker=r?.privateEnrolMarker??null;let a=await o(Object.freeze({signal:i}));if(this.check(i),!(a instanceof Uint8Array)||!a.length)throw be("binding");this.native=await nc.createDevice(new Uint8Array(a)),this.check(i);let c=await new xc(this.pin,this.key,this.keys).openNativeDevice(this.native,{signal:i,mode:t,noise:t==="fresh"?{mode:"fresh"}:{mode:"existing",envelope:r.envelope}});return this.check(i),{custody:c,restored:r}}async bootstrapCloudCopy(e){let{scope:t,collectionCurrent:i,purpose:o,outcomeMode:s,signal:r,reconcile:a,fetch:c,allowLoopbackHttp:l}=e,p=this.operationSignal(r),d=e.displayName,u=d===void 0?void 0:li(d);if(u!==void 0&&o!=="create"||(this.check(p),this.collectionAttempted||!this.native||!this.key||!this.publicReceipt||t.account!==this.selected.accountId||t.installation!==this.selected.installationId||!["create","join"].includes(o)||!["fresh","existing"].includes(s)||N(t.collection).every(w=>w===0)))throw be("binding");let f=Object.freeze({account:t.account,installation:t.installation,collection:t.collection}),h=()=>{try{return this.current()&&!p.aborted&&e.scope===t&&e.collectionCurrent===i&&Object.entries(f).every(([w,b])=>t[w]===b)&&i.call(e)===!0&&this.outcomeStore?.fenced!==!0}catch{return!1}};if(!h())throw be("fenced");this.collectionAttempted=!0,this.collectionSignal=p,this.collectionCurrent=h,this.collectionScope=f;let m=Object.freeze({...this.pin,collection:f.collection,purpose:o,assetSha256:this.trust.assetSha256,...u===void 0?{}:{displayName:u},isCurrent:h});this.collectionSession=m;try{this.outcomeStore=await Qy.open({source:m,origin:this.origin,mode:s,signal:p}),this.checkCollection(p),this.outcome=new Xy(m,this.publicReceipt,this.key,this.outcomeStore,{mode:s,signal:p}),this.native.prepareCloudCopyCollection(m),this.checkCollection(p),this.bootstrap=new Gl(this.native,m,this.trust,this.outcome,{fetch:c,allowLoopbackHttp:l,...u===void 0?{}:{displayName:u}});let w=await this.bootstrap.bootstrap(Object.freeze({signal:p,...a?{reconcile:a}:{}}));return this.checkCollection(p),this.bootstrapConfirmed=!0,w}catch(w){throw await this.close(),w}}async bootstrapPrivateDevice(e){let{scope:t,collectionCurrent:i,signal:o,fetch:s,allowLoopbackHttp:r}=e,a=this.operationSignal(o);if(this.check(a),this.collectionAttempted||!this.native||!this.key||!this.noise||!this.publicReceipt||t.account!==this.selected.accountId||t.installation!==this.selected.installationId||N(t.collection).every(u=>u===0))throw be("binding");let c=this.restoredPrivateMarker;if(c&&c.collection!==t.collection)throw be("private_device_limit");let l=Object.freeze({account:t.account,installation:t.installation,collection:t.collection}),p=()=>{try{return this.current()&&!a.aborted&&e.scope===t&&e.collectionCurrent===i&&Object.entries(l).every(([u,f])=>t[u]===f)&&i.call(e)===!0}catch{return!1}};if(!p())throw be("fenced");this.collectionAttempted=!0,this.collectionSignal=a,this.collectionCurrent=p,this.collectionScope=l;let d=Object.freeze({...this.pin,collection:l.collection,purpose:"enrol",rootPublicKey:new Uint8Array(this.trust.trustedRoots[0]),isCurrent:p});this.collectionSession=d;try{this.privateStore=await rg.open({source:d,origin:this.origin,mode:c?"existing":"fresh",signal:a}),this.checkCollection(a);let u=new ng(d,this.publicReceipt,this.key,this.privateStore,this.noise,{allowLoopbackHttp:r});this.native.preparePrivateCollection(d,c?{mode:"existing",marker:c}:{mode:"fresh"}),this.checkCollection(a),this.privateBootstrap=new eg(this.native,d,u,{fetch:s,allowLoopbackHttp:r}),this.privateMetadata=await this.privateBootstrap.bootstrap(Object.freeze({signal:a})),this.checkCollection(a),this.bootstrapConfirmed=!0}catch(u){throw await this.close(),u}}adoptPrivateDevice(e,t){let i=this.operationSignal(e.signal);this.checkCollection(i);let o=this.privateMetadata,s=this.publicReceipt;if(!this.native||!this.privateBootstrap||!o||!s||!this.bootstrapConfirmed||this.adoptedEndpoint!==null)throw be("fenced");let r=o.collection;this.native.adoptDevice({replicaId:e.replicaId,endpoint:e.endpoint,opened:e.opened,sqliteVersion:e.sqliteVersion,collection:r,deviceId:o.deviceId,state:"e2e",cloudCopyOptIn:!1,trustedRoots:this.trust.trustedRoots.map(a=>new Uint8Array(a)),policyPins:new Uint8Array(this.trust.policyPins),trustedSigners:[],expectedGenesis:o.expectedGenesis},t),this.checkCollection(i),this.adoptedEndpoint=e.endpoint,this.accountKeyPin=Object.freeze({connectorId:s.connectorId,deviceId:s.deviceId,installationId:s.installationId,collection:r,approvalMode:"password-ak1",isCurrent:()=>this.collectionCurrent?.()===!0})}checkCollection(e){if(this.check(e),this.collectionCurrent?.()!==!0)throw be("fenced")}adoptCloudCopy(e,t){let i=this.operationSignal(e.signal);if(this.checkCollection(i),!this.bootstrap||!this.bootstrapConfirmed||this.adoptedEndpoint!==null)throw be("fenced");let o=e.endpoint;this.bootstrap.adoptCollection({...e,signal:this.collectionSignal},t),this.checkCollection(i),this.adoptedEndpoint=o}async openCollectionSql(e){let{replicaId:t,endpoint:i,openSql:o}=e,s=this.operationSignal(e.signal);if(this.checkCollection(s),!this.bootstrapConfirmed||!this.collectionScope||this.sqlAttempted||this.adoptedEndpoint!==null||N(t).every(r=>r===0)||typeof i!="bigint"&&!Number.isSafeInteger(i)||BigInt(i)<0n||BigInt(i)>(1n<<64n)-1n)throw be("binding");this.sqlAttempted=!0;try{let r=await o.call(e,Object.freeze({scope:this.collectionScope,signal:s})),a=r.close;if(this.sqlClose=async()=>{await a.call(r)},this.collectionSql=r.sql,this.checkCollection(s),e.openSql!==o)throw be("fenced");this.privateBootstrap?this.adoptPrivateDevice({signal:s,replicaId:t,endpoint:i,opened:r.opened,sqliteVersion:r.sqliteVersion},r.sql):this.adoptCloudCopy({signal:s,replicaId:t,endpoint:i,opened:r.opened,sqliteVersion:r.sqliteVersion,cloudCopyOptIn:!0},r.sql)}catch(r){throw await this.close(),r}}async startCollectionLog(e){let{fetch:t,allowLoopbackHttp:i}=e,o=this.operationSignal(e.signal);if(this.checkCollection(o),!this.native||!this.collectionSession||this.adoptedEndpoint===null)throw be("binding");let s=t??globalThis.fetch,r=i===!0;if(this.authority&&(s!==this.logRequest||r!==this.logLoopback))throw be("fenced");if(this.pump)return;if(this.logWork){await this.logWork,this.checkCollection(o);return}this.authority||(this.logRequest=s,this.logLoopback=r,this.authority=new Hl(this.native,Object.freeze({...this.collectionSession,endpoint:this.adoptedEndpoint,directOrigins:Object.freeze([])}),{fetch:s,allowLoopbackHttp:i,tokenCache:v1()}));let a=this.authority,c=(async()=>{await a.accessToken(Object.freeze({signal:o})),this.checkCollection(o),this.pump=this.native.bindLogTransport(a.logTransport())})();this.logWork=c;try{await c}finally{this.logWork===c&&(this.logWork=null)}}peopleAuthority(){if(this.checkCollection(this.lifetime),!this.collectionSession||this.adoptedEndpoint===null||!this.logRequest||this.accountKeyPin)throw be("binding");if(!this.peopleMetadata){let e=this.adoptedEndpoint,t=this.collectionSession,i=new yc(Object.freeze({...t,endpoint:e,directOrigins:Object.freeze([]),isCurrent:()=>this.collectionCurrent?.()===!0&&this.adoptedEndpoint===e,connectorBearer:async({signal:s})=>{s.throwIfAborted(),this.checkCollection(this.lifetime);let r=await t.connectorBearer({signal:this.lifetime});return this.checkCollection(this.lifetime),s.throwIfAborted(),r}}),{fetch:this.logRequest,allowLoopbackHttp:this.logLoopback}),o=Object.freeze({collection:i.collection,isCurrent:()=>i.isCurrent(),request:(s,r)=>i.request(s,r)});this.peopleMetadata={authority:i,view:o}}return this.peopleMetadata.view}timerConsentKey(e){let t=this.timerGrant(e);return t?JSON.stringify(t.consent):null}timerGrant(e){let t=this.source.timerConsent,i=t?.call(this.source);if(!i?.approved)return null;let o=i.grants.find(s=>s.collectionId===e);return o?{callback:t,consent:i,grant:o}:null}openTimersPort(e){if(this.checkCollection(this.lifetime),!this.readVerified||!this.logRequest||!this.collectionScope||e.signal.aborted)throw be("binding");let{scope:t,generation:i,signal:o}=e,s=this.collectionScope;if(t.account!==s.account||t.installation!==s.installation||t.collection!==s.collection||N(i).every(m=>m===0))throw be("binding");let r=this.timerGrant(t.collection);if(!r)return null;let{callback:a,consent:c,grant:l}=r,p=globalThis.WorkerGlobalScope;if(typeof p!="function"||!(globalThis instanceof p)||N(l.grantId).every(m=>m===0)||!/^[0-9a-f]{64}$/.test(l.declarationDigest))throw be("binding");let d=JSON.stringify(c),u=new MessageChannel,f=()=>{try{return!o.aborted&&e.signal===o&&e.scope===t&&e.generation===i&&this.collectionCurrent?.()===!0&&this.current()&&t.account===s.account&&t.installation===s.installation&&t.collection===s.collection&&this.source.timerConsent===a&&JSON.stringify(a?.call(this.source))===d}catch{return!1}},h=xE(u.port1,{scope:s,generation:i,grantId:l.grantId,cpOrigin:new URL(this.selected.cpOrigin).origin,signal:o,isCurrent:f,fetch:this.logRequest,...this.signIn?{journal:{read:()=>this.signIn.originalTimerChannel(l.grantId),write:m=>this.signIn.retainTimerChannel(l.grantId,m)}}:{},bearer:async()=>{if(!f())throw be("fenced");let m=await this.bearerCallback.call(this.source,{signal:this.lifetime});if(!f())throw be("fenced");return m}});return this.timerPorts.add(h),Object.freeze({port:u.port2,close:async()=>{await h.close(),u.port2.close(),this.timerPorts.delete(h)}})}serverProblem(){return this.pump?.serverProblem??null}transportHealth(){return this.pump?.transportHealth??null}initialSync(){try{return this.native?gc(this.native.observations().status):"unavailable"}catch{return"unavailable"}}holdsLog(){try{if(!this.native)return!1;let e=this.native.observations().status;return e.mode==="local_only"||e.headKnown>0}catch{return!1}}keyWaitDetail(){try{return this.native?Yy(this.native.observations().status):null}catch{return null}}keyringSettled(){if(!this.native)throw be("binding");let e=this.native.observations();return e.requiresReopen||e.keyringRebuildFailed?"failed":e.keyringRebuilding?"pending":"settled"}pendingWrites(){try{return this.native?.observations().status.pending??0}catch{return 0}}pushLog(e){try{let t=this.native?.pushLog(e)===!0;return t&&this.readWake?.(),t}catch{return!1}}openLogPush(e){this.checkCollection(this.lifetime);let t=this.native,i=this.authority,o=this.collectionSession,s=this.logRequest;if(!t||!this.pump||!i||!o||!s)throw be("binding");if(!t.supportsLogPush||typeof WebSocket!="function")return null;let r=this.logLoopback,a=i.origin,c=()=>{try{return this.collectionCurrent?.()===!0&&this.current()&&this.authority===i&&i.isCurrent()}catch{return!1}},l=i.logTransport(),p=new Hy({origin:a,collection:i.collection,deviceId:o.deviceId,isCurrent:c,accessToken:d=>i.accessToken(d),invalidateToken:d=>i.invalidateToken(d),nonce:async({signal:d})=>{let u=await s(`${a}/v1/nonce`,{signal:d,cache:"no-store",credentials:"omit",redirect:"error",referrerPolicy:"no-referrer"}),f=(await u.text()).trim();if(!u.ok||!/^[0-9a-f]{64}$/.test(f))throw be("unavailable","push_nonce");return Uint8Array.from(f.match(/../g).map(h=>parseInt(h,16)))},signHello:(d,u)=>c()?t.signLogHello(d,u):null},{push:e.push,ended:e.ended,live:d=>{try{c()&&t.setLogStreamLink(d)}catch{}if(e.live(d),d)try{this.logWorkListener?.()}catch{}}},{allowLoopbackHttp:r});return l.setStreamRoute((d,u)=>p.request(d,u)),p}async driveCollection(e){let t=this.operationSignal(e.signal);if(this.checkCollection(t),!this.native||!this.pump||this.adoptedEndpoint===null)throw be("binding");for(let i=0;i<qD;i++){let o=this.pump.callsSent;if(this.native.tick(),await this.pump.pump(),this.checkCollection(t),this.pump?.callsSent===o)break}}async wakeCollectionLog(e){let t=this.operationSignal(e.signal);if(this.checkCollection(t),!this.native||!this.pump||this.adoptedEndpoint===null)throw be("binding");this.native.tick(),(await this.pump.pump()).quiet&&(this.checkCollection(t),this.native.requestLogHead()&&(await this.pump.pump(),this.checkCollection(t),this.native.tick()))}waitForVerifiedRead(e){let{timeoutMs:t=15e3,cold:i=!1,local:o=!1}=e,s=this.operationSignal(e.signal);if(this.checkCollection(s),!this.native||!this.collectionScope||this.adoptedEndpoint===null||!Number.isSafeInteger(t)||t<1||t>15e3||typeof i!="boolean"||typeof o!="boolean"||i&&(o||!this.pump))throw be("binding");if(o&&!this.holdsLog())return Promise.reject(be("unavailable","local_read_without_log"));if(this.readWork)return this.readWork.then(()=>{this.checkCollection(s)});let r=this.verifyRead(s,t,i,o,e.onProgress);return this.readWork=r,r.finally(()=>{this.readWork===r&&(this.readWork=null)}).catch(()=>{}),r}async verifyRead(e,t,i,o,s){let r=new AbortController,a=()=>r.abort(),c=()=>o?null:this.pump;this.readAbort=r;let l=!1,p=null;c()&&(this.readWake=()=>{l=!0,p?.()});let d=_=>l?(l=!1,Promise.resolve()):c()?new Promise((k,S)=>{if(r.signal.aborted){S(r.signal.reason);return}let x=()=>{clearTimeout(O),r.signal.removeEventListener("abort",I),p===P&&(p=null)},P=()=>{x(),l=!1,k()},I=()=>{x(),S(r.signal.reason)},O=setTimeout(()=>{x(),k()},_);p=P,r.signal.addEventListener("abort",I,{once:!0})}):ya(_,r.signal);e.addEventListener("abort",a,{once:!0});let u=null,f="read_connect",h=null,m=()=>h??=be(i?"sync_stalled":"unavailable",f),w,b=new Promise((_,k)=>{w=()=>k(m()),r.signal.addEventListener("abort",w,{once:!0})});b.catch(()=>{});let g=null,y=_=>{if(_!==g){g=_;try{s?.(_)}catch{}}},v=()=>{this.checkCollection(e);let _=i?c().terminalProblem:null;if(rn(_))throw new En(Rt(_)??"unavailable",_);let k=this.native.observations();if(k.requiresReopen||k.keyringRebuildFailed)throw be("recovery_required");let S=gc(k.status);return y(S==="installing"?"loading_snapshot":S==="waiting_for_key"?"waiting_for_key":S==="behind"?"replaying":S===null?"verifying_read":"syncing"),k};this.readVerified=!1;try{if(c()){let k=!1,S=()=>{let q=v();return k=i&&RE(q.status),[q.status.confirmedThrough,q.status.installing?.done??0,q.status.installing?.total??0,c().readProgress]},x=S(),P=Date.now(),I=new Map,O=null,R=()=>{try{let q=Date.now(),j=S();j.some((V,U)=>V>x[U])&&(P=q,O=null),x=j.map((V,U)=>Math.max(V,x[U]));let B=c().responseProgress(),D=new Set(B.map(V=>V.id));for(let V of I.keys())D.has(V)||I.delete(V);for(let V of B){let U=I.get(V.id);V.bytes>(U?.bytes??0)&&I.set(V.id,{bytes:V.bytes,at:q})}let X=(k?Math.max(t,CE):t)-(q-P);X<=0&&(O??=new Set(I.keys()),X=Math.max(0,...[...O].map(V=>{let U=I.get(V);return U?t-(q-U.at):0}))),X<=0?a():u=setTimeout(R,Math.min(250,X))}catch(q){h=q,a()}};u=setTimeout(R,Math.min(250,t))}else u=setTimeout(a,t);this.readClient=await Promise.race([wr.connect({app:{name:"app-local-read-gate",version:"1"},connector:Dl(this.native,{collection:this.collectionScope.collection}),reconnect:!1,signal:r.signal}).then(k=>{if(r.signal.aborted)throw k.close(),m();return k}),b]),this.checkCollection(e);let _=250;for(;!r.signal.aborted;){f="read_catch_up",l=!1,this.native.tick();let k=c();k&&await Promise.race([k.pump(),b]),this.checkCollection(e);let S=v();if(i&&gc(S.status)!==null){await d(_),_=Math.min(1e3,_*2);continue}f="read_query";try{if(await Promise.race([this.readClient.query({limit:1},{signal:r.signal}),b]),this.checkCollection(e),r.signal.aborted)throw m();this.readVerified=!0;return}catch(x){if(this.checkCollection(e),!(x instanceof ne)||x.code!=="unavailable"||!c()||r.signal.aborted)throw x}await d(_),_=Math.min(1e3,_*2)}throw m()}catch(_){throw this.checkCollection(e),r.signal.aborted?m():_}finally{u!==null&&clearTimeout(u),e.removeEventListener("abort",a),r.signal.removeEventListener("abort",w),this.readWake=null,p=null,this.readClient?.close(),this.readClient=null,this.readAbort=null}}get privateDevice(){return this.accountKeyPin!==null}accountKeyState(){if(!this.native||!this.accountKeyPin||this.adoptedEndpoint===null)throw be("binding");return this.native.accountKeyStatus(this.accountKeyPin)}async settlePrivateKey(e){let{timeoutMs:t=15e3}=e,i=this.operationSignal(e.signal);if(this.checkCollection(i),!this.native||!this.pump||!this.accountKeyPin||this.adoptedEndpoint===null||!Number.isSafeInteger(t)||t<1||t>15e3)throw be("binding");let o=null,s=Date.now(),r=100,a=!1,c=async()=>a?!0:(a=!0,await this.wakeCollectionLog({signal:i}),!1);for(;;){let l=this.accountKeyState();if(l.state==="keyed")return"keyed";if(l.state==="refused"&&l.reason==="outcome_unknown")throw be("recovery_required");await this.driveCollection({signal:i});let p=this.pump?.terminalProblem;if(rn(p))throw new En(Rt(p)??"unavailable",p);if(this.accountKeyState().state==="keyed")return"keyed";let d=this.native.observations();if(d.requiresReopen||d.keyringRebuildFailed)throw be("recovery_required");let u=gc(d.status);if(u==="offline"||this.pump?.transportHealth?.kind==="offline")throw be("unavailable","key_wait_offline");let f=u==="waiting_for_key"?Yy(d.status)?.key:void 0;if(u===null||f!==void 0&&f!=="reading"){if(await c())return"locked";continue}let h=Date.now(),m=[d.status.confirmedThrough,d.status.headKnown,this.pump.readProgress];if((o===null||m.some((w,b)=>w>o[b]))&&(s=h),o=o===null?m:m.map((w,b)=>Math.max(w,o[b])),h-s>=t)throw be("sync_stalled");await ya(r,i),this.checkCollection(i),r=Math.min(1e3,r*2)}}accountKeySession(e){let t=this.collectionSession;if(!t)throw be("binding");return Object.freeze({accountId:this.selected.accountId,connectorId:e.connectorId,deviceId:e.deviceId,collection:e.collection,cpOrigin:this.selected.cpOrigin,isCurrent:()=>this.collectionCurrent?.()===!0&&this.accountKeyPin===e,connectorBearer:async({signal:i})=>{i.throwIfAborted(),this.checkCollection(this.lifetime);let o=await t.connectorBearer({signal:this.lifetime});return this.checkCollection(this.lifetime),i.throwIfAborted(),o}})}async accountKeyMode(e){let t=this.operationSignal(e.signal);this.checkCollection(t);let i=this.accountKeyPin;if(!i||!this.logRequest)throw be("binding");return hg(this.accountKeySession(i),{signal:t,fetch:this.logRequest,allowLoopbackHttp:this.logLoopback})}async unlockAccountKey(e,t){let i=this.operationSignal(t.signal);this.checkCollection(i);let o=this.native,s=this.accountKeyPin,r=this.logRequest;if(!o||!s||!r||!this.pump||this.adoptedEndpoint===null||this.accountKeyWork)throw be("binding");let a=Object.freeze({supportsFetchProof:()=>o.supportsAccountKeyFetchProof,signFetch:c=>o.signAccountKeyFetch(s,this.selected.accountId,c),unlockConsuming:c=>o.unlockAccountKeyConsuming(s,c),status:()=>o.accountKeyStatus(s),drive:c=>this.driveCollection({signal:c.signal}),headKnown:()=>o.observations().status.headKnown});this.accountKeyWork=!0;try{await mg(this.accountKeySession(s),a,e,{signal:i,fetch:r,allowLoopbackHttp:this.logLoopback,sealed:this.accountKeySealed,...t.onMode?{onMode:t.onMode}:{}}),this.checkCollection(i)}finally{this.accountKeyWork=!1}}onLogWork(e){this.logWorkListener=e}attachDataFacade(e){if(this.checkCollection(this.lifetime),!this.native||!this.collectionScope||!this.readVerified||this.facades.size>=ED||this.facades.has(e))throw be("fenced");let t=Object.freeze({...this.collectionScope,isCurrent:()=>{try{return this.checkCollection(this.lifetime),!0}catch{return!1}}}),i=Qm(this.native,e,t,()=>this.logWorkListener?.());return this.facades.set(e,i),i.resourceSetup}detachDataFacade(e){let t=this.facades.get(e);t&&(this.facades.delete(e),t.close())}registeredReceipt(){this.check(this.lifetime);let e=this.publicReceipt;if(!e)throw be("fenced");return Object.freeze({...e,signPublicKey:new Uint8Array(e.signPublicKey),kemPublicKey:new Uint8Array(e.kemPublicKey),noisePublicKey:new Uint8Array(e.noisePublicKey)})}close(){if(this.closing=!0,this.readVerified=!1,this.readAbort?.abort(),this.closeResult)return this.closeResult;let e=!1;for(let t of[()=>this.readClient?.close(),()=>{for(let i of this.facades.values())i.close();this.facades.clear()},()=>this.peopleMetadata?.authority.close(),()=>this.bootstrap?.close(),()=>this.outcome?.close(),()=>this.accountKeySealed.clear()])try{t()}catch{e=!0}return this.closeResult??=(async()=>{try{await Promise.all([...this.timerPorts].map(async i=>{try{await i.close()}catch{e=!0}})),this.timerPorts.clear();let t=await this.native?.close();if(this.collectionSql&&t!==!0&&this.collectionSql.fence(),this.authority?.close(),await this.sqlClose?.(),e)throw be("unavailable","close_fence")}finally{this.key=null,this.noise=null,this.originalCustody?.envelope.fill(0),this.originalCustody=null,this.signIn=null,this.publicReceipt=null,this.outcomeStore?.close(),this.privateStore?.close(),this.noiseStore?.close(),this.keys?.close(),this.provider?.close()}})()}}});var Ec,TD,MD,ws,Un,qc,_g=C(()=>{"use strict";Ec="original-join",TD=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,MD="00000000-0000-0000-0000-000000000000",ws=class extends Error{constructor(t){super(`app collection join: ${t}`);this.reason=t;this.name="AppCollectionJoinError"}reason},Un=(n="recovery_required")=>new ws(n),qc=class{options;key;busy=!1;constructor(e){let t=Object.freeze({account:e.scope.account,installation:e.scope.installation,collection:e.scope.collection});if(Object.values(t).some(i=>typeof i!="string"||!TD.test(i)||i===MD)||typeof e.databaseName!="string"||!e.databaseName.length||e.databaseName.length>256||/[\u0000-\u001f\u007f]/.test(e.databaseName)||typeof e.isCurrent!="function")throw Un("binding");this.options=Object.freeze({databaseName:e.databaseName,scope:t,isCurrent:e.isCurrent}),this.key=JSON.stringify([t.account,t.installation,t.collection])}check(e){if(e.aborted||this.options.isCurrent()!==!0)throw Un("fenced")}marker(e){if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).sort().join()!=="account,collection,installation,phase,version")throw Un();let t=e;if(t.version!==1||t.phase!=="attempted"&&t.phase!=="completed"||Object.entries(this.options.scope).some(([i,o])=>t[i]!==o))throw Un();return t}open(e){if(this.check(e),!globalThis.indexedDB)throw Un();return new Promise((t,i)=>{let o=indexedDB.open(this.options.databaseName,1),s=!1,r=()=>e.removeEventListener("abort",a),a=()=>{s=!0,r();try{o.transaction?.abort()}catch{}i(Un())};e.addEventListener("abort",a,{once:!0}),o.onblocked=o.onerror=a,o.onupgradeneeded=()=>{try{if(this.check(e),s||o.result.objectStoreNames.length)throw Un();o.result.createObjectStore(Ec)}catch{try{o.transaction?.abort()}catch{}}},o.onsuccess=()=>{r();try{if(this.check(e),s||o.result.objectStoreNames.length!==1||!o.result.objectStoreNames.contains(Ec))throw Un();t(o.result)}catch{o.result.close(),i(Un())}}})}async change(e,t){if(this.check(t),this.busy)throw Un("busy");this.busy=!0;let i=null;try{return i=await this.open(t),this.check(t),await new Promise((o,s)=>{this.check(t);let r=i.transaction(Ec,"readwrite",{durability:"strict"}),a=null,c,l=()=>{try{r.abort()}catch{}},p=()=>t.removeEventListener("abort",l);t.addEventListener("abort",l,{once:!0}),r.onabort=r.onerror=()=>{p(),s(c??Un())},r.oncomplete=()=>{p();try{if(this.check(t),!a)throw Un();o(Object.freeze(a))}catch{s(Un())}};let d=r.objectStore(Ec),u=d.get(this.key);u.onsuccess=()=>{try{this.check(t);let f=u.result;if(f===void 0){if(e!=="prepare")throw Un();d.add({version:1,...this.options.scope,phase:"attempted"},this.key),a={outcomeMode:"fresh",phase:"attempted"}}else{let h=this.marker(f);e==="complete"&&h.phase!=="completed"&&d.put({...h,phase:"completed"},this.key),a={outcomeMode:"existing",phase:e==="complete"?"completed":h.phase}}}catch(f){c=f,l()}}})}catch(o){throw o instanceof ws?o:Un()}finally{i?.close(),this.busy=!1}}prepare(e){return this.change("prepare",e.signal)}async syncedBefore(e){return await this.synced("read",e.signal)===!0}async markSynced(e){await this.synced("mark",e.signal)}async synced(e,t){let i=null;try{i=await this.open(t),this.check(t);let o=JSON.stringify([this.options.scope.account,this.options.scope.installation,this.options.scope.collection,"synced"]);return await new Promise(s=>{let r=i.transaction(Ec,e==="mark"?"readwrite":"readonly"),a=!1;r.onabort=r.onerror=()=>s(!1),r.oncomplete=()=>s(e==="mark"||a);let c=r.objectStore(Ec);if(e==="mark")c.put({version:1,synced:!0},o);else{let l=c.get(o);l.onsuccess=()=>{let p=l.result;a=!!p&&p.version===1&&p.synced===!0}}})}catch{return!1}finally{i?.close()}}async complete(e){await this.change("complete",e.signal)}}});function A2(n){let e=Object.freeze({...n,setupJournal:Object.freeze({...n.setupJournal})}),t=Q1(e.sql);if(typeof e.handoff!="function")throw cr("binding");let i=new Set;return async o=>{let s=JSON.stringify([o.scope.account,o.scope.installation,o.scope.collection]);if(i.has(s))throw cr("fenced");i.add(s);let{host:r,installation:a,signal:c,collection:l,setupPolicy:p}=o,d=a.isCurrent,u=l.displayName,f=l.mode==="private",h=ue=>{if(oe())try{o.onProgress?.(ue)}catch{}},m=Object.freeze({account:o.scope.account,installation:o.scope.installation,collection:o.scope.collection}),w=JSON.stringify([m.account,m.installation,m.collection]),b=new AbortController,g=!1,y=!0,v=null,_=null,k=null,S=null,x=null,P=null,I=null,O=null,R="setup_required",q=null,j=!1,B=!1,D=null,X=null,V="settled",U=null,ce=!1,ee=null,te=!1,Ie=null,tt=null,$=new Map,Y=new Map,K=()=>{try{return r.timerConsentKey(m.collection)}catch{return}},Q=null,Ae=new Set,oe=()=>{try{return!g&&!b.signal.aborted&&!c.aborted&&o.signal===c&&o.host===r&&o.installation===a&&a.isCurrent===d&&d.call(a)===!0&&o.collection===l&&o.setupPolicy===p&&a.scope.account===m.account&&a.scope.installation===m.installation&&JSON.stringify([o.scope.account,o.scope.installation,o.scope.collection])===w&&l.collectionId===m.collection}catch{return!1}},ie=()=>{if(!oe())throw cr("fenced")},He=()=>{for(let ue of[...Ae])try{ue()}catch{}},Fe=()=>{if(k)return k;g=!0,R="setup_required",v!==null&&clearTimeout(v),v=null,ee!==null&&clearTimeout(ee),ee=null,tt=null;try{U?.close()}catch{}U=null;try{r.onLogWork?.(null)}catch{}c.removeEventListener("abort",Ft);let ue=[...$.values()];return $.clear(),k=Promise.resolve().then(async()=>{let Ce=!1;try{await x?.close()}catch{Ce=!0}try{await S?.close()}catch{Ce=!0}for(let st of ue){try{await st.timers?.close()}catch{Ce=!0}try{await st.control.close()}catch{Ce=!0}try{st.data.port1.postMessage([1,JSON.stringify([m.account,m.installation,m.collection]),"close"])}catch{Ce=!0}for(let mi of[st.data.port1,st.data.port2,st.command.port1,st.command.port2])try{mi.close()}catch{Ce=!0}}try{I?.port1.postMessage([1,JSON.stringify([m.account,m.installation,m.collection]),"close"])}catch{Ce=!0}for(let st of[I?.port1,I?.port2,O?.port1,O?.port2])try{st?.close()}catch{Ce=!0}await _?.catch(()=>{});try{P?.close()}catch{Ce=!0}if(Ce)throw cr("unavailable");Ae.clear(),i.delete(s)}),b.abort(),He(),k},Ft=()=>{Fe().catch(()=>{})},Ee=null,nt=0,dr=()=>{let ue=Rt(Q);if(ue!==null)return ue==="collection_migrating"?Math.min(6e5,Math.max(5e3,Q?.retryAfterMs??3e4)):3e5;let Ce=Math.min(6e4,1e3*2**Math.min(Math.max(nt,Vr),6));return Ee?.kind==="offline"?Dn?Ce:null:Ee?.kind==="server_busy"||Ee?.kind==="rate_limited"?Ee.retryAfterMs??Ce:Vr||Ee?Ce:250},_o=()=>{let ue=null;try{ue=r.serverProblem()}catch{ue=null}let Ce=null;try{Ce=r.transportHealth()}catch{Ce=null}nt=Ce?nt+1:0;let st=JSON.stringify(Ce)===JSON.stringify(Ee);(ue!==Q||!st)&&(Q=ue,Ee=Ce,He())},Ao=Number.POSITIVE_INFINITY,Vr=0,ko=0,vs=!1,Dn=null,dn=ue=>{let Ce=ue&&typeof ue=="object"&&typeof ue.code=="string"?ue.code:null;try{console.debug("mdbase: sync turn failed",{reason:Ee?.kind??Rt(Q)??Ce??"unknown",failures:Vr})}catch{}},So=()=>{if(y||Date.now()-ko>=LD)return!1;try{return r.pendingWrites()>0}catch{return!1}},Bc=()=>r.startCollectionLog({signal:b.signal,fetch:e.fetch,allowLoopbackHttp:e.allowLoopbackHttp}),xa=ue=>{Ie=ue,Lg(),Vc(!1),Dn?.(),He()},_s=()=>{if(!(U||!oe())){try{U=typeof r.openLogPush=="function"?r.openLogPush({push:ue=>{oe()&&(r.pushLog(ue),Lg())},live:Vc,ended:ue=>{if(!j){tt??=ue,Vc(!1);return}xa(ue)}}):null}catch{U=null}if(U){try{U.start()}catch{try{U.close()}catch{}U=null,Ia(!0);return}Vc(!1)}else Ia(!0)}},Ui=async()=>{let ue=D;D=null,await(ue??Bc()),ie(),B=!0,_s()},ok=()=>{if(!(V!=="pending"||!B)){try{V=r.keyringSettled?.()??"settled"}catch{return}V==="failed"&&sk(new hi("recovery_required"))}},sk=ue=>{X=ue,j=!1,v!==null&&clearTimeout(v),v=null,He()},pq=ue=>{let Ce=null;try{Ce=ue.server}catch{Ce=null}let st=rn(Ce)&&Rt(Ce)!==null?Ce:null,mi=!rn(Ce)&&ue instanceof pi&&ue.reason==="response",An=st?null:mi?{kind:"unreachable"}:Nd(ue);if(!st&&(An===null||An.kind==="auth")){sk(ue);return}nt=An?nt+1:0,(st!==Q||JSON.stringify(An)!==JSON.stringify(Ee))&&(Q=st,Ee=An,He())},As=()=>{if(!j||!oe())return;if(!y&&!So()&&!te){_||U?.suspend();return}if(v!==null||_)return;let ue=te?0:dr();te=!1,ue!==null&&(v=setTimeout(()=>{if(v=null,!oe())return;let Ce=y&&Date.now()>=Ao;Ce&&(Ao=Number.POSITIVE_INFINITY);let st=_=B?Ce?r.wakeCollectionLog({signal:b.signal}):r.driveCollection({signal:b.signal}):Ui().then(()=>r.driveCollection({signal:b.signal}));st.then(()=>{_===st&&(_=null),Vr=0,vs=!0,oe()&&(_o(),ok()),Dn?.(),As()},mi=>{_===st&&(_=null),Vr++,oe()&&(B?(_o(),ok()):pq(mi)),dn(mi),Dn?.(),As()})},ue))},Lg=()=>{oe()&&(te=!0,v!==null&&clearTimeout(v),v=null,As())},Ia=ue=>{ce!==ue&&(ce=ue,He())},Vc=ue=>{if(ee!==null&&clearTimeout(ee),ee=null,ue){Ia(!1);return}if(!U?.available){Ia(Ie===null);return}U.suspended||(ee=setTimeout(()=>{ee=null,oe()&&!U?.live&&Ia(!0)},_2))},ak=ue=>{if(ie(),ue){(!U?.live||Ee?.kind==="offline")&&(Ao=0),Vr=0,nt=0,Ee?.kind==="offline"&&(te=!0);try{U?.resume(),U&&!U.live&&Vc(!1)}catch{}}else y&&(ko=Date.now());y=ue,v!==null&&clearTimeout(v),v=null,As()},dq=()=>new Promise((ue,Ce)=>{let st,mi=null,An=Qn=>{Dn=null,mi!==null&&clearTimeout(mi),b.signal.removeEventListener("abort",Ca),Qn?Ce(Qn):ue()},Ca=()=>An(cr("fenced"));b.signal.addEventListener("abort",Ca,{once:!0}),Dn=()=>{if(!oe()){An(cr("fenced"));return}if(Ie!==null){An();return}let Qn="first_turn";if(vs)try{Qn=typeof r.initialSync=="function"?r.initialSync():null}catch{Qn="unavailable"}if(Qn===null||Qn==="offline"||Ee?.kind==="offline"){An();return}let yi=null;if(Qn==="waiting_for_key"&&typeof r.keyWaitDetail=="function")try{yi=r.keyWaitDetail()}catch{yi=null}let Ra=Qn+(yi?JSON.stringify(yi):"");if(Ra!==st){st=Ra;try{console.debug("mdbase: waiting for the first sync",{...yi,reason:Qn})}catch{}}},mi=setTimeout(()=>An(),jD),Dn()});c.addEventListener("abort",Ft,{once:!0});try{ie(),P=new Xl({...e.setupJournal,scope:m,isCurrent:oe});let ue=new qc({databaseName:e.joinDatabaseName,scope:m,isCurrent:oe});if(f)h("joining"),await r.bootstrapPrivateDevice({scope:m,collectionCurrent:oe,signal:b.signal,fetch:e.fetch,allowLoopbackHttp:e.allowLoopbackHttp}),ie();else{let Ct=await ue.prepare({signal:b.signal});ie(),h("joining"),await r.bootstrapCloudCopy({scope:m,collectionCurrent:oe,purpose:"join",outcomeMode:Ct.outcomeMode,signal:b.signal,...Ct.outcomeMode==="existing"?{reconcile:"explicit-unknown-outcome"}:{},fetch:e.fetch,allowLoopbackHttp:e.allowLoopbackHttp}),ie(),await ue.complete({signal:b.signal}),ie()}let Ce=r.registeredReceipt();if(Ce.installationId!==m.installation)throw cr("binding");let st=null,mi=async Ct=>{let Tt=await t(Ct);return st=Tt.ledger??null,Tt};h("opening_store"),await r.openCollectionSql({signal:b.signal,replicaId:Ce.deviceId,endpoint:0,openSql:mi}),ie();let An=!0;try{An=r.holdsLog?.()??!0}catch{An=!1}let Ca=!f&&An&&await ue.syncedBefore({signal:b.signal});ie();let Qn=async()=>{h("connecting_log");let Ct=Date.now()+ND;for(let Tt=0;;Tt++)try{await Bc(),ie();break}catch(gi){ie();let Fr=gi instanceof pi&&gi.reason==="unavailable"?gi.server:null;if(!rn(Fr)||Fr.status!==503||Fr.code!=="busy"||Rt(Fr)!==null||Tt+1>=DD)throw gi;let Fc=Fr.retryAfterMs??1e3*2**Tt;if(Date.now()+Fc>=Ct||(await ya(Fc,b.signal),ie(),Date.now()>=Ct))throw gi}B=!0};Ca?(D=Bc(),D.catch(()=>{})):await Qn();let yi=crypto.randomUUID(),Ra=null,lk=null,jg=null;if(f){h("syncing");let Ct=await r.settlePrivateKey({signal:b.signal});if(ie(),Ct==="locked"){let Tt=await r.accountKeyMode({signal:b.signal});ie(),q={mode:Tt,unlocking:!1,problem:null}}}let ck=async()=>{let Ct=f?await ue.syncedBefore({signal:b.signal}):Ca;ie();let Tt=!1;if(Ca&&!B)try{await r.waitForVerifiedRead({signal:b.signal,local:!0,timeoutMs:UD,onProgress:h}),ie(),Tt=!0}catch{ie();let Kt=D;D=null;let vt=Kt?await Kt.then(()=>!0,()=>!1):!1;ie(),vt?B=!0:await Qn()}if(Tt||(_s(),h("syncing"),await r.waitForVerifiedRead({signal:b.signal,cold:!Ct,onProgress:h}),ie()),j=!0,r.onLogWork?.(Lg),tt!==null){let Kt=tt;tt=null,xa(Kt)}Tt?(V="pending",te=!0,As(),ee=setTimeout(()=>{ee=null,oe()&&!U?.live&&Ia(!0)},_2)):(As(),Ct&&(h("syncing"),await dq()),ie()),h("checking_setup"),ue.markSynced({signal:b.signal}).catch(()=>{});let gi=await P.load(b.signal);ie();let Fr=gi&&gi.version!==1&&(gi.phase==="attempted"||gi.phase==="confirmed")?"reconcile-original":gi===null&&p==="approved-new-collection"?"approved-new":"inspect",Fc=e.people===!0&&!f,pk=Fc?{people:!0}:f?{privateDevice:!0}:{},hq={owner:null},dk=(Kt,vt,Wt,Kr)=>cR(vt,{scope:m,generation:yi},{journal:P,resourceSetup:r.attachDataFacade(Kt),signal:b.signal,isCurrent:oe,ledger:()=>oe()?st:null,setupTurn:hq,assess(Kc){ie(),R=Kc,He()},foreground:Wt,onProtocolFailure:Kr,...Fc?{peopleAuthority:r.peopleAuthority()}:{}});x=r.openTimersPort({scope:m,generation:yi,signal:b.signal}),ie();let mq=K()??null;I=new MessageChannel,O=new MessageChannel,S=dk(I.port1,O.port1,ak,Ft),ie();let Ug=Kt=>{if(Y.delete(Kt.dataPort),I&&O&&Kt.dataPort===I.port2){let Wt={data:I,command:O,control:S,timers:x};I=null,O=null,S=null,x=null;try{r.detachDataFacade(Wt.data.port1)}catch{}Wt.timers?.close().catch(()=>{}),Wt.control?.close().catch(()=>{});for(let Kr of[Wt.data.port1,Wt.command.port1])try{Kr.close()}catch{}return}let vt=$.get(Kt.dataPort);if(vt){$.delete(Kt.dataPort);try{r.detachDataFacade(vt.data.port1)}catch{}vt.timers?.close().catch(()=>{}),vt.control.close().catch(()=>{});for(let Wt of[vt.data.port1,vt.command.port1])try{Wt.close()}catch{}}},uk=(Kt=Fr==="reconcile-original"?Fr:"inspect")=>{if(!oe()||Ie!==null)return null;let vt=new MessageChannel,Wt=new MessageChannel,Kr=null,Kc=null;try{Kr=r.openTimersPort({scope:m,generation:yi,signal:b.signal});let Oa=null,gq=K()??null;return Kc=dk(vt.port1,Wt.port1,()=>{},()=>{Oa&&Ug(Oa)}),Oa=Object.freeze({schema:"mdbn-app-collection/1",scope:m,generation:yi,displayName:u,setupMode:Kt,dataPort:vt.port2,controlPort:Wt.port2,...pk,...Kr?{timerPort:Kr.port}:{}}),$.set(vt.port2,{data:vt,command:Wt,control:Kc,timers:Kr}),Y.set(vt.port2,gq),Oa}catch{try{r.detachDataFacade(vt.port1)}catch{}Kr?.close().catch(()=>{}),Kc?.close().catch(()=>{});for(let Oa of[vt.port1,vt.port2,Wt.port1,Wt.port2])Oa.close();return null}},yq=Kt=>{if(!oe()||!Y.has(Kt.dataPort))return null;let vt=K();if(vt===void 0||vt===Y.get(Kt.dataPort))return null;let Wt=uk(Kt.setupMode);return Wt&&Ug(Kt),Wt};Ra=uk,lk=Ug,jg=yq,Y.set(I.port2,mq),e.handoff(Object.freeze({schema:"mdbn-app-collection/1",scope:m,generation:yi,displayName:u,setupMode:Fr,dataPort:I.port2,controlPort:O.port2,...pk,...x?{timerPort:x.port}:{}})),ie(),As()},uq=Object.freeze({scope:m,generation:yi,isCurrent:oe,setForeground:ak,attach:()=>Ra?Ra():null,detach:Ct=>{lk?.(Ct)},renewTimers:Ct=>jg?jg(Ct):null}),fq={get state(){return oe()?q?"needs_unlock":R:"setup_required"},get locked(){return oe()&&q?Object.freeze({...q}):null},get problem(){return oe()?Q:null},get health(){return oe()?Ee:null},get live(){return oe()?!ce:null},get ended(){return oe()?Ie:null},get failure(){return oe()?X:null},connection:uq,close:Fe,subscribe(Ct){return ie(),Ae.add(Ct),()=>{Ae.delete(Ct)}},...f?{unlock:async Ct=>{if(ie(),!q||q.unlocking)throw cr("binding");q={mode:q.mode,unlocking:!0,problem:null},He();try{await r.unlockAccountKey(Ct,{signal:b.signal,onMode:Tt=>{q&&oe()&&(q={...q,mode:Tt})}}),ie()}catch(Tt){if(Tt instanceof pt&&oe()&&q){q={mode:q.mode,unlocking:!1,problem:Tt.reason},He();return}throw await Fe(),Tt}try{await ck(),ie()}catch(Tt){throw await Fe(),Tt}q=null,He()}}:{}};return q||await ck(),ie(),Object.freeze(fq)}catch(ue){throw await Fe(),ue}}}async function Ag(n,e){if(n.schema!=="mdbn-app-collection/1"||Tc.has(n.dataPort)||Tc.has(n.controlPort)||n.dataPort===n.controlPort||!["inspect","approved-new","reconcile-original"].includes(n.setupMode)||n.people!==void 0&&n.people!==!0||n.privateDevice!==void 0&&(n.privateDevice!==!0||n.people!==void 0)||e.signal.aborted||n.timerPort&&(Tc.has(n.timerPort)||n.timerPort===n.dataPort||n.timerPort===n.controlPort))throw cr("binding");Tc.add(n.dataPort),Tc.add(n.controlPort),n.timerPort&&Tc.add(n.timerPort);let t=Object.freeze({...n.scope}),i=n.generation,o=n.setupMode,s=n.people===!0,r=n.dataPort,a=n.controlPort,c=e.signal,l=!1,p=null,d=null,u=null,f,h=()=>{if(!l){l=!0,c.removeEventListener("abort",h);for(let m of[()=>f?.close(),()=>d?.close(),()=>p?.close(),()=>u?.close(),()=>r.close(),()=>a.close()])try{m()}catch{}}};c.addEventListener("abort",h,{once:!0});try{if(u=ey(r,{...t,isCurrent:()=>!l&&!c.aborted}),d=Zm(a,{scope:t,generation:i},{signal:c,isCurrent:()=>!l,onClose:h,...s?{people:!0}:{}}),n.timerPort&&(f=new Ha(IE(n.timerPort,{scope:t,generation:i},{signal:c,onClose:()=>{}}),{criteria:e.timerCriteria??[]})),p=await wr.connect({app:e.app,connector:u,reconnect:!1,signal:c,ledger:d.ledger}),l||c.aborted)throw p.close(),cr("fenced");let m=s?Jm(p,d):void 0;return Object.freeze({client:p,resourceSetup:d.resourceSetup,...m?{people:m}:{},journal:d.journal,scope:t,setupMode:o,close:h,...f?{timers:f}:{},assess:(w,b)=>d.assess(w,b),setForeground:(w,b)=>d.setForeground(w,b)})}catch(m){throw h(),m}}var _2,LD,jD,UD,ND,DD,vu,cr,Tc,q0=C(()=>{"use strict";ri();Od();wu();Wy();iy();Ls();_w();JA();eR();_g();Qs();ss();ty();gu();Ld();_2=1e4,LD=12e4,jD=2e3,UD=5e3,ND=15e3,DD=3,vu=class extends Error{constructor(t){super(`app web collection: ${t}`);this.reason=t;this.name="AppWebCollectionError"}reason},cr=n=>new vu(n);Tc=new WeakSet});function zD(n,e){return Object.freeze({collection:n,isCurrent:e,request:()=>Promise.reject(A("upgrade_required","People is not available for a Private collection opened by this app","people_unsupported"))})}var pn,kg,$D,Mc,T0=C(()=>{"use strict";q0();re();xp();pn=class extends Error{constructor(t){super("SDK application connection unavailable");this.code=t;this.name="ApplicationUiConnectionError"}code},kg=new WeakSet;$D=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,Mc=class{app;signal;current=null;pending=null;opening=null;retiring=null;closing=null;epoch=0;timerCriteria;constructor(e,t,i=[]){this.app=Object.freeze({...e}),this.signal=t,this.timerCriteria=Object.freeze([...i]),t.addEventListener("abort",this.abort,{once:!0})}abort=()=>{this.close().catch(()=>{})};connection(e){let t=this.current?.public;return t?.id===e&&t.isCurrent()?t:null}owned(){return this.current?.public.isCurrent()?this.current.ui:null}adopt(e,t){let i=t.caller,o=t.isCurrent,s=[e.dataPort,e.controlPort,...e.timerPort?[e.timerPort]:[]];if(s.some(y=>!(y instanceof MessagePort))||new Set(s).size!==s.length||s.some(y=>kg.has(y))){for(let y of new Set(s))y instanceof MessagePort&&!kg.has(y)&&(kg.add(y),y.close());return Promise.reject(new pn("application_connection_binding"))}for(let y of s)kg.add(y);let r=y=>{for(let v of s)v.close();return Promise.reject(new pn(y))};if(this.pending||this.current||this.retiring)return r("application_connection_busy");if(this.closing||this.signal.aborted||i.aborted||!o())return r("application_connection_fenced");let a=Object.freeze({...e.scope}),c=e.generation,l=e.displayName;if(e.schema!=="mdbn-app-collection/1"||Object.keys(a).sort().join()!=="account,collection,installation"||Object.values(a).some(y=>!$D.test(y)||y==="00000000-0000-0000-0000-000000000000")||typeof c!="string"||!c||c.length>256||typeof l!="string"||!l.trim()||new TextEncoder().encode(l).length>4096||!["inspect","approved-new","reconcile-original"].includes(e.setupMode))return r("application_connection_binding");let p=e.privateDevice===!0;if(e.privateDevice!==void 0&&(!p||e.people!==void 0))return r("application_connection_binding");if(e.people!==!0&&!p)return r("application_connection_people_unavailable");let d=Object.freeze({...e,scope:a,generation:c,displayName:l}),u=new AbortController,f=this.epoch;this.opening=u;let h=()=>u.abort();i.addEventListener("abort",h,{once:!0});let m=AbortSignal.any([this.signal,u.signal]),w=()=>!m.aborted&&!this.closing&&!this.retiring&&this.epoch===f&&o(),b=null,g=Promise.resolve().then(async()=>{if(!w()||i.aborted)throw new pn("application_connection_fenced");if(b=await Ag(d,{app:this.app,signal:m,timerCriteria:this.timerCriteria}),!w()||i.aborted)throw new pn("application_connection_fenced");if(b.client.collection!==a.collection||b.client.link!=="open")throw new pn("application_connection_binding");if(p?b.people!==void 0:!b.people)throw new pn(p?"application_connection_binding":"application_connection_people_unavailable");let y=b,v=b.people??new vr(y.client,zD(a.collection,()=>w()&&this.current?.ui===y&&y.client.link==="open")),_=Object.freeze({id:a.collection,scope:a,generation:c,displayName:l,records:y.client,files:y.client.files,people:v,...y.timers?{timers:y.timers}:{},isCurrent:()=>w()&&this.current?.ui===y&&y.client.link==="open"});return this.current={public:_,ui:y,lifetime:u},_}).catch(y=>{u.abort(),b?.close();for(let v of s)v.close();throw y}).finally(()=>{i.removeEventListener("abort",h),this.pending===g&&(this.pending=null,this.opening=null)});return this.pending=g,g}retire(){if(this.retiring)return this.retiring;++this.epoch;let e=this.current,t=this.pending;this.opening?.abort(),e?.lifetime.abort();let i=Promise.resolve().then(async()=>{await t?.catch(()=>{}),e?.ui.close(),this.current===e&&(this.current=null)});return this.retiring=i,i.then(()=>{this.retiring===i&&(this.retiring=null)},()=>{}),i}close(){return this.closing?this.closing:(this.closing=Promise.resolve().then(()=>this.retire()),this.signal.removeEventListener("abort",this.abort),++this.epoch,this.opening?.abort(),this.current?.lifetime.abort(),this.closing)}}});function HD(n){if(n.capabilityContractVersion!==2)throw A("upgrade_required","unsupported readiness capability projection","readiness_capability_version");if(!Array.isArray(n.contracts)||n.contracts.length>128||!Array.isArray(n.requiredNativeCapabilities)||n.requiredNativeCapabilities.length>64)throw Vt("unsupported");let e=n.contracts.map(i=>{if(!i||!jc(i.id,256)||!jc(i.version,128)||!WD.test(i.digest))throw Vt("unsupported");return Object.freeze({id:i.id,version:i.version,digest:i.digest})}),t=n.requiredNativeCapabilities.map(i=>{if(!jc(i,128))throw Vt("unsupported");return i});if(new Set(e.map(i=>JSON.stringify([i.id,i.version]))).size!==e.length||new Set(t).size!==t.length||n.typeIssues!==void 0&&n.typeIssues!=="block"&&n.typeIssues!=="degrade")throw Vt("unsupported");return Object.freeze({capabilityContractVersion:2,typeIssues:n.typeIssues??"block",contracts:Object.freeze(e),requiredNativeCapabilities:Object.freeze(t)})}function GD(n){let e=de(n,"path");return typeof e=="string"&&e?e:null}function Lc(n,e){return Object.freeze({reason:n,...n==="fenced"&&e?{detail:e}:{}})}function M0(n){if(!J(n))return;let e=de(n.details,"condition"),t=BD.find(i=>i===e);if(t)return t;if(n.code==="unauthenticated")return"read_unauthenticated";if(n.code==="cancelled")return"read_cancelled"}function L0(n){try{if(J(n)){if(n.code==="unauthenticated"||n.code==="cancelled")return"fenced";if(n.code==="too_large")return"budget";if(n.code==="upgrade_required"||n.code==="forbidden")return"unsupported";if(n.reason==="readiness_changed"||n.reason==="cursor_stale"||n.reason==="cursor_expired")return"changed";if(n.reason==="readiness_busy")return"busy";if(n.reason==="readiness_catalog_response")return"catalog_response"}}catch{}return"unavailable"}function U0(n){let e=n.status;return JSON.stringify([e.mode,e.confirmedThrough,e.headKnown,e.pending,e.holds,e.unresolved,e.connection,e.installing,e.resyncing,e.incidents.map(t=>t.kind),e.confirmedHead])}function N0(n){return n.mode==="local_only"}function Uc(n){return JSON.stringify(n,(e,t)=>typeof t=="bigint"?`${t}n`:t instanceof Uint8Array?[...t]:t)}function S2(n,e,t){return new j0(n,e,t)}var BD,VD,FD,KD,k2,WD,jc,Vt,j0,D0=C(()=>{"use strict";re();un();BD=["binding_invalid","binding_aborted","binding_not_current","readiness_closed","read_aborted","session_closed","session_replaced","session_collection_mismatch","read_unauthenticated","read_cancelled"],VD=4096,FD=2*1024*1024,KD=64,k2=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,WD=/^sha256:[0-9a-f]{64}$/,jc=(n,e=4096)=>typeof n=="string"&&!!n.trim()&&new TextEncoder().encode(n).length<=e,Vt=(n,e)=>A(n==="fenced"?"unauthenticated":n==="budget"?"too_large":"unavailable","collection readiness unavailable",{reason:`readiness_${n}`,...e?{details:{condition:e}}:{}});j0=class{constructor(e,t,i){this.client=e;if(this.declared=HD(t),!k2.test(i.collection)||i.collection==="00000000-0000-0000-0000-000000000000"||!k2.test(i.generation))throw Vt("fenced","binding_invalid");this.binding=Object.freeze({collection:i.collection,generation:i.generation,signal:i.signal,isCurrent:i.isCurrent.bind(i)}),this.readSignal=AbortSignal.any([this.binding.signal,this.lifetime.signal]),this.check(),this.binding.signal.addEventListener("abort",this.abort,{once:!0})}client;declared;binding;lifetime=new AbortController;readSignal;listeners=new Set;snapshotValue=Object.freeze({checking:!1,assessment:null,problem:null});watch=null;stops=[];pending=null;epoch=0;dirty=!1;scheduled=!1;retries=0;failures=0;closed=!1;lastStatus=null;assessedSession;assessedEpoch;assessedCatalog=null;probing=null;probeAgain=!1;abort=()=>{this.close()};getSnapshot(){if(this.snapshotValue.assessment)try{this.check(void 0,this.assessedSession,this.assessedEpoch)}catch(e){let t=L0(e);t==="fenced"&&!this.closed&&!this.binding.signal.aborted&&this.binding.isCurrent()===!0&&(t="changed"),this.retryLater(t)||this.publish({checking:!1,assessment:null,problem:Lc(t,M0(e))})}return this.snapshotValue}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}publish(e){this.snapshotValue=Object.freeze(e);for(let t of this.listeners)try{t()}catch{}}check(e,t,i){e?.throwIfAborted();let o=this.fenceDetail(e);if(o)throw Vt("fenced",o);if(t?.closed)throw Vt("fenced","session_closed");if(t&&t!==this.client.currentSession())throw Vt("fenced","session_replaced");if(t&&t.hello.collection!==this.binding.collection)throw Vt("fenced","session_collection_mismatch");if(i!==void 0&&(i!==this.epoch||this.watch?.state!=="active"))throw Vt("changed")}fenceDetail(e){if(this.binding.signal.aborted)return"binding_aborted";if(this.closed)return"readiness_closed";if(e?.aborted)return"read_aborted";if(this.binding.isCurrent()!==!0)return"binding_not_current"}invalidate=()=>{if(this.closed)return;if(this.pending||!this.snapshotValue.assessment||this.assessedCatalog===null||this.client.link!=="open"){this.recheck();return}if(this.probing){this.probeAgain=!0;return}let e=this.snapshotValue.assessment,t=this.assessedCatalog,i=this.client.describe({signal:this.readSignal}).then(o=>{this.closed||this.snapshotValue.assessment!==e||Uc(o)!==t&&this.recheck()},()=>{this.closed||this.recheck()});this.probing=i.finally(()=>{this.probing=null,this.probeAgain&&!this.closed&&(this.probeAgain=!1,this.invalidate())})};recheck(){this.closed||(this.epoch++,this.dirty=!0,this.publish({checking:!0,assessment:null,problem:null}),this.schedule())}schedule(){if(this.closed||this.pending||this.scheduled||!this.dirty||this.watch?.state!=="active"||this.client.link!=="open")return;this.scheduled=!0;let e=()=>{this.scheduled=!1,!this.closed&&this.dirty&&!this.pending&&this.watch?.state==="active"&&this.client.link==="open"&&this.refresh(void 0,!0).catch(()=>{})};this.retries?setTimeout(e,Math.min(5e3,100*2**this.retries,this.retrySince===null?5e3:Math.max(0,15e3-(Date.now()-this.retrySince)))):queueMicrotask(e)}retrySince=null;retryLater(e,t=!1){if(this.closed)return!1;if((e==="busy"||e==="changed")&&(this.retrySince??=Date.now(),Date.now()-this.retrySince>=15e3))return this.dirty=!1,this.publish({checking:!1,assessment:null,problem:Lc("busy_timeout")}),!0;if(e==="unavailable"&&t&&this.failures<5)this.failures++;else if(e!=="changed"&&e!=="busy")return!1;return this.dirty=!0,this.retries=Math.min(this.retries+1,6),this.publish({checking:!0,assessment:null,problem:null}),this.schedule(),!0}attach(){this.watch||(this.watch=this.client.watchChanges(this.invalidate),this.stops.push(this.watch.subscribe(this.invalidate),this.client.onLink(this.invalidate),this.client.onStatus(e=>{let t=U0(this.client);(t!==this.lastStatus||N0(e))&&(this.lastStatus=t,this.invalidate())})))}start(e){return this.refresh(e)}refresh(e,t=!1){try{if(this.check(e),this.pending)throw Vt("busy")}catch(a){return Promise.reject(a)}t||(this.retrySince=null);let i=AbortSignal.any([this.binding.signal,this.lifetime.signal,...e?[e]:[]]),o,s,r=Promise.resolve().then(async()=>{this.check(i),this.attach();let a=await this.client.readyForRead(i);this.check(i,a),await this.watch.ready,this.check(i,a);let c=this.epoch;this.dirty=!1,this.check(i,a,c);let l=await this.inventory(i,a,c),p=await this.client.describe({signal:this.readSignal});this.check(i,a,c);let d=this.evaluate(p,a),u=Uc(p);for(let w of d.paths){let b=l.find(y=>y.path===w);if(!b)throw Vt("changed");let g=await this.client.resources.get(w,{signal:this.readSignal});if(this.check(i,a,c),g.path!==b.path||g.revision!==b.revision||g.size!==b.size||g.state!=="confirmed")throw Vt("changed")}let f=await this.inventory(i,a,c);if(JSON.stringify(l)!==JSON.stringify(f))throw Vt("changed");this.check(i,a,c);let h=Object.freeze({collection:this.binding.collection,generation:this.binding.generation,resources:Object.freeze(f)}),m=Object.freeze({status:d.status,problem:d.reason?Lc(d.reason):null,witness:h,...d.unavailable.length?{unavailableTypes:Object.freeze(d.unavailable)}:{}});return o=a,s=c,this.retries=0,this.failures=0,this.retrySince=null,this.assessedSession=a,this.assessedEpoch=c,this.assessedCatalog=u,this.publish({checking:!1,assessment:m,problem:m.problem}),this.check(i,a,c),m}).catch(a=>{let c=i.aborted||this.closed?"fenced":L0(a);throw this.retryLater(c,t)||this.publish({checking:!1,assessment:null,problem:Lc(c,this.fenceDetail(i)??M0(a))}),a});return this.pending=r,this.publish({checking:!0,assessment:null,problem:null}),r.finally(()=>{this.pending===r&&(this.pending=null),this.schedule()}).catch(()=>{}),r.then(a=>{try{if(this.check(i,o,s),this.snapshotValue.assessment!==a)throw Vt("changed");return a}catch(c){let l=i.aborted?"fenced":L0(c);throw this.snapshotValue.assessment===a&&!this.retryLater(l)&&this.publish({checking:!1,assessment:null,problem:Lc(l,this.fenceDetail(i)??M0(c))}),c}})}async inventory(e,t,i){let o=[],s=new Set,r,a="",c=0;for(let l=0;l<KD;l++){this.check(e,t,i);let p=await this.client.resources.list({text:!1,limit:128,...r?{cursor:r}:{},signal:this.readSignal});this.check(e,t,i);for(let d of p.resources){if(!jc(d.path)||d.path<=a||!jc(d.revision,128)||!Number.isSafeInteger(d.size)||d.size<0||d.state!=="confirmed")throw Vt("catalog_response");a=d.path;let u=Object.freeze({path:d.path,revision:d.revision,size:d.size,state:d.state});if(c+=new TextEncoder().encode(JSON.stringify(u)).length,o.length>=VD||c>FD)throw Vt("budget");o.push(u)}if(p.complete===!0&&p.cursor===void 0)return o;if(p.complete!==!1||!jc(p.cursor)||s.has(p.cursor))throw Vt("catalog_response");s.add(p.cursor),r=p.cursor}throw Vt("budget")}evaluate(e,t){let i=e.issues.filter(d=>d.severity==="error"),o=new Set;for(let d of i){let u=GD(d.details);if(!u)return{status:"incompatible",reason:"catalog_invalid",paths:[],unavailable:[]};o.add(u)}let s={status:"incompatible",reason:"catalog_invalid",paths:[],unavailable:[]};if(this.declared.requiredNativeCapabilities.some(d=>!t.hello.grant.capabilities.includes(d)))return{status:"incompatible",reason:"capability_missing",paths:[],unavailable:[]};let r=new Set,a=new Set,c=new Set;for(let d of e.contracts){let u=JSON.stringify([d.id,d.version]);if(a.has(u))return{status:"incompatible",reason:"catalog_response",paths:[],unavailable:[]};a.add(u)}for(let d of e.types){if(c.has(d.name))return{status:"incompatible",reason:"catalog_response",paths:[],unavailable:[]};c.add(d.name)}let l,p=[];for(let d of this.declared.contracts){let u=e.contracts.find(f=>f.id===d.id&&f.version===d.version);if(!u){l??="contract_missing";continue}if(u.digest!==d.digest)return{status:"incompatible",reason:"contract_mismatch",paths:[],unavailable:[]};if(r.add(u.path),o.has(u.path))return s;if(!u.implementedBy.length){l??="implementation_missing";continue}for(let f of u.implementedBy){let h=e.types.find(m=>m.name===f);if(!h||!h.implements.some(m=>m.contract===d.id&&m.version===d.version))return{status:"incompatible",reason:"catalog_response",paths:[],unavailable:[]};if(r.add(h.path),o.has(h.path)){if(this.declared.typeIssues!=="degrade")return s;p.some(m=>m.name===h.name)||p.push(Object.freeze({name:h.name,path:h.path,contract:Object.freeze({id:d.id,version:d.version}),problem:Object.freeze({code:"readiness_type_invalid"})}))}}}return{status:l?"setup_required":"ready",...l?{reason:l}:{},paths:[...r].sort(),unavailable:p}}async close(){if(!this.closed){this.closed=!0,this.dirty=!1,this.lifetime.abort(),this.binding.signal.removeEventListener("abort",this.abort);for(let e of this.stops.splice(0))e();this.watch?.(),this.watch=null,this.publish({checking:!1,assessment:null,problem:Lc("fenced",this.fenceDetail())})}await this.pending?.catch(()=>{})}}});function JD(n){let e=o=>o?Object.freeze({code:`readiness_${o.reason}`,...o.detail?{detail:o.detail}:{}}):null,t=e(n.problem),i=n.assessment?.unavailableTypes;return Object.freeze({checking:n.checking,assessment:n.assessment?Object.freeze({status:n.assessment.status,problem:e(n.assessment.problem),...i?.length?{unavailableTypes:i}:{}}):null,problem:t})}var P2,YD,_u,Br,Sg,x2=C(()=>{"use strict";Tp();re();D0();P2=["configuration","files"],YD=["people","notifications"],_u=class extends Error{constructor(t,i){super("SDK application readiness unavailable");this.code=t;this.detail=i;this.name="ApplicationReadinessError"}code;detail},Br=(n,e=!1,t)=>Object.freeze({checking:e,assessment:null,problem:n?Object.freeze({code:n,...t?{detail:t}:{}}):null});Sg=class{connection;signal;observed;native;sources;listeners=new Set;stops=[];pending=null;closing=null;checking=!1;closed=!1;advisory=Promise.resolve();lastReady=null;constructor(e){this.connection=e.connection,this.signal=e.signal,this.observed=e.isCurrent,this.sources=Object.freeze({configuration:e.configuration,files:e.files,people:e.people,notifications:e.notifications}),this.native=e.nativeRequirements?S2(this.connection.records,e.nativeRequirements,{collection:this.connection.id,generation:this.connection.generation,signal:this.signal,isCurrent:()=>this.current()}):null,this.native&&this.stops.push(this.native.subscribe(this.changed));for(let t of Object.values(this.sources))t&&this.stops.push(t.subscribe(this.changed));this.signal.addEventListener("abort",this.abort,{once:!0})}fenceDetail(){try{return this.signal.aborted?"scope_aborted":this.closed?"scope_closed":this.observed()!==!0?"observer_not_current":this.connection.isCurrent()?this.connection.records.collection!==this.connection.id?"collection_mismatch":null:"connection_not_current"}catch{return"currentness_check_failed"}}current(){return this.fenceDetail()===null}connectionProblem(){if(!this.closed&&!this.signal.aborted&&this.connection.records.collection===this.connection.id&&this.connection.records.link==="closed"){let e=this.connection.records.linkProblem;if(J(e)){let t=Us(e);return t&&t.key!=="unknown"?t.key:e.code}}return"readiness_fenced"}changed=()=>{for(let e of[...this.listeners])try{e()}catch{}};abort=()=>{this.close().catch(()=>{})};subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getSnapshot(){let e=this.current(),t=Br(e?"readiness_unsupported":"readiness_fenced"),i=t;if(e&&this.native){let u=this.native.getSnapshot(),f=u.assessment?.witness,h=f&&f.collection!==this.connection.id?"native_witness_collection_mismatch":f&&f.generation!==this.connection.generation?"native_witness_generation_mismatch":null;i=h?Br("readiness_fenced",!1,h):JD(u)}let o=u=>{if(!e)return t;let f=this.sources[u];if(!f)return Br(`${u}_unsupported`);try{let h=f.getSnapshot();return Object.freeze({checking:h.checking,assessment:h.assessment?Object.freeze({...h.assessment,problem:h.assessment.problem?Object.freeze({...h.assessment.problem}):null}):null,problem:h.problem?Object.freeze({...h.problem}):null})}catch{return Br(`${u}_unavailable`)}},s=Object.freeze({capabilities:i,contracts:i,configuration:o("configuration"),files:o("files"),people:o("people"),notifications:o("notifications")}),r=[s.capabilities,s.contracts,s.configuration,s.files],a=e&&(this.checking||r.some(u=>u.checking)),c=null,l=null;if(!e)l=Object.freeze({code:"readiness_fenced"});else if(!a){let u=["capabilities","contracts",...P2].find(f=>s[f].problem);if(l=u?s[u].problem:null,u&&l?.code==="readiness_fenced"&&!l.detail&&(l=Object.freeze({...l,detail:`${u}_facet`})),r.every(f=>f.assessment!==null)){let f=s.configuration.assessment?.status==="setup_required",h=y=>y.assessment?.status==="incompatible"&&!(f&&y===i&&y.assessment.problem?.code==="readiness_contract_mismatch"),m=r.find(h),w=r.find(y=>y.assessment?.status==="setup_required"),b=m??w,g=i.assessment?.unavailableTypes;c=Object.freeze({status:m?"incompatible":w?"setup_required":"ready",problem:b?.assessment?.problem??null,...g?.length?{unavailableTypes:g}:{}})}}let p=this.fenceDetail();if(p)return this.lastReady=null,Object.freeze({checking:!1,assessment:null,problem:Object.freeze({code:this.connectionProblem(),detail:p}),facets:Object.freeze({capabilities:Br("readiness_fenced",!1,p),contracts:Br("readiness_fenced",!1,p),configuration:Br("readiness_fenced",!1,p),files:Br("readiness_fenced",!1,p),people:Br("readiness_fenced",!1,p),notifications:Br("readiness_fenced",!1,p)})});let d=!l||/_(changed|busy)$/.test(l.code);if(l===null&&c!==null&&!a)this.lastReady=Object.freeze({checking:a,assessment:c,problem:l,facets:s});else{if(this.lastReady&&d&&(a||c===null)&&(this.lastReady.assessment?.status==="ready"||!this.checking))return Object.freeze({...this.lastReady,facets:s});this.lastReady=null}return Object.freeze({checking:a,assessment:c,problem:l,facets:s})}refresh(e={}){let t=e.signal,i=this.fenceDetail()??(t?.aborted?"caller_aborted":null);if(i)return Promise.reject(new _u("application_readiness_fenced",i));if(this.pending)return Promise.reject(new _u("application_readiness_busy"));this.checking=!0;let o=Promise.resolve().then(async()=>{if(!this.current())return this.getSnapshot();await this.advisory;let s=[],r=async(c,l)=>{try{await l()}catch(p){let d=!1;try{d=c.getSnapshot().checking===!0}catch{}if(!d||!this.current())throw p;s.push(p)}},a=this.native;a&&await r(a,()=>a.start());for(let c of P2){let l=this.sources[c];if(!this.current())break;l&&await r(l,()=>l.refresh())}if(await this.reassessAfterSetup(),s.length)throw s[0];return this.getSnapshot()}).finally(()=>{if(this.pending!==o)return;this.pending=null,this.checking=!1;let s=(async()=>{for(let r of YD){let a=this.sources[r];if(!this.current())break;a&&await a.refresh().catch(()=>{})}})();this.advisory=s,this.changed()}).then(()=>this.getSnapshot());return this.pending=o,this.changed(),o.then(s=>{let r=this.fenceDetail()??(t?.aborted?"caller_aborted":null);if(r)throw new _u("application_readiness_fenced",r);return s})}async reassessAfterSetup(){if(!this.native||!this.current())return;let e=this.native.getSnapshot(),t=null;try{t=this.sources.configuration?.getSnapshot()??null}catch{}e.checking||e.assessment?.status!=="setup_required"||t?.checking||t?.assessment?.status!=="ready"||await this.native.start().catch(i=>{if(!(J(i)&&i.reason==="readiness_busy"))throw i})}close(){return this.closing?this.closing:(this.closed=!0,this.checking=!1,this.signal.removeEventListener("abort",this.abort),this.closing=Promise.resolve().then(async()=>{for(let e of this.stops.splice(0))e();for(let e of Object.values(this.sources))await e?.close();await this.native?.close(),await this.pending?.catch(()=>{}),await this.advisory,this.listeners.clear()}),this.changed(),this.closing)}}});function XD(n){let e=new Set,t=[],i=[];for(let o of n.review?.packs??[]){if(o.status!=="conflict"&&o.status!=="downgrade")continue;let s=o.installedVersion?Ns(o.installedVersion,o.version):"unknown";s==="installed_newer"&&!o.resources.some(r=>r.action==="conflict")?(e.add(o.id),i.push(Object.freeze({id:o.id,version:o.version,installedVersion:o.installedVersion}))):s==="installed_newer_major"&&t.push(o.id)}return Object.freeze({kept:Object.freeze(i),compatible:e,major:Object.freeze(t)})}function ZD(n,e){let t=n,i=t.provisions?.type_packs;return!e.size||!Array.isArray(i)?n:{...t,provisions:{...t.provisions,type_packs:i.filter(o=>!(typeof o?.manifest?.id=="string"&&e.has(o.manifest.id)))}}}function C2(n){return new Proxy({},{get(e,t){let i=Reflect.get(n,t,n);return typeof i!="function"?i:async(...o)=>{let s=o.find(a=>a instanceof AbortSignal),r=Date.now()+QD;for(let a=25;;a=Math.min(a*2,500))try{return await i.apply(n,o)}catch(c){if(!(c instanceof Ei&&c.reason==="busy")||!s)throw c;if(Date.now()+a>r)throw Xe("busy_timeout");await e4(a,s)}}}})}function O2(n,e){let t=Object.freeze({...n,scope:Object.freeze({...n.scope}),journal:C2(n.journal)});if(e&&(e=C2(e)),Object.values(t.scope).some($=>!I2.test($)||/^0{8}-0{4}-0{4}-0{4}-0{12}$/.test($))||!I2.test(t.generation)||!["inspect","approved-new","reconcile-original"].includes(t.setupMode))throw Xe("binding");let i=JSON.stringify([t.scope.account,t.scope.installation,t.scope.collection]),o=new AbortController,s=AbortSignal.any([t.signal,o.signal]),r=new Set,a=bo(),c=null,l=null,p=!1,d,u=null,f=!1,h=!1,m=0,w=!1,b=!1,g=null,y=null,v=()=>{try{return JSON.stringify([t.client.link,U0(t.client)])}catch{return null}},_=[],k=new WeakMap;function S($,Y){if($?.throwIfAborted(),p||s.aborted||t.isCurrent()!==!0||JSON.stringify([t.journal.scope.account,t.journal.scope.installation,t.journal.scope.collection])!==i||Y&&(Y.closed||t.client.currentSession()!==Y||Y.hello.collection!==t.scope.collection))throw Xe("fenced")}function x($){a=Object.freeze($);for(let Y of r)try{Y()}catch{}}function P(){if(p)return;let $=v();if($!==null&&$===y)return;if(y=$,c||!a.assessment||u===null||t.client.link!=="open"){I();return}if(f){h=!0;return}f=!0;let Y=a,K=u;t.client.describe({signal:s}).then(Q=>{!p&&a===Y&&Uc(Q)!==K&&I()},()=>{p||I()}).finally(()=>{f=!1,h&&!p&&(h=!1,y=null,P())})}function I(){p||(w=!0,c||x(bo(null,!0)),O())}function O(){p||c||b||!w||(b=!0,setTimeout(()=>{if(b=!1,p||c||!w)return;let $=te(!1,{},void 0,!0);g=c,$.catch(()=>{})},m?Math.min(5e3,250*2**m):50))}function R(){if(a.assessment)try{S(void 0,d)}catch{p||s.aborted||t.isCurrent()!==!0?x(bo("configuration_fenced")):(w=!0,y=null,x(bo(null,!0)),O())}return a}async function q($,Y,K){let Q=await t.client.awaitReceipt($.mutationId,{timeoutMs:12e4,signal:s});if(S(Y,K),Q.mutation!==$.mutationId||Q.state!=="confirmed"||Q.status!=="applied"||(Q.conflicts?.length??0)!==0||Q.published==="publishing"||Q.published==="not_published")throw Xe("recovery_required");return Q}async function j($,Y,K){let Q,Ae=0,oe=0,ie=new Set,He=new Set,Fe=new TextEncoder;for(let Ft=0;Ft<64;Ft++){S(Y,K);let Ee=await t.client.resources.list({text:!1,limit:128,...Q===void 0?{}:{cursor:Q},signal:s});if(S(Y,K),Ee.resources.length>128)throw Xe("recovery_required");for(let nt of Ee.resources){let dr=Fe.encode(nt.path).length;if(Ae++,oe+=dr+128,!nt.path||dr>4096||He.has(nt.path)||nt.state!=="confirmed"||!z0.test(nt.revision)||!Number.isSafeInteger(nt.size)||nt.size<0||Ae>4096||oe>2*1024*1024||$.has(nt.path))throw Xe("recovery_required");He.add(nt.path)}if(Ee.complete===!0&&Ee.cursor===void 0)return;if(Ee.complete!==!1||!Ee.resources.length||typeof Ee.cursor!="string"||!Ee.cursor||Fe.encode(Ee.cursor).length>4096||ie.has(Ee.cursor))throw Xe("recovery_required");ie.add(Ee.cursor),Q=Ee.cursor}throw Xe("recovery_required")}async function B($,Y,K){let Q=$.version===2?$.plan.readback:$.plan.resourceReadback,Ae=new Set(Q.filter(oe=>oe.doc===null).map(oe=>oe.path));Ae.size&&await j(Ae,Y,K);for(let oe of Q){if(oe.doc===null)continue;let ie=await t.client.resources.get(oe.path,{signal:s});if(S(Y,K),ie.path!==oe.path||ie.text!==oe.doc||ie.state!=="confirmed")throw Xe("recovery_required")}if($.version!==2)for(let oe of $.plan.sources){let ie=await t.client.get(oe.id,{signal:s});if(S(Y,K),ie.id!==oe.id||ie.path!==oe.path||ie.state.state!=="confirmed"||ie.state.hold||ie.state.unresolved)throw Xe("recovery_required")}}async function D($,Y,K){return await q($,Y,K),$.phase==="attempted"&&($=$.version===2?await t.journal.recordConfirmed($.mutationId,s):await t.journal.recordResourceConfirmed($.mutationId,s),S(Y,K)),$.phase==="verified"||(await B($,Y,K),$.phase==="confirmed"&&($=$.version===2?await t.journal.recordVerified($.mutationId,s):await t.journal.recordResourceVerified($.mutationId,s),S(Y,K))),$}async function X($,Y){let K=await t.journal.load(s);if(S($,Y),!K)return{journaled:!1,previous:null};if(K=Zt(K,t.scope),K.version===1||K.phase==="prepared")throw Xe("recovery_required");if(K.phase==="attempted"&&(K.version===3||K.version===4)&&t.journal.recordResourceRejected){let Q=await t.client.awaitReceipt(K.mutationId,{timeoutMs:12e4,signal:s});S($,Y),Q.mutation===K.mutationId&&Q.state==="rejected"&&(K=Zt(await t.journal.recordResourceRejected(K.mutationId,s),t.scope),S($,Y))}if(K.version===1)throw Xe("recovery_required");return K.phase==="rejected"?{journaled:!0,previous:K.version===4?K.previous:null}:{journaled:!0,previous:await D(K,$,Y)}}async function V($,Y){let K=t.compiledManifest.manifest,Q=await $0(e.assess(K,s,$),$),Ae=Q;Q.status==="conflict"&&!Q.review&&(Ae=await e.assess(K,s,Oi({})));let oe=XD(Ae);if(!oe.compatible.size)return{assessed:Q,manifest:K,newer:oe};let ie=ZD(K,oe.compatible),He=Y?$??Oi({}):$;return Q=await $0(e.assess(ie,s,He),He),{assessed:Q,manifest:ie,newer:oe}}async function U($,Y,K={}){S(Y);let Q=await t.client.readyForRead(s);S(Y,Q),_.length||(y=v(),_.push(t.client.onStatus(ko=>{N0(ko)&&(y=null),P()}),t.client.onLink(P))),w=!1;let{journaled:Ae,previous:oe}=await X(Y,Q);if(!e)throw Xe("unsupported");let ie=null;try{ie=Uc(await t.client.describe({signal:s}))}catch{}S(Y,Q);let He=await V(K.decisions,!1),Fe=He.assessed,Ft=He.manifest;if(S(Y,Q),!z0.test(Fe.assessmentDigest)||!["current","provision","conflict"].includes(Fe.status))throw Xe("response");if(K.expected!==void 0&&Fe.assessmentDigest!==K.expected)throw B0();let Ee=!Ae&&t.setupMode==="approved-new";if(Fe.status==="provision"&&($||Ee)){if(t.setupMode==="reconcile-original")throw Xe("recovery_required");if(!(t.compiledManifest.operations.includes("apply_collection_setup")||t.compiledManifest.operations.includes("apply_type_pack"))||!Q.hello.grant.capabilities.includes("definitions.manage"))throw Xe("not_authorized");let ko=K.records??[];if(ko.length&&!Q.hello.grant.capabilities.includes("records.create"))throw Xe("not_authorized");let vs=$t(await $0(e.apply(Ft,Fe.assessmentDigest,s,K.decisions),K.decisions));if(S(Y,Q),vs.assessmentDigest!==Fe.assessmentDigest)throw Xe("response");if(vs.sources.length)throw Xe("unsupported_source_provision");let Dn=ko.length?$t({...vs,sources:ko.map(Ui=>({id:crypto.randomUUID(),path:Ui.path,document:Ui.document}))}):vs,dn;if(oe){if(!t.journal.prepareResourceRound)throw Xe("recovery_required");dn=await t.journal.prepareResourceRound(Dn,oe.mutationId,s)}else dn=await t.journal.prepareResources(Dn,s);if(S(Y,Q),dn=Zt(dn,t.scope),dn.version!==3&&dn.version!==4||dn.phase!=="prepared"||JSON.stringify(dn.plan)!==JSON.stringify(Dn))throw Xe("recovery_required");let So=Zt(await t.journal.recordResourceAttempt(dn.mutationId,s),t.scope);if(S(Y,Q),So.version!==3&&So.version!==4||So.mutationId!==dn.mutationId||So.phase!=="attempted"||JSON.stringify(So.plan)!==JSON.stringify(Dn))throw Xe("recovery_required");let Bc=[...Dn.resourceOps,...Dn.sources.map(Ui=>({kind:"create",id:Ui.id,path:Ui.path,document:Ui.document}))],xa=await t.client.submit(Bc,{mutationId:dn.mutationId,wait:"confirmed",signal:s});if(S(Y,Q),xa.mutationId!==dn.mutationId)throw Xe("recovery_required");let _s;try{_s=await xa.confirmed}catch(Ui){throw S(Y,Q),xa.receipt.state!=="rejected"||!t.journal.recordResourceRejected?Ui:(await t.journal.recordResourceRejected(dn.mutationId,s),S(Y,Q),B0(dn.mutationId,Ui))}if(S(Y,Q),_s.state!=="confirmed"||_s.status!=="applied"||(_s.conflicts?.length??0)!==0)throw Xe("recovery_required");await D(So,Y,Q),w=!1,y=v();try{ie=Uc(await t.client.describe({signal:s}))}catch{ie=null}if(Fe=await e.assess(Ft,s),S(Y,Q),Fe.status!=="current"||!z0.test(Fe.assessmentDigest))throw Xe("recovery_required")}let nt=Fe.status==="conflict"&&He.newer.major.length>0,dr=Fe.status==="conflict"?nt?"installed_newer":"setup_conflict":null,_o=dr?Object.freeze({code:dr}):null,Ao=Object.freeze({status:Fe.status==="current"?"ready":nt?"incompatible":"setup_required",problem:_o});d=Q,u=ie;let Vr=Object.freeze({checking:!1,assessment:Ao,problem:_o});return m=0,x(w?bo(null,!0):Vr),S(Y,Q),Vr}function ce($={}){try{S($.signal)}catch(Q){return Promise.reject(Q)}let Y=c,K=(Y?Y.then(()=>{},()=>{}):Promise.resolve()).then(()=>ee($));return c=K,K.finally(()=>{c===K&&(c=null)}).catch(()=>{}),K}async function ee($){let Y=fy($.records),K=Oi($.adopt===void 0?{}:{adopt:$.adopt}),Q=AbortSignal.any([s,...$.signal?[$.signal]:[]]),Ae=await t.client.readyForRead(s);if(S(Q,Ae),await X(Q,Ae),!e)throw Xe("unsupported");let{assessed:oe,newer:ie}=await V(K,!0);if(S(Q,Ae),!oe.review)throw Xe("response");let He=[];if(oe.status!=="current")for(let Ee of Y){let nt=await t.client.find({path:Ee.path},{signal:s});S(Q,Ae),He.push({path:Ee.path,free:nt===null})}let Fe=Ae.hello.grant.capabilities,Ft=Bd(oe,{records:He,canManage:Fe.includes("definitions.manage")&&(t.compiledManifest.operations.includes("apply_collection_setup")||t.compiledManifest.operations.includes("apply_type_pack")),canCreateRecords:Fe.includes("records.create"),newer:ie});return k.set(Ft,Object.freeze({decisions:K,records:Y.filter(Ee=>He.some(nt=>nt.path===Ee.path&&nt.free))})),Ft}function te($,Y={},K,Q=!1){try{S(Y.signal)}catch(ie){return Promise.reject(ie)}if(c&&c===g){let ie=c;return ie.then(()=>{},()=>{}).then(()=>c&&c!==ie?Promise.reject(Xe("busy")):te($,Y,K))}if(c)return Promise.reject(Xe("busy"));let Ae=AbortSignal.any([s,...Y.signal?[Y.signal]:[]]),oe=Promise.resolve().then(()=>U($,Ae,K)).catch(ie=>{let He=s.aborted||Ae.aborted,Fe=J(ie)&&ie.reason==="configuration_busy_timeout";Fe&&(w=!1);let Ft=!He&&!Fe&&(w||R2(ie));throw Ft&&R2(ie)&&(w=!0,m=Math.min(m+1,4)),!He&&!Fe&&!w&&Q&&m<5&&!p&&t.isCurrent()===!0&&(m++,w=!0,Ft=!0),x(Ft?bo(null,!0):bo(He?"configuration_fenced":Fe?"configuration_busy_timeout":"configuration_unavailable")),ie});return c=oe,x(bo(null,!0)),oe.finally(()=>{c===oe&&(c=null),g===oe&&(g=null),O()}).catch(()=>{}),oe.then(ie=>(S(Ae,d),ie))}let Ie=()=>{if(!l){p=!0,t.signal.removeEventListener("abort",tt),o.abort();for(let Y of _.splice(0))Y();x(bo("configuration_fenced"));let $=c;l=Promise.resolve().then(async()=>{await $})}return l},tt=()=>{Ie().catch(()=>{})};return t.signal.addEventListener("abort",tt,{once:!0}),Object.freeze({getSnapshot:R,subscribe($){return r.add($),()=>{r.delete($)}},assess:$=>te(!1,$),configure:$=>te(!0,$),plan:ce,async apply($,Y={}){let K=k.get($);if(!K)throw new TypeError("setup.apply needs a plan returned by setup.plan");if($.refusal)throw A($.refusal.code==="setup_conflict"?"conflict":$.refusal.code==="installed_newer"?"upgrade_required":"forbidden",$.refusal.message,$.refusal.code);if($.status==="current"){await te(!1,Y,{decisions:K.decisions,expected:$.digest});return}await te(!0,Y,{decisions:K.decisions,expected:$.digest,records:K.records})},close:Ie})}var I2,z0,Xe,B0,$0,QD,e4,R2,bo,E2=C(()=>{"use strict";re();Qs();D0();ss();th();hy();I2=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,z0=/^sha256:[0-9a-f]{64}$/,Xe=n=>A("unavailable","application configuration unavailable",`configuration_${n}`),B0=(n,e)=>new ne(A("conflict","This collection changed since the setup was reviewed. Review it again.","setup_changed").toProblem(),{...n?{mutationId:n}:{},...e===void 0?{}:{cause:e}}),$0=async(n,e)=>{try{return await n}catch(t){throw e?.adopt&&Object.keys(e.adopt).length&&J(t,"unavailable")&&t.reason==="resource_setup_unavailable"?B0(void 0,t):t}};QD=15e3,e4=(n,e)=>new Promise((t,i)=>{if(e.aborted){i(e.reason);return}let o=()=>{clearTimeout(s),i(e.reason)},s=setTimeout(()=>{e.removeEventListener("abort",o),t()},n);e.addEventListener("abort",o,{once:!0})});R2=n=>J(n)&&n.reason==="configuration_busy",bo=(n=null,e=!1)=>Object.freeze({checking:e,assessment:null,problem:n?Object.freeze({code:n}):null})});function q2(n){return{issuer:n.issuer,subject:n.subject,name:n.name,...n.accountId===void 0?{}:{account_id:n.accountId}}}function T2(n){let e=n.scope,t=e.account,i=e.installation,o=e.collection,s=n.generation,r=n.signal,a=n.people,c=n.isCurrent.bind(n),l=typeof a?.current=="function"?a.current.bind(a):void 0,p=typeof a?.members=="function"?a.members.bind(a):void 0,d=new Set,u=Sa(null),f=!1,h=!1,m=null;function w(){try{return f||r.aborted||c()!==!0?!1:!f&&!r.aborted&&n.scope===e&&n.generation===s&&n.signal===r&&n.people===a&&!!s&&s.length<=256&&[t,i,o].every(k=>typeof k=="string"&&!!k&&k.length<=128)&&e.account===t&&e.installation===i&&e.collection===o}catch{return!1}}function b(k){u=w()?k:wo;for(let S of[...d])try{S()}catch{}w()||(u=wo)}function g(){return w()||(u=wo),u}function y(){if(!f){f=!0,r.removeEventListener("abort",y),u=wo;for(let k of[...d])try{k()}catch{}d.clear()}}r.addEventListener("abort",y,{once:!0}),r.aborted&&y();function v(k,S){return!w()||S?.aborted?Promise.reject(Au()):new Promise((x,P)=>{let I=!1,O=(j,B)=>{I||(I=!0,S?.removeEventListener("abort",R),r.removeEventListener("abort",R),d.delete(q),B!==void 0?P(B):x(j))},R=()=>O(void 0,Au()),q=()=>{w()||R()};d.add(q),S?.addEventListener("abort",R,{once:!0}),r.addEventListener("abort",R,{once:!0}),k.then(()=>{!w()||S?.aborted?R():O(g())},()=>O(void 0,Au())),(!w()||S?.aborted)&&R()})}function _(k={}){let S=k.signal;if(!w()||S?.aborted)return Promise.reject(Au());if(m)return Promise.reject(A("unavailable","People readiness READ is occupied","people_readiness_busy"));let x=Promise.resolve().then(async()=>{if(!w())return wo;if(!l||!p)return Sa("people_unsupported");try{let I=await l({signal:r});if(!w()||(Zl("identity",{...q2(I),...I.personSettingsUrl===void 0?{}:{person_settings_url:I.personSettingsUrl}}),!w()))return wo;let O=await p({signal:r});return w()?!Array.isArray(O)||O.length>1e3?Sa("people_response"):(Zl("members",{members:Array.from(O,R=>({...q2(R),role:R.role}))}),w()?t4:wo):wo}catch{return Sa(w()?"people_unavailable":"people_fenced")}});m=x,b(Sa(null,!0));let P=x.then(I=>(b(I),g()),()=>(b(Sa("people_unavailable")),g())).finally(()=>{m===x&&(m=null)});return v(P,S)}return Object.freeze({getSnapshot:g,subscribe(k){return f?()=>{}:(d.add(k),()=>{d.delete(k)})},start(k={}){return h?v(m??Promise.resolve(g()),k.signal):!w()||k.signal?.aborted?Promise.reject(Au()):(h=!0,_(k))},refresh:_,close:y})}var Sa,wo,t4,Au,M2=C(()=>{"use strict";Ld();re();Sa=(n,e=!1)=>Object.freeze({checking:e,assessment:null,problem:n===null?null:Object.freeze({code:n})}),wo=Sa("people_fenced"),t4=Object.freeze({checking:!1,assessment:Object.freeze({status:"ready",problem:null}),problem:null}),Au=()=>A("cancelled","People readiness ended","people_readiness_fenced")});function Pg(n){if(!n||!Array.isArray(n.criteria))return Object.freeze([]);let e=n.criteria.filter(t=>t?.event?.id===lm.id&&t.event.version===lm.version&&t.event.digest===lm.digest).map(t=>t.id);return Object.freeze([...new Set(e)])}var V0=C(()=>{"use strict";fd()});function L2(n){let e=n.scope,t=e.account,i=e.installation,o=e.collection,s=n.generation,r=n.signal,a=n.isCurrent.bind(n),c=n.notifications,l=c?.declaration,p=c?.timerNamespace,d=n.timers,u=typeof d?.list=="function"?d.list.bind(d):void 0,f=new Set,h=pr(null),m=!1,w=!1,b=null;function g(){try{return m||r.aborted||a()!==!0?!1:!m&&!r.aborted&&n.signal===r&&n.scope===e&&n.generation===s&&!!s&&s.length<=256&&[t,i,o].every(x=>typeof x=="string"&&!!x&&x.length<=128)&&e.account===t&&e.installation===i&&e.collection===o&&n.notifications===c&&c?.declaration===l&&c?.timerNamespace===p&&n.timers===d}catch{return!1}}function y(x){h=g()?x:xg;for(let P of[...f])try{P()}catch{}g()||(h=xg)}function v(){return g()||(h=xg),h}function _(){if(!m){m=!0,r.removeEventListener("abort",_),h=xg;for(let x of[...f])try{x()}catch{}f.clear()}}r.addEventListener("abort",_,{once:!0}),r.aborted&&_();function k(x,P){return!g()||P?.aborted?Promise.reject(ku()):new Promise((I,O)=>{let R=!1,q=(D,X)=>{R||(R=!0,P?.removeEventListener("abort",j),r.removeEventListener("abort",j),f.delete(B),X!==void 0?O(X):I(D))},j=()=>q(void 0,ku()),B=()=>{g()||j()};f.add(B),P?.addEventListener("abort",j,{once:!0}),r.addEventListener("abort",j,{once:!0}),x.then(()=>{!g()||P?.aborted?j():q(v())},()=>q(void 0,ku())),(!g()||P?.aborted)&&j()})}function S(x={}){let P=x.signal;if(!g()||P?.aborted)return Promise.reject(ku());if(b)return Promise.reject(A("unavailable","Notification readiness READ is occupied","notification_readiness_busy"));let I=Promise.resolve().then(async()=>{if(!g())return pr("notifications_fenced");if(l===null&&c&&Object.hasOwn(c,"declaration"))return Object.freeze({checking:!1,assessment:Object.freeze({status:"ready",problem:null}),problem:null});if(!u&&Pg(l).length)return pr("notifications_consent_required");if(!l||typeof l!="object"||!u||typeof p!="string"||!/^[A-Za-z0-9._-]{1,64}$/.test(p))return pr("notifications_unsupported");try{let R=await u(p,{signal:r});return g()?!R||R.namespace!==p||!Array.isArray(R.timers)||R.timers.length>1e4?pr("notifications_response"):pr("notifications_unsupported"):pr("notifications_fenced")}catch{return pr(g()?"notifications_unavailable":"notifications_fenced")}});b=I,y(pr(null,!0));let O=I.then(R=>(y(R),v()),()=>(y(pr("notifications_unavailable")),v())).finally(()=>{b===I&&(b=null)});return k(O,P)}return Object.freeze({getSnapshot:v,subscribe(x){return m?()=>{}:(f.add(x),()=>{f.delete(x)})},start(x={}){return w?k(b??Promise.resolve(v()),x.signal):!g()||x.signal?.aborted?Promise.reject(ku()):(w=!0,S(x))},refresh:S,close:_})}var n4,pr,xg,ku,j2=C(()=>{"use strict";re();V0();n4=n=>Object.freeze({code:n}),pr=(n,e=!1)=>Object.freeze({checking:e,assessment:null,problem:n===null?null:n4(n)}),xg=pr("notifications_fenced"),ku=()=>A("cancelled","Notification readiness ended","notification_readiness_fenced")});function D2(n){let e=new Set,t=!1,i=()=>{if(t||!n.isCurrent())return U2;let s=n.declaration;if(!s)return F0;let r;try{r=n.grant()}catch{return i4}return r?s.required.some(a=>!r.actions.includes(a))?N2("files_access_missing"):n.scope==="collection"&&r.scope.kind!=="collection"?N2("files_scope_missing"):F0:F0},o=i();return Object.freeze({getSnapshot:()=>t||!n.isCurrent()?U2:o,subscribe(s){return t?()=>{}:(e.add(s),()=>{e.delete(s)})},async refresh(){let s=i();if(s!==o){o=s;for(let r of[...e])try{r()}catch{}}return o},close(){t=!0,e.clear()}})}var Ig,F0,U2,i4,N2,z2=C(()=>{"use strict";Ig=n=>Object.freeze(n),F0=Ig({checking:!1,assessment:Object.freeze({status:"ready",problem:null}),problem:null}),U2=Ig({checking:!1,assessment:null,problem:Object.freeze({code:"files_fenced"})}),i4=Ig({checking:!1,assessment:null,problem:Object.freeze({code:"files_unavailable"})}),N2=n=>Ig({checking:!1,assessment:Object.freeze({status:"incompatible",problem:Object.freeze({code:n})}),problem:null})});var Cg,$2=C(()=>{"use strict";T0();x2();E2();M2();j2();V0();wp();zd();z2();Cg=class{constructor(e,t,i,o="block",s=()=>[]){this.typeIssues=o;this.consented=s;this.compiled=e,this.signal=i,this.ui=new Mc(t,i,Pg(this.compiled.manifest.notifications)),i.addEventListener("abort",this.abort,{once:!0})}typeIssues;consented;ui;signal;compiled;listeners=new Set;selected=null;epoch=0;opening=null;retiring=null;closing=null;changed=()=>{for(let e of[...this.listeners])try{e()}catch{}};abort=()=>{this.close().catch(()=>{})};subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}connection(e){return this.ui.connection(e)}getReadiness(){return this.selected?.readiness.getSnapshot()??null}selectedId(){return this.selected?.connection.id??null}adopt(e,t,i){let o=this.epoch,s=()=>!this.signal.aborted&&!this.closing&&!this.retiring&&this.epoch===o&&i(),r=!!this.opening||!!this.selected||!!this.retiring||!!this.closing,a=this.ui.adopt(e,{caller:t,isCurrent:s});if(r)return a;let c=null,l=[],p=a.then(d=>{if(!s()||t.aborted)throw new pn("application_connection_fenced");let u=this.ui.owned();if(!u)throw new pn("application_connection_binding");let f=ay(this.compiled);f&&QS(d.files,PR(f,()=>this.consented(d.id)));let h=new AbortController,m=AbortSignal.any([this.signal,h.signal]);c=h;let w=()=>s()&&d.isCurrent(),b={scope:d.scope,generation:d.generation,signal:m,isCurrent:w},g=O2({client:d.records,compiledManifest:this.compiled,journal:u.journal,...b,setupMode:u.setupMode},u.resourceSetup);l.push(()=>g.close());let y={getSnapshot:g.getSnapshot,subscribe:g.subscribe,refresh:g.assess,close:g.close},v=T2({people:d.people,...b});l.push(()=>v.close());let _=this.compiled.manifest.notifications,k=L2({notifications:{declaration:_?.criteria?.length?_:null},timers:d.timers,...b});l.push(()=>k.close());let S=this.compiled.manifest.requirements.files?.scope?.kind,x=D2({declaration:f,scope:typeof S=="string"?S:null,grant:()=>d.files.grant,isCurrent:w});l.push(()=>x.close());let P=this.compiled.nativeCapabilities?{...this.compiled.nativeCapabilities,contracts:this.compiled.manifest.requirements.contracts,typeIssues:this.typeIssues}:null,I=new Sg({connection:d,nativeRequirements:P,signal:m,isCurrent:w,configuration:y,files:x,people:v,notifications:k}),O=I.subscribe(this.changed);return this.selected={connection:d,lifetime:h,readiness:I,configuration:g,unsubscribe:O},c=null,l.length=0,this.changed(),d}).catch(async d=>{c?.abort();let f=(await Promise.allSettled([this.ui.retire(),...l.map(h=>Promise.resolve().then(h))])).find(h=>h.status==="rejected");throw f?.status==="rejected"?f.reason:d}).finally(()=>{this.opening===p&&(this.opening=null)});return this.opening=p,p}assess(e={}){return!this.selected||!this.selected.connection.isCurrent()||this.retiring||this.closing?Promise.reject(new pn("application_connection_fenced")):this.selected.readiness.refresh(e)}async configure(e={}){let t=this.selected,i=this.epoch;if(!t||!t.connection.isCurrent()||this.retiring||this.closing)throw new pn("application_connection_fenced");if(await t.configuration.configure(e),e.signal?.aborted||this.epoch!==i||this.selected!==t||!t.connection.isCurrent())throw new pn("application_connection_fenced");return t.readiness.refresh(e)}planSetup(e={}){let t=this.selected;return!t||!t.connection.isCurrent()||this.retiring||this.closing?Promise.reject(new pn("application_connection_fenced")):t.configuration.plan(e)}async applySetup(e,t={}){let i=this.selected,o=this.epoch;if(!i||!i.connection.isCurrent()||this.retiring||this.closing)throw new pn("application_connection_fenced");if(await i.configuration.apply(e,t),t.signal?.aborted||this.epoch!==o||this.selected!==i||!i.connection.isCurrent())throw new pn("application_connection_fenced");return i.readiness.refresh(t)}retire(){if(this.retiring)return this.retiring;++this.epoch;let e=this.selected,t=this.opening;e?.lifetime.abort(),e?.unsubscribe();let i=this.ui.retire(),o=Promise.resolve().then(async()=>{let r=(await Promise.allSettled([i,t?.catch(()=>{}),e?.readiness.close()])).find(a=>a.status==="rejected");if(r?.status==="rejected")throw r.reason;this.selected===e&&(this.selected=null)});return this.retiring=o,this.changed(),o.then(()=>{this.retiring===o&&(this.retiring=null),this.changed()},()=>{}),o}close(){return this.closing?this.closing:(this.signal.removeEventListener("abort",this.abort),this.closing=Promise.resolve().then(async()=>{await this.retire(),await this.ui.close(),this.listeners.clear()}),this.closing)}}});function K0(n,e){return!n||typeof n!="object"||Array.isArray(n)||Object.keys(n).sort().join()!==e.split(",").sort().join()?Nc():n}function W0(n){(typeof n!="string"||!r4.test(n)||/^0{8}-0{4}-0{4}-0{4}-0{12}$/.test(n))&&Nc()}function B2(n){let e=K0(n,"rpc,action,value");if((!Number.isSafeInteger(e.rpc)||e.rpc<1||e.rpc>4294967295)&&Nc(),e.action==="cancel")e.value!==null&&Nc();else if(e.action==="prepare"){let t=K0(e.value,`requestId,accountId,appId,challenge${Object.hasOwn(e.value,"authorizationId")?",authorizationId":""}`);for(let i of["requestId","accountId","appId"])W0(t[i]);t.authorizationId!==void 0&&W0(t.authorizationId),(typeof t.challenge!="string"||!/^[0-9a-f]{64}$/.test(t.challenge))&&Nc()}else if(e.action==="finish"){let t=K0(e.value,"requestId,authorizationRequestId,collectionId");for(let i of Object.keys(t))W0(t[i])}else Nc();return Object.freeze({...e,value:e.value===null?null:Object.freeze({...e.value})})}var r4,Nc,V2=C(()=>{"use strict";qd();r4=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,Nc=()=>{throw new xe("application_worker_binding")}});function H0(n){if(!n||typeof n!="object"||Array.isArray(n))throw new xe("application_worker_binding");let e=n,t=e.unlock;if(e.status==="needs_unlock"!=(t!=null)||t!=null&&(typeof t!="object"||!["password","strict","none"].includes(t.mode)||typeof t.unlocking!="boolean"||!(t.problem===null||typeof t.problem=="string"&&/^[a-z][a-z0-9_]{0,63}$/.test(t.problem))))throw new xe("application_worker_binding");if(!["not_started","starting","signed_out","authorizing","unselected","opening","setup_required","ready","blocked","closed","needs_unlock"].includes(e.status)||!(e.openingProgress==null||typeof e.openingProgress=="string")||!Array.isArray(e.collections)||e.collections.length>1024||!(e.selectedCollectionId===null||typeof e.selectedCollectionId=="string")||!(e.problem===null||typeof e.problem=="string"&&/^[a-z0-9_-]{1,128}$/.test(e.problem))||!(e.unsynced==null||typeof e.unsynced=="object"&&e.unsynced.collectionId===e.selectedCollectionId&&typeof e.unsynced.sessionStatus=="string")||!(e.unsyncedWork==null||typeof e.unsyncedWork=="object"&&Number.isSafeInteger(e.unsyncedWork.since)&&e.unsyncedWork.since>=0))throw new xe("application_worker_binding");return Object.freeze({...e,openingProgress:Ky(e.openingProgress)?e.openingProgress:null})}var Dc,Rg,F2=C(()=>{"use strict";WA();V2();qd();Dc=class extends Error{constructor(t){super("SDK application operation unavailable");this.code=t;this.name="ApplicationWorkerReplyError"}code};Rg=class{port;binding;owner;nextId=0;active=null;portal=null;fault=null;stopping=null;stopReply=null;watch=null;closedPortal=null;abandoned=!1;constructor(e,t,i){if(!z1(t))throw new xe("application_worker_binding");this.port=e,this.binding=t,this.owner=Object.freeze({...i}),e.addEventListener("message",this.message),e.addEventListener("messageerror",this.messageError),e.start()}id(){if(this.nextId===Bm)throw new xe("application_worker_stop_failed");return++this.nextId}send(e,t,i){let o=P_([di,this.binding,e,t,i],this.binding);try{this.port.postMessage(o)}catch{throw this.quarantine("application_worker_unavailable"),this.fault}}request(e,t,i,o){if(this.fault||this.stopping||i.aborted)return Promise.reject(this.fault??new xe("application_worker_fenced"));if(this.active)return Promise.reject(new xe("application_worker_busy"));let s;try{s=this.id(),P_([di,this.binding,s,e,t],this.binding)}catch(c){return Promise.reject(c)}if(o){if(!["authorize","renewExpiredPairing","requestFileAccess"].includes(e))return Promise.reject(new xe("application_worker_binding"));this.portal?.life.abort(),this.portal&&(this.closedPortal=this.portal.id);try{this.portal?.value.close()}catch{return this.quarantine("application_worker_stop_failed"),Promise.reject(this.fault)}this.portal={id:s,value:o,caller:i,life:new AbortController,lastRpc:0,busy:!1},this.watchPortal()}let r,a=new Promise(c=>{r=c});return new Promise((c,l)=>{let p={id:s,caller:i,done:a,finish:r,resolve:c,reject:l,fenced:!1,reply:!1,handoff:null,cancel:()=>{p.fenced=!0,l(new xe("application_worker_fenced"))}};this.active=p,i.addEventListener("abort",p.cancel,{once:!0});try{this.send(s,e,t)}catch(d){l(d)}i.aborted&&p.cancel()})}drain(){return this.fault?Promise.reject(this.fault):this.active?.done??Promise.resolve()}setForeground(e){!this.stopping&&!this.fault&&this.send(0,"foreground",e)}watchPortal(){this.watch!==null&&clearInterval(this.watch),this.watch=null;let e=this.portal;!e||!("closed"in e.value)||(this.watch=setInterval(()=>{if(this.portal!==e||this.stopping||this.fault){clearInterval(this.watch),this.watch=null;return}let t=!1;try{t=e.value.closed===!0}catch{}if(t){clearInterval(this.watch),this.watch=null,e.lastRpc===0&&(this.portal=null,this.closedPortal=e.id);try{this.send(0,"approvalClosed",!0)}catch{}}},500))}messageError=()=>this.quarantine("application_worker_unavailable");quarantine(e){if(!this.fault){this.fault=new xe(e),this.active&&(this.active.fenced=!0,this.active.reject(this.fault)),this.stopReply?.reject(this.fault);try{this.owner.failed?.(this.fault)}catch{}}}message=e=>{try{let t=e.data;if(!Array.isArray(t)||t.length!==5||t[0]!==di||t[1]!==this.binding||!Number.isInteger(t[3])||t[3]<0||t[3]>Bm)throw new xe("application_worker_binding");if(this.fault)return;let[,,i,o,s]=t;if(i==="nativeSnapshot"){if(o!==0)throw new xe("application_worker_binding");let l=H0(s);this.stopping||this.owner.snapshot(l);return}if(i==="fatal"){if(o!==0)throw new xe("application_worker_binding");this.quarantine("application_worker_stop_failed");return}if(i==="nativeAuthorization"){let l=B2(s),p=this.portal;if(o===this.closedPortal&&p?.id!==o){l.action!=="cancel"&&this.port.postMessage([di,this.binding,"nativeAuthorizationReply",o,{rpc:l.rpc,ok:!1}]);return}if(!p||p.id!==o||this.stopping||p.caller.aborted||l.rpc<=p.lastRpc)throw new xe("application_worker_fenced");if(p.lastRpc=l.rpc,l.action==="cancel")p.life.abort();else if(p.busy)throw new xe("application_worker_binding");l.action!=="cancel"&&(p.busy=!0);let d=AbortSignal.any([p.caller,p.life.signal]);Promise.resolve().then(()=>{if(!this.owner.nativeAuthorization)throw new xe("application_worker_unavailable");return this.owner.nativeAuthorization(l,p.value,d)}).then(u=>{if(d.aborted||this.portal!==p||this.stopping)throw new xe("application_worker_fenced");this.port.postMessage([di,this.binding,"nativeAuthorizationReply",o,{rpc:l.rpc,ok:!0,value:u}])},()=>{this.port.postMessage([di,this.binding,"nativeAuthorizationReply",o,{rpc:l.rpc,ok:!1}])}).catch(()=>{try{this.port.postMessage([di,this.binding,"nativeAuthorizationReply",o,{rpc:l.rpc,ok:!1}])}catch{}}).finally(()=>{p.busy=!1});return}if(i==="portal"){if(!s||!["navigate","focus","close"].includes(s.action))throw new xe("application_worker_binding");let l=this.portal;if(!l||l.id!==o)return;if(s.action==="close")l.life.abort(),l.value.close(),this.portal=null;else if(s.action==="focus")try{l.value.focus?.()}catch{}else{if(this.stopping||typeof s.uri!="string"||s.uri.length>8192)throw new xe("application_worker_binding");l.value.navigate(s.uri)}return}if(i==="handoff"&&o===0){if(!s||s.schema!=="mdbn-app-collection/1")throw new xe("application_worker_binding");let l=[s.dataPort,s.controlPort,...s.timerPort?[s.timerPort]:[]];if(l.some(p=>!(p instanceof MessagePort)))throw new xe("application_worker_binding");if(this.stopping||!this.owner.attached){for(let p of l)p.close();return}this.owner.attached(s);return}if(i==="handoff"){let l=this.active;if(!l||l.id!==o||l.reply||l.handoff)throw new xe("application_worker_binding");if(this.stopping){if(!s||s.schema!=="mdbn-app-collection/1")throw new xe("application_worker_binding");for(let p of[s.dataPort,s.controlPort,...s.timerPort?[s.timerPort]:[]]){if(!(p instanceof MessagePort))throw new xe("application_worker_binding");p.close()}l.handoff=Promise.resolve();return}l.handoff=Promise.resolve().then(()=>this.owner.handoff(s,l.caller)),l.handoff.catch(()=>{});return}if(i!=="reply"||!s||typeof s.ok!="boolean"||!s.ok&&(!s.problem||typeof s.problem.code!="string"||s.problem.code.length>128))throw new xe("application_worker_binding");let r=this.stopReply;if(r&&r.id===o){if(s.ok){let l=H0(s.snapshot);if(l.status!=="closed"||l.selectedCollectionId!==null)throw new xe("application_worker_stop_failed");r.resolve()}else r.reject(new xe("application_worker_stop_failed"));return}let a=this.active;if(!a||a.id!==o||a.reply)throw new xe("application_worker_binding");a.reply=!0;let c=s.ok?H0(s.snapshot):null;this.settle(a,c,s.ok?null:Object.freeze({code:s.problem.code}))}catch{this.quarantine("application_worker_binding")}};async settle(e,t,i){try{if(await e.handoff,e.fenced||e.caller.aborted||this.stopping||this.fault)throw this.fault??new xe("application_worker_fenced");if(i)throw new Dc(i.code);t&&e.resolve(t)}catch(o){e.reject(o)}finally{e.caller.removeEventListener("abort",e.cancel),this.active===e&&(this.active=null),e.finish()}}abandon(){if(this.abandoned)return;this.abandoned=!0,this.fault||(this.fault=new xe("application_worker_fenced")),this.watch!==null&&(clearInterval(this.watch),this.watch=null);let e=this.active;e&&(e.fenced=!0,e.reject(this.fault),e.finish(),this.active=null),this.stopReply?.reject(this.fault),this.stopReply=null,this.portal?.life.abort();try{this.portal?.value.close()}catch{}this.portal=null;try{this.owner.releaseWorker()}catch{}this.port.removeEventListener("message",this.message),this.port.removeEventListener("messageerror",this.messageError),this.port.close()}close(){if(this.stopping)return this.stopping;let e=this.active;return e&&(e.fenced=!0,e.reject(new xe("application_worker_fenced"))),this.stopping=Promise.resolve().then(async()=>{if(this.fault)throw new xe("application_worker_stop_failed");this.portal?.life.abort(),this.portal?.value.close(),this.portal=null;let t=this.id();if(await new Promise((i,o)=>{this.stopReply={id:t,resolve:i,reject:o};try{this.send(t,"close",null)}catch(s){o(s)}}),await e?.done,this.fault)throw new xe("application_worker_stop_failed");this.owner.releaseWorker(),this.port.removeEventListener("message",this.message),this.port.removeEventListener("messageerror",this.messageError),this.port.close()}).catch(t=>{throw this.quarantine("application_worker_stop_failed"),t}),this.stopping}}});var W2={};Ea(W2,{ApplicationRuntime:()=>Y0,ApplicationRuntimeError:()=>Nn});function o4(n,e){let t=()=>A("invalid_request","Pass the collection and either { password } or { recoveryKey }.","unlock_secret_invalid");if(typeof n!="string"||!e||typeof e!="object")throw t();let i=Object.hasOwn(e,"password"),o=Object.hasOwn(e,"recoveryKey");if(i===o)throw t();let s=i?e.password:e.recoveryKey;if(typeof s!="string"||!s.length)throw t();let r=new TextEncoder().encode(s);if(r.length>S_)throw r.fill(0),t();return Object.freeze([n,i?"password":"recoveryKey",r])}function K2(n){try{if(!n||!Su.test(String(n.name)))return;let e=o=>typeof o=="string"&&Su.test(o)?o:"-",t=`${n.name}:${e(n.code)}`;typeof n.stage=="string"&&Su.test(n.stage)&&(t+=`@${n.stage}`),n.cause&&Su.test(String(n.cause.name))&&(t+=` cause=${n.cause.name}:${e(n.cause.code)}`);let i=n.server?.status;return Number.isInteger(i)&&i>=100&&i<=599&&(t+=` http=${i}${n.server.code&&Su.test(n.server.code)?`:${n.server.code}`:""}`),t}catch{return}}var Nn,Su,G0,Y0,H2=C(()=>{"use strict";WA();re();rp();qd();bE();$2();T0();St();zd();F2();x_();Nn=class extends Error{constructor(t){super("SDK application runtime unavailable");this.code=t;this.name="ApplicationRuntimeError"}code},Su=/^[A-Za-z][A-Za-z0-9_]{0,63}$/;G0=()=>{let n=Object.freeze({checking:!1,assessment:null,problem:null});return Object.freeze({checking:!1,assessment:null,problem:null,facets:Object.freeze({capabilities:n,contracts:n,configuration:n,files:n,people:n,notifications:n})})},Y0=class{lifetime=new AbortController;scope;worker;cpOrigin;lab;appName;sourceAdopt=null;listeners=new Set;unsubscribe;raw=Object.freeze({status:"not_started",collections:Object.freeze([]),selectedCollectionId:null,signIn:null,problem:null,timing:null});snapshot=Object.freeze({...this.raw,readiness:G0()});pending=null;closing=null;epoch=0;loggedProblem=null;assessing=!1;retiring=!1;closed=!1;stopped=!1;stopFailed=!1;constructor(e){this.cpOrigin=e.cpOrigin,this.appName=e.declaration.name,this.lab=Ml(e.declaration.environment),this.scope=new Cg(e.compiledManifest,{name:e.declaration.name,version:"1"},this.lifetime.signal,e.typeIssues,t=>ly(this.raw,t)),this.worker=new Rg(e.port,e.binding,{snapshot:t=>{this.closed||(this.raw=t,this.followSession(),this.publish())},handoff:(t,i)=>{if(this.sourceAdopt)return this.sourceAdopt(t,i);let o=this.epoch;return this.scope.adopt(t,i,()=>!this.closed&&this.epoch===o).then(()=>{this.portsFailed=null},s=>{throw this.portsFailed=t.scope.collection,s})},attached:t=>this.attached(t),releaseWorker:e.releaseWorker,...e.nativeAuthorization?{nativeAuthorization:e.nativeAuthorization}:{},failed:t=>{this.closed||(this.raw=Object.freeze({...this.raw,status:"blocked",problem:t.code,unlock:null}),this.publish())}}),this.unsubscribe=this.scope.subscribe(()=>this.publish())}portsFailed=null;attached(e){let t=()=>{for(let o of[e.dataPort,e.controlPort,...e.timerPort?[e.timerPort]:[]])try{o.close()}catch{}};if(this.closed){t();return}let i=this.lifetime.signal;this.queue(()=>this.action(async()=>{if(this.raw.selectedCollectionId!==e.scope.collection)return t(),this.snapshot;this.scope.selectedId()!==null&&(++this.epoch,await this.retireOwn());let o=this.epoch;return await this.scope.adopt(e,i,()=>!this.closed&&this.epoch===o).catch(s=>{throw this.portsFailed=e.scope.collection,s}),this.portsFailed=null,this.complete(this.raw,i)},i)).catch(()=>{this.closed||this.publish()})}followSession(){if(this.pending)return;let e=this.raw.status==="ready"||this.raw.status==="setup_required",t=this.raw.selectedCollectionId,i=this.scope.selectedId();if(i!==null&&(i!==t||!e&&this.raw.status!=="opening"&&this.raw.status!=="authorizing")){let o=this.lifetime.signal;this.queue(()=>this.action(async()=>(this.scope.selectedId()===i&&(++this.epoch,await this.retireOwn()),this.publish(),this.snapshot),o)).catch(()=>{})}}connection(e){return this.closed?null:this.scope.connection(e)}getSnapshot(){return this.snapshot}getNativeSnapshot(){return this.raw}async queue(e){for(;this.pending&&!this.closed;)await this.pending.catch(()=>{});return e()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}publish(){if(this.closed)this.snapshot=Object.freeze({...this.raw,status:this.stopped?"closed":"blocked",problem:this.stopped?null:this.stopFailed?"application_stop_failed":"application_closing",selectedCollectionId:null,unlock:null,readiness:G0()});else{let e=this.scope.getReadiness()??G0(),t=this.raw.status,i=this.raw.problem,o,s=this.raw.problemDetail,r=this.raw.selectedCollectionId,a=this.retiring&&e.problem?.code==="readiness_fenced",c=r!==null&&(this.scope.getReadiness()===null||a)&&this.portsFailed!==r;if((t==="ready"||t==="setup_required")&&c)t="opening";else if(t==="ready"||t==="setup_required"){let h=this.assessing&&!e.assessment&&e.problem?.code!=="readiness_fenced";if(t=e.checking||h?"opening":e.assessment?.status==="ready"?"ready":e.assessment?.status==="setup_required"?"setup_required":"blocked",t==="blocked"){let m=e.problem??e.assessment?.problem;i=m?.code??"application_readiness_unavailable",o=m?.detail,s=void 0}}let l=`${i}:${o??K2(s)??""}`;if(t==="blocked"&&i&&l!==this.loggedProblem){this.loggedProblem=l;try{let h=o??K2(s);h?console.error("mdbase application blocked:",i,h):console.error("mdbase application blocked:",i)}catch{}}else t!=="blocked"&&(this.loggedProblem=null);let{problemDetail:p,...d}=this.raw,u=t==="opening"?d.status==="opening"?d.openingProgress??null:e.checking?"checking_setup":null:null,f=this.snapshot;this.snapshot=Object.freeze({...d,...s?{problemDetail:s}:{},status:t,problem:i,openingProgress:u,collections:Object.freeze(this.raw.collections.map(h=>Object.freeze({...h}))),readiness:e}),r!==null&&Ky(u)&&(f.selectedCollectionId!==r||f.openingProgress!==u)&&fr(`mdbase:open:stage:${u}`)}for(let e of[...this.listeners])try{e()}catch{}}retireOwn(){return this.retiring=!0,this.scope.retire()}settled(){return this.assessing=!1,this.publish(),this.snapshot}signal(e){return e.signal?AbortSignal.any([this.lifetime.signal,e.signal]):this.lifetime.signal}action(e,t){if(this.closed||t.aborted)return Promise.reject(new Nn("application_fenced"));if(this.pending)return Promise.reject(new Nn("application_busy"));this.assessing=!0;let i=Promise.resolve().then(async()=>{if(this.closed||t.aborted)throw new Nn("application_fenced");let o=await e();if(this.closed||t.aborted)throw new Nn("application_fenced");return o}).finally(async()=>{(this.assessing||this.retiring)&&(this.assessing=!1,this.retiring=!1,this.publish()),await this.worker.drain(),this.pending===i&&(this.pending=null)});return this.pending=i,i}async complete(e,t){if(this.closed||t.aborted)throw new Nn("application_fenced");let i=!!(e.selectedCollectionId&&this.scope.connection(e.selectedCollectionId));if(this.raw=e,this.assessing=i,this.publish(),i){try{await this.scope.assess({signal:t}).catch(()=>{})}finally{this.assessing=!1}this.publish()}if(this.closed||t.aborted)throw new Nn("application_fenced");return this.snapshot}start(e={}){let t=this.signal(e);return this.action(async()=>this.complete(await this.worker.request("start",null,t),t),t)}authorizeReserved(e,t={},i=null){let o=this.signal(t);return this.action(async()=>this.complete(await this.worker.request("authorize",i,o,e),o),o).catch(s=>{throw e.close(),s})}authorize(e={}){let t=this.signal(e),i;try{i=Vm(Fm(this.cpOrigin,t,()=>!this.closed,this.lab))}catch(o){return Promise.reject(o)}return this.authorizeReserved(i,e)}select(e,t={}){let i=this.signal(t);return this.action(async()=>{if(this.raw.selectedCollectionId===e&&(this.raw.status==="ready"||this.raw.status==="setup_required")&&this.scope.connection(e)?.isCurrent())return this.snapshot.status==="blocked"?this.complete(this.raw,i):this.snapshot;++this.epoch;let o=this.retireOwn();if(this.publish(),await o,this.closed||i.aborted)throw new Nn("application_fenced");return this.complete(await this.worker.request("select",e,i),i)},i)}unlock(e,t,i={}){let o=this.signal(i),s;try{s=o4(e,t)}catch(a){return Promise.reject(a)}let r=()=>{s[2].fill(0)};return this.action(async()=>{if(this.raw.selectedCollectionId!==e||this.raw.status!=="needs_unlock")throw A("invalid_request","This collection is not waiting to be unlocked.","unlock_not_locked");let a;try{a=this.worker.request("unlock",s,o)}finally{r()}return this.complete(await a,o)},o).finally(r)}openUnsynced(e={}){let t=this.signal(e);return this.action(async()=>{let i=this.raw.unsynced?.collectionId??null;if(i!==null&&this.raw.selectedCollectionId===i&&(this.raw.status==="ready"||this.raw.status==="setup_required")&&this.scope.connection(i)?.isCurrent())return this.snapshot.status==="blocked"?this.complete(this.raw,t):this.snapshot;++this.epoch;let o=this.retireOwn();if(this.publish(),await o,this.closed||t.aborted)throw new Nn("application_fenced");return this.complete(await this.worker.request("openUnsynced",e.timezone??null,t),t)},t)}async retireUnsynced(e,t,i={}){let o=this.signal(i),s=!0;return await this.queue(()=>this.action(async()=>{try{return this.complete(await this.worker.request("retireUnsynced",[e,t],o),o)}catch(r){if(r instanceof Dc&&r.code==="application_worker_busy")return s=!1,this.snapshot;throw r}},o)),s}discardUnsynced(e={}){let t=this.signal(e);return this.action(async()=>{let i=this.raw.unsynced?.collectionId??null,o=i!==null&&this.raw.selectedCollectionId===i;if(o){++this.epoch;let s=this.retireOwn();if(this.publish(),await s,this.closed||t.aborted)throw new Nn("application_fenced")}try{return this.complete(await this.worker.request("discardUnsynced",null,t),t)}catch(s){throw o&&s instanceof Dc&&s.code==="application_worker_busy"&&!this.closed&&!t.aborted&&this.complete(await this.worker.request("openUnsynced",null,t),t),s}},t)}async withUnsyncedSource(e,t={}){let i=this.signal(t),o=new Mc({name:this.appName,version:"1"},i),s=null;try{if(await this.queue(()=>this.action(async()=>{this.sourceAdopt=(r,a)=>(s=o.adopt(r,{caller:a,isCurrent:()=>!this.closed&&!i.aborted}),s.then(()=>{}));try{await this.worker.request("attachUnsynced",null,i)}finally{this.sourceAdopt=null}return this.snapshot},i)),!s)throw new Nn("application_connection_unavailable");return await e(await s,i)}finally{if(await o.close().catch(()=>{}),!this.closed){let r=this.lifetime.signal;await this.queue(()=>this.action(async()=>(await this.worker.request("detachUnsynced",null,r),this.snapshot),r)).catch(()=>{})}}}assess(e={}){let t=this.signal(e);return this.action(async()=>(await this.scope.assess({signal:t}),this.settled()),t).then(i=>i.readiness)}configure(e={}){let t=this.signal(e);return this.action(async()=>(await this.scope.configure({signal:t}),this.settled()),t)}planSetup(e={}){let t=this.signal(e);return this.closed||t.aborted?Promise.reject(new Nn("application_fenced")):this.scope.planSetup({...e,signal:t})}applySetup(e,t={}){let i=this.signal(t);return this.action(async()=>(await this.scope.applySetup(e,{signal:i}),this.settled()),i)}cancelAuthorization(e={}){let t=this.signal(e);return this.action(async()=>this.complete(await this.worker.request("cancelAuthorization",null,t),t),t)}clearSelection(e={}){let t=this.signal(e);return this.action(async()=>(++this.epoch,await this.retireOwn(),this.complete(await this.worker.request("clearSelection",null,t),t)),t)}forget(e,t={}){let i=this.signal(t);return this.action(async()=>(this.raw.selectedCollectionId===e&&(++this.epoch,await this.retireOwn()),this.complete(await this.worker.request("forget",e,i),i)),i)}refreshCollections(e={}){let t=this.signal(e);return this.action(async()=>(this.raw=await this.worker.request("refreshCollections",null,t),this.publish(),this.snapshot),t)}signOut(e={}){let t=this.signal(e),i=this.raw.selectedCollectionId,o=e.discard!==!0&&i?yE(this.scope.connection(i)):0;return o>0?Promise.reject(gE(o)):this.action(async()=>(++this.epoch,await this.retireOwn(),this.complete(await this.worker.request("signOut",null,t),t)),t)}deleteCollection(e,t,i={}){let o=this.signal(i);return this.action(async()=>(await this.worker.request("deleteCollection",[e,t],o),this.raw.selectedCollectionId===e&&(++this.epoch,await this.retireOwn()),this.complete(await this.worker.request("forget",e,o),o)),o)}requestFileAccess(e,t,i,o,s={}){let r=this.signal(s);return this.action(async()=>(this.raw=await this.worker.request("requestFileAccess",[t,i,o],r,e),this.publish(),this.snapshot),r).catch(a=>{throw e.close(),a})}pollFileAccess(e){let t=this.lifetime.signal;return this.action(async()=>(this.raw=await this.worker.request("pollFileAccess",e,t),this.publish(),this.snapshot),t)}setForeground(e){this.closed||this.worker.setForeground(e)}abandon(){this.closed||(this.closed=!0,this.stopped=!0,++this.epoch,this.unsubscribe(),this.listeners.clear(),this.closing=Promise.resolve(),this.worker.abandon(),this.lifetime.abort())}close(){return this.closing?this.closing:(this.closed=!0,++this.epoch,this.lifetime.abort(),this.unsubscribe(),this.closing=Promise.resolve().then(async()=>{await Promise.all([this.scope.close(),this.worker.close()]),await this.pending?.catch(()=>{}),this.stopped=!0,this.publish(),this.listeners.clear()}).catch(()=>{throw this.stopFailed=!0,this.publish(),new Nn("application_stop_failed")}),this.publish(),this.closing)}}});var R4={};Ea(R4,{ACCOUNT_KEY_STATES:()=>Zb,API_VERSIONS:()=>mf,AppHost:()=>rk,COLLECTION_UNAVAILABLE_REASONS:()=>Cw,CborError:()=>Le,Client:()=>zf,DESCRIBE_TYPING_MAX_PATHS:()=>ip,DESCRIBE_TYPING_MAX_TYPES:()=>np,DEVICE_KINDS:()=>Jb,ERROR_CODES:()=>Pu,FilesApi:()=>za,Float64:()=>_t,HOLD_COMPARE_SCHEME:()=>qp,HOLD_TITLE:()=>Ep,IkInitiator:()=>cc,IkResponder:()=>Uy,LiveQuery:()=>Wa,MAX_CONVENIENCE_BYTES:()=>yf,MAX_DEPTH:()=>zg,MDBASE_NOTIFICATION_CLICK:()=>kw,MDBASE_NOTIFICATION_TYPE:()=>Op,MdbaseClient:()=>wr,MdbaseError:()=>ne,MdbasePeopleClient:()=>vr,NoiseError:()=>bt,PERSON_CONTRACT:()=>gw,PROBLEM_CODES:()=>Ex,PresenceApi:()=>Ka,READ_MANY_MAX_CONCURRENCY:()=>tw,READ_MANY_MAX_REFS:()=>ew,RecordReader:()=>hp,RecordSet:()=>Fa,SESSION_LIFETIME_MS:()=>CA,SLOW_OPENING_MS:()=>ih,SchemaError:()=>ae,Session:()=>Es,TEMPORAL_HINTS:()=>Ju,TimersApi:()=>Ha,WasmRuntime:()=>tc,Write:()=>Ms,applicationPhase:()=>Mp,approvalReadiness:()=>rP,bytesEqual:()=>Bg,clientPrologue:()=>Ur,collectionUnavailableError:()=>Fn,compareVersions:()=>qw,connect:()=>yw,controlRouteResolver:()=>oq,createMdbase:()=>X2,createViewSource:()=>Cf,decode:()=>we,describeDiagnostic:()=>Qf,describeError:()=>Us,describeHold:()=>wx,diffEdits:()=>of,duplexCarrier:()=>EA,effectiveCapabilities:()=>Z2,encode:()=>fe,encodeSecret:()=>zn,fileGrant:()=>Yb,formatSas:()=>aP,framedPort:()=>df,fromHex:()=>Wr,generateKeyPair:()=>pc,handleMdbaseNotificationClick:()=>gx,handleMdbasePush:()=>yx,holdCompareLink:()=>Iw,holdNotice:()=>vx,inProcessConnector:()=>Dl,indexedDbKeyStorage:()=>tk,isCollectionUnavailableReason:()=>Ya,isConfirmed:()=>rx,isErrorCode:()=>Po,isMdbaseError:()=>J,isProtected:()=>Qr,isReadyPhase:()=>Nx,isValid:()=>Eq,keyPairFromSecret:()=>FO,loadOrCreateClientKey:()=>rq,localLinkConnector:()=>eq,localLinkFirstPayload:()=>Q0,mdbaseError:()=>A,memoryKeyStorage:()=>ek,memoryWriteLedgerStore:()=>Mf,nextRelayConnector:()=>JO,noiseChannel:()=>RA,noiseConnector:()=>Nr,orderTargets:()=>iu,parseCollectionAvailability:()=>wi,parseHoldCompareLink:()=>bx,parseMdbaseNativeNotification:()=>Sw,parseMdbasePush:()=>Kf,parseVersion:()=>Za,pipeCloseError:()=>ua,portPair:()=>DS,problemCodeOf:()=>Ow,queryPages:()=>wf,readMany:()=>bf,readMdbaseNotificationData:()=>Pw,readViewSourceRecord:()=>If,recoveryFor:()=>kq,relayConnector:()=>Q2,relayPipeCarrier:()=>fc,resolveRecordLinks:()=>gP,revisionOf:()=>zi,routeFromControl:()=>nk,sameIdentity:()=>Vf,showMdbaseNotification:()=>xw,staticKeyOf:()=>Ly,streamCarrier:()=>WO,structMap:()=>$g,summarizeSync:()=>$f,syncStatusText:()=>_x,toHex:()=>ht,toPlain:()=>ei,toValue:()=>Ke,updateViewSource:()=>Rf,uuidv7:()=>$i,valueEquals:()=>To,versionRelation:()=>Ns,webSocketCarrier:()=>dc,wire:()=>Ib});re();tn();tn();Ls();_f();nw();sw();lw();wp();wp();cw();Je();br();gf();var FT=["collection_not_yet_migrated","collection_migrating","update_required","account_suspended"];function $f(n){let e=n.status,t=e.mode==="local_only",i=n.writes??null,o=Math.max(e.pending,i?.pending.length??0),s=!t&&n.transport?n.transport.kind:null,r=n.link===void 0||n.link==="open",a=r?t?"local":n.online===!1||s==="offline"?"offline":s?"reconnecting":e.connection==="offline"?"offline":e.connection==="connecting"?"reconnecting":"online":"reconnecting",c=[],l=t?void 0:FT.find(f=>f===n.problem);l&&c.push(l),i?.rejected.length&&c.push("rejected"),e.unresolved>0&&c.push("conflicts"),e.holds>0&&c.push("held"),e.incidents.length&&c.push("incident"),o>0&&n.storageWarning&&c.push("storage_may_be_evicted");let p=a==="offline"||s!==null||!r,d=c.length?"attention":o>0&&p?"saved_on_device":a==="offline"?"offline":a==="reconnecting"?"reconnecting":o>0?"saving":!t&&(e.installing!==void 0||e.resyncing!==void 0||e.confirmedThrough<e.headKnown)?"catching_up":"saved",u=n.pendingForMs;return{state:d,connection:a,health:s,live:t||typeof n.live!="boolean"?null:n.live,pending:o,pendingFor:o===0?null:u===void 0?"while":u<2e3?"moment":u<3e4?"while":"long",writes:i,attention:c,conflicts:e.unresolved,holds:e.holds,incidents:e.incidents}}function rx(n){return n.state==="confirmed"}uw();xp();_w();re();var Op="mdbase.notification",kw="mdbase.notification.click",dx=/^[\x21-\x7e]{1,256}$/,ZT=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,Uo=n=>A("invalid_request",n,"invalid_push_payload"),QT=()=>A("upgrade_required","The push uses an envelope version this SDK does not support.","unsupported_push_version");function fx(n){if(typeof n=="string")try{n=JSON.parse(n)}catch{throw Uo("The push payload is not JSON.")}else if(n&&typeof n=="object"&&typeof n.json=="function")try{n=n.json()}catch{throw Uo("The push payload is not JSON.")}if(!n||typeof n!="object"||Array.isArray(n))throw Uo("The push payload is not an object.");return n}function Ga(n,e,t){return typeof n=="string"&&n.length>=e&&n.length<=t}function hx(n){if(!n||typeof n!="object"||Array.isArray(n))return null;let e=n;return!Ga(e.title,1,80)||e.body!==void 0&&!Ga(e.body,0,160)||e.tag!==void 0&&!Ga(e.tag,1,80)?null:Object.freeze({title:e.title,...typeof e.body=="string"&&e.body.length?{body:e.body}:{},...typeof e.tag=="string"?{tag:e.tag}:{}})}function mx(n,e,t){if(n.type!==Op)throw Uo("The payload is not an mdbase notification.");if(e!==1)throw typeof e=="number"&&Number.isSafeInteger(e)&&e>1?QT():Uo("The payload has no valid envelope version.");if(!Ga(n.signal_id,1,256)||!dx.test(n.signal_id)||!Ga(n.cursor,1,256)||!dx.test(n.cursor)||!Ga(n.criterion_id,1,100)||!ZT.test(n.criterion_id))throw Uo("The payload is not an mdbase notification.");return Object.freeze({version:1,signalId:n.signal_id,criterionId:n.criterion_id,cursor:n.cursor,presentation:t})}function Kf(n){let e=fx(n),t=mx(e,e.version,hx(e.presentation));if(!t.presentation)throw Uo("The push has no valid presentation.");return t}function Sw(n){if(!n||typeof n!="object"||Array.isArray(n))throw Uo("The native notification data is not an object.");let e=n,t=typeof e.version=="string"&&/^[1-9][0-9]{0,8}$/.test(e.version)?Number(e.version):e.version;return mx(e,t,null)}function Pw(n){try{return Sw(n)}catch{return null}}function eM(n){return{type:Op,version:n.version,signal_id:n.signalId,criterion_id:n.criterionId,cursor:n.cursor}}async function xw(n,e,t={}){let i=Kf(e),o=i.presentation;return await n.showNotification(o.title,{...o.body?{body:o.body}:{},...o.tag?{tag:o.tag}:{},...t.icon?{icon:t.icon}:{},...t.badge?{badge:t.badge}:{},data:eM(i)}),i}function Aw(n){return globalThis[n]}function tM(n){let e=globalThis.location;if(typeof e?.origin=="string"&&e.origin!=="null")return e.origin;try{return n?new URL(n).origin:null}catch{return null}}function ux(n,e,t){let i=()=>A("invalid_request",`The notification click ${t} must be on the app's own origin.`,"click_target_cross_origin");if(typeof n!="string")throw i();if(e===null){if(!n.startsWith("/")||n.startsWith("//")||n.startsWith("/\\"))throw i();return n}let o;try{o=new URL(n,`${e}/`)}catch{throw i()}if(o.origin!==e)throw i();return o.href}function yx(n,e={}){let t;try{t=fx(n.data?.text()??null)}catch{return!1}if(t.type!==Op)return!1;let i=e.registration??Aw("registration");if(!i)throw A("invalid_request","No service worker registration to show the notification.","push_registration_missing");let o={...e.icon?{icon:e.icon}:{},...e.badge?{badge:e.badge}:{}};return n.waitUntil((async()=>{try{Kf(t)}catch(s){let r=s instanceof ne&&s.reason==="unsupported_push_version"?hx(t.presentation):null;if(!r)throw s;return await i.showNotification(r.title,{...r.body?{body:r.body}:{},...r.tag?{tag:r.tag}:{},...o}),null}return xw(i,t,o)})()),!0}function gx(n,e={}){let t=Pw(n.notification.data);if(!t)return!1;n.notification.close();let i=e.clients??Aw("clients"),o=Aw("registration")?.scope,s=tM(o),r=e.scope===void 0?o:ux(e.scope,s,"scope"),a=e.url===void 0?r??"/":ux(e.url,s,"url");return i&&n.waitUntil((async()=>{let l=(await i.matchAll({type:"window",includeUncontrolled:!0})).find(d=>!r||d.url.startsWith(r));if(!l)return i.openWindow(a);await l.focus();let p={type:kw,notification:t};return l.postMessage(p),l})()),!0}var Ep="mdbase protected your edit",nM={conflict:{cause:"This file was also changed on another device while you were editing it.",detail:"Your version is kept here and is not synced until you choose what to keep."},unknown_provenance:{cause:"This file changed on disk in a way mdbase could not trace to an app or a sync.",detail:"The bytes on disk are kept here and are not synced until you confirm them."},deleted_elsewhere:{cause:"This file was deleted on another device after you edited it.",detail:"Your version is kept here; nothing is deleted until you choose."},read_only:{cause:"Changed with view access.",detail:"Edit access will not sync these changes. Submit or discard them."},editor_busy:{cause:"An editor still has this file open with unsaved changes.",detail:"mdbase waits so that it never overwrites what you are typing."},suspect_write:{cause:"The last write to this file looked incomplete, for example after a crash.",detail:"The file is kept aside and is not synced until you confirm it."}},iM={keep_mine:{label:"Keep mine",description:"Sync the version on this device.",resolution:"keep_mine",needs:"records.edit",discardsMine:!1},take_theirs:{label:"Take theirs",description:"Replace this file with the synced version.",resolution:"take_theirs",needs:"records.edit",discardsMine:!0},keep_both:{label:"Keep both",description:"Save your version as a copy next to the synced one.",resolution:"keep_both",needs:"records.edit",discardsMine:!1},delete:{label:"Delete",description:"Accept the deletion and remove this file here too.",resolution:"delete",needs:"records.delete",discardsMine:!0},use:{label:"Use merged",description:"Sync the document you merged.",resolution:"use",needs:"records.edit",discardsMine:!1},compare:{label:"Compare side by side",description:"Open both versions to merge them.",discardsMine:!1}},rM={conflict:["keep_mine","take_theirs","compare","keep_both"],unknown_provenance:["keep_mine","take_theirs","compare","keep_both"],deleted_elsewhere:["keep_mine","delete"],read_only:["keep_mine","take_theirs","compare","keep_both"],editor_busy:["keep_mine","take_theirs","compare"],suspect_write:["keep_mine","take_theirs","compare","keep_both"]},qp="mdbase://hold/compare",Wf=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Iw(n,e){if(!Wf.test(n)||!Wf.test(e))throw new Error("holdCompareLink: collection and id are UUIDs");return`${qp}?collection=${n.toLowerCase()}&id=${e.toLowerCase()}`}function bx(n){if(typeof n!="string"||n.length>512||!n.startsWith(`${qp}?`))return null;let e=new URLSearchParams(n.slice(qp.length+1)),t=e.get("collection")??"",i=e.get("id")??"";return!Wf.test(t)||!Wf.test(i)?null:{collectionId:t.toLowerCase(),id:i.toLowerCase()}}function wx(n,e){let t=n.reason==="read_only",i=n.theirs!==void 0,o=(e.canCompare??!0)&&i,s=c=>!c||!e.capabilities||e.capabilities.includes(c),r=rM[n.reason].filter(c=>c==="compare"?o:(!t||e.host===!0)&&(c!=="take_theirs"||i||t)).map(c=>{let l={action:c,...iM[c]};return t&&c==="take_theirs"&&(l.label="Discard local changes",l.description="Discard unsynced changes on this device.",l.needs="collection.read"),l}).filter(c=>s(c.needs)),a=nM[n.reason];return{id:n.id,path:n.path,reason:n.reason,title:Ep,cause:a.cause,detail:a.detail,since:n.since,saves:n.saves,hasTheirs:i,actions:r,reversible:!t,reversibleNote:t?"Copy before discarding.":"You can change your mind later: resolving is an ordinary change, and the previous version stays in the collection's history. Keep both if you want your version kept as a file as well.",compareLink:o?Iw(e.collectionId,n.id):null}}function vx(n){return n.length?n.length===1?`${Ep}: ${n[0].path} is waiting for your choice.`:`${Ep}: ${n.length} files are waiting for your choice.`:null}function _x(n){let e=(i,o)=>`${i} ${o}`,t=`, plus ${e(n.pending,"pending")}, plus ${e(n.holds,"held")}`;return n.mode==="local_only"?`Saved on this device${t}`:`Confirmed through ${n.confirmedThrough}${t}`}Tp();th();Tp();var ih=15e3,nh=(n,e)=>{try{return!!n&&n.id===e&&n.isCurrent()}catch{return!1}},Ds=(n,e)=>Us(n,e),Ai=(n,e)=>Ds(n,e);function Mp(n,e={}){let t=PM(n,e),i=xM(t,n,e);return i.kind==="opening"&&n.status==="opening"&&n.selectedCollectionId===i.collectionId&&n.openingProgress?{...i,progress:n.openingProgress}:i}function PM(n,e){let t={...e.cpOrigin?{cpOrigin:e.cpOrigin}:{},...e.messages?{messages:e.messages}:{}},i=n.selection,o=i?.requested??null;if(n.status==="closed")return{kind:"closed"};if(n.problem==="application_not_yet_available"||n.problem==="application_worker_unavailable"||n.problem==="browser_unsupported"||n.problem==="application_storage_unavailable")return{kind:"unavailable",problem:Ai(n.problem,t)};if(i?.state==="invalid")return{kind:"problem",collectionId:null,problem:Ai(i.problem??"application_selection_invalid",t)};let s=n.signIn?.state==="paired";if(i?.state==="approving"||n.status==="authorizing"){if(n.problem==="private_authorization_failed")return{kind:"problem",collectionId:o?.collectionId??null,problem:Ai(n.problem,t)};let p=i?.approval??null;return s?p?.kind==="add"?{kind:"authorizing",purpose:"add",collectionId:null}:{kind:"authorizing",purpose:"approve",collectionId:p?.collectionId??o?.collectionId??null}:{kind:"authorizing",purpose:"sign_in",collectionId:p?.collectionId??o?.collectionId??null}}let r=n.unsynced??null;if(r&&n.selectedCollectionId===r.collectionId){let p=r.collectionId;return n.status==="ready"&&nh(e.connection,p)?{kind:"unsynced",collectionId:p,connection:e.connection,rechecking:n.readiness.checking}:n.status==="blocked"||n.status==="setup_required"&&!n.readiness.checking&&n.readiness.assessment?{kind:"problem",collectionId:p,problem:(n.status==="blocked"?Ds(n,t):Ds(n.readiness,t))??Ai("open_failed",t)}:{kind:"opening",collectionId:p,displayName:null,slow:!!e.slow}}if(n.status==="not_started"||n.status==="starting"){let p=o?.collectionId??null;return p&&n.status==="starting"?{kind:"opening",collectionId:p,displayName:o?.displayName??null,slow:!!e.slow}:{kind:"starting"}}if(n.status==="signed_out")return n.problem?{kind:"signed_out",notice:Ds(n,t)}:n.signOutResult?.server==="incomplete"?{kind:"signed_out",notice:Ai("sign_out_unconfirmed",t)}:e.openingUnsynced?{kind:"starting"}:{kind:"signed_out",notice:null};if(n.status==="blocked"){let p=n.selectedCollectionId??o?.collectionId??null;return n.problem==="recovery_account_mismatch"?{kind:"problem",collectionId:p,problem:Us(n,{...t,recoveryAccountLabel:n.recoveryAccountLabel})}:{kind:"problem",collectionId:p,problem:p&&n.removedScopeIds?.includes(p)?Ai("installation_scope_removed",t):Ds(n,t)??Ai("open_failed",t)}}if(n.status==="needs_unlock"&&n.selectedCollectionId){let p=n.selectedCollectionId,d=n.unlock??null;return d?{kind:"needs_unlock",collectionId:p,displayName:n.collections.find(u=>u.collectionId===p)?.displayName??o?.displayName??null,mode:d.mode,unlocking:d.unlocking,problem:d.problem===null?null:Ds(d.problem,t)??Ai("unlock_failed",t)}:{kind:"problem",collectionId:p,problem:Ai("open_failed",t)}}if(i?.state==="approval_required"&&o?.collectionId&&n.removedScopeIds?.includes(o.collectionId))return{kind:"problem",collectionId:o.collectionId,problem:Ai("installation_scope_removed",t)};if(i?.state==="approval_required"&&o?.collectionId)return{kind:"needs_approval",collectionId:o.collectionId,displayName:o.displayName,declined:i.problem==="application_selection_not_approved"};if(i?.state==="blocked"&&o?.collectionId&&!o.approved)return{kind:"problem",collectionId:o.collectionId,problem:Ai("unavailable",t)};if(i?.state==="pending"&&o?.collectionId)return{kind:"opening",collectionId:o.collectionId,displayName:o.displayName,slow:!!e.slow};let a=i?.usable??(n.status==="ready"||n.status==="setup_required"?n.collections.find(p=>p.collectionId===n.selectedCollectionId)??null:null);if(n.status==="setup_required"&&a)return n.readiness.assessment?.status==="incompatible"?{kind:"problem",collectionId:a.collectionId,problem:Ds(n.readiness,t)??Ai("incompatible",t)}:{kind:"needs_setup",collectionId:a.collectionId,collection:a};if(n.status==="ready"&&a&&nh(e.connection,a.collectionId))return{kind:"ready",collectionId:a.collectionId,collection:a,connection:e.connection,rechecking:n.readiness.checking,problem:null,unavailableTypes:n.readiness.assessment?.unavailableTypes??[]};let c=n.status==="opening"||n.status==="ready"||i?.state==="opening"||i?.state==="usable",l=n.selectedCollectionId??o?.collectionId??null;if(c&&l){let p=n.collections.find(d=>d.collectionId===l)?.displayName??o?.displayName??null;return{kind:"opening",collectionId:l,displayName:p,slow:!!e.slow}}return e.startPending&&s&&n.status==="unselected"&&!n.problem&&i?.state==="none"?{kind:"starting"}:{kind:"choosing",lastApproval:i?.lastApproval??null}}function xM(n,e,t){let i=t.previous;return i?.kind==="needs_setup"&&n.kind==="opening"&&n.collectionId===i.collectionId&&e.selectedCollectionId===i.collectionId&&e.readiness.checking?i:i?.kind==="unsynced"&&n.kind==="opening"&&n.collectionId===i.collectionId&&e.selectedCollectionId===i.collectionId&&nh(t.connection,i.collectionId)?{...i,connection:t.connection,rechecking:!0}:!i||i.kind!=="ready"||n.kind==="ready"||!nh(t.connection,i.collectionId)||e.selectedCollectionId!==i.collectionId?n:n.kind==="opening"&&n.collectionId===i.collectionId?{...i,connection:t.connection,rechecking:!0,problem:null}:n.kind==="problem"&&n.problem.transient?{...i,connection:t.connection,rechecking:!0,problem:n.problem}:n}function Nx(n,e){return n?.kind==="ready"&&(e===void 0||n.collectionId===e)}Ll();Tp();Jt();hm();ym();_m();var Rr={runtime:{sha256:"30af71a27c5a97592a9380b3d9e3ce683542667fbced7fcd63a188e5d17ac643",bytes:4261471,maxBytes:4261471,source:{repository:"mdbase-dev/mdbase-connect",commit:"3af3e8e1bb878be36a4efc654c70590c413fdb44"}},sqlite:{sha256:"2ee8f3dab694532afc8840e07703127287662d08b74e6ff50491ce63f00d5752",bytes:868907,maxBytes:11e5,initializer:{sha256:"a6d3fe46aa3f924e7686329f97b0564549ef1f787e0c19924179aef7f72bcc01",bytes:642742},asyncProxy:{sha256:"9f1970e05ee07a79332498858740b705eeb1dcee03bc150f6f690bc0fb5f0a06",bytes:32505}}};Jt();re();St();var lj=Math.max(Rr.runtime.maxBytes,Rr.sqlite.maxBytes),Ri=n=>A("unavailable","application asset unavailable",n),cj=()=>A("cancelled","application asset read fenced","application_asset_fenced");function Or(n){if(n.aborted)throw cj()}function QC(n,e){let t=Object.freeze({...n}),i=Object.freeze({...e}),o,s;try{o=new URL(t.url),s=new URL(i.origin)}catch{throw Ri("application_asset_binding")}if(!ut(i.origin)||s.protocol!==o.protocol||!ts(i.environment)||Cr(i.environment)&&!ns(i.origin)||dt(o)!==i.origin||o.username||o.password||o.search||o.hash||!/^[0-9a-f]{64}$/.test(t.sha256)||!Number.isSafeInteger(t.bytes)||t.bytes<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<t.bytes||t.maxBytes>lj)throw Ri("application_asset_binding");let r=i.fetch??globalThis.fetch;if(typeof r!="function")throw Ri("application_asset_unavailable");let a=new URL(o.href);return a.searchParams.set("mdbase-sdk-asset",t.sha256),async({signal:c})=>{Or(c);let l=null,p;try{globalThis.caches&&(l=await globalThis.caches.open("mdbase.sdk.application-assets.v1"),p=await l.match(a.href))}catch{}let d=p!==void 0;if(!p){Or(c);try{p=await r(o.href,{signal:c,credentials:"omit",cache:"force-cache",redirect:"error"})}catch{throw Or(c),Ri("application_asset_fetch")}}let u=p.body?.getReader();if(!u)throw Or(c),Ri("application_asset_response");let f=!1,h=null,m=()=>h??=Promise.resolve().then(async()=>{try{await u.cancel()}catch{throw Ri("application_asset_stop_failed")}}),w=()=>{m().catch(()=>{})};c.addEventListener("abort",w,{once:!0});try{if(Or(c),!p.ok||p.redirected||p.url&&p.url!==o.href)throw Ri("application_asset_response");let b=p.headers.get("content-length"),g=p.headers.get("content-encoding");if(b!==null&&(g===null||g.trim().toLowerCase()==="identity")&&(!/^(?:0|[1-9][0-9]*)$/.test(b)||Number(b)!==t.bytes))throw Ri("application_asset_binding");let y=new Uint8Array(t.bytes),v=0;for(;;){let k=await u.read();if(Or(c),k.done){f=!0;break}if(!(k.value instanceof Uint8Array)||k.value.byteLength>t.bytes-v)throw Ri("application_asset_binding");y.set(k.value,v),v+=k.value.byteLength}if(v!==t.bytes)throw Ri("application_asset_binding");let _=new Uint8Array(await crypto.subtle.digest("SHA-256",y));if(Or(c),Array.from(_,k=>k.toString(16).padStart(2,"0")).join("")!==t.sha256)throw Ri("application_asset_binding");if(Or(c),l&&!d)try{await l.put(a.href,new Response(y))}catch{}return Or(c),y}catch(b){throw Or(c),J(b)?b:Ri("application_asset_response")}finally{c.removeEventListener("abort",w);try{(!f||c.aborted)&&await m()}finally{u.releaseLock()}}}}rs();Jt();re();gm();St();var Am={},pj=Object.freeze({sha256:Rr.runtime.sha256,bytes:Rr.runtime.bytes,maxBytes:Rr.runtime.maxBytes}),dj=Object.freeze({sha256:Rr.sqlite.sha256,bytes:Rr.sqlite.bytes,maxBytes:Rr.sqlite.maxBytes}),wd=()=>A("unavailable","SDK packaged application assets unavailable","application_packaged_assets_unavailable");function e1(n,e,t){if(!ts(n))throw wd();let i=Ks();Ci({environment:n,appOrigin:e,release:i});let o,s;try{let c=new URL(t??Am.url);if(dt(c)!==e||c.username||c.password||(o=t===void 0?new URL("../native/runtime.wasm",Am.url):new URL("../native/runtime.wasm",c),s=t===void 0?new URL("../native/sqlite3.wasm",Am.url):new URL("../native/sqlite3.wasm",c),dt(o)!==e||dt(s)!==e))throw wd()}catch{throw wd()}let r=(c,l)=>Object.freeze({url:c.href,...l}),a=async c=>{let l=globalThis.WorkerGlobalScope;if(typeof l!="function"||!(globalThis instanceof l))throw wd();let p=t===void 0?new URL("../native/sqlite3.js",Am.url):new URL("../native/sqlite3.js",t),{default:d}=await import(p.href);return globalThis.sqlite3ApiConfig={disable:{vfs:{opfs:!0,"opfs-wl":!0}}},d(c)};return Object.freeze({release:()=>Ks(),runtime:r(o,pj),sqlite:r(s,dj),initializeSqlite:a})}rp();var uj="mdbase:startup:",fj=new Set(["signed_out","authorizing","choosing","needs_approval","needs_setup","problem","unavailable","closed"]);function hj(){let n=globalThis.performance;return typeof n?.now=="function"&&typeof n.measure=="function"?n:null}var km=class{clock=hj();began=this.clock?.now()??0;stage=null;since=this.began;done=this.clock===null;measure(e,t,i){try{this.clock?.measure(`${uj}${e}`,{start:t,end:i})}catch{}}async time(e,t){if(this.done)return t();let i=this.clock.now();try{return await t()}finally{this.measure(e,i,this.clock.now())}}observe(e){if(this.done)return;let t=e.kind==="opening"&&e.progress?`opening:${e.progress}`:e.kind;if(t===this.stage)return;let i=this.clock.now();this.stage!==null&&this.measure(this.stage,this.since,i),this.stage=t,this.since=i;let o=e.kind==="ready"||e.kind==="unsynced";o&&this.measure("total",this.began,i),(o||fj.has(e.kind))&&(this.done=!0)}};function t1(n,e,t){if(n.requested.collectionId!==null){let i=n.requested.collectionId!==t?.selection.requested.collectionId;i&&fr("mdbase:open:requested"),n.requested.approved&&(i||!t?.selection.requested.approved)&&fr("mdbase:open:approved")}e.kind==="ready"&&(t?.phase.kind!=="ready"||t.phase.connection!==e.connection)&&fr("mdbase:open:ready")}gm();St();rs();Jt();var yn=class extends Error{constructor(t){super("SDK collection selection unavailable");this.code=t;this.name="ApplicationSelectionError"}code},vd=n=>typeof n=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(n)&&n!=="00000000-0000-0000-0000-000000000000",mn=(n,e,t=null)=>Object.freeze({requestedCollectionId:n,source:e,problem:t});function n1(n,e){return n.source!=="none"?n:e.storedId!==void 0&&e.storedId!==null?vd(e.storedId)?mn(e.storedId,"stored"):mn(null,"stored","application_selection_invalid"):e.collections.length>1024||e.collections.some(t=>!vd(t.collectionId))||new Set(e.collections.map(t=>t.collectionId)).size!==e.collections.length?mn(null,"none","application_selection_metadata"):e.preferredId!==void 0&&e.preferredId!==null?vd(e.preferredId)&&e.collections.some(t=>t.collectionId===e.preferredId)?mn(e.preferredId,"preferred"):mn(null,"preferred","application_selection_metadata"):e.collections.length===1?mn(e.collections[0].collectionId,"sole"):mn(null,"none")}var Sm=class{port;origin;parameter;fallback;listeners=new Set;snapshot=mn(null,"none");stopListening=null;started=!1;closed=!1;constructor(e,t={},i=null){let o,s;try{o=new URL(e),s=new URL(t.fallbackPath??"/",o)}catch{throw new yn("application_selection_binding")}let r=t.parameter??"collection";if(!ut(e)||dt(o)!==e||dt(s)!==e||s.username||s.password||s.search||s.hash||typeof r!="string"||!/^[a-z][a-zA-Z0-9_.-]{0,63}$/.test(r)||["code","state","error","error_description"].includes(r))throw new yn("application_selection_binding");this.origin=e,this.parameter=r,this.fallback=s.href,this.port=i}getSnapshot(){return this.snapshot}subscribe(e){return this.check(),this.listeners.add(e),()=>{this.listeners.delete(e)}}start(){return this.check(),this.started?this.snapshot:(this.started=!0,this.stopListening=this.port?.listen(()=>{this.closed||this.publish(this.read())})??null,this.publish(this.read()),this.snapshot)}check(){if(this.closed)throw new yn("application_selection_fenced")}url(){let e;try{e=new URL(this.port.href())}catch{throw new yn("application_selection_binding")}if(dt(e)!==this.origin||e.username||e.password)throw new yn("application_selection_binding");return e}read(){if(!this.port)return mn(null,"none");let e;try{e=this.url().searchParams.getAll(this.parameter)}catch{return mn(null,"url","application_selection_binding")}return e.length===0?mn(null,"none"):e.length!==1?mn(null,"url","application_selection_duplicate"):e[0]===""?mn(null,"url","application_selection_empty"):vd(e[0])?mn(e[0],"url"):mn(null,"url","application_selection_invalid")}publish(e){if(!(this.snapshot.requestedCollectionId===e.requestedCollectionId&&this.snapshot.source===e.source&&this.snapshot.problem===e.problem)){this.snapshot=e;for(let t of[...this.listeners])try{t()}catch{}}}select(e,t={}){if(this.check(),e!==null&&!vd(e))throw new yn("application_selection_invalid");let i=t.history??"replace";if(i!=="push"&&i!=="replace")throw new yn("application_selection_binding");if(this.port){let o=this.url(),s=o.href;e===null?o.searchParams.delete(this.parameter):o.searchParams.set(this.parameter,e),o.href!==s&&this.port.write(o.href,i)}return this.publish(mn(e,e===null?"none":"user")),this.snapshot}returnUrl(e){this.check();try{let t=new URL(e,this.origin);if(dt(t)===this.origin&&!t.username&&!t.password)return t.href}catch{}return this.fallback}close(){if(this.closed)return;this.closed=!0;let e=this.stopListening;this.stopListening=null,e?.(),this.listeners.clear()}};function i1(){if(typeof window>"u"||!window.location||!window.history)return null;let n=window;return Object.freeze({href:()=>n.location.href,write:(e,t)=>{t==="push"?n.history.pushState(n.history.state,"",e):n.history.replaceState(n.history.state,"",e)},listen:e=>(n.addEventListener("popstate",e),()=>n.removeEventListener("popstate",e))})}var mj=n=>typeof n=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(n)&&n!=="00000000-0000-0000-0000-000000000000",Ul=n=>n.status==="ready"||n.status==="setup_required",Nl=n=>n.status==="needs_unlock",r1=n=>n.signIn?.state==="paired"&&(n.status==="unselected"||n.status==="blocked"||Ul(n)||Nl(n)),yj=n=>n.status==="not_started"||n.status==="starting"||n.status==="signed_out"||n.status==="authorizing",Er=(n,e)=>e===null?null:n.collections.find(t=>t.collectionId===e)??null,Pm=class{browser;session;memory;preferredId;schedule;listeners=new Set;stops=[];value;key="";startTarget=null;startApplied=!1;startHeld=!0;failed=null;before=null;attempted=void 0;lastRequested=null;opening=null;approval=null;lastApproval=null;declined=null;remembered=void 0;queued=!1;started=!1;closed=!1;constructor(e){this.browser=e.browser,this.session=e.session,this.memory=e.memory??null,this.preferredId=e.preferredId??null,this.schedule=e.schedule??(t=>{setTimeout(t,0)}),this.value=this.derive(),this.key=this.keyOf(this.value)}startPending(){return this.startHeld}keyOf(e){return JSON.stringify(e)+(this.startHeld?"|start":"")}getSnapshot(){return this.value}subscribe(e){return this.check(),this.listeners.add(e),()=>{this.listeners.delete(e)}}start(){return this.check(),this.started?this.value:(this.started=!0,this.browser.start(),this.stops.push(this.browser.subscribe(this.changed),this.session.subscribe(this.changed)),this.changed(),this.value)}select(e,t={}){this.check(),this.startTarget=null,this.browser.select(e,t.history?{history:t.history}:{}),this.declined=null,this.refresh(),e===null&&this.remember(null);let i=this.session.getSnapshot();return e!==null&&i.selectedCollectionId===e&&i.status==="opening"?(this.attempted=e,Promise.resolve(this.value)):this.whenIdle(async()=>{let o=this.session.getSnapshot();this.requested().requestedCollectionId===e&&((e===null?o.selectedCollectionId===null&&o.status!=="opening":o.selectedCollectionId===e&&(Ul(o)||Nl(o))||!Er(o,e))||await this.run(e,t,!0))}).then(()=>this.value)}chooseAnother(e={}){return this.select(null,{...e,history:"push"})}approve(e,t={}){if(this.check(),e!=null&&!mj(e))return Promise.reject(new yn("application_selection_invalid"));if(this.approval&&!this.approval.settled)return Promise.reject(new yn("application_selection_busy"));e!=null&&e!==this.requested().requestedCollectionId&&(this.startTarget=null,this.browser.select(e,t.history?{history:t.history}:{}));let i=this.session.getSnapshot().signIn,o=i?.nativeSelection?.requestId??i?.collectionSelection?.requestId??null,s,r=e===null?null:this.requested().requestedCollectionId;try{s=this.session.authorize({...t.signal?{signal:t.signal}:{},collectionHint:r})}catch(p){return Promise.reject(p)}let a=r===null?"add":"collection",c=new Set(this.session.getSnapshot().collections.map(p=>p.collectionId)),l={receipt:o,kind:a,collectionId:r,before:c,settled:!1};return this.approval=l,this.lastApproval=null,this.declined=null,this.attempted=void 0,this.refresh(),s.then(()=>(l.settled=!0,this.changed(),this.value),p=>{if(this.approval===l){this.approval=null;let d=p?.code;(d==="cancelled"||d==="aborted")&&(this.lastApproval=Object.freeze({kind:a,outcome:"closed",collectionId:r}))}throw this.changed(),p})}clearLastApproval(){this.check(),this.lastApproval=null,this.refresh()}reauthorize(e={}){this.check();let t=this.value.usable?.collectionId??this.requested().requestedCollectionId;return t===null?Promise.reject(new yn("application_selection_empty")):this.approve(t,e)}resync(){this.closed||(this.attempted=void 0,this.failed=null,this.approval=null,this.changed())}close(){if(!this.closed){this.closed=!0;for(let e of this.stops.splice(0))try{e()}catch{}this.browser.close(),this.listeners.clear()}}check(){if(this.closed)throw new yn("application_selection_fenced")}requested(){let e=this.browser.getSnapshot(),t=this.startTarget;return t&&e.source==="user"&&e.requestedCollectionId===t.requestedCollectionId?t:e}changed=()=>{this.closed||(this.refresh(),!(this.queued||!this.started)&&(this.queued=!0,this.schedule(()=>{this.queued=!1,this.reconcile()})))};refresh(){let e=this.requested().requestedCollectionId;if(e!==this.lastRequested&&(this.lastRequested=e,this.attempted=void 0,this.failed=null,this.declined!==e&&(this.declined=null)),e!==null&&this.attempted===e){let o=this.session.getSnapshot();o!==this.before&&(o.status==="blocked"?o.selectedCollectionId===e:o.status==="unselected"&&o.problem!==null)&&(this.failed=e)}let t=this.derive(),i=this.keyOf(t);if(t.state==="usable"&&this.remember(t.usable.collectionId),i!==this.key){this.key=i,this.value=Object.freeze(t);for(let o of[...this.listeners])try{o()}catch{}}}remember(e){if(!(!this.memory||this.remembered===e)){this.remembered=e;try{this.memory.write(e)}catch{}}}derive(){let e=this.session.getSnapshot(),t=this.requested(),i=t.requestedCollectionId,o=Er(e,i),s=Ul(e)?Er(e,e.selectedCollectionId):null,r,a=null;if(t.problem)r="invalid",a=t.problem;else if(this.approval)r="approving";else if(i===null)r="none";else if(s?.collectionId===i)r="usable";else if(e.selectedCollectionId===i&&(e.status==="blocked"||e.status==="opening"||Nl(e)))r=e.status==="blocked"?"blocked":"opening";else if(!r1(e))r="pending";else if(o)r="opening";else{let l=this.session.listing?.();l==="unavailable"?r="blocked":l?r="pending":(r="approval_required",this.declined===i&&(a="application_selection_not_approved"))}let c=this.approval?Object.freeze({kind:this.approval.kind,collectionId:this.approval.collectionId,reopenable:this.approval.settled}):null;return Object.freeze({state:r,problem:a,approval:c,lastApproval:this.lastApproval,usable:s?Object.freeze({...s}):null,requested:Object.freeze({collectionId:i,source:t.source,displayName:o?.displayName??null,approved:o!==null})})}async whenIdle(e){for(;this.opening;)await this.opening;this.check(),await e()}run(e,t={},i=!1){this.attempted=e,this.failed=null,this.before=this.session.getSnapshot();let o=t.signal?{signal:t.signal}:{},s=Promise.resolve().then(()=>e===null?this.session.clear(o):this.session.open(e,o)),r=s.then(()=>{},()=>{}).finally(()=>{this.opening===r&&(this.opening=null,this.changed())});return this.opening=r,i?s.then(()=>{}):r}async reconcile(){if(this.closed||this.opening)return;let e=this.session.getSnapshot();if(this.approval)if(this.approval.settled&&e.status==="signed_out"&&(e.problem!==null||e.approval?.outcome==="closed")){let o=this.approval;this.approval=null,this.attempted=void 0,this.lastApproval=Object.freeze({kind:o.kind,outcome:e.problem==="approval_window_closed"||e.approval?.outcome==="closed"?"closed":"declined",collectionId:o.collectionId}),this.refresh()}else{if(!this.approval.settled||yj(e))return;let o=e.signIn?.nativeSelection;if(o&&o.requestId!==this.approval.receipt&&!Er(e,o.collectionId)&&this.session.listing?.()===!0)return;this.finishApproval(e)}if(!r1(e))return;if(!this.startApplied){if(this.browser.getSnapshot().source==="none"){let o=null;try{o=this.memory?.read()??null}catch{}if(o!==null&&!Er(e,o)&&this.session.listing?.()){this.startHeld=!1,this.refresh();return}this.startApplied=!0;let s=n1(this.browser.getSnapshot(),{storedId:o,preferredId:this.preferredId,collections:e.collections});s.requestedCollectionId!==null&&!s.problem&&(this.browser.select(s.requestedCollectionId,{history:"replace"}),this.startTarget=s)}else this.startApplied=!0;this.startHeld=!1,this.refresh()}let t=this.requested(),i=t.requestedCollectionId;if(!t.problem){if(i===null){this.attempted!==null&&e.selectedCollectionId!==null&&(Ul(e)||Nl(e))&&this.run(null);return}if(e.selectedCollectionId===i&&(Ul(e)||Nl(e)||e.status==="opening")){this.attempted=i,this.failed=null;return}if(e.selectedCollectionId===i&&e.status==="blocked"){this.failed=i;return}Er(e,i)&&(this.attempted===i&&(this.failed!==i||e.status!=="unselected"||e.problem!==null)||(this.failed=null,this.run(i)))}}finishApproval(e){let t=this.approval,i=t.receipt;this.approval=null,this.attempted=void 0;let o=u=>u!==null&&Er(e,u)?t.before.has(u)?"unchanged":"added":e.approval?.outcome==="closed"?"closed":"declined",s=e.signIn?.collectionSelection,r=e.signIn?.nativeSelection,c=(r&&r.requestId!==i&&Er(e,r.collectionId)?r.collectionId:null)??(s&&s.requestId!==i&&Er(e,s.selectedCollectionId)?s.selectedCollectionId:null);if(c!==null){c!==this.requested().requestedCollectionId&&(this.startTarget=null,this.browser.select(c,{history:"replace"})),this.lastApproval=Object.freeze({kind:t.kind,outcome:o(c),collectionId:c}),this.refresh(),e.selectedCollectionId===c&&(Ul(e)||Nl(e)||e.status==="opening")?this.attempted=c:this.run(c);return}let l=this.requested().requestedCollectionId;l!==null&&!Er(e,l)&&(this.declined=l);let p=t.kind==="add"?e.collections.find(u=>!t.before.has(u.collectionId))?.collectionId??null:null,d=t.kind==="add"?p:t.collectionId??l;this.lastApproval=Object.freeze({kind:t.kind,outcome:o(d),collectionId:d}),this.refresh()}};qd();x_();re();t_();var ic="unsynced",xU="current";var V_="moved.",oy=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/;var F_=class extends Error{constructor(t){super(`app unsynced collection: ${t}`);this.reason=t;this.name="AppUnsyncedCollectionError"}reason},Jn=(n="unavailable")=>new F_(n);function IU(n){if(!n||typeof n!="object"||Array.isArray(n)||Object.keys(n).some(i=>!["version","account","installation","collection","replica","device","timezone"].includes(i)))throw Jn();let e=n,t=[e.account,e.installation,e.collection,e.replica,e.device];if(e.version!==1||t.some(i=>typeof i!="string"||!oy.test(i))||new Set(t).size!==t.length||"timezone"in e&&e.timezone!==null&&!Im(e.timezone))throw Jn();return Object.freeze({...e})}function gR(n,e){if(e.throwIfAborted(),!globalThis.indexedDB)throw Jn();return new Promise((t,i)=>{let o=indexedDB.open(n,1),s=!1,r=()=>e.removeEventListener("abort",a),a=()=>{s=!0,r();try{o.transaction?.abort()}catch{}i(Jn("fenced"))};e.addEventListener("abort",a,{once:!0}),o.onblocked=o.onerror=a,o.onupgradeneeded=()=>{try{if(s||o.result.objectStoreNames.length)throw Jn();o.result.createObjectStore(ic)}catch{try{o.transaction?.abort()}catch{}}},o.onsuccess=()=>{if(r(),s||o.result.objectStoreNames.length!==1||!o.result.objectStoreNames.contains(ic)){o.result.close(),i(Jn());return}t(o.result)}})}async function CU(n,e,t,i,o){let s=await gR(n,o);try{return await new Promise((r,a)=>{let c=s.transaction(ic,i?"readwrite":"readonly",{durability:"strict"}),l=null,p=null;c.onabort=c.onerror=()=>a(p??Jn()),c.oncomplete=()=>r(l);let d=c.objectStore(ic),u=d.get(e);u.onsuccess=()=>{try{if(u.result!==void 0){l=t(u.result);return}if(!i)return;let f=t(i());d.add(f,e),l=f}catch(f){p=f,c.abort()}}})}finally{s.close()}}async function RU(n,e,t){let i=await gR(n,e);try{return await new Promise((o,s)=>{let r=i.transaction(ic,"readwrite",{durability:"strict"}),a,c=null;r.onabort=r.onerror=()=>s(c??Jn()),r.oncomplete=()=>o(a),t(r.objectStore(ic),l=>{a=l},l=>{c=l,r.abort()})})}finally{i.close()}}var bR=/^sha256:[0-9a-f]{64}$/;function wR(n){let e=n;if(!e||e.version!==1||!e.revisions||typeof e.revisions!="object"||Array.isArray(e.revisions))throw Jn();let t=new Map;for(let[i,o]of Object.entries(e.revisions)){if(!oy.test(i)||typeof o!="string"||!bR.test(o))throw Jn();t.set(i,o)}return t}async function vR(n,e,t){if(!oy.test(e))throw Jn("binding");return await CU(n,V_+e,wR,null,t)??new Map}function _R(n,e,t,i){for(let[o,s]of t)if(!oy.test(o)||!bR.test(s))return Promise.reject(Jn("binding"));return RU(n,i,(o,s,r)=>{let a=o.get(xU),c=o.get(V_+e);c.onsuccess=()=>{try{if(a.result===void 0||IU(a.result).collection!==e){r(Jn());return}let l=c.result===void 0?new Map:wR(c.result);for(let[p,d]of t)l.set(p,d);o.put({version:1,revisions:Object.fromEntries(l)},V_+e),s()}catch(l){r(l)}}})}var zG=720*60*60*1e3;re();var K_=new WeakMap,OU=100,EU=(n,e)=>`unsynced/1\0${n}\0${e}`;async function sy(n,e,t){try{return await n.get(e,{signal:t})}catch(i){if(J(i,"not_found"))return null;throw i}}function qU(n,e){let t=n.lastIndexOf("/"),i=n.lastIndexOf("."),o=i>t+1?i:n.length;return`${n.slice(0,o)} ${e}${n.slice(o)}`}async function TU(n,e){let t=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`unsynced/1\0copy\0${n}\0${e}`))).slice(0,16);t[6]=t[6]&15|128,t[8]=t[8]&63|128;let i=[...t].map(o=>o.toString(16).padStart(2,"0")).join("");return`${i.slice(0,8)}-${i.slice(8,12)}-${i.slice(12,16)}-${i.slice(16,20)}-${i.slice(20)}`}function MU(n){if(n.document===void 0)throw A("invalid_request","the source record has no document");return{path:n.path,document:n.document}}async function W_(n,e,t={}){let{signal:i}=t,o=t.map??MU;if(n.collection===e.collection)throw A("invalid_request","a collection cannot be transferred into itself");let s=t.ledger?await t.ledger.read(n.collection,i):new Map,r=new Map,a=await e.describe(i?{signal:i}:{}),c=new Set(a.types.map(b=>b.name.toLowerCase())),l=[],p=new Map,d=new Set,u=new Set,f=0;for await(let b of n.pages({},{include:{body:!0,document:!0},signal:i}))for(let g of b.records){i?.throwIfAborted();let y=null;if(await sy(e,g.id,i)){let S=s.get(g.id);if(S===void 0&&r.set(g.id,g.revision),S===void 0||S===g.revision){l.push(Object.freeze({sourceId:g.id,sourcePath:g.path,outcome:"present"}));continue}if(y=await TU(g.id,g.revision),await sy(e,y,i)){r.set(g.id,g.revision),l.push(Object.freeze({sourceId:g.id,sourcePath:g.path,outcome:"present"}));continue}}let v=await o(g);if(v===null){l.push(Object.freeze({sourceId:g.id,sourcePath:g.path,outcome:"skipped"}));continue}if(!v||typeof v!="object"||v.id!==void 0&&v.id!==g.id)throw A("invalid_request","the transfer map must keep the record ID");r.set(g.id,g.revision);let _=v.path??g.path,k=_;for(let S=2;d.has(k.toLowerCase())||await sy(e,{path:k},i);S++){if(S>OU)throw A("conflict",`no free path beside ${_}`,"path_taken");k=qU(_,S)}d.add(k.toLowerCase());for(let S of v.type?[v.type]:g.types)c.has(S.toLowerCase())||u.add(S);p.set(g.id,Object.freeze({...v,id:y??g.id,path:k})),k!==_&&!y&&f++,l.push(Object.freeze({sourceId:g.id,sourcePath:g.path,outcome:y?"changed":"create",path:k,...y?{copyId:y}:k!==_?{renamedFrom:_}:{}}))}let h=new Map;if(t.addTypes&&u.size){let b=new Map((await n.describe(i?{signal:i}:{})).types.map(g=>[g.name.toLowerCase(),g]));for(let g of[...u].sort()){let y=b.get(g.toLowerCase());if(!y?.revision)continue;let v;try{v=(await n.resources.get(y.path,{signal:i})).text}catch(_){if(J(_,"not_found"))continue;throw _}typeof v=="string"&&(h.set(y.name,v),u.delete(g))}}let m=b=>l.filter(g=>g.outcome===b).length,w=Object.freeze({source:n.collection,destination:e.collection,items:Object.freeze(l),missingTypes:Object.freeze([...u].sort()),addTypes:Object.freeze([...h.keys()].sort()),counts:Object.freeze({create:m("create"),present:m("present"),skipped:m("skipped"),renamed:f,changed:m("changed")})});return K_.set(w,Object.freeze({inputs:p,types:h,map:t.map,ledger:t.ledger,settle:r})),w}async function AR(n,e,t,i){let o=K_.get(n);if(!o)throw A("invalid_request","plan the transfer first");if(e.collection!==n.source||t.collection!==n.destination)return!1;let s=await W_(e,t,{...o.map?{map:o.map}:{},...o.ledger?{ledger:o.ledger}:{},...i?{signal:i}:{}});return s.counts.create===0&&s.counts.changed===0}async function kR(n,e,t={}){let i=K_.get(n),{signal:o}=t;if(!i)throw A("invalid_request","plan the transfer first");let{inputs:s}=i;if(e.collection!==n.destination)throw A("invalid_request","the plan is for another collection");let r=n.items.filter(m=>m.outcome==="create"||m.outcome==="changed"),a=[],c=[],l=0,p=n.counts.present,d=0,u=()=>{try{t.onProgress?.(Object.freeze({done:d,total:r.length}))}catch{}};i.ledger&&i.settle.size&&await i.ledger.record(n.source,i.settle,o);let f=[],h=[];for(let[m,w]of i.types){o?.throwIfAborted();try{await e.createType(w,o?{signal:o}:{}),f.push(m)}catch(b){o?.throwIfAborted(),J(b,"conflict")?f.push(m):h.push(Object.freeze({name:m,code:J(b)?b.code:"unavailable"}))}}u();for(let m of r){o?.throwIfAborted();try{let w=await e.create(s.get(m.sourceId),{intent:EU(n.source,m.copyId??m.sourceId),...o?{signal:o}:{}});c.push(w.mutationId),l++}catch(w){o?.throwIfAborted(),await sy(e,m.copyId??m.sourceId,o).catch(()=>null)?p++:a.push(Object.freeze({sourceId:m.sourceId,code:J(w)?w.code:"unavailable"}))}d++,u()}return Object.freeze({source:n.source,destination:n.destination,created:l,present:p,skipped:n.counts.skipped,failed:Object.freeze(a),addedTypes:Object.freeze(f),failedTypes:Object.freeze(h),mutations:Object.freeze(c),retired:!1})}zd();Gf();os();oh();var RR="mdbn-app-tabs/1",J_="\0mdbn-port";var $d=n=>typeof n=="string"&&/^[0-9a-f-]{36}$/.test(n);function UU(n){if(!n||typeof n!="object")return null;let e=n;switch(e.k){case"join":case"leave":return $d(e.tab)?e:null;case"leader":case"bye":case"fault":case"signedOut":case"signedIn":return $d(e.leader)?e:null;case"joined":return $d(e.tab)&&$d(e.leader)&&typeof e.binding=="string"?e:null;case"m":return $d(e.tab)&&typeof e.up=="boolean"&&Number.isSafeInteger(e.s)&&e.s>=0?e:null;default:return null}}function X_(n){if(!n||typeof n!="object")return!1;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}function Z_(n,e,t=0){return n instanceof MessagePort?{[J_]:e(n)}:t>=6?n:Array.isArray(n)?n.map(i=>Z_(i,e,t+1)):X_(n)?Object.fromEntries(Object.entries(n).map(([i,o])=>[i,Z_(o,e,t+1)])):n}function Q_(n,e,t,i=0){if(X_(n)&&Object.keys(n).length===1&&Number.isSafeInteger(n[J_])){let o=e(n[J_]);return t.push(o),o}return i>=6?n:Array.isArray(n)?n.map(o=>Q_(o,e,t,i+1)):X_(n)?Object.fromEntries(Object.entries(n).map(([o,s])=>[o,Q_(s,e,t,i+1)])):n}var cy=class{constructor(e,t){this.send=e;this.up=t;this.next=t?1:2}send;up;streams=new Map;next;bridge(e,t){this.streams.set(t,e),e.onmessage=i=>{let o=i.ports.length?Z_(i.data,s=>{let r=this.next;return this.next+=2,this.bridge(s,r),r}):i.data;try{this.send(t,o)}catch{}}}deliver(e,t){let i=this.streams.get(e);if(!i)return;let o=[],s=Q_(t,r=>{let a=new MessageChannel;return this.bridge(a.port1,r),a.port2},o);try{i.postMessage(s,o)}catch{for(let r of o)r.close()}}close(){for(let e of this.streams.values()){e.onmessage=null;try{e.close()}catch{}}this.streams.clear()}},py=class{constructor(e,t,i,o=()=>{},s={}){this.env=t;this.lost=i;this.signedInElsewhere=o;this.role=s;this.base=e.storageNamespace===void 0?`${RR}/${e.cpOrigin}/${e.appId}/${e.build}`:`${RR}/namespace/${JSON.stringify([e.cpOrigin,e.appId,e.build,e.storageNamespace])}`}env;lost;signedInElsewhere;role;tab=crypto.randomUUID();base;channel=null;presence=null;leading=null;hub=null;follower=null;signingOut=!1;announced=!1;joining=null;get leader(){return this.leading!==null}open(){if(this.channel)return this.channel;let e=new this.env.BroadcastChannel(this.base);return e.onmessage=t=>this.received(UU(t.data)),this.channel=e,e}post(e){this.channel?.postMessage(e)}hold(e,t,i){return new Promise((o,s)=>{let r=c=>{if(!c){o(null);return}return new Promise(l=>o(l))};(t?this.env.locks.request(e,{ifAvailable:!0},r):this.env.locks.request(e,{signal:i},r)).catch(s)})}async elect(e){e.throwIfAborted(),this.open(),this.presence??=await this.hold(`${this.base}/tab/${this.tab}`,!0),e.throwIfAborted();let t=this.role.lead!==!1;if(t&&!this.leading&&(this.leading=await this.hold(`${this.base}/leader`,!0)),this.leading)return e.aborted&&(this.resign(),e.throwIfAborted()),{kind:"leader"};let i=new AbortController,o=()=>i.abort();e.addEventListener("abort",o,{once:!0});let s=t?this.hold(`${this.base}/leader`,!1,i.signal):null,r;try{r=await new Promise((d,u)=>{s?.then(f=>{f&&d({release:f})},()=>{}),this.joining={resolve:d,reject:u},e.addEventListener("abort",()=>u(e.reason),{once:!0}),this.join()})}catch(d){throw this.joining=null,i.abort(),d}finally{e.removeEventListener("abort",o)}if(this.joining=null,"release"in r)return this.leading=r.release,e.aborted&&(this.resign(),e.throwIfAborted()),{kind:"leader"};e.aborted&&(i.abort(),e.throwIfAborted());let a=new MessageChannel,c=this.tab,l=new cy((d,u)=>this.post({k:"m",tab:c,up:!0,s:d,d:u}),!0);l.bridge(a.port2,0);let p={leader:r.leader,tunnel:l,wait:i,port:a.port1,left:!1,signedOut:!1};return this.follower=p,(s??this.hold(`${this.base}/leader`,!1,i.signal)).then(d=>{if(!d)return;let u=this.follower===p&&!p.left;u&&t?this.leading=d:d(),u&&this.departed(p)},()=>{}),{kind:"follower",port:a.port1,binding:r.binding,leave:()=>this.leave(p)}}join(){this.post({k:"join",tab:this.tab,...this.role.lead===!1?{needsLeader:!0}:{}})}lead(e){!this.leading||this.hub||(this.hub={followers:new Map,worker:e,faulted:!1},this.post({k:"leader",leader:this.tab}))}fault(){!this.hub||this.hub.faulted||(this.hub.faulted=!0,this.post({k:"fault",leader:this.tab}))}signedOut(){this.hub&&(this.signingOut=!0,this.post({k:"signedOut",leader:this.tab}))}signedIn(){!this.hub||this.announced||this.signingOut||(this.announced=!0,this.post({k:"signedIn",leader:this.tab}))}resign(){let e=this.hub,t=this.signingOut;this.hub=null,this.signingOut=!1,this.announced=!1,e&&this.post({k:"bye",leader:this.tab,...t?{signedOut:!0}:{}});let i=this.leading;if(this.leading=null,i?.(),e){for(let o of e.followers.values())o.watch.abort(),o.tunnel.close();e.followers.clear()}}leave(e){e.left||(e.left=!0,e.wait.abort(),e.tunnel.close(),this.follower===e&&(this.follower=null,this.post({k:"leave",tab:this.tab})))}departed(e,t=!1){e.left||this.follower!==e||(e.left=!0,e.wait.abort(),e.tunnel.close(),this.follower=null,this.lost(t||e.signedOut))}release(){this.joining?.reject(new DOMException("released","AbortError")),this.joining=null,this.follower&&this.leave(this.follower),this.resign();let e=this.presence;this.presence=null,e?.(),this.channel&&(this.channel.onmessage=null,this.channel.close(),this.channel=null)}received(e){if(!e)return;let t=this.hub,i=this.follower;switch(e.k){case"join":{if(!t&&e.needsLeader===!0&&this.role.lead!==!1&&!this.leading&&!i&&!this.joining&&this.hold(`${this.base}/leader`,!0).then(l=>{l&&(l(),this.role.wanted?.())},()=>{}),!t||t.followers.has(e.tab)||e.tab===this.tab)return;let o=crypto.randomUUID(),s=new MessageChannel,r=e.tab,a=new cy((l,p)=>this.post({k:"m",tab:r,up:!1,s:l,d:p}),!1);a.bridge(s.port1,0);let c=new AbortController;t.followers.set(r,{binding:o,tunnel:a,watch:c});try{t.worker.attach(s.port2,o)}catch{t.followers.delete(r),a.close();return}this.post({k:"joined",tab:r,binding:o,leader:this.tab}),t.faulted&&this.post({k:"fault",leader:this.tab}),this.hold(`${this.base}/tab/${r}`,!1,c.signal).then(l=>{l?.(),this.drop(t,r)},()=>{});return}case"leave":t&&this.drop(t,e.tab);return;case"joined":if(e.tab===this.tab&&this.joining){let o=this.joining;this.joining=null,o.resolve({binding:e.binding,leader:e.leader})}return;case"leader":this.joining&&this.join();return;case"bye":i&&i.leader===e.leader&&this.departed(i,e.signedOut===!0);return;case"signedOut":i&&i.leader===e.leader&&(i.signedOut=!0);return;case"signedIn":!t&&!i&&!this.joining&&e.leader!==this.tab&&this.signedInElsewhere();return;case"fault":i&&!i.left&&i.leader===e.leader&&i.port.dispatchEvent(new MessageEvent("messageerror"));return;case"m":e.up&&t?t.followers.get(e.tab)?.tunnel.deliver(e.s,e.d):!e.up&&i&&e.tab===this.tab&&i.tunnel.deliver(e.s,e.d);return}}drop(e,t){let i=e.followers.get(t);if(i){e.followers.delete(t),i.watch.abort(),i.tunnel.close();try{e.worker.detach(i.binding)}catch{}}}};function Mr(n){try{return n()}catch{return}}function NU(){let n=Mr(()=>globalThis.crypto?.subtle),e=Mr(()=>globalThis.navigator?.storage),t=Mr(()=>typeof e?.getDirectory=="function"?()=>e.getDirectory.call(e):void 0);return{subtle:n,abortSignalAny:Mr(()=>typeof AbortSignal=="function"&&typeof AbortSignal.any=="function")===!0,randomUUID:Mr(()=>typeof globalThis.crypto?.randomUUID=="function")===!0,worker:Mr(()=>typeof Worker=="function")===!0,messageChannel:Mr(()=>typeof MessageChannel=="function")===!0,locks:Mr(()=>typeof globalThis.navigator?.locks?.request=="function")===!0,broadcastChannel:Mr(()=>typeof BroadcastChannel=="function")===!0,indexedDB:Mr(()=>typeof globalThis.indexedDB<"u")===!0,getDirectory:t}}async function OR(n=NU(),e=!0){let t=[];if(n.subtle||t.push("web_crypto"),n.abortSignalAny||t.push("abort_signal_any"),n.randomUUID||t.push("random_uuid"),e&&!n.worker&&t.push("worker"),n.messageChannel||t.push("message_channel"),n.locks||t.push("web_locks"),n.broadcastChannel||t.push("broadcast_channel"),n.indexedDB||t.push("indexed_db"),n.subtle)try{await n.subtle.generateKey({name:"X25519"},!1,["deriveBits"])}catch{t.push("x25519")}if(t.length)return{ok:!1,problem:"browser_unsupported",missing:Object.freeze(t)};if(typeof n.getDirectory!="function")return{ok:!1,problem:"application_storage_unavailable",missing:Object.freeze(["opfs"])};try{await n.getDirectory()}catch{return{ok:!1,problem:"application_storage_unavailable",missing:Object.freeze(["opfs"])}}return{ok:!0}}function dy(n,e,t={pendingForMs:0,connection:"online"}){if(!Number.isSafeInteger(n)||n<0)throw new RangeError("invalid unsynced count");return n===0?{kind:"no_pending_edits",unsynced:0,warning:null}:{kind:"not_yet_synced",unsynced:n,warning:!e.persistent&&(t.pendingForMs>=3e4||t.connection==="offline")?"storage_may_be_evicted":null}}function ER(n){switch(n){case"pending":return"not_yet_synced";case"confirmed":return"saved";case"rejected":return"rejected";case"unknown":return"outcome_unknown";default:throw new RangeError("invalid receipt state")}}var qR="Some changes are only on this device. Stay online so they can sync.";async function uy(n,e,t=!1){let i=!1;try{i=await n?.persisted()===!0,!i&&t&&(i=await n?.persist?.()===!0)}catch{}return{persistent:i,installed:e}}hy();var jR=Object.freeze(new Set);function UR(n,e){let t=`mdbase.${n}.forgotten-collections.v1.${encodeURIComponent(e)}`,i=()=>{try{return globalThis.localStorage??null}catch{return null}},o=null,s=()=>{let a=null;try{a=i()?.getItem(t)??null}catch{}if(o&&o.raw===a)return o;let c=null,l=jR;try{let p=a?JSON.parse(a):null;p?.v===1&&typeof p.account=="string"&&p.account.length<=64&&Array.isArray(p.ids)&&p.ids.length<=1024&&p.ids.every(d=>typeof d=="string"&&d.length>0&&d.length<=64)&&(c=p.account,l=Object.freeze(new Set(p.ids)))}catch{}return o={raw:a,account:c,ids:l},o},r=(a,c)=>{try{c.size?i()?.setItem(t,JSON.stringify({v:1,account:a,ids:[...c].slice(-1024)})):i()?.removeItem(t)}catch{}o=null};return Object.freeze({read(a){let c=s();return a&&c.account===a?c.ids:jR},add(a,c){let l=s(),p=new Set(l.account===a?l.ids:[]);p.has(c)||(p.add(c),r(a,p))},remove(a,c){let l=s();if(l.account!==a||!l.ids.has(c))return!1;let p=new Set(l.ids);return p.delete(c),r(a,p),!0},clear(){try{i()?.removeItem(t)}catch{}o=null}})}var KU=new Set(["owner","editor","viewer"]),ls=(n,e=512)=>typeof n=="string"&&n.length>0&&n.length<=e,WU=new Set(["unselected","opening","setup_required","ready"]);function NR(n){let e=n;return!e||typeof e!="object"||!ls(e.collectionId,64)||typeof e.displayName!="string"||e.displayName.length>512||!KU.has(e.role)?null:Object.freeze({collectionId:e.collectionId,displayName:e.displayName,role:e.role})}function DR(n){let e=n;return!e||typeof e!="object"||e.state!=="paired"||!ls(e.requestId,64)||!ls(e.installationId,64)||!ls(e.deviceId,64)||!ls(e.appId,64)||e.kind!=="app-runtime"&&e.kind!=="mobile"||!ls(e.verificationUri,2048)||!ls(e.accountId,64)||!Array.isArray(e.collectionIds)||e.collectionIds.length>1024||!e.collectionIds.every(t=>ls(t,64))?null:Object.freeze({requestId:e.requestId,installationId:e.installationId,deviceId:e.deviceId,appId:e.appId,kind:e.kind,verificationUri:e.verificationUri,state:"paired",accountId:e.accountId,...typeof e.accountEmail=="string"&&e.accountEmail.length<=320?{accountEmail:e.accountEmail}:{},collectionIds:Object.freeze([...e.collectionIds]),createCollections:e.createCollections===!0,requestedCreateCollections:e.requestedCreateCollections===!0})}function zR(n,e){let t=`mdbase.${n}.session-hint.v1.${encodeURIComponent(e)}`,i=null,o=null,s=()=>{try{return globalThis.localStorage??null}catch{return null}},r=()=>{let c=null;try{c=s()?.getItem(t)??null}catch{return null}if(i&&i.raw===c)return i.value;let l=null;try{let p=c?JSON.parse(c):null,d=p?.v===1?DR(p.signIn):null,u=Array.isArray(p?.collections)&&p.collections.length<=1024?p.collections.map(NR):null;d&&u&&u.every(f=>f!==null)&&(l=Object.freeze({signIn:d,collections:Object.freeze(u)}))}catch{l=null}return i={raw:c,value:l},l},a=()=>{o=null;try{s()?.removeItem(t)}catch{}};return Object.freeze({read:r,clear:a,observe(c){if(c.status==="signed_out"&&c.signIn===null){o!==""&&(a(),o="");return}if(!WU.has(c.status)||c.signIn?.state!=="paired")return;let l=DR(c.signIn),p=c.collections.map(NR);if(!l||!p.every(u=>u!==null))return;let d=JSON.stringify({v:1,signIn:l,collections:p});if(d!==o){o=d;try{s()?.setItem(t,d)}catch{}}}})}tA();re();ym();Jt();rp();un();function m8(n,e){return new Promise((t,i)=>{let o=()=>{clearTimeout(s),i(A("cancelled","The original collection closed."))};if(n.aborted){i(A("cancelled","The original collection closed."));return}let s=setTimeout(()=>{n.removeEventListener("abort",o),t()},e);n.addEventListener("abort",o,{once:!0})})}var y8=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,mc=Object.freeze({checking:!1,assessment:null,problem:null}),g8=Object.freeze({capabilities:mc,contracts:mc,configuration:mc,files:mc,people:mc,notifications:mc}),$r=(n,e)=>{let t=e?Object.freeze({status:e,problem:e==="incompatible"?Object.freeze({code:"incompatible"}):null}):null;return Object.freeze({checking:n,assessment:t,problem:null,facets:Object.freeze({...g8,configuration:Object.freeze({checking:n,assessment:t,problem:null})})})},Vy=n=>n==="approval_required"?"device_approval_required":n,b8=n=>n.state==="opening"||n.state==="unavailable"&&n.reason!=="sync_required"&&n.reason!=="access_removed"&&n.reason!=="collection_deleted",FA=n=>{if(J(n)){let e=de(n.details,"availability");return typeof e=="string"?Vy(e):n.reason??n.code}return"open_failed"},KA=n=>{if(!J(n))return;let e=$R(n.details);return Object.freeze({name:"MdbaseError",code:n.code,...e?{relay:e}:{}})};function w8(n){let e=n.manifest?.redirect_uris,t=Array.isArray(e)?e.filter(i=>typeof i=="string"):[];if(n.origin.startsWith("capacitor://")){let i=t.find(o=>jl(o,n.origin,n.manifest));if(!i)throw A("invalid_request","Declare an iOS Private collection callback in redirect_uris","redirect_uri");return i}return t.find(i=>{try{return dt(new URL(i))===n.origin}catch{return!1}})??new URL("/",n.origin).href}function mE(n,e,t){if(n.signIn?.state!=="paired"||!e.length&&!t)return n;let i=new Set(n.collections.map(c=>c.collectionId)),o=e.filter(c=>!i.has(c.collectionId)),s=o.length?Object.freeze([...n.collections,...o]):n.collections;if(!t||n.status!=="unselected"||i.has(t.collectionId))return s===n.collections?n:Object.freeze({...n,collections:s});let{problemDetail:r,...a}=n;return Object.freeze({...a,collections:s,status:t.status,selectedCollectionId:t.collectionId,problem:t.problem,transport:null,live:null,...t.problemDetail?{problemDetail:t.problemDetail}:{},..."readiness"in n?{readiness:t.readiness}:{}})}var Fy=class{options;loading=null;list=Object.freeze([]);open=null;listed=null;failedListing=null;refreshing=null;closed=!1;bindings=null;bindingsAccount=null;native=null;revision=0;constructor(e){this.options=e}grants(){let e=this.loading??=(this.options.grants??(async()=>{let{MdbaseAppGrants:t}=await Promise.resolve().then(()=>(hE(),fE));return new t({declaration:this.options.declaration,redirectUri:this.options.grantRedirectUri??w8(this.options.declaration)})}))();return e.catch(()=>{this.loading===e&&(this.loading=null)}),e}changed(){if(!this.closed){this.revision++;try{this.options.onChange()}catch{}}}bind(e,t){let i=t.filter(r=>r.account_id===e);if(this.bindingsAccount===e&&JSON.stringify(i)===JSON.stringify(this.bindings))return;let o=this.bindings;this.bindingsAccount=e,this.bindings=Object.freeze([...i]),this.failedListing=null,this.listed=null;let s=this.open;if(s){let r=o?.find(c=>c.collection_id===s.id),a=i.find(c=>c.collection_id===s.id);!a||e!==s.scope.account?this.close(!1):(a.grant_id!==r?.grant_id||a.client_noise_public_key!==r?.client_noise_public_key)&&this.openCollection(s.id,s.scope).catch(()=>{})}this.setList([])}async nativeAuthorization(e,t,i){if(e.action==="cancel")return this.native?.life.abort(),this.native?.prepared?.cancel(),this.native=null,null;if(this.closed||i.aborted)throw A("cancelled","Original Native authorization fenced");if(e.action==="prepare"){if(this.native||e.value.authorizationId)throw A("unauthenticated","Original Native preparation unavailable");let a={context:e.value,portal:t,prepared:null,life:new AbortController};this.native=a;let c=AbortSignal.any([i,a.life.signal]),l=await this.grants();if(!l.prepareAuthorization)throw A("unavailable","Native authorization unavailable");let p=btoa(String.fromCharCode(...Uint8Array.from(e.value.challenge.match(/../g),u=>parseInt(u,16)))).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,""),d=await l.prepareAuthorization({authorizationNonce:p,expectedAccountId:e.value.accountId,signal:c});if(a.prepared=d,this.native!==a||c.aborted||d.applicationId!==e.value.appId)throw d.cancel(),A("unauthenticated","Original application registration mismatch");return Object.freeze({authorizationId:d.authorizationId,applicationId:d.applicationId,manifestDigest:d.manifestDigest})}let o=this.native,s=o?.prepared;if(!o||!s||o.portal!==t||o.context.requestId!==e.value.requestId||s.authorizationId!==e.value.authorizationRequestId)throw A("unauthenticated","Original Native preparation unavailable");let r=await s.finish({popup:t,collection:e.value.collectionId,signal:AbortSignal.any([i,o.life.signal])});if(this.native!==o||i.aborted||!r.nativeCompletion)throw A("unauthenticated","Original Native completion unavailable");return r.nativeCompletion}entries(){return this.list}has(e){return this.list.some(t=>t.collectionId===e)||this.open?.id===e}state(){return this.open?.state??null}connection(e){let t=this.open;return t&&t.id===e&&t.state.status==="ready"?t.connection:null}listing(e){return this.closed||e===null?!1:this.failedListing===e?"unavailable":this.listed!==e}ensure(e){this.listing(e)===!0&&!this.refreshing&&this.refresh(e).catch(()=>{})}refresh(e=this.bindings===null?this.listed:this.bindingsAccount){if(this.closed)return Promise.resolve();if(this.refreshing)return this.refreshing;let t=this.bindings,i=()=>!this.closed&&t===this.bindings,o=(async()=>{try{let s=await this.grants(),r=[];if(t)for(let p of t)p.account_id===e&&await s.verifiedStoredNativeGrant?.(p)&&r.push(p);let a=await s.collections(t===null?{}:{bindings:r});if(!i())return;let c=this.listing(e)!==!1;this.listed=e,this.failedListing=null;let l=this.revision;this.setList(a),c&&l===this.revision&&this.changed()}catch(s){throw i()&&e!==null&&this.failedListing!==e&&(this.failedListing=e,this.changed()),s}})().finally(()=>{this.refreshing===o&&(this.refreshing=null,!i()&&this.bindingsAccount!==null&&this.ensure(this.bindingsAccount))});return this.refreshing=o,o}setList(e){let t=Object.freeze(e.filter(i=>y8.test(i.collectionId)).map(i=>Object.freeze({collectionId:i.collectionId,displayName:i.displayName,...i.fileActions?{fileActions:i.fileActions}:{},role:i.role??"editor",availability:i.availability,kind:"private"})));JSON.stringify(t)!==JSON.stringify(this.list)&&(this.list=t,this.changed())}setAvailability(e,t){this.list.some(i=>i.collectionId===e&&JSON.stringify(i.availability)!==JSON.stringify(t))&&(this.list=Object.freeze(this.list.map(i=>i.collectionId===e?Object.freeze({...i,availability:t}):i)),this.changed())}set(e,t){if(this.open!==e||e.life.signal.aborted)return;let{problemDetail:i,...o}=e.state,{problemDetail:s,...r}=t,a=r.problem===null?void 0:s??(r.problem===void 0?i:void 0);e.state=Object.freeze({...o,...r,...a?{problemDetail:a}:{}}),this.changed()}async openCollection(e,t){if(this.closed)throw A("cancelled","Private collections closed","application_entry_fenced");this.close(!1);let i={id:e,scope:t,life:new AbortController,client:null,setup:null,connection:null,stopLink:null,state:Object.freeze({collectionId:e,status:"opening",problem:null,readiness:$r(!0,null)})};this.open=i,this.changed();let o=i.life.signal;try{let s=await this.grants(),r=this.bindings?.find(d=>d.account_id===t.account&&d.collection_id===e),a=async()=>{if(this.bindings!==null&&(!r||this.bindingsAccount!==t.account||!this.bindings.includes(r)||!await s.verifiedStoredNativeGrant?.(r)))throw A("unauthenticated","Original account-bound Native grant unavailable");if(o.aborted)throw A("cancelled","Original Native open fenced")};await a();let c=await s.availability(e,{signal:o});if(this.setAvailability(e,c),b8(c)&&(c.state==="unavailable"&&this.set(i,{status:"blocked",problem:Vy(c.reason),readiness:$r(!1,null)}),c=await s.waitForAvailable(e,{signal:o,timeoutMs:this.options.waitMs??10*6e4,onAvailability:d=>{this.setAvailability(e,d),d.state==="unavailable"?this.set(i,{status:"blocked",problem:Vy(d.reason)}):this.set(i,{status:"opening",problem:null,readiness:$r(!0,null)})}})),c.state!=="available"){if(c.state==="opening")throw A("unavailable","The collection is still getting ready","collection_unavailable");this.set(i,{status:"blocked",problem:Vy(c.reason),readiness:$r(!1,null)});return}this.set(i,{status:"opening",problem:null}),await a();let l=await(this.options.connect??v8(this.options.declaration))(s,e,o,d=>{this.open===i&&!o.aborted&&(d.reason==="not_served"||d.reason==="device_not_serving"||d.reason==="no_device_online")&&this.set(i,{status:"blocked",problem:FA(d),problemDetail:KA(d),readiness:$r(!1,null)})});if(this.open!==i||o.aborted||l.collection!==e){if(l.close(),this.open===i&&!o.aborted)throw A("invalid_request","a different collection opened","collection_mismatch");return}i.client=l,i.state.status==="blocked"&&this.set(i,{status:"opening",problem:null,readiness:$r(!0,null)}),i.setup=s.setup(l),i.connection=Object.freeze({id:e,displayName:this.list.find(d=>d.collectionId===e)?.displayName??"Collection",scope:Object.freeze({account:t.account,installation:t.installation,collection:e}),generation:crypto.randomUUID(),records:l,files:l.files,people:s.people(e,l),isCurrent:()=>this.open===i&&!o.aborted&&!this.closed}),fr("mdbase:open:stage:checking_setup"),await this.assessOpen(i);let p=0;i.stopLink=l.onLink((d,u)=>{u?this.set(i,{problem:FA(u),problemDetail:KA(u)}):d==="open"&&this.set(i,{problem:null});let f=++p;s.availability(e,{signal:o}).then(h=>{this.open===i&&!o.aborted&&f===p&&this.setAvailability(e,h)}).catch(()=>{})})}catch(s){throw this.open===i&&!o.aborted&&this.set(i,{status:"blocked",problem:FA(s),problemDetail:KA(s),readiness:$r(!1,null)}),s}}async assessOpen(e){this.set(e,{readiness:$r(!0,e.state.readiness.assessment?.status??null)});let t=1e3;for(;;){if(this.open!==e||e.life.signal.aborted)throw A("cancelled","The original collection closed.");let i;try{i=await e.setup.assess({signal:e.life.signal})}catch(o){if(!J(o)||o.code!=="rate_limited")throw o;let s=o.retryAfterMs;await m8(e.life.signal,Math.min(2147483647,Math.max(t,typeof s=="number"&&Number.isFinite(s)?s:0))),t=Math.min(3e4,t*2);continue}if(this.open!==e||e.life.signal.aborted)throw A("cancelled","The original collection closed.");return this.set(e,{status:i==="ready"?"ready":"setup_required",problem:null,readiness:$r(!1,i)}),i}}current(){let e=this.open;if(!e?.setup||e.life.signal.aborted)throw A("invalid_request","No Private collection is open","application_connection_fenced");return e}isOpen(){return this.open!==null}async assess(){let e=this.current();return await this.assessOpen(e),e.state.readiness}plan(e){return this.current().setup.plan(e)}async apply(e,t={}){let i=this.current(),o=await i.setup.apply(e,t);this.set(i,{status:o==="ready"?"ready":"setup_required",problem:null,readiness:$r(!1,o)})}async configure(e={}){let i=await this.current().setup.plan(e.signal?{signal:e.signal}:{});await this.apply(i,e)}async add(e,t,i){let o;try{o=await this.grants()}catch(r){throw e.close(),r}let s=await o.authorize({popup:e,...t?{collection:t}:{},...i?{signal:i}:{}});return await this.refresh().catch(()=>{}),s.collectionId}async forget(e){this.open?.id===e&&this.close();let t=await this.grants(),i=this.bindings?.find(o=>o.collection_id===e&&o.account_id===this.bindingsAccount);(this.bindings===null||i&&await t.verifiedStoredNativeGrant?.(i))&&await(i?t.forget(e,{expectedNoisePublicKey:i.client_noise_public_key}):t.forget(e)),this.list.some(o=>o.collectionId===e)&&(this.list=Object.freeze(this.list.filter(o=>o.collectionId!==e)),this.changed())}async forgetAll(){this.native?.life.abort(),this.native?.prepared?.cancel(),this.native=null,this.close();try{await(await this.grants()).forgetAllGrants()}finally{this.list=Object.freeze([]),this.listed=null,this.failedListing=null,this.changed()}}close(e=!0){let t=this.open;if(t){this.open=null,t.life.abort(),t.stopLink?.();try{t.client?.close()}catch{}e&&this.changed()}}dispose(){this.native?.life.abort(),this.native?.prepared?.cancel(),this.native=null,this.close(!1),this.closed=!0}};function v8(n){return async(e,t,i,o)=>{let{connect:s}=await Promise.resolve().then(()=>(Ls(),zf));return s({connector:e.connector(t),app:{name:n.id,version:"1"},signal:i,waitForDevice:!0,onWaiting:o})}}var Eg={};function a4(n){let e=globalThis.document;return!e||typeof e.addEventListener!="function"||e.visibilityState!=="hidden"?Promise.resolve():new Promise((t,i)=>{let o=()=>{e.visibilityState!=="hidden"&&(e.removeEventListener("visibilitychange",o),n.removeEventListener("abort",s),t())},s=()=>{e.removeEventListener("visibilitychange",o),i(n.reason)};e.addEventListener("visibilitychange",o),n.addEventListener("abort",s,{once:!0})})}var Y2=new WeakMap;function l4(n){let e=n.unsynced;if(!e)return n;let t=Y2.get(n);return t||(t=Object.freeze({...n,status:e.sessionStatus,selectedCollectionId:null,unsynced:null}),Y2.set(n,t)),t}var J0=class extends Error{code="application_not_yet_available";constructor(){super("mdbase cannot run in this context"),this.name="MdbaseApplicationUnavailableError"}},Z0=Object.freeze({code:"application_not_yet_available"}),zc=Object.freeze({checking:!1,assessment:null,problem:Z0}),c4=Object.freeze({checking:!1,assessment:null,problem:Z0,facets:Object.freeze({capabilities:zc,contracts:zc,configuration:zc,files:zc,people:zc,notifications:zc})}),$c=Object.freeze({checking:!1,assessment:null,problem:null}),Og=Object.freeze({checking:!1,assessment:null,problem:null,facets:Object.freeze({capabilities:$c,contracts:$c,configuration:$c,files:$c,people:$c,notifications:$c})}),X0=()=>new J0,J2=Object.freeze({state:"none",problem:null,usable:null,requested:Object.freeze({collectionId:null,source:"none",displayName:null,approved:!1})});function p4(n){let e={status:"blocked",signIn:null,collections:Object.freeze([]),selectedCollectionId:null,problem:Z0.code,timing:null,readiness:c4,selection:J2},t=Object.freeze({...e,phase:Mp(e,n?{messages:n}:{}),sync:null,writes:null,links:null}),i=()=>Promise.reject(X0());return Object.freeze({getSnapshot:()=>t,subscribe:()=>()=>{},start:i,signIn:i,addCollection:i,cancelAuthorization:i,select:i,approve:i,reauthorize:i,refreshCollectionList:i,requestAccess:i,chooseAnother:i,assess:i,configure:i,setup:Object.freeze({plan:i,apply:i}),forget:i,deleteCollection:i,unlock:i,connection:()=>null,setForeground(){throw X0()},close:i,signOut:i,unsynced:Object.freeze({open:i,planTransfer:i,transfer:i,discard:i})})}var d4=n=>typeof n=="object"&&n!==null&&["postMessage","terminate","addEventListener","removeEventListener"].every(e=>typeof n[e]=="function"),u4=(n,e)=>(!e||typeof Worker=="function")&&typeof MessageChannel=="function"&&Et()!==null&&ut(n);function f4(n){if(n===void 0)return{build:null,host:!0};if(!n||typeof n!="object"||typeof n.build!="string"||!n.build||n.build.length>128||/[\u0000-\u001f\u007f]/.test(n.build))throw new TypeError("session.build must be a short non-empty string");if(n.host!==void 0&&typeof n.host!="boolean")throw new TypeError("session.host must be a boolean");return{build:n.build,host:n.host!==!1}}function h4(n,e){if(n===void 0)return null;let t=()=>{throw A("invalid_request","Invalid sign-in opener","application_sign_in_opener")};if(!n||typeof n!="object"||typeof n.open!="function"||n.close!==void 0&&typeof n.close!="function")return t();let i=n.returnUrl,o=n.grantReturnUrl;i!==void 0&&(mm(i,e.manifest)||t()),o!==void 0&&!jl(o,e.origin,e.manifest)&&(!mm(o,e.manifest)||new URL(o).origin!==e.origin)&&t();let s=n.open.bind(n),r=n.close?.bind(n);return Object.freeze({open:s,...r?{close:r}:{},...i!==void 0?{returnUrl:i}:{},...o!==void 0?{grantReturnUrl:o}:{}})}async function m4(n){let e=!0;if(n.webPush){let t=globalThis.navigator?.serviceWorker,i;t&&typeof t.getRegistration=="function"&&(e=await Promise.race([(async()=>{let o=await(await t.getRegistration())?.pushManager?.getSubscription();return o?await o.unsubscribe():!0})().catch(()=>!1),new Promise(o=>{i=setTimeout(()=>o(!1),5e3)})]).finally(()=>clearTimeout(i)))}try{n.server==="incomplete"&&console.warn("mdbase: signed out on this device. This installation may still have collection access. Remove it under Apps in your mdbase account."),(n.local==="incomplete"||!e)&&console.warn("mdbase: signed out, but some local data on this device could not be removed.")}catch{}}function y4(n){let e=`mdbase.${n}.selected-collection.v1`;return Object.freeze({read:()=>{try{return globalThis.localStorage?.getItem(e)??null}catch{return null}},write:t=>{try{t===null?globalThis.localStorage?.removeItem(e):globalThis.localStorage?.setItem(e,t)}catch{}}})}var qg=class{mdbase;declaration;compiled;lifetime=new AbortController;listeners=new Set;nativeListeners=new Set;selection=null;memory=null;runtime=null;initialization=null;closing=null;closed=!1;foreground=!0;incarnation=0;hidden=null;tabs=null;election=null;signingOut=!1;snapshot=Object.freeze({status:"not_started",signIn:null,collections:Object.freeze([]),selectedCollectionId:null,problem:null,timing:null,readiness:Og});composed=null;hint=null;forgotten=null;handledApproval=null;refreshing=null;refreshedAt=0;approvalPortal=null;revision=0;links=null;cpOrigin=null;messages;opening=null;syncing=null;storagePolicy=null;pendingSave=null;signIn;typeIssues;createWorker;session;privates=null;unsyncedFirst;unsyncedTried=!1;unsyncedOpening=0;timing=new km;overlaid=new WeakMap;constructor(e,t={}){this.declaration=co(e),this.compiled=is(this.declaration);let i=t.readiness?.typeIssues??"block";if(i!=="block"&&i!=="degrade")throw new TypeError('readiness.typeIssues must be "block" or "degrade"');if(this.typeIssues=i,this.unsyncedFirst=t.unsynced===!0,t.urlSelection!==void 0&&typeof t.urlSelection!="boolean")throw new TypeError("urlSelection must be a boolean");if(t.worker!==void 0&&typeof t.worker!="function")throw new TypeError("worker must be a function");if(this.createWorker=t.worker??null,this.messages=t.messages,this.session=f4(t.session),!this.session.host&&this.createWorker)throw new TypeError("worker has no effect with session.host: false");if(this.signIn=h4(t.signIn,this.declaration),!u4(this.declaration.origin,this.session.host)){this.mdbase=p4(t.messages);return}try{let s=this.environment().cpOrigin;this.cpOrigin=s,this.hint=zR(this.declaration.storage.applicationNamespace,s),this.forgotten=UR(this.declaration.storage.applicationNamespace,s),this.links=Object.freeze({account:`${s}/account`,manageAccess:`${s}/account/applications`})}catch{}t.followVisibility!==!1&&this.followVisibility(),this.followPageLifecycle(),this.followFocus(),this.followStoragePolicy(),this.followNetwork(),this.memory=y4(this.declaration.storage.applicationNamespace),t.privateCollections!==!1&&(this.privates=new Fy({declaration:this.declaration,...this.signIn?.grantReturnUrl?{grantRedirectUri:this.signIn.grantReturnUrl}:{},onChange:()=>{this.revision++,this.notify()}})),this.selection=new Pm({browser:new Sm(this.declaration.origin,{},t.urlSelection===!1?null:i1()),session:this.selectionSession(),memory:this.memory}),this.selection.subscribe(()=>{this.unforgetApproved(),this.notify(!1)});let o=()=>this.getSnapshot();this.mdbase=Object.freeze({getSnapshot:o,subscribe:s=>(this.listeners.add(s),()=>{this.listeners.delete(s)}),start:s=>this.track(()=>{let r=this.unsyncedFirst&&(!this.unsyncedTried||this.runtime===null);return r&&(this.unsyncedOpening++,this.revision++,this.notify(!1)),this.call(async a=>{let c=this.account();this.privates?.listing(c)==="unavailable"&&await this.privates.refresh(c).catch(()=>{});let l=a.getNativeSnapshot();l.status==="blocked"&&l.signIn&&l.selectedCollectionId===null?await a.queue(()=>a.start(s)):await this.timing.time("session",()=>this.started(a,s));let p=this.choose(),d=p.getSnapshot();d.state==="blocked"&&d.requested.approved&&d.requested.collectionId!==null&&await p.select(d.requested.collectionId,s);let u=a.getNativeSnapshot();this.unsyncedFirst&&!this.unsyncedTried&&u.status==="signed_out"&&!u.unsynced&&!u.signOutResult&&p.getSnapshot().requested.collectionId===null&&(this.unsyncedTried=!0,await this.timing.time("unsynced",()=>a.queue(()=>a.openUnsynced(s))))}).catch(a=>{let c=this.runtime?.getNativeSnapshot();if(!(a?.code==="open_in_another_tab"&&c?.status==="blocked"&&c.problem==="open_in_another_tab"))throw a}).finally(()=>{r&&(this.unsyncedOpening--,this.revision++,this.notify(!1))})}),signIn:s=>this.track(()=>this.approve(void 0,s)),approve:(s,r)=>this.track(()=>this.approve(s,r)),reauthorize:s=>this.track(()=>{let r=this.choose(),a=r.getSnapshot(),c=this.privates?.state()?.collectionId??a.usable?.collectionId??a.requested.collectionId;return c?this.approve(c,s):r.reauthorize(s)}),addCollection:s=>this.track(()=>this.approve(null,s)),cancelAuthorization:s=>this.track(()=>this.call(async r=>{await r.queue(()=>r.cancelAuthorization(s));let a=r.getNativeSnapshot();this.unsyncedFirst&&a.status==="signed_out"&&!a.unsynced&&this.choose().getSnapshot().requested.collectionId===null&&await r.queue(()=>r.openUnsynced(s))})),refreshCollectionList:s=>this.track(()=>Promise.all([this.call(r=>r.queue(()=>r.refreshCollections(s))),this.privates?.refresh(this.account()).catch(()=>{})])),requestAccess:(s,r)=>this.requestAccess(s,r),select:(s,r)=>this.track(()=>this.choose().select(s,{...r,history:"push"})),chooseAnother:s=>this.track(()=>this.choose().chooseAnother(s)),forget:(s,r)=>this.track(async()=>{let a=this.choose(),c=this.account();if(this.privates?.has(s)){await this.privates.forget(s),a.getSnapshot().requested.collectionId===s&&await a.select(null,r);return}if(c&&this.forgotten){this.forgotten.add(c,s),this.revision++,(a.getSnapshot().requested.collectionId===s||(this.runtime?.getSnapshot()??this.snapshot).selectedCollectionId===s)&&await a.select(null,r),this.notify(!1);return}await this.call(l=>l.queue(()=>l.forget(s,r))),a.getSnapshot().requested.collectionId===s&&await a.select(null,r)}),deleteCollection:(s,r)=>this.track(async()=>{let a=this.choose(),{confirmName:c,...l}=r??{};await this.call(p=>p.queue(()=>p.deleteCollection(s,c,l))),a.getSnapshot().requested.collectionId===s&&await a.select(null,l)}),unlock:(s,r,a)=>this.track(()=>this.call(c=>c.queue(()=>c.unlock(s,r,a)))),assess:s=>this.privates?.isOpen()?this.privates.assess():this.call(r=>r.queue(()=>r.assess(s))),configure:s=>this.track(()=>this.privates?.isOpen()?this.privates.configure(s):this.call(r=>r.queue(()=>r.configure(s)))),setup:Object.freeze({plan:s=>(this.privates?.isOpen()?this.privates.plan(s):this.call(r=>r.queue(()=>r.planSetup(s)))).then(r=>LR(r,this.getSnapshot().readiness)),apply:(s,r)=>MR(this.track(()=>this.privates?.isOpen()?this.privates.apply(s,r):this.call(a=>a.queue(()=>a.applySetup(s,r)))),o)}),connection:s=>this.connection(s),setForeground:s=>this.setForeground(s),close:()=>this.close(),signOut:s=>this.signOut(s),unsynced:Object.freeze({planTransfer:(s={})=>this.call(r=>{let a=this.transferDestination(null);return r.withUnsyncedSource((c,l)=>W_(c.records,a.records,{...s.map?{map:s.map}:{},...s.addTypes?{addTypes:!0}:{},ledger:this.transferLedger(),signal:l}),s)}),transfer:(s,r={})=>this.call(async a=>{let c=this.transferDestination(s?.destination??null),l=await kR(s,c.records,{...r.signal?{signal:r.signal}:{},...r.onProgress?{onProgress:r.onProgress}:{}});if(l.failed.length||l.failedTypes.length)return l;let p=r.signal?{signal:r.signal}:{};return await a.withUnsyncedSource((d,u)=>AR(s,d.records,c.records,u),p)?Object.freeze({...l,retired:await a.retireUnsynced(s.source,s.destination,p)}):l}),discard:s=>this.track(async()=>{await this.call(async r=>(await this.started(r,s),r.queue(()=>r.discardUnsynced(s))))}),open:s=>this.track(async()=>{let r=this.choose();this.privates?.close(),r.getSnapshot().requested.collectionId!==null&&await r.select(null,{...s,history:"replace"}),await this.call(async a=>(await this.started(a,s),a.queue(()=>a.openUnsynced(s))))})})})}withPrivate(e){let t=this.privates;if(!t)return e;let i=this.overlaid.get(e);if(i&&i.revision===t.revision)return i.value;let o=mE(e,t.entries(),t.state());return this.overlaid.set(e,{revision:t.revision,value:o}),o}getSnapshot(){let e=this.withPrivate(this.runtime?.getSnapshot()??this.snapshot),t=this.selection?.getSnapshot()??J2,i=this.composed,o=e.signIn===null&&(e.status==="starting"||e.status==="blocked"&&e.problem==="open_in_another_tab")?this.hint?.read()??null:null;if(i&&i.base===e&&i.selection===t&&i.revision===this.revision&&i.hint===o)return i.value;let s=o?Object.freeze({...e,signIn:o.signIn,collections:o.collections}):e,r=this.forgotten?.read(s.signIn?.accountId)??null,a=r?.size&&s.collections.some(_=>r.has(_.collectionId)&&_.collectionId!==s.selectedCollectionId)?Object.freeze({...s,collections:Object.freeze(s.collections.filter(_=>!r.has(_.collectionId)||_.collectionId===s.selectedCollectionId))}):s,c=a.selectedCollectionId,l=c&&!this.closed?this.privates?.connection(c)??this.runtime?.connection(c)??null:null,p=this.unsyncedOpening>0&&!a.unsynced&&!a.signOutResult&&t.requested.collectionId===null,d=Mp({...a,selection:t},{connection:l,previous:i?.value.phase??null,openingUnsynced:p,startPending:this.selection?.startPending()??!1,...this.cpOrigin?{cpOrigin:this.cpOrigin}:{},...this.messages?{messages:this.messages}:{}});d=this.trackOpening(d),this.timing.observe(d),t1(t,d,i?.value);let u=a.transport??null,f=globalThis.navigator?.onLine,h=this.trackSync(d,u!==null||f===!1),m=this.syncing?.writes()??null,w=this.trackPending(Math.max(h?.pending??0,m?.pending.length??0)),b=h&&w!==null?dy(h.pending,this.storagePolicy??{persistent:!1,installed:!1},{pendingForMs:w,connection:h.connection}).warning:null,g=this.syncing?.link(),y=h?Object.freeze($f({status:h,writes:m,problem:a.problem,transport:u,live:a.live??null,storageWarning:b!==null,...g===void 0?{}:{link:g},...typeof f=="boolean"?{online:f}:{},...w===null?{}:{pendingForMs:w}})):null,v=Object.freeze({...a,selection:t,phase:d,sync:y,storage:this.storagePolicy,saveWarning:b,links:this.linksFor(c)});return this.composed={base:e,selection:t,revision:this.revision,hint:o,value:v},v}linksFor(e){return this.links&&e?Object.freeze({...this.links,manageAccess:`${this.cpOrigin}/access?collection=${encodeURIComponent(e)}`}):this.links}trackPending(e){let t=this.syncing;if(this.pendingSave&&(this.closed||this.hidden||!e||this.pendingSave.id!==t?.id)&&this.clearPendingSave(),this.closed||this.hidden||!t||!e)return null;if(!this.pendingSave){let i={id:t.id,since:performance.now(),timer:null},o=s=>()=>{this.pendingSave===i&&(i.timer=s===null?null:setTimeout(o(null),s),this.revision++,this.notify(!1))};i.timer=setTimeout(o(28e3),2e3),this.pendingSave=i}return performance.now()-this.pendingSave.since}clearPendingSave(){this.pendingSave?.timer!==null&&this.pendingSave?.timer!==void 0&&clearTimeout(this.pendingSave.timer),this.pendingSave=null}trackOpening(e){let t=e.kind==="opening"?e.collectionId:null;if(this.opening&&this.opening.id!==t&&(clearTimeout(this.opening.timer),this.opening=null),t===null||this.closed)return e;if(!this.opening){let i={id:t,slow:!1,timer:setTimeout(()=>{this.opening===i&&(i.slow=!0,this.revision++,this.notify(!1))},ih)};this.opening=i}return e.kind==="opening"&&this.opening.slow?{...e,slow:!0}:e}trackSync(e,t){let i=e.kind==="ready"?e.collectionId:null;if(this.syncing&&this.syncing.id!==i){try{this.syncing.stop()}catch{}this.syncing=null}if(e.kind!=="ready"||this.closed)return null;if(!this.syncing){let o=e.connection.records,s=null;try{s=o.status}catch{}let r={id:e.collectionId,stop:()=>{},status:s,writes:()=>null,link:()=>{}},a=()=>{this.syncing===r&&(this.revision++,this.getSnapshot(),this.notify(!1))},c=()=>{},l=()=>{},p=()=>{};try{c=o.onStatus(d=>{r.status=d,a()})}catch{}try{let d=o.ledger;l=d.subscribe(a),r.writes=()=>{try{return d.getSnapshot()}catch{return null}}}catch{}try{p=o.onLink(a),r.link=()=>{try{return o.link}catch{return}}}catch{}r.stop=()=>{c(),l(),p()},this.syncing=r}try{e.connection.records.setTransportDeferred(t)}catch{}return this.syncing.status}nativeAuthorization(e,t,i){return!this.privates||this.closed||this.hidden?Promise.reject(A("unavailable","Native authorization unavailable")):this.privates.nativeAuthorization(e,t,AbortSignal.any([i,this.lifetime.signal]))}account(){return(this.runtime?.getSnapshot()??this.snapshot).signIn?.accountId??null}unforgetApproved(){let e=this.selection?.getSnapshot().lastApproval??null,t=this.account();!e||e===this.handledApproval||(this.handledApproval=e,t&&e.collectionId&&(e.outcome==="added"||e.outcome==="unchanged")&&this.forgotten?.remove(t,e.collectionId)&&this.revision++)}followFocus(){let e=typeof window>"u"?void 0:window,t=globalThis.document;if(!e||typeof e.addEventListener!="function")return;let i=()=>{t?.visibilityState!=="hidden"&&this.refreshCollections()};e.addEventListener("focus",i,{signal:this.lifetime.signal}),t&&typeof t.addEventListener=="function"&&t.addEventListener("visibilitychange",i,{signal:this.lifetime.signal})}refreshCollections(){let e=this.runtime,t=Date.now();if(!e||this.closed||this.hidden||this.refreshing||t-this.refreshedAt<2e3)return;let i=e.getNativeSnapshot();i.signIn?.state!=="paired"||i.status!=="unselected"&&i.status!=="ready"&&i.status!=="setup_required"||(this.refreshedAt=t,this.privates?.refresh(i.signIn.accountId).catch(()=>{}),this.refreshing=e.queue(()=>e.refreshCollections()).catch(()=>{}).finally(()=>{this.refreshing=null}))}followStoragePolicy(){let e=globalThis.navigator?.storage;if(!e||typeof e.persisted!="function")return;let t=()=>{try{return globalThis.matchMedia?.("(display-mode: standalone)").matches===!0||globalThis.navigator?.standalone===!0}catch{return!1}},i=(s=!1)=>{this.closed||uy(e,t(),s).then(r=>{this.closed||this.storagePolicy?.persistent===r.persistent&&this.storagePolicy?.installed===r.installed||(this.storagePolicy=r,this.revision++,this.notify(!1))}).catch(()=>{})},o=globalThis.document;o&&typeof o.addEventListener=="function"&&o.addEventListener("visibilitychange",()=>{o.visibilityState!=="hidden"&&i()},{signal:this.lifetime.signal}),i(!0)}notify(e=!0){let t=this.runtime?.getSnapshot(),i=t?.signIn?.state==="paired"?t.signIn.accountId:null;if(i&&!this.closed&&!this.hidden&&(this.privates?.bind(i,t?.signIn?.nativeGrants??[]),this.privates?.ensure(i)),e)for(let o of[...this.nativeListeners])try{o()}catch{}for(let o of[...this.listeners])try{o()}catch{}}choose(){this.check();let e=this.selection;return e.start(),e}async track(e){return await e(),this.getSnapshot()}selectionSession(){return Object.freeze({getSnapshot:()=>this.withPrivate(l4(this.runtime?.getNativeSnapshot()??this.snapshot)),subscribe:e=>(this.nativeListeners.add(e),()=>{this.nativeListeners.delete(e)}),open:(e,t={})=>this.call(async i=>{let o=this.privates,s=i.getNativeSnapshot().collections.some(c=>c.collectionId===e);if(!o||s||!o.has(e))return o?.close(),i.queue(()=>i.select(e,t));i.getNativeSnapshot().selectedCollectionId!==null&&await i.queue(()=>i.clearSelection(t));let r=i.getNativeSnapshot().signIn?.accountId,a=i.getNativeSnapshot().signIn?.installationId;if(!r||!a)throw A("unauthenticated","Sign in before opening a collection");o.openCollection(e,{account:r,installation:a}).catch(()=>{})}),clear:(e={})=>(this.privates?.close(),this.call(t=>t.queue(()=>t.clearSelection(e)))),authorize:(e={})=>this.authorize(e,e.collectionHint??null),listing:()=>this.privates?.listing(this.account())??!1})}check(){if(this.closed||this.hidden||this.lifetime.signal.aborted)throw A("cancelled","Application entry fenced","application_entry_fenced")}environment(){return Ci({environment:this.declaration.environment,appOrigin:this.declaration.origin,release:Ks()})}initialize(){if(this.initialization)return this.initialization;let e=this.incarnation,t=Promise.resolve().then(async()=>{if(this.check(),typeof Eg.url!="string")throw X0();let i=new URL(Eg.url);if(dt(i)!==this.declaration.origin||Et()!==this.declaration.origin)throw A("unavailable","Application module binding unavailable","application_worker_module_binding");let o=this.environment(),s=e1(this.declaration.environment,this.declaration.origin),r=await this.timing.time("capabilities",()=>OR(void 0,this.session.host));if(this.check(),!r.ok)throw A("unavailable","This browser can't run mdbase",{reason:r.problem,details:{missing:r.missing.join(",")}});let a=()=>{if(!this.unsyncedFirst)return;let P={origin:this.declaration.origin,environment:this.declaration.environment};for(let I of[s.runtime,s.sqlite])try{QC(I,P)({signal:this.lifetime.signal}).catch(()=>{})}catch{}},c=Promise.resolve().then(()=>(H2(),W2));c.catch(()=>{});let{registered:l,ApplicationRuntime:p}=await this.timing.time("registration",async()=>({registered:await vm({declaration:this.declaration,signal:this.lifetime.signal,isCurrent:()=>!this.closed,onRequest:a}),ApplicationRuntime:(await c).ApplicationRuntime}));if(this.check(),e!==this.incarnation)throw A("cancelled","Application entry fenced","application_entry_fenced");let d=WC(this.declaration,l);l.supersededDeclaredId&&console.info(`mdbase: ${Qf("application_registration_id_superseded")}`);let u=rh(this.declaration),f=Object.freeze({cpOrigin:o.cpOrigin,appId:d.id,...u===null?{}:{storageNamespace:u}}),h=P=>(this.runtime=P,this.unsyncedTried=!1,P.subscribe(()=>{this.hint?.observe(P.getNativeSnapshot()),this.observeSignOut(P),P.getNativeSnapshot().signIn?.state==="paired"&&this.tabs?.signedIn(),this.notify(),this.awaitOtherTab(P,f)}),P.setForeground(this.foreground),this.notify(),P),m=this.tabsFor(f),w=new AbortController;this.election?.abort(),this.election=w;let b=await this.timing.time("election",()=>m.elect(AbortSignal.any([this.lifetime.signal,w.signal])));if(this.closed||this.hidden||e!==this.incarnation||w.signal.aborted)throw b.kind==="follower"?b.leave():m.resign(),A("cancelled","Application entry fenced","application_entry_fenced");if(b.kind==="follower")return h(new p({declaration:d,compiledManifest:this.compiled,typeIssues:this.typeIssues,cpOrigin:o.cpOrigin,port:b.port,binding:b.binding,releaseWorker:()=>b.leave(),nativeAuthorization:(P,I,O)=>this.nativeAuthorization(P,I,O)}));let g=new MessageChannel,y=crypto.randomUUID(),v,_=this.createWorker,k=_?new URL("./worker.js",i).href:null;try{if(!_)v=new Worker(new URL("./worker.js",Eg.url),{type:"module"});else if(v=_(k),!d4(v))throw new TypeError("not a Worker")}catch{throw m.resign(),g.port1.close(),g.port2.close(),A("unavailable","Application Worker construction unavailable","application_worker_unavailable")}let S=P=>{P.preventDefault(),g.port1.dispatchEvent(new MessageEvent("messageerror")),m.fault()};v.addEventListener("error",S);let x=new p({declaration:d,compiledManifest:this.compiled,typeIssues:this.typeIssues,cpOrigin:o.cpOrigin,port:g.port1,binding:y,releaseWorker:()=>{v.removeEventListener("error",S),v.terminate(),m.resign()},nativeAuthorization:(P,I,O)=>this.nativeAuthorization(P,I,O)});try{v.postMessage([di,y,d,...k!==null?[u,k]:u===null?[]:[u]],[g.port2])}catch{throw v.removeEventListener("error",S),v.terminate(),m.resign(),g.port1.close(),g.port2.close(),A("unavailable","Application bootstrap unavailable","application_worker_binding")}return m.lead({attach:(P,I)=>v.postMessage([di,y,"attach",I],[P]),detach:P=>v.postMessage([di,y,"detach",P])}),h(x)}).catch(i=>{let o=this.initialization===t;if(o&&(this.initialization=null),!this.closed&&o){let{problemDetail:s,...r}=this.snapshot,a=i instanceof ne&&i.reason==="application_registration_refused"?js(i.details):null;this.snapshot=Object.freeze({...r,status:"blocked",problem:typeof i?.reason=="string"?i.reason:typeof i?.code=="string"?i.code:"application_entry_unavailable",...a?{problemDetail:Object.freeze({name:"MdbaseError",code:i.code,registration:a})}:{}}),this.notify()}throw i});this.initialization=t;{let{problemDetail:i,signOutResult:o,...s}=this.snapshot;this.snapshot=Object.freeze({...s,status:"starting",problem:null})}return this.notify(),t}async call(e){this.check();let t=await this.initialize();return this.check(),e(t)}started(e,t){this.choose();let i=e.getNativeSnapshot().status;return i==="not_started"||i==="starting"||i==="blocked"&&!e.getNativeSnapshot().signIn?e.queue(()=>e.start(t)):Promise.resolve()}reservePortal(e){this.check();let t=this.environment(),i=e.signal?AbortSignal.any([this.lifetime.signal,e.signal]):this.lifetime.signal,o=Ml(this.declaration.environment),s=()=>!this.closed,r=this.signIn?K1(t.cpOrigin,i,s,this.signIn,o):Fm(t.cpOrigin,i,s,o);return{portal:Vm(r),signal:i}}requestAccess(e,t){try{this.check();let i=this.runtime,o=i?.getNativeSnapshot(),s=this.privates?.state()?.collectionId,r=s??o?.selectedCollectionId??null,a=ay(this.compiled),c=()=>r&&i?ly(i.getNativeSnapshot(),r):[],l=xR(a,e,t,c()),p=r?this.connection(r):null;if(!i||!r||!p)throw A("invalid_request","requestAccess needs an open collection","access_no_collection");if(s){let h=this.privates?.entries().find(w=>w.collectionId===s)?.fileActions??[],m=(p.files.grant?.actions??[]).filter(w=>a?.required.includes(w)||a?.optional.includes(w)&&h.includes(w));return Promise.resolve(e.files.every(w=>m.includes(w))?Object.freeze({status:"granted",actions:Object.freeze(m)}):Object.freeze({status:"unavailable",reason:"private_relay"}))}let d=()=>IR(p.files,a,c());if(!l.length)return Promise.resolve(d());if(o?.unsynced?.collectionId===r)return Promise.resolve(Object.freeze({status:"unavailable",reason:"until_connected"}));let{portal:u,signal:f}=this.reservePortal(t);return CR({granted:d,native:()=>i.getNativeSnapshot(),start:()=>i.queue(()=>i.requestFileAccess(u,r,l,t.reason,{signal:f})),poll:h=>i.queue(()=>i.pollFileAccess(h))},u,f,t.signal??null)}catch(i){return Promise.reject(i)}}approve(e,t={}){let i=this.choose(),o=i.getSnapshot(),s=this.approvalPortal;if(s&&o.approval){if((e===void 0?o.requested.collectionId:e)!==o.approval.collectionId)return Promise.reject(new yn("application_selection_busy"));if(t.signal?.aborted)throw A("cancelled","Application entry fenced","application_entry_fenced");return s.closed||s.focus(),Promise.resolve()}return i.approve(e,t)}authorize(e={},t=null){let i;try{i=this.approvalPortal=this.reservePortal(e).portal}catch(o){return Promise.reject(o)}return this.call(async o=>(await this.started(o,e),o.queue(()=>o.authorizeReserved(i,e,t)))).catch(o=>{try{i.close()}catch{}throw o})}async signOut(e={}){let t=await this.call(async s=>(await this.started(s,e),s));this.signingOut=!0;try{await t.queue(()=>t.signOut(e))}finally{this.signingOut=!1}let i=t.getNativeSnapshot().signOutResult??null;await this.signedOut(t,i);let o=this.snapshot.signOutResult??i;return o&&await m4(o),this.getSnapshot()}async signedOut(e,t,i=!1){i||this.tabs?.signedOut(),this.clearPendingSave(),++this.incarnation,this.runtime===e&&(this.runtime=null),this.initialization=null,this.hint?.clear(),this.forgotten?.clear(),this.handledApproval=null;let o=null;if(this.privates)try{await this.privates.forgetAll(),o="erased"}catch{o="incomplete"}let s=t&&o?Object.freeze({...t,grants:o,...o==="incomplete"?{local:"incomplete"}:{}}):t;this.snapshot=Object.freeze({status:"signed_out",signIn:null,collections:Object.freeze([]),selectedCollectionId:null,problem:!s&&o==="incomplete"?"sign_out_failed":null,timing:null,readiness:Og,...s?{signOutResult:s}:{}});try{this.memory?.write(null)}catch{}if(this.selection&&!this.closed&&(this.selection.resync(),await this.selection.select(null,{history:"replace"}).catch(()=>{})),this.revision++,this.notify(),i){e.abandon();return}await e.close().catch(()=>{})}observeSignOut(e){let t=e.getNativeSnapshot().signOutResult;!t||this.signingOut||this.closed||this.runtime!==e||this.signedOut(e,t)}tabsFor(e){return this.tabs??=new py({...e,build:this.session.build===null?Eg.url:`app-build/${this.session.build}`},{locks:globalThis.navigator.locks,BroadcastChannel:globalThis.BroadcastChannel},this.leaderLost,this.signedInElsewhere,{lead:this.session.host,wanted:this.hostWanted})}leaderLost=e=>{if(this.closed||this.hidden)return;let t=this.runtime,i=t!==null||this.initialization!==null;if(this.election?.abort(),this.election=null,e&&t&&!this.signingOut?this.signedOut(t,t.getNativeSnapshot().signOutResult??null,!0):e&&i&&(++this.incarnation,this.initialization=null),!i||e){this.tabs?.resign();return}++this.incarnation,this.initialization=null,this.runtime=null,t?.abandon();let{problemDetail:o,...s}=this.snapshot;this.snapshot=Object.freeze({...s,status:"starting",problem:null,selectedCollectionId:null,readiness:Og}),this.notify(),this.selection?.resync(),this.mdbase.start().catch(()=>{})};hostWanted=()=>{this.closed||this.hidden||this.signingOut||this.runtime!==null||this.initialization!==null||(this.selection?.resync(),this.mdbase.start().catch(()=>{}))};signedInElsewhere=()=>{this.closed||this.hidden||this.signingOut||this.runtime!==null||this.initialization!==null||this.snapshot.status!=="signed_out"||(this.selection?.resync(),this.mdbase.start().catch(()=>{}))};setForeground(e){this.foreground=e,this.runtime?.setForeground(e)}followVisibility(){let e=globalThis.document;if(!e||typeof e.addEventListener!="function")return;let t=()=>{this.closed||this.setForeground(e.visibilityState!=="hidden")},i=()=>{e.visibilityState!=="hidden"&&t()};e.addEventListener("visibilitychange",t,{signal:this.lifetime.signal});let o=typeof window>"u"?void 0:window;o&&typeof o.addEventListener=="function"&&(o.addEventListener("focus",i,{signal:this.lifetime.signal}),o.addEventListener("online",i,{signal:this.lifetime.signal})),t()}followNetwork(){let e=typeof window>"u"?globalThis:window;if(typeof e.addEventListener!="function")return;let t=()=>{this.closed||(this.revision++,this.notify(!1))};e.addEventListener("online",()=>{let i=this.account();!this.closed&&!this.hidden&&this.privates?.listing(i)==="unavailable"&&this.privates.refresh(i).catch(()=>{}),t()},{signal:this.lifetime.signal}),e.addEventListener("offline",t,{signal:this.lifetime.signal})}followPageLifecycle(){let e=typeof window>"u"?void 0:window;if(!e||typeof e.addEventListener!="function")return;e.addEventListener("pagehide",this.pageHidden,{signal:this.lifetime.signal}),e.addEventListener("pageshow",this.pageShown,{signal:this.lifetime.signal});let t=globalThis.document,i=this.signIn?.returnUrl!==void 0&&!/^https?:/i.test(this.signIn.returnUrl);t&&typeof t.addEventListener=="function"&&!i&&(t.addEventListener("freeze",()=>this.pageHidden(),{signal:this.lifetime.signal}),t.addEventListener("resume",()=>this.pageShown({persisted:!0}),{signal:this.lifetime.signal}))}pageHidden=()=>{if(this.closed||this.hidden)return;let e=this.runtime,t=e!==null||this.initialization!==null;++this.incarnation,this.hidden=Object.freeze({resume:t}),this.clearPendingSave(),this.initialization=null,this.runtime=null,this.election?.abort(),this.election=null,e?.abandon(),this.tabs?.release();let{problemDetail:i,...o}=this.snapshot;this.snapshot=Object.freeze({...o,status:t?"starting":this.snapshot.status,problem:null,selectedCollectionId:null,readiness:Og})};pageShown=e=>{let t=this.hidden;this.closed||!t||!e.persisted||(this.hidden=null,this.notify(),t.resume&&(this.selection?.resync(),this.mdbase.start().catch(()=>{})))};awaitingOtherTab=!1;awaitOtherTab(e,t){let i=e.getNativeSnapshot(),o=globalThis.navigator?.locks;if(this.awaitingOtherTab||this.closed||i.status!=="blocked"||i.problem!=="open_in_another_tab"||!o)return;this.awaitingOtherTab=!0;let s=this.incarnation,r=this.lifetime.signal,a=()=>!this.closed&&!this.hidden&&s===this.incarnation&&this.runtime===e;f1(o,t,r).then(()=>a4(r)).then(()=>{this.awaitingOtherTab=!1,a()&&(this.selection?.resync(),this.mdbase.start().catch(()=>{}))},()=>{this.awaitingOtherTab=!1})}close(){if(this.closing)return this.closing;if(this.closed=!0,this.lifetime.abort(),this.selection?.close(),this.election?.abort(),this.privates?.dispose(),this.opening&&(clearTimeout(this.opening.timer),this.opening=null),this.clearPendingSave(),this.syncing){try{this.syncing.stop()}catch{}this.syncing=null}return this.closing=Promise.resolve().then(async()=>{await this.initialization?.catch(()=>{}),await this.runtime?.close(),this.tabs?.release();{let{problemDetail:e,...t}=this.snapshot;this.snapshot=Object.freeze({...t,status:"closed",problem:null,selectedCollectionId:null})}this.runtime=null,this.notify(),this.listeners.clear(),this.nativeListeners.clear()}),this.closing}transferLedger(){let e=this.declaration.storage.unsyncedDatabaseName,t=new AbortController().signal;return Object.freeze({read:(i,o)=>vR(e,i,o??t),record:(i,o,s)=>_R(e,i,o,s??t)})}transferDestination(e){let t=this.getSnapshot().phase;if(t.kind!=="ready")throw A("invalid_request","Open the collection to bring this work into first.","unsynced_transfer_needs_collection");if(e!==null&&t.collectionId!==e)throw A("invalid_request","This plan is for another collection. Plan the transfer again.","unsynced_transfer_plan_stale");return t.connection}connection(e){return this.closed?null:this.privates?.connection(e)??this.runtime?.connection(e)??null}};function X2(n,e={}){return new qg(n,e).mdbase}Ll();hm();re();function Z2(n,e){let t=is(co(n)).manifest.requirements.capabilities;if(t?.contract_version!==2)return null;if(!e.isCurrent())throw A("invalid_request","the application connection is not current","application_connection_fenced");let i=new Set(e.records.hello.grant.capabilities),o=new Set(t.required),s=Object.freeze([...new Set([...t.required,...t.optional??[]])].map(r=>Object.freeze({id:r,requirement:o.has(r)?"required":"optional",state:i.has(r)?"available":"missing"})));return Object.freeze({values:s,requiredAvailable:s.every(r=>r.requirement==="optional"||r.state==="available"),missing:Object.freeze(s.filter(r=>r.state==="missing").map(r=>r.id))})}Je();ve();Ls();qs();mp();ve();re();da();uc();nu();function Q2(n){let e=N(n.collection),t=n.grant?N(n.grant):null;return Nr({description:`relay:${n.collection}`,staticKey:n.staticKey,target:async()=>{let i=await n.resolveRoute();if(!i)throw A("unavailable","no device of this collection is online","no_device_online");let o=Ur(e,t,N(i.targetDevice));return{prologue:o,...i.prologueFirst&&!i.pipe?{preamble:o}:{},remoteStatic:i.noisePublicKey,device:i.targetDevice,openCarrier:s=>i.pipe?fc(i.url,{accessToken:i.pipe.accessToken,collection:i.pipe.collection,grant:n.grant??"",device:i.targetDevice,devicePublicKey:i.noisePublicKey},n.webSocket,s):dc(i.url,n.webSocket,s)}}})}MA();uc();da();Je();ve();re();tn();da();uc();var g4=new Uint8Array(16);function Q0(n,e){if(n.length!==32)throw A("invalid_request","the link token is 32 bytes");let t=Yr.dec(e);if(t.kind!=="request"||t.method!=="hello")throw A("internal","expected the hello request");return fe(new Map([[0,n],[1,t.params]]))}function eq(n){let e=N(n.collection),t=n.staticKey??pc(),i=null;return Nr({description:"localhost-link",staticKey:t,firstPayload:o=>Q0(i.token,o),target:async()=>{i=typeof n.link=="function"?await n.link():n.link;let o=i;if(!Number.isInteger(o.port)||o.port<=0||o.port>65535)throw A("unavailable","invalid local link port","daemon_not_running");let s=Ur(e,null,n.localOnly?g4:N(o.device));return{prologue:s,preamble:s,remoteStatic:o.noisePublicKey,openCarrier:r=>dc(`ws://127.0.0.1:${o.port}/v1/plugin`,n.webSocket,r)}}})}qy();re();function ek(){let n=new Map;return{get:async e=>n.get(e),put:async(e,t)=>{n.set(e,t)},putIfAbsent:async(e,t)=>{let i=n.get(e);return i||(n.set(e,t),t)},delete:async e=>{n.delete(e)}}}function tk(n="mdbase-keys",e="keys"){let t=globalThis.indexedDB;if(!t)throw A("invalid_request","IndexedDB is not available here; pass another KeyStorage");let i=()=>new Promise((r,a)=>{let c=t.open(n,1);c.onupgradeneeded=()=>c.result.createObjectStore(e),c.onsuccess=()=>r(c.result),c.onerror=()=>a(c.error)}),o=async(r,a)=>{let c=await i();try{return await new Promise((l,p)=>{let d=c.transaction(e,r),u,f=!1;d.oncomplete=()=>f?l(u):p(A("unavailable","key storage transaction completed without a result","key_storage")),d.onabort=()=>p(d.error??A("unavailable","key storage transaction aborted","key_storage")),d.onerror=()=>p(d.error??A("unavailable","key storage transaction failed","key_storage"));try{a(d.objectStore(e),h=>{u=h,f=!0})}catch(h){d.abort(),p(h)}})}finally{c.close()}},s=(r,a)=>o(r,(c,l)=>{let p=a(c);p.onsuccess=()=>l(p.result)});return{get:r=>s("readonly",a=>a.get(r)),put:(r,a)=>s("readwrite",c=>c.put(a,r)).then(()=>{}),putIfAbsent:(r,a)=>o("readwrite",(c,l)=>{let p=c.get(r);p.onsuccess=()=>{if(p.result!==void 0){l(p.result);return}try{let d=c.add(a,r);d.onsuccess=()=>l(a)}catch{c.transaction.abort()}}}),delete:r=>s("readwrite",a=>a.delete(r)).then(()=>{})}}function iq(){return globalThis.crypto?.subtle}async function b4(){let n=iq();if(!n)return null;try{let e=await n.generateKey({name:"X25519"},!1,["deriveBits"]),t=new Uint8Array(await n.exportKey("raw",e.publicKey));return{kind:"webcrypto",privateKey:e.privateKey,publicKey:t}}catch{return null}}function w4(n){return n.kind==="raw"?{publicKey:n.publicKey,nonExtractable:!1,dh:e=>or.getSharedSecret(n.secretKey,e)}:{publicKey:n.publicKey,nonExtractable:!n.privateKey.extractable,dh:async e=>{let t=iq(),i=await t.importKey("raw",e,{name:"X25519"},!1,[]),o=await t.deriveBits({name:"X25519",public:i},n.privateKey,256);return new Uint8Array(o)}}}var v4=ek(),tq=new WeakMap;function nq(n,e){if(e&&(n.kind!=="webcrypto"||n.privateKey.extractable!==!1||n.privateKey.type!=="private"||n.privateKey.algorithm.name!=="X25519"||!n.privateKey.usages.includes("deriveBits")))throw A("invalid_request","a non-extractable X25519 key is required; explicitly reauthorize incompatible stored identities","key_storage")}async function rq(n,e={}){let t=e.storage??(globalThis.indexedDB?tk():v4),i=e.requireNonExtractable,o=tq.get(t);o||(o=new Map,tq.set(t,o));let s=o.get(n);s||(s=(async()=>{let r=await t.get(n);if(r)return r;let a=await b4();if(!a){if(i)throw A("invalid_request","this platform cannot keep a non-extractable X25519 key","key_storage");let c=or.utils.randomSecretKey();a={kind:"raw",secretKey:c,publicKey:or.getPublicKey(c)}}return nq(a,i),t.putIfAbsent?t.putIfAbsent(n,a):(await t.put(n,a),a)})(),o.set(n,s));try{let r=await s;return nq(r,i),w4(r)}finally{o.get(n)===s&&o.delete(n)}}nu();um();Je();No();re();function nk(n,e){for(let t of n.targets??[]){if(!/^[0-9a-f]{64}$/i.test(t.noise_pk)||!t.url||!t.device)continue;let i={url:t.url,targetDevice:t.device,noisePublicKey:Wr(t.noise_pk)};return t.relay_collection?i.pipe={collection:t.relay_collection,accessToken:e}:t.kind==="hosted"&&(i.prologueFirst=!0),i}return null}function oq(n){let e;try{e=new URL(n.server)}catch{throw A("invalid_request","The control plane requires an HTTPS origin")}if(e.protocol!=="https:"&&!!1||e.username||e.password||e.pathname!=="/"||e.search||e.hash)throw A("invalid_request","The control plane requires an HTTPS origin without credentials, path, query or fragment");let t=`${e.origin}/v1/next/collections/${encodeURIComponent(n.collection)}/route`,i=n.fetch??globalThis.fetch.bind(globalThis);return async()=>{let o=await n.accessToken(),s;try{s=await i(t,{headers:{authorization:`Bearer ${o}`},redirect:"error",credentials:"omit"})}catch{throw A("unavailable","cannot reach the control plane","control_unreachable")}if(s.status===401)throw A("unauthenticated","the control plane refused the access token");if(s.status===409)throw A("unauthenticated","this app's key is not registered with its grant","client_key_required");if(!s.ok)throw A("unavailable",`control plane answered ${s.status}`,"control_error");let r=await s.json(),a=wi(r.availability);if(a?.state==="unavailable")throw Fn(a.reason);let c=nk(r,o);if(!c&&r.reason==="no_device_registered")throw A("unavailable","this collection has no device set up to serve it","no_device_registered");return c}}xm();B_();No();Ls();var rk={};Ea(rk,{APP_BASES_PROFILE:()=>Vb,APP_COLLECTION_SETUP_LIMITS:()=>ho,AppAccountKeyProofUnavailableError:()=>as,AppAccountKeySealedBundle:()=>_c,AppAccountKeyUnlockError:()=>pt,AppCloudCopyBootstrapError:()=>qn,AppCloudCopyHostError:()=>hi,AppCollectionControlError:()=>Ei,AppCollectionJoinError:()=>ws,AppCollectionJoinLedger:()=>qc,AppCollectionSetupError:()=>Ln,AppCollectionSetupJournal:()=>Xl,AppCpAccountKeyControl:()=>Ac,AppCpAuthorityError:()=>pi,AppCpCloudCopyBootstrap:()=>Gl,AppCpDeviceRegistration:()=>Rc,AppCpLogAuthority:()=>Hl,AppCpPeopleAuthority:()=>yc,AppDeviceRegistrationError:()=>ka,AppHttpLogError:()=>En,AppHttpLogTransport:()=>Wl,AppIndexedDbDeviceKeyProtectedStore:()=>Pc,AppIndexedDbDeviceKeyProvider:()=>Sc,AppIndexedDbNoiseProtectedStore:()=>Ic,AppInstallationSignInError:()=>et,AppLogHostError:()=>xt,AppLogPump:()=>ia,AppProtectedInstallationSignIn:()=>Fl,AppReplicaOwnerError:()=>rt,AppStrictDeviceApprovalError:()=>Lt,AppWasmRuntime:()=>nc,AppWebCloudCopyHost:()=>Oc,AppWebCollectionError:()=>vu,AppWebDeviceKeyCustody:()=>xc,AppWebNoiseCustody:()=>Cc,AppWebSignInSession:()=>Mg,UNSYNCED_STORAGE_WARNING:()=>qR,acquireAppInstallationLease:()=>kd,acquireAppReplicaLease:()=>Ad,appBrowserDirectAccess:()=>Tg,appCollectionControlClient:()=>Zm,appInstallationLockName:()=>r_,appLocalConnector:()=>ey,appLogHealth:()=>Nd,appModelPackPlan:()=>Zs,appModelResourcePlan:()=>$t,appMutationSaveState:()=>ER,appReplicaLockName:()=>Rm,appSaveState:()=>dy,appStoragePolicy:()=>uy,attachAppLocalFacade:()=>Qm,createAppCollectionPeople:()=>Jm,createAppWebCollectionAdapter:()=>A2,decodeAppBasesCell:()=>Os,decodeAppBasesDiscoveryResult:()=>cf,decodeAppBasesResult:()=>af,decodeAppBasesSourceResult:()=>pf,decodeAppCollectionSetupIntent:()=>Zt,encodeAppBasesDiscoveryRequest:()=>fp,encodeAppBasesRequest:()=>sf,encodeAppBasesSourceRequest:()=>lf,openAppWebCollectionClient:()=>Ag,openOwnedAppWorker:()=>h1,probeAppStorage:()=>lq,readAccountKeyMode:()=>hg,selectAppEnvironment:()=>Ci,unlockPrivateDevice:()=>mg,verifyAppHandover:()=>aq});ty();Fb();function sq(n,e){return n.seq===e.seq&&n.chain===e.chain&&n.policyGeneration===e.policyGeneration&&n.catalogGeneration===e.catalogGeneration}async function aq(n,e){let t=null;try{let{runtime:i,localPort:o,localClient:s,hostedClient:r,source:a}=n,c=r.hello,l=s.hello,p=a.collection,d=a.deviceId,u=r.authenticatedDevice;if(!(P=>typeof P=="string"&&P.replace(/-/g,"").toLowerCase()===d.replace(/-/g,"").toLowerCase())(u))return null;let h=c.status.confirmedHead,m=h?Object.freeze({...h}):void 0;if(!m||!c.headWitness||c.headWitness.length>64*1024||m.seq===0||c.collection!==p||l.collection!==p)return null;t=new Uint8Array(c.headWitness);let w=t,b=()=>{try{return!e.aborted&&n.isCurrent()===!0&&a.isCurrent()===!0&&l.collection===p&&a.collection===p&&a.deviceId===d&&s.hello===l}catch{return!1}},g=()=>{try{let P=i.observations();return!P.requiresReopen&&!P.keyringRebuilding&&!P.keyringRebuildFailed&&P.status.mode==="synced"&&P.status.confirmedHead!==void 0&&P.status.confirmedHead.seq>=m.seq}catch{return!1}},y=()=>{if(!b()||!g())return!1;let P=i.verifyHandover(o,a,w);return P!==null&&sq(P,m)},v=()=>{try{return!e.aborted&&b()&&r.hello===c&&r.authenticatedDevice===u}catch{return!1}};if(!v()||!y())return null;let _=await s.appliedPrefix(m.seq,{signal:e});if(!v()||!y()||_.seq!==m.seq||_.appliedThrough<m.seq||_.chain!==m.chain)return null;let k=Object.freeze({...m}),S=!1,x={head:k,appliedThrough:_.appliedThrough,isCurrent:()=>{if(S)return!1;try{return y()&&sq(k,m)}catch{return!1}},dispose:()=>{S=!0,w.fill(0)}};return t=null,x}catch{return null}finally{t?.fill(0)}}E0();P0();k0();S0();O0();R0();Ed();Od();HA();Rd();ry();iy();async function lq(n){if(!n.worker)return{supported:!1,reason:"worker_required"};if(!n.storage?.getDirectory)return{supported:!1,reason:"opfs_unavailable"};let e,t,i=!1,o,s={supported:!1,reason:"probe_failed"};try{let r=n.randomUUID();if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(r))return s;t=r.toLowerCase(),e=await(await n.storage.getDirectory()).getDirectoryHandle(".mdbase-app-probes",{create:!0});let a=await e.getFileHandle(t,{create:!0});if(i=!0,!a.createSyncAccessHandle)s={supported:!1,reason:"sync_handle_unavailable"};else{o=await a.createSyncAccessHandle();let c=new Uint8Array([109,100,98,110]),l=new Uint8Array(c.length);if(o.write(c,{at:0})!==c.length)throw new Error("short probe write");if(o.flush(),o.read(l,{at:0})!==c.length||l.some((p,d)=>p!==c[d]))throw new Error("probe readback failed");s={supported:!0,backend:"opfs_sahpool_candidate",crashDurability:"unqualified",eviction:"possible"}}}catch{s={supported:!1,reason:"probe_failed"}}finally{let r=!0;try{o?.close()}catch{r=!1,s={supported:!1,reason:"cleanup_failed"}}if(i&&r&&e&&t)try{await e.removeEntry(t)}catch{s={supported:!1,reason:"cleanup_failed"}}}return s}os();rs();q0();ss();Ld();Qs();j_();_g();Id();var ik=Object.freeze({status:"unsupported"}),Tg=Object.freeze({snapshot(){return ik},async check(n={}){return n.signal?.throwIfAborted(),ik},async request(n={}){return n.signal?.throwIfAborted(),ik},disable(){}});ri();Id();wu();D1();re();Id();wu();Ed();Qs();ss();_g();Od();Rd();s0();gu();os();kc();ri();var _4=new Set(["binding","fenced","busy","open_in_another_tab","account_confirmation_required","recovery_account_mismatch","outcome_unknown","response","refused","expired","recovery_required","unavailable","collection_migrating","collection_not_yet_migrated","account_suspended","update_required","private_device_limit","private_device_not_allowed"]),A4=new Set(["AbortError","ConstraintError","DataCloneError","InvalidStateError","NotAllowedError","NotFoundError","NotReadableError","OperationError","QuotaExceededError","SecurityError","TimeoutError","TransactionInactiveError","UnknownError","VersionError"]),k4=new Set(["device_open","push_nonce","local_read_without_log","read_connect","read_catch_up","read_query","key_wait_offline","close_fence"]),vo=(n,e,t,i={})=>Object.freeze({problem:n,detail:Object.freeze({name:e,code:t,...Object.fromEntries(Object.entries(i).filter(([,o])=>o!==void 0))})});function S4(n){let e=k4.has(n.stage)?n.stage:void 0;if(e!=="device_open"||n.cause instanceof hi)return{stage:e};let{name:t,code:i}=Pa(n.cause).detail;return{stage:e,cause:Object.freeze({name:t,code:i})}}function Pa(n){try{for(let[e,t]of[[et,"AppInstallationSignInError"],[hi,"AppCloudCopyHostError"],[qn,"AppCloudCopyBootstrapError"],[Ln,"AppCollectionSetupError"],[Ei,"AppCollectionControlError"],[ws,"AppCollectionJoinError"],[pi,"AppCpAuthorityError"],[En,"AppHttpLogError"],[ga,"AppPrivateBootstrapError"],[pt,"AppAccountKeyUnlockError"]])if(n instanceof e){let i=n.reason,s={server:("server"in n?zo(n.server):null)??void 0,...n instanceof hi?S4(n):{}};return i==="sync_stalled"?vo("unavailable",t,i,s):_4.has(i)?vo(i,t,i,s):vo("open_failed",t,null,s)}if(n instanceof ji)return vo(n.reason,"AppDeviceCustodyError",n.reason);if(n instanceof rt&&n.reason==="busy")return vo("open_in_another_tab","AppReplicaOwnerError","busy");if(n instanceof ne){let e=Po(n.code)?n.code:null;return vo(e==="outcome_unknown"?e:"open_failed","MdbaseError",e)}if(typeof DOMException<"u"&&n instanceof DOMException){let e=A4.has(n.name)?n.name:null;return vo("open_failed","DOMException",e)}for(let[e,t]of[[TypeError,"TypeError"],[RangeError,"RangeError"],[SyntaxError,"SyntaxError"],[ReferenceError,"ReferenceError"],[URIError,"URIError"],[EvalError,"EvalError"],[Error,"Error"]])if(n instanceof e)return vo("open_failed",t,null)}catch{}return vo("open_failed","UnknownError",null)}Ed();rs();os();Tm();re();var P4=Object.freeze({status:"unselected",problem:null,transport:null,live:null}),ft=n=>new et(n),cq=(n,e,t)=>n.problem===void 0||n.problem===e?t:void 0,x4=new Set(["collection_not_yet_migrated","collection_migrating","account_suspended","update_required"]),I4,C4,Mg=class{static{I4=(e,t,i,o)=>e.authorizeInstallation(t,i,o),C4={references:e=>e.flow?uo.references(e.flow):[],paired:(e,t)=>e.scopedInstallationPaired(t)}}lifetime=new AbortController;flowLifetime=new AbortController;options;environment;listeners=new Set;flow=null;host=null;installation=null;installationLease=null;slots=new Map;focus=null;openingSlot=null;abortCollections=()=>{for(let e of this.slots.values())e.lifetime?.abort()};base=Object.freeze({status:"not_started",signIn:null,collections:Object.freeze([]),selectedCollectionId:null,problem:null,timing:null});snapshotValue=this.base;authorizationStartedAt=null;authorizationRetryAt=0;authorizationRateLimit=null;pending=null;polling=null;timer=null;closing=null;foreground=!0;receiptRead=null;foregroundRead=null;attested=!1;restoredPending=!1;acknowledged=!1;consentPending=!1;listCached=!1;fileAccess=null;freshApproval=!1;approvalWindow=null;leftForApproval=!1;nativePending=null;forgotten=new Set;removedScopes=new Set;onAbort=()=>{this.close().catch(()=>{})};constructor(e){this.options=Object.freeze({...e}),this.environment=Ci({environment:e.environment,appOrigin:e.origin,release:e.release}),e.signal.addEventListener("abort",this.onAbort,{once:!0}),this.lifetime.signal.addEventListener("abort",this.abortCollections,{once:!0})}getSnapshot(){return this.snapshotValue}snapshot(){return this.getSnapshot()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}viewFor(e,t={}){return t.bystander&&this.base.status==="authorizing"&&this.consentPending&&e!==null&&this.slots.has(e)?this.compose(e,!0):e===this.focus?this.snapshotValue:this.compose(e)}collectionView(e){return this.slots.get(e)?.view??null}heldCollections(){return[...this.slots.keys()]}compose(e,t=!1){let i=this.base,o=e===null?void 0:this.slots.get(e);if(!o)return i;if(i.status!=="unselected"&&!t)return Object.freeze({...i,selectedCollectionId:o.id,transport:o.view.transport,live:o.view.live});let{problemDetail:s,...r}=i,{problemDetail:a,...c}=o.view;return Object.freeze({...r,...t?{status:"unselected",problem:null,approval:null}:{},...c,selectedCollectionId:o.id,...a?{problemDetail:a}:{}})}connection(e=this.focus){let t=e===null?void 0:this.slots.get(e),i=this.base.status==="unselected"||this.base.status==="authorizing"&&this.consentPending;return!t||this.closing||this.options.signal.aborted||!t.usable||t.lifetime?.signal.aborted||!this.installation?.isCurrent()||!i||!["ready","setup_required"].includes(t.view.status)||!this.sameScope(t.scope,t.leaseScope)||t.scope?.collection!==t.id?null:t.selected?.connection??null}sameScope(e,t){return e!==null&&t!==null&&e.account===t.account&&e.installation===t.installation&&e.collection===t.collection&&e.account===this.installation?.scope.account&&e.installation===this.installation?.scope.installation}directAccess=Tg;checkDirectAccess(e){return this.check(),this.directAccess.check(e)}requestDirectAccess(e){return this.check(),this.directAccess.request(e)}check(){if(this.closing||this.options.signal.aborted||this.lifetime.signal.aborted)throw ft("fenced")}publish(e){this.check(),this.setBase(e),this.changed()}setBase(e){let{problemDetail:t,...i}=this.base,o=e.problemDetail??cq(e,i.problem,t);this.base=Object.freeze({...i,...e,selectedCollectionId:null,signIn:this.flow?.view()??null,...o?{problemDetail:o}:{}})}publishSlot(e,t){if(this.check(),this.slots.get(e.id)!==e)return;let i=this.base.timing;if(this.authorizationStartedAt!==null&&(t.status==="ready"||t.status==="setup_required")){let u=Math.max(0,performance.now()-this.authorizationStartedAt);i=Object.freeze({firstScreenMs:i?.firstScreenMs??u,readyMs:t.status==="ready"?i?.readyMs??u:i?.readyMs??null})}this.setBase({timing:i});let{problemDetail:o,unlock:s,...r}=e.view,{unlock:a,...c}=t,l=t.problemDetail??cq(t,r.problem,o),p=(t.status??r.status)==="opening"?"openingProgress"in t?t.openingProgress??null:r.openingProgress??null:null,d=(t.status??r.status)==="needs_unlock"?a??s??null:null;e.view=Object.freeze({...r,...c,openingProgress:p,...d?{unlock:d}:{},...l?{problemDetail:l}:{}}),this.changed()}changed(){this.snapshotValue=this.compose(this.focus);for(let e of[...this.listeners])try{e()}catch{}}poll(e){this.pending||(this.operation(e).catch(()=>{}),this.polling=this.pending)}stopPolling(){this.timer!==null&&clearTimeout(this.timer),this.timer=null}operation(e,t=!1){if(this.check(),this.pending)return Promise.reject(ft("busy"));this.foregroundRead=null,this.stopPolling();let o=Promise.resolve().then(()=>(this.check(),e())).catch(async s=>{if(!t&&!this.closing&&!this.options.signal.aborted){let{problem:r,detail:a}=Pa(s);if(r==="open_failed")try{console.error("mdbase web sign-in open failed",a.name,a.code)}catch{}let c=this.openingSlot;if(this.openingSlot=null,c&&this.slots.get(c.id)===c){let l=!1;try{l=s instanceof qn&&s.reason==="unavailable"&&s.retryable===!0&&c.view.status==="opening"&&this.base.collections.some(p=>p.collectionId===c.id)&&this.flow?.view().state==="paired"&&this.installation?.isCurrent()===!0}catch{}if(l){try{await this.closeSlot(c),this.check()}catch(p){throw!this.closing&&!this.options.signal.aborted&&this.publishSlot(c,{status:"blocked",problem:"recovery_required",problemDetail:Pa(p).detail}),p}this.publishSlot(c,{status:"unselected",problem:r,problemDetail:a})}else this.publishSlot(c,{status:"blocked",problem:r,problemDetail:a})}else this.publish({status:"blocked",problem:r,problemDetail:a})}throw s});return this.pending=o,o.finally(()=>{this.pending===o&&(this.pending=null),this.schedulePoll()})}start(){return this.operation(async()=>{if(this.flow&&(this.base.status!=="blocked"||this.base.problem==="installation_removed"))return this.getSnapshot();this.publish({status:"starting",problem:null,signOutResult:null});let e=this.options;this.flow??=await Fl.open({...e,mode:e.storeMode??"open",signal:this.flowLifetime.signal,environmentSelection:this.environment}),this.check();let t=this.flow.view();if(uo.replacementPending(this.flow)){for(let i of t.collectionIds)this.removedScopes.add(i);this.publish({status:"blocked",problem:"installation_removed",collections:Object.freeze([])})}else if(t.state==="paired")if(await this.openDevice(!1,this.options.recoveryFor!==void 0),await this.abandonUnfinishedNativeChoice(),this.flow.collectionConsentView()?.state==="pending")this.consentPending=!0,this.publish({status:"authorizing"});else{let i=null;try{i=this.flow.cachedApprovedCollections(this.installation)}catch{i=null}await this.refreshCollections(i)}else this.restoredPending=t.state==="pending"&&this.flow.requestSent(),this.publish({status:t.state==="pending"&&!this.restoredPending?"signed_out":"authorizing"});return this.getSnapshot()})}authorize(e={}){return this.authorizeInstallation(e,!1)}authorizeInstallation(e,t,i){if(this.check(),this.authorizationRateLimit&&Date.now()<this.authorizationRetryAt)return Promise.reject(this.authorizationRateLimit);let o=this.pending!==null&&this.pending===this.polling?this.pending:null;if(!this.flow||this.pending&&!o)return Promise.reject(ft("busy"));let s=this.options.openPortal();return o?o.catch(()=>{}).then(()=>{try{this.check()}catch(a){throw s.close(),a}if(this.pending)throw s.close(),ft("busy");let r=this.base.status;return r!=="authorizing"&&r!=="signed_out"?(s.close(),this.getSnapshot()):this.beginAuthorization(s,e,t,i)}):this.beginAuthorization(s,e,t,i)}beginAuthorization(e,t,i,o){let s={collectionHint:t.collectionHint??null};return this.restoredPending=!1,this.authorizationStartedAt=performance.now(),this.publish({timing:Object.freeze({firstScreenMs:null,readyMs:null}),approval:null}),this.operation(async()=>{try{(this.base.problem==="installation_removed"||uo.replacementPending(this.flow))&&await this.replaceRemovedInstallation(o);let r=null;if(this.flow.view().state==="paired"){await this.openDevice(),this.check(),await this.abandonUnfinishedNativeChoice();try{let a=await this.flow.startCollectionConsent(this.installation,this.options.requestedCreateCollections??this.options.freshRequestedCreateCollections??!1,s,this.options.freshRequestedPrivateDevice===!0);this.consentPending=!0,r=a.verificationUri}catch(a){if(!await this.handleRemovedInstallation(a))throw a;if(i)return e.close(),this.getSnapshot();await this.replaceRemovedInstallation(o)}}return r===null&&(r=(await this.flow.start(s).catch(c=>this.renewFromGesture(c))).verificationUri),this.check(),e.navigate(r),this.holdApprovalWindow(e),this.publish({status:"authorizing",problem:null}),await this.advance(),this.getSnapshot()}catch(r){throw r instanceof et&&r.server?.status===429&&(this.authorizationRateLimit=r,this.authorizationRetryAt=Date.now()+Math.min(Xa,Math.max(Ja,r.server.retryAfterMs??3e4))),e.close(),r}})}requestFileAccess(e,t,i){if(this.check(),!this.flow||this.pending)return Promise.reject(ft("busy"));let o=this.options.openPortal();return this.operation(async()=>{try{if(this.flow.view().state!=="paired"||!this.installation||!this.base.collections.some(r=>r.collectionId===e))throw ft("refused");let s=await this.flow.startFileAccess(this.installation,e,t,i);return this.check(),this.fileAccess=s,o.navigate(s.verificationUri),this.holdApprovalWindow(o),this.publish({fileAccess:Object.freeze({requestId:s.requestId,collectionId:e,actions:s.actions,state:"pending"})}),this.getSnapshot()}catch(s){throw o.close(),s}},!0)}pollFileAccess(e){let t=this.fileAccess;return!t||t.requestId!==e||!this.flow||!this.installation?Promise.resolve(this.getSnapshot()):this.operation(async()=>{let i={state:"pending"};try{i=await this.flow.exchangeFileAccess(this.installation,t)}catch(r){if(Date.now()<t.expiresAt)throw r}if(this.check(),this.fileAccess!==t||i.state==="pending"&&Date.now()<t.expiresAt)return this.getSnapshot();this.fileAccess=null,this.closeApprovalWindow();let o=i.state==="granted"?i.actions:null,s=o?Object.freeze(this.base.collections.map(r=>r.collectionId!==t.collectionId?r:Object.freeze({...r,fileActions:Object.freeze([...new Set([...r.fileActions??[],...o])])}))):this.base.collections;return this.publish({collections:s,fileAccess:Object.freeze({requestId:e,collectionId:t.collectionId,actions:o??t.actions,state:i.state==="pending"?"expired":i.state})}),this.getSnapshot()},!0)}async renewFromGesture(e){if(!(e instanceof et)||e.reason!=="expired"&&e.reason!=="refused")throw e;try{return await this.flow.renewExpiredPairing()}catch(t){throw t instanceof et&&t.reason==="recovery_required"?e:t}}renewExpiredPairing(){return this.operation(async()=>{if(!this.flow)throw ft("binding");return await this.flow.renewExpiredPairing(),this.check(),this.publish({status:"signed_out",problem:null}),this.getSnapshot()})}receiptGeneration(e){try{if(!e.isCurrent())return null;let t=e.view(),i=this.consentPending?e.collectionConsentView():null;return(this.consentPending?i?.state!=="pending":!["pending","awaiting_approval"].includes(t.state))?null:JSON.stringify([t.requestId,t.installationId,t.deviceId,t.accountId,t.state,this.consentPending,i?.requestId,i?.state])}catch{return null}}currentReceipt(e){try{return!this.closing&&!this.lifetime.signal.aborted&&!this.flowLifetime.signal.aborted&&!e.caller.aborted&&this.options.signal===e.caller&&this.flow===e.flow&&this.installation===e.installation&&(e.installation===null||e.installation.isCurrent()===!0)&&this.attested===e.attested&&this.acknowledged===e.acknowledged&&this.receiptGeneration(e.flow)===e.generation}catch{return!1}}async exchangeReceipt(e){let t=this.flow,i=this.pending,o=t?this.receiptGeneration(t):null,s=t&&i&&o!==null?Object.freeze({flow:t,operation:i,generation:o,caller:this.options.signal,installation:this.installation,attested:this.attested,acknowledged:this.acknowledged}):null;this.receiptRead=s;let r=!1;try{let a=await e();return r=a!=null,a}catch(a){if(a instanceof et&&a.reason==="outcome_unknown"&&this.flow?.isCurrent())return this.publish({status:"authorizing",problem:"outcome_unknown"}),null;throw a}finally{this.receiptRead===s&&(this.receiptRead=null),this.foregroundRead===s&&(!r||!s||!this.currentReceipt(s))&&(this.foregroundRead=null)}}async advance(){if(this.consentPending){let t;try{t=await this.exchangeReceipt(()=>this.flow.exchangeCollectionConsent(this.installation))}catch(i){if(!(i instanceof et)||i.reason!=="refused"&&i.reason!=="expired")throw i;this.check(),this.consentPending=!1,this.closeApprovalWindow(),this.publish({status:"unselected",problem:null,approval:Object.freeze({outcome:"cancelled"})}),await this.refreshCollections();return}if(this.check(),!t)return;if(t.state==="scope_updated"){if(t.accountSelectionConfirmed!==!0)throw ft("account_confirmation_required");let i=this.flow.pendingNativeSelection?.();if(i?.requestId===t.requestId){if(!await this.settleNativeChoice(i)){this.consentPending=!1,this.closeApprovalWindow(),this.publish({status:"unselected",problem:null,approval:Object.freeze({outcome:"closed"})}),await this.refreshCollections();return}}else if(this.flow.view().collectionSelection?.requestId!==t.requestId&&!this.deviceAccessWithoutPick(t.requestedPrivateDevice===!0?t.addedCollectionIds:[]))throw ft("response");this.consentPending=!1,this.freshApproval=!0,this.closeApprovalWindow(),await this.refreshCollections()}else await this.prepareNativeChoice(),this.resumeApprovalWindow(),this.publish({status:"authorizing",problem:this.nativePending?.failed?"private_authorization_failed":null});return}let e;try{e=await this.exchangeReceipt(()=>this.flow.exchange())}catch(t){if(!this.restoredPending||!(t instanceof et)||t.reason!=="expired"&&t.reason!=="refused")throw t;this.check(),this.restoredPending=!1,this.publish({status:"signed_out",problem:null});return}if(this.check(),!!e)if(e.state==="account_selected"&&(e=await this.flow.confirmPortalSelectedAccount(),this.check()),(e.state==="account_confirmed"||e.state==="awaiting_approval")&&(await this.openDevice(),this.check(),this.attested||(await this.host.attestInstallation(),this.check(),this.attested=!0),await this.prepareNativeChoice(),this.resumeApprovalWindow()),e.state==="paired"){let t=this.flow.pendingNativeSelection?.(),i=t?.requestId===e.requestId&&!await this.settleNativeChoice(t);if(t?.requestId!==e.requestId&&e.collectionSelection?.requestId!==e.requestId&&!this.deviceAccessWithoutPick(e.privateDeviceCollectionIds??[]))throw ft("response");this.freshApproval=!0,this.closeApprovalWindow(),await this.openDevice(),this.check(),i&&this.publish({approval:Object.freeze({outcome:"closed"})}),await this.refreshCollections()}else this.publish({status:"authorizing",problem:this.nativePending?.failed?"private_authorization_failed":null})}deviceAccessWithoutPick(e){let t=this.flow.view(),i=t.privateDeviceCollectionIds??[];return(t.collectionSelection??null)===null&&e.some(o=>i.includes(o))}resumeApprovalWindow(){if(!(!this.leftForApproval||!this.foreground||!this.approvalWindow||!this.appPartDone())){this.leftForApproval=!1;try{this.approvalWindow.focus?.()}catch{}}}appPartDone(){if(!this.attested)return!1;if(!this.approvalWindow?.nativeAuthorization||!this.installation||!this.flow.nativeAuthorizationContext(this.installation))return!0;let e=this.nativePending;return e!==null&&e.attempted&&!e.failed}async prepareNativeChoice(){let e=this.approvalWindow?.nativeAuthorization;if(!e||!this.installation)return;let t=this.flow.nativeAuthorizationContext(this.installation);if(!t)return;let i=this.nativePending;if(!i){if(i={context:t,port:e,life:new AbortController,prepared:null,failed:!1,attempted:!1},this.nativePending=i,t.authorizationId){i.failed=!0;return}let o=i,s=AbortSignal.any([this.lifetime.signal,this.flowLifetime.signal,i.life.signal]);e.prepare(t,s).then(r=>{this.nativePending!==o||s.aborted||(o.prepared=Object.freeze({...r}))},()=>{o.failed=!0})}if(i.context.requestId!==t.requestId||i.context.accountId!==t.accountId||i.context.challenge!==t.challenge)throw ft("fenced");if(i.prepared&&!i.attempted){i.attempted=!0;try{await this.flow.attachNativeAuthorization(this.installation,i.context,i.prepared),this.check()}catch{i.failed=!0}}}async finishNativeChoice(e){let t=this.nativePending;if(!t||!t.prepared||!t.attempted||t.context.requestId!==e.requestId||t.prepared.authorizationId!==e.authorizationRequestId)throw ft("recovery_required");let i=await t.port.finish(e,AbortSignal.any([this.lifetime.signal,this.flowLifetime.signal,t.life.signal]));if(this.check(),this.nativePending!==t||!this.acknowledged||!this.installation)throw ft("fenced");await this.flow.completeNativeAuthorization(this.installation,i),this.check()}async settleNativeChoice(e){await this.openDevice(),this.check();try{return await this.finishNativeChoice(e),!0}catch(t){this.check();let i=!1;try{i=this.installation!==null&&await this.flow.abandonNativeSelection?.(this.installation)===!0}catch{i=!1}if(this.check(),!i)throw t;try{console.warn("mdbase: a Private collection pick was not finished",Pa(t).detail.code)}catch{}return!1}}async abandonUnfinishedNativeChoice(){let e=this.flow;if(!e.pendingNativeSelection?.()||e.view().nativeSelection)return;if(!this.installation||!e.abandonNativeSelection)throw ft("recovery_required");let t=await e.abandonNativeSelection(this.installation);if(this.check(),!t)throw ft("recovery_required")}holdApprovalWindow(e){this.approvalWindow!==e&&this.closeApprovalWindow(),this.approvalWindow=e,this.leftForApproval=!1}closeApprovalWindow(){let e=this.approvalWindow;this.approvalWindow=null,this.leftForApproval=!1;let t=this.nativePending;this.nativePending=null,t?.life.abort();try{t?.port.cancel()}catch{}if(e)try{e.close()}catch{}}async openDevice(e=!1,t=!1){if(!this.installation){let i=this.flow.confirmedSelection(),o=Object.freeze({account:i.accountId,installation:i.installationId});this.installationLease=await kd(this.options.locks,o,this.lifetime.signal),this.check();let s=this.installationLease;this.installation=Object.freeze({scope:o,isCurrent:()=>!this.closing&&!this.options.signal.aborted&&!this.lifetime.signal.aborted&&this.installationLease===s})}t||!this.host&&!e&&this.acknowledged&&this.flow.view().state==="paired"&&[...this.slots.values()].some(i=>i.host!==null)||(this.host?!this.acknowledged&&this.flow.view().state==="paired"&&(await this.host.completeInstallationSignIn(),this.check(),this.acknowledged=!0):(this.host=await Oc.openInstallationDevice({signIn:this.flow,installation:this.installation,release:this.options.release,origin:this.options.origin,signal:this.lifetime.signal,loadRuntime:this.options.loadRuntime,allowLoopbackHttp:this.environment.allowLoopbackHttp}),this.check(),this.acknowledged=this.flow.view().state==="paired"))}async refreshCollections(e=null){let t;try{t=e??await this.flow.listApprovedCollections(this.installation)}catch(s){if(await this.handleRemovedInstallation(s))return;throw s}if(this.check(),this.listCached=e!==null,!e)for(let s of this.flow.view().collectionIds)t.some(r=>r.collectionId===s)||this.removedScopes.add(s);let i=Object.freeze(t.filter(s=>!this.forgotten.has(s.collectionId)));for(let s of this.slots.values()){if(s.usable&&s.selected&&!i.some(p=>p.collectionId===s.id)){s.usable=!1,s.lifetime?.abort(),await this.closeSlot(s),this.check(),this.deleteSlot(s);continue}let r=s.usable&&s.selected!==null&&i.some(p=>p.collectionId===s.id),{problemDetail:a,unlock:c,...l}=s.view;s.view=Object.freeze({...l,...r?this.assessed(s.selected):{status:"unselected"},problem:null})}this.publish({status:"unselected",collections:i,problem:null});let o=this.flow.view().collectionSelection?.selectedCollectionId;(this.options.autoSelect??"only")==="only"&&(this.freshApproval&&o&&i.some(s=>s.collectionId===o)?await this.openSlot(o,!0):i.length===1&&await this.openSlot(i[0].collectionId,!0))}async handleRemovedInstallation(e){if(!(e instanceof et)||!rn(e.server)||e.server.status!==401||e.server.code!=="invalid_connector")return!1;this.check(),this.listCached=!1;for(let t of this.flow.view().collectionIds)this.removedScopes.add(t);this.consentPending=!1,this.closeApprovalWindow();for(let t of this.slots.values())t.usable=!1,t.lifetime?.abort();return this.publish({status:"blocked",problem:"installation_removed",problemDetail:Pa(e).detail,collections:Object.freeze([])}),await this.closeSlots(),this.check(),this.changed(),!0}async replaceRemovedInstallation(e){let t=this.flow;try{await g_(t,async()=>{await e?.stopChildren(),await this.closeSlots(),this.check()},e?.childPaired)}catch(i){throw t.isCurrent()||(this.flow=null),i}this.check(),await this.installationLease?.release(),this.installationLease=null,this.installation=null,this.check(),this.attested=!1,this.acknowledged=!1,this.freshApproval=!1,this.fileAccess=null,this.forgotten.clear(),this.removedScopes.clear(),this.publish({status:"signed_out",problem:null,fileAccess:void 0})}schedulePoll(){if(this.pending&&!this.closing&&!this.options.signal.aborted)return;let e=this.foregroundRead;this.foregroundRead=null;for(let i of this.closing||this.options.signal.aborted?[]:this.slots.values()){let o=this.retryAfterMs(i);o===null||i.timer!==null||i.view.status!=="blocked"||(i.timer=setTimeout(()=>{i.timer=null,!(this.slots.get(i.id)!==i||i.view.status!=="blocked"||i.view.problem!=="collection_migrating"||this.flow?.view().state!=="paired")&&this.operation(()=>this.openSlot(i.id)).catch(()=>{})},o))}if(this.closing||this.options.signal.aborted||this.timer!==null||this.base.status!=="authorizing")return;let t=this.foreground&&e&&this.currentReceipt(e)?e:null;this.timer=setTimeout(()=>{this.timer=null,this.poll(async()=>{t&&(!this.foreground||!this.currentReceipt(t))||await this.advanceApproval()})},t?0:this.foreground?this.base.problem==="outcome_unknown"?5e3:1e3:1e4)}retryAfterMs(e){let t=e.view;if(t.problem!=="collection_migrating")return null;let i=null;try{i=zo(t.problemDetail?.server)?.retryAfterMs??null}catch{i=null}return Math.min(Xa,Math.max(Ja,i??3e4))}setForeground(e){this.check();let t=e&&!this.foreground;this.foreground=e,this.stopPolling(),e?t&&this.receiptRead?.operation===this.pending&&(this.foregroundRead=this.receiptRead):(this.foregroundRead=null,this.approvalWindow&&!this.appPartDone()&&(this.leftForApproval=!0)),e&&this.base.status==="authorizing"&&!this.pending?this.poll(()=>this.advanceApproval()):this.schedulePoll()}approvalWindowClosed(){this.check(),!(this.pending||this.base.status!=="authorizing"||!this.approvalWindowGone())&&(this.stopPolling(),this.poll(()=>this.advanceApproval()))}approvalWindowGone(){let e=this.approvalWindow;try{return e?.closed===!0}catch{return!1}}async cancelAuthorization(){for(this.check();this.pending;)await this.pending.catch(()=>{}),this.check();return this.operation(async()=>{if(this.base.status!=="authorizing")return this.getSnapshot();this.closeApprovalWindow();let e=Object.freeze({outcome:"closed"});return this.consentPending?(this.consentPending=!1,this.publish({status:"unselected",problem:null,approval:e}),await this.refreshCollections()):(await this.flow.forgetSentRequest(),this.check(),this.restoredPending=!1,this.publish({status:"signed_out",problem:null,approval:e})),this.getSnapshot()})}async advanceApproval(){let e=this.approvalWindowGone()?this.approvalWindow:null;if(await this.advance(),this.check(),!(!e||this.approvalWindow!==e||this.base.status!=="authorizing")&&this.base.problem!=="outcome_unknown"){if(this.closeApprovalWindow(),this.consentPending){this.consentPending=!1,this.publish({status:"unselected",problem:null,approval:Object.freeze({outcome:"closed"})}),await this.refreshCollections();return}this.publish({status:"signed_out",problem:"approval_window_closed",approval:Object.freeze({outcome:"closed"})})}}select(e){return this.operation(async()=>(await this.openSlot(e,!0),this.getSnapshot()))}openCollection(e){return this.operation(async()=>(await this.openSlot(e),this.viewFor(e)))}releaseCollection(e){return this.slots.has(e)?this.operation(async()=>{let t=this.slots.get(e);return t&&(await this.closeSlot(t),this.check(),this.deleteSlot(t),this.changed()),this.getSnapshot()}):Promise.resolve(this.getSnapshot())}async openSlot(e,t=!1){this.check();let i=this.base.collections.find(h=>h.collectionId===e);if(!i||this.flow?.view().state!=="paired"||!this.installation)throw ft("refused");let o=t?[...this.slots.values()].filter(h=>h.id!==e):[],s=this.slots.get(e);if(s&&s.usable&&s.selected&&!s.lifetime?.signal.aborted&&this.sameScope(s.scope,s.leaseScope)&&s.scope?.collection===e){for(let h of o)h.usable=!1,h.lifetime?.abort();this.focus=e,this.settleBase(),this.publishSlot(s,{...this.assessed(s.selected),problem:null});for(let h of o)await this.closeSlot(h),this.check(),this.deleteSlot(h),this.changed();return}for(let h of o)h.usable=!1,h.lifetime?.abort();let r=s??{id:e,host:null,lease:null,leaseScope:null,selected:null,scope:null,lifetime:null,usable:!1,stopAssessment:null,timer:null,view:P4};r.usable=!1,r.lifetime?.abort(),this.slots.set(e,r),this.focus=e,this.openingSlot=r,this.settleBase(),this.publishSlot(r,{status:"opening",problem:null,openingProgress:null});for(let h of o)await this.closeSlot(h),this.check(),this.deleteSlot(h),this.changed();(r.lease||r.selected||r.host)&&await this.closeSlot(r),this.check(),await this.openDevice(!0),this.check(),r.host=this.host,this.host=null;let a=Object.freeze({...this.installation.scope,collection:e});r.lease=await Ad(this.options.locks,a,this.lifetime.signal),r.leaseScope=a,this.check(),r.lifetime=new AbortController;let c=this.freshApproval&&this.flow.view().collectionSelection?.createdCollectionIds.includes(e)===!0,l=r.lifetime,p=await this.options.openCollection({host:r.host,installation:this.installation,scope:a,collection:i,setupPolicy:c?"approved-new-collection":"explicit",signal:l.signal,onProgress:h=>{this.closing||this.slots.get(r.id)!==r||r.lifetime!==l||l.signal.aborted||r.view.status!=="opening"||r.view.openingProgress!==h&&this.publishSlot(r,{openingProgress:h})}});r.selected=p,r.scope=a,this.check();let d=this.assessed(p);r.usable=!0,this.openingSlot===r&&(this.openingSlot=null),r.stopAssessment=p.subscribe?.(()=>{if(this.closing||this.slots.get(r.id)!==r||!r.usable||r.selected!==p||r.lifetime?.signal.aborted||!this.sameScope(r.scope,r.leaseScope)||r.scope?.collection!==r.id)return;let h=null;try{h=p.ended??null}catch{h=null}if(h){this.accessEnded(r,p,h);return}let m=null;try{m=p.failure??null}catch{m=null}if(m!==null){this.openFailedLate(r,p,m);return}let w;try{w=this.assessed(p)}catch{return}this.publishSlot(r,w.status==="needs_unlock"?{...w,problem:null,transport:null,live:null}:{...w,...this.liveProblem(r,p)})})??null;let u=null;try{u=p.ended??null}catch{u=null}let f=null;try{f=p.failure??null}catch{f=null}if(u){this.accessEnded(r,p,u);return}if(f!==null){this.openFailedLate(r,p,f);return}this.publishSlot(r,{...d,transport:null,live:null,openingProgress:null})}assessed(e){let t=e.state;if(t==="ready"||t==="setup_required")return{status:t};if(t!=="needs_unlock"||typeof e.unlock!="function")throw ft("response");let i=e.locked;if(!i||typeof i!="object"||!["password","strict","none"].includes(i.mode)||typeof i.unlocking!="boolean"||i.problem!==null&&(typeof i.problem!="string"||!/^[a-z][a-z0-9_]{0,63}$/.test(i.problem)))throw ft("response");return{status:t,unlock:Object.freeze({mode:i.mode,unlocking:i.unlocking,problem:i.problem})}}unlockCollection(e,t){let i=()=>{let o=this.slots.get(e);return o&&o.usable&&o.selected&&typeof o.selected.unlock=="function"&&o.view.status==="needs_unlock"&&!o.lifetime?.signal.aborted&&this.base.status==="unselected"&&this.installation?.isCurrent()===!0&&this.sameScope(o.scope,o.leaseScope)&&o.scope?.collection===e?o:null};return!this.closing&&!this.options.signal.aborted&&!this.pending&&!i()?Promise.reject(ft("refused")):this.operation(async()=>{let o=i();if(!o)throw ft("refused");let s=o.selected;this.openingSlot=o;try{await s.unlock(t),this.check()}catch(a){throw o.usable=!1,o.lifetime?.abort(),a}if(this.slots.get(o.id)!==o||o.selected!==s||!o.usable)throw ft("fenced");this.openingSlot===o&&(this.openingSlot=null);let r=this.assessed(s);return this.publishSlot(o,r.status==="needs_unlock"?{...r,problem:null}:{...r,...this.liveProblem(o,s)}),this.viewFor(e)})}settleBase(){(this.base.status==="blocked"||this.base.status==="unselected")&&this.setBase({status:"unselected",problem:null})}deleteSlot(e){e.timer!==null&&clearTimeout(e.timer),e.timer=null,this.slots.get(e.id)===e&&this.slots.delete(e.id),this.focus===e.id&&(this.focus=null),this.openingSlot===e&&(this.openingSlot=null)}accessEnded(e,t,i){if(e.selected!==t||!e.usable)return;let o=i==="gone"?"collection_deleted":i==="revoked"?"unauthenticated":"access_removed";i!=="gone"&&this.removedScopes.add(e.id),e.usable=!1,this.publishSlot(e,{status:"blocked",problem:o,transport:null,live:null});let s=()=>{if(!(this.closing||this.options.signal.aborted||e.selected!==t||this.slots.get(e.id)!==e)){if(this.pending){this.pending.catch(()=>{}).then(s);return}this.operation(async()=>{if(await this.closeSlot(e),this.publishSlot(e,{status:"blocked",problem:o}),!(!this.flow||!this.installation||this.flow.view().state!=="paired"))try{let r=await this.flow.listApprovedCollections(this.installation);this.check(),this.publish({collections:Object.freeze(r.filter(a=>!this.forgotten.has(a.collectionId)))})}catch{}}).catch(()=>{})}};s()}openFailedLate(e,t,i){if(e.selected!==t||!e.usable)return;let{problem:o,detail:s}=Pa(i);if(o==="open_failed")try{console.error("mdbase web sign-in open failed",s.name,s.code)}catch{}e.usable=!1,this.publishSlot(e,{status:"blocked",problem:o,problemDetail:s,transport:null,live:null});let r=()=>{if(!(this.closing||this.options.signal.aborted||e.selected!==t||this.slots.get(e.id)!==e)){if(this.pending){this.pending.catch(()=>{}).then(r);return}this.operation(async()=>{await this.closeSlot(e),this.publishSlot(e,{status:"blocked",problem:o,problemDetail:s})},!0).catch(()=>{})}};r()}liveProblem(e,t){let i=null;try{i=t.problem??null}catch{i=null}let o=null;try{o=t.health??null}catch{o=null}let s=o?Object.freeze({...o}):null,r=null;try{let c=t.live;r=typeof c=="boolean"?c:null}catch{r=null}let a=rn(i)?Rt(i):null;return a&&i?{problem:a,problemDetail:Object.freeze({name:"AppHttpLogError",code:a,server:i}),transport:s,live:r}:{...x4.has(e.view.problem??"")?{problem:null}:{},transport:s,live:r}}async closeSlot(e){e.usable=!1,e.timer!==null&&clearTimeout(e.timer),e.timer=null;let t=e.stopAssessment;e.stopAssessment=null;try{t?.()}catch{}e.lifetime?.abort(),await e.selected?.close(),e.selected=null,e.scope=null,e.lifetime=null,await e.host?.close(),e.host=null,await e.lease?.release(),e.lease=null,e.leaseScope=null}async closeSlots(){for(let e of[...this.slots.values()])await this.closeSlot(e),this.deleteSlot(e);await this.host?.close(),this.host=null}clearSelection(){return this.operation(async()=>(await this.closeSlots(),this.focus=null,this.publish({status:"unselected",problem:null}),this.getSnapshot()))}refreshCollectionList(){return this.pending||!this.flow||!this.installation||this.consentPending||this.flow.view().state!=="paired"||this.base.status!=="unselected"?Promise.resolve(this.getSnapshot()):this.operation(async()=>(await this.refreshCollections(),this.getSnapshot()),!0)}collectionListCached(){return this.listCached}scopeWasRemoved(e){return this.removedScopes.has(e)}removedScopeIds(){return Object.freeze([...this.removedScopes])}canAbandonWrongAccount(){return!this.closing&&!this.options.signal.aborted&&this.pending===null&&this.flow?.canAbandonWrongAccount()===!0&&this.installation===null&&this.host===null&&this.slots.size===0&&!this.attested&&!this.acknowledged}scopeRecoveryContext(){if(!this.flow||!this.installation||uo.replacementPending(this.flow))return null;let e=this.flow.view();return e.state!=="paired"?null:Object.freeze({accountId:this.installation.scope.account,accountLabel:e.accountEmail??(e.accountLogin?`@${e.accountLogin}`:null),references:this.flow.collectionRecoveries()})}scopedInstallationPaired(e){if(this.pending||!this.flow||uo.replacementPending(this.flow))return!1;let t=this.flow.view();return t.state==="paired"&&t.accountId===e}prepareScopedRecovery(e,t){return this.check(),this.pending?this.pending.catch(()=>{}).then(()=>this.prepareScopedRecovery(e,t)):this.operation(async()=>{if(!this.flow||!this.installation||this.consentPending||this.flow.view().state!=="paired"||uo.replacementPending(this.flow))throw ft("binding");if(t!==void 0){let c=await uo.replaceRetained(this.flow,this.installation,e,t);if(this.check(),c!==null)return Object.freeze({accountId:this.installation.scope.account,reference:c})}if(!this.flow.view().collectionIds.includes(e))throw ft("binding");let i=this.flow.collectionRecoveries(),o=this.slots.get(e);if(t===void 0&&!Object.hasOwn(i,e)&&!this.scopeWasRemoved(e))throw ft("binding");o&&(await this.closeSlot(o),this.check(),this.deleteSlot(o)),await this.flow.retireCollectionScope(this.installation,e,t??null),this.check();let s=this.flow.confirmedSelection(),r=this.options;if(!await S1({cpOrigin:r.cpOrigin,appId:r.appId,accountId:s.accountId,connectorId:s.connectorId,installationId:s.installationId,deviceId:s.deviceId,collectionIds:[e],databases:[]},e))throw ft("recovery_required");this.check();let a=await this.flow.freshCollectionInstallation(this.installation,e);return this.check(),Object.freeze({accountId:s.accountId,reference:a})},!0)}forget(e){return this.operation(async()=>{let t=this.slots.get(e);return t&&(await this.closeSlot(t),this.check(),this.deleteSlot(t)),this.forgotten.add(e),this.publish({collections:Object.freeze(this.base.collections.filter(i=>i.collectionId!==e))}),this.getSnapshot()})}deleteCollection(e,t){let i=null;return this.operation(async()=>{let o=this.base.collections.find(s=>s.collectionId===e);if(!this.flow||!this.installation||!o)i=new ir("collection_delete_not_found");else if(o.role!=="owner")i=new ir("collection_delete_not_owner");else{try{await this.flow.deleteApprovedCollection(this.installation,e,t)}catch(s){i=N1(s)}this.check()}return this.getSnapshot()}).then(o=>{if(i)throw i;return o})}signOut(){this.check();let e=this.pending!==null&&this.pending===this.polling?this.pending:null;return Promise.resolve(e?.catch(()=>{})).then(()=>this.operation(async()=>{let t=this.flow,i=null,o=null,s=!1;try{i=t?.view()??null}catch{i=null}try{o=t?.confirmedSelection().connectorId??null}catch{o=null}try{s=t?.hasWebPushChannel()===!0}catch{s=!1}let r=[...new Set([...i?.collectionIds??[],...this.base.collections.map(p=>p.collectionId)])];this.closeApprovalWindow(),this.fileAccess=null,this.consentPending=!1;try{await this.closeSlots()}catch(p){throw this.failSignOut(),p}this.check();let a="not_paired";if(t&&i?.state==="paired"){try{a=await t.signOutInstallation()}catch{a="incomplete"}this.check()}this.flow=null,this.installation=null;try{await t?.close()}catch{}this.flowLifetime.abort(),this.flowLifetime=new AbortController,await this.installationLease?.release(),this.installationLease=null,this.attested=!1,this.acknowledged=!1,this.freshApproval=!1,this.authorizationStartedAt=null,this.receiptRead=null,this.foregroundRead=null,this.forgotten.clear(),this.removedScopes.clear();let c=this.options,l=await P1({cpOrigin:c.cpOrigin,appId:c.appId,...c.owner===void 0?{}:{owner:c.owner},...c.storageNamespace===void 0?{}:{storageNamespace:c.storageNamespace},accountId:i?.accountId??null,connectorId:o,installationId:i?.installationId??null,deviceId:i?.deviceId??null,collectionIds:r,databases:c.localDatabases??[],...c.recoveryFor?{isolated:!0}:{}});if(this.check(),!l.ledger)throw this.failSignOut(),A("unavailable","This device couldn't remove its sign-in data.","sign_out_failed");return this.emit(Object.freeze({status:"signed_out",signIn:null,collections:Object.freeze([]),selectedCollectionId:null,problem:null,timing:null,signOutResult:Object.freeze({server:a,local:l.complete?"erased":"incomplete",webPush:s})})),this.getSnapshot()},!0))}failSignOut(){if(this.closing||this.options.signal.aborted)return;let e=null;try{e=this.flow?.view()??null}catch{e=null}let{problemDetail:t,...i}=this.base;this.focus=null,this.emit(Object.freeze({...i,status:"blocked",signIn:e,selectedCollectionId:null,problem:"sign_out_failed"}))}emit(e){if(this.check(),this.base=e,e.status==="signed_out"){for(let t of[...this.slots.values()])this.deleteSlot(t);this.focus=null}this.changed()}close(){if(this.closing)return this.closing;let e=this.pending;return this.foregroundRead=null,this.stopPolling(),this.options.signal.removeEventListener("abort",this.onAbort),this.closing=Promise.resolve().then(async()=>{await e?.catch(()=>{}),await this.closeSlots(),this.focus=null,await this.flow?.close(),this.flowLifetime.abort(),this.flow=null,this.installation=null,await this.installationLease?.release(),this.installationLease=null,this.base=Object.freeze({status:"closed",signIn:null,collections:Object.freeze([]),selectedCollectionId:null,problem:null,timing:this.base.timing}),this.snapshotValue=this.base;for(let t of[...this.listeners])try{t()}catch{}this.listeners.clear()}),this.lifetime.abort(),this.closing}};gu();wu();return Aq(R4);})();
|
|
130
|
+
`);return{[ud.version]:String(Fv),[ud.timestamp]:String(o),[ud.nonce]:s,[ud.signature]:bn(await BA(n,new TextEncoder().encode(r)))}}async function zA(n,e){let t=await crypto.subtle.generateKey({name:e,namedCurve:"P-256"},!1,n);return{privateKey:t.privateKey,publicKey:bn(new Uint8Array(await crypto.subtle.exportKey("raw",t.publicKey)))}}async function d8(){let n;try{n=await crypto.subtle.generateKey({name:"X25519"},!1,["deriveBits"])}catch{throw A("unavailable","this browser cannot keep a non-extractable X25519 key","browser_unsupported")}if(n.privateKey.extractable)throw A("unavailable","the Noise key must be non-extractable","browser_unsupported");return{privateKey:n.privateKey,publicKey:new Uint8Array(await crypto.subtle.exportKey("raw",n.publicKey))}}function u8(n){return{publicKey:n.noisePublicKey.slice(),dh:async e=>{let t=await crypto.subtle.importKey("raw",e,{name:"X25519"},!1,[]);return new Uint8Array(await crypto.subtle.deriveBits({name:"X25519",public:t},n.noisePrivateKey,256))}}}function f8(n,e){let t=new AbortController,i=()=>t.abort(),o=setTimeout(i,e);return o.unref?.(),n?.addEventListener("abort",i,{once:!0}),n?.aborted&&t.abort(),{signal:t.signal,done:()=>{clearTimeout(o),n?.removeEventListener("abort",i)}}}async function h8(n,e){let t=globalThis.navigator?.locks;if(t)return t.request(n,{mode:"exclusive"},e);let i=$y.get(n)??Promise.resolve(),o,s=new Promise(r=>{o=r});$y.set(n,s),await i;try{return await e()}finally{o(),$y.get(n)===s&&$y.delete(n)}}var i8,uE,fs,r8,lE,s8,bn,zy,cE,pE,dE,By,ma,$A,zr,$y,VA,hE=C(()=>{"use strict";fd();zd();ym();Jt();rs();Ll();oh();hm();VR();_m();ve();No();re();un();MA();da();uc();gp();nu();xp();ZO();nE();oE();Wb();aE();n_();i8=new Set(["owner","editor","viewer"]),uE="mdbase.app-grant.v1",fs=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,r8=15e3;lE=BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),s8=new TextEncoder().encode("mdbase-next client noise key v1\0");bn=n=>{let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")},zy=n=>crypto.getRandomValues(new Uint8Array(n)),cE=n=>{let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,n),e},pE=(...n)=>{let e=new Uint8Array(n.reduce((i,o)=>i+o.length,0)),t=0;for(let i of n)e.set(i,t),t+=i.length;return e};dE=async n=>bn(new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n))));By=(n,e)=>n.length===e.length&&n.every((t,i)=>t===e[i]),ma=(n,e)=>!!e&&n.collection===e.collection&&n.owner===e.owner&&By(n.noisePublicKey,e.noisePublicKey),$A=(n,e)=>ma(n,e)&&By(n.refresh,e.refresh),zr=()=>A("cancelled","the stored grant changed during this operation"),$y=new Map;VA=class{constructor(e){this.options=e;this.declaration=co(e.declaration),this.cpOrigin=Ci({environment:this.declaration.environment,appOrigin:this.declaration.origin,release:BR()}).cpOrigin;try{this.redirect=new URL(e.redirectUri)}catch{throw A("invalid_request","redirectUri must be an absolute URL","redirect_uri")}if(!(this.declaration.origin.startsWith("capacitor://")?jl(e.redirectUri,this.declaration.origin,this.declaration.manifest):this.redirect.protocol===new URL(this.declaration.origin).protocol&&this.redirect.origin===this.declaration.origin&&!this.redirect.hash))throw A("invalid_request","redirectUri must be a valid callback for this app","redirect_uri");this.fetcher=e.fetch??globalThis.fetch.bind(globalThis),this.callbacks=e.callbacks??l8(),this.storeValue=e.store??null}options;declaration;cpOrigin;redirect;fetcher;callbacks;storeValue;registration=null;tokens=new Map;routeProbe;refreshing=new Map;forgotten=new Set;epoch=0;register(){let e=this.registration??=vm({declaration:this.options.declaration,signal:new AbortController().signal,isCurrent:()=>!0,fetch:this.fetcher});return e.catch(()=>{this.registration===e&&(this.registration=null)}),e}ownerValue=null;owner(){return this.ownerValue??=Dx(is(this.declaration).manifest.id,rh(this.declaration))}async store(){if(this.storeValue)return this.storeValue;let e=this.owner();return this.storeValue=sE(this.cpOrigin,(await this.register()).id,{owner:e})}async identity(){let e=await this.store(),t=await e.getIdentity();if(t)return t;let i=await zA(["sign"],"ECDSA");return e.putIdentityIfAbsent({version:1,privateKey:i.privateKey,publicKey:i.publicKey})}async request(e,t,i){let o=f8(i,r8);try{let s;try{s=await this.fetcher(`${this.cpOrigin}${e}`,{...t,redirect:"error",credentials:"omit",signal:o.signal})}catch{throw i?.aborted?A("cancelled","request cancelled"):A("unavailable","cannot reach the control plane","control_unreachable")}let r=null;try{let a=await s.json();a&&typeof a=="object"&&!Array.isArray(a)&&(r=a)}catch{r=null}return{status:s.status,body:r}}finally{o.done()}}async authorize(e){e=Object.freeze({...e});let t=await this.prepareAuthorization(e).catch(i=>{throw e.popup.close(),i});try{e.popup.navigate(t.authorizationUri);let{collectionId:i}=await t.finish(e);return{collectionId:i}}finally{t.cancel();try{e.popup.close()}catch{}}}async prepareAuthorization(e={}){if(e=Object.freeze({...e}),e.collection!==void 0&&!fs.test(e.collection))throw A("invalid_request","collection must be a UUID");if(e.expectedAccountId!==void 0&&(!fs.test(e.expectedAccountId)||!e.authorizationNonce))throw A("invalid_request","original account and challenge required","authorization_binding");if(e.authorizationNonce!==void 0&&(!/^[A-Za-z0-9_-]{43}$/.test(e.authorizationNonce)||!o8(e.authorizationNonce)))throw A("invalid_request","invalid original challenge","authorization_binding");let t=new AbortController,i=e.signal?AbortSignal.any([e.signal,t.signal]):t.signal,o=this.epoch,s=()=>{if(i.aborted)throw A("cancelled","authorization fenced","authorization_cancelled");if(o!==this.epoch)throw zr()};s();let r=await this.register(),a=is(this.declaration),c=await this.identity(),l=await zA(["deriveBits"],"ECDH"),p=await zA(["sign"],"ECDSA"),d=await d8(),u=bn(zy(32)),f=bn(new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(u)))),h=bn(zy(24)),m=crypto.randomUUID(),w=new Date,b={protocol_version:lo,authorization_id:m,application_id:r.id,application_declaration_id:String(a.manifest.id),application_manifest_digest:r.manifestDigest,application_installation_id:await EC(c.publicKey),installation_signing_public_key:c.publicKey,grant_agreement_public_key:l.publicKey,grant_signing_public_key:p.publicKey,flow:"authorization_code",authorization_nonce:e.authorizationNonce??bn(zy(32)),issued_at:w.toISOString(),expires_at:new Date(w.getTime()+10*6e4).toISOString(),redirect_uri:this.redirect.href,state:h,code_challenge:f,contracts:a.contracts,requested_operations:[...a.operations],...a.files?{requested_files:a.files}:{},...e.collection?{collection_id:e.collection}:{}},g={binding:b,signature:bn(await BA(c.privateKey,qC(b)))},y=pE(s8,cE(16),N(m),cE(32),d.publicKey),v={public_key:bn(d.publicKey),signature:bn(await BA(p.privateKey,y))};s();let _=await this.request("/oauth/authorization_request",{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:r.id,redirect_uri:this.redirect.href,code_challenge:f,code_challenge_method:"S256",state:h,operations:a.operations.join(","),...e.collection?{collection_id:e.collection}:{},application_authorization:JSON.stringify(g),client_noise_key:JSON.stringify(v)})},i);s();let k=_.body?.authorization_uri;if(_.status!==200||_.body?.authorization_id!==m||typeof k!="string"||!k.startsWith(`${this.cpOrigin}/oauth/authorize?`))throw A("unavailable",`authorization could not be started (${_.status})`,"authorization_start");let S=null,x=this.awaitCallback(h,{navigate(){},close(){},get closed(){return S?.closed===!0}},{popup:{navigate(){},close(){}},signal:i,timeoutMs:e.timeoutMs});x.catch(()=>{});let P=!1;return Object.freeze({applicationId:r.id,manifestDigest:r.manifestDigest,authorizationId:m,authorizationUri:k,cancel:()=>t.abort(),finish:async I=>{if(I=Object.freeze({...I}),P)throw A("invalid_request","original authorization already consumed","authorization_binding");P=!0,S=I.popup;let O=()=>t.abort();I.signal?.addEventListener("abort",O,{once:!0}),I.signal?.aborted&&t.abort();try{s();let R=I.collection??e.collection;if(R!==void 0&&!fs.test(R))throw A("invalid_request","invalid approved collection","authorization_binding");if(e.collection&&R!==e.collection)throw A("forbidden","a different collection was approved","collection_mismatch");if(e.expectedAccountId&&!R)throw A("invalid_request","original Private choice required","authorization_binding");let q=await x;s();let j=await this.request("/oauth/token",{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:q,client_id:r.id,redirect_uri:this.redirect.href,code_verifier:u})},i);s();let B=e.expectedAccountId?Cm(j.body,{accountId:e.expectedAccountId,authorizationRequestId:m,applicationId:r.id,declarationId:b.application_declaration_id,manifestDigest:r.manifestDigest,applicationInstallationId:b.application_installation_id,applicationOrigin:this.declaration.origin,collectionId:R,grantSigningPublicKey:p.publicKey,clientNoisePublicKey:bn(d.publicKey)}):void 0,D=await this.saveTokens(j,{noise:d,signing:p.privateKey,collection:R,check:s});return s(),{collectionId:D,...B?{nativeCompletion:B}:{}}}finally{I.signal?.removeEventListener("abort",O),t.abort()}}})}awaitCallback(e,t,i){let o=Math.min(Math.max(i.timeoutMs??6e5,1e3),18e5);return new Promise((s,r)=>{let a=null,c=f=>{p(),clearTimeout(d),clearInterval(u),i.signal?.removeEventListener("abort",l),f()},l=()=>c(()=>r(A("cancelled","authorization cancelled","authorization_cancelled"))),p=this.callbacks.subscribe(f=>{let h;try{h=new URL(f)}catch{return}if(dt(h)!==dt(this.redirect)||h.username||h.password||h.hash||h.pathname!==this.redirect.pathname||h.searchParams.get("state")!==e)return;if(h.searchParams.get("error"))return c(()=>r(A("forbidden","access was not approved","authorization_denied")));let w=h.searchParams.get("code");if(!w)return c(()=>r(A("unavailable","the authorization callback has no code","authorization_callback")));c(()=>s(w))}),d=setTimeout(()=>c(()=>r(A("cancelled","authorization timed out","authorization_timed_out"))),o),u=setInterval(()=>{let f=!1;try{f=t.closed===!0}catch{f=!1}if(!f){a=null;return}a??=Date.now(),Date.now()-a>=3e3&&c(()=>r(A("cancelled","the authorization window was closed","authorization_cancelled")))},500);i.signal?.addEventListener("abort",l,{once:!0}),i.signal?.aborted&&l()})}async saveTokens(e,t){let i=e.body;if(e.status!==200||!i)throw e.status===400&&i&&(i.error==="invalid_grant"||de(i.error,"code")==="invalid_grant")?A("unauthenticated","the grant is no longer valid","grant_invalid"):e.status===400?Fn("sync_required"):A("unavailable",`token request failed (${e.status})`,"token_error");let o=i.access_token,s=i.refresh_token,r=i.collection_id,a=i.expires_in,c=i.refresh_expires_in;if(typeof o!="string"||typeof s!="string"||typeof r!="string"||!fs.test(r)||typeof a!="number"||!(a>0)||typeof c!="number"||!(c>0))throw A("unavailable","invalid token response","token_response");let l=r.toLowerCase();if(t.collection&&t.collection.toLowerCase()!==l)throw A("forbidden","a different collection was approved","collection_mismatch");if(t.previous&&t.previous.collection!==l)throw A("unavailable","the token names another collection","token_response");let p=t.previous?.refreshKey??await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),d=zy(12),u=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:d,additionalData:this.aad(l)},p,new TextEncoder().encode(s))),f=t.noise??{privateKey:t.previous.noisePrivateKey,publicKey:t.previous.noisePublicKey},h=t.signing??t.previous?.signingPrivateKey,m={version:1,collection:l,noisePrivateKey:f.privateKey,noisePublicKey:f.publicKey,refreshKey:p,refresh:pE(d,u),refreshExpiresAt:Date.now()+c*1e3,...h?{signingPrivateKey:h}:{},...t.previous?.owner?{owner:t.previous.owner}:{}},w=this.epoch;return await this.withLock(l,"commit",async()=>{let b=await this.store();if(w!==this.epoch||t.previous&&!$A(t.previous,await b.getGrant(l)))throw zr();t.check?.(),await b.putGrant(m);let g=await b.getGrant(l);if(!g||!By(m.noisePublicKey,g.noisePublicKey)||!By(m.refresh,g.refresh))throw zr();t.check?.(),this.tokens.set(l,{access:o,expiresAt:Date.now()+a*1e3,collection:l,owner:g.owner,noisePublicKey:g.noisePublicKey.slice()}),this.forgotten.delete(l)}),l}aad(e){return new TextEncoder().encode(`mdbase.app-grant.v2\0${this.cpOrigin}\0${this.owner()}\0${e}`)}async accessToken(e,t=!1){let i=await this.heldGrant(e),o=this.tokens.get(e);if(!t&&o&&ma(i,o)&&o.expiresAt-Date.now()>6e4)return o.access;let s=this.refreshing.get(e);if(s&&$A(i,s.grant)){let c=await s.work;return await this.assertCurrent(i),c}let r=this.withLock(e,"refresh",async()=>{let c=await this.assertCurrent(i);return this.refresh(e,c)}),a={grant:i,work:r};this.refreshing.set(e,a);try{let c=await r;return await this.assertCurrent(i),c}finally{this.refreshing.get(e)===a&&this.refreshing.delete(e)}}withLock(e,t,i){return h8(`mdbase.app-grant.${t}:${JSON.stringify([this.cpOrigin,this.owner(),e])}`,i)}async heldGrant(e){let t=await(await this.store()).getGrant(e);if(!t)throw Fn("sync_required");return{...t,noisePublicKey:t.noisePublicKey.slice(),refresh:t.refresh.slice()}}async assertCurrent(e){let t=await(await this.store()).getGrant(e.collection);if(!ma(e,t))throw zr();return t}async refresh(e,t){if(t.refreshExpiresAt<=Date.now())throw Fn("sync_required");let i;try{let c=await crypto.subtle.decrypt({name:"AES-GCM",iv:t.refresh.slice(0,12),additionalData:this.aad(e)},t.refreshKey,t.refresh.slice(12));i=new TextDecoder().decode(c)}catch{throw A("unauthenticated","the stored grant could not be read","grant_storage")}let o=await this.register(),s=new URLSearchParams({grant_type:"refresh_token",refresh_token:i,client_id:o.id}),r=t.signingPrivateKey?await p8(t.signingPrivateKey,"/oauth/token",s.toString(),i):{},a=await this.request("/oauth/token",{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",...r},body:s});try{await this.saveTokens(a,{previous:t})}catch(c){throw J(c,"unauthenticated")&&c.reason==="grant_invalid"&&await this.withLock(e,"commit",async()=>{let l=await this.store();if(!$A(t,await l.getGrant(e)))throw zr();await l.deleteGrant(e),this.forgotten.add(e);let p=this.tokens.get(e);p&&ma(t,p)&&this.tokens.delete(e)}),c}return a.body.access_token}async route(e,t){for(let i=0;;i++){let o=await this.accessToken(e,i>0),s=await this.request(`/v1/next/collections/${encodeURIComponent(e)}/route`,{headers:{authorization:`Bearer ${o}`}},t);if(s.status===401&&i===0)continue;if(s.status===401)throw A("unauthenticated","the control plane refused the access token");if(s.status===409)throw A("unauthenticated","this app's key is not registered with its grant","client_key_required");if(s.status!==200||!s.body)throw A("unavailable",`control plane answered ${s.status}`,"control_error");let r=s.body;if(typeof r.collection!="string"||r.collection.toLowerCase()!==e||!Array.isArray(r.targets))throw A("unauthenticated","the route does not match this collection's grant","route_mismatch");let c=wi(r.availability)??(iu(r,null).length?{state:"available"}:{state:"unavailable",reason:r.reason==="no_device_registered"?"no_device_registered":"device_offline"});return{token:o,route:r,availability:c}}}async verifiedStoredNativeGrant(e){let t=await this.register(),i=await(await this.store()).getGrant(e.collection_id);return!!i&&e.application_id===t.id&&e.application_origin===this.declaration.origin&&i.owner===this.owner()&&bn(i.noisePublicKey)===e.client_noise_public_key}async collections(e={}){let t=await(await this.store()).listGrants(),i=[];for(let r of t)(e.bindings===void 0||e.bindings.some(a=>a.collection_id===r.collection&&a.application_origin===this.declaration.origin&&bn(r.noisePublicKey)===a.client_noise_public_key))&&i.push(r);let o=new Set(i.map(r=>r.collection)),s=new Set;e:for(let r of i){let a;for(let l=0;;l++){let p;try{p=await this.accessToken(r.collection)}catch(d){if(J(d,"unauthenticated")&&d.reason==="grant_invalid"){s.add(r.collection);continue e}if(J(d,"forbidden")&&d.reason==="sync_required")continue e;throw d}if(await this.assertCurrent(r),a=await this.request("/v1/next/apps/collections",{headers:{authorization:`Bearer ${p}`}},e.signal),await this.assertCurrent(r),a.status===403){s.add(r.collection);continue e}if(a.status!==401)break;if(await this.withLock(r.collection,"commit",async()=>{await this.assertCurrent(r);let d=this.tokens.get(r.collection);if(d?.access!==p||!ma(r,d))throw zr();this.tokens.delete(r.collection)}),l>0)throw A("unauthenticated","the control plane refused the collection listing token")}if(a.status!==200||!Array.isArray(a.body?.collections))throw A("unavailable",`control plane answered ${a.status}`,"control_error");let c=[];for(let l of a.body.collections){let p=typeof l.collection=="string"?l.collection.toLowerCase():"";if(!fs.test(p)||s.has(p)||c.some(b=>b.collectionId===p))continue;let d=wi(l.availability);if(l.state!=="synced_e2e"&&!d)continue;let u=o.has(p)?d??{state:"opening"}:{state:"unavailable",reason:"sync_required"},f=l.authorization_grant??l.grant,h=i.find(b=>b.collection===p),m=l.reviewed_file_actions,w=h&&e.bindings?.some(b=>b.collection_id===p&&b.grant_id===f&&b.application_origin===this.declaration.origin&&b.client_noise_public_key===bn(h.noisePublicKey));c.push(Object.freeze({...w&&Array.isArray(m)?{fileActions:Object.freeze(Y_.filter(b=>m.includes(b)))}:{},collectionId:p,displayName:typeof l.name=="string"?l.name:"Collection",operations:Object.freeze(Array.isArray(l.operations)?l.operations.filter(b=>typeof b=="string"):[]),availability:Object.freeze(u),role:i8.has(l.role)?l.role:null}))}return c}return[]}async availability(e,t={}){let i=e.toLowerCase(),o=this.routeProbe={};try{let{token:s,route:r,availability:a}=await this.route(i,t.signal),c=this.tokens.get(i);return a.state==="available"&&!t.signal?.aborted&&c?.access===s&&(o.ready={credentials:c,route:r,until:performance.now()+3e3,signal:t.signal}),a}catch(s){let r=J(s)?de(s.details,"availability"):void 0;if(typeof r=="string")return wi({state:"unavailable",reason:r});throw s}}async waitForAvailable(e,t={}){let i=Date.now()+Math.min(Math.max(t.timeoutMs??6e4,0),6e5),o=Math.max(t.intervalMs??3e3,1e3),s=null;for(;;){if(t.signal?.aborted)throw A("cancelled","wait cancelled");let r=await this.availability(e,t.signal?{signal:t.signal}:{});if((!s||r.state!==s.state||r.state==="unavailable"&&s.state==="unavailable"&&r.reason!==s.reason)&&t.onAvailability?.(r),s=r,r.state==="available"||r.state==="unavailable"&&(r.reason==="sync_required"||r.reason==="access_removed"))return r;let a=i-Date.now();if(a<=0)return r;await new Promise(c=>{let l=setTimeout(p,Math.min(o,a));function p(){clearTimeout(l),t.signal?.removeEventListener("abort",p),c()}t.signal?.addEventListener("abort",p,{once:!0})})}}connector(e){let t=e.toLowerCase();if(!fs.test(t))throw A("invalid_request","collection must be a UUID");let i=null,o=this.options.webSocket,s;return hf({description:`app-grant:${t}`,open:async(r,a)=>{let c=s===void 0?this.routeProbe?.ready:void 0;this.routeProbe=void 0;let l=await(s??=this.heldGrant(t));if(await this.assertCurrent(l),a?.aborted)throw A("cancelled","connect aborted");let{token:p,route:d,availability:u}=c&&!c.signal?.aborted&&performance.now()<c.until&&c.credentials===this.tokens.get(t)&&ma(l,c.credentials)&&c.credentials.expiresAt>Date.now()?{token:c.credentials.access,route:c.route,availability:{state:"available"}}:await this.route(t,a);if(await this.assertCurrent(l),a?.aborted)throw A("cancelled","connect aborted");if(u.state==="unavailable")throw Fn(u.reason);if(!fs.test(d.grant))throw A("unauthenticated","the route names no grant","route_mismatch");let f=qA(d,i);if(!f.length)throw Fn("device_offline");let h;for(let m of f){await this.assertCurrent(l);let w=new Uint8Array(32);for(let y=0;y<32;y++)w[y]=parseInt(m.noise_pk.slice(2*y,2*y+2),16);let b=Nr({description:`app-grant:${t}`,staticKey:u8(l),target:async()=>({prologue:Ur(N(m.relay_collection),N(d.grant),N(m.device)),remoteStatic:w,device:m.device,openCarrier:async y=>{await this.assertCurrent(l);let v=await fc(m.url,{accessToken:p,collection:m.relay_collection,grant:d.grant,device:m.device,devicePublicKey:w},o,y);try{return await this.assertCurrent(l),v}catch(_){throw v.close(),_}}})}),g;try{g=await b.open(r,a)}catch(y){if(!TA(y,a))throw y;i===m.device&&(i=null),h??=y;continue}try{await this.assertCurrent(l)}catch(y){throw g.port.close(),y}return $S(g.port,l),i=g.device??null,g}throw h},get target(){return i}})}people(e,t){let i=e.toLowerCase();if(!fs.test(i))throw A("invalid_request","collection must be a UUID");return new vr(t,XO(i,{cpOrigin:this.cpOrigin,fetch:this.fetcher,accessToken:(o,s)=>this.accessToken(o,s),holds:o=>!this.forgotten.has(o)}))}setup(e){let t=is(this.declaration),i,o=async()=>{let r=e.currentSession(),a=r&&VS(r);if(!a||a.collection!==e.collection||(i??=a,!ma(i,a)))throw zr();return i};return tE({assertCurrent:async()=>this.assertCurrent(await o()),journal:rE({store:()=>this.store(),grant:o,assertCurrent:r=>this.assertCurrent(r),aad:this.aad(e.collection)}),client:e,manifest:t.manifest,operations:t.operations})}async forget(e,t={}){let i=e.toLowerCase(),o=t.expectedNoisePublicKey;await this.withLock(i,"commit",async()=>{let s=await this.store(),r=await s.getGrant(i);if(o!==void 0&&r&&bn(r.noisePublicKey)!==o)throw zr();await s.deleteGrant(i),this.forgotten.add(i),this.tokens.delete(i),this.routeProbe=void 0})}async forgetAllGrants(){this.routeProbe=void 0,this.epoch++;let e=await this.store(),t=[];try{t=(await e.listGrants()).map(o=>o.collection).sort()}catch{}for(let o of t)this.forgotten.add(o);let i=async(o,s)=>o.length?this.withLock(o[0],"commit",()=>i(o.slice(1),s)):s();await i(t,async()=>{if(this.tokens.clear(),typeof e.clearGrants=="function"){await e.clearGrants();return}for(let o of await e.listGrants())await e.deleteGrant(o.collection),this.forgotten.add(o.collection);if((await e.listGrants()).length)throw A("unavailable","grant storage could not be cleared","grant_storage")}),this.tokens.clear()}}});function Ky(n){return typeof n=="string"&&_8.includes(n)}var _8,WA=C(()=>{"use strict";_8=["joining","opening_store","connecting_log","syncing","loading_snapshot","replaying","waiting_for_key","verifying_read","checking_setup"]});function yE(n){let e=0,t=0;try{let i=n?.records.status.pending;e=typeof i=="number"&&i>0?i:0}catch{e=0}try{t=n?.records.ledger?.getSnapshot().pending.length??0}catch{t=0}return Math.max(e,t)}function gE(n=0){let e=n===1?"1 change hasn't":n>1?`${n} changes haven't`:"Some changes haven't";return A("conflict",`${e} reached mdbase yet. Wait for them to finish, or sign out anyway and lose them on this device.`,{reason:"sign_out_pending_writes",details:n})}var bE=C(()=>{"use strict";re()});function ya(n,e){return new Promise((t,i)=>{if(e.aborted){i(e.reason);return}let o=()=>{clearTimeout(s),i(e.reason)},s=setTimeout(()=>{e.removeEventListener("abort",o),t()},n);e.addEventListener("abort",o,{once:!0})})}var Wy=C(()=>{"use strict"});function U8(n,e){let t=new URL(n);if(t.protocol==="https:")return`wss://${t.host}`;if(e&&Qe(n))return`ws://${t.host}`;throw new Error("app log push: origin")}function vE(n){if(typeof n=="bigint"?n<0n:typeof n!="number"||!Number.isSafeInteger(n)||n<0)throw new Error("app log push: id");return BigInt(n).toString()}function D8(n){let e=n.get(3);if(!(e instanceof Map))return null;let t=e.get(0),i=e.get(1);return{code:typeof t=="string"?t:"unavailable",reason:typeof i=="string"?i:""}}var A8,k8,S8,P8,x8,I8,C8,R8,O8,E8,q8,T8,M8,L8,j8,N8,wE,Hy,_E=C(()=>{"use strict";St();Je();ve();A8=4401,k8=4403,S8=4410,P8=3e4,x8=1e4,I8=6e4,C8=6e4,R8=15e3,O8=4,E8=64*1024,q8=1024*1024,T8=new Set(["stream_join","stream_leave","stream_send"]),M8=1e4,L8=64,j8=32*1024;N8=n=>[...n].map(e=>e.toString(16).padStart(2,"0")).join(""),wE=(n,e,t)=>fe(new Map([[0,0],[1,n],[2,e],[3,t]]));Hy=class{constructor(e,t,i={}){this.source=e;this.events=t;this.base=U8(e.origin,i.allowLoopbackHttp===!0),this.collectionBytes=N(e.collection);let o=i.WebSocket??globalThis.WebSocket;if(typeof o!="function")throw new Error("app log push: no WebSocket");this.Ws=o,this.random=i.random??Math.random,this.now=i.now??Date.now}source;events;base;collectionBytes;Ws;random;now;socket=null;connecting=!1;closed=!1;finished=null;unsupported=!1;paused=!1;isLive=!1;attempts=0;liveSince=0;retry=null;ping=null;pongDue=null;opening=null;unsigned=0;life=new AbortController;token=null;phase="hello";calls=new Map;get live(){return this.isLive}get available(){return!this.unsupported&&this.finished===null&&!this.closed}get suspended(){return this.paused}start(){this.connect()}nudge(){this.unsupported=!1,this.unsigned=0,!(this.paused||this.socket||this.connecting||!this.available)&&(this.attempts=0,this.clearRetry(),this.connect())}suspend(){this.paused||!this.available||(this.paused=!0,this.clearRetry(),this.drop(1e3,"hidden"))}resume(){if(!this.paused){this.nudge();return}this.paused=!1,this.nudge()}close(){this.closed||(this.closed=!0,this.life.abort(),this.clearRetry(),this.drop(1e3,"closed"))}request(e,t){return new Promise((i,o)=>{let s=p=>o(new Error(`app log push: ${p}`)),r=this.socket;if(!r||!this.isLive){s("not live");return}if(!(e instanceof Uint8Array)||e.length>j8||this.calls.size>=L8){s("call");return}let a;try{let p=we(e);if(!(p instanceof Map))throw new Error;let d=p;if(d.get(0)!==0||!T8.has(d.get(2)))throw new Error;a=vE(d.get(1))}catch{s("call");return}if(this.calls.has(a)||t.signal.aborted){s("call");return}let c=()=>{clearTimeout(l.timer),t.signal.removeEventListener("abort",l.stop),this.calls.delete(a)},l={resolve:p=>{c(),i(p)},reject:p=>{c(),o(p)},timer:setTimeout(()=>l.reject(new Error("app log push: no reply")),M8),stop:()=>l.reject(new Error("app log push: aborted"))};t.signal.addEventListener("abort",l.stop,{once:!0}),this.calls.set(a,l);try{r.send(e)}catch{l.reject(new Error("app log push: send")),this.lost(r,1006)}})}clearRetry(){this.retry!==null&&clearTimeout(this.retry),this.retry=null}clearPing(){this.ping!==null&&clearInterval(this.ping),this.ping=null,this.pongDue!==null&&clearTimeout(this.pongDue),this.pongDue=null,this.opening!==null&&clearTimeout(this.opening),this.opening=null}setLive(e){if(this.isLive!==e){this.isLive=e,e&&(this.liveSince=this.now());try{this.events.live(e)}catch{}}}end(e){if(!(this.finished||this.closed)){this.finished=e,this.clearRetry(),this.drop(1e3,e);try{this.events.ended(e)}catch{}}}drop(e,t){this.clearPing();let i=this.socket;if(this.socket=null,i){i.onopen=i.onmessage=i.onclose=i.onerror=null;try{i.close(e,t)}catch{}}for(let o of[...this.calls.values()])o.reject(new Error("app log push: lost"));this.setLive(!1)}schedule(e=!1){if(this.paused||!this.available||this.retry!==null)return;let t=e?0:Math.floor(this.random()*Math.min(C8,1e3*2**Math.min(this.attempts,6)));this.attempts++,this.retry=setTimeout(()=>{this.retry=null,this.connect()},t)}async connect(){if(this.paused||this.socket||this.connecting||!this.available)return;if(!this.source.isCurrent()){this.close();return}this.connecting=!0;let e,t,i;try{let r=this.life.signal;if(e=await this.source.accessToken({signal:r}),t=await this.source.nonce({signal:r}),this.paused||!this.available||!this.source.isCurrent())return;if(i=this.source.signHello(t,e),!i){++this.unsigned>=O8?this.unsupported=!0:this.schedule();return}this.unsigned=0}catch{this.connecting=!1,this.schedule();return}finally{this.connecting=!1}this.token=e;let o;try{o=new this.Ws(`${this.base}/v1/ws?c=${this.source.collection}&n=${N8(t)}`)}catch{this.schedule();return}o.binaryType="arraybuffer",this.socket=o,this.phase="hello";let s=wE(1,"hello",new Map([[0,[1,0]],[1,e],[2,N(this.source.deviceId)],[3,i]]));i.fill(0),t.fill(0),o.onopen=()=>{try{o.send(s)}catch{this.lost(o,1006)}},o.onmessage=r=>this.message(o,r.data),o.onclose=r=>this.lost(o,r.code),o.onerror=()=>{},this.opening=setTimeout(()=>{this.opening=null,this.lost(o,1006)},R8)}message(e,t){if(e!==this.socket)return;if(typeof t=="string"){t==="pong"&&this.pongDue!==null&&(clearTimeout(this.pongDue),this.pongDue=null);return}if(!(t instanceof ArrayBuffer)||t.byteLength>q8){this.lost(e,1009);return}let i=new Uint8Array(t),o;try{let a=we(i);if(!(a instanceof Map))throw new Error;o=a}catch{this.lost(e,1007);return}if(o.get(0)===2){if(!this.isLive)return;if(this.deliver(i),o.get(1)==="closed"){let a=o.get(2),c=a instanceof Map?a.get(1):null;this.end(c==="gone"?"gone":c==="revoked"?"revoked":"forbidden")}return}if(o.get(0)!==1)return;let s=o.get(1),r=D8(o);if(this.phase==="live"){let a;try{a=vE(s)}catch{return}this.calls.get(a)?.resolve(i.slice());return}if(this.phase==="hello"){if(s!==1)return;if(r){this.refused(e,r);return}this.phase="subscribe";try{e.send(wE(2,"subscribe",new Map([[0,this.collectionBytes],[1,0],[2,E8]])))}catch{this.lost(e,1006)}return}if(s===2){if(r){this.refused(e,r);return}let a=o.get(2);if(!(a instanceof Map)){this.lost(e,1007);return}let c=a.get(0),l=a.get(1);this.phase="live",this.startPing(e),this.setLive(!0),(typeof c=="number"||typeof c=="bigint")&&l instanceof Uint8Array&&l.length===32&&this.deliver(fe(new Map([[0,2],[1,"head"],[2,new Map([[0,this.collectionBytes],[1,c],[2,l]])]])))}}deliver(e){try{this.events.push(e)}catch{}}refused(e,t){if(t.code==="forbidden"&&t.reason==="credentials_revoked"){this.end("revoked");return}if(t.code==="forbidden"||t.code==="not_found"){this.end(t.code==="not_found"?"gone":"forbidden");return}if(t.code==="gone"){this.end("gone");return}t.code==="unauthenticated"&&this.token&&(this.source.invalidateToken?.(this.token),this.token=null),this.lost(e,1008)}startPing(e){this.clearPing(),this.ping=setInterval(()=>{if(!(e!==this.socket||this.pongDue!==null)){try{e.send("ping")}catch{this.lost(e,1006);return}this.pongDue=setTimeout(()=>{this.pongDue=null,this.lost(e,1006)},x8)}},P8)}lost(e,t){if(e!==this.socket)return;let i=this.isLive&&this.now()-this.liveSince>=I8;if(this.drop(1e3,"lost"),t===k8){this.end("forbidden");return}if(t===S8){this.end("gone");return}if(i&&(this.attempts=0),t===A8){this.token&&this.source.invalidateToken?.(this.token),this.token=null,this.attempts=0,this.schedule(!0);return}this.schedule()}}});function AE(n){if(!n||typeof n!="object"||Array.isArray(n))throw sr();return n}function kE(n){if(typeof n=="number"&&!Number.isSafeInteger(n))throw sr();let e=BigInt(n);if(e<0n||e>(1n<<64n)-1n)throw sr();return e}var sr,yc,HA=C(()=>{"use strict";St();ve();re();sr=()=>A("unavailable","people metadata is unavailable","people_response");yc=class{constructor(e,t={}){this.session=e;this.rawOrigin=e.cpOrigin;let i=new URL(this.rawOrigin);if(i.username||i.password||i.pathname!=="/"||i.search||i.hash||i.protocol!=="https:"&&!(t.allowLoopbackHttp===!0&&Qe(e.cpOrigin)))throw A("invalid_request","invalid people CP origin","people_binding");this.cpOrigin=i.origin,this.collection=e.collection,this.connector=e.connectorId,this.device=e.deviceId,this.ep=kE(e.endpoint);for(let o of[this.collection,this.connector,this.device])if(N(o).every(s=>s===0))throw A("invalid_request","nil people binding","people_binding");if(this.fetchImpl=t.fetch??globalThis.fetch,!this.isCurrent())throw A("unauthenticated","people scope is not current","people_fenced")}session;cpOrigin;rawOrigin;collection;connector;device;ep;fetchImpl;lifetime=new AbortController;isCurrent(){try{return!this.lifetime.signal.aborted&&this.session.isCurrent()===!0&&this.session.cpOrigin===this.rawOrigin&&this.session.collection===this.collection&&this.session.connectorId===this.connector&&this.session.deviceId===this.device&&kE(this.session.endpoint)===this.ep}catch{return!1}}check(e){if(e?.throwIfAborted(),!this.isCurrent())throw A("unauthenticated","people scope changed","people_fenced")}async request(e,t={}){if(e!=="identity"&&e!=="members")throw A("invalid_request","invalid people resource");this.check(t.signal);let i=new AbortController,o=()=>i.abort();t.signal?.addEventListener("abort",o,{once:!0}),this.lifetime.signal.addEventListener("abort",o,{once:!0});let s=setTimeout(o,15e3);s.unref?.();let r=new Uint8Array(1024*1024),a=0,c,l;try{let p=await this.session.connectorBearer({signal:i.signal});if(this.check(t.signal),i.signal.aborted)throw sr();if(typeof p!="string"||!/^(idev_|ct_)/.test(p)||p.length>16*1024||/[^\x21-\x7e]/.test(p))throw A("unauthenticated","invalid people credential","people_binding");let d=this.fetchImpl;if(c=await d(`${this.cpOrigin}/v1/authorities/${this.collection}/${e}?device_id=${this.device}`,{method:"GET",headers:{authorization:`Bearer ${p}`},signal:i.signal,redirect:"error",credentials:"omit",cache:"default",referrerPolicy:"no-referrer"}),this.check(t.signal),i.signal.aborted)throw sr();let u=c.headers.get("content-length");if(u!==null&&/^(0|[1-9][0-9]*)$/.test(u)&&Number(u)>r.length||!c.body)throw sr();for(l=c.body.getReader();;){let{done:h,value:m}=await l.read();try{if(this.check(t.signal),i.signal.aborted)throw sr();if(h)break;if(a+m.length>r.length)throw sr();r.set(m,a),a+=m.length}finally{m?.fill(0)}}let f=AE(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r.subarray(0,a))));if(this.check(t.signal),c.status===401)throw A("unauthenticated","people credential is no longer current","people_fenced");if(c.status===403){let h=AE(f.error);throw A("forbidden","people access was refused",e==="members"&&h.code==="people_permission_declined"?"people_permission_declined":"people_access")}if(c.status===404)throw A("upgrade_required","people metadata is unsupported","people_unsupported");if(!c.ok)throw sr();return f}catch(p){throw this.check(t.signal),p instanceof ne?p:sr()}finally{i.abort(),r.fill(0),(l?.cancel()??c?.body?.cancel())?.catch(()=>{}),l?.releaseLock(),clearTimeout(s),t.signal?.removeEventListener("abort",o),this.lifetime.signal.removeEventListener("abort",o)}}close(){this.lifetime.abort()}}});function Gy(n,e){if(typeof n!="string"||!e.test(n))throw ge("invalid_request","timer_input");return encodeURIComponent(n)}function hs(n,e){if(!n||typeof n!="object"||Array.isArray(n)||Object.keys(n).sort().join()!==e.split(",").sort().join())throw ge("invalid_request","timer_input");return n}function SE(n){let e=hs(n,"id,fire_at");if(Gy(e.id,GA),typeof e.fire_at!="string"||!/^\d{4}-\d{2}-\d{2}T/.test(e.fire_at)||!Number.isFinite(Date.parse(e.fire_at)))throw ge("invalid_request","timer_input");return{id:e.id,fire_at:e.fire_at}}function YA(n){if(typeof n!="string"||!n.length||n.length>100)throw ge("invalid_request","timer_input")}function $8(n,e,t){let i=`${n}/${Gy(t[0],z8)}`;if(e==="list"&&t.length===1)return{path:i,method:"GET",write:!1};if(e==="put"&&t.length===3){let o=hs(t[2],"criterion_id,fire_at");return YA(o.criterion_id),SE({id:t[1],fire_at:o.fire_at}),{path:`${i}/${Gy(t[1],GA)}`,method:"PUT",body:o,write:!0}}if(e==="cancel"&&t.length===3){let o=t[2];if(o!==void 0&&(!Number.isSafeInteger(o)||o<1))throw ge("invalid_request","timer_input");return{path:`${i}/${Gy(t[1],GA)}${o===void 0?"":`?generation=${o}`}`,method:"DELETE",write:!0}}if((e==="reconcile"||e==="reconcileWithReceipt")&&t.length===2){let o=hs(t[1],`criterion_id,timers${e==="reconcileWithReceipt"?",recovery":""}`);if(YA(o.criterion_id),!Array.isArray(o.timers)||o.timers.length>1e4)throw ge("invalid_request","timer_input");let s=o.timers.map(SE);if(new Set(s.map(r=>r.id)).size!==s.length)throw ge("invalid_request","timer_input");if(e==="reconcileWithReceipt"){let r=hs(o.recovery,"protocol_version,operation_id,expected_revision");if(r.protocol_version!==1||typeof r.operation_id!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(r.operation_id)||!Number.isSafeInteger(r.expected_revision)||r.expected_revision<0||r.expected_revision>=Number.MAX_SAFE_INTEGER)throw ge("invalid_request","timer_input")}return{path:`${i}/reconcile`,method:"POST",body:{...o,timers:s},write:!0}}if(e==="lookupOperation"&&t.length===2&&typeof t[1]=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(t[1]))return{path:`${i}/operations/${t[1]}`,method:"GET",write:!1};throw ge("invalid_request","timer_input")}function xE(n,e){let t=PE(e.scope),i=e.generation,o=`/v1/next/collections/${e.scope.collection}/background-grants/${e.grantId}/timers`,s=!1,r=0,a=null,c=null,l=()=>{if(s||e.signal.aborted||!e.isCurrent())throw ge("unauthenticated","timer_fenced")},p=()=>{if(c)return c;s=!0,e.signal.removeEventListener("abort",d),a?.ctrl.abort();try{n.postMessage([1,t,i,"close"])}finally{n.removeEventListener("message",u),n.close()}return c=Promise.resolve().then(async()=>{await a?.work})},d=()=>{p()},u=f=>{let h=f.data;if(!Array.isArray(h)||h[0]!==1||h[1]!==t||h[2]!==i){p();return}if(h.length===4&&h[3]==="close"){p();return}if(h.length===5&&h[4]==="cancel"&&Number.isSafeInteger(h[3])&&h[3]>0){a&&a.id===h[3]&&a.ctrl.abort();return}if(h.length!==6||!Number.isSafeInteger(h[3])||h[3]<=r||a||typeof h[4]!="string"||!Array.isArray(h[5])){p();return}let m=h[3],w=h[4],b=h[5],g=new AbortController;r=m;let y=!1,v=w!=="list"&&w!=="lookupOperation",_=Promise.resolve().then(async()=>{let k=setTimeout(()=>g.abort(),1e4),S,x,P=new Uint8Array(au),I=0,O=()=>{x?.cancel().catch(()=>{})};g.signal.addEventListener("abort",O,{once:!0});try{l(),g.signal.throwIfAborted();let R=o.slice(0,-7)+"/notifications/channels",q,j,B=null;if(w==="vapid"&&b.length===0){if(!e.journal)throw ge("upgrade_required","native_timer_channel_journal_unavailable");e.journal.read(),q={path:"/v1/notifications/vapid-public-key",method:"GET",write:!1}}else if(w==="registerChannel"&&b.length===1){if(!e.journal)throw ge("upgrade_required","native_timer_channel_journal_unavailable");let ee=b[0],te=hs(ee,`kind,criteria,${ee?.kind==="web_push"?"subscription":"token"}`);if(!["web_push","fcm"].includes(te.kind)||!Array.isArray(te.criteria)||!te.criteria.length||te.criteria.length>100||(te.criteria.forEach(YA),new Set(te.criteria).size!==te.criteria.length))throw ge("invalid_request","timer_input");let Ie;if(te.kind==="fcm"){if(typeof te.token!="string"||te.token.length<16||te.token.length>4096||/[\s\u0000-\u001f\u007f]/.test(te.token))throw ge("invalid_request","timer_input");Ie={transport:"fcm",token:te.token}}else{let K=hs(te.subscription,"endpoint,expirationTime,keys"),Q=hs(K.keys,"p256dh,auth");if(typeof K.endpoint!="string"||K.endpoint.length>2048||typeof Q.p256dh!="string"||typeof Q.auth!="string"||!/^[A-Za-z0-9_-]{87}$/.test(Q.p256dh)||!/^[A-Za-z0-9_-]{22}$/.test(Q.auth))throw ge("invalid_request","timer_input");let Ae;try{Ae=new URL(K.endpoint)}catch{throw ge("invalid_request","timer_input")}if(Ae.protocol!=="https:"||Ae.username||Ae.password||Ae.hash||Ae.href!==K.endpoint||K.expirationTime!==null&&(!Number.isFinite(K.expirationTime)||K.expirationTime<0))throw ge("invalid_request","timer_input");Ie={subscription:K}}q={path:R,method:"POST",write:!0,body:{installation_id:e.scope.installation,criteria:[...te.criteria].sort(),...Ie}};let tt=new TextEncoder().encode(JSON.stringify(q.body)),$;try{$=[...new Uint8Array(await crypto.subtle.digest("SHA-256",tt))].map(K=>K.toString(16).padStart(2,"0")).join("")}finally{tt.fill(0)}l(),g.signal.throwIfAborted();let Y=e.journal.read();if(B=Y,Y?.pending)throw ge("outcome_unknown","timer_channel_reapproval_required");j={grantId:e.grantId,kind:te.kind,targetDigest:$,channelId:Y?.channelId??null,pending:"register"}}else if(w==="unregisterChannel"&&b.length===1&&["web_push","fcm"].includes(b[0])){if(!e.journal)throw ge("upgrade_required","native_timer_channel_journal_unavailable");let ee=e.journal.read();if(B=ee,!ee){n.postMessage([1,t,i,m,!0,void 0]);return}if(ee.pending==="register")throw ge("outcome_unknown","timer_channel_reapproval_required");if(ee.kind!==b[0]||!ee.channelId)throw ge("invalid_request","timer_channel_kind");j={...ee,pending:"delete"},q={path:`${R}/${ee.channelId}`,method:"DELETE",write:!0}}else q=$8(o,w,b);v=q.write;let D=q.body===void 0?void 0:JSON.stringify(q.body);if(D&&new TextEncoder().encode(D).length>au)throw ge("invalid_request","timer_input");let X=await e.bearer();if(l(),g.signal.throwIfAborted(),typeof X!="string"||!/^(idev_|ct_)[A-Za-z0-9_-]{43}$/.test(X))throw ge("unauthenticated","timer_credential");j&&(await e.journal.write(j),l(),g.signal.throwIfAborted()),y=v;let V=e.fetch;if(S=await V(`${e.cpOrigin}${q.path}`,{method:q.method,body:D,headers:{authorization:`Bearer ${X}`,...D===void 0?{}:{"content-type":"application/json"}},credentials:"omit",redirect:"error",cache:q.method==="GET"?"no-store":"default",referrerPolicy:"no-referrer",signal:g.signal}),l(),g.signal.throwIfAborted(),S.redirected)throw ge("unavailable","timer_response");if(w==="unregisterChannel"&&S.status===204){await e.journal.write(null),l(),g.signal.throwIfAborted(),n.postMessage([1,t,i,m,!0,void 0]);return}if(S.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase()!=="application/json"||!S.body)throw ge("unavailable","timer_response");let U=S.headers.get("content-length");if(U&&/^\d+$/.test(U)&&Number(U)>au)throw ge("unavailable","timer_response");for(x=S.body.getReader();;){let ee=await x.read();try{if(l(),g.signal.throwIfAborted(),ee.done)break;if(I+ee.value.length>au)throw ge("unavailable","timer_response");P.set(ee.value,I),I+=ee.value.length}finally{ee.value?.fill(0)}}let ce=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(P.subarray(0,I)));if(w==="unregisterChannel"&&S.status===404&&ce?.error?.code==="channel_not_found"){await e.journal.write(null),l(),g.signal.throwIfAborted(),n.postMessage([1,t,i,m,!0,void 0]);return}if(!S.ok){let ee=!!j&&S.status===503&&typeof ce?.error?.code=="string";throw S.status>=500&&!ee?ge("unavailable","timer_http"):ce?.error?.operation_outcome==="unknown"?ge("outcome_unknown","timer_write_unknown"):(j&&(await e.journal.write(B),l(),g.signal.throwIfAborted()),y=!1,ee?ge("unavailable","timer_http"):A(S.status===401||S.status===403?"unauthenticated":S.status===409?"conflict":S.status===404?"upgrade_required":S.status===429?"rate_limited":"invalid_request","Timer request was refused.","timer_refused"))}if(l(),g.signal.throwIfAborted(),w==="registerChannel"){if(typeof ce?.channel_id!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(ce.channel_id))throw ge("unavailable","timer_channel_response");await e.journal.write({...j,channelId:ce.channel_id,pending:null}),l(),g.signal.throwIfAborted(),n.postMessage([1,t,i,m,!0,{channelId:ce.channel_id,installationId:e.scope.installation,criteria:q.body.criteria}])}else n.postMessage([1,t,i,m,!0,ce])}catch(R){let q=y?ge("outcome_unknown","timer_write_unknown"):R instanceof ne?R:ge(g.signal.aborted?"cancelled":"unavailable","timer_request");s||n.postMessage([1,t,i,m,!1,q.code,q.reason])}finally{clearTimeout(k),g.signal.removeEventListener("abort",O),P.fill(0),(x?.cancel()??S?.body?.cancel())?.catch(()=>{}),x?.releaseLock(),a?.id===m&&(a=null)}});a={id:m,ctrl:g,work:_}};n.addEventListener("message",u),n.start(),e.signal.addEventListener("abort",d,{once:!0});try{l()}catch(f){throw p(),f}return Object.freeze({close:p})}function IE(n,e,t){let i=PE(e.scope),o=e.generation,s=!1,r=0,a=null,c=()=>{if(s)return;s=!0,t.signal.removeEventListener("abort",c);let y=a;a=null,y?.signal?.removeEventListener("abort",y.abort),y?.reject(ge(y.write?"outcome_unknown":"cancelled","timer_port_closed"));try{n.postMessage([1,i,o,"close"])}finally{n.removeEventListener("message",l),n.close(),t.onClose()}},l=y=>{let v=y.data;if(!Array.isArray(v)||v[0]!==1||v[1]!==i||v[2]!==o){c();return}if(v.length===4&&v[3]==="close"){c();return}let _=a;if(!_||v[3]!==_.id||!(v.length===6&&v[4]===!0||v.length===7&&v[4]===!1&&typeof v[5]=="string"&&Po(v[5]))){c();return}a=null,_.signal?.removeEventListener("abort",_.abort),v[4]?_.resolve(v[5]):_.reject(A(v[5],"Timer request could not complete.",typeof v[6]=="string"?v[6]:void 0))},p=(y,v,_,k=!1)=>{if(s||t.signal.aborted||_.signal?.aborted)return Promise.reject(ge("cancelled","timer_port_closed"));if(a||d&&!k)return Promise.reject(ge("unavailable","timer_port_busy"));if(r>=Number.MAX_SAFE_INTEGER)return c(),Promise.reject(ge("unavailable","timer_port_closed"));let S=++r,x=y!=="list"&&y!=="lookupOperation"&&y!=="vapid";return new Promise((P,I)=>{let O=()=>{try{n.postMessage([1,i,o,S,"cancel"])}catch{c()}I(ge(x?"outcome_unknown":"cancelled","timer_request_cancelled"))};a={id:S,write:x,resolve:P,reject:I,abort:O,signal:_.signal},_.signal?.addEventListener("abort",O,{once:!0});try{if(new TextEncoder().encode(JSON.stringify(v)).length>au)throw ge("invalid_request","timer_input");n.postMessage([1,i,o,S,y,v])}catch(R){a=null,_.signal?.removeEventListener("abort",O),I(R)}})},d=!1,u=()=>{if(s||t.signal.aborted)throw ge("cancelled","timer_port_closed")},f=y=>{if(!y?.length||y.length>100||y.some(v=>typeof v!="string"||!v.length||v.length>100)||new Set(y).size!==y.length)throw ge("invalid_request","timer_channel_criteria_required");return[...y].sort()},h=(y,v)=>{let _=hs(y,"channelId,installationId,criteria");if(typeof _.channelId!="string"||_.installationId!==e.scope.installation||JSON.stringify(_.criteria)!==JSON.stringify(v))throw ge("outcome_unknown","timer_channel_response");return{channelId:_.channelId,installationId:e.scope.installation,criteria:[...v]}},m=async(y,v)=>{if(u(),y.signal?.throwIfAborted(),d||a)throw ge("unavailable","timer_port_busy");d=!0;try{return await v()}finally{d=!1}},w=y=>m(y,async()=>{let v=f(y.criteria);if(y.installationId!==void 0&&y.installationId!==e.scope.installation)throw ge("invalid_request","timer_channel_installation");let _=y.serviceWorker;if(!_?.pushManager||typeof _.pushManager.getSubscription!="function"||typeof _.pushManager.subscribe!="function")throw ge("invalid_request","timer_push_platform");let k=await p("vapid",[],y,!0);if(u(),y.signal?.throwIfAborted(),typeof k.public_key!="string"||!/^[A-Za-z0-9_-]{87}$/.test(k.public_key))throw ge("unavailable","timer_vapid_response");let S=atob(k.public_key.replace(/-/g,"+").replace(/_/g,"/")),x=Uint8Array.from(S,O=>O.charCodeAt(0));if(x.length!==65||x[0]!==4||btoa(S).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")!==k.public_key)throw ge("unavailable","timer_vapid_response");let P=await _.pushManager.getSubscription();if(u(),y.signal?.throwIfAborted(),P){let O=P.options.applicationServerKey;if(!O||O.byteLength!==x.length||new Uint8Array(O).some((R,q)=>R!==x[q]))throw ge("invalid_request","timer_push_key_changed")}if(!P&&(P=await _.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:x}),s||t.signal.aborted||y.signal?.aborted))throw await P.unsubscribe(),ge("cancelled","timer_port_closed");let I=P.toJSON();return h(await p("registerChannel",[{kind:"web_push",criteria:v,subscription:{endpoint:I.endpoint,expirationTime:I.expirationTime??null,keys:I.keys}}],y,!0),v)}),b=y=>m(y,async()=>{let v=f(y.criteria);if(y.installationId!==void 0&&y.installationId!==e.scope.installation)throw ge("invalid_request","timer_channel_installation");return{...h(await p("registerChannel",[{kind:"fcm",criteria:v,token:y.token}],y,!0),v),transport:"fcm"}}),g=(y,v)=>m(v,async()=>{if(await p("unregisterChannel",["web_push"],v,!0),u(),v.signal?.throwIfAborted(),y){let _=await y.pushManager.getSubscription();u(),v.signal?.throwIfAborted(),_&&await _.unsubscribe(),u(),v.signal?.throwIfAborted()}});return n.addEventListener("message",l),n.start(),t.signal.addEventListener("abort",c,{once:!0}),t.signal.aborted&&c(),Object.freeze({list:(y,v)=>p("list",[y],v),put:(y,v,_,k)=>p("put",[y,v,_],k),cancel:(y,v,_,k)=>p("cancel",[y,v,_],k),reconcile:(y,v,_)=>p("reconcile",[y,v],_),reconcileWithReceipt:(y,v,_)=>p("reconcileWithReceipt",[y,v],_),lookupOperation:(y,v,_)=>p("lookupOperation",[y,v],_),registerWebPush:w,unregisterWebPush:g,registerFcm:b,unregisterFcm:y=>m(y,async()=>{await p("unregisterChannel",["fcm"],y,!0)}),close:c})}var z8,GA,au,ge,PE,JA=C(()=>{"use strict";re();z8=/^[A-Za-z0-9._-]{1,64}$/,GA=/^[A-Za-z0-9._:-]{1,128}$/,au=2*1024*1024,ge=(n,e)=>A(n,"Timer request could not complete.",e),PE=n=>JSON.stringify([n.account,n.installation,n.collection])});function gc(n){return n.mode==="local_only"?null:n.incidents.some(e=>e.kind==="waiting_for_key")?"waiting_for_key":n.installing?"installing":n.resyncing?"resyncing":n.connection==="offline"?"offline":n.headKnown===0?"head_unknown":n.confirmedThrough<n.headKnown?"behind":null}function Yy(n){let e=n.incidents.find(s=>s.kind==="waiting_for_key");if(!e)return null;let t={through:n.confirmedThrough,head:n.headKnown},i=s=>de(e.details,s),o=i("reason");typeof o=="string"&&/^[a-z_]{1,32}$/.test(o)&&(t.key=o);for(let s of["position","at"]){let r=i(s);typeof r=="number"&&(t[s]=r)}return t}function RE(n){if(gc(n)!=="waiting_for_key")return!1;let e=Yy(n)?.key;return e==="reading"||e==="no_grant"}var CE,OE=C(()=>{"use strict";un();CE=15e4});var Jy,XA,Ye,ZA,B8,Xy,QA=C(()=>{"use strict";Je();ve();Ws();Jy=264*1024+256,XA=264*1024,Ye=()=>new Error("app cloud copy outcome unavailable; preserve storage and reopen"),ZA=(n,e)=>n.length===e.length&&n.every((t,i)=>t===e[i]),B8=n=>Array.from(n,e=>e.toString(16).padStart(2,"0")).join(""),Xy=class{constructor(e,t,i,o,s){this.source=e;this.store=o;this.key=i;try{this.mode=s.mode,this.lifetime=s.signal,this.fields=Object.freeze({accountId:e.accountId,connectorId:e.connectorId,deviceId:e.deviceId,installationId:e.installationId,collection:e.collection,purpose:e.purpose,cpOrigin:e.cpOrigin,logOrigin:e.logOrigin,assetSha256:e.assetSha256});let r=e.displayName;if(this.displayName=r===void 0?void 0:li(r),this.displayName!==void 0&&e.purpose!=="create"||r!==this.displayName)throw Ye();this.current=e.isCurrent,this.owned=e.installationOwned,this.io=Object.freeze({read:o.read,cas:o.compareAndSet});let a=[e.accountId,e.connectorId,e.deviceId,e.installationId,e.collection].map(N);if(a.some(c=>c.every(l=>l===0))||!["create","join"].includes(e.purpose)||!["fresh","existing"].includes(this.mode)||!/^[0-9a-f]{64}$/.test(e.assetSha256)||(this.keys=Object.freeze([t.signPublicKey,t.kemPublicKey,t.noisePublicKey].map(c=>{if(!(c instanceof Uint8Array)||c.length!==32||c.every(l=>l===0))throw Ye();return new Uint8Array(c)})),t.connectorId!==e.connectorId||t.deviceId!==e.deviceId||t.installationId!==e.installationId)||typeof globalThis.CryptoKey!="function"||!(i instanceof CryptoKey)||i.type!=="secret"||i.extractable||i.algorithm.name!=="AES-GCM"||i.algorithm.length!==256||i.usages.length!==2||!i.usages.includes("encrypt")||!i.usages.includes("decrypt"))throw Ye();this.aad=fe(["mdbase/v1/app-cloud-copy-outcome-platform",...a,e.purpose,e.cpOrigin,e.logOrigin,e.assetSha256,...this.keys]),this.check(this.lifetime)}catch{throw Ye()}}source;store;closed=!1;key;fields;displayName;current;owned;io;keys;aad;mode;lifetime;check(e){try{if(this.closed||!this.key||e!==this.lifetime||e.aborted||this.source.displayName!==this.displayName||this.source.isCurrent!==this.current||this.source.installationOwned!==this.owned||this.current.call(this.source)!==!0||this.owned.call(this.source)!==!0||this.store.read!==this.io.read||this.store.compareAndSet!==this.io.cas||Object.entries(this.fields).some(([t,i])=>this.source[t]!==i))throw Ye()}catch{throw Ye()}}operation(e){if(e){if(e.displayName!==this.displayName)throw Ye();for(let t of Object.keys(this.fields))if(e[t]!==this.fields[t])throw Ye();for(let[t,i]of["signPublicKey","kemPublicKey","noisePublicKey"].entries())if(!(e[i]instanceof Uint8Array)||!ZA(e[i],this.keys[t]))throw Ye()}return Object.freeze({...this.fields,...this.displayName===void 0?{}:{displayName:this.displayName},signPublicKey:new Uint8Array(this.keys[0]),kemPublicKey:new Uint8Array(this.keys[1]),noisePublicKey:new Uint8Array(this.keys[2])})}metadata(e){let t=this.operation(e.operation);if(!(e.genesisItem instanceof Uint8Array)||!e.genesisItem.length||e.genesisItem.length>256*1024||typeof e.expectedGenesis!="string"||!/^sha256:[0-9a-f]{64}$/.test(e.expectedGenesis))throw Ye();return Object.freeze({operation:t,genesisItem:new Uint8Array(e.genesisItem),expectedGenesis:e.expectedGenesis})}async hashChecked(e,t){let i=new TextEncoder().encode("mdbase/v1/chain"),o=new Uint8Array(1+i.length+e.genesisItem.length);o[0]=i.length,o.set(i,1),o.set(e.genesisItem,1+i.length);let s=new Uint8Array(await crypto.subtle.digest("SHA-256",o));if(this.check(t),e.expectedGenesis!==`sha256:${B8(s)}`)throw Ye()}async read(e){let t=null;try{this.check(e);let i=await this.io.read.call(this.store,Object.freeze({signal:e}));if(this.check(e),i===null){if(this.mode!=="fresh")throw Ye();return null}if(!(i instanceof Uint8Array)||!i.length||i.length>Jy)throw Ye();let o=new Uint8Array(i),s=we(o);if(!(s instanceof Map))throw Ye();let r=s;if(r.size!==3||r.get(0)!==1)throw Ye();let a=r.get(1),c=r.get(2);if(!(a instanceof Uint8Array)||a.length!==12||!(c instanceof Uint8Array)||c.length<16||c.length>XA+16||(t=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:new Uint8Array(a),additionalData:new Uint8Array(this.aad),tagLength:128},this.key,new Uint8Array(c))),this.check(e),t.length>XA))throw Ye();let l=we(t);if(!(l instanceof Map))throw Ye();let p=l,d=p.get(0)===1&&p.size===3;if(!d&&!(p.get(0)===2&&p.size===4)||(d?null:p.get(3))!==(this.displayName??null))throw Ye();let u=p.get(1);if(!Array.isArray(u)||u.length!==3||u.some((m,w)=>!(m instanceof Uint8Array)||!ZA(m,this.keys[w])))throw Ye();let f=p.get(2),h=null;if(f!==null){if(!Array.isArray(f)||f.length!==2||!(f[0]instanceof Uint8Array)||typeof f[1]!="string")throw Ye();h=this.metadata({operation:this.operation(),genesisItem:f[0],expectedGenesis:f[1]}),await this.hashChecked(h,e)}return{encrypted:o,metadata:h}}catch{throw Ye()}finally{t?.fill(0)}}async write(e,t,i){let o=null,s=null;try{if(this.check(i),o=fe(new Map([[0,2],[1,this.keys.map(l=>new Uint8Array(l))],[2,e===null?null:[e.genesisItem,e.expectedGenesis]],[3,this.displayName??null]])),o.length>XA)throw Ye();let r=crypto.getRandomValues(new Uint8Array(12)),a=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:r,additionalData:new Uint8Array(this.aad),tagLength:128},this.key,new Uint8Array(o)));if(this.check(i),s=fe(new Map([[0,1],[1,r],[2,a]])),s.length>Jy)throw Ye();let c=await this.io.cas.call(this.store,t,s,Object.freeze({signal:i}));if(this.check(i),c!==!0)throw Ye()}catch{throw Ye()}finally{o?.fill(0),s?.fill(0)}}async restore(e){let{signal:t}=e,i=await this.read(t);return this.check(t),i===null?Object.freeze({state:"none"}):i.metadata===null?Object.freeze({state:"pending",operation:this.operation()}):Object.freeze({state:"completed",metadata:this.metadata(i.metadata)})}async pending(e,t){let{signal:i}=t;this.check(i),this.operation(e);let o=await this.read(i);this.check(i),!o&&await this.write(null,null,i)}async completed(e,t){let{signal:i}=t;this.check(i);let o=this.metadata(e);await this.hashChecked(o,i);let s=await this.read(i);if(this.check(i),!s)throw Ye();if(s.metadata){if(!ZA(s.metadata.genesisItem,o.genesisItem)||s.metadata.expectedGenesis!==o.expectedGenesis)throw Ye();return}await this.write(o,s.encrypted,i)}close(){this.closed=!0,this.key=null}}});function t0(n){if(!(n instanceof Uint8Array)||!n.length||n.length>Jy)throw wn();return new Uint8Array(n)}var Zy,e0,wn,V8,Qy,EE=C(()=>{"use strict";Jt();ve();QA();Zy="public-outcome",e0="operation",wn=()=>new Error("app cloud copy outcome store unavailable; preserve storage and reopen"),V8=(n,e)=>n===null||e===null?n===e:n.length===e.length&&n.every((t,i)=>t===e[i]);Qy=class n{constructor(e,t,i){this.source=e;this.origin=t;this.lifetime=i;this.fields=Object.freeze({accountId:e.accountId,connectorId:e.connectorId,deviceId:e.deviceId,installationId:e.installationId,collection:e.collection,purpose:e.purpose,cpOrigin:e.cpOrigin,logOrigin:e.logOrigin,assetSha256:e.assetSha256}),this.current=e.isCurrent,this.owned=e.installationOwned}source;origin;lifetime;db=null;closed=!1;fields;current;owned;get fenced(){return this.closed||this.lifetime.aborted}check(e){try{if(this.fenced||e!==this.lifetime||e.aborted||Et()!==this.origin||this.source.isCurrent!==this.current||this.source.installationOwned!==this.owned||this.current.call(this.source)!==!0||this.owned.call(this.source)!==!0||Object.entries(this.fields).some(([t,i])=>this.source[t]!==i))throw wn()}catch{throw wn()}}static async open(e){let{source:t,origin:i,mode:o,signal:s}=e,r=null;try{r=new n(t,i,s);let a=[r.fields.accountId,r.fields.connectorId,r.fields.deviceId,r.fields.installationId,r.fields.collection].map(l=>{if(N(l).every(p=>p===0))throw wn();return l.toLowerCase()});if(!ut(i)||!["fresh","existing"].includes(o)||!["create","join"].includes(r.fields.purpose)||!/^[0-9a-f]{64}$/.test(r.fields.assetSha256)||!globalThis.indexedDB)throw wn();r.check(s),r.db=await r.openDatabase(`mdbase.app.cloud-copy-outcome.v1.${a.join(".")}.${r.fields.purpose}`,o),r.db.onversionchange=()=>r.close(),r.check(s);let c=await r.read(Object.freeze({signal:s}));try{if(o==="fresh"!=(c===null))throw wn();r.check(s)}finally{c?.fill(0)}return r}catch{throw r?.close(),wn()}}openDatabase(e,t){return new Promise((i,o)=>{this.check(this.lifetime);let s=indexedDB.open(e,1),r=!1,a=!1,c=()=>{r=!0,o(wn())},l=()=>this.lifetime.removeEventListener("abort",c);this.lifetime.addEventListener("abort",c,{once:!0}),s.onblocked=c,s.onupgradeneeded=()=>{try{if(this.check(this.lifetime),r||t!=="fresh"||s.result.objectStoreNames.length!==0)throw wn();s.result.createObjectStore(Zy),a=!0}catch{s.transaction?.abort()}},s.onerror=()=>{l(),o(wn())},s.onsuccess=()=>{l();try{if(this.check(this.lifetime),r||t==="fresh"&&!a||s.result.objectStoreNames.length!==1||!s.result.objectStoreNames.contains(Zy))throw wn();i(s.result)}catch{s.result.close(),o(wn())}}})}async read(e){let{signal:t}=e;this.check(t);let i=await this.transaction("readonly",t,null,null);return this.check(t),i}async compareAndSet(e,t,i){let{signal:o}=i;this.check(o);let s=e===null?null:t0(e),r=t0(t);try{let a=await this.transaction("readwrite",o,s,r);return this.check(o),a===!0}finally{s?.fill(0),r.fill(0)}}transaction(e,t,i,o){return new Promise((s,r)=>{if(this.check(t),!this.db)throw wn();let a=this.db.transaction(Zy,e,{durability:"strict"}),c=a.objectStore(Zy),l=null,p=!1,d=()=>{p=!0;try{a.abort()}catch{}},u=()=>t.removeEventListener("abort",d);t.addEventListener("abort",d,{once:!0}),a.onabort=a.onerror=()=>{u(),l instanceof Uint8Array&&l.fill(0),r(wn())},a.oncomplete=()=>{u();try{if(this.check(t),p)throw wn();s(l)}catch{l instanceof Uint8Array&&l.fill(0),r(wn())}};let f=c.get(e0);f.onsuccess=()=>{let h=null;try{this.check(t),h=f.result===void 0?null:t0(f.result),e==="readonly"?(l=h,h=null):(l=V8(h,i),l===!0&&o!==null&&(i===null?c.add(new Uint8Array(o),e0):c.put(new Uint8Array(o),e0)))}catch{d()}finally{h?.fill(0)}}})}close(){this.closed||(this.closed=!0,this.db?.close(),this.db=null)}}});function r0(n,e){if(typeof n!="string"||!n.length||n.length>e*2||n.length%2||!/^[0-9a-f]+$/.test(n))throw ot("response");return Uint8Array.from(n.match(/../g).map(t=>parseInt(t,16)))}function o0(n){if(!n||typeof n!="object"||Array.isArray(n))throw ot("response");return n}var ga,ot,n0,i0,eg,s0=C(()=>{"use strict";St();ve();Ws();ga=class extends Error{constructor(t){super(`app private bootstrap: ${t}`);this.reason=t;this.name="AppPrivateBootstrapError"}reason},ot=n=>new ga(n),n0=n=>Array.from(n,e=>e.toString(16).padStart(2,"0")).join(""),i0=(n,e)=>n.length===e.length&&n.every((t,i)=>t===e[i]);eg=class{constructor(e,t,i,o={}){this.runtime=e;this.session=t;this.persistence=i;this.options=o;try{let s=o.displayName;if(this.displayName=s===void 0?void 0:li(s),this.displayName!==void 0&&t.purpose!=="create")throw ot("binding");this.scope=Object.freeze({connectorId:t.connectorId,deviceId:t.deviceId,installationId:t.installationId,collection:t.collection,purpose:t.purpose,accountId:t.accountId,cpOrigin:t.cpOrigin,logOrigin:t.logOrigin});for(let r of[this.scope.connectorId,this.scope.deviceId,this.scope.installationId,this.scope.collection,this.scope.accountId])if(N(r).every(a=>a===0))throw ot("binding");if(this.origin(this.scope.cpOrigin),this.origin(this.scope.logOrigin),!(t.rootPublicKey instanceof Uint8Array)||t.rootPublicKey.length!==32||t.rootPublicKey.every(r=>r===0)||(this.root=new Uint8Array(t.rootPublicKey),this.fetchImpl=o.fetch??globalThis.fetch,this.now=o.now??Date.now,this.marker=this.scope.purpose==="enrol"?e.privateEnrolMarker():null,!this.current()))throw ot("binding")}catch{throw e.retireLog(),ot("binding")}}runtime;session;persistence;options;attempted=!1;lifetime=new AbortController;scope;root;marker;fetchImpl;now;displayName;origin(e){let t=new URL(e);if(t.username||t.password||t.pathname!=="/"||t.search||t.hash||t.protocol!=="https:"&&!(this.options.allowLoopbackHttp===!0&&Qe(e)))throw ot("binding");return t.origin}current(){try{return!this.lifetime.signal.aborted&&this.runtime.privateCollectionCurrent(this.session)&&this.session.isCurrent()===!0&&this.session.approvalMode==="password-ak1"&&i0(this.session.rootPublicKey,this.root)&&Object.entries(this.scope).every(([e,t])=>this.session[e]===t)}catch{return!1}}markerCopy(){let e=this.marker;if(!e)throw ot("binding");return Object.freeze({...e,sasCommitment:new Uint8Array(e.sasCommitment),signPublicKey:new Uint8Array(e.signPublicKey),kemPublicKey:new Uint8Array(e.kemPublicKey),noisePublicKey:new Uint8Array(e.noisePublicKey)})}check(e){if(!this.current()||e.aborted)throw this.close(),ot("fenced")}async json(e,t,i,o){this.check(o);let s=new AbortController,r=()=>s.abort(),a=setTimeout(r,15e3);a.unref?.(),o.addEventListener("abort",r,{once:!0}),this.lifetime.signal.addEventListener("abort",r,{once:!0});let c=new Uint8Array(1024*1024),l=0,p=null,d=null;try{let u=this.fetchImpl;if(d=await u(`${this.origin(this.scope.cpOrigin)}${e}`,{method:"POST",headers:{authorization:`Bearer ${t}`,...i===void 0?{}:{"content-type":"application/json"}},body:i,signal:s.signal,redirect:"error",credentials:"omit",cache:"default",referrerPolicy:"no-referrer"}),this.check(o),s.signal.aborted||!d.ok)throw ot("unavailable");let f=d.headers.get("content-length");if(f!==null&&/^(0|[1-9][0-9]*)$/.test(f)&&Number(f)>c.length)throw s.abort(),ot("response");if(!d.body)throw ot("response");for(p=d.body.getReader();;){let{done:h,value:m}=await p.read();try{if(this.check(o),s.signal.aborted)throw ot("unavailable");if(h)break;if(l+m.length>c.length)throw s.abort(),ot("response");c.set(m,l),l+=m.length}finally{m?.fill(0)}}return o0(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(c.subarray(0,l))))}catch(u){throw this.check(o),u instanceof ga?u:ot("unavailable")}finally{c.fill(0),(p?.cancel()??d?.body?.cancel())?.catch(()=>{}),p?.releaseLock(),clearTimeout(a),o.removeEventListener("abort",r),this.lifetime.signal.removeEventListener("abort",r)}}copy(e){if(e.displayName!==this.displayName||e.collection!==this.scope.collection||e.deviceId!==this.scope.deviceId||e.logOrigin!==this.scope.logOrigin||!i0(e.rootPublicKey,this.root)||!(e.genesisItem instanceof Uint8Array)||!e.genesisItem.length||e.genesisItem.length>256*1024||e.expectedGenesis.length!==71||!/^sha256:[0-9a-f]{64}$/.test(e.expectedGenesis)||e.approval!==(this.scope.purpose==="create"?"creator":"pending"))throw ot("response");return Object.freeze({collection:e.collection,deviceId:e.deviceId,logOrigin:e.logOrigin,expectedGenesis:e.expectedGenesis,approval:e.approval,...this.displayName===void 0?{}:{displayName:this.displayName},rootPublicKey:new Uint8Array(e.rootPublicKey),genesisItem:new Uint8Array(e.genesisItem)})}async bootstrap(e){let t=null,i=null;try{if(this.check(e.signal),this.attempted)throw ot("fenced");this.attempted=!0;let o=await this.persistence.restoredCompletion(e);if(this.check(e.signal),o){let w=this.copy(o);return this.marker&&!this.marker.acknowledged&&(await this.persistence.privateEnrolAcknowledged(this.markerCopy(),e),this.check(e.signal)),w}if(this.marker?.acknowledged)throw ot("response");this.marker?await this.persistence.privateEnrolPending(this.markerCopy(),e):await this.persistence.pendingCreate({...this.runtime.registeredDeviceReceipt(),collection:this.scope.collection,...this.displayName===void 0?{}:{displayName:this.displayName}},e),this.check(e.signal);let s=await this.session.connectorBearer(e);if(this.check(e.signal),typeof s!="string"||!s||s.length>16384||/[^\x21-\x7e]/.test(s))throw ot("binding");let r=await this.json("/v1/next/devices/challenge",s,void 0,e.signal);if(this.check(e.signal),t=r0(r.challenge,32),t.length!==32||typeof r.expires_at!="number"||!Number.isSafeInteger(r.expires_at)||r.expires_at-this.now()<=5e3||r.expires_at-this.now()>16*6e4)throw ot("response");let a=this.scope.purpose==="enrol";i=a?this.runtime.signPrivateDeviceEnrol(t).signature:this.runtime.signPrivateCreate(t),this.check(e.signal);let c=await this.json(a?`/v1/next/collections/${this.scope.collection}/private/devices`:"/v1/next/collections/private",s,JSON.stringify({device_id:this.scope.deviceId,capabilities:["collection_mode_switch_v2"],challenge:r.challenge,sig:n0(i),...a?{sas_commit:n0(this.marker.sasCommitment)}:{collection_id:this.scope.collection,...this.displayName===void 0?{}:{display_name:this.displayName}}}),e.signal);if(this.check(e.signal),c.collection_id!==this.scope.collection||this.origin(c.log_url)!==this.origin(this.scope.logOrigin))throw ot("response");if(a){if(c.approval!=="pending"||typeof c.enrolled_at!="number"||!Number.isSafeInteger(c.enrolled_at)||c.enrolled_at<1)throw ot("response")}else if(c.state!=="private"||c.owner_account!==this.scope.accountId||!i0(r0(c.root_public_key,32),this.root))throw ot("response");let l=o0(c.device);if(l.device_id!==this.scope.deviceId||typeof l.token!="string"||!l.token.length||l.token.length>16384||/[^\x21-\x7e]/.test(l.token)||typeof l.expires_at!="number"||!Number.isSafeInteger(l.expires_at)||l.expires_at-this.now()<=5e3||l.expires_at-this.now()>16*6e4)throw ot("response");let p=o0(c.genesis);if(p.seq!==1)throw ot("response");let d=r0(p.item,256*1024),u=new TextEncoder().encode("mdbase/v1/chain"),f=new Uint8Array(1+u.length+d.length);f[0]=u.length,f.set(u,1),f.set(d,1+u.length);let h=new Uint8Array(await crypto.subtle.digest("SHA-256",f));this.check(e.signal);let m=this.copy({collection:this.scope.collection,deviceId:this.scope.deviceId,logOrigin:this.scope.logOrigin,rootPublicKey:this.root,genesisItem:d,expectedGenesis:`sha256:${n0(h)}`,approval:a?"pending":"creator",...this.displayName===void 0?{}:{displayName:this.displayName}});return await this.persistence.completed(this.copy(m),e),this.check(e.signal),this.marker&&(await this.persistence.privateEnrolAcknowledged(this.markerCopy(),e),this.check(e.signal)),m}catch(o){throw this.close(),o instanceof ga?o:ot("unavailable")}finally{t?.fill(0),i?.fill(0)}}close(){this.lifetime.abort(),this.runtime.retireLog()}}});var tg,a0,Oe,ba,F8,ng,l0=C(()=>{"use strict";St();Je();ve();Ws();tg=264*1024,a0=tg+256,Oe=()=>new Error("app private bootstrap custody unavailable; preserve storage and reopen"),ba=(n,e)=>n.length===e.length&&n.every((t,i)=>t===e[i]),F8=n=>Array.from(n,e=>e.toString(16).padStart(2,"0")).join(""),ng=class{constructor(e,t,i,o,s,r={}){this.source=e;this.key=i;this.store=o;this.noise=s;try{let a=r.displayName;if(this.displayName=a===void 0?void 0:li(a),this.displayName!==void 0&&e.purpose!=="create")throw Oe();this.pins=Object.freeze({accountId:e.accountId,connectorId:e.connectorId,deviceId:e.deviceId,installationId:e.installationId,collection:e.collection,purpose:e.purpose,cpOrigin:e.cpOrigin,logOrigin:e.logOrigin});let c=[this.pins.accountId,this.pins.connectorId,this.pins.deviceId,this.pins.installationId,this.pins.collection].map(N);if(c.some(l=>l.every(p=>p===0))||!["create","enrol"].includes(this.pins.purpose))throw Oe();for(let l of[e.cpOrigin,e.logOrigin]){let p=new URL(l);if(!(r.allowLoopbackHttp===!0&&Qe(l))&&p.protocol!=="https:"||p.origin!==l||p.username||p.password)throw Oe()}if(!(e.rootPublicKey instanceof Uint8Array)||e.rootPublicKey.length!==32||e.rootPublicKey.every(l=>l===0)||(this.root=new Uint8Array(e.rootPublicKey),this.keys=[t.signPublicKey,t.kemPublicKey,t.noisePublicKey].map(l=>{if(!(l instanceof Uint8Array)||l.length!==32||l.every(p=>p===0))throw Oe();return new Uint8Array(l)}),this.checkReceipt(t),i.type!=="secret"||i.extractable||i.algorithm.name!=="AES-GCM"||i.algorithm.length!==256||!i.usages.includes("encrypt")||!i.usages.includes("decrypt")))throw Oe();this.aad=fe(["mdbase/v1/app-private-bootstrap-platform",...c,this.pins.purpose,e.cpOrigin,e.logOrigin,this.root]),this.check(new AbortController().signal)}catch{throw Oe()}}source;key;store;noise;pins;root;keys;aad;displayName;check(e){try{if(e.aborted||this.source.isCurrent()!==!0||this.source.approvalMode!=="password-ak1"||!ba(this.source.rootPublicKey,this.root)||Object.entries(this.pins).some(([t,i])=>this.source[t]!==i))throw Oe()}catch{throw Oe()}}checkReceipt(e){if(e.connectorId!==this.pins.connectorId||e.deviceId!==this.pins.deviceId||e.installationId!==this.pins.installationId||[e.signPublicKey,e.kemPublicKey,e.noisePublicKey].some((i,o)=>!(i instanceof Uint8Array)||i.length!==32||i.every(s=>s===0)||!ba(i,this.keys[o])))throw Oe()}commit(e){if(this.checkReceipt(e),this.pins.purpose!=="enrol"||e.collection!==this.pins.collection||typeof e.acknowledged!="boolean"||!(e.sasCommitment instanceof Uint8Array)||e.sasCommitment.length!==32||e.sasCommitment.every(t=>t===0))throw Oe();return new Uint8Array(e.sasCommitment)}markerCopy(e,t){return Object.freeze({connectorId:this.pins.connectorId,deviceId:this.pins.deviceId,installationId:this.pins.installationId,collection:this.pins.collection,signPublicKey:new Uint8Array(this.keys[0]),kemPublicKey:new Uint8Array(this.keys[1]),noisePublicKey:new Uint8Array(this.keys[2]),sasCommitment:new Uint8Array(t),acknowledged:e.acknowledged})}copy(e){if(e.displayName!==this.displayName||e.collection!==this.pins.collection||e.deviceId!==this.pins.deviceId||e.logOrigin!==this.pins.logOrigin||!(e.rootPublicKey instanceof Uint8Array)||!ba(e.rootPublicKey,this.root)||!(e.genesisItem instanceof Uint8Array)||!e.genesisItem.length||e.genesisItem.length>256*1024||!/^sha256:[0-9a-f]{64}$/.test(e.expectedGenesis)||e.approval!==(this.pins.purpose==="create"?"creator":"pending"))throw Oe();return Object.freeze({collection:this.pins.collection,deviceId:this.pins.deviceId,logOrigin:this.pins.logOrigin,rootPublicKey:new Uint8Array(this.root),genesisItem:new Uint8Array(e.genesisItem),expectedGenesis:e.expectedGenesis,approval:e.approval,...this.displayName===void 0?{}:{displayName:this.displayName}})}async hashChecked(e,t){let i=new TextEncoder().encode("mdbase/v1/chain"),o=new Uint8Array(1+i.length+e.genesisItem.length);o[0]=i.length,o.set(i,1),o.set(e.genesisItem,1+i.length);let s=new Uint8Array(await crypto.subtle.digest("SHA-256",o));if(this.check(t),e.expectedGenesis!==`sha256:${F8(s)}`)throw Oe()}async read(e){let t=null;try{this.check(e.signal);let i=await this.store.read(e);if(this.check(e.signal),i===null)return null;if(!(i instanceof Uint8Array)||!i.length||i.length>a0)throw Oe();let o=new Uint8Array(i),s=we(o);if(!(s instanceof Map))throw Oe();let r=s;if(r.size!==3||r.get(0)!==1)throw Oe();let a=r.get(1),c=r.get(2);if(!(a instanceof Uint8Array)||a.length!==12||!(c instanceof Uint8Array)||c.length<16||c.length>tg+16||(t=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:new Uint8Array(a),additionalData:new Uint8Array(this.aad),tagLength:128},this.key,new Uint8Array(c))),this.check(e.signal),t.length>tg))throw Oe();let l=we(t);if(!(l instanceof Map))throw Oe();let p=l,d=p.get(0)===1&&p.size===4;if(!d&&!(p.get(0)===2&&p.size===5)||(d?null:p.get(4))!==(this.displayName??null))throw Oe();let u=p.get(1);if(!Array.isArray(u)||u.length!==3||u.some((w,b)=>!(w instanceof Uint8Array)||!ba(w,this.keys[b])))throw Oe();let f=p.get(2);if(this.pins.purpose==="create"?f!==null:!(f instanceof Uint8Array)||f.length!==32||f.every(w=>w===0))throw Oe();let h=p.get(3),m=null;if(h!==null){if(!Array.isArray(h)||h.length!==2||!(h[0]instanceof Uint8Array)||typeof h[1]!="string")throw Oe();m=this.copy({...this.pins,rootPublicKey:this.root,genesisItem:h[0],expectedGenesis:h[1],approval:this.pins.purpose==="create"?"creator":"pending",...this.displayName===void 0?{}:{displayName:this.displayName}}),await this.hashChecked(m,e.signal)}return{encrypted:o,value:{commit:f===null?null:new Uint8Array(f),metadata:m}}}catch{throw Oe()}finally{t?.fill(0)}}async write(e,t,i){let o=null,s=null;try{if(this.check(i.signal),o=fe(new Map([[0,2],[1,this.keys.map(l=>new Uint8Array(l))],[2,e.commit],[3,e.metadata===null?null:[e.metadata.genesisItem,e.metadata.expectedGenesis]],[4,this.displayName??null]])),o.length>tg)throw Oe();let r=crypto.getRandomValues(new Uint8Array(12)),a=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:r,additionalData:new Uint8Array(this.aad),tagLength:128},this.key,new Uint8Array(o)));this.check(i.signal),s=fe(new Map([[0,1],[1,r],[2,a]]));let c=await this.store.compareAndSet(t,s,i);if(this.check(i.signal),c!==!0)throw Oe()}catch{throw Oe()}finally{o?.fill(0),s?.fill(0)}}async pendingCreate(e,t){if(this.check(t.signal),this.checkReceipt(e),this.pins.purpose!=="create"||e.collection!==this.pins.collection||e.displayName!==this.displayName)throw Oe();let i=await this.read(t);this.check(t.signal),!i&&await this.write({commit:null,metadata:null},null,t)}async privateEnrolPending(e,t){this.check(t.signal);let i=this.commit(e),o=this.markerCopy(e,i);if(o.acknowledged)throw Oe();let s=await this.read(t);if(this.check(t.signal),s&&!ba(s.value.commit,i))throw Oe();try{await this.noise.privateEnrolPending(o,t),this.check(t.signal)}catch{throw Oe()}s||await this.write({commit:i,metadata:null},null,t)}async completed(e,t){this.check(t.signal);let i=this.copy(e);await this.hashChecked(i,t.signal);let o=await this.read(t);if(this.check(t.signal),!o)throw Oe();if(o.value.metadata){if(!ba(o.value.metadata.genesisItem,i.genesisItem)||o.value.metadata.expectedGenesis!==i.expectedGenesis)throw Oe();return}await this.write({...o.value,metadata:i},o.encrypted,t)}async privateEnrolAcknowledged(e,t){this.check(t.signal);let i=this.commit(e),o=this.markerCopy(e,i),s=await this.read(t);if(this.check(t.signal),!s?.value.metadata||!ba(s.value.commit,i))throw Oe();try{await this.noise.privateEnrolAcknowledged(o,t),this.check(t.signal)}catch{throw Oe()}}async restoredCompletion(e){let t=await this.read(e);return this.check(e.signal),t?.value.metadata?this.copy(t.value.metadata):null}}});function p0(n){if(!(n instanceof Uint8Array)||!n.length||n.length>a0)throw vn();return new Uint8Array(n)}var ig,qE,vn,c0,rg,TE=C(()=>{"use strict";Jt();ve();l0();ig="public-outcome",qE="operation",vn=()=>new Error("app private bootstrap store unavailable"),c0=(n,e)=>n===null||e===null?n===e:n.length===e.length&&n.every((t,i)=>t===e[i]);rg=class n{constructor(e,t,i,o,s){this.db=e;this.source=t;this.pins=i;this.root=o;this.origin=s;e.onversionchange=()=>this.close()}db;source;pins;root;origin;closed=!1;static async open(e){try{return await this.openChecked(e)}catch{throw vn()}}static async openChecked(e){let{source:t,signal:i}=e,o=Object.freeze({accountId:t.accountId,connectorId:t.connectorId,deviceId:t.deviceId,installationId:t.installationId,collection:t.collection,purpose:t.purpose,cpOrigin:t.cpOrigin,logOrigin:t.logOrigin}),s=[o.accountId,o.connectorId,o.deviceId,o.installationId,o.collection];for(let d of s)if(N(d).every(u=>u===0))throw vn();if(!(t.rootPublicKey instanceof Uint8Array)||t.rootPublicKey.length!==32||t.rootPublicKey.every(d=>d===0))throw vn();let r=new Uint8Array(t.rootPublicKey);if(!ut(e.origin)||Et()!==e.origin||!["fresh","existing"].includes(e.mode)||!["create","enrol"].includes(o.purpose)||!globalThis.indexedDB)throw vn();let a=()=>{try{return!i.aborted&&t.isCurrent()===!0&&t.approvalMode==="password-ak1"&&t.rootPublicKey instanceof Uint8Array&&c0(t.rootPublicKey,r)&&Object.entries(o).every(([d,u])=>t[d]===u)}catch{return!1}};if(!a())throw vn();let c=`mdbase.app.private-bootstrap.v1.${s.map(d=>d.toLowerCase()).join(".")}.${o.purpose}`,l=await new Promise((d,u)=>{let f=indexedDB.open(c,1),h=!1,m=()=>{h=!0,u(vn())},w=()=>i.removeEventListener("abort",m);i.addEventListener("abort",m,{once:!0}),f.onblocked=m,f.onupgradeneeded=()=>{if(h||!a()||e.mode!=="fresh"||f.result.objectStoreNames.length!==0){f.transaction?.abort();return}f.result.createObjectStore(ig)},f.onerror=()=>{w(),u(vn())},f.onsuccess=()=>{if(w(),h||!a()||f.result.objectStoreNames.length!==1||!f.result.objectStoreNames.contains(ig)){f.result.close(),u(vn());return}d(f.result)}}),p=new n(l,t,o,r,e.origin);try{let d=await p.read({signal:i});if(e.mode==="fresh"!=(d===null))throw vn();return d?.fill(0),p.check(i),p}catch{throw p.close(),vn()}}check(e){try{if(this.closed||e.aborted||Et()!==this.origin||this.source.isCurrent()!==!0||this.source.approvalMode!=="password-ak1"||!(this.source.rootPublicKey instanceof Uint8Array)||!c0(this.source.rootPublicKey,this.root)||Object.entries(this.pins).some(([t,i])=>this.source[t]!==i))throw vn()}catch{throw vn()}}async read(e){this.check(e.signal);let t=await this.transaction("readonly",e.signal,null,null);return this.check(e.signal),t}async compareAndSet(e,t,i){this.check(i.signal);let o=null,s=null;try{o=e===null?null:p0(e),s=p0(t);let r=await this.transaction("readwrite",i.signal,o,s);return this.check(i.signal),r===!0}finally{o?.fill(0),s?.fill(0)}}transaction(e,t,i,o){return new Promise((s,r)=>{this.check(t);let a=this.db.transaction(ig,e,{durability:"strict"}),c=a.objectStore(ig),l=null,p=!1,d=()=>{p=!0;try{a.abort()}catch{}},u=()=>t.removeEventListener("abort",d);t.addEventListener("abort",d,{once:!0}),a.onabort=a.onerror=()=>{u(),l instanceof Uint8Array&&l.fill(0),r(vn())},a.oncomplete=()=>{u();try{if(this.check(t),p)throw vn();s(l)}catch{l instanceof Uint8Array&&l.fill(0),r(vn())}};let f=c.get(qE);f.onsuccess=()=>{let h=null;try{this.check(t),h=f.result===void 0?null:p0(f.result),e==="readonly"?(l=h,h=null):(l=c0(h,i),l===!0&&o!==null&&c.put(new Uint8Array(o),qE))}catch{d()}finally{h?.fill(0)}}})}close(){this.closed||(this.closed=!0,this.db.close())}}});var ME,LE=C(()=>{ME=Uint8Array.from([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9])});function ms(n,e,t,i,o,s){let r=o[s],a=o[s+1],c=H[2*n],l=H[2*n+1],p=H[2*e],d=H[2*e+1],u=H[2*t],f=H[2*t+1],h=H[2*i],m=H[2*i+1],w=op(c,p,r);l=sp(w,l,d,a),c=w|0;let b=m^l,g=h^c;m=eS(b,g),h=tS(b,g),{h:f,l:u}=ni(f,u,m,h),b=d^f,g=p^u,d=hr(b,g,24),p=mr(b,g,24),H[2*n]=c,H[2*n+1]=l,H[2*e]=p,H[2*e+1]=d,H[2*t]=u,H[2*t+1]=f,H[2*i]=h,H[2*i+1]=m}function ys(n,e,t,i,o,s){let r=o[s],a=o[s+1],c=H[2*n],l=H[2*n+1],p=H[2*e],d=H[2*e+1],u=H[2*t],f=H[2*t+1],h=H[2*i],m=H[2*i+1],w=op(c,p,r);l=sp(w,l,d,a),c=w|0;let b=m^l,g=h^c;m=hr(b,g,16),h=mr(b,g,16),{h:f,l:u}=ni(f,u,m,h),b=d^f,g=p^u,d=xs(b,g,63),p=Is(b,g,63),H[2*n]=c,H[2*n+1]=l,H[2*e]=p,H[2*e+1]=d,H[2*t]=u,H[2*t+1]=f,H[2*i]=h,H[2*i+1]=m}function K8(n,e={},t,i,o){if(xn(t),n<=0||n>t)throw new Error('"dkLen" must be 1..'+t+", got "+n);let{key:s,salt:r,personalization:a}=e;if(s!==void 0&&(s.length<1||s.length>t))throw new Error('"key" expected to be undefined or of length=1..'+t);r!==void 0&&mt(r,i,"salt"),a!==void 0&&mt(a,o,"personalization")}var Bt,H,d0,u0,bc,jE=C(()=>{LE();Zu();yr();Bt=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),H=new Uint32Array(32);d0=class{buffer;buffer32;finished=!1;destroyed=!1;length=0;pos=0;blockLen;outputLen;canXOF=!1;constructor(e,t){xn(e),xn(t),this.blockLen=e,this.outputLen=t,this.buffer=new Uint8Array(e),this.buffer32=Ro(this.buffer)}update(e){Xr(this),mt(e);let{blockLen:t,buffer:i,buffer32:o}=this,s=e.length,r=e.byteOffset,a=e.buffer;for(let c=0;c<s;){this.pos===t&&(Di(o),this.compress(o,0,!1),Di(o),this.pos=0);let l=Math.min(t-this.pos,s-c),p=r+c;if(l===t&&!(p%4)&&c+l<s){let d=new Uint32Array(a,p,Math.floor((s-c)/4));Di(d);for(let u=0;c+t<s;u+=o.length,c+=t)this.length+=t,this.compress(d,u,!1);Di(d);continue}i.set(c===0&&l===s?e:e.subarray(c,c+l),this.pos),this.pos+=l,this.length+=l,c+=l}return this}digestInto(e){if(Xr(this),ja(e,this),e.byteOffset&3)throw new RangeError('"output" expected 4-byte aligned byteOffset, got '+e.byteOffset);let{pos:t,buffer32:i}=this;this.finished=!0,this.buffer.fill(0,t),Di(i),this.compress(i,0,!0),Di(i);let o=this.get(),s=e===this.buffer?i:Ro(e),r=Math.floor(this.outputLen/4);for(let p=0;p<r;p++)s[p]=nn(o[p]);let a=this.outputLen%4;if(!a)return;let c=r*4,l=o[r];for(let p=0;p<a;p++)e[c+p]=l>>>8*p}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let i=e.slice(0,t);return this.destroy(),i}_cloneInto(e){let{buffer:t,length:i,finished:o,destroyed:s,outputLen:r,pos:a}=this;return e||=new this.constructor({dkLen:r}),e.set(...this.get()),e.buffer.set(t),e.destroyed=s,e.finished=o,e.length=i,e.pos=a,e.outputLen=r,e}clone(){return this._cloneInto()}},u0=class extends d0{v0l=Bt[0]|0;v0h=Bt[1]|0;v1l=Bt[2]|0;v1h=Bt[3]|0;v2l=Bt[4]|0;v2h=Bt[5]|0;v3l=Bt[6]|0;v3h=Bt[7]|0;v4l=Bt[8]|0;v4h=Bt[9]|0;v5l=Bt[10]|0;v5h=Bt[11]|0;v6l=Bt[12]|0;v6h=Bt[13]|0;v7l=Bt[14]|0;v7h=Bt[15]|0;constructor(e={}){e=cp({},e);let t=e.dkLen===void 0?64:e.dkLen;super(128,t),K8(t,e,64,16,16);let{key:i,personalization:o,salt:s}=e,r=0;if(i!==void 0&&(mt(i,void 0,"key"),r=i.length),this.v0l^=this.outputLen|r<<8|65536|1<<24,s!==void 0){mt(s,void 0,"salt");let a=Ro(Tb(s));this.v4l^=nn(a[0]),this.v4h^=nn(a[1]),this.v5l^=nn(a[2]),this.v5h^=nn(a[3])}if(o!==void 0){mt(o,void 0,"personalization");let a=Ro(Tb(o));this.v6l^=nn(a[0]),this.v6h^=nn(a[1]),this.v7l^=nn(a[2]),this.v7h^=nn(a[3])}if(i!==void 0){let a=new Uint8Array(this.blockLen);a.set(i),this.update(a),at(a)}}get(){let{v0l:e,v0h:t,v1l:i,v1h:o,v2l:s,v2h:r,v3l:a,v3h:c,v4l:l,v4h:p,v5l:d,v5h:u,v6l:f,v6h:h,v7l:m,v7h:w}=this;return[e,t,i,o,s,r,a,c,l,p,d,u,f,h,m,w]}set(e,t,i,o,s,r,a,c,l,p,d,u,f,h,m,w){this.v0l=e|0,this.v0h=t|0,this.v1l=i|0,this.v1h=o|0,this.v2l=s|0,this.v2h=r|0,this.v3l=a|0,this.v3h=c|0,this.v4l=l|0,this.v4h=p|0,this.v5l=d|0,this.v5h=u|0,this.v6l=f|0,this.v6h=h|0,this.v7l=m|0,this.v7h=w|0}compress(e,t,i){let{v0l:o,v0h:s,v1l:r,v1h:a,v2l:c,v2h:l,v3l:p,v3h:d,v4l:u,v4h:f,v5l:h,v5h:m,v6l:w,v6h:b,v7l:g,v7h:y}=this;H[0]=o,H[1]=s,H[2]=r,H[3]=a,H[4]=c,H[5]=l,H[6]=p,H[7]=d,H[8]=u,H[9]=f,H[10]=h,H[11]=m,H[12]=w,H[13]=b,H[14]=g,H[15]=y,H.set(Bt,16);let v=Rb(this.length),_=Cb(this.length);H[24]=Bt[8]^v,H[25]=Bt[9]^_,i&&(H[28]=~H[28],H[29]=~H[29]);let k=0,S=ME;for(let x=0;x<12;x++)ms(0,4,8,12,e,t+2*S[k++]),ys(0,4,8,12,e,t+2*S[k++]),ms(1,5,9,13,e,t+2*S[k++]),ys(1,5,9,13,e,t+2*S[k++]),ms(2,6,10,14,e,t+2*S[k++]),ys(2,6,10,14,e,t+2*S[k++]),ms(3,7,11,15,e,t+2*S[k++]),ys(3,7,11,15,e,t+2*S[k++]),ms(0,5,10,15,e,t+2*S[k++]),ys(0,5,10,15,e,t+2*S[k++]),ms(1,6,11,12,e,t+2*S[k++]),ys(1,6,11,12,e,t+2*S[k++]),ms(2,7,8,13,e,t+2*S[k++]),ys(2,7,8,13,e,t+2*S[k++]),ms(3,4,9,14,e,t+2*S[k++]),ys(3,4,9,14,e,t+2*S[k++]);this.v0l^=H[0]^H[16],this.v0h^=H[1]^H[17],this.v1l^=H[2]^H[18],this.v1h^=H[3]^H[19],this.v2l^=H[4]^H[20],this.v2h^=H[5]^H[21],this.v3l^=H[6]^H[22],this.v3h^=H[7]^H[23],this.v4l^=H[8]^H[24],this.v4h^=H[9]^H[25],this.v5l^=H[10]^H[26],this.v5h^=H[11]^H[27],this.v6l^=H[12]^H[28],this.v6h^=H[13]^H[29],this.v7l^=H[14]^H[30],this.v7h^=H[15]^H[31],at(H)}destroy(){this.destroyed=!0,at(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},bc=pp(n=>new u0(n))});function gs(n,e,t,i){let o=jt[2*n],s=jt[2*n+1],r=jt[2*e],a=jt[2*e+1],c=jt[2*t],l=jt[2*t+1],p=jt[2*i],d=jt[2*i+1],u=0,f=0,h=0,m=0,w=0;u=Math.imul(o,r),f=((o>>>0)*(r>>>0)-(u>>>0))/4294967296+.5|0,h=(o>>>0)+(r>>>0)+(u<<1>>>0),s=s+a+(f<<1|u>>>31)+(h/4294967296|0)|0,o=h|0,m=d^s,w=p^o,d=w,p=m,u=Math.imul(c,p),f=((c>>>0)*(p>>>0)-(u>>>0))/4294967296+.5|0,h=(c>>>0)+(p>>>0)+(u<<1>>>0),l=l+d+(f<<1|u>>>31)+(h/4294967296|0)|0,c=h|0,m=a^l,w=r^c,a=m>>>24|w<<8,r=m<<8|w>>>24,u=Math.imul(o,r),f=((o>>>0)*(r>>>0)-(u>>>0))/4294967296+.5|0,h=(o>>>0)+(r>>>0)+(u<<1>>>0),s=s+a+(f<<1|u>>>31)+(h/4294967296|0)|0,o=h|0,m=d^s,w=p^o,d=m>>>16|w<<16,p=m<<16|w>>>16,u=Math.imul(c,p),f=((c>>>0)*(p>>>0)-(u>>>0))/4294967296+.5|0,h=(c>>>0)+(p>>>0)+(u<<1>>>0),l=l+d+(f<<1|u>>>31)+(h/4294967296|0)|0,c=h|0,m=a^l,w=r^c,a=m<<1|w>>>31,r=m>>>31|w<<1,jt[2*n]=o,jt[2*n+1]=s,jt[2*e]=r,jt[2*e+1]=a,jt[2*t]=c,jt[2*t+1]=l,jt[2*i]=p,jt[2*i+1]=d}function NE(n,e,t,i,o,s,r,a,c,l,p,d,u,f,h,m){gs(n,o,c,u),gs(e,s,l,f),gs(t,r,p,h),gs(i,a,d,m),gs(n,s,p,m),gs(e,r,d,u),gs(t,a,c,f),gs(i,o,l,h)}function lu(n,e,t,i,o){if(o)for(let s=0;s<256;s++){let r=n[e+s]^n[t+s];jt[s]=r,n[i+s]^=r}else for(let s=0;s<256;s++){let r=n[e+s]^n[t+s];jt[s]=r,n[i+s]=r}for(let s=0;s<128;s+=16)NE(s,s+1,s+2,s+3,s+4,s+5,s+6,s+7,s+8,s+9,s+10,s+11,s+12,s+13,s+14,s+15);for(let s=0;s<16;s+=2)NE(s,s+1,s+16,s+17,s+32,s+33,s+48,s+49,s+64,s+65,s+80,s+81,s+96,s+97,s+112,s+113);for(let s=0;s<256;s++)n[i+s]^=jt[s];at(jt)}function f0(n,e){let t=lp(n),i=new Uint32Array(1),o=lp(i);if(i[0]=nn(e),e<=64)return bc.create({dkLen:e}).update(o).update(t).digest();let s=new Uint8Array(e),r=bc.create({}).update(o).update(t).digest(),a=0;for(s.set(r.subarray(0,32)),a+=32;e-a>64;a+=32){let c=bc.create({}).update(r);c.digestInto(r),c.destroy(),s.set(r.subarray(0,32),a)}return s.set(bc(r,{dkLen:e-a}),a),at(r,i),s}function W8(n,e,t,i,o,s,r=!1){let a;n===0?e===0?a=o-1:r?a=e*i+o-1:a=e*i+(o==0?-1:0):r?a=t-i+o-1:a=t-i+(o==0?-1:0);let c=n!==0&&e!==cu-1?(e+1)*i:0,l=Math.imul(s,s),p=((s>>>0)*(s>>>0)-(l>>>0))/4294967296+.5|0,d=Math.imul(a,p),u=((a>>>0)*(p>>>0)-(d>>>0))/4294967296+.5|0,f=a-1-u;return(c+f)%t}function bs(n){return Number.isSafeInteger(n)&&n>=0&&n<H8}function Y8(n={}){n=cp({},n);let e={t:3,m:DE,p:1,version:19,dkLen:32,maxmem:G8,asyncTick:10};for(let[l,p]of Object.entries(n))p!==void 0&&(e[l]=p);let{dkLen:t,p:i,m:o,t:s,version:r,onProgress:a,asyncTick:c}=e;if(!bs(t)||t<4)throw new Error('"dkLen" must be 4..');if(!bs(i)||i<1||i>=Math.pow(2,24))throw new Error('"p" must be 1..2^24');if(!bs(o))throw new Error('"m" must be 0..2^32');if(!bs(s)||s<1)throw new Error('"t" (iterations) must be 1..2^32');if(a!==void 0&&typeof a!="function")throw new Error('"onProgress" must be a function');if(xn(c,"asyncTick"),!bs(o)||o<8*i)throw new Error('"m" (memory) must be at least 8*p bytes');if(r!==16&&r!==19)throw new Error('"version" must be 0x10 or 0x13, got '+r);return e}function J8(n,e,t,i){let o=[],s=new Uint32Array(1),r=lp(s),a,c,l=!1,p=(d,u)=>(typeof d=="string"&&o.push(u),u);try{let d=p(n,nf(n,"password")),u=p(e,nf(e,"salt"));if(!bs(d.length))throw new Error('"password" must be less of length 1..4Gb');if(!bs(u.length)||u.length<8)throw new Error('"salt" must be of length 8..4Gb');if(!Object.values(og).includes(t))throw new Error('"type" was invalid');let{p:f,dkLen:h,m,t:w,version:b,key:g,personalization:y,maxmem:v,onProgress:_,asyncTick:k}=Y8(i),S=g;g=p(S,UE(S,"key"));let x=y;y=p(x,UE(x,"personalization")),a=bc.create();for(let P of[f,h,m,w,b,t])s[0]=nn(P),a.update(r);for(let P of[d,u,g,y])s[0]=nn(P.length),a.update(r).update(P);return c=new Uint32Array(18),a.digestInto(lp(c)),l=!0,{H0:c,p:f,dkLen:h,m,t:w,version:b,maxmem:v,onProgress:_,asyncTick:k}}finally{a&&a.destroy(),at(s,...o),!l&&c&&at(c)}}function X8(n,e,t,i){let{H0:o,p:s,dkLen:r,m:a,t:c,version:l,maxmem:p,onProgress:d,asyncTick:u}=J8(n,e,t,i);try{let f=s,h=4*s*Math.floor(a/(cu*s)),m=Math.floor(h/s),w=Math.floor(m/cu),b=h*1024;if(!bs(p))throw new Error('"maxmem" expected <2**32, got '+p);if(b>p)throw new Error('"maxmem" limit was hit: memUsed(mP*1024)='+b+", maxmem="+p);let g=new Uint32Array(b/4);for(let v=0;v<s;v++){let _=256*m*v;o[17]=nn(v),o[16]=nn(0),g.set(Di(Ro(f0(o,1024))),_),o[16]=nn(1),g.set(Di(Ro(f0(o,1024))),_+256)}let y=()=>{};if(d){let v=c*cu*s*w-2*s,_=Math.max(Math.floor(v/1e4),1),k=0;y=()=>{k++,d&&(!(k%_)||k===v)&&d(k/v)}}return{type:t,mP:h,p:s,t:c,version:l,B:g,laneLen:m,lanes:f,segmentLen:w,dkLen:r,perBlock:y,asyncTick:u}}finally{at(o)}}function Z8(n,e,t,i){let o=new Uint32Array(256);for(let r=0;r<e;r++)for(let a=0;a<256;a++)o[a]^=n[256*(t*r+t-1)+a];let s=f0(Di(o),i);return at(n,o),s}function*Q8(n,e){let{type:t,mP:i,p:o,t:s,version:r,B:a,laneLen:c,lanes:l,segmentLen:p,perBlock:d}=n;e[262]=i,e[264]=s,e[266]=t;for(let u=0;u<s;u++){let f=u!==0&&r===19;e[256]=u;for(let h=0;h<cu;h++){e[260]=h;let m=t==og.Argon2i||t==og.Argon2id&&u===0&&h<2;for(let w=0;w<o;w++){e[258]=w,e[268]=0;let b=0;u===0&&h===0&&(b=2,m&&(e[268]++,lu(e,256,2*256,0,!1),lu(e,0,2*256,0,!1)));let g=w*c+h*p+b;for(let y=b;y<p;y++,g++){d();let v=g%c?g-1:g+c-1,_,k;if(m){let I=y%128;I===0&&(e[268]++,lu(e,256,2*256,0,!1),lu(e,0,2*256,0,!1)),_=e[2*I],k=e[2*I+1]}else{let I=256*v;_=a[I],k=a[I+1]}let S=u===0&&h===0?w:k%l,x=W8(u,h,c,p,y,_,S==w),P=c*S+x;lu(a,256*v,256*P,g*256,f),yield}}}}at(e)}async function eD(n,e,t,i){let o=X8(e,t,n,i),s=new Uint32Array(3*256),r=Q8(o,s),a=()=>at(s,o.B),c=Date.now();for(;!r.next().done;){let l=Date.now()-c;l>=0&&l<o.asyncTick||(await uS(a),c=Date.now())}return Z8(o.B,o.p,o.laneLen,o.dkLen)}var og,cu,UE,jt,H8,DE,G8,zE,$E=C(()=>{jE();yr();og={Argon2d:0,Argon2i:1,Argon2id:2},cu=4,UE=(n,e="")=>n===void 0?Uint8Array.of():nf(n,e),jt=new Uint32Array(256);H8=Math.pow(2,32),DE=1024**2,G8=DE*1024;zE=(n,e,t={})=>eD(og.Argon2id,n,e,t)});function nD(n,e,t,i=32,o){ap(n),xn(i,"length"),mt(e,void 0,"prk");let s=n.outputLen;if(e.length<s)throw new Error('"prk" must be at least HashLen octets');if(i>255*s)throw new Error("Length must be <= 255*HashLen");let r=Math.ceil(i/s);if(t===void 0?t=tD:mt(t,void 0,"info"),!r)return o&&at(e),new Uint8Array;let a=o&&r===1?e:new Uint8Array(r*s),{iHash:c,oHash:l}=ca.create(n,e),p=o?e:new Uint8Array(s),d=r>1?o?.iHash||n.create():void 0;for(let f=0;f<r-1;f++){pu[0]=f+1;let h=c._cloneInto(d);f&&h.update(p),h.update(t).update(pu).digestInto(p),l._cloneInto(d).update(p).digestInto(p),a.set(p,s*f)}if(pu[0]=r,r>1&&c.update(p),c.update(t).update(pu).digestInto(p),l.update(p).digestInto(p),a.set(p,s*(r-1)),c.destroy(),l.destroy(),d?.destroy(),p!==a&&at(p),at(pu),i===a.length)return a;let u=a.slice(0,i);return at(a),u}var pu,tD,sg,BE=C(()=>{xA();yr();pu=Uint8Array.of(0),tD=Uint8Array.of();sg=(n,e,t,i,o)=>{ap(n),t===void 0&&(t=new Uint8Array(n.outputLen));let s=ca.create(n,t).update(e);return nD(n,s.digest(),i,o,s)}});function va(n,e){let t=wc.encode(n);if(t.length>255)throw De("internal","domain tag longer than 255 bytes");return Ze(y0(Uint8Array.of(t.length),t,e))}function y0(...n){let e=0;for(let o of n)e+=o.length;let t=new Uint8Array(e),i=0;for(let o of n)t.set(o,i),i+=o.length;return t}function g0(n,e){if(n.length!==e.length)return!1;let t=0;for(let i=0;i<n.length;i++)t|=n[i]^e[i];return t===0}function wt(...n){for(let e of n)e.fill(0)}function Xn(n){if(!iD.test(n))throw De("internal","not a UUID");let e=n.replace(/-/g,"").toLowerCase(),t=new Uint8Array(16);for(let i=0;i<16;i++)t[i]=parseInt(e.slice(i*2,i*2+2),16);return t}function rD(n){let e="";for(let t of n)e+=t.toString(16).padStart(2,"0");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function FE(n=ag){let e=n(ar);if(e.length!==ar)throw De("internal","entropy returned the wrong length");return e}function KE(n){return va("mdbase/v1/recovery-key-check",n).subarray(0,VE)}function WE(n){if(n.length!==ar)throw De("internal","recovery secret is 32 bytes");let e=y0(n,KE(n)),t="",i=0,o=0;for(let s of e){for(i=i<<8|s,o+=8;o>=5;)t+=h0[i>>>o-5&31],o-=5;i&=(1<<o)-1}return o>0&&(t+=h0[i<<5-o&31]),wt(e),[m0,...t.match(/.{1,5}/g)].join("-")}function uu(n){if(typeof n!="string"||n.length>4096)throw De("invalid_recovery_key","Not a recovery key.","wrong_length");let e=n.toUpperCase().replace(/[\s-]/g,"").replace(/O/g,"0").replace(/[IL]/g,"1");if(!e.startsWith(m0))throw De("invalid_recovery_key","A recovery key starts with MDB1.","wrong_prefix");if(e=e.slice(m0.length),e.length!==oD)throw De("invalid_recovery_key","A recovery key has 55 characters after MDB1.","wrong_length");let t=new Uint8Array(ar+VE),i=0,o=0,s=0;for(let c of e){let l=h0.indexOf(c);if(l<0)throw De("invalid_recovery_key","A recovery key uses only Crockford base32 characters.","bad_character");i=i<<5|l,o+=5,o>=8&&(s<t.length&&(t[s++]=i>>>o-8&255),o-=8),i&=(1<<o)-1}if(s!==t.length||i!==0)throw De("invalid_recovery_key","Not a recovery key.","bad_character");let r=t.slice(0,ar),a=g0(KE(r),t.subarray(ar));if(wt(t),!a)throw wt(r),De("invalid_recovery_key","The recovery key has a typo (check failed).","checksum");return r}function HE(n,e){if(n.length!==ar)throw De("internal","recovery secret is 32 bytes");let t=Xn(e),i=sg(Ze,n,t,wc.encode("mdbase/v1/recovery-sign"),32),o=sg(Ze,n,t,wc.encode("mdbase/v1/recovery-kem"),32),s=eu.getPublicKey(i),r=or.getPublicKey(o);return{device:rD(va("mdbase/v1/recovery-id",y0(t,s)).subarray(0,16)),signSeed:i,signPk:s,kemSk:o,kemPk:r,noisePk:new Uint8Array(32)}}function GE(n,e){return eu.sign(e,n.signSeed)}function YE(n){wt(n.signSeed,n.kemSk)}function JE(n,e){if(n.length!==ar)throw De("internal","recovery secret is 32 bytes");let t=sg(Ze,n,Xn(e),wc.encode("mdbase/v1/account-key-proof"),32);return{seed:t,pk:eu.getPublicKey(t)}}function sD(n,e,t){if(!Number.isSafeInteger(t)||t<0)throw De("internal","expected_version");return va("mdbase/v1/account-key-rewrap",fe([Xn(n),Ze(e),t]))}function XE(n,e,t,i){return eu.sign(sD(e,t,i),n.seed)}function fu(n){return va("mdbase/v1/account-key-id",n)}function fD(n){if(!(wa(n.mKib)&&wa(n.t)&&wa(n.p)&&n.mKib>=cD&&n.mKib<=QE&&n.t>=pD&&n.t<=dD&&n.p>=1&&n.p<=uD&&n.mKib>=8*n.p&&n.salt instanceof Uint8Array&&n.salt.length===16))throw De("params","Unsupported key derivation parameters.")}function e2(n){return[ZE,n.mKib,n.t,n.p,n.salt]}function hD(n){if(!Array.isArray(n)||n.length!==5)throw De("encoding","Not an account key bundle.");let[e,t,i,o,s]=n;if(!wa(e)||!wa(t)||!wa(i)||!wa(o)||!(s instanceof Uint8Array)||s.length!==16)throw De("encoding","Not an account key bundle.");if(e!==ZE||t>4294967295||i>4294967295||o>4294967295)throw De("params","Unsupported key derivation parameters.");return{mKib:t,t:i,p:o,salt:s}}function w0(n){return fe($g([[0,b0],[1,e2(n.kdf)],[2,n.nonce],[3,n.ct],[4,n.keyId]]))}function t2(n){if(!(n instanceof Uint8Array)||n.length>aD)throw De("encoding","Not an account key bundle.");let e;try{e=we(n)}catch{throw De("encoding","Not an account key bundle.")}if(!(e instanceof Map)||e.size!==5||[...e.keys()].join()!=="0,1,2,3,4")throw De("encoding","Not an account key bundle.");let t=e,i=t.get(2),o=t.get(3),s=t.get(4);if(t.get(0)!==b0||!(i instanceof Uint8Array)||i.length!==24||!(o instanceof Uint8Array)||o.length!==48||!(s instanceof Uint8Array)||s.length!==32)throw De("encoding","Not an account key bundle.");let r={kdf:hD(t.get(1)),nonce:i,ct:o,keyId:s};if(!Bg(w0(r),n))throw De("encoding","Not an account key bundle.");return r}function n2(n){if(typeof n!="string")throw De("weak_password","The password is required.","too_short");if(wc.encode(n).length>du)throw De("weak_password","The password is too long.","too_long");let e=n.normalize("NFKC"),t=wc.encode(e);if(t.length>du)throw De("weak_password","The password is too long.","too_long");if([...e].length<vc)throw wt(t),De("weak_password",`The password needs at least ${vc} characters.`,"too_short");return t}function _a(n){wt(n2(n))}async function i2(n,e,t,i){fD(e);let o=n2(n);try{let s=await t(o,e.salt,{mKib:e.mKib,t:e.t,p:e.p},i);if(!(s instanceof Uint8Array)||s.length!==32)throw De("internal","The KDF runner returned the wrong length.");return s}finally{wt(o)}}function r2(n,e,t){return va("mdbase/v1/account-key-bundle",fe([b0,Xn(n),e,e2(t)]))}async function cg(n,e,t,i={}){if(n.length!==ar)throw De("internal","recovery secret is 32 bytes");_a(e);let o=i.entropy??ag,s=i.kdf??{...lD,salt:o(16)},r=i.nonce??o(24);if(r.length!==24)throw De("internal","nonce is 24 bytes");let a=fu(n),c=await i2(e,s,i.argon2id??lg,i.signal);try{let l=pA(c,r,r2(t,a,s)).encrypt(n);return{kdf:s,nonce:r,ct:l,keyId:a}}finally{wt(c)}}async function o2(n,e,t,i={}){let o=await i2(e,n.kdf,i.argon2id??lg,i.signal),s;try{s=pA(o,n.nonce,r2(t,n.keyId,n.kdf)).decrypt(n.ct)}catch{throw De("wrong_secret","Wrong password.")}finally{wt(o)}if(s.length!==ar||!g0(fu(s),n.keyId))throw wt(s),De("wrong_secret","Wrong password.");return s}function hu(n,e){if(n.length!==ar||!g0(fu(n),e.keyId))throw De("wrong_secret","This recovery key belongs to a different account key.")}var Ve,De,wc,ag,iD,h0,m0,ar,VE,oD,b0,ZE,aD,vc,du,lD,cD,QE,pD,dD,uD,wa,lg,pg=C(()=>{"use strict";dA();qy();$E();BE();gr();Je();Ve=class extends Error{code;reason;retryAfterMs;constructor(e,t,i={}){super(t),this.name="AccountKeyError",this.code=e,i.reason!==void 0&&(this.reason=i.reason),i.retryAfterMs!==void 0&&(this.retryAfterMs=i.retryAfterMs)}},De=(n,e,t)=>new Ve(n,e,t===void 0?{}:{reason:t}),wc=new TextEncoder;ag=n=>crypto.getRandomValues(new Uint8Array(n)),iD=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;h0="0123456789ABCDEFGHJKMNPQRSTVWXYZ",m0="MDB1",ar=32,VE=2,oD=55;b0=1,ZE=1,aD=512,vc=12,du=1024,lD={mKib:19456,t:3,p:1},cD=19456,QE=24576,pD=2,dD=10,uD=4;wa=n=>typeof n=="number"&&Number.isSafeInteger(n)&&n>=0;lg=async(n,e,t,i)=>{let o=()=>De("cancelled","Key derivation cancelled.");if(i?.aborted)throw o();try{return await zE(n,e,{t:t.t,m:t.mKib,p:t.p,dkLen:32,version:19,maxmem:QE*1024+(1<<20),asyncTick:20,onProgress:()=>{if(i?.aborted)throw o()}})}catch(s){throw s instanceof Ve?s:De("params","Key derivation failed.")}}});function s2(n){if(n.length<3)return!1;let e=[...n].reverse().join("");return[l2,...yD].some(t=>t.includes(n)||t.includes(e))}function gD(n){for(let e=1;e<=n.length/2;e++)if(n.length%e===0&&n.slice(0,e).repeat(n.length/e)===n)return n.slice(0,e);return null}function bD(n){let e=[];for(let t of n){let i=/\p{L}/u.test(t)?"letter":/\p{Nd}/u.test(t)?"digit":t.charCodeAt(0)<128?"symbol":"other",o=e[e.length-1];o&&o.kind===i?o.text+=t:e.push({kind:i,text:t})}return e}function c2(n,e,t,i){let o=e.toLowerCase();if(t.has(o))return i.add("repeat"),1;t.add(o);let s=gD(o);if(s&&s.length<o.length)return i.add("repeat"),c2(n,s,new Set,i)+lr(o.length/s.length);if(n==="letter"){let r=[...o].map(c=>a2[c]??c).join("");if(mu.has(o)||mu.has(r))return i.add("common"),lr(mu.size)+1;if(s2(o))return i.add("sequence"),lr(l2.length)+lr(o.length)+1;let a=2.5*[...o].length;return o!==e&&e.toUpperCase()!==e?a+=1+lr([...e].length):e.toUpperCase()===e&&e.length>1&&(a+=1),a}return n==="digit"?mD.has(o)||s2(o)?(i.add("sequence"),4):/^(19|20)\d\d$/.test(o)||/^\d{6}$/.test(o)||/^\d{8}$/.test(o)?(i.add("date"),6):3.32*o.length:n==="symbol"?[...e].reduce((r,a)=>r+(a===" "?1:"!?.,*#-_".includes(a)?2:5),0):7*[...e].length}function wD(n){let e=[...n],t=e.map(r=>a2[r.toLowerCase()]??r.toLowerCase()),i=[],o="",s=0;for(;s<e.length;){let r=null;for(let a=Math.min(24,e.length-s);a>=4;a--){let c=t.slice(s,s+a).join("");if(mu.has(c)){r=c;break}}r?(o&&i.push({word:null,text:o}),o="",i.push({word:r,text:e.slice(s,s+[...r].length).join("")}),s+=[...r].length):(o+=e[s],s++)}return o&&i.push({word:null,text:o}),i}function yu(n){typeof n!="string"&&(n="");let e=new TextEncoder().encode(n).length,t=n.normalize("NFKC"),i=[...t].length,o=new TextEncoder().encode(t).length,s=new Set,r=new Set,a=0,c=0,l=new Set;for(let h of wD(t)){if(h.word){s.add("common"),c++,l.add("word");let m=h.text.toLowerCase();a+=r.has(h.word)?1:lr(mu.size)+1+(m!==h.text?1:0)+(m!==h.word?1:0),r.add(h.word);continue}for(let m of bD(h.text))c++,l.add(m.kind),a+=c2(m.kind,m.text,r,s)}a+=Math.max(0,l.size-1)+lr(Math.max(1,c));let p=a<lr(1e3)?0:a<lr(1e6)?1:a<lr(1e8)?2:a<lr(1e10)?3:4,d=[],u=e>du||o>du;i<vc&&d.push(`Use at least ${vc} characters.`),u&&d.push("The password is too long."),s.has("common")&&d.push("Avoid common words and passwords."),s.has("sequence")&&d.push("Avoid sequences like abcd, 1234 or qwerty."),s.has("repeat")&&d.push("Avoid repeated characters or words."),s.has("date")&&d.push("Avoid years and dates."),p<3&&d.length===0&&d.push("Add another word or two; uncommon words are best.");let f=p>=3&&i>=vc&&!u;return{score:p,acceptable:f,feedback:f?[]:d,bits:Math.round(a*10)/10}}var mu,mD,a2,l2,yD,lr,p2=C(()=>{"use strict";pg();mu=new Set(["password","passwort","passw0rd","letmein","welcome","admin","administrator","login","master","monkey","dragon","football","baseball","soccer","hockey","qwerty","qwertyuiop","asdfgh","asdfghjkl","zxcvbn","zxcvbnm","azerty","iloveyou","sunshine","princess","shadow","superman","batman","michael","jennifer","jessica","charlie","thomas","trustno1","abc","abcd","abcdef","abcdefg","abcdefgh","secret","freedom","whatever","starwars","pokemon","computer","internet","hello","mustang","ginger","cheese","summer","winter","spring","autumn","flower","killer","hunter","ranger","buster","soccer","tigger","pepper","jordan","harley","robert","matthew","daniel","andrew","joshua","ashley","nicole","chelsea","amanda","orange","purple","yellow","silver","golden","cookie","chocolate","mdbase","task","note","notes","obsidian","recovery","private","encryption","unlock","account","default","changeme","temp","test","testing","guest","root","user","system","server","database","oracle","google","apple","facebook","twitter","github","linkedin","amazon","netflix","spotify","windows","android","iphone","samsung","nokia","sony","january","february","march","april","june","july","august","september","october","november","december","monday","tuesday","wednesday","thursday","friday","saturday","sunday","spider","lovely","liverpool","arsenal","chelsea","manchester","barcelona","madrid","america","london","paris","berlin","sydney","melbourne","canada"]),mD=new Set(["123","1234","12345","123456","1234567","12345678","123456789","1234567890","111111","000000","123123","654321","696969","112233","121212","131313","007","666","777","888","999","420","69"]),a2={0:"o",1:"i",3:"e",4:"a",5:"s",7:"t",8:"b","@":"a",$:"s","!":"i","+":"t"},l2="abcdefghijklmnopqrstuvwxyz0123456789",yD=["qwertyuiop","asdfghjkl","zxcvbnm","1234567890"],lr=n=>Math.log2(Math.max(1,n))});function u2(){let n=null;return{get:async()=>n?n.slice():null,set:async e=>{n&&wt(n),n=e.slice()},clear:async()=>{n&&wt(n),n=null}}}function Aa(n){if(!n||typeof n!="object"||Array.isArray(n))throw cn("not_object");return n}function d2(n){if(typeof n.complete!="boolean"||!Array.isArray(n.pending)||n.pending.length>1024)throw cn("strict_completion");let e=new Set,t=n.pending.map(i=>{let o=Aa(i);if(typeof o.collection_id!="string"||typeof o.device_id!="string"||o.revoked_at!==null&&(!Number.isSafeInteger(o.revoked_at)||o.revoked_at<0))throw cn("strict_pending");Xn(o.collection_id),Xn(o.device_id);let s=`${o.collection_id.toLowerCase()}/${o.device_id.toLowerCase()}`;if(e.has(s))throw cn("strict_pending");return e.add(s),{collectionId:o.collection_id,deviceId:o.device_id,revokedAt:o.revoked_at}});if(n.complete&&t.length!==0)throw cn("strict_completion");return{complete:n.complete,pending:t}}function go(n){if(n instanceof Ve)return n;let e=n&&typeof n=="object"?n:{},t=e.problem&&typeof e.problem=="object"?e.problem:{},i=typeof t.code=="string"?t.code:typeof e.code=="string"?e.code:"",o=typeof e.status=="number"?e.status:void 0,s=e.retryAfterMs??t.retryAfterMs??(typeof e.retry_after=="number"?e.retry_after*1e3:void 0),r=typeof s=="number"&&Number.isFinite(s)&&s>=0?s:void 0;return i==="rate_limited"||o===429?new Ve("rate_limited","Too many account key requests; try again later.",r===void 0?{}:{retryAfterMs:r}):i==="version_conflict"||i==="rotate_requires_strict"?new Ve("conflict","The account key changed; fetch the current state and retry.",{reason:i}):i==="strict_mode"?new Ve("strict_mode","The account is in strict mode."):i==="account_key_proof_required"?new Ve("wrong_secret","The account key held here is not the one registered for this bundle.",{reason:i}):i==="no_account_key"?new Ve("no_account_key","The account has no account key."):i==="cancelled"||e.name==="AbortError"?new Ve("cancelled","Account key request cancelled."):_D(i||(o===void 0?"port_failure":`http_${o}`),r)}var v0,vD,cn,_D,dg,ug,f2=C(()=>{"use strict";pg();Je();p2();v0=/^[0-9a-f]{64}$/,vD=/^([0-9a-f]{2}){1,512}$/,cn=n=>new Ve("internal","Invalid control-plane account-key response.",{reason:n}),_D=(n,e)=>new Ve("unavailable","The account key service refused or was unreachable.",e===void 0?{reason:n}:{reason:n,retryAfterMs:e});dg=n=>{if(!Number.isSafeInteger(n)||n<0)throw cn("version");return n};ug=class{lifetime=new AbortController;control;replica;secrets;argon2id;entropy;busy=Promise.resolve();last=null;constructor(e){if(this.control=e.control,this.replica=e.replica,!e.secrets)throw new Ve("internal","PrivateAccount needs a secret store (the platform keychain).");this.secrets=e.secrets,this.argon2id=e.argon2id??lg,this.entropy=e.entropy??ag,Xn(this.control.accountId)}close(){this.lifetime.signal.aborted||(this.lifetime.abort(),this.control.close?.())}passwordStrength(e){return yu(e)}async status(e={}){return this.serial(e,t=>this.readStatus(t))}get lastStatus(){return this.last}async setup(e,t){return this.serial({signal:t},async i=>{let o=yu(e);if(_a(e),!o.acceptable)throw new Ve("weak_password","The password is too weak.",{reason:"strength"});let s=await this.fetchState(i);if(s.mode==="password")throw new Ve("already_set_up","This account already has an account key; unlock it instead.");let r=FE(this.entropy);try{let a=await cg(r,e,this.control.accountId,{entropy:this.entropy,argon2id:this.argon2id,signal:i});this.check(i),await this.putBundle(r,s.version,a,i),await this.secrets.set(r);let c=WE(r),l=await this.keyAll(r,i);return l.length?{recoveryKey:c,incomplete:l}:{recoveryKey:c}}finally{wt(r)}})}async unlock(e,t){return this.serial({signal:t},async i=>{let o="recoveryKey"in e?uu(e.recoveryKey):null;try{let s=await this.requirePassword(i);o?hu(o,s.bundle):o=await o2(s.bundle,e.password,this.control.accountId,{argon2id:this.argon2id,signal:i}),this.check(i),await this.secrets.set(o);let r=await this.grantAll(o,i);return r.length?{incomplete:r}:{}}finally{o&&wt(o)}})}async changePassword(e,t){return this.serial({signal:t},async i=>{let o=yu(e);if(_a(e),!o.acceptable)throw new Ve("weak_password","The password is too weak.",{reason:"strength"});let s=await this.secrets.get();if(!s)throw new Ve("locked","Unlock the account key on this device first.");try{let r=await this.requirePassword(i);try{hu(s,r.bundle)}catch{throw new Ve("conflict","The account key on the server is not the one unlocked here; unlock again.",{reason:"key_id_changed"})}let a=await cg(s,e,this.control.accountId,{entropy:this.entropy,argon2id:this.argon2id,signal:i});this.check(i),await this.putBundle(s,r.version,a,i)}finally{wt(s)}})}async recover(e,t,i){return this.serial({signal:i},async o=>{let s=yu(t);if(_a(t),!s.acceptable)throw new Ve("weak_password","The password is too weak.",{reason:"strength"});let r=uu(e);try{let a=await this.requirePassword(o);hu(r,a.bundle);let c=await cg(r,t,this.control.accountId,{entropy:this.entropy,argon2id:this.argon2id,signal:o});this.check(o),await this.putBundle(r,a.version,c,o),await this.secrets.set(r);let l=await this.grantAll(r,o);return l.length?{incomplete:l}:{}}finally{wt(r)}})}async enableStrict(e){return this.serial({signal:e},async t=>{let i=await this.readStatus(t);if(i.mode==="strict"){i.strictComplete===!0&&await this.secrets.clear();let p=i.strictComplete===!0?!1:i.accountKeyKept;return this.last={...i,accountKeyKept:p},{version:i.version,complete:i.strictComplete,pending:i.pending,accountKeyKept:p,revocations:[],alreadyStrict:!0}}let o;try{o=await this.control.strict({expected_version:i.version},{signal:t})}catch(p){throw go(p)}let s=Aa(o);if(s.mode!=="strict"||dg(s.version)!==i.version+1||!Array.isArray(s.revocations))throw cn("strict");let r=d2(s),a=s.revocations.map(p=>{let d=Aa(p);if(typeof d.collection_id!="string"||typeof d.device_id!="string")throw cn("strict");return Xn(d.collection_id),Xn(d.device_id),{collectionId:d.collection_id,deviceId:d.device_id}});r.complete===!0&&await this.secrets.clear();let c=await this.secrets.get(),l=c!==null;return c&&wt(c),this.last={mode:"strict",version:s.version,unlocked:!1,strictComplete:r.complete,pending:r.pending,accountKeyKept:l},{version:s.version,...r,accountKeyKept:l,revocations:a,alreadyStrict:!1}})}async keyCollections(e){return this.serial({signal:e},async t=>{let i=await this.secrets.get();if(!i)throw new Ve("locked","Unlock the account key on this device first.");try{let o=await this.requirePassword(t);return hu(i,o.bundle),await this.keyAll(i,t)}finally{wt(i)}})}async lock(){await this.secrets.clear()}serial(e,t){let i=e.signal?AbortSignal.any([this.lifetime.signal,e.signal]):this.lifetime.signal,o=this.busy.then(()=>(this.check(i),t(i)),()=>(this.check(i),t(i)));return this.busy=o.catch(()=>{}),o}check(e){if(e.aborted)throw new Ve("cancelled","Account key request cancelled.")}async readStatus(e){let t;try{t=await this.control.status({signal:e})}catch(l){throw go(l)}this.check(e);let i=Aa(t),o=dg(i.version),s,r=null;if(i.mode==="none"&&o===0)s="none";else if(i.mode==="strict")s="strict";else if(i.mode==="password"&&typeof i.key_id=="string"&&v0.test(i.key_id))s="password",r=i.key_id;else throw cn("status");let a=s==="strict"?d2(i):void 0,c=await this.secrets.get();try{let l=r!==null&&c!==null&&c.length===32&&ht(fu(c))===r;return this.last={mode:s,unlocked:l,version:o,...a?{strictComplete:a.complete,pending:a.pending,accountKeyKept:c!==null}:{}}}finally{c&&wt(c)}}async fetchState(e){let t;try{t=await this.control.fetch({signal:e})}catch(r){throw go(r)}this.check(e);let i=Aa(t),o=dg(i.version);if(i.mode==="none"){if(o!==0)throw cn("mode");return{mode:"none",version:0}}if(i.mode==="strict")return{mode:"strict",version:o};if(i.mode!=="password")throw cn("mode");if(typeof i.key_id!="string"||!v0.test(i.key_id)||typeof i.bundle!="string"||!vD.test(i.bundle))throw cn("bundle");let s=t2(Wr(i.bundle));if(ht(s.keyId)!==i.key_id)throw cn("key_id");return{mode:"password",version:o,bundle:s}}async requirePassword(e){let t=await this.fetchState(e);if(t.mode==="none")throw new Ve("no_account_key","The account has no account key yet; set one up on a device that holds the keys.");if(t.mode==="strict")throw new Ve("strict_mode","The account is in strict mode; approve this device from an existing device.");return t}async putBundle(e,t,i,o){let s=ht(i.keyId),r=w0(i),a=JE(e,this.control.accountId),c;try{let p=ht(XE(a,this.control.accountId,r,t));c=await this.control.put({expected_version:t,key_id:s,bundle:ht(r),proof_pk:ht(a.pk),proof_sig:p},{signal:o})}catch(p){throw go(p)}finally{wt(a.seed)}let l=Aa(c);if(l.mode!=="password"||dg(l.version)!==t+1||l.key_id!==s)throw cn("put")}async collections(e){let t;try{t=await this.replica.privateCollections({signal:e})}catch(i){throw go(i)}if(this.check(e),!Array.isArray(t)||t.some(i=>typeof i!="string")||new Set(t).size!==t.length)throw cn("collections");for(let i of t)Xn(i);return t}async keyAll(e,t){let i=[];for(let o of await this.collections(t)){this.check(t);try{await this.enrol(e,o,t),await this.replica.keyAccountKeyDevice(o,e,{signal:t})}catch(s){if(s instanceof Ve&&s.code==="cancelled")throw s;i.push(o)}}return i}async grantAll(e,t){let i=[];for(let o of await this.collections(t)){this.check(t);try{await this.replica.selfGrantWithAccountKey(o,e,{signal:t})}catch(s){if(s instanceof Ve&&s.code==="cancelled")throw s;i.push(o)}}return i}async enrol(e,t,i){let o;try{o=await this.control.challenge({signal:i})}catch(a){throw go(a)}let s=typeof o=="string"?o.toLowerCase():typeof o?.challenge=="string"?o.challenge.toLowerCase():"";if(!v0.test(s))throw cn("challenge");this.check(i);let r=HE(e,t);try{let a=va("mdbase/v1/account-key-enrol",fe([Wr(s),Xn(t),Xn(r.device),Xn(this.control.accountId),r.signPk,r.kemPk,r.noisePk])),c=ht(GE(r,a)),l;try{l=await this.control.enrolRecoveryDevice(t,{challenge:s,recovery_device:r.device,sign_pk:ht(r.signPk),kem_pk:ht(r.kemPk),pop:c},{signal:i})}catch(d){throw go(d)}let p=Aa(l);if(p.collection_id!==t||p.device_id!==r.device||!Number.isSafeInteger(p.enrolled_at))throw cn("enrol")}finally{YE(r)}}}});function _0(n){if(n instanceof pt)return n;if(n instanceof Lt)return new pt("unlock_strict");if(n instanceof as)return new pt("unlock_unavailable");if(!(n instanceof Ve))return null;switch(n.code){case"wrong_secret":return new pt("wrong_secret");case"invalid_recovery_key":return new pt("invalid_recovery_key",n.reason);case"no_account_key":return new pt("no_account_key");case"strict_mode":return new pt("unlock_strict");case"rate_limited":return new pt("rate_limited",void 0,n.retryAfterMs);case"cancelled":return null;default:return n.reason==="account_key_proof_unavailable"?new pt("unlock_unavailable"):new pt("unavailable",n.reason??n.code,n.retryAfterMs)}}async function xD(n,e){return(await m2(n,e)).mode}async function m2(n,e){let t;try{t=await n.status({signal:e})}catch(s){throw go(s)}if(e.aborted)throw A0();let i=t&&typeof t=="object"&&!Array.isArray(t)?t:{},o=i.mode;if(o!=="password"&&o!=="strict"&&o!=="none")throw It("response");return{mode:o,version:Number.isSafeInteger(i.version)&&i.version>=1?i.version:null,keyId:typeof i.key_id=="string"&&h2.test(i.key_id)?i.key_id:null}}async function hg(n,e){let t=new Ac(n,()=>{throw It("proof")},e);try{return await xD(t,e.signal)}catch(i){throw e.signal.aborted?i:_0(i)??i}finally{t.close()}}async function mg(n,e,t,i){let o=i.signal,s=i.settleMs??SD,r=i.sealed,a="password"in t,c="recoveryKey"in t;if(a===c||typeof(a?t.password:t.recoveryKey)!="string"||!Number.isSafeInteger(s)||s<1)throw new pt("unavailable","binding");let l=()=>{if(o.aborted)throw A0();if(n.isCurrent()!==!0)throw It("fenced")};if(l(),e.status().state==="keyed"){r?.clear();return}if(c)try{wt(uu(t.recoveryKey))}catch(g){throw _0(g)??g}else try{_a(t.password)}catch{throw new pt("wrong_secret")}let p,d=null,u={privateCollections:async()=>[n.collection],keyAccountKeyDevice:()=>Promise.reject(fg()),async selfGrantWithAccountKey(g,y,v){let _=v.signal??o;try{if(l(),g!==n.collection||!(y instanceof Uint8Array)||y.length!==32)throw It("binding");let k=new Uint8Array(y),S;try{S=e.unlockConsuming(k)}finally{k.fill(0)}let x=Date.now()+s,P=100;for(;S.state==="pending";){if(Date.now()>=x)throw p="grant_pending",It("grant_pending");if(await e.drive({signal:_}),l(),S=e.status(),S.state!=="pending")break;await ya(P,_),l(),P=Math.min(1e3,P*2)}if(S.state==="refused")throw p=S.reason,It(S.reason)}catch(k){throw p===void 0&&(d={error:k}),k}}},f=new Ac(n,g=>e.signFetch(g),i),h=null,m=r?{accountId:f.accountId,status:g=>f.status(g),challenge:g=>f.challenge(g),async fetch(g){let y=r.take(n,h?.version??null,h?.keyId??null);if(y)return y;let v=await f.fetch(g);return r.keep(n,v),v},put:()=>f.put(),strict:()=>f.strict(),enrolRecoveryDevice:()=>f.enrolRecoveryDevice(),close:()=>f.close()}:f,w=u2(),b=new ug({control:m,replica:u,secrets:w,...i.argon2id?{argon2id:i.argon2id}:{}});try{h=await m2(f,o),l();let g=h.mode;try{i.onMode?.(g)}catch{}if(g==="none")throw new pt("no_account_key");if(g==="strict")throw new pt("unlock_strict");if(!e.supportsFetchProof())throw new pt("unlock_unavailable");if(e.headKnown()<=0&&(await e.drive({signal:o}),l()),e.headKnown()<=0)throw new pt("unavailable","log_head_unknown");let y=await b.unlock(t,o),v=d;if(v)throw v.error;if(l(),y.incomplete?.length)throw new pt(p==="grant_pending"?"unavailable":"unlock_failed",p??"incomplete");if(e.status().state!=="keyed")throw new pt("unlock_failed","not_keyed");r?.clear()}catch(g){throw(!(g instanceof Ve&&g.code==="wrong_secret")||o.aborted||n.isCurrent()!==!0)&&r?.clear(),o.aborted||n.isCurrent()!==!0?g:_0(g)??g}finally{try{await w.clear()}finally{b.close()}}}var pt,_c,AD,kD,SD,It,A0,fg,PD,h2,Ac,gu=C(()=>{"use strict";St();pg();ve();f2();ri();Wy();ry();pt=class extends Error{constructor(t,i,o){super(`app account key unlock: ${t}`);this.reason=t;this.detail=i;this.retryAfterMs=o;this.name="AppAccountKeyUnlockError"}reason;detail;retryAfterMs},_c=class{held=null;get holding(){return this.held!==null}take(e,t,i){let o=this.held;return o&&t!==null&&i!==null&&o.accountId===e.accountId&&o.connectorId===e.connectorId&&o.deviceId===e.deviceId&&o.version===t&&o.keyId===i?{mode:"password",version:o.version,key_id:o.keyId,bundle:o.bundle}:(this.held=null,null)}keep(e,t){this.held=null;let i=t&&typeof t=="object"&&!Array.isArray(t)?t:{};i.mode!=="password"||!Number.isSafeInteger(i.version)||i.version<1||typeof i.key_id!="string"||!h2.test(i.key_id)||typeof i.bundle!="string"||!/^([0-9a-f]{2}){1,512}$/.test(i.bundle)||(this.held=Object.freeze({accountId:e.accountId,connectorId:e.connectorId,deviceId:e.deviceId,version:i.version,keyId:i.key_id,bundle:i.bundle}))}clear(){this.held=null}},AD=64*1024,kD=15e3,SD=45e3,It=n=>new Ve("unavailable","The account key service refused or was unreachable.",{reason:n}),A0=()=>new Ve("cancelled","Account key request cancelled."),fg=()=>It("not_supported"),PD=n=>Array.from(n,e=>e.toString(16).padStart(2,"0")).join(""),h2=/^[0-9a-f]{64}$/,Ac=class{constructor(e,t,i={}){this.session=e;this.sign=t;for(let s of[e.accountId,e.connectorId,e.deviceId,e.collection])if(N(s).every(r=>r===0))throw It("binding");let o=new URL(e.cpOrigin);if(o.origin!==e.cpOrigin||o.username||o.password||o.protocol!=="https:"&&!(i.allowLoopbackHttp===!0&&Qe(e.cpOrigin)))throw It("binding");if(this.accountId=e.accountId,this.deviceId=e.deviceId,this.origin=o.origin,this.fetchImpl=i.fetch??globalThis.fetch,this.now=i.now??Date.now,e.isCurrent()!==!0)throw It("fenced")}session;sign;accountId;lifetime=new AbortController;origin;deviceId;fetchImpl;now;check(e){if(e.aborted||this.lifetime.signal.aborted)throw A0();let t=!1;try{t=this.session.isCurrent()===!0&&this.session.accountId===this.accountId&&this.session.deviceId===this.deviceId&&this.session.cpOrigin===this.origin}catch{t=!1}if(!t)throw It("fenced")}async request(e,t,i,o){let s=o.signal??this.lifetime.signal;this.check(s);let r=await this.session.connectorBearer({signal:s});if(this.check(s),typeof r!="string"||!r||r.length>16384||/[^\x21-\x7e]/.test(r))throw It("binding");let a=new AbortController,c=()=>a.abort(),l=setTimeout(c,kD);l.unref?.(),s.addEventListener("abort",c,{once:!0}),this.lifetime.signal.addEventListener("abort",c,{once:!0});let p=new Uint8Array(AD),d=0,u=null,f=null;try{let h=this.fetchImpl;try{u=await h(`${this.origin}${t}`,{method:e,headers:{authorization:`Bearer ${r}`,...i},signal:a.signal,redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer"})}catch{throw this.check(s),It("network")}if(this.check(s),a.signal.aborted)throw It("timeout");if(u.body)for(f=u.body.getReader();;){let w;try{w=await f.read()}catch{throw this.check(s),It("network")}try{if(this.check(s),a.signal.aborted)throw It("timeout");if(w.done)break;if(d+w.value.length>p.length)throw a.abort(),It("response");p.set(w.value,d),d+=w.value.length}finally{w.value?.fill(0)}}let m=$o(p.subarray(0,d));if(!u.ok)throw vi(u.status,m,u.headers);if(!m||typeof m!="object"||Array.isArray(m))throw It("response");return m}finally{p.fill(0),(f?.cancel()??u?.body?.cancel())?.catch(()=>{});try{f?.releaseLock()}catch{}clearTimeout(l),s.removeEventListener("abort",c),this.lifetime.signal.removeEventListener("abort",c)}}status(e){return this.request("GET","/v1/next/account-key/status",{},e)}challenge(e){return this.request("POST","/v1/next/devices/challenge",{},e)}async fetch(e){let t=null,i=null;try{let o=await this.request("POST","/v1/next/devices/challenge",{},e),s=o.challenge,r=o.expires_at;if(typeof s!="string"||!/^[0-9a-f]{64}$/.test(s)||typeof r!="number"||!Number.isSafeInteger(r)||r-this.now()<=5e3||r-this.now()>16*6e4)throw It("response");t=Uint8Array.from(s.match(/../g).map(a=>parseInt(a,16)));try{i=this.sign(t)}catch(a){throw a instanceof as?It(a.reason):a instanceof Lt?new Ve("strict_mode","The account is in strict mode."):It("proof")}if(!(i instanceof Uint8Array)||i.length!==64)throw It("proof");return await this.request("GET","/v1/next/account-key",{"x-mdbase-device-id":this.deviceId,"x-mdbase-challenge":s,"x-mdbase-signature":PD(i)},e)}finally{t?.fill(0),i?.fill(0)}}put(){return Promise.reject(fg())}strict(){return Promise.reject(fg())}enrolRecoveryDevice(){return Promise.reject(fg())}close(){this.lifetime.abort()}}});var ji,kc=C(()=>{"use strict";ji=class extends Error{reason="device_keys_unavailable";constructor(e){super(e),this.name="AppDeviceCustodyError"}}});function gg(n){if(typeof globalThis.CryptoKey!="function"||!(n instanceof CryptoKey)||n.type!=="secret"||n.extractable||n.algorithm.name!=="AES-GCM"||n.algorithm.length!==256||n.usages.length!==2||!n.usages.includes("encrypt")||!n.usages.includes("decrypt"))throw Ut();return n}function ID(n){if(n===void 0)return null;if(!n||typeof n!="object"||Array.isArray(n)||Object.keys(n).length!==2||!Object.hasOwn(n,"version")||!Object.hasOwn(n,"key")||n.version!==1)throw Ut();return gg(n.key)}var yg,y2,Ut,Sc,k0=C(()=>{"use strict";Jt();ve();kc();yg="device-key-kek",y2="original-device-kek",Ut=()=>new ji("app device key provider unavailable; preserve storage and reopen");Sc=class n{constructor(e,t,i){this.source=e;this.origin=t;this.lifetime=i;this.scope=Object.freeze({accountId:e.accountId,connectorId:e.connectorId,deviceId:e.deviceId,installationId:e.installationId}),this.current=e.isCurrent,this.owned=e.installationOwned}source;origin;lifetime;db=null;value=null;closed=!1;loaned=!1;scope;current;owned;static async open(e){let t=null;try{let{source:i,origin:o,mode:s,signal:r}=e;t=new n(i,o,r);let a=Object.values(t.scope).map(u=>{let f=N(u);if(f.every(h=>h===0))throw Ut();return Array.from(f,h=>h.toString(16).padStart(2,"0")).join("")});if(!ut(o)||!["fresh","existing"].includes(s)||!globalThis.indexedDB||!globalThis.crypto?.subtle||typeof globalThis.CryptoKey!="function")throw Ut();t.check(r);let c=crypto.subtle.generateKey.bind(crypto.subtle),l=`mdbase.app.device-key-kek.v1.${a.join(".")}`,p=await t.openDatabase(l,s);t.db=p,p.onversionchange=()=>t.close(),t.check(r);let d=await t.transaction("readonly",r,null);if(t.check(r),s==="existing"){if(d===null||typeof d=="boolean")throw Ut();t.value=d}else{if(d!==null)throw Ut();let u=gg(await c({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]));if(t.check(r),await t.transaction("readwrite",r,u)!==!0)throw Ut();t.check(r),t.value=u}return t.check(r),t}catch{throw t?.close(),Ut()}}check(e){try{if(this.closed||this.lifetime.aborted||e.aborted||Et()!==this.origin||this.source.isCurrent!==this.current||this.source.installationOwned!==this.owned||this.current.call(this.source)!==!0||this.owned.call(this.source)!==!0||Object.entries(this.scope).some(([t,i])=>this.source[t]!==i))throw Ut()}catch{throw Ut()}}openDatabase(e,t){return new Promise((i,o)=>{this.check(this.lifetime);let s=indexedDB.open(e,1),r=!1,a=!1,c=()=>{r=!0,o(Ut())};this.lifetime.addEventListener("abort",c,{once:!0});let l=()=>this.lifetime.removeEventListener("abort",c);s.onblocked=c,s.onupgradeneeded=()=>{try{if(this.check(this.lifetime),r||t!=="fresh"||s.result.objectStoreNames.length!==0)throw Ut();s.result.createObjectStore(yg),a=!0}catch{s.transaction?.abort()}},s.onerror=()=>{l(),o(Ut())},s.onsuccess=()=>{l();try{if(this.check(this.lifetime),r||t==="fresh"&&!a||s.result.objectStoreNames.length!==1||!s.result.objectStoreNames.contains(yg))throw Ut();i(s.result)}catch{s.result.close(),o(Ut())}}})}transaction(e,t,i){return new Promise((o,s)=>{if(this.check(t),!this.db)throw Ut();let r=this.db.transaction(yg,e,{durability:"strict"}),a=r.objectStore(yg),c=null,l=!1,p=()=>{l=!0;try{r.abort()}catch{}};t.addEventListener("abort",p,{once:!0}),this.lifetime.addEventListener("abort",p,{once:!0});let d=()=>{t.removeEventListener("abort",p),this.lifetime.removeEventListener("abort",p)};r.onerror=r.onabort=()=>{d(),c=null,s(Ut())},r.oncomplete=()=>{d();try{if(this.check(t),l)throw Ut();o(c)}catch{c=null,s(Ut())}};let u=a.get(y2);u.onsuccess=()=>{try{this.check(t);let f=ID(u.result);e==="readonly"?c=f:(c=f===null,c===!0&&i!==null&&a.add({version:1,key:gg(i)},y2))}catch{p()}}})}deviceCustodyKek(e){if(this.check(e.signal),this.loaned||!this.value)throw Ut();return this.loaned=!0,gg(this.value)}close(){this.closed||(this.closed=!0,this.value=null,this.db?.close(),this.db=null)}}});function b2(n){if(!(n instanceof Uint8Array)||!n.length||n.length>CD)throw jn();return new Uint8Array(n)}var bg,g2,CD,jn,Pc,S0=C(()=>{"use strict";Jt();ve();kc();bg="original-device-keys",g2="custody",CD=256,jn=()=>new ji("app device key custody store unavailable");Pc=class n{constructor(e,t,i,o,s){this.db=e;this.source=t;this.scope=i;this.namespace=o;this.origin=s;this.current=t.isCurrent,this.owned=t.installationOwned,e.onversionchange=()=>this.close()}db;source;scope;namespace;origin;closed=!1;current;owned;static async open(e){try{return await this.openChecked(e)}catch{throw jn()}}static async openChecked(e){let{source:t,signal:i,mode:o,origin:s}=e,r=Object.freeze({accountId:t.accountId,connectorId:t.connectorId,deviceId:t.deviceId,installationId:t.installationId}),a=t.isCurrent,c=t.installationOwned,l=()=>{try{return!i.aborted&&t.isCurrent===a&&t.installationOwned===c&&a.call(t)===!0&&c.call(t)===!0&&Object.keys(r).every(m=>t[m]===r[m])}catch{return!1}},p=[r.accountId,r.connectorId,r.deviceId,r.installationId].map(m=>{let w=N(m);if(w.every(b=>b===0))throw jn();return Array.from(w,b=>b.toString(16).padStart(2,"0")).join("")});if(!ut(s)||Et()!==s||!["fresh","existing"].includes(o)||!l()||!globalThis.indexedDB)throw jn();let d=`mdbase.app-device-keys.v1:${p.join(":")}`,u=`mdbase.app.device-keys.v1.${p.join(".")}`,f=await new Promise((m,w)=>{let b=indexedDB.open(u,1),g=!1,y=()=>{g=!0,w(jn())};i.addEventListener("abort",y,{once:!0});let v=()=>i.removeEventListener("abort",y);b.onblocked=y,b.onupgradeneeded=()=>{if(g||o!=="fresh"||!l()||b.result.objectStoreNames.length!==0){b.transaction?.abort();return}b.result.createObjectStore(bg)},b.onerror=()=>{v(),w(jn())},b.onsuccess=()=>{if(v(),g||!l()||b.result.objectStoreNames.length!==1||!b.result.objectStoreNames.contains(bg)){b.result.close(),w(jn());return}m(b.result)}}),h=new n(f,t,r,d,s);try{h.check(i);let m=await h.read(d,{signal:i});try{if(o==="fresh"!=(m===null))throw jn();return h.check(i),h}finally{m?.fill(0)}}catch{throw h.close(),jn()}}check(e,t=this.namespace){try{if(this.closed||e.aborted||t!==this.namespace||Et()!==this.origin||this.source.isCurrent!==this.current||this.source.installationOwned!==this.owned||this.current.call(this.source)!==!0||this.owned.call(this.source)!==!0||Object.keys(this.scope).some(i=>this.source[i]!==this.scope[i]))throw jn()}catch{throw jn()}}async read(e,t){let i=await this.transaction("readonly",e,t.signal,null);try{return this.check(t.signal,e),i}catch{throw i instanceof Uint8Array&&i.fill(0),jn()}}async create(e,t,i){this.check(i.signal,e);let o=b2(t);try{let s=await this.transaction("readwrite",e,i.signal,o);return this.check(i.signal,e),s===!0}finally{o.fill(0)}}transaction(e,t,i,o){return new Promise((s,r)=>{this.check(i,t);let a=this.db.transaction(bg,e,{durability:"strict"}),c=a.objectStore(bg),l=null,p=!1,d=()=>{p=!0;try{a.abort()}catch{}},u=()=>i.removeEventListener("abort",d);i.addEventListener("abort",d,{once:!0}),a.onabort=a.onerror=()=>{u(),l instanceof Uint8Array&&l.fill(0),r(jn())},a.oncomplete=()=>{u();try{if(this.check(i,t),p)throw jn();s(l)}catch{l instanceof Uint8Array&&l.fill(0),r(jn())}};let f=c.get(g2);f.onsuccess=()=>{let h=null;try{this.check(i,t),h=f.result===void 0?null:b2(f.result),e==="readonly"?(l=h,h=null):(l=h===null,l===!0&&o!==null&&c.add(new Uint8Array(o),g2))}catch{d()}finally{h?.fill(0)}}})}close(){this.closed||(this.closed=!0,this.db.close())}}});var _n,xc,P0=C(()=>{"use strict";Je();ve();_n=()=>new Error("app device key custody unavailable; preserve storage and reopen"),xc=class{constructor(e,t,i){this.pin=e;this.key=t;this.store=i;try{this.scope=Object.freeze({accountId:e.accountId,connectorId:e.connectorId,deviceId:e.deviceId,installationId:e.installationId}),this.current=e.isCurrent,this.owned=e.installationOwned;let o=[this.scope.accountId,this.scope.connectorId,this.scope.deviceId,this.scope.installationId].map(N);if(o.some(s=>s.every(r=>r===0))||t.type!=="secret"||t.extractable||t.algorithm.name!=="AES-GCM"||t.algorithm.length!==256||!t.usages.includes("encrypt")||!t.usages.includes("decrypt"))throw _n();this.namespace=`mdbase.app-device-keys.v1:${o.map(s=>Array.from(s,r=>r.toString(16).padStart(2,"0")).join("")).join(":")}`,this.aad=fe(["mdbase/v1/app-device-keys-platform",...o]),this.check(new AbortController().signal)}catch{throw _n()}}pin;key;store;scope;namespace;aad;current;owned;attempted=!1;check(e){try{if(e.aborted||this.pin.isCurrent!==this.current||this.pin.installationOwned!==this.owned||this.current.call(this.pin)!==!0||this.owned.call(this.pin)!==!0||this.pin.accountId!==this.scope.accountId||this.pin.connectorId!==this.scope.connectorId||this.pin.deviceId!==this.scope.deviceId||this.pin.installationId!==this.scope.installationId)throw _n()}catch{throw _n()}}async openNativeDevice(e,t){let i=null,o=null,s=!1;try{if(this.attempted)throw _n();this.attempted=!0;let r=t.signal,a=t.mode;if(this.check(r),!["fresh","existing"].includes(a)||t.noise.mode!==a||t.noise.mode==="existing"&&!(t.noise.envelope instanceof Uint8Array))throw _n();let c=t.noise.mode==="fresh"?{mode:"fresh"}:{mode:"existing",envelope:new Uint8Array(t.noise.envelope)};if(c.mode==="existing"&&(!c.envelope.length||c.envelope.length>1024))throw _n();let l=await this.store.read(this.namespace,{signal:r});if(this.check(r),a==="fresh"){if(l!==null)throw _n();i=globalThis.crypto.getRandomValues(new Uint8Array(64));let u=globalThis.crypto.getRandomValues(new Uint8Array(12)),f=new Uint8Array(await globalThis.crypto.subtle.encrypt({name:"AES-GCM",iv:u,additionalData:new Uint8Array(this.aad),tagLength:128},this.key,i));if(this.check(r),o=fe(new Map([[0,1],[1,u],[2,f]])),await this.store.create(this.namespace,o,{signal:r})!==!0)throw _n();this.check(r)}else{if(!(l instanceof Uint8Array)||l.length===0||l.length>256)throw _n();o=new Uint8Array(l);let u=we(o);if(!(u instanceof Map))throw _n();let f=u;if(f.size!==3||f.get(0)!==1)throw _n();let h=f.get(1),m=f.get(2);if(!(h instanceof Uint8Array)||h.length!==12||!(m instanceof Uint8Array)||m.length!==80||(i=new Uint8Array(await globalThis.crypto.subtle.decrypt({name:"AES-GCM",iv:new Uint8Array(h),additionalData:new Uint8Array(this.aad),tagLength:128},this.key,new Uint8Array(m))),this.check(r),i.length!==64))throw _n()}this.check(r);let p=Object.freeze({connectorId:this.scope.connectorId,deviceId:this.scope.deviceId,installationId:this.scope.installationId,isCurrent:()=>{try{return this.check(r),!0}catch{return!1}}});s=!0;let d=e.openDeviceConsuming({pin:p,signSecretKey:i.subarray(0,32),kemSecretKey:i.subarray(32),opened:c});return this.check(r),d}catch{if(s)try{e.retireLog()}catch{}throw _n()}finally{i?.fill(0),o?.fill(0)}}}});function x0(n){if(!(n instanceof Uint8Array)||n.byteLength<1||n.byteLength>RD)throw Zn();return new Uint8Array(n)}function OD(n,e){return n===null||e===null?n===e:n.length===e.length&&n.every((t,i)=>t===e[i])}function I0(n){if(N(n).every(t=>t===0))throw Zn();return n.toLowerCase()}function C0(n,e){try{return n.isCurrent()===!0&&n.connectorId===e[0]&&n.deviceId===e[1]&&n.installationId===e[2]}catch{return!1}}var wg,w2,RD,Zn,Ic,R0=C(()=>{"use strict";Jt();ve();kc();wg="opaque-noise",w2="custody",RD=4096,Zn=()=>new ji("app noise custody store unavailable");Ic=class n{constructor(e,t,i,o){this.db=e;this.source=t;this.pins=i;this.origin=o;e.onversionchange=()=>this.close()}db;source;pins;origin;closed=!1;static async open(e){try{return await this.openChecked(e)}catch{throw Zn()}}static async openChecked(e){let{source:t,signal:i}=e,o=[t.connectorId,t.deviceId,t.installationId];if(!ut(e.origin)||Et()!==e.origin||!["fresh","existing"].includes(e.mode)||i.aborted||!C0(t,o)||typeof globalThis.indexedDB>"u")throw Zn();let s=`mdbase.app.noise.v1.${I0(o[2])}.${I0(o[0])}.${I0(o[1])}`,r=await new Promise((c,l)=>{let p=indexedDB.open(s,1),d=!1,u=()=>{d=!0,l(Zn())};i.addEventListener("abort",u,{once:!0});let f=()=>i.removeEventListener("abort",u);p.onblocked=u,p.onupgradeneeded=()=>{if(d||i.aborted||e.mode!=="fresh"||!C0(t,o)||p.result.objectStoreNames.length!==0){p.transaction?.abort();return}p.result.createObjectStore(wg)},p.onerror=()=>{f(),l(Zn())},p.onsuccess=()=>{if(f(),d||i.aborted||p.result.objectStoreNames.length!==1||!p.result.objectStoreNames.contains(wg)){p.result.close(),l(Zn());return}c(p.result)}}),a=new n(r,t,o,e.origin);try{let c=await a.read(a.namespace,{signal:i});if(e.mode==="fresh"!=(c===null))throw Zn();return c?.fill(0),a.check(i),a}catch{throw a.close(),Zn()}}get namespace(){return`mdbase.app-noise.v1:${this.pins[0]}:${this.pins[1]}:${this.pins[2]}`}check(e,t=this.namespace){if(this.closed||e.aborted||t!==this.namespace||Et()!==this.origin||!C0(this.source,this.pins))throw Zn()}async read(e,t){this.check(t.signal,e);let i=await this.transaction("readonly",t.signal,null,null);try{return this.check(t.signal),i}catch{throw i instanceof Uint8Array&&i.fill(0),Zn()}}async compareAndSet(e,t,i,o){this.check(o.signal,e);let s=null,r=null;try{s=t===null?null:x0(t),r=x0(i);let a=await this.transaction("readwrite",o.signal,s,r);return this.check(o.signal),a===!0}finally{s?.fill(0),r?.fill(0)}}transaction(e,t,i,o){return new Promise((s,r)=>{this.check(t);let a=this.db.transaction(wg,e,{durability:"strict"}),c=a.objectStore(wg),l=null,p=!1,d=()=>{p=!0;try{a.abort()}catch{}},u=()=>t.removeEventListener("abort",d);t.addEventListener("abort",d,{once:!0}),a.onabort=a.onerror=()=>{u(),l instanceof Uint8Array&&l.fill(0),r(Zn())},a.oncomplete=()=>{u();try{if(this.check(t),p)throw Zn();s(l)}catch{l instanceof Uint8Array&&l.fill(0),r(Zn())}};let f=c.get(w2);f.onsuccess=()=>{let h=null;try{this.check(t),h=f.result===void 0?null:x0(f.result),e==="readonly"?(l=h,h=null):(l=OD(h,i),l===!0&&o!==null&&c.put(new Uint8Array(o),w2))}catch{d()}finally{h?.fill(0)}}})}close(){this.closed||(this.closed=!0,this.db.close())}}});var ze,bu,Cc,O0=C(()=>{"use strict";Je();ve();ze=()=>new Error("app Noise custody unavailable; preserve storage and reopen"),bu=(n,e)=>n.length===e.length&&n.every((t,i)=>t===e[i]),Cc=class{constructor(e,t,i){this.pin=e;this.key=t;this.store=i;try{this.scope=Object.freeze({connectorId:e.connectorId,deviceId:e.deviceId,installationId:e.installationId});let o=[this.scope.connectorId,this.scope.deviceId,this.scope.installationId].map(N);if(o.some(s=>s.every(r=>r===0))||t.type!=="secret"||t.extractable||t.algorithm.name!=="AES-GCM"||t.algorithm.length!==256||!t.usages.includes("encrypt")||!t.usages.includes("decrypt"))throw ze();this.namespace=`mdbase.app-noise.v1:${this.scope.connectorId}:${this.scope.deviceId}:${this.scope.installationId}`,this.aad=fe(["mdbase/v1/app-noise-platform",...o]),this.check(new AbortController().signal)}catch{throw ze()}}pin;key;store;scope;namespace;aad;check(e){try{if(e.aborted||this.pin.isCurrent()!==!0||this.pin.connectorId!==this.scope.connectorId||this.pin.deviceId!==this.scope.deviceId||this.pin.installationId!==this.scope.installationId)throw ze()}catch{throw ze()}}receiptValue(e){if(e.connectorId!==this.scope.connectorId||e.deviceId!==this.scope.deviceId||e.installationId!==this.scope.installationId)throw ze();let t=[e.signPublicKey,e.kemPublicKey,e.noisePublicKey];if(t.some(i=>!(i instanceof Uint8Array)||i.length!==32||i.every(o=>o===0)))throw ze();return t.map(i=>new Uint8Array(i))}receipt(e){if(e===null)return null;if(!Array.isArray(e)||e.length!==3||e.some(t=>!(t instanceof Uint8Array)||t.length!==32||t.every(i=>i===0)))throw ze();return Object.freeze({...this.scope,signPublicKey:new Uint8Array(e[0]),kemPublicKey:new Uint8Array(e[1]),noisePublicKey:new Uint8Array(e[2])})}markerValue(e){let t=N(e.collection);if(t.every(i=>i===0)||typeof e.acknowledged!="boolean"||!(e.sasCommitment instanceof Uint8Array)||e.sasCommitment.length!==32||e.sasCommitment.every(i=>i===0))throw ze();return[t,...this.receiptValue(e),new Uint8Array(e.sasCommitment),e.acknowledged]}marker(e,t){if(e===null)return null;if(!t||!Array.isArray(e)||e.length!==6||!(e[0]instanceof Uint8Array)||e[0].length!==16||e[0].every(r=>r===0)||typeof e[5]!="boolean")throw ze();let i=this.receipt(e.slice(1,4));for(let r of["signPublicKey","kemPublicKey","noisePublicKey"])if(!bu(i[r],t[r]))throw ze();let o=e[4];if(!(o instanceof Uint8Array)||o.length!==32||o.every(r=>r===0))throw ze();let s=Array.from(e[0],r=>r.toString(16).padStart(2,"0")).join("");return Object.freeze({...i,collection:`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`,sasCommitment:new Uint8Array(o),acknowledged:e[5]})}async restore(e){let t=await this.read(e);return this.check(e.signal),t?.value??null}async read(e){let t=null,i=null;try{this.check(e.signal);let o=await this.store.read(this.namespace,e);if(this.check(e.signal),o===null)return null;if(!(o instanceof Uint8Array)||o.length===0||o.length>4096)throw ze();t=new Uint8Array(o);let s=we(t);if(!(s instanceof Map))throw ze();let r=s,a=r.get(1),c=r.get(2);if(r.size!==3||r.get(0)!==1||!(a instanceof Uint8Array)||a.length!==12||!(c instanceof Uint8Array)||c.length<16||c.length>2064||(i=new Uint8Array(await globalThis.crypto.subtle.decrypt({name:"AES-GCM",iv:new Uint8Array(a),additionalData:new Uint8Array(this.aad),tagLength:128},this.key,new Uint8Array(c))),this.check(e.signal),i.length>2048))throw ze();let l=we(i);if(!(l instanceof Map))throw ze();let p=l,d=p.get(1);if(!(p.get(0)===1&&p.size===3||p.get(0)===2&&p.size===4&&p.has(3))||!(d instanceof Uint8Array)||d.length===0||d.length>1024||!p.has(2))throw ze();let u=this.receipt(p.get(2)),f=p.get(0)===2?this.marker(p.get(3),u):null;return{value:Object.freeze({envelope:new Uint8Array(d),receipt:u,privateEnrolMarker:f}),encrypted:new Uint8Array(t)}}catch{throw ze()}finally{t?.fill(0),i?.fill(0)}}async write(e,t,i,o,s=null){let r=null,a=null;try{if(this.check(o.signal),!(e instanceof Uint8Array)||!e.length||e.length>1024)throw ze();let c=new Map([[0,s===null?1:2],[1,new Uint8Array(e)],[2,t===null?null:this.receiptValue(t)]]);if(s!==null){let u=this.markerValue(s);this.marker(u,t),c.set(3,u)}if(r=fe(c),r.length>2048)throw ze();let l=globalThis.crypto.getRandomValues(new Uint8Array(12)),p=new Uint8Array(await globalThis.crypto.subtle.encrypt({name:"AES-GCM",iv:l,additionalData:new Uint8Array(this.aad),tagLength:128},this.key,new Uint8Array(r)));this.check(o.signal),a=fe(new Map([[0,1],[1,l],[2,p]]));let d=await this.store.compareAndSet(this.namespace,i,a,o);if(this.check(o.signal),d!==!0)throw ze()}catch{throw ze()}finally{r?.fill(0),a?.fill(0)}}async pending(e,t){let i=await this.read(t);if(this.check(t.signal),i){if(!bu(i.value.envelope,e))throw ze();return}await this.write(e,null,null,t),this.check(t.signal)}async privateEnrolPending(e,t){try{if(e.acknowledged!==!1)throw ze();await this.writePrivateMarker(e,!1,t)}catch{throw ze()}}async privateEnrolAcknowledged(e,t){try{await this.writePrivateMarker(e,!0,t)}catch{throw ze()}}async writePrivateMarker(e,t,i){this.check(i.signal);let o=this.marker(this.markerValue(e),e),s=await this.read(i);if(this.check(i.signal),!s?.value.receipt)throw ze();for(let a of["signPublicKey","kemPublicKey","noisePublicKey"])if(!bu(o[a],s.value.receipt[a]))throw ze();let r=s.value.privateEnrolMarker;if(r){if(r.collection!==o.collection||!bu(r.sasCommitment,o.sasCommitment))throw ze();if(r.acknowledged){if(!t)throw ze();return}if(!t)return}else if(t)throw ze();await this.write(s.value.envelope,s.value.receipt,s.encrypted,i,Object.freeze({...o,acknowledged:t})),this.check(i.signal)}async registered(e,t){let i=await this.read(t);if(this.check(t.signal),!i)throw ze();if(i.value.receipt){for(let o of["signPublicKey","kemPublicKey","noisePublicKey"])if(!bu(i.value.receipt[o],e[o]))throw ze();this.receiptValue(e);return}await this.write(i.value.envelope,e,i.encrypted,t),this.check(t.signal)}}});var ka,Nt,vg,Rc,E0=C(()=>{"use strict";St();ve();ka=class extends Error{constructor(t){super(`app device registration: ${t}`);this.reason=t;this.name="AppDeviceRegistrationError"}reason},Nt=n=>new ka(n),vg=n=>Array.from(n,e=>e.toString(16).padStart(2,"0")).join(""),Rc=class{constructor(e,t,i,o,s={}){this.runtime=e;this.session=t;this.persistence=o;try{this.scope=Object.freeze({connectorId:t.connectorId,deviceId:t.deviceId,installationId:t.installationId,kind:t.kind});for(let a of[this.scope.connectorId,this.scope.deviceId,this.scope.installationId])if(N(a).every(c=>c===0))throw Nt("binding");if(t.kind!=="mobile"&&t.kind!=="app-runtime")throw Nt("binding");this.rawOrigin=t.cpOrigin;let r=new URL(this.rawOrigin);if(r.username||r.password||r.pathname!=="/"||r.search||r.hash||r.protocol!=="https:"&&!(s.allowLoopbackHttp===!0&&Qe(this.rawOrigin))||(this.origin=r.origin,this.now=s.now??Date.now,this.fetchImpl=s.fetch??globalThis.fetch,!(i.envelope instanceof Uint8Array)||!i.envelope.length||i.envelope.length>1024)||!e.deviceCustodyCurrent(t,i)||(this.custody=Object.freeze({signPublicKey:new Uint8Array(i.signPublicKey),kemPublicKey:new Uint8Array(i.kemPublicKey),noisePublicKey:new Uint8Array(i.noisePublicKey),envelope:new Uint8Array(i.envelope)}),!this.current()))throw Nt("binding")}catch{throw e.retireLog(),Nt("binding")}}runtime;session;persistence;attempted=!1;lifetime=new AbortController;origin;rawOrigin;scope;custody;now;fetchImpl;current(){try{return!this.lifetime.signal.aborted&&this.runtime.deviceCustodyCurrent(this.session,this.custody)&&this.session.isCurrent()===!0&&this.session.cpOrigin===this.rawOrigin&&this.session.connectorId===this.scope.connectorId&&this.session.deviceId===this.scope.deviceId&&this.session.installationId===this.scope.installationId&&this.session.kind===this.scope.kind}catch{return!1}}check(e){if(!this.current()||e.aborted)throw this.close(),Nt("fenced")}async json(e,t,i,o){this.check(o);let s=new AbortController,r=()=>s.abort(),a=setTimeout(r,15e3);a.unref?.(),o.addEventListener("abort",r,{once:!0}),this.lifetime.signal.addEventListener("abort",r,{once:!0});let c=new Uint8Array(32*1024),l=0,p=null,d=null;try{let u=this.fetchImpl;if(p=await u(`${this.origin}${e}`,{method:"POST",headers:{authorization:`Bearer ${t}`,...i===void 0?{}:{"content-type":"application/json"}},body:i,signal:s.signal,redirect:"error",credentials:"omit",cache:"default",referrerPolicy:"no-referrer"}),this.check(o),s.signal.aborted||!p.ok)throw Nt("unavailable");let f=p.headers.get("content-length");if(f!==null&&/^(0|[1-9][0-9]*)$/.test(f)&&Number(f)>c.length)throw s.abort(),Nt("response");if(!p.body)throw Nt("response");for(d=p.body.getReader();;){let{done:m,value:w}=await d.read();try{if(this.check(o),s.signal.aborted)throw Nt("unavailable");if(m)break;if(l+w.length>c.length)throw s.abort(),Nt("response");c.set(w,l),l+=w.length}finally{w?.fill(0)}}let h=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(c.subarray(0,l)));if(!h||typeof h!="object"||Array.isArray(h))throw Nt("response");return h}catch(u){throw this.check(o),u instanceof ka?u:Nt("unavailable")}finally{c.fill(0),(d?.cancel()??p?.body?.cancel())?.catch(()=>{}),d?.releaseLock(),clearTimeout(a),o.removeEventListener("abort",r),this.lifetime.signal.removeEventListener("abort",r)}}async register(e){let t=null,i=null;try{if(this.check(e.signal),this.attempted)throw Nt("fenced");this.attempted=!0,await this.persistence.pending(new Uint8Array(this.custody.envelope),e),this.check(e.signal);let o=await this.session.connectorBearer(e);if(this.check(e.signal),typeof o!="string"||!o||o.length>16*1024||/[^\x21-\x7e]/.test(o))throw Nt("binding");let s=await this.json("/v1/next/devices/challenge",o,void 0,e.signal);if(this.check(e.signal),typeof s.challenge!="string"||!/^[0-9a-f]{64}$/.test(s.challenge)||typeof s.expires_at!="number"||!Number.isSafeInteger(s.expires_at)||s.expires_at-this.now()<=5e3||s.expires_at-this.now()>16*6e4)throw Nt("response");t=Uint8Array.from(s.challenge.match(/../g).map(l=>parseInt(l,16)));let r=this.runtime.signCpEnrol(t);this.check(e.signal),i=r.signature;let a=await this.json("/v1/next/devices",o,JSON.stringify({device_id:this.scope.deviceId,kind:this.scope.kind,capabilities:["collection_mode_switch_v2"],challenge:s.challenge,sign_pk:vg(r.signPublicKey),kem_pk:vg(r.kemPublicKey),noise_pk:vg(r.noisePublicKey),sig:vg(i)}),e.signal);if(this.check(e.signal),a.device_id!==this.scope.deviceId)throw Nt("response");let c=Object.freeze({connectorId:this.scope.connectorId,deviceId:this.scope.deviceId,installationId:this.scope.installationId,signPublicKey:new Uint8Array(r.signPublicKey),kemPublicKey:new Uint8Array(r.kemPublicKey),noisePublicKey:new Uint8Array(r.noisePublicKey)});return await this.persistence.registered(c,e),this.check(e.signal),this.runtime.acknowledgeDeviceRegistration(c),c}catch(o){throw this.close(),o instanceof ka?o:Nt("unavailable")}finally{t?.fill(0),i?.fill(0)}}close(){this.lifetime.signal.aborted||(this.lifetime.abort(),this.custody.envelope.fill(0),this.runtime.retireLog())}}});var hi,ED,qD,be,v2,Oc,wu=C(()=>{"use strict";a_();Wy();Jt();ve();Ws();Ls();re();xm();Od();_E();HA();JA();ri();Rd();OE();ty();Ed();QA();EE();s0();l0();TE();gu();k0();S0();P0();R0();kc();Tm();O0();E0();ry();hi=class extends Error{constructor(t,i,o){super(`app cloud copy host: ${t}`,o);this.reason=t;this.stage=i;this.name="AppCloudCopyHostError"}reason;stage},ED=32,qD=8,be=(n,e)=>new hi(n,e),v2=(n,e)=>n.length===e.length&&n.every((t,i)=>t===e[i]),Oc=class n{constructor(e,t,i,o,s){this.source=e;this.installation=t;this.originalRelease=i;this.origin=o;this.lifetime=s;this.selected=Object.freeze({accountId:e.accountId,connectorId:e.connectorId,deviceId:e.deviceId,installationId:e.installationId,kind:e.kind,cpOrigin:e.cpOrigin,logOrigin:e.logOrigin,approvalMode:e.approvalMode}),this.currentCallback=e.isCurrent,this.bearerCallback=e.connectorBearer,this.ownershipCallback=t.isCurrent;for(let r of[e.accountId,e.connectorId,e.deviceId,e.installationId])if(N(r).every(a=>a===0))throw be("binding");if(e.kind!=="app-runtime"&&e.kind!=="mobile"||i.schema!=="mdbn-app-trust/release/1"||i.cpOrigin!==e.cpOrigin||i.logOrigin!==e.logOrigin||!/^[0-9a-f]{64}$/.test(i.assetSha256)||!i.trustedRoots.length||i.trustedRoots.length>64||!i.policyPins.length||i.policyPins.length>65536)throw be("binding");if(this.trust=Object.freeze({...i,source:Object.freeze({...i.source}),trustedRoots:Object.freeze(i.trustedRoots.map(r=>{if(!(r instanceof Uint8Array)||r.length!==32||r.every(a=>a===0))throw be("binding");return new Uint8Array(r)})),policyPins:new Uint8Array(i.policyPins)}),this.pin=Object.freeze({...this.selected,isCurrent:()=>this.current(),installationOwned:()=>this.current(),connectorBearer:async({signal:r})=>{this.check(r);let a=await this.bearerCallback.call(this.source,Object.freeze({signal:r}));return this.check(r),a}}),e.approvalMode==="strict")throw new Lt;this.check(s)}source;installation;originalRelease;origin;lifetime;closing=!1;closeResult=null;provider=null;keys=null;noiseStore=null;key=null;noise=null;native=null;publicReceipt=null;signIn=null;originalCustody=null;collectionAttempted=!1;collectionSignal=null;collectionCurrent=null;outcomeStore=null;outcome=null;bootstrap=null;bootstrapConfirmed=!1;collectionScope=null;collectionSession=null;restoredPrivateMarker=null;privateStore=null;privateBootstrap=null;privateMetadata=null;accountKeyPin=null;accountKeyWork=!1;accountKeySealed=new _c;adoptedEndpoint=null;sqlAttempted=!1;sqlClose=null;collectionSql=null;logRequest=null;logLoopback=!1;logWork=null;authority=null;peopleMetadata=null;pump=null;timerPorts=new Set;readWork=null;readAbort=null;readWake=null;readClient=null;readVerified=!1;facades=new Map;logWorkListener=null;selected;currentCallback;bearerCallback;ownershipCallback;trust;pin;current(){try{let e=this.originalRelease,t=this.trust;return!this.closing&&!this.lifetime.aborted&&Et()===this.origin&&this.source.isCurrent===this.currentCallback&&this.source.connectorBearer===this.bearerCallback&&this.installation.isCurrent===this.ownershipCallback&&this.currentCallback.call(this.source)===!0&&this.ownershipCallback.call(this.installation)===!0&&this.installation.scope.account===this.selected.accountId&&this.installation.scope.installation===this.selected.installationId&&Object.entries(this.selected).every(([i,o])=>this.source[i]===o)&&e.schema===t.schema&&e.environment===t.environment&&e.cpOrigin===t.cpOrigin&&e.logOrigin===t.logOrigin&&e.assetSha256===t.assetSha256&&e.source.repository===t.source.repository&&e.source.commit===t.source.commit&&e.source.version===t.source.version&&e.trustedRoots.length===t.trustedRoots.length&&e.trustedRoots.every((i,o)=>v2(i,t.trustedRoots[o]))&&v2(e.policyPins,t.policyPins)}catch{return!1}}check(e){if(e.aborted||!this.current())throw be("fenced")}operationSignal(e){let t=AbortSignal.any([this.lifetime,...this.collectionSignal?[this.collectionSignal]:[],e]);return this.check(t),t}static async openOriginalDevice(e){let{session:t,installation:i,release:o,origin:s,mode:r,signal:a,loadRuntime:c,fetch:l,allowLoopbackHttp:p}=e,d=null;try{if(!["fresh","existing"].includes(r))throw be("binding");d=new n(t,i,o,s,a);let{custody:u,restored:f}=await d.openOwnedDevice({mode:r,signal:a,loadRuntime:c,requireReceipt:!0});if(r==="existing")d.native.acknowledgeDeviceRegistration(f.receipt),d.check(a),d.publicReceipt=d.native.registeredDeviceReceipt();else{let h=await new Rc(d.native,d.pin,u,d.noise,{fetch:l,allowLoopbackHttp:p}).register(Object.freeze({signal:a}));d.check(a),d.publicReceipt=h}return d}catch(u){throw await d?.close(),u instanceof hi||u instanceof Lt?u:new hi("unavailable","device_open",{cause:u})}}static async openInstallationDevice(e){let{signIn:t,installation:i,release:o,origin:s,signal:r,loadRuntime:a,allowLoopbackHttp:c}=e,l=null;try{let p=t.confirmedHostSession(o.logOrigin,o.environment);l=new n(p,i,o,s,r),l.signIn=t;let d=await t.prepareOriginalDevice(i);if(l.check(r),d.mode==="fresh"&&!await k1(d.pin))throw new ji("an unfinished device creation could not be cleared");l.check(r);let{custody:u,restored:f}=await l.openOwnedDevice({mode:d.mode,signal:r,loadRuntime:a,requireReceipt:!1});if(l.originalCustody=u,f?.receipt&&t.view().state!=="paired")throw be("recovery_required");return await l.noise.pending(new Uint8Array(u.envelope),{signal:r}),l.check(r),t.view().state==="paired"&&await l.completeInstallationSignIn(),l}catch(p){throw await l?.close(),p}}async attestInstallation(){if(this.check(this.lifetime),!this.signIn||!this.native||!this.originalCustody||!this.noise)throw be("binding");let e=await this.signIn.attest({runtime:this.native,custody:this.originalCustody,persistence:this.noise,installation:this.installation});return this.check(this.lifetime),e}async completeInstallationSignIn(){if(this.check(this.lifetime),!this.signIn||!this.native||!this.originalCustody||!this.noise)throw be("binding");return await this.signIn.acknowledge({runtime:this.native,custody:this.originalCustody,persistence:this.noise,installation:this.installation}),this.check(this.lifetime),this.publicReceipt=this.native.registeredDeviceReceipt(),this.registeredReceipt()}async openOwnedDevice(e){let{mode:t,signal:i,loadRuntime:o,requireReceipt:s}=e;this.check(i),this.provider=await Sc.open({source:this.pin,origin:this.origin,mode:t,signal:i}),this.check(i),this.key=this.provider.deviceCustodyKek({signal:i}),this.check(i),this.keys=await Pc.open({source:this.pin,origin:this.origin,mode:t,signal:i}),this.check(i),this.noiseStore=await Ic.open({source:this.pin,origin:this.origin,mode:t,signal:i}),this.check(i),this.noise=new Cc(this.pin,this.key,this.noiseStore);let r=await this.noise.restore({signal:i});if(this.check(i),t==="existing"?!r||s&&!r.receipt:r!==null)throw be("recovery_required");this.restoredPrivateMarker=r?.privateEnrolMarker??null;let a=await o(Object.freeze({signal:i}));if(this.check(i),!(a instanceof Uint8Array)||!a.length)throw be("binding");this.native=await nc.createDevice(new Uint8Array(a)),this.check(i);let c=await new xc(this.pin,this.key,this.keys).openNativeDevice(this.native,{signal:i,mode:t,noise:t==="fresh"?{mode:"fresh"}:{mode:"existing",envelope:r.envelope}});return this.check(i),{custody:c,restored:r}}async bootstrapCloudCopy(e){let{scope:t,collectionCurrent:i,purpose:o,outcomeMode:s,signal:r,reconcile:a,fetch:c,allowLoopbackHttp:l}=e,p=this.operationSignal(r),d=e.displayName,u=d===void 0?void 0:li(d);if(u!==void 0&&o!=="create"||(this.check(p),this.collectionAttempted||!this.native||!this.key||!this.publicReceipt||t.account!==this.selected.accountId||t.installation!==this.selected.installationId||!["create","join"].includes(o)||!["fresh","existing"].includes(s)||N(t.collection).every(w=>w===0)))throw be("binding");let f=Object.freeze({account:t.account,installation:t.installation,collection:t.collection}),h=()=>{try{return this.current()&&!p.aborted&&e.scope===t&&e.collectionCurrent===i&&Object.entries(f).every(([w,b])=>t[w]===b)&&i.call(e)===!0&&this.outcomeStore?.fenced!==!0}catch{return!1}};if(!h())throw be("fenced");this.collectionAttempted=!0,this.collectionSignal=p,this.collectionCurrent=h,this.collectionScope=f;let m=Object.freeze({...this.pin,collection:f.collection,purpose:o,assetSha256:this.trust.assetSha256,...u===void 0?{}:{displayName:u},isCurrent:h});this.collectionSession=m;try{this.outcomeStore=await Qy.open({source:m,origin:this.origin,mode:s,signal:p}),this.checkCollection(p),this.outcome=new Xy(m,this.publicReceipt,this.key,this.outcomeStore,{mode:s,signal:p}),this.native.prepareCloudCopyCollection(m),this.checkCollection(p),this.bootstrap=new Gl(this.native,m,this.trust,this.outcome,{fetch:c,allowLoopbackHttp:l,...u===void 0?{}:{displayName:u}});let w=await this.bootstrap.bootstrap(Object.freeze({signal:p,...a?{reconcile:a}:{}}));return this.checkCollection(p),this.bootstrapConfirmed=!0,w}catch(w){throw await this.close(),w}}async bootstrapPrivateDevice(e){let{scope:t,collectionCurrent:i,signal:o,fetch:s,allowLoopbackHttp:r}=e,a=this.operationSignal(o);if(this.check(a),this.collectionAttempted||!this.native||!this.key||!this.noise||!this.publicReceipt||t.account!==this.selected.accountId||t.installation!==this.selected.installationId||N(t.collection).every(u=>u===0))throw be("binding");let c=this.restoredPrivateMarker;if(c&&c.collection!==t.collection)throw be("private_device_limit");let l=Object.freeze({account:t.account,installation:t.installation,collection:t.collection}),p=()=>{try{return this.current()&&!a.aborted&&e.scope===t&&e.collectionCurrent===i&&Object.entries(l).every(([u,f])=>t[u]===f)&&i.call(e)===!0}catch{return!1}};if(!p())throw be("fenced");this.collectionAttempted=!0,this.collectionSignal=a,this.collectionCurrent=p,this.collectionScope=l;let d=Object.freeze({...this.pin,collection:l.collection,purpose:"enrol",rootPublicKey:new Uint8Array(this.trust.trustedRoots[0]),isCurrent:p});this.collectionSession=d;try{this.privateStore=await rg.open({source:d,origin:this.origin,mode:c?"existing":"fresh",signal:a}),this.checkCollection(a);let u=new ng(d,this.publicReceipt,this.key,this.privateStore,this.noise,{allowLoopbackHttp:r});this.native.preparePrivateCollection(d,c?{mode:"existing",marker:c}:{mode:"fresh"}),this.checkCollection(a),this.privateBootstrap=new eg(this.native,d,u,{fetch:s,allowLoopbackHttp:r}),this.privateMetadata=await this.privateBootstrap.bootstrap(Object.freeze({signal:a})),this.checkCollection(a),this.bootstrapConfirmed=!0}catch(u){throw await this.close(),u}}adoptPrivateDevice(e,t){let i=this.operationSignal(e.signal);this.checkCollection(i);let o=this.privateMetadata,s=this.publicReceipt;if(!this.native||!this.privateBootstrap||!o||!s||!this.bootstrapConfirmed||this.adoptedEndpoint!==null)throw be("fenced");let r=o.collection;this.native.adoptDevice({replicaId:e.replicaId,endpoint:e.endpoint,opened:e.opened,sqliteVersion:e.sqliteVersion,collection:r,deviceId:o.deviceId,state:"e2e",cloudCopyOptIn:!1,trustedRoots:this.trust.trustedRoots.map(a=>new Uint8Array(a)),policyPins:new Uint8Array(this.trust.policyPins),trustedSigners:[],expectedGenesis:o.expectedGenesis},t),this.checkCollection(i),this.adoptedEndpoint=e.endpoint,this.accountKeyPin=Object.freeze({connectorId:s.connectorId,deviceId:s.deviceId,installationId:s.installationId,collection:r,approvalMode:"password-ak1",isCurrent:()=>this.collectionCurrent?.()===!0})}checkCollection(e){if(this.check(e),this.collectionCurrent?.()!==!0)throw be("fenced")}adoptCloudCopy(e,t){let i=this.operationSignal(e.signal);if(this.checkCollection(i),!this.bootstrap||!this.bootstrapConfirmed||this.adoptedEndpoint!==null)throw be("fenced");let o=e.endpoint;this.bootstrap.adoptCollection({...e,signal:this.collectionSignal},t),this.checkCollection(i),this.adoptedEndpoint=o}async openCollectionSql(e){let{replicaId:t,endpoint:i,openSql:o}=e,s=this.operationSignal(e.signal);if(this.checkCollection(s),!this.bootstrapConfirmed||!this.collectionScope||this.sqlAttempted||this.adoptedEndpoint!==null||N(t).every(r=>r===0)||typeof i!="bigint"&&!Number.isSafeInteger(i)||BigInt(i)<0n||BigInt(i)>(1n<<64n)-1n)throw be("binding");this.sqlAttempted=!0;try{let r=await o.call(e,Object.freeze({scope:this.collectionScope,signal:s})),a=r.close;if(this.sqlClose=async()=>{await a.call(r)},this.collectionSql=r.sql,this.checkCollection(s),e.openSql!==o)throw be("fenced");this.privateBootstrap?this.adoptPrivateDevice({signal:s,replicaId:t,endpoint:i,opened:r.opened,sqliteVersion:r.sqliteVersion},r.sql):this.adoptCloudCopy({signal:s,replicaId:t,endpoint:i,opened:r.opened,sqliteVersion:r.sqliteVersion,cloudCopyOptIn:!0},r.sql)}catch(r){throw await this.close(),r}}async startCollectionLog(e){let{fetch:t,allowLoopbackHttp:i}=e,o=this.operationSignal(e.signal);if(this.checkCollection(o),!this.native||!this.collectionSession||this.adoptedEndpoint===null)throw be("binding");let s=t??globalThis.fetch,r=i===!0;if(this.authority&&(s!==this.logRequest||r!==this.logLoopback))throw be("fenced");if(this.pump)return;if(this.logWork){await this.logWork,this.checkCollection(o);return}this.authority||(this.logRequest=s,this.logLoopback=r,this.authority=new Hl(this.native,Object.freeze({...this.collectionSession,endpoint:this.adoptedEndpoint,directOrigins:Object.freeze([])}),{fetch:s,allowLoopbackHttp:i,tokenCache:v1()}));let a=this.authority,c=(async()=>{await a.accessToken(Object.freeze({signal:o})),this.checkCollection(o),this.pump=this.native.bindLogTransport(a.logTransport())})();this.logWork=c;try{await c}finally{this.logWork===c&&(this.logWork=null)}}peopleAuthority(){if(this.checkCollection(this.lifetime),!this.collectionSession||this.adoptedEndpoint===null||!this.logRequest||this.accountKeyPin)throw be("binding");if(!this.peopleMetadata){let e=this.adoptedEndpoint,t=this.collectionSession,i=new yc(Object.freeze({...t,endpoint:e,directOrigins:Object.freeze([]),isCurrent:()=>this.collectionCurrent?.()===!0&&this.adoptedEndpoint===e,connectorBearer:async({signal:s})=>{s.throwIfAborted(),this.checkCollection(this.lifetime);let r=await t.connectorBearer({signal:this.lifetime});return this.checkCollection(this.lifetime),s.throwIfAborted(),r}}),{fetch:this.logRequest,allowLoopbackHttp:this.logLoopback}),o=Object.freeze({collection:i.collection,isCurrent:()=>i.isCurrent(),request:(s,r)=>i.request(s,r)});this.peopleMetadata={authority:i,view:o}}return this.peopleMetadata.view}timerConsentKey(e){let t=this.timerGrant(e);return t?JSON.stringify(t.consent):null}timerGrant(e){let t=this.source.timerConsent,i=t?.call(this.source);if(!i?.approved)return null;let o=i.grants.find(s=>s.collectionId===e);return o?{callback:t,consent:i,grant:o}:null}openTimersPort(e){if(this.checkCollection(this.lifetime),!this.readVerified||!this.logRequest||!this.collectionScope||e.signal.aborted)throw be("binding");let{scope:t,generation:i,signal:o}=e,s=this.collectionScope;if(t.account!==s.account||t.installation!==s.installation||t.collection!==s.collection||N(i).every(m=>m===0))throw be("binding");let r=this.timerGrant(t.collection);if(!r)return null;let{callback:a,consent:c,grant:l}=r,p=globalThis.WorkerGlobalScope;if(typeof p!="function"||!(globalThis instanceof p)||N(l.grantId).every(m=>m===0)||!/^[0-9a-f]{64}$/.test(l.declarationDigest))throw be("binding");let d=JSON.stringify(c),u=new MessageChannel,f=()=>{try{return!o.aborted&&e.signal===o&&e.scope===t&&e.generation===i&&this.collectionCurrent?.()===!0&&this.current()&&t.account===s.account&&t.installation===s.installation&&t.collection===s.collection&&this.source.timerConsent===a&&JSON.stringify(a?.call(this.source))===d}catch{return!1}},h=xE(u.port1,{scope:s,generation:i,grantId:l.grantId,cpOrigin:new URL(this.selected.cpOrigin).origin,signal:o,isCurrent:f,fetch:this.logRequest,...this.signIn?{journal:{read:()=>this.signIn.originalTimerChannel(l.grantId),write:m=>this.signIn.retainTimerChannel(l.grantId,m)}}:{},bearer:async()=>{if(!f())throw be("fenced");let m=await this.bearerCallback.call(this.source,{signal:this.lifetime});if(!f())throw be("fenced");return m}});return this.timerPorts.add(h),Object.freeze({port:u.port2,close:async()=>{await h.close(),u.port2.close(),this.timerPorts.delete(h)}})}serverProblem(){return this.pump?.serverProblem??null}transportHealth(){return this.pump?.transportHealth??null}initialSync(){try{return this.native?gc(this.native.observations().status):"unavailable"}catch{return"unavailable"}}holdsLog(){try{if(!this.native)return!1;let e=this.native.observations().status;return e.mode==="local_only"||e.headKnown>0}catch{return!1}}keyWaitDetail(){try{return this.native?Yy(this.native.observations().status):null}catch{return null}}keyringSettled(){if(!this.native)throw be("binding");let e=this.native.observations();return e.requiresReopen||e.keyringRebuildFailed?"failed":e.keyringRebuilding?"pending":"settled"}pendingWrites(){try{return this.native?.observations().status.pending??0}catch{return 0}}pushLog(e){try{let t=this.native?.pushLog(e)===!0;return t&&this.readWake?.(),t}catch{return!1}}openLogPush(e){this.checkCollection(this.lifetime);let t=this.native,i=this.authority,o=this.collectionSession,s=this.logRequest;if(!t||!this.pump||!i||!o||!s)throw be("binding");if(!t.supportsLogPush||typeof WebSocket!="function")return null;let r=this.logLoopback,a=i.origin,c=()=>{try{return this.collectionCurrent?.()===!0&&this.current()&&this.authority===i&&i.isCurrent()}catch{return!1}},l=i.logTransport(),p=new Hy({origin:a,collection:i.collection,deviceId:o.deviceId,isCurrent:c,accessToken:d=>i.accessToken(d),invalidateToken:d=>i.invalidateToken(d),nonce:async({signal:d})=>{let u=await s(`${a}/v1/nonce`,{signal:d,cache:"no-store",credentials:"omit",redirect:"error",referrerPolicy:"no-referrer"}),f=(await u.text()).trim();if(!u.ok||!/^[0-9a-f]{64}$/.test(f))throw be("unavailable","push_nonce");return Uint8Array.from(f.match(/../g).map(h=>parseInt(h,16)))},signHello:(d,u)=>c()?t.signLogHello(d,u):null},{push:e.push,ended:e.ended,live:d=>{try{c()&&t.setLogStreamLink(d)}catch{}if(e.live(d),d)try{this.logWorkListener?.()}catch{}}},{allowLoopbackHttp:r});return l.setStreamRoute((d,u)=>p.request(d,u)),p}async driveCollection(e){let t=this.operationSignal(e.signal);if(this.checkCollection(t),!this.native||!this.pump||this.adoptedEndpoint===null)throw be("binding");for(let i=0;i<qD;i++){let o=this.pump.callsSent;if(this.native.tick(),await this.pump.pump(),this.checkCollection(t),this.pump?.callsSent===o)break}}async wakeCollectionLog(e){let t=this.operationSignal(e.signal);if(this.checkCollection(t),!this.native||!this.pump||this.adoptedEndpoint===null)throw be("binding");this.native.tick(),(await this.pump.pump()).quiet&&(this.checkCollection(t),this.native.requestLogHead()&&(await this.pump.pump(),this.checkCollection(t),this.native.tick()))}waitForVerifiedRead(e){let{timeoutMs:t=15e3,cold:i=!1,local:o=!1}=e,s=this.operationSignal(e.signal);if(this.checkCollection(s),!this.native||!this.collectionScope||this.adoptedEndpoint===null||!Number.isSafeInteger(t)||t<1||t>15e3||typeof i!="boolean"||typeof o!="boolean"||i&&(o||!this.pump))throw be("binding");if(o&&!this.holdsLog())return Promise.reject(be("unavailable","local_read_without_log"));if(this.readWork)return this.readWork.then(()=>{this.checkCollection(s)});let r=this.verifyRead(s,t,i,o,e.onProgress);return this.readWork=r,r.finally(()=>{this.readWork===r&&(this.readWork=null)}).catch(()=>{}),r}async verifyRead(e,t,i,o,s){let r=new AbortController,a=()=>r.abort(),c=()=>o?null:this.pump;this.readAbort=r;let l=!1,p=null;c()&&(this.readWake=()=>{l=!0,p?.()});let d=_=>l?(l=!1,Promise.resolve()):c()?new Promise((k,S)=>{if(r.signal.aborted){S(r.signal.reason);return}let x=()=>{clearTimeout(O),r.signal.removeEventListener("abort",I),p===P&&(p=null)},P=()=>{x(),l=!1,k()},I=()=>{x(),S(r.signal.reason)},O=setTimeout(()=>{x(),k()},_);p=P,r.signal.addEventListener("abort",I,{once:!0})}):ya(_,r.signal);e.addEventListener("abort",a,{once:!0});let u=null,f="read_connect",h=null,m=()=>h??=be(i?"sync_stalled":"unavailable",f),w,b=new Promise((_,k)=>{w=()=>k(m()),r.signal.addEventListener("abort",w,{once:!0})});b.catch(()=>{});let g=null,y=_=>{if(_!==g){g=_;try{s?.(_)}catch{}}},v=()=>{this.checkCollection(e);let _=i?c().terminalProblem:null;if(rn(_))throw new En(Rt(_)??"unavailable",_);let k=this.native.observations();if(k.requiresReopen||k.keyringRebuildFailed)throw be("recovery_required");let S=gc(k.status);return y(S==="installing"?"loading_snapshot":S==="waiting_for_key"?"waiting_for_key":S==="behind"?"replaying":S===null?"verifying_read":"syncing"),k};this.readVerified=!1;try{if(c()){let k=!1,S=()=>{let q=v();return k=i&&RE(q.status),[q.status.confirmedThrough,q.status.installing?.done??0,q.status.installing?.total??0,c().readProgress]},x=S(),P=Date.now(),I=new Map,O=null,R=()=>{try{let q=Date.now(),j=S();j.some((V,U)=>V>x[U])&&(P=q,O=null),x=j.map((V,U)=>Math.max(V,x[U]));let B=c().responseProgress(),D=new Set(B.map(V=>V.id));for(let V of I.keys())D.has(V)||I.delete(V);for(let V of B){let U=I.get(V.id);V.bytes>(U?.bytes??0)&&I.set(V.id,{bytes:V.bytes,at:q})}let X=(k?Math.max(t,CE):t)-(q-P);X<=0&&(O??=new Set(I.keys()),X=Math.max(0,...[...O].map(V=>{let U=I.get(V);return U?t-(q-U.at):0}))),X<=0?a():u=setTimeout(R,Math.min(250,X))}catch(q){h=q,a()}};u=setTimeout(R,Math.min(250,t))}else u=setTimeout(a,t);this.readClient=await Promise.race([wr.connect({app:{name:"app-local-read-gate",version:"1"},connector:Dl(this.native,{collection:this.collectionScope.collection}),reconnect:!1,signal:r.signal}).then(k=>{if(r.signal.aborted)throw k.close(),m();return k}),b]),this.checkCollection(e);let _=250;for(;!r.signal.aborted;){f="read_catch_up",l=!1,this.native.tick();let k=c();k&&await Promise.race([k.pump(),b]),this.checkCollection(e);let S=v();if(i&&gc(S.status)!==null){await d(_),_=Math.min(1e3,_*2);continue}f="read_query";try{if(await Promise.race([this.readClient.query({limit:1},{signal:r.signal}),b]),this.checkCollection(e),r.signal.aborted)throw m();this.readVerified=!0;return}catch(x){if(this.checkCollection(e),!(x instanceof ne)||x.code!=="unavailable"||!c()||r.signal.aborted)throw x}await d(_),_=Math.min(1e3,_*2)}throw m()}catch(_){throw this.checkCollection(e),r.signal.aborted?m():_}finally{u!==null&&clearTimeout(u),e.removeEventListener("abort",a),r.signal.removeEventListener("abort",w),this.readWake=null,p=null,this.readClient?.close(),this.readClient=null,this.readAbort=null}}get privateDevice(){return this.accountKeyPin!==null}accountKeyState(){if(!this.native||!this.accountKeyPin||this.adoptedEndpoint===null)throw be("binding");return this.native.accountKeyStatus(this.accountKeyPin)}async settlePrivateKey(e){let{timeoutMs:t=15e3}=e,i=this.operationSignal(e.signal);if(this.checkCollection(i),!this.native||!this.pump||!this.accountKeyPin||this.adoptedEndpoint===null||!Number.isSafeInteger(t)||t<1||t>15e3)throw be("binding");let o=null,s=Date.now(),r=100,a=!1,c=async()=>a?!0:(a=!0,await this.wakeCollectionLog({signal:i}),!1);for(;;){let l=this.accountKeyState();if(l.state==="keyed")return"keyed";if(l.state==="refused"&&l.reason==="outcome_unknown")throw be("recovery_required");await this.driveCollection({signal:i});let p=this.pump?.terminalProblem;if(rn(p))throw new En(Rt(p)??"unavailable",p);if(this.accountKeyState().state==="keyed")return"keyed";let d=this.native.observations();if(d.requiresReopen||d.keyringRebuildFailed)throw be("recovery_required");let u=gc(d.status);if(u==="offline"||this.pump?.transportHealth?.kind==="offline")throw be("unavailable","key_wait_offline");let f=u==="waiting_for_key"?Yy(d.status)?.key:void 0;if(u===null||f!==void 0&&f!=="reading"){if(await c())return"locked";continue}let h=Date.now(),m=[d.status.confirmedThrough,d.status.headKnown,this.pump.readProgress];if((o===null||m.some((w,b)=>w>o[b]))&&(s=h),o=o===null?m:m.map((w,b)=>Math.max(w,o[b])),h-s>=t)throw be("sync_stalled");await ya(r,i),this.checkCollection(i),r=Math.min(1e3,r*2)}}accountKeySession(e){let t=this.collectionSession;if(!t)throw be("binding");return Object.freeze({accountId:this.selected.accountId,connectorId:e.connectorId,deviceId:e.deviceId,collection:e.collection,cpOrigin:this.selected.cpOrigin,isCurrent:()=>this.collectionCurrent?.()===!0&&this.accountKeyPin===e,connectorBearer:async({signal:i})=>{i.throwIfAborted(),this.checkCollection(this.lifetime);let o=await t.connectorBearer({signal:this.lifetime});return this.checkCollection(this.lifetime),i.throwIfAborted(),o}})}async accountKeyMode(e){let t=this.operationSignal(e.signal);this.checkCollection(t);let i=this.accountKeyPin;if(!i||!this.logRequest)throw be("binding");return hg(this.accountKeySession(i),{signal:t,fetch:this.logRequest,allowLoopbackHttp:this.logLoopback})}async unlockAccountKey(e,t){let i=this.operationSignal(t.signal);this.checkCollection(i);let o=this.native,s=this.accountKeyPin,r=this.logRequest;if(!o||!s||!r||!this.pump||this.adoptedEndpoint===null||this.accountKeyWork)throw be("binding");let a=Object.freeze({supportsFetchProof:()=>o.supportsAccountKeyFetchProof,signFetch:c=>o.signAccountKeyFetch(s,this.selected.accountId,c),unlockConsuming:c=>o.unlockAccountKeyConsuming(s,c),status:()=>o.accountKeyStatus(s),drive:c=>this.driveCollection({signal:c.signal}),headKnown:()=>o.observations().status.headKnown});this.accountKeyWork=!0;try{await mg(this.accountKeySession(s),a,e,{signal:i,fetch:r,allowLoopbackHttp:this.logLoopback,sealed:this.accountKeySealed,...t.onMode?{onMode:t.onMode}:{}}),this.checkCollection(i)}finally{this.accountKeyWork=!1}}onLogWork(e){this.logWorkListener=e}attachDataFacade(e){if(this.checkCollection(this.lifetime),!this.native||!this.collectionScope||!this.readVerified||this.facades.size>=ED||this.facades.has(e))throw be("fenced");let t=Object.freeze({...this.collectionScope,isCurrent:()=>{try{return this.checkCollection(this.lifetime),!0}catch{return!1}}}),i=Qm(this.native,e,t,()=>this.logWorkListener?.());return this.facades.set(e,i),i.resourceSetup}detachDataFacade(e){let t=this.facades.get(e);t&&(this.facades.delete(e),t.close())}registeredReceipt(){this.check(this.lifetime);let e=this.publicReceipt;if(!e)throw be("fenced");return Object.freeze({...e,signPublicKey:new Uint8Array(e.signPublicKey),kemPublicKey:new Uint8Array(e.kemPublicKey),noisePublicKey:new Uint8Array(e.noisePublicKey)})}close(){if(this.closing=!0,this.readVerified=!1,this.readAbort?.abort(),this.closeResult)return this.closeResult;let e=!1;for(let t of[()=>this.readClient?.close(),()=>{for(let i of this.facades.values())i.close();this.facades.clear()},()=>this.peopleMetadata?.authority.close(),()=>this.bootstrap?.close(),()=>this.outcome?.close(),()=>this.accountKeySealed.clear()])try{t()}catch{e=!0}return this.closeResult??=(async()=>{try{await Promise.all([...this.timerPorts].map(async i=>{try{await i.close()}catch{e=!0}})),this.timerPorts.clear();let t=await this.native?.close();if(this.collectionSql&&t!==!0&&this.collectionSql.fence(),this.authority?.close(),await this.sqlClose?.(),e)throw be("unavailable","close_fence")}finally{this.key=null,this.noise=null,this.originalCustody?.envelope.fill(0),this.originalCustody=null,this.signIn=null,this.publicReceipt=null,this.outcomeStore?.close(),this.privateStore?.close(),this.noiseStore?.close(),this.keys?.close(),this.provider?.close()}})()}}});var Ec,TD,MD,ws,Un,qc,_g=C(()=>{"use strict";Ec="original-join",TD=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,MD="00000000-0000-0000-0000-000000000000",ws=class extends Error{constructor(t){super(`app collection join: ${t}`);this.reason=t;this.name="AppCollectionJoinError"}reason},Un=(n="recovery_required")=>new ws(n),qc=class{options;key;busy=!1;constructor(e){let t=Object.freeze({account:e.scope.account,installation:e.scope.installation,collection:e.scope.collection});if(Object.values(t).some(i=>typeof i!="string"||!TD.test(i)||i===MD)||typeof e.databaseName!="string"||!e.databaseName.length||e.databaseName.length>256||/[\u0000-\u001f\u007f]/.test(e.databaseName)||typeof e.isCurrent!="function")throw Un("binding");this.options=Object.freeze({databaseName:e.databaseName,scope:t,isCurrent:e.isCurrent}),this.key=JSON.stringify([t.account,t.installation,t.collection])}check(e){if(e.aborted||this.options.isCurrent()!==!0)throw Un("fenced")}marker(e){if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).sort().join()!=="account,collection,installation,phase,version")throw Un();let t=e;if(t.version!==1||t.phase!=="attempted"&&t.phase!=="completed"||Object.entries(this.options.scope).some(([i,o])=>t[i]!==o))throw Un();return t}open(e){if(this.check(e),!globalThis.indexedDB)throw Un();return new Promise((t,i)=>{let o=indexedDB.open(this.options.databaseName,1),s=!1,r=()=>e.removeEventListener("abort",a),a=()=>{s=!0,r();try{o.transaction?.abort()}catch{}i(Un())};e.addEventListener("abort",a,{once:!0}),o.onblocked=o.onerror=a,o.onupgradeneeded=()=>{try{if(this.check(e),s||o.result.objectStoreNames.length)throw Un();o.result.createObjectStore(Ec)}catch{try{o.transaction?.abort()}catch{}}},o.onsuccess=()=>{r();try{if(this.check(e),s||o.result.objectStoreNames.length!==1||!o.result.objectStoreNames.contains(Ec))throw Un();t(o.result)}catch{o.result.close(),i(Un())}}})}async change(e,t){if(this.check(t),this.busy)throw Un("busy");this.busy=!0;let i=null;try{return i=await this.open(t),this.check(t),await new Promise((o,s)=>{this.check(t);let r=i.transaction(Ec,"readwrite",{durability:"strict"}),a=null,c,l=()=>{try{r.abort()}catch{}},p=()=>t.removeEventListener("abort",l);t.addEventListener("abort",l,{once:!0}),r.onabort=r.onerror=()=>{p(),s(c??Un())},r.oncomplete=()=>{p();try{if(this.check(t),!a)throw Un();o(Object.freeze(a))}catch{s(Un())}};let d=r.objectStore(Ec),u=d.get(this.key);u.onsuccess=()=>{try{this.check(t);let f=u.result;if(f===void 0){if(e!=="prepare")throw Un();d.add({version:1,...this.options.scope,phase:"attempted"},this.key),a={outcomeMode:"fresh",phase:"attempted"}}else{let h=this.marker(f);e==="complete"&&h.phase!=="completed"&&d.put({...h,phase:"completed"},this.key),a={outcomeMode:"existing",phase:e==="complete"?"completed":h.phase}}}catch(f){c=f,l()}}})}catch(o){throw o instanceof ws?o:Un()}finally{i?.close(),this.busy=!1}}prepare(e){return this.change("prepare",e.signal)}async syncedBefore(e){return await this.synced("read",e.signal)===!0}async markSynced(e){await this.synced("mark",e.signal)}async synced(e,t){let i=null;try{i=await this.open(t),this.check(t);let o=JSON.stringify([this.options.scope.account,this.options.scope.installation,this.options.scope.collection,"synced"]);return await new Promise(s=>{let r=i.transaction(Ec,e==="mark"?"readwrite":"readonly"),a=!1;r.onabort=r.onerror=()=>s(!1),r.oncomplete=()=>s(e==="mark"||a);let c=r.objectStore(Ec);if(e==="mark")c.put({version:1,synced:!0},o);else{let l=c.get(o);l.onsuccess=()=>{let p=l.result;a=!!p&&p.version===1&&p.synced===!0}}})}catch{return!1}finally{i?.close()}}async complete(e){await this.change("complete",e.signal)}}});function A2(n){let e=Object.freeze({...n,setupJournal:Object.freeze({...n.setupJournal})}),t=Q1(e.sql);if(typeof e.handoff!="function")throw cr("binding");let i=new Set;return async o=>{let s=JSON.stringify([o.scope.account,o.scope.installation,o.scope.collection]);if(i.has(s))throw cr("fenced");i.add(s);let{host:r,installation:a,signal:c,collection:l,setupPolicy:p}=o,d=a.isCurrent,u=l.displayName,f=l.mode==="private",h=ue=>{if(oe())try{o.onProgress?.(ue)}catch{}},m=Object.freeze({account:o.scope.account,installation:o.scope.installation,collection:o.scope.collection}),w=JSON.stringify([m.account,m.installation,m.collection]),b=new AbortController,g=!1,y=!0,v=null,_=null,k=null,S=null,x=null,P=null,I=null,O=null,R="setup_required",q=null,j=!1,B=!1,D=null,X=null,V="settled",U=null,ce=!1,ee=null,te=!1,Ie=null,tt=null,$=new Map,Y=new Map,K=()=>{try{return r.timerConsentKey(m.collection)}catch{return}},Q=null,Ae=new Set,oe=()=>{try{return!g&&!b.signal.aborted&&!c.aborted&&o.signal===c&&o.host===r&&o.installation===a&&a.isCurrent===d&&d.call(a)===!0&&o.collection===l&&o.setupPolicy===p&&a.scope.account===m.account&&a.scope.installation===m.installation&&JSON.stringify([o.scope.account,o.scope.installation,o.scope.collection])===w&&l.collectionId===m.collection}catch{return!1}},ie=()=>{if(!oe())throw cr("fenced")},He=()=>{for(let ue of[...Ae])try{ue()}catch{}},Fe=()=>{if(k)return k;g=!0,R="setup_required",v!==null&&clearTimeout(v),v=null,ee!==null&&clearTimeout(ee),ee=null,tt=null;try{U?.close()}catch{}U=null;try{r.onLogWork?.(null)}catch{}c.removeEventListener("abort",Ft);let ue=[...$.values()];return $.clear(),k=Promise.resolve().then(async()=>{let Ce=!1;try{await x?.close()}catch{Ce=!0}try{await S?.close()}catch{Ce=!0}for(let st of ue){try{await st.timers?.close()}catch{Ce=!0}try{await st.control.close()}catch{Ce=!0}try{st.data.port1.postMessage([1,JSON.stringify([m.account,m.installation,m.collection]),"close"])}catch{Ce=!0}for(let mi of[st.data.port1,st.data.port2,st.command.port1,st.command.port2])try{mi.close()}catch{Ce=!0}}try{I?.port1.postMessage([1,JSON.stringify([m.account,m.installation,m.collection]),"close"])}catch{Ce=!0}for(let st of[I?.port1,I?.port2,O?.port1,O?.port2])try{st?.close()}catch{Ce=!0}await _?.catch(()=>{});try{P?.close()}catch{Ce=!0}if(Ce)throw cr("unavailable");Ae.clear(),i.delete(s)}),b.abort(),He(),k},Ft=()=>{Fe().catch(()=>{})},Ee=null,nt=0,dr=()=>{let ue=Rt(Q);if(ue!==null)return ue==="collection_migrating"?Math.min(6e5,Math.max(5e3,Q?.retryAfterMs??3e4)):3e5;let Ce=Math.min(6e4,1e3*2**Math.min(Math.max(nt,Vr),6));return Ee?.kind==="offline"?Dn?Ce:null:Ee?.kind==="server_busy"||Ee?.kind==="rate_limited"?Ee.retryAfterMs??Ce:Vr||Ee?Ce:250},_o=()=>{let ue=null;try{ue=r.serverProblem()}catch{ue=null}let Ce=null;try{Ce=r.transportHealth()}catch{Ce=null}nt=Ce?nt+1:0;let st=JSON.stringify(Ce)===JSON.stringify(Ee);(ue!==Q||!st)&&(Q=ue,Ee=Ce,He())},Ao=Number.POSITIVE_INFINITY,Vr=0,ko=0,vs=!1,Dn=null,dn=ue=>{let Ce=ue&&typeof ue=="object"&&typeof ue.code=="string"?ue.code:null;try{console.debug("mdbase: sync turn failed",{reason:Ee?.kind??Rt(Q)??Ce??"unknown",failures:Vr})}catch{}},So=()=>{if(y||Date.now()-ko>=LD)return!1;try{return r.pendingWrites()>0}catch{return!1}},Bc=()=>r.startCollectionLog({signal:b.signal,fetch:e.fetch,allowLoopbackHttp:e.allowLoopbackHttp}),xa=ue=>{Ie=ue,Lg(),Vc(!1),Dn?.(),He()},_s=()=>{if(!(U||!oe())){try{U=typeof r.openLogPush=="function"?r.openLogPush({push:ue=>{oe()&&(r.pushLog(ue),Lg())},live:Vc,ended:ue=>{if(!j){tt??=ue,Vc(!1);return}xa(ue)}}):null}catch{U=null}if(U){try{U.start()}catch{try{U.close()}catch{}U=null,Ia(!0);return}Vc(!1)}else Ia(!0)}},Ui=async()=>{let ue=D;D=null,await(ue??Bc()),ie(),B=!0,_s()},ok=()=>{if(!(V!=="pending"||!B)){try{V=r.keyringSettled?.()??"settled"}catch{return}V==="failed"&&sk(new hi("recovery_required"))}},sk=ue=>{X=ue,j=!1,v!==null&&clearTimeout(v),v=null,He()},pq=ue=>{let Ce=null;try{Ce=ue.server}catch{Ce=null}let st=rn(Ce)&&Rt(Ce)!==null?Ce:null,mi=!rn(Ce)&&ue instanceof pi&&ue.reason==="response",An=st?null:mi?{kind:"unreachable"}:Nd(ue);if(!st&&(An===null||An.kind==="auth")){sk(ue);return}nt=An?nt+1:0,(st!==Q||JSON.stringify(An)!==JSON.stringify(Ee))&&(Q=st,Ee=An,He())},As=()=>{if(!j||!oe())return;if(!y&&!So()&&!te){_||U?.suspend();return}if(v!==null||_)return;let ue=te?0:dr();te=!1,ue!==null&&(v=setTimeout(()=>{if(v=null,!oe())return;let Ce=y&&Date.now()>=Ao;Ce&&(Ao=Number.POSITIVE_INFINITY);let st=_=B?Ce?r.wakeCollectionLog({signal:b.signal}):r.driveCollection({signal:b.signal}):Ui().then(()=>r.driveCollection({signal:b.signal}));st.then(()=>{_===st&&(_=null),Vr=0,vs=!0,oe()&&(_o(),ok()),Dn?.(),As()},mi=>{_===st&&(_=null),Vr++,oe()&&(B?(_o(),ok()):pq(mi)),dn(mi),Dn?.(),As()})},ue))},Lg=()=>{oe()&&(te=!0,v!==null&&clearTimeout(v),v=null,As())},Ia=ue=>{ce!==ue&&(ce=ue,He())},Vc=ue=>{if(ee!==null&&clearTimeout(ee),ee=null,ue){Ia(!1);return}if(!U?.available){Ia(Ie===null);return}U.suspended||(ee=setTimeout(()=>{ee=null,oe()&&!U?.live&&Ia(!0)},_2))},ak=ue=>{if(ie(),ue){(!U?.live||Ee?.kind==="offline")&&(Ao=0),Vr=0,nt=0,Ee?.kind==="offline"&&(te=!0);try{U?.resume(),U&&!U.live&&Vc(!1)}catch{}}else y&&(ko=Date.now());y=ue,v!==null&&clearTimeout(v),v=null,As()},dq=()=>new Promise((ue,Ce)=>{let st,mi=null,An=Qn=>{Dn=null,mi!==null&&clearTimeout(mi),b.signal.removeEventListener("abort",Ca),Qn?Ce(Qn):ue()},Ca=()=>An(cr("fenced"));b.signal.addEventListener("abort",Ca,{once:!0}),Dn=()=>{if(!oe()){An(cr("fenced"));return}if(Ie!==null){An();return}let Qn="first_turn";if(vs)try{Qn=typeof r.initialSync=="function"?r.initialSync():null}catch{Qn="unavailable"}if(Qn===null||Qn==="offline"||Ee?.kind==="offline"){An();return}let yi=null;if(Qn==="waiting_for_key"&&typeof r.keyWaitDetail=="function")try{yi=r.keyWaitDetail()}catch{yi=null}let Ra=Qn+(yi?JSON.stringify(yi):"");if(Ra!==st){st=Ra;try{console.debug("mdbase: waiting for the first sync",{...yi,reason:Qn})}catch{}}},mi=setTimeout(()=>An(),jD),Dn()});c.addEventListener("abort",Ft,{once:!0});try{ie(),P=new Xl({...e.setupJournal,scope:m,isCurrent:oe});let ue=new qc({databaseName:e.joinDatabaseName,scope:m,isCurrent:oe});if(f)h("joining"),await r.bootstrapPrivateDevice({scope:m,collectionCurrent:oe,signal:b.signal,fetch:e.fetch,allowLoopbackHttp:e.allowLoopbackHttp}),ie();else{let Ct=await ue.prepare({signal:b.signal});ie(),h("joining"),await r.bootstrapCloudCopy({scope:m,collectionCurrent:oe,purpose:"join",outcomeMode:Ct.outcomeMode,signal:b.signal,...Ct.outcomeMode==="existing"?{reconcile:"explicit-unknown-outcome"}:{},fetch:e.fetch,allowLoopbackHttp:e.allowLoopbackHttp}),ie(),await ue.complete({signal:b.signal}),ie()}let Ce=r.registeredReceipt();if(Ce.installationId!==m.installation)throw cr("binding");let st=null,mi=async Ct=>{let Tt=await t(Ct);return st=Tt.ledger??null,Tt};h("opening_store"),await r.openCollectionSql({signal:b.signal,replicaId:Ce.deviceId,endpoint:0,openSql:mi}),ie();let An=!0;try{An=r.holdsLog?.()??!0}catch{An=!1}let Ca=!f&&An&&await ue.syncedBefore({signal:b.signal});ie();let Qn=async()=>{h("connecting_log");let Ct=Date.now()+ND;for(let Tt=0;;Tt++)try{await Bc(),ie();break}catch(gi){ie();let Fr=gi instanceof pi&&gi.reason==="unavailable"?gi.server:null;if(!rn(Fr)||Fr.status!==503||Fr.code!=="busy"||Rt(Fr)!==null||Tt+1>=DD)throw gi;let Fc=Fr.retryAfterMs??1e3*2**Tt;if(Date.now()+Fc>=Ct||(await ya(Fc,b.signal),ie(),Date.now()>=Ct))throw gi}B=!0};Ca?(D=Bc(),D.catch(()=>{})):await Qn();let yi=crypto.randomUUID(),Ra=null,lk=null,jg=null;if(f){h("syncing");let Ct=await r.settlePrivateKey({signal:b.signal});if(ie(),Ct==="locked"){let Tt=await r.accountKeyMode({signal:b.signal});ie(),q={mode:Tt,unlocking:!1,problem:null}}}let ck=async()=>{let Ct=f?await ue.syncedBefore({signal:b.signal}):Ca;ie();let Tt=!1;if(Ca&&!B)try{await r.waitForVerifiedRead({signal:b.signal,local:!0,timeoutMs:UD,onProgress:h}),ie(),Tt=!0}catch{ie();let Kt=D;D=null;let vt=Kt?await Kt.then(()=>!0,()=>!1):!1;ie(),vt?B=!0:await Qn()}if(Tt||(_s(),h("syncing"),await r.waitForVerifiedRead({signal:b.signal,cold:!Ct,onProgress:h}),ie()),j=!0,r.onLogWork?.(Lg),tt!==null){let Kt=tt;tt=null,xa(Kt)}Tt?(V="pending",te=!0,As(),ee=setTimeout(()=>{ee=null,oe()&&!U?.live&&Ia(!0)},_2)):(As(),Ct&&(h("syncing"),await dq()),ie()),h("checking_setup"),ue.markSynced({signal:b.signal}).catch(()=>{});let gi=await P.load(b.signal);ie();let Fr=gi&&gi.version!==1&&(gi.phase==="attempted"||gi.phase==="confirmed")?"reconcile-original":gi===null&&p==="approved-new-collection"?"approved-new":"inspect",Fc=e.people===!0&&!f,pk=Fc?{people:!0}:f?{privateDevice:!0}:{},hq={owner:null},dk=(Kt,vt,Wt,Kr)=>cR(vt,{scope:m,generation:yi},{journal:P,resourceSetup:r.attachDataFacade(Kt),signal:b.signal,isCurrent:oe,ledger:()=>oe()?st:null,setupTurn:hq,assess(Kc){ie(),R=Kc,He()},foreground:Wt,onProtocolFailure:Kr,...Fc?{peopleAuthority:r.peopleAuthority()}:{}});x=r.openTimersPort({scope:m,generation:yi,signal:b.signal}),ie();let mq=K()??null;I=new MessageChannel,O=new MessageChannel,S=dk(I.port1,O.port1,ak,Ft),ie();let Ug=Kt=>{if(Y.delete(Kt.dataPort),I&&O&&Kt.dataPort===I.port2){let Wt={data:I,command:O,control:S,timers:x};I=null,O=null,S=null,x=null;try{r.detachDataFacade(Wt.data.port1)}catch{}Wt.timers?.close().catch(()=>{}),Wt.control?.close().catch(()=>{});for(let Kr of[Wt.data.port1,Wt.command.port1])try{Kr.close()}catch{}return}let vt=$.get(Kt.dataPort);if(vt){$.delete(Kt.dataPort);try{r.detachDataFacade(vt.data.port1)}catch{}vt.timers?.close().catch(()=>{}),vt.control.close().catch(()=>{});for(let Wt of[vt.data.port1,vt.command.port1])try{Wt.close()}catch{}}},uk=(Kt=Fr==="reconcile-original"?Fr:"inspect")=>{if(!oe()||Ie!==null)return null;let vt=new MessageChannel,Wt=new MessageChannel,Kr=null,Kc=null;try{Kr=r.openTimersPort({scope:m,generation:yi,signal:b.signal});let Oa=null,gq=K()??null;return Kc=dk(vt.port1,Wt.port1,()=>{},()=>{Oa&&Ug(Oa)}),Oa=Object.freeze({schema:"mdbn-app-collection/1",scope:m,generation:yi,displayName:u,setupMode:Kt,dataPort:vt.port2,controlPort:Wt.port2,...pk,...Kr?{timerPort:Kr.port}:{}}),$.set(vt.port2,{data:vt,command:Wt,control:Kc,timers:Kr}),Y.set(vt.port2,gq),Oa}catch{try{r.detachDataFacade(vt.port1)}catch{}Kr?.close().catch(()=>{}),Kc?.close().catch(()=>{});for(let Oa of[vt.port1,vt.port2,Wt.port1,Wt.port2])Oa.close();return null}},yq=Kt=>{if(!oe()||!Y.has(Kt.dataPort))return null;let vt=K();if(vt===void 0||vt===Y.get(Kt.dataPort))return null;let Wt=uk(Kt.setupMode);return Wt&&Ug(Kt),Wt};Ra=uk,lk=Ug,jg=yq,Y.set(I.port2,mq),e.handoff(Object.freeze({schema:"mdbn-app-collection/1",scope:m,generation:yi,displayName:u,setupMode:Fr,dataPort:I.port2,controlPort:O.port2,...pk,...x?{timerPort:x.port}:{}})),ie(),As()},uq=Object.freeze({scope:m,generation:yi,isCurrent:oe,setForeground:ak,attach:()=>Ra?Ra():null,detach:Ct=>{lk?.(Ct)},renewTimers:Ct=>jg?jg(Ct):null}),fq={get state(){return oe()?q?"needs_unlock":R:"setup_required"},get locked(){return oe()&&q?Object.freeze({...q}):null},get problem(){return oe()?Q:null},get health(){return oe()?Ee:null},get live(){return oe()?!ce:null},get ended(){return oe()?Ie:null},get failure(){return oe()?X:null},connection:uq,close:Fe,subscribe(Ct){return ie(),Ae.add(Ct),()=>{Ae.delete(Ct)}},...f?{unlock:async Ct=>{if(ie(),!q||q.unlocking)throw cr("binding");q={mode:q.mode,unlocking:!0,problem:null},He();try{await r.unlockAccountKey(Ct,{signal:b.signal,onMode:Tt=>{q&&oe()&&(q={...q,mode:Tt})}}),ie()}catch(Tt){if(Tt instanceof pt&&oe()&&q){q={mode:q.mode,unlocking:!1,problem:Tt.reason},He();return}throw await Fe(),Tt}try{await ck(),ie()}catch(Tt){throw await Fe(),Tt}q=null,He()}}:{}};return q||await ck(),ie(),Object.freeze(fq)}catch(ue){throw await Fe(),ue}}}async function Ag(n,e){if(n.schema!=="mdbn-app-collection/1"||Tc.has(n.dataPort)||Tc.has(n.controlPort)||n.dataPort===n.controlPort||!["inspect","approved-new","reconcile-original"].includes(n.setupMode)||n.people!==void 0&&n.people!==!0||n.privateDevice!==void 0&&(n.privateDevice!==!0||n.people!==void 0)||e.signal.aborted||n.timerPort&&(Tc.has(n.timerPort)||n.timerPort===n.dataPort||n.timerPort===n.controlPort))throw cr("binding");Tc.add(n.dataPort),Tc.add(n.controlPort),n.timerPort&&Tc.add(n.timerPort);let t=Object.freeze({...n.scope}),i=n.generation,o=n.setupMode,s=n.people===!0,r=n.dataPort,a=n.controlPort,c=e.signal,l=!1,p=null,d=null,u=null,f,h=()=>{if(!l){l=!0,c.removeEventListener("abort",h);for(let m of[()=>f?.close(),()=>d?.close(),()=>p?.close(),()=>u?.close(),()=>r.close(),()=>a.close()])try{m()}catch{}}};c.addEventListener("abort",h,{once:!0});try{if(u=ey(r,{...t,isCurrent:()=>!l&&!c.aborted}),d=Zm(a,{scope:t,generation:i},{signal:c,isCurrent:()=>!l,onClose:h,...s?{people:!0}:{}}),n.timerPort&&(f=new Ha(IE(n.timerPort,{scope:t,generation:i},{signal:c,onClose:()=>{}}),{criteria:e.timerCriteria??[]})),p=await wr.connect({app:e.app,connector:u,reconnect:!1,signal:c,ledger:d.ledger}),l||c.aborted)throw p.close(),cr("fenced");let m=s?Jm(p,d):void 0;return Object.freeze({client:p,resourceSetup:d.resourceSetup,...m?{people:m}:{},journal:d.journal,scope:t,setupMode:o,close:h,...f?{timers:f}:{},assess:(w,b)=>d.assess(w,b),setForeground:(w,b)=>d.setForeground(w,b)})}catch(m){throw h(),m}}var _2,LD,jD,UD,ND,DD,vu,cr,Tc,q0=C(()=>{"use strict";ri();Od();wu();Wy();iy();Ls();_w();JA();eR();_g();Qs();ss();ty();gu();Ld();_2=1e4,LD=12e4,jD=2e3,UD=5e3,ND=15e3,DD=3,vu=class extends Error{constructor(t){super(`app web collection: ${t}`);this.reason=t;this.name="AppWebCollectionError"}reason},cr=n=>new vu(n);Tc=new WeakSet});function zD(n,e){return Object.freeze({collection:n,isCurrent:e,request:()=>Promise.reject(A("upgrade_required","People is not available for a Private collection opened by this app","people_unsupported"))})}var pn,kg,$D,Mc,T0=C(()=>{"use strict";q0();re();xp();pn=class extends Error{constructor(t){super("SDK application connection unavailable");this.code=t;this.name="ApplicationUiConnectionError"}code},kg=new WeakSet;$D=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,Mc=class{app;signal;current=null;pending=null;opening=null;retiring=null;closing=null;epoch=0;timerCriteria;constructor(e,t,i=[]){this.app=Object.freeze({...e}),this.signal=t,this.timerCriteria=Object.freeze([...i]),t.addEventListener("abort",this.abort,{once:!0})}abort=()=>{this.close().catch(()=>{})};connection(e){let t=this.current?.public;return t?.id===e&&t.isCurrent()?t:null}owned(){return this.current?.public.isCurrent()?this.current.ui:null}adopt(e,t){let i=t.caller,o=t.isCurrent,s=[e.dataPort,e.controlPort,...e.timerPort?[e.timerPort]:[]];if(s.some(y=>!(y instanceof MessagePort))||new Set(s).size!==s.length||s.some(y=>kg.has(y))){for(let y of new Set(s))y instanceof MessagePort&&!kg.has(y)&&(kg.add(y),y.close());return Promise.reject(new pn("application_connection_binding"))}for(let y of s)kg.add(y);let r=y=>{for(let v of s)v.close();return Promise.reject(new pn(y))};if(this.pending||this.current||this.retiring)return r("application_connection_busy");if(this.closing||this.signal.aborted||i.aborted||!o())return r("application_connection_fenced");let a=Object.freeze({...e.scope}),c=e.generation,l=e.displayName;if(e.schema!=="mdbn-app-collection/1"||Object.keys(a).sort().join()!=="account,collection,installation"||Object.values(a).some(y=>!$D.test(y)||y==="00000000-0000-0000-0000-000000000000")||typeof c!="string"||!c||c.length>256||typeof l!="string"||!l.trim()||new TextEncoder().encode(l).length>4096||!["inspect","approved-new","reconcile-original"].includes(e.setupMode))return r("application_connection_binding");let p=e.privateDevice===!0;if(e.privateDevice!==void 0&&(!p||e.people!==void 0))return r("application_connection_binding");if(e.people!==!0&&!p)return r("application_connection_people_unavailable");let d=Object.freeze({...e,scope:a,generation:c,displayName:l}),u=new AbortController,f=this.epoch;this.opening=u;let h=()=>u.abort();i.addEventListener("abort",h,{once:!0});let m=AbortSignal.any([this.signal,u.signal]),w=()=>!m.aborted&&!this.closing&&!this.retiring&&this.epoch===f&&o(),b=null,g=Promise.resolve().then(async()=>{if(!w()||i.aborted)throw new pn("application_connection_fenced");if(b=await Ag(d,{app:this.app,signal:m,timerCriteria:this.timerCriteria}),!w()||i.aborted)throw new pn("application_connection_fenced");if(b.client.collection!==a.collection||b.client.link!=="open")throw new pn("application_connection_binding");if(p?b.people!==void 0:!b.people)throw new pn(p?"application_connection_binding":"application_connection_people_unavailable");let y=b,v=b.people??new vr(y.client,zD(a.collection,()=>w()&&this.current?.ui===y&&y.client.link==="open")),_=Object.freeze({id:a.collection,scope:a,generation:c,displayName:l,records:y.client,files:y.client.files,people:v,...y.timers?{timers:y.timers}:{},isCurrent:()=>w()&&this.current?.ui===y&&y.client.link==="open"});return this.current={public:_,ui:y,lifetime:u},_}).catch(y=>{u.abort(),b?.close();for(let v of s)v.close();throw y}).finally(()=>{i.removeEventListener("abort",h),this.pending===g&&(this.pending=null,this.opening=null)});return this.pending=g,g}retire(){if(this.retiring)return this.retiring;++this.epoch;let e=this.current,t=this.pending;this.opening?.abort(),e?.lifetime.abort();let i=Promise.resolve().then(async()=>{await t?.catch(()=>{}),e?.ui.close(),this.current===e&&(this.current=null)});return this.retiring=i,i.then(()=>{this.retiring===i&&(this.retiring=null)},()=>{}),i}close(){return this.closing?this.closing:(this.closing=Promise.resolve().then(()=>this.retire()),this.signal.removeEventListener("abort",this.abort),++this.epoch,this.opening?.abort(),this.current?.lifetime.abort(),this.closing)}}});function HD(n){if(n.capabilityContractVersion!==2)throw A("upgrade_required","unsupported readiness capability projection","readiness_capability_version");if(!Array.isArray(n.contracts)||n.contracts.length>128||!Array.isArray(n.requiredNativeCapabilities)||n.requiredNativeCapabilities.length>64)throw Vt("unsupported");let e=n.contracts.map(i=>{if(!i||!jc(i.id,256)||!jc(i.version,128)||!WD.test(i.digest))throw Vt("unsupported");return Object.freeze({id:i.id,version:i.version,digest:i.digest})}),t=n.requiredNativeCapabilities.map(i=>{if(!jc(i,128))throw Vt("unsupported");return i});if(new Set(e.map(i=>JSON.stringify([i.id,i.version]))).size!==e.length||new Set(t).size!==t.length||n.typeIssues!==void 0&&n.typeIssues!=="block"&&n.typeIssues!=="degrade")throw Vt("unsupported");return Object.freeze({capabilityContractVersion:2,typeIssues:n.typeIssues??"block",contracts:Object.freeze(e),requiredNativeCapabilities:Object.freeze(t)})}function GD(n){let e=de(n,"path");return typeof e=="string"&&e?e:null}function Lc(n,e){return Object.freeze({reason:n,...n==="fenced"&&e?{detail:e}:{}})}function M0(n){if(!J(n))return;let e=de(n.details,"condition"),t=BD.find(i=>i===e);if(t)return t;if(n.code==="unauthenticated")return"read_unauthenticated";if(n.code==="cancelled")return"read_cancelled"}function L0(n){try{if(J(n)){if(n.code==="unauthenticated"||n.code==="cancelled")return"fenced";if(n.code==="too_large")return"budget";if(n.code==="upgrade_required"||n.code==="forbidden")return"unsupported";if(n.reason==="readiness_changed"||n.reason==="cursor_stale"||n.reason==="cursor_expired")return"changed";if(n.reason==="readiness_busy")return"busy";if(n.reason==="readiness_catalog_response")return"catalog_response"}}catch{}return"unavailable"}function U0(n){let e=n.status;return JSON.stringify([e.mode,e.confirmedThrough,e.headKnown,e.pending,e.holds,e.unresolved,e.connection,e.installing,e.resyncing,e.incidents.map(t=>t.kind),e.confirmedHead])}function N0(n){return n.mode==="local_only"}function Uc(n){return JSON.stringify(n,(e,t)=>typeof t=="bigint"?`${t}n`:t instanceof Uint8Array?[...t]:t)}function S2(n,e,t){return new j0(n,e,t)}var BD,VD,FD,KD,k2,WD,jc,Vt,j0,D0=C(()=>{"use strict";re();un();BD=["binding_invalid","binding_aborted","binding_not_current","readiness_closed","read_aborted","session_closed","session_replaced","session_collection_mismatch","read_unauthenticated","read_cancelled"],VD=4096,FD=2*1024*1024,KD=64,k2=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,WD=/^sha256:[0-9a-f]{64}$/,jc=(n,e=4096)=>typeof n=="string"&&!!n.trim()&&new TextEncoder().encode(n).length<=e,Vt=(n,e)=>A(n==="fenced"?"unauthenticated":n==="budget"?"too_large":"unavailable","collection readiness unavailable",{reason:`readiness_${n}`,...e?{details:{condition:e}}:{}});j0=class{constructor(e,t,i){this.client=e;if(this.declared=HD(t),!k2.test(i.collection)||i.collection==="00000000-0000-0000-0000-000000000000"||!k2.test(i.generation))throw Vt("fenced","binding_invalid");this.binding=Object.freeze({collection:i.collection,generation:i.generation,signal:i.signal,isCurrent:i.isCurrent.bind(i)}),this.readSignal=AbortSignal.any([this.binding.signal,this.lifetime.signal]),this.check(),this.binding.signal.addEventListener("abort",this.abort,{once:!0})}client;declared;binding;lifetime=new AbortController;readSignal;listeners=new Set;snapshotValue=Object.freeze({checking:!1,assessment:null,problem:null});watch=null;stops=[];pending=null;epoch=0;dirty=!1;scheduled=!1;retries=0;failures=0;closed=!1;lastStatus=null;assessedSession;assessedEpoch;assessedCatalog=null;probing=null;probeAgain=!1;abort=()=>{this.close()};getSnapshot(){if(this.snapshotValue.assessment)try{this.check(void 0,this.assessedSession,this.assessedEpoch)}catch(e){let t=L0(e);t==="fenced"&&!this.closed&&!this.binding.signal.aborted&&this.binding.isCurrent()===!0&&(t="changed"),this.retryLater(t)||this.publish({checking:!1,assessment:null,problem:Lc(t,M0(e))})}return this.snapshotValue}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}publish(e){this.snapshotValue=Object.freeze(e);for(let t of this.listeners)try{t()}catch{}}check(e,t,i){e?.throwIfAborted();let o=this.fenceDetail(e);if(o)throw Vt("fenced",o);if(t?.closed)throw Vt("fenced","session_closed");if(t&&t!==this.client.currentSession())throw Vt("fenced","session_replaced");if(t&&t.hello.collection!==this.binding.collection)throw Vt("fenced","session_collection_mismatch");if(i!==void 0&&(i!==this.epoch||this.watch?.state!=="active"))throw Vt("changed")}fenceDetail(e){if(this.binding.signal.aborted)return"binding_aborted";if(this.closed)return"readiness_closed";if(e?.aborted)return"read_aborted";if(this.binding.isCurrent()!==!0)return"binding_not_current"}invalidate=()=>{if(this.closed)return;if(this.pending||!this.snapshotValue.assessment||this.assessedCatalog===null||this.client.link!=="open"){this.recheck();return}if(this.probing){this.probeAgain=!0;return}let e=this.snapshotValue.assessment,t=this.assessedCatalog,i=this.client.describe({signal:this.readSignal}).then(o=>{this.closed||this.snapshotValue.assessment!==e||Uc(o)!==t&&this.recheck()},()=>{this.closed||this.recheck()});this.probing=i.finally(()=>{this.probing=null,this.probeAgain&&!this.closed&&(this.probeAgain=!1,this.invalidate())})};recheck(){this.closed||(this.epoch++,this.dirty=!0,this.publish({checking:!0,assessment:null,problem:null}),this.schedule())}schedule(){if(this.closed||this.pending||this.scheduled||!this.dirty||this.watch?.state!=="active"||this.client.link!=="open")return;this.scheduled=!0;let e=()=>{this.scheduled=!1,!this.closed&&this.dirty&&!this.pending&&this.watch?.state==="active"&&this.client.link==="open"&&this.refresh(void 0,!0).catch(()=>{})};this.retries?setTimeout(e,Math.min(5e3,100*2**this.retries,this.retrySince===null?5e3:Math.max(0,15e3-(Date.now()-this.retrySince)))):queueMicrotask(e)}retrySince=null;retryLater(e,t=!1){if(this.closed)return!1;if((e==="busy"||e==="changed")&&(this.retrySince??=Date.now(),Date.now()-this.retrySince>=15e3))return this.dirty=!1,this.publish({checking:!1,assessment:null,problem:Lc("busy_timeout")}),!0;if(e==="unavailable"&&t&&this.failures<5)this.failures++;else if(e!=="changed"&&e!=="busy")return!1;return this.dirty=!0,this.retries=Math.min(this.retries+1,6),this.publish({checking:!0,assessment:null,problem:null}),this.schedule(),!0}attach(){this.watch||(this.watch=this.client.watchChanges(this.invalidate),this.stops.push(this.watch.subscribe(this.invalidate),this.client.onLink(this.invalidate),this.client.onStatus(e=>{let t=U0(this.client);(t!==this.lastStatus||N0(e))&&(this.lastStatus=t,this.invalidate())})))}start(e){return this.refresh(e)}refresh(e,t=!1){try{if(this.check(e),this.pending)throw Vt("busy")}catch(a){return Promise.reject(a)}t||(this.retrySince=null);let i=AbortSignal.any([this.binding.signal,this.lifetime.signal,...e?[e]:[]]),o,s,r=Promise.resolve().then(async()=>{this.check(i),this.attach();let a=await this.client.readyForRead(i);this.check(i,a),await this.watch.ready,this.check(i,a);let c=this.epoch;this.dirty=!1,this.check(i,a,c);let l=await this.inventory(i,a,c),p=await this.client.describe({signal:this.readSignal});this.check(i,a,c);let d=this.evaluate(p,a),u=Uc(p);for(let w of d.paths){let b=l.find(y=>y.path===w);if(!b)throw Vt("changed");let g=await this.client.resources.get(w,{signal:this.readSignal});if(this.check(i,a,c),g.path!==b.path||g.revision!==b.revision||g.size!==b.size||g.state!=="confirmed")throw Vt("changed")}let f=await this.inventory(i,a,c);if(JSON.stringify(l)!==JSON.stringify(f))throw Vt("changed");this.check(i,a,c);let h=Object.freeze({collection:this.binding.collection,generation:this.binding.generation,resources:Object.freeze(f)}),m=Object.freeze({status:d.status,problem:d.reason?Lc(d.reason):null,witness:h,...d.unavailable.length?{unavailableTypes:Object.freeze(d.unavailable)}:{}});return o=a,s=c,this.retries=0,this.failures=0,this.retrySince=null,this.assessedSession=a,this.assessedEpoch=c,this.assessedCatalog=u,this.publish({checking:!1,assessment:m,problem:m.problem}),this.check(i,a,c),m}).catch(a=>{let c=i.aborted||this.closed?"fenced":L0(a);throw this.retryLater(c,t)||this.publish({checking:!1,assessment:null,problem:Lc(c,this.fenceDetail(i)??M0(a))}),a});return this.pending=r,this.publish({checking:!0,assessment:null,problem:null}),r.finally(()=>{this.pending===r&&(this.pending=null),this.schedule()}).catch(()=>{}),r.then(a=>{try{if(this.check(i,o,s),this.snapshotValue.assessment!==a)throw Vt("changed");return a}catch(c){let l=i.aborted?"fenced":L0(c);throw this.snapshotValue.assessment===a&&!this.retryLater(l)&&this.publish({checking:!1,assessment:null,problem:Lc(l,this.fenceDetail(i)??M0(c))}),c}})}async inventory(e,t,i){let o=[],s=new Set,r,a="",c=0;for(let l=0;l<KD;l++){this.check(e,t,i);let p=await this.client.resources.list({text:!1,limit:128,...r?{cursor:r}:{},signal:this.readSignal});this.check(e,t,i);for(let d of p.resources){if(!jc(d.path)||d.path<=a||!jc(d.revision,128)||!Number.isSafeInteger(d.size)||d.size<0||d.state!=="confirmed")throw Vt("catalog_response");a=d.path;let u=Object.freeze({path:d.path,revision:d.revision,size:d.size,state:d.state});if(c+=new TextEncoder().encode(JSON.stringify(u)).length,o.length>=VD||c>FD)throw Vt("budget");o.push(u)}if(p.complete===!0&&p.cursor===void 0)return o;if(p.complete!==!1||!jc(p.cursor)||s.has(p.cursor))throw Vt("catalog_response");s.add(p.cursor),r=p.cursor}throw Vt("budget")}evaluate(e,t){let i=e.issues.filter(d=>d.severity==="error"),o=new Set;for(let d of i){let u=GD(d.details);if(!u)return{status:"incompatible",reason:"catalog_invalid",paths:[],unavailable:[]};o.add(u)}let s={status:"incompatible",reason:"catalog_invalid",paths:[],unavailable:[]};if(this.declared.requiredNativeCapabilities.some(d=>!t.hello.grant.capabilities.includes(d)))return{status:"incompatible",reason:"capability_missing",paths:[],unavailable:[]};let r=new Set,a=new Set,c=new Set;for(let d of e.contracts){let u=JSON.stringify([d.id,d.version]);if(a.has(u))return{status:"incompatible",reason:"catalog_response",paths:[],unavailable:[]};a.add(u)}for(let d of e.types){if(c.has(d.name))return{status:"incompatible",reason:"catalog_response",paths:[],unavailable:[]};c.add(d.name)}let l,p=[];for(let d of this.declared.contracts){let u=e.contracts.find(f=>f.id===d.id&&f.version===d.version);if(!u){l??="contract_missing";continue}if(u.digest!==d.digest)return{status:"incompatible",reason:"contract_mismatch",paths:[],unavailable:[]};if(r.add(u.path),o.has(u.path))return s;if(!u.implementedBy.length){l??="implementation_missing";continue}for(let f of u.implementedBy){let h=e.types.find(m=>m.name===f);if(!h||!h.implements.some(m=>m.contract===d.id&&m.version===d.version))return{status:"incompatible",reason:"catalog_response",paths:[],unavailable:[]};if(r.add(h.path),o.has(h.path)){if(this.declared.typeIssues!=="degrade")return s;p.some(m=>m.name===h.name)||p.push(Object.freeze({name:h.name,path:h.path,contract:Object.freeze({id:d.id,version:d.version}),problem:Object.freeze({code:"readiness_type_invalid"})}))}}}return{status:l?"setup_required":"ready",...l?{reason:l}:{},paths:[...r].sort(),unavailable:p}}async close(){if(!this.closed){this.closed=!0,this.dirty=!1,this.lifetime.abort(),this.binding.signal.removeEventListener("abort",this.abort);for(let e of this.stops.splice(0))e();this.watch?.(),this.watch=null,this.publish({checking:!1,assessment:null,problem:Lc("fenced",this.fenceDetail())})}await this.pending?.catch(()=>{})}}});function JD(n){let e=o=>o?Object.freeze({code:`readiness_${o.reason}`,...o.detail?{detail:o.detail}:{}}):null,t=e(n.problem),i=n.assessment?.unavailableTypes;return Object.freeze({checking:n.checking,assessment:n.assessment?Object.freeze({status:n.assessment.status,problem:e(n.assessment.problem),...i?.length?{unavailableTypes:i}:{}}):null,problem:t})}var P2,YD,_u,Br,Sg,x2=C(()=>{"use strict";Tp();re();D0();P2=["configuration","files"],YD=["people","notifications"],_u=class extends Error{constructor(t,i){super("SDK application readiness unavailable");this.code=t;this.detail=i;this.name="ApplicationReadinessError"}code;detail},Br=(n,e=!1,t)=>Object.freeze({checking:e,assessment:null,problem:n?Object.freeze({code:n,...t?{detail:t}:{}}):null});Sg=class{connection;signal;observed;native;sources;listeners=new Set;stops=[];pending=null;closing=null;checking=!1;closed=!1;advisory=Promise.resolve();lastReady=null;constructor(e){this.connection=e.connection,this.signal=e.signal,this.observed=e.isCurrent,this.sources=Object.freeze({configuration:e.configuration,files:e.files,people:e.people,notifications:e.notifications}),this.native=e.nativeRequirements?S2(this.connection.records,e.nativeRequirements,{collection:this.connection.id,generation:this.connection.generation,signal:this.signal,isCurrent:()=>this.current()}):null,this.native&&this.stops.push(this.native.subscribe(this.changed));for(let t of Object.values(this.sources))t&&this.stops.push(t.subscribe(this.changed));this.signal.addEventListener("abort",this.abort,{once:!0})}fenceDetail(){try{return this.signal.aborted?"scope_aborted":this.closed?"scope_closed":this.observed()!==!0?"observer_not_current":this.connection.isCurrent()?this.connection.records.collection!==this.connection.id?"collection_mismatch":null:"connection_not_current"}catch{return"currentness_check_failed"}}current(){return this.fenceDetail()===null}connectionProblem(){if(!this.closed&&!this.signal.aborted&&this.connection.records.collection===this.connection.id&&this.connection.records.link==="closed"){let e=this.connection.records.linkProblem;if(J(e)){let t=Us(e);return t&&t.key!=="unknown"?t.key:e.code}}return"readiness_fenced"}changed=()=>{for(let e of[...this.listeners])try{e()}catch{}};abort=()=>{this.close().catch(()=>{})};subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getSnapshot(){let e=this.current(),t=Br(e?"readiness_unsupported":"readiness_fenced"),i=t;if(e&&this.native){let u=this.native.getSnapshot(),f=u.assessment?.witness,h=f&&f.collection!==this.connection.id?"native_witness_collection_mismatch":f&&f.generation!==this.connection.generation?"native_witness_generation_mismatch":null;i=h?Br("readiness_fenced",!1,h):JD(u)}let o=u=>{if(!e)return t;let f=this.sources[u];if(!f)return Br(`${u}_unsupported`);try{let h=f.getSnapshot();return Object.freeze({checking:h.checking,assessment:h.assessment?Object.freeze({...h.assessment,problem:h.assessment.problem?Object.freeze({...h.assessment.problem}):null}):null,problem:h.problem?Object.freeze({...h.problem}):null})}catch{return Br(`${u}_unavailable`)}},s=Object.freeze({capabilities:i,contracts:i,configuration:o("configuration"),files:o("files"),people:o("people"),notifications:o("notifications")}),r=[s.capabilities,s.contracts,s.configuration,s.files],a=e&&(this.checking||r.some(u=>u.checking)),c=null,l=null;if(!e)l=Object.freeze({code:"readiness_fenced"});else if(!a){let u=["capabilities","contracts",...P2].find(f=>s[f].problem);if(l=u?s[u].problem:null,u&&l?.code==="readiness_fenced"&&!l.detail&&(l=Object.freeze({...l,detail:`${u}_facet`})),r.every(f=>f.assessment!==null)){let f=s.configuration.assessment?.status==="setup_required",h=y=>y.assessment?.status==="incompatible"&&!(f&&y===i&&y.assessment.problem?.code==="readiness_contract_mismatch"),m=r.find(h),w=r.find(y=>y.assessment?.status==="setup_required"),b=m??w,g=i.assessment?.unavailableTypes;c=Object.freeze({status:m?"incompatible":w?"setup_required":"ready",problem:b?.assessment?.problem??null,...g?.length?{unavailableTypes:g}:{}})}}let p=this.fenceDetail();if(p)return this.lastReady=null,Object.freeze({checking:!1,assessment:null,problem:Object.freeze({code:this.connectionProblem(),detail:p}),facets:Object.freeze({capabilities:Br("readiness_fenced",!1,p),contracts:Br("readiness_fenced",!1,p),configuration:Br("readiness_fenced",!1,p),files:Br("readiness_fenced",!1,p),people:Br("readiness_fenced",!1,p),notifications:Br("readiness_fenced",!1,p)})});let d=!l||/_(changed|busy)$/.test(l.code);if(l===null&&c!==null&&!a)this.lastReady=Object.freeze({checking:a,assessment:c,problem:l,facets:s});else{if(this.lastReady&&d&&(a||c===null)&&(this.lastReady.assessment?.status==="ready"||!this.checking))return Object.freeze({...this.lastReady,facets:s});this.lastReady=null}return Object.freeze({checking:a,assessment:c,problem:l,facets:s})}refresh(e={}){let t=e.signal,i=this.fenceDetail()??(t?.aborted?"caller_aborted":null);if(i)return Promise.reject(new _u("application_readiness_fenced",i));if(this.pending)return Promise.reject(new _u("application_readiness_busy"));this.checking=!0;let o=Promise.resolve().then(async()=>{if(!this.current())return this.getSnapshot();await this.advisory;let s=[],r=async(c,l)=>{try{await l()}catch(p){let d=!1;try{d=c.getSnapshot().checking===!0}catch{}if(!d||!this.current())throw p;s.push(p)}},a=this.native;a&&await r(a,()=>a.start());for(let c of P2){let l=this.sources[c];if(!this.current())break;l&&await r(l,()=>l.refresh())}if(await this.reassessAfterSetup(),s.length)throw s[0];return this.getSnapshot()}).finally(()=>{if(this.pending!==o)return;this.pending=null,this.checking=!1;let s=(async()=>{for(let r of YD){let a=this.sources[r];if(!this.current())break;a&&await a.refresh().catch(()=>{})}})();this.advisory=s,this.changed()}).then(()=>this.getSnapshot());return this.pending=o,this.changed(),o.then(s=>{let r=this.fenceDetail()??(t?.aborted?"caller_aborted":null);if(r)throw new _u("application_readiness_fenced",r);return s})}async reassessAfterSetup(){if(!this.native||!this.current())return;let e=this.native.getSnapshot(),t=null;try{t=this.sources.configuration?.getSnapshot()??null}catch{}e.checking||e.assessment?.status!=="setup_required"||t?.checking||t?.assessment?.status!=="ready"||await this.native.start().catch(i=>{if(!(J(i)&&i.reason==="readiness_busy"))throw i})}close(){return this.closing?this.closing:(this.closed=!0,this.checking=!1,this.signal.removeEventListener("abort",this.abort),this.closing=Promise.resolve().then(async()=>{for(let e of this.stops.splice(0))e();for(let e of Object.values(this.sources))await e?.close();await this.native?.close(),await this.pending?.catch(()=>{}),await this.advisory,this.listeners.clear()}),this.changed(),this.closing)}}});function XD(n){let e=new Set,t=[],i=[];for(let o of n.review?.packs??[]){if(o.status!=="conflict"&&o.status!=="downgrade")continue;let s=o.installedVersion?Ns(o.installedVersion,o.version):"unknown";s==="installed_newer"&&!o.resources.some(r=>r.action==="conflict")?(e.add(o.id),i.push(Object.freeze({id:o.id,version:o.version,installedVersion:o.installedVersion}))):s==="installed_newer_major"&&t.push(o.id)}return Object.freeze({kept:Object.freeze(i),compatible:e,major:Object.freeze(t)})}function ZD(n,e){let t=n,i=t.provisions?.type_packs;return!e.size||!Array.isArray(i)?n:{...t,provisions:{...t.provisions,type_packs:i.filter(o=>!(typeof o?.manifest?.id=="string"&&e.has(o.manifest.id)))}}}function C2(n){return new Proxy({},{get(e,t){let i=Reflect.get(n,t,n);return typeof i!="function"?i:async(...o)=>{let s=o.find(a=>a instanceof AbortSignal),r=Date.now()+QD;for(let a=25;;a=Math.min(a*2,500))try{return await i.apply(n,o)}catch(c){if(!(c instanceof Ei&&c.reason==="busy")||!s)throw c;if(Date.now()+a>r)throw Xe("busy_timeout");await e4(a,s)}}}})}function O2(n,e){let t=Object.freeze({...n,scope:Object.freeze({...n.scope}),journal:C2(n.journal)});if(e&&(e=C2(e)),Object.values(t.scope).some($=>!I2.test($)||/^0{8}-0{4}-0{4}-0{4}-0{12}$/.test($))||!I2.test(t.generation)||!["inspect","approved-new","reconcile-original"].includes(t.setupMode))throw Xe("binding");let i=JSON.stringify([t.scope.account,t.scope.installation,t.scope.collection]),o=new AbortController,s=AbortSignal.any([t.signal,o.signal]),r=new Set,a=bo(),c=null,l=null,p=!1,d,u=null,f=!1,h=!1,m=0,w=!1,b=!1,g=null,y=null,v=()=>{try{return JSON.stringify([t.client.link,U0(t.client)])}catch{return null}},_=[],k=new WeakMap;function S($,Y){if($?.throwIfAborted(),p||s.aborted||t.isCurrent()!==!0||JSON.stringify([t.journal.scope.account,t.journal.scope.installation,t.journal.scope.collection])!==i||Y&&(Y.closed||t.client.currentSession()!==Y||Y.hello.collection!==t.scope.collection))throw Xe("fenced")}function x($){a=Object.freeze($);for(let Y of r)try{Y()}catch{}}function P(){if(p)return;let $=v();if($!==null&&$===y)return;if(y=$,c||!a.assessment||u===null||t.client.link!=="open"){I();return}if(f){h=!0;return}f=!0;let Y=a,K=u;t.client.describe({signal:s}).then(Q=>{!p&&a===Y&&Uc(Q)!==K&&I()},()=>{p||I()}).finally(()=>{f=!1,h&&!p&&(h=!1,y=null,P())})}function I(){p||(w=!0,c||x(bo(null,!0)),O())}function O(){p||c||b||!w||(b=!0,setTimeout(()=>{if(b=!1,p||c||!w)return;let $=te(!1,{},void 0,!0);g=c,$.catch(()=>{})},m?Math.min(5e3,250*2**m):50))}function R(){if(a.assessment)try{S(void 0,d)}catch{p||s.aborted||t.isCurrent()!==!0?x(bo("configuration_fenced")):(w=!0,y=null,x(bo(null,!0)),O())}return a}async function q($,Y,K){let Q=await t.client.awaitReceipt($.mutationId,{timeoutMs:12e4,signal:s});if(S(Y,K),Q.mutation!==$.mutationId||Q.state!=="confirmed"||Q.status!=="applied"||(Q.conflicts?.length??0)!==0||Q.published==="publishing"||Q.published==="not_published")throw Xe("recovery_required");return Q}async function j($,Y,K){let Q,Ae=0,oe=0,ie=new Set,He=new Set,Fe=new TextEncoder;for(let Ft=0;Ft<64;Ft++){S(Y,K);let Ee=await t.client.resources.list({text:!1,limit:128,...Q===void 0?{}:{cursor:Q},signal:s});if(S(Y,K),Ee.resources.length>128)throw Xe("recovery_required");for(let nt of Ee.resources){let dr=Fe.encode(nt.path).length;if(Ae++,oe+=dr+128,!nt.path||dr>4096||He.has(nt.path)||nt.state!=="confirmed"||!z0.test(nt.revision)||!Number.isSafeInteger(nt.size)||nt.size<0||Ae>4096||oe>2*1024*1024||$.has(nt.path))throw Xe("recovery_required");He.add(nt.path)}if(Ee.complete===!0&&Ee.cursor===void 0)return;if(Ee.complete!==!1||!Ee.resources.length||typeof Ee.cursor!="string"||!Ee.cursor||Fe.encode(Ee.cursor).length>4096||ie.has(Ee.cursor))throw Xe("recovery_required");ie.add(Ee.cursor),Q=Ee.cursor}throw Xe("recovery_required")}async function B($,Y,K){let Q=$.version===2?$.plan.readback:$.plan.resourceReadback,Ae=new Set(Q.filter(oe=>oe.doc===null).map(oe=>oe.path));Ae.size&&await j(Ae,Y,K);for(let oe of Q){if(oe.doc===null)continue;let ie=await t.client.resources.get(oe.path,{signal:s});if(S(Y,K),ie.path!==oe.path||ie.text!==oe.doc||ie.state!=="confirmed")throw Xe("recovery_required")}if($.version!==2)for(let oe of $.plan.sources){let ie=await t.client.get(oe.id,{signal:s});if(S(Y,K),ie.id!==oe.id||ie.path!==oe.path||ie.state.state!=="confirmed"||ie.state.hold||ie.state.unresolved)throw Xe("recovery_required")}}async function D($,Y,K){return await q($,Y,K),$.phase==="attempted"&&($=$.version===2?await t.journal.recordConfirmed($.mutationId,s):await t.journal.recordResourceConfirmed($.mutationId,s),S(Y,K)),$.phase==="verified"||(await B($,Y,K),$.phase==="confirmed"&&($=$.version===2?await t.journal.recordVerified($.mutationId,s):await t.journal.recordResourceVerified($.mutationId,s),S(Y,K))),$}async function X($,Y){let K=await t.journal.load(s);if(S($,Y),!K)return{journaled:!1,previous:null};if(K=Zt(K,t.scope),K.version===1||K.phase==="prepared")throw Xe("recovery_required");if(K.phase==="attempted"&&(K.version===3||K.version===4)&&t.journal.recordResourceRejected){let Q=await t.client.awaitReceipt(K.mutationId,{timeoutMs:12e4,signal:s});S($,Y),Q.mutation===K.mutationId&&Q.state==="rejected"&&(K=Zt(await t.journal.recordResourceRejected(K.mutationId,s),t.scope),S($,Y))}if(K.version===1)throw Xe("recovery_required");return K.phase==="rejected"?{journaled:!0,previous:K.version===4?K.previous:null}:{journaled:!0,previous:await D(K,$,Y)}}async function V($,Y){let K=t.compiledManifest.manifest,Q=await $0(e.assess(K,s,$),$),Ae=Q;Q.status==="conflict"&&!Q.review&&(Ae=await e.assess(K,s,Oi({})));let oe=XD(Ae);if(!oe.compatible.size)return{assessed:Q,manifest:K,newer:oe};let ie=ZD(K,oe.compatible),He=Y?$??Oi({}):$;return Q=await $0(e.assess(ie,s,He),He),{assessed:Q,manifest:ie,newer:oe}}async function U($,Y,K={}){S(Y);let Q=await t.client.readyForRead(s);S(Y,Q),_.length||(y=v(),_.push(t.client.onStatus(ko=>{N0(ko)&&(y=null),P()}),t.client.onLink(P))),w=!1;let{journaled:Ae,previous:oe}=await X(Y,Q);if(!e)throw Xe("unsupported");let ie=null;try{ie=Uc(await t.client.describe({signal:s}))}catch{}S(Y,Q);let He=await V(K.decisions,!1),Fe=He.assessed,Ft=He.manifest;if(S(Y,Q),!z0.test(Fe.assessmentDigest)||!["current","provision","conflict"].includes(Fe.status))throw Xe("response");if(K.expected!==void 0&&Fe.assessmentDigest!==K.expected)throw B0();let Ee=!Ae&&t.setupMode==="approved-new";if(Fe.status==="provision"&&($||Ee)){if(t.setupMode==="reconcile-original")throw Xe("recovery_required");if(!(t.compiledManifest.operations.includes("apply_collection_setup")||t.compiledManifest.operations.includes("apply_type_pack"))||!Q.hello.grant.capabilities.includes("definitions.manage"))throw Xe("not_authorized");let ko=K.records??[];if(ko.length&&!Q.hello.grant.capabilities.includes("records.create"))throw Xe("not_authorized");let vs=$t(await $0(e.apply(Ft,Fe.assessmentDigest,s,K.decisions),K.decisions));if(S(Y,Q),vs.assessmentDigest!==Fe.assessmentDigest)throw Xe("response");if(vs.sources.length)throw Xe("unsupported_source_provision");let Dn=ko.length?$t({...vs,sources:ko.map(Ui=>({id:crypto.randomUUID(),path:Ui.path,document:Ui.document}))}):vs,dn;if(oe){if(!t.journal.prepareResourceRound)throw Xe("recovery_required");dn=await t.journal.prepareResourceRound(Dn,oe.mutationId,s)}else dn=await t.journal.prepareResources(Dn,s);if(S(Y,Q),dn=Zt(dn,t.scope),dn.version!==3&&dn.version!==4||dn.phase!=="prepared"||JSON.stringify(dn.plan)!==JSON.stringify(Dn))throw Xe("recovery_required");let So=Zt(await t.journal.recordResourceAttempt(dn.mutationId,s),t.scope);if(S(Y,Q),So.version!==3&&So.version!==4||So.mutationId!==dn.mutationId||So.phase!=="attempted"||JSON.stringify(So.plan)!==JSON.stringify(Dn))throw Xe("recovery_required");let Bc=[...Dn.resourceOps,...Dn.sources.map(Ui=>({kind:"create",id:Ui.id,path:Ui.path,document:Ui.document}))],xa=await t.client.submit(Bc,{mutationId:dn.mutationId,wait:"confirmed",signal:s});if(S(Y,Q),xa.mutationId!==dn.mutationId)throw Xe("recovery_required");let _s;try{_s=await xa.confirmed}catch(Ui){throw S(Y,Q),xa.receipt.state!=="rejected"||!t.journal.recordResourceRejected?Ui:(await t.journal.recordResourceRejected(dn.mutationId,s),S(Y,Q),B0(dn.mutationId,Ui))}if(S(Y,Q),_s.state!=="confirmed"||_s.status!=="applied"||(_s.conflicts?.length??0)!==0)throw Xe("recovery_required");await D(So,Y,Q),w=!1,y=v();try{ie=Uc(await t.client.describe({signal:s}))}catch{ie=null}if(Fe=await e.assess(Ft,s),S(Y,Q),Fe.status!=="current"||!z0.test(Fe.assessmentDigest))throw Xe("recovery_required")}let nt=Fe.status==="conflict"&&He.newer.major.length>0,dr=Fe.status==="conflict"?nt?"installed_newer":"setup_conflict":null,_o=dr?Object.freeze({code:dr}):null,Ao=Object.freeze({status:Fe.status==="current"?"ready":nt?"incompatible":"setup_required",problem:_o});d=Q,u=ie;let Vr=Object.freeze({checking:!1,assessment:Ao,problem:_o});return m=0,x(w?bo(null,!0):Vr),S(Y,Q),Vr}function ce($={}){try{S($.signal)}catch(Q){return Promise.reject(Q)}let Y=c,K=(Y?Y.then(()=>{},()=>{}):Promise.resolve()).then(()=>ee($));return c=K,K.finally(()=>{c===K&&(c=null)}).catch(()=>{}),K}async function ee($){let Y=fy($.records),K=Oi($.adopt===void 0?{}:{adopt:$.adopt}),Q=AbortSignal.any([s,...$.signal?[$.signal]:[]]),Ae=await t.client.readyForRead(s);if(S(Q,Ae),await X(Q,Ae),!e)throw Xe("unsupported");let{assessed:oe,newer:ie}=await V(K,!0);if(S(Q,Ae),!oe.review)throw Xe("response");let He=[];if(oe.status!=="current")for(let Ee of Y){let nt=await t.client.find({path:Ee.path},{signal:s});S(Q,Ae),He.push({path:Ee.path,free:nt===null})}let Fe=Ae.hello.grant.capabilities,Ft=Bd(oe,{records:He,canManage:Fe.includes("definitions.manage")&&(t.compiledManifest.operations.includes("apply_collection_setup")||t.compiledManifest.operations.includes("apply_type_pack")),canCreateRecords:Fe.includes("records.create"),newer:ie});return k.set(Ft,Object.freeze({decisions:K,records:Y.filter(Ee=>He.some(nt=>nt.path===Ee.path&&nt.free))})),Ft}function te($,Y={},K,Q=!1){try{S(Y.signal)}catch(ie){return Promise.reject(ie)}if(c&&c===g){let ie=c;return ie.then(()=>{},()=>{}).then(()=>c&&c!==ie?Promise.reject(Xe("busy")):te($,Y,K))}if(c)return Promise.reject(Xe("busy"));let Ae=AbortSignal.any([s,...Y.signal?[Y.signal]:[]]),oe=Promise.resolve().then(()=>U($,Ae,K)).catch(ie=>{let He=s.aborted||Ae.aborted,Fe=J(ie)&&ie.reason==="configuration_busy_timeout";Fe&&(w=!1);let Ft=!He&&!Fe&&(w||R2(ie));throw Ft&&R2(ie)&&(w=!0,m=Math.min(m+1,4)),!He&&!Fe&&!w&&Q&&m<5&&!p&&t.isCurrent()===!0&&(m++,w=!0,Ft=!0),x(Ft?bo(null,!0):bo(He?"configuration_fenced":Fe?"configuration_busy_timeout":"configuration_unavailable")),ie});return c=oe,x(bo(null,!0)),oe.finally(()=>{c===oe&&(c=null),g===oe&&(g=null),O()}).catch(()=>{}),oe.then(ie=>(S(Ae,d),ie))}let Ie=()=>{if(!l){p=!0,t.signal.removeEventListener("abort",tt),o.abort();for(let Y of _.splice(0))Y();x(bo("configuration_fenced"));let $=c;l=Promise.resolve().then(async()=>{await $})}return l},tt=()=>{Ie().catch(()=>{})};return t.signal.addEventListener("abort",tt,{once:!0}),Object.freeze({getSnapshot:R,subscribe($){return r.add($),()=>{r.delete($)}},assess:$=>te(!1,$),configure:$=>te(!0,$),plan:ce,async apply($,Y={}){let K=k.get($);if(!K)throw new TypeError("setup.apply needs a plan returned by setup.plan");if($.refusal)throw A($.refusal.code==="setup_conflict"?"conflict":$.refusal.code==="installed_newer"?"upgrade_required":"forbidden",$.refusal.message,$.refusal.code);if($.status==="current"){await te(!1,Y,{decisions:K.decisions,expected:$.digest});return}await te(!0,Y,{decisions:K.decisions,expected:$.digest,records:K.records})},close:Ie})}var I2,z0,Xe,B0,$0,QD,e4,R2,bo,E2=C(()=>{"use strict";re();Qs();D0();ss();th();hy();I2=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,z0=/^sha256:[0-9a-f]{64}$/,Xe=n=>A("unavailable","application configuration unavailable",`configuration_${n}`),B0=(n,e)=>new ne(A("conflict","This collection changed since the setup was reviewed. Review it again.","setup_changed").toProblem(),{...n?{mutationId:n}:{},...e===void 0?{}:{cause:e}}),$0=async(n,e)=>{try{return await n}catch(t){throw e?.adopt&&Object.keys(e.adopt).length&&J(t,"unavailable")&&t.reason==="resource_setup_unavailable"?B0(void 0,t):t}};QD=15e3,e4=(n,e)=>new Promise((t,i)=>{if(e.aborted){i(e.reason);return}let o=()=>{clearTimeout(s),i(e.reason)},s=setTimeout(()=>{e.removeEventListener("abort",o),t()},n);e.addEventListener("abort",o,{once:!0})});R2=n=>J(n)&&n.reason==="configuration_busy",bo=(n=null,e=!1)=>Object.freeze({checking:e,assessment:null,problem:n?Object.freeze({code:n}):null})});function q2(n){return{issuer:n.issuer,subject:n.subject,name:n.name,...n.accountId===void 0?{}:{account_id:n.accountId}}}function T2(n){let e=n.scope,t=e.account,i=e.installation,o=e.collection,s=n.generation,r=n.signal,a=n.people,c=n.isCurrent.bind(n),l=typeof a?.current=="function"?a.current.bind(a):void 0,p=typeof a?.members=="function"?a.members.bind(a):void 0,d=new Set,u=Sa(null),f=!1,h=!1,m=null;function w(){try{return f||r.aborted||c()!==!0?!1:!f&&!r.aborted&&n.scope===e&&n.generation===s&&n.signal===r&&n.people===a&&!!s&&s.length<=256&&[t,i,o].every(k=>typeof k=="string"&&!!k&&k.length<=128)&&e.account===t&&e.installation===i&&e.collection===o}catch{return!1}}function b(k){u=w()?k:wo;for(let S of[...d])try{S()}catch{}w()||(u=wo)}function g(){return w()||(u=wo),u}function y(){if(!f){f=!0,r.removeEventListener("abort",y),u=wo;for(let k of[...d])try{k()}catch{}d.clear()}}r.addEventListener("abort",y,{once:!0}),r.aborted&&y();function v(k,S){return!w()||S?.aborted?Promise.reject(Au()):new Promise((x,P)=>{let I=!1,O=(j,B)=>{I||(I=!0,S?.removeEventListener("abort",R),r.removeEventListener("abort",R),d.delete(q),B!==void 0?P(B):x(j))},R=()=>O(void 0,Au()),q=()=>{w()||R()};d.add(q),S?.addEventListener("abort",R,{once:!0}),r.addEventListener("abort",R,{once:!0}),k.then(()=>{!w()||S?.aborted?R():O(g())},()=>O(void 0,Au())),(!w()||S?.aborted)&&R()})}function _(k={}){let S=k.signal;if(!w()||S?.aborted)return Promise.reject(Au());if(m)return Promise.reject(A("unavailable","People readiness READ is occupied","people_readiness_busy"));let x=Promise.resolve().then(async()=>{if(!w())return wo;if(!l||!p)return Sa("people_unsupported");try{let I=await l({signal:r});if(!w()||(Zl("identity",{...q2(I),...I.personSettingsUrl===void 0?{}:{person_settings_url:I.personSettingsUrl}}),!w()))return wo;let O=await p({signal:r});return w()?!Array.isArray(O)||O.length>1e3?Sa("people_response"):(Zl("members",{members:Array.from(O,R=>({...q2(R),role:R.role}))}),w()?t4:wo):wo}catch{return Sa(w()?"people_unavailable":"people_fenced")}});m=x,b(Sa(null,!0));let P=x.then(I=>(b(I),g()),()=>(b(Sa("people_unavailable")),g())).finally(()=>{m===x&&(m=null)});return v(P,S)}return Object.freeze({getSnapshot:g,subscribe(k){return f?()=>{}:(d.add(k),()=>{d.delete(k)})},start(k={}){return h?v(m??Promise.resolve(g()),k.signal):!w()||k.signal?.aborted?Promise.reject(Au()):(h=!0,_(k))},refresh:_,close:y})}var Sa,wo,t4,Au,M2=C(()=>{"use strict";Ld();re();Sa=(n,e=!1)=>Object.freeze({checking:e,assessment:null,problem:n===null?null:Object.freeze({code:n})}),wo=Sa("people_fenced"),t4=Object.freeze({checking:!1,assessment:Object.freeze({status:"ready",problem:null}),problem:null}),Au=()=>A("cancelled","People readiness ended","people_readiness_fenced")});function Pg(n){if(!n||!Array.isArray(n.criteria))return Object.freeze([]);let e=n.criteria.filter(t=>t?.event?.id===lm.id&&t.event.version===lm.version&&t.event.digest===lm.digest).map(t=>t.id);return Object.freeze([...new Set(e)])}var V0=C(()=>{"use strict";fd()});function L2(n){let e=n.scope,t=e.account,i=e.installation,o=e.collection,s=n.generation,r=n.signal,a=n.isCurrent.bind(n),c=n.notifications,l=c?.declaration,p=c?.timerNamespace,d=n.timers,u=typeof d?.list=="function"?d.list.bind(d):void 0,f=new Set,h=pr(null),m=!1,w=!1,b=null;function g(){try{return m||r.aborted||a()!==!0?!1:!m&&!r.aborted&&n.signal===r&&n.scope===e&&n.generation===s&&!!s&&s.length<=256&&[t,i,o].every(x=>typeof x=="string"&&!!x&&x.length<=128)&&e.account===t&&e.installation===i&&e.collection===o&&n.notifications===c&&c?.declaration===l&&c?.timerNamespace===p&&n.timers===d}catch{return!1}}function y(x){h=g()?x:xg;for(let P of[...f])try{P()}catch{}g()||(h=xg)}function v(){return g()||(h=xg),h}function _(){if(!m){m=!0,r.removeEventListener("abort",_),h=xg;for(let x of[...f])try{x()}catch{}f.clear()}}r.addEventListener("abort",_,{once:!0}),r.aborted&&_();function k(x,P){return!g()||P?.aborted?Promise.reject(ku()):new Promise((I,O)=>{let R=!1,q=(D,X)=>{R||(R=!0,P?.removeEventListener("abort",j),r.removeEventListener("abort",j),f.delete(B),X!==void 0?O(X):I(D))},j=()=>q(void 0,ku()),B=()=>{g()||j()};f.add(B),P?.addEventListener("abort",j,{once:!0}),r.addEventListener("abort",j,{once:!0}),x.then(()=>{!g()||P?.aborted?j():q(v())},()=>q(void 0,ku())),(!g()||P?.aborted)&&j()})}function S(x={}){let P=x.signal;if(!g()||P?.aborted)return Promise.reject(ku());if(b)return Promise.reject(A("unavailable","Notification readiness READ is occupied","notification_readiness_busy"));let I=Promise.resolve().then(async()=>{if(!g())return pr("notifications_fenced");if(l===null&&c&&Object.hasOwn(c,"declaration"))return Object.freeze({checking:!1,assessment:Object.freeze({status:"ready",problem:null}),problem:null});if(!u&&Pg(l).length)return pr("notifications_consent_required");if(!l||typeof l!="object"||!u||typeof p!="string"||!/^[A-Za-z0-9._-]{1,64}$/.test(p))return pr("notifications_unsupported");try{let R=await u(p,{signal:r});return g()?!R||R.namespace!==p||!Array.isArray(R.timers)||R.timers.length>1e4?pr("notifications_response"):pr("notifications_unsupported"):pr("notifications_fenced")}catch{return pr(g()?"notifications_unavailable":"notifications_fenced")}});b=I,y(pr(null,!0));let O=I.then(R=>(y(R),v()),()=>(y(pr("notifications_unavailable")),v())).finally(()=>{b===I&&(b=null)});return k(O,P)}return Object.freeze({getSnapshot:v,subscribe(x){return m?()=>{}:(f.add(x),()=>{f.delete(x)})},start(x={}){return w?k(b??Promise.resolve(v()),x.signal):!g()||x.signal?.aborted?Promise.reject(ku()):(w=!0,S(x))},refresh:S,close:_})}var n4,pr,xg,ku,j2=C(()=>{"use strict";re();V0();n4=n=>Object.freeze({code:n}),pr=(n,e=!1)=>Object.freeze({checking:e,assessment:null,problem:n===null?null:n4(n)}),xg=pr("notifications_fenced"),ku=()=>A("cancelled","Notification readiness ended","notification_readiness_fenced")});function D2(n){let e=new Set,t=!1,i=()=>{if(t||!n.isCurrent())return U2;let s=n.declaration;if(!s)return F0;let r;try{r=n.grant()}catch{return i4}return r?s.required.some(a=>!r.actions.includes(a))?N2("files_access_missing"):n.scope==="collection"&&r.scope.kind!=="collection"?N2("files_scope_missing"):F0:F0},o=i();return Object.freeze({getSnapshot:()=>t||!n.isCurrent()?U2:o,subscribe(s){return t?()=>{}:(e.add(s),()=>{e.delete(s)})},async refresh(){let s=i();if(s!==o){o=s;for(let r of[...e])try{r()}catch{}}return o},close(){t=!0,e.clear()}})}var Ig,F0,U2,i4,N2,z2=C(()=>{"use strict";Ig=n=>Object.freeze(n),F0=Ig({checking:!1,assessment:Object.freeze({status:"ready",problem:null}),problem:null}),U2=Ig({checking:!1,assessment:null,problem:Object.freeze({code:"files_fenced"})}),i4=Ig({checking:!1,assessment:null,problem:Object.freeze({code:"files_unavailable"})}),N2=n=>Ig({checking:!1,assessment:Object.freeze({status:"incompatible",problem:Object.freeze({code:n})}),problem:null})});var Cg,$2=C(()=>{"use strict";T0();x2();E2();M2();j2();V0();wp();zd();z2();Cg=class{constructor(e,t,i,o="block",s=()=>[]){this.typeIssues=o;this.consented=s;this.compiled=e,this.signal=i,this.ui=new Mc(t,i,Pg(this.compiled.manifest.notifications)),i.addEventListener("abort",this.abort,{once:!0})}typeIssues;consented;ui;signal;compiled;listeners=new Set;selected=null;epoch=0;opening=null;retiring=null;closing=null;changed=()=>{for(let e of[...this.listeners])try{e()}catch{}};abort=()=>{this.close().catch(()=>{})};subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}connection(e){return this.ui.connection(e)}getReadiness(){return this.selected?.readiness.getSnapshot()??null}selectedId(){return this.selected?.connection.id??null}adopt(e,t,i){let o=this.epoch,s=()=>!this.signal.aborted&&!this.closing&&!this.retiring&&this.epoch===o&&i(),r=!!this.opening||!!this.selected||!!this.retiring||!!this.closing,a=this.ui.adopt(e,{caller:t,isCurrent:s});if(r)return a;let c=null,l=[],p=a.then(d=>{if(!s()||t.aborted)throw new pn("application_connection_fenced");let u=this.ui.owned();if(!u)throw new pn("application_connection_binding");let f=ay(this.compiled);f&&QS(d.files,PR(f,()=>this.consented(d.id)));let h=new AbortController,m=AbortSignal.any([this.signal,h.signal]);c=h;let w=()=>s()&&d.isCurrent(),b={scope:d.scope,generation:d.generation,signal:m,isCurrent:w},g=O2({client:d.records,compiledManifest:this.compiled,journal:u.journal,...b,setupMode:u.setupMode},u.resourceSetup);l.push(()=>g.close());let y={getSnapshot:g.getSnapshot,subscribe:g.subscribe,refresh:g.assess,close:g.close},v=T2({people:d.people,...b});l.push(()=>v.close());let _=this.compiled.manifest.notifications,k=L2({notifications:{declaration:_?.criteria?.length?_:null},timers:d.timers,...b});l.push(()=>k.close());let S=this.compiled.manifest.requirements.files?.scope?.kind,x=D2({declaration:f,scope:typeof S=="string"?S:null,grant:()=>d.files.grant,isCurrent:w});l.push(()=>x.close());let P=this.compiled.nativeCapabilities?{...this.compiled.nativeCapabilities,contracts:this.compiled.manifest.requirements.contracts,typeIssues:this.typeIssues}:null,I=new Sg({connection:d,nativeRequirements:P,signal:m,isCurrent:w,configuration:y,files:x,people:v,notifications:k}),O=I.subscribe(this.changed);return this.selected={connection:d,lifetime:h,readiness:I,configuration:g,unsubscribe:O},c=null,l.length=0,this.changed(),d}).catch(async d=>{c?.abort();let f=(await Promise.allSettled([this.ui.retire(),...l.map(h=>Promise.resolve().then(h))])).find(h=>h.status==="rejected");throw f?.status==="rejected"?f.reason:d}).finally(()=>{this.opening===p&&(this.opening=null)});return this.opening=p,p}assess(e={}){return!this.selected||!this.selected.connection.isCurrent()||this.retiring||this.closing?Promise.reject(new pn("application_connection_fenced")):this.selected.readiness.refresh(e)}async configure(e={}){let t=this.selected,i=this.epoch;if(!t||!t.connection.isCurrent()||this.retiring||this.closing)throw new pn("application_connection_fenced");if(await t.configuration.configure(e),e.signal?.aborted||this.epoch!==i||this.selected!==t||!t.connection.isCurrent())throw new pn("application_connection_fenced");return t.readiness.refresh(e)}planSetup(e={}){let t=this.selected;return!t||!t.connection.isCurrent()||this.retiring||this.closing?Promise.reject(new pn("application_connection_fenced")):t.configuration.plan(e)}async applySetup(e,t={}){let i=this.selected,o=this.epoch;if(!i||!i.connection.isCurrent()||this.retiring||this.closing)throw new pn("application_connection_fenced");if(await i.configuration.apply(e,t),t.signal?.aborted||this.epoch!==o||this.selected!==i||!i.connection.isCurrent())throw new pn("application_connection_fenced");return i.readiness.refresh(t)}retire(){if(this.retiring)return this.retiring;++this.epoch;let e=this.selected,t=this.opening;e?.lifetime.abort(),e?.unsubscribe();let i=this.ui.retire(),o=Promise.resolve().then(async()=>{let r=(await Promise.allSettled([i,t?.catch(()=>{}),e?.readiness.close()])).find(a=>a.status==="rejected");if(r?.status==="rejected")throw r.reason;this.selected===e&&(this.selected=null)});return this.retiring=o,this.changed(),o.then(()=>{this.retiring===o&&(this.retiring=null),this.changed()},()=>{}),o}close(){return this.closing?this.closing:(this.signal.removeEventListener("abort",this.abort),this.closing=Promise.resolve().then(async()=>{await this.retire(),await this.ui.close(),this.listeners.clear()}),this.closing)}}});function K0(n,e){return!n||typeof n!="object"||Array.isArray(n)||Object.keys(n).sort().join()!==e.split(",").sort().join()?Nc():n}function W0(n){(typeof n!="string"||!r4.test(n)||/^0{8}-0{4}-0{4}-0{4}-0{12}$/.test(n))&&Nc()}function B2(n){let e=K0(n,"rpc,action,value");if((!Number.isSafeInteger(e.rpc)||e.rpc<1||e.rpc>4294967295)&&Nc(),e.action==="cancel")e.value!==null&&Nc();else if(e.action==="prepare"){let t=K0(e.value,`requestId,accountId,appId,challenge${Object.hasOwn(e.value,"authorizationId")?",authorizationId":""}`);for(let i of["requestId","accountId","appId"])W0(t[i]);t.authorizationId!==void 0&&W0(t.authorizationId),(typeof t.challenge!="string"||!/^[0-9a-f]{64}$/.test(t.challenge))&&Nc()}else if(e.action==="finish"){let t=K0(e.value,"requestId,authorizationRequestId,collectionId");for(let i of Object.keys(t))W0(t[i])}else Nc();return Object.freeze({...e,value:e.value===null?null:Object.freeze({...e.value})})}var r4,Nc,V2=C(()=>{"use strict";qd();r4=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,Nc=()=>{throw new xe("application_worker_binding")}});function H0(n){if(!n||typeof n!="object"||Array.isArray(n))throw new xe("application_worker_binding");let e=n,t=e.unlock;if(e.status==="needs_unlock"!=(t!=null)||t!=null&&(typeof t!="object"||!["password","strict","none"].includes(t.mode)||typeof t.unlocking!="boolean"||!(t.problem===null||typeof t.problem=="string"&&/^[a-z][a-z0-9_]{0,63}$/.test(t.problem))))throw new xe("application_worker_binding");if(!["not_started","starting","signed_out","authorizing","unselected","opening","setup_required","ready","blocked","closed","needs_unlock"].includes(e.status)||!(e.openingProgress==null||typeof e.openingProgress=="string")||!Array.isArray(e.collections)||e.collections.length>1024||!(e.selectedCollectionId===null||typeof e.selectedCollectionId=="string")||!(e.problem===null||typeof e.problem=="string"&&/^[a-z0-9_-]{1,128}$/.test(e.problem))||!(e.unsynced==null||typeof e.unsynced=="object"&&e.unsynced.collectionId===e.selectedCollectionId&&typeof e.unsynced.sessionStatus=="string")||!(e.unsyncedWork==null||typeof e.unsyncedWork=="object"&&Number.isSafeInteger(e.unsyncedWork.since)&&e.unsyncedWork.since>=0))throw new xe("application_worker_binding");return Object.freeze({...e,openingProgress:Ky(e.openingProgress)?e.openingProgress:null})}var Dc,Rg,F2=C(()=>{"use strict";WA();V2();qd();Dc=class extends Error{constructor(t){super("SDK application operation unavailable");this.code=t;this.name="ApplicationWorkerReplyError"}code};Rg=class{port;binding;owner;nextId=0;active=null;portal=null;fault=null;stopping=null;stopReply=null;watch=null;closedPortal=null;abandoned=!1;constructor(e,t,i){if(!z1(t))throw new xe("application_worker_binding");this.port=e,this.binding=t,this.owner=Object.freeze({...i}),e.addEventListener("message",this.message),e.addEventListener("messageerror",this.messageError),e.start()}id(){if(this.nextId===Bm)throw new xe("application_worker_stop_failed");return++this.nextId}send(e,t,i){let o=P_([di,this.binding,e,t,i],this.binding);try{this.port.postMessage(o)}catch{throw this.quarantine("application_worker_unavailable"),this.fault}}request(e,t,i,o){if(this.fault||this.stopping||i.aborted)return Promise.reject(this.fault??new xe("application_worker_fenced"));if(this.active)return Promise.reject(new xe("application_worker_busy"));let s;try{s=this.id(),P_([di,this.binding,s,e,t],this.binding)}catch(c){return Promise.reject(c)}if(o){if(!["authorize","renewExpiredPairing","requestFileAccess"].includes(e))return Promise.reject(new xe("application_worker_binding"));this.portal?.life.abort(),this.portal&&(this.closedPortal=this.portal.id);try{this.portal?.value.close()}catch{return this.quarantine("application_worker_stop_failed"),Promise.reject(this.fault)}this.portal={id:s,value:o,caller:i,life:new AbortController,lastRpc:0,busy:!1},this.watchPortal()}let r,a=new Promise(c=>{r=c});return new Promise((c,l)=>{let p={id:s,caller:i,done:a,finish:r,resolve:c,reject:l,fenced:!1,reply:!1,handoff:null,cancel:()=>{p.fenced=!0,l(new xe("application_worker_fenced"))}};this.active=p,i.addEventListener("abort",p.cancel,{once:!0});try{this.send(s,e,t)}catch(d){l(d)}i.aborted&&p.cancel()})}drain(){return this.fault?Promise.reject(this.fault):this.active?.done??Promise.resolve()}setForeground(e){!this.stopping&&!this.fault&&this.send(0,"foreground",e)}watchPortal(){this.watch!==null&&clearInterval(this.watch),this.watch=null;let e=this.portal;!e||!("closed"in e.value)||(this.watch=setInterval(()=>{if(this.portal!==e||this.stopping||this.fault){clearInterval(this.watch),this.watch=null;return}let t=!1;try{t=e.value.closed===!0}catch{}if(t){clearInterval(this.watch),this.watch=null,e.lastRpc===0&&(this.portal=null,this.closedPortal=e.id);try{this.send(0,"approvalClosed",!0)}catch{}}},500))}messageError=()=>this.quarantine("application_worker_unavailable");quarantine(e){if(!this.fault){this.fault=new xe(e),this.active&&(this.active.fenced=!0,this.active.reject(this.fault)),this.stopReply?.reject(this.fault);try{this.owner.failed?.(this.fault)}catch{}}}message=e=>{try{let t=e.data;if(!Array.isArray(t)||t.length!==5||t[0]!==di||t[1]!==this.binding||!Number.isInteger(t[3])||t[3]<0||t[3]>Bm)throw new xe("application_worker_binding");if(this.fault)return;let[,,i,o,s]=t;if(i==="nativeSnapshot"){if(o!==0)throw new xe("application_worker_binding");let l=H0(s);this.stopping||this.owner.snapshot(l);return}if(i==="fatal"){if(o!==0)throw new xe("application_worker_binding");this.quarantine("application_worker_stop_failed");return}if(i==="nativeAuthorization"){let l=B2(s),p=this.portal;if(o===this.closedPortal&&p?.id!==o){l.action!=="cancel"&&this.port.postMessage([di,this.binding,"nativeAuthorizationReply",o,{rpc:l.rpc,ok:!1}]);return}if(!p||p.id!==o||this.stopping||p.caller.aborted||l.rpc<=p.lastRpc)throw new xe("application_worker_fenced");if(p.lastRpc=l.rpc,l.action==="cancel")p.life.abort();else if(p.busy)throw new xe("application_worker_binding");l.action!=="cancel"&&(p.busy=!0);let d=AbortSignal.any([p.caller,p.life.signal]);Promise.resolve().then(()=>{if(!this.owner.nativeAuthorization)throw new xe("application_worker_unavailable");return this.owner.nativeAuthorization(l,p.value,d)}).then(u=>{if(d.aborted||this.portal!==p||this.stopping)throw new xe("application_worker_fenced");this.port.postMessage([di,this.binding,"nativeAuthorizationReply",o,{rpc:l.rpc,ok:!0,value:u}])},()=>{this.port.postMessage([di,this.binding,"nativeAuthorizationReply",o,{rpc:l.rpc,ok:!1}])}).catch(()=>{try{this.port.postMessage([di,this.binding,"nativeAuthorizationReply",o,{rpc:l.rpc,ok:!1}])}catch{}}).finally(()=>{p.busy=!1});return}if(i==="portal"){if(!s||!["navigate","focus","close"].includes(s.action))throw new xe("application_worker_binding");let l=this.portal;if(!l||l.id!==o)return;if(s.action==="close")l.life.abort(),l.value.close(),this.portal=null;else if(s.action==="focus")try{l.value.focus?.()}catch{}else{if(this.stopping||typeof s.uri!="string"||s.uri.length>8192)throw new xe("application_worker_binding");l.value.navigate(s.uri)}return}if(i==="handoff"&&o===0){if(!s||s.schema!=="mdbn-app-collection/1")throw new xe("application_worker_binding");let l=[s.dataPort,s.controlPort,...s.timerPort?[s.timerPort]:[]];if(l.some(p=>!(p instanceof MessagePort)))throw new xe("application_worker_binding");if(this.stopping||!this.owner.attached){for(let p of l)p.close();return}this.owner.attached(s);return}if(i==="handoff"){let l=this.active;if(!l||l.id!==o||l.reply||l.handoff)throw new xe("application_worker_binding");if(this.stopping){if(!s||s.schema!=="mdbn-app-collection/1")throw new xe("application_worker_binding");for(let p of[s.dataPort,s.controlPort,...s.timerPort?[s.timerPort]:[]]){if(!(p instanceof MessagePort))throw new xe("application_worker_binding");p.close()}l.handoff=Promise.resolve();return}l.handoff=Promise.resolve().then(()=>this.owner.handoff(s,l.caller)),l.handoff.catch(()=>{});return}if(i!=="reply"||!s||typeof s.ok!="boolean"||!s.ok&&(!s.problem||typeof s.problem.code!="string"||s.problem.code.length>128))throw new xe("application_worker_binding");let r=this.stopReply;if(r&&r.id===o){if(s.ok){let l=H0(s.snapshot);if(l.status!=="closed"||l.selectedCollectionId!==null)throw new xe("application_worker_stop_failed");r.resolve()}else r.reject(new xe("application_worker_stop_failed"));return}let a=this.active;if(!a||a.id!==o||a.reply)throw new xe("application_worker_binding");a.reply=!0;let c=s.ok?H0(s.snapshot):null;this.settle(a,c,s.ok?null:Object.freeze({code:s.problem.code}))}catch{this.quarantine("application_worker_binding")}};async settle(e,t,i){try{if(await e.handoff,e.fenced||e.caller.aborted||this.stopping||this.fault)throw this.fault??new xe("application_worker_fenced");if(i)throw new Dc(i.code);t&&e.resolve(t)}catch(o){e.reject(o)}finally{e.caller.removeEventListener("abort",e.cancel),this.active===e&&(this.active=null),e.finish()}}abandon(){if(this.abandoned)return;this.abandoned=!0,this.fault||(this.fault=new xe("application_worker_fenced")),this.watch!==null&&(clearInterval(this.watch),this.watch=null);let e=this.active;e&&(e.fenced=!0,e.reject(this.fault),e.finish(),this.active=null),this.stopReply?.reject(this.fault),this.stopReply=null,this.portal?.life.abort();try{this.portal?.value.close()}catch{}this.portal=null;try{this.owner.releaseWorker()}catch{}this.port.removeEventListener("message",this.message),this.port.removeEventListener("messageerror",this.messageError),this.port.close()}close(){if(this.stopping)return this.stopping;let e=this.active;return e&&(e.fenced=!0,e.reject(new xe("application_worker_fenced"))),this.stopping=Promise.resolve().then(async()=>{if(this.fault)throw new xe("application_worker_stop_failed");this.portal?.life.abort(),this.portal?.value.close(),this.portal=null;let t=this.id();if(await new Promise((i,o)=>{this.stopReply={id:t,resolve:i,reject:o};try{this.send(t,"close",null)}catch(s){o(s)}}),await e?.done,this.fault)throw new xe("application_worker_stop_failed");this.owner.releaseWorker(),this.port.removeEventListener("message",this.message),this.port.removeEventListener("messageerror",this.messageError),this.port.close()}).catch(t=>{throw this.quarantine("application_worker_stop_failed"),t}),this.stopping}}});var W2={};Ea(W2,{ApplicationRuntime:()=>Y0,ApplicationRuntimeError:()=>Nn});function o4(n,e){let t=()=>A("invalid_request","Pass the collection and either { password } or { recoveryKey }.","unlock_secret_invalid");if(typeof n!="string"||!e||typeof e!="object")throw t();let i=Object.hasOwn(e,"password"),o=Object.hasOwn(e,"recoveryKey");if(i===o)throw t();let s=i?e.password:e.recoveryKey;if(typeof s!="string"||!s.length)throw t();let r=new TextEncoder().encode(s);if(r.length>S_)throw r.fill(0),t();return Object.freeze([n,i?"password":"recoveryKey",r])}function K2(n){try{if(!n||!Su.test(String(n.name)))return;let e=o=>typeof o=="string"&&Su.test(o)?o:"-",t=`${n.name}:${e(n.code)}`;typeof n.stage=="string"&&Su.test(n.stage)&&(t+=`@${n.stage}`),n.cause&&Su.test(String(n.cause.name))&&(t+=` cause=${n.cause.name}:${e(n.cause.code)}`);let i=n.server?.status;return Number.isInteger(i)&&i>=100&&i<=599&&(t+=` http=${i}${n.server.code&&Su.test(n.server.code)?`:${n.server.code}`:""}`),t}catch{return}}var Nn,Su,G0,Y0,H2=C(()=>{"use strict";WA();re();rp();qd();bE();$2();T0();St();zd();F2();x_();Nn=class extends Error{constructor(t){super("SDK application runtime unavailable");this.code=t;this.name="ApplicationRuntimeError"}code},Su=/^[A-Za-z][A-Za-z0-9_]{0,63}$/;G0=()=>{let n=Object.freeze({checking:!1,assessment:null,problem:null});return Object.freeze({checking:!1,assessment:null,problem:null,facets:Object.freeze({capabilities:n,contracts:n,configuration:n,files:n,people:n,notifications:n})})},Y0=class{lifetime=new AbortController;scope;worker;cpOrigin;lab;appName;sourceAdopt=null;listeners=new Set;unsubscribe;raw=Object.freeze({status:"not_started",collections:Object.freeze([]),selectedCollectionId:null,signIn:null,problem:null,timing:null});snapshot=Object.freeze({...this.raw,readiness:G0()});pending=null;closing=null;epoch=0;loggedProblem=null;assessing=!1;retiring=!1;closed=!1;stopped=!1;stopFailed=!1;constructor(e){this.cpOrigin=e.cpOrigin,this.appName=e.declaration.name,this.lab=Ml(e.declaration.environment),this.scope=new Cg(e.compiledManifest,{name:e.declaration.name,version:"1"},this.lifetime.signal,e.typeIssues,t=>ly(this.raw,t)),this.worker=new Rg(e.port,e.binding,{snapshot:t=>{this.closed||(this.raw=t,this.followSession(),this.publish())},handoff:(t,i)=>{if(this.sourceAdopt)return this.sourceAdopt(t,i);let o=this.epoch;return this.scope.adopt(t,i,()=>!this.closed&&this.epoch===o).then(()=>{this.portsFailed=null},s=>{throw this.portsFailed=t.scope.collection,s})},attached:t=>this.attached(t),releaseWorker:e.releaseWorker,...e.nativeAuthorization?{nativeAuthorization:e.nativeAuthorization}:{},failed:t=>{this.closed||(this.raw=Object.freeze({...this.raw,status:"blocked",problem:t.code,unlock:null}),this.publish())}}),this.unsubscribe=this.scope.subscribe(()=>this.publish())}portsFailed=null;attached(e){let t=()=>{for(let o of[e.dataPort,e.controlPort,...e.timerPort?[e.timerPort]:[]])try{o.close()}catch{}};if(this.closed){t();return}let i=this.lifetime.signal;this.queue(()=>this.action(async()=>{if(this.raw.selectedCollectionId!==e.scope.collection)return t(),this.snapshot;this.scope.selectedId()!==null&&(++this.epoch,await this.retireOwn());let o=this.epoch;return await this.scope.adopt(e,i,()=>!this.closed&&this.epoch===o).catch(s=>{throw this.portsFailed=e.scope.collection,s}),this.portsFailed=null,this.complete(this.raw,i)},i)).catch(()=>{this.closed||this.publish()})}followSession(){if(this.pending)return;let e=this.raw.status==="ready"||this.raw.status==="setup_required",t=this.raw.selectedCollectionId,i=this.scope.selectedId();if(i!==null&&(i!==t||!e&&this.raw.status!=="opening"&&this.raw.status!=="authorizing")){let o=this.lifetime.signal;this.queue(()=>this.action(async()=>(this.scope.selectedId()===i&&(++this.epoch,await this.retireOwn()),this.publish(),this.snapshot),o)).catch(()=>{})}}connection(e){return this.closed?null:this.scope.connection(e)}getSnapshot(){return this.snapshot}getNativeSnapshot(){return this.raw}async queue(e){for(;this.pending&&!this.closed;)await this.pending.catch(()=>{});return e()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}publish(){if(this.closed)this.snapshot=Object.freeze({...this.raw,status:this.stopped?"closed":"blocked",problem:this.stopped?null:this.stopFailed?"application_stop_failed":"application_closing",selectedCollectionId:null,unlock:null,readiness:G0()});else{let e=this.scope.getReadiness()??G0(),t=this.raw.status,i=this.raw.problem,o,s=this.raw.problemDetail,r=this.raw.selectedCollectionId,a=this.retiring&&e.problem?.code==="readiness_fenced",c=r!==null&&(this.scope.getReadiness()===null||a)&&this.portsFailed!==r;if((t==="ready"||t==="setup_required")&&c)t="opening";else if(t==="ready"||t==="setup_required"){let h=this.assessing&&!e.assessment&&e.problem?.code!=="readiness_fenced";if(t=e.checking||h?"opening":e.assessment?.status==="ready"?"ready":e.assessment?.status==="setup_required"?"setup_required":"blocked",t==="blocked"){let m=e.problem??e.assessment?.problem;i=m?.code??"application_readiness_unavailable",o=m?.detail,s=void 0}}let l=`${i}:${o??K2(s)??""}`;if(t==="blocked"&&i&&l!==this.loggedProblem){this.loggedProblem=l;try{let h=o??K2(s);h?console.error("mdbase application blocked:",i,h):console.error("mdbase application blocked:",i)}catch{}}else t!=="blocked"&&(this.loggedProblem=null);let{problemDetail:p,...d}=this.raw,u=t==="opening"?d.status==="opening"?d.openingProgress??null:e.checking?"checking_setup":null:null,f=this.snapshot;this.snapshot=Object.freeze({...d,...s?{problemDetail:s}:{},status:t,problem:i,openingProgress:u,collections:Object.freeze(this.raw.collections.map(h=>Object.freeze({...h}))),readiness:e}),r!==null&&Ky(u)&&(f.selectedCollectionId!==r||f.openingProgress!==u)&&fr(`mdbase:open:stage:${u}`)}for(let e of[...this.listeners])try{e()}catch{}}retireOwn(){return this.retiring=!0,this.scope.retire()}settled(){return this.assessing=!1,this.publish(),this.snapshot}signal(e){return e.signal?AbortSignal.any([this.lifetime.signal,e.signal]):this.lifetime.signal}action(e,t){if(this.closed||t.aborted)return Promise.reject(new Nn("application_fenced"));if(this.pending)return Promise.reject(new Nn("application_busy"));this.assessing=!0;let i=Promise.resolve().then(async()=>{if(this.closed||t.aborted)throw new Nn("application_fenced");let o=await e();if(this.closed||t.aborted)throw new Nn("application_fenced");return o}).finally(async()=>{(this.assessing||this.retiring)&&(this.assessing=!1,this.retiring=!1,this.publish()),await this.worker.drain(),this.pending===i&&(this.pending=null)});return this.pending=i,i}async complete(e,t){if(this.closed||t.aborted)throw new Nn("application_fenced");let i=!!(e.selectedCollectionId&&this.scope.connection(e.selectedCollectionId));if(this.raw=e,this.assessing=i,this.publish(),i){try{await this.scope.assess({signal:t}).catch(()=>{})}finally{this.assessing=!1}this.publish()}if(this.closed||t.aborted)throw new Nn("application_fenced");return this.snapshot}start(e={}){let t=this.signal(e);return this.action(async()=>this.complete(await this.worker.request("start",null,t),t),t)}authorizeReserved(e,t={},i=null){let o=this.signal(t);return this.action(async()=>this.complete(await this.worker.request("authorize",i,o,e),o),o).catch(s=>{throw e.close(),s})}authorize(e={}){let t=this.signal(e),i;try{i=Vm(Fm(this.cpOrigin,t,()=>!this.closed,this.lab))}catch(o){return Promise.reject(o)}return this.authorizeReserved(i,e)}select(e,t={}){let i=this.signal(t);return this.action(async()=>{if(this.raw.selectedCollectionId===e&&(this.raw.status==="ready"||this.raw.status==="setup_required")&&this.scope.connection(e)?.isCurrent())return this.snapshot.status==="blocked"?this.complete(this.raw,i):this.snapshot;++this.epoch;let o=this.retireOwn();if(this.publish(),await o,this.closed||i.aborted)throw new Nn("application_fenced");return this.complete(await this.worker.request("select",e,i),i)},i)}unlock(e,t,i={}){let o=this.signal(i),s;try{s=o4(e,t)}catch(a){return Promise.reject(a)}let r=()=>{s[2].fill(0)};return this.action(async()=>{if(this.raw.selectedCollectionId!==e||this.raw.status!=="needs_unlock")throw A("invalid_request","This collection is not waiting to be unlocked.","unlock_not_locked");let a;try{a=this.worker.request("unlock",s,o)}finally{r()}return this.complete(await a,o)},o).finally(r)}openUnsynced(e={}){let t=this.signal(e);return this.action(async()=>{let i=this.raw.unsynced?.collectionId??null;if(i!==null&&this.raw.selectedCollectionId===i&&(this.raw.status==="ready"||this.raw.status==="setup_required")&&this.scope.connection(i)?.isCurrent())return this.snapshot.status==="blocked"?this.complete(this.raw,t):this.snapshot;++this.epoch;let o=this.retireOwn();if(this.publish(),await o,this.closed||t.aborted)throw new Nn("application_fenced");return this.complete(await this.worker.request("openUnsynced",e.timezone??null,t),t)},t)}async retireUnsynced(e,t,i={}){let o=this.signal(i),s=!0;return await this.queue(()=>this.action(async()=>{try{return this.complete(await this.worker.request("retireUnsynced",[e,t],o),o)}catch(r){if(r instanceof Dc&&r.code==="application_worker_busy")return s=!1,this.snapshot;throw r}},o)),s}discardUnsynced(e={}){let t=this.signal(e);return this.action(async()=>{let i=this.raw.unsynced?.collectionId??null,o=i!==null&&this.raw.selectedCollectionId===i;if(o){++this.epoch;let s=this.retireOwn();if(this.publish(),await s,this.closed||t.aborted)throw new Nn("application_fenced")}try{return this.complete(await this.worker.request("discardUnsynced",null,t),t)}catch(s){throw o&&s instanceof Dc&&s.code==="application_worker_busy"&&!this.closed&&!t.aborted&&this.complete(await this.worker.request("openUnsynced",null,t),t),s}},t)}async withUnsyncedSource(e,t={}){let i=this.signal(t),o=new Mc({name:this.appName,version:"1"},i),s=null;try{if(await this.queue(()=>this.action(async()=>{this.sourceAdopt=(r,a)=>(s=o.adopt(r,{caller:a,isCurrent:()=>!this.closed&&!i.aborted}),s.then(()=>{}));try{await this.worker.request("attachUnsynced",null,i)}finally{this.sourceAdopt=null}return this.snapshot},i)),!s)throw new Nn("application_connection_unavailable");return await e(await s,i)}finally{if(await o.close().catch(()=>{}),!this.closed){let r=this.lifetime.signal;await this.queue(()=>this.action(async()=>(await this.worker.request("detachUnsynced",null,r),this.snapshot),r)).catch(()=>{})}}}assess(e={}){let t=this.signal(e);return this.action(async()=>(await this.scope.assess({signal:t}),this.settled()),t).then(i=>i.readiness)}configure(e={}){let t=this.signal(e);return this.action(async()=>(await this.scope.configure({signal:t}),this.settled()),t)}planSetup(e={}){let t=this.signal(e);return this.closed||t.aborted?Promise.reject(new Nn("application_fenced")):this.scope.planSetup({...e,signal:t})}applySetup(e,t={}){let i=this.signal(t);return this.action(async()=>(await this.scope.applySetup(e,{signal:i}),this.settled()),i)}cancelAuthorization(e={}){let t=this.signal(e);return this.action(async()=>this.complete(await this.worker.request("cancelAuthorization",null,t),t),t)}clearSelection(e={}){let t=this.signal(e);return this.action(async()=>(++this.epoch,await this.retireOwn(),this.complete(await this.worker.request("clearSelection",null,t),t)),t)}forget(e,t={}){let i=this.signal(t);return this.action(async()=>(this.raw.selectedCollectionId===e&&(++this.epoch,await this.retireOwn()),this.complete(await this.worker.request("forget",e,i),i)),i)}refreshCollections(e={}){let t=this.signal(e);return this.action(async()=>(this.raw=await this.worker.request("refreshCollections",null,t),this.publish(),this.snapshot),t)}signOut(e={}){let t=this.signal(e),i=this.raw.selectedCollectionId,o=e.discard!==!0&&i?yE(this.scope.connection(i)):0;return o>0?Promise.reject(gE(o)):this.action(async()=>(++this.epoch,await this.retireOwn(),this.complete(await this.worker.request("signOut",null,t),t)),t)}deleteCollection(e,t,i={}){let o=this.signal(i);return this.action(async()=>(await this.worker.request("deleteCollection",[e,t],o),this.raw.selectedCollectionId===e&&(++this.epoch,await this.retireOwn()),this.complete(await this.worker.request("forget",e,o),o)),o)}requestFileAccess(e,t,i,o,s={}){let r=this.signal(s);return this.action(async()=>(this.raw=await this.worker.request("requestFileAccess",[t,i,o],r,e),this.publish(),this.snapshot),r).catch(a=>{throw e.close(),a})}pollFileAccess(e){let t=this.lifetime.signal;return this.action(async()=>(this.raw=await this.worker.request("pollFileAccess",e,t),this.publish(),this.snapshot),t)}setForeground(e){this.closed||this.worker.setForeground(e)}abandon(){this.closed||(this.closed=!0,this.stopped=!0,++this.epoch,this.unsubscribe(),this.listeners.clear(),this.closing=Promise.resolve(),this.worker.abandon(),this.lifetime.abort())}close(){return this.closing?this.closing:(this.closed=!0,++this.epoch,this.lifetime.abort(),this.unsubscribe(),this.closing=Promise.resolve().then(async()=>{await Promise.all([this.scope.close(),this.worker.close()]),await this.pending?.catch(()=>{}),this.stopped=!0,this.publish(),this.listeners.clear()}).catch(()=>{throw this.stopFailed=!0,this.publish(),new Nn("application_stop_failed")}),this.publish(),this.closing)}}});var R4={};Ea(R4,{ACCOUNT_KEY_STATES:()=>Zb,API_VERSIONS:()=>mf,AppHost:()=>rk,COLLECTION_UNAVAILABLE_REASONS:()=>Cw,CborError:()=>Le,Client:()=>zf,DESCRIBE_TYPING_MAX_PATHS:()=>ip,DESCRIBE_TYPING_MAX_TYPES:()=>np,DEVICE_KINDS:()=>Jb,ERROR_CODES:()=>Pu,FilesApi:()=>za,Float64:()=>_t,HOLD_COMPARE_SCHEME:()=>qp,HOLD_TITLE:()=>Ep,IkInitiator:()=>cc,IkResponder:()=>Uy,LiveQuery:()=>Wa,MAX_CONVENIENCE_BYTES:()=>yf,MAX_DEPTH:()=>zg,MDBASE_NOTIFICATION_CLICK:()=>kw,MDBASE_NOTIFICATION_TYPE:()=>Op,MdbaseClient:()=>wr,MdbaseError:()=>ne,MdbasePeopleClient:()=>vr,NoiseError:()=>bt,PERSON_CONTRACT:()=>gw,PROBLEM_CODES:()=>Ex,PresenceApi:()=>Ka,READ_MANY_MAX_CONCURRENCY:()=>tw,READ_MANY_MAX_REFS:()=>ew,RecordReader:()=>hp,RecordSet:()=>Fa,SESSION_LIFETIME_MS:()=>CA,SLOW_OPENING_MS:()=>ih,SchemaError:()=>ae,Session:()=>Es,TEMPORAL_HINTS:()=>Ju,TimersApi:()=>Ha,WasmRuntime:()=>tc,Write:()=>Ms,applicationPhase:()=>Mp,approvalReadiness:()=>rP,bytesEqual:()=>Bg,clientPrologue:()=>Ur,collectionUnavailableError:()=>Fn,compareVersions:()=>qw,connect:()=>yw,controlRouteResolver:()=>oq,createMdbase:()=>X2,createViewSource:()=>Cf,decode:()=>we,describeDiagnostic:()=>Qf,describeError:()=>Us,describeHold:()=>wx,diffEdits:()=>of,duplexCarrier:()=>EA,effectiveCapabilities:()=>Z2,encode:()=>fe,encodeSecret:()=>zn,fileGrant:()=>Yb,formatSas:()=>aP,framedPort:()=>df,fromHex:()=>Wr,generateKeyPair:()=>pc,handleMdbaseNotificationClick:()=>gx,handleMdbasePush:()=>yx,holdCompareLink:()=>Iw,holdNotice:()=>vx,inProcessConnector:()=>Dl,indexedDbKeyStorage:()=>tk,isCollectionUnavailableReason:()=>Ya,isConfirmed:()=>rx,isErrorCode:()=>Po,isMdbaseError:()=>J,isProtected:()=>Qr,isReadyPhase:()=>Nx,isValid:()=>Eq,keyPairFromSecret:()=>FO,loadOrCreateClientKey:()=>rq,localLinkConnector:()=>eq,localLinkFirstPayload:()=>Q0,mdbaseError:()=>A,memoryKeyStorage:()=>ek,memoryWriteLedgerStore:()=>Mf,nextRelayConnector:()=>JO,noiseChannel:()=>RA,noiseConnector:()=>Nr,orderTargets:()=>iu,parseCollectionAvailability:()=>wi,parseHoldCompareLink:()=>bx,parseMdbaseNativeNotification:()=>Sw,parseMdbasePush:()=>Kf,parseVersion:()=>Za,pipeCloseError:()=>ua,portPair:()=>DS,problemCodeOf:()=>Ow,queryPages:()=>wf,readMany:()=>bf,readMdbaseNotificationData:()=>Pw,readViewSourceRecord:()=>If,recoveryFor:()=>kq,relayConnector:()=>Q2,relayPipeCarrier:()=>fc,resolveRecordLinks:()=>gP,revisionOf:()=>zi,routeFromControl:()=>nk,sameIdentity:()=>Vf,showMdbaseNotification:()=>xw,staticKeyOf:()=>Ly,streamCarrier:()=>WO,structMap:()=>$g,summarizeSync:()=>$f,syncStatusText:()=>_x,toHex:()=>ht,toPlain:()=>ei,toValue:()=>Ke,updateViewSource:()=>Rf,uuidv7:()=>$i,valueEquals:()=>To,versionRelation:()=>Ns,webSocketCarrier:()=>dc,wire:()=>Ib});re();tn();tn();Ls();_f();nw();sw();lw();wp();wp();cw();Je();br();gf();var FT=["collection_not_yet_migrated","collection_migrating","update_required","account_suspended"];function $f(n){let e=n.status,t=e.mode==="local_only",i=n.writes??null,o=Math.max(e.pending,i?.pending.length??0),s=!t&&n.transport?n.transport.kind:null,r=n.link===void 0||n.link==="open",a=r?t?"local":n.online===!1||s==="offline"?"offline":s?"reconnecting":e.connection==="offline"?"offline":e.connection==="connecting"?"reconnecting":"online":"reconnecting",c=[],l=t?void 0:FT.find(f=>f===n.problem);l&&c.push(l),i?.rejected.length&&c.push("rejected"),e.unresolved>0&&c.push("conflicts"),e.holds>0&&c.push("held"),e.incidents.length&&c.push("incident"),o>0&&n.storageWarning&&c.push("storage_may_be_evicted");let p=a==="offline"||s!==null||!r,d=c.length?"attention":o>0&&p?"saved_on_device":a==="offline"?"offline":a==="reconnecting"?"reconnecting":o>0?"saving":!t&&(e.installing!==void 0||e.resyncing!==void 0||e.confirmedThrough<e.headKnown)?"catching_up":"saved",u=n.pendingForMs;return{state:d,connection:a,health:s,live:t||typeof n.live!="boolean"?null:n.live,pending:o,pendingFor:o===0?null:u===void 0?"while":u<2e3?"moment":u<3e4?"while":"long",writes:i,attention:c,conflicts:e.unresolved,holds:e.holds,incidents:e.incidents}}function rx(n){return n.state==="confirmed"}uw();xp();_w();re();var Op="mdbase.notification",kw="mdbase.notification.click",dx=/^[\x21-\x7e]{1,256}$/,ZT=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,Uo=n=>A("invalid_request",n,"invalid_push_payload"),QT=()=>A("upgrade_required","The push uses an envelope version this SDK does not support.","unsupported_push_version");function fx(n){if(typeof n=="string")try{n=JSON.parse(n)}catch{throw Uo("The push payload is not JSON.")}else if(n&&typeof n=="object"&&typeof n.json=="function")try{n=n.json()}catch{throw Uo("The push payload is not JSON.")}if(!n||typeof n!="object"||Array.isArray(n))throw Uo("The push payload is not an object.");return n}function Ga(n,e,t){return typeof n=="string"&&n.length>=e&&n.length<=t}function hx(n){if(!n||typeof n!="object"||Array.isArray(n))return null;let e=n;return!Ga(e.title,1,80)||e.body!==void 0&&!Ga(e.body,0,160)||e.tag!==void 0&&!Ga(e.tag,1,80)?null:Object.freeze({title:e.title,...typeof e.body=="string"&&e.body.length?{body:e.body}:{},...typeof e.tag=="string"?{tag:e.tag}:{}})}function mx(n,e,t){if(n.type!==Op)throw Uo("The payload is not an mdbase notification.");if(e!==1)throw typeof e=="number"&&Number.isSafeInteger(e)&&e>1?QT():Uo("The payload has no valid envelope version.");if(!Ga(n.signal_id,1,256)||!dx.test(n.signal_id)||!Ga(n.cursor,1,256)||!dx.test(n.cursor)||!Ga(n.criterion_id,1,100)||!ZT.test(n.criterion_id))throw Uo("The payload is not an mdbase notification.");return Object.freeze({version:1,signalId:n.signal_id,criterionId:n.criterion_id,cursor:n.cursor,presentation:t})}function Kf(n){let e=fx(n),t=mx(e,e.version,hx(e.presentation));if(!t.presentation)throw Uo("The push has no valid presentation.");return t}function Sw(n){if(!n||typeof n!="object"||Array.isArray(n))throw Uo("The native notification data is not an object.");let e=n,t=typeof e.version=="string"&&/^[1-9][0-9]{0,8}$/.test(e.version)?Number(e.version):e.version;return mx(e,t,null)}function Pw(n){try{return Sw(n)}catch{return null}}function eM(n){return{type:Op,version:n.version,signal_id:n.signalId,criterion_id:n.criterionId,cursor:n.cursor}}async function xw(n,e,t={}){let i=Kf(e),o=i.presentation;return await n.showNotification(o.title,{...o.body?{body:o.body}:{},...o.tag?{tag:o.tag}:{},...t.icon?{icon:t.icon}:{},...t.badge?{badge:t.badge}:{},data:eM(i)}),i}function Aw(n){return globalThis[n]}function tM(n){let e=globalThis.location;if(typeof e?.origin=="string"&&e.origin!=="null")return e.origin;try{return n?new URL(n).origin:null}catch{return null}}function ux(n,e,t){let i=()=>A("invalid_request",`The notification click ${t} must be on the app's own origin.`,"click_target_cross_origin");if(typeof n!="string")throw i();if(e===null){if(!n.startsWith("/")||n.startsWith("//")||n.startsWith("/\\"))throw i();return n}let o;try{o=new URL(n,`${e}/`)}catch{throw i()}if(o.origin!==e)throw i();return o.href}function yx(n,e={}){let t;try{t=fx(n.data?.text()??null)}catch{return!1}if(t.type!==Op)return!1;let i=e.registration??Aw("registration");if(!i)throw A("invalid_request","No service worker registration to show the notification.","push_registration_missing");let o={...e.icon?{icon:e.icon}:{},...e.badge?{badge:e.badge}:{}};return n.waitUntil((async()=>{try{Kf(t)}catch(s){let r=s instanceof ne&&s.reason==="unsupported_push_version"?hx(t.presentation):null;if(!r)throw s;return await i.showNotification(r.title,{...r.body?{body:r.body}:{},...r.tag?{tag:r.tag}:{},...o}),null}return xw(i,t,o)})()),!0}function gx(n,e={}){let t=Pw(n.notification.data);if(!t)return!1;n.notification.close();let i=e.clients??Aw("clients"),o=Aw("registration")?.scope,s=tM(o),r=e.scope===void 0?o:ux(e.scope,s,"scope"),a=e.url===void 0?r??"/":ux(e.url,s,"url");return i&&n.waitUntil((async()=>{let l=(await i.matchAll({type:"window",includeUncontrolled:!0})).find(d=>!r||d.url.startsWith(r));if(!l)return i.openWindow(a);await l.focus();let p={type:kw,notification:t};return l.postMessage(p),l})()),!0}var Ep="mdbase protected your edit",nM={conflict:{cause:"This file was also changed on another device while you were editing it.",detail:"Your version is kept here and is not synced until you choose what to keep."},unknown_provenance:{cause:"This file changed on disk in a way mdbase could not trace to an app or a sync.",detail:"The bytes on disk are kept here and are not synced until you confirm them."},deleted_elsewhere:{cause:"This file was deleted on another device after you edited it.",detail:"Your version is kept here; nothing is deleted until you choose."},read_only:{cause:"Changed with view access.",detail:"Edit access will not sync these changes. Submit or discard them."},editor_busy:{cause:"An editor still has this file open with unsaved changes.",detail:"mdbase waits so that it never overwrites what you are typing."},suspect_write:{cause:"The last write to this file looked incomplete, for example after a crash.",detail:"The file is kept aside and is not synced until you confirm it."}},iM={keep_mine:{label:"Keep mine",description:"Sync the version on this device.",resolution:"keep_mine",needs:"records.edit",discardsMine:!1},take_theirs:{label:"Take theirs",description:"Replace this file with the synced version.",resolution:"take_theirs",needs:"records.edit",discardsMine:!0},keep_both:{label:"Keep both",description:"Save your version as a copy next to the synced one.",resolution:"keep_both",needs:"records.edit",discardsMine:!1},delete:{label:"Delete",description:"Accept the deletion and remove this file here too.",resolution:"delete",needs:"records.delete",discardsMine:!0},use:{label:"Use merged",description:"Sync the document you merged.",resolution:"use",needs:"records.edit",discardsMine:!1},compare:{label:"Compare side by side",description:"Open both versions to merge them.",discardsMine:!1}},rM={conflict:["keep_mine","take_theirs","compare","keep_both"],unknown_provenance:["keep_mine","take_theirs","compare","keep_both"],deleted_elsewhere:["keep_mine","delete"],read_only:["keep_mine","take_theirs","compare","keep_both"],editor_busy:["keep_mine","take_theirs","compare"],suspect_write:["keep_mine","take_theirs","compare","keep_both"]},qp="mdbase://hold/compare",Wf=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Iw(n,e){if(!Wf.test(n)||!Wf.test(e))throw new Error("holdCompareLink: collection and id are UUIDs");return`${qp}?collection=${n.toLowerCase()}&id=${e.toLowerCase()}`}function bx(n){if(typeof n!="string"||n.length>512||!n.startsWith(`${qp}?`))return null;let e=new URLSearchParams(n.slice(qp.length+1)),t=e.get("collection")??"",i=e.get("id")??"";return!Wf.test(t)||!Wf.test(i)?null:{collectionId:t.toLowerCase(),id:i.toLowerCase()}}function wx(n,e){let t=n.reason==="read_only",i=n.theirs!==void 0,o=(e.canCompare??!0)&&i,s=c=>!c||!e.capabilities||e.capabilities.includes(c),r=rM[n.reason].filter(c=>c==="compare"?o:(!t||e.host===!0)&&(c!=="take_theirs"||i||t)).map(c=>{let l={action:c,...iM[c]};return t&&c==="take_theirs"&&(l.label="Discard local changes",l.description="Discard unsynced changes on this device.",l.needs="collection.read"),l}).filter(c=>s(c.needs)),a=nM[n.reason];return{id:n.id,path:n.path,reason:n.reason,title:Ep,cause:a.cause,detail:a.detail,since:n.since,saves:n.saves,hasTheirs:i,actions:r,reversible:!t,reversibleNote:t?"Copy before discarding.":"You can change your mind later: resolving is an ordinary change, and the previous version stays in the collection's history. Keep both if you want your version kept as a file as well.",compareLink:o?Iw(e.collectionId,n.id):null}}function vx(n){return n.length?n.length===1?`${Ep}: ${n[0].path} is waiting for your choice.`:`${Ep}: ${n.length} files are waiting for your choice.`:null}function _x(n){let e=(i,o)=>`${i} ${o}`,t=`, plus ${e(n.pending,"pending")}, plus ${e(n.holds,"held")}`;return n.mode==="local_only"?`Saved on this device${t}`:`Confirmed through ${n.confirmedThrough}${t}`}Tp();th();Tp();var ih=15e3,nh=(n,e)=>{try{return!!n&&n.id===e&&n.isCurrent()}catch{return!1}},Ds=(n,e)=>Us(n,e),Ai=(n,e)=>Ds(n,e);function Mp(n,e={}){let t=PM(n,e),i=xM(t,n,e);return i.kind==="opening"&&n.status==="opening"&&n.selectedCollectionId===i.collectionId&&n.openingProgress?{...i,progress:n.openingProgress}:i}function PM(n,e){let t={...e.cpOrigin?{cpOrigin:e.cpOrigin}:{},...e.messages?{messages:e.messages}:{}},i=n.selection,o=i?.requested??null;if(n.status==="closed")return{kind:"closed"};if(n.problem==="application_not_yet_available"||n.problem==="application_worker_unavailable"||n.problem==="browser_unsupported"||n.problem==="application_storage_unavailable")return{kind:"unavailable",problem:Ai(n.problem,t)};if(i?.state==="invalid")return{kind:"problem",collectionId:null,problem:Ai(i.problem??"application_selection_invalid",t)};let s=n.signIn?.state==="paired";if(i?.state==="approving"||n.status==="authorizing"){if(n.problem==="private_authorization_failed")return{kind:"problem",collectionId:o?.collectionId??null,problem:Ai(n.problem,t)};let p=i?.approval??null;return s?p?.kind==="add"?{kind:"authorizing",purpose:"add",collectionId:null}:{kind:"authorizing",purpose:"approve",collectionId:p?.collectionId??o?.collectionId??null}:{kind:"authorizing",purpose:"sign_in",collectionId:p?.collectionId??o?.collectionId??null}}let r=n.unsynced??null;if(r&&n.selectedCollectionId===r.collectionId){let p=r.collectionId;return n.status==="ready"&&nh(e.connection,p)?{kind:"unsynced",collectionId:p,connection:e.connection,rechecking:n.readiness.checking}:n.status==="blocked"||n.status==="setup_required"&&!n.readiness.checking&&n.readiness.assessment?{kind:"problem",collectionId:p,problem:(n.status==="blocked"?Ds(n,t):Ds(n.readiness,t))??Ai("open_failed",t)}:{kind:"opening",collectionId:p,displayName:null,slow:!!e.slow}}if(n.status==="not_started"||n.status==="starting"){let p=o?.collectionId??null;return p&&n.status==="starting"?{kind:"opening",collectionId:p,displayName:o?.displayName??null,slow:!!e.slow}:{kind:"starting"}}if(n.status==="signed_out")return n.problem?{kind:"signed_out",notice:Ds(n,t)}:n.signOutResult?.server==="incomplete"?{kind:"signed_out",notice:Ai("sign_out_unconfirmed",t)}:e.openingUnsynced?{kind:"starting"}:{kind:"signed_out",notice:null};if(n.status==="blocked"){let p=n.selectedCollectionId??o?.collectionId??null;return n.problem==="recovery_account_mismatch"?{kind:"problem",collectionId:p,problem:Us(n,{...t,recoveryAccountLabel:n.recoveryAccountLabel})}:{kind:"problem",collectionId:p,problem:p&&n.removedScopeIds?.includes(p)?Ai("installation_scope_removed",t):Ds(n,t)??Ai("open_failed",t)}}if(n.status==="needs_unlock"&&n.selectedCollectionId){let p=n.selectedCollectionId,d=n.unlock??null;return d?{kind:"needs_unlock",collectionId:p,displayName:n.collections.find(u=>u.collectionId===p)?.displayName??o?.displayName??null,mode:d.mode,unlocking:d.unlocking,problem:d.problem===null?null:Ds(d.problem,t)??Ai("unlock_failed",t)}:{kind:"problem",collectionId:p,problem:Ai("open_failed",t)}}if(i?.state==="approval_required"&&o?.collectionId&&n.removedScopeIds?.includes(o.collectionId))return{kind:"problem",collectionId:o.collectionId,problem:Ai("installation_scope_removed",t)};if(i?.state==="approval_required"&&o?.collectionId)return{kind:"needs_approval",collectionId:o.collectionId,displayName:o.displayName,declined:i.problem==="application_selection_not_approved"};if(i?.state==="blocked"&&o?.collectionId&&!o.approved)return{kind:"problem",collectionId:o.collectionId,problem:Ai("unavailable",t)};if(i?.state==="pending"&&o?.collectionId)return{kind:"opening",collectionId:o.collectionId,displayName:o.displayName,slow:!!e.slow};let a=i?.usable??(n.status==="ready"||n.status==="setup_required"?n.collections.find(p=>p.collectionId===n.selectedCollectionId)??null:null);if(n.status==="setup_required"&&a)return n.readiness.assessment?.status==="incompatible"?{kind:"problem",collectionId:a.collectionId,problem:Ds(n.readiness,t)??Ai("incompatible",t)}:{kind:"needs_setup",collectionId:a.collectionId,collection:a};if(n.status==="ready"&&a&&nh(e.connection,a.collectionId))return{kind:"ready",collectionId:a.collectionId,collection:a,connection:e.connection,rechecking:n.readiness.checking,problem:null,unavailableTypes:n.readiness.assessment?.unavailableTypes??[]};let c=n.status==="opening"||n.status==="ready"||i?.state==="opening"||i?.state==="usable",l=n.selectedCollectionId??o?.collectionId??null;if(c&&l){let p=n.collections.find(d=>d.collectionId===l)?.displayName??o?.displayName??null;return{kind:"opening",collectionId:l,displayName:p,slow:!!e.slow}}return e.startPending&&s&&n.status==="unselected"&&!n.problem&&i?.state==="none"?{kind:"starting"}:{kind:"choosing",lastApproval:i?.lastApproval??null}}function xM(n,e,t){let i=t.previous;return i?.kind==="needs_setup"&&n.kind==="opening"&&n.collectionId===i.collectionId&&e.selectedCollectionId===i.collectionId&&e.readiness.checking?i:i?.kind==="unsynced"&&n.kind==="opening"&&n.collectionId===i.collectionId&&e.selectedCollectionId===i.collectionId&&nh(t.connection,i.collectionId)?{...i,connection:t.connection,rechecking:!0}:!i||i.kind!=="ready"||n.kind==="ready"||!nh(t.connection,i.collectionId)||e.selectedCollectionId!==i.collectionId?n:n.kind==="opening"&&n.collectionId===i.collectionId?{...i,connection:t.connection,rechecking:!0,problem:null}:n.kind==="problem"&&n.problem.transient?{...i,connection:t.connection,rechecking:!0,problem:n.problem}:n}function Nx(n,e){return n?.kind==="ready"&&(e===void 0||n.collectionId===e)}Ll();Tp();Jt();hm();ym();_m();var Rr={runtime:{sha256:"cb7e1bde045fbe9395feca75364e6325546d63de1475e8d3df8f0cf2fa07cb14",bytes:4264356,maxBytes:4264356,source:{repository:"mdbase-dev/mdbase-connect",commit:"7302674e51ceb15ca8d3e9e4e93239d48e2c8314"}},sqlite:{sha256:"2ee8f3dab694532afc8840e07703127287662d08b74e6ff50491ce63f00d5752",bytes:868907,maxBytes:11e5,initializer:{sha256:"a6d3fe46aa3f924e7686329f97b0564549ef1f787e0c19924179aef7f72bcc01",bytes:642742},asyncProxy:{sha256:"9f1970e05ee07a79332498858740b705eeb1dcee03bc150f6f690bc0fb5f0a06",bytes:32505}}};Jt();re();St();var lj=Math.max(Rr.runtime.maxBytes,Rr.sqlite.maxBytes),Ri=n=>A("unavailable","application asset unavailable",n),cj=()=>A("cancelled","application asset read fenced","application_asset_fenced");function Or(n){if(n.aborted)throw cj()}function QC(n,e){let t=Object.freeze({...n}),i=Object.freeze({...e}),o,s;try{o=new URL(t.url),s=new URL(i.origin)}catch{throw Ri("application_asset_binding")}if(!ut(i.origin)||s.protocol!==o.protocol||!ts(i.environment)||Cr(i.environment)&&!ns(i.origin)||dt(o)!==i.origin||o.username||o.password||o.search||o.hash||!/^[0-9a-f]{64}$/.test(t.sha256)||!Number.isSafeInteger(t.bytes)||t.bytes<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<t.bytes||t.maxBytes>lj)throw Ri("application_asset_binding");let r=i.fetch??globalThis.fetch;if(typeof r!="function")throw Ri("application_asset_unavailable");let a=new URL(o.href);return a.searchParams.set("mdbase-sdk-asset",t.sha256),async({signal:c})=>{Or(c);let l=null,p;try{globalThis.caches&&(l=await globalThis.caches.open("mdbase.sdk.application-assets.v1"),p=await l.match(a.href))}catch{}let d=p!==void 0;if(!p){Or(c);try{p=await r(o.href,{signal:c,credentials:"omit",cache:"force-cache",redirect:"error"})}catch{throw Or(c),Ri("application_asset_fetch")}}let u=p.body?.getReader();if(!u)throw Or(c),Ri("application_asset_response");let f=!1,h=null,m=()=>h??=Promise.resolve().then(async()=>{try{await u.cancel()}catch{throw Ri("application_asset_stop_failed")}}),w=()=>{m().catch(()=>{})};c.addEventListener("abort",w,{once:!0});try{if(Or(c),!p.ok||p.redirected||p.url&&p.url!==o.href)throw Ri("application_asset_response");let b=p.headers.get("content-length"),g=p.headers.get("content-encoding");if(b!==null&&(g===null||g.trim().toLowerCase()==="identity")&&(!/^(?:0|[1-9][0-9]*)$/.test(b)||Number(b)!==t.bytes))throw Ri("application_asset_binding");let y=new Uint8Array(t.bytes),v=0;for(;;){let k=await u.read();if(Or(c),k.done){f=!0;break}if(!(k.value instanceof Uint8Array)||k.value.byteLength>t.bytes-v)throw Ri("application_asset_binding");y.set(k.value,v),v+=k.value.byteLength}if(v!==t.bytes)throw Ri("application_asset_binding");let _=new Uint8Array(await crypto.subtle.digest("SHA-256",y));if(Or(c),Array.from(_,k=>k.toString(16).padStart(2,"0")).join("")!==t.sha256)throw Ri("application_asset_binding");if(Or(c),l&&!d)try{await l.put(a.href,new Response(y))}catch{}return Or(c),y}catch(b){throw Or(c),J(b)?b:Ri("application_asset_response")}finally{c.removeEventListener("abort",w);try{(!f||c.aborted)&&await m()}finally{u.releaseLock()}}}}rs();Jt();re();gm();St();var Am={},pj=Object.freeze({sha256:Rr.runtime.sha256,bytes:Rr.runtime.bytes,maxBytes:Rr.runtime.maxBytes}),dj=Object.freeze({sha256:Rr.sqlite.sha256,bytes:Rr.sqlite.bytes,maxBytes:Rr.sqlite.maxBytes}),wd=()=>A("unavailable","SDK packaged application assets unavailable","application_packaged_assets_unavailable");function e1(n,e,t){if(!ts(n))throw wd();let i=Ks();Ci({environment:n,appOrigin:e,release:i});let o,s;try{let c=new URL(t??Am.url);if(dt(c)!==e||c.username||c.password||(o=t===void 0?new URL("../native/runtime.wasm",Am.url):new URL("../native/runtime.wasm",c),s=t===void 0?new URL("../native/sqlite3.wasm",Am.url):new URL("../native/sqlite3.wasm",c),dt(o)!==e||dt(s)!==e))throw wd()}catch{throw wd()}let r=(c,l)=>Object.freeze({url:c.href,...l}),a=async c=>{let l=globalThis.WorkerGlobalScope;if(typeof l!="function"||!(globalThis instanceof l))throw wd();let p=t===void 0?new URL("../native/sqlite3.js",Am.url):new URL("../native/sqlite3.js",t),{default:d}=await import(p.href);return globalThis.sqlite3ApiConfig={disable:{vfs:{opfs:!0,"opfs-wl":!0}}},d(c)};return Object.freeze({release:()=>Ks(),runtime:r(o,pj),sqlite:r(s,dj),initializeSqlite:a})}rp();var uj="mdbase:startup:",fj=new Set(["signed_out","authorizing","choosing","needs_approval","needs_setup","problem","unavailable","closed"]);function hj(){let n=globalThis.performance;return typeof n?.now=="function"&&typeof n.measure=="function"?n:null}var km=class{clock=hj();began=this.clock?.now()??0;stage=null;since=this.began;done=this.clock===null;measure(e,t,i){try{this.clock?.measure(`${uj}${e}`,{start:t,end:i})}catch{}}async time(e,t){if(this.done)return t();let i=this.clock.now();try{return await t()}finally{this.measure(e,i,this.clock.now())}}observe(e){if(this.done)return;let t=e.kind==="opening"&&e.progress?`opening:${e.progress}`:e.kind;if(t===this.stage)return;let i=this.clock.now();this.stage!==null&&this.measure(this.stage,this.since,i),this.stage=t,this.since=i;let o=e.kind==="ready"||e.kind==="unsynced";o&&this.measure("total",this.began,i),(o||fj.has(e.kind))&&(this.done=!0)}};function t1(n,e,t){if(n.requested.collectionId!==null){let i=n.requested.collectionId!==t?.selection.requested.collectionId;i&&fr("mdbase:open:requested"),n.requested.approved&&(i||!t?.selection.requested.approved)&&fr("mdbase:open:approved")}e.kind==="ready"&&(t?.phase.kind!=="ready"||t.phase.connection!==e.connection)&&fr("mdbase:open:ready")}gm();St();rs();Jt();var yn=class extends Error{constructor(t){super("SDK collection selection unavailable");this.code=t;this.name="ApplicationSelectionError"}code},vd=n=>typeof n=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(n)&&n!=="00000000-0000-0000-0000-000000000000",mn=(n,e,t=null)=>Object.freeze({requestedCollectionId:n,source:e,problem:t});function n1(n,e){return n.source!=="none"?n:e.storedId!==void 0&&e.storedId!==null?vd(e.storedId)?mn(e.storedId,"stored"):mn(null,"stored","application_selection_invalid"):e.collections.length>1024||e.collections.some(t=>!vd(t.collectionId))||new Set(e.collections.map(t=>t.collectionId)).size!==e.collections.length?mn(null,"none","application_selection_metadata"):e.preferredId!==void 0&&e.preferredId!==null?vd(e.preferredId)&&e.collections.some(t=>t.collectionId===e.preferredId)?mn(e.preferredId,"preferred"):mn(null,"preferred","application_selection_metadata"):e.collections.length===1?mn(e.collections[0].collectionId,"sole"):mn(null,"none")}var Sm=class{port;origin;parameter;fallback;listeners=new Set;snapshot=mn(null,"none");stopListening=null;started=!1;closed=!1;constructor(e,t={},i=null){let o,s;try{o=new URL(e),s=new URL(t.fallbackPath??"/",o)}catch{throw new yn("application_selection_binding")}let r=t.parameter??"collection";if(!ut(e)||dt(o)!==e||dt(s)!==e||s.username||s.password||s.search||s.hash||typeof r!="string"||!/^[a-z][a-zA-Z0-9_.-]{0,63}$/.test(r)||["code","state","error","error_description"].includes(r))throw new yn("application_selection_binding");this.origin=e,this.parameter=r,this.fallback=s.href,this.port=i}getSnapshot(){return this.snapshot}subscribe(e){return this.check(),this.listeners.add(e),()=>{this.listeners.delete(e)}}start(){return this.check(),this.started?this.snapshot:(this.started=!0,this.stopListening=this.port?.listen(()=>{this.closed||this.publish(this.read())})??null,this.publish(this.read()),this.snapshot)}check(){if(this.closed)throw new yn("application_selection_fenced")}url(){let e;try{e=new URL(this.port.href())}catch{throw new yn("application_selection_binding")}if(dt(e)!==this.origin||e.username||e.password)throw new yn("application_selection_binding");return e}read(){if(!this.port)return mn(null,"none");let e;try{e=this.url().searchParams.getAll(this.parameter)}catch{return mn(null,"url","application_selection_binding")}return e.length===0?mn(null,"none"):e.length!==1?mn(null,"url","application_selection_duplicate"):e[0]===""?mn(null,"url","application_selection_empty"):vd(e[0])?mn(e[0],"url"):mn(null,"url","application_selection_invalid")}publish(e){if(!(this.snapshot.requestedCollectionId===e.requestedCollectionId&&this.snapshot.source===e.source&&this.snapshot.problem===e.problem)){this.snapshot=e;for(let t of[...this.listeners])try{t()}catch{}}}select(e,t={}){if(this.check(),e!==null&&!vd(e))throw new yn("application_selection_invalid");let i=t.history??"replace";if(i!=="push"&&i!=="replace")throw new yn("application_selection_binding");if(this.port){let o=this.url(),s=o.href;e===null?o.searchParams.delete(this.parameter):o.searchParams.set(this.parameter,e),o.href!==s&&this.port.write(o.href,i)}return this.publish(mn(e,e===null?"none":"user")),this.snapshot}returnUrl(e){this.check();try{let t=new URL(e,this.origin);if(dt(t)===this.origin&&!t.username&&!t.password)return t.href}catch{}return this.fallback}close(){if(this.closed)return;this.closed=!0;let e=this.stopListening;this.stopListening=null,e?.(),this.listeners.clear()}};function i1(){if(typeof window>"u"||!window.location||!window.history)return null;let n=window;return Object.freeze({href:()=>n.location.href,write:(e,t)=>{t==="push"?n.history.pushState(n.history.state,"",e):n.history.replaceState(n.history.state,"",e)},listen:e=>(n.addEventListener("popstate",e),()=>n.removeEventListener("popstate",e))})}var mj=n=>typeof n=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(n)&&n!=="00000000-0000-0000-0000-000000000000",Ul=n=>n.status==="ready"||n.status==="setup_required",Nl=n=>n.status==="needs_unlock",r1=n=>n.signIn?.state==="paired"&&(n.status==="unselected"||n.status==="blocked"||Ul(n)||Nl(n)),yj=n=>n.status==="not_started"||n.status==="starting"||n.status==="signed_out"||n.status==="authorizing",Er=(n,e)=>e===null?null:n.collections.find(t=>t.collectionId===e)??null,Pm=class{browser;session;memory;preferredId;schedule;listeners=new Set;stops=[];value;key="";startTarget=null;startApplied=!1;startHeld=!0;failed=null;before=null;attempted=void 0;lastRequested=null;opening=null;approval=null;lastApproval=null;declined=null;remembered=void 0;queued=!1;started=!1;closed=!1;constructor(e){this.browser=e.browser,this.session=e.session,this.memory=e.memory??null,this.preferredId=e.preferredId??null,this.schedule=e.schedule??(t=>{setTimeout(t,0)}),this.value=this.derive(),this.key=this.keyOf(this.value)}startPending(){return this.startHeld}keyOf(e){return JSON.stringify(e)+(this.startHeld?"|start":"")}getSnapshot(){return this.value}subscribe(e){return this.check(),this.listeners.add(e),()=>{this.listeners.delete(e)}}start(){return this.check(),this.started?this.value:(this.started=!0,this.browser.start(),this.stops.push(this.browser.subscribe(this.changed),this.session.subscribe(this.changed)),this.changed(),this.value)}select(e,t={}){this.check(),this.startTarget=null,this.browser.select(e,t.history?{history:t.history}:{}),this.declined=null,this.refresh(),e===null&&this.remember(null);let i=this.session.getSnapshot();return e!==null&&i.selectedCollectionId===e&&i.status==="opening"?(this.attempted=e,Promise.resolve(this.value)):this.whenIdle(async()=>{let o=this.session.getSnapshot();this.requested().requestedCollectionId===e&&((e===null?o.selectedCollectionId===null&&o.status!=="opening":o.selectedCollectionId===e&&(Ul(o)||Nl(o))||!Er(o,e))||await this.run(e,t,!0))}).then(()=>this.value)}chooseAnother(e={}){return this.select(null,{...e,history:"push"})}approve(e,t={}){if(this.check(),e!=null&&!mj(e))return Promise.reject(new yn("application_selection_invalid"));if(this.approval&&!this.approval.settled)return Promise.reject(new yn("application_selection_busy"));e!=null&&e!==this.requested().requestedCollectionId&&(this.startTarget=null,this.browser.select(e,t.history?{history:t.history}:{}));let i=this.session.getSnapshot().signIn,o=i?.nativeSelection?.requestId??i?.collectionSelection?.requestId??null,s,r=e===null?null:this.requested().requestedCollectionId;try{s=this.session.authorize({...t.signal?{signal:t.signal}:{},collectionHint:r})}catch(p){return Promise.reject(p)}let a=r===null?"add":"collection",c=new Set(this.session.getSnapshot().collections.map(p=>p.collectionId)),l={receipt:o,kind:a,collectionId:r,before:c,settled:!1};return this.approval=l,this.lastApproval=null,this.declined=null,this.attempted=void 0,this.refresh(),s.then(()=>(l.settled=!0,this.changed(),this.value),p=>{if(this.approval===l){this.approval=null;let d=p?.code;(d==="cancelled"||d==="aborted")&&(this.lastApproval=Object.freeze({kind:a,outcome:"closed",collectionId:r}))}throw this.changed(),p})}clearLastApproval(){this.check(),this.lastApproval=null,this.refresh()}reauthorize(e={}){this.check();let t=this.value.usable?.collectionId??this.requested().requestedCollectionId;return t===null?Promise.reject(new yn("application_selection_empty")):this.approve(t,e)}resync(){this.closed||(this.attempted=void 0,this.failed=null,this.approval=null,this.changed())}close(){if(!this.closed){this.closed=!0;for(let e of this.stops.splice(0))try{e()}catch{}this.browser.close(),this.listeners.clear()}}check(){if(this.closed)throw new yn("application_selection_fenced")}requested(){let e=this.browser.getSnapshot(),t=this.startTarget;return t&&e.source==="user"&&e.requestedCollectionId===t.requestedCollectionId?t:e}changed=()=>{this.closed||(this.refresh(),!(this.queued||!this.started)&&(this.queued=!0,this.schedule(()=>{this.queued=!1,this.reconcile()})))};refresh(){let e=this.requested().requestedCollectionId;if(e!==this.lastRequested&&(this.lastRequested=e,this.attempted=void 0,this.failed=null,this.declined!==e&&(this.declined=null)),e!==null&&this.attempted===e){let o=this.session.getSnapshot();o!==this.before&&(o.status==="blocked"?o.selectedCollectionId===e:o.status==="unselected"&&o.problem!==null)&&(this.failed=e)}let t=this.derive(),i=this.keyOf(t);if(t.state==="usable"&&this.remember(t.usable.collectionId),i!==this.key){this.key=i,this.value=Object.freeze(t);for(let o of[...this.listeners])try{o()}catch{}}}remember(e){if(!(!this.memory||this.remembered===e)){this.remembered=e;try{this.memory.write(e)}catch{}}}derive(){let e=this.session.getSnapshot(),t=this.requested(),i=t.requestedCollectionId,o=Er(e,i),s=Ul(e)?Er(e,e.selectedCollectionId):null,r,a=null;if(t.problem)r="invalid",a=t.problem;else if(this.approval)r="approving";else if(i===null)r="none";else if(s?.collectionId===i)r="usable";else if(e.selectedCollectionId===i&&(e.status==="blocked"||e.status==="opening"||Nl(e)))r=e.status==="blocked"?"blocked":"opening";else if(!r1(e))r="pending";else if(o)r="opening";else{let l=this.session.listing?.();l==="unavailable"?r="blocked":l?r="pending":(r="approval_required",this.declined===i&&(a="application_selection_not_approved"))}let c=this.approval?Object.freeze({kind:this.approval.kind,collectionId:this.approval.collectionId,reopenable:this.approval.settled}):null;return Object.freeze({state:r,problem:a,approval:c,lastApproval:this.lastApproval,usable:s?Object.freeze({...s}):null,requested:Object.freeze({collectionId:i,source:t.source,displayName:o?.displayName??null,approved:o!==null})})}async whenIdle(e){for(;this.opening;)await this.opening;this.check(),await e()}run(e,t={},i=!1){this.attempted=e,this.failed=null,this.before=this.session.getSnapshot();let o=t.signal?{signal:t.signal}:{},s=Promise.resolve().then(()=>e===null?this.session.clear(o):this.session.open(e,o)),r=s.then(()=>{},()=>{}).finally(()=>{this.opening===r&&(this.opening=null,this.changed())});return this.opening=r,i?s.then(()=>{}):r}async reconcile(){if(this.closed||this.opening)return;let e=this.session.getSnapshot();if(this.approval)if(this.approval.settled&&e.status==="signed_out"&&(e.problem!==null||e.approval?.outcome==="closed")){let o=this.approval;this.approval=null,this.attempted=void 0,this.lastApproval=Object.freeze({kind:o.kind,outcome:e.problem==="approval_window_closed"||e.approval?.outcome==="closed"?"closed":"declined",collectionId:o.collectionId}),this.refresh()}else{if(!this.approval.settled||yj(e))return;let o=e.signIn?.nativeSelection;if(o&&o.requestId!==this.approval.receipt&&!Er(e,o.collectionId)&&this.session.listing?.()===!0)return;this.finishApproval(e)}if(!r1(e))return;if(!this.startApplied){if(this.browser.getSnapshot().source==="none"){let o=null;try{o=this.memory?.read()??null}catch{}if(o!==null&&!Er(e,o)&&this.session.listing?.()){this.startHeld=!1,this.refresh();return}this.startApplied=!0;let s=n1(this.browser.getSnapshot(),{storedId:o,preferredId:this.preferredId,collections:e.collections});s.requestedCollectionId!==null&&!s.problem&&(this.browser.select(s.requestedCollectionId,{history:"replace"}),this.startTarget=s)}else this.startApplied=!0;this.startHeld=!1,this.refresh()}let t=this.requested(),i=t.requestedCollectionId;if(!t.problem){if(i===null){this.attempted!==null&&e.selectedCollectionId!==null&&(Ul(e)||Nl(e))&&this.run(null);return}if(e.selectedCollectionId===i&&(Ul(e)||Nl(e)||e.status==="opening")){this.attempted=i,this.failed=null;return}if(e.selectedCollectionId===i&&e.status==="blocked"){this.failed=i;return}Er(e,i)&&(this.attempted===i&&(this.failed!==i||e.status!=="unselected"||e.problem!==null)||(this.failed=null,this.run(i)))}}finishApproval(e){let t=this.approval,i=t.receipt;this.approval=null,this.attempted=void 0;let o=u=>u!==null&&Er(e,u)?t.before.has(u)?"unchanged":"added":e.approval?.outcome==="closed"?"closed":"declined",s=e.signIn?.collectionSelection,r=e.signIn?.nativeSelection,c=(r&&r.requestId!==i&&Er(e,r.collectionId)?r.collectionId:null)??(s&&s.requestId!==i&&Er(e,s.selectedCollectionId)?s.selectedCollectionId:null);if(c!==null){c!==this.requested().requestedCollectionId&&(this.startTarget=null,this.browser.select(c,{history:"replace"})),this.lastApproval=Object.freeze({kind:t.kind,outcome:o(c),collectionId:c}),this.refresh(),e.selectedCollectionId===c&&(Ul(e)||Nl(e)||e.status==="opening")?this.attempted=c:this.run(c);return}let l=this.requested().requestedCollectionId;l!==null&&!Er(e,l)&&(this.declined=l);let p=t.kind==="add"?e.collections.find(u=>!t.before.has(u.collectionId))?.collectionId??null:null,d=t.kind==="add"?p:t.collectionId??l;this.lastApproval=Object.freeze({kind:t.kind,outcome:o(d),collectionId:d}),this.refresh()}};qd();x_();re();t_();var ic="unsynced",xU="current";var V_="moved.",oy=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/;var F_=class extends Error{constructor(t){super(`app unsynced collection: ${t}`);this.reason=t;this.name="AppUnsyncedCollectionError"}reason},Jn=(n="unavailable")=>new F_(n);function IU(n){if(!n||typeof n!="object"||Array.isArray(n)||Object.keys(n).some(i=>!["version","account","installation","collection","replica","device","timezone"].includes(i)))throw Jn();let e=n,t=[e.account,e.installation,e.collection,e.replica,e.device];if(e.version!==1||t.some(i=>typeof i!="string"||!oy.test(i))||new Set(t).size!==t.length||"timezone"in e&&e.timezone!==null&&!Im(e.timezone))throw Jn();return Object.freeze({...e})}function gR(n,e){if(e.throwIfAborted(),!globalThis.indexedDB)throw Jn();return new Promise((t,i)=>{let o=indexedDB.open(n,1),s=!1,r=()=>e.removeEventListener("abort",a),a=()=>{s=!0,r();try{o.transaction?.abort()}catch{}i(Jn("fenced"))};e.addEventListener("abort",a,{once:!0}),o.onblocked=o.onerror=a,o.onupgradeneeded=()=>{try{if(s||o.result.objectStoreNames.length)throw Jn();o.result.createObjectStore(ic)}catch{try{o.transaction?.abort()}catch{}}},o.onsuccess=()=>{if(r(),s||o.result.objectStoreNames.length!==1||!o.result.objectStoreNames.contains(ic)){o.result.close(),i(Jn());return}t(o.result)}})}async function CU(n,e,t,i,o){let s=await gR(n,o);try{return await new Promise((r,a)=>{let c=s.transaction(ic,i?"readwrite":"readonly",{durability:"strict"}),l=null,p=null;c.onabort=c.onerror=()=>a(p??Jn()),c.oncomplete=()=>r(l);let d=c.objectStore(ic),u=d.get(e);u.onsuccess=()=>{try{if(u.result!==void 0){l=t(u.result);return}if(!i)return;let f=t(i());d.add(f,e),l=f}catch(f){p=f,c.abort()}}})}finally{s.close()}}async function RU(n,e,t){let i=await gR(n,e);try{return await new Promise((o,s)=>{let r=i.transaction(ic,"readwrite",{durability:"strict"}),a,c=null;r.onabort=r.onerror=()=>s(c??Jn()),r.oncomplete=()=>o(a),t(r.objectStore(ic),l=>{a=l},l=>{c=l,r.abort()})})}finally{i.close()}}var bR=/^sha256:[0-9a-f]{64}$/;function wR(n){let e=n;if(!e||e.version!==1||!e.revisions||typeof e.revisions!="object"||Array.isArray(e.revisions))throw Jn();let t=new Map;for(let[i,o]of Object.entries(e.revisions)){if(!oy.test(i)||typeof o!="string"||!bR.test(o))throw Jn();t.set(i,o)}return t}async function vR(n,e,t){if(!oy.test(e))throw Jn("binding");return await CU(n,V_+e,wR,null,t)??new Map}function _R(n,e,t,i){for(let[o,s]of t)if(!oy.test(o)||!bR.test(s))return Promise.reject(Jn("binding"));return RU(n,i,(o,s,r)=>{let a=o.get(xU),c=o.get(V_+e);c.onsuccess=()=>{try{if(a.result===void 0||IU(a.result).collection!==e){r(Jn());return}let l=c.result===void 0?new Map:wR(c.result);for(let[p,d]of t)l.set(p,d);o.put({version:1,revisions:Object.fromEntries(l)},V_+e),s()}catch(l){r(l)}}})}var zG=720*60*60*1e3;re();var K_=new WeakMap,OU=100,EU=(n,e)=>`unsynced/1\0${n}\0${e}`;async function sy(n,e,t){try{return await n.get(e,{signal:t})}catch(i){if(J(i,"not_found"))return null;throw i}}function qU(n,e){let t=n.lastIndexOf("/"),i=n.lastIndexOf("."),o=i>t+1?i:n.length;return`${n.slice(0,o)} ${e}${n.slice(o)}`}async function TU(n,e){let t=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`unsynced/1\0copy\0${n}\0${e}`))).slice(0,16);t[6]=t[6]&15|128,t[8]=t[8]&63|128;let i=[...t].map(o=>o.toString(16).padStart(2,"0")).join("");return`${i.slice(0,8)}-${i.slice(8,12)}-${i.slice(12,16)}-${i.slice(16,20)}-${i.slice(20)}`}function MU(n){if(n.document===void 0)throw A("invalid_request","the source record has no document");return{path:n.path,document:n.document}}async function W_(n,e,t={}){let{signal:i}=t,o=t.map??MU;if(n.collection===e.collection)throw A("invalid_request","a collection cannot be transferred into itself");let s=t.ledger?await t.ledger.read(n.collection,i):new Map,r=new Map,a=await e.describe(i?{signal:i}:{}),c=new Set(a.types.map(b=>b.name.toLowerCase())),l=[],p=new Map,d=new Set,u=new Set,f=0;for await(let b of n.pages({},{include:{body:!0,document:!0},signal:i}))for(let g of b.records){i?.throwIfAborted();let y=null;if(await sy(e,g.id,i)){let S=s.get(g.id);if(S===void 0&&r.set(g.id,g.revision),S===void 0||S===g.revision){l.push(Object.freeze({sourceId:g.id,sourcePath:g.path,outcome:"present"}));continue}if(y=await TU(g.id,g.revision),await sy(e,y,i)){r.set(g.id,g.revision),l.push(Object.freeze({sourceId:g.id,sourcePath:g.path,outcome:"present"}));continue}}let v=await o(g);if(v===null){l.push(Object.freeze({sourceId:g.id,sourcePath:g.path,outcome:"skipped"}));continue}if(!v||typeof v!="object"||v.id!==void 0&&v.id!==g.id)throw A("invalid_request","the transfer map must keep the record ID");r.set(g.id,g.revision);let _=v.path??g.path,k=_;for(let S=2;d.has(k.toLowerCase())||await sy(e,{path:k},i);S++){if(S>OU)throw A("conflict",`no free path beside ${_}`,"path_taken");k=qU(_,S)}d.add(k.toLowerCase());for(let S of v.type?[v.type]:g.types)c.has(S.toLowerCase())||u.add(S);p.set(g.id,Object.freeze({...v,id:y??g.id,path:k})),k!==_&&!y&&f++,l.push(Object.freeze({sourceId:g.id,sourcePath:g.path,outcome:y?"changed":"create",path:k,...y?{copyId:y}:k!==_?{renamedFrom:_}:{}}))}let h=new Map;if(t.addTypes&&u.size){let b=new Map((await n.describe(i?{signal:i}:{})).types.map(g=>[g.name.toLowerCase(),g]));for(let g of[...u].sort()){let y=b.get(g.toLowerCase());if(!y?.revision)continue;let v;try{v=(await n.resources.get(y.path,{signal:i})).text}catch(_){if(J(_,"not_found"))continue;throw _}typeof v=="string"&&(h.set(y.name,v),u.delete(g))}}let m=b=>l.filter(g=>g.outcome===b).length,w=Object.freeze({source:n.collection,destination:e.collection,items:Object.freeze(l),missingTypes:Object.freeze([...u].sort()),addTypes:Object.freeze([...h.keys()].sort()),counts:Object.freeze({create:m("create"),present:m("present"),skipped:m("skipped"),renamed:f,changed:m("changed")})});return K_.set(w,Object.freeze({inputs:p,types:h,map:t.map,ledger:t.ledger,settle:r})),w}async function AR(n,e,t,i){let o=K_.get(n);if(!o)throw A("invalid_request","plan the transfer first");if(e.collection!==n.source||t.collection!==n.destination)return!1;let s=await W_(e,t,{...o.map?{map:o.map}:{},...o.ledger?{ledger:o.ledger}:{},...i?{signal:i}:{}});return s.counts.create===0&&s.counts.changed===0}async function kR(n,e,t={}){let i=K_.get(n),{signal:o}=t;if(!i)throw A("invalid_request","plan the transfer first");let{inputs:s}=i;if(e.collection!==n.destination)throw A("invalid_request","the plan is for another collection");let r=n.items.filter(m=>m.outcome==="create"||m.outcome==="changed"),a=[],c=[],l=0,p=n.counts.present,d=0,u=()=>{try{t.onProgress?.(Object.freeze({done:d,total:r.length}))}catch{}};i.ledger&&i.settle.size&&await i.ledger.record(n.source,i.settle,o);let f=[],h=[];for(let[m,w]of i.types){o?.throwIfAborted();try{await e.createType(w,o?{signal:o}:{}),f.push(m)}catch(b){o?.throwIfAborted(),J(b,"conflict")?f.push(m):h.push(Object.freeze({name:m,code:J(b)?b.code:"unavailable"}))}}u();for(let m of r){o?.throwIfAborted();try{let w=await e.create(s.get(m.sourceId),{intent:EU(n.source,m.copyId??m.sourceId),...o?{signal:o}:{}});c.push(w.mutationId),l++}catch(w){o?.throwIfAborted(),await sy(e,m.copyId??m.sourceId,o).catch(()=>null)?p++:a.push(Object.freeze({sourceId:m.sourceId,code:J(w)?w.code:"unavailable"}))}d++,u()}return Object.freeze({source:n.source,destination:n.destination,created:l,present:p,skipped:n.counts.skipped,failed:Object.freeze(a),addedTypes:Object.freeze(f),failedTypes:Object.freeze(h),mutations:Object.freeze(c),retired:!1})}zd();Gf();os();oh();var RR="mdbn-app-tabs/1",J_="\0mdbn-port";var $d=n=>typeof n=="string"&&/^[0-9a-f-]{36}$/.test(n);function UU(n){if(!n||typeof n!="object")return null;let e=n;switch(e.k){case"join":case"leave":return $d(e.tab)?e:null;case"leader":case"bye":case"fault":case"signedOut":case"signedIn":return $d(e.leader)?e:null;case"joined":return $d(e.tab)&&$d(e.leader)&&typeof e.binding=="string"?e:null;case"m":return $d(e.tab)&&typeof e.up=="boolean"&&Number.isSafeInteger(e.s)&&e.s>=0?e:null;default:return null}}function X_(n){if(!n||typeof n!="object")return!1;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}function Z_(n,e,t=0){return n instanceof MessagePort?{[J_]:e(n)}:t>=6?n:Array.isArray(n)?n.map(i=>Z_(i,e,t+1)):X_(n)?Object.fromEntries(Object.entries(n).map(([i,o])=>[i,Z_(o,e,t+1)])):n}function Q_(n,e,t,i=0){if(X_(n)&&Object.keys(n).length===1&&Number.isSafeInteger(n[J_])){let o=e(n[J_]);return t.push(o),o}return i>=6?n:Array.isArray(n)?n.map(o=>Q_(o,e,t,i+1)):X_(n)?Object.fromEntries(Object.entries(n).map(([o,s])=>[o,Q_(s,e,t,i+1)])):n}var cy=class{constructor(e,t){this.send=e;this.up=t;this.next=t?1:2}send;up;streams=new Map;next;bridge(e,t){this.streams.set(t,e),e.onmessage=i=>{let o=i.ports.length?Z_(i.data,s=>{let r=this.next;return this.next+=2,this.bridge(s,r),r}):i.data;try{this.send(t,o)}catch{}}}deliver(e,t){let i=this.streams.get(e);if(!i)return;let o=[],s=Q_(t,r=>{let a=new MessageChannel;return this.bridge(a.port1,r),a.port2},o);try{i.postMessage(s,o)}catch{for(let r of o)r.close()}}close(){for(let e of this.streams.values()){e.onmessage=null;try{e.close()}catch{}}this.streams.clear()}},py=class{constructor(e,t,i,o=()=>{},s={}){this.env=t;this.lost=i;this.signedInElsewhere=o;this.role=s;this.base=e.storageNamespace===void 0?`${RR}/${e.cpOrigin}/${e.appId}/${e.build}`:`${RR}/namespace/${JSON.stringify([e.cpOrigin,e.appId,e.build,e.storageNamespace])}`}env;lost;signedInElsewhere;role;tab=crypto.randomUUID();base;channel=null;presence=null;leading=null;hub=null;follower=null;signingOut=!1;announced=!1;joining=null;get leader(){return this.leading!==null}open(){if(this.channel)return this.channel;let e=new this.env.BroadcastChannel(this.base);return e.onmessage=t=>this.received(UU(t.data)),this.channel=e,e}post(e){this.channel?.postMessage(e)}hold(e,t,i){return new Promise((o,s)=>{let r=c=>{if(!c){o(null);return}return new Promise(l=>o(l))};(t?this.env.locks.request(e,{ifAvailable:!0},r):this.env.locks.request(e,{signal:i},r)).catch(s)})}async elect(e){e.throwIfAborted(),this.open(),this.presence??=await this.hold(`${this.base}/tab/${this.tab}`,!0),e.throwIfAborted();let t=this.role.lead!==!1;if(t&&!this.leading&&(this.leading=await this.hold(`${this.base}/leader`,!0)),this.leading)return e.aborted&&(this.resign(),e.throwIfAborted()),{kind:"leader"};let i=new AbortController,o=()=>i.abort();e.addEventListener("abort",o,{once:!0});let s=t?this.hold(`${this.base}/leader`,!1,i.signal):null,r;try{r=await new Promise((d,u)=>{s?.then(f=>{f&&d({release:f})},()=>{}),this.joining={resolve:d,reject:u},e.addEventListener("abort",()=>u(e.reason),{once:!0}),this.join()})}catch(d){throw this.joining=null,i.abort(),d}finally{e.removeEventListener("abort",o)}if(this.joining=null,"release"in r)return this.leading=r.release,e.aborted&&(this.resign(),e.throwIfAborted()),{kind:"leader"};e.aborted&&(i.abort(),e.throwIfAborted());let a=new MessageChannel,c=this.tab,l=new cy((d,u)=>this.post({k:"m",tab:c,up:!0,s:d,d:u}),!0);l.bridge(a.port2,0);let p={leader:r.leader,tunnel:l,wait:i,port:a.port1,left:!1,signedOut:!1};return this.follower=p,(s??this.hold(`${this.base}/leader`,!1,i.signal)).then(d=>{if(!d)return;let u=this.follower===p&&!p.left;u&&t?this.leading=d:d(),u&&this.departed(p)},()=>{}),{kind:"follower",port:a.port1,binding:r.binding,leave:()=>this.leave(p)}}join(){this.post({k:"join",tab:this.tab,...this.role.lead===!1?{needsLeader:!0}:{}})}lead(e){!this.leading||this.hub||(this.hub={followers:new Map,worker:e,faulted:!1},this.post({k:"leader",leader:this.tab}))}fault(){!this.hub||this.hub.faulted||(this.hub.faulted=!0,this.post({k:"fault",leader:this.tab}))}signedOut(){this.hub&&(this.signingOut=!0,this.post({k:"signedOut",leader:this.tab}))}signedIn(){!this.hub||this.announced||this.signingOut||(this.announced=!0,this.post({k:"signedIn",leader:this.tab}))}resign(){let e=this.hub,t=this.signingOut;this.hub=null,this.signingOut=!1,this.announced=!1,e&&this.post({k:"bye",leader:this.tab,...t?{signedOut:!0}:{}});let i=this.leading;if(this.leading=null,i?.(),e){for(let o of e.followers.values())o.watch.abort(),o.tunnel.close();e.followers.clear()}}leave(e){e.left||(e.left=!0,e.wait.abort(),e.tunnel.close(),this.follower===e&&(this.follower=null,this.post({k:"leave",tab:this.tab})))}departed(e,t=!1){e.left||this.follower!==e||(e.left=!0,e.wait.abort(),e.tunnel.close(),this.follower=null,this.lost(t||e.signedOut))}release(){this.joining?.reject(new DOMException("released","AbortError")),this.joining=null,this.follower&&this.leave(this.follower),this.resign();let e=this.presence;this.presence=null,e?.(),this.channel&&(this.channel.onmessage=null,this.channel.close(),this.channel=null)}received(e){if(!e)return;let t=this.hub,i=this.follower;switch(e.k){case"join":{if(!t&&e.needsLeader===!0&&this.role.lead!==!1&&!this.leading&&!i&&!this.joining&&this.hold(`${this.base}/leader`,!0).then(l=>{l&&(l(),this.role.wanted?.())},()=>{}),!t||t.followers.has(e.tab)||e.tab===this.tab)return;let o=crypto.randomUUID(),s=new MessageChannel,r=e.tab,a=new cy((l,p)=>this.post({k:"m",tab:r,up:!1,s:l,d:p}),!1);a.bridge(s.port1,0);let c=new AbortController;t.followers.set(r,{binding:o,tunnel:a,watch:c});try{t.worker.attach(s.port2,o)}catch{t.followers.delete(r),a.close();return}this.post({k:"joined",tab:r,binding:o,leader:this.tab}),t.faulted&&this.post({k:"fault",leader:this.tab}),this.hold(`${this.base}/tab/${r}`,!1,c.signal).then(l=>{l?.(),this.drop(t,r)},()=>{});return}case"leave":t&&this.drop(t,e.tab);return;case"joined":if(e.tab===this.tab&&this.joining){let o=this.joining;this.joining=null,o.resolve({binding:e.binding,leader:e.leader})}return;case"leader":this.joining&&this.join();return;case"bye":i&&i.leader===e.leader&&this.departed(i,e.signedOut===!0);return;case"signedOut":i&&i.leader===e.leader&&(i.signedOut=!0);return;case"signedIn":!t&&!i&&!this.joining&&e.leader!==this.tab&&this.signedInElsewhere();return;case"fault":i&&!i.left&&i.leader===e.leader&&i.port.dispatchEvent(new MessageEvent("messageerror"));return;case"m":e.up&&t?t.followers.get(e.tab)?.tunnel.deliver(e.s,e.d):!e.up&&i&&e.tab===this.tab&&i.tunnel.deliver(e.s,e.d);return}}drop(e,t){let i=e.followers.get(t);if(i){e.followers.delete(t),i.watch.abort(),i.tunnel.close();try{e.worker.detach(i.binding)}catch{}}}};function Mr(n){try{return n()}catch{return}}function NU(){let n=Mr(()=>globalThis.crypto?.subtle),e=Mr(()=>globalThis.navigator?.storage),t=Mr(()=>typeof e?.getDirectory=="function"?()=>e.getDirectory.call(e):void 0);return{subtle:n,abortSignalAny:Mr(()=>typeof AbortSignal=="function"&&typeof AbortSignal.any=="function")===!0,randomUUID:Mr(()=>typeof globalThis.crypto?.randomUUID=="function")===!0,worker:Mr(()=>typeof Worker=="function")===!0,messageChannel:Mr(()=>typeof MessageChannel=="function")===!0,locks:Mr(()=>typeof globalThis.navigator?.locks?.request=="function")===!0,broadcastChannel:Mr(()=>typeof BroadcastChannel=="function")===!0,indexedDB:Mr(()=>typeof globalThis.indexedDB<"u")===!0,getDirectory:t}}async function OR(n=NU(),e=!0){let t=[];if(n.subtle||t.push("web_crypto"),n.abortSignalAny||t.push("abort_signal_any"),n.randomUUID||t.push("random_uuid"),e&&!n.worker&&t.push("worker"),n.messageChannel||t.push("message_channel"),n.locks||t.push("web_locks"),n.broadcastChannel||t.push("broadcast_channel"),n.indexedDB||t.push("indexed_db"),n.subtle)try{await n.subtle.generateKey({name:"X25519"},!1,["deriveBits"])}catch{t.push("x25519")}if(t.length)return{ok:!1,problem:"browser_unsupported",missing:Object.freeze(t)};if(typeof n.getDirectory!="function")return{ok:!1,problem:"application_storage_unavailable",missing:Object.freeze(["opfs"])};try{await n.getDirectory()}catch{return{ok:!1,problem:"application_storage_unavailable",missing:Object.freeze(["opfs"])}}return{ok:!0}}function dy(n,e,t={pendingForMs:0,connection:"online"}){if(!Number.isSafeInteger(n)||n<0)throw new RangeError("invalid unsynced count");return n===0?{kind:"no_pending_edits",unsynced:0,warning:null}:{kind:"not_yet_synced",unsynced:n,warning:!e.persistent&&(t.pendingForMs>=3e4||t.connection==="offline")?"storage_may_be_evicted":null}}function ER(n){switch(n){case"pending":return"not_yet_synced";case"confirmed":return"saved";case"rejected":return"rejected";case"unknown":return"outcome_unknown";default:throw new RangeError("invalid receipt state")}}var qR="Some changes are only on this device. Stay online so they can sync.";async function uy(n,e,t=!1){let i=!1;try{i=await n?.persisted()===!0,!i&&t&&(i=await n?.persist?.()===!0)}catch{}return{persistent:i,installed:e}}hy();var jR=Object.freeze(new Set);function UR(n,e){let t=`mdbase.${n}.forgotten-collections.v1.${encodeURIComponent(e)}`,i=()=>{try{return globalThis.localStorage??null}catch{return null}},o=null,s=()=>{let a=null;try{a=i()?.getItem(t)??null}catch{}if(o&&o.raw===a)return o;let c=null,l=jR;try{let p=a?JSON.parse(a):null;p?.v===1&&typeof p.account=="string"&&p.account.length<=64&&Array.isArray(p.ids)&&p.ids.length<=1024&&p.ids.every(d=>typeof d=="string"&&d.length>0&&d.length<=64)&&(c=p.account,l=Object.freeze(new Set(p.ids)))}catch{}return o={raw:a,account:c,ids:l},o},r=(a,c)=>{try{c.size?i()?.setItem(t,JSON.stringify({v:1,account:a,ids:[...c].slice(-1024)})):i()?.removeItem(t)}catch{}o=null};return Object.freeze({read(a){let c=s();return a&&c.account===a?c.ids:jR},add(a,c){let l=s(),p=new Set(l.account===a?l.ids:[]);p.has(c)||(p.add(c),r(a,p))},remove(a,c){let l=s();if(l.account!==a||!l.ids.has(c))return!1;let p=new Set(l.ids);return p.delete(c),r(a,p),!0},clear(){try{i()?.removeItem(t)}catch{}o=null}})}var KU=new Set(["owner","editor","viewer"]),ls=(n,e=512)=>typeof n=="string"&&n.length>0&&n.length<=e,WU=new Set(["unselected","opening","setup_required","ready"]);function NR(n){let e=n;return!e||typeof e!="object"||!ls(e.collectionId,64)||typeof e.displayName!="string"||e.displayName.length>512||!KU.has(e.role)?null:Object.freeze({collectionId:e.collectionId,displayName:e.displayName,role:e.role})}function DR(n){let e=n;return!e||typeof e!="object"||e.state!=="paired"||!ls(e.requestId,64)||!ls(e.installationId,64)||!ls(e.deviceId,64)||!ls(e.appId,64)||e.kind!=="app-runtime"&&e.kind!=="mobile"||!ls(e.verificationUri,2048)||!ls(e.accountId,64)||!Array.isArray(e.collectionIds)||e.collectionIds.length>1024||!e.collectionIds.every(t=>ls(t,64))?null:Object.freeze({requestId:e.requestId,installationId:e.installationId,deviceId:e.deviceId,appId:e.appId,kind:e.kind,verificationUri:e.verificationUri,state:"paired",accountId:e.accountId,...typeof e.accountEmail=="string"&&e.accountEmail.length<=320?{accountEmail:e.accountEmail}:{},collectionIds:Object.freeze([...e.collectionIds]),createCollections:e.createCollections===!0,requestedCreateCollections:e.requestedCreateCollections===!0})}function zR(n,e){let t=`mdbase.${n}.session-hint.v1.${encodeURIComponent(e)}`,i=null,o=null,s=()=>{try{return globalThis.localStorage??null}catch{return null}},r=()=>{let c=null;try{c=s()?.getItem(t)??null}catch{return null}if(i&&i.raw===c)return i.value;let l=null;try{let p=c?JSON.parse(c):null,d=p?.v===1?DR(p.signIn):null,u=Array.isArray(p?.collections)&&p.collections.length<=1024?p.collections.map(NR):null;d&&u&&u.every(f=>f!==null)&&(l=Object.freeze({signIn:d,collections:Object.freeze(u)}))}catch{l=null}return i={raw:c,value:l},l},a=()=>{o=null;try{s()?.removeItem(t)}catch{}};return Object.freeze({read:r,clear:a,observe(c){if(c.status==="signed_out"&&c.signIn===null){o!==""&&(a(),o="");return}if(!WU.has(c.status)||c.signIn?.state!=="paired")return;let l=DR(c.signIn),p=c.collections.map(NR);if(!l||!p.every(u=>u!==null))return;let d=JSON.stringify({v:1,signIn:l,collections:p});if(d!==o){o=d;try{s()?.setItem(t,d)}catch{}}}})}tA();re();ym();Jt();rp();un();function m8(n,e){return new Promise((t,i)=>{let o=()=>{clearTimeout(s),i(A("cancelled","The original collection closed."))};if(n.aborted){i(A("cancelled","The original collection closed."));return}let s=setTimeout(()=>{n.removeEventListener("abort",o),t()},e);n.addEventListener("abort",o,{once:!0})})}var y8=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,mc=Object.freeze({checking:!1,assessment:null,problem:null}),g8=Object.freeze({capabilities:mc,contracts:mc,configuration:mc,files:mc,people:mc,notifications:mc}),$r=(n,e)=>{let t=e?Object.freeze({status:e,problem:e==="incompatible"?Object.freeze({code:"incompatible"}):null}):null;return Object.freeze({checking:n,assessment:t,problem:null,facets:Object.freeze({...g8,configuration:Object.freeze({checking:n,assessment:t,problem:null})})})},Vy=n=>n==="approval_required"?"device_approval_required":n,b8=n=>n.state==="opening"||n.state==="unavailable"&&n.reason!=="sync_required"&&n.reason!=="access_removed"&&n.reason!=="collection_deleted",FA=n=>{if(J(n)){let e=de(n.details,"availability");return typeof e=="string"?Vy(e):n.reason??n.code}return"open_failed"},KA=n=>{if(!J(n))return;let e=$R(n.details);return Object.freeze({name:"MdbaseError",code:n.code,...e?{relay:e}:{}})};function w8(n){let e=n.manifest?.redirect_uris,t=Array.isArray(e)?e.filter(i=>typeof i=="string"):[];if(n.origin.startsWith("capacitor://")){let i=t.find(o=>jl(o,n.origin,n.manifest));if(!i)throw A("invalid_request","Declare an iOS Private collection callback in redirect_uris","redirect_uri");return i}return t.find(i=>{try{return dt(new URL(i))===n.origin}catch{return!1}})??new URL("/",n.origin).href}function mE(n,e,t){if(n.signIn?.state!=="paired"||!e.length&&!t)return n;let i=new Set(n.collections.map(c=>c.collectionId)),o=e.filter(c=>!i.has(c.collectionId)),s=o.length?Object.freeze([...n.collections,...o]):n.collections;if(!t||n.status!=="unselected"||i.has(t.collectionId))return s===n.collections?n:Object.freeze({...n,collections:s});let{problemDetail:r,...a}=n;return Object.freeze({...a,collections:s,status:t.status,selectedCollectionId:t.collectionId,problem:t.problem,transport:null,live:null,...t.problemDetail?{problemDetail:t.problemDetail}:{},..."readiness"in n?{readiness:t.readiness}:{}})}var Fy=class{options;loading=null;list=Object.freeze([]);open=null;listed=null;failedListing=null;refreshing=null;closed=!1;bindings=null;bindingsAccount=null;native=null;revision=0;constructor(e){this.options=e}grants(){let e=this.loading??=(this.options.grants??(async()=>{let{MdbaseAppGrants:t}=await Promise.resolve().then(()=>(hE(),fE));return new t({declaration:this.options.declaration,redirectUri:this.options.grantRedirectUri??w8(this.options.declaration)})}))();return e.catch(()=>{this.loading===e&&(this.loading=null)}),e}changed(){if(!this.closed){this.revision++;try{this.options.onChange()}catch{}}}bind(e,t){let i=t.filter(r=>r.account_id===e);if(this.bindingsAccount===e&&JSON.stringify(i)===JSON.stringify(this.bindings))return;let o=this.bindings;this.bindingsAccount=e,this.bindings=Object.freeze([...i]),this.failedListing=null,this.listed=null;let s=this.open;if(s){let r=o?.find(c=>c.collection_id===s.id),a=i.find(c=>c.collection_id===s.id);!a||e!==s.scope.account?this.close(!1):(a.grant_id!==r?.grant_id||a.client_noise_public_key!==r?.client_noise_public_key)&&this.openCollection(s.id,s.scope).catch(()=>{})}this.setList([])}async nativeAuthorization(e,t,i){if(e.action==="cancel")return this.native?.life.abort(),this.native?.prepared?.cancel(),this.native=null,null;if(this.closed||i.aborted)throw A("cancelled","Original Native authorization fenced");if(e.action==="prepare"){if(this.native||e.value.authorizationId)throw A("unauthenticated","Original Native preparation unavailable");let a={context:e.value,portal:t,prepared:null,life:new AbortController};this.native=a;let c=AbortSignal.any([i,a.life.signal]),l=await this.grants();if(!l.prepareAuthorization)throw A("unavailable","Native authorization unavailable");let p=btoa(String.fromCharCode(...Uint8Array.from(e.value.challenge.match(/../g),u=>parseInt(u,16)))).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,""),d=await l.prepareAuthorization({authorizationNonce:p,expectedAccountId:e.value.accountId,signal:c});if(a.prepared=d,this.native!==a||c.aborted||d.applicationId!==e.value.appId)throw d.cancel(),A("unauthenticated","Original application registration mismatch");return Object.freeze({authorizationId:d.authorizationId,applicationId:d.applicationId,manifestDigest:d.manifestDigest})}let o=this.native,s=o?.prepared;if(!o||!s||o.portal!==t||o.context.requestId!==e.value.requestId||s.authorizationId!==e.value.authorizationRequestId)throw A("unauthenticated","Original Native preparation unavailable");let r=await s.finish({popup:t,collection:e.value.collectionId,signal:AbortSignal.any([i,o.life.signal])});if(this.native!==o||i.aborted||!r.nativeCompletion)throw A("unauthenticated","Original Native completion unavailable");return r.nativeCompletion}entries(){return this.list}has(e){return this.list.some(t=>t.collectionId===e)||this.open?.id===e}state(){return this.open?.state??null}connection(e){let t=this.open;return t&&t.id===e&&t.state.status==="ready"?t.connection:null}listing(e){return this.closed||e===null?!1:this.failedListing===e?"unavailable":this.listed!==e}ensure(e){this.listing(e)===!0&&!this.refreshing&&this.refresh(e).catch(()=>{})}refresh(e=this.bindings===null?this.listed:this.bindingsAccount){if(this.closed)return Promise.resolve();if(this.refreshing)return this.refreshing;let t=this.bindings,i=()=>!this.closed&&t===this.bindings,o=(async()=>{try{let s=await this.grants(),r=[];if(t)for(let p of t)p.account_id===e&&await s.verifiedStoredNativeGrant?.(p)&&r.push(p);let a=await s.collections(t===null?{}:{bindings:r});if(!i())return;let c=this.listing(e)!==!1;this.listed=e,this.failedListing=null;let l=this.revision;this.setList(a),c&&l===this.revision&&this.changed()}catch(s){throw i()&&e!==null&&this.failedListing!==e&&(this.failedListing=e,this.changed()),s}})().finally(()=>{this.refreshing===o&&(this.refreshing=null,!i()&&this.bindingsAccount!==null&&this.ensure(this.bindingsAccount))});return this.refreshing=o,o}setList(e){let t=Object.freeze(e.filter(i=>y8.test(i.collectionId)).map(i=>Object.freeze({collectionId:i.collectionId,displayName:i.displayName,...i.fileActions?{fileActions:i.fileActions}:{},role:i.role??"editor",availability:i.availability,kind:"private"})));JSON.stringify(t)!==JSON.stringify(this.list)&&(this.list=t,this.changed())}setAvailability(e,t){this.list.some(i=>i.collectionId===e&&JSON.stringify(i.availability)!==JSON.stringify(t))&&(this.list=Object.freeze(this.list.map(i=>i.collectionId===e?Object.freeze({...i,availability:t}):i)),this.changed())}set(e,t){if(this.open!==e||e.life.signal.aborted)return;let{problemDetail:i,...o}=e.state,{problemDetail:s,...r}=t,a=r.problem===null?void 0:s??(r.problem===void 0?i:void 0);e.state=Object.freeze({...o,...r,...a?{problemDetail:a}:{}}),this.changed()}async openCollection(e,t){if(this.closed)throw A("cancelled","Private collections closed","application_entry_fenced");this.close(!1);let i={id:e,scope:t,life:new AbortController,client:null,setup:null,connection:null,stopLink:null,state:Object.freeze({collectionId:e,status:"opening",problem:null,readiness:$r(!0,null)})};this.open=i,this.changed();let o=i.life.signal;try{let s=await this.grants(),r=this.bindings?.find(d=>d.account_id===t.account&&d.collection_id===e),a=async()=>{if(this.bindings!==null&&(!r||this.bindingsAccount!==t.account||!this.bindings.includes(r)||!await s.verifiedStoredNativeGrant?.(r)))throw A("unauthenticated","Original account-bound Native grant unavailable");if(o.aborted)throw A("cancelled","Original Native open fenced")};await a();let c=await s.availability(e,{signal:o});if(this.setAvailability(e,c),b8(c)&&(c.state==="unavailable"&&this.set(i,{status:"blocked",problem:Vy(c.reason),readiness:$r(!1,null)}),c=await s.waitForAvailable(e,{signal:o,timeoutMs:this.options.waitMs??10*6e4,onAvailability:d=>{this.setAvailability(e,d),d.state==="unavailable"?this.set(i,{status:"blocked",problem:Vy(d.reason)}):this.set(i,{status:"opening",problem:null,readiness:$r(!0,null)})}})),c.state!=="available"){if(c.state==="opening")throw A("unavailable","The collection is still getting ready","collection_unavailable");this.set(i,{status:"blocked",problem:Vy(c.reason),readiness:$r(!1,null)});return}this.set(i,{status:"opening",problem:null}),await a();let l=await(this.options.connect??v8(this.options.declaration))(s,e,o,d=>{this.open===i&&!o.aborted&&(d.reason==="not_served"||d.reason==="device_not_serving"||d.reason==="no_device_online")&&this.set(i,{status:"blocked",problem:FA(d),problemDetail:KA(d),readiness:$r(!1,null)})});if(this.open!==i||o.aborted||l.collection!==e){if(l.close(),this.open===i&&!o.aborted)throw A("invalid_request","a different collection opened","collection_mismatch");return}i.client=l,i.state.status==="blocked"&&this.set(i,{status:"opening",problem:null,readiness:$r(!0,null)}),i.setup=s.setup(l),i.connection=Object.freeze({id:e,displayName:this.list.find(d=>d.collectionId===e)?.displayName??"Collection",scope:Object.freeze({account:t.account,installation:t.installation,collection:e}),generation:crypto.randomUUID(),records:l,files:l.files,people:s.people(e,l),isCurrent:()=>this.open===i&&!o.aborted&&!this.closed}),fr("mdbase:open:stage:checking_setup"),await this.assessOpen(i);let p=0;i.stopLink=l.onLink((d,u)=>{u?this.set(i,{problem:FA(u),problemDetail:KA(u)}):d==="open"&&this.set(i,{problem:null});let f=++p;s.availability(e,{signal:o}).then(h=>{this.open===i&&!o.aborted&&f===p&&this.setAvailability(e,h)}).catch(()=>{})})}catch(s){throw this.open===i&&!o.aborted&&this.set(i,{status:"blocked",problem:FA(s),problemDetail:KA(s),readiness:$r(!1,null)}),s}}async assessOpen(e){this.set(e,{readiness:$r(!0,e.state.readiness.assessment?.status??null)});let t=1e3;for(;;){if(this.open!==e||e.life.signal.aborted)throw A("cancelled","The original collection closed.");let i;try{i=await e.setup.assess({signal:e.life.signal})}catch(o){if(!J(o)||o.code!=="rate_limited")throw o;let s=o.retryAfterMs;await m8(e.life.signal,Math.min(2147483647,Math.max(t,typeof s=="number"&&Number.isFinite(s)?s:0))),t=Math.min(3e4,t*2);continue}if(this.open!==e||e.life.signal.aborted)throw A("cancelled","The original collection closed.");return this.set(e,{status:i==="ready"?"ready":"setup_required",problem:null,readiness:$r(!1,i)}),i}}current(){let e=this.open;if(!e?.setup||e.life.signal.aborted)throw A("invalid_request","No Private collection is open","application_connection_fenced");return e}isOpen(){return this.open!==null}async assess(){let e=this.current();return await this.assessOpen(e),e.state.readiness}plan(e){return this.current().setup.plan(e)}async apply(e,t={}){let i=this.current(),o=await i.setup.apply(e,t);this.set(i,{status:o==="ready"?"ready":"setup_required",problem:null,readiness:$r(!1,o)})}async configure(e={}){let i=await this.current().setup.plan(e.signal?{signal:e.signal}:{});await this.apply(i,e)}async add(e,t,i){let o;try{o=await this.grants()}catch(r){throw e.close(),r}let s=await o.authorize({popup:e,...t?{collection:t}:{},...i?{signal:i}:{}});return await this.refresh().catch(()=>{}),s.collectionId}async forget(e){this.open?.id===e&&this.close();let t=await this.grants(),i=this.bindings?.find(o=>o.collection_id===e&&o.account_id===this.bindingsAccount);(this.bindings===null||i&&await t.verifiedStoredNativeGrant?.(i))&&await(i?t.forget(e,{expectedNoisePublicKey:i.client_noise_public_key}):t.forget(e)),this.list.some(o=>o.collectionId===e)&&(this.list=Object.freeze(this.list.filter(o=>o.collectionId!==e)),this.changed())}async forgetAll(){this.native?.life.abort(),this.native?.prepared?.cancel(),this.native=null,this.close();try{await(await this.grants()).forgetAllGrants()}finally{this.list=Object.freeze([]),this.listed=null,this.failedListing=null,this.changed()}}close(e=!0){let t=this.open;if(t){this.open=null,t.life.abort(),t.stopLink?.();try{t.client?.close()}catch{}e&&this.changed()}}dispose(){this.native?.life.abort(),this.native?.prepared?.cancel(),this.native=null,this.close(!1),this.closed=!0}};function v8(n){return async(e,t,i,o)=>{let{connect:s}=await Promise.resolve().then(()=>(Ls(),zf));return s({connector:e.connector(t),app:{name:n.id,version:"1"},signal:i,waitForDevice:!0,onWaiting:o})}}var Eg={};function a4(n){let e=globalThis.document;return!e||typeof e.addEventListener!="function"||e.visibilityState!=="hidden"?Promise.resolve():new Promise((t,i)=>{let o=()=>{e.visibilityState!=="hidden"&&(e.removeEventListener("visibilitychange",o),n.removeEventListener("abort",s),t())},s=()=>{e.removeEventListener("visibilitychange",o),i(n.reason)};e.addEventListener("visibilitychange",o),n.addEventListener("abort",s,{once:!0})})}var Y2=new WeakMap;function l4(n){let e=n.unsynced;if(!e)return n;let t=Y2.get(n);return t||(t=Object.freeze({...n,status:e.sessionStatus,selectedCollectionId:null,unsynced:null}),Y2.set(n,t)),t}var J0=class extends Error{code="application_not_yet_available";constructor(){super("mdbase cannot run in this context"),this.name="MdbaseApplicationUnavailableError"}},Z0=Object.freeze({code:"application_not_yet_available"}),zc=Object.freeze({checking:!1,assessment:null,problem:Z0}),c4=Object.freeze({checking:!1,assessment:null,problem:Z0,facets:Object.freeze({capabilities:zc,contracts:zc,configuration:zc,files:zc,people:zc,notifications:zc})}),$c=Object.freeze({checking:!1,assessment:null,problem:null}),Og=Object.freeze({checking:!1,assessment:null,problem:null,facets:Object.freeze({capabilities:$c,contracts:$c,configuration:$c,files:$c,people:$c,notifications:$c})}),X0=()=>new J0,J2=Object.freeze({state:"none",problem:null,usable:null,requested:Object.freeze({collectionId:null,source:"none",displayName:null,approved:!1})});function p4(n){let e={status:"blocked",signIn:null,collections:Object.freeze([]),selectedCollectionId:null,problem:Z0.code,timing:null,readiness:c4,selection:J2},t=Object.freeze({...e,phase:Mp(e,n?{messages:n}:{}),sync:null,writes:null,links:null}),i=()=>Promise.reject(X0());return Object.freeze({getSnapshot:()=>t,subscribe:()=>()=>{},start:i,signIn:i,addCollection:i,cancelAuthorization:i,select:i,approve:i,reauthorize:i,refreshCollectionList:i,requestAccess:i,chooseAnother:i,assess:i,configure:i,setup:Object.freeze({plan:i,apply:i}),forget:i,deleteCollection:i,unlock:i,connection:()=>null,setForeground(){throw X0()},close:i,signOut:i,unsynced:Object.freeze({open:i,planTransfer:i,transfer:i,discard:i})})}var d4=n=>typeof n=="object"&&n!==null&&["postMessage","terminate","addEventListener","removeEventListener"].every(e=>typeof n[e]=="function"),u4=(n,e)=>(!e||typeof Worker=="function")&&typeof MessageChannel=="function"&&Et()!==null&&ut(n);function f4(n){if(n===void 0)return{build:null,host:!0};if(!n||typeof n!="object"||typeof n.build!="string"||!n.build||n.build.length>128||/[\u0000-\u001f\u007f]/.test(n.build))throw new TypeError("session.build must be a short non-empty string");if(n.host!==void 0&&typeof n.host!="boolean")throw new TypeError("session.host must be a boolean");return{build:n.build,host:n.host!==!1}}function h4(n,e){if(n===void 0)return null;let t=()=>{throw A("invalid_request","Invalid sign-in opener","application_sign_in_opener")};if(!n||typeof n!="object"||typeof n.open!="function"||n.close!==void 0&&typeof n.close!="function")return t();let i=n.returnUrl,o=n.grantReturnUrl;i!==void 0&&(mm(i,e.manifest)||t()),o!==void 0&&!jl(o,e.origin,e.manifest)&&(!mm(o,e.manifest)||new URL(o).origin!==e.origin)&&t();let s=n.open.bind(n),r=n.close?.bind(n);return Object.freeze({open:s,...r?{close:r}:{},...i!==void 0?{returnUrl:i}:{},...o!==void 0?{grantReturnUrl:o}:{}})}async function m4(n){let e=!0;if(n.webPush){let t=globalThis.navigator?.serviceWorker,i;t&&typeof t.getRegistration=="function"&&(e=await Promise.race([(async()=>{let o=await(await t.getRegistration())?.pushManager?.getSubscription();return o?await o.unsubscribe():!0})().catch(()=>!1),new Promise(o=>{i=setTimeout(()=>o(!1),5e3)})]).finally(()=>clearTimeout(i)))}try{n.server==="incomplete"&&console.warn("mdbase: signed out on this device. This installation may still have collection access. Remove it under Apps in your mdbase account."),(n.local==="incomplete"||!e)&&console.warn("mdbase: signed out, but some local data on this device could not be removed.")}catch{}}function y4(n){let e=`mdbase.${n}.selected-collection.v1`;return Object.freeze({read:()=>{try{return globalThis.localStorage?.getItem(e)??null}catch{return null}},write:t=>{try{t===null?globalThis.localStorage?.removeItem(e):globalThis.localStorage?.setItem(e,t)}catch{}}})}var qg=class{mdbase;declaration;compiled;lifetime=new AbortController;listeners=new Set;nativeListeners=new Set;selection=null;memory=null;runtime=null;initialization=null;closing=null;closed=!1;foreground=!0;incarnation=0;hidden=null;tabs=null;election=null;signingOut=!1;snapshot=Object.freeze({status:"not_started",signIn:null,collections:Object.freeze([]),selectedCollectionId:null,problem:null,timing:null,readiness:Og});composed=null;hint=null;forgotten=null;handledApproval=null;refreshing=null;refreshedAt=0;approvalPortal=null;revision=0;links=null;cpOrigin=null;messages;opening=null;syncing=null;storagePolicy=null;pendingSave=null;signIn;typeIssues;createWorker;session;privates=null;unsyncedFirst;unsyncedTried=!1;unsyncedOpening=0;timing=new km;overlaid=new WeakMap;constructor(e,t={}){this.declaration=co(e),this.compiled=is(this.declaration);let i=t.readiness?.typeIssues??"block";if(i!=="block"&&i!=="degrade")throw new TypeError('readiness.typeIssues must be "block" or "degrade"');if(this.typeIssues=i,this.unsyncedFirst=t.unsynced===!0,t.urlSelection!==void 0&&typeof t.urlSelection!="boolean")throw new TypeError("urlSelection must be a boolean");if(t.worker!==void 0&&typeof t.worker!="function")throw new TypeError("worker must be a function");if(this.createWorker=t.worker??null,this.messages=t.messages,this.session=f4(t.session),!this.session.host&&this.createWorker)throw new TypeError("worker has no effect with session.host: false");if(this.signIn=h4(t.signIn,this.declaration),!u4(this.declaration.origin,this.session.host)){this.mdbase=p4(t.messages);return}try{let s=this.environment().cpOrigin;this.cpOrigin=s,this.hint=zR(this.declaration.storage.applicationNamespace,s),this.forgotten=UR(this.declaration.storage.applicationNamespace,s),this.links=Object.freeze({account:`${s}/account`,manageAccess:`${s}/account/applications`})}catch{}t.followVisibility!==!1&&this.followVisibility(),this.followPageLifecycle(),this.followFocus(),this.followStoragePolicy(),this.followNetwork(),this.memory=y4(this.declaration.storage.applicationNamespace),t.privateCollections!==!1&&(this.privates=new Fy({declaration:this.declaration,...this.signIn?.grantReturnUrl?{grantRedirectUri:this.signIn.grantReturnUrl}:{},onChange:()=>{this.revision++,this.notify()}})),this.selection=new Pm({browser:new Sm(this.declaration.origin,{},t.urlSelection===!1?null:i1()),session:this.selectionSession(),memory:this.memory}),this.selection.subscribe(()=>{this.unforgetApproved(),this.notify(!1)});let o=()=>this.getSnapshot();this.mdbase=Object.freeze({getSnapshot:o,subscribe:s=>(this.listeners.add(s),()=>{this.listeners.delete(s)}),start:s=>this.track(()=>{let r=this.unsyncedFirst&&(!this.unsyncedTried||this.runtime===null);return r&&(this.unsyncedOpening++,this.revision++,this.notify(!1)),this.call(async a=>{let c=this.account();this.privates?.listing(c)==="unavailable"&&await this.privates.refresh(c).catch(()=>{});let l=a.getNativeSnapshot();l.status==="blocked"&&l.signIn&&l.selectedCollectionId===null?await a.queue(()=>a.start(s)):await this.timing.time("session",()=>this.started(a,s));let p=this.choose(),d=p.getSnapshot();d.state==="blocked"&&d.requested.approved&&d.requested.collectionId!==null&&await p.select(d.requested.collectionId,s);let u=a.getNativeSnapshot();this.unsyncedFirst&&!this.unsyncedTried&&u.status==="signed_out"&&!u.unsynced&&!u.signOutResult&&p.getSnapshot().requested.collectionId===null&&(this.unsyncedTried=!0,await this.timing.time("unsynced",()=>a.queue(()=>a.openUnsynced(s))))}).catch(a=>{let c=this.runtime?.getNativeSnapshot();if(!(a?.code==="open_in_another_tab"&&c?.status==="blocked"&&c.problem==="open_in_another_tab"))throw a}).finally(()=>{r&&(this.unsyncedOpening--,this.revision++,this.notify(!1))})}),signIn:s=>this.track(()=>this.approve(void 0,s)),approve:(s,r)=>this.track(()=>this.approve(s,r)),reauthorize:s=>this.track(()=>{let r=this.choose(),a=r.getSnapshot(),c=this.privates?.state()?.collectionId??a.usable?.collectionId??a.requested.collectionId;return c?this.approve(c,s):r.reauthorize(s)}),addCollection:s=>this.track(()=>this.approve(null,s)),cancelAuthorization:s=>this.track(()=>this.call(async r=>{await r.queue(()=>r.cancelAuthorization(s));let a=r.getNativeSnapshot();this.unsyncedFirst&&a.status==="signed_out"&&!a.unsynced&&this.choose().getSnapshot().requested.collectionId===null&&await r.queue(()=>r.openUnsynced(s))})),refreshCollectionList:s=>this.track(()=>Promise.all([this.call(r=>r.queue(()=>r.refreshCollections(s))),this.privates?.refresh(this.account()).catch(()=>{})])),requestAccess:(s,r)=>this.requestAccess(s,r),select:(s,r)=>this.track(()=>this.choose().select(s,{...r,history:"push"})),chooseAnother:s=>this.track(()=>this.choose().chooseAnother(s)),forget:(s,r)=>this.track(async()=>{let a=this.choose(),c=this.account();if(this.privates?.has(s)){await this.privates.forget(s),a.getSnapshot().requested.collectionId===s&&await a.select(null,r);return}if(c&&this.forgotten){this.forgotten.add(c,s),this.revision++,(a.getSnapshot().requested.collectionId===s||(this.runtime?.getSnapshot()??this.snapshot).selectedCollectionId===s)&&await a.select(null,r),this.notify(!1);return}await this.call(l=>l.queue(()=>l.forget(s,r))),a.getSnapshot().requested.collectionId===s&&await a.select(null,r)}),deleteCollection:(s,r)=>this.track(async()=>{let a=this.choose(),{confirmName:c,...l}=r??{};await this.call(p=>p.queue(()=>p.deleteCollection(s,c,l))),a.getSnapshot().requested.collectionId===s&&await a.select(null,l)}),unlock:(s,r,a)=>this.track(()=>this.call(c=>c.queue(()=>c.unlock(s,r,a)))),assess:s=>this.privates?.isOpen()?this.privates.assess():this.call(r=>r.queue(()=>r.assess(s))),configure:s=>this.track(()=>this.privates?.isOpen()?this.privates.configure(s):this.call(r=>r.queue(()=>r.configure(s)))),setup:Object.freeze({plan:s=>(this.privates?.isOpen()?this.privates.plan(s):this.call(r=>r.queue(()=>r.planSetup(s)))).then(r=>LR(r,this.getSnapshot().readiness)),apply:(s,r)=>MR(this.track(()=>this.privates?.isOpen()?this.privates.apply(s,r):this.call(a=>a.queue(()=>a.applySetup(s,r)))),o)}),connection:s=>this.connection(s),setForeground:s=>this.setForeground(s),close:()=>this.close(),signOut:s=>this.signOut(s),unsynced:Object.freeze({planTransfer:(s={})=>this.call(r=>{let a=this.transferDestination(null);return r.withUnsyncedSource((c,l)=>W_(c.records,a.records,{...s.map?{map:s.map}:{},...s.addTypes?{addTypes:!0}:{},ledger:this.transferLedger(),signal:l}),s)}),transfer:(s,r={})=>this.call(async a=>{let c=this.transferDestination(s?.destination??null),l=await kR(s,c.records,{...r.signal?{signal:r.signal}:{},...r.onProgress?{onProgress:r.onProgress}:{}});if(l.failed.length||l.failedTypes.length)return l;let p=r.signal?{signal:r.signal}:{};return await a.withUnsyncedSource((d,u)=>AR(s,d.records,c.records,u),p)?Object.freeze({...l,retired:await a.retireUnsynced(s.source,s.destination,p)}):l}),discard:s=>this.track(async()=>{await this.call(async r=>(await this.started(r,s),r.queue(()=>r.discardUnsynced(s))))}),open:s=>this.track(async()=>{let r=this.choose();this.privates?.close(),r.getSnapshot().requested.collectionId!==null&&await r.select(null,{...s,history:"replace"}),await this.call(async a=>(await this.started(a,s),a.queue(()=>a.openUnsynced(s))))})})})}withPrivate(e){let t=this.privates;if(!t)return e;let i=this.overlaid.get(e);if(i&&i.revision===t.revision)return i.value;let o=mE(e,t.entries(),t.state());return this.overlaid.set(e,{revision:t.revision,value:o}),o}getSnapshot(){let e=this.withPrivate(this.runtime?.getSnapshot()??this.snapshot),t=this.selection?.getSnapshot()??J2,i=this.composed,o=e.signIn===null&&(e.status==="starting"||e.status==="blocked"&&e.problem==="open_in_another_tab")?this.hint?.read()??null:null;if(i&&i.base===e&&i.selection===t&&i.revision===this.revision&&i.hint===o)return i.value;let s=o?Object.freeze({...e,signIn:o.signIn,collections:o.collections}):e,r=this.forgotten?.read(s.signIn?.accountId)??null,a=r?.size&&s.collections.some(_=>r.has(_.collectionId)&&_.collectionId!==s.selectedCollectionId)?Object.freeze({...s,collections:Object.freeze(s.collections.filter(_=>!r.has(_.collectionId)||_.collectionId===s.selectedCollectionId))}):s,c=a.selectedCollectionId,l=c&&!this.closed?this.privates?.connection(c)??this.runtime?.connection(c)??null:null,p=this.unsyncedOpening>0&&!a.unsynced&&!a.signOutResult&&t.requested.collectionId===null,d=Mp({...a,selection:t},{connection:l,previous:i?.value.phase??null,openingUnsynced:p,startPending:this.selection?.startPending()??!1,...this.cpOrigin?{cpOrigin:this.cpOrigin}:{},...this.messages?{messages:this.messages}:{}});d=this.trackOpening(d),this.timing.observe(d),t1(t,d,i?.value);let u=a.transport??null,f=globalThis.navigator?.onLine,h=this.trackSync(d,u!==null||f===!1),m=this.syncing?.writes()??null,w=this.trackPending(Math.max(h?.pending??0,m?.pending.length??0)),b=h&&w!==null?dy(h.pending,this.storagePolicy??{persistent:!1,installed:!1},{pendingForMs:w,connection:h.connection}).warning:null,g=this.syncing?.link(),y=h?Object.freeze($f({status:h,writes:m,problem:a.problem,transport:u,live:a.live??null,storageWarning:b!==null,...g===void 0?{}:{link:g},...typeof f=="boolean"?{online:f}:{},...w===null?{}:{pendingForMs:w}})):null,v=Object.freeze({...a,selection:t,phase:d,sync:y,storage:this.storagePolicy,saveWarning:b,links:this.linksFor(c)});return this.composed={base:e,selection:t,revision:this.revision,hint:o,value:v},v}linksFor(e){return this.links&&e?Object.freeze({...this.links,manageAccess:`${this.cpOrigin}/access?collection=${encodeURIComponent(e)}`}):this.links}trackPending(e){let t=this.syncing;if(this.pendingSave&&(this.closed||this.hidden||!e||this.pendingSave.id!==t?.id)&&this.clearPendingSave(),this.closed||this.hidden||!t||!e)return null;if(!this.pendingSave){let i={id:t.id,since:performance.now(),timer:null},o=s=>()=>{this.pendingSave===i&&(i.timer=s===null?null:setTimeout(o(null),s),this.revision++,this.notify(!1))};i.timer=setTimeout(o(28e3),2e3),this.pendingSave=i}return performance.now()-this.pendingSave.since}clearPendingSave(){this.pendingSave?.timer!==null&&this.pendingSave?.timer!==void 0&&clearTimeout(this.pendingSave.timer),this.pendingSave=null}trackOpening(e){let t=e.kind==="opening"?e.collectionId:null;if(this.opening&&this.opening.id!==t&&(clearTimeout(this.opening.timer),this.opening=null),t===null||this.closed)return e;if(!this.opening){let i={id:t,slow:!1,timer:setTimeout(()=>{this.opening===i&&(i.slow=!0,this.revision++,this.notify(!1))},ih)};this.opening=i}return e.kind==="opening"&&this.opening.slow?{...e,slow:!0}:e}trackSync(e,t){let i=e.kind==="ready"?e.collectionId:null;if(this.syncing&&this.syncing.id!==i){try{this.syncing.stop()}catch{}this.syncing=null}if(e.kind!=="ready"||this.closed)return null;if(!this.syncing){let o=e.connection.records,s=null;try{s=o.status}catch{}let r={id:e.collectionId,stop:()=>{},status:s,writes:()=>null,link:()=>{}},a=()=>{this.syncing===r&&(this.revision++,this.getSnapshot(),this.notify(!1))},c=()=>{},l=()=>{},p=()=>{};try{c=o.onStatus(d=>{r.status=d,a()})}catch{}try{let d=o.ledger;l=d.subscribe(a),r.writes=()=>{try{return d.getSnapshot()}catch{return null}}}catch{}try{p=o.onLink(a),r.link=()=>{try{return o.link}catch{return}}}catch{}r.stop=()=>{c(),l(),p()},this.syncing=r}try{e.connection.records.setTransportDeferred(t)}catch{}return this.syncing.status}nativeAuthorization(e,t,i){return!this.privates||this.closed||this.hidden?Promise.reject(A("unavailable","Native authorization unavailable")):this.privates.nativeAuthorization(e,t,AbortSignal.any([i,this.lifetime.signal]))}account(){return(this.runtime?.getSnapshot()??this.snapshot).signIn?.accountId??null}unforgetApproved(){let e=this.selection?.getSnapshot().lastApproval??null,t=this.account();!e||e===this.handledApproval||(this.handledApproval=e,t&&e.collectionId&&(e.outcome==="added"||e.outcome==="unchanged")&&this.forgotten?.remove(t,e.collectionId)&&this.revision++)}followFocus(){let e=typeof window>"u"?void 0:window,t=globalThis.document;if(!e||typeof e.addEventListener!="function")return;let i=()=>{t?.visibilityState!=="hidden"&&this.refreshCollections()};e.addEventListener("focus",i,{signal:this.lifetime.signal}),t&&typeof t.addEventListener=="function"&&t.addEventListener("visibilitychange",i,{signal:this.lifetime.signal})}refreshCollections(){let e=this.runtime,t=Date.now();if(!e||this.closed||this.hidden||this.refreshing||t-this.refreshedAt<2e3)return;let i=e.getNativeSnapshot();i.signIn?.state!=="paired"||i.status!=="unselected"&&i.status!=="ready"&&i.status!=="setup_required"||(this.refreshedAt=t,this.privates?.refresh(i.signIn.accountId).catch(()=>{}),this.refreshing=e.queue(()=>e.refreshCollections()).catch(()=>{}).finally(()=>{this.refreshing=null}))}followStoragePolicy(){let e=globalThis.navigator?.storage;if(!e||typeof e.persisted!="function")return;let t=()=>{try{return globalThis.matchMedia?.("(display-mode: standalone)").matches===!0||globalThis.navigator?.standalone===!0}catch{return!1}},i=(s=!1)=>{this.closed||uy(e,t(),s).then(r=>{this.closed||this.storagePolicy?.persistent===r.persistent&&this.storagePolicy?.installed===r.installed||(this.storagePolicy=r,this.revision++,this.notify(!1))}).catch(()=>{})},o=globalThis.document;o&&typeof o.addEventListener=="function"&&o.addEventListener("visibilitychange",()=>{o.visibilityState!=="hidden"&&i()},{signal:this.lifetime.signal}),i(!0)}notify(e=!0){let t=this.runtime?.getSnapshot(),i=t?.signIn?.state==="paired"?t.signIn.accountId:null;if(i&&!this.closed&&!this.hidden&&(this.privates?.bind(i,t?.signIn?.nativeGrants??[]),this.privates?.ensure(i)),e)for(let o of[...this.nativeListeners])try{o()}catch{}for(let o of[...this.listeners])try{o()}catch{}}choose(){this.check();let e=this.selection;return e.start(),e}async track(e){return await e(),this.getSnapshot()}selectionSession(){return Object.freeze({getSnapshot:()=>this.withPrivate(l4(this.runtime?.getNativeSnapshot()??this.snapshot)),subscribe:e=>(this.nativeListeners.add(e),()=>{this.nativeListeners.delete(e)}),open:(e,t={})=>this.call(async i=>{let o=this.privates,s=i.getNativeSnapshot().collections.some(c=>c.collectionId===e);if(!o||s||!o.has(e))return o?.close(),i.queue(()=>i.select(e,t));i.getNativeSnapshot().selectedCollectionId!==null&&await i.queue(()=>i.clearSelection(t));let r=i.getNativeSnapshot().signIn?.accountId,a=i.getNativeSnapshot().signIn?.installationId;if(!r||!a)throw A("unauthenticated","Sign in before opening a collection");o.openCollection(e,{account:r,installation:a}).catch(()=>{})}),clear:(e={})=>(this.privates?.close(),this.call(t=>t.queue(()=>t.clearSelection(e)))),authorize:(e={})=>this.authorize(e,e.collectionHint??null),listing:()=>this.privates?.listing(this.account())??!1})}check(){if(this.closed||this.hidden||this.lifetime.signal.aborted)throw A("cancelled","Application entry fenced","application_entry_fenced")}environment(){return Ci({environment:this.declaration.environment,appOrigin:this.declaration.origin,release:Ks()})}initialize(){if(this.initialization)return this.initialization;let e=this.incarnation,t=Promise.resolve().then(async()=>{if(this.check(),typeof Eg.url!="string")throw X0();let i=new URL(Eg.url);if(dt(i)!==this.declaration.origin||Et()!==this.declaration.origin)throw A("unavailable","Application module binding unavailable","application_worker_module_binding");let o=this.environment(),s=e1(this.declaration.environment,this.declaration.origin),r=await this.timing.time("capabilities",()=>OR(void 0,this.session.host));if(this.check(),!r.ok)throw A("unavailable","This browser can't run mdbase",{reason:r.problem,details:{missing:r.missing.join(",")}});let a=()=>{if(!this.unsyncedFirst)return;let P={origin:this.declaration.origin,environment:this.declaration.environment};for(let I of[s.runtime,s.sqlite])try{QC(I,P)({signal:this.lifetime.signal}).catch(()=>{})}catch{}},c=Promise.resolve().then(()=>(H2(),W2));c.catch(()=>{});let{registered:l,ApplicationRuntime:p}=await this.timing.time("registration",async()=>({registered:await vm({declaration:this.declaration,signal:this.lifetime.signal,isCurrent:()=>!this.closed,onRequest:a}),ApplicationRuntime:(await c).ApplicationRuntime}));if(this.check(),e!==this.incarnation)throw A("cancelled","Application entry fenced","application_entry_fenced");let d=WC(this.declaration,l);l.supersededDeclaredId&&console.info(`mdbase: ${Qf("application_registration_id_superseded")}`);let u=rh(this.declaration),f=Object.freeze({cpOrigin:o.cpOrigin,appId:d.id,...u===null?{}:{storageNamespace:u}}),h=P=>(this.runtime=P,this.unsyncedTried=!1,P.subscribe(()=>{this.hint?.observe(P.getNativeSnapshot()),this.observeSignOut(P),P.getNativeSnapshot().signIn?.state==="paired"&&this.tabs?.signedIn(),this.notify(),this.awaitOtherTab(P,f)}),P.setForeground(this.foreground),this.notify(),P),m=this.tabsFor(f),w=new AbortController;this.election?.abort(),this.election=w;let b=await this.timing.time("election",()=>m.elect(AbortSignal.any([this.lifetime.signal,w.signal])));if(this.closed||this.hidden||e!==this.incarnation||w.signal.aborted)throw b.kind==="follower"?b.leave():m.resign(),A("cancelled","Application entry fenced","application_entry_fenced");if(b.kind==="follower")return h(new p({declaration:d,compiledManifest:this.compiled,typeIssues:this.typeIssues,cpOrigin:o.cpOrigin,port:b.port,binding:b.binding,releaseWorker:()=>b.leave(),nativeAuthorization:(P,I,O)=>this.nativeAuthorization(P,I,O)}));let g=new MessageChannel,y=crypto.randomUUID(),v,_=this.createWorker,k=_?new URL("./worker.js",i).href:null;try{if(!_)v=new Worker(new URL("./worker.js",Eg.url),{type:"module"});else if(v=_(k),!d4(v))throw new TypeError("not a Worker")}catch{throw m.resign(),g.port1.close(),g.port2.close(),A("unavailable","Application Worker construction unavailable","application_worker_unavailable")}let S=P=>{P.preventDefault(),g.port1.dispatchEvent(new MessageEvent("messageerror")),m.fault()};v.addEventListener("error",S);let x=new p({declaration:d,compiledManifest:this.compiled,typeIssues:this.typeIssues,cpOrigin:o.cpOrigin,port:g.port1,binding:y,releaseWorker:()=>{v.removeEventListener("error",S),v.terminate(),m.resign()},nativeAuthorization:(P,I,O)=>this.nativeAuthorization(P,I,O)});try{v.postMessage([di,y,d,...k!==null?[u,k]:u===null?[]:[u]],[g.port2])}catch{throw v.removeEventListener("error",S),v.terminate(),m.resign(),g.port1.close(),g.port2.close(),A("unavailable","Application bootstrap unavailable","application_worker_binding")}return m.lead({attach:(P,I)=>v.postMessage([di,y,"attach",I],[P]),detach:P=>v.postMessage([di,y,"detach",P])}),h(x)}).catch(i=>{let o=this.initialization===t;if(o&&(this.initialization=null),!this.closed&&o){let{problemDetail:s,...r}=this.snapshot,a=i instanceof ne&&i.reason==="application_registration_refused"?js(i.details):null;this.snapshot=Object.freeze({...r,status:"blocked",problem:typeof i?.reason=="string"?i.reason:typeof i?.code=="string"?i.code:"application_entry_unavailable",...a?{problemDetail:Object.freeze({name:"MdbaseError",code:i.code,registration:a})}:{}}),this.notify()}throw i});this.initialization=t;{let{problemDetail:i,signOutResult:o,...s}=this.snapshot;this.snapshot=Object.freeze({...s,status:"starting",problem:null})}return this.notify(),t}async call(e){this.check();let t=await this.initialize();return this.check(),e(t)}started(e,t){this.choose();let i=e.getNativeSnapshot().status;return i==="not_started"||i==="starting"||i==="blocked"&&!e.getNativeSnapshot().signIn?e.queue(()=>e.start(t)):Promise.resolve()}reservePortal(e){this.check();let t=this.environment(),i=e.signal?AbortSignal.any([this.lifetime.signal,e.signal]):this.lifetime.signal,o=Ml(this.declaration.environment),s=()=>!this.closed,r=this.signIn?K1(t.cpOrigin,i,s,this.signIn,o):Fm(t.cpOrigin,i,s,o);return{portal:Vm(r),signal:i}}requestAccess(e,t){try{this.check();let i=this.runtime,o=i?.getNativeSnapshot(),s=this.privates?.state()?.collectionId,r=s??o?.selectedCollectionId??null,a=ay(this.compiled),c=()=>r&&i?ly(i.getNativeSnapshot(),r):[],l=xR(a,e,t,c()),p=r?this.connection(r):null;if(!i||!r||!p)throw A("invalid_request","requestAccess needs an open collection","access_no_collection");if(s){let h=this.privates?.entries().find(w=>w.collectionId===s)?.fileActions??[],m=(p.files.grant?.actions??[]).filter(w=>a?.required.includes(w)||a?.optional.includes(w)&&h.includes(w));return Promise.resolve(e.files.every(w=>m.includes(w))?Object.freeze({status:"granted",actions:Object.freeze(m)}):Object.freeze({status:"unavailable",reason:"private_relay"}))}let d=()=>IR(p.files,a,c());if(!l.length)return Promise.resolve(d());if(o?.unsynced?.collectionId===r)return Promise.resolve(Object.freeze({status:"unavailable",reason:"until_connected"}));let{portal:u,signal:f}=this.reservePortal(t);return CR({granted:d,native:()=>i.getNativeSnapshot(),start:()=>i.queue(()=>i.requestFileAccess(u,r,l,t.reason,{signal:f})),poll:h=>i.queue(()=>i.pollFileAccess(h))},u,f,t.signal??null)}catch(i){return Promise.reject(i)}}approve(e,t={}){let i=this.choose(),o=i.getSnapshot(),s=this.approvalPortal;if(s&&o.approval){if((e===void 0?o.requested.collectionId:e)!==o.approval.collectionId)return Promise.reject(new yn("application_selection_busy"));if(t.signal?.aborted)throw A("cancelled","Application entry fenced","application_entry_fenced");return s.closed||s.focus(),Promise.resolve()}return i.approve(e,t)}authorize(e={},t=null){let i;try{i=this.approvalPortal=this.reservePortal(e).portal}catch(o){return Promise.reject(o)}return this.call(async o=>(await this.started(o,e),o.queue(()=>o.authorizeReserved(i,e,t)))).catch(o=>{try{i.close()}catch{}throw o})}async signOut(e={}){let t=await this.call(async s=>(await this.started(s,e),s));this.signingOut=!0;try{await t.queue(()=>t.signOut(e))}finally{this.signingOut=!1}let i=t.getNativeSnapshot().signOutResult??null;await this.signedOut(t,i);let o=this.snapshot.signOutResult??i;return o&&await m4(o),this.getSnapshot()}async signedOut(e,t,i=!1){i||this.tabs?.signedOut(),this.clearPendingSave(),++this.incarnation,this.runtime===e&&(this.runtime=null),this.initialization=null,this.hint?.clear(),this.forgotten?.clear(),this.handledApproval=null;let o=null;if(this.privates)try{await this.privates.forgetAll(),o="erased"}catch{o="incomplete"}let s=t&&o?Object.freeze({...t,grants:o,...o==="incomplete"?{local:"incomplete"}:{}}):t;this.snapshot=Object.freeze({status:"signed_out",signIn:null,collections:Object.freeze([]),selectedCollectionId:null,problem:!s&&o==="incomplete"?"sign_out_failed":null,timing:null,readiness:Og,...s?{signOutResult:s}:{}});try{this.memory?.write(null)}catch{}if(this.selection&&!this.closed&&(this.selection.resync(),await this.selection.select(null,{history:"replace"}).catch(()=>{})),this.revision++,this.notify(),i){e.abandon();return}await e.close().catch(()=>{})}observeSignOut(e){let t=e.getNativeSnapshot().signOutResult;!t||this.signingOut||this.closed||this.runtime!==e||this.signedOut(e,t)}tabsFor(e){return this.tabs??=new py({...e,build:this.session.build===null?Eg.url:`app-build/${this.session.build}`},{locks:globalThis.navigator.locks,BroadcastChannel:globalThis.BroadcastChannel},this.leaderLost,this.signedInElsewhere,{lead:this.session.host,wanted:this.hostWanted})}leaderLost=e=>{if(this.closed||this.hidden)return;let t=this.runtime,i=t!==null||this.initialization!==null;if(this.election?.abort(),this.election=null,e&&t&&!this.signingOut?this.signedOut(t,t.getNativeSnapshot().signOutResult??null,!0):e&&i&&(++this.incarnation,this.initialization=null),!i||e){this.tabs?.resign();return}++this.incarnation,this.initialization=null,this.runtime=null,t?.abandon();let{problemDetail:o,...s}=this.snapshot;this.snapshot=Object.freeze({...s,status:"starting",problem:null,selectedCollectionId:null,readiness:Og}),this.notify(),this.selection?.resync(),this.mdbase.start().catch(()=>{})};hostWanted=()=>{this.closed||this.hidden||this.signingOut||this.runtime!==null||this.initialization!==null||(this.selection?.resync(),this.mdbase.start().catch(()=>{}))};signedInElsewhere=()=>{this.closed||this.hidden||this.signingOut||this.runtime!==null||this.initialization!==null||this.snapshot.status!=="signed_out"||(this.selection?.resync(),this.mdbase.start().catch(()=>{}))};setForeground(e){this.foreground=e,this.runtime?.setForeground(e)}followVisibility(){let e=globalThis.document;if(!e||typeof e.addEventListener!="function")return;let t=()=>{this.closed||this.setForeground(e.visibilityState!=="hidden")},i=()=>{e.visibilityState!=="hidden"&&t()};e.addEventListener("visibilitychange",t,{signal:this.lifetime.signal});let o=typeof window>"u"?void 0:window;o&&typeof o.addEventListener=="function"&&(o.addEventListener("focus",i,{signal:this.lifetime.signal}),o.addEventListener("online",i,{signal:this.lifetime.signal})),t()}followNetwork(){let e=typeof window>"u"?globalThis:window;if(typeof e.addEventListener!="function")return;let t=()=>{this.closed||(this.revision++,this.notify(!1))};e.addEventListener("online",()=>{let i=this.account();!this.closed&&!this.hidden&&this.privates?.listing(i)==="unavailable"&&this.privates.refresh(i).catch(()=>{}),t()},{signal:this.lifetime.signal}),e.addEventListener("offline",t,{signal:this.lifetime.signal})}followPageLifecycle(){let e=typeof window>"u"?void 0:window;if(!e||typeof e.addEventListener!="function")return;e.addEventListener("pagehide",this.pageHidden,{signal:this.lifetime.signal}),e.addEventListener("pageshow",this.pageShown,{signal:this.lifetime.signal});let t=globalThis.document,i=this.signIn?.returnUrl!==void 0&&!/^https?:/i.test(this.signIn.returnUrl);t&&typeof t.addEventListener=="function"&&!i&&(t.addEventListener("freeze",()=>this.pageHidden(),{signal:this.lifetime.signal}),t.addEventListener("resume",()=>this.pageShown({persisted:!0}),{signal:this.lifetime.signal}))}pageHidden=()=>{if(this.closed||this.hidden)return;let e=this.runtime,t=e!==null||this.initialization!==null;++this.incarnation,this.hidden=Object.freeze({resume:t}),this.clearPendingSave(),this.initialization=null,this.runtime=null,this.election?.abort(),this.election=null,e?.abandon(),this.tabs?.release();let{problemDetail:i,...o}=this.snapshot;this.snapshot=Object.freeze({...o,status:t?"starting":this.snapshot.status,problem:null,selectedCollectionId:null,readiness:Og})};pageShown=e=>{let t=this.hidden;this.closed||!t||!e.persisted||(this.hidden=null,this.notify(),t.resume&&(this.selection?.resync(),this.mdbase.start().catch(()=>{})))};awaitingOtherTab=!1;awaitOtherTab(e,t){let i=e.getNativeSnapshot(),o=globalThis.navigator?.locks;if(this.awaitingOtherTab||this.closed||i.status!=="blocked"||i.problem!=="open_in_another_tab"||!o)return;this.awaitingOtherTab=!0;let s=this.incarnation,r=this.lifetime.signal,a=()=>!this.closed&&!this.hidden&&s===this.incarnation&&this.runtime===e;f1(o,t,r).then(()=>a4(r)).then(()=>{this.awaitingOtherTab=!1,a()&&(this.selection?.resync(),this.mdbase.start().catch(()=>{}))},()=>{this.awaitingOtherTab=!1})}close(){if(this.closing)return this.closing;if(this.closed=!0,this.lifetime.abort(),this.selection?.close(),this.election?.abort(),this.privates?.dispose(),this.opening&&(clearTimeout(this.opening.timer),this.opening=null),this.clearPendingSave(),this.syncing){try{this.syncing.stop()}catch{}this.syncing=null}return this.closing=Promise.resolve().then(async()=>{await this.initialization?.catch(()=>{}),await this.runtime?.close(),this.tabs?.release();{let{problemDetail:e,...t}=this.snapshot;this.snapshot=Object.freeze({...t,status:"closed",problem:null,selectedCollectionId:null})}this.runtime=null,this.notify(),this.listeners.clear(),this.nativeListeners.clear()}),this.closing}transferLedger(){let e=this.declaration.storage.unsyncedDatabaseName,t=new AbortController().signal;return Object.freeze({read:(i,o)=>vR(e,i,o??t),record:(i,o,s)=>_R(e,i,o,s??t)})}transferDestination(e){let t=this.getSnapshot().phase;if(t.kind!=="ready")throw A("invalid_request","Open the collection to bring this work into first.","unsynced_transfer_needs_collection");if(e!==null&&t.collectionId!==e)throw A("invalid_request","This plan is for another collection. Plan the transfer again.","unsynced_transfer_plan_stale");return t.connection}connection(e){return this.closed?null:this.privates?.connection(e)??this.runtime?.connection(e)??null}};function X2(n,e={}){return new qg(n,e).mdbase}Ll();hm();re();function Z2(n,e){let t=is(co(n)).manifest.requirements.capabilities;if(t?.contract_version!==2)return null;if(!e.isCurrent())throw A("invalid_request","the application connection is not current","application_connection_fenced");let i=new Set(e.records.hello.grant.capabilities),o=new Set(t.required),s=Object.freeze([...new Set([...t.required,...t.optional??[]])].map(r=>Object.freeze({id:r,requirement:o.has(r)?"required":"optional",state:i.has(r)?"available":"missing"})));return Object.freeze({values:s,requiredAvailable:s.every(r=>r.requirement==="optional"||r.state==="available"),missing:Object.freeze(s.filter(r=>r.state==="missing").map(r=>r.id))})}Je();ve();Ls();qs();mp();ve();re();da();uc();nu();function Q2(n){let e=N(n.collection),t=n.grant?N(n.grant):null;return Nr({description:`relay:${n.collection}`,staticKey:n.staticKey,target:async()=>{let i=await n.resolveRoute();if(!i)throw A("unavailable","no device of this collection is online","no_device_online");let o=Ur(e,t,N(i.targetDevice));return{prologue:o,...i.prologueFirst&&!i.pipe?{preamble:o}:{},remoteStatic:i.noisePublicKey,device:i.targetDevice,openCarrier:s=>i.pipe?fc(i.url,{accessToken:i.pipe.accessToken,collection:i.pipe.collection,grant:n.grant??"",device:i.targetDevice,devicePublicKey:i.noisePublicKey},n.webSocket,s):dc(i.url,n.webSocket,s)}}})}MA();uc();da();Je();ve();re();tn();da();uc();var g4=new Uint8Array(16);function Q0(n,e){if(n.length!==32)throw A("invalid_request","the link token is 32 bytes");let t=Yr.dec(e);if(t.kind!=="request"||t.method!=="hello")throw A("internal","expected the hello request");return fe(new Map([[0,n],[1,t.params]]))}function eq(n){let e=N(n.collection),t=n.staticKey??pc(),i=null;return Nr({description:"localhost-link",staticKey:t,firstPayload:o=>Q0(i.token,o),target:async()=>{i=typeof n.link=="function"?await n.link():n.link;let o=i;if(!Number.isInteger(o.port)||o.port<=0||o.port>65535)throw A("unavailable","invalid local link port","daemon_not_running");let s=Ur(e,null,n.localOnly?g4:N(o.device));return{prologue:s,preamble:s,remoteStatic:o.noisePublicKey,openCarrier:r=>dc(`ws://127.0.0.1:${o.port}/v1/plugin`,n.webSocket,r)}}})}qy();re();function ek(){let n=new Map;return{get:async e=>n.get(e),put:async(e,t)=>{n.set(e,t)},putIfAbsent:async(e,t)=>{let i=n.get(e);return i||(n.set(e,t),t)},delete:async e=>{n.delete(e)}}}function tk(n="mdbase-keys",e="keys"){let t=globalThis.indexedDB;if(!t)throw A("invalid_request","IndexedDB is not available here; pass another KeyStorage");let i=()=>new Promise((r,a)=>{let c=t.open(n,1);c.onupgradeneeded=()=>c.result.createObjectStore(e),c.onsuccess=()=>r(c.result),c.onerror=()=>a(c.error)}),o=async(r,a)=>{let c=await i();try{return await new Promise((l,p)=>{let d=c.transaction(e,r),u,f=!1;d.oncomplete=()=>f?l(u):p(A("unavailable","key storage transaction completed without a result","key_storage")),d.onabort=()=>p(d.error??A("unavailable","key storage transaction aborted","key_storage")),d.onerror=()=>p(d.error??A("unavailable","key storage transaction failed","key_storage"));try{a(d.objectStore(e),h=>{u=h,f=!0})}catch(h){d.abort(),p(h)}})}finally{c.close()}},s=(r,a)=>o(r,(c,l)=>{let p=a(c);p.onsuccess=()=>l(p.result)});return{get:r=>s("readonly",a=>a.get(r)),put:(r,a)=>s("readwrite",c=>c.put(a,r)).then(()=>{}),putIfAbsent:(r,a)=>o("readwrite",(c,l)=>{let p=c.get(r);p.onsuccess=()=>{if(p.result!==void 0){l(p.result);return}try{let d=c.add(a,r);d.onsuccess=()=>l(a)}catch{c.transaction.abort()}}}),delete:r=>s("readwrite",a=>a.delete(r)).then(()=>{})}}function iq(){return globalThis.crypto?.subtle}async function b4(){let n=iq();if(!n)return null;try{let e=await n.generateKey({name:"X25519"},!1,["deriveBits"]),t=new Uint8Array(await n.exportKey("raw",e.publicKey));return{kind:"webcrypto",privateKey:e.privateKey,publicKey:t}}catch{return null}}function w4(n){return n.kind==="raw"?{publicKey:n.publicKey,nonExtractable:!1,dh:e=>or.getSharedSecret(n.secretKey,e)}:{publicKey:n.publicKey,nonExtractable:!n.privateKey.extractable,dh:async e=>{let t=iq(),i=await t.importKey("raw",e,{name:"X25519"},!1,[]),o=await t.deriveBits({name:"X25519",public:i},n.privateKey,256);return new Uint8Array(o)}}}var v4=ek(),tq=new WeakMap;function nq(n,e){if(e&&(n.kind!=="webcrypto"||n.privateKey.extractable!==!1||n.privateKey.type!=="private"||n.privateKey.algorithm.name!=="X25519"||!n.privateKey.usages.includes("deriveBits")))throw A("invalid_request","a non-extractable X25519 key is required; explicitly reauthorize incompatible stored identities","key_storage")}async function rq(n,e={}){let t=e.storage??(globalThis.indexedDB?tk():v4),i=e.requireNonExtractable,o=tq.get(t);o||(o=new Map,tq.set(t,o));let s=o.get(n);s||(s=(async()=>{let r=await t.get(n);if(r)return r;let a=await b4();if(!a){if(i)throw A("invalid_request","this platform cannot keep a non-extractable X25519 key","key_storage");let c=or.utils.randomSecretKey();a={kind:"raw",secretKey:c,publicKey:or.getPublicKey(c)}}return nq(a,i),t.putIfAbsent?t.putIfAbsent(n,a):(await t.put(n,a),a)})(),o.set(n,s));try{let r=await s;return nq(r,i),w4(r)}finally{o.get(n)===s&&o.delete(n)}}nu();um();Je();No();re();function nk(n,e){for(let t of n.targets??[]){if(!/^[0-9a-f]{64}$/i.test(t.noise_pk)||!t.url||!t.device)continue;let i={url:t.url,targetDevice:t.device,noisePublicKey:Wr(t.noise_pk)};return t.relay_collection?i.pipe={collection:t.relay_collection,accessToken:e}:t.kind==="hosted"&&(i.prologueFirst=!0),i}return null}function oq(n){let e;try{e=new URL(n.server)}catch{throw A("invalid_request","The control plane requires an HTTPS origin")}if(e.protocol!=="https:"&&!!1||e.username||e.password||e.pathname!=="/"||e.search||e.hash)throw A("invalid_request","The control plane requires an HTTPS origin without credentials, path, query or fragment");let t=`${e.origin}/v1/next/collections/${encodeURIComponent(n.collection)}/route`,i=n.fetch??globalThis.fetch.bind(globalThis);return async()=>{let o=await n.accessToken(),s;try{s=await i(t,{headers:{authorization:`Bearer ${o}`},redirect:"error",credentials:"omit"})}catch{throw A("unavailable","cannot reach the control plane","control_unreachable")}if(s.status===401)throw A("unauthenticated","the control plane refused the access token");if(s.status===409)throw A("unauthenticated","this app's key is not registered with its grant","client_key_required");if(!s.ok)throw A("unavailable",`control plane answered ${s.status}`,"control_error");let r=await s.json(),a=wi(r.availability);if(a?.state==="unavailable")throw Fn(a.reason);let c=nk(r,o);if(!c&&r.reason==="no_device_registered")throw A("unavailable","this collection has no device set up to serve it","no_device_registered");return c}}xm();B_();No();Ls();var rk={};Ea(rk,{APP_BASES_PROFILE:()=>Vb,APP_COLLECTION_SETUP_LIMITS:()=>ho,AppAccountKeyProofUnavailableError:()=>as,AppAccountKeySealedBundle:()=>_c,AppAccountKeyUnlockError:()=>pt,AppCloudCopyBootstrapError:()=>qn,AppCloudCopyHostError:()=>hi,AppCollectionControlError:()=>Ei,AppCollectionJoinError:()=>ws,AppCollectionJoinLedger:()=>qc,AppCollectionSetupError:()=>Ln,AppCollectionSetupJournal:()=>Xl,AppCpAccountKeyControl:()=>Ac,AppCpAuthorityError:()=>pi,AppCpCloudCopyBootstrap:()=>Gl,AppCpDeviceRegistration:()=>Rc,AppCpLogAuthority:()=>Hl,AppCpPeopleAuthority:()=>yc,AppDeviceRegistrationError:()=>ka,AppHttpLogError:()=>En,AppHttpLogTransport:()=>Wl,AppIndexedDbDeviceKeyProtectedStore:()=>Pc,AppIndexedDbDeviceKeyProvider:()=>Sc,AppIndexedDbNoiseProtectedStore:()=>Ic,AppInstallationSignInError:()=>et,AppLogHostError:()=>xt,AppLogPump:()=>ia,AppProtectedInstallationSignIn:()=>Fl,AppReplicaOwnerError:()=>rt,AppStrictDeviceApprovalError:()=>Lt,AppWasmRuntime:()=>nc,AppWebCloudCopyHost:()=>Oc,AppWebCollectionError:()=>vu,AppWebDeviceKeyCustody:()=>xc,AppWebNoiseCustody:()=>Cc,AppWebSignInSession:()=>Mg,UNSYNCED_STORAGE_WARNING:()=>qR,acquireAppInstallationLease:()=>kd,acquireAppReplicaLease:()=>Ad,appBrowserDirectAccess:()=>Tg,appCollectionControlClient:()=>Zm,appInstallationLockName:()=>r_,appLocalConnector:()=>ey,appLogHealth:()=>Nd,appModelPackPlan:()=>Zs,appModelResourcePlan:()=>$t,appMutationSaveState:()=>ER,appReplicaLockName:()=>Rm,appSaveState:()=>dy,appStoragePolicy:()=>uy,attachAppLocalFacade:()=>Qm,createAppCollectionPeople:()=>Jm,createAppWebCollectionAdapter:()=>A2,decodeAppBasesCell:()=>Os,decodeAppBasesDiscoveryResult:()=>cf,decodeAppBasesResult:()=>af,decodeAppBasesSourceResult:()=>pf,decodeAppCollectionSetupIntent:()=>Zt,encodeAppBasesDiscoveryRequest:()=>fp,encodeAppBasesRequest:()=>sf,encodeAppBasesSourceRequest:()=>lf,openAppWebCollectionClient:()=>Ag,openOwnedAppWorker:()=>h1,probeAppStorage:()=>lq,readAccountKeyMode:()=>hg,selectAppEnvironment:()=>Ci,unlockPrivateDevice:()=>mg,verifyAppHandover:()=>aq});ty();Fb();function sq(n,e){return n.seq===e.seq&&n.chain===e.chain&&n.policyGeneration===e.policyGeneration&&n.catalogGeneration===e.catalogGeneration}async function aq(n,e){let t=null;try{let{runtime:i,localPort:o,localClient:s,hostedClient:r,source:a}=n,c=r.hello,l=s.hello,p=a.collection,d=a.deviceId,u=r.authenticatedDevice;if(!(P=>typeof P=="string"&&P.replace(/-/g,"").toLowerCase()===d.replace(/-/g,"").toLowerCase())(u))return null;let h=c.status.confirmedHead,m=h?Object.freeze({...h}):void 0;if(!m||!c.headWitness||c.headWitness.length>64*1024||m.seq===0||c.collection!==p||l.collection!==p)return null;t=new Uint8Array(c.headWitness);let w=t,b=()=>{try{return!e.aborted&&n.isCurrent()===!0&&a.isCurrent()===!0&&l.collection===p&&a.collection===p&&a.deviceId===d&&s.hello===l}catch{return!1}},g=()=>{try{let P=i.observations();return!P.requiresReopen&&!P.keyringRebuilding&&!P.keyringRebuildFailed&&P.status.mode==="synced"&&P.status.confirmedHead!==void 0&&P.status.confirmedHead.seq>=m.seq}catch{return!1}},y=()=>{if(!b()||!g())return!1;let P=i.verifyHandover(o,a,w);return P!==null&&sq(P,m)},v=()=>{try{return!e.aborted&&b()&&r.hello===c&&r.authenticatedDevice===u}catch{return!1}};if(!v()||!y())return null;let _=await s.appliedPrefix(m.seq,{signal:e});if(!v()||!y()||_.seq!==m.seq||_.appliedThrough<m.seq||_.chain!==m.chain)return null;let k=Object.freeze({...m}),S=!1,x={head:k,appliedThrough:_.appliedThrough,isCurrent:()=>{if(S)return!1;try{return y()&&sq(k,m)}catch{return!1}},dispose:()=>{S=!0,w.fill(0)}};return t=null,x}catch{return null}finally{t?.fill(0)}}E0();P0();k0();S0();O0();R0();Ed();Od();HA();Rd();ry();iy();async function lq(n){if(!n.worker)return{supported:!1,reason:"worker_required"};if(!n.storage?.getDirectory)return{supported:!1,reason:"opfs_unavailable"};let e,t,i=!1,o,s={supported:!1,reason:"probe_failed"};try{let r=n.randomUUID();if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(r))return s;t=r.toLowerCase(),e=await(await n.storage.getDirectory()).getDirectoryHandle(".mdbase-app-probes",{create:!0});let a=await e.getFileHandle(t,{create:!0});if(i=!0,!a.createSyncAccessHandle)s={supported:!1,reason:"sync_handle_unavailable"};else{o=await a.createSyncAccessHandle();let c=new Uint8Array([109,100,98,110]),l=new Uint8Array(c.length);if(o.write(c,{at:0})!==c.length)throw new Error("short probe write");if(o.flush(),o.read(l,{at:0})!==c.length||l.some((p,d)=>p!==c[d]))throw new Error("probe readback failed");s={supported:!0,backend:"opfs_sahpool_candidate",crashDurability:"unqualified",eviction:"possible"}}}catch{s={supported:!1,reason:"probe_failed"}}finally{let r=!0;try{o?.close()}catch{r=!1,s={supported:!1,reason:"cleanup_failed"}}if(i&&r&&e&&t)try{await e.removeEntry(t)}catch{s={supported:!1,reason:"cleanup_failed"}}}return s}os();rs();q0();ss();Ld();Qs();j_();_g();Id();var ik=Object.freeze({status:"unsupported"}),Tg=Object.freeze({snapshot(){return ik},async check(n={}){return n.signal?.throwIfAborted(),ik},async request(n={}){return n.signal?.throwIfAborted(),ik},disable(){}});ri();Id();wu();D1();re();Id();wu();Ed();Qs();ss();_g();Od();Rd();s0();gu();os();kc();ri();var _4=new Set(["binding","fenced","busy","open_in_another_tab","account_confirmation_required","recovery_account_mismatch","outcome_unknown","response","refused","expired","recovery_required","unavailable","collection_migrating","collection_not_yet_migrated","account_suspended","update_required","private_device_limit","private_device_not_allowed"]),A4=new Set(["AbortError","ConstraintError","DataCloneError","InvalidStateError","NotAllowedError","NotFoundError","NotReadableError","OperationError","QuotaExceededError","SecurityError","TimeoutError","TransactionInactiveError","UnknownError","VersionError"]),k4=new Set(["device_open","push_nonce","local_read_without_log","read_connect","read_catch_up","read_query","key_wait_offline","close_fence"]),vo=(n,e,t,i={})=>Object.freeze({problem:n,detail:Object.freeze({name:e,code:t,...Object.fromEntries(Object.entries(i).filter(([,o])=>o!==void 0))})});function S4(n){let e=k4.has(n.stage)?n.stage:void 0;if(e!=="device_open"||n.cause instanceof hi)return{stage:e};let{name:t,code:i}=Pa(n.cause).detail;return{stage:e,cause:Object.freeze({name:t,code:i})}}function Pa(n){try{for(let[e,t]of[[et,"AppInstallationSignInError"],[hi,"AppCloudCopyHostError"],[qn,"AppCloudCopyBootstrapError"],[Ln,"AppCollectionSetupError"],[Ei,"AppCollectionControlError"],[ws,"AppCollectionJoinError"],[pi,"AppCpAuthorityError"],[En,"AppHttpLogError"],[ga,"AppPrivateBootstrapError"],[pt,"AppAccountKeyUnlockError"]])if(n instanceof e){let i=n.reason,s={server:("server"in n?zo(n.server):null)??void 0,...n instanceof hi?S4(n):{}};return i==="sync_stalled"?vo("unavailable",t,i,s):_4.has(i)?vo(i,t,i,s):vo("open_failed",t,null,s)}if(n instanceof ji)return vo(n.reason,"AppDeviceCustodyError",n.reason);if(n instanceof rt&&n.reason==="busy")return vo("open_in_another_tab","AppReplicaOwnerError","busy");if(n instanceof ne){let e=Po(n.code)?n.code:null;return vo(e==="outcome_unknown"?e:"open_failed","MdbaseError",e)}if(typeof DOMException<"u"&&n instanceof DOMException){let e=A4.has(n.name)?n.name:null;return vo("open_failed","DOMException",e)}for(let[e,t]of[[TypeError,"TypeError"],[RangeError,"RangeError"],[SyntaxError,"SyntaxError"],[ReferenceError,"ReferenceError"],[URIError,"URIError"],[EvalError,"EvalError"],[Error,"Error"]])if(n instanceof e)return vo("open_failed",t,null)}catch{}return vo("open_failed","UnknownError",null)}Ed();rs();os();Tm();re();var P4=Object.freeze({status:"unselected",problem:null,transport:null,live:null}),ft=n=>new et(n),cq=(n,e,t)=>n.problem===void 0||n.problem===e?t:void 0,x4=new Set(["collection_not_yet_migrated","collection_migrating","account_suspended","update_required"]),I4,C4,Mg=class{static{I4=(e,t,i,o)=>e.authorizeInstallation(t,i,o),C4={references:e=>e.flow?uo.references(e.flow):[],paired:(e,t)=>e.scopedInstallationPaired(t)}}lifetime=new AbortController;flowLifetime=new AbortController;options;environment;listeners=new Set;flow=null;host=null;installation=null;installationLease=null;slots=new Map;focus=null;openingSlot=null;abortCollections=()=>{for(let e of this.slots.values())e.lifetime?.abort()};base=Object.freeze({status:"not_started",signIn:null,collections:Object.freeze([]),selectedCollectionId:null,problem:null,timing:null});snapshotValue=this.base;authorizationStartedAt=null;authorizationRetryAt=0;authorizationRateLimit=null;pending=null;polling=null;timer=null;closing=null;foreground=!0;receiptRead=null;foregroundRead=null;attested=!1;restoredPending=!1;acknowledged=!1;consentPending=!1;listCached=!1;fileAccess=null;freshApproval=!1;approvalWindow=null;leftForApproval=!1;nativePending=null;forgotten=new Set;removedScopes=new Set;onAbort=()=>{this.close().catch(()=>{})};constructor(e){this.options=Object.freeze({...e}),this.environment=Ci({environment:e.environment,appOrigin:e.origin,release:e.release}),e.signal.addEventListener("abort",this.onAbort,{once:!0}),this.lifetime.signal.addEventListener("abort",this.abortCollections,{once:!0})}getSnapshot(){return this.snapshotValue}snapshot(){return this.getSnapshot()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}viewFor(e,t={}){return t.bystander&&this.base.status==="authorizing"&&this.consentPending&&e!==null&&this.slots.has(e)?this.compose(e,!0):e===this.focus?this.snapshotValue:this.compose(e)}collectionView(e){return this.slots.get(e)?.view??null}heldCollections(){return[...this.slots.keys()]}compose(e,t=!1){let i=this.base,o=e===null?void 0:this.slots.get(e);if(!o)return i;if(i.status!=="unselected"&&!t)return Object.freeze({...i,selectedCollectionId:o.id,transport:o.view.transport,live:o.view.live});let{problemDetail:s,...r}=i,{problemDetail:a,...c}=o.view;return Object.freeze({...r,...t?{status:"unselected",problem:null,approval:null}:{},...c,selectedCollectionId:o.id,...a?{problemDetail:a}:{}})}connection(e=this.focus){let t=e===null?void 0:this.slots.get(e),i=this.base.status==="unselected"||this.base.status==="authorizing"&&this.consentPending;return!t||this.closing||this.options.signal.aborted||!t.usable||t.lifetime?.signal.aborted||!this.installation?.isCurrent()||!i||!["ready","setup_required"].includes(t.view.status)||!this.sameScope(t.scope,t.leaseScope)||t.scope?.collection!==t.id?null:t.selected?.connection??null}sameScope(e,t){return e!==null&&t!==null&&e.account===t.account&&e.installation===t.installation&&e.collection===t.collection&&e.account===this.installation?.scope.account&&e.installation===this.installation?.scope.installation}directAccess=Tg;checkDirectAccess(e){return this.check(),this.directAccess.check(e)}requestDirectAccess(e){return this.check(),this.directAccess.request(e)}check(){if(this.closing||this.options.signal.aborted||this.lifetime.signal.aborted)throw ft("fenced")}publish(e){this.check(),this.setBase(e),this.changed()}setBase(e){let{problemDetail:t,...i}=this.base,o=e.problemDetail??cq(e,i.problem,t);this.base=Object.freeze({...i,...e,selectedCollectionId:null,signIn:this.flow?.view()??null,...o?{problemDetail:o}:{}})}publishSlot(e,t){if(this.check(),this.slots.get(e.id)!==e)return;let i=this.base.timing;if(this.authorizationStartedAt!==null&&(t.status==="ready"||t.status==="setup_required")){let u=Math.max(0,performance.now()-this.authorizationStartedAt);i=Object.freeze({firstScreenMs:i?.firstScreenMs??u,readyMs:t.status==="ready"?i?.readyMs??u:i?.readyMs??null})}this.setBase({timing:i});let{problemDetail:o,unlock:s,...r}=e.view,{unlock:a,...c}=t,l=t.problemDetail??cq(t,r.problem,o),p=(t.status??r.status)==="opening"?"openingProgress"in t?t.openingProgress??null:r.openingProgress??null:null,d=(t.status??r.status)==="needs_unlock"?a??s??null:null;e.view=Object.freeze({...r,...c,openingProgress:p,...d?{unlock:d}:{},...l?{problemDetail:l}:{}}),this.changed()}changed(){this.snapshotValue=this.compose(this.focus);for(let e of[...this.listeners])try{e()}catch{}}poll(e){this.pending||(this.operation(e).catch(()=>{}),this.polling=this.pending)}stopPolling(){this.timer!==null&&clearTimeout(this.timer),this.timer=null}operation(e,t=!1){if(this.check(),this.pending)return Promise.reject(ft("busy"));this.foregroundRead=null,this.stopPolling();let o=Promise.resolve().then(()=>(this.check(),e())).catch(async s=>{if(!t&&!this.closing&&!this.options.signal.aborted){let{problem:r,detail:a}=Pa(s);if(r==="open_failed")try{console.error("mdbase web sign-in open failed",a.name,a.code)}catch{}let c=this.openingSlot;if(this.openingSlot=null,c&&this.slots.get(c.id)===c){let l=!1;try{l=s instanceof qn&&s.reason==="unavailable"&&s.retryable===!0&&c.view.status==="opening"&&this.base.collections.some(p=>p.collectionId===c.id)&&this.flow?.view().state==="paired"&&this.installation?.isCurrent()===!0}catch{}if(l){try{await this.closeSlot(c),this.check()}catch(p){throw!this.closing&&!this.options.signal.aborted&&this.publishSlot(c,{status:"blocked",problem:"recovery_required",problemDetail:Pa(p).detail}),p}this.publishSlot(c,{status:"unselected",problem:r,problemDetail:a})}else this.publishSlot(c,{status:"blocked",problem:r,problemDetail:a})}else this.publish({status:"blocked",problem:r,problemDetail:a})}throw s});return this.pending=o,o.finally(()=>{this.pending===o&&(this.pending=null),this.schedulePoll()})}start(){return this.operation(async()=>{if(this.flow&&(this.base.status!=="blocked"||this.base.problem==="installation_removed"))return this.getSnapshot();this.publish({status:"starting",problem:null,signOutResult:null});let e=this.options;this.flow??=await Fl.open({...e,mode:e.storeMode??"open",signal:this.flowLifetime.signal,environmentSelection:this.environment}),this.check();let t=this.flow.view();if(uo.replacementPending(this.flow)){for(let i of t.collectionIds)this.removedScopes.add(i);this.publish({status:"blocked",problem:"installation_removed",collections:Object.freeze([])})}else if(t.state==="paired")if(await this.openDevice(!1,this.options.recoveryFor!==void 0),await this.abandonUnfinishedNativeChoice(),this.flow.collectionConsentView()?.state==="pending")this.consentPending=!0,this.publish({status:"authorizing"});else{let i=null;try{i=this.flow.cachedApprovedCollections(this.installation)}catch{i=null}await this.refreshCollections(i)}else this.restoredPending=t.state==="pending"&&this.flow.requestSent(),this.publish({status:t.state==="pending"&&!this.restoredPending?"signed_out":"authorizing"});return this.getSnapshot()})}authorize(e={}){return this.authorizeInstallation(e,!1)}authorizeInstallation(e,t,i){if(this.check(),this.authorizationRateLimit&&Date.now()<this.authorizationRetryAt)return Promise.reject(this.authorizationRateLimit);let o=this.pending!==null&&this.pending===this.polling?this.pending:null;if(!this.flow||this.pending&&!o)return Promise.reject(ft("busy"));let s=this.options.openPortal();return o?o.catch(()=>{}).then(()=>{try{this.check()}catch(a){throw s.close(),a}if(this.pending)throw s.close(),ft("busy");let r=this.base.status;return r!=="authorizing"&&r!=="signed_out"?(s.close(),this.getSnapshot()):this.beginAuthorization(s,e,t,i)}):this.beginAuthorization(s,e,t,i)}beginAuthorization(e,t,i,o){let s={collectionHint:t.collectionHint??null};return this.restoredPending=!1,this.authorizationStartedAt=performance.now(),this.publish({timing:Object.freeze({firstScreenMs:null,readyMs:null}),approval:null}),this.operation(async()=>{try{(this.base.problem==="installation_removed"||uo.replacementPending(this.flow))&&await this.replaceRemovedInstallation(o);let r=null;if(this.flow.view().state==="paired"){await this.openDevice(),this.check(),await this.abandonUnfinishedNativeChoice();try{let a=await this.flow.startCollectionConsent(this.installation,this.options.requestedCreateCollections??this.options.freshRequestedCreateCollections??!1,s,this.options.freshRequestedPrivateDevice===!0);this.consentPending=!0,r=a.verificationUri}catch(a){if(!await this.handleRemovedInstallation(a))throw a;if(i)return e.close(),this.getSnapshot();await this.replaceRemovedInstallation(o)}}return r===null&&(r=(await this.flow.start(s).catch(c=>this.renewFromGesture(c))).verificationUri),this.check(),e.navigate(r),this.holdApprovalWindow(e),this.publish({status:"authorizing",problem:null}),await this.advance(),this.getSnapshot()}catch(r){throw r instanceof et&&r.server?.status===429&&(this.authorizationRateLimit=r,this.authorizationRetryAt=Date.now()+Math.min(Xa,Math.max(Ja,r.server.retryAfterMs??3e4))),e.close(),r}})}requestFileAccess(e,t,i){if(this.check(),!this.flow||this.pending)return Promise.reject(ft("busy"));let o=this.options.openPortal();return this.operation(async()=>{try{if(this.flow.view().state!=="paired"||!this.installation||!this.base.collections.some(r=>r.collectionId===e))throw ft("refused");let s=await this.flow.startFileAccess(this.installation,e,t,i);return this.check(),this.fileAccess=s,o.navigate(s.verificationUri),this.holdApprovalWindow(o),this.publish({fileAccess:Object.freeze({requestId:s.requestId,collectionId:e,actions:s.actions,state:"pending"})}),this.getSnapshot()}catch(s){throw o.close(),s}},!0)}pollFileAccess(e){let t=this.fileAccess;return!t||t.requestId!==e||!this.flow||!this.installation?Promise.resolve(this.getSnapshot()):this.operation(async()=>{let i={state:"pending"};try{i=await this.flow.exchangeFileAccess(this.installation,t)}catch(r){if(Date.now()<t.expiresAt)throw r}if(this.check(),this.fileAccess!==t||i.state==="pending"&&Date.now()<t.expiresAt)return this.getSnapshot();this.fileAccess=null,this.closeApprovalWindow();let o=i.state==="granted"?i.actions:null,s=o?Object.freeze(this.base.collections.map(r=>r.collectionId!==t.collectionId?r:Object.freeze({...r,fileActions:Object.freeze([...new Set([...r.fileActions??[],...o])])}))):this.base.collections;return this.publish({collections:s,fileAccess:Object.freeze({requestId:e,collectionId:t.collectionId,actions:o??t.actions,state:i.state==="pending"?"expired":i.state})}),this.getSnapshot()},!0)}async renewFromGesture(e){if(!(e instanceof et)||e.reason!=="expired"&&e.reason!=="refused")throw e;try{return await this.flow.renewExpiredPairing()}catch(t){throw t instanceof et&&t.reason==="recovery_required"?e:t}}renewExpiredPairing(){return this.operation(async()=>{if(!this.flow)throw ft("binding");return await this.flow.renewExpiredPairing(),this.check(),this.publish({status:"signed_out",problem:null}),this.getSnapshot()})}receiptGeneration(e){try{if(!e.isCurrent())return null;let t=e.view(),i=this.consentPending?e.collectionConsentView():null;return(this.consentPending?i?.state!=="pending":!["pending","awaiting_approval"].includes(t.state))?null:JSON.stringify([t.requestId,t.installationId,t.deviceId,t.accountId,t.state,this.consentPending,i?.requestId,i?.state])}catch{return null}}currentReceipt(e){try{return!this.closing&&!this.lifetime.signal.aborted&&!this.flowLifetime.signal.aborted&&!e.caller.aborted&&this.options.signal===e.caller&&this.flow===e.flow&&this.installation===e.installation&&(e.installation===null||e.installation.isCurrent()===!0)&&this.attested===e.attested&&this.acknowledged===e.acknowledged&&this.receiptGeneration(e.flow)===e.generation}catch{return!1}}async exchangeReceipt(e){let t=this.flow,i=this.pending,o=t?this.receiptGeneration(t):null,s=t&&i&&o!==null?Object.freeze({flow:t,operation:i,generation:o,caller:this.options.signal,installation:this.installation,attested:this.attested,acknowledged:this.acknowledged}):null;this.receiptRead=s;let r=!1;try{let a=await e();return r=a!=null,a}catch(a){if(a instanceof et&&a.reason==="outcome_unknown"&&this.flow?.isCurrent())return this.publish({status:"authorizing",problem:"outcome_unknown"}),null;throw a}finally{this.receiptRead===s&&(this.receiptRead=null),this.foregroundRead===s&&(!r||!s||!this.currentReceipt(s))&&(this.foregroundRead=null)}}async advance(){if(this.consentPending){let t;try{t=await this.exchangeReceipt(()=>this.flow.exchangeCollectionConsent(this.installation))}catch(i){if(!(i instanceof et)||i.reason!=="refused"&&i.reason!=="expired")throw i;this.check(),this.consentPending=!1,this.closeApprovalWindow(),this.publish({status:"unselected",problem:null,approval:Object.freeze({outcome:"cancelled"})}),await this.refreshCollections();return}if(this.check(),!t)return;if(t.state==="scope_updated"){if(t.accountSelectionConfirmed!==!0)throw ft("account_confirmation_required");let i=this.flow.pendingNativeSelection?.();if(i?.requestId===t.requestId){if(!await this.settleNativeChoice(i)){this.consentPending=!1,this.closeApprovalWindow(),this.publish({status:"unselected",problem:null,approval:Object.freeze({outcome:"closed"})}),await this.refreshCollections();return}}else if(this.flow.view().collectionSelection?.requestId!==t.requestId&&!this.deviceAccessWithoutPick(t.requestedPrivateDevice===!0?t.addedCollectionIds:[]))throw ft("response");this.consentPending=!1,this.freshApproval=!0,this.closeApprovalWindow(),await this.refreshCollections()}else await this.prepareNativeChoice(),this.resumeApprovalWindow(),this.publish({status:"authorizing",problem:this.nativePending?.failed?"private_authorization_failed":null});return}let e;try{e=await this.exchangeReceipt(()=>this.flow.exchange())}catch(t){if(!this.restoredPending||!(t instanceof et)||t.reason!=="expired"&&t.reason!=="refused")throw t;this.check(),this.restoredPending=!1,this.publish({status:"signed_out",problem:null});return}if(this.check(),!!e)if(e.state==="account_selected"&&(e=await this.flow.confirmPortalSelectedAccount(),this.check()),(e.state==="account_confirmed"||e.state==="awaiting_approval")&&(await this.openDevice(),this.check(),this.attested||(await this.host.attestInstallation(),this.check(),this.attested=!0),await this.prepareNativeChoice(),this.resumeApprovalWindow()),e.state==="paired"){let t=this.flow.pendingNativeSelection?.(),i=t?.requestId===e.requestId&&!await this.settleNativeChoice(t);if(t?.requestId!==e.requestId&&e.collectionSelection?.requestId!==e.requestId&&!this.deviceAccessWithoutPick(e.privateDeviceCollectionIds??[]))throw ft("response");this.freshApproval=!0,this.closeApprovalWindow(),await this.openDevice(),this.check(),i&&this.publish({approval:Object.freeze({outcome:"closed"})}),await this.refreshCollections()}else this.publish({status:"authorizing",problem:this.nativePending?.failed?"private_authorization_failed":null})}deviceAccessWithoutPick(e){let t=this.flow.view(),i=t.privateDeviceCollectionIds??[];return(t.collectionSelection??null)===null&&e.some(o=>i.includes(o))}resumeApprovalWindow(){if(!(!this.leftForApproval||!this.foreground||!this.approvalWindow||!this.appPartDone())){this.leftForApproval=!1;try{this.approvalWindow.focus?.()}catch{}}}appPartDone(){if(!this.attested)return!1;if(!this.approvalWindow?.nativeAuthorization||!this.installation||!this.flow.nativeAuthorizationContext(this.installation))return!0;let e=this.nativePending;return e!==null&&e.attempted&&!e.failed}async prepareNativeChoice(){let e=this.approvalWindow?.nativeAuthorization;if(!e||!this.installation)return;let t=this.flow.nativeAuthorizationContext(this.installation);if(!t)return;let i=this.nativePending;if(!i){if(i={context:t,port:e,life:new AbortController,prepared:null,failed:!1,attempted:!1},this.nativePending=i,t.authorizationId){i.failed=!0;return}let o=i,s=AbortSignal.any([this.lifetime.signal,this.flowLifetime.signal,i.life.signal]);e.prepare(t,s).then(r=>{this.nativePending!==o||s.aborted||(o.prepared=Object.freeze({...r}))},()=>{o.failed=!0})}if(i.context.requestId!==t.requestId||i.context.accountId!==t.accountId||i.context.challenge!==t.challenge)throw ft("fenced");if(i.prepared&&!i.attempted){i.attempted=!0;try{await this.flow.attachNativeAuthorization(this.installation,i.context,i.prepared),this.check()}catch{i.failed=!0}}}async finishNativeChoice(e){let t=this.nativePending;if(!t||!t.prepared||!t.attempted||t.context.requestId!==e.requestId||t.prepared.authorizationId!==e.authorizationRequestId)throw ft("recovery_required");let i=await t.port.finish(e,AbortSignal.any([this.lifetime.signal,this.flowLifetime.signal,t.life.signal]));if(this.check(),this.nativePending!==t||!this.acknowledged||!this.installation)throw ft("fenced");await this.flow.completeNativeAuthorization(this.installation,i),this.check()}async settleNativeChoice(e){await this.openDevice(),this.check();try{return await this.finishNativeChoice(e),!0}catch(t){this.check();let i=!1;try{i=this.installation!==null&&await this.flow.abandonNativeSelection?.(this.installation)===!0}catch{i=!1}if(this.check(),!i)throw t;try{console.warn("mdbase: a Private collection pick was not finished",Pa(t).detail.code)}catch{}return!1}}async abandonUnfinishedNativeChoice(){let e=this.flow;if(!e.pendingNativeSelection?.()||e.view().nativeSelection)return;if(!this.installation||!e.abandonNativeSelection)throw ft("recovery_required");let t=await e.abandonNativeSelection(this.installation);if(this.check(),!t)throw ft("recovery_required")}holdApprovalWindow(e){this.approvalWindow!==e&&this.closeApprovalWindow(),this.approvalWindow=e,this.leftForApproval=!1}closeApprovalWindow(){let e=this.approvalWindow;this.approvalWindow=null,this.leftForApproval=!1;let t=this.nativePending;this.nativePending=null,t?.life.abort();try{t?.port.cancel()}catch{}if(e)try{e.close()}catch{}}async openDevice(e=!1,t=!1){if(!this.installation){let i=this.flow.confirmedSelection(),o=Object.freeze({account:i.accountId,installation:i.installationId});this.installationLease=await kd(this.options.locks,o,this.lifetime.signal),this.check();let s=this.installationLease;this.installation=Object.freeze({scope:o,isCurrent:()=>!this.closing&&!this.options.signal.aborted&&!this.lifetime.signal.aborted&&this.installationLease===s})}t||!this.host&&!e&&this.acknowledged&&this.flow.view().state==="paired"&&[...this.slots.values()].some(i=>i.host!==null)||(this.host?!this.acknowledged&&this.flow.view().state==="paired"&&(await this.host.completeInstallationSignIn(),this.check(),this.acknowledged=!0):(this.host=await Oc.openInstallationDevice({signIn:this.flow,installation:this.installation,release:this.options.release,origin:this.options.origin,signal:this.lifetime.signal,loadRuntime:this.options.loadRuntime,allowLoopbackHttp:this.environment.allowLoopbackHttp}),this.check(),this.acknowledged=this.flow.view().state==="paired"))}async refreshCollections(e=null){let t;try{t=e??await this.flow.listApprovedCollections(this.installation)}catch(s){if(await this.handleRemovedInstallation(s))return;throw s}if(this.check(),this.listCached=e!==null,!e)for(let s of this.flow.view().collectionIds)t.some(r=>r.collectionId===s)||this.removedScopes.add(s);let i=Object.freeze(t.filter(s=>!this.forgotten.has(s.collectionId)));for(let s of this.slots.values()){if(s.usable&&s.selected&&!i.some(p=>p.collectionId===s.id)){s.usable=!1,s.lifetime?.abort(),await this.closeSlot(s),this.check(),this.deleteSlot(s);continue}let r=s.usable&&s.selected!==null&&i.some(p=>p.collectionId===s.id),{problemDetail:a,unlock:c,...l}=s.view;s.view=Object.freeze({...l,...r?this.assessed(s.selected):{status:"unselected"},problem:null})}this.publish({status:"unselected",collections:i,problem:null});let o=this.flow.view().collectionSelection?.selectedCollectionId;(this.options.autoSelect??"only")==="only"&&(this.freshApproval&&o&&i.some(s=>s.collectionId===o)?await this.openSlot(o,!0):i.length===1&&await this.openSlot(i[0].collectionId,!0))}async handleRemovedInstallation(e){if(!(e instanceof et)||!rn(e.server)||e.server.status!==401||e.server.code!=="invalid_connector")return!1;this.check(),this.listCached=!1;for(let t of this.flow.view().collectionIds)this.removedScopes.add(t);this.consentPending=!1,this.closeApprovalWindow();for(let t of this.slots.values())t.usable=!1,t.lifetime?.abort();return this.publish({status:"blocked",problem:"installation_removed",problemDetail:Pa(e).detail,collections:Object.freeze([])}),await this.closeSlots(),this.check(),this.changed(),!0}async replaceRemovedInstallation(e){let t=this.flow;try{await g_(t,async()=>{await e?.stopChildren(),await this.closeSlots(),this.check()},e?.childPaired)}catch(i){throw t.isCurrent()||(this.flow=null),i}this.check(),await this.installationLease?.release(),this.installationLease=null,this.installation=null,this.check(),this.attested=!1,this.acknowledged=!1,this.freshApproval=!1,this.fileAccess=null,this.forgotten.clear(),this.removedScopes.clear(),this.publish({status:"signed_out",problem:null,fileAccess:void 0})}schedulePoll(){if(this.pending&&!this.closing&&!this.options.signal.aborted)return;let e=this.foregroundRead;this.foregroundRead=null;for(let i of this.closing||this.options.signal.aborted?[]:this.slots.values()){let o=this.retryAfterMs(i);o===null||i.timer!==null||i.view.status!=="blocked"||(i.timer=setTimeout(()=>{i.timer=null,!(this.slots.get(i.id)!==i||i.view.status!=="blocked"||i.view.problem!=="collection_migrating"||this.flow?.view().state!=="paired")&&this.operation(()=>this.openSlot(i.id)).catch(()=>{})},o))}if(this.closing||this.options.signal.aborted||this.timer!==null||this.base.status!=="authorizing")return;let t=this.foreground&&e&&this.currentReceipt(e)?e:null;this.timer=setTimeout(()=>{this.timer=null,this.poll(async()=>{t&&(!this.foreground||!this.currentReceipt(t))||await this.advanceApproval()})},t?0:this.foreground?this.base.problem==="outcome_unknown"?5e3:1e3:1e4)}retryAfterMs(e){let t=e.view;if(t.problem!=="collection_migrating")return null;let i=null;try{i=zo(t.problemDetail?.server)?.retryAfterMs??null}catch{i=null}return Math.min(Xa,Math.max(Ja,i??3e4))}setForeground(e){this.check();let t=e&&!this.foreground;this.foreground=e,this.stopPolling(),e?t&&this.receiptRead?.operation===this.pending&&(this.foregroundRead=this.receiptRead):(this.foregroundRead=null,this.approvalWindow&&!this.appPartDone()&&(this.leftForApproval=!0)),e&&this.base.status==="authorizing"&&!this.pending?this.poll(()=>this.advanceApproval()):this.schedulePoll()}approvalWindowClosed(){this.check(),!(this.pending||this.base.status!=="authorizing"||!this.approvalWindowGone())&&(this.stopPolling(),this.poll(()=>this.advanceApproval()))}approvalWindowGone(){let e=this.approvalWindow;try{return e?.closed===!0}catch{return!1}}async cancelAuthorization(){for(this.check();this.pending;)await this.pending.catch(()=>{}),this.check();return this.operation(async()=>{if(this.base.status!=="authorizing")return this.getSnapshot();this.closeApprovalWindow();let e=Object.freeze({outcome:"closed"});return this.consentPending?(this.consentPending=!1,this.publish({status:"unselected",problem:null,approval:e}),await this.refreshCollections()):(await this.flow.forgetSentRequest(),this.check(),this.restoredPending=!1,this.publish({status:"signed_out",problem:null,approval:e})),this.getSnapshot()})}async advanceApproval(){let e=this.approvalWindowGone()?this.approvalWindow:null;if(await this.advance(),this.check(),!(!e||this.approvalWindow!==e||this.base.status!=="authorizing")&&this.base.problem!=="outcome_unknown"){if(this.closeApprovalWindow(),this.consentPending){this.consentPending=!1,this.publish({status:"unselected",problem:null,approval:Object.freeze({outcome:"closed"})}),await this.refreshCollections();return}this.publish({status:"signed_out",problem:"approval_window_closed",approval:Object.freeze({outcome:"closed"})})}}select(e){return this.operation(async()=>(await this.openSlot(e,!0),this.getSnapshot()))}openCollection(e){return this.operation(async()=>(await this.openSlot(e),this.viewFor(e)))}releaseCollection(e){return this.slots.has(e)?this.operation(async()=>{let t=this.slots.get(e);return t&&(await this.closeSlot(t),this.check(),this.deleteSlot(t),this.changed()),this.getSnapshot()}):Promise.resolve(this.getSnapshot())}async openSlot(e,t=!1){this.check();let i=this.base.collections.find(h=>h.collectionId===e);if(!i||this.flow?.view().state!=="paired"||!this.installation)throw ft("refused");let o=t?[...this.slots.values()].filter(h=>h.id!==e):[],s=this.slots.get(e);if(s&&s.usable&&s.selected&&!s.lifetime?.signal.aborted&&this.sameScope(s.scope,s.leaseScope)&&s.scope?.collection===e){for(let h of o)h.usable=!1,h.lifetime?.abort();this.focus=e,this.settleBase(),this.publishSlot(s,{...this.assessed(s.selected),problem:null});for(let h of o)await this.closeSlot(h),this.check(),this.deleteSlot(h),this.changed();return}for(let h of o)h.usable=!1,h.lifetime?.abort();let r=s??{id:e,host:null,lease:null,leaseScope:null,selected:null,scope:null,lifetime:null,usable:!1,stopAssessment:null,timer:null,view:P4};r.usable=!1,r.lifetime?.abort(),this.slots.set(e,r),this.focus=e,this.openingSlot=r,this.settleBase(),this.publishSlot(r,{status:"opening",problem:null,openingProgress:null});for(let h of o)await this.closeSlot(h),this.check(),this.deleteSlot(h),this.changed();(r.lease||r.selected||r.host)&&await this.closeSlot(r),this.check(),await this.openDevice(!0),this.check(),r.host=this.host,this.host=null;let a=Object.freeze({...this.installation.scope,collection:e});r.lease=await Ad(this.options.locks,a,this.lifetime.signal),r.leaseScope=a,this.check(),r.lifetime=new AbortController;let c=this.freshApproval&&this.flow.view().collectionSelection?.createdCollectionIds.includes(e)===!0,l=r.lifetime,p=await this.options.openCollection({host:r.host,installation:this.installation,scope:a,collection:i,setupPolicy:c?"approved-new-collection":"explicit",signal:l.signal,onProgress:h=>{this.closing||this.slots.get(r.id)!==r||r.lifetime!==l||l.signal.aborted||r.view.status!=="opening"||r.view.openingProgress!==h&&this.publishSlot(r,{openingProgress:h})}});r.selected=p,r.scope=a,this.check();let d=this.assessed(p);r.usable=!0,this.openingSlot===r&&(this.openingSlot=null),r.stopAssessment=p.subscribe?.(()=>{if(this.closing||this.slots.get(r.id)!==r||!r.usable||r.selected!==p||r.lifetime?.signal.aborted||!this.sameScope(r.scope,r.leaseScope)||r.scope?.collection!==r.id)return;let h=null;try{h=p.ended??null}catch{h=null}if(h){this.accessEnded(r,p,h);return}let m=null;try{m=p.failure??null}catch{m=null}if(m!==null){this.openFailedLate(r,p,m);return}let w;try{w=this.assessed(p)}catch{return}this.publishSlot(r,w.status==="needs_unlock"?{...w,problem:null,transport:null,live:null}:{...w,...this.liveProblem(r,p)})})??null;let u=null;try{u=p.ended??null}catch{u=null}let f=null;try{f=p.failure??null}catch{f=null}if(u){this.accessEnded(r,p,u);return}if(f!==null){this.openFailedLate(r,p,f);return}this.publishSlot(r,{...d,transport:null,live:null,openingProgress:null})}assessed(e){let t=e.state;if(t==="ready"||t==="setup_required")return{status:t};if(t!=="needs_unlock"||typeof e.unlock!="function")throw ft("response");let i=e.locked;if(!i||typeof i!="object"||!["password","strict","none"].includes(i.mode)||typeof i.unlocking!="boolean"||i.problem!==null&&(typeof i.problem!="string"||!/^[a-z][a-z0-9_]{0,63}$/.test(i.problem)))throw ft("response");return{status:t,unlock:Object.freeze({mode:i.mode,unlocking:i.unlocking,problem:i.problem})}}unlockCollection(e,t){let i=()=>{let o=this.slots.get(e);return o&&o.usable&&o.selected&&typeof o.selected.unlock=="function"&&o.view.status==="needs_unlock"&&!o.lifetime?.signal.aborted&&this.base.status==="unselected"&&this.installation?.isCurrent()===!0&&this.sameScope(o.scope,o.leaseScope)&&o.scope?.collection===e?o:null};return!this.closing&&!this.options.signal.aborted&&!this.pending&&!i()?Promise.reject(ft("refused")):this.operation(async()=>{let o=i();if(!o)throw ft("refused");let s=o.selected;this.openingSlot=o;try{await s.unlock(t),this.check()}catch(a){throw o.usable=!1,o.lifetime?.abort(),a}if(this.slots.get(o.id)!==o||o.selected!==s||!o.usable)throw ft("fenced");this.openingSlot===o&&(this.openingSlot=null);let r=this.assessed(s);return this.publishSlot(o,r.status==="needs_unlock"?{...r,problem:null}:{...r,...this.liveProblem(o,s)}),this.viewFor(e)})}settleBase(){(this.base.status==="blocked"||this.base.status==="unselected")&&this.setBase({status:"unselected",problem:null})}deleteSlot(e){e.timer!==null&&clearTimeout(e.timer),e.timer=null,this.slots.get(e.id)===e&&this.slots.delete(e.id),this.focus===e.id&&(this.focus=null),this.openingSlot===e&&(this.openingSlot=null)}accessEnded(e,t,i){if(e.selected!==t||!e.usable)return;let o=i==="gone"?"collection_deleted":i==="revoked"?"unauthenticated":"access_removed";i!=="gone"&&this.removedScopes.add(e.id),e.usable=!1,this.publishSlot(e,{status:"blocked",problem:o,transport:null,live:null});let s=()=>{if(!(this.closing||this.options.signal.aborted||e.selected!==t||this.slots.get(e.id)!==e)){if(this.pending){this.pending.catch(()=>{}).then(s);return}this.operation(async()=>{if(await this.closeSlot(e),this.publishSlot(e,{status:"blocked",problem:o}),!(!this.flow||!this.installation||this.flow.view().state!=="paired"))try{let r=await this.flow.listApprovedCollections(this.installation);this.check(),this.publish({collections:Object.freeze(r.filter(a=>!this.forgotten.has(a.collectionId)))})}catch{}}).catch(()=>{})}};s()}openFailedLate(e,t,i){if(e.selected!==t||!e.usable)return;let{problem:o,detail:s}=Pa(i);if(o==="open_failed")try{console.error("mdbase web sign-in open failed",s.name,s.code)}catch{}e.usable=!1,this.publishSlot(e,{status:"blocked",problem:o,problemDetail:s,transport:null,live:null});let r=()=>{if(!(this.closing||this.options.signal.aborted||e.selected!==t||this.slots.get(e.id)!==e)){if(this.pending){this.pending.catch(()=>{}).then(r);return}this.operation(async()=>{await this.closeSlot(e),this.publishSlot(e,{status:"blocked",problem:o,problemDetail:s})},!0).catch(()=>{})}};r()}liveProblem(e,t){let i=null;try{i=t.problem??null}catch{i=null}let o=null;try{o=t.health??null}catch{o=null}let s=o?Object.freeze({...o}):null,r=null;try{let c=t.live;r=typeof c=="boolean"?c:null}catch{r=null}let a=rn(i)?Rt(i):null;return a&&i?{problem:a,problemDetail:Object.freeze({name:"AppHttpLogError",code:a,server:i}),transport:s,live:r}:{...x4.has(e.view.problem??"")?{problem:null}:{},transport:s,live:r}}async closeSlot(e){e.usable=!1,e.timer!==null&&clearTimeout(e.timer),e.timer=null;let t=e.stopAssessment;e.stopAssessment=null;try{t?.()}catch{}e.lifetime?.abort(),await e.selected?.close(),e.selected=null,e.scope=null,e.lifetime=null,await e.host?.close(),e.host=null,await e.lease?.release(),e.lease=null,e.leaseScope=null}async closeSlots(){for(let e of[...this.slots.values()])await this.closeSlot(e),this.deleteSlot(e);await this.host?.close(),this.host=null}clearSelection(){return this.operation(async()=>(await this.closeSlots(),this.focus=null,this.publish({status:"unselected",problem:null}),this.getSnapshot()))}refreshCollectionList(){return this.pending||!this.flow||!this.installation||this.consentPending||this.flow.view().state!=="paired"||this.base.status!=="unselected"?Promise.resolve(this.getSnapshot()):this.operation(async()=>(await this.refreshCollections(),this.getSnapshot()),!0)}collectionListCached(){return this.listCached}scopeWasRemoved(e){return this.removedScopes.has(e)}removedScopeIds(){return Object.freeze([...this.removedScopes])}canAbandonWrongAccount(){return!this.closing&&!this.options.signal.aborted&&this.pending===null&&this.flow?.canAbandonWrongAccount()===!0&&this.installation===null&&this.host===null&&this.slots.size===0&&!this.attested&&!this.acknowledged}scopeRecoveryContext(){if(!this.flow||!this.installation||uo.replacementPending(this.flow))return null;let e=this.flow.view();return e.state!=="paired"?null:Object.freeze({accountId:this.installation.scope.account,accountLabel:e.accountEmail??(e.accountLogin?`@${e.accountLogin}`:null),references:this.flow.collectionRecoveries()})}scopedInstallationPaired(e){if(this.pending||!this.flow||uo.replacementPending(this.flow))return!1;let t=this.flow.view();return t.state==="paired"&&t.accountId===e}prepareScopedRecovery(e,t){return this.check(),this.pending?this.pending.catch(()=>{}).then(()=>this.prepareScopedRecovery(e,t)):this.operation(async()=>{if(!this.flow||!this.installation||this.consentPending||this.flow.view().state!=="paired"||uo.replacementPending(this.flow))throw ft("binding");if(t!==void 0){let c=await uo.replaceRetained(this.flow,this.installation,e,t);if(this.check(),c!==null)return Object.freeze({accountId:this.installation.scope.account,reference:c})}if(!this.flow.view().collectionIds.includes(e))throw ft("binding");let i=this.flow.collectionRecoveries(),o=this.slots.get(e);if(t===void 0&&!Object.hasOwn(i,e)&&!this.scopeWasRemoved(e))throw ft("binding");o&&(await this.closeSlot(o),this.check(),this.deleteSlot(o)),await this.flow.retireCollectionScope(this.installation,e,t??null),this.check();let s=this.flow.confirmedSelection(),r=this.options;if(!await S1({cpOrigin:r.cpOrigin,appId:r.appId,accountId:s.accountId,connectorId:s.connectorId,installationId:s.installationId,deviceId:s.deviceId,collectionIds:[e],databases:[]},e))throw ft("recovery_required");this.check();let a=await this.flow.freshCollectionInstallation(this.installation,e);return this.check(),Object.freeze({accountId:s.accountId,reference:a})},!0)}forget(e){return this.operation(async()=>{let t=this.slots.get(e);return t&&(await this.closeSlot(t),this.check(),this.deleteSlot(t)),this.forgotten.add(e),this.publish({collections:Object.freeze(this.base.collections.filter(i=>i.collectionId!==e))}),this.getSnapshot()})}deleteCollection(e,t){let i=null;return this.operation(async()=>{let o=this.base.collections.find(s=>s.collectionId===e);if(!this.flow||!this.installation||!o)i=new ir("collection_delete_not_found");else if(o.role!=="owner")i=new ir("collection_delete_not_owner");else{try{await this.flow.deleteApprovedCollection(this.installation,e,t)}catch(s){i=N1(s)}this.check()}return this.getSnapshot()}).then(o=>{if(i)throw i;return o})}signOut(){this.check();let e=this.pending!==null&&this.pending===this.polling?this.pending:null;return Promise.resolve(e?.catch(()=>{})).then(()=>this.operation(async()=>{let t=this.flow,i=null,o=null,s=!1;try{i=t?.view()??null}catch{i=null}try{o=t?.confirmedSelection().connectorId??null}catch{o=null}try{s=t?.hasWebPushChannel()===!0}catch{s=!1}let r=[...new Set([...i?.collectionIds??[],...this.base.collections.map(p=>p.collectionId)])];this.closeApprovalWindow(),this.fileAccess=null,this.consentPending=!1;try{await this.closeSlots()}catch(p){throw this.failSignOut(),p}this.check();let a="not_paired";if(t&&i?.state==="paired"){try{a=await t.signOutInstallation()}catch{a="incomplete"}this.check()}this.flow=null,this.installation=null;try{await t?.close()}catch{}this.flowLifetime.abort(),this.flowLifetime=new AbortController,await this.installationLease?.release(),this.installationLease=null,this.attested=!1,this.acknowledged=!1,this.freshApproval=!1,this.authorizationStartedAt=null,this.receiptRead=null,this.foregroundRead=null,this.forgotten.clear(),this.removedScopes.clear();let c=this.options,l=await P1({cpOrigin:c.cpOrigin,appId:c.appId,...c.owner===void 0?{}:{owner:c.owner},...c.storageNamespace===void 0?{}:{storageNamespace:c.storageNamespace},accountId:i?.accountId??null,connectorId:o,installationId:i?.installationId??null,deviceId:i?.deviceId??null,collectionIds:r,databases:c.localDatabases??[],...c.recoveryFor?{isolated:!0}:{}});if(this.check(),!l.ledger)throw this.failSignOut(),A("unavailable","This device couldn't remove its sign-in data.","sign_out_failed");return this.emit(Object.freeze({status:"signed_out",signIn:null,collections:Object.freeze([]),selectedCollectionId:null,problem:null,timing:null,signOutResult:Object.freeze({server:a,local:l.complete?"erased":"incomplete",webPush:s})})),this.getSnapshot()},!0))}failSignOut(){if(this.closing||this.options.signal.aborted)return;let e=null;try{e=this.flow?.view()??null}catch{e=null}let{problemDetail:t,...i}=this.base;this.focus=null,this.emit(Object.freeze({...i,status:"blocked",signIn:e,selectedCollectionId:null,problem:"sign_out_failed"}))}emit(e){if(this.check(),this.base=e,e.status==="signed_out"){for(let t of[...this.slots.values()])this.deleteSlot(t);this.focus=null}this.changed()}close(){if(this.closing)return this.closing;let e=this.pending;return this.foregroundRead=null,this.stopPolling(),this.options.signal.removeEventListener("abort",this.onAbort),this.closing=Promise.resolve().then(async()=>{await e?.catch(()=>{}),await this.closeSlots(),this.focus=null,await this.flow?.close(),this.flowLifetime.abort(),this.flow=null,this.installation=null,await this.installationLease?.release(),this.installationLease=null,this.base=Object.freeze({status:"closed",signIn:null,collections:Object.freeze([]),selectedCollectionId:null,problem:null,timing:this.base.timing}),this.snapshotValue=this.base;for(let t of[...this.listeners])try{t()}catch{}this.listeners.clear()}),this.lifetime.abort(),this.closing}};gu();wu();return Aq(R4);})();
|