Files
personal-git/.obsidian/plugins/obsidian-livesync/main.js
T

19 lines
3.6 MiB
Plaintext
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD AND TERSER
if you want to view the source, please visit the github repository of this plugin
*/
"use strict";function cloneQuery2(query3){return Object.keys(query3).reduce((carry,paramName)=>{const param=query3[paramName];return{...carry,[paramName]:Array.isArray(param)?[...param]:param}},{})}function parseQueryString(querystring){const query3={};querystring=querystring.replace(/^\?/,"");if(querystring)for(const pair of querystring.split("&")){let[key3,value=null]=pair.split("=");key3=decodeURIComponent(key3);value&&(value=decodeURIComponent(value));key3 in query3?Array.isArray(query3[key3])?query3[key3].push(value):query3[key3]=[query3[key3],value]:query3[key3]=value}return query3}function toBase64(_input){let input;input="string"==typeof _input?fromUtf8(_input):_input;const isArrayLike="object"==typeof input&&"number"==typeof input.length,isUint8Array="object"==typeof input&&"number"==typeof input.byteOffset&&"number"==typeof input.byteLength;if(!isArrayLike&&!isUint8Array)throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");let str="";for(let i3=0;i3<input.length;i3+=3){let bits2=0,bitLength=0;for(let j2=i3,limit=Math.min(i3+3,input.length);j2<limit;j2++){bits2|=input[j2]<<(limit-j2-1)*bitsPerByte;bitLength+=bitsPerByte}const bitClusterCount=Math.ceil(bitLength/bitsPerLetter);bits2<<=bitClusterCount*bitsPerLetter-bitLength;for(let k2=1;k2<=bitClusterCount;k2++){const offset=(bitClusterCount-k2)*bitsPerLetter;str+=alphabetByValue[(bits2&maxLetterValue<<offset)>>offset]}str+="==".slice(0,4-bitClusterCount)}return str}function bindUint8ArrayBlobAdapter(toUtf82,fromUtf85,toBase643,fromBase643){return class Uint8ArrayBlobAdapter2 extends Uint8Array{static fromString(source2,encoding="utf-8"){if("string"==typeof source2)return"base64"===encoding?Uint8ArrayBlobAdapter2.mutate(fromBase643(source2)):Uint8ArrayBlobAdapter2.mutate(fromUtf85(source2));throw new Error(`Unsupported conversion from ${typeof source2} to Uint8ArrayBlobAdapter.`)}static mutate(source2){Object.setPrototypeOf(source2,Uint8ArrayBlobAdapter2.prototype);return source2}transformToString(encoding="utf-8"){return"base64"===encoding?toBase643(this):toUtf82(this)}}}function bindV4(getRandomValues2){return"undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID?()=>crypto.randomUUID():()=>{const rnds=new Uint8Array(16);getRandomValues2(rnds);rnds[6]=15&rnds[6]|64;rnds[8]=63&rnds[8]|128;return decimalToHex[rnds[0]]+decimalToHex[rnds[1]]+decimalToHex[rnds[2]]+decimalToHex[rnds[3]]+"-"+decimalToHex[rnds[4]]+decimalToHex[rnds[5]]+"-"+decimalToHex[rnds[6]]+decimalToHex[rnds[7]]+"-"+decimalToHex[rnds[8]]+decimalToHex[rnds[9]]+"-"+decimalToHex[rnds[10]]+decimalToHex[rnds[11]]+decimalToHex[rnds[12]]+decimalToHex[rnds[13]]+decimalToHex[rnds[14]]+decimalToHex[rnds[15]]}}function dateToUtcString(date2){const year2=date2.getUTCFullYear(),month=date2.getUTCMonth(),dayOfWeek=date2.getUTCDay(),dayOfMonthInt=date2.getUTCDate(),hoursInt=date2.getUTCHours(),minutesInt=date2.getUTCMinutes(),secondsInt=date2.getUTCSeconds(),dayOfMonthString=dayOfMonthInt<10?`0${dayOfMonthInt}`:`${dayOfMonthInt}`,hoursString=hoursInt<10?`0${hoursInt}`:`${hoursInt}`,minutesString=minutesInt<10?`0${minutesInt}`:`${minutesInt}`,secondsString=secondsInt<10?`0${secondsInt}`:`${secondsInt}`;return`${DAYS[dayOfWeek]}, ${dayOfMonthString} ${MONTHS[month]} ${year2} ${hoursString}:${minutesString}:${secondsString} GMT`}function quoteHeader(part){(part.includes(",")||part.includes('"'))&&(part=`"${part.replace(/"/g,'\\"')}"`);return part}function range3(v2,min2,max3){const _v=Number(v2);if(_v<min2||_v>max3)throw new Error(`Value ${_v} out of range [${min2}, ${max3}]`)}function splitEvery(value,delimiter,numDelimiters){if(numDelimiters<=0||!Number.isInteger(numDelimiters))throw new Error("Invalid number of delimiters ("+numDelimiters+") for splitEvery.");const segments=value.split(delimiter);if(1===numDelimiters)return segments;const compoundSegments=[];let currentSegment="";for(let i3=0;i3<segments.length;i3++){""===currentSegment?currentSegment=segments[i3]:currentSegment+=delimiter+segments[i3];if((i3+1)%numDelimiters===0){compoundSegments.push(currentSegment);currentSegment=""}}""!==currentSegment&&compoundSegments.push(currentSegment);return compoundSegments}function fromHex(encoded){if(encoded.length%2!=0)throw new Error("Hex encoded strings must have an even number length");const out=new Uint8Array(encoded.length/2);for(let i3=0;i3<encoded.length;i3+=2){const encodedByte=encoded.slice(i3,i3+2).toLowerCase();if(!(encodedByte in HEX_TO_SHORT))throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`);out[i3/2]=HEX_TO_SHORT[encodedByte]}return out}function toHex2(bytes){let out="";for(let i3=0;i3<bytes.byteLength;i3++)out+=SHORT_TO_HEX[bytes[i3]];return out}function bindGetEndpointFromInstructions(getEndpointFromConfig3){return async(commandInput,instructionsSupplier,clientConfig,context2)=>{if(!clientConfig.isCustomEndpoint){let endpointFromConfig;endpointFromConfig=clientConfig.serviceConfiguredEndpoint?await clientConfig.serviceConfiguredEndpoint():await getEndpointFromConfig3(clientConfig.serviceId);if(endpointFromConfig){clientConfig.endpoint=()=>Promise.resolve(toEndpointV1(endpointFromConfig));clientConfig.isCustomEndpoint=!0}}const endpointParams=await resolveParams(commandInput,instructionsSupplier,clientConfig);if("function"!=typeof clientConfig.endpointProvider)throw new Error("config.endpointProvider is not set.");const endpoint=clientConfig.endpointProvider(endpointParams,context2);if(clientConfig.isCustomEndpoint&&clientConfig.endpoint){const customEndpoint=await clientConfig.endpoint();if(null==customEndpoint?void 0:customEndpoint.headers){null!=endpoint.headers||(endpoint.headers={});for(const[name,value]of Object.entries(customEndpoint.headers))endpoint.headers[name]=Array.isArray(value)?value:[value]}}return endpoint}}function setFeature2(context2,feature,value){context2.__smithy_context?context2.__smithy_context.features||(context2.__smithy_context.features={}):context2.__smithy_context={features:{}};context2.__smithy_context.features[feature]=value}function bindEndpointMiddleware(getEndpointFromConfig3){const getEndpointFromInstructions3=bindGetEndpointFromInstructions(getEndpointFromConfig3);return({config,instructions})=>(next2,context2)=>async args=>{var _a13,_b6,_c3;config.isCustomEndpoint&&setFeature2(context2,"ENDPOINT_OVERRIDE","N");const endpoint=await getEndpointFromInstructions3(args.input,{getEndpointParameterInstructions:()=>instructions},{...config},context2);context2.endpointV2=endpoint;context2.authSchemes=null==(_a13=endpoint.properties)?void 0:_a13.authSchemes;const authScheme=null==(_b6=context2.authSchemes)?void 0:_b6[0];if(authScheme){context2.signing_region=authScheme.signingRegion;context2.signing_service=authScheme.signingName;const smithyContext=getSmithyContext(context2),httpAuthOption=null==(_c3=null==smithyContext?void 0:smithyContext.selectedHttpAuthScheme)?void 0:_c3.httpAuthOption;httpAuthOption&&(httpAuthOption.signingProperties=Object.assign(httpAuthOption.signingProperties||{},{signing_region:authScheme.signingRegion,signingRegion:authScheme.signingRegion,signing_service:authScheme.signingName,signingName:authScheme.signingName,signingRegionSet:authScheme.signingRegionSet},authScheme.properties))}return next2({...args})}}function bindGetEndpointPlugin(getEndpointFromConfig3){const endpointMiddleware3=bindEndpointMiddleware(getEndpointFromConfig3);return(config,instructions)=>({applyToStack:clientStack=>{clientStack.addRelativeTo(endpointMiddleware3({config,instructions}),endpointMiddlewareOptions)}})}function bindResolveEndpointConfig(getEndpointFromConfig3){return input=>{var _a13;const tls=null==(_a13=input.tls)||_a13,{endpoint,useDualstackEndpoint,useFipsEndpoint}=input,customEndpointProvider=null!=endpoint?async()=>toEndpointV1(await normalizeProvider(endpoint)()):void 0,isCustomEndpoint=!!endpoint,resolvedConfig=Object.assign(input,{endpoint:customEndpointProvider,tls,isCustomEndpoint,useDualstackEndpoint:normalizeProvider(null!=useDualstackEndpoint&&useDualstackEndpoint),useFipsEndpoint:normalizeProvider(null!=useFipsEndpoint&&useFipsEndpoint)});let configuredEndpointPromise;resolvedConfig.serviceConfiguredEndpoint=async()=>{input.serviceId&&!configuredEndpointPromise&&(configuredEndpointPromise=getEndpointFromConfig3(input.serviceId));return configuredEndpointPromise};return resolvedConfig}}async function collectBlob(blob){const base64=await readToBase64(blob),arrayBuffer=fromBase64(base64);return new Uint8Array(arrayBuffer)}async function collectStream(stream){const chunks=[],reader=stream.getReader();let isDone=!1,length=0;for(;!isDone;){const{done,value}=await reader.read();if(value){chunks.push(value);length+=value.length}isDone=done}const collected=new Uint8Array(length);let offset=0;for(const chunk of chunks){collected.set(chunk,offset);offset+=chunk.length}return collected}function readToBase64(blob){return new Promise((resolve,reject)=>{const reader=new FileReader;reader.onloadend=()=>{var _a13;if(2!==reader.readyState)return reject(new Error("Reader aborted too early"));const result=null!=(_a13=reader.result)?_a13:"",commaIndex=result.indexOf(","),dataOffset=commaIndex>-1?commaIndex+1:result.length;resolve(result.substring(dataOffset))};reader.onabort=()=>reject(new Error("Read aborted"));reader.onerror=()=>reject(reader.error);reader.readAsDataURL(blob)})}function __extends(d4,b3){function __(){this.constructor=d4}if("function"!=typeof b3&&null!==b3)throw new TypeError("Class extends value "+String(b3)+" is not a constructor or null");extendStatics(d4,b3);d4.prototype=null===b3?Object.create(b3):(__.prototype=b3.prototype,new __)}function __rest(s2,e3){var p2,i3,t9={};for(p2 in s2)Object.prototype.hasOwnProperty.call(s2,p2)&&e3.indexOf(p2)<0&&(t9[p2]=s2[p2]);if(null!=s2&&"function"==typeof Object.getOwnPropertySymbols)for(i3=0,p2=Object.getOwnPropertySymbols(s2);i3<p2.length;i3++)e3.indexOf(p2[i3])<0&&Object.prototype.propertyIsEnumerable.call(s2,p2[i3])&&(t9[p2[i3]]=s2[p2[i3]]);return t9}function __decorate(decorators,target,key3,desc){var d4,i3,c3=arguments.length,r4=c3<3?target:null===desc?desc=Object.getOwnPropertyDescriptor(target,key3):desc;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)r4=Reflect.decorate(decorators,target,key3,desc);else for(i3=decorators.length-1;i3>=0;i3--)(d4=decorators[i3])&&(r4=(c3<3?d4(r4):c3>3?d4(target,key3,r4):d4(target,key3))||r4);return c3>3&&r4&&Object.defineProperty(target,key3,r4),r4}function __param(paramIndex,decorator){return function(target,key3){decorator(target,key3,paramIndex)}}function __esDecorate(ctor,descriptorIn,decorators,contextIn,initializers,extraInitializers){function accept(f4){if(void 0!==f4&&"function"!=typeof f4)throw new TypeError("Function expected");return f4}var _,i3,context2,p2,result,kind=contextIn.kind,key3="getter"===kind?"get":"setter"===kind?"set":"value",target=!descriptorIn&&ctor?contextIn.static?ctor:ctor.prototype:null,descriptor=descriptorIn||(target?Object.getOwnPropertyDescriptor(target,contextIn.name):{}),done=!1;for(i3=decorators.length-1;i3>=0;i3--){context2={};for(p2 in contextIn)context2[p2]="access"===p2?{}:contextIn[p2];for(p2 in contextIn.access)context2.access[p2]=contextIn.access[p2];context2.addInitializer=function(f4){if(done)throw new TypeError("Cannot add initializers after decoration has completed");extraInitializers.push(accept(f4||null))};result=(0,decorators[i3])("accessor"===kind?{get:descriptor.get,set:descriptor.set}:descriptor[key3],context2);if("accessor"===kind){if(void 0===result)continue;if(null===result||"object"!=typeof result)throw new TypeError("Object expected");(_=accept(result.get))&&(descriptor.get=_);(_=accept(result.set))&&(descriptor.set=_);(_=accept(result.init))&&initializers.unshift(_)}else(_=accept(result))&&("field"===kind?initializers.unshift(_):descriptor[key3]=_)}target&&Object.defineProperty(target,contextIn.name,descriptor);done=!0}function __runInitializers(thisArg,initializers,value){var i3,useValue=arguments.length>2;for(i3=0;i3<initializers.length;i3++)value=useValue?initializers[i3].call(thisArg,value):initializers[i3].call(thisArg);return useValue?value:void 0}function __propKey(x3){return"symbol"==typeof x3?x3:"".concat(x3)}function __setFunctionName(f4,name,prefix){"symbol"==typeof name&&(name=name.description?"[".concat(name.description,"]"):"");return Object.defineProperty(f4,"name",{configurable:!0,value:prefix?"".concat(prefix," ",name):name})}function __metadata(metadataKey,metadataValue){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(metadataKey,metadataValue)}function __awaiter(thisArg,_arguments,P3,generator){function adopt(value){return value instanceof P3?value:new P3(function(resolve){resolve(value)})}return new(P3||(P3=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e3){reject(e3)}}function rejected(value){try{step(generator.throw(value))}catch(e3){reject(e3)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})}function __generator(thisArg,body){function verb(n3){return function(v2){return step([n3,v2])}}function step(op){if(f4)throw new TypeError("Generator is already executing.");for(;g2&&(g2=0,op[0]&&(_=0)),_;)try{if(f4=1,y2&&(t9=2&op[0]?y2.return:op[0]?y2.throw||((t9=y2.return)&&t9.call(y2),0):y2.next)&&!(t9=t9.call(y2,op[1])).done)return t9;(y2=0,t9)&&(op=[2&op[0],t9.value]);switch(op[0]){case 0:case 1:t9=op;break;case 4:_.label++;return{value:op[1],done:!1};case 5:_.label++;y2=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t9=_.trys,t9=t9.length>0&&t9[t9.length-1])&&(6===op[0]||2===op[0])){_=0;continue}if(3===op[0]&&(!t9||op[1]>t9[0]&&op[1]<t9[3])){_.label=op[1];break}if(6===op[0]&&_.label<t9[1]){_.label=t9[1];t9=op;break}if(t9&&_.label<t9[2]){_.label=t9[2];_.ops.push(op);break}t9[2]&&_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e3){op=[6,e3];y2=0}finally{f4=t9=0}if(5&op[0])throw op[1];return{value:op[0]?op[1]:void 0,done:!0}}var f4,y2,t9,_={label:0,sent:function(){if(1&t9[0])throw t9[1];return t9[1]},trys:[],ops:[]},g2=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return g2.next=verb(0),g2.throw=verb(1),g2.return=verb(2),"function"==typeof Symbol&&(g2[Symbol.iterator]=function(){return this}),g2}function __exportStar(m3,o2){for(var p2 in m3)"default"===p2||Object.prototype.hasOwnProperty.call(o2,p2)||__createBinding(o2,m3,p2)}function __values(o2){var s2="function"==typeof Symbol&&Symbol.iterator,m3=s2&&o2[s2],i3=0;if(m3)return m3.call(o2);if(o2&&"number"==typeof o2.length)return{next:function(){o2&&i3>=o2.length&&(o2=void 0);return{value:o2&&o2[i3++],done:!o2}}};throw new TypeError(s2?"Object is not iterable.":"Symbol.iterator is not defined.")}function __read(o2,n3){var i3,r4,ar2,e3,m3="function"==typeof Symbol&&o2[Symbol.iterator];if(!m3)return o2;i3=m3.call(o2),ar2=[];try{for(;(void 0===n3||n3-- >0)&&!(r4=i3.next()).done;)ar2.push(r4.value)}catch(error){e3={error}}finally{try{r4&&!r4.done&&(m3=i3.return)&&m3.call(i3)}finally{if(e3)throw e3.error}}return ar2}function __spread(){for(var ar2=[],i3=0;i3<arguments.length;i3++)ar2=ar2.concat(__read(arguments[i3]));return ar2}function __spreadArrays(){var s2,i3,il,r4,k2,a2,j2,jl;for(s2=0,i3=0,il=arguments.length;i3<il;i3++)s2+=arguments[i3].length;for(r4=Array(s2),k2=0,i3=0;i3<il;i3++)for(a2=arguments[i3],j2=0,jl=a2.length;j2<jl;j2++,k2++)r4[k2]=a2[j2];return r4}function __spreadArray(to,from,pack2){if(pack2||2===arguments.length)for(var ar2,i3=0,l2=from.length;i3<l2;i3++)if(ar2||!(i3 in from)){ar2||(ar2=Array.prototype.slice.call(from,0,i3));ar2[i3]=from[i3]}return to.concat(ar2||Array.prototype.slice.call(from))}function __await(v2){return this instanceof __await?(this.v=v2,this):new __await(v2)}function __asyncGenerator(thisArg,_arguments,generator){function verb(n3,f4){if(g2[n3]){i3[n3]=function(v2){return new Promise(function(a2,b3){q2.push([n3,v2,a2,b3])>1||resume(n3,v2)})};f4&&(i3[n3]=f4(i3[n3]))}}function resume(n3,v2){try{step(g2[n3](v2))}catch(e3){settle(q2[0][3],e3)}}function step(r4){r4.value instanceof __await?Promise.resolve(r4.value.v).then(fulfill,reject):settle(q2[0][2],r4)}function fulfill(value){resume("next",value)}function reject(value){resume("throw",value)}function settle(f4,v2){(f4(v2),q2.shift(),q2.length)&&resume(q2[0][0],q2[0][1])}if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i3,g2=generator.apply(thisArg,_arguments||[]),q2=[];return i3=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),verb("next"),verb("throw"),verb("return",function awaitReturn(f4){return function(v2){return Promise.resolve(v2).then(f4,reject)}}),i3[Symbol.asyncIterator]=function(){return this},i3}function __asyncDelegator(o2){function verb(n3,f4){i3[n3]=o2[n3]?function(v2){return(p2=!p2)?{value:__await(o2[n3](v2)),done:!1}:f4?f4(v2):v2}:f4}var i3,p2;return i3={},verb("next"),verb("throw",function(e3){throw e3}),verb("return"),i3[Symbol.iterator]=function(){return this},i3}function __asyncValues(o2){function verb(n3){i3[n3]=o2[n3]&&function(v2){return new Promise(function(resolve,reject){v2=o2[n3](v2),settle(resolve,reject,v2.done,v2.value)})}}function settle(resolve,reject,d4,v2){Promise.resolve(v2).then(function(v3){resolve({value:v3,done:d4})},reject)}if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i3,m3=o2[Symbol.asyncIterator];return m3?m3.call(o2):(o2=__values(o2),i3={},verb("next"),verb("throw"),verb("return"),i3[Symbol.asyncIterator]=function(){return this},i3)}function __makeTemplateObject(cooked,raw){Object.defineProperty?Object.defineProperty(cooked,"raw",{value:raw}):cooked.raw=raw;return cooked}function __importStar(mod){var result,k2,i3;if(mod&&mod.__esModule)return mod;result={};if(null!=mod)for(k2=ownKeys(mod),i3=0;i3<k2.length;i3++)"default"!==k2[i3]&&__createBinding(result,mod,k2[i3]);__setModuleDefault(result,mod);return result}function __importDefault(mod){return mod&&mod.__esModule?mod:{default:mod}}function __classPrivateFieldGet(receiver,state2,kind,f4){if("a"===kind&&!f4)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof state2?receiver!==state2||!f4:!state2.has(receiver))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===kind?f4:"a"===kind?f4.call(receiver):f4?f4.value:state2.get(receiver)}function __classPrivateFieldSet(receiver,state2,value,kind,f4){if("m"===kind)throw new TypeError("Private method is not writable");if("a"===kind&&!f4)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof state2?receiver!==state2||!f4:!state2.has(receiver))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===kind?f4.call(receiver,value):f4?f4.value=value:state2.set(receiver,value),value}function __classPrivateFieldIn(state2,receiver){if(null===receiver||"object"!=typeof receiver&&"function"!=typeof receiver)throw new TypeError("Cannot use 'in' operator on non-object");return"function"==typeof state2?receiver===state2:state2.has(receiver)}function __addDisposableResource(env,value,async2){if(null!=value){if("object"!=typeof value&&"function"!=typeof value)throw new TypeError("Object expected.");var dispose,inner;if(async2){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");dispose=value[Symbol.asyncDispose]}if(void 0===dispose){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");dispose=value[Symbol.dispose];async2&&(inner=dispose)}if("function"!=typeof dispose)throw new TypeError("Object not disposable.");inner&&(dispose=function(){try{inner.call(this)}catch(e3){return Promise.reject(e3)}});env.stack.push({value,dispose,async:async2})}else async2&&env.stack.push({async:!0});return value}function __disposeResources(env){function fail(e3){env.error=env.hasError?new _SuppressedError(e3,env.error,"An error was suppressed during disposal."):e3;env.hasError=!0}var r4,s2=0;return function next2(){for(;r4=env.stack.pop();)try{if(!r4.async&&1===s2)return s2=0,env.stack.push(r4),Promise.resolve().then(next2);if(r4.dispose){var result=r4.dispose.call(r4.value);if(r4.async)return s2|=2,Promise.resolve(result).then(next2,function(e3){fail(e3);return next2()})}else s2|=1}catch(e3){fail(e3)}if(1===s2)return env.hasError?Promise.reject(env.error):Promise.resolve();if(env.hasError)throw env.error}()}function __rewriteRelativeImportExtension(path2,preserveJsx){return"string"==typeof path2&&/^\.\.?\//.test(path2)?path2.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(m3,tsx,d4,ext2,cm2){return tsx?preserveJsx?".jsx":".js":!d4||ext2&&cm2?d4+ext2+"."+cm2.toLowerCase()+"js":m3}):path2}function convertToBuffer(data){return data instanceof Uint8Array?data:"string"==typeof data?fromUtf83(data):ArrayBuffer.isView(data)?new Uint8Array(data.buffer,data.byteOffset,data.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(data)}function isEmptyData(data){return"string"==typeof data?0===data.length:0===data.byteLength}function numToUint8(num){return new Uint8Array([(4278190080&num)>>24,(16711680&num)>>16,(65280&num)>>8,255&num])}function uint32ArrayFrom(a_lookUpTable2){var return_array,a_index;if(!Uint32Array.from){return_array=new Uint32Array(a_lookUpTable2.length);a_index=0;for(;a_index<a_lookUpTable2.length;){return_array[a_index]=a_lookUpTable2[a_index];a_index+=1}return return_array}return Uint32Array.from(a_lookUpTable2)}function negate(bytes){for(let i3=0;i3<8;i3++)bytes[i3]^=255;for(let i3=7;i3>-1;i3--){bytes[i3]++;if(0!==bytes[i3])break}}function splitMessage({byteLength,byteOffset,buffer}){if(byteLength<MINIMUM_MESSAGE_LENGTH)throw new Error("Provided message too short to accommodate event stream message overhead");const view=new DataView(buffer,byteOffset,byteLength),messageLength=view.getUint32(0,!1);if(byteLength!==messageLength)throw new Error("Reported message length does not match received message length");const headerLength=view.getUint32(PRELUDE_MEMBER_LENGTH,!1),expectedPreludeChecksum=view.getUint32(PRELUDE_LENGTH,!1),expectedMessageChecksum=view.getUint32(byteLength-CHECKSUM_LENGTH,!1),checksummer=(new Crc32).update(new Uint8Array(buffer,byteOffset,PRELUDE_LENGTH));if(expectedPreludeChecksum!==checksummer.digest())throw new Error(`The prelude checksum specified in the message (${expectedPreludeChecksum}) does not match the calculated CRC32 checksum (${checksummer.digest()})`);checksummer.update(new Uint8Array(buffer,byteOffset+PRELUDE_LENGTH,byteLength-(PRELUDE_LENGTH+CHECKSUM_LENGTH)));if(expectedMessageChecksum!==checksummer.digest())throw new Error(`The message checksum (${checksummer.digest()}) did not match the expected value of ${expectedMessageChecksum}`);return{headers:new DataView(buffer,byteOffset+PRELUDE_LENGTH+CHECKSUM_LENGTH,headerLength),body:new Uint8Array(buffer,byteOffset+PRELUDE_LENGTH+CHECKSUM_LENGTH+headerLength,messageLength-headerLength-(PRELUDE_LENGTH+CHECKSUM_LENGTH+CHECKSUM_LENGTH))}}function getChunkedStream(source2){let currentMessageTotalLength=0,currentMessagePendingLength=0,currentMessage=null,messageLengthBuffer=null;const allocateMessage=size=>{if("number"!=typeof size)throw new Error("Attempted to allocate an event message where size was not a number: "+size);currentMessageTotalLength=size;currentMessagePendingLength=4;currentMessage=new Uint8Array(size);const currentMessageView=new DataView(currentMessage.buffer);currentMessageView.setUint32(0,size,!1)};return{[Symbol.asyncIterator]:async function*(){const sourceIterator=source2[Symbol.asyncIterator]();for(;;){const{value,done}=await sourceIterator.next();if(done){if(!currentMessageTotalLength)return;if(currentMessageTotalLength!==currentMessagePendingLength)throw new Error("Truncated event message received.");yield currentMessage;return}const chunkLength=value.length;let currentOffset=0;for(;currentOffset<chunkLength;){if(!currentMessage){const bytesRemaining=chunkLength-currentOffset;messageLengthBuffer||(messageLengthBuffer=new Uint8Array(4));const numBytesForTotal=Math.min(4-currentMessagePendingLength,bytesRemaining);messageLengthBuffer.set(value.slice(currentOffset,currentOffset+numBytesForTotal),currentMessagePendingLength);currentMessagePendingLength+=numBytesForTotal;currentOffset+=numBytesForTotal;if(currentMessagePendingLength<4)break;allocateMessage(new DataView(messageLengthBuffer.buffer).getUint32(0,!1));messageLengthBuffer=null}const numBytesToWrite=Math.min(currentMessageTotalLength-currentMessagePendingLength,chunkLength-currentOffset);currentMessage.set(value.slice(currentOffset,currentOffset+numBytesToWrite),currentMessagePendingLength);currentMessagePendingLength+=numBytesToWrite;currentOffset+=numBytesToWrite;if(currentMessageTotalLength&&currentMessageTotalLength===currentMessagePendingLength){yield currentMessage;currentMessage=null;currentMessageTotalLength=0;currentMessagePendingLength=0}}}}}}function getUnmarshalledStream(source2,options){const messageUnmarshaller=getMessageUnmarshaller(options.deserializer,options.toUtf8);return{[Symbol.asyncIterator]:async function*(){for await(const chunk of source2){const message=options.eventStreamCodec.decode(chunk),type=await messageUnmarshaller(message);void 0!==type&&(yield type)}}}}function getMessageUnmarshaller(deserializer,toUtf82){return async function(message){const{value:messageType}=message.headers[":message-type"];if("error"===messageType){const unmodeledError=new Error(message.headers[":error-message"].value||"UnknownError");unmodeledError.name=message.headers[":error-code"].value;throw unmodeledError}if("exception"===messageType){const code=message.headers[":exception-type"].value,exception={[code]:message},deserializedException=await deserializer(exception);if(deserializedException.$unknown){const error=new Error(toUtf82(message.body));error.name=code;throw error}throw deserializedException[code]}if("event"===messageType){const event2={[message.headers[":event-type"].value]:message},deserialized=await deserializer(event2);if(deserialized.$unknown)return;return deserialized}throw Error(`Unrecognizable event type: ${message.headers[":event-type"].value}`)}}function setGlobalLogFunction(logger2){_logger=logger2}function Logger(message,level,key3){_logger(message,level,key3)}function __logger(message,baseLevel,flagsOrKey,key3){let level=baseLevel;"string"==typeof flagsOrKey?key3=flagsOrKey:void 0!==flagsOrKey&&(level|=flagsOrKey);_logger(message,level,key3)}function info(message,flagsOrKey,key3){__logger(message,LEVEL_INFO,flagsOrKey,key3)}function debug(message,flagsOrKey,key3){__logger(message,LEVEL_INFO,flagsOrKey,key3)}function verbose(message,flagsOrKey,key3){__logger(message,LEVEL_INFO,flagsOrKey,key3)}function notice(message,flagsOrKey,key3){__logger(message,LEVEL_INFO,flagsOrKey,key3)}function normaliseP2PMaxWirePayloadBytes(value){return"number"!=typeof value||!Number.isSafeInteger(value)||value<P2PMessageSizePresets_MaximumCompatibility||value>P2PMessageSizePresets_Standard?P2PMessageSizePresets_Standard:value}function normaliseP2PConnectionPath(value){return value===P2PConnectionPaths_Relay?P2PConnectionPaths_Relay:P2PConnectionPaths_Automatic}function splitP2PTurnServerUrls(value){return value.split(",").map(entry=>entry.trim()).filter(entry=>entry.length>0)}function isValidP2PTurnServerUrl(value){const candidate=value.trim();if(!candidate||/\s/.test(candidate))return!1;try{const parsed=new URL(candidate),protocol=parsed.protocol.toLowerCase();return("turn:"===protocol||"turns:"===protocol)&&(parsed.hostname||parsed.pathname).length>0}catch(e3){return!1}}function hasValidP2PTurnServerUrl(value){return splitP2PTurnServerUrls(value).some(isValidP2PTurnServerUrl)}function createNewVaultSettings(){return{...NEW_VAULT_SETTINGS,remoteConfigurations:{},pluginSyncExtendedSetting:{}}}function cloneSettings(source2,fallbacks){var _a13;return{...fallbacks,...source2,remoteConfigurations:Object.fromEntries(Object.entries(null!=(_a13=source2.remoteConfigurations)?_a13:fallbacks.remoteConfigurations).map(([id,config])=>[id,{...config}])),pluginSyncExtendedSetting:{...fallbacks.pluginSyncExtendedSetting,...source2.pluginSyncExtendedSetting}}}function storedSettingVersion(settings){const version2=settings.settingVersion;return"number"==typeof version2&&Number.isSafeInteger(version2)&&version2>=SETTING_VERSION_INITIAL?version2:SETTING_VERSION_INITIAL}function isBlankSettings(settings){return void 0===settings||0===Object.keys(settings).length}function inferLegacyConfiguredState(settings){const completed={...SETTINGS_SCHEMA_DEFAULTS,...settings};return JSON.stringify(completed)!==JSON.stringify(SETTINGS_SCHEMA_DEFAULTS)}function prepareSettingsForLoad(storedSettings){var _a13;if(isBlankSettings(storedSettings))return{settings:createNewVaultSettings(),sourceVersion:CURRENT_SETTING_VERSION,targetVersion:CURRENT_SETTING_VERSION,isNewVault:!0,isFromFutureSchema:!1,changed:!1,requiresSyncReview:!1,reviewReasons:[]};const source2={...storedSettings},sourceVersion=storedSettingVersion(source2);if(sourceVersion>CURRENT_SETTING_VERSION){const reviewReasons2=[{code:SettingsMigrationReviewCodes_FutureSchema,fromVersion:sourceVersion,toVersion:CURRENT_SETTING_VERSION}];return{settings:cloneSettings(source2,SETTINGS_SCHEMA_DEFAULTS),sourceVersion,targetVersion:sourceVersion,isNewVault:!1,isFromFutureSchema:!0,changed:!1,requiresSyncReview:!0,reviewReasons:reviewReasons2}}let migrated=source2,targetVersion=sourceVersion;const reviewReasons=[];for(const migration of SETTINGS_MIGRATIONS){if(targetVersion>=migration.toVersion)continue;const reason=null==(_a13=migration.reviewReason)?void 0:_a13.call(migration,migrated,targetVersion);reason&&reviewReasons.push(reason);migrated=migration.apply(migrated);targetVersion=migration.toVersion;migrated.settingVersion=targetVersion}if(targetVersion!==CURRENT_SETTING_VERSION)throw new Error(`No setting migration reaches schema ${CURRENT_SETTING_VERSION} from schema ${sourceVersion}.`);const normalisedConfiguredState=void 0===migrated.isConfigured;normalisedConfiguredState&&(migrated={...migrated,isConfigured:inferLegacyConfiguredState(source2)});const normalisedFilenameCase="boolean"!=typeof migrated.handleFilenameCaseSensitive;normalisedFilenameCase&&(migrated={...migrated,handleFilenameCaseSensitive:!1});return{settings:cloneSettings(migrated,SETTINGS_SCHEMA_DEFAULTS),sourceVersion,targetVersion,isNewVault:!1,isFromFutureSchema:!1,changed:sourceVersion!==targetVersion||normalisedConfiguredState||normalisedFilenameCase,requiresSyncReview:reviewReasons.length>0,reviewReasons}}function isMetaEntry(entry){return"children"in entry}function statusDisplay(status){return status?"EXPERIMENTAL"==status?" (Experimental)":"ALPHA"==status?" (Alpha)":"BETA"==status?" (Beta)":` (${status})`:""}function getLanguage2(){return _getLanguage()}function isValidLength(len){return len>=1&&len<=5}function encodeObjectAsArray(obj){if(Array.isArray(obj))return ARRAY_MARKER+encodeAnyArray(obj,!0);const objArray=[...Object.entries(obj)].flat();return OBJECT_MARKER+encodeAnyArray(objArray,!0)}function decodeObjectFromArray(str){if(str[0]==ARRAY_MARKER){const innerEncoded=str.substring(1),arr=decodeAnyArray(innerEncoded);return arr}if(str[0]==OBJECT_MARKER){const innerEncoded=str.substring(1),arr=decodeAnyArray(innerEncoded),entries2=[];for(let i3=0;i3<arr.length;i3+=2){const key3=arr[i3],value=arr[i3+1];entries2.push([key3,value])}return Object.fromEntries(entries2)}return JSON.parse(str)}function encodeAnyArray(obj,safer=!1){const tempArray=obj.map(v2=>{if(void 0===v2)return"u";if(null===v2)return"n";if(!1===v2)return"f";if(!0===v2)return"t";if("number"==typeof v2){const isFloat=!Number.isInteger(v2),b36=v2.toString(36),strNum=v2.toString(),expression=isFloat||b36.length>strNum.length?"n":"N",encodedStr="N"==expression?b36:strNum,len=encodedStr.length.toString(36),lenLen2=len.length;if(!isValidLength(lenLen2))throw new Error("Number length exceeds maximum encodable length of 5 in base36.");const prefix22=prefixMapNumber[expression][lenLen2];return prefix22+len+encodedStr}let str,prefix;if("string"==typeof v2){str=v2;prefix="s"}else{prefix="o";const objectStr=JSON.stringify(v2),containUndefined=-1!==Object.values(v2).indexOf(void 0);if(!safer||containUndefined){const objectEncoded=encodeObjectAsArray(v2),encoded=containUndefined||objectEncoded.length<objectStr.length?objectEncoded:objectStr;str=encoded}else str=objectStr}const length=str.length.toString(36),lenLen=length.length;if(!isValidLength(lenLen))throw new Error("String/Object length exceeds maximum encodable length of 5 in base36.");const prefix2=prefixMapObject[prefix][lenLen];return prefix2+length+str}),w2=tempArray.join("");return w2}function isDecodeMapConstantKey(key3){return key3 in decodeMapConstant}function isDecodePrefixMapNumberKey(key3){return key3 in decodePrefixMapNumber}function isDecodePrefixMapObjectKey(key3){return key3 in decodePrefixMapObject}function decodeAnyArray(str){const result=[];let i3=0;for(;i3<str.length;){const char=str[i3];i3++;if(isDecodeMapConstantKey(char))result.push(decodeMapConstant[char]);else if(isDecodePrefixMapNumberKey(char)){const{prefix,len}=decodePrefixMapNumber[char],lenStr=str.substring(i3,i3+len);i3+=len;const lenNum=parseInt(lenStr,36),value=str.substring(i3,i3+lenNum);i3+=lenNum;"N"==prefix?result.push(parseInt(value,36)):result.push(parseFloat(value))}else{if(!isDecodePrefixMapObjectKey(char))throw new Error(`Invalid encoding at position ${i3-1}: unexpected character '${char}'`);{const{prefix,len}=decodePrefixMapObject[char],lenStr=str.substring(i3,i3+len);i3+=len;const lenNum=parseInt(lenStr,36),value=str.substring(i3,i3+lenNum);i3+=lenNum;"s"==prefix?result.push(value):result.push(decodeObjectFromArray(value))}}}return result}function extractObject(template,obj){const ret={...template};for(const key3 in ret)ret[key3]=obj[key3];return ret}function isObjectDifferent(a2,b3,ignoreUndefined=!1){if(typeof a2!=typeof b3)return!0;if("object"==typeof a2){if(null===a2||null===b3)return a2!==b3;const keys3=[...new Set([...Object.keys(a2),...Object.keys(b3)])];return ignoreUndefined?keys3.map(key3=>void 0!==(null==a2?void 0:a2[key3])&&void 0!==(null==b3?void 0:b3[key3])&&isObjectDifferent(null==a2?void 0:a2[key3],null==b3?void 0:b3[key3])).some(e3=>1==e3):keys3.map(key3=>isObjectDifferent(key3 in a2?a2[key3]:SYMBOL_A,key3 in b3?b3[key3]:SYMBOL_B)).some(e3=>1==e3)}return a2!==b3}function reactiveSource(initialValue){return _reactive({initialValue})}function reactive(expression,initialValue){return _reactive({expression,initialValue})}function resetTopologicalSortCacheFor(ids){ids.forEach(id=>topologicalSortCache.delete(id));topologicalSortCache.forEach((value,key3)=>{ids.includes(key3)||topologicalSortCache.delete(key3)})}function topologicalSort(startNode){if(topologicalSortCache.has(startNode.id)){const ref=topologicalSortCache.get(startNode.id);if(ref){const result2=ref.map(e3=>e3.instance.deref()).filter(e3=>e3);if(result2.length===ref.length)return result2}}const visited=new Set,sorted=[],recursionStack=new Set;(function visit(node){if(!visited.has(node)){if(recursionStack.has(node))throw new Error("Circular dependency detected!");visited.add(node);recursionStack.add(node);for(const dependant of node.dependants)visit(dependant);sorted.push(node);recursionStack.delete(node)}})(startNode);const result=sorted.reverse();topologicalSortCache.set(startNode.id,result.map(e3=>({id:e3.id,instance:new FallbackWeakRef(e3)})));return result}function _reactive({expression,initialValue,isSource}){let value,_isDirty=!1;const id=_reactiveSourceId++,changeHandlers=new Set,instance={id,dependants:new Set,_markDirty(){_isDirty||(_isDirty=!0)},markDirty(){const sorted=topologicalSort(instance);sorted.forEach(node=>node._markDirty())},_rippleChanged(){changeHandlers.forEach(e3=>e3(instance))},rippleChanged(){const sorted=topologicalSort(instance);sorted.forEach(node=>node._rippleChanged())},markClean(){_isDirty=!1},get isDirty(){return _isDirty},get value(){if(context&&!instance.dependants.has(context)){instance.dependants.add(context);resetTopologicalSortCacheFor([instance.id,context.id])}if(_isDirty){if(expression){const oldValue=value,newValue=expression();isObjectDifferent(oldValue,newValue)&&(value=newValue)}instance.markClean()}return value},set value(newValue){if(_isDirty&&!expression)value=newValue;else if(isObjectDifferent(value,newValue)){value=newValue;if(!_isDirty){instance.markDirty();instance.rippleChanged()}}},onChanged(handler){changeHandlers.add(handler)},offChanged(handler){changeHandlers.delete(handler)}};value=function initialize(){const previousContext=context;context=instance;const r4=expression?expression(initialValue):initialValue;context=previousContext;return r4}();return instance}function computed(expression){const v2=reactive(expression);return()=>v2.value}async function isSomeResolved(promises){return 0!=promises.length&&await Promise.race([...promises,Promise.resolve(UNRESOLVED)])!==UNRESOLVED}function fireAndForget(p2){if("function"==typeof p2)return fireAndForget(p2());p2.then(noop).catch(noop)}function yieldMicrotask(){return new Promise(res2=>queueMicrotask(res2))}function yieldAnimationFrame(){return new Promise(res2=>requestAnimationFrame(res2))}function yieldNextAnimationFrame(){if(currentYieldingAnimationFrame)return currentYieldingAnimationFrame;currentYieldingAnimationFrame=(async()=>{const ret=await yieldAnimationFrame();currentYieldingAnimationFrame=void 0;return ret})();return currentYieldingAnimationFrame}function cancelableDelay(timeout,cancel=TIMED_OUT_SIGNAL){let timer;const promise=promiseWithResolvers();timer=setTimeout(()=>{timer=void 0;promise.resolve(cancel)},timeout);return{promise:promise.promise,cancel(){if(timer){clearTimeout(timer);timer=void 0}}}}function serialized(key3,proc){var _a13;const prev=serializedMap.get(key3),p2=promiseWithResolvers();queueCount.set(key3,(null!=(_a13=queueCount.get(key3))?_a13:0)+1);const nextTask=async()=>{try{p2.resolve(await proc())}catch(ex){p2.reject(ex)}finally{const count=queueCount.get(key3)-1;if(0===count){serializedMap.delete(key3);queueCount.delete(key3)}else queueCount.set(key3,count)}};if(prev){const newP=prev.then(()=>nextTask());serializedMap.set(key3,newP)}else serializedMap.set(key3,nextTask());return p2.promise}function shareRunningResult(key3,proc){const prev=shareSerializedMap.get(key3);if(prev)return prev;const p2=promiseWithResolvers();shareSerializedMap.set(key3,p2.promise);const task=async()=>{try{p2.resolve(await proc())}catch(ex){p2.reject(ex)}finally{shareSerializedMap.delete(key3)}};fireAndForget(()=>task());return p2.promise}function skipIfDuplicated(key3,proc){const prev=skipDuplicatedMap.get(key3);if(prev)return Promise.resolve(null);const p2=promiseWithResolvers();skipDuplicatedMap.set(key3,p2.promise);const task=async()=>{try{p2.resolve(await proc())}catch(ex){p2.reject(ex)}finally{skipDuplicatedMap.delete(key3)}};fireAndForget(()=>task());return p2.promise}async function scheduleOnceIfDuplicated(key3,proc){if(isLockAcquired(key3)){waitingProcessMap.set(key3,proc);return Promise.resolve(void 0)}return await serialized(key3,proc).then(()=>{const nextProc=waitingProcessMap.get(key3);if(nextProc){waitingProcessMap.delete(key3);return scheduleOnceIfDuplicated(key3,nextProc)}})}function isLockAcquired(key3){var _a13;const count=null!=(_a13=queueCount.get(key3))?_a13:0;return count>0}async function waitForSignal(id,timeout){return await globalSlipBoard.awaitNext(GENERIC_COMPATIBILITY_SIGNAL,id,{timeout})!==TIMED_OUT_SIGNAL}function sendSignal(id){globalSlipBoard.submit(GENERIC_COMPATIBILITY_SIGNAL,id)}function sendValue(id,result){globalSlipBoard.submit(GENERIC_COMPATIBILITY_VALUE,id,result)}function unwrapTaskResult(result){if("ok"in result)return result.ok;if("err"in result)return result.err;throw new Error("Argument Exception: Could not unwrap")}function isTaskWaiting(task){if(task instanceof Promise)return!1;if(task instanceof Function)return!0;throw new Error("Invalid state")}async function wrapEachProcess(key3,task){try{const r4=await task;return{key:key3,ok:r4}}catch(ex){return{key:key3,err:ex instanceof Error?ex:new Error(`${ex}`)}}}async function*processAllTasksWithConcurrencyLimit(limit,tasks3){const nowProcessing=new Map;let idx2=0;const pendingTasks=tasks3.reverse();for(;pendingTasks.length>0||nowProcessing.size>0;){L2:for(;nowProcessing.size<limit&&pendingTasks.length>0;){const task=pendingTasks.pop();if(void 0===task)break L2;idx2++;const newProcess=isTaskWaiting(task)?task():task,wrappedPromise=wrapEachProcess(idx2,newProcess);nowProcessing.set(idx2,wrappedPromise)}const done=await Promise.race(nowProcessing.values());nowProcessing.delete(done.key);yield done}}async function mapAllTasksWithConcurrencyLimit(limit,tasks3){const results=new Map;for await(const v2 of processAllTasksWithConcurrencyLimit(limit,tasks3))results.set(v2.key,v2);const ret=[...results.entries()].sort((a2,b3)=>a2[0]-b3[0]).map(e3=>e3[1]);return ret}function scheduleTask(key3,timeout,proc,skipIfTaskExist){if(tasks.has(key3)){if(skipIfTaskExist)return;cancelTask(key3)}const newTask=setTimeout(()=>{tasks.delete(key3);proc()},timeout);tasks.set(key3,newTask)}function cancelTask(key3){const old=tasks.get(key3);if(old){clearTimeout(old);tasks.delete(key3)}}function cancelAllTasks(){for(const v2 of tasks.keys())cancelTask(v2)}function cancelPeriodicTask(key3){if(key3 in intervals){clearInterval(intervals[key3]);delete intervals[key3]}}function cancelAllPeriodicTask(){for(const v2 in intervals)cancelPeriodicTask(v2)}function isWaitingForTimeout(key3){return waitingItems.has(key3)}function numeric(str){return isNaN(str)?str.charCodeAt(0):parseInt(str,10)}function escapeBraces(str){return str.replace(slashPattern,escSlash).replace(openPattern,escOpen).replace(closePattern,escClose).replace(commaPattern,escComma).replace(periodPattern,escPeriod)}function unescapeBraces(str){return str.replace(escSlashPattern,"\\").replace(escOpenPattern,"{").replace(escClosePattern,"}").replace(escCommaPattern,",").replace(escPeriodPattern,".")}function parseCommaParts(str){if(!str)return[""];const parts=[],m3=balanced("{","}",str);if(!m3)return str.split(",");const{pre,body,post}=m3,p2=pre.split(",");p2[p2.length-1]+="{"+body+"}";const postParts=parseCommaParts(post);if(post.length){p2[p2.length-1]+=postParts.shift();p2.push.apply(p2,postParts)}parts.push.apply(parts,p2);return parts}function expand(str,options={}){if(!str)return[];const{max:max3=EXPANSION_MAX,maxLength=EXPANSION_MAX_LENGTH}=options;"{}"===str.slice(0,2)&&(str="\\{\\}"+str.slice(2));return expand_(escapeBraces(str),max3,maxLength,!0).map(unescapeBraces)}function embrace(str){return"{"+str+"}"}function isPadded(el){return/^-?0\d/.test(el)}function lte(i3,y2){return i3<=y2}function gte(i3,y2){return i3>=y2}function combine(acc,pre,values2,max3,maxLength,dropEmpties){const out=[];let length=0;for(let a2=0;a2<acc.length;a2++)for(let v2=0;v2<values2.length;v2++){if(out.length>=max3)return out;const expansion=acc[a2]+pre+values2[v2];if(!dropEmpties||expansion){if(length+expansion.length>maxLength)return out;out.push(expansion);length+=expansion.length}}return out}function expandSequence(body,isAlphaSequence,max3,maxLength){const n3=body.split(/\.\./),N3=[];if(void 0===n3[0]||void 0===n3[1])return N3;const x3=numeric(n3[0]),y2=numeric(n3[1]),width=Math.max(n3[0].length,n3[1].length);let incr=3===n3.length&&void 0!==n3[2]?Math.max(Math.abs(numeric(n3[2])),1):1,test=lte;const reverse=y2<x3;if(reverse){incr*=-1;test=gte}const pad2=n3.some(isPadded);let length=0;for(let i3=x3;test(i3,y2)&&N3.length<max3;i3+=incr){let c3;if(isAlphaSequence){c3=String.fromCharCode(i3);"\\"===c3&&(c3="")}else{c3=String(i3);if(pad2){const need=width-c3.length;if(need>0){const z2=new Array(need+1).join("0");c3=i3<0?"-"+z2+c3.slice(1):z2+c3}}}if(length+c3.length>maxLength)break;N3.push(c3);length+=c3.length}return N3}function expand_(str,max3,maxLength,isTop){let acc=[""],dropEmpties=!1,firstGroup=!0;for(;;){const m3=balanced("{","}",str);if(!m3)return combine(acc,str,[""],max3,maxLength,dropEmpties);const pre=m3.pre;if(/\$$/.test(pre)){acc=combine(acc,pre+"{"+m3.body+"}",[""],max3,maxLength,dropEmpties&&!m3.post.length);firstGroup=!1;if(!m3.post.length)break;str=m3.post;continue}const isNumericSequence=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m3.body),isAlphaSequence=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m3.body),isSequence=isNumericSequence||isAlphaSequence,isOptions=m3.body.indexOf(",")>=0;if(!isSequence&&!isOptions){if(m3.post.match(/,(?!,).*\}/)){str=m3.pre+"{"+m3.body+escClose+m3.post;isTop=!0;continue}return combine(acc,pre+"{"+m3.body+"}"+m3.post,[""],max3,maxLength,dropEmpties)}if(firstGroup){dropEmpties=isTop&&!isSequence;firstGroup=!1}let values2;if(isSequence)values2=expandSequence(m3.body,isAlphaSequence,max3,maxLength);else{let n3=parseCommaParts(m3.body);if(1===n3.length&&void 0!==n3[0]){n3=expand_(n3[0],max3,maxLength,!1).map(embrace);if(1===n3.length){acc=combine(acc,pre+n3[0],[""],max3,maxLength,dropEmpties&&!m3.post.length);if(!m3.post.length)break;str=m3.post;continue}}let dropsEmpties=dropEmpties&&!m3.post.length&&!pre;for(let d4=0;dropsEmpties&&d4<acc.length;d4++)acc[d4]&&(dropsEmpties=!1);values2=[];let valuesLength=0;outer:for(let j2=0;j2<n3.length;j2++){const expanded=expand_(n3[j2],max3,maxLength,!1);for(let k2=0;k2<expanded.length;k2++){const v2=expanded[k2];if(!dropsEmpties||v2){if(values2.length>=max3||valuesLength+v2.length>maxLength)break outer;values2.push(v2);valuesLength+=v2.length}}}}acc=combine(acc,pre,values2,max3,maxLength,dropEmpties&&!m3.post.length);if(!m3.post.length)break;str=m3.post}return acc}async function getWebCrypto(){if(webcrypto)return webcrypto;if(compatGlobal.crypto){webcrypto=compatGlobal.crypto;return webcrypto}{const module2=await import("crypto");webcrypto=module2.webcrypto;return webcrypto}}function base64ToArrayBufferNative(base64){if(0===base64.length)return new ArrayBuffer(0);try{if("string"==typeof base64)return Uint8Array.fromBase64(base64).buffer;const bufItems=base64.map(e3=>Uint8Array.fromBase64(e3).buffer),len=bufItems.reduce((p2,c3)=>p2+c3.byteLength,0),joinedArray=new Uint8Array(len);let offset=0;bufItems.forEach(e3=>{joinedArray.set(new Uint8Array(e3),offset);offset+=e3.byteLength});return joinedArray.buffer}catch(ex){Logger("Base64 Decode error",LOG_LEVEL_VERBOSE);Logger(ex,LOG_LEVEL_VERBOSE);return new ArrayBuffer(0)}}function base64ToArrayBufferInternalBrowser(base64){try{const binary_string=globalThis.atob(base64),len=binary_string.length,bytes=new Uint8Array(len);for(let i3=0;i3<len;i3++)bytes[i3]=binary_string.charCodeAt(i3);return bytes.buffer}catch(ex){Logger("Base64 Decode error",LOG_LEVEL_VERBOSE);Logger(ex,LOG_LEVEL_VERBOSE);return new ArrayBuffer(0)}}function arrayBufferToBase64internalBrowser(buffer){if("undefined"==typeof FileReader){const nodeBuffer=globalThis.Buffer;return void 0===nodeBuffer?Promise.reject(new TypeError("Base64 encoding requires FileReader or Buffer support")):Promise.resolve(nodeBuffer.from(buffer.buffer,buffer.byteOffset,buffer.byteLength).toString("base64"))}return new Promise((res2,rej)=>{const blob=new Blob([buffer],{type:"application/octet-binary"}),reader=new FileReader;reader.onload=function(evt){var _a13,_b6;const dataURI=(null==(_b6=null==(_a13=evt.target)?void 0:_a13.result)?void 0:_b6.toString())||"";if(0!=buffer.byteLength&&(""==dataURI||"data:"==dataURI))return rej(new TypeError("Could not parse the encoded string"));const result=dataURI.substring(dataURI.indexOf(",")+1);res2(result)};reader.readAsDataURL(blob)})}function writeString(string){if(string.length>128){const buf=te.encode(string);return buf}const buffer=new Uint8Array(4*string.length),length=string.length;let index6=0,chr=0,idx2=0;for(;idx2<length;){chr=string.charCodeAt(idx2++);if(chr<128)buffer[index6++]=chr;else if(chr<2048){buffer[index6++]=192|chr>>>6;buffer[index6++]=128|63&chr}else if(chr<55296||chr>57343){buffer[index6++]=224|chr>>>12;buffer[index6++]=128|chr>>>6&63;buffer[index6++]=128|63&chr}else{chr=65536+(chr-55296<<10|string.charCodeAt(idx2++)-56320);buffer[index6++]=240|chr>>>18;buffer[index6++]=128|chr>>>12&63;buffer[index6++]=128|chr>>>6&63;buffer[index6++]=128|63&chr}}return buffer.slice(0,index6)}function readString(buffer){const length=buffer.length;if(length>128)return td.decode(buffer);let index6=0;const end=length;let string="";for(;index6<end;){const chunk=[],cEnd=Math.min(index6+QUANTUM,end);for(;index6<cEnd;){const chr=buffer[index6++];if(chr<128)chunk.push(chr);else if(192==(224&chr))chunk.push((31&chr)<<6|63&buffer[index6++]);else if(224==(240&chr))chunk.push((15&chr)<<12|(63&buffer[index6++])<<6|63&buffer[index6++]);else if(240==(248&chr)){let code=(7&chr)<<18|(63&buffer[index6++])<<12|(63&buffer[index6++])<<6|63&buffer[index6++];if(code<65536)chunk.push(code);else{code-=65536;chunk.push((code>>>10)+55296,56320+(1023&code))}}}string+=String.fromCharCode(...chunk)}return string}function*arrayToChunkedArray(arr,chunkLength){const source2=[...arr];for(;source2.length;){const s2=source2.splice(0,chunkLength);yield s2}}function unique(arr){return[...new Set(arr)]}function createTypedArrayReader(buffer){let offset=0;return{read(length){const result=buffer.slice(offset,offset+length);offset+=length;return result},readAll(){const result=buffer.slice(offset);offset=buffer.length;return result}}}function concatUInt8Array(arrays){const totalLength=arrays.reduce((sum2,arr)=>sum2+arr.length,0),result=new Uint8Array(totalLength);let offset=0;for(const array of arrays){result.set(array,offset);offset+=array.length}return result}function decodeToArrayBuffer(src){if(1==src.length)return _decodeToArrayBuffer(src[0]);const bufItems=src.map(e3=>_decodeToArrayBuffer(e3)),len=bufItems.reduce((p2,c3)=>p2+c3.byteLength,0),joinedArray=new Uint8Array(len);let offset=0;bufItems.forEach(e3=>{joinedArray.set(new Uint8Array(e3),offset);offset+=e3.byteLength});return joinedArray.buffer}function _decodeToArrayBuffer(src){const out=new Uint8Array(src.length),len=src.length;for(let i3=0;i3<len;i3++){const char=src.charCodeAt(i3);out[i3]=char>=38&&char<=126&&58!=char?char:revTable[char]}return out.buffer}function concatUInt8Array2(arrays){const length=arrays.reduce((acc,cur)=>acc+cur.length,0),result=new Uint8Array(length);let pos=0;for(const array of arrays){result.set(array,pos);pos+=array.length}return result}function decodeBinary(src){if(0==src.length)return(new Uint8Array).buffer;if("string"==typeof src){if("%"===src[0])return _decodeToArrayBuffer(src.substring(1))}else if("%"===src[0][0]){const[head2,...last]=src;return decodeToArrayBuffer([head2.substring(1),...last])}return base64ToArrayBuffer(src)}function replaceAll(str,search,replace){return"replaceAll"in String.prototype?str.replaceAll(search,replace):str.split(search).join(replace)}function replaceAllPairs(str,...fromTo){let r4=`${str}`;for(const[from,to]of fromTo)r4=replaceAll(r4,from,to);return r4}function escapeStringToHTML(str){return str?str.replace(/[<>&"'`]/g,match3=>({"<":"&lt;",">":"&gt;","&":"&amp;",'"':"&quot;","'":"&#39;","`":"&#x60;"}[match3])):""}async function arrayBufferToBase64Single2(buffer){var _a13;try{return await arrayBufferToBase64Single(buffer)}catch(ex){const maybeBuffer=null==(_a13=compatGlobal)?void 0:_a13.Buffer;if("function"==typeof(null==maybeBuffer?void 0:maybeBuffer.from)){const view=buffer instanceof Uint8Array?buffer:new Uint8Array(buffer);return maybeBuffer.from(view.buffer,view.byteOffset,view.byteLength).toString("base64")}throw ex}}function isValidFilenameInWidows(filename){if(/[\u0000-\u001f]|[\\":?<>|*#]/g.test(filename))return!1;return!/(\\|\/)(COM\d|LPT\d|CON|PRN|AUX|NUL|CLOCK$)($|\.)/gi.test(filename)}function isValidFilenameInDarwin(filename){return!/[\u0000-\u001f]|[:]/g.test(filename)}function isValidFilenameInLinux(filename){return!/[\u0000-\u001f]|[:]/g.test(filename)}function isValidFilenameInAndroid(filename){return!/[\u0000-\u001f]|[\\":?<>|*#]/g.test(filename)}function isFilePath(path2){return-1===path2.indexOf(":")}function stripAllPrefixes(prefixedPath){if(isFilePath(prefixedPath))return prefixedPath;const[,body]=expandFilePathPrefix(prefixedPath);return stripAllPrefixes(body)}function addPrefix(path2,prefix){return prefix&&path2.startsWith(prefix)?path2:`${null!=prefix?prefix:""}${path2}`}function expandFilePathPrefix(path2){let[prefix,body]=path2.split(":",2);if(body)prefix+=":";else{body=prefix;prefix=""}return[prefix,body]}function expandDocumentIDPrefix(id){let[prefix,body]=id.split(":",2);if(body)prefix+=":";else{body=prefix;prefix=""}return[prefix,body]}function hashString(key3){return _hashString(key3)}async function path2id_base(filenameSrc,obfuscatePassphrase,caseInsensitive){if(filenameSrc.startsWith(PREFIX_OBFUSCATED))return`${filenameSrc}`;let filename=`${filenameSrc}`;const newPrefix=obfuscatePassphrase?PREFIX_OBFUSCATED:"";caseInsensitive&&(filename=filename.toLowerCase());let x3=filename;x3.startsWith("_")&&(x3="/"+x3);if(!obfuscatePassphrase)return newPrefix+x3;const[prefix,body]=expandFilePathPrefix(x3);if(body.startsWith(PREFIX_OBFUSCATED))return newPrefix+x3;const hashedPassphrase=await hashString(obfuscatePassphrase),out=await hashString(`${hashedPassphrase}:${filename}`);return prefix+newPrefix+out}function id2path_base(id,entry){if(entry&&(null==entry?void 0:entry.path))return id2path_base(entry.path);if(id.startsWith(PREFIX_OBFUSCATED))throw new Error("Entry has been obfuscated!");const[prefix,body]=expandDocumentIDPrefix(id);if(body.startsWith(PREFIX_OBFUSCATED))throw new Error("Entry has been obfuscated!");return body.startsWith("/")?body.substring(1):prefix+body}function getPath(entry){return id2path_base(entry._id,entry)}function stripPrefix(prefixedPath){const[prefix,body]=prefixedPath.split(":",2);return body||prefix}function shouldBeIgnored(filename){return filename==FLAGMD_REDFLAG||(filename==FLAGMD_REDFLAG2||(filename==FLAGMD_REDFLAG2_HR||(filename==FLAGMD_REDFLAG3||(filename==FLAGMD_REDFLAG3_HR||(!!filename.startsWith(PREFIXMD_LOGFILE)||!!filename.startsWith(PREFIXMD_LOGFILE_UC))))))}function isPlainText(filename){return!!filename.endsWith(".md")||(!!filename.endsWith(".txt")||(!!filename.endsWith(".svg")||(!!filename.endsWith(".html")||(!!filename.endsWith(".csv")||(!!filename.endsWith(".css")||(!!filename.endsWith(".js")||(!!filename.endsWith(".xml")||!!filename.endsWith(".canvas"))))))))}function shouldSplitAsPlainText(filename){return!!filename.endsWith(".md")||(!!filename.endsWith(".txt")||!!filename.endsWith(".canvas"))}function matchIgnoredPath(path2,pattern,ignore){let matchers2=matcherCache.get(ignore);if(void 0===matchers2){matchers2=new Map;matcherCache.set(ignore,matchers2)}let matcher=matchers2.get(pattern);if(void 0===matcher){matcher=new Minimatch(pattern,matchOpts);matchers2.set(pattern,matcher)}return matcher.match(path2)}function isAccepted(path2,ignore){if(-1!==path2.indexOf("./")||-1!==path2.indexOf("../"))return!1;const patterns=ignore.map(e3=>e3.trim()).filter(e3=>e3.length>0&&!e3.startsWith("#"));let result;for(const pattern of patterns){if(pattern.endsWith("/")&&matchIgnoredPath(path2,`${pattern}**`,ignore))return!1;const newResult=pattern.startsWith("!"),matched=matchIgnoredPath(path2,pattern,ignore)||!pattern.endsWith("/")&&matchIgnoredPath(path2,pattern+"/**",ignore);matched&&(result=newResult)}return result}async function isAcceptedAll(path2,ignoreFiles,getList){const pathBase=path2.substring(0,path2.lastIndexOf("/")),intermediatePaths=unique(pathBase.split("/").reduce((p2,c3)=>[...p2,p2[p2.length-1]+"/"+c3],[""]).map(e3=>e3.substring(1))).reverse();for(const intermediatePath of intermediatePaths)for(const ignoreFile of ignoreFiles){const ignoreFilePath=intermediatePath+"/"+ignoreFile,list=await getList(ignoreFilePath);if(!1===list)continue;const result=isAccepted(path2.substring(intermediatePath.length?intermediatePath.length+1:0),list);if(void 0!==result)return result}return!0}function Semaphore(limit){let counter=0;const _limit=limit,queue2=[],semaphore={get waiting(){return queue2.length},async tryAcquire(quantity=1,timeout){if(counter<_limit){counter+=quantity;return()=>{this.release(quantity)}}const d4=cancelableDelay(timeout,TIMED_OUT_SIGNAL),aq2=this.acquire(quantity),p2=await Promise.race([d4.promise,aq2]);if(p2===TIMED_OUT_SIGNAL){fireAndForget(()=>aq2.then(release=>release()));return!1}return p2},async acquire(quantity=1){if(counter<_limit){counter+=quantity;return()=>this.release()}const n3=promiseWithResolvers();queue2.push(n3);await n3.promise;return()=>{this.release(quantity)}},release(quantity=1){if(queue2.length>0){const next2=queue2.shift();next2&&fireAndForget(async()=>await yieldMicrotask().then(()=>next2.resolve()))}else counter>0&&(counter-=quantity)}};return semaphore}function isCloudantURI(uri){return-1!==uri.indexOf(".cloudantnosqldb.")||-1!==uri.indexOf(".cloudant.com")}function isErrorOfMissingDoc(ex){return 404==(ex&&ex.status)}function sizeToHumanReadable(size){const units=["B","KB","MB","GB","TB"];let i3=0;for(;size>=1024&&i3<units.length;){size/=1024;i3++}return size.toFixed(2)+units[i3]}function getStatusFromError(error){if(error&&"object"==typeof error){if("status"in error&&"number"==typeof error.status)return error.status;if("cause"in error)return getStatusFromError(error.cause)}return 500}function getMessageFromError(error){return error instanceof Error?error.message:"object"==typeof error&&null!==error?JSON.stringify(error):String(error)}function getErrorCause(error){if(error&&"object"==typeof error&&"cause"in error)return error.cause}function ensureError(error){return error instanceof Error?error:LiveSyncError.fromError(error)}function unorderedArrayToObject(obj){return obj.map(e3=>({[e3.id]:e3})).reduce((p2,c3)=>({...p2,...c3}),{})}function objectToUnorderedArray(obj){const entries2=Object.entries(obj);if(entries2.some(e3=>{var _a13;return e3[0]!=(null==(_a13=e3[1])?void 0:_a13.id)}))throw new Error("Item looks like not unordered array");return entries2.map(e3=>e3[1])}function generatePatchUnorderedArray(from,to){if(from.every(e3=>"object"==typeof e3&&"id"in e3)&&to.every(e3=>"object"==typeof e3&&"id"in e3)){const fObj=unorderedArrayToObject(from),tObj=unorderedArrayToObject(to),diff=generatePatchObj(fObj,tObj);return Object.keys(diff).length>0?{[MARK_ISARRAY]:diff}:{}}return{[MARK_SWAPPED]:to}}function generatePatchObj(from,to){const entries2=Object.entries(from),tempMap=new Map(entries2),ret={},newEntries=Object.entries(to);for(const[key3,value]of newEntries)if(tempMap.has(key3)){const v2=tempMap.get(key3);if(typeof v2!=typeof value||Array.isArray(v2)!==Array.isArray(value))ret[key3]={[MARK_SWAPPED]:value};else if(null===v2&&null===value);else if(null===v2&&null!==value)ret[key3]={[MARK_SWAPPED]:value};else if(null!==v2&&null===value)ret[key3]={[MARK_SWAPPED]:value};else if("object"!=typeof v2||"object"!=typeof value||Array.isArray(v2)||Array.isArray(value))if("object"==typeof v2&&"object"==typeof value&&Array.isArray(v2)&&Array.isArray(value)){const wk2=generatePatchUnorderedArray(v2,value);Object.keys(wk2).length>0&&(ret[key3]=wk2)}else"object"!=typeof v2&&"object"!=typeof value?JSON.stringify(tempMap.get(key3))!==JSON.stringify(value)&&(ret[key3]=value):JSON.stringify(tempMap.get(key3))!==JSON.stringify(value)&&(ret[key3]={[MARK_SWAPPED]:value});else{const wk2=generatePatchObj(v2,value);Object.keys(wk2).length>0&&(ret[key3]=wk2)}tempMap.delete(key3)}else{ret[key3]=value;tempMap.delete(key3)}for(const[key3]of tempMap)ret[key3]=MARK_DELETED;return ret}function applyPatch(from,patch){const ret=from,patches=Object.entries(patch);for(const[key3,value]of patches)if(value!=MARK_DELETED)if(null!==value)if("object"==typeof value){if(MARK_SWAPPED in value){ret[key3]=value[MARK_SWAPPED];continue}if(MARK_ISARRAY in value){key3 in ret||(ret[key3]=[]);if(!Array.isArray(ret[key3]))throw new Error("Patch target type is mismatched (array to something)");const orgArrayObject=unorderedArrayToObject(ret[key3]),appliedObject=applyPatch(orgArrayObject,value[MARK_ISARRAY]),appliedArray=objectToUnorderedArray(appliedObject);ret[key3]=[...appliedArray]}else{if(!(key3 in ret)){ret[key3]=value;continue}ret[key3]=applyPatch(ret[key3],value)}}else ret[key3]=value;else ret[key3]=null;else delete ret[key3];return ret}function mergeObject(objA,objB){const newEntries=Object.entries(objB),ret={...objA};if(typeof objA!=typeof objB||Array.isArray(objA)!==Array.isArray(objB))return objB;for(const[key3,v2]of newEntries)if(key3 in ret){const value=ret[key3];typeof v2!=typeof value||Array.isArray(v2)!==Array.isArray(value)?ret[key3]=v2:"object"!=typeof v2||"object"!=typeof value||Array.isArray(v2)||Array.isArray(value)?"object"==typeof v2&&"object"==typeof value&&Array.isArray(v2)&&Array.isArray(value)?ret[key3]=[...new Set([...v2,...value])]:ret[key3]=v2:ret[key3]=mergeObject(v2,value)}else ret[key3]=v2;const retSorted=Object.fromEntries(Object.entries(ret).sort((a2,b3)=>a2[0]<b3[0]?-1:a2[0]>b3[0]?1:0));return Array.isArray(objA)&&Array.isArray(objB)?Object.values(retSorted):retSorted}function flattenObject(obj,path2=[]){if("object"!=typeof obj)return[[path2.join("."),obj]];if(null===obj)return[[path2.join("."),null]];if(Array.isArray(obj))return[[path2.join("."),JSON.stringify(obj)]];const e3=Object.entries(obj),ret=[];for(const[key3,value]of e3){const p2=flattenObject(value,[...path2,key3]);ret.push(...p2)}return ret}function isSensibleMargeApplicable(path2){return!!path2.endsWith(".md")}function isObjectMargeApplicable(path2){return!!path2.endsWith(".canvas")||!!path2.endsWith(".json")}function resolveWithIgnoreKnownError(p2,def){return new Promise((res2,rej)=>{p2.then(res2).catch(ex=>isErrorOfMissingDoc(ex)?res2(def):rej(ensureError(ex)))})}function getDocData(doc){return"string"==typeof doc?doc:doc.join("")}function getDocDataAsArray(doc){return"string"==typeof doc?[doc]:doc}function isTextBlob(blob){return"text/plain"===blob.type}function createTextBlob(data){const d4=Array.isArray(data)?data:[data];return new Blob(d4,{endings:"transparent",type:"text/plain"})}function createBinaryBlob(data){return new Blob([data],{endings:"transparent",type:"application/octet-stream"})}function createBlob(data){return data instanceof Blob?data:data instanceof Uint8Array||data instanceof ArrayBuffer?createBinaryBlob(data):createTextBlob(data)}function isTextDocument(doc){return"plain"==doc.type||("plain"==doc.datatype||!!isPlainText(doc.path))}function readAsBlob(doc){return isTextDocument(doc)?createTextBlob(doc.data):createBinaryBlob(decodeBinary(doc.data))}function readContent(doc){return isTextDocument(doc)?getDocData(doc.data):decodeBinary(doc.data)}async function isDocContentSame(docA,docB){const blob1=createBlob(docA),blob2=createBlob(docB);if(blob1.size!=blob2.size)return!1;if(isIndexDBCmpExist)return 0===compatGlobal.indexedDB.cmp(await blob1.arrayBuffer(),await blob2.arrayBuffer());const length=blob1.size;let i3=0;for(;i3<length;){const ab1=await blob1.slice(i3,i3+1e4).arrayBuffer(),ab2=await blob2.slice(i3,i3+1e4).arrayBuffer();i3+=1e4;if(await arrayBufferToBase64Single2(ab1)!=await arrayBufferToBase64Single2(ab2))return!1}return!0}function isObfuscatedEntry(doc){return!!doc._id.startsWith(PREFIX_OBFUSCATED)}function isEncryptedChunkEntry(doc){return!!doc._id.startsWith(PREFIX_ENCRYPTED_CHUNK)}function isSyncInfoEntry(doc){return doc._id==SYNCINFO_ID}function determineTypeFromBlob(data){return isTextBlob(data)?"plain":"newnote"}function determineType(path2,data){return data instanceof Blob?determineTypeFromBlob(data):isPlainText(path2)?"plain":data instanceof Uint8Array||data instanceof ArrayBuffer?"newnote":"plain"}function isAnyNote(doc){return"type"in doc&&("newnote"==doc.type||"plain"==doc.type)}function isLoadedEntry(doc){return"type"in doc&&("newnote"==doc.type||"plain"==doc.type)&&"data"in doc}function isDeletedEntry(doc){return doc._deleted||doc.deleted||!1}function createSavingEntryFromLoadedEntry(doc){const data=readAsBlob(doc),type=determineType(doc.path,data);return{...doc,data,datatype:type,type,children:[]}}function setAllItems(set2,items){items.forEach(e3=>set2.add(e3));return set2}function escapeNewLineFromString(str){if(-1===str.indexOf("\n")&&-1===str.indexOf("\r"))return str;const p2=str.replace(/(\n|\r|\\)/g,m3=>`${map[m3]}`);return"\\f"+p2}function unescapeNewLineFromString(str){if(!str.startsWith("\\f"))return str;const p2=str.substring(2).replace(/(\\n|\\r|\\\\)/g,m3=>`${revMap2[m3]}`);return p2}function escapeMarkdownValue(value){return"string"==typeof value?replaceAllPairs(value,["|","\\|"],["`","\\`"]):value}function timeDeltaToHumanReadable(delta){const sec=delta/1e3;if(sec<60)return`${sec.toFixed(2)}s`;const min2=sec/60;if(min2<60)return`${min2.toFixed(2)}m`;const hour=min2/60;if(hour<24)return`${hour.toFixed(2)}h`;const day=hour/24;if(day<365)return`${day.toFixed(2)}d`;const year2=day/365;return`${year2.toFixed(2)}y`}async function wrapException(func){try{return await func()}catch(ex){return ex instanceof Error?ex:new Error(String(ex))}}function isDirty(key3,value){const prev=previousValues.get(key3);if(prev===value)return!1;previousValues.set(key3,value);return!0}function tryParseJSON(str,fallbackValue){try{return JSON.parse(str)}catch(e3){return fallbackValue}}function parseHeaderValues(strHeader){const headers={},lines=strHeader.split("\n");for(const line of lines){const[key3,value]=line.split(":",2).map(e3=>e3.trim());key3&&value&&(headers[key3]=value)}return headers}function parseCustomRegExp(regexp){return regexp.startsWith("!!")?[!0,regexp.slice(2)]:[!1,regexp]}function isValidRegExp(regexp){try{const[,exp]=parseCustomRegExp(regexp);new RegExp(exp);return!0}catch(e3){return!1}}function isInvertedRegExp(regexp){const[negate4]=parseCustomRegExp(regexp);return negate4}function parseCustomRegExpList(list,flags2,delimiter){const d4=null!=delimiter?delimiter:",",source2=`${null!=list?list:""}`,items=source2.replace(/\n| /g,"").split(d4).filter(e3=>e3);return items.map(e3=>new CustomRegExp(e3,flags2))}function constructCustomRegExpList(items,delimiter){return items.map(e3=>`${e3}`).join(`${delimiter}`)}function splitCustomRegExpList(list,delimiter){const d4=delimiter,source2=`${null!=list?list:""}`;return source2.split(d4).filter(e3=>e3)}function getFileRegExp(settings,key3){const flagCase=settings.handleFilenameCaseSensitive?"":"i";if("syncInternalFilesIgnorePatterns"===key3||"syncInternalFilesTargetPatterns"===key3||"syncInternalFileOverwritePatterns"===key3){const regExp2=settings[key3];return parseCustomRegExpList(regExp2,flagCase,",")}const regExp=settings[key3];return parseCustomRegExpList(regExp,flagCase,"|[]|")}function copyTo(source2,target){for(const key3 of Object.keys(target))target[key3]=source2[key3]}function pickBucketSyncSettings(setting){return{bucket:setting.bucket,region:setting.region,endpoint:setting.endpoint,accessKey:setting.accessKey,secretKey:setting.secretKey,bucketPrefix:setting.bucketPrefix,forcePathStyle:setting.forcePathStyle,useCustomRequestHandler:setting.useCustomRequestHandler,bucketCustomHeaders:setting.bucketCustomHeaders}}function pickCouchDBSyncSettings(setting){return{couchDB_URI:setting.couchDB_URI,couchDB_USER:setting.couchDB_USER,couchDB_PASSWORD:setting.couchDB_PASSWORD,couchDB_DBNAME:setting.couchDB_DBNAME,useRequestAPI:setting.useRequestAPI,couchDB_CustomHeaders:setting.couchDB_CustomHeaders,jwtAlgorithm:setting.jwtAlgorithm,jwtExpDuration:setting.jwtExpDuration,jwtKey:setting.jwtKey,jwtKid:setting.jwtKid,jwtSub:setting.jwtSub,useJWT:setting.useJWT}}function pickEncryptionSettings(setting){return{E2EEAlgorithm:setting.E2EEAlgorithm,encrypt:setting.encrypt,passphrase:setting.passphrase,usePathObfuscation:setting.usePathObfuscation}}function pickP2PSyncSettings(setting){return{P2P_Enabled:setting.P2P_Enabled,P2P_AppID:setting.P2P_AppID,P2P_roomID:setting.P2P_roomID,P2P_passphrase:setting.P2P_passphrase,P2P_relays:setting.P2P_relays,P2P_AutoStart:setting.P2P_AutoStart,P2P_AutoBroadcast:setting.P2P_AutoBroadcast,P2P_DevicePeerName:setting.P2P_DevicePeerName||"",P2P_turnServers:setting.P2P_turnServers,P2P_turnUsername:setting.P2P_turnUsername,P2P_turnCredential:setting.P2P_turnCredential,P2P_maxWirePayloadBytes:normaliseP2PMaxWirePayloadBytes(setting.P2P_maxWirePayloadBytes),P2P_connectionPath:normaliseP2PConnectionPath(setting.P2P_connectionPath)}}function compareMTime(baseMTime,targetMTime){const truncatedBaseMTime=~~(baseMTime/resolution)*resolution,truncatedTargetMTime=~~(targetMTime/resolution)*resolution;if(truncatedBaseMTime==truncatedTargetMTime)return EVEN;if(truncatedBaseMTime>truncatedTargetMTime)return BASE_IS_NEW;if(truncatedBaseMTime<truncatedTargetMTime)return TARGET_IS_NEW;throw new Error("Unexpected error")}function displayRev(rev3){const[number,hash3]=rev3.split("-");return`${number}-${hash3.substring(0,6)}`}function generateP2PRoomId(){const randomValues=new Uint16Array(4);crypto.getRandomValues(randomValues);const a2=Math.floor(randomValues[0]/65536*1e3),b3=Math.floor(randomValues[1]/65536*1e3),c3=Math.floor(randomValues[2]/65536*1e3),d4=Math.floor(randomValues[3]/65536*46656);return`${a2.toString().padStart(3,"0")}-${b3.toString().padStart(3,"0")}-${c3.toString().padStart(3,"0")}-${d4.toString(36).padStart(3,"0")}`}function extractP2PRoomSuffix(roomId){var _a13;const trimmed=roomId.trim();if(""===trimmed)return"";const parts=trimmed.split("-").map(e3=>e3.trim()).filter(e3=>e3);return 0===parts.length?"":null!=(_a13=parts[parts.length-1])?_a13:""}function createLiveSyncEventHub(){return new EventHub}function resolveEnglishMessage(key3,seen=new Set){var _a13;if(seen.has(key3))return key3;seen.add(key3);const message=null!=(_a13=commonlibEnglishMessages[key3])?_a13:key3;return message.replace(/%\{([^}]+)\}/g,(_token,referencedKey)=>{const directKey=referencedKey,keywordKey=`K.${referencedKey}`;return directKey in commonlibEnglishMessages?resolveEnglishMessage(directKey,new Set(seen)):keywordKey in commonlibEnglishMessages?resolveEnglishMessage(keywordKey,new Set(seen)):`%{${referencedKey}}`})}function createInstanceLogFunction(serviceName,APIService2){var _a13;const logFunc=null!=(_a13=null==APIService2?void 0:APIService2.addLog.bind(APIService2))?_a13:Logger;return(msg,level=LOG_LEVEL_INFO,key3="")=>{const isError=msg instanceof Error;if(isError&&level<=LOG_LEVEL_VERBOSE){logFunc(msg,level,key3);return}let formattedMsg="string"==typeof msg?msg:isError?msg.message:JSON.stringify(msg);level<LOG_LEVEL_NOTICE&&(formattedMsg=`[${serviceName}]${MARK_LOG_SEPARATOR} ${formattedMsg}`);logFunc(formattedMsg,level,key3)}}function is_function(thing){return"function"==typeof thing}function run(fn){return fn()}function run_all(arr){for(var i3=0;i3<arr.length;i3++)arr[i3]()}function deferred(){var resolve,reject,promise=new Promise((res2,rej)=>{resolve=res2;reject=rej});return{promise,resolve,reject}}function to_array(value,n3){if(Array.isArray(value))return value;if(void 0===n3||!(Symbol.iterator in value))return Array.from(value);const array=[];for(const element2 of value){array.push(element2);if(array.length===n3)break}return array}function invariant_violation(message){if(dev_fallback_default){const error=new Error(`invariant_violation\nAn invariant violation occurred, meaning Svelte's internal assumptions were flawed. This is a bug in Svelte, not your app — please open an issue at https://github.com/sveltejs/svelte, citing the following message: "${message}"\nhttps://svelte.dev/e/invariant_violation`);error.name="Svelte error";throw error}throw new Error("https://svelte.dev/e/invariant_violation")}function lifecycle_outside_component(name){if(dev_fallback_default){const error=new Error(`lifecycle_outside_component\n\`${name}(...)\` can only be used during component initialisation\nhttps://svelte.dev/e/lifecycle_outside_component`);error.name="Svelte error";throw error}throw new Error("https://svelte.dev/e/lifecycle_outside_component")}function async_derived_orphan(){if(dev_fallback_default){const error=new Error("async_derived_orphan\nCannot create a `$derived(...)` with an `await` expression outside of an effect tree\nhttps://svelte.dev/e/async_derived_orphan");error.name="Svelte error";throw error}throw new Error("https://svelte.dev/e/async_derived_orphan")}function bind_invalid_checkbox_value(){if(dev_fallback_default){const error=new Error("bind_invalid_checkbox_value\nUsing `bind:value` together with a checkbox input is not allowed. Use `bind:checked` instead\nhttps://svelte.dev/e/bind_invalid_checkbox_value");error.name="Svelte error";throw error}throw new Error("https://svelte.dev/e/bind_invalid_checkbox_value")}function derived_references_self(){if(dev_fallback_default){const error=new Error("derived_references_self\nA derived value cannot reference itself recursively\nhttps://svelte.dev/e/derived_references_self");error.name="Svelte error";throw error}throw new Error("https://svelte.dev/e/derived_references_self")}function each_key_duplicate(a2,b3,value){if(dev_fallback_default){const error=new Error(`each_key_duplicate\n${value?`Keyed each block has duplicate key \`${value}\` at indexes ${a2} and ${b3}`:`Keyed each block has duplicate key at indexes ${a2} and ${b3}`}\nhttps://svelte.dev/e/each_key_duplicate`);error.name="Svelte error";throw error}throw new Error("https://svelte.dev/e/each_key_duplicate")}function each_key_volatile(index6,a2,b3){if(dev_fallback_default){const error=new Error(`each_key_volatile\nKeyed each block has key that is not idempotent — the key for item at index ${index6} was \`${a2}\` but is now \`${b3}\`. Keys must be the same each time for a given item\nhttps://svelte.dev/e/each_key_volatile`);error.name="Svelte error";throw error}throw new Error("https://svelte.dev/e/each_key_volatile")}function effect_in_teardown(rune){if(dev_fallback_default){const error=new Error(`effect_in_teardown\n\`${rune}\` cannot be used inside an effect cleanup function\nhttps://svelte.dev/e/effect_in_teardown`);error.name="Svelte error";throw error}throw new Error("https://svelte.dev/e/effect_in_teardown")}function effect_in_unowned_derived(){if(dev_fallback_default){const error=new Error("effect_in_unowned_derived\nEffect cannot be created inside a `$derived` value that was not itself created inside an effect\nhttps://svelte.dev/e/effect_in_unowned_derived");error.name="Svelte error";throw error}throw new Error("https://svelte.dev/e/effect_in_unowned_derived")}function effect_orphan(rune){if(dev_fallback_default){const error=new Error(`effect_orphan\n\`${rune}\` can only be used inside an effect (e.g. during component initialisation)\nhttps://svelte.dev/e/effect_orphan`);error.name="Svelte error";throw error}throw new Error("https://svelte.dev/e/effect_orphan")}function effect_update_depth_exceeded(){if(dev_fallback_default){const error=new Error("effect_update_depth_exceeded\nMaximum update depth exceeded. This typically indicates that an effect reads and writes the same piece of state\nhttps://svelte.dev/e/effect_update_depth_exceeded");error.name="Svelte error";throw error}throw new Error("https://svelte.dev/e/effect_update_depth_exceeded")}function hydration_failed(){if(dev_fallback_default){const error=new Error("hydration_failed\nFailed to hydrate the application\nhttps://svelte.dev/e/hydration_failed");error.name="Svelte error";throw error}throw new Error("https://svelte.dev/e/hydration_failed")}function invalid_snippet(){if(dev_fallback_default){const error=new Error("invalid_snippet\nCould not `{@render}` snippet due to the expression being `null` or `undefined`. Consider using optional chaining `{@render snippet?.()}`\nhttps://svelte.dev/e/invalid_snippet");error.name="Svelte error";throw error}throw new Error("https://svelte.dev/e/invalid_snippet")}function props_invalid_value(key3){if(dev_fallback_default){const error=new Error(`props_invalid_value\nCannot do \`bind:${key3}={undefined}\` when \`${key3}\` has a fallback value\nhttps://svelte.dev/e/props_invalid_value`);error.name="Svelte error";throw error}throw new Error("https://svelte.dev/e/props_invalid_value")}function props_rest_readonly(property){if(dev_fallback_default){const error=new Error(`props_rest_readonly\nRest element properties of \`$props()\` such as \`${property}\` are readonly\nhttps://svelte.dev/e/props_rest_readonly`);error.name="Svelte error";throw error}throw new Error("https://svelte.dev/e/props_rest_readonly")}function rune_outside_svelte(rune){if(dev_fallback_default){const error=new Error(`rune_outside_svelte\nThe \`${rune}\` rune is only available inside \`.svelte\` and \`.svelte.js/ts\` files\nhttps://svelte.dev/e/rune_outside_svelte`);error.name="Svelte error";throw error}throw new Error("https://svelte.dev/e/rune_outside_svelte")}function set_context_after_init(){if(dev_fallback_default){const error=new Error("set_context_after_init\n`setContext` must be called when a component first initializes, not in a subsequent effect or after an `await` expression\nhttps://svelte.dev/e/set_context_after_init");error.name="Svelte error";throw error}throw new Error("https://svelte.dev/e/set_context_after_init")}function state_descriptors_fixed(){if(dev_fallback_default){const error=new Error("state_descriptors_fixed\nProperty descriptors defined on `$state` objects must contain `value` and always be `enumerable`, `configurable` and `writable`.\nhttps://svelte.dev/e/state_descriptors_fixed");error.name="Svelte error";throw error}throw new Error("https://svelte.dev/e/state_descriptors_fixed")}function state_prototype_fixed(){if(dev_fallback_default){const error=new Error("state_prototype_fixed\nCannot set prototype of `$state` object\nhttps://svelte.dev/e/state_prototype_fixed");error.name="Svelte error";throw error}throw new Error("https://svelte.dev/e/state_prototype_fixed")}function state_unsafe_mutation(){if(dev_fallback_default){const error=new Error("state_unsafe_mutation\nUpdating state inside `$derived(...)`, `$inspect(...)` or a template expression is forbidden. If the value should not be reactive, declare it without `$state`\nhttps://svelte.dev/e/state_unsafe_mutation");error.name="Svelte error";throw error}throw new Error("https://svelte.dev/e/state_unsafe_mutation")}function svelte_boundary_reset_onerror(){if(dev_fallback_default){const error=new Error("svelte_boundary_reset_onerror\nA `<svelte:boundary>` `reset` function cannot be called while an error is still being handled\nhttps://svelte.dev/e/svelte_boundary_reset_onerror");error.name="Svelte error";throw error}throw new Error("https://svelte.dev/e/svelte_boundary_reset_onerror")}function await_reactivity_loss(name){dev_fallback_default?console.warn(`%c[svelte] await_reactivity_loss\n%cDetected reactivity loss when reading \`${name}\`. This happens when state is read in an async function after an earlier \`await\`\nhttps://svelte.dev/e/await_reactivity_loss`,bold,normal):console.warn("https://svelte.dev/e/await_reactivity_loss")}function await_waterfall(name,location){dev_fallback_default?console.warn(`%c[svelte] await_waterfall\n%cAn async derived, \`${name}\` (${location}) was not read immediately after it resolved. This often indicates an unnecessary waterfall, which can slow down your app\nhttps://svelte.dev/e/await_waterfall`,bold,normal):console.warn("https://svelte.dev/e/await_waterfall")}function derived_inert(){dev_fallback_default?console.warn("%c[svelte] derived_inert\n%cReading a derived belonging to a now-destroyed effect may result in stale values\nhttps://svelte.dev/e/derived_inert",bold,normal):console.warn("https://svelte.dev/e/derived_inert")}function hydration_attribute_changed(attribute,html2,value){dev_fallback_default?console.warn(`%c[svelte] hydration_attribute_changed\n%cThe \`${attribute}\` attribute on \`${html2}\` changed its value between server and client renders. The client value, \`${value}\`, will be ignored in favour of the server value\nhttps://svelte.dev/e/hydration_attribute_changed`,bold,normal):console.warn("https://svelte.dev/e/hydration_attribute_changed")}function hydration_mismatch(location){dev_fallback_default?console.warn(`%c[svelte] hydration_mismatch\n%c${location?`Hydration failed because the initial UI does not match what was rendered on the server. The error occurred near ${location}`:"Hydration failed because the initial UI does not match what was rendered on the server"}\nhttps://svelte.dev/e/hydration_mismatch`,bold,normal):console.warn("https://svelte.dev/e/hydration_mismatch")}function lifecycle_double_unmount(){dev_fallback_default?console.warn("%c[svelte] lifecycle_double_unmount\n%cTried to unmount a component that was not mounted\nhttps://svelte.dev/e/lifecycle_double_unmount",bold,normal):console.warn("https://svelte.dev/e/lifecycle_double_unmount")}function select_multiple_invalid_value(){dev_fallback_default?console.warn("%c[svelte] select_multiple_invalid_value\n%cThe `value` property of a `<select multiple>` element should be an array, but it received a non-array value. The selection will be kept as is.\nhttps://svelte.dev/e/select_multiple_invalid_value",bold,normal):console.warn("https://svelte.dev/e/select_multiple_invalid_value")}function state_proxy_equality_mismatch(operator){dev_fallback_default?console.warn(`%c[svelte] state_proxy_equality_mismatch\n%cReactive \`$state(...)\` proxies and the values they proxy have different identities. Because of this, comparisons with \`${operator}\` will produce unexpected results\nhttps://svelte.dev/e/state_proxy_equality_mismatch`,bold,normal):console.warn("https://svelte.dev/e/state_proxy_equality_mismatch")}function state_proxy_unmount(){dev_fallback_default?console.warn("%c[svelte] state_proxy_unmount\n%cTried to unmount a state proxy, rather than a component\nhttps://svelte.dev/e/state_proxy_unmount",bold,normal):console.warn("https://svelte.dev/e/state_proxy_unmount")}function svelte_boundary_reset_noop(){dev_fallback_default?console.warn("%c[svelte] svelte_boundary_reset_noop\n%cA `<svelte:boundary>` `reset` function only resets the boundary the first time it is called\nhttps://svelte.dev/e/svelte_boundary_reset_noop",bold,normal):console.warn("https://svelte.dev/e/svelte_boundary_reset_noop")}function set_hydrating(value){hydrating=value}function set_hydrate_node(node){if(null===node){hydration_mismatch();throw HYDRATION_ERROR}return hydrate_node=node}function hydrate_next(){return set_hydrate_node(get_next_sibling(hydrate_node))}function reset(node){if(hydrating){if(null!==get_next_sibling(hydrate_node)){hydration_mismatch();throw HYDRATION_ERROR}hydrate_node=node}}function next(count=1){var i3,node;if(hydrating){i3=count;node=hydrate_node;for(;i3--;)node=get_next_sibling(node);hydrate_node=node}}function skip_nodes(remove=!0){for(var data,next2,depth=0,node=hydrate_node;;){if(node.nodeType===COMMENT_NODE){data=node.data;if(data===HYDRATION_END){if(0===depth)return node;depth-=1}else(data===HYDRATION_START||data===HYDRATION_START_ELSE||"["===data[0]&&!isNaN(Number(data.slice(1))))&&(depth+=1)}next2=get_next_sibling(node);remove&&node.remove();node=next2}}function read_hydration_instruction(node){if(!node||node.nodeType!==COMMENT_NODE){hydration_mismatch();throw HYDRATION_ERROR}return node.data}function equals(value){return value===this.v}function safe_not_equal(a2,b3){return a2!=a2?b3==b3:a2!==b3||null!==a2&&"object"==typeof a2||"function"==typeof a2}function safe_equals(value){return!safe_not_equal(value,this.v)}function tag(source2,label2){source2.label=label2;tag_proxy(source2.v,label2);return source2}function tag_proxy(value,label2){var _a13;null==(_a13=null==value?void 0:value[PROXY_PATH_SYMBOL])||_a13.call(value,label2);return value}function get_error(label2){const error=new Error,stack2=get_stack();if(0===stack2.length)return null;stack2.unshift("\n");define_property(error,"stack",{value:stack2.join("\n")});define_property(error,"name",{value:label2});return error}function get_stack(){const limit=Error.stackTraceLimit;Error.stackTraceLimit=1/0;const stack2=(new Error).stack;Error.stackTraceLimit=limit;if(!stack2)return[];const lines=stack2.split("\n"),new_lines=[];for(let i3=0;i3<lines.length;i3++){const line=lines[i3],posixified=line.replaceAll("\\","/");if("Error"!==line.trim()){if(line.includes("validate_each_keys"))return[];posixified.includes("svelte/src/internal")||posixified.includes("node_modules/.vite")||new_lines.push(line)}}return new_lines}function invariant(condition,message){if(!dev_fallback_default)throw new Error("invariant(...) was not guarded by if (DEV)");condition||invariant_violation(message)}function set_component_context(context2){component_context=context2}function set_dev_stack(stack2){dev_stack=stack2}function set_dev_current_component_function(fn){dev_current_component_function=fn}function getContext(key3){const context_map=get_or_init_context_map("getContext"),result=context_map.get(key3);return result}function setContext(key3,context2){var flags2,valid;const context_map=get_or_init_context_map("setContext");if(async_mode_flag){flags2=active_effect.f;valid=!active_reaction&&0!==(flags2&BRANCH_EFFECT)&&!component_context.i;valid||set_context_after_init()}context_map.set(key3,context2);return context2}function push(props,runes=!1,fn){component_context={p:component_context,i:!1,c:null,e:null,s:props,x:null,r:active_effect,l:legacy_mode_flag&&!runes?{s:null,u:null,$:[]}:null};if(dev_fallback_default){component_context.function=fn;dev_current_component_function=fn}}function pop(component2){var _a13,fn,context2=component_context,effects=context2.e;if(null!==effects){context2.e=null;for(fn of effects)create_user_effect(fn)}void 0!==component2&&(context2.x=component2);context2.i=!0;component_context=context2.p;dev_fallback_default&&(dev_current_component_function=null!=(_a13=null==component_context?void 0:component_context.function)?_a13:null);return null!=component2?component2:{}}function is_runes(){return!legacy_mode_flag||null!==component_context&&null===component_context.l}function get_or_init_context_map(name){var _a13;null===component_context&&lifecycle_outside_component(name);return null!=(_a13=component_context.c)?_a13:component_context.c=new Map(get_parent_context(component_context)||void 0)}function get_parent_context(component_context2){let parent=component_context2.p;for(;null!==parent;){const context_map=parent.c;if(null!==context_map)return context_map;parent=parent.p}return null}function run_micro_tasks(){var tasks3=micro_tasks;micro_tasks=[];run_all(tasks3)}function queue_micro_task(fn){if(0===micro_tasks.length&&!is_flushing_sync){var tasks3=micro_tasks;queueMicrotask(()=>{tasks3===micro_tasks&&run_micro_tasks()})}micro_tasks.push(fn)}function flush_tasks(){for(;micro_tasks.length>0;)run_micro_tasks()}function handle_error(error){var effect2=active_effect;if(null===effect2){active_reaction.f|=ERROR_VALUE;return error}dev_fallback_default&&error instanceof Error&&!adjustments.has(error)&&adjustments.set(error,get_adjustments(error,effect2));if(0===(effect2.f&REACTION_RAN)&&0===(effect2.f&EFFECT)){dev_fallback_default&&!effect2.parent&&error instanceof Error&&apply_adjustments(error);throw error}invoke_error_boundary(error,effect2)}function invoke_error_boundary(error,effect2){if(null===effect2||0===(effect2.f&DESTROYED)){for(;null!==effect2;){if(0!==(effect2.f&BOUNDARY_EFFECT)){if(0===(effect2.f&REACTION_RAN))throw error;try{effect2.b.error(error);return}catch(e3){error=e3}}effect2=effect2.parent}dev_fallback_default&&error instanceof Error&&apply_adjustments(error);throw error}}function get_adjustments(error,effect2){var _a13,_b6,_c3,indent,component_stack,context2;const message_descriptor=get_descriptor(error,"message");if(!message_descriptor||message_descriptor.configurable){indent=is_firefox?" ":"\t";component_stack=`\n${indent}in ${(null==(_a13=effect2.fn)?void 0:_a13.name)||"<unknown>"}`;context2=effect2.ctx;for(;null!==context2;){component_stack+=`\n${indent}in ${null==(_b6=context2.function)?void 0:_b6[FILENAME].split("/").pop()}`;context2=context2.p}return{message:error.message+`\n${component_stack}\n`,stack:null==(_c3=error.stack)?void 0:_c3.split("\n").filter(line=>!line.includes("svelte/src/internal")).join("\n")}}}function apply_adjustments(error){const adjusted=adjustments.get(error);if(adjusted){define_property(error,"message",{value:adjusted.message});define_property(error,"stack",{value:adjusted.stack})}}function set_signal_status(signal,status){signal.f=signal.f&STATUS_MASK|status}function update_derived_status(derived3){0!==(derived3.f&CONNECTED)||null===derived3.deps?set_signal_status(derived3,CLEAN):set_signal_status(derived3,MAYBE_DIRTY)}function clear_marked(deps){if(null!==deps)for(const dep of deps)if(0!==(dep.f&DERIVED)&&0!==(dep.f&WAS_MARKED)){dep.f^=WAS_MARKED;clear_marked(dep.deps)}}function defer_effect(effect2,dirty_effects,maybe_dirty_effects){0!==(effect2.f&DIRTY)?dirty_effects.add(effect2):0!==(effect2.f&MAYBE_DIRTY)&&maybe_dirty_effects.add(effect2);clear_marked(effect2.deps);set_signal_status(effect2,CLEAN)}function subscribe_to_store(store,run4,invalidate){if(null==store){run4(void 0);invalidate&&invalidate(void 0);return noop2}const unsub=untrack(()=>store.subscribe(run4,invalidate));return unsub.unsubscribe?()=>unsub.unsubscribe():unsub}function writable(value,start=noop2){function set2(new_value){if(safe_not_equal(value,new_value)){value=new_value;if(stop){const run_queue=!subscriber_queue.length;for(const subscriber of subscribers){subscriber[1]();subscriber_queue.push(subscriber,value)}if(run_queue){for(let i3=0;i3<subscriber_queue.length;i3+=2)subscriber_queue[i3][0](subscriber_queue[i3+1]);subscriber_queue.length=0}}}}function update2(fn){set2(fn(value))}let stop=null;const subscribers=new Set;return{set:set2,update:update2,subscribe:function subscribe2(run4,invalidate=noop2){const subscriber=[run4,invalidate];subscribers.add(subscriber);1===subscribers.size&&(stop=start(set2,update2)||noop2);run4(value);return()=>{subscribers.delete(subscriber);if(0===subscribers.size&&stop){stop();stop=null}}}}}function get(store){let value;subscribe_to_store(store,_=>value=_)();return value}function store_get(store,store_name,stores){var _a13,is_synchronous_callback;const entry=null!=(_a13=stores[store_name])?_a13:stores[store_name]={store:null,source:mutable_source(void 0),unsubscribe:noop2};dev_fallback_default&&(entry.source.label=store_name);if(entry.store!==store&&!(IS_UNMOUNTED in stores)){entry.unsubscribe();entry.store=null!=store?store:null;if(null==store){entry.source.v=void 0;entry.unsubscribe=noop2}else{is_synchronous_callback=!0;entry.unsubscribe=subscribe_to_store(store,v2=>{is_synchronous_callback?entry.source.v=v2:set(entry.source,v2)});is_synchronous_callback=!1}}return store&&IS_UNMOUNTED in stores?get(store):get2(entry.source)}function setup_stores(){const stores={};return[stores,function cleanup(){teardown(()=>{for(var store_name in stores){const ref=stores[store_name];ref.unsubscribe()}define_property(stores,IS_UNMOUNTED,{enumerable:!1,value:!0})})}]}function capture_store_binding(fn){var previous_is_store_binding=is_store_binding;try{is_store_binding=!1;return[fn(),is_store_binding]}finally{is_store_binding=previous_is_store_binding}}function createSubscriber(start){let stop,subscribers=0,version2=source(0);dev_fallback_default&&tag(version2,"createSubscriber version");return()=>{if(effect_tracking()){get2(version2);render_effect(()=>{0===subscribers&&(stop=untrack(()=>start(()=>increment(version2))));subscribers+=1;return()=>{queue_micro_task(()=>{subscribers-=1;if(0===subscribers){null==stop||stop();stop=void 0;increment(version2)}})}})}}}function boundary(node,props,children,transform_error){new Boundary(node,props,children,transform_error)}function flatten(blockers,sync2,async2,fn){function finish(async3){if(0===(parent.f&DESTROYED)){restore();try{fn([...deriveds,...async3])}catch(error){invoke_error_boundary(error,parent)}unset_context()}}function run4(){Promise.all(async2.map(expression=>async_derived(expression))).then(finish).catch(error=>invoke_error_boundary(error,parent)).finally(decrement_pending)}var pending3,deriveds,parent,restore,blocker_promise,decrement_pending;const d4=is_runes()?derived2:derived_safe_equal;pending3=blockers.filter(b3=>!b3.settled);deriveds=sync2.map(d4);dev_fallback_default&&deriveds.forEach((d5,i3)=>{d5.label=sync2[i3].toString().replace("() => ","").replaceAll("$.eager(() => ","$state.eager(").replace(/\$\.get\((.+?)\)/g,(_,id)=>id)});if(0!==async2.length||0!==pending3.length){parent=active_effect;restore=capture();blocker_promise=1===pending3.length?pending3[0].promise:pending3.length>1?Promise.all(pending3.map(b3=>b3.promise)):null;decrement_pending=increment_pending();0!==async2.length?blocker_promise?blocker_promise.then(()=>{restore();run4();unset_context()}):run4():blocker_promise.then(()=>finish([])).finally(decrement_pending)}else fn(deriveds)}function capture(){var previous_dev_stack,previous_effect=active_effect,previous_reaction=active_reaction,previous_component_context=component_context,previous_batch2=current_batch;dev_fallback_default&&(previous_dev_stack=dev_stack);return function restore(activate_batch=!0){set_active_effect(previous_effect);set_active_reaction(previous_reaction);set_component_context(previous_component_context);if(activate_batch&&0===(previous_effect.f&DESTROYED)){null==previous_batch2||previous_batch2.activate();null==previous_batch2||previous_batch2.apply()}if(dev_fallback_default){set_reactivity_loss_tracker(null);set_dev_stack(previous_dev_stack)}}}function unset_context(deactivate_batch=!0){var _a13;set_active_effect(null);set_active_reaction(null);set_component_context(null);deactivate_batch&&(null==(_a13=current_batch)||_a13.deactivate());if(dev_fallback_default){set_reactivity_loss_tracker(null);set_dev_stack(null)}}function increment_pending(){var effect2=active_effect,boundary2=effect2.b,batch=current_batch,blocking=!!(null==boundary2?void 0:boundary2.is_rendered());null==boundary2||boundary2.update_pending_count(1,batch);batch.increment(blocking,effect2);return()=>{null==boundary2||boundary2.update_pending_count(-1,batch);batch.decrement(blocking,effect2)}}function set_reactivity_loss_tracker(v2){reactivity_loss_tracker=v2}function derived2(fn){var flags2=DERIVED|DIRTY;null!==active_effect&&(active_effect.f|=EFFECT_PRESERVED);const signal={ctx:component_context,deps:null,effects:null,equals,f:flags2,fn,reactions:null,rv:0,v:UNINITIALIZED,wv:0,parent:active_effect,ac:null};dev_fallback_default&&tracing_mode_flag&&(signal.created=get_error("created at"));return signal}function async_derived(fn,label2,location){var promise,signal,should_suspend,deferreds;let parent=active_effect;null===parent&&async_derived_orphan();promise=void 0;signal=source(UNINITIALIZED);dev_fallback_default&&(signal.label=null!=label2?label2:fn.toString());should_suspend=!active_reaction;deferreds=new Set;async_effect(()=>{var _a13,_b6,d4,batch,decrement_pending,effect2=active_effect;dev_fallback_default&&(reactivity_loss_tracker={effect:effect2,effect_deps:new Set,warned:!1});d4=deferred();promise=d4.promise;try{Promise.resolve(fn()).then(d4.resolve,e3=>{e3!==STALE_REACTION&&d4.reject(e3)}).finally(unset_context)}catch(error){d4.reject(error);unset_context()}if(dev_fallback_default){if(reactivity_loss_tracker){if(null!==effect2.deps)for(let i3=0;i3<skipped_deps;i3+=1)reactivity_loss_tracker.effect_deps.add(effect2.deps[i3]);if(null!==new_deps)for(let i3=0;i3<new_deps.length;i3+=1)reactivity_loss_tracker.effect_deps.add(new_deps[i3])}reactivity_loss_tracker=null}batch=current_batch;if(should_suspend){0!==(effect2.f&REACTION_RAN)&&(decrement_pending=increment_pending());if(null==(_a13=parent.b)?void 0:_a13.is_rendered())null==(_b6=batch.async_deriveds.get(effect2))||_b6.reject(OBSOLETE);else for(const d5 of deferreds.values())d5.reject(OBSOLETE);deferreds.add(d4);batch.async_deriveds.set(effect2,d4)}const handler=(value,error=void 0)=>{dev_fallback_default&&(reactivity_loss_tracker=null);null==decrement_pending||decrement_pending();deferreds.delete(d4);if(error!==OBSOLETE){batch.activate();if(error){signal.f|=ERROR_VALUE;internal_set(signal,error)}else{0!==(signal.f&ERROR_VALUE)&&(signal.f^=ERROR_VALUE);if(dev_fallback_default&&void 0!==location&&!signal.equals(value)){recent_async_deriveds.add(signal);setTimeout(()=>{if(recent_async_deriveds.has(signal)&&0===(effect2.f&DESTROYED)){await_waterfall(signal.label,location);recent_async_deriveds.delete(signal)}})}internal_set(signal,value)}batch.deactivate()}};d4.promise.then(handler,e3=>handler(null,e3||"unknown"))});teardown(()=>{for(const d4 of deferreds)d4.reject(OBSOLETE)});dev_fallback_default&&(signal.f|=ASYNC);return new Promise(fulfil=>{(function next2(p2){function go(){p2===promise?fulfil(signal):next2(promise)}p2.then(go,go)})(promise)})}function user_derived(fn){const d4=derived2(fn);async_mode_flag||push_reaction_value(d4);return d4}function derived_safe_equal(fn){const signal=derived2(fn);signal.equals=safe_equals;return signal}function destroy_derived_effects(derived3){var i3,effects=derived3.effects;if(null!==effects){derived3.effects=null;for(i3=0;i3<effects.length;i3+=1)destroy_effect(effects[i3])}}function execute_derived(derived3){var value,prev_active_effect=active_effect,parent=derived3.parent;if(!is_destroying_effect&&null!==parent&&derived3.v!==UNINITIALIZED&&0!==(parent.f&(DESTROYED|INERT))){derived_inert();return derived3.v}set_active_effect(parent);if(dev_fallback_default){let prev_eager_effects=eager_effects;set_eager_effects(new Set);try{includes.call(stack,derived3)&&derived_references_self();stack.push(derived3);derived3.f&=~WAS_MARKED;destroy_derived_effects(derived3);value=update_reaction(derived3)}finally{set_active_effect(prev_active_effect);set_eager_effects(prev_eager_effects);stack.pop()}}else try{derived3.f&=~WAS_MARKED;destroy_derived_effects(derived3);value=update_reaction(derived3)}finally{set_active_effect(prev_active_effect)}return value}function update_derived(derived3){var _a13,_b6,_c3,value=execute_derived(derived3);if(!derived3.equals(value)){derived3.wv=increment_write_version();if(!(null==(_a13=current_batch)?void 0:_a13.is_fork)||null===derived3.deps){if(null!==current_batch){current_batch.capture(derived3,value,!0);null==(_b6=previous_batch)||_b6.capture(derived3,value,!0)}else derived3.v=value;if(null===derived3.deps){set_signal_status(derived3,CLEAN);return}}}is_destroying_effect||(null!==batch_values?(effect_tracking()||(null==(_c3=current_batch)?void 0:_c3.is_fork))&&batch_values.set(derived3,value):update_derived_status(derived3))}function freeze_derived_effects(derived3){var _a13,_b6;if(null!==derived3.effects)for(const e3 of derived3.effects)if(e3.teardown||e3.ac){null==(_a13=e3.teardown)||_a13.call(e3);null==(_b6=e3.ac)||_b6.abort(STALE_REACTION);null!==e3.fn&&(e3.teardown=noop2);e3.ac=null;remove_reactions(e3,0);destroy_effect_children(e3)}}function unfreeze_derived_effects(derived3){if(null!==derived3.effects)for(const e3 of derived3.effects)e3.teardown&&null!==e3.fn&&update_effect(e3)}function flushSync(fn){var result,was_flushing_sync=is_flushing_sync;is_flushing_sync=!0;try{if(fn){null===current_batch||current_batch.is_fork||current_batch.flush();result=fn()}for(;;){flush_tasks();if(null===current_batch)return result;current_batch.flush()}}finally{is_flushing_sync=was_flushing_sync}}function infinite_loop_guard(){var _a13,updates,entry;if(dev_fallback_default){updates=new Map;for(const source2 of current_batch.current.keys())for(const[stack2,update2]of null!=(_a13=source2.updated)?_a13:[]){entry=updates.get(stack2);if(!entry){entry={error:update2.error,count:0};updates.set(stack2,entry)}entry.count+=update2.count}for(const update2 of updates.values())update2.error&&console.error(update2.error)}try{effect_update_depth_exceeded()}catch(error){dev_fallback_default&&define_property(error,"stack",{value:""});invoke_error_boundary(error,last_scheduled_effect)}}function flush_queued_effects(effects){var i3,effect2,length=effects.length;if(0!==length){i3=0;for(;i3<length;){effect2=effects[i3++];if(0===(effect2.f&(DESTROYED|INERT))&&is_dirty(effect2)){eager_block_effects=new Set;update_effect(effect2);null===effect2.deps&&null===effect2.first&&null===effect2.nodes&&null===effect2.teardown&&null===effect2.ac&&unlink_effect(effect2);if((null==eager_block_effects?void 0:eager_block_effects.size)>0){old_values.clear();for(const e3 of eager_block_effects){if(0!==(e3.f&(DESTROYED|INERT)))continue;const ordered_effects=[e3];let ancestor=e3.parent;for(;null!==ancestor;){if(eager_block_effects.has(ancestor)){eager_block_effects.delete(ancestor);ordered_effects.push(ancestor)}ancestor=ancestor.parent}for(let j2=ordered_effects.length-1;j2>=0;j2--){const e4=ordered_effects[j2];0===(e4.f&(DESTROYED|INERT))&&update_effect(e4)}}eager_block_effects.clear()}}}eager_block_effects=null}}function mark_effects(value,sources,marked,checked){if(!marked.has(value)){marked.add(value);if(null!==value.reactions)for(const reaction of value.reactions){const flags2=reaction.f;if(0!==(flags2&DERIVED))mark_effects(reaction,sources,marked,checked);else if(0!==(flags2&(ASYNC|BLOCK_EFFECT))&&0===(flags2&DIRTY)&&depends_on(reaction,sources,checked)){set_signal_status(reaction,DIRTY);schedule_effect(reaction)}}}}function depends_on(reaction,sources,checked){const depends=checked.get(reaction);if(void 0!==depends)return depends;if(null!==reaction.deps)for(const dep of reaction.deps){if(includes.call(sources,dep))return!0;if(0!==(dep.f&DERIVED)&&depends_on(dep,sources,checked)){checked.set(dep,!0);return!0}}checked.set(reaction,!1);return!1}function schedule_effect(effect2){current_batch.schedule(effect2)}function reset_branch(effect2,tracked){if(0===(effect2.f&BRANCH_EFFECT)||0===(effect2.f&CLEAN)){0!==(effect2.f&DIRTY)?tracked.d.push(effect2):0!==(effect2.f&MAYBE_DIRTY)&&tracked.m.push(effect2);set_signal_status(effect2,CLEAN);for(var e3=effect2.first;null!==e3;){reset_branch(e3,tracked);e3=e3.next}}}function reset_all(effect2){set_signal_status(effect2,CLEAN);for(var e3=effect2.first;null!==e3;){reset_all(e3);e3=e3.next}}function set_eager_effects(v2){eager_effects=v2}function set_eager_effects_deferred(){eager_effects_deferred=!0}function source(v2,stack2){var signal={f:0,v:v2,reactions:null,equals,rv:0,wv:0};if(dev_fallback_default&&tracing_mode_flag){signal.created=null!=stack2?stack2:get_error("created at");signal.updated=null;signal.set_during_effect=!1;signal.trace=null}return signal}function state(v2,stack2){const s2=source(v2,stack2);push_reaction_value(s2);return s2}function mutable_source(initial_value,immutable=!1,trackable=!0){var _a13,_b6;const s2=source(initial_value);immutable||(s2.equals=safe_equals);legacy_mode_flag&&trackable&&null!==component_context&&null!==component_context.l&&(null!=(_b6=(_a13=component_context.l).s)?_b6:_a13.s=[]).push(s2);return s2}function set(source2,value,should_proxy=!1){null===active_reaction||untracking&&0===(active_reaction.f&EAGER_EFFECT)||!is_runes()||0===(active_reaction.f&(DERIVED|BLOCK_EFFECT|ASYNC|EAGER_EFFECT))||null!==current_sources&&current_sources.has(source2)||state_unsafe_mutation();let new_value=should_proxy?proxy(value):value;dev_fallback_default&&tag_proxy(new_value,source2.label);return internal_set(source2,new_value,legacy_updates)}function internal_set(source2,value,updated_during_traversal=null){var _b6,_c3,batch;if(!source2.equals(value)){old_values.set(source2,is_destroying_effect?value:source2.v);batch=Batch.ensure();batch.capture(source2,value);if(dev_fallback_default){if(tracing_mode_flag||null!==active_effect){null!=source2.updated||(source2.updated=new Map);const count=(null!=(_c3=null==(_b6=source2.updated.get(""))?void 0:_b6.count)?_c3:0)+1;source2.updated.set("",{error:null,count});if(tracing_mode_flag||count>5){const error=get_error("updated at");if(null!==error){let entry=source2.updated.get(error.stack);if(!entry){entry={error,count:0};source2.updated.set(error.stack,entry)}entry.count++}}}null!==active_effect&&(source2.set_during_effect=!0)}if(0!==(source2.f&DERIVED)){const derived3=source2;0!==(source2.f&DIRTY)&&execute_derived(derived3);null===batch_values&&update_derived_status(derived3)}source2.wv=increment_write_version();mark_reactions(source2,DIRTY,updated_during_traversal);is_runes()&&null!==active_effect&&0!==(active_effect.f&CLEAN)&&0===(active_effect.f&(BRANCH_EFFECT|ROOT_EFFECT))&&(null===untracked_writes?set_untracked_writes([source2]):untracked_writes.push(source2));!batch.is_fork&&eager_effects.size>0&&!eager_effects_deferred&&flush_eager_effects()}return value}function flush_eager_effects(){eager_effects_deferred=!1;for(const effect2 of eager_effects){0!==(effect2.f&CLEAN)&&set_signal_status(effect2,MAYBE_DIRTY);let dirty;try{dirty=is_dirty(effect2)}catch(e3){dirty=!0}dirty&&update_effect(effect2)}eager_effects.clear()}function update(source2,d4=1){var value=get2(source2),result=1===d4?value++:value--;set(source2,value);return result}function increment(source2){set(source2,source2.v+1)}function mark_reactions(signal,status,updated_during_traversal){var _a13,runes,length,i3,reaction,flags2,not_dirty,derived3,effect2,reactions=signal.reactions;if(null!==reactions){runes=is_runes();length=reactions.length;for(i3=0;i3<length;i3++){reaction=reactions[i3];flags2=reaction.f;if(runes||reaction!==active_effect){not_dirty=0===(flags2&DIRTY);not_dirty&&set_signal_status(reaction,status);if(0!==(flags2&EAGER_EFFECT))eager_effects.add(reaction);else if(0!==(flags2&DERIVED)){derived3=reaction;null==(_a13=batch_values)||_a13.delete(derived3);if(0===(flags2&WAS_MARKED)){flags2&CONNECTED&&(null===active_effect||0===(active_effect.f&REACTION_IS_UPDATING))&&(reaction.f|=WAS_MARKED);mark_reactions(derived3,MAYBE_DIRTY,updated_during_traversal)}}else if(not_dirty){effect2=reaction;0!==(flags2&BLOCK_EFFECT)&&null!==eager_block_effects&&eager_block_effects.add(effect2);null!==updated_during_traversal?updated_during_traversal.push(effect2):schedule_effect(effect2)}}}}}function proxy(value){function update_path(new_path){if(!updating){updating=!0;path2=new_path;tag(version2,`${path2} version`);for(const[prop2,source2]of sources)tag(source2,get_label(path2,prop2));updating=!1}}var sources,is_proxied_array,version2,stack2,parent_version,with_parent,path2;if("object"!=typeof value||null===value||STATE_SYMBOL in value)return value;const prototype=get_prototype_of(value);if(prototype!==object_prototype&&prototype!==array_prototype)return value;sources=new Map;is_proxied_array=is_array(value);version2=state(0);stack2=dev_fallback_default&&tracing_mode_flag?get_error("created at"):null;parent_version=update_version;with_parent=fn=>{var reaction,version3,result;if(update_version===parent_version)return fn();reaction=active_reaction;version3=update_version;set_active_reaction(null);set_update_version(parent_version);result=fn();set_active_reaction(reaction);set_update_version(version3);return result};if(is_proxied_array){sources.set("length",state(value.length,stack2));dev_fallback_default&&(value=inspectable_array(value))}path2="";let updating=!1;return new Proxy(value,{defineProperty(_,prop2,descriptor){"value"in descriptor&&!1!==descriptor.configurable&&!1!==descriptor.enumerable&&!1!==descriptor.writable||state_descriptors_fixed();var s2=sources.get(prop2);void 0===s2?with_parent(()=>{var s3=state(descriptor.value,stack2);sources.set(prop2,s3);dev_fallback_default&&"string"==typeof prop2&&tag(s3,get_label(path2,prop2));return s3}):set(s2,descriptor.value,!0);return!0},deleteProperty(target,prop2){var s2=sources.get(prop2);if(void 0===s2){if(prop2 in target){const s3=with_parent(()=>state(UNINITIALIZED,stack2));sources.set(prop2,s3);increment(version2);dev_fallback_default&&tag(s3,get_label(path2,prop2))}}else{set(s2,UNINITIALIZED);increment(version2)}return!0},get(target,prop2,receiver){var _a13,s2,exists,v2;if(prop2===STATE_SYMBOL)return value;if(dev_fallback_default&&prop2===PROXY_PATH_SYMBOL)return update_path;s2=sources.get(prop2);exists=prop2 in target;if(void 0===s2&&(!exists||(null==(_a13=get_descriptor(target,prop2))?void 0:_a13.writable))){s2=with_parent(()=>{var p2=proxy(exists?target[prop2]:UNINITIALIZED),s3=state(p2,stack2);dev_fallback_default&&tag(s3,get_label(path2,prop2));return s3});sources.set(prop2,s2)}if(void 0!==s2){v2=get2(s2);return v2===UNINITIALIZED?void 0:v2}return Reflect.get(target,prop2,receiver)},getOwnPropertyDescriptor(target,prop2){var s2,source2,value2,descriptor=Reflect.getOwnPropertyDescriptor(target,prop2);if(descriptor&&"value"in descriptor){s2=sources.get(prop2);s2&&(descriptor.value=get2(s2))}else if(void 0===descriptor){source2=sources.get(prop2);value2=null==source2?void 0:source2.v;if(void 0!==source2&&value2!==UNINITIALIZED)return{enumerable:!0,configurable:!0,value:value2,writable:!0}}return descriptor},has(target,prop2){var _a13,s2,has,value2;if(prop2===STATE_SYMBOL)return!0;s2=sources.get(prop2);has=void 0!==s2&&s2.v!==UNINITIALIZED||Reflect.has(target,prop2);if(void 0!==s2||null!==active_effect&&(!has||(null==(_a13=get_descriptor(target,prop2))?void 0:_a13.writable))){if(void 0===s2){s2=with_parent(()=>{var p2=has?proxy(target[prop2]):UNINITIALIZED,s3=state(p2,stack2);dev_fallback_default&&tag(s3,get_label(path2,prop2));return s3});sources.set(prop2,s2)}value2=get2(s2);if(value2===UNINITIALIZED)return!1}return has},set(target,prop2,value2,receiver){var _a13,i3,other_s,p2,descriptor,ls,n3,s2=sources.get(prop2),has=prop2 in target;if(is_proxied_array&&"length"===prop2)for(i3=value2;i3<s2.v;i3+=1){other_s=sources.get(i3+"");if(void 0!==other_s)set(other_s,UNINITIALIZED);else if(i3 in target){other_s=with_parent(()=>state(UNINITIALIZED,stack2));sources.set(i3+"",other_s);dev_fallback_default&&tag(other_s,get_label(path2,i3))}}if(void 0===s2){if(!has||(null==(_a13=get_descriptor(target,prop2))?void 0:_a13.writable)){s2=with_parent(()=>state(void 0,stack2));dev_fallback_default&&tag(s2,get_label(path2,prop2));set(s2,proxy(value2));sources.set(prop2,s2)}}else{has=s2.v!==UNINITIALIZED;p2=with_parent(()=>proxy(value2));set(s2,p2)}descriptor=Reflect.getOwnPropertyDescriptor(target,prop2);(null==descriptor?void 0:descriptor.set)&&descriptor.set.call(receiver,value2);if(!has){if(is_proxied_array&&"string"==typeof prop2){ls=sources.get("length");n3=Number(prop2);Number.isInteger(n3)&&n3>=ls.v&&set(ls,n3+1)}increment(version2)}return!0},ownKeys(target){var own_keys;get2(version2);own_keys=Reflect.ownKeys(target).filter(key4=>{var source3=sources.get(key4);return void 0===source3||source3.v!==UNINITIALIZED});for(var[key3,source2]of sources)source2.v===UNINITIALIZED||key3 in target||own_keys.push(key3);return own_keys},setPrototypeOf(){state_prototype_fixed()}})}function get_label(path2,prop2){var _a13;return"symbol"==typeof prop2?`${path2}[Symbol(${null!=(_a13=prop2.description)?_a13:""})]`:regex_is_valid_identifier.test(prop2)?`${path2}.${prop2}`:/^\d+$/.test(prop2)?`${path2}[${prop2}]`:`${path2}['${prop2}']`}function get_proxied_value(value){try{if(null!==value&&"object"==typeof value&&STATE_SYMBOL in value)return value[STATE_SYMBOL]}catch(e3){}return value}function is(a2,b3){return Object.is(get_proxied_value(a2),get_proxied_value(b3))}function inspectable_array(array){return new Proxy(array,{get(target,prop2,receiver){var value=Reflect.get(target,prop2,receiver);return ARRAY_MUTATING_METHODS.has(prop2)?function(...args){set_eager_effects_deferred();var result=value.apply(this,args);flush_eager_effects();return result}:value}})}function init_array_prototype_warnings(){const array_prototype2=Array.prototype,cleanup=Array.__svelte_cleanup;cleanup&&cleanup();const{indexOf,lastIndexOf,includes:includes2}=array_prototype2;array_prototype2.indexOf=function(item,from_index){const index6=indexOf.call(this,item,from_index);if(-1===index6)for(let i3=null!=from_index?from_index:0;i3<this.length;i3+=1)if(get_proxied_value(this[i3])===item){state_proxy_equality_mismatch("array.indexOf(...)");break}return index6};array_prototype2.lastIndexOf=function(item,from_index){const index6=lastIndexOf.call(this,item,null!=from_index?from_index:this.length-1);if(-1===index6)for(let i3=0;i3<=(null!=from_index?from_index:this.length-1);i3+=1)if(get_proxied_value(this[i3])===item){state_proxy_equality_mismatch("array.lastIndexOf(...)");break}return index6};array_prototype2.includes=function(item,from_index){const has=includes2.call(this,item,from_index);if(!has)for(let i3=0;i3<this.length;i3+=1)if(get_proxied_value(this[i3])===item){state_proxy_equality_mismatch("array.includes(...)");break}return has};Array.__svelte_cleanup=()=>{array_prototype2.indexOf=indexOf;array_prototype2.lastIndexOf=lastIndexOf;array_prototype2.includes=includes2}}function init_operations(){var element_prototype,node_prototype,text_prototype;if(void 0===$window){$window=window;document;is_firefox=/Firefox/.test(navigator.userAgent);element_prototype=Element.prototype;node_prototype=Node.prototype;text_prototype=Text.prototype;first_child_getter=get_descriptor(node_prototype,"firstChild").get;next_sibling_getter=get_descriptor(node_prototype,"nextSibling").get;if(is_extensible(element_prototype)){element_prototype[CLASS_CACHE]=void 0;element_prototype[ATTRIBUTES_CACHE]=null;element_prototype[STYLE_CACHE]=void 0;element_prototype.__e=void 0}is_extensible(text_prototype)&&(text_prototype[TEXT_CACHE]=void 0);if(dev_fallback_default){element_prototype.__svelte_meta=null;init_array_prototype_warnings()}}}function create_text(value=""){return document.createTextNode(value)}function get_first_child(node){return first_child_getter.call(node)}function get_next_sibling(node){return next_sibling_getter.call(node)}function child(node,is_text){var child2,text2;if(!hydrating)return get_first_child(node);child2=get_first_child(hydrate_node);if(null===child2)child2=hydrate_node.appendChild(create_text());else if(is_text&&child2.nodeType!==TEXT_NODE){text2=create_text();null==child2||child2.before(text2);set_hydrate_node(text2);return text2}is_text&&merge_text_nodes(child2);set_hydrate_node(child2);return child2}function first_child(node,is_text=!1){var _a13,_b6,first,text2;if(!hydrating){first=get_first_child(node);return first instanceof Comment&&""===first.data?get_next_sibling(first):first}if(is_text){if((null==(_a13=hydrate_node)?void 0:_a13.nodeType)!==TEXT_NODE){text2=create_text();null==(_b6=hydrate_node)||_b6.before(text2);set_hydrate_node(text2);return text2}merge_text_nodes(hydrate_node)}return hydrate_node}function sibling(node,count=1,is_text=!1){var last_sibling,text2;let next_sibling=hydrating?hydrate_node:node;for(;count--;){last_sibling=next_sibling;next_sibling=get_next_sibling(next_sibling)}if(!hydrating)return next_sibling;if(is_text){if((null==next_sibling?void 0:next_sibling.nodeType)!==TEXT_NODE){text2=create_text();null===next_sibling?null==last_sibling||last_sibling.after(text2):next_sibling.before(text2);set_hydrate_node(text2);return text2}merge_text_nodes(next_sibling)}set_hydrate_node(next_sibling);return next_sibling}function clear_text_content(node){node.textContent=""}function should_defer_append(){if(!async_mode_flag)return!1;if(null!==eager_block_effects)return!1;var flags2=active_effect.f;return 0!==(flags2&REACTION_RAN)}function create_element(tag3,namespace,is2){return null==namespace||namespace===NAMESPACE_HTML?is2?document.createElement(tag3,{is:is2}):document.createElement(tag3):is2?document.createElementNS(namespace,tag3,{is:is2}):document.createElementNS(namespace,tag3)}function merge_text_nodes(text2){if(text2.nodeValue.length<65536)return;let next2=text2.nextSibling;for(;null!==next2&&next2.nodeType===TEXT_NODE;){next2.remove();text2.nodeValue+=next2.nodeValue;next2=text2.nextSibling}}function remove_textarea_child(dom){hydrating&&null!==get_first_child(dom)&&clear_text_content(dom)}function add_form_reset_listener(){if(!listening_to_form_reset){listening_to_form_reset=!0;document.addEventListener("reset",evt=>{Promise.resolve().then(()=>{var _a13;if(!evt.defaultPrevented)for(const e3 of evt.target.elements)null==(_a13=e3[FORM_RESET_HANDLER])||_a13.call(e3)})},{capture:!0})}}function without_reactive_context(fn){var previous_reaction=active_reaction,previous_effect=active_effect;set_active_reaction(null);set_active_effect(null);try{return fn()}finally{set_active_reaction(previous_reaction);set_active_effect(previous_effect)}}function listen_to_event_and_reset_event(element2,event2,handler,on_reset=handler){element2.addEventListener(event2,()=>without_reactive_context(handler));const prev=element2[FORM_RESET_HANDLER];element2[FORM_RESET_HANDLER]=prev?()=>{prev();on_reset(!0)}:()=>on_reset(!0);add_form_reset_listener()}function validate_effect(rune){if(null===active_effect){null===active_reaction&&effect_orphan(rune);effect_in_unowned_derived()}is_destroying_effect&&effect_in_teardown(rune)}function push_effect(effect2,parent_effect){var parent_last=parent_effect.last;if(null===parent_last)parent_effect.last=parent_effect.first=effect2;else{parent_last.next=effect2;effect2.prev=parent_last;parent_effect.last=effect2}}function create_effect(type,fn){var _a13,_b6,effect2,e3,derived3,parent=active_effect;if(dev_fallback_default)for(;null!==parent&&0!==(parent.f&EAGER_EFFECT);)parent=parent.parent;null!==parent&&0!==(parent.f&INERT)&&(type|=INERT);effect2={ctx:component_context,deps:null,nodes:null,f:type|DIRTY|CONNECTED,first:null,fn,last:null,next:null,parent,b:parent&&parent.b,prev:null,teardown:null,wv:0,ac:null};dev_fallback_default&&(effect2.component_function=dev_current_component_function);null==(_a13=current_batch)||_a13.register_created_effect(effect2);e3=effect2;if(0!==(type&EFFECT))null!==collected_effects?collected_effects.push(effect2):Batch.ensure().schedule(effect2);else if(null!==fn){try{update_effect(effect2)}catch(e4){destroy_effect(effect2);throw e4}if(null===e3.deps&&null===e3.teardown&&null===e3.nodes&&e3.first===e3.last&&0===(e3.f&EFFECT_PRESERVED)){e3=e3.first;0!==(type&BLOCK_EFFECT)&&0!==(type&EFFECT_TRANSPARENT)&&null!==e3&&(e3.f|=EFFECT_TRANSPARENT)}}if(null!==e3){e3.parent=parent;null!==parent&&push_effect(e3,parent);if(null!==active_reaction&&0!==(active_reaction.f&DERIVED)&&0===(type&ROOT_EFFECT)){derived3=active_reaction;(null!=(_b6=derived3.effects)?_b6:derived3.effects=[]).push(e3)}}return effect2}function effect_tracking(){return null!==active_reaction&&!untracking}function teardown(fn){const effect2=create_effect(RENDER_EFFECT,null);set_signal_status(effect2,CLEAN);effect2.teardown=fn;return effect2}function user_effect(fn){var _a13,flags2,defer,context2;validate_effect("$effect");dev_fallback_default&&define_property(fn,"name",{value:"$effect"});flags2=active_effect.f;defer=!active_reaction&&0!==(flags2&BRANCH_EFFECT)&&null!==component_context&&!component_context.i;if(!defer)return create_user_effect(fn);context2=component_context;(null!=(_a13=context2.e)?_a13:context2.e=[]).push(fn)}function create_user_effect(fn){return create_effect(EFFECT|USER_EFFECT,fn)}function user_pre_effect(fn){validate_effect("$effect.pre");dev_fallback_default&&define_property(fn,"name",{value:"$effect.pre"});return create_effect(RENDER_EFFECT|USER_EFFECT,fn)}function effect_root(fn){Batch.ensure();const effect2=create_effect(ROOT_EFFECT|EFFECT_PRESERVED,fn);return()=>{destroy_effect(effect2)}}function component_root(fn){Batch.ensure();const effect2=create_effect(ROOT_EFFECT|EFFECT_PRESERVED,fn);return(options={})=>new Promise(fulfil=>{if(options.outro)pause_effect(effect2,()=>{destroy_effect(effect2);fulfil(void 0)});else{destroy_effect(effect2);fulfil(void 0)}})}function effect(fn){return create_effect(EFFECT,fn)}function legacy_pre_effect(deps,fn){var context2=component_context,token={effect:null,ran:!1,deps};context2.l.$.push(token);token.effect=render_effect(()=>{deps();if(!token.ran){token.ran=!0;var effect2=active_effect;try{set_active_effect(effect2.parent);untrack(fn)}finally{set_active_effect(effect2)}}})}function legacy_pre_effect_reset(){var context2=component_context;render_effect(()=>{var token,effect2;for(token of context2.l.$){token.deps();effect2=token.effect;0!==(effect2.f&CLEAN)&&null!==effect2.deps&&set_signal_status(effect2,MAYBE_DIRTY);is_dirty(effect2)&&update_effect(effect2);token.ran=!1}})}function async_effect(fn){return create_effect(ASYNC|EFFECT_PRESERVED,fn)}function render_effect(fn,flags2=0){return create_effect(RENDER_EFFECT|flags2,fn)}function template_effect(fn,sync2=[],async2=[],blockers=[]){flatten(blockers,sync2,async2,values2=>{create_effect(RENDER_EFFECT,()=>{fn(...values2.map(get2))})})}function block(fn,flags2=0){var effect2=create_effect(BLOCK_EFFECT|flags2,fn);dev_fallback_default&&(effect2.dev_stack=dev_stack);return effect2}function branch(fn){return create_effect(BRANCH_EFFECT|EFFECT_PRESERVED,fn)}function execute_effect_teardown(effect2){var teardown2=effect2.teardown;if(null!==teardown2){const previously_destroying_effect=is_destroying_effect,previous_reaction=active_reaction;set_is_destroying_effect(!0);set_active_reaction(null);try{teardown2.call(null)}finally{set_is_destroying_effect(previously_destroying_effect);set_active_reaction(previous_reaction)}}}function destroy_effect_children(signal,remove_dom=!1){var next2,effect2=signal.first;signal.first=signal.last=null;for(;null!==effect2;){const controller=effect2.ac;null!==controller&&without_reactive_context(()=>{controller.abort(STALE_REACTION)});next2=effect2.next;0!==(effect2.f&ROOT_EFFECT)?effect2.parent=null:destroy_effect(effect2,remove_dom);effect2=next2}}function destroy_block_effect_children(signal){for(var next2,effect2=signal.first;null!==effect2;){next2=effect2.next;0===(effect2.f&BRANCH_EFFECT)&&destroy_effect(effect2);effect2=next2}}function destroy_effect(effect2,remove_dom=!0){var transitions,parent,removed=!1;if((remove_dom||0!==(effect2.f&HEAD_EFFECT))&&null!==effect2.nodes&&null!==effect2.nodes.end){remove_effect_dom(effect2.nodes.start,effect2.nodes.end);removed=!0}effect2.f|=DESTROYING;destroy_effect_children(effect2,remove_dom&&!removed);remove_reactions(effect2,0);transitions=effect2.nodes&&effect2.nodes.t;if(null!==transitions)for(const transition2 of transitions)transition2.stop();execute_effect_teardown(effect2);effect2.f^=DESTROYING;effect2.f|=DESTROYED;parent=effect2.parent;null!==parent&&null!==parent.first&&unlink_effect(effect2);dev_fallback_default&&(effect2.component_function=null);effect2.next=effect2.prev=effect2.teardown=effect2.ctx=effect2.deps=effect2.fn=effect2.nodes=effect2.ac=effect2.b=null}function remove_effect_dom(node,end){for(;null!==node;){var next2=node===end?null:get_next_sibling(node);node.remove();node=next2}}function unlink_effect(effect2){var parent=effect2.parent,prev=effect2.prev,next2=effect2.next;null!==prev&&(prev.next=next2);null!==next2&&(next2.prev=prev);if(null!==parent){parent.first===effect2&&(parent.first=next2);parent.last===effect2&&(parent.last=prev)}}function pause_effect(effect2,callback,destroy2=!0){var fn,remaining,check,transition2,transitions=[];pause_children(effect2,transitions,!0);fn=()=>{destroy2&&destroy_effect(effect2);callback&&callback()};remaining=transitions.length;if(remaining>0){check=()=>--remaining||fn();for(transition2 of transitions)transition2.out(check)}else fn()}function pause_children(effect2,transitions,local){var t9,child2,sibling2,transparent;if(0===(effect2.f&INERT)){effect2.f^=INERT;t9=effect2.nodes&&effect2.nodes.t;if(null!==t9)for(const transition2 of t9)(transition2.is_global||local)&&transitions.push(transition2);child2=effect2.first;for(;null!==child2;){sibling2=child2.next;if(0===(child2.f&ROOT_EFFECT)){transparent=0!==(child2.f&EFFECT_TRANSPARENT)||0!==(child2.f&BRANCH_EFFECT)&&0!==(effect2.f&BLOCK_EFFECT);pause_children(child2,transitions,!!transparent&&local)}child2=sibling2}}}function resume_effect(effect2){resume_children(effect2,!0)}function resume_children(effect2,local){var child2,sibling2,transparent,t9;if(0!==(effect2.f&INERT)){effect2.f^=INERT;if(0===(effect2.f&CLEAN)){set_signal_status(effect2,DIRTY);Batch.ensure().schedule(effect2)}child2=effect2.first;for(;null!==child2;){sibling2=child2.next;transparent=0!==(child2.f&EFFECT_TRANSPARENT)||0!==(child2.f&BRANCH_EFFECT);resume_children(child2,!!transparent&&local);child2=sibling2}t9=effect2.nodes&&effect2.nodes.t;if(null!==t9)for(const transition2 of t9)(transition2.is_global||local)&&transition2.in()}}function move_effect(effect2,fragment){var node,end,next2;if(effect2.nodes){node=effect2.nodes.start;end=effect2.nodes.end;for(;null!==node;){next2=node===end?null:get_next_sibling(node);fragment.append(node);node=next2}}}function capture_signals(fn){var signal,previous_captured_signals=captured_signals;try{captured_signals=new Set;untrack(fn);if(null!==previous_captured_signals)for(signal of captured_signals)previous_captured_signals.add(signal);return captured_signals}finally{captured_signals=previous_captured_signals}}function invalidate_inner_signals(fn){for(var signal of capture_signals(fn))internal_set(signal,signal.v)}function set_is_destroying_effect(value){is_destroying_effect=value}function set_active_reaction(reaction){active_reaction=reaction}function set_active_effect(effect2){active_effect=effect2}function push_reaction_value(value){null===active_reaction||async_mode_flag&&0===(active_reaction.f&DERIVED)||(null!=current_sources?current_sources:current_sources=new Set).add(value)}function set_untracked_writes(value){untracked_writes=value}function set_update_version(value){update_version=value}function increment_write_version(){return++write_version}function is_dirty(reaction){var dependencies,length,i3,dependency,flags2=reaction.f;if(0!==(flags2&DIRTY))return!0;flags2&DERIVED&&(reaction.f&=~WAS_MARKED);if(0!==(flags2&MAYBE_DIRTY)){dependencies=reaction.deps;length=dependencies.length;for(i3=0;i3<length;i3++){dependency=dependencies[i3];is_dirty(dependency)&&update_derived(dependency);if(dependency.wv>reaction.wv)return!0}0!==(flags2&CONNECTED)&&null===batch_values&&set_signal_status(reaction,CLEAN)}return!1}function schedule_possible_effect_self_invalidation(signal,effect2,root44=!0){var i3,reaction,reactions=signal.reactions;if(null!==reactions&&(async_mode_flag||null===current_sources||!current_sources.has(signal)))for(i3=0;i3<reactions.length;i3++){reaction=reactions[i3];if(0!==(reaction.f&DERIVED))schedule_possible_effect_self_invalidation(reaction,effect2,!1);else if(effect2===reaction){root44?set_signal_status(reaction,DIRTY):0!==(reaction.f&CLEAN)&&set_signal_status(reaction,MAYBE_DIRTY);schedule_effect(reaction)}}}function update_reaction(reaction){var _a13,_b6,_c3,fn,result,deps,is_fork,i3,previous_deps=new_deps,previous_skipped_deps=skipped_deps,previous_untracked_writes=untracked_writes,previous_reaction=active_reaction,previous_sources=current_sources,previous_component_context=component_context,previous_untracking=untracking,previous_update_version=update_version,flags2=reaction.f;new_deps=null;skipped_deps=0;untracked_writes=null;active_reaction=0===(flags2&(BRANCH_EFFECT|ROOT_EFFECT))?reaction:null;current_sources=null;set_component_context(reaction.ctx);untracking=!1;update_version=++read_version;if(null!==reaction.ac){without_reactive_context(()=>{reaction.ac.abort(STALE_REACTION)});reaction.ac=null}try{reaction.f|=REACTION_IS_UPDATING;fn=reaction.fn;result=fn();reaction.f|=REACTION_RAN;deps=reaction.deps;is_fork=null==(_a13=current_batch)?void 0:_a13.is_fork;if(null!==new_deps){is_fork||remove_reactions(reaction,skipped_deps);if(null!==deps&&skipped_deps>0){deps.length=skipped_deps+new_deps.length;for(i3=0;i3<new_deps.length;i3++)deps[skipped_deps+i3]=new_deps[i3]}else reaction.deps=deps=new_deps;if(effect_tracking()&&0!==(reaction.f&CONNECTED))for(i3=skipped_deps;i3<deps.length;i3++)(null!=(_c3=(_b6=deps[i3]).reactions)?_c3:_b6.reactions=[]).push(reaction)}else if(!is_fork&&null!==deps&&skipped_deps<deps.length){remove_reactions(reaction,skipped_deps);deps.length=skipped_deps}if(is_runes()&&null!==untracked_writes&&!untracking&&null!==deps&&0===(reaction.f&(DERIVED|MAYBE_DIRTY|DIRTY)))for(i3=0;i3<untracked_writes.length;i3++)schedule_possible_effect_self_invalidation(untracked_writes[i3],reaction);if(null!==previous_reaction&&previous_reaction!==reaction){read_version++;if(null!==previous_reaction.deps)for(let i4=0;i4<previous_skipped_deps;i4+=1)previous_reaction.deps[i4].rv=read_version;if(null!==previous_deps)for(const dep of previous_deps)dep.rv=read_version;null!==untracked_writes&&(null===previous_untracked_writes?previous_untracked_writes=untracked_writes:previous_untracked_writes.push(...untracked_writes))}0!==(reaction.f&ERROR_VALUE)&&(reaction.f^=ERROR_VALUE);return result}catch(error){return handle_error(error)}finally{reaction.f^=REACTION_IS_UPDATING;new_deps=previous_deps;skipped_deps=previous_skipped_deps;untracked_writes=previous_untracked_writes;active_reaction=previous_reaction;current_sources=previous_sources;set_component_context(previous_component_context);untracking=previous_untracking;update_version=previous_update_version}}function remove_reaction(signal,dependency){var index6,new_length,derived3;let reactions=dependency.reactions;if(null!==reactions){index6=index_of.call(reactions,signal);if(-1!==index6){new_length=reactions.length-1;if(0===new_length)reactions=dependency.reactions=null;else{reactions[index6]=reactions[new_length];reactions.pop()}}}if(null===reactions&&0!==(dependency.f&DERIVED)&&(null===new_deps||!includes.call(new_deps,dependency))){derived3=dependency;if(0!==(derived3.f&CONNECTED)){derived3.f^=CONNECTED;derived3.f&=~WAS_MARKED}derived3.v!==UNINITIALIZED&&update_derived_status(derived3);freeze_derived_effects(derived3);remove_reactions(derived3,0)}}function remove_reactions(signal,start_index){var i3,dependencies=signal.deps;if(null!==dependencies)for(i3=start_index;i3<dependencies.length;i3++)remove_reaction(signal,dependencies[i3])}function update_effect(effect2){var _a13,previous_effect,was_updating_effect,previous_component_fn,previous_stack,teardown2,dep,flags2=effect2.f;if(0===(flags2&DESTROYED)){set_signal_status(effect2,CLEAN);previous_effect=active_effect;was_updating_effect=is_updating_effect;active_effect=effect2;is_updating_effect=!0;if(dev_fallback_default){previous_component_fn=dev_current_component_function;set_dev_current_component_function(effect2.component_function);previous_stack=dev_stack;set_dev_stack(null!=(_a13=effect2.dev_stack)?_a13:dev_stack)}try{0!==(flags2&(BLOCK_EFFECT|MANAGED_EFFECT))?destroy_block_effect_children(effect2):destroy_effect_children(effect2);execute_effect_teardown(effect2);teardown2=update_reaction(effect2);effect2.teardown="function"==typeof teardown2?teardown2:null;effect2.wv=write_version;if(dev_fallback_default&&tracing_mode_flag&&0!==(effect2.f&DIRTY)&&null!==effect2.deps)for(dep of effect2.deps)if(dep.set_during_effect){dep.wv=increment_write_version();dep.set_during_effect=!1}}finally{is_updating_effect=was_updating_effect;active_effect=previous_effect;if(dev_fallback_default){set_dev_current_component_function(previous_component_fn);set_dev_stack(previous_stack)}}}}async function tick(){if(async_mode_flag)return new Promise(f4=>{requestAnimationFrame(()=>f4());setTimeout(()=>f4())});await Promise.resolve();flushSync()}function get2(signal){var _a13,_c3,destroyed,deps,reactions,trace2,entry,last,derived3,value,should_connect,is_new,flags2=signal.f,is_derived=0!==(flags2&DERIVED);null==(_a13=captured_signals)||_a13.add(signal);if(null!==active_reaction&&!untracking){destroyed=null!==active_effect&&0!==(active_effect.f&DESTROYED);if(!(destroyed||null!==current_sources&&current_sources.has(signal))){deps=active_reaction.deps;if(0!==(active_reaction.f&REACTION_IS_UPDATING)){if(signal.rv<read_version){signal.rv=read_version;null===new_deps&&null!==deps&&deps[skipped_deps]===signal?skipped_deps++:null===new_deps?new_deps=[signal]:new_deps.push(signal)}}else{null!=active_reaction.deps||(active_reaction.deps=[]);includes.call(active_reaction.deps,signal)||active_reaction.deps.push(signal);reactions=signal.reactions;null===reactions?signal.reactions=[active_reaction]:includes.call(reactions,active_reaction)||reactions.push(active_reaction)}}}if(dev_fallback_default){if(!untracking&&reactivity_loss_tracker&&null===current_batch&&null===previous_batch&&!reactivity_loss_tracker.warned&&0===(reactivity_loss_tracker.effect.f&REACTION_IS_UPDATING)&&!reactivity_loss_tracker.effect_deps.has(signal)){reactivity_loss_tracker.warned=!0;await_reactivity_loss(signal.label);trace2=get_error("traced at");trace2&&console.warn(trace2)}recent_async_deriveds.delete(signal);if(tracing_mode_flag&&!untracking&&null!==tracing_expressions&&null!==active_reaction&&tracing_expressions.reaction===active_reaction)if(signal.trace)signal.trace();else{trace2=get_error("traced at");if(trace2){entry=tracing_expressions.entries.get(signal);if(void 0===entry){entry={traces:[]};tracing_expressions.entries.set(signal,entry)}last=entry.traces[entry.traces.length-1];trace2.stack!==(null==last?void 0:last.stack)&&entry.traces.push(trace2)}}}if(is_destroying_effect&&old_values.has(signal))return old_values.get(signal);if(is_derived){derived3=signal;if(is_destroying_effect){value=derived3.v;(0===(derived3.f&CLEAN)&&null!==derived3.reactions||depends_on_old_values(derived3))&&(value=execute_derived(derived3));old_values.set(derived3,value);return value}should_connect=0===(derived3.f&CONNECTED)&&!untracking&&null!==active_reaction&&(is_updating_effect||0!==(active_reaction.f&CONNECTED));is_new=0===(derived3.f&REACTION_RAN);if(is_dirty(derived3)){should_connect&&(derived3.f|=CONNECTED);update_derived(derived3)}if(should_connect&&!is_new){unfreeze_derived_effects(derived3);reconnect(derived3)}}if(null==(_c3=batch_values)?void 0:_c3.has(signal))return batch_values.get(signal);if(0!==(signal.f&ERROR_VALUE))throw signal.v;return signal.v}function reconnect(derived3){var _a13;derived3.f|=CONNECTED;if(null!==derived3.deps)for(const dep of derived3.deps){(null!=(_a13=dep.reactions)?_a13:dep.reactions=[]).push(derived3);if(0!==(dep.f&DERIVED)&&0===(dep.f&CONNECTED)){unfreeze_derived_effects(dep);reconnect(dep)}}}function depends_on_old_values(derived3){if(derived3.v===UNINITIALIZED)return!0;if(null===derived3.deps)return!1;for(const dep of derived3.deps){if(old_values.has(dep))return!0;if(0!==(dep.f&DERIVED)&&depends_on_old_values(dep))return!0}return!1}function untrack(fn){var previous_untracking=untracking;try{untracking=!0;return fn()}finally{untracking=previous_untracking}}function deep_read_state(value){if("object"==typeof value&&value&&!(value instanceof EventTarget))if(STATE_SYMBOL in value)deep_read(value);else if(!Array.isArray(value))for(let key3 in value){const prop2=value[key3];"object"==typeof prop2&&prop2&&STATE_SYMBOL in prop2&&deep_read(prop2)}}function deep_read(value,visited=new Set){if(!("object"!=typeof value||null===value||value instanceof EventTarget||visited.has(value))){visited.add(value);value instanceof Date&&value.getTime();for(let key3 in value)try{deep_read(value[key3],visited)}catch(e3){}const proto=get_prototype_of(value);if(proto!==Object.prototype&&proto!==Array.prototype&&proto!==Map.prototype&&proto!==Set.prototype&&proto!==Date.prototype){const descriptors=get_descriptors(proto);for(let key3 in descriptors){const get5=descriptors[key3].get;if(get5)try{get5.call(value)}catch(e3){}}}}}function create_event(event_name,dom,handler,options={}){function target_handler(event2){options.capture||handle_event_propagation.call(dom,event2);if(!event2.cancelBubble)return without_reactive_context(()=>null==handler?void 0:handler.call(this,event2))}event_name.startsWith("pointer")||event_name.startsWith("touch")||"wheel"===event_name?queue_micro_task(()=>{dom.addEventListener(event_name,target_handler,options)}):dom.addEventListener(event_name,target_handler,options);return target_handler}function event(event_name,dom,handler,capture2,passive2){var options={capture:capture2,passive:passive2},target_handler=create_event(event_name,dom,handler,options);(dom===document.body||dom===window||dom===document||dom instanceof HTMLMediaElement)&&teardown(()=>{dom.removeEventListener(event_name,target_handler,options)})}function delegated(event_name,element2,handler){var _a13;(null!=(_a13=element2[event_symbol])?_a13:element2[event_symbol]={})[event_name]=handler}function delegate(events){var i3,fn;for(i3=0;i3<events.length;i3++)all_registered_events.add(events[i3]);for(fn of root_event_handles)fn(events)}function handle_event_propagation(event2){var _a13,_b6,path_idx,handled_at,at_idx,handler_idx,previous_reaction,previous_effect,throw_error,other_errors,delegated2,handler_element=this,owner_document=handler_element.ownerDocument,event_name=event2.type,path2=(null==(_a13=event2.composedPath)?void 0:_a13.call(event2))||[],current_target=path2[0]||event2.target;last_propagated_event=event2;path_idx=0;handled_at=last_propagated_event===event2&&event2[event_symbol];if(handled_at){at_idx=path2.indexOf(handled_at);if(-1!==at_idx&&(handler_element===document||handler_element===window)){event2[event_symbol]=handler_element;return}handler_idx=path2.indexOf(handler_element);if(-1===handler_idx)return;at_idx<=handler_idx&&(path_idx=at_idx)}current_target=path2[path_idx]||event2.target;if(current_target!==handler_element){define_property(event2,"currentTarget",{configurable:!0,get:()=>current_target||owner_document});previous_reaction=active_reaction;previous_effect=active_effect;set_active_reaction(null);set_active_effect(null);try{other_errors=[];for(;null!==current_target&&current_target!==handler_element;){try{delegated2=null==(_b6=current_target[event_symbol])?void 0:_b6[event_name];null==delegated2||current_target.disabled&&event2.target!==current_target||delegated2.call(current_target,event2)}catch(error){throw_error?other_errors.push(error):throw_error=error}if(event2.cancelBubble)break;path_idx++;current_target=path_idx<path2.length?path2[path_idx]:null}if(throw_error){for(let error of other_errors)queueMicrotask(()=>{throw error});throw throw_error}}finally{event2[event_symbol]=handler_element;delete event2.currentTarget;set_active_reaction(previous_reaction);set_active_effect(previous_effect)}}}function create_trusted_html(html2){var _a13;return null!=(_a13=null==policy?void 0:policy.createHTML(html2))?_a13:html2}function create_fragment_from_html(html2){var elem=create_element("template");elem.innerHTML=create_trusted_html(html2.replaceAll("<!>","\x3c!----\x3e"));return elem.content}function assign_nodes(start,end){var effect2=active_effect;null===effect2.nodes&&(effect2.nodes={start,end,a:null,t:null})}function from_html(content,flags2){var node,is_fragment=0!==(flags2&TEMPLATE_FRAGMENT),use_import_node=0!==(flags2&TEMPLATE_USE_IMPORT_NODE),has_start=!content.startsWith("<!>");return()=>{var clone3,start,end;if(hydrating){assign_nodes(hydrate_node,null);return hydrate_node}if(void 0===node){node=create_fragment_from_html(has_start?content:"<!>"+content);is_fragment||(node=get_first_child(node))}clone3=use_import_node||is_firefox?document.importNode(node,!0):node.cloneNode(!0);if(is_fragment){start=get_first_child(clone3);end=clone3.lastChild;assign_nodes(start,end)}else assign_nodes(clone3,clone3);return clone3}}function text(value=""){var t9,node;if(!hydrating){t9=create_text(value+"");assign_nodes(t9,t9);return t9}node=hydrate_node;if(node.nodeType!==TEXT_NODE){node.before(node=create_text());set_hydrate_node(node)}else merge_text_nodes(node);assign_nodes(node,node);return node}function comment(){var frag,start,anchor;if(hydrating){assign_nodes(hydrate_node,null);return hydrate_node}frag=document.createDocumentFragment();start=document.createComment("");anchor=create_text();frag.append(start,anchor);assign_nodes(start,anchor);return frag}function append(anchor,dom){if(hydrating){var effect2=active_effect;0!==(effect2.f&REACTION_RAN)&&null!==effect2.nodes.end||(effect2.nodes.end=hydrate_node);hydrate_next()}else null!==anchor&&anchor.before(dom)}function is_passive_event(name){return PASSIVE_EVENTS.includes(name)}function set_text(text2,value){var _a13,_b6,str=null==value?"":"object"==typeof value?`${value}`:value;if(str!==(null!=(_b6=text2[_a13=TEXT_CACHE])?_b6:text2[_a13]=text2.nodeValue)){text2[TEXT_CACHE]=str;text2.nodeValue=`${str}`}}function mount(component2,options){return _mount(component2,options)}function hydrate(component2,options){var _a13,anchor;init_operations();options.intro=null!=(_a13=options.intro)&&_a13;const target=options.target,was_hydrating=hydrating,previous_hydrate_node=hydrate_node;try{anchor=get_first_child(target);for(;anchor&&(anchor.nodeType!==COMMENT_NODE||anchor.data!==HYDRATION_START);)anchor=get_next_sibling(anchor);if(!anchor)throw HYDRATION_ERROR;set_hydrating(!0);set_hydrate_node(anchor);const instance=_mount(component2,{...options,anchor});set_hydrating(!1);return instance}catch(error){if(error instanceof Error&&error.message.split("\n").some(line=>line.startsWith("https://svelte.dev/e/")))throw error;error!==HYDRATION_ERROR&&console.warn("Failed to hydrate: ",error);!1===options.recover&&hydration_failed();init_operations();clear_text_content(target);set_hydrating(!1);return mount(component2,options)}finally{set_hydrating(was_hydrating);set_hydrate_node(previous_hydrate_node)}}function _mount(Component3,{target,anchor,props={},events,context:context2,intro=!0,transformError}){var component2,unmount2;init_operations();component2=void 0;unmount2=component_root(()=>{var registered_events,event_handle,anchor_node=null!=anchor?anchor:target.appendChild(create_text());boundary(anchor_node,{pending:()=>{}},anchor_node2=>{push({});var ctx=component_context;context2&&(ctx.c=context2);events&&(props.$$events=events);hydrating&&assign_nodes(anchor_node2,null);0;component2=Component3(anchor_node2,props)||{};0;if(hydrating){active_effect.nodes.end=hydrate_node;if(null===hydrate_node||hydrate_node.nodeType!==COMMENT_NODE||hydrate_node.data!==HYDRATION_END){hydration_mismatch();throw HYDRATION_ERROR}}pop()},transformError);registered_events=new Set;event_handle=events2=>{var i3,event_name,passive2,counts,count;for(i3=0;i3<events2.length;i3++){event_name=events2[i3];if(!registered_events.has(event_name)){registered_events.add(event_name);passive2=is_passive_event(event_name);for(const node of[target,document]){counts=listeners.get(node);if(void 0===counts){counts=new Map;listeners.set(node,counts)}count=counts.get(event_name);if(void 0===count){node.addEventListener(event_name,handle_event_propagation,{passive:passive2});counts.set(event_name,1)}else counts.set(event_name,count+1)}}}};event_handle(array_from(all_registered_events));root_event_handles.add(event_handle);return()=>{var _a13,event_name,counts,count;for(event_name of registered_events)for(const node of[target,document]){counts=listeners.get(node);count=counts.get(event_name);if(0==--count){node.removeEventListener(event_name,handle_event_propagation);counts.delete(event_name);0===counts.size&&listeners.delete(node)}else counts.set(event_name,count)}root_event_handles.delete(event_handle);anchor_node!==anchor&&(null==(_a13=anchor_node.parentNode)||_a13.removeChild(anchor_node))}});mounted_components.set(component2,unmount2);return component2}function unmount(component2,options){const fn=mounted_components.get(component2);if(fn){mounted_components.delete(component2);return fn(options)}dev_fallback_default&&(STATE_SYMBOL in component2?state_proxy_unmount():lifecycle_double_unmount());return Promise.resolve()}function snippet(node,get_snippet,...args){var branches=new BranchManager(node);block(()=>{var _a13;const snippet2=null!=(_a13=get_snippet())?_a13:null;dev_fallback_default&&null==snippet2&&invalid_snippet();branches.ensure(snippet2,snippet2&&(anchor=>snippet2(anchor,...args)))},EFFECT_TRANSPARENT)}function onMount(fn){null===component_context&&lifecycle_outside_component("onMount");legacy_mode_flag&&null!==component_context.l?init_update_callbacks(component_context).m.push(fn):user_effect(()=>{const cleanup=untrack(fn);if("function"==typeof cleanup)return cleanup})}function onDestroy(fn){null===component_context&&lifecycle_outside_component("onDestroy");onMount(()=>()=>untrack(fn))}function init_update_callbacks(context2){var _a13,l2=context2.l;return null!=(_a13=l2.u)?_a13:l2.u={a:[],b:[],m:[]}}function register_style(hash3,style){var styles=all_styles.get(hash3);if(!styles){styles=new Set;all_styles.set(hash3,styles)}styles.add(style)}function if_block(node,fn,elseif=!1){function update_branch(key3,fn2){var data,anchor;if(hydrating){data=read_hydration_instruction(marker);if(key3!==parseInt(data.substring(1))){anchor=skip_nodes();set_hydrate_node(anchor);branches.anchor=anchor;set_hydrating(!1);branches.ensure(key3,fn2);set_hydrating(!0);return}}branches.ensure(key3,fn2)}var marker,branches,flags2;if(hydrating){marker=hydrate_node;hydrate_next()}branches=new BranchManager(node);flags2=elseif?EFFECT_TRANSPARENT:0;block(()=>{var has_branch=!1;fn((fn2,key3=0)=>{has_branch=!0;update_branch(key3,fn2)});has_branch||update_branch(-1,null)},flags2)}function index(_,i3){return i3}function pause_effects(state2,to_destroy,controlled_anchor){var _a13,group4,i3,fast_path,anchor,parent_node,transitions=[],length=to_destroy.length,remaining=to_destroy.length;for(i3=0;i3<length;i3++){let effect2=to_destroy[i3];pause_effect(effect2,()=>{if(group4){group4.pending.delete(effect2);group4.done.add(effect2);if(0===group4.pending.size){var groups=state2.outrogroups;destroy_effects(state2,array_from(group4.done));groups.delete(group4);0===groups.size&&(state2.outrogroups=null)}}else remaining-=1},!1)}if(0===remaining){fast_path=0===transitions.length&&null!==controlled_anchor;if(fast_path){anchor=controlled_anchor;parent_node=anchor.parentNode;clear_text_content(parent_node);parent_node.append(anchor);state2.items.clear()}destroy_effects(state2,to_destroy,!fast_path)}else{group4={pending:new Set(to_destroy),done:new Set};(null!=(_a13=state2.outrogroups)?_a13:state2.outrogroups=new Set).add(group4)}}function destroy_effects(state2,to_destroy,remove_dom=!0){var preserved_effects,i3,e3;if(state2.pending.size>0){preserved_effects=new Set;for(const keys3 of state2.pending.values())for(const key3 of keys3)preserved_effects.add(state2.items.get(key3).e)}for(i3=0;i3<to_destroy.length;i3++){e3=to_destroy[i3];if(null==preserved_effects?void 0:preserved_effects.has(e3)){e3.f|=EFFECT_OFFSCREEN;const fragment=document.createDocumentFragment();move_effect(e3,fragment)}else destroy_effect(to_destroy[i3],remove_dom)}}function each(node,flags2,get_collection,get_key,render_fn2,fallback_fn=null){function commit(batch){if(0===(state2.effect.f&DESTROYED)){state2.pending.delete(batch);state2.fallback=fallback3;reconcile(state2,array,anchor,flags2,get_key);if(null!==fallback3)if(0===array.length)if(0===(fallback3.f&EFFECT_OFFSCREEN))resume_effect(fallback3);else{fallback3.f^=EFFECT_OFFSCREEN;move(fallback3,null,anchor)}else pause_effect(fallback3,()=>{fallback3=null})}}function discard(batch){state2.pending.delete(batch)}var parent_node,fallback3,each_array,array,pending3,first_run,effect2,state2,anchor=node,items=new Map,is_controlled=0!==(flags2&EACH_IS_CONTROLLED);if(is_controlled){parent_node=node;anchor=hydrating?set_hydrate_node(get_first_child(parent_node)):parent_node.appendChild(create_text())}hydrating&&hydrate_next();fallback3=null;each_array=derived_safe_equal(()=>{var collection=get_collection();return is_array(collection)?collection:null==collection?[]:array_from(collection)});dev_fallback_default&&tag(each_array,"{#each ...}");pending3=new Map;first_run=!0;effect2=block(()=>{var length,is_else,keys3,batch,defer,index6,value,key3,key_again,item;array=get2(each_array);length=array.length;let mismatch=!1;if(hydrating){is_else=read_hydration_instruction(anchor)===HYDRATION_START_ELSE;if(is_else!==(0===length)){anchor=skip_nodes();set_hydrate_node(anchor);set_hydrating(!1);mismatch=!0}}keys3=new Set;batch=current_batch;defer=should_defer_append();for(index6=0;index6<length;index6+=1){if(hydrating&&hydrate_node.nodeType===COMMENT_NODE&&hydrate_node.data===HYDRATION_END){anchor=hydrate_node;mismatch=!0;set_hydrating(!1)}value=array[index6];key3=get_key(value,index6);if(dev_fallback_default){key_again=get_key(value,index6);key3!==key_again&&each_key_volatile(String(index6),String(key3),String(key_again))}item=first_run?null:items.get(key3);if(item){item.v&&internal_set(item.v,value);item.i&&internal_set(item.i,index6);defer&&batch.unskip_effect(item.e)}else{item=create_item(items,first_run?anchor:null!=offscreen_anchor?offscreen_anchor:offscreen_anchor=create_text(),value,key3,index6,render_fn2,flags2,get_collection);first_run||(item.e.f|=EFFECT_OFFSCREEN);items.set(key3,item)}keys3.add(key3)}if(0===length&&fallback_fn&&!fallback3)if(first_run)fallback3=branch(()=>fallback_fn(anchor));else{fallback3=branch(()=>fallback_fn(null!=offscreen_anchor?offscreen_anchor:offscreen_anchor=create_text()));fallback3.f|=EFFECT_OFFSCREEN}length>keys3.size&&(dev_fallback_default?validate_each_keys(array,get_key):each_key_duplicate("","",""));hydrating&&length>0&&set_hydrate_node(skip_nodes());if(!first_run){pending3.set(batch,keys3);if(defer){for(const[key4,item2]of items)keys3.has(key4)||batch.skip_effect(item2.e);batch.oncommit(commit);batch.ondiscard(discard)}else commit(batch)}mismatch&&set_hydrating(!0);get2(each_array)});state2={effect:effect2,flags:flags2,items,pending:pending3,outrogroups:null,fallback:fallback3};first_run=!1;hydrating&&(anchor=hydrate_node)}function skip_to_branch(effect2){for(;null!==effect2&&0===(effect2.f&BRANCH_EFFECT);)effect2=effect2.next;return effect2}function reconcile(state2,array,anchor,flags2,get_key){var _a13,_b6,_c3,_d2,_e2,_f,_g,_h2,_i2,seen,to_animate,value,key3,effect2,i3,next2,start,j2,a2,b3,to_destroy,destroy_length,controlled_anchor,is_animated=0!==(flags2&EACH_IS_ANIMATED),length=array.length,items=state2.items,current=skip_to_branch(state2.effect.first),prev=null,matched=[],stashed=[];if(is_animated)for(i3=0;i3<length;i3+=1){value=array[i3];key3=get_key(value,i3);effect2=items.get(key3).e;if(0===(effect2.f&EFFECT_OFFSCREEN)){null==(_b6=null==(_a13=effect2.nodes)?void 0:_a13.a)||_b6.measure();(null!=to_animate?to_animate:to_animate=new Set).add(effect2)}}for(i3=0;i3<length;i3+=1){value=array[i3];key3=get_key(value,i3);effect2=items.get(key3).e;if(null!==state2.outrogroups)for(const group4 of state2.outrogroups){group4.pending.delete(effect2);group4.done.delete(effect2)}if(0!==(effect2.f&INERT)){resume_effect(effect2);if(is_animated){null==(_d2=null==(_c3=effect2.nodes)?void 0:_c3.a)||_d2.unfix();(null!=to_animate?to_animate:to_animate=new Set).delete(effect2)}}if(0!==(effect2.f&EFFECT_OFFSCREEN)){effect2.f^=EFFECT_OFFSCREEN;if(effect2!==current){next2=prev?prev.next:current;effect2===state2.effect.last&&(state2.effect.last=effect2.prev);effect2.prev&&(effect2.prev.next=effect2.next);effect2.next&&(effect2.next.prev=effect2.prev);link(state2,prev,effect2);link(state2,effect2,next2);move(effect2,next2,anchor);prev=effect2;matched=[];stashed=[];current=skip_to_branch(prev.next);continue}move(effect2,null,anchor)}if(effect2!==current){if(void 0!==seen&&seen.has(effect2)){if(matched.length<stashed.length){start=stashed[0];prev=start.prev;a2=matched[0];b3=matched[matched.length-1];for(j2=0;j2<matched.length;j2+=1)move(matched[j2],start,anchor);for(j2=0;j2<stashed.length;j2+=1)seen.delete(stashed[j2]);link(state2,a2.prev,b3.next);link(state2,prev,a2);link(state2,b3,start);current=start;prev=b3;i3-=1;matched=[];stashed=[]}else{seen.delete(effect2);move(effect2,current,anchor);link(state2,effect2.prev,effect2.next);link(state2,effect2,null===prev?state2.effect.first:prev.next);link(state2,prev,effect2);prev=effect2}continue}matched=[];stashed=[];for(;null!==current&&current!==effect2;){(null!=seen?seen:seen=new Set).add(current);stashed.push(current);current=skip_to_branch(current.next)}if(null===current)continue}0===(effect2.f&EFFECT_OFFSCREEN)&&matched.push(effect2);prev=effect2;current=skip_to_branch(effect2.next)}if(null!==state2.outrogroups){for(const group4 of state2.outrogroups)if(0===group4.pending.size){destroy_effects(state2,array_from(group4.done));null==(_e2=state2.outrogroups)||_e2.delete(group4)}0===state2.outrogroups.size&&(state2.outrogroups=null)}if(null!==current||void 0!==seen){to_destroy=[];if(void 0!==seen)for(effect2 of seen)0===(effect2.f&INERT)&&to_destroy.push(effect2);for(;null!==current;){0===(current.f&INERT)&&current!==state2.fallback&&to_destroy.push(current);current=skip_to_branch(current.next)}destroy_length=to_destroy.length;if(destroy_length>0){controlled_anchor=0!==(flags2&EACH_IS_CONTROLLED)&&0===length?anchor:null;if(is_animated){for(i3=0;i3<destroy_length;i3+=1)null==(_g=null==(_f=to_destroy[i3].nodes)?void 0:_f.a)||_g.measure();for(i3=0;i3<destroy_length;i3+=1)null==(_i2=null==(_h2=to_destroy[i3].nodes)?void 0:_h2.a)||_i2.fix()}pause_effects(state2,to_destroy,controlled_anchor)}}is_animated&&queue_micro_task(()=>{var _a14,_b7;if(void 0!==to_animate)for(effect2 of to_animate)null==(_b7=null==(_a14=effect2.nodes)?void 0:_a14.a)||_b7.apply()})}function create_item(items,anchor,value,key3,index6,render_fn2,flags2,get_collection){var v2=0!==(flags2&EACH_ITEM_REACTIVE)?0===(flags2&EACH_ITEM_IMMUTABLE)?mutable_source(value,!1,!1):source(value):null,i3=0!==(flags2&EACH_INDEX_REACTIVE)?source(index6):null;dev_fallback_default&&v2&&(v2.trace=()=>{var _a13;get_collection()[null!=(_a13=null==i3?void 0:i3.v)?_a13:index6]});return{v:v2,i:i3,e:branch(()=>{render_fn2(anchor,null!=v2?v2:value,null!=i3?i3:index6,get_collection);return()=>{items.delete(key3)}})}}function move(effect2,next2,anchor){var node,end,dest,next_node;if(effect2.nodes){node=effect2.nodes.start;end=effect2.nodes.end;dest=next2&&0===(next2.f&EFFECT_OFFSCREEN)?next2.nodes.start:anchor;for(;null!==node;){next_node=get_next_sibling(node);dest.before(node);if(node===end)return;node=next_node}}}function link(state2,prev,next2){null===prev?state2.effect.first=next2:prev.next=next2;null===next2?state2.effect.last=prev:next2.prev=prev}function validate_each_keys(array,key_fn){const keys3=new Map,length=array.length;for(let i3=0;i3<length;i3++){const key3=key_fn(array[i3],i3);if(keys3.has(key3)){const a2=String(keys3.get(key3)),b3=String(i3);let k2=String(key3);k2.startsWith("[object ")&&(k2=null);each_key_duplicate(a2,b3,k2)}keys3.set(key3,i3)}}function component(node,get_component,render_fn2){var hydration_start_node,branches;if(hydrating){hydration_start_node=hydrate_node;hydrate_next()}branches=new BranchManager(node);block(()=>{var _a13,data,server_had_component,client_has_component,anchor,component2=null!=(_a13=get_component())?_a13:null;if(hydrating){data=read_hydration_instruction(hydration_start_node);server_had_component=data===HYDRATION_START;client_has_component=null!==component2;if(server_had_component!==client_has_component){anchor=skip_nodes();set_hydrate_node(anchor);branches.anchor=anchor;set_hydrating(!1);branches.ensure(component2,component2&&(target=>render_fn2(target,component2)));set_hydrating(!0);return}}branches.ensure(component2,component2&&(target=>render_fn2(target,component2)))},EFFECT_TRANSPARENT)}function append_styles(anchor,css){effect(()=>{var _a13,root44=anchor.getRootNode(),target=root44.host?root44:null!=(_a13=root44.head)?_a13:root44.ownerDocument.head;if(!target.querySelector("#"+css.hash)){const style=create_element("style");style.id=css.hash;style.textContent=css.code;target.appendChild(style);dev_fallback_default&&register_style(css.hash,style)}})}function r(e3){var t9,f4,o2,n3="";if("string"==typeof e3||"number"==typeof e3)n3+=e3;else if("object"==typeof e3)if(Array.isArray(e3)){o2=e3.length;for(t9=0;t9<o2;t9++)e3[t9]&&(f4=r(e3[t9]))&&(n3&&(n3+=" "),n3+=f4)}else for(f4 in e3)e3[f4]&&(n3&&(n3+=" "),n3+=f4);return n3}function clsx(){for(var e3,t9,f4=0,n3="",o2=arguments.length;f4<o2;f4++)(e3=arguments[f4])&&(t9=r(e3))&&(n3&&(n3+=" "),n3+=t9);return n3}function clsx2(value){return"object"==typeof value?clsx(value):null!=value?value:""}function to_class(value,hash3,directives){var key3,len,a2,b3,classname=null==value?"":""+value;hash3&&(classname=classname?classname+" "+hash3:hash3);if(directives)for(key3 of Object.keys(directives))if(directives[key3])classname=classname?classname+" "+key3:key3;else if(classname.length){len=key3.length;a2=0;for(;(a2=classname.indexOf(key3,a2))>=0;){b3=a2+len;0!==a2&&!whitespace.includes(classname[a2-1])||b3!==classname.length&&!whitespace.includes(classname[b3])?a2=b3:classname=(0===a2?"":classname.substring(0,a2))+classname.substring(b3+1)}}return""===classname?null:classname}function set_class(dom,is_html,value,hash3,prev_classes,next_classes){var next_class_name,key3,is_present,prev=dom[CLASS_CACHE];if(hydrating||prev!==value||void 0===prev){next_class_name=to_class(value,hash3,next_classes);hydrating&&next_class_name===dom.getAttribute("class")||(null==next_class_name?dom.removeAttribute("class"):is_html?dom.className=next_class_name:dom.setAttribute("class",next_class_name));dom[CLASS_CACHE]=value}else if(next_classes&&prev_classes!==next_classes)for(key3 in next_classes){is_present=!!next_classes[key3];null!=prev_classes&&is_present===!!prev_classes[key3]||dom.classList.toggle(key3,is_present)}return next_classes}function select_option(select,value,mounting=!1){var option,option_value;if(select.multiple){if(null==value)return;if(!is_array(value))return select_multiple_invalid_value();for(option of select.options)option.selected=value.includes(get_option_value(option))}else{for(option of select.options){option_value=get_option_value(option);if(is(option_value,value)){option.selected=!0;return}}mounting&&void 0===value||(select.selectedIndex=-1)}}function init_select(select){var observer=new MutationObserver(()=>{select_option(select,select.__value)});observer.observe(select,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["value"]});teardown(()=>{observer.disconnect()})}function bind_select_value(select,get5,set2=get5){var batches=new WeakSet,mounting=!0;listen_to_event_and_reset_event(select,"change",is_reset=>{var _a13,value,selected_option,query3=is_reset?"[selected]":":checked";if(select.multiple)value=[].map.call(select.querySelectorAll(query3),get_option_value);else{selected_option=null!=(_a13=select.querySelector(query3))?_a13:select.querySelector("option:not([disabled])");value=selected_option&&get_option_value(selected_option)}set2(value);select.__value=value;null!==current_batch&&batches.add(current_batch)});effect(()=>{var batch,selected_option,value=get5();if(select===document.activeElement){batch=async_mode_flag?previous_batch:current_batch;if(batches.has(batch))return}select_option(select,value,mounting);if(mounting&&void 0===value){selected_option=select.querySelector(":checked");if(null!==selected_option){value=get_option_value(selected_option);set2(value)}}select.__value=value;mounting=!1});init_select(select)}function get_option_value(option){return"__value"in option?option.__value:option.value}function remove_input_defaults(input){var already_removed,remove_defaults;if(hydrating){already_removed=!1;remove_defaults=()=>{var value,checked;if(!already_removed){already_removed=!0;if(input.hasAttribute("value")){value=input.value;set_attribute2(input,"value",null);input.value=value}if(input.hasAttribute("checked")){checked=input.checked;set_attribute2(input,"checked",null);input.checked=checked}}};input[FORM_RESET_HANDLER]=remove_defaults;queue_micro_task(remove_defaults);add_form_reset_listener()}}function set_value(element2,value){var attributes=get_attributes(element2);attributes.value!==(attributes.value=null!=value?value:void 0)&&(element2.value!==value||0===value&&element2.nodeName===PROGRESS_TAG)&&(element2.value=null!=value?value:"")}function set_attribute2(element2,attribute,value,skip_warning){var attributes=get_attributes(element2);if(hydrating){attributes[attribute]=element2.getAttribute(attribute);if("src"===attribute||"srcset"===attribute||"href"===attribute&&element2.nodeName===LINK_TAG){skip_warning||check_src_in_dev_hydration(element2,attribute,null!=value?value:"");return}}if(attributes[attribute]!==(attributes[attribute]=value)){"loading"===attribute&&(element2[LOADING_ATTR_SYMBOL]=value);null==value?element2.removeAttribute(attribute):"string"!=typeof value&&get_setters(element2).includes(attribute)?element2[attribute]=value:element2.setAttribute(attribute,value)}}function get_attributes(element2){var _a13,_b6;return null!=(_b6=element2[_a13=ATTRIBUTES_CACHE])?_b6:element2[_a13]={[IS_CUSTOM_ELEMENT]:element2.nodeName.includes("-"),[IS_HTML]:element2.namespaceURI===NAMESPACE_HTML}}function get_setters(element2){var descriptors,proto,element_proto,key3,cache_key=element2.getAttribute("is")||element2.nodeName,setters=setters_cache.get(cache_key);if(setters)return setters;setters_cache.set(cache_key,setters=[]);proto=element2;element_proto=Element.prototype;for(;element_proto!==proto;){descriptors=get_descriptors(proto);for(key3 in descriptors)descriptors[key3].set&&"innerHTML"!==key3&&"textContent"!==key3&&"innerText"!==key3&&setters.push(key3);proto=get_prototype_of(proto)}return setters}function check_src_in_dev_hydration(element2,attribute,value){var _a13;dev_fallback_default&&("srcset"===attribute&&srcset_url_equal(element2,value)||src_url_equal(null!=(_a13=element2.getAttribute(attribute))?_a13:"",value)||hydration_attribute_changed(attribute,element2.outerHTML.replace(element2.innerHTML,element2.innerHTML&&"..."),String(value)))}function src_url_equal(element_src,url){return element_src===url||new URL(element_src,document.baseURI).href===new URL(url,document.baseURI).href}function split_srcset(srcset){return srcset.split(",").map(src=>src.trim().split(" ").filter(Boolean))}function srcset_url_equal(element2,srcset){var element_urls=split_srcset(element2.srcset),urls=split_srcset(srcset);return urls.length===element_urls.length&&urls.every(([url,width],i3)=>width===element_urls[i3][1]&&(src_url_equal(element_urls[i3][0],url)||src_url_equal(url,element_urls[i3][0])))}function bind_value(input,get5,set2=get5){var batches=new WeakSet;listen_to_event_and_reset_event(input,"input",async is_reset=>{var value,start,end,length,new_length;dev_fallback_default&&"checkbox"===input.type&&bind_invalid_checkbox_value();value=is_reset?input.defaultValue:input.value;value=is_numberlike_input(input)?to_number(value):value;set2(value);null!==current_batch&&batches.add(current_batch);await tick();if(value!==(value=get5())){start=input.selectionStart;end=input.selectionEnd;length=input.value.length;input.value=null!=value?value:"";if(null!==end){new_length=input.value.length;if(start===end&&end===length&&new_length>length){input.selectionStart=new_length;input.selectionEnd=new_length}else{input.selectionStart=start;input.selectionEnd=Math.min(end,new_length)}}}});if(hydrating&&input.defaultValue!==input.value||null==untrack(get5)&&input.value){set2(is_numberlike_input(input)?to_number(input.value):input.value);null!==current_batch&&batches.add(current_batch)}render_effect(()=>{var value,batch;dev_fallback_default&&"checkbox"===input.type&&bind_invalid_checkbox_value();value=get5();if(input===document.activeElement){batch=async_mode_flag?previous_batch:current_batch;if(batches.has(batch))return}is_numberlike_input(input)&&value===to_number(input.value)||("date"!==input.type||value||input.value)&&value!==input.value&&(input.value=null!=value?value:"")})}function bind_group(inputs,group_index,input,get5,set2=get5){var _a13,index6,is_checkbox="checkbox"===input.getAttribute("type"),binding_group=inputs;let hydration_mismatch2=!1;if(null!==group_index)for(index6 of group_index)binding_group=null!=(_a13=binding_group[index6])?_a13:binding_group[index6]=[];binding_group.push(input);listen_to_event_and_reset_event(input,"change",()=>{var value=input.__value;is_checkbox&&(value=get_binding_group_value(binding_group,value,input.checked));set2(value)},()=>set2(is_checkbox?[]:null));render_effect(()=>{var value=get5();if(hydrating&&input.defaultChecked!==input.checked)hydration_mismatch2=!0;else if(is_checkbox){value=value||[];input.checked=value.includes(input.__value)}else input.checked=is(input.__value,value)});teardown(()=>{var index7=binding_group.indexOf(input);-1!==index7&&binding_group.splice(index7,1)});if(!pending2.has(binding_group)){pending2.add(binding_group);queue_micro_task(()=>{binding_group.sort((a2,b3)=>4===a2.compareDocumentPosition(b3)?-1:1);pending2.delete(binding_group)})}queue_micro_task(()=>{var value,hydration_input;if(hydration_mismatch2){if(is_checkbox)value=get_binding_group_value(binding_group,value,input.checked);else{hydration_input=binding_group.find(input2=>input2.checked);value=null==hydration_input?void 0:hydration_input.__value}set2(value)}})}function bind_checked(input,get5,set2=get5){listen_to_event_and_reset_event(input,"change",is_reset=>{var value=is_reset?input.defaultChecked:input.checked;set2(value)});(hydrating&&input.defaultChecked!==input.checked||null==untrack(get5))&&set2(input.checked);render_effect(()=>{var value=get5();input.checked=Boolean(value)})}function get_binding_group_value(group4,__value,checked){var i3,value=new Set;for(i3=0;i3<group4.length;i3+=1)group4[i3].checked&&value.add(group4[i3].__value);checked||value.delete(__value);return Array.from(value)}function is_numberlike_input(input){var type=input.type;return"number"===type||"range"===type}function to_number(value){return""===value?null:+value}function is_bound_this(bound_value,element_or_component){return bound_value===element_or_component||(null==bound_value?void 0:bound_value[STATE_SYMBOL])===element_or_component}function bind_this(element_or_component={},update2,get_value,get_parts){var component_effect=component_context.r,parent=active_effect;effect(()=>{var old_parts,parts;render_effect(()=>{old_parts=parts;parts=(null==get_parts?void 0:get_parts())||[];untrack(()=>{if(!is_bound_this(get_value(...parts),element_or_component)){update2(element_or_component,...parts);old_parts&&is_bound_this(get_value(...old_parts),element_or_component)&&update2(null,...old_parts)}})});return()=>{let p2=parent;for(;p2!==component_effect&&null!==p2.parent&&p2.parent.f&DESTROYING;)p2=p2.parent;const teardown2=()=>{parts&&is_bound_this(get_value(...parts),element_or_component)&&update2(null,...parts)},original_teardown=p2.teardown;p2.teardown=()=>{teardown2();null==original_teardown||original_teardown()}}});return element_or_component}function init(immutable=!1){const context2=component_context,callbacks=context2.l.u;if(!callbacks)return;let props=()=>deep_read_state(context2.s);if(immutable){let version2=0,prev={};const d4=derived2(()=>{let changed=!1;const props2=context2.s;for(const key3 in props2)if(props2[key3]!==prev[key3]){prev[key3]=props2[key3];changed=!0}changed&&version2++;return version2});props=()=>get2(d4)}callbacks.b.length&&user_pre_effect(()=>{observe_all(context2,props);run_all(callbacks.b)});user_effect(()=>{const fns=untrack(()=>callbacks.m.map(run));return()=>{for(const fn of fns)"function"==typeof fn&&fn()}});callbacks.a.length&&user_effect(()=>{observe_all(context2,props);run_all(callbacks.a)})}function observe_all(context2,props){if(context2.l.s)for(const signal of context2.l.s)get2(signal);props()}function rest_props(props,exclude,name){return new Proxy(dev_fallback_default?{props,exclude,name,other:{},to_proxy:[]}:{props,exclude},rest_props_handler)}function spread_props(...props){return new Proxy({props},spread_props_handler)}function prop(props,key3,flags2,fallback3){var _a13,_b6,is_entry_props,initial_value,is_store_sub,getter,legacy_parent,overridden,d4,parent_effect,runes=!legacy_mode_flag||0!==(flags2&PROPS_IS_RUNES),bindable=0!==(flags2&PROPS_IS_BINDABLE),lazy=0!==(flags2&PROPS_IS_LAZY_INITIAL),fallback_value=fallback3,fallback_dirty=!0,fallback_signal=void 0,get_fallback=()=>{if(lazy&&runes){null!=fallback_signal||(fallback_signal=derived2(fallback3));return get2(fallback_signal)}if(fallback_dirty){fallback_dirty=!1;fallback_value=lazy?untrack(fallback3):fallback3}return fallback_value};let setter;if(bindable){is_entry_props=STATE_SYMBOL in props||LEGACY_PROPS in props;setter=null!=(_b6=null==(_a13=get_descriptor(props,key3))?void 0:_a13.set)?_b6:is_entry_props&&key3 in props?v2=>props[key3]=v2:void 0}is_store_sub=!1;bindable?[initial_value,is_store_sub]=capture_store_binding(()=>props[key3]):initial_value=props[key3];if(void 0===initial_value&&void 0!==fallback3){initial_value=get_fallback();if(setter){runes&&props_invalid_value(key3);setter(initial_value)}}getter=runes?()=>{var value=props[key3];if(void 0===value)return get_fallback();fallback_dirty=!0;return value}:()=>{var value=props[key3];void 0!==value&&(fallback_value=void 0);return void 0===value?fallback_value:value};if(runes&&0===(flags2&PROPS_IS_UPDATED))return getter;if(setter){legacy_parent=props.$$legacy;return function(value,mutation){if(arguments.length>0){runes&&mutation&&!legacy_parent&&!is_store_sub||setter(mutation?getter():value);return value}return getter()}}overridden=!1;d4=(0!==(flags2&PROPS_IS_IMMUTABLE)?derived2:derived_safe_equal)(()=>{overridden=!1;return getter()});dev_fallback_default&&(d4.label=key3);bindable&&get2(d4);parent_effect=active_effect;return function(value,mutation){if(arguments.length>0){const new_value=mutation?get2(d4):runes&&bindable?proxy(value):value;set(d4,new_value);overridden=!0;void 0!==fallback_value&&(fallback_value=new_value);return value}return is_destroying_effect&&overridden||0!==(parent_effect.f&DESTROYED)?d4.v:get2(d4)}}function createClassComponent(options){return new Svelte4Component(options)}function get_custom_element_value(prop2,value,props_definition,transform2){var _a13;const type=null==(_a13=props_definition[prop2])?void 0:_a13.type;value="Boolean"===type&&"boolean"!=typeof value?null!=value:value;if(!transform2||!props_definition[prop2])return value;if("toAttribute"===transform2)switch(type){case"Object":case"Array":return null==value?null:JSON.stringify(value);case"Boolean":return value?"":null;case"Number":return null==value?null:value;default:return value}else switch(type){case"Object":case"Array":return value&&JSON.parse(value);case"Boolean":return value;case"Number":return null!=value?+value:value;default:return value}}function get_custom_elements_slots(element2){const result={};element2.childNodes.forEach(node=>{result[node.slot||"default"]=!0});return result}function resolveLanguage(lang){var _a13;if(""!==lang)return lang;const obsidianLanguage=getLanguage2().toLowerCase();return null!=(_a13=obsidianLangMap[obsidianLanguage])?_a13:"def"}function __onMissingTranslation(callback){__onMissingTranslations=callback}function setLang(lang){const resolvedLang=resolveLanguage(lang);if(resolvedLang!==currentLang){currentLang=resolvedLang;msgCache.clear()}}function _getMessage(key3,lang){var _a13;if(""==key3.trim())return key3;const provisionalEnglish=liveSyncProvisionalEnglishMessages[key3],msgs=null!=(_a13=allMessages[key3])?_a13:void 0===provisionalEnglish?void 0:{def:provisionalEnglish};if(void 0===msgs&&isCommonlibMessageKey(key3))return englishMessageTranslator(key3);const resolvedLang=resolveLanguage(lang);let msg=null==msgs?void 0:msgs[resolvedLang];if(!msg){if(-1===missingTranslations.indexOf(key3)){__onMissingTranslations(key3);missingTranslations.push(key3)}msg=null==msgs?void 0:msgs.def}return null!=msg?msg:key3}function getMessage(key3){if(msgCache.has(key3))return msgCache.get(key3);const msg=_getMessage(key3,currentLang);msgCache.set(key3,msg);return msg}function $t(message,lang){return void 0!==lang?_getMessage(message,lang):getMessage(message)}function translateIfAvailable(message,lang){return""==message.trim()||!isLiveSyncMessageKey(message)&&!isCommonlibMessageKey(message)?message:$t(message,lang)}function isCommonlibMessageKey(key3){return key3 in commonlibEnglishMessages}function isLiveSyncMessageKey(key3){return key3 in allMessages||key3 in liveSyncProvisionalEnglishMessages}function $msg(key3,params={},lang){let msg=$t(key3,lang);for(const[placeholder,value]of Object.entries(params)){const regex=new RegExp(`\\\${${placeholder}}`,"g");msg=msg.replace(regex,value)}return msg}function LogPane($$anchor,$$props){function updateLog(logs){const e3=logs.value;if(!get2(suspended)){set(messages,[...e3],!0);compatGlobal.setTimeout(()=>{scroll&&(scroll.scrollTop=scroll.scrollHeight)},10)}}function closeDialogue(){$$props.close()}var div,div_1,div_2,label2,input,span,text2,label_1,input_1,span_1,text_1,label_2,input_2,span_2,text_2,button,div_3;push($$props,!0);append_styles($$anchor,$$css);let unsubscribe,scroll,messages=state(proxy([])),wrapRight=state(!1),autoScroll=state(!0),suspended=state(!1);onMount(async()=>{const _logMessages=reactive(()=>logMessages.value);_logMessages.onChanged(updateLog);Logger($msg("logPane.logWindowOpened",{},currentLang));unsubscribe=()=>_logMessages.offChanged(updateLog)});onDestroy(()=>{unsubscribe&&unsubscribe()});div=root_1();div_1=child(div);div_2=child(div_1);label2=child(div_2);input=child(label2);remove_input_defaults(input);span=sibling(input,2);text2=child(span,!0);reset(span);reset(label2);label_1=sibling(label2,2);input_1=child(label_1);remove_input_defaults(input_1);span_1=sibling(input_1,2);text_1=child(span_1,!0);reset(span_1);reset(label_1);label_2=sibling(label_1,2);input_2=child(label_2);remove_input_defaults(input_2);span_2=sibling(input_2,2);text_2=child(span_2,!0);reset(span_2);reset(label_2);button=sibling(label_2,4);reset(div_2);reset(div_1);div_3=sibling(div_1,2);each(div_3,21,()=>get2(messages),index,($$anchor2,line)=>{var text_3,pre=root2();let classes;text_3=child(pre,!0);reset(pre);template_effect(()=>{classes=set_class(pre,1,"svelte-o3lsbg",null,classes,{"wrap-right":get2(wrapRight)});set_text(text_3,get2(line))});append($$anchor2,pre)});reset(div_3);bind_this(div_3,$$value=>scroll=$$value,()=>scroll);reset(div);template_effect(($0,$1,$2)=>{set_text(text2,$0);set_text(text_1,$1);set_text(text_2,$2)},[()=>$msg("logPane.wrap",{},currentLang),()=>$msg("logPane.autoScroll",{},currentLang),()=>$msg("logPane.pause",{},currentLang)]);bind_checked(input,()=>get2(wrapRight),$$value=>set(wrapRight,$$value));bind_checked(input_1,()=>get2(autoScroll),$$value=>set(autoScroll,$$value));bind_checked(input_2,()=>get2(suspended),$$value=>set(suspended,$$value));delegated("click",button,()=>closeDialogue());append($$anchor,div);pop()}function toRpcMethodName(method){return method.includes(".")||method.includes("/")?method:DB_METHODS.has(method)?`db.${method}`:`legacy/${method}`}function createHostingDB(env){let db=env.db;const hostingDB={info:()=>db.info(),changes:options=>db.changes(options),revsDiff:diff=>db.revsDiff(diff),bulkDocs:(docs,options)=>db.bulkDocs(docs,options),bulkGet:options=>db.bulkGet(options),put:(doc,options)=>db.put(doc,options),get:(id,options)=>db.get(id,options),_stopHosting:()=>{db=void 0}};return hostingDB}function estimateBytes(text2){return encoder2.encode(text2).byteLength}function splitIntoChunks(payload,maxBytes){if(maxBytes<=0)return[payload];if(estimateBytes(payload)<=maxBytes)return[payload];const chunks=[];let cursor=0;for(;cursor<payload.length;){let end=Math.min(payload.length,cursor+Math.max(16,Math.floor(maxBytes/2))),part=payload.slice(cursor,end);for(;part.length>1&&estimateBytes(part)>maxBytes;){end=Math.max(cursor+1,end-1);part=payload.slice(cursor,end)}chunks.push(part);cursor=end}return chunks}function asRpcErrorShape(ex){return ex instanceof RpcError?ex.toShape():ex instanceof Error?{code:"REMOTE_ERROR",message:ex.message}:{code:"REMOTE_ERROR",message:"Unknown remote error"}}function newId(prefix){return`${prefix}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function validNamespacedMethod(method){return method.includes(".")||method.includes("/")}function parseSlsUri(uriString){const match3=uriString.match(/^sls\+([^:]+):(.*)$/);if(!match3)throw new Error(`Unsupported URI: ${uriString}`);const subscheme=match3[1],rest=match3[2];return{url:new URL(`${PROXY_SCHEME}:${rest}`),subscheme}}function withSlsScheme(url,subscheme){const out=url.toString();return`sls+${subscheme}:${out.slice(PROXY_SCHEME.length+1)}`}function mixedHash(str,seed,fnv1aHash_=epochFNV1a){let h1=seed,fnv1aHash=fnv1aHash_;const len=str.length;for(let i3=0;i3<len;i3++){let k1=str.charCodeAt(i3);fnv1aHash^=k1;fnv1aHash=Math.imul(fnv1aHash,16777619)>>>0;k1*=c1;k1=k1<<r1|k1>>>32-r1;k1*=c2;h1^=k1;h1=h1<<r2|h1>>>32-r2;h1=h1*m+n}h1^=len;h1^=h1>>>16;h1=Math.imul(h1,2246822507);h1^=h1>>>13;h1=Math.imul(h1,3266489909);h1^=h1>>>16;return[h1>>>0,fnv1aHash]}function fallbackMixedHashEach(src){let m3=1,f4=epochFNV1a;[m3,f4]=mixedHash(`${src.length}${src}`,m3,f4);return`${m3.toString(36)}${f4.toString(36)}`}async function sha12(src){const bytes=writeString(src),digest=await globalThis.crypto.subtle.digest({name:"SHA-1"},bytes);return await arrayBufferToBase64Single(digest)}function asFiniteNumber(value){return"number"==typeof value&&Number.isFinite(value)?value:void 0}function formatHistory(history){return history.length>0?history.join(">"):"none"}function getLastOrFallback(items,fallback3){var _a13;return 0===items.length?fallback3:null!=(_a13=items[items.length-1])?_a13:fallback3}function tryGetValue(record,key3){const value=record[key3];return"string"==typeof value||"number"==typeof value?value:"unknown"}function maskIdentifier(value){return"unknown"===value?value:value.length<=8?"[id]":`${value.slice(0,4)}...${value.slice(-4)}`}function diagnoseRtcFailure(internalStateHistory,selectedPair){var _a13;const hasSelectedPair=!!selectedPair,selectedPairState=null!=(_a13=null==selectedPair?void 0:selectedPair.state)?_a13:"unknown",requestsSent=asFiniteNumber(null==selectedPair?void 0:selectedPair.requestsSent),responsesReceived=asFiniteNumber(null==selectedPair?void 0:selectedPair.responsesReceived),hasIceGatheringStarted=internalStateHistory.iceGatheringHistory.includes("gathering"),hasIceGatheringComplete=internalStateHistory.iceGatheringHistory.includes("complete"),hasIceChecking=internalStateHistory.iceConnectionHistory.includes("checking"),hasIceConnected=internalStateHistory.iceConnectionHistory.includes("connected"),hasIceFailed=internalStateHistory.iceConnectionHistory.includes("failed"),hasIceDisconnected=internalStateHistory.iceConnectionHistory.includes("disconnected"),hasConnectionConnected=internalStateHistory.connectionHistory.includes("connected"),hasConnectionFailed=internalStateHistory.connectionHistory.includes("failed"),hasSignalingStable=internalStateHistory.signalingHistory.includes("stable");return hasSelectedPair||!hasIceGatheringStarted||hasIceGatheringComplete?hasIceChecking&&hasIceFailed&&!hasIceConnected?{reasonCode:DiagRTCFailureReasonCodes_ICE_CONNECTIVITY_FAILED,userMessage:"Connection attempt reached candidate checks but no route was established."}:hasSelectedPair&&"succeeded"!==selectedPairState&&(null!=requestsSent?requestsSent:0)>0&&0===(null!=responsesReceived?responsesReceived:0)?{reasonCode:DiagRTCFailureReasonCodes_STUN_REQUEST_TIMEOUT,userMessage:"Connection requests were sent but no response was returned. Network path may block UDP/STUN."}:hasSignalingStable?hasConnectionConnected&&hasConnectionFailed?{reasonCode:DiagRTCFailureReasonCodes_CONNECTION_DROPPED_AFTER_ESTABLISHED,userMessage:"Connection was established once, but dropped afterwards."}:hasIceDisconnected&&hasIceFailed?{reasonCode:DiagRTCFailureReasonCodes_NETWORK_INTERRUPTED,userMessage:"Connection was interrupted while exchanging data."}:{reasonCode:DiagRTCFailureReasonCodes_UNKNOWN,userMessage:"Connection failed for an unknown reason. Please retry and collect diagnostics."}:{reasonCode:DiagRTCFailureReasonCodes_SIGNALING_NOT_STABLE,userMessage:"Connection negotiation did not reach a stable signalling state."}:{reasonCode:DiagRTCFailureReasonCodes_ICE_GATHERING_NOT_COMPLETED,userMessage:"Connection could not collect enough network candidates. Check VPN, proxy, or firewall settings."}}function describeRTCProgress(internalStateHistory,selectedPair){const lastConnectionState=getLastOrFallback(internalStateHistory.connectionHistory,"new"),lastIceConnectionState=getLastOrFallback(internalStateHistory.iceConnectionHistory,"new"),lastIceGatheringState=getLastOrFallback(internalStateHistory.iceGatheringHistory,"new"),lastSignalingState=getLastOrFallback(internalStateHistory.signalingHistory,"stable"),pairState=tryGetValue(null!=selectedPair?selectedPair:{},"state"),requestsSent=tryGetValue(null!=selectedPair?selectedPair:{},"requestsSent"),responsesReceived=tryGetValue(null!=selectedPair?selectedPair:{},"responsesReceived");if("connected"===lastConnectionState||"connected"===lastIceConnectionState)return`Connected (pair=${pairState})`;if("failed"===lastConnectionState||"failed"===lastIceConnectionState){const diagnosis=diagnoseRtcFailure(internalStateHistory,selectedPair);return`Failed (${diagnosis.reasonCode})`}return"checking"===lastIceConnectionState?"unknown"!==requestsSent&&"unknown"!==responsesReceived?`Checking connectivity (responses ${responsesReceived}/${requestsSent})`:"Checking connectivity":"gathering"===lastIceGatheringState?"Gathering network candidates":"stable"!==lastSignalingState?`Negotiating signalling (${lastSignalingState})`:"connecting"===lastConnectionState||"new"===lastIceConnectionState?"Starting peer connection":`Verbose state: State=${lastConnectionState}, ice=${lastIceConnectionState}, pair=${pairState}`}async function getPeerConnectionStats(instanceId,peer){var _a13;try{const stats=await peer.getStats(),reports=[];stats.forEach(value=>{reports.push(value)});const selectedPair=reports.map(r4=>r4).find(r4=>"candidate-pair"===r4.type&&(!0===r4.selected||!0===r4.nominated)),selectedPairId=null!=(_a13=tryGetValue(null!=selectedPair?selectedPair:{},"id"))?_a13:"none",state2=tryGetValue(null!=selectedPair?selectedPair:{},"state"),localCandidateId=tryGetValue(null!=selectedPair?selectedPair:{},"localCandidateId"),remoteCandidateId=tryGetValue(null!=selectedPair?selectedPair:{},"remoteCandidateId"),currentRoundTripTime=tryGetValue(null!=selectedPair?selectedPair:{},"currentRoundTripTime"),totalRoundTripTime=tryGetValue(null!=selectedPair?selectedPair:{},"totalRoundTripTime"),requestsSent=tryGetValue(null!=selectedPair?selectedPair:{},"requestsSent"),responsesReceived=tryGetValue(null!=selectedPair?selectedPair:{},"responsesReceived"),packetsDiscardedOnSend=tryGetValue(null!=selectedPair?selectedPair:{},"packetsDiscardedOnSend"),bytesSent=tryGetValue(null!=selectedPair?selectedPair:{},"bytesSent"),bytesReceived=tryGetValue(null!=selectedPair?selectedPair:{},"bytesReceived");return{selectedPair,selectedPairId,state:state2,localCandidateId,remoteCandidateId,currentRoundTripTime,totalRoundTripTime,requestsSent,responsesReceived,packetsDiscardedOnSend,bytesSent,bytesReceived,reports}}catch(ex){Logger(`[DiagRTC:${instanceId}] progress/getStats threw: ${ex instanceof Error?ex.message:String(ex)}`,LOG_LEVEL_DEBUG);return}}async function auditRtcConnectionFailures(instanceId,internalStateHistory,peer){try{const stats=await getPeerConnectionStats(instanceId,peer);if(!stats){Logger(`[DiagRTC:${instanceId}] failed/getStats: Unable to retrieve connection statistics.`,LOG_LEVEL_INFO);return}const reports=stats.reports,diagnosis=diagnoseRtcFailure(internalStateHistory,stats.selectedPair),connectionHistory=formatHistory(internalStateHistory.connectionHistory),iceConnectionHistory=formatHistory(internalStateHistory.iceConnectionHistory),iceGatheringHistory=formatHistory(internalStateHistory.iceGatheringHistory),signalingHistory=formatHistory(internalStateHistory.signalingHistory),maskedSelectedPairId=maskIdentifier(String(stats.selectedPairId)),maskedLocalCandidateId=maskIdentifier(String(stats.localCandidateId)),maskedRemoteCandidateId=maskIdentifier(String(stats.remoteCandidateId));Logger(`[DiagRTC:${instanceId}] failed/summary: reasonCode=${diagnosis.reasonCode}, userMessage="${diagnosis.userMessage}", history.connection=${connectionHistory}, history.iceConnection=${iceConnectionHistory}, history.iceGathering=${iceGatheringHistory}, history.signaling=${signalingHistory}`,LOG_LEVEL_INFO);Logger(`[DiagRTC:${instanceId}] failed/getStats/detail: reports=${reports.length}, reasonCode=${diagnosis.reasonCode}, userMessage="${diagnosis.userMessage}", history.connection=${connectionHistory}, history.iceConnection=${iceConnectionHistory}, history.iceGathering=${iceGatheringHistory}, history.signaling=${signalingHistory}, selectedPair=${maskedSelectedPairId}, pairState=${stats.state}, localCandidate=${maskedLocalCandidateId}, remoteCandidate=${maskedRemoteCandidateId}, rtt=${stats.currentRoundTripTime}, totalRtt=${stats.totalRoundTripTime}, requestsSent=${stats.requestsSent}, responsesReceived=${stats.responsesReceived}, packetsDiscardedOnSend=${stats.packetsDiscardedOnSend}, bytesSent=${stats.bytesSent}, bytesReceived=${stats.bytesReceived}`,LOG_LEVEL_DEBUG);return{diagnosis,stats:{reportsCount:reports.length,selectedPair:{id:maskedSelectedPairId,state:stats.state,localCandidateId:maskedLocalCandidateId,remoteCandidateId:maskedRemoteCandidateId,currentRoundTripTime:stats.currentRoundTripTime,totalRoundTripTime:stats.totalRoundTripTime,requestsSent:stats.requestsSent,responsesReceived:stats.responsesReceived,packetsDiscardedOnSend:stats.packetsDiscardedOnSend,bytesSent:stats.bytesSent,bytesReceived:stats.bytesReceived}}}}catch(ex){Logger(`[DiagRTC:${instanceId}] failed/getStats threw: ${ex instanceof Error?ex.message:String(ex)}`,LOG_LEVEL_DEBUG)}}function logRtcProgress(instanceId,eventName,peer){Logger(`[DiagRTC:${instanceId}] ${eventName}: connection=${peer.connectionState}, iceConnection=${peer.iceConnectionState}, iceGathering=${peer.iceGatheringState}, signaling=${peer.signalingState}`,LOG_LEVEL_DEBUG)}function dispatchStatus(status){const details=Object.fromEntries(RTCConnectionStatuses);for(const subscriber of connectionStatusSubscribers)try{subscriber({totalNewConnections,totalFailedConnections,totalSuccessfulConnections,totalClosedConnections,details})}catch(e3){}}function dispatchFailureDiagnosis(diagnosis){for(const subscriber of failureDiagnosisSubscribers)try{subscriber(diagnosis)}catch(e3){}}function subscribeConnectionStatus(callback){connectionStatusSubscribers.push(callback);return()=>{connectionStatusSubscribers=connectionStatusSubscribers.filter(cb2=>cb2!==callback)}}function subscribeFailureDiagnosis(callback){failureDiagnosisSubscribers.push(callback);return()=>{failureDiagnosisSubscribers=failureDiagnosisSubscribers.filter(cb2=>cb2!==callback)}}function createDiagRTCPeerConnectionConstructor(){if(void 0===compatGlobal.RTCPeerConnection)throw new Error("RTCPeerConnection is not available in the current environment.");return class DiagRTCPeerConnection extends compatGlobal.RTCPeerConnection{constructor(configuration){super(configuration);__publicField(this,"__instanceId");__publicField(this,"__failureStatsLogged",!1);__publicField(this,"_connectionStateHistory",[]);__publicField(this,"_iceConnectionHistory",[]);__publicField(this,"_iceGatheringHistory",[]);__publicField(this,"_signalingHistory",[]);__publicField(this,"_previousConnectionState");rtcInstanceCounter+=1;this.__instanceId=`rtc-${rtcInstanceCounter}`;this._logProgress("created");this.addEventListener("connectionstatechange",()=>{this._connectionStateHistory.push(this.connectionState);this._logProgress("connectionstatechange");this.trackConnectionProgress();"failed"!==this.connectionState&&(this.__failureStatsLogged=!1);if("failed"===this.connectionState&&!this.__failureStatsLogged){this.__failureStatsLogged=!0;this.analyseFailureAndDispatch()}});this.addEventListener("iceconnectionstatechange",()=>{this._iceConnectionHistory.push(this.iceConnectionState);this._logProgress("iceconnectionstatechange");this.trackConnectionProgress();"failed"!==this.iceConnectionState&&"failed"!==this.connectionState&&(this.__failureStatsLogged=!1);if(("failed"===this.connectionState||"failed"===this.iceConnectionState)&&!this.__failureStatsLogged){this.__failureStatsLogged=!0;this.analyseFailureAndDispatch()}});this.addEventListener("icegatheringstatechange",()=>{this._iceGatheringHistory.push(this.iceGatheringState);this._logProgress("icegatheringstatechange")});this.addEventListener("signalingstatechange",()=>{this._signalingHistory.push(this.signalingState);this._logProgress("signalingstatechange")})}get stateHistory(){return{connectionHistory:this._connectionStateHistory,iceConnectionHistory:this._iceConnectionHistory,iceGatheringHistory:this._iceGatheringHistory,signalingHistory:this._signalingHistory}}_logProgress(eventName){logRtcProgress(this.__instanceId,eventName,this)}async notifyConnectionProgress(status){const metrics=await getPeerConnectionStats(this.__instanceId,this),progress=describeRTCProgress(this.stateHistory,null==metrics?void 0:metrics.selectedPair);Logger(`[DiagRTC:${this.__instanceId}]: ${progress}`,LOG_LEVEL_INFO);Logger(`[DiagRTC:${this.__instanceId}] status: connection=${status.connectionState}, iceConnection=${status.iceConnectionState}`,LOG_LEVEL_VERBOSE)}trackConnectionProgress(){const status={connectionState:this.connectionState,iceConnectionState:this.iceConnectionState},instanceId=this.__instanceId;"closed"===status.connectionState||"failed"===status.connectionState?RTCConnectionStatuses.delete(instanceId):RTCConnectionStatuses.set(instanceId,status);if(this._previousConnectionState!=status.connectionState){"connected"===status.connectionState&&(totalSuccessfulConnections+=1);"failed"===status.connectionState&&(totalFailedConnections+=1);"new"===status.connectionState&&(totalNewConnections+=1);"closed"===status.connectionState&&(totalClosedConnections+=1);this._previousConnectionState=status.connectionState;this.notifyConnectionProgress(status);dispatchStatus()}}async analyseFailureAndDispatch(){const history=this.stateHistory,diagnosis=await auditRtcConnectionFailures(this.__instanceId,history,this);diagnosis&&dispatchFailureDiagnosis(diagnosis.diagnosis)}}}function generateJoinRoomOptions(settings){const passphraseNumbers=mixedHash(settings.P2P_passphrase,0),passphrase=passphraseNumbers[0].toString(36)+passphraseNumbers[1].toString(36),relays=settings.P2P_relays.split(",").map(e3=>e3.trim()).filter(e3=>e3.length>0),turnServers=splitP2PTurnServerUrls(settings.P2P_turnServers),relayConfig={manualReconnection:!0,urls:relays},options={appId:settings.P2P_AppID||"self-hosted-livesync",password:passphrase,relayConfig};settings.P2P_useDiagRTC?options.rtcPolyfill=createDiagRTCPeerConnectionConstructor():void 0!==compatGlobal.RTCPeerConnection&&(options.rtcPolyfill=compatGlobal.RTCPeerConnection);turnServers.length>0&&(options.turnConfig=[{urls:turnServers,username:settings.P2P_turnUsername,credential:settings.P2P_turnCredential}]);normaliseP2PConnectionPath(settings.P2P_connectionPath)===P2PConnectionPaths_Relay&&hasValidP2PTurnServerUrl(settings.P2P_turnServers)&&(options.rtcConfig={iceTransportPolicy:"relay"});return options}function getSubscribers(room){const existing=subscribersByRoom.get(room);if(existing)return existing;const subscribers={join:new Set,leave:new Set};subscribersByRoom.set(room,subscribers);room.onPeerJoin=peerId=>{for(const handler of[...subscribers.join])handler(peerId)};room.onPeerLeave=peerId=>{for(const handler of[...subscribers.leave])handler(peerId)};return subscribers}function subscribeTrysteroPeerEvents(room,handlers3){const subscribers=getSubscribers(room);handlers3.onJoin&&subscribers.join.add(handlers3.onJoin);handlers3.onLeave&&subscribers.leave.add(handlers3.onLeave);return()=>{handlers3.onJoin&&subscribers.join.delete(handlers3.onJoin);handlers3.onLeave&&subscribers.leave.delete(handlers3.onLeave);if(0===subscribers.join.size&&0===subscribers.leave.size){room.onPeerJoin=null;room.onPeerLeave=null;subscribersByRoom.delete(room)}}}function resolveTrysteroRpcOptions(settings){return{...TRYSTERO_RPC_DEFAULTS,maxWirePayloadBytes:normaliseP2PMaxWirePayloadBytes(settings.P2P_maxWirePayloadBytes)}}function getTrackedRequestCount(requestCount,responseCount){return Math.max(0,requestCount-responseCount)}function formatRemoteActivityStatusLabel(status){const labels=[status.remoteOperationCount>0?REMOTE_OPERATION_ACTIVITY_ICON:"",status.trackedRequestCount>0?`${REMOTE_REQUEST_ACTIVITY_ICON}${status.trackedRequestCount}`:""].filter(label2=>""!==label2);return labels.length>0?`${labels.join(" ")} `:""}function asDisposableReactiveValue(value,dispose){return{get value(){return value.value},onChanged(handler){value.onChanged(handler)},offChanged(handler){value.offChanged(handler)},dispose}}function createMinimumVisibleActivityCount(source2,minimumVisibleMs){const minimumLifetime=Math.max(0,minimumVisibleMs),displayed=reactiveSource(Math.max(0,source2.value));let hideTimer,visibleSince=displayed.value>0?Date.now():void 0,disposed=!1;const cancelHide=()=>{if(void 0!==hideTimer){compatGlobal.clearTimeout(hideTimer);hideTimer=void 0}},hideIfIdle=()=>{hideTimer=void 0;if(!(disposed||Math.max(0,source2.value)>0)){displayed.value=0;visibleSince=void 0}},update2=()=>{if(disposed)return;const nextCount=Math.max(0,source2.value);cancelHide();if(nextCount>0){0===displayed.value&&(visibleSince=Date.now());displayed.value=nextCount;return}if(0===displayed.value){visibleSince=void 0;return}const elapsed=Date.now()-(null!=visibleSince?visibleSince:Date.now()),remaining=Math.max(0,minimumLifetime-elapsed);0===remaining?hideIfIdle():hideTimer=compatGlobal.setTimeout(hideIfIdle,remaining)};source2.onChanged(update2);return asDisposableReactiveValue(displayed,()=>{if(!disposed){disposed=!0;cancelHide();source2.offChanged(update2)}})}function createPaddedCounterLabel(source2,mark,inactiveLingerMs=STATUS_COUNTER_INACTIVE_LINGER_MS){const linger=Math.max(0,inactiveLingerMs),formatted=reactiveSource("");let clearTimer,maximumLength=1,disposed=!1;const cancelClear=()=>{if(void 0!==clearTimer){compatGlobal.clearTimeout(clearTimer);clearTimer=void 0}},format2=count=>{const requiredLength=`${Math.abs(count)}`.length+1;maximumLength=Math.max(maximumLength,requiredLength);return` ${mark}${`${STATUS_COUNTER_PADDING}${count}`.slice(-maximumLength)}`},update2=()=>{if(disposed)return;cancelClear();const count=source2.value;formatted.value=format2(count);0===count&&(clearTimer=compatGlobal.setTimeout(()=>{clearTimer=void 0;if(!disposed){formatted.value="";maximumLength=1}},linger))};source2.onChanged(update2);return asDisposableReactiveValue(formatted,()=>{if(!disposed){disposed=!0;cancelClear();source2.offChanged(update2)}})}function initializeStores(vaultName){sameChangePairs=new PersistentMap(`ls-persist-same-changes-${vaultName}`)}function generateCredentialObject(settings){return settings.useJWT?{jwtAlgorithm:settings.jwtAlgorithm,jwtKey:settings.jwtKey,jwtKid:settings.jwtKid,jwtSub:settings.jwtSub,jwtExpDuration:settings.jwtExpDuration,type:"jwt"}:{username:settings.couchDB_USER,password:settings.couchDB_PASSWORD,type:"basic"}}function isInternalMetadata(id){return id.startsWith(ICHeader)}function isInternalFile(file){return"string"==typeof file?isInternalMetadata(file):!!file.isInternal}function stripInternalMetadataPrefix(id){return id.substring(ICHeaderLength)}function isChunk(str){return str.startsWith(CHeader)}function isPluginMetadata(str){return str.startsWith(PSCHeader)}function isCustomisationSyncMetadata(str){return str.startsWith(ICXHeader)}function getStoragePathFromUXFileInfo(file){return stripAllPrefixes("string"==typeof file?file:file.path)}function getDatabasePathFromUXFileInfo(file){if("string"==typeof file&&file.startsWith(ICXHeader))return file;const prefix=isInternalFile(file)?ICHeader:"";return"string"==typeof file?prefix+stripAllPrefixes(file):prefix+stripAllPrefixes(file.path)}function getPathFromTFile(file){return file.path}function isValidPath(filename){if(import_obsidian.Platform.isDesktop)return"darwin"==process.platform?isValidFilenameInDarwin(filename):"linux"==process.platform?isValidFilenameInLinux(filename):isValidFilenameInWidows(filename);if(import_obsidian.Platform.isAndroidApp)return isValidFilenameInAndroid(filename);if(import_obsidian.Platform.isIosApp)return isValidFilenameInDarwin(filename);Logger("Could not determine platform for checking filename",LOG_LEVEL_VERBOSE);return isValidFilenameInWidows(filename)}function requestToCouchDBWithCredentials(baseUri,credentials,origin2="",key3,body,method,customHeaders){const uri="_node/_local/_config"+(key3?"/"+key3:"");return _requestToCouchDB(baseUri,credentials,origin2,uri,body,method,customHeaders)}function getKey(file){const key3="string"==typeof file?file:stripAllPrefixes(file.path);return key3}function markChangesAreSame(file,mtime1,mtime2){if(mtime1===mtime2)return!0;const key3=getKey(file),pairs=sameChangePairs.get(key3,[])||[];pairs.some(e3=>e3==mtime1||e3==mtime2)?sameChangePairs.set(key3,[...new Set([...pairs,mtime1,mtime2])]):sameChangePairs.set(key3,[mtime1,mtime2])}function unmarkChanges(file){const key3=getKey(file);sameChangePairs.delete(key3)}function isMarkedAsSameChanges(file,mtimes){const key3=getKey(file),pairs=sameChangePairs.get(key3,[])||[];if(mtimes.every(e3=>-1!==pairs.indexOf(e3)))return EVEN}function compareFileFreshness(baseFile,checkTarget){var _a13,_b6,_c3,_d2,_e2,_f;if(void 0===baseFile&&null==checkTarget)return EVEN;if(null==baseFile)return TARGET_IS_NEW;if(null==checkTarget)return BASE_IS_NEW;const modifiedBase="stat"in baseFile?null!=(_b6=null==(_a13=null==baseFile?void 0:baseFile.stat)?void 0:_a13.mtime)?_b6:0:null!=(_c3=null==baseFile?void 0:baseFile.mtime)?_c3:0,modifiedTarget="stat"in checkTarget?null!=(_e2=null==(_d2=null==checkTarget?void 0:checkTarget.stat)?void 0:_d2.mtime)?_e2:0:null!=(_f=null==checkTarget?void 0:checkTarget.mtime)?_f:0;return modifiedBase&&modifiedTarget&&isMarkedAsSameChanges(baseFile,[modifiedBase,modifiedTarget])?EVEN:compareMTime(modifiedBase,modifiedTarget)}function getLogLevel(showNotice){return showNotice?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO}async function autosaveCache(db,mapKey){var _a13;const savedData=null!=(_a13=await db.get(mapKey))?_a13:new Map,_commit2=()=>{try{scheduleTask("commit-map-save-"+mapKey,250,async()=>{await db.set(mapKey,savedData)})}catch(e3){}};return{set(key3,value){const modified=savedData.get(key3)!==value,result=savedData.set(key3,value);modified&&_commit2();return result},clear(){savedData.clear();_commit2()},delete(key3){const result=savedData.delete(key3);result&&_commit2();return result},get:key3=>savedData.get(key3),has:key3=>savedData.has(key3),keys:()=>savedData.keys(),get size(){return savedData.size}}}function onlyInNTimes(n3,proc){let counter=0;return function(){counter++%n3==0&&proc(counter)}}function redactObject(obj,dotted,redactedValue="REDACTED"){const keys3=dotted.split(".");let current=obj;for(let i3=0;i3<keys3.length-1;i3++){const key3=keys3[i3];key3 in current||(current[key3]={});current=current[key3]}const lastKey=keys3[keys3.length-1];lastKey in current&&(current[lastKey]=redactedValue);return obj}async function generateReport(settings,core){let responseConfig={};const REDACTED="𝑅𝐸𝐷𝐴𝐶𝑇𝐸𝐷";if(settings.remoteType==REMOTE_COUCHDB)try{const credential=generateCredentialObject(settings),customHeaders=parseHeaderValues(settings.couchDB_CustomHeaders),r4=await requestToCouchDBWithCredentials(settings.couchDB_URI,credential,compatGlobal.origin,void 0,void 0,void 0,customHeaders);responseConfig=r4.json;redactObject(responseConfig,"couch_httpd_auth.secret");redactObject(responseConfig,"couch_httpd_auth.authentication_db");redactObject(responseConfig,"couch_httpd_auth.authentication_redirect");redactObject(responseConfig,"couchdb.uuid");redactObject(responseConfig,"admins");redactObject(responseConfig,"users");redactObject(responseConfig,"chttpd_auth.secret");delete responseConfig.jwt_keys}catch(ex){Logger(ex,LOG_LEVEL_VERBOSE);responseConfig={error:"Requesting information from the remote CouchDB has failed. If you are using IBM Cloudant, this is normal behaviour."}}else settings.remoteType==REMOTE_MINIO&&(responseConfig={error:"Object Storage Synchronisation"});const defaultKeys=Object.keys(DEFAULT_SETTINGS),pluginConfig=JSON.parse(JSON.stringify(settings)),pluginKeys=Object.keys(pluginConfig);for(const key3 of pluginKeys)defaultKeys.includes(key3)||delete pluginConfig[key3];pluginConfig.couchDB_DBNAME=REDACTED;pluginConfig.couchDB_PASSWORD=REDACTED;const scheme=pluginConfig.couchDB_URI.startsWith("http:")?"(HTTP)":pluginConfig.couchDB_URI.startsWith("https:")?"(HTTPS)":"";pluginConfig.couchDB_URI=isCloudantURI(pluginConfig.couchDB_URI)?"cloudant":`self-hosted${scheme}`;pluginConfig.couchDB_USER=REDACTED;pluginConfig.passphrase=REDACTED;pluginConfig.encryptedPassphrase=REDACTED;pluginConfig.encryptedCouchDBConnection=REDACTED;pluginConfig.accessKey=REDACTED;pluginConfig.secretKey=REDACTED;const redact=source2=>`${REDACTED}(${source2.length} letters)`,toSchemeOnly=uri=>{var _a13;try{return`${new URL(uri).protocol}//`}catch(e3){const matched=uri.match(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//);return null!=(_a13=null==matched?void 0:matched[0])?_a13:REDACTED}};pluginConfig.remoteConfigurations=Object.fromEntries(Object.entries(pluginConfig.remoteConfigurations||{}).map(([id,config])=>[id,{...config,uri:toSchemeOnly(config.uri)}]));pluginConfig.region=redact(pluginConfig.region);pluginConfig.bucket=redact(pluginConfig.bucket);pluginConfig.pluginSyncExtendedSetting={};pluginConfig.P2P_AppID=redact(pluginConfig.P2P_AppID);pluginConfig.P2P_passphrase=redact(pluginConfig.P2P_passphrase);pluginConfig.P2P_roomID=redact(pluginConfig.P2P_roomID);pluginConfig.P2P_relays=redact(pluginConfig.P2P_relays);pluginConfig.jwtKey=redact(pluginConfig.jwtKey);pluginConfig.jwtSub=redact(pluginConfig.jwtSub);pluginConfig.jwtKid=redact(pluginConfig.jwtKid);pluginConfig.bucketCustomHeaders=redact(pluginConfig.bucketCustomHeaders);pluginConfig.couchDB_CustomHeaders=redact(pluginConfig.couchDB_CustomHeaders);pluginConfig.P2P_turnCredential=redact(pluginConfig.P2P_turnCredential);pluginConfig.P2P_turnUsername=redact(pluginConfig.P2P_turnUsername);pluginConfig.P2P_turnServers=`(${pluginConfig.P2P_turnServers.split(",").length} servers configured)`;const endpoint=pluginConfig.endpoint;if(""==endpoint)pluginConfig.endpoint="Not configured or AWS";else{const endpointScheme=pluginConfig.endpoint.startsWith("http:")?"(HTTP)":pluginConfig.endpoint.startsWith("https:")?"(HTTPS)":"";pluginConfig.endpoint=`${-1!==endpoint.indexOf(".r2.cloudflarestorage.")?"R2":"self-hosted?"}(${endpointScheme})`}const obsidianInfo={navigator:compatGlobal.navigator.userAgent,fileSystem:core.services.vault.isStorageInsensitive()?"insensitive":"sensitive"},result={obsidianInfo,responseConfig,pluginConfig,manifestVersion,packageVersion};return result}function addLog(log2){logForDump.push(log2);for(;logForDump.length>1e3;)logForDump.shift()}function addDisplayLog(log2){logForDisplay.push(log2);for(;logForDisplay.length>200;)logForDisplay.shift();updateLogMessage()}function redactLog(log2){let redactedLog=log2;for(const pattern of redactPatterns)redactedLog=redactedLog.replace(pattern,match3=>match3.split(":")[0]+": [REDACTED]");return redactedLog}function JsonResolvePane($$anchor,$$props){function parseJson(json){if(!1===json)return!1;try{return JSON.parse(json)}catch(ex){return!1}}function docToString(doc){return"plain"==doc.datatype?getDocData(doc.data):readString(new Uint8Array(decodeBinary(doc.data)))}function revStringToRevNumber(rev3){return rev3?rev3.split("-")[0]:""}function getDiff(left,right){const dmp=new import_diff_match_patch.diff_match_patch,mapLeft=dmp.diff_linesToChars_(left,right),diffLeftSrc=dmp.diff_main(mapLeft.chars1,mapLeft.chars2,!1);dmp.diff_charsToLines_(diffLeftSrc,mapLeft.lineArray);return diffLeftSrc}function getJsonDiff(a2,b3){return getDiff(JSON.stringify(a2,null,2),JSON.stringify(b3,null,2))}function apply2(){if(get2(docA)&&get2(docB)){if(get2(docA)._id==get2(docB)._id){if("A"==get2(mode))return callback()(get2(docA)._rev,void 0);if("B"==get2(mode))return callback()(get2(docB)._rev,void 0)}else{if("A"==get2(mode))return callback()(void 0,docToString(get2(docA)));if("B"==get2(mode))return callback()(void 0,docToString(get2(docB)))}if("BA"==get2(mode))return callback()(void 0,JSON.stringify(get2(objBA),null,2));if("AB"==get2(mode))return callback()(void 0,JSON.stringify(get2(objAB),null,2));callback()(void 0,void 0)}}function cancel(){callback()(void 0,void 0)}var fragment,h22,text2,node,consequent,alternate_1;push($$props,!0);append_styles($$anchor,$$css2);const binding_group=[];let docs=prop($$props,"docs",27,()=>proxy([])),callback=prop($$props,"callback",11,async(_,__)=>{Promise.resolve()}),filename=prop($$props,"filename",11,""),nameA=prop($$props,"nameA",11,"A"),nameB=prop($$props,"nameB",11,"B"),defaultSelect=prop($$props,"defaultSelect",11,""),keepOrder=prop($$props,"keepOrder",11,!1),hideLocal=prop($$props,"hideLocal",11,!1);const docsArray=user_derived(()=>docs()&&docs().length>=2?keepOrder()||docs()[0].mtime<docs()[1].mtime?{a:docs()[0],b:docs()[1]}:{a:docs()[1],b:docs()[0]}:{a:!1,b:!1}),docA=user_derived(()=>get2(docsArray).a),docB=user_derived(()=>get2(docsArray).b),docAContent=user_derived(()=>get2(docA)&&docToString(get2(docA))),docBContent=user_derived(()=>get2(docB)&&docToString(get2(docB))),objA=user_derived(()=>parseJson(get2(docAContent))||{}),objB=user_derived(()=>parseJson(get2(docBContent))||{}),objAB=user_derived(()=>mergeObject(get2(objA),get2(objB))),objBAw=user_derived(()=>mergeObject(get2(objB),get2(objA))),objBA=user_derived(()=>!!isObjectDifferent(get2(objBAw),get2(objAB))&&get2(objBAw));let diffs=user_derived(()=>get2(objA)&&get2(selectedObj)?getJsonDiff(get2(objA),get2(selectedObj)):[]),mode=state(proxy(defaultSelect()));const mergedObjs=user_derived(()=>({"":!1,A:get2(objA),B:get2(objB),AB:get2(objAB),BA:get2(objBA)}));let selectedObj=user_derived(()=>get2(mode)in get2(mergedObjs)?get2(mergedObjs)[get2(mode)]:{});proxy([]);const modes=user_derived(()=>{let newModes=[];if(!hideLocal()){newModes.push(["",$msg("Not now")]);newModes.push(["A",nameA()||"A"])}newModes.push(["B",nameB()||"B"]);newModes.push(["AB",`${nameA()||"A"} + ${nameB()||"B"}`]);newModes.push(["BA",`${nameB()||"B"} + ${nameA()||"A"}`]);return newModes});fragment=root_6();h22=first_child(fragment);text2=child(h22,!0);reset(h22);node=sibling(h22,2);consequent=$$anchor2=>{var div_1,button,text_2,fragment_1=root3(),div=first_child(fragment_1),text_1=child(div,!0);reset(div);div_1=sibling(div,2);button=child(div_1);text_2=child(button,!0);reset(button);reset(div_1);template_effect(($0,$1)=>{set_text(text_1,$0);set_text(text_2,$1)},[()=>$msg("Just for a minute, please!"),()=>$msg("Dismiss")]);delegated("click",button,apply2);append($$anchor2,fragment_1)};alternate_1=$$anchor2=>{var node_2,consequent_2,alternate,div_5,table3,tbody,tr,th,text_6,td3,node_3,consequent_3,text_8,td_1,text_9,tr_1,th_1,text_10,td_2,node_4,consequent_4,text_12,td_3,text_13,div_6,node_5,consequent_5,button_2,fragment_2=root_5(),div_2=first_child(fragment_2);each(div_2,21,()=>get2(modes),index,($$anchor3,m3)=>{var fragment_3=comment(),node_1=first_child(fragment_3),consequent_1=$$anchor4=>{var input_value,div_3,text_3,label2=root_12(),input=child(label2);remove_input_defaults(input);div_3=sibling(input,2);text_3=child(div_3,!0);reset(div_3);reset(label2);template_effect(()=>{var _a13;set_class(label2,1,"sls-setting-label "+(get2(m3)[0]==get2(mode)?"selected":""),"svelte-1ah3y1j");input_value!==(input_value=get2(m3)[0])&&(input.value=null!=(_a13=input.__value=get2(m3)[0])?_a13:"");set_text(text_3,get2(m3)[1])});bind_group(binding_group,[],input,()=>{get2(m3)[0];return get2(mode)},$$value=>set(mode,$$value));append($$anchor4,label2)};if_block(node_1,$$render=>{""!=get2(m3)[0]&&0==get2(mergedObjs)[get2(m3)[0]]||$$render(consequent_1)});append($$anchor3,fragment_3)});reset(div_2);node_2=sibling(div_2,2);consequent_2=$$anchor3=>{var div_4=root_3();each(div_4,21,()=>get2(diffs),index,($$anchor4,diff)=>{var span=root_2(),text_4=child(span,!0);reset(span);template_effect(()=>{set_class(span,1,clsx2(get2(diff)[0]==import_diff_match_patch.DIFF_DELETE?"deleted":get2(diff)[0]==import_diff_match_patch.DIFF_INSERT?"added":"normal"),"svelte-1ah3y1j");set_text(text_4,get2(diff)[1])});append($$anchor4,span)});reset(div_4);append($$anchor3,div_4)};alternate=$$anchor3=>{var text_5=text();template_effect($0=>set_text(text_5,$0),[()=>$msg("NO PREVIEW")]);append($$anchor3,text_5)};if_block(node_2,$$render=>{0!=get2(selectedObj)?$$render(consequent_2):$$render(alternate,-1)});div_5=sibling(node_2,2);table3=child(div_5);tbody=child(table3);tr=child(tbody);th=child(tr);text_6=child(th,!0);reset(th);td3=sibling(th);node_3=child(td3);consequent_3=$$anchor3=>{var text_7=text();template_effect($0=>set_text(text_7,`Rev:${null!=$0?$0:""}`),[()=>revStringToRevNumber(get2(docA)._rev)]);append($$anchor3,text_7)};if_block(node_3,$$render=>{get2(docA)._id==get2(docB)._id&&$$render(consequent_3)});text_8=sibling(node_3);reset(td3);td_1=sibling(td3);text_9=child(td_1);reset(td_1);reset(tr);tr_1=sibling(tr);th_1=child(tr_1);text_10=child(th_1,!0);reset(th_1);td_2=sibling(th_1);node_4=child(td_2);consequent_4=$$anchor3=>{var text_11=text();template_effect($0=>set_text(text_11,`Rev:${null!=$0?$0:""}`),[()=>revStringToRevNumber(get2(docB)._rev)]);append($$anchor3,text_11)};if_block(node_4,$$render=>{get2(docA)._id==get2(docB)._id&&$$render(consequent_4)});text_12=sibling(node_4);reset(td_2);td_3=sibling(td_2);text_13=child(td_3);reset(td_3);reset(tr_1);reset(tbody);reset(table3);reset(div_5);div_6=sibling(div_5,2);node_5=child(div_6);consequent_5=$$anchor3=>{var button_1=root_4();delegated("click",button_1,cancel);append($$anchor3,button_1)};if_block(node_5,$$render=>{hideLocal()&&$$render(consequent_5)});button_2=sibling(node_5,2);reset(div_6);template_effect(($0,$1)=>{var _a13,_b6;set_text(text_6,nameA());set_text(text_8,` ${null!=$0?$0:""}`);set_text(text_9,`${null!=(_a13=get2(docAContent)&&get2(docAContent).length)?_a13:""} letters`);set_text(text_10,nameB());set_text(text_12,` ${null!=$1?$1:""}`);set_text(text_13,`${null!=(_b6=get2(docBContent)&&get2(docBContent).length)?_b6:""} letters`)},[()=>new Date(get2(docA).mtime).toLocaleString(),()=>new Date(get2(docB).mtime).toLocaleString()]);delegated("click",button_2,apply2);append($$anchor2,fragment_2)};if_block(node,$$render=>{get2(docA)&&get2(docB)?$$render(alternate_1,-1):$$render(consequent)});template_effect(()=>set_text(text2,filename()));append($$anchor,fragment);pop()}function stopAllRunningProcessors(){const processors=[...allRunningProcessors];for(const processor of processors)processor.terminate()}function isErrorOf(ex,statusCode){if(!ex||"object"!=typeof ex)throw new Error("Expected an object error, but got "+typeof ex);return"status"in ex&&"number"==typeof ex.status&&ex.status==statusCode}function isNotFoundError(ex){return isErrorOf(ex,404)}function isUnauthorizedError(ex){return isErrorOf(ex,401)}function isEntryWithPath(entry){return!(!entry||"object"!=typeof entry)&&("path"in entry&&"string"==typeof entry.path)}function tryGetFilePath(entry){if(isEntryWithPath(entry))return entry.path}function getInitialiseDirection(mode){return"FETCH"==mode?"pullForce":"OVERWRITE"==mode?"pushForce":"MERGE"==mode&&"safe"}function isDisableMode(mode){return"DISABLE"==mode||"DISABLE_HIDDEN"==mode}function isHiddenFileSyncMode(mode){return"FETCH"==mode||"OVERWRITE"==mode||"MERGE"==mode||isDisableMode(mode)}async function configureHiddenFileSyncMode(mode,handlers3){if(!isHiddenFileSyncMode(mode))return"ignored";if(isDisableMode(mode)){await handlers3.disable();return"disabled"}const direction=getInitialiseDirection(mode);if(!1===direction)return"ignored";await handlers3.enable();await handlers3.initialise(direction);return"enabled"}function isRecord(value){return"object"==typeof value&&null!==value}function isPluginManifest(value){return isRecord(value)&&"string"==typeof value.id&&"string"==typeof value.name&&(void 0===value.dir||"string"==typeof value.dir)}function isStringSet(value){if(!(value instanceof Set))return!1;const entries2=value;for(const entry of entries2)if("string"!=typeof entry)return!1;return!0}async function invokeLifecycleMethod(manager,methodName,pluginId){const method=manager[methodName];if("function"!=typeof method)throw new TypeError(`Obsidian does not expose ${methodName}`);const result=Reflect.apply(method,manager,[pluginId]);await result}function getObsidianCommunityPluginManager(app){const managerValue=Reflect.get(app,"plugins");if(!isRecord(managerValue)||!isRecord(managerValue.manifests)||!isStringSet(managerValue.enabledPlugins))throw new TypeError("Obsidian does not expose the community plug-in manager");const manifests=Object.values(managerValue.manifests).filter(isPluginManifest);return{enabledPlugins:managerValue.enabledPlugins,manifests,loadPlugin:async pluginId=>await invokeLifecycleMethod(managerValue,"loadPlugin",pluginId),unloadPlugin:async pluginId=>await invokeLifecycleMethod(managerValue,"unloadPlugin",pluginId)}}function getComparingMTime(doc,includeDeleted=!1){var _a13,_b6,_c3;if(null===doc)return 0;if(!1===doc)return 0;if(void 0===doc)return 0;if(!includeDeleted){if("deleted"in doc&&doc.deleted)return 0;if("_deleted"in doc&&doc._deleted)return 0}return"stat"in doc?null!=(_b6=null==(_a13=doc.stat)?void 0:_a13.mtime)?_b6:0:null!=(_c3=doc.mtime)?_c3:0}async function e(){function c3(t9,n4){if(e3.buffer.byteLength<t9+n4){const r5=Math.ceil((t9+n4-e3.buffer.byteLength)/65536);e3.grow(r5),a2=new Uint8Array(e3.buffer)}}function l2(t9,e4,n4,r5,i4,o3){c3(t9);const h4=new Uint8Array(t9);return a2.set(h4),n4(0,e4),h4.set(a2.slice(0,t9)),{update(e5){let n5;return a2.set(h4),"string"==typeof e5?(c3(3*e5.length,t9),n5=b3.encodeInto(e5,a2.subarray(t9)).written):(c3(e5.byteLength,t9),a2.set(e5,t9),n5=e5.byteLength),r5(0,t9,n5),h4.set(a2.slice(0,t9)),this},digest:()=>(a2.set(h4),o3(i4(0)))}}function d4(t9){return t9>>>0}function y2(t9){return t9&f4}function p2(t9){let e4=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return c3(3*t9.length,0),d4(n3(0,b3.encodeInto(t9,a2).written,e4))}function v2(t9){let e4=arguments.length>1&&void 0!==arguments[1]?arguments[1]:w2;return c3(3*t9.length,0),y2(r4(0,b3.encodeInto(t9,a2).written,e4))}const{instance:{exports:{mem:e3,xxh32:n3,xxh64:r4,init32:i3,update32:o2,digest32:h3,init64:s2,update64:u2,digest64:g2}}}=await WebAssembly.instantiate(t);let a2=new Uint8Array(e3.buffer);const f4=BigInt(2)**BigInt(64)-BigInt(1),b3=new TextEncoder,w2=BigInt(0);return{h32:p2,h32ToString(t9){return p2(t9,arguments.length>1&&void 0!==arguments[1]?arguments[1]:0).toString(16).padStart(8,"0")},h32Raw(t9){let e4=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return c3(t9.byteLength,0),a2.set(t9),d4(n3(0,t9.byteLength,e4))},create32(){return l2(48,arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,i3,o2,h3,d4)},h64:v2,h64ToString(t9){return v2(t9,arguments.length>1&&void 0!==arguments[1]?arguments[1]:w2).toString(16).padStart(16,"0")},h64Raw(t9){let e4=arguments.length>1&&void 0!==arguments[1]?arguments[1]:w2;return c3(t9.byteLength,0),a2.set(t9),y2(r4(0,t9.byteLength,e4))},create64(){return l2(88,arguments.length>0&&void 0!==arguments[0]?arguments[0]:w2,s2,u2,g2,y2)}}}function digestHash(src){let hash3="";for(const v2 of src)hash3=hashFunc(hash3+v2);return""==hash3?hashFunc("**"):hash3}function PluginCombo($$anchor,$$props){async function comparePlugin(local,remote){var _a13,_b6;let freshness2="",version3="",contentCheck=!1,canApply2=!1;if(local||remote)if(local&&!remote)freshness2=$msg("Local only");else if(remote&&!local){freshness2=$msg("Remote only");canApply2=!0}else{const dtDiff=(null!==(_a13=null==local?void 0:local.mtime)&&void 0!==_a13?_a13:0)-(null!==(_b6=null==remote?void 0:remote.mtime)&&void 0!==_b6?_b6:0),diff=timeDeltaToHumanReadable(Math.abs(dtDiff));if(dtDiff/1e3<-10){freshness2=$msg("Newer (${diff})",{diff});canApply2=!0;contentCheck=!0}else if(dtDiff/1e3>10){freshness2=$msg("Older (${diff})",{diff});canApply2=!0;contentCheck=!0}else{freshness2=$msg("Same");canApply2=!1;contentCheck=!0}}else freshness2="";const localVersionStr=(null==local?void 0:local.version)||"0.0.0",remoteVersionStr=(null==remote?void 0:remote.version)||"0.0.0";if((null==local?void 0:local.version)||(null==remote?void 0:remote.version)){const compare3=`${localVersionStr}`.localeCompare(remoteVersionStr,void 0,{numeric:!0});0==compare3?version3=$msg("Same"):compare3<0?version3=$msg("Lower (${local} < ${remote})",{local:localVersionStr,remote:remoteVersionStr}):compare3>0&&(version3=$msg("Higher (${local} > ${remote})",{local:localVersionStr,remote:remoteVersionStr}))}if(contentCheck&&local&&remote){const{canApply:canApply3,equivalency:equivalency3,canCompare:canCompare3}=await checkEquivalency(local,remote);return{canApply:canApply3,freshness:freshness2,equivalency:equivalency3,version:version3,canCompare:canCompare3}}return{canApply:canApply2,freshness:freshness2,equivalency:"",version:version3,canCompare:!1}}async function checkEquivalency(local,remote){let equivalency2="",canApply2=!1,canCompare2=!1;const filenames=[...new Set([...local.files.map(e3=>e3.filename),...remote.files.map(e3=>e3.filename)])],matchingStatus=filenames.map(filename=>{const localFile=local.files.find(e3=>e3.filename==filename),remoteFile=remote.files.find(e3=>e3.filename==filename);if(localFile||remoteFile){if(localFile&&!remoteFile)return 2;if(!localFile&&remoteFile)return 8;if(localFile&&remoteFile){const localDoc=getDocData(localFile.data),remoteDoc=getDocData(remoteFile.data);return localDoc==remoteDoc?4:16}return 16}return 0}).reduce((p2,c3)=>p2|c3,0);if(4==matchingStatus){equivalency2=$msg("Same");canApply2=!1}else if(matchingStatus<=4){equivalency2=$msg("Same or local only");canApply2=!1}else if(16==matchingStatus){canApply2=!0;canCompare2=!0;equivalency2=$msg("Different")}else{canApply2=!0;canCompare2=!0;equivalency2=$msg("Mixed")}return{equivalency:equivalency2,canApply:canApply2,canCompare:canCompare2}}async function performCompare(local,remote){const result=await comparePlugin(local,remote);set(canApply,result.canApply);set(freshness,result.freshness);set(equivalency,result.equivalency);set(version2,result.version);set(canCompare,result.canCompare);set(pickToCompare,!1);get2(canCompare)&&((null==local?void 0:local.files.length)==(null==remote?void 0:remote.files.length)&&1==(null==local?void 0:local.files.length)&&(null==local?void 0:local.files[0].filename)==(null==remote?void 0:remote.files[0].filename)?set(pickToCompare,!1):set(pickToCompare,!0))}async function updateTerms(list2,selectNewest2,isMaintenanceMode2){const local=list2.find(e3=>e3.term==thisTerm());if(isMaintenanceMode2)set(terms,[...new Set(list2.map(e3=>e3.term))]);else if(hideNotApplicable()){const termsTmp=[],wk2=[...new Set(list2.map(e3=>e3.term))];for(const termName of wk2){const remote=list2.find(e3=>e3.term==termName);(await comparePlugin(local,remote)).canApply&&termsTmp.push(termName)}set(terms,[...termsTmp])}else set(terms,[...new Set(list2.map(e3=>e3.term))].filter(e3=>e3!=thisTerm()));let newest=local;if(selectNewest2){for(const term of get2(terms)){const remote=list2.find(e3=>e3.term==term);remote&&remote.mtime&&((null==newest?void 0:newest.mtime)||0)<remote.mtime&&(newest=remote)}newest&&newest.term!=thisTerm()&&selected(newest.term)}get2(terms).indexOf(selected())<0&&selected("")}async function applySelected(){const local=list().find(e3=>e3.term==thisTerm()),selectedItem=list().find(e3=>e3.term==selected());selectedItem&&await applyData()(selectedItem)&&addOn.updatePluginList(!0,null==local?void 0:local.documentPath)}async function compareSelected(){const local=list().find(e3=>e3.term==thisTerm()),selectedItem=list().find(e3=>e3.term==selected());await compareItems(local,selectedItem)}async function compareItems(local,remote,filename){if(local&&remote){if(!filename){await compareData()(local,remote)&&addOn.updatePluginList(!0,local.documentPath);return}{const localCopy=local instanceof PluginDataExDisplayV2?new PluginDataExDisplayV2(local):{...local},remoteCopy=remote instanceof PluginDataExDisplayV2?new PluginDataExDisplayV2(remote):{...remote};localCopy.files=localCopy.files.filter(e3=>e3.filename==filename);remoteCopy.files=remoteCopy.files.filter(e3=>e3.filename==filename);await compareData()(localCopy,remoteCopy,!0)&&addOn.updatePluginList(!0,local.documentPath)}}else remote||local?remote?local||Logger("Could not locally item",LOG_LEVEL_INFO):Logger("Could not find remote item",LOG_LEVEL_INFO):Logger("Could not find both remote and local item",LOG_LEVEL_INFO)}async function pickCompareItem(evt){const local=list().find(e3=>e3.term==thisTerm()),selectedItem=list().find(e3=>e3.term==selected());if(!local)return;if(!selectedItem)return;const menu=new import_obsidian.Menu;menu.addItem(item=>item.setTitle($msg("Compare file")).setIsLabel(!0));menu.addSeparator();const files=unique(local.files.map(e3=>e3.filename).concat(selectedItem.files.map(e3=>e3.filename))),convDate=dt=>{if(!dt)return $msg("(Missing)");const d4=new Date(dt.mtime);return d4.toLocaleString()};for(const filename of files)menu.addItem(item=>{const localFile=local.files.find(e3=>e3.filename==filename),remoteFile=selectedItem.files.find(e3=>e3.filename==filename),title=`${filename} (${convDate(localFile)} <--\x3e ${convDate(remoteFile)})`;item.setTitle(title).onClick(e3=>compareItems(local,selectedItem,filename))});menu.showAtMouseEvent(evt)}async function deleteSelected(){const selectedItem=list().find(e3=>e3.term==selected());selectedItem&&await deleteData()(selectedItem)&&addOn.reloadPluginList(!0)}async function duplicateItem(){const local=list().find(e3=>e3.term==thisTerm());if(!local){Logger("Could not find local item",LOG_LEVEL_VERBOSE);return}const duplicateTermName=await get2(core).confirm.askString($msg("Duplicate"),$msg("device name"),"");if(duplicateTermName){if(duplicateTermName.contains("/")){Logger($msg('We can not use "/" to the device name'),LOG_LEVEL_NOTICE);return}const key3=`${plugin2().core.services.API.getSystemConfigDir()}/${local.files[0].filename}`;await addOn.storeCustomizationFiles(key3,duplicateTermName);await addOn.updatePluginList(!1,addOn.filenameToUnifiedKey(key3,duplicateTermName))}}var fragment,node,consequent_6,alternate_4;push($$props,!1);append_styles($$anchor,$$css3);const core=mutable_source();let list=prop($$props,"list",24,()=>[]),thisTerm=prop($$props,"thisTerm",8,""),hideNotApplicable=prop($$props,"hideNotApplicable",8,!1),selectNewest=prop($$props,"selectNewest",8,0),selectNewestStyle=prop($$props,"selectNewestStyle",8,0),applyAllPluse=prop($$props,"applyAllPluse",8,0),applyData=prop($$props,"applyData",8),compareData=prop($$props,"compareData",8),deleteData=prop($$props,"deleteData",8),hidden=prop($$props,"hidden",8),plugin2=prop($$props,"plugin",8),isMaintenanceMode=prop($$props,"isMaintenanceMode",8,!1),isFlagged=prop($$props,"isFlagged",8,!1);const addOn=plugin2().core.getAddOn(ConfigSync.name);if(!addOn){Logger(`Could not load the add-on ${ConfigSync.name}`,LOG_LEVEL_INFO);throw new Error(`Could not load the add-on ${ConfigSync.name}`)}let selected=prop($$props,"selected",12,""),freshness=mutable_source(""),equivalency=mutable_source(""),version2=mutable_source(""),canApply=mutable_source(!1),canCompare=mutable_source(!1),pickToCompare=mutable_source(!1),currentSelectNewest=mutable_source(0),currentApplyAll=mutable_source(0),terms=mutable_source([]);legacy_pre_effect(()=>deep_read_state(plugin2()),()=>{set(core,plugin2().core)});legacy_pre_effect(()=>(deep_read_state(selectNewest()),get2(currentSelectNewest),deep_read_state(selectNewestStyle()),deep_read_state(isFlagged()),deep_read_state(list()),deep_read_state(isMaintenanceMode())),()=>{let doSelectNewest=!1;selectNewest()!=get2(currentSelectNewest)&&(1==selectNewestStyle()?doSelectNewest=!0:2==selectNewestStyle()?doSelectNewest=isFlagged():3==selectNewestStyle()&&selected(""));updateTerms(list(),doSelectNewest,isMaintenanceMode());set(currentSelectNewest,selectNewest())});legacy_pre_effect(()=>(deep_read_state(applyAllPluse()),get2(currentApplyAll),deep_read_state(selected()),deep_read_state(hidden())),()=>{const doApply=applyAllPluse()!=get2(currentApplyAll);set(currentApplyAll,applyAllPluse());doApply&&selected()&&(hidden()||applySelected())});legacy_pre_effect(()=>(deep_read_state(selected()),deep_read_state(thisTerm()),deep_read_state(list())),()=>{set(freshness,"");set(equivalency,"");set(version2,"");set(canApply,!1);if(""==selected());else if(selected()==thisTerm()){set(freshness,$msg("This device"));set(canApply,!1)}else{const local=list().find(e3=>e3.term==thisTerm()),remote=list().find(e3=>e3.term==selected());performCompare(local,remote)}});legacy_pre_effect_reset();init();fragment=comment();node=first_child(fragment);consequent_6=$$anchor2=>{var fragment_1=root_9(),node_1=sibling(first_child(fragment_1),2),consequent_5=$$anchor3=>{var span_2,text_1,span_3,text_2,select,option,node_2,node_3,consequent_2,alternate_2,node_6,consequent_4,fragment_2=root_8(),span=first_child(fragment_2),span_1=child(span),text2=child(span_1,!0);reset(span_1);span_2=sibling(span_1,2);text_1=child(span_2,!0);reset(span_2);span_3=sibling(span_2,2);text_2=child(span_3,!0);reset(span_3);reset(span);select=sibling(span,2);option=child(select);option.value=option.__value="";node_2=sibling(option);each(node_2,1,()=>get2(terms),index,($$anchor4,term)=>{var option_1_value,option_1=root4(),text_3=child(option_1,!0);reset(option_1);option_1_value={};template_effect(()=>{var _a13;set_text(text_3,get2(term));option_1_value!==(option_1_value=get2(term))&&(option_1.value=null!=(_a13=option_1.__value=get2(term))?_a13:"")});append($$anchor4,option_1)});reset(select);node_3=sibling(select,2);consequent_2=$$anchor4=>{var button_3,fragment_3=root_42(),node_4=first_child(fragment_3),consequent_1=$$anchor5=>{var fragment_4=comment(),node_5=first_child(fragment_4),consequent=$$anchor6=>{var button=root_13();event("click",button,pickCompareItem);append($$anchor6,button)},alternate=$$anchor6=>{var button_1=root_22();event("click",button_1,compareSelected);append($$anchor6,button_1)};if_block(node_5,$$render=>{get2(pickToCompare)?$$render(consequent):$$render(alternate,-1)});append($$anchor5,fragment_4)},alternate_1=$$anchor5=>{var button_2=root_32();append($$anchor5,button_2)};if_block(node_4,$$render=>{get2(canCompare)?$$render(consequent_1):$$render(alternate_1,-1)});button_3=sibling(node_4,2);event("click",button_3,applySelected);append($$anchor4,fragment_3)};alternate_2=$$anchor4=>{var fragment_5=root_52();next(2);append($$anchor4,fragment_5)};if_block(node_3,$$render=>{get2(canApply)||isMaintenanceMode()&&""!=selected()?$$render(consequent_2):$$render(alternate_2,-1)});node_6=sibling(node_3,2);consequent_4=$$anchor4=>{var fragment_6=comment(),node_7=first_child(fragment_6),consequent_3=$$anchor5=>{var button_4=root_62();event("click",button_4,deleteSelected);append($$anchor5,button_4)},alternate_3=$$anchor5=>{var button_5=root_7();event("click",button_5,duplicateItem);append($$anchor5,button_5)};if_block(node_7,$$render=>{""!=selected()?$$render(consequent_3):$$render(alternate_3,-1)});append($$anchor4,fragment_6)};if_block(node_6,$$render=>{isMaintenanceMode()&&$$render(consequent_4)});template_effect(()=>{set_text(text2,get2(freshness));set_text(text_1,get2(equivalency));set_text(text_2,get2(version2))});bind_select_value(select,selected);append($$anchor3,fragment_2)};if_block(node_1,$$render=>{hidden()||$$render(consequent_5)});append($$anchor2,fragment_1)};alternate_4=$$anchor2=>{var fragment_7=root_10(),span_4=sibling(first_child(fragment_7),2),text_4=child(span_4,!0);reset(span_4);next(4);template_effect($0=>set_text(text_4,$0),[()=>(deep_read_state($msg),untrack(()=>$msg("All the same or non-existent")))]);append($$anchor2,fragment_7)};if_block(node,$$render=>{get2(terms),untrack(()=>get2(terms).length>0)?$$render(consequent_6):$$render(alternate_4,-1)});append($$anchor,fragment);pop()}function PluginPane($$anchor,$$props){async function requestUpdate(){await addOn.updatePluginList(!0)}async function requestReload(){await addOn.reloadPluginList(!0)}function filterList(list2,categories){const w2=list2.filter(e3=>-1!==categories.indexOf(e3.category));return w2.sort((a2,b3)=>`${a2.category}-${a2.name}`.localeCompare(`${b3.category}-${b3.name}`))}function groupBy(items,key3){let ret={};for(const v2 of items){const k2=key3 in v2?v2[key3]:"";ret[k2]=ret[k2]||[];ret[k2].push(v2)}for(const k2 in ret)ret[k2]=ret[k2].sort((a2,b3)=>`${a2.category}-${a2.name}`.localeCompare(`${b3.category}-${b3.name}`));const w2=Object.entries(ret);return w2.sort(([a2],[b3])=>`${a2}`.localeCompare(`${b3}`))}async function scanAgain(){await addOn.scanAllConfigFiles(!0);await requestUpdate()}async function replicate2(){await core().services.replication.replicate(!0)}function selectAllNewest(selectMode){update(selectNewestPulse);set(selectNewestStyle,selectMode?1:2)}function resetSelectNewest(){update(selectNewestPulse);set(selectNewestStyle,3)}function applyAll(){update(applyAllPluse)}async function applyData(data){return await addOn.applyData(data)}async function compareData(docA,docB,compareEach=!1){return await addOn.compareUsingDisplayData(docA,docB,compareEach)}async function deleteData(data){return await addOn.deleteData(data)}function askMode(evt,title,key3){var _a13;const menu=new import_obsidian.Menu;menu.addItem(item=>item.setTitle(title).setIsLabel(!0));menu.addSeparator();const prevMode=null!==(_a13=automaticList.get(key3))&&void 0!==_a13?_a13:MODE_SELECTIVE;for(const mode of[MODE_SELECTIVE,MODE_AUTOMATIC,MODE_PAUSED,MODE_SHINY])menu.addItem(item=>{item.setTitle(`${getIcon(mode)}:${TITLES[mode]}`).onClick(e3=>{mode===MODE_AUTOMATIC?askOverwriteModeForAutomatic(evt,key3):setMode(key3,mode)}).setChecked(prevMode==mode).setDisabled(prevMode==mode)});menu.showAtMouseEvent(evt)}function applyAutomaticSync(key3,direction){var _a13,_b6;setMode(key3,MODE_AUTOMATIC);const configDir=normalizePath(plugin2().core.services.API.getSystemConfigDir()),files=(null!==(_b6=null===(_a13=plugin2().core.settings.pluginSyncExtendedSetting[key3])||void 0===_a13?void 0:_a13.files)&&void 0!==_b6?_b6:[]).map(e3=>`${configDir}/${e3}`);addOnHiddenFileSync.initialiseInternalFileSync(direction,!0,files)}function askOverwriteModeForAutomatic(evt,key3){const menu=new import_obsidian.Menu;menu.addItem(item=>item.setTitle($msg("Initial Action")).setIsLabel(!0));menu.addSeparator();menu.addItem(item=>{item.setTitle($msg("↑: Overwrite Remote")).onClick(e3=>{applyAutomaticSync(key3,"pushForce")})}).addItem(item=>{item.setTitle($msg("↓: Overwrite Local")).onClick(e3=>{applyAutomaticSync(key3,"pullForce")})}).addItem(item=>{item.setTitle($msg("⇅: Use newer")).onClick(e3=>{applyAutomaticSync(key3,"safe")})});menu.showAtMouseEvent(evt)}function setMode(key3,mode){if(key3.startsWith(PREFIX_PLUGIN_ALL+"/")){setMode(PREFIX_PLUGIN_DATA+key3.substring(PREFIX_PLUGIN_ALL.length),mode);setMode(PREFIX_PLUGIN_MAIN+key3.substring(PREFIX_PLUGIN_ALL.length),mode);return}const files=unique(get2(list).filter(e3=>`${e3.category}/${e3.name}`==key3).map(e3=>e3.files).flat().map(e3=>e3.filename));if(mode==MODE_SELECTIVE){automaticList.delete(key3);delete plugin2().core.settings.pluginSyncExtendedSetting[key3];set(automaticListDisp,automaticList)}else{automaticList.set(key3,mode);set(automaticListDisp,automaticList);key3 in plugin2().core.settings.pluginSyncExtendedSetting||plugin2(plugin2().core.settings.pluginSyncExtendedSetting[key3]={key:key3,mode,files:[]},!0);plugin2(plugin2().core.settings.pluginSyncExtendedSetting[key3].files=files,!0);plugin2(plugin2().core.settings.pluginSyncExtendedSetting[key3].mode=mode,!0)}core().services.setting.saveSettingData()}function getIcon(mode){if(mode in ICONS)return ICONS[mode]}function computeDisplayKeys(list2){const extraKeys=Object.keys(plugin2().core.settings.pluginSyncExtendedSetting);return[...list2,...extraKeys.map(e3=>`${e3}///`.split("/")).filter(e3=>e3[0]&&e3[1]).map(e3=>({category:e3[0],name:e3[1],displayName:e3[1]}))].sort((a2,b3)=>{var _a13,_b6;return(null!==(_a13=a2.displayName)&&void 0!==_a13?_a13:a2.name).localeCompare(null!==(_b6=b3.displayName)&&void 0!==_b6?_b6:b3.name)}).reduce((p2,c3)=>{var _a13,_b6;return{...p2,[c3.category]:unique(c3.category in p2?[...p2[c3.category],null!==(_a13=c3.displayName)&&void 0!==_a13?_a13:c3.name]:[null!==(_b6=c3.displayName)&&void 0!==_b6?_b6:c3.name])}},{})}async function deleteAllItems(term){const deleteItems=get2(list).filter(e3=>e3.term==term);for(const item of deleteItems)await deleteData(item);addOn.reloadPluginList(!0)}function updateNameMap(e3){const items=[...e3.entries()].map(([k2,v2])=>[k2.split("/").slice(-2).join("/"),v2.name]),newMap=new Map(items);if(newMap.size==get2(nameMap).size){let diff=!1;for(const[k2,v2]of newMap)if(get2(nameMap).get(k2)!=v2){diff=!0;break}if(!diff)return}set(nameMap,newMap)}var fragment,div,div_1,button,text2,button_1,text_1,button_2,text_2,node,consequent,div_2,button_4,text_4,button_5,text_5,button_6,text_6,button_7,text_7,div_3,node_1,consequent_1,div_4,node_2,consequent_2,alternate_5,node_13,consequent_10,div_32,label_2,span_4,text_28,input,div_33,label_3,span_5,text_29,input_1;push($$props,!1);append_styles($$anchor,$$css4);const $pluginManifestStore=()=>store_get(pluginManifestStore,"$pluginManifestStore",$$stores),$pluginV2Progress=()=>store_get(pluginV2Progress,"$pluginV2Progress",$$stores),[$$stores,$$cleanup]=setup_stores(),hideNotApplicable=mutable_source(),thisTerm=mutable_source(),options=mutable_source();let plugin2=prop($$props,"plugin",12),core=prop($$props,"core",8);const addOn=core().getAddOn(ConfigSync.name);if(!addOn){const msg=$msg("AddOn Module (ConfigSync) has not been loaded. This is very unexpected situation. Please report this issue.");Logger(msg,LOG_LEVEL_NOTICE);throw new Error(msg)}const addOnHiddenFileSync=core().getAddOn(HiddenFileSync.name);if(!addOnHiddenFileSync){const msg=$msg("AddOn Module (HiddenFileSync) has not been loaded. This is very unexpected situation. Please report this issue.");Logger(msg,LOG_LEVEL_NOTICE);throw new Error(msg)}let list=mutable_source([]),selectNewestPulse=mutable_source(0),selectNewestStyle=mutable_source(0),hideEven=mutable_source(!1),loading=mutable_source(!1),applyAllPluse=mutable_source(0),isMaintenanceMode=mutable_source(!1),allTerms=mutable_source([]);pluginList.subscribe(e3=>{set(list,e3);set(allTerms,unique(get2(list).map(e4=>e4.term)))});pluginIsEnumerating.subscribe(e3=>{set(loading,e3)});onMount(async()=>{requestUpdate()});const displays={CONFIG:$msg("Configuration"),THEME:$msg("Themes"),SNIPPET:$msg("Snippets")},ICONS={[MODE_SELECTIVE]:"🔀",[MODE_PAUSED]:"⛔",[MODE_AUTOMATIC]:"✨",[MODE_SHINY]:"🚩"},TITLES={[MODE_SELECTIVE]:$msg("Selective"),[MODE_PAUSED]:$msg("Ignore"),[MODE_AUTOMATIC]:$msg("Automatic"),[MODE_SHINY]:$msg("Flagged Selective")},PREFIX_PLUGIN_ALL="PLUGIN_ALL",PREFIX_PLUGIN_DATA="PLUGIN_DATA",PREFIX_PLUGIN_MAIN="PLUGIN_MAIN";let automaticList=new Map,automaticListDisp=mutable_source(new Map);for(const{key:key3,mode}of Object.values(plugin2().core.settings.pluginSyncExtendedSetting))automaticList.set(key3,mode);set(automaticListDisp,automaticList);let displayKeys=mutable_source({}),deleteTerm=mutable_source(""),nameMap=mutable_source(new Map),displayEntries=mutable_source([]),pluginEntries=mutable_source([]),useSyncPluginEtc=plugin2().core.settings.usePluginEtc;legacy_pre_effect(()=>{},()=>{set(hideNotApplicable,!1)});legacy_pre_effect(()=>deep_read_state(core()),()=>{set(thisTerm,core().services.setting.getDeviceAndVaultName())});legacy_pre_effect(()=>(get2(thisTerm),get2(hideNotApplicable),get2(selectNewestPulse),get2(selectNewestStyle),get2(applyAllPluse),deep_read_state(plugin2()),get2(isMaintenanceMode)),()=>{set(options,{thisTerm:get2(thisTerm),hideNotApplicable:get2(hideNotApplicable),selectNewest:get2(selectNewestPulse),selectNewestStyle:get2(selectNewestStyle),applyAllPluse:get2(applyAllPluse),applyData,compareData,deleteData,plugin:plugin2(),isMaintenanceMode:get2(isMaintenanceMode)})});legacy_pre_effect(()=>get2(list),()=>{set(displayKeys,computeDisplayKeys(get2(list)))});legacy_pre_effect(()=>$pluginManifestStore(),()=>{updateNameMap($pluginManifestStore())});legacy_pre_effect(()=>get2(displayKeys),()=>{set(displayEntries,Object.entries(displays).filter(([key3,_])=>key3 in get2(displayKeys)))});legacy_pre_effect(()=>get2(list),()=>{set(pluginEntries,groupBy(filterList(get2(list),["PLUGIN_MAIN","PLUGIN_DATA","PLUGIN_ETC"]),"name"))});legacy_pre_effect_reset();init();fragment=root_132();div=first_child(fragment);div_1=child(div);button=child(div_1);text2=child(button,!0);reset(button);button_1=sibling(button,2);text_1=child(button_1,!0);reset(button_1);button_2=sibling(button_1,2);text_2=child(button_2,!0);reset(button_2);node=sibling(button_2,2);consequent=$$anchor2=>{var button_3=root5(),text_3=child(button_3,!0);reset(button_3);template_effect($0=>set_text(text_3,$0),[()=>(deep_read_state($msg),untrack(()=>$msg("Reload")))]);event("click",button_3,()=>requestReload());append($$anchor2,button_3)};if_block(node,$$render=>{get2(isMaintenanceMode)&&$$render(consequent)});reset(div_1);div_2=sibling(div_1,2);button_4=child(div_2);text_4=child(button_4,!0);reset(button_4);button_5=sibling(button_4,2);text_5=child(button_5);reset(button_5);button_6=sibling(button_5,2);text_6=child(button_6,!0);reset(button_6);button_7=sibling(button_6,2);text_7=child(button_7,!0);reset(button_7);reset(div_2);reset(div);div_3=sibling(div,2);node_1=child(div_3);consequent_1=$$anchor2=>{var span=root_14(),text_8=child(span);reset(span);template_effect($0=>set_text(text_8,`${null!=$0?$0:""}${0==$pluginV2Progress()?"":` (${$pluginV2Progress()})`}`),[()=>(deep_read_state($msg),untrack(()=>$msg("Updating list...")))]);append($$anchor2,span)};if_block(node_1,$$render=>{(get2(loading)||0!==$pluginV2Progress())&&$$render(consequent_1)});reset(div_3);div_4=sibling(div_3,2);node_2=child(div_4);consequent_2=$$anchor2=>{var div_5=root_23(),text_9=child(div_5,!0);reset(div_5);template_effect($0=>set_text(text_9,$0),[()=>(deep_read_state($msg),untrack(()=>$msg("No Items.")))]);append($$anchor2,div_5)};alternate_5=$$anchor2=>{var div_11,h3_1,text_14,node_6,fragment_1=root_102(),node_3=first_child(fragment_1);each(node_3,1,()=>get2(displayEntries),index,($$anchor3,$$item)=>{var div_6,h3,text_10,node_4,$$array=user_derived(()=>to_array(get2($$item),2));let key3=()=>get2($$array)[0],label2=()=>get2($$array)[1];div_6=root_53();h3=child(div_6);text_10=child(h3,!0);reset(h3);node_4=sibling(h3,2);each(node_4,1,()=>(get2(displayKeys),key3(),untrack(()=>get2(displayKeys)[key3()])),index,($$anchor4,name)=>{var div_7,div_8,button_8,text_11,span_1,text_12,div_9,node_5,consequent_3,alternate;const bindKey=derived_safe_equal(()=>`${key3()}/${get2(name)}`),mode=derived_safe_equal(()=>(get2(automaticListDisp),deep_read_state(get2(bindKey)),deep_read_state(MODE_SELECTIVE),untrack(()=>{var _a13;return null!=(_a13=get2(automaticListDisp).get(get2(bindKey)))?_a13:MODE_SELECTIVE})));div_7=root_43();div_8=child(div_7);button_8=child(div_8);text_11=child(button_8,!0);reset(button_8);span_1=sibling(button_8,2);text_12=child(span_1,!0);reset(span_1);reset(div_8);div_9=sibling(div_8,2);node_5=child(div_9);consequent_3=$$anchor5=>{{let $0=derived_safe_equal(()=>get2(mode)==MODE_SHINY),$1=derived_safe_equal(()=>(get2(list),key3(),get2(name),untrack(()=>get2(list).filter(e3=>e3.category==key3()&&e3.name==get2(name)))));PluginCombo($$anchor5,spread_props(()=>get2(options),{get isFlagged(){return get2($0)},get list(){return get2($1)},hidden:!1}))}};alternate=$$anchor5=>{var div_10=root_33(),text_13=child(div_10,!0);reset(div_10);template_effect(()=>set_text(text_13,(deep_read_state(get2(mode)),untrack(()=>TITLES[get2(mode)]))));append($$anchor5,div_10)};if_block(node_5,$$render=>{get2(mode)==MODE_SELECTIVE||get2(mode)==MODE_SHINY?$$render(consequent_3):$$render(alternate,-1)});reset(div_9);reset(div_7);template_effect(($0,$1)=>{set_class(div_7,1,"labelrow "+(get2(hideEven)?"hideeven":""),"svelte-10jah2g");set_text(text_11,$0);set_text(text_12,$1)},[()=>(deep_read_state(get2(mode)),untrack(()=>getIcon(get2(mode)))),()=>(key3(),get2(nameMap),get2(name),untrack(()=>"THEME"==key3()&&get2(nameMap).get(`themes/${get2(name)}`)||get2(name)))]);event("click",button_8,evt=>askMode(evt,`${key3()}/${get2(name)}`,get2(bindKey)));append($$anchor4,div_7)});reset(div_6);template_effect(()=>set_text(text_10,label2()));append($$anchor3,div_6)});div_11=sibling(node_3,2);h3_1=child(div_11);text_14=child(h3_1,!0);reset(h3_1);node_6=sibling(h3_1,2);each(node_6,1,()=>get2(pluginEntries),index,($$anchor3,$$item)=>{var fragment_3,div_12,div_13,button_9,text_15,span_2,text_16,div_14,node_7,consequent_4,node_8,consequent_9,alternate_4,$$array_1=user_derived(()=>to_array(get2($$item),2));let name=()=>get2($$array_1)[0],listX=()=>get2($$array_1)[1];const bindKeyAll=derived_safe_equal(()=>`${PREFIX_PLUGIN_ALL}/${name()}`),modeAll=derived_safe_equal(()=>(get2(automaticListDisp),deep_read_state(get2(bindKeyAll)),deep_read_state(MODE_SELECTIVE),untrack(()=>{var _a13;return null!=(_a13=get2(automaticListDisp).get(get2(bindKeyAll)))?_a13:MODE_SELECTIVE}))),bindKeyMain=derived_safe_equal(()=>`${PREFIX_PLUGIN_MAIN}/${name()}`),modeMain=derived_safe_equal(()=>(get2(automaticListDisp),deep_read_state(get2(bindKeyMain)),deep_read_state(MODE_SELECTIVE),untrack(()=>{var _a13;return null!=(_a13=get2(automaticListDisp).get(get2(bindKeyMain)))?_a13:MODE_SELECTIVE}))),bindKeyData=derived_safe_equal(()=>`${PREFIX_PLUGIN_DATA}/${name()}`),modeData=derived_safe_equal(()=>(get2(automaticListDisp),deep_read_state(get2(bindKeyData)),deep_read_state(MODE_SELECTIVE),untrack(()=>{var _a13;return null!=(_a13=get2(automaticListDisp).get(get2(bindKeyData)))?_a13:MODE_SELECTIVE}))),bindKeyETC=derived_safe_equal(()=>`PLUGIN_ETC/${name()}`),modeEtc=derived_safe_equal(()=>(get2(automaticListDisp),deep_read_state(get2(bindKeyETC)),deep_read_state(MODE_SELECTIVE),untrack(()=>{var _a13;return null!=(_a13=get2(automaticListDisp).get(get2(bindKeyETC)))?_a13:MODE_SELECTIVE})));fragment_3=root_92();div_12=first_child(fragment_3);div_13=child(div_12);button_9=child(div_13);text_15=child(button_9,!0);reset(button_9);span_2=sibling(button_9,2);text_16=child(span_2,!0);reset(span_2);reset(div_13);div_14=sibling(div_13,2);node_7=child(div_14);consequent_4=$$anchor4=>{{let $0=derived_safe_equal(()=>get2(modeAll)==MODE_SHINY);PluginCombo($$anchor4,spread_props(()=>get2(options),{get isFlagged(){return get2($0)},get list(){return listX()},hidden:!0}))}};if_block(node_7,$$render=>{get2(modeAll)!=MODE_SELECTIVE&&get2(modeAll)!=MODE_SHINY||$$render(consequent_4)});reset(div_14);reset(div_12);node_8=sibling(div_12,2);consequent_9=$$anchor4=>{var div_17,node_9,consequent_5,alternate_1,div_19,div_20,button_11,text_19,div_21,node_10,consequent_6,alternate_2,node_11,consequent_8,fragment_5=root_72(),div_15=first_child(fragment_5),div_16=child(div_15),button_10=child(div_16),text_17=child(button_10,!0);reset(button_10);next(2);reset(div_16);div_17=sibling(div_16,2);node_9=child(div_17);consequent_5=$$anchor5=>{{let $0=derived_safe_equal(()=>get2(modeMain)==MODE_SHINY),$1=derived_safe_equal(()=>(listX(),untrack(()=>filterList(listX(),["PLUGIN_MAIN"]))));PluginCombo($$anchor5,spread_props(()=>get2(options),{get isFlagged(){return get2($0)},get list(){return get2($1)},hidden:!1}))}};alternate_1=$$anchor5=>{var div_18=root_33(),text_18=child(div_18,!0);reset(div_18);template_effect(()=>set_text(text_18,(deep_read_state(get2(modeMain)),untrack(()=>TITLES[get2(modeMain)]))));append($$anchor5,div_18)};if_block(node_9,$$render=>{get2(modeMain)==MODE_SELECTIVE||get2(modeMain)==MODE_SHINY?$$render(consequent_5):$$render(alternate_1,-1)});reset(div_17);reset(div_15);div_19=sibling(div_15,2);div_20=child(div_19);button_11=child(div_20);text_19=child(button_11,!0);reset(button_11);next(2);reset(div_20);div_21=sibling(div_20,2);node_10=child(div_21);consequent_6=$$anchor5=>{{let $0=derived_safe_equal(()=>get2(modeData)==MODE_SHINY),$1=derived_safe_equal(()=>(listX(),untrack(()=>filterList(listX(),["PLUGIN_DATA"]))));PluginCombo($$anchor5,spread_props(()=>get2(options),{get isFlagged(){return get2($0)},get list(){return get2($1)},hidden:!1}))}};alternate_2=$$anchor5=>{var div_22=root_33(),text_20=child(div_22,!0);reset(div_22);template_effect(()=>set_text(text_20,(deep_read_state(get2(modeData)),untrack(()=>TITLES[get2(modeData)]))));append($$anchor5,div_22)};if_block(node_10,$$render=>{get2(modeData)==MODE_SELECTIVE||get2(modeData)==MODE_SHINY?$$render(consequent_6):$$render(alternate_2,-1)});reset(div_21);reset(div_19);node_11=sibling(div_19,2);consequent_8=$$anchor5=>{var span_3,text_22,div_25,node_12,consequent_7,alternate_3,div_23=root_63(),div_24=child(div_23),button_12=child(div_24),text_21=child(button_12,!0);reset(button_12);span_3=sibling(button_12,2);text_22=child(span_3,!0);reset(span_3);reset(div_24);div_25=sibling(div_24,2);node_12=child(div_25);consequent_7=$$anchor6=>{{let $0=derived_safe_equal(()=>get2(modeEtc)==MODE_SHINY),$1=derived_safe_equal(()=>(listX(),untrack(()=>filterList(listX(),["PLUGIN_ETC"]))));PluginCombo($$anchor6,spread_props(()=>get2(options),{get isFlagged(){return get2($0)},get list(){return get2($1)},hidden:!1}))}};alternate_3=$$anchor6=>{var div_26=root_33(),text_23=child(div_26,!0);reset(div_26);template_effect(()=>set_text(text_23,(deep_read_state(get2(modeEtc)),untrack(()=>TITLES[get2(modeEtc)]))));append($$anchor6,div_26)};if_block(node_12,$$render=>{get2(modeEtc)==MODE_SELECTIVE||get2(modeEtc)==MODE_SHINY?$$render(consequent_7):$$render(alternate_3,-1)});reset(div_25);reset(div_23);template_effect(($0,$1)=>{set_class(div_23,1,"filerow "+(get2(hideEven)?"hideeven":""),"svelte-10jah2g");set_text(text_21,$0);set_text(text_22,$1)},[()=>(deep_read_state(get2(modeEtc)),untrack(()=>getIcon(get2(modeEtc)))),()=>(deep_read_state($msg),untrack(()=>$msg("Other files")))]);event("click",button_12,evt=>askMode(evt,`PLUGIN_ETC/${name()}`,get2(bindKeyETC)));append($$anchor5,div_23)};if_block(node_11,$$render=>{useSyncPluginEtc&&$$render(consequent_8)});template_effect(($0,$1)=>{set_class(div_15,1,"filerow "+(get2(hideEven)?"hideeven":""),"svelte-10jah2g");set_text(text_17,$0);set_class(div_19,1,"filerow "+(get2(hideEven)?"hideeven":""),"svelte-10jah2g");set_text(text_19,$1)},[()=>(deep_read_state(get2(modeMain)),untrack(()=>getIcon(get2(modeMain)))),()=>(deep_read_state(get2(modeData)),untrack(()=>getIcon(get2(modeData))))]);event("click",button_10,evt=>askMode(evt,`${PREFIX_PLUGIN_MAIN}/${name()}/MAIN`,get2(bindKeyMain)));event("click",button_11,evt=>askMode(evt,`${PREFIX_PLUGIN_DATA}/${name()}`,get2(bindKeyData)));append($$anchor4,fragment_5)};alternate_4=$$anchor4=>{var div_27=root_82(),div_28=child(div_27),text_24=child(div_28,!0);reset(div_28);reset(div_27);template_effect(()=>set_text(text_24,(deep_read_state(get2(modeAll)),untrack(()=>TITLES[get2(modeAll)]))));append($$anchor4,div_27)};if_block(node_8,$$render=>{get2(modeAll)==MODE_SELECTIVE||get2(modeAll)==MODE_SHINY?$$render(consequent_9):$$render(alternate_4,-1)});template_effect(($0,$1)=>{set_class(div_12,1,"labelrow "+(get2(hideEven)?"hideeven":""),"svelte-10jah2g");set_text(text_15,$0);set_text(text_16,$1)},[()=>(deep_read_state(get2(modeAll)),untrack(()=>getIcon(get2(modeAll)))),()=>(get2(nameMap),name(),untrack(()=>get2(nameMap).get(`plugins/${name()}`)||name()))]);event("click",button_9,evt=>askMode(evt,`${PREFIX_PLUGIN_ALL}/${name()}`,get2(bindKeyAll)));append($$anchor3,fragment_3)});reset(div_11);template_effect($0=>set_text(text_14,$0),[()=>(deep_read_state($msg),untrack(()=>$msg("Plugins")))]);append($$anchor2,fragment_1)};if_block(node_2,$$render=>{get2(list),untrack(()=>0==get2(list).length)?$$render(consequent_2):$$render(alternate_5,-1)});reset(div_4);node_13=sibling(div_4,2);consequent_10=$$anchor2=>{var div_31,label_1,text_26,select,button_13,div_29=root_122(),div_30=child(div_29),h3_2=child(div_30),text_25=child(h3_2,!0);reset(h3_2);div_31=sibling(h3_2,2);label_1=child(div_31);text_26=child(label_1,!0);reset(label_1);select=sibling(label_1,2);each(select,5,()=>get2(allTerms),index,($$anchor3,term)=>{var option_value,option=root_11(),text_27=child(option,!0);reset(option);option_value={};template_effect(()=>{var _a13;set_text(text_27,get2(term));option_value!==(option_value=get2(term))&&(option.value=null!=(_a13=option.__value=get2(term))?_a13:"")});append($$anchor3,option)});reset(select);button_13=sibling(select,2);reset(div_31);reset(div_30);reset(div_29);template_effect(($0,$1)=>{set_text(text_25,$0);set_text(text_26,$1)},[()=>(deep_read_state($msg),untrack(()=>$msg("Maintenance Commands"))),()=>(deep_read_state($msg),untrack(()=>$msg("Delete All of")))]);bind_select_value(select,()=>get2(deleteTerm),$$value=>set(deleteTerm,$$value));event("click",button_13,evt=>{deleteAllItems(get2(deleteTerm))});append($$anchor2,div_29)};if_block(node_13,$$render=>{get2(isMaintenanceMode)&&$$render(consequent_10)});div_32=sibling(node_13,2);label_2=child(div_32);span_4=child(label_2);text_28=child(span_4,!0);reset(span_4);input=sibling(span_4);remove_input_defaults(input);reset(label_2);reset(div_32);div_33=sibling(div_32,2);label_3=child(div_33);span_5=child(label_3);text_29=child(span_5,!0);reset(span_5);input_1=sibling(span_5);remove_input_defaults(input_1);reset(label_3);reset(div_33);template_effect(($0,$1,$2,$3,$4,$5,$6,$7,$8)=>{set_text(text2,$0);set_text(text_1,$1);set_text(text_2,$2);set_text(text_4,$3);set_text(text_5,`🚩 ${null!=$4?$4:""}`);set_text(text_6,$5);set_text(text_7,$6);set_text(text_28,$7);set_text(text_29,$8)},[()=>(deep_read_state($msg),untrack(()=>$msg("Scan changes"))),()=>(deep_read_state($msg),untrack(()=>$msg("Sync once"))),()=>(deep_read_state($msg),untrack(()=>$msg("Refresh"))),()=>(deep_read_state($msg),untrack(()=>$msg("Select All Shiny"))),()=>(deep_read_state($msg),untrack(()=>$msg("Select Flagged Shiny"))),()=>(deep_read_state($msg),untrack(()=>$msg("Deselect all"))),()=>(deep_read_state($msg),untrack(()=>$msg("Apply All Selected"))),()=>(deep_read_state($msg),untrack(()=>$msg("Hide not applicable items"))),()=>(deep_read_state($msg),untrack(()=>$msg("Maintenance mode")))]);event("click",button,()=>scanAgain());event("click",button_1,()=>replicate2());event("click",button_2,()=>requestUpdate());event("click",button_4,()=>selectAllNewest(!0));event("click",button_5,()=>selectAllNewest(!1));event("click",button_6,()=>resetSelectNewest());event("click",button_7,()=>applyAll());bind_checked(input,()=>get2(hideEven),$$value=>set(hideEven,$$value));bind_checked(input_1,()=>get2(isMaintenanceMode),$$value=>set(isMaintenanceMode,$$value));append($$anchor,fragment);pop();$$cleanup()}function serialize(data){var _a13,_b6,_c3,_d2,_e2;let ret="";ret+=":";ret+=data.category+d+data.name+d+data.term+d2;ret+=(null!=(_a13=data.version)?_a13:"")+d2;ret+=data.mtime+d2;for(const file of data.files){ret+=file.filename+d+(null!=(_b6=file.displayName)?_b6:"")+d+(null!=(_c3=file.version)?_c3:"")+d2;const hash3=digestHash(null!=(_d2=file.data)?_d2:[]);ret+=file.mtime+d+file.size+d+hash3+d2;for(const data2 of null!=(_e2=file.data)?_e2:[])ret+=data2+d;ret+=d2}return ret}function splitWithDelimiters(sources){const result=[];for(const str of sources){let startIndex=0;const maxLen=str.length;let i1,i22,i3=-1;do{i1=str.indexOf(d,startIndex);i22=str.indexOf(d2,startIndex);if(-1==i1&&-1==i22)break;i3=-1==i1?i22:-1==i22||i1<i22?i1:i22;result.push(str.slice(startIndex,i3+1));startIndex=i3+1}while(i3<maxLen);startIndex<maxLen&&result.push(str.slice(startIndex))}""==sources[sources.length-1]&&result.push("");return result}function getTokenizer(source2){const sources=splitWithDelimiters(source2);sources[0]=sources[0].substring(1);let pos=0,lineRunOut=!1;const t9={next(){if(lineRunOut)return"";if(pos>=sources.length)return"";const item=sources[pos];item.endsWith(d2)?lineRunOut=!0:pos++;return item.endsWith(d)||item.endsWith(d2)?item.substring(0,item.length-1):item+this.next()},nextLine(){if(lineRunOut)pos++;else{for(;!sources[pos].endsWith(d2);){pos++;if(pos>=sources.length)break}pos++}lineRunOut=!1}};return t9}function deserialize2(str){const tokens=getTokenizer(str),category=tokens.next(),name=tokens.next(),term=tokens.next();tokens.nextLine();const version2=tokens.next();tokens.nextLine();const mtime=Number(tokens.next());tokens.nextLine();const result=Object.assign({},{category,name,term,version:version2,mtime,files:[]});let filename="";do{filename=tokens.next();if(!filename)break;const displayName=tokens.next(),version3=tokens.next();tokens.nextLine();const mtime2=Number(tokens.next()),size=Number(tokens.next()),hash3=tokens.next();tokens.nextLine();const data=[];let piece="";do{piece=tokens.next();if(""==piece)break;data.push(piece)}while(""!=piece);result.files.push({filename,displayName,version:version3,mtime:mtime2,size,data,hash:hash3});tokens.nextLine()}while(filename);return result}function deserialize(str,def){try{if(":"==str[0][0]){const o2=deserialize2(str);return o2}return JSON.parse(str.join(""))}catch(e3){try{const parsed=(0,import_obsidian.parseYaml)(str.join(""));return parsed}catch(e4){return def}}}function categoryToFolder(category,configDir=""){switch(category){case"CONFIG":return`${configDir}/`;case"THEME":return`${configDir}/themes/`;case"SNIPPET":return`${configDir}/snippets/`;case"PLUGIN_MAIN":return`${configDir}/plugins/`;case"PLUGIN_DATA":return`${configDir}/plugins/`;case"PLUGIN_ETC":return`${configDir}/plugins/`;default:return""}}function setManifest(key3,manifest){const old=pluginManifests.get(key3);if(!old||isObjectDifferent(manifest,old)){pluginManifests.set(key3,manifest);pluginManifestStore.set(pluginManifests)}}async function countCompromisedChunks(db){try{Logger("Counting compromised chunks...",LOG_LEVEL_VERBOSE);const task1=db.find(SELECTOR_COMPROMISED_CHUNK_1),task2=db.find(SELECTOR_COMPROMISED_CHUNK_2),[result1,result2]=await Promise.all([task1,task2]);return result1.docs.length+result2.docs.length}catch(ex){Logger("Error counting compromised chunks!",LOG_LEVEL_INFO);Logger(ex,LOG_LEVEL_VERBOSE);return!1}}function resetV3Buf(){_nonceV3[0]=0;const _wk=webcrypto2.getRandomValues(new Uint8Array(12));bufV3.set(_wk);bufV3.set(_nonceV3,8)}function incIV(){_nonceV3[0]++;bufV3.set(_nonceV3,8);_nonceV3[0]>1500&&resetV3Buf();return bufV3}async function generateKey(passphrase){const passphraseBin=(new TextEncoder).encode(passphrase),digestOfPassphrase=await webcrypto2.subtle.digest("SHA-256",new Uint8Array([...passphraseBin,...SALT])),salt=digestOfPassphrase.slice(0,16),baseKey=await webcrypto2.subtle.importKey("raw",passphraseBin,"PBKDF2",!1,["deriveBits","deriveKey"]),pbkdf2Params={name:"PBKDF2",hash:"SHA-256",salt,iterations:1e5},derivedKey=await webcrypto2.subtle.deriveKey(pbkdf2Params,baseKey,{name:"AES-GCM",length:256},!1,["decrypt","encrypt"]);return derivedKey}async function encryptV3(input,passphrase){if(previousPassphrase!==passphrase){resetV3Buf();const key3=await generateKey(passphrase);encryptionKey=key3;previousPassphrase=passphrase}const iv=incIV(),dataBuf=writeString(input),encryptedDataArrayBuffer=await webcrypto2.subtle.encrypt({name:"AES-GCM",iv},encryptionKey,dataBuf),encryptedData2=""+await arrayBufferToBase64Single(new Uint8Array(encryptedDataArrayBuffer)),ret=`%~${uint8ArrayToHexString(iv)}${encryptedData2}`;return ret}async function decryptV3(encryptedResult,passphrase){if(previousDecryptionPassphrase!==passphrase){const key3=await generateKey(passphrase);decryptionKey=key3;previousDecryptionPassphrase=passphrase}const ivStr=encryptedResult.substring(2,26),encryptedData=encryptedResult.substring(26),iv=hexStringToUint8Array(ivStr),encryptedDataArrayBuffer=base64ToArrayBuffer(encryptedData),dataBuffer=await webcrypto2.subtle.decrypt({name:"AES-GCM",iv},decryptionKey,encryptedDataArrayBuffer),plain=readString(new Uint8Array(dataBuffer));return plain}function createPBKDF2Salt(){return webcrypto3.getRandomValues(new Uint8Array(PBKDF2_SALT_LENGTH))}async function deriveKey(passphrase,pbkdf2Salt,hkdfSalt){const masterKey=await deriveMasterKey(passphrase,pbkdf2Salt),chunkKey=await webcrypto3.subtle.deriveKey({name:"HKDF",salt:hkdfSalt,info:new Uint8Array,hash:"SHA-256"},masterKey,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return chunkKey}async function encryptData(key3,iv,data){return await webcrypto3.subtle.encrypt({name:"AES-GCM",iv,tagLength:gcmTagLength},key3,data)}async function _encrypt(input,passphrase,pbkdf2Salt){const hkdfSalt=webcrypto3.getRandomValues(new Uint8Array(HKDF_SALT_LENGTH)),key3=await deriveKey(passphrase,pbkdf2Salt,hkdfSalt),iv=webcrypto3.getRandomValues(new Uint8Array(IV_LENGTH)),encryptedDataArrayBuffer=await encryptData(key3,iv,input),encryptedData=new Uint8Array(encryptedDataArrayBuffer);return[iv,hkdfSalt,encryptedData]}async function encryptBinary(input,passphrase,pbkdf2Salt){const[iv,hkdfSalt,encryptedData]=await _encrypt(input,passphrase,pbkdf2Salt),totalLength=iv.length+hkdfSalt.length+encryptedData.length,result=new Uint8Array(totalLength);result.set(iv,0);result.set(hkdfSalt,iv.length);result.set(encryptedData,iv.length+hkdfSalt.length);return result}async function encrypt2(input,passphrase,pbkdf2Salt){const inputBuffer=writeString(input),encrypted=await encryptBinary(inputBuffer,passphrase,pbkdf2Salt),inBase64=await arrayBufferToBase64Single(encrypted);return`${HKDF_ENCRYPTED_PREFIX}${inBase64}`}async function _decrypt(iv,pbkdf2Salt,hkdfSalt,encryptedData,passphrase){const key3=await deriveKey(passphrase,pbkdf2Salt,hkdfSalt),decryptedDataArrayBuffer=await webcrypto3.subtle.decrypt({name:"AES-GCM",iv,tagLength:gcmTagLength},key3,encryptedData);return new Uint8Array(decryptedDataArrayBuffer)}async function decryptBinary(binary,passphrase,pbkdf2Salt){if(binary.length<IV_LENGTH+HKDF_SALT_LENGTH)throw new Error("Invalid binary data length. Expected at least ivLength + saltLength bytes.");const iv=binary.slice(0,IV_LENGTH),hkdfSalt=binary.slice(IV_LENGTH,IV_LENGTH+HKDF_SALT_LENGTH),encryptedData=binary.slice(IV_LENGTH+HKDF_SALT_LENGTH),decryptedData=await _decrypt(iv,pbkdf2Salt,hkdfSalt,encryptedData,passphrase);return decryptedData}async function decrypt2(input,passphrase,pbkdf2Salt){if(!input.startsWith(HKDF_ENCRYPTED_PREFIX))throw new Error(`Invalid input format. Expected input to start with '${HKDF_ENCRYPTED_PREFIX}'.`);const headerLength=HKDF_ENCRYPTED_PREFIX.length,encryptedData=base64ToArrayBuffer(input.slice(headerLength)),decrypted=await decryptBinary(new Uint8Array(encryptedData),passphrase,pbkdf2Salt);return readString(decrypted)}async function testEncryptionFeature(){const testValue="Supercalifragilisticexpialidocious1234567890!@#$%^&*()_+[]{}|;':\",.<>?✔️✔️⚡𠮷𠮷",pbkdf2Salt=createPBKDF2Salt();try{const encrypted=await encrypt2(testValue,"test-passphrase",pbkdf2Salt),decrypted=await decrypt2(encrypted,"test-passphrase",pbkdf2Salt);if(decrypted!==testValue)throw new Error("Decryption did not return the original value.");Logger("Encryption feature test passed.",LOG_LEVEL_VERBOSE);return!0}catch(error){Logger("WARNING! Your device would not support encryption.",LOG_LEVEL_VERBOSE);Logger(error,LOG_LEVEL_VERBOSE);return!1}}function getSessionPBKDFSalt(refresh=!1){(void 0===_sessionPBKDFSalt||refresh)&&(_sessionPBKDFSalt=createPBKDF2Salt());return _sessionPBKDFSalt}async function encryptWithEphemeralSaltBinary(input,passphrase,refresh=!1){const pbkdf2Salt=getSessionPBKDFSalt(refresh),result=await _encrypt(input,passphrase,pbkdf2Salt),resultX=[pbkdf2Salt,...result],resultBuf=concatUInt8Array(resultX);return resultBuf}async function encryptWithEphemeralSalt(input,passphrase,refresh=!1){const encrypted=await encryptWithEphemeralSaltBinary(writeString(input),passphrase,refresh),inBase64=await arrayBufferToBase64Single(encrypted);return`${HKDF_SALTED_ENCRYPTED_PREFIX}${inBase64}`}async function decryptWithEphemeralSaltBinary(input,passphrase){if(input.length<IV_LENGTH+HKDF_SALT_LENGTH+PBKDF2_SALT_LENGTH)throw new Error("Invalid binary data length.");const r4=createTypedArrayReader(input),pbkdf2Salt=r4.read(PBKDF2_SALT_LENGTH),iv=r4.read(IV_LENGTH),hkdfSalt=r4.read(HKDF_SALT_LENGTH),encryptedData=r4.readAll(),decryptedData=await _decrypt(iv,pbkdf2Salt,hkdfSalt,encryptedData,passphrase);return decryptedData}async function decryptWithEphemeralSalt(input,passphrase){if(!input.startsWith(HKDF_SALTED_ENCRYPTED_PREFIX))throw new Error(`Invalid input format. Expected input to start with '${HKDF_SALTED_ENCRYPTED_PREFIX}'.`);const headerLength=HKDF_SALTED_ENCRYPTED_PREFIX.length,encryptedData=base64ToArrayBuffer(input.slice(headerLength)),decrypted=await decryptWithEphemeralSaltBinary(new Uint8Array(encryptedData),passphrase);return readString(decrypted)}async function obfuscatePath(path2,passphrase,autoCalculateIterations){const dataBuf=writeString(path2),[key3,salt,iv]=await getKeyForObfuscatePath(passphrase,dataBuf,autoCalculateIterations),encryptedDataArrayBuffer=await webcrypto4.subtle.encrypt({name:"AES-GCM",iv},key3,dataBuf),encryptedData2=await arrayBufferToBase64Single(new Uint8Array(encryptedDataArrayBuffer)),ret=`%${uint8ArrayToHexString(iv)}${uint8ArrayToHexString(salt)}${encryptedData2}`;return ret}function isPathProbablyObfuscated(path2){return path2.startsWith("%")&&path2.length>64}async function getKeyForObfuscatePath(passphrase,dataBuf,autoCalculateIterations){const passphraseLen=15-passphrase.length,iteration=autoCalculateIterations?1e3*(passphraseLen>0?passphraseLen:0)+121-passphraseLen:1e5,passphraseBin=(new TextEncoder).encode(passphrase),digest=await webcrypto4.subtle.digest({name:"SHA-256"},passphraseBin),buf2=new Uint8Array(await webcrypto4.subtle.digest({name:"SHA-256"},new Uint8Array([...dataBuf,...passphraseBin]))),salt=buf2.slice(0,16),iv=buf2.slice(16,32),keyMaterial=await webcrypto4.subtle.importKey("raw",digest,{name:"PBKDF2"},!1,["deriveKey"]),key3=await webcrypto4.subtle.deriveKey({name:"PBKDF2",salt,iterations:iteration,hash:"SHA-256"},keyMaterial,{name:"AES-GCM",length:256},!1,["encrypt"]);return[key3,salt,iv]}async function getKeyForEncrypt(passphrase,autoCalculateIterations){const buffKey=`${passphrase}-${autoCalculateIterations}`,f4=KeyBuffs.get(buffKey);if(f4){f4.count--;if(f4.count>0)return[f4.key,f4.salt];f4.count--}const passphraseLen=15-passphrase.length,iteration=autoCalculateIterations?1e3*(passphraseLen>0?passphraseLen:0)+121-passphraseLen:1e5,passphraseBin=(new TextEncoder).encode(passphrase),digest=await webcrypto5.subtle.digest({name:"SHA-256"},passphraseBin),keyMaterial=await webcrypto5.subtle.importKey("raw",digest,{name:"PBKDF2"},!1,["deriveKey"]),salt=webcrypto5.getRandomValues(new Uint8Array(16)),key3=await webcrypto5.subtle.deriveKey({name:"PBKDF2",salt,iterations:iteration,hash:"SHA-256"},keyMaterial,{name:"AES-GCM",length:256},!1,["encrypt"]);KeyBuffs.set(buffKey,{key:key3,salt,count:KEY_RECYCLE_COUNT});return[key3,salt]}async function getKeyForDecryption(passphrase,salt,autoCalculateIterations){keyGCCount--;if(keyGCCount<0){keyGCCount=KEY_RECYCLE_COUNT;const threshold=(decKeyIdx-decKeyMin)/2;for(const[key4,buff]of decKeyBuffs){buff.count<threshold&&decKeyBuffs.delete(key4);decKeyMin=decKeyIdx}}decKeyIdx++;const bufKey=passphrase+uint8ArrayToHexString(salt)+autoCalculateIterations,f4=decKeyBuffs.get(bufKey);if(f4){f4.count=decKeyIdx;return[f4.key,f4.salt]}const passphraseLen=15-passphrase.length,iteration=autoCalculateIterations?1e3*(passphraseLen>0?passphraseLen:0)+121-passphraseLen:1e5,passphraseBin=(new TextEncoder).encode(passphrase),digest=await webcrypto5.subtle.digest({name:"SHA-256"},passphraseBin),keyMaterial=await webcrypto5.subtle.importKey("raw",digest,{name:"PBKDF2"},!1,["deriveKey"]),key3=await webcrypto5.subtle.deriveKey({name:"PBKDF2",salt,iterations:iteration,hash:"SHA-256"},keyMaterial,{name:"AES-GCM",length:256},!1,["decrypt"]);decKeyBuffs.set(bufKey,{key:key3,salt,count:0});return[key3,salt]}function getSemiStaticField(reset2){if(null!=semiStaticFieldBuffer&&!reset2)return semiStaticFieldBuffer;semiStaticFieldBuffer=webcrypto5.getRandomValues(new Uint8Array(12));return semiStaticFieldBuffer}function getNonce(){nonceBuffer[0]++;nonceBuffer[0]>1e4&&getSemiStaticField(!0);return nonceBuffer}async function encrypt3(input,passphrase,autoCalculateIterations){const[key3,salt]=await getKeyForEncrypt(passphrase,autoCalculateIterations),fixedPart=getSemiStaticField(),invocationPart=getNonce(),iv=new Uint8Array([...fixedPart,...new Uint8Array(invocationPart.buffer)]),dataBuf=writeString(input),encryptedDataArrayBuffer=await webcrypto5.subtle.encrypt({name:"AES-GCM",iv},key3,dataBuf),encryptedData2=""+await arrayBufferToBase64Single(new Uint8Array(encryptedDataArrayBuffer)),ret=`%${uint8ArrayToHexString(iv)}${uint8ArrayToHexString(salt)}${encryptedData2}`;return ret}async function decryptV2(encryptedResult,passphrase,autoCalculateIterations){try{const ivStr=encryptedResult.substring(1,33),salt=encryptedResult.substring(33,65),encryptedData=encryptedResult.substring(65),[key3]=await getKeyForDecryption(passphrase,hexStringToUint8Array(salt),autoCalculateIterations),iv=hexStringToUint8Array(ivStr),encryptedDataArrayBuffer=decodeBinary(encryptedData),dataBuffer=await webcrypto5.subtle.decrypt({name:"AES-GCM",iv},key3,encryptedDataArrayBuffer),plain=readString(new Uint8Array(dataBuffer));return plain}catch(ex){Logger("Couldn't decode! You should wrong the passphrases (V2)",LOG_LEVEL_VERBOSE);Logger(ex,LOG_LEVEL_VERBOSE);throw ex}}async function decrypt3(encryptedResult,passphrase,autoCalculateIterations){try{if("%"==encryptedResult[0])return"~"===encryptedResult[1]?decryptV3(encryptedResult,passphrase):decryptV2(encryptedResult,passphrase,autoCalculateIterations);if(!encryptedResult.startsWith("[")||!encryptedResult.endsWith("]"))throw new Error("Encrypted data corrupted!");const w2=encryptedResult.substring(1,encryptedResult.length-1).split(",").map(e3=>'"'==e3[0]?e3.substring(1,e3.length-1):e3),[encryptedData,ivString,salt]=w2,[key3]=await getKeyForDecryption(passphrase,hexStringToUint8Array(salt),autoCalculateIterations),iv=hexStringToUint8Array(ivString),encryptedDataBin=atob(encryptedData),len=encryptedDataBin.length,encryptedDataArrayBuffer=new Uint8Array(len);for(let i3=len;i3>=0;--i3)encryptedDataArrayBuffer[i3]=encryptedDataBin.charCodeAt(i3);const plainStringBuffer=await webcrypto5.subtle.decrypt({name:"AES-GCM",iv},key3,encryptedDataArrayBuffer),plainStringified=readString(new Uint8Array(plainStringBuffer)),plain=JSON.parse(plainStringified);return plain}catch(ex){Logger("Couldn't decode! You should wrong the passphrases",LOG_LEVEL_VERBOSE);Logger(ex,LOG_LEVEL_VERBOSE);throw ex}}async function testCryptV3(){const src="✨supercalifragilisticexpialidocious✨⛰️",encoded=await encryptV3(src,"passwordTest"),decrypted=await decrypt3(encoded,"passwordTest",!1);if(src!=decrypted){Logger("WARNING! Your device would not support encryption V3.",LOG_LEVEL_VERBOSE);return!1}Logger("CRYPT LOGIC (V3) OK",LOG_LEVEL_VERBOSE);return!0}async function testCrypt(){const src="✨supercalifragilisticexpialidocious✨⛰️",encoded=await encrypt3(src,"passwordTest",!1),decrypted=await decrypt3(encoded,"passwordTest",!1);if(src!=decrypted){Logger("WARNING! Your device would not support encryption.",LOG_LEVEL_VERBOSE);return!1}{Logger("CRYPT LOGIC OK",LOG_LEVEL_VERBOSE);const w2=writeString(src),encodedBinary=await encryptBinary2(w2,"passwordTest",!1),decryptedBinary=await decryptBinary2(encodedBinary,"passwordTest",!1);if(w2.join("-")!==decryptedBinary.join("-")){Logger("WARNING! Your device would not support encryption (Binary).",LOG_LEVEL_VERBOSE);return!1}Logger("CRYPT LOGIC OK (Binary)",LOG_LEVEL_VERBOSE);return await testCryptV3()&&await testEncryptionFeature()}}async function encryptBinary2(input,passphrase,autoCalculateIterations){const[key3,salt]=await getKeyForEncrypt(passphrase,autoCalculateIterations),fixedPart=getSemiStaticField(),invocationPart=getNonce(),iv=new Uint8Array([...fixedPart,...new Uint8Array(invocationPart.buffer)]),dataBuf=input,encryptedDataArrayBuffer=new Uint8Array(await webcrypto5.subtle.encrypt({name:"AES-GCM",iv},key3,dataBuf)),ret=new Uint8Array(encryptedDataArrayBuffer.byteLength+iv.byteLength+salt.byteLength);ret.set(iv,0);ret.set(salt,iv.byteLength);ret.set(encryptedDataArrayBuffer,iv.byteLength+salt.byteLength);return ret}async function decryptBinary2(encryptedResult,passphrase,autoCalculateIterations){try{const iv=encryptedResult.slice(0,16),salt=encryptedResult.slice(16,32),encryptedData=encryptedResult.slice(32),[key3]=await getKeyForDecryption(passphrase,salt,autoCalculateIterations),dataBuffer=await webcrypto5.subtle.decrypt({name:"AES-GCM",iv},key3,encryptedData);return new Uint8Array(dataBuffer)}catch(ex){Logger("Couldn't decode! You should wrong the passphrases (V2 Bin)",LOG_LEVEL_VERBOSE);Logger(ex,LOG_LEVEL_VERBOSE);throw ex}}function createWorker(){const blob=new Blob([workerSource],{type:"text/javascript"}),url=URL.createObjectURL(blob),worker=new Worker(url);URL.revokeObjectURL(url);return worker}function encryptionOnWorker(data){const process2=startWorker(data);return(async()=>{const ret=await process2.task.promise;process2.finalize();return ret})()}function encryptionHKDFOnWorker(data){const process2=startWorker(data);return(async()=>{const ret=await process2.task.promise;process2.finalize();return ret})()}function handleTaskEncrypt(process2,data){const key22=data.key,task=process2.task;"result"in data?task.resolve(data.result):data.error?task.reject(data.error):task.reject(new Error("Unknown error in background encryption"));removeTask(key22)}function _splitPieces2Worker(dataSrc,pieceSize,plainSplit,minimumChunkSize,filename,splitVersion,useSegmenter){const process2=startWorker({type:"split",dataSrc,pieceSize,plainSplit,minimumChunkSize,filename,useSegmenter,splitVersion}),_key=process2.key,stream=new TransformStream({transform:(chunk,controller)=>{null!==chunk?controller.enqueue(chunk):controller.terminate()},flush:()=>{}});workerStreams.set(_key,stream);const readable2=stream.readable,reader=readable2.getReader(),writer=stream.writable.getWriter();writers.set(_key,writer);return async function*(){try{let done=!1;do{const results=await reader.read();done=results.done;if(done)break;yield results.value}while(!done)}catch(ex){(0,logger_exports2.Logger)(`Error in worker stream for key ${_key}`);(0,logger_exports2.Logger)(ex,logger_exports2.LOG_LEVEL_VERBOSE);throw ex}finally{process2.finalize();workerStreams.delete(_key);writers.delete(_key)}}}function abortSplitTasks(keys3,error){for(const key22 of keys3){responseBuf.delete(key22);writerPromise=writerPromise.then(async()=>{const writer=writers.get(key22);if(writer){await writer.abort(error);writers.delete(key22)}workerStreams.delete(key22)})}}function handleTaskSplit(process2,data){const key22=data.key;if(!("result"in data)){responseBuf.delete(key22);const reportError=data.error||new Error("Unknown error in background splitting");writerPromise=writerPromise.then(async()=>{const writer=writers.get(key22);writer&&await writer.abort(reportError)});return}let thisBuf=responseBuf.get(key22);if(!thisBuf){thisBuf=new Map;responseBuf.set(key22,thisBuf)}const seq=data.seq;thisBuf.set(seq,null===data.result?SYMBOL_END_OF_DATA:data.result);responseBuf.set(key22,thisBuf);const keys3=Array.from(thisBuf.keys()).sort((a2,b3)=>a2-b3),max3=keys3[keys3.length-1];for(let i3=0;i3<=max3;i3++){const result=thisBuf.get(i3);if(void 0===result)break;if(result!==SYMBOL_USED){thisBuf.set(i3,SYMBOL_USED);responseBuf.set(key22,thisBuf);writerPromise=writerPromise.then(async()=>{const writer=writers.get(key22);if(!writer)throw new Error(`Invalid writer for key ${key22} in background splitting`);await writer.write(result===SYMBOL_END_OF_DATA?null:result);if(result===SYMBOL_END_OF_DATA){removeTask(key22);responseBuf.delete(key22)}})}}}function splitPieces2Worker(dataSrc,pieceSize,plainSplit,minimumChunkSize,filename,useSegmenter){return _splitPieces2Worker(dataSrc,pieceSize,plainSplit,minimumChunkSize,filename,1,null!=useSegmenter&&useSegmenter)}function splitPieces2WorkerV2(dataSrc,pieceSize,plainSplit,minimumChunkSize,filename,useSegmenter){return _splitPieces2Worker(dataSrc,pieceSize,plainSplit,minimumChunkSize,filename,2,null!=useSegmenter&&useSegmenter)}function splitPieces2WorkerRabinKarp(dataSrc,pieceSize,plainSplit,minimumChunkSize,filename,useSegmenter){return _splitPieces2Worker(dataSrc,pieceSize,plainSplit,minimumChunkSize,filename,3,null!=useSegmenter&&useSegmenter)}function encryptHKDFWorker(input,passphrase,pbkdf2Salt){return encryptionHKDFOnWorker({type:"encryptHKDF",input,passphrase,pbkdf2Salt})}function removeTask(key22){tasks2.delete(key22);const inst=taskWorkerMap.get(key22);if(inst){inst.taskKeys.delete(key22);taskWorkerMap.delete(key22)}}function initialiseWorkers(){const maxConcurrency=~~((compatGlobal2.navigator.hardwareConcurrency||8)/2);return Array.from({length:maxConcurrency},()=>({worker:createWorker(),processing:0,taskKeys:new Set}))}function initialiseWorkerModule(events){workers.length>0&&terminateWorker();workers=initialiseWorkers();for(const inst of workers){inst.worker.onmessage=({data})=>{const key22=data.key,process2=tasks2.get(key22);process2?"split"===process2.type?handleTaskSplit(0,data):"encrypt"===process2.type||"decrypt"===process2.type||"encryptHKDF"===process2.type||"decryptHKDF"===process2.type?handleTaskEncrypt(process2,data):info("Invalid response type"+("string"==typeof process2.type?process2.type:JSON.stringify(process2))):info(`Invalid key ${key22} of background processing`,LOG_KIND_ERROR)};inst.worker.onerror=ev=>{var _a13;inst.worker.terminate();workers.splice(workers.indexOf(inst),1);const crashError=new Error(`Background worker crashed: ${null!=(_a13=null==ev?void 0:ev.message)?_a13:"unknown error"}`),splitKeys=[];for(const key22 of inst.taskKeys){const process2=tasks2.get(key22);if(process2){tasks2.delete(key22);"split"===process2.type?splitKeys.push(key22):"task"in process2&&process2.task.reject(crashError)}}inst.taskKeys.clear();splitKeys.length>0&&abortSplitTasks(splitKeys,crashError)}}offPlatformUnloaded=events.onEvent(EVENT_PLATFORM_UNLOADED2,()=>{terminateWorker()})}function nextWorker(){if(void 0===workers||0===workers.length)throw new Error("No available workers");const inst=workers[roundRobinIdx];roundRobinIdx=(roundRobinIdx+1)%workers.length;return inst}function startWorker(data){const _key=key2++,inst=nextWorker(),promise=promiseWithResolvers(),item={key:_key,task:promise,type:data.type,finalize:()=>{inst.processing--}};tasks2.set(_key,item);inst.taskKeys.add(_key);taskWorkerMap.set(_key,inst);inst.processing++;inst.worker.postMessage({data:{...data,key:_key}});return item}function terminateWorker(){for(const inst of workers)inst.worker.terminate();workers=[];null==offPlatformUnloaded||offPlatformUnloaded();offPlatformUnloaded=void 0}function getEncryptionVersion(data){return"e_"in data&&!0===data.e_?data.data.startsWith(Encrypt_HKDF_Header)?EncryptionVersions_HKDF:data.data.startsWith(Encrypt_OLD_Header)?EncryptionVersions_ENCRYPTED:EncryptionVersions_UNKNOWN:EncryptionVersions_UNENCRYPTED}async function tryDecryptV1AsFallback(encryptedData,passphrase,useDynamicIterationCount){try{return await decrypt4(encryptedData,passphrase,useDynamicIterationCount)}catch(ex){try{Logger("Failed to decrypt with V1 method. Fallback to disable useDynamicIterationCount.",LOG_LEVEL_VERBOSE);Logger(ex,LOG_LEVEL_VERBOSE);return await decrypt4(encryptedData,passphrase,!1)}catch(ex2){Logger("Completely failed to decrypt with V1 method.",LOG_LEVEL_VERBOSE);Logger(ex2,LOG_LEVEL_VERBOSE);return!1}}}function isEncryptedMeta(doc){return"path"in doc&&doc.path.startsWith(ENCRYPTED_META_PREFIX)}async function encryptMetaWithHKDF(doc,passphrase,pbkdf2Salt){if(isEncryptedMeta(doc))return doc.path;const props={path:getPath(doc),mtime:doc.mtime,ctime:doc.ctime,size:doc.size,children:isMetaEntry(doc)?doc.children:void 0},propStr=JSON.stringify(props),encryptedMeta=await encryptHKDFWorker(propStr,passphrase,pbkdf2Salt);return ENCRYPTED_META_PREFIX+encryptedMeta}async function decryptMetaWithHKDF(meta,passphrase,pbkdf2Salt){if(!meta.startsWith(ENCRYPTED_META_PREFIX))throw new Error("Meta is not encrypted with HKDF.");const encryptedMeta=meta.slice(ENCRYPTED_META_PREFIX.length),props=await decryptHKDF(encryptedMeta,passphrase,pbkdf2Salt),parsedProps=JSON.parse(props);return parsedProps}async function incomingEncryptHKDF(doc,passphrase,useDynamicIterationCount,getPBKDF2Salt){const saveDoc={...doc};if(isEncryptedChunkEntry(saveDoc)||isSyncInfoEntry(saveDoc))try{const encryptionVersion=getEncryptionVersion(saveDoc);if(encryptionVersion===EncryptionVersions_ENCRYPTED){const decrypted=await tryDecryptV1AsFallback(saveDoc.data,passphrase,useDynamicIterationCount);if(!1===decrypted){Logger(MESSAGE_FALLBACK_DECRYPT_FAILED,LOG_LEVEL_NOTICE);throw new Error(MESSAGE_FALLBACK_DECRYPT_FAILED)}const pbkdf2salt=await getPBKDF2Salt();saveDoc.data=await encryptHKDF(saveDoc.data,passphrase,pbkdf2salt);saveDoc.e_=!0}if(encryptionVersion===EncryptionVersions_HKDF);else if(encryptionVersion===EncryptionVersions_UNENCRYPTED){const pbkdf2salt=await getPBKDF2Salt();saveDoc.data=await encryptHKDF(saveDoc.data,passphrase,pbkdf2salt);saveDoc.e_=!0}}catch(ex){Logger(ENCRYPTION_HKDF_FAILED,LOG_LEVEL_NOTICE);Logger(ex);throw ex}if(shouldEncryptEdenHKDF(saveDoc)){const pbkdf2salt=await getPBKDF2Salt();try{saveDoc.eden={[EDEN_ENCRYPTED_KEY_HKDF]:{data:await encryptHKDF(JSON.stringify(saveDoc.eden),passphrase,pbkdf2salt),epoch:999999}}}catch(ex){Logger(`${ENCRYPTION_HKDF_FAILED} on Eden`,LOG_LEVEL_NOTICE);Logger(ex);throw ex}}if(isObfuscatedEntry(saveDoc)){const pbkdf2salt=await getPBKDF2Salt();if(!isEncryptedMeta(saveDoc))try{saveDoc.path=await encryptMetaWithHKDF(saveDoc,passphrase,pbkdf2salt);saveDoc.mtime=0;saveDoc.ctime=0;saveDoc.size=0;"children"in saveDoc&&(saveDoc.children=[])}catch(ex){Logger(`${ENCRYPTION_HKDF_FAILED} on Metadata`,LOG_LEVEL_NOTICE);Logger(ex);throw ex}}return saveDoc}async function outgoingDecryptHKDF(doc,migrationDecrypt,decrypted,passphrase,useDynamicIterationCount,getPBKDF2Salt){const loadDoc={...doc};if(isEncryptedChunkEntry(loadDoc)||isSyncInfoEntry(loadDoc))try{const encryptionVersion=getEncryptionVersion(loadDoc);if(encryptionVersion===EncryptionVersions_HKDF){const pbkdf2salt=await getPBKDF2Salt();loadDoc.data=await decryptHKDF(loadDoc.data,passphrase,pbkdf2salt);delete loadDoc.e_}else if(encryptionVersion===EncryptionVersions_ENCRYPTED){const decryptedData=await tryDecryptV1AsFallback(loadDoc.data,passphrase,useDynamicIterationCount);if(!1===decryptedData){Logger(MESSAGE_FALLBACK_DECRYPT_FAILED,LOG_LEVEL_NOTICE);throw new Error(MESSAGE_FALLBACK_DECRYPT_FAILED)}loadDoc.data=decryptedData;delete loadDoc.e_}else if(encryptionVersion!==EncryptionVersions_UNENCRYPTED){Logger("Unknown encryption version. Cannot decrypt.",LOG_LEVEL_NOTICE);throw new Error("Unknown encryption version. Cannot decrypt.")}}catch(ex){Logger(DECRYPTION_HKDF_FAILED,LOG_LEVEL_NOTICE);Logger(ex);throw ex}if(isObfuscatedEntry(loadDoc)){const path2=getPath(loadDoc);if(isEncryptedMeta(loadDoc)){const pbkdf2salt=await getPBKDF2Salt();try{const metadata=await decryptMetaWithHKDF(path2,passphrase,pbkdf2salt);for(const key3 of Object.keys(metadata))loadDoc[key3]=metadata[key3]}catch(ex){Logger(`${DECRYPTION_HKDF_FAILED} on Path`,LOG_LEVEL_NOTICE);Logger(ex);throw ex}}else if(isPathProbablyObfuscated(path2)){const decryptedPath=await tryDecryptV1AsFallback(path2,passphrase,useDynamicIterationCount);if(!1===decryptedPath){Logger(`${MESSAGE_FALLBACK_DECRYPT_FAILED} on Path`,LOG_LEVEL_NOTICE);throw new Error(MESSAGE_FALLBACK_DECRYPT_FAILED)}loadDoc.path=decryptedPath}}let readEden={},edenDecrypted=!1;if(shouldDecryptEden(loadDoc))try{const decryptedEden=await tryDecryptV1AsFallback(loadDoc.eden[EDEN_ENCRYPTED_KEY].data,passphrase,useDynamicIterationCount);if(!1===decryptedEden)throw new Error(MESSAGE_FALLBACK_DECRYPT_FAILED);readEden={...readEden,...JSON.parse(decryptedEden)};edenDecrypted=!0}catch(ex){Logger(`${DECRYPTION_FALLBACK_FAILED} on Eden`,LOG_LEVEL_NOTICE);Logger(ex);throw ex}if(shouldDecryptEdenHKDF(loadDoc)){const pbkdf2salt=await getPBKDF2Salt();try{const decryptedEdenData=await decryptHKDF(loadDoc.eden[EDEN_ENCRYPTED_KEY_HKDF].data,passphrase,pbkdf2salt);readEden={...readEden,...JSON.parse(decryptedEdenData)};edenDecrypted=!0}catch(ex){Logger(`${DECRYPTION_HKDF_FAILED} on Eden`,LOG_LEVEL_NOTICE);Logger(ex);throw ex}}edenDecrypted&&(loadDoc.eden=readEden);return loadDoc}async function incomingEncryptV1(doc,passphrase,useDynamicIterationCount){const saveDoc={...doc};if(isEncryptedChunkEntry(saveDoc)||isSyncInfoEntry(saveDoc))try{if(!("e_"in saveDoc)){saveDoc.data=await encrypt4(saveDoc.data,passphrase,useDynamicIterationCount);saveDoc.e_=!0}}catch(ex){Logger("Encryption failed.",LOG_LEVEL_NOTICE);Logger(ex);throw ex}shouldEncryptEden(saveDoc)&&(saveDoc.eden={[EDEN_ENCRYPTED_KEY]:{data:await encrypt4(JSON.stringify(saveDoc.eden),passphrase,useDynamicIterationCount),epoch:999999}});if(isObfuscatedEntry(saveDoc))try{const path2=getPath(saveDoc);isPathProbablyObfuscated(path2)||(saveDoc.path=await obfuscatePath(path2,passphrase,useDynamicIterationCount))}catch(ex){Logger("Encryption failed.",LOG_LEVEL_NOTICE);Logger(ex);throw ex}return saveDoc}async function outgoingDecryptV1(doc,migrationDecrypt,decrypted,passphrase,useDynamicIterationCount){var _a13,_b6;const loadDoc={...doc},_isChunkOrSyncInfo=isEncryptedChunkEntry(loadDoc)||isSyncInfoEntry(loadDoc),_isObfuscatedEntry=isObfuscatedEntry(loadDoc),_shouldDecryptEden=shouldDecryptEden(loadDoc);if(_isChunkOrSyncInfo||_isObfuscatedEntry||_shouldDecryptEden){if(migrationDecrypt&&decrypted.has(loadDoc._id))return loadDoc;try{if(_isChunkOrSyncInfo){loadDoc.data=await decrypt4(loadDoc.data,passphrase,useDynamicIterationCount);delete loadDoc.e_}else if("e_"in loadDoc){loadDoc.data=await decrypt4(loadDoc.data,passphrase,useDynamicIterationCount);delete loadDoc.e_}if(_isObfuscatedEntry){const path2=getPath(loadDoc);isPathProbablyObfuscated(path2)&&(loadDoc.path=await decrypt4(path2,passphrase,useDynamicIterationCount))}_shouldDecryptEden&&(loadDoc.eden=JSON.parse(await decrypt4(loadDoc.eden[EDEN_ENCRYPTED_KEY].data,passphrase,useDynamicIterationCount)));migrationDecrypt&&decrypted.set(loadDoc._id,!0)}catch(ex){if(!useDynamicIterationCount){Logger("Decryption failed.",LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_VERBOSE);Logger(`id:${loadDoc._id}-${null==(_b6=loadDoc._rev)?void 0:_b6.substring(0,10)}`,LOG_LEVEL_VERBOSE);throw ex}try{_isChunkOrSyncInfo&&(loadDoc.data=await decrypt4(loadDoc.data,passphrase,!1));if(_isObfuscatedEntry){const path2=getPath(loadDoc);isPathProbablyObfuscated(path2)&&(loadDoc.path=await decrypt4(path2,passphrase,!1))}_shouldDecryptEden&&(loadDoc.eden=JSON.parse(await decrypt4(loadDoc.eden[EDEN_ENCRYPTED_KEY].data,passphrase,!1)));migrationDecrypt&&decrypted.set(loadDoc._id,!0)}catch(ex2){if(migrationDecrypt&&ex2 instanceof SyntaxError)return loadDoc;Logger("Decryption failed.",LOG_LEVEL_NOTICE);Logger(ex2,LOG_LEVEL_VERBOSE);Logger(`id:${loadDoc._id}-${null==(_a13=loadDoc._rev)?void 0:_a13.substring(0,10)}`,LOG_LEVEL_VERBOSE);throw ex2}}}return loadDoc}function getConfiguredFunctionsForEncryption(passphrase,useDynamicIterationCount,migrationDecrypt,getPBKDF2Salt,algorithm){const decryptedCache=new Map;return{incoming:doc=>algorithm===E2EEAlgorithms.V2?incomingEncryptHKDF(doc,passphrase,useDynamicIterationCount,getPBKDF2Salt):incomingEncryptV1(doc,passphrase,useDynamicIterationCount),outgoing:doc=>algorithm!==E2EEAlgorithms.ForceV1?outgoingDecryptHKDF(doc,0,0,passphrase,useDynamicIterationCount,getPBKDF2Salt):outgoingDecryptV1(doc,migrationDecrypt,decryptedCache,passphrase,useDynamicIterationCount)}}function disableEncryption(){preprocessOutgoing=async doc=>await Promise.resolve(doc);0}function shouldEncryptEden(doc){return"eden"in doc&&!(EDEN_ENCRYPTED_KEY in doc.eden)}function shouldEncryptEdenHKDF(doc){return"eden"in doc&&!(EDEN_ENCRYPTED_KEY_HKDF in doc.eden)&&0!==Object.keys(doc.eden).length}function shouldDecryptEden(doc){return"eden"in doc&&EDEN_ENCRYPTED_KEY in doc.eden}function shouldDecryptEdenHKDF(doc){return"eden"in doc&&EDEN_ENCRYPTED_KEY_HKDF in doc.eden}async function ensureRemoteIsCompatible(infoSrc,setting,deviceNodeID,currentVersionRange3,nodeDeviceInfo,updateCallback){var _a13,_b6,_c3,_d2;const now3=Date.now(),baseMilestone={_id:MILESTONE_DOCID,type:"milestoneinfo",created:now3,locked:!1,accepted_nodes:[deviceNodeID],node_chunk_info:{[deviceNodeID]:currentVersionRange3},node_info:{[deviceNodeID]:{...nodeDeviceInfo,last_connected:0,progress:""}},tweak_values:{}};let remoteMilestone=infoSrc;remoteMilestone||(remoteMilestone=baseMilestone);const currentTweakValues=extractObject(TweakValuesTemplate,setting);remoteMilestone.node_chunk_info={...baseMilestone.node_chunk_info,...remoteMilestone.node_chunk_info};let writeMilestone=remoteMilestone.node_chunk_info[deviceNodeID].min!=currentVersionRange3.min||remoteMilestone.node_chunk_info[deviceNodeID].max!=currentVersionRange3.max||isObjectDifferent(null==(_a13=remoteMilestone.tweak_values)?void 0:_a13[deviceNodeID],currentTweakValues)||void 0===remoteMilestone._rev||!(DEVICE_ID_PREFERRED in remoteMilestone.tweak_values);remoteMilestone.node_info||(remoteMilestone.node_info={});if(!(deviceNodeID in remoteMilestone.node_info)){remoteMilestone.node_info[deviceNodeID]={...nodeDeviceInfo,last_connected:0,progress:""};writeMilestone=!0}const info3=remoteMilestone.node_info[deviceNodeID],keys3=["device_name","app_version","plugin_version","vault_name","progress"];for(const key3 of keys3)if(info3[key3]!=nodeDeviceInfo[key3]){remoteMilestone.node_info[deviceNodeID][key3]=nodeDeviceInfo[key3];writeMilestone=!0}const diffLastConnected=now3-(remoteMilestone.node_info[deviceNodeID].last_connected||0);if(diffLastConnected>6e4){remoteMilestone.node_info[deviceNodeID].last_connected=now3;writeMilestone=!0}if(writeMilestone){remoteMilestone.node_chunk_info[deviceNodeID].min=currentVersionRange3.min;remoteMilestone.node_chunk_info[deviceNodeID].max=currentVersionRange3.max;remoteMilestone.tweak_values={...null!=(_b6=remoteMilestone.tweak_values)?_b6:{},[deviceNodeID]:currentTweakValues};DEVICE_ID_PREFERRED in remoteMilestone.tweak_values||(remoteMilestone.tweak_values[DEVICE_ID_PREFERRED]=currentTweakValues);await updateCallback(remoteMilestone)}let globalMin=currentVersionRange3.min,globalMax=currentVersionRange3.max;for(const nodeId of remoteMilestone.accepted_nodes)if(nodeId!=deviceNodeID)if(nodeId in remoteMilestone.node_chunk_info){const nodeInfo=remoteMilestone.node_chunk_info[nodeId];globalMin=Math.max(nodeInfo.min,globalMin);globalMax=Math.min(nodeInfo.max,globalMax)}else{globalMin=0;globalMax=0}if(globalMax<globalMin&&!setting.ignoreVersionCheck)return"INCOMPATIBLE";if(!setting.disableCheckingConfigMismatch){const preferred_tweak=null!=(_d2=null==(_c3=remoteMilestone.tweak_values)?void 0:_c3[DEVICE_ID_PREFERRED])?_d2:currentTweakValues,current_tweak=currentTweakValues,preferred_should_matched=extractObject(TweakValuesShouldMatchedTemplate,{...TweakValuesDefault,...preferred_tweak}),current_should_matched=extractObject(TweakValuesShouldMatchedTemplate,{...TweakValuesDefault,...current_tweak});if(isObjectDifferent(preferred_should_matched,current_should_matched,!0))return["MISMATCHED",preferred_tweak]}return remoteMilestone.locked?-1==remoteMilestone.accepted_nodes.indexOf(deviceNodeID)?remoteMilestone.cleaned?"NODE_CLEANED":"NODE_LOCKED":"LOCKED":"OK"}async function ensureDatabaseIsCompatible(db,setting,deviceNodeID,currentVersionRange3,nodeDeviceInfo){const remoteMilestone=await resolveWithIgnoreKnownError(db.get(MILESTONE_DOCID),!1),ret=await ensureRemoteIsCompatible(remoteMilestone,setting,deviceNodeID,currentVersionRange3,nodeDeviceInfo,async info3=>{await db.put(info3)});return ret}function generateId(prefix){idx++;if(idx>1e4){series=`${Date.now()}`;idx=0}const paddedIdx=idx+1e7;return`${PREFIX_TRENCH}-${prefix}-${series}-${paddedIdx}`}function createRange(prefix,series2){return[`${PREFIX_TRENCH}-${prefix}-${series2}-`,`${PREFIX_TRENCH}-${prefix}-${series2}.`]}function createId(prefix,series2,idx2){const paddedIdx=idx2+1e7;return`${PREFIX_TRENCH}-${prefix}-${series2}-${paddedIdx}`}function createSyncParamsHanderForServer(key3,options){if(_handlers.has(key3))return _handlers.get(key3);const handler=createSyncParamsHandler(options);_handlers.set(key3,handler);return handler}function clearHandlers(){_handlers.clear()}function createSyncParamsHandler({put,get:get5,create}){let taskFetchParameters;const _fetchSyncParameters=async()=>{let syncParams;try{let shouldRetry=!1;do{shouldRetry=!1;try{syncParams=await get5();Logger("Fetched synchronisation parameters",LOG_LEVEL_INFO)}catch(ex){if(!LiveSyncError.isCausedBy(ex,SyncParamsNotFoundError))throw ex;{Logger("Synchronisation parameters not found, creating new ones",LOG_LEVEL_INFO);const newSyncParams=await create(),putResult=await put(newSyncParams);if(!putResult){Logger("Failed to store initial synchronisation parameters",LOG_LEVEL_INFO);throw new SyncParamsUpdateError("Failed to store initial synchronisation parameters")}Logger("Initial synchronisation parameters stored successfully, retrying fetch",LOG_LEVEL_INFO);shouldRetry=!0}}}while(shouldRetry);if(!syncParams)throw new SyncParamsFetchError("Unexpected empty synchronisation parameters");if(!syncParams.pbkdf2salt){Logger("Synchronisation parameters do not have PBKDF2 salt, generating a new salt",LOG_LEVEL_INFO);const salt=await arrayBufferToBase64Single2(createPBKDF2Salt());if(!salt){Logger("Failed to generate PBKDF2 salt",LOG_LEVEL_INFO);throw new SyncParamsFetchError("Failed to generate PBKDF2 salt")}syncParams.pbkdf2salt=salt;const putResult=await put(syncParams);if(!putResult){Logger("Failed to store synchronisation parameters with new PBKDF2 salt",LOG_LEVEL_INFO);throw new SyncParamsUpdateError("Failed to store synchronisation parameters with new PBKDF2 salt")}syncParams=await get5()}if(!syncParams)throw new Error("Failed to prepare synchronisation key in synchronisation parameters");Logger("Synchronisation parameters fetched successfully",LOG_LEVEL_INFO);if(!syncParams.pbkdf2saltDecoded){const decodedSalt=new Uint8Array(base64ToArrayBufferInternalBrowser(syncParams.pbkdf2salt));if(!decodedSalt)throw new SyncParamsFetchError("Failed to decode PBKDF2 salt");syncParams.pbkdf2saltDecoded=decodedSalt}return syncParams}catch(ex){Logger("Failed to fetch synchronisation parameters",LOG_LEVEL_INFO);Logger(ex,LOG_LEVEL_VERBOSE);taskFetchParameters=void 0;return!1}},fetchSyncParameters=(refresh=!1)=>{if(taskFetchParameters&&!refresh)return taskFetchParameters;taskFetchParameters=_fetchSyncParameters();return taskFetchParameters};return{fetch:fetchSyncParameters,getPBKDF2Salt:async(refresh=!1)=>{const syncParams=await fetchSyncParameters(refresh);if(!syncParams){Logger("Failed to fetch synchronisation parameters",LOG_LEVEL_INFO);throw new SyncParamsFetchError("Failed to fetch synchronisation parameters")}return syncParams.pbkdf2saltDecoded}}}async function*genReplication(s2,signal){const inbox=new StreamInbox({capacity:1e4}),push2=function(e3){if(!signal.aborted&&!inbox.isClosed&&!inbox.post(e3)){Logger(`Replication event queue is full: ${e3[0]}`,LOG_LEVEL_VERBOSE);"error"===e3[0]||"denied"===e3[0]?inbox.error(e3[1]):"complete"!==e3[0]&&"finally"!==e3[0]||inbox.close()}};s2.on("complete",result=>push2(["complete",result]));s2.on("change",result=>push2(["change",result]));s2.on("active",()=>push2(["active"]));s2.on("denied",err3=>push2(["denied",err3]));s2.on("error",err3=>push2(["error",err3]));s2.on("paused",err3=>push2(["paused",err3]));s2.then(()=>push2(["finally"])).catch(()=>push2(["finally"]));const onAbort=()=>inbox.close();signal.addEventListener("abort",onAbort,{once:!0});try{const reader=inbox.readable.getReader();for(;!signal.aborted;){const{done,value}=await reader.read();if(done)break;yield value}}catch(ex){if(!(ex instanceof Error&&"AbortError"==ex.name))throw ex;Logger("Replication aborted",LOG_LEVEL_VERBOSE)}finally{signal.removeEventListener("abort",onAbort);s2.cancel();inbox.close()}}function translateInfo(infoSrc,translate=englishMessageTranslator){if(!infoSrc)return!1;const info3={...infoSrc};info3.name=translate(info3.name);info3.desc&&(info3.desc=translate(info3.desc));return info3}function _getConfig(key3){return key3 in configurationNames?configurationNames[key3]:key3 in SettingInformation&&SettingInformation[key3]}function getConfig(key3,translate){return translateInfo(_getConfig(key3),translate)}function getConfName(key3,translate){const conf=getConfig(key3,translate);return conf?conf.name:`${key3} (No info)`}function getConfig2(key3,translate=translateLiveSyncMessage){return getConfig(key3,translate)}function getConfName2(key3,translate=translateLiveSyncMessage){return getConfName(key3,translate)}function setStyle(el,styleHead,condition){if(condition()){el.addClass(`${styleHead}-enabled`);el.removeClass(`${styleHead}-disabled`)}else{el.addClass(`${styleHead}-disabled`);el.removeClass(`${styleHead}-enabled`)}}function visibleOnly(cond){return()=>({visibility:cond()})}function enableOnly(cond){return()=>({disabled:!cond()})}function wrapMemo(func){let buf;return arg=>{if(buf!==arg){func(arg);buf=arg}}}function setButtonDestructiveState(button,isDestructive=!0){const compatibleButton=button,updateNativeStyle=isDestructive?compatibleButton.setDestructive:compatibleButton.removeDestructive;"function"==typeof updateNativeStyle?updateNativeStyle.call(button):button.buttonEl.classList.toggle("mod-warning",isDestructive);return button}function setSettingAdditionalActionsState(setting,hasAdditionalActions=!0){setting.settingEl.classList.toggle(SETTING_WITH_ADDITIONAL_ACTIONS_CLASS,hasAdditionalActions);return setting}function setButtonAdditionalActionState(button,isAdditionalAction=!0){button.buttonEl.classList.toggle(ADDITIONAL_ACTION_CLASS,isAdditionalAction);return button}function StrmOpt(opts,cb2){"function"==typeof opts&&(cb2=opts,opts={});this.ondata=cb2;return opts}function deflate(data,opts,cb2){cb2||(cb2=opts,opts={});"function"!=typeof cb2&&err2(7);return cbify(data,opts,[bDflt],function(ev){return pbf(deflateSync(ev.data[0],ev.data[1]))},0,cb2)}function deflateSync(data,opts){return dopt(data,opts||{},0,0)}function inflate(data,opts,cb2){cb2||(cb2=opts,opts={});"function"!=typeof cb2&&err2(7);return cbify(data,opts,[bInflt],function(ev){return pbf(inflateSync(ev.data[0],gopt(ev.data[1])))},1,cb2)}function inflateSync(data,opts){return inflt(data,{i:2},opts&&opts.out,opts&&opts.dictionary)}function strToU8(str,latin1){var ar_1,i3,l2,ar2,ai2,w2,n3,c3;if(latin1){ar_1=new u8(str.length);for(i3=0;i3<str.length;++i3)ar_1[i3]=str.charCodeAt(i3);return ar_1}if(te3)return te3.encode(str);l2=str.length;ar2=new u8(str.length+(str.length>>1));ai2=0;w2=function(v2){ar2[ai2++]=v2};for(i3=0;i3<l2;++i3){if(ai2+5>ar2.length){n3=new u8(ai2+8+(l2-i3<<1));n3.set(ar2);ar2=n3}c3=str.charCodeAt(i3);c3<128||latin1?w2(c3):c3<2048?(w2(192|c3>>6),w2(128|63&c3)):c3>55295&&c3<57344?(c3=65536+(1047552&c3)|1023&str.charCodeAt(++i3),w2(240|c3>>18),w2(128|c3>>12&63),w2(128|c3>>6&63),w2(128|63&c3)):(w2(224|c3>>12),w2(128|c3>>6&63),w2(128|63&c3))}return slc(ar2,0,ai2)}function strFromU8(dat,latin1){var r4,i3,_a13,s2;if(latin1){r4="";for(i3=0;i3<dat.length;i3+=16384)r4+=String.fromCharCode.apply(null,dat.subarray(i3,i3+16384));return r4}if(td2)return td2.decode(dat);_a13=dutf8(dat),s2=_a13.s,r4=_a13.r;r4.length&&err2(8);return s2}async function _compressText(text2){const converted=tryConvertBase64ToArrayBuffer(text2),data=new Uint8Array(converted||await new Blob([text2],{type:"application/octet-stream"}).arrayBuffer());if(0==data.buffer.byteLength)return"";const df=await wrappedDeflate(new Uint8Array(data),{consume:!0,level:8}),deflateResult=(converted?"~":"")+await arrayBufferToBase64Single2(df);return deflateResult}async function _decompressText(compressed,_useUTF16=!1){if(0==compressed.length)return"";const converted="~"==compressed[0],src=compressed.substring(converted?1:0);if(0==src.length)return"";const ab2=new Uint8Array(base64ToArrayBuffer(src));if(0==ab2.length)return"";const ret=await wrappedInflate(new Uint8Array(ab2),{consume:!0});if(converted)return await arrayBufferToBase64Single2(ret);const response=new Blob([ret]),text2=await response.text();return text2}async function compressDoc(doc){if(!("data"in doc))return doc;if("string"!=typeof doc.data)return doc;if(doc.data.startsWith(MARK_SHIFT_COMPRESSED))return doc;const oldData=doc.data,compressed=await _compressText(oldData),newData=MARK_SHIFT_COMPRESSED+compressed;doc.data.length>newData.length&&(doc.data=newData);return doc}async function decompressDoc(doc){if(!("data"in doc))return doc;if("string"!=typeof doc.data)return doc;doc.data.startsWith(MARK_SHIFT_COMPRESSED)&&(doc.data=await _decompressText(doc.data.substring(MARK_SHIFT_COMPRESSED.length)));return doc}function wrapFflateFunc(func){return(data,opts)=>new Promise((res2,rej)=>{func(data,opts,(err3,result)=>{err3?rej(err3):res2(new Uint8Array(result))})})}function isTextBlob2(blob){return"text/plain"===blob.type}function*pickPiece(leftData,minimumChunkSize){let buffer="";L1:do{const curLine=leftData.shift();if(void 0===curLine){yield buffer;break L1}if(curLine.startsWith("```")||curLine.startsWith(" ```")||curLine.startsWith(" ```")||curLine.startsWith(" ```")){yield buffer;buffer=curLine+(0!=leftData.length?"\n":"");L2:do{const curPx=leftData.shift();if(void 0===curPx)break L2;buffer+=curPx+(0!=leftData.length?"\n":"")}while(leftData.length>0&&!(leftData[0].startsWith("```")||leftData[0].startsWith(" ```")||leftData[0].startsWith(" ```")||leftData[0].startsWith(" ```")));const isLooksLikeBASE64=buffer.endsWith("="),maybeUneditable=buffer.length>2048,endOfCodeBlock=leftData.shift();if(void 0!==endOfCodeBlock){buffer+=endOfCodeBlock;buffer+=0!=leftData.length?"\n":""}if(isLooksLikeBASE64||maybeUneditable)yield buffer;else{const splitExpr=/(.*?[;,:<])/g,sx=buffer.split(splitExpr).filter(e3=>""!=e3);for(const v2 of sx)yield v2}buffer=""}else{buffer+=curLine+(0!=leftData.length?"\n":"");if(buffer.length>=minimumChunkSize||0==leftData.length||"#"==leftData[0]||"#"==buffer[0]){yield buffer;buffer=""}}}while(leftData.length>0)}function*splitStringWithinLength(text2,pieceSize){let leftData=text2;do{const splitSize=pieceSize,piece=leftData.substring(0,splitSize);leftData=leftData.substring(splitSize);yield piece}while(""!=leftData)}function*splitTextInSegment(text2,pieceSize,minimumChunkSize){const segments=segmenter.segment(text2);let prev="",buf="";for(const seg of segments){const buffer=seg.segment;if(prev==buffer||buf.length<minimumChunkSize){buf+=buffer;prev=buffer}else{prev=buffer;buf.length>0&&(yield*splitStringWithinLength(buf,pieceSize));buf=buffer}}buf.length>0&&(yield*splitStringWithinLength(buf,pieceSize))}function*splitInNewLine(texts){for(const text2 of texts){let start=-1,end=-1;do{end=text2.indexOf("\n",start);if(-1==end){yield text2.substring(start);break}for(;"\n"==text2[end];)end++;yield text2.substring(start,end);start=end}while(-1!=end)}}function splitPiecesTextV2(dataSrc,pieceSize,minimumChunkSize){const dataListAllArray="string"==typeof dataSrc?[dataSrc]:dataSrc,dataListAll=splitInNewLine(dataListAllArray);let inCodeBlock=0,flush2=!1,flushBefore=!1;return function*(){const buf=[];for(const line of dataListAll){if(line.startsWith("````")){if(0==inCodeBlock){inCodeBlock=4;flushBefore=!0}else if(4==inCodeBlock){inCodeBlock=0;flush2=!0}}else if(line.startsWith("```"))if(0==inCodeBlock){inCodeBlock=3;flushBefore=!0}else if(3==inCodeBlock){inCodeBlock=0;flush2=!0}if(flushBefore){if(buf.length>0){yield*splitTextInSegment(buf.join(""),pieceSize,minimumChunkSize);buf.length=0}flushBefore=!1}buf.push(line);if(flush2){if(buf.length>0){yield*splitStringWithinLength(buf.join(""),pieceSize);buf.length=0}flush2=!1}}buf.length>0&&(0==inCodeBlock?yield*splitTextInSegment(buf.join(""),pieceSize,minimumChunkSize):yield*splitStringWithinLength(buf.join(""),pieceSize))}}function binaryTextSplit(data,pieceSize,minimumChunkSize){return function*pieces(){yield*splitStringWithinLength(data,pieceSize)}}function splitPiecesText(dataSrc,pieceSize,plainSplit,minimumChunkSize,useSegmenter){return useSegmenter&&segmenter?plainSplit?splitPiecesTextV2(dataSrc,pieceSize,minimumChunkSize):binaryTextSplit(dataSrc,pieceSize):splitPiecesTextV1(dataSrc,pieceSize,plainSplit,minimumChunkSize)}function splitPiecesTextV1(dataSrc,pieceSize,plainSplit,minimumChunkSize){const dataList="string"==typeof dataSrc?[dataSrc]:dataSrc;return function*pieces(){for(const data of dataList)if(plainSplit){const leftData=data.split("\n"),f4=pickPiece(leftData,minimumChunkSize);for(const piece of f4){let buffer=piece;do{let ps=pieceSize;buffer.charCodeAt(ps-1)!=buffer.codePointAt(ps-1)&&ps++;yield buffer.substring(0,ps);buffer=buffer.substring(ps)}while(""!=buffer)}}else{let leftData=data;do{const splitSize=pieceSize,piece=leftData.substring(0,splitSize);leftData=leftData.substring(splitSize);yield piece}while(""!=leftData)}}}function*splitByDelimiterWithMinLength(sources,delimiter,minimumChunkLength=25,splitThreshold){let buf="",last=!1;const dl=delimiter.length;for(const source2 of sources){const max3=source2.length;if(splitThreshold&&max3>splitThreshold){yield buf+source2;last=!1;buf="";continue}let i3=-1,prev=0;L1:do{i3=source2.indexOf(delimiter,prev);if(-1==i3)break L1;buf+=source2.slice(prev,i3)+delimiter;if(buf.length>minimumChunkLength){yield buf;buf="";last=!1}else last=!0;prev=i3+dl}while(i3<max3);if(prev!=i3||-1==prev&&-1==i3){buf+=source2.slice(prev);last=!0}}last&&(yield buf)}function*chunkStringGenerator(source2,maxLength){const strLen=source2.length;if(strLen>maxLength){let from=0;do{let end=from+maxLength;if(end>strLen){yield source2.substring(from);break}for(;source2.charCodeAt(end-1)!=source2.codePointAt(end-1);)end++;yield source2.substring(from,end);from=end}while(from<strLen)}else yield source2}function*chunkStringGeneratorFromGenerator(sources,maxLength){for(const source2 of sources)yield*chunkStringGenerator(source2,maxLength)}function*stringGenerator(sources){for(const str of sources)yield str}async function splitPieces2V2(dataSrc,pieceSize,plainSplit,minimumChunkSize,filename,useSegmenter){if(0==dataSrc.size)return function*noItems(){};if(isTextBlob2(dataSrc)){const text2=await dataSrc.text();if(!plainSplit){const gen2=chunkStringGenerator(text2,pieceSize);return function*pieces(){yield*gen2}}const textLen=text2.length;let xMinimumChunkSize=minimumChunkSize;for(;textLen/xMinimumChunkSize>MAX_ITEMS;)xMinimumChunkSize+=minimumChunkSize;const org=stringGenerator([text2]),gen1=splitByDelimiterWithMinLength(org,"\n",xMinimumChunkSize),gen=chunkStringGeneratorFromGenerator(gen1,pieceSize);return function*pieces(){yield*gen}}let canBeSmall=!1,delimiter=0;if(filename&&filename.endsWith(".pdf"))delimiter="/".charCodeAt(0);else if(filename&&filename.endsWith(".json")){canBeSmall=!0;delimiter=",".charCodeAt(0)}const clampMin=canBeSmall?100:1e5,clampedSize=Math.max(clampMin,Math.min(1e8,dataSrc.size));let step=1,w2=clampedSize;for(;w2>10;){w2/=12.5;step++}minimumChunkSize=Math.floor(10**(step-1));return async function*piecesBlob(){const size=dataSrc.size;let i3=0;const buf=new Uint8Array(await dataSrc.arrayBuffer());do{const findStart=i3+minimumChunkSize,defaultSplitEnd=i3+pieceSize;let splitEnd,i1=buf.indexOf(delimiter,findStart);-1==i1&&(i1=buf.indexOf(charNewLine,findStart));splitEnd=-1==i1?defaultSplitEnd:i1<defaultSplitEnd?i1:defaultSplitEnd;yield await arrayBufferToBase64Single2(buf.slice(i3,splitEnd));i3=splitEnd}while(i3<size)}}async function splitPieces2(dataSrc,pieceSize,plainSplit,minimumChunkSize,filename,useSegmenter){if(isTextBlob2(dataSrc))return splitPiecesText(await dataSrc.text(),pieceSize,plainSplit,minimumChunkSize,null!=useSegmenter&&useSegmenter);let delimiter=0,canBeSmall=!1;if(filename&&filename.endsWith(".pdf"))delimiter="/".charCodeAt(0);else if(filename&&filename.endsWith(".json")){canBeSmall=!0;delimiter=",".charCodeAt(0)}const clampMin=canBeSmall?100:1e5,clampedSize=Math.max(clampMin,Math.min(1e8,dataSrc.size));let step=1,w2=clampedSize;for(;w2>10;){w2/=12.5;step++}minimumChunkSize=Math.floor(10**(step-1));return async function*piecesBlob(){const size=dataSrc.size;let i3=0;do{let splitSize=pieceSize;const currentData=new Uint8Array(await dataSrc.slice(i3,i3+pieceSize).arrayBuffer());let nextIdx=currentData.indexOf(delimiter,minimumChunkSize);splitSize=-1==nextIdx?pieceSize:Math.min(pieceSize,nextIdx);-1==nextIdx&&(nextIdx=currentData.indexOf(charNewLine,minimumChunkSize));const piece=currentData.slice(0,splitSize);i3+=piece.length;const b64=await arrayBufferToBase64Single2(piece);yield b64}while(i3<size)}}async function splitPiecesRabinKarp(dataSrc,absoluteMaxPieceSize,doPlainSplit,minimumChunkSize,_filename,_useSegmenter){let plainSplit=doPlainSplit||isTextBlob2(dataSrc);const dataSize=dataSrc.size;let chunkUnitPlain=64;if(plainSplit){const isDataSizeTooLargeForPlainSplit=dataSize>=4194304;if(isDataSizeTooLargeForPlainSplit)plainSplit=!1;else{let estimatedChunkCount;do{estimatedChunkCount=dataSize/(4*chunkUnitPlain);estimatedChunkCount>500&&(chunkUnitPlain+=32)}while(estimatedChunkCount>500)}}const fixedAvgChunkSize=plainSplit?4*chunkUnitPlain:1048576,fixedMaxChunkSize=plainSplit?16*chunkUnitPlain:4194304,fixedMinChunkSize=plainSplit?2*chunkUnitPlain:262144,effectiveAbsoluteMaxPieceSize=Math.max(absoluteMaxPieceSize,30720),maxChunkSize=Math.min(fixedMaxChunkSize,effectiveAbsoluteMaxPieceSize),minChunkSize=Math.min(Math.max(fixedMinChunkSize,minimumChunkSize),maxChunkSize),avgChunkSize=Math.min(Math.max(fixedAvgChunkSize,minChunkSize),maxChunkSize),hashModulus=avgChunkSize;let P_pow_w=1;for(let i3=0;i3<47;i3++)P_pow_w=Math.imul(P_pow_w,31);const buffer=new Uint8Array(await dataSrc.arrayBuffer());let pos=0,hash3=0,start=0;const isText=isTextBlob2(dataSrc),length=buffer.length;return async function*piecesBlob(){for(;pos<length;){const byte=buffer[pos];if(pos>=start+48){const oldByte=buffer[pos-48],oldByteTerm=Math.imul(oldByte,P_pow_w);hash3=hash3-oldByteTerm|0;hash3=Math.imul(hash3,31);hash3=hash3+byte|0}else{hash3=Math.imul(hash3,31);hash3=hash3+byte|0}const currentChunkSize=pos-start+1;let isBoundaryCandidate=!1;currentChunkSize>=minChunkSize&&(hash3>>>0)%hashModulus==1&&(isBoundaryCandidate=!0);currentChunkSize>=maxChunkSize&&(isBoundaryCandidate=!0);if(isBoundaryCandidate){let isSafeBoundary=!0;isText&&pos+1<length&&128==(192&buffer[pos+1])&&(isSafeBoundary=!1);if(isSafeBoundary){isText?yield Promise.resolve(readString(buffer.subarray(start,pos+1))):yield await arrayBufferToBase64Single2(buffer.subarray(start,pos+1));start=pos+1}}pos++}start<length&&(isText?yield Promise.resolve(readString(buffer.subarray(start,length))):yield await arrayBufferToBase64Single2(buffer.subarray(start,length)))}}function revisionGeneration(revision){const generation=Number(revision.split("-",1)[0]);return Number.isFinite(generation)?generation:Number.MAX_SAFE_INTEGER}function compareConflictCandidates(left,right){const generationDifference=revisionGeneration(left.revision)-revisionGeneration(right.revision);if(0!==generationDifference)return generationDifference;const leftMtime=!1!==left.leaf&&Number.isFinite(left.leaf.mtime)?left.leaf.mtime:Number.NEGATIVE_INFINITY,rightMtime=!1!==right.leaf&&Number.isFinite(right.leaf.mtime)?right.leaf.mtime:Number.NEGATIVE_INFINITY,mtimeDifference=leftMtime-rightMtime;return 0!==mtimeDifference?mtimeDifference:left.revision<right.revision?-1:left.revision>right.revision?1:0}async function createChunks(managers,dispFilename,note){const{chunkManager,splitter}=managers;let bufferedChunk=[],bufferedSize=0,writeCount=0,newCount=0,cachedCount=0,resultCachedCount=0,duplicatedCount=0,totalWritingCount=0,createChunkCount=0;const chunks=[];let writeChars=0;const flushBufferedChunks=async()=>{if(0===bufferedChunk.length){Logger(`No chunks to flush for ${dispFilename}`,LOG_LEVEL_VERBOSE);return!0}const writeBuf=[...bufferedChunk];bufferedSize=0;bufferedChunk=[];const result=await chunkManager.write(writeBuf,{skipCache:!1,timeout:0},note._id);if(!1===result.result){Logger(`Failed to write buffered chunks for ${dispFilename}`,LOG_LEVEL_NOTICE);return!1}totalWritingCount++;writeCount+=result.processed.written;resultCachedCount+=result.processed.cached;duplicatedCount+=result.processed.duplicated;writeChars+=writeBuf.map(e3=>e3.data.length).reduce((a2,b3)=>a2+b3,0);Logger(`Flushed ${writeBuf.length} (${writeChars}) chunks for ${dispFilename}`,LOG_LEVEL_VERBOSE);return!0},flushIfNeeded=async()=>{if(bufferedSize>2048e3&&!await flushBufferedChunks()){Logger(`Failed to flush buffered chunks for ${dispFilename}`,LOG_LEVEL_NOTICE);return!1}return!0},addBuffer=async(id,data)=>{const chunk={_id:id,data,type:"leaf"};bufferedChunk.push(chunk);chunks.push(chunk._id);bufferedSize+=chunk.data.length;return await flushIfNeeded()},pieces=await splitter.splitContent(note);let totalChunkCount=0;try{for await(const piece of pieces){totalChunkCount++;if(0===piece.length)continue;createChunkCount++;const chunk=await prepareChunk(managers,piece);cachedCount+=chunk.isNew?0:1;newCount+=chunk.isNew?1:0;if(!await addBuffer(chunk.id,chunk.piece))return!1}}catch(ex){Logger(`Error processing pieces for ${dispFilename}`);Logger(ex,LOG_LEVEL_VERBOSE);return!1}if(!await flushBufferedChunks())return!1;const dataSize=note.data.size,stats=`(✨: ${newCount}, 🗃️: ${cachedCount} (${resultCachedCount}) / 🗄️: ${writeCount}, ♻:${duplicatedCount})`;Logger(`Chunks processed for ${dispFilename} (${dataSize}): 📚:${totalChunkCount} (${createChunkCount}) , 📥:${totalWritingCount} ${stats}`,LOG_LEVEL_VERBOSE);dataSize>0&&0===totalWritingCount&&Logger(`No data to save in ${dispFilename}!! This document may be corrupted in the local database! Please back it up immediately, and report an issue!`,LOG_LEVEL_NOTICE);return chunks}async function putDBEntry(host,managers,note,onlyChunks,conflictBaseRev){const revisionTarget=conflictBaseRev?{mode:"force-base",baseRevision:conflictBaseRev}:{mode:"latest"};return await putDBEntryInternal(host,managers,note,onlyChunks,revisionTarget)}async function putDBEntryWithLiveBaseRevision(host,managers,note,baseRevision,onlyChunks){try{return await putDBEntryInternal(host,managers,note,onlyChunks,{mode:"live-base",baseRevision})}catch(ex){if(ex&&"object"==typeof ex&&"status"in ex&&409===ex.status)return!1;throw ex}}async function putDBEntryInternal(host,managers,note,onlyChunks,revisionTarget){const{localDatabase,chunkManager,splitter}=managers,filename=host.services.path.id2path(note._id,note),dispFilename=stripAllPrefixes(filename);note.eden||(note.eden={});if(!isTargetFile(host,filename)){Logger(`File skipped:${dispFilename}`,LOG_LEVEL_VERBOSE);return!1}const data=note.data instanceof Blob?note.data:createTextBlob(note.data);note.data=data;note.type=isTextBlob(data)?"plain":"newnote";note.datatype=note.type;await splitter.initialised;const result=await chunkManager.transaction(async()=>{var _a13;const chunks=await createChunks(managers,dispFilename,note);if(!1===chunks)return!1;if(onlyChunks)return{id:note._id,ok:!0,rev:"dummy"};const newDoc={children:chunks,_id:note._id,path:note.path,ctime:note.ctime,mtime:note.mtime,size:note.size,type:note.datatype,eden:{}};return null!=(_a13=await serialized("file:"+filename,async()=>{if("latest"!==revisionTarget.mode)newDoc._rev=revisionTarget.baseRevision;else try{const old=await localDatabase.get(newDoc._id);newDoc._rev=old._rev}catch(ex){if(!isErrorOfMissingDoc(ex))throw ex}const r4="live-base"===revisionTarget.mode?await localDatabase.put(newDoc):await localDatabase.put(newDoc,{force:!0});return!!r4.ok&&r4}))&&_a13});if(!1===result){Logger(`Failed to write document ${dispFilename}`,LOG_LEVEL_NOTICE);return!1}Logger(`Document saved: ${dispFilename} (${result.id.substring(0,8)}-${result.rev})`,LOG_LEVEL_VERBOSE);return result}function isTargetFile(host,filenameSrc){const settings=host.services.setting.currentSettings(),file=filenameSrc.startsWith(ICHeader)?filenameSrc.substring(ICHeader.length):filenameSrc;if(file.startsWith(ICXHeader))return!0;if(file.startsWith(PSCHeader))return!0;if(file.includes(":"))return!1;if(!settings.syncInternalFiles&&file.startsWith("."))return!1;if(settings.syncOnlyRegEx){const syncOnly=getFileRegExp(settings,"syncOnlyRegEx");if(syncOnly.length>0&&!syncOnly.some(e3=>e3.test(file)))return!1}if(settings.syncIgnoreRegEx){const syncIgnore=getFileRegExp(settings,"syncIgnoreRegEx");if(syncIgnore.some(e3=>e3.test(file)))return!1}return!0}async function prepareChunk({chunkManager,hashManager},piece){const cachedChunkId=chunkManager.getChunkIDFromCache(piece);if(!1!==cachedChunkId)return{isNew:!1,id:cachedChunkId,piece};const chunkId=await hashManager.computeHash(piece);return{isNew:!0,id:`${IDPrefixes_Chunk}${chunkId}`,piece}}async function getDBEntryMetaByPath(host,{localDatabase},path2,opt,includeDeleted=!1){var _a13,_b6,_c3,_d2;if(!isTargetFile(host,path2))return!1;const id=await host.services.path.path2id(path2);try{let obj=null;obj=opt?await localDatabase.get(id,opt):await localDatabase.get(id);const deleted=null!=(_b6=null!=(_a13=null==obj?void 0:obj.deleted)?_a13:obj._deleted)?_b6:void 0;if(!includeDeleted&&deleted)return!1;if(obj.type&&"leaf"==obj.type)return!1;if(!obj.type||obj.type&&"notes"==obj.type||"newnote"==obj.type||"plain"==obj.type){const note=obj;let children=[],type="plain";if("newnote"==obj.type||"plain"==obj.type){children=obj.children;type=obj.type}const doc={data:"",_id:note._id,path:path2,ctime:note.ctime,mtime:note.mtime,size:note.size,_rev:obj._rev,_conflicts:obj._conflicts,children,datatype:type,deleted,_revisions:null!=(_c3=null==obj?void 0:obj._revisions)?_c3:void 0,_revs_info:null!=(_d2=null==obj?void 0:obj._revs_info)?_d2:void 0,type,eden:"eden"in obj?obj.eden:{}};return doc}}catch(ex){if(isErrorOfMissingDoc(ex))return!1;throw ex}return!1}function isLegacyNote(meta){return!meta.type||meta.type&&"notes"==meta.type}function complementEntryMeta(note){var _a13,_b6;const deleted=null!=(_b6=null!=(_a13=note.deleted)?_a13:note._deleted)?_b6:void 0,doc={data:note.data,path:note.path,_id:note._id,ctime:note.ctime,mtime:note.mtime,size:note.size,_rev:note._rev,_conflicts:note._conflicts,children:[],datatype:"newnote",deleted,type:"newnote",eden:"eden"in note?note.eden:{}};return doc}function respondOldFashionedEntry(note,dump=!1){const doc=complementEntryMeta(note);if(dump){Logger("--Old fashioned document--");Logger(doc)}return doc}function canUseOnDemandChunking(settings){return settings.remoteType===REMOTE_COUCHDB&&!settings.useOnlyLocalChunk}function canFetchRemotely(settings){return!!canUseOnDemandChunking(settings)&&settings.remoteType!==RemoteTypes_REMOTE_MINIO}function computeChunkRetrievalMethod(waitForReady,settings){const isOnDemandFetchEnabled=canFetchRemotely(settings);return waitForReady?{waitForDelivery:!0,preventRemoteRequest:!isOnDemandFetchEnabled}:isOnDemandFetchEnabled?{waitForDelivery:!0,preventRemoteRequest:!1}:{waitForDelivery:!1,preventRemoteRequest:!0}}async function respondEntryFromMeta({localDatabase,chunkManager},settings,filename,meta,dump,waitForReady){var _a13,_b6,_c3;const dispFilename=stripAllPrefixes(filename),deleted=null!=(_b6=null!=(_a13=meta.deleted)?_a13:meta._deleted)?_b6:void 0;if(dump){const conflicts=await localDatabase.get(meta._id,{rev:meta._rev,conflicts:!0,revs_info:!0});Logger("-- Conflicts --");Logger(null!=(_c3=conflicts._conflicts)?_c3:"No conflicts");Logger("-- Revs info -- ");Logger(conflicts._revs_info)}try{if(dump){Logger("--Bare document--");Logger(meta)}let edenChunks={};if(meta.eden&&Object.keys(meta.eden).length>0){const chunks2=Object.entries(meta.eden).map(([id,data])=>({_id:id,data:data.data,type:"leaf"}));edenChunks=Object.fromEntries(chunks2.map(e3=>[e3._id,e3]))}const{waitForDelivery,preventRemoteRequest}=computeChunkRetrievalMethod(waitForReady,settings),childrenKeys=[...meta.children],chunks=await chunkManager.read(childrenKeys,{skipCache:!1,waitForDelivery,preventRemoteRequest},edenChunks);if(chunks.some(e3=>!1===e3))throw new Error("Load failed");const doc={data:chunks.map(e3=>e3.data),path:meta.path,_id:meta._id,ctime:meta.ctime,mtime:meta.mtime,size:meta.size,_rev:meta._rev,children:meta.children,datatype:meta.type,_conflicts:meta._conflicts,eden:meta.eden,deleted,type:meta.type};if(dump){Logger("--Loaded Document--");Logger(doc)}return doc}catch(ex){if(isErrorOfMissingDoc(ex)){Logger(`Missing document content!, could not read ${dispFilename}(${meta._id.substring(0,8)}) from database.`,LOG_LEVEL_NOTICE);return!1}Logger(`Something went wrong on reading ${dispFilename}(${meta._id.substring(0,8)}) from database:`,LOG_LEVEL_NOTICE);Logger(ex)}return!1}async function getDBEntryFromMeta(host,{localDatabase,chunkManager},meta,dump=!1,waitForReady=!0){const filename=host.services.path.id2path(meta._id,meta);if(!isTargetFile(host,filename))return!1;const settings=host.services.setting.currentSettings();if(isLegacyNote(meta)){const note=meta;return respondOldFashionedEntry(note,dump)}return("newnote"==meta.type||"plain"==meta.type)&&await respondEntryFromMeta({localDatabase,chunkManager},settings,filename,meta,dump,waitForReady)}async function getDBEntryByPath(host,managers,path2,opt,dump=!1,waitForReady=!0,includeDeleted=!1){const meta=await getDBEntryMetaByPath(host,managers,path2,opt,includeDeleted);return!!meta&&await getDBEntryFromMeta(host,managers,meta,dump,waitForReady)}async function deleteDBEntryByPath(host,{localDatabase},path2,opt){var _a13;if(!isTargetFile(host,path2))return!1;const id=await host.services.path.path2id(path2);try{return null!=(_a13=await serialized("file:"+path2,async()=>{const settings=host.services.setting.currentSettings();let obj=null;obj=opt?await localDatabase.get(id,opt):await localDatabase.get(id);const revDeletion=opt&&""!=("rev"in opt?opt.rev:"");if(obj.type&&"leaf"==obj.type)return!1;if(!obj.type||obj.type&&"notes"==obj.type){obj._deleted=!0;const r4=await localDatabase.put(obj,{force:!revDeletion});Logger(`Entry removed: ${path2} (${obj._id.substring(0,8)}-${r4.rev}) `);return!0}if("newnote"==obj.type||"plain"==obj.type){if(revDeletion)obj._deleted=!0;else{obj.deleted=!0;obj.mtime=Date.now();settings.deleteMetadataOfDeletedFiles&&(obj._deleted=!0)}const r4=await localDatabase.put(obj,{force:!revDeletion});Logger(`Entry removed: [${revDeletion?"REV":"DEL"}] ${path2} (${obj._id.substring(0,8)}-${r4.rev})`);return!0}return!1}))&&_a13}catch(ex){if(isErrorOfMissingDoc(ex))return!1;throw ex}}async function storeDeletionByPathAtRevision(host,{localDatabase},path2,baseRevision){var _a13;if(!isTargetFile(host,path2))return!1;const id=await host.services.path.path2id(path2);try{return null!=(_a13=await serialized("file:"+path2,async()=>{const obj=await localDatabase.get(id,{rev:baseRevision});if("leaf"===obj.type)return!1;delete obj._deleted;obj.deleted=!0;obj.mtime=Date.now();const result=await localDatabase.put(obj,{force:!0});Logger(`Entry soft-deleted from revision: ${path2} (${obj._id.substring(0,8)}-${result.rev})`);return result}))&&_a13}catch(ex){if(isErrorOfMissingDoc(ex))return!1;throw ex}}function getNoFromRev(rev3){return rev3?parseInt(rev3.split("-")[0]):0}function serializeDoc(doc){if(doc._id.startsWith("h:")){const data=doc.data,writeData=escapeNewLineFromString(data);return te4.encode(`~${doc._id}${UNIT_SPLIT}${writeData}${RECORD_SPLIT}`)}return te4.encode(JSON.stringify(doc)+RECORD_SPLIT)}function cloneQuery(query3){return Object.keys(query3).reduce((carry,paramName)=>{const param=query3[paramName];return{...carry,[paramName]:Array.isArray(param)?[...param]:param}},{})}function addExpectContinueMiddleware(options){return next2=>async args=>{var _a13,_b6,_c3,_d2,_e2,_f;const{request:request2}=args;if(!1!==options.expectContinueHeader&&HttpRequest.isInstance(request2)&&request2.body&&"node"===options.runtime&&"FetchHttpHandler"!==(null==(_b6=null==(_a13=options.requestHandler)?void 0:_a13.constructor)?void 0:_b6.name)){let sendHeader=!0;if("number"==typeof options.expectContinueHeader)try{const bodyLength=null!=(_f=null!=(_e2=Number(null==(_c3=request2.headers)?void 0:_c3["content-length"]))?_e2:null==(_d2=options.bodyLengthChecker)?void 0:_d2.call(options,request2.body))?_f:1/0;sendHeader=bodyLength>=options.expectContinueHeader}catch(e3){}else sendHeader=!!options.expectContinueHeader;sendHeader&&(request2.headers.Expect="100-continue")}return next2({...args,request:request2})}}function setCredentialFeature(credentials,feature,value){credentials.$source||(credentials.$source={});credentials.$source[feature]=value;return credentials}function setFeature(context2,feature,value){context2.__aws_sdk_context?context2.__aws_sdk_context.features||(context2.__aws_sdk_context.features={}):context2.__aws_sdk_context={features:{}};context2.__aws_sdk_context.features[feature]=value}function convertHttpAuthSchemesToMap(httpAuthSchemes){const map4=new Map;for(const scheme of httpAuthSchemes)map4.set(scheme.schemeId,scheme);return map4}function extendedEncodeURIComponent(str){return encodeURIComponent(str).replace(/[!'()*]/g,function(c3){return"%"+c3.charCodeAt(0).toString(16).toUpperCase()})}function getSchemaSerdePlugin(config){return{applyToStack:commandStack=>{commandStack.add(schemaSerializationMiddleware(config),serializerMiddlewareOption3);commandStack.add(schemaDeserializationMiddleware(config),deserializerMiddlewareOption2);config.protocol.setSerdeContext(config)}}}function translateTraits(indicator){if("object"==typeof indicator)return indicator;indicator|=0;if(traitsCache[indicator])return traitsCache[indicator];const traits={};let i3=0;for(const trait of["httpLabel","idempotent","idempotencyToken","sensitive","httpPayload","httpResponseCode","httpQueryParams"])1==(indicator>>i3++&1)&&(traits[trait]=1);return traitsCache[indicator]=traits}function member(memberSchema,memberName){if(memberSchema instanceof NormalizedSchema)return Object.assign(memberSchema,{memberName,_isMemberSchema:!0});const internalCtorAccess=NormalizedSchema;return new internalCtorAccess(memberSchema,memberName)}function determineTimestampFormat(ns,settings){if(settings.timestampFormat.useTrait&&ns.isTimestampSchema()&&(5===ns.getSchema()||6===ns.getSchema()||7===ns.getSchema()))return ns.getSchema();const{httpLabel,httpPrefixHeaders,httpHeader,httpQuery}=ns.getMergedTraits(),bindingFormat=settings.httpBindings?"string"==typeof httpPrefixHeaders||Boolean(httpHeader)?6:Boolean(httpQuery)||Boolean(httpLabel)?5:void 0:void 0;return null!=bindingFormat?bindingFormat:settings.timestampFormat.default}function createPaginator(ClientCtor,CommandCtor,inputTokenName,outputTokenName,pageSizeTokenName){return async function*paginateOperation(config,input,...additionalArguments){var _a13,_b6;const _input=input;let page,token=null!=(_a13=config.startingToken)?_a13:_input[inputTokenName],hasNext=!0;for(;hasNext;){_input[inputTokenName]=token;pageSizeTokenName&&(_input[pageSizeTokenName]=null!=(_b6=_input[pageSizeTokenName])?_b6:config.pageSize);if(!(config.client instanceof ClientCtor))throw new Error(`Invalid client, expected instance of ${ClientCtor.name}`);page=await makePagedClientRequest(CommandCtor,config.client,input,config.withCommand,...additionalArguments);yield page;const prevToken=token;token=get3(page,outputTokenName);hasNext=!(!token||config.stopOnSameToken&&token===prevToken)}}}function setFeature3(context2,feature,value){context2.__smithy_context?context2.__smithy_context.features||(context2.__smithy_context.features={}):context2.__smithy_context={features:{}};context2.__smithy_context.features[feature]=value}function fromHex2(encoded){if(encoded.length%2!=0)throw new Error("Hex encoded strings must have an even number length");const out=new Uint8Array(encoded.length/2);for(let i3=0;i3<encoded.length;i3+=2){const encodedByte=encoded.slice(i3,i3+2).toLowerCase();if(!(encodedByte in HEX_TO_SHORT2))throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`);out[i3/2]=HEX_TO_SHORT2[encodedByte]}return out}function toHex3(bytes){let out="";for(let i3=0;i3<bytes.byteLength;i3++)out+=SHORT_TO_HEX2[bytes[i3]];return out}function negate2(bytes){for(let i3=0;i3<8;i3++)bytes[i3]^=255;for(let i3=7;i3>-1;i3--){bytes[i3]++;if(0!==bytes[i3])break}}function normalizeCredentialProvider(config,{credentials,credentialDefaultProvider}){let credentialsProvider;credentialsProvider=credentials?(null==credentials?void 0:credentials.memoized)?credentials:memoizeIdentityProvider(credentials,isIdentityExpired,doesIdentityRequireRefresh):credentialDefaultProvider?normalizeProvider2(credentialDefaultProvider(Object.assign({},config,{parentClientConfig:config}))):async()=>{throw new Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured.")};credentialsProvider.memoized=!0;return credentialsProvider}function bindCallerConfig(config,credentialsProvider){if(credentialsProvider.configBound)return credentialsProvider;const fn=async options=>credentialsProvider({...options,callerClientConfig:config});fn.memoized=credentialsProvider.memoized;fn.configBound=!0;return fn}function schemaLogFilter(schema,data){if(null==data)return data;const ns=NormalizedSchema.of(schema);if(ns.getMergedTraits().sensitive)return SENSITIVE_STRING;if(ns.isListSchema()){const isSensitive=!!ns.getValueSchema().getMergedTraits().sensitive;if(isSensitive)return SENSITIVE_STRING}else if(ns.isMapSchema()){const isSensitive=!!ns.getKeySchema().getMergedTraits().sensitive||!!ns.getValueSchema().getMergedTraits().sensitive;if(isSensitive)return SENSITIVE_STRING}else if(ns.isStructSchema()&&"object"==typeof data){const object=data,newObject={};for(const[member2,memberNs]of ns.structIterator())null!=object[member2]&&(newObject[member2]=schemaLogFilter(memberNs,object[member2]));return newObject}return data}function toBase642(_input){let input;input="string"==typeof _input?fromUtf8(_input):_input;const isArrayLike="object"==typeof input&&"number"==typeof input.length,isUint8Array="object"==typeof input&&"number"==typeof input.byteOffset&&"number"==typeof input.byteLength;if(!isArrayLike&&!isUint8Array)throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");let str="";for(let i3=0;i3<input.length;i3+=3){let bits2=0,bitLength=0;for(let j2=i3,limit=Math.min(i3+3,input.length);j2<limit;j2++){bits2|=input[j2]<<(limit-j2-1)*bitsPerByte2;bitLength+=bitsPerByte2}const bitClusterCount=Math.ceil(bitLength/bitsPerLetter2);bits2<<=bitClusterCount*bitsPerLetter2-bitLength;for(let k2=1;k2<=bitClusterCount;k2++){const offset=(bitClusterCount-k2)*bitsPerLetter2;str+=alphabetByValue2[(bits2&maxLetterValue2<<offset)>>offset]}str+="==".slice(0,4-bitClusterCount)}return str}function escapeAttribute(value){return value.replace(ATTR_ESCAPE_RE,ch4=>ATTR_ESCAPE_MAP[ch4])}function escapeElement(value){return value.replace(ELEMENT_ESCAPE_RE,ch4=>ELEMENT_ESCAPE_MAP[ch4])}function parseXML(xmlString){parser||(parser=new DOMParser);const xmlDocument=parser.parseFromString(xmlString,"application/xml");if(xmlDocument.getElementsByTagName("parsererror").length>0)throw new Error("DOMParser XML parsing error.");const xmlToObj=node=>{var _a13;if(node.nodeType===Node.TEXT_NODE&&(null==(_a13=node.textContent)?void 0:_a13.trim()))return node.textContent;if(node.nodeType===Node.ELEMENT_NODE){const element2=node;if(0===element2.attributes.length&&0===element2.childNodes.length)return"";const obj={},attributes=Array.from(element2.attributes);for(const attr2 of attributes)obj[`${attr2.name}`]=attr2.value;const childNodes=Array.from(element2.childNodes);for(const child2 of childNodes){const childResult=xmlToObj(child2);if(null!=childResult){const childName=child2.nodeName;if(1===childNodes.length&&0===attributes.length&&"#text"===childName)return childResult;obj[childName]?Array.isArray(obj[childName])?obj[childName].push(childResult):obj[childName]=[obj[childName],childResult]:obj[childName]=childResult}else if(1===childNodes.length&&0===attributes.length)return element2.textContent}return obj}return null};return{[xmlDocument.documentElement.nodeName]:xmlToObj(xmlDocument.documentElement)}}function merge(buffers,mode,chunk){switch(mode){case 0:buffers[0]+=chunk;return sizeOf(buffers[0]);case 1:case 2:buffers[mode].push(chunk);return sizeOf(buffers[mode])}}function flush(buffers,mode){switch(mode){case 0:const s2=buffers[0];buffers[0]="";return s2;case 1:case 2:return buffers[mode].flush()}throw new Error(`@smithy/util-stream - invalid index ${mode} given to flush()`)}function sizeOf(chunk){var _a13,_b6;return null!=(_b6=null!=(_a13=null==chunk?void 0:chunk.byteLength)?_a13:null==chunk?void 0:chunk.length)?_b6:0}function modeOf(chunk,allowBuffer=!0){return allowBuffer&&"undefined"!=typeof Buffer&&chunk instanceof Buffer?2:chunk instanceof Uint8Array?1:"string"==typeof chunk?0:-1}async function headStream2(stream,bytes){var _a13;let byteLengthCounter=0;const chunks=[],reader=stream.getReader();let isDone=!1;for(;!isDone;){const{done,value}=await reader.read();if(value){chunks.push(value);byteLengthCounter+=null!=(_a13=null==value?void 0:value.byteLength)?_a13:0}if(byteLengthCounter>=bytes)break;isDone=done}reader.releaseLock();const collected=new Uint8Array(Math.min(bytes,byteLengthCounter));let offset=0;for(const chunk of chunks){if(chunk.byteLength>collected.byteLength-offset){collected.set(chunk.subarray(0,collected.byteLength-offset),offset);break}collected.set(chunk,offset);offset+=chunk.length}return collected}function buildQueryString2(query3){const parts=[];for(let key3 of Object.keys(query3).sort()){const value=query3[key3];key3=escapeUri2(key3);if(Array.isArray(value))for(let i3=0,iLen=value.length;i3<iLen;i3++)parts.push(`${key3}=${escapeUri2(value[i3])}`);else{let qsEntry=key3;(value||"string"==typeof value)&&(qsEntry+=`=${escapeUri2(value)}`);parts.push(qsEntry)}}return parts.join("&")}function createRequest(url,requestOptions){return new Request(url,requestOptions)}function requestTimeout(timeoutInMs=0){return new Promise((resolve,reject)=>{timeoutInMs&&setTimeout(()=>{const timeoutError=new Error(`Request did not complete within ${timeoutInMs} ms`);timeoutError.name="TimeoutError";reject(timeoutError)},timeoutInMs)})}function buildAbortError(abortSignal){const reason=abortSignal&&"object"==typeof abortSignal&&"reason"in abortSignal?abortSignal.reason:void 0;if(reason){if(reason instanceof Error){const abortError3=new Error("Request aborted");abortError3.name="AbortError";abortError3.cause=reason;return abortError3}const abortError2=new Error(String(reason));abortError2.name="AbortError";return abortError2}const abortError=new Error("Request aborted");abortError.name="AbortError";return abortError}async function collectBlob2(blob){const base64=await readToBase642(blob),arrayBuffer=fromBase642(base64);return new Uint8Array(arrayBuffer)}async function collectStream2(stream){const chunks=[],reader=stream.getReader();let isDone=!1,length=0;for(;!isDone;){const{done,value}=await reader.read();if(value){chunks.push(value);length+=value.length}isDone=done}const collected=new Uint8Array(length);let offset=0;for(const chunk of chunks){collected.set(chunk,offset);offset+=chunk.length}return collected}function readToBase642(blob){return new Promise((resolve,reject)=>{const reader=new FileReader;reader.onloadend=()=>{var _a13;if(2!==reader.readyState)return reject(new Error("Reader aborted too early"));const result=null!=(_a13=reader.result)?_a13:"",commaIndex=result.indexOf(","),dataOffset=commaIndex>-1?commaIndex+1:result.length;resolve(result.substring(dataOffset))};reader.onabort=()=>reject(new Error("Read aborted"));reader.onerror=()=>reject(reader.error);reader.readAsDataURL(blob)})}async function splitStream2(stream){"function"==typeof stream.stream&&(stream=stream.stream());const readableStream=stream;return readableStream.tee()}function resolveHostHeaderConfig(input){return input}function checkContentLengthHeader(){return(next2,context2)=>async args=>{var _a13;const{request:request2}=args;if(HttpRequest.isInstance(request2)&&!(CONTENT_LENGTH_HEADER in request2.headers)&&!(DECODED_CONTENT_LENGTH_HEADER in request2.headers)){const message="Are you using a Stream of unknown length as the Body of a PutObject request? Consider using Upload instead from @aws-sdk/lib-storage.";"function"!=typeof(null==(_a13=null==context2?void 0:context2.logger)?void 0:_a13.warn)||context2.logger instanceof NoOpLogger?console.warn(message):context2.logger.warn(message)}return next2({...args})}}function regionRedirectMiddleware(clientConfig){return(next2,context2)=>async args=>{var _a13,_b6,_c3,_d2;try{return await next2(args)}catch(err3){if(clientConfig.followRegionRedirects){const statusCode=null==(_a13=null==err3?void 0:err3.$metadata)?void 0:_a13.httpStatusCode,isHeadBucket="HeadBucketCommand"===context2.commandName,bucketRegionHeader=null==(_c3=null==(_b6=null==err3?void 0:err3.$response)?void 0:_b6.headers)?void 0:_c3["x-amz-bucket-region"];if(bucketRegionHeader&&(301===statusCode||400===statusCode&&("IllegalLocationConstraintException"===(null==err3?void 0:err3.name)||isHeadBucket))){try{const actualRegion=bucketRegionHeader;null==(_d2=context2.logger)||_d2.debug(`Redirecting from ${await clientConfig.region()} to ${actualRegion}`);context2.__s3RegionRedirect=actualRegion}catch(e3){throw new Error("Region redirect failed: "+e3)}return next2(args)}}throw err3}}}function getCredentialsWithoutSessionToken(credentials){const credentialsWithoutSessionToken={accessKeyId:credentials.accessKeyId,secretAccessKey:credentials.secretAccessKey,expiration:credentials.expiration};return credentialsWithoutSessionToken}function setSingleOverride(privateAccess,credentialsWithoutSessionToken){const id=setTimeout(()=>{throw new Error("SignatureV4S3Express credential override was created but not called.")},10),currentCredentialProvider=privateAccess.credentialProvider;privateAccess.credentialProvider=()=>{clearTimeout(id);privateAccess.credentialProvider=currentCredentialProvider;return Promise.resolve(credentialsWithoutSessionToken)}}function bucketEndpointMiddleware(options){return(next2,context2)=>async args=>{var _a13,_b6,_c3,_d2;if(options.bucketEndpoint){const endpoint=context2.endpointV2;if(endpoint){const bucket=args.input.Bucket;if("string"==typeof bucket)try{const bucketEndpointUrl=new URL(bucket);context2.endpointV2={...endpoint,url:bucketEndpointUrl}}catch(e3){const warning=`@aws-sdk/middleware-sdk-s3: bucketEndpoint=true was set but Bucket=${bucket} could not be parsed as URL.`;"NoOpLogger"===(null==(_b6=null==(_a13=context2.logger)?void 0:_a13.constructor)?void 0:_b6.name)?console.warn(warning):null==(_d2=null==(_c3=context2.logger)?void 0:_c3.warn)||_d2.call(_c3,warning);throw e3}}}return next2(args)}}function validateBucketNameMiddleware({bucketEndpoint}){return next2=>async args=>{const{input:{Bucket}}=args;if(!bucketEndpoint&&"string"==typeof Bucket&&!validate(Bucket)&&Bucket.indexOf("/")>=0){const err3=new Error(`Bucket name shouldn't contain '/', received '${Bucket}'`);err3.name="InvalidBucketName";throw err3}return next2({...args})}}function isValidUserAgentAppId(appId){return void 0===appId||"string"==typeof appId&&appId.length<=50}function resolveUserAgentConfig(input){var _a13;const normalizedAppIdProvider=normalizeProvider2(null!=(_a13=input.userAgentAppId)?_a13:DEFAULT_UA_APP_ID),{customUserAgent}=input;return Object.assign(input,{customUserAgent:"string"==typeof customUserAgent?[[customUserAgent]]:customUserAgent,userAgentAppId:async()=>{var _a14,_b6;const appId=await normalizedAppIdProvider();if(!isValidUserAgentAppId(appId)){const logger2="NoOpLogger"!==(null==(_b6=null==(_a14=input.logger)?void 0:_a14.constructor)?void 0:_b6.name)&&input.logger?input.logger:console;"string"!=typeof appId?null==logger2||logger2.warn("userAgentAppId must be a string or undefined."):appId.length>50&&(null==logger2||logger2.warn("The provided userAgentAppId exceeds the maximum length of 50 characters."))}return appId}})}function toDebugString(input){return"object"!=typeof input||null==input?input:"ref"in input?`$${toDebugString(input.ref)}`:"fn"in input?`${input.fn}(${(input.argv||[]).map(toDebugString).join(", ")})`:JSON.stringify(input,null,2)}function parseQueryString2(querystring){const query3={};querystring=querystring.replace(/^\?/,"");if(querystring)for(const pair of querystring.split("&")){let[key3,value=null]=pair.split("=");key3=decodeURIComponent(key3);value&&(value=decodeURIComponent(value));key3 in query3?Array.isArray(query3[key3])?query3[key3].push(value):query3[key3]=[query3[key3],value]:query3[key3]=value}return query3}function isNodeJsHttp2TransientError(error){return"ERR_HTTP2_STREAM_ERROR"===error.code&&error.message.includes("NGHTTP2_REFUSED_STREAM")}function parseRetryAfterHeader(response,logger2){var _a13,_b6,_c3,_d2;if(HttpResponse2.isInstance(response))for(const header of Object.keys(response.headers)){const h3=header.toLowerCase();if("retry-after"===h3){const retryAfter=response.headers[header];let retryAfterSeconds=NaN;if(retryAfter.endsWith("GMT"))try{const date2=parseRfc7231DateTime(retryAfter);retryAfterSeconds=(date2.getTime()-Date.now())/1e3}catch(e3){null==(_a13=null==logger2?void 0:logger2.trace)||_a13.call(logger2,"Failed to parse retry-after header");null==(_b6=null==logger2?void 0:logger2.trace)||_b6.call(logger2,e3)}else retryAfter.match(/ GMT, ((\d+)|(\d+\.\d+))$/)?retryAfterSeconds=Number(null==(_c3=retryAfter.match(/ GMT, ([\d.]+)$/))?void 0:_c3[1]):retryAfter.match(/^((\d+)|(\d+\.\d+))$/)?retryAfterSeconds=Number(retryAfter):Date.parse(retryAfter)>=Date.now()&&(retryAfterSeconds=(Date.parse(retryAfter)-Date.now())/1e3);if(isNaN(retryAfterSeconds))return;return new Date(Date.now()+1e3*retryAfterSeconds)}if("x-amz-retry-after"===h3){const v2=response.headers[header],backoffMilliseconds=Number(v2);if(isNaN(backoffMilliseconds)){null==(_d2=null==logger2?void 0:logger2.trace)||_d2.call(logger2,`Failed to parse x-amz-retry-after=${v2}`);return}return new Date(Date.now()+backoffMilliseconds)}}}function bindRetryMiddleware(isStreamingPayload3){return options=>(next2,context2)=>async args=>{var _a13,_b6,_c3,_d2;let retryStrategy=await options.retryStrategy();const maxAttempts=await options.maxAttempts();if(!isRetryStrategyV2(retryStrategy)){(null==retryStrategy?void 0:retryStrategy.mode)&&(context2.userAgent=[...context2.userAgent||[],["cfg/retry-mode",retryStrategy.mode]]);return retryStrategy.retry(next2,args)}{let retryToken=await retryStrategy.acquireInitialRetryToken((null!=(_a13=context2.partition_id)?_a13:"")+(context2.__retryLongPoll?":longpoll":"")),lastError=new Error,attempts=0,totalRetryDelay=0;const{request:request2}=args,isRequest=HttpRequest2.isInstance(request2);isRequest&&(request2.headers[INVOCATION_ID_HEADER]=v4());for(;;)try{isRequest&&(request2.headers[REQUEST_HEADER]=`attempt=${attempts+1}; max=${maxAttempts}`);const{response,output}=await next2(args);retryStrategy.recordSuccess(retryToken);output.$metadata.attempts=attempts+1;output.$metadata.totalRetryDelay=totalRetryDelay;return{response,output}}catch(e3){const retryErrorInfo=getRetryErrorInfo(e3,options.logger);lastError=asSdkError(e3);if(isRequest&&isStreamingPayload3(request2)){null==(_b6=context2.logger instanceof NoOpLogger2?console:context2.logger)||_b6.warn("An error was encountered in a non-retryable streaming request.");throw lastError}try{retryToken=await retryStrategy.refreshRetryTokenForRetry(retryToken,retryErrorInfo)}catch(refreshError){lastError.$metadata||(lastError.$metadata={});lastError.$metadata.attempts=attempts+1;lastError.$metadata.totalRetryDelay=totalRetryDelay;throw lastError}attempts=retryToken.getRetryCount();const delay2=retryToken.getRetryDelay();totalRetryDelay+=(null!=(_d2=null==(_c3=null==retryToken?void 0:retryToken.$retryLog)?void 0:_c3.acquisitionDelay)?_d2:0)+delay2;delay2>0&&await cooldown(delay2)}}}}async function checkFeatures(context2,config,args){var _a13,_b6,_c3,_d2,_e2,_f;const request2=args.request;"rpc-v2-cbor"===(null==(_a13=null==request2?void 0:request2.headers)?void 0:_a13["smithy-protocol"])&&setFeature(context2,"PROTOCOL_RPC_V2_CBOR","M");if("function"==typeof config.retryStrategy){const retryStrategy=await config.retryStrategy();if("string"==typeof retryStrategy.mode)switch(retryStrategy.mode){case RETRY_MODES.ADAPTIVE:setFeature(context2,"RETRY_MODE_ADAPTIVE","F");break;case RETRY_MODES.STANDARD:setFeature(context2,"RETRY_MODE_STANDARD","E");break}}if("function"==typeof config.accountIdEndpointMode){const endpointV2=context2.endpointV2;String(null==(_b6=null==endpointV2?void 0:endpointV2.url)?void 0:_b6.hostname).match(ACCOUNT_ID_ENDPOINT_REGEX)&&setFeature(context2,"ACCOUNT_ID_ENDPOINT","O");switch(await(null==(_c3=config.accountIdEndpointMode)?void 0:_c3.call(config))){case"disabled":setFeature(context2,"ACCOUNT_ID_MODE_DISABLED","Q");break;case"preferred":setFeature(context2,"ACCOUNT_ID_MODE_PREFERRED","P");break;case"required":setFeature(context2,"ACCOUNT_ID_MODE_REQUIRED","R");break}}const identity=null==(_e2=null==(_d2=context2.__smithy_context)?void 0:_d2.selectedHttpAuthScheme)?void 0:_e2.identity;if(null==identity?void 0:identity.$source){const credentials=identity;credentials.accountId&&setFeature(context2,"RESOLVED_ACCOUNT_ID","T");for(const[key3,value]of Object.entries(null!=(_f=credentials.$source)?_f:{}))setFeature(context2,key3,value)}}function encodeFeatures(features){let buffer="";for(const key3 in features){const val=features[key3];if(!(buffer.length+val.length+1<=BYTE_LIMIT))break;buffer.length?buffer+=","+val:buffer+=val}return buffer}function contentLengthMiddleware2(bodyLengthChecker){return next2=>async args=>{const request2=args.request;if(HttpRequest.isInstance(request2)){const{body,headers}=request2;if(body&&-1===Object.keys(headers).map(str=>str.toLowerCase()).indexOf(CONTENT_LENGTH_HEADER2))try{const length=bodyLengthChecker(body);request2.headers={...request2.headers,[CONTENT_LENGTH_HEADER2]:String(length)}}catch(error){}}return next2({...args,request:request2})}}function createAwsAuthSigv4HttpAuthOption(authParameters){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"s3",region:authParameters.region},propertiesExtractor:(config,context2)=>({signingProperties:{config,context:context2}})}}function createAwsAuthSigv4aHttpAuthOption(authParameters){return{schemeId:"aws.auth#sigv4a",signingProperties:{name:"s3",region:authParameters.region},propertiesExtractor:(config,context2)=>({signingProperties:{config,context:context2}})}}function isEmptyData2(data){return"string"==typeof data?0===data.length:0===data.byteLength}function locateWindow(){return"undefined"!=typeof window?window:"undefined"!=typeof self?self:fallbackWindow}function convertToBuffer2(data){return"string"==typeof data?fromUtf84(data):ArrayBuffer.isView(data)?new Uint8Array(data.buffer,data.byteOffset,data.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(data)}function supportsWebCrypto(window2){if(supportsSecureRandom(window2)&&"object"==typeof window2.crypto.subtle){var subtle2=window2.crypto.subtle;return supportsSubtleCrypto(subtle2)}return!1}function supportsSecureRandom(window2){if("object"==typeof window2&&"object"==typeof window2.crypto){var getRandomValues2=window2.crypto.getRandomValues;return"function"==typeof getRandomValues2}return!1}function supportsSubtleCrypto(subtle2){return subtle2&&subtleCryptoMethods.every(function(methodName){return"function"==typeof subtle2[methodName]})}function bufferFromSecret(secret){var bufferHash,buffer,input=convertToBuffer(secret);if(input.byteLength>BLOCK_SIZE){bufferHash=new RawSha256;bufferHash.update(input);input=bufferHash.digest()}buffer=new Uint8Array(BLOCK_SIZE);buffer.set(input);return buffer}function negate3(bytes){for(let i3=0;i3<8;i3++)bytes[i3]^=255;for(let i3=7;i3>-1;i3--){bytes[i3]++;if(0!==bytes[i3])break}}function splitMessage2({byteLength,byteOffset,buffer}){if(byteLength<MINIMUM_MESSAGE_LENGTH2)throw new Error("Provided message too short to accommodate event stream message overhead");const view=new DataView(buffer,byteOffset,byteLength),messageLength=view.getUint32(0,!1);if(byteLength!==messageLength)throw new Error("Reported message length does not match received message length");const headerLength=view.getUint32(PRELUDE_MEMBER_LENGTH2,!1),expectedPreludeChecksum=view.getUint32(PRELUDE_LENGTH2,!1),expectedMessageChecksum=view.getUint32(byteLength-CHECKSUM_LENGTH2,!1),checksummer=(new Crc32).update(new Uint8Array(buffer,byteOffset,PRELUDE_LENGTH2));if(expectedPreludeChecksum!==checksummer.digest())throw new Error(`The prelude checksum specified in the message (${expectedPreludeChecksum}) does not match the calculated CRC32 checksum (${checksummer.digest()})`);checksummer.update(new Uint8Array(buffer,byteOffset+PRELUDE_LENGTH2,byteLength-(PRELUDE_LENGTH2+CHECKSUM_LENGTH2)));if(expectedMessageChecksum!==checksummer.digest())throw new Error(`The message checksum (${checksummer.digest()}) did not match the expected value of ${expectedMessageChecksum}`);return{headers:new DataView(buffer,byteOffset+PRELUDE_LENGTH2+CHECKSUM_LENGTH2,headerLength),body:new Uint8Array(buffer,byteOffset+PRELUDE_LENGTH2+CHECKSUM_LENGTH2+headerLength,messageLength-headerLength-(PRELUDE_LENGTH2+CHECKSUM_LENGTH2+CHECKSUM_LENGTH2))}}function getChunkedStream2(source2){let currentMessageTotalLength=0,currentMessagePendingLength=0,currentMessage=null,messageLengthBuffer=null;const allocateMessage=size=>{if("number"!=typeof size)throw new Error("Attempted to allocate an event message where size was not a number: "+size);currentMessageTotalLength=size;currentMessagePendingLength=4;currentMessage=new Uint8Array(size);const currentMessageView=new DataView(currentMessage.buffer);currentMessageView.setUint32(0,size,!1)};return{[Symbol.asyncIterator]:async function*(){const sourceIterator=source2[Symbol.asyncIterator]();for(;;){const{value,done}=await sourceIterator.next();if(done){if(!currentMessageTotalLength)return;if(currentMessageTotalLength!==currentMessagePendingLength)throw new Error("Truncated event message received.");yield currentMessage;return}const chunkLength=value.length;let currentOffset=0;for(;currentOffset<chunkLength;){if(!currentMessage){const bytesRemaining=chunkLength-currentOffset;messageLengthBuffer||(messageLengthBuffer=new Uint8Array(4));const numBytesForTotal=Math.min(4-currentMessagePendingLength,bytesRemaining);messageLengthBuffer.set(value.slice(currentOffset,currentOffset+numBytesForTotal),currentMessagePendingLength);currentMessagePendingLength+=numBytesForTotal;currentOffset+=numBytesForTotal;if(currentMessagePendingLength<4)break;allocateMessage(new DataView(messageLengthBuffer.buffer).getUint32(0,!1));messageLengthBuffer=null}const numBytesToWrite=Math.min(currentMessageTotalLength-currentMessagePendingLength,chunkLength-currentOffset);currentMessage.set(value.slice(currentOffset,currentOffset+numBytesToWrite),currentMessagePendingLength);currentMessagePendingLength+=numBytesToWrite;currentOffset+=numBytesToWrite;if(currentMessageTotalLength&&currentMessageTotalLength===currentMessagePendingLength){yield currentMessage;currentMessage=null;currentMessageTotalLength=0;currentMessagePendingLength=0}}}}}}function getMessageUnmarshaller2(deserializer,toUtf82){return async function(message){const{value:messageType}=message.headers[":message-type"];if("error"===messageType){const unmodeledError=new Error(message.headers[":error-message"].value||"UnknownError");unmodeledError.name=message.headers[":error-code"].value;throw unmodeledError}if("exception"===messageType){const code=message.headers[":exception-type"].value,exception={[code]:message},deserializedException=await deserializer(exception);if(deserializedException.$unknown){const error=new Error(toUtf82(message.body));error.name=code;throw error}throw deserializedException[code]}if("event"===messageType){const event2={[message.headers[":event-type"].value]:message},deserialized=await deserializer(event2);if(deserialized.$unknown)return;return deserialized}throw Error(`Unrecognizable event type: ${message.headers[":event-type"].value}`)}}async function blobReader(blob,onChunk,chunkSize2=1048576){const size=blob.size;let totalBytesRead=0;for(;totalBytesRead<size;){const slice=blob.slice(totalBytesRead,Math.min(size,totalBytesRead+chunkSize2));onChunk(new Uint8Array(await slice.arrayBuffer()));totalBytesRead+=slice.size}}function cmn(q2,a2,b3,x3,s2,t9){a2=(a2+q2&4294967295)+(x3+t9&4294967295)&4294967295;return(a2<<s2|a2>>>32-s2)+b3&4294967295}function ff(a2,b3,c3,d4,x3,s2,t9){return cmn(b3&c3|~b3&d4,a2,b3,x3,s2,t9)}function gg(a2,b3,c3,d4,x3,s2,t9){return cmn(b3&d4|c3&~d4,a2,b3,x3,s2,t9)}function hh(a2,b3,c3,d4,x3,s2,t9){return cmn(b3^c3^d4,a2,b3,x3,s2,t9)}function ii(a2,b3,c3,d4,x3,s2,t9){return cmn(c3^(b3|~d4),a2,b3,x3,s2,t9)}function isEmptyData3(data){return"string"==typeof data?0===data.length:0===data.byteLength}function convertToBuffer3(data){return"string"==typeof data?fromUtf8(data):ArrayBuffer.isView(data)?new Uint8Array(data.buffer,data.byteOffset,data.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(data)}function ssecMiddleware(options){return next2=>async args=>{const input={...args.input},properties=[{target:"SSECustomerKey",hash:"SSECustomerKeyMD5"},{target:"CopySourceSSECustomerKey",hash:"CopySourceSSECustomerKeyMD5"}];for(const prop2 of properties){const value=input[prop2.target];if(value){let valueForHash;if("string"==typeof value)if(isValidBase64EncodedSSECustomerKey(value,options))valueForHash=options.base64Decoder(value);else{valueForHash=options.utf8Decoder(value);input[prop2.target]=options.base64Encoder(valueForHash)}else{valueForHash=ArrayBuffer.isView(value)?new Uint8Array(value.buffer,value.byteOffset,value.byteLength):new Uint8Array(value);input[prop2.target]=options.base64Encoder(valueForHash)}const hash3=new options.md5;hash3.update(valueForHash);input[prop2.hash]=options.base64Encoder(await hash3.digest())}}return next2({...args,input})}}function isValidBase64EncodedSSECustomerKey(str,options){if(!/^(?:[A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(str))return!1;try{const decodedBytes=options.base64Decoder(str);return 32===decodedBytes.length}catch(e3){return!1}}function locationConstraintMiddleware(options){return next2=>async args=>{var _a13;const{CreateBucketConfiguration}=args.input,region=await options.region();if(!(null==CreateBucketConfiguration?void 0:CreateBucketConfiguration.LocationConstraint)&&!(null==CreateBucketConfiguration?void 0:CreateBucketConfiguration.Location)&&"us-east-1"!==region){args.input.CreateBucketConfiguration=null!=(_a13=args.input.CreateBucketConfiguration)?_a13:{};args.input.CreateBucketConfiguration.LocationConstraint=region}return next2(args)}}async function runWithTrackedPhysicalRequest(counters,task){counters.requestCount.value++;try{return await task()}finally{counters.responseCount.value++}}function isMissingObjectError(error){var _a13;if(!error||"object"!=typeof error)return!1;const{name,Code,code}=error,errorCode=null!=(_a13=null!=Code?Code:code)?_a13:name;return"NoSuchKey"===errorCode||"NotFound"===errorCode}function getSettingsManager(app){const manager=Reflect.get(app,"setting");if("object"!=typeof manager||null===manager)throw new TypeError("Obsidian does not expose the settings manager");return manager}function invokeSettingsMethod(app,methodName,args=[]){const manager=getSettingsManager(app),method=manager[methodName];if("function"!=typeof method)throw new TypeError(`Obsidian does not expose settings.${methodName}`);Reflect.apply(method,manager,args)}function openObsidianSettings(app,tabId){invokeSettingsMethod(app,"open");invokeSettingsMethod(app,"openTabById",[tabId])}function closeObsidianSettings(app){invokeSettingsMethod(app,"close")}function createAdvancedSettingSpecGroups({isCouchDB}){return[{heading:"Memory cache",items:[{key:"hashCacheMaxCount",control:{type:"number",min:10}}]},{heading:"Local Database Tweak",items:[{key:"chunkSplitterVersion",control:{type:"dropdown",options:()=>ChunkAlgorithmNames}},{key:"customChunkSize",control:{type:"number",min:0,allowZero:!0}}]},{heading:"Transfer Tweak",items:[{key:"readChunksOnline",control:{type:"toggle"},visible:isCouchDB},{key:"useOnlyLocalChunk",control:{type:"toggle"},visible:isCouchDB},{key:"concurrencyOfReadChunksOnline",control:{type:"number",min:10},visible:isCouchDB},{key:"minimumIntervalOfReadChunksOnline",control:{type:"number",min:10},visible:isCouchDB},{key:"autoAcceptCompatibleTweak",control:{type:"toggle",defaultValue:!0}}]},{heading:"Remote Database Tweak",items:[{key:"enableCompression",control:{type:"toggle"}}]}]}function isToggleSettingSpec(spec){return"toggle"===spec.control.type}function isNumberSettingSpec(spec){return"number"===spec.control.type}function toLegacyUpdateOptions(spec){return spec.visible||spec.disabled?{onUpdate:()=>({...spec.visible?{visibility:spec.visible()}:{},...spec.disabled?{disabled:spec.disabled()}:{}})}:{}}function toLegacySettingBinding(spec){const updateOptions=toLegacyUpdateOptions(spec);return isToggleSettingSpec(spec)?{type:"toggle",key:spec.key,options:{...updateOptions,...void 0===spec.control.defaultValue?{}:{defaultToggleValue:spec.control.defaultValue}}}:isNumberSettingSpec(spec)?{type:"number",key:spec.key,options:{...updateOptions,...void 0===spec.control.min?{}:{clampMin:spec.control.min},...void 0===spec.control.max?{}:{clampMax:spec.control.max},...void 0===spec.control.allowZero?{}:{acceptZero:spec.control.allowZero}}}:{type:"dropdown",key:spec.key,options:{...updateOptions,options:spec.control.options()}}}function renderLegacySettingSpec(renderer,spec){const binding=toLegacySettingBinding(spec);switch(binding.type){case"toggle":renderer.autoWireToggle(binding.key,binding.options);return;case"number":renderer.autoWireNumeric(binding.key,binding.options);return;case"dropdown":renderer.autoWireDropDown(binding.key,binding.options)}}function numberIsOutOfRange(value,control){return!Number.isFinite(value)||(void 0!==control.max&&value>control.max||(!control.allowZero||0!==value)&&(void 0!==control.min&&value<control.min))}function isValidSettingSpecValue(spec,value){switch(spec.control.type){case"toggle":return"boolean"==typeof value;case"number":return"number"==typeof value&&!numberIsOutOfRange(value,spec.control);case"dropdown":return"string"==typeof value&&Object.prototype.hasOwnProperty.call(spec.control.options(),value)}}function toObsidianSettingDefinition(spec,metadata,messages){let control;switch(spec.control.type){case"toggle":control={type:"toggle",key:spec.key,...void 0===spec.control.defaultValue?{}:{defaultValue:spec.control.defaultValue},...spec.disabled?{disabled:spec.disabled}:{}};break;case"number":{const numericControl=spec.control,hasRange=void 0!==numericControl.min||void 0!==numericControl.max;control={type:"number",key:spec.key,...void 0===numericControl.min?{}:{min:numericControl.allowZero?Math.min(0,numericControl.min):numericControl.min},...void 0===numericControl.max?{}:{max:numericControl.max},...metadata.placeHolder?{placeholder:metadata.placeHolder}:{},...hasRange?{validate:value=>numberIsOutOfRange(value,numericControl)?messages.valueShouldBeInRange({min:numericControl.min,max:numericControl.max}):void 0}:{},...spec.disabled?{disabled:spec.disabled}:{}};break}case"dropdown":control={type:"dropdown",key:spec.key,options:spec.control.options(),...spec.disabled?{disabled:spec.disabled}:{}};break}return{name:`${metadata.name}${statusDisplay(metadata.status)}`,...metadata.desc?{desc:metadata.desc}:{},...spec.aliases?{aliases:spec.aliases}:{},...spec.visible?{visible:spec.visible}:{},control}}function createGeneralSettingSpecGroups({showEditorStatusDetails,showVerboseLog}){return[{heading:$msg("obsidianLiveSyncSettingTab.titleAppearance"),items:[{key:"displayLanguage",control:{type:"dropdown",options:()=>Object.fromEntries(SUPPORTED_I18N_LANGS.map(language=>[language,$t(`lang-${language}`)]))}},{key:"showStatusOnEditor",control:{type:"toggle"}},{key:"showOnlyIconsOnEditor",control:{type:"toggle"},visible:showEditorStatusDetails},{key:"showStatusOnStatusbar",control:{type:"toggle"}},{key:"hideFileWarningNotice",control:{type:"toggle"}},{key:"networkWarningStyle",control:{type:"dropdown",options:()=>({[NetworkWarningStyles_BANNER]:"Show full banner",[NetworkWarningStyles_ICON]:"Show icon only",[NetworkWarningStyles_HIDDEN]:"Hide completely"})}}]},{heading:$msg("obsidianLiveSyncSettingTab.titleLogging"),items:[{key:"lessInformationInLog",control:{type:"toggle"}},{key:"showVerboseLog",control:{type:"toggle"},visible:showVerboseLog}]}]}function createExtraMenuSettingSpecGroup(){return{heading:$msg("obsidianLiveSyncSettingTab.titleExtraMenus"),items:[{key:"useAdvancedMode",control:{type:"toggle"}},{key:"usePowerUserMode",control:{type:"toggle"}},{key:"useEdgeCaseMode",control:{type:"toggle"}}]}}function paneAdvanced(paneEl,{addPanel}){const groups=createAdvancedSettingSpecGroups({isCouchDB:()=>!1!==this.onlyOnCouchDB().visibility});for(const group4 of groups)addPanel(paneEl,group4.heading).then(panelEl=>{for(const spec of group4.items)renderLegacySettingSpec(new LiveSyncSetting(panelEl),spec)})}function paneChangeLog(paneEl){const informationDivEl=this.createEl(paneEl,"div",{text:""}),lifetimeComponent=this.lifetimeComponent;fireAndForget(()=>import_obsidian.MarkdownRenderer.render(this.plugin.app,updateInformation,informationDivEl,"/",lifetimeComponent))}function paneCustomisationSync(paneEl,{addPanel}){addPanel(paneEl,"Customization Sync").then(paneEl2=>{const enableOnlyOnPluginSyncIsNotEnabled=enableOnly(()=>this.isConfiguredAs("usePluginSync",!1)),visibleOnlyOnPluginSyncEnabled=visibleOnly(()=>this.isConfiguredAs("usePluginSync",!0));this.createEl(paneEl2,"div",{text:"Please set device name to identify this device. This name should be unique among your devices. While not configured, we cannot enable this feature.",cls:"op-warn"},c3=>{},visibleOnly(()=>this.isConfiguredAs("deviceAndVaultName","")));this.createEl(paneEl2,"div",{text:"We cannot change the device name while this feature is enabled. Please disable this feature to change the device name.",cls:"op-warn-info"},c3=>{},visibleOnly(()=>this.isConfiguredAs("usePluginSync",!0)));new LiveSyncSetting(paneEl2).autoWireText("deviceAndVaultName",{placeHolder:"desktop",onUpdate:enableOnlyOnPluginSyncIsNotEnabled});new LiveSyncSetting(paneEl2).autoWireToggle("usePluginSyncV2");new LiveSyncSetting(paneEl2).autoWireToggle("usePluginSync",{onUpdate:enableOnly(()=>!this.isConfiguredAs("deviceAndVaultName",""))});new LiveSyncSetting(paneEl2).autoWireToggle("autoSweepPlugins",{onUpdate:visibleOnlyOnPluginSyncEnabled});new LiveSyncSetting(paneEl2).autoWireToggle("autoSweepPluginsPeriodic",{onUpdate:visibleOnly(()=>this.isConfiguredAs("usePluginSync",!0)&&this.isConfiguredAs("autoSweepPlugins",!0))});new LiveSyncSetting(paneEl2).autoWireToggle("notifyPluginOrSettingUpdated",{onUpdate:visibleOnlyOnPluginSyncEnabled});new LiveSyncSetting(paneEl2).setName("Open").setDesc("Open the dialog").addButton(button=>{button.setButtonText("Open").setDisabled(!1).onClick(()=>{eventHub.emitEvent(EVENT_REQUEST_OPEN_PLUGIN_SYNC_DIALOG2)})}).addOnUpdate(visibleOnlyOnPluginSyncEnabled)})}function paneGeneral(paneEl,{addPanel}){const groups=[...createGeneralSettingSpecGroups({showEditorStatusDetails:()=>this.isConfiguredAs("showStatusOnEditor",!0),showVerboseLog:()=>this.isConfiguredAs("lessInformationInLog",!1)}),createExtraMenuSettingSpecGroup()];for(const group4 of groups)addPanel(paneEl,group4.heading).then(panelEl=>{for(const spec of group4.items)renderLegacySettingSpec(new LiveSyncSetting(panelEl),spec)})}function toDatabasePath(path2){return path2.startsWith(".")?addPrefix(path2,ICHeader):path2}async function getLocalDatabaseMeta(core,path2,options){var _a13,_b6,_c3,_d2,_e2,_f,_g;const documentId=await core.services.path.path2id(path2);let raw;try{raw=await core.localDatabase.localDatabase.get(documentId,options)}catch(error){if(isNotFoundError(error))return!1;throw error}if("leaf"===raw.type)return!1;if(raw.type&&"notes"!==raw.type&&"newnote"!==raw.type&&"plain"!==raw.type)return!1;const rawStorageType=null!=(_a13=raw.type)?_a13:null,legacy=null===rawStorageType||"notes"===rawStorageType,type=legacy?"notes":rawStorageType,legacyBodyPresent=legacy&&("string"==typeof raw.data||Array.isArray(raw.data)&&raw.data.every(item=>"string"==typeof item));return{_id:raw._id,_rev:raw._rev,_conflicts:raw._conflicts,_revs_info:raw._revs_info,path:path2,data:legacyBodyPresent?raw.data:"",ctime:null!=(_b6=raw.ctime)?_b6:0,mtime:null!=(_c3=raw.mtime)?_c3:0,size:null!=(_d2=raw.size)?_d2:0,children:("newnote"===type||"plain"===type)&&null!=(_e2=raw.children)?_e2:[],datatype:"newnote"===type?"newnote":"plain",deleted:null!=(_f=raw.deleted)?_f:raw._deleted,type,eden:null!=(_g=raw.eden)?_g:{},_rawStorageType:rawStorageType,_legacyBodyPresent:legacyBodyPresent}}async function collectRevisionDatabaseInfo(core,meta,current){var _a13,_b6,_c3,_d2,_e2;const legacy=null===meta._rawStorageType||"notes"===meta._rawStorageType,children=legacy?[]:"children"in meta?meta.children:[],uniqueChildren=[...new Set(children)],referenceCounts=new Map;for(const child2 of children)referenceCounts.set(child2,(null!=(_a13=referenceCounts.get(child2))?_a13:0)+1);const embeddedChildren=new Set(Object.keys("eden"in meta&&meta.eden?meta.eden:{}).filter(id=>uniqueChildren.includes(id))),localRows=0===uniqueChildren.length?[]:(await core.localDatabase.allDocsRaw({keys:uniqueChildren,include_docs:!1})).rows,localChunkStates=new Map(localRows.filter(row=>"value"in row).map(row=>[row.key,{state:row.value.deleted?"deleted":"available",revision:row.value.rev}]));return{documentId:meta._id,revision:null!=(_b6=meta._rev)?_b6:null,current,deleted:Boolean(null!=(_c3=meta.deleted)?_c3:meta._deleted),storageType:null!=(_d2=meta._rawStorageType)?_d2:"absent",storageLayout:legacy?"legacy-inline":"chunked",ctime:meta.ctime,mtime:meta.mtime,recordedSize:meta.size,revisionHistory:(null!=(_e2=meta._revs_info)?_e2:[]).map(({rev:rev3,status})=>({revision:rev3,status})),chunkReferences:children.length,uniqueChunkReferences:uniqueChildren.length,embeddedChunkReferences:children.filter(id=>embeddedChildren.has(id)).length,locallyStoredChunkReferences:children.filter(id=>{var _a14;return"available"===(null==(_a14=localChunkStates.get(id))?void 0:_a14.state)}).length,contentAvailableLocally:legacy?meta._legacyBodyPresent:uniqueChildren.every(id=>{var _a14;return embeddedChildren.has(id)||"available"===(null==(_a14=localChunkStates.get(id))?void 0:_a14.state)}),chunks:uniqueChildren.map(id=>{var _a14,_b7,_c4;const localState=localChunkStates.get(id);return{id,referenceCount:null!=(_a14=referenceCounts.get(id))?_a14:0,embedded:embeddedChildren.has(id),storedInLocalDatabase:"available"===(null==localState?void 0:localState.state),localDatabaseState:null!=(_b7=null==localState?void 0:localState.state)?_b7:"missing",localDatabaseRevision:null!=(_c4=null==localState?void 0:localState.revision)?_c4:null}})}}function revisionHistory(meta){var _a13;const history=(null!=(_a13=meta._revs_info)?_a13:[]).map(({rev:rev3,status})=>({revision:rev3,status}));meta._rev&&!history.some(({revision})=>revision===meta._rev)&&history.unshift({revision:meta._rev,status:"available"});return history}function missingChunkIds(info3){return info3.chunks.filter(({embedded,localDatabaseState})=>!embedded&&"available"!==localDatabaseState).map(({id})=>id)}async function inspectFileDatabaseInfo(core,path2){var _a13,_b6,_c3,_d2,_e2,_f;const storageExists=await core.storageAccess.isExistsIncludeHidden(path2),storageStat=storageExists?await core.storageAccess.statHidden(path2):null,databasePath=toDatabasePath(path2),currentMeta=await getLocalDatabaseMeta(core,databasePath,{conflicts:!0,revs:!0,revs_info:!0}),revisions=[],conflictRevisions=!1===currentMeta?[]:null!=(_a13=currentMeta._conflicts)?_a13:[],unavailableConflictRevisions=[],mergeBases=[],metadataByRevision=new Map;!1!==currentMeta&&currentMeta._rev&&metadataByRevision.set(currentMeta._rev,currentMeta);const getRevisionMeta=async revision=>{const cached=metadataByRevision.get(revision);if(void 0!==cached)return cached;const meta=await getLocalDatabaseMeta(core,databasePath,{rev:revision,revs:!0,revs_info:!0});metadataByRevision.set(revision,meta);return meta};if(currentMeta){revisions.push(await collectRevisionDatabaseInfo(core,currentMeta,!0));for(const revision of conflictRevisions){const conflictMeta=await getRevisionMeta(revision);if(conflictMeta){revisions.push(await collectRevisionDatabaseInfo(core,conflictMeta,!1));const winnerHistory=revisionHistory(currentMeta),conflictHistory=revisionHistory(conflictMeta),conflictHistoryByRevision=new Map(conflictHistory.map(({revision:historyRevision,status})=>[historyRevision,status])),sharedHistory=winnerHistory.filter(({revision:historyRevision})=>conflictHistoryByRevision.has(historyRevision)),sharedRevision=null!=(_c3=null==(_b6=sharedHistory[0])?void 0:_b6.revision)?_c3:null,unavailableSharedRevisions=sharedHistory.filter(({revision:historyRevision,status})=>"available"!==status||"available"!==conflictHistoryByRevision.get(historyRevision)).map(({revision:historyRevision})=>historyRevision),sharedMeta=!!sharedRevision&&await getRevisionMeta(sharedRevision),sharedInfo=sharedMeta?await collectRevisionDatabaseInfo(core,sharedMeta,!1):void 0;mergeBases.push({winnerRevision:null!=(_d2=currentMeta._rev)?_d2:"",conflictRevision:revision,revision:sharedRevision,metadataAvailableLocally:Boolean(sharedMeta),contentAvailableLocally:null!=(_e2=null==sharedInfo?void 0:sharedInfo.contentAvailableLocally)&&_e2,missingChunkIds:sharedInfo?missingChunkIds(sharedInfo):[],unavailableSharedRevisions})}else unavailableConflictRevisions.push(revision)}}const report={path:path2,databasePath,storage:storageStat?{exists:!0,ctime:storageStat.ctime,mtime:storageStat.mtime,size:storageStat.size}:{exists:!1},database:{source:"local database on this device",remoteQueried:!1,exists:!1!==currentMeta,currentRevision:currentMeta&&null!=(_f=currentMeta._rev)?_f:null,conflictCount:conflictRevisions.length,conflictRevisions,unavailableConflictRevisions,revisions,mergeBases}};return report}async function readFileDatabaseRevisionLocally(core,path2,revision){const databasePath=toDatabasePath(path2),meta=await getLocalDatabaseMeta(core,databasePath,{rev:revision,revs:!0,revs_info:!0});if(!meta)return!1;const info3=await collectRevisionDatabaseInfo(core,meta,!1);return!(info3.deleted||!info3.contentAvailableLocally)&&await core.localDatabase.getDBEntryFromMeta(meta,!1,!1)}async function retryReadFileDatabaseRevision(core,path2,revision){return await core.localDatabase.getDBEntry(toDatabasePath(path2),{rev:revision},!1,!0,!0)}async function buildFileDatabaseInfoReport(core,path2){const report=await inspectFileDatabaseInfo(core,path2);return`${$msg(REPORT_WARNING)}\n\n\`\`\`json\n${JSON.stringify(report,null,2)}\n\`\`\``}async function copyFileDatabaseInfo(core,path2){const report=await buildFileDatabaseInfoReport(core,path2);return await core.services.UI.promptCopyToClipboard($msg("Database information for ${FILE}",{FILE:path2}),report)}async function collectFileDatabaseInfoPaths(core){const ignorePatterns=getFileRegExp(core.settings,"syncInternalFilesIgnorePatterns"),targetPatterns=getFileRegExp(core.settings,"syncInternalFilesTargetPatterns"),storagePaths=core.settings.syncInternalFiles?await core.storageAccess.getFilesIncludeHidden("/",targetPatterns,ignorePatterns):await core.storageAccess.getFileNames(),databasePaths=[];for await(const entry of core.localDatabase.findAllDocs()){const prefixedPath=entry.path;prefixedPath.startsWith(ICXHeader)||prefixedPath.startsWith(PSCHeader)||(!core.settings.syncInternalFiles&&prefixedPath.startsWith(ICHeader)||databasePaths.push(stripAllPrefixes(prefixedPath)))}return[...new Set([...storagePaths,...databasePaths])].sort((left,right)=>left<right?-1:left>right?1:0)}async function chooseAndCopyFileDatabaseInfo(core){const paths=await collectFileDatabaseInfoPaths(core),selected=await core.services.UI.confirm.askSelectString($msg("Choose a file to inspect"),paths);return!!selected&&await copyFileDatabaseInfo(core,selected)}async function inspectFileRepair(core,path2){var _a13;const information=await inspectFileDatabaseInfo(core,path2),storageContent=information.storage.exists?createBlob(await core.storageAccess.readHiddenFileBinary(path2)):void 0,revisions=[];for(const metadata of information.database.revisions){const loadedEntry=!(metadata.deleted||!metadata.contentAvailableLocally)&&await readFileDatabaseRevisionLocally(core,path2,null!=(_a13=metadata.revision)?_a13:""),contentReadable=metadata.deleted||!1!==loadedEntry,contentMatchesStorage=storageContent&&!1!==loadedEntry?await isDocContentSame(storageContent,readAsBlob(loadedEntry)):null;revisions.push({role:metadata.current?"winner":"conflict",metadata,contentReadable,contentMatchesStorage,loadedEntry})}const winner=revisions.find(({role})=>"winner"===role),winnerRepresentsStoredFile=void 0!==winner&&!winner.metadata.deleted,databaseAndStorageDiffer=information.storage.exists!==winnerRepresentsStoredFile||information.storage.exists&&winnerRepresentsStoredFile&&!1===winner.contentMatchesStorage,unreadableLiveRevision=information.database.unavailableConflictRevisions.length>0||revisions.some(({contentReadable})=>!contentReadable),requiresAttention=databaseAndStorageDiffer||information.database.conflictCount>0||unreadableLiveRevision||information.database.exists&&void 0===winner;return{information,revisions,requiresAttention}}async function discardUnreadableLiveRevision(core,path2,revision){const latest2=await inspectFileDatabaseInfo(core,path2),liveRevisions=[latest2.database.currentRevision,...latest2.database.conflictRevisions].filter(candidate=>null!==candidate);if(!liveRevisions.includes(revision))return"no-longer-live";const metadata=latest2.database.revisions.find(candidate=>candidate.revision===revision),metadataUnavailable=latest2.database.unavailableConflictRevisions.includes(revision);if(!metadataUnavailable&&((null==metadata?void 0:metadata.deleted)||(null==metadata?void 0:metadata.contentAvailableLocally)))return"revision-is-readable";const deleted=await core.fileHandler.deleteRevisionFromDB(latest2.databasePath,revision);return deleted?"discarded":"failed"}async function discardLiveBranch(core,path2,revision){const latest2=await inspectFileDatabaseInfo(core,path2),liveRevisions=[latest2.database.currentRevision,...latest2.database.conflictRevisions].filter(candidate=>null!==candidate);if(!liveRevisions.includes(revision))return"no-longer-live";if(liveRevisions.length<2)return"only-live-revision";const deleted=await core.fileHandler.deleteRevisionFromDB(latest2.databasePath,revision);return deleted?"discarded":"failed"}function getFileRepairRevisionActions(inspection,revision){const storageExists=inspection.information.storage.exists,hasRevision=null!==revision.metadata.revision,readableFileRevision=!revision.metadata.deleted&&revision.contentReadable&&!1!==revision.loadedEntry,matchesVault=storageExists&&!0===revision.contentMatchesStorage,hasConflictBranches=inspection.information.database.conflictCount>0;return{compareWithVault:readableFileRevision&&storageExists&&!1===revision.contentMatchesStorage&&isPlainText(inspection.information.path),applyRevisionToVault:hasRevision&&readableFileRevision&&(!storageExists||!0!==revision.contentMatchesStorage),markAsVaultRevision:hasRevision&&readableFileRevision&&matchesVault,storeVaultOnBranch:hasRevision&&storageExists&&!0!==revision.contentMatchesStorage,applyLogicalDeletionToVault:hasRevision&&revision.metadata.deleted&&storageExists,retryRevision:hasRevision&&!revision.metadata.deleted&&!revision.contentReadable,discardBranch:hasRevision&&hasConflictBranches,discardRevision:hasRevision&&!hasConflictBranches&&!revision.metadata.deleted&&!revision.contentReadable}}function getFileRepairRevisionComparison(inspection,revision){var _a13,_b6;const decodedSize=!1===revision.loadedEntry?null:readAsBlob(revision.loadedEntry).size,vaultSize=inspection.information.storage.exists&&null!=(_a13=inspection.information.storage.size)?_a13:null,databaseMtime=revision.metadata.mtime,vaultMtime=inspection.information.storage.exists&&null!=(_b6=inspection.information.storage.mtime)?_b6:null,timestampDifferenceMs=databaseMtime>0&&null!==vaultMtime&&vaultMtime>0?vaultMtime-databaseMtime:null;let timestampRelation="unavailable";if(null!==timestampDifferenceMs){const comparison=compareMTime(vaultMtime,databaseMtime);timestampRelation=comparison===EVEN?"same-window":comparison===BASE_IS_NEW?"vault-newer":comparison===TARGET_IS_NEW?"database-newer":"unavailable"}return{recordedSize:revision.metadata.recordedSize,decodedSize,recordedToDecodedSizeDifference:null===decodedSize?null:decodedSize-revision.metadata.recordedSize,vaultSize,databaseToVaultSizeDifference:null===decodedSize||null===vaultSize?null:vaultSize-decodedSize,databaseMtime,vaultMtime,timestampDifferenceMs,timestampRelation}}async function*withConcurrency(iterable,callback,concurrency){const processes=new Set,mapTaskToPromise=new Map;let serial=0;const enqueue=item=>{const idx2=serial++,promise=(async()=>[idx2,await callback(item)])();processes.add(promise);mapTaskToPromise.set(idx2,promise)},consume=async()=>{const r4=await Promise.race(processes),item=mapTaskToPromise.get(r4[0]);processes.delete(item);mapTaskToPromise.delete(r4[0]);return r4[1]};for await(const t9 of iterable){for(;processes.size>=concurrency;)yield await consume();enqueue(t9)}for(;processes.size>0;)yield await consume()}function getMetadataDocumentNamespace(value){return value.startsWith(ICXHeader)?MetadataDocumentNamespaces_CUSTOMISATION:value.startsWith(ICHeader)?MetadataDocumentNamespaces_INTERNAL:value.startsWith(PSCHeader)?MetadataDocumentNamespaces_PLUGIN_STORAGE:MetadataDocumentNamespaces_NORMAL}async function inspectMetadataDocumentIdentity(host,doc){const actualDocumentId=doc._id,declaredPath=getPathFromEntry(host,doc),actualNamespace=getMetadataDocumentNamespace(actualDocumentId),declaredPathNamespace=getMetadataDocumentNamespace(declaredPath);if(actualNamespace!==MetadataDocumentNamespaces_NORMAL||declaredPathNamespace!==MetadataDocumentNamespaces_NORMAL)return actualNamespace===declaredPathNamespace?{status:MetadataDocumentIdentityStatuses_EXCLUDED,actualDocumentId,declaredPath,namespace:actualNamespace}:{status:MetadataDocumentIdentityStatuses_UNRESOLVED,diagnostic:{reason:OfflineScanUnresolvedReasons_NAMESPACE_MISMATCH,actualDocumentId,declaredPath,actualNamespace,declaredPathNamespace}};const expectedDocumentId=await host.services.path.path2id(declaredPath);return actualDocumentId!==expectedDocumentId?{status:MetadataDocumentIdentityStatuses_UNRESOLVED,diagnostic:{reason:OfflineScanUnresolvedReasons_DOCUMENT_ID_MISMATCH,actualDocumentId,declaredPath,expectedDocumentId,actualNamespace,declaredPathNamespace}}:{status:MetadataDocumentIdentityStatuses_CONSISTENT,actualDocumentId,declaredPath,expectedDocumentId}}function stableValue(value){return Array.isArray(value)?value.map(stableValue):null===value||"object"!=typeof value?value:Object.fromEntries(Object.entries(value).filter(([,item])=>void 0!==item).sort(([left],[right])=>left.localeCompare(right)).map(([key3,item])=>[key3,stableValue(item)]))}function logicalMetadataPayload(doc){var _a13;return stableValue({path:doc.path,ctime:doc.ctime,mtime:doc.mtime,size:doc.size,type:doc.type,children:[...doc.children],eden:null!=(_a13=doc.eden)?_a13:{},deleted:Boolean(doc.deleted||doc._deleted)})}function isExactMetadataCopy(source2,target){return JSON.stringify(logicalMetadataPayload(source2))===JSON.stringify(logicalMetadataPayload(target))}async function inspectMetadataDocumentIdentities(host){var _a13,_b6,_c3,_d2,_e2,_f,_g,_h2,_i2,_j,_k,_l;const observations=[];for await(const doc of host.services.database.localDatabase.findAllNormalDocs({conflicts:!0})||[]){if(!isMetaEntry(doc))continue;const inspection=await inspectMetadataDocumentIdentity(host,doc);observations.push({doc,inspection})}const expectedTargetIds=unique(observations.flatMap(({inspection})=>{if(inspection.status!==MetadataDocumentIdentityStatuses_UNRESOLVED)return[];const{diagnostic}=inspection;return diagnostic.reason!==OfflineScanUnresolvedReasons_DOCUMENT_ID_MISMATCH||void 0===diagnostic.expectedDocumentId?[]:[diagnostic.expectedDocumentId]})),targetRows=new Map;if(expectedTargetIds.length>0){const result=await host.services.database.localDatabase.allDocsRaw({keys:expectedTargetIds,include_docs:!0,conflicts:!0});for(const row of result.rows)targetRows.set(row.key,row)}const settings=host.services.setting.currentSettings(),observationsByDocumentId=new Map(observations.map(observation=>[observation.doc._id,observation])),pathClaims=new Map,targetClaims=new Map;for(const{doc,inspection}of observations){const declaredPath=inspection.status===MetadataDocumentIdentityStatuses_UNRESOLVED?inspection.diagnostic.declaredPath:inspection.declaredPath,declaredNamespace=getMetadataDocumentNamespace(declaredPath);if(declaredNamespace===MetadataDocumentNamespaces_NORMAL){const key3=convertCase(settings,declaredPath),claims=null!=(_a13=pathClaims.get(key3))?_a13:new Set;claims.add(doc._id);pathClaims.set(key3,claims)}if(inspection.status===MetadataDocumentIdentityStatuses_UNRESOLVED&&inspection.diagnostic.reason===OfflineScanUnresolvedReasons_DOCUMENT_ID_MISMATCH&&void 0!==inspection.diagnostic.expectedDocumentId){const claims=null!=(_b6=targetClaims.get(inspection.diagnostic.expectedDocumentId))?_b6:new Set;claims.add(doc._id);targetClaims.set(inspection.diagnostic.expectedDocumentId,claims)}}const entries2=[];for(const{doc,inspection}of observations){if(inspection.status!==MetadataDocumentIdentityStatuses_UNRESOLVED)continue;const{diagnostic}=inspection;let repairAvailable=!1,targetAlreadyPresent=!1,ordinaryPathAvailable=!1;if(diagnostic.reason===OfflineScanUnresolvedReasons_DOCUMENT_ID_MISMATCH&&void 0!==diagnostic.expectedDocumentId){const expectedDocumentId=diagnostic.expectedDocumentId,normalisedPath=convertCase(settings,diagnostic.declaredPath),targetObservation=observationsByDocumentId.get(expectedDocumentId),targetPath=(null==targetObservation?void 0:targetObservation.inspection.status)===MetadataDocumentIdentityStatuses_CONSISTENT?targetObservation.inspection.declaredPath:void 0;ordinaryPathAvailable=void 0!==targetPath&&convertCase(settings,targetPath)===normalisedPath&&host.services.vault.isValidPath(targetPath)&&!shouldBeIgnored(targetPath)&&await host.services.vault.isTargetFile(targetPath);const row=targetRows.get(expectedDocumentId),target=null==row?void 0:row.doc,targetMetadata=target&&isMetaEntry(target)?target:void 0;targetAlreadyPresent=Boolean(targetMetadata&&isExactMetadataCopy(doc,targetMetadata));const targetIsAvailable=!row||"not_found"===row.error||targetAlreadyPresent&&!(null==(_c3=null==row?void 0:row.value)?void 0:_c3.deleted)&&!(null==targetMetadata?void 0:targetMetadata._deleted)&&!(null==targetMetadata?void 0:targetMetadata.deleted)&&0===(null!=(_e2=null==(_d2=null==targetMetadata?void 0:targetMetadata._conflicts)?void 0:_d2.length)?_e2:0),samePathClaims=null!=(_f=pathClaims.get(normalisedPath))?_f:new Set,permittedExactPair=targetAlreadyPresent&&2===samePathClaims.size&&samePathClaims.has(doc._id)&&samePathClaims.has(expectedDocumentId),pathIsUnambiguous=1===samePathClaims.size||permittedExactPair,targetIsUnambiguous=1===(null!=(_h2=null==(_g=targetClaims.get(expectedDocumentId))?void 0:_g.size)?_h2:0);repairAvailable=Boolean(doc._rev)&&!doc.deleted&&!doc._deleted&&0===(null!=(_j=null==(_i2=doc._conflicts)?void 0:_i2.length)?_j:0)&&host.services.vault.isValidPath(diagnostic.declaredPath)&&await host.services.vault.isTargetFile(diagnostic.declaredPath)&&pathIsUnambiguous&&targetIsUnambiguous&&targetIsAvailable}entries2.push({inspection,sourceRevision:null!=(_k=doc._rev)?_k:null,logicallyDeleted:Boolean(doc.deleted||doc._deleted),conflictRevisions:[...null!=(_l=doc._conflicts)?_l:[]],repairAvailable,targetAlreadyPresent,ordinaryPathAvailable})}return entries2}function cloneEden(eden){return Object.fromEntries(Object.entries(null!=eden?eden:{}).map(([id,chunk])=>[id,{data:chunk.data,epoch:chunk.epoch}]))}function createReaddressedMetadata(source2,expectedDocumentId){return{_id:expectedDocumentId,path:source2.path,ctime:source2.ctime,mtime:source2.mtime,size:source2.size,type:source2.type,children:[...source2.children],eden:cloneEden(source2.eden),...void 0===source2.deleted?{}:{deleted:source2.deleted}}}async function serializedByMetadataDocumentIds(documentIds,callback){const lockKeys=[...new Set(documentIds)].sort().map(documentId=>`processFileEvent-${documentId}`),acquire=async index6=>{const key3=lockKeys[index6];return void 0===key3?await callback():await serialized(key3,()=>acquire(index6+1))};return await acquire(0)}function findRepairEntry(entries2,actualDocumentId){return entries2.find(({inspection})=>inspection.diagnostic.actualDocumentId===actualDocumentId)}async function repairMetadataDocumentIdentity(host,request2){const baseResult={actualDocumentId:request2.actualDocumentId,expectedDocumentId:request2.expectedDocumentId,sourceRevision:request2.sourceRevision,targetCreated:!1};return await serializedByMetadataDocumentIds([request2.actualDocumentId,request2.expectedDocumentId],async()=>{var _a13,_b6;let targetCreated=!1;try{const entries2=await inspectMetadataDocumentIdentities(host),entry=findRepairEntry(entries2,request2.actualDocumentId);if(!entry||entry.sourceRevision!==request2.sourceRevision||entry.inspection.diagnostic.reason!==OfflineScanUnresolvedReasons_DOCUMENT_ID_MISMATCH||entry.inspection.diagnostic.expectedDocumentId!==request2.expectedDocumentId)return{...baseResult,status:MetadataDocumentRepairResults_STALE,message:"The inspected source revision or expected document ID has changed."};if(!entry.repairAvailable)return{...baseResult,status:MetadataDocumentRepairResults_BLOCKED,message:"The source no longer satisfies the repair preconditions."};const source2=await host.services.database.localDatabase.getRaw(request2.actualDocumentId,{rev:request2.sourceRevision,conflicts:!0});if(!isMetaEntry(source2)||source2._rev!==request2.sourceRevision)return{...baseResult,status:MetadataDocumentRepairResults_STALE,message:"The source revision changed during repair validation."};await clearOfflineScannerLastSeen(host,entry.inspection.diagnostic.declaredPath);if(!entry.targetAlreadyPresent){await host.services.database.localDatabase.putRaw(createReaddressedMetadata(source2,request2.expectedDocumentId));targetCreated=!0}const target=await host.services.database.localDatabase.getRaw(request2.expectedDocumentId,{conflicts:!0});if(!isMetaEntry(target)||target.deleted||target._deleted||(null!=(_b6=null==(_a13=target._conflicts)?void 0:_a13.length)?_b6:0)>0||!isExactMetadataCopy(source2,target))return{...baseResult,targetCreated,status:MetadataDocumentRepairResults_FAILED,message:"The repair target could not be verified as an exact local copy."};await host.services.database.localDatabase.removeRaw(request2.actualDocumentId,request2.sourceRevision);return{...baseResult,targetCreated,status:MetadataDocumentRepairResults_COMPLETED}}catch(error){return{...baseResult,targetCreated,status:MetadataDocumentRepairResults_FAILED,message:error instanceof Error?error.message:`${error}`}}})}async function collectDeletedFiles(host,log2){const limitDays=host.services.setting.currentSettings().automaticallyDeleteMetadataOfDeletedFiles;if(limitDays<=0)return;log2("Checking expired file history");const limit=Date.now()-864e5*limitDays,notes=[];for await(const doc of host.services.database.localDatabase.findAllDocs({conflicts:!0}))if(isAnyNote(doc)&&doc.deleted&&doc.mtime-limit<0){if(isMetaEntry(doc)){const identity=await inspectMetadataDocumentIdentity(host,doc);if(identity.status===MetadataDocumentIdentityStatuses_UNRESOLVED){log2(`Expired deletion history has an unresolved Metadata identity and will be left unchanged: ${identity.diagnostic.declaredPath} (${identity.diagnostic.reason})`,LOG_LEVEL_INFO);continue}}notes.push({path:doc.path,mtime:doc.mtime,ttl:(doc.mtime-limit)/1e3/86400,doc})}if(0!==notes.length){for(const v2 of notes){log2(`Deletion history expired: ${v2.path}`);const delDoc=v2.doc;delDoc._deleted=!0;await host.services.database.localDatabase.putRaw(delDoc)}log2("Checking expired file history done")}else{log2("There are no old documents");log2("Checking expired file history done")}}function getPathFromEntry(host,doc){const path2=host.services.path.getPath(doc);return path2}async function syncFileBetweenDBandStorage(host,log2,file,doc){const docPath=getPathFromEntry(host,doc);if(!doc)throw new Error(`Missing doc:${docPath}`);const compareResult=host.services.path.compareFileFreshness(file,doc);switch(compareResult){case BASE_IS_NEW:if(host.services.vault.isFileSizeTooLarge(file.stat.size)){log2(`STORAGE -> DB : ${file.path} has been skipped due to file size exceeding the limit`,LOG_LEVEL_NOTICE);return FilePairProcessResults_SKIPPED}log2("STORAGE -> DB :"+file.path);await host.serviceModules.fileHandler.storeFileToDB(file);return FilePairProcessResults_COMPLETED;case TARGET_IS_NEW:if(host.services.vault.isFileSizeTooLarge(doc.size)){log2(`STORAGE <- DB : ${file.path} has been skipped due to file size exceeding the limit`,LOG_LEVEL_NOTICE);return FilePairProcessResults_SKIPPED}log2("STORAGE <- DB :"+docPath);if(await host.serviceModules.fileHandler.dbToStorage(doc,stripAllPrefixes(docPath),!1)){host.services.context.events.emitEvent("event-file-changed",{file:file.path,automated:!0});return FilePairProcessResults_COMPLETED}log2(`STORAGE <- DB : Cloud not read ${file.path}, possibly deleted`,LOG_LEVEL_NOTICE);return FilePairProcessResults_FAILED;case EVEN:log2("STORAGE == DB :"+file.path,LOG_LEVEL_DEBUG);return FilePairProcessResults_COMPLETED;default:log2("STORAGE ?? DB :"+file.path+" Something got weird");return FilePairProcessResults_FAILED}}function canProceedScan(host,errorManager,log2,showingNotice=!1,ignoreSuspending=!1){const settings=host.services.setting.currentSettings(),ERR_NOT_CONFIGURED="LiveSync is not configured yet. Synchronising between the storage and the local database is now prevented.";if(!settings.isConfigured){errorManager.showError(ERR_NOT_CONFIGURED,showingNotice?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO);return!1}errorManager.clearError(ERR_NOT_CONFIGURED);const ERR_SUSPENDING="Now suspending file watching. Synchronising between the storage and the local database is now prevented.";if(!ignoreSuspending&&settings.suspendFileWatching){errorManager.showError(ERR_SUSPENDING,showingNotice?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO);return!1}errorManager.clearError(ERR_SUSPENDING);const MSG_IN_REMEDIATION="Started in remediation Mode! (Max mtime for reflect events is set). Synchronising between the storage and the local database is now prevented.";if(settings.maxMTimeForReflectEvents>0){errorManager.showError(MSG_IN_REMEDIATION,LOG_LEVEL_NOTICE);return!1}errorManager.clearError(MSG_IN_REMEDIATION);return!0}function convertCase(settings,path2){return settings.handleFilenameCaseSensitive?path2:path2.toLowerCase()}async function collectFilesOnStorage(host,settings,log2){log2("Collecting local files on the storage",LOG_LEVEL_VERBOSE);const filesStorageSrc=await host.serviceModules.storageAccess.getFiles(),_filesStorage=[];for(const f4 of filesStorageSrc)shouldBeIgnored(f4.path)||await host.services.vault.isTargetFile(f4.path)&&_filesStorage.push(f4);const storageFileNameMap=Object.fromEntries(_filesStorage.map(e3=>[e3.path,e3])),storageFileNames=Object.keys(storageFileNameMap),storageFileNameCapsPair=storageFileNames.map(e3=>[e3,convertCase(settings,e3)]),storageFileNameCI2CS=Object.fromEntries(storageFileNameCapsPair.map(e3=>[e3[1],e3[0]]));return{storageFileNameMap,storageFileNames,storageFileNameCI2CS}}async function collectDatabaseFiles(host,settings,log2,showingNotice){var _a13;log2("Collecting local files on the DB",LOG_LEVEL_VERBOSE);const _DBEntries=[],unresolvedFileNamesLC=new Set,resolvableFileNamesLC=new Set;let count=0;for await(const doc of host.services.database.localDatabase.findAllNormalDocs({conflicts:!0})||[]){count++;count%25==0&&log2(`Collecting local files on the DB: ${count}`,showingNotice?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,"syncAll");if(!isMetaEntry(doc)){const documentId=null!=(_a13=doc._id)?_a13:"unknown";log2(`Invalid Metadata entry: ${documentId}`,LOG_LEVEL_INFO);continue}const identity=await inspectMetadataDocumentIdentity(host,doc);if(identity.status===MetadataDocumentIdentityStatuses_EXCLUDED)continue;if(identity.status===MetadataDocumentIdentityStatuses_UNRESOLVED){const{diagnostic}=identity,unresolvedKey=convertCase(settings,stripAllPrefixes(diagnostic.declaredPath));unresolvedFileNamesLC.add(unresolvedKey);log2(`Metadata identity is unresolved and will be left unchanged: ${diagnostic.declaredPath} (${diagnostic.reason})`,LOG_LEVEL_INFO);continue}const path2=identity.declaredPath;if(host.services.vault.isValidPath(path2)&&!shouldBeIgnored(path2)&&await host.services.vault.isTargetFile(path2)){_DBEntries.push(doc);resolvableFileNamesLC.add(convertCase(settings,stripAllPrefixes(path2)))}}const databaseFileNameMap=Object.fromEntries(_DBEntries.map(e3=>[getPathFromEntry(host,e3),e3])),databaseFileNames=Object.keys(databaseFileNameMap),databaseFileNameCapsPair=databaseFileNames.map(e3=>[e3,convertCase(settings,e3)]),databaseFileNameCI2CS=Object.fromEntries(databaseFileNameCapsPair.map(e3=>[e3[1],e3[0]])),quarantinedFileNamesLC=new Set([...unresolvedFileNamesLC].filter(path2=>!resolvableFileNamesLC.has(path2)));return{databaseFileNameMap,databaseFileNames,databaseFileNameCI2CS,quarantinedFileNamesLC}}async function updateToDatabase(host,log2,logLevel,file){if(host.services.vault.isFileSizeTooLarge(file.stat.size)){log2(`UPDATE DATABASE: ${file.path} has been skipped due to file size exceeding the limit`,logLevel);return FilePairProcessResults_SKIPPED}{const path2=file.path;await host.serviceModules.fileHandler.storeFileToDB(file);host.services.context.events.emitEvent("event-file-changed",{file:path2,automated:!0});return FilePairProcessResults_COMPLETED}}async function updateToStorage(host,log2,logLevel,w2){var _a13,_b6;const path2=getPathFromEntry(host,w2);if(!w2||w2.deleted||w2._deleted){if(w2){log2(`Deletion history skipped: ${path2}`,LOG_LEVEL_VERBOSE);return FilePairProcessResults_SKIPPED}log2(`entry not found: ${path2}`);return FilePairProcessResults_FAILED}if(host.services.vault.isFileSizeTooLarge(w2.size)){log2(`UPDATE STORAGE: ${path2} has been skipped due to file size exceeding the limit`,logLevel);return FilePairProcessResults_SKIPPED}{if((null!=(_b6=null==(_a13=w2._conflicts)?void 0:_a13.length)?_b6:0)>0){log2(`UPDATE STORAGE: ${path2} has conflicts. skipped (x)`,LOG_LEVEL_INFO);return FilePairProcessResults_SKIPPED}const reflected=await host.serviceModules.fileHandler.dbToStorage(path2,null,!0);if(!reflected)return FilePairProcessResults_FAILED;host.services.context.events.emitEvent("event-file-changed",{file:path2,automated:!0});log2(`Check or pull from db:${path2} OK`);return FilePairProcessResults_COMPLETED}}async function syncStorageAndDatabase(host,log2,file,logLevel,doc){var _a13,_b6;if((null!=(_b6=null==(_a13=doc._conflicts)?void 0:_a13.length)?_b6:0)>0){log2(`SYNC DATABASE AND STORAGE: ${file.path} has conflicts. skipped`,LOG_LEVEL_INFO);return FilePairProcessResults_SKIPPED}if(host.services.vault.isFileSizeTooLarge(file.stat.size)||host.services.vault.isFileSizeTooLarge(doc.size)){log2(`SYNC DATABASE AND STORAGE: ${getPathFromEntry(host,doc)} has been skipped due to file size exceeding the limit`,logLevel);return FilePairProcessResults_SKIPPED}return await syncFileBetweenDBandStorage(host,log2,file,doc)}function isDeletedEntry2(entry){return entry.deleted||entry._deleted||!1}function getFilePairState(pair){const{file,doc}=pair;if(file&&doc)return isDeletedEntry2(doc)?"both-db-deleted":"both";if(file)return"storage-only";if(doc)return isDeletedEntry2(doc)?"db-only-deleted":"db-only";throw new Error("Corrupted file pair")}function shouldDeleteLocalWhenRemoteMissing(options){return options.extraOnRemote===ExtraOnRemote_DELETE_LOCAL_MISSING||options.extraOnLocal===ExtraOnLocal_DELETE_DB_MISSING}function shouldDeleteLocalWhenRemoteDeleted(options){return options.extraOnRemote===ExtraOnRemote_DELETE_LOCAL_MISSING||options.extraOnLocal===ExtraOnLocal_DELETE_DB_DELETED||options.extraOnLocal===ExtraOnLocal_DELETE_DB_MISSING}function resolveFilePairAction(state2,options){switch(options.mode){case FullScanModes_DB_APPLY:switch(state2){case"both":case"db-only":return"update-storage";case"storage-only":return shouldDeleteLocalWhenRemoteMissing(options)?"delete-local":"skip";case"both-db-deleted":return shouldDeleteLocalWhenRemoteDeleted(options)?"delete-local":"skip";case"db-only-deleted":return"skip"}break;case FullScanModes_NEWER_WINS:switch(state2){case"both":return"sync-newer";case"storage-only":return shouldDeleteLocalWhenRemoteMissing(options)?"delete-local":"update-db";case"db-only":return"update-storage";case"both-db-deleted":return shouldDeleteLocalWhenRemoteDeleted(options)?"delete-local":options.extraOnLocal===ExtraOnLocal_APPEND_STORAGE_ONLY?"update-db":"skip";case"db-only-deleted":return"skip"}break}return"skip"}async function processFilePair(host,log2,pair,options){var _a13,_b6;const{file,doc}=pair,canonicalPath=doc?getPathFromEntry(host,doc):null==file?void 0:file.path;if(!canonicalPath)throw new Error("Corrupted file pair");const path2=canonicalPath,fileMapKey=convertCase(host.services.setting.currentSettings(),canonicalPath);file&&updateFileMTimeInMap(host,fileMapKey,file.stat.mtime);if(doc&&(null!=(_b6=null==(_a13=doc._conflicts)?void 0:_a13.length)?_b6:0)>0){log2(`SKIP ${options.mode}: ${path2} has conflicts`,LOG_LEVEL_INFO);return FilePairProcessResults_SKIPPED}const state2=getFilePairState(pair);let action2=resolveFilePairAction(state2,options);if(options.mode===FullScanModes_NEWER_WINS&&"db-only"===state2&&doc){const lastSeenMTime=getFileMTimeFromMap(fileMapKey);if(void 0!==lastSeenMTime){const recency=compareMTime(lastSeenMTime,doc.mtime);if(recency===BASE_IS_NEW||recency===EVEN){action2="delete-db";log2(`NEWER_WINS: Treating missing local file as deletion (${path2})`,LOG_LEVEL_VERBOSE)}}}try{switch(action2){case"update-db":if(!file)throw new Error(`Missing storage file for ${path2}`);return await updateToDatabase(host,log2,LOG_LEVEL_INFO,file);case"update-storage":if(!doc)throw new Error(`Missing database entry for ${path2}`);const updateStorageResult=await updateToStorage(host,log2,LOG_LEVEL_INFO,doc);updateStorageResult===FilePairProcessResults_COMPLETED&&updateFileMTimeInMap(host,fileMapKey,doc.mtime);return updateStorageResult;case"sync-newer":if(!file||!doc)throw new Error(`Cannot compare freshness for ${path2}`);const syncResult=await syncStorageAndDatabase(host,log2,file,LOG_LEVEL_INFO,doc);syncResult===FilePairProcessResults_COMPLETED&&updateFileMTimeInMap(host,fileMapKey,Math.max(file.stat.mtime,doc.mtime));return syncResult;case"delete-local":if(!file){log2(`DELETE LOCAL: ${path2} is already absent from storage`,LOG_LEVEL_VERBOSE);return FilePairProcessResults_COMPLETED}log2(`DELETE LOCAL: ${file.path}`,LOG_LEVEL_INFO);await host.serviceModules.storageAccess.delete(file.path,!0);fileMaps.delete(fileMapKey);saveFileStatus(host);return FilePairProcessResults_COMPLETED;case"delete-db":{if(!doc)throw new Error(`Missing database entry for ${path2}`);log2(`DELETE DATABASE: ${path2}`,LOG_LEVEL_INFO);const dbDeleted=await host.serviceModules.fileHandler.deleteFileFromDB(stripAllPrefixes(path2));if(dbDeleted){fileMaps.delete(fileMapKey);saveFileStatus(host);return FilePairProcessResults_COMPLETED}log2(`DELETE DATABASE did not delete ${path2}; keeping last-seen record to avoid resurrecting the file`,LOG_LEVEL_NOTICE);return FilePairProcessResults_FAILED}case"skip":log2(`SKIP ${options.mode}: ${path2} (${state2})`,LOG_LEVEL_VERBOSE);return FilePairProcessResults_SKIPPED}}catch(ex){log2(`Error processing ${path2} with action ${action2}`,LOG_LEVEL_NOTICE);log2(ex,LOG_LEVEL_VERBOSE);return FilePairProcessResults_FAILED}}async function synchroniseAllFilesBetweenDBandStorage(host,log2,errorManager,options){var _a13;const settings=host.services.setting.currentSettings(),showingNotice=null!=(_a13=options.showingNotice)&&_a13;await loadFileStatus(host);const{storageFileNameMap,storageFileNameCI2CS}=await collectFilesOnStorage(host,settings,log2),{databaseFileNameMap,databaseFileNameCI2CS,quarantinedFileNamesLC}=await collectDatabaseFiles(host,settings,log2,showingNotice),pairs=[];for(const fileNameLC of unique([...Object.keys(storageFileNameCI2CS),...Object.keys(databaseFileNameCI2CS)])){if(quarantinedFileNamesLC.has(fileNameLC))continue;const fileName=fileNameLC in storageFileNameCI2CS?storageFileNameCI2CS[fileNameLC]:void 0,file=fileName?storageFileNameMap[fileName]:void 0,databaseName=fileNameLC in databaseFileNameCI2CS?databaseFileNameCI2CS[fileNameLC]:void 0,doc=databaseName?databaseFileNameMap[databaseName]:void 0,pair={file,doc};pairs.push(pair)}log2(`Total files to synchronise: ${pairs.length}`,LOG_LEVEL_VERBOSE,"syncAll");let completedCount=0,skippedCount=0,failedCount=0,processedCount=0;for await(const result of withConcurrency(pairs,async e3=>{try{return await processFilePair(host,log2,e3,options)}catch(ex){log2("Error while synchronising files",LOG_LEVEL_NOTICE);log2(ex,LOG_LEVEL_VERBOSE);return FilePairProcessResults_FAILED}},10)){processedCount++;switch(result){case FilePairProcessResults_COMPLETED:completedCount++;break;case FilePairProcessResults_SKIPPED:skippedCount++;break;case FilePairProcessResults_FAILED:failedCount++;break}processedCount%25==0&&log2(`Processing: ${processedCount}/${pairs.length}`,showingNotice?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,"syncAll")}log2(`Synchronisation completed: ${processedCount} files processed (${completedCount} completed, ${skippedCount} skipped, ${failedCount} failed)`,showingNotice?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,"syncAll");saveFileStatus(host,!0);return 0===failedCount}function normaliseFullScanOptions(showingNoticeOrOptions,ignoreSuspending=!1){return"object"==typeof showingNoticeOrOptions?{mode:FullScanModes_NEWER_WINS,...showingNoticeOrOptions}:{mode:FullScanModes_NEWER_WINS,showingNotice:null!=showingNoticeOrOptions&&showingNoticeOrOptions,ignoreSuspending}}async function loadFileStatus(host){await serialized(FILE_STATUS_MAP_LOCK,async()=>{const kvDB=host.services.keyValueDB.kvDB;if(!(null==kvDB?void 0:kvDB.get)){fileMaps=new Map;return}const mapItems=await kvDB.get(FILE_STATUS_MAP_KEY)||{};fileMaps=new Map(Object.entries(mapItems))})}async function _saveFileStatus(host){await serialized(FILE_STATUS_MAP_LOCK,async()=>{const kvDB=host.services.keyValueDB.kvDB;(null==kvDB?void 0:kvDB.set)&&await kvDB.set(FILE_STATUS_MAP_KEY,Object.fromEntries(fileMaps))})}async function clearOfflineScannerLastSeen(host,path2){const key3=convertCase(host.services.setting.currentSettings(),path2);if(null!==saveFileStatusTimeout){compatGlobal.clearTimeout(saveFileStatusTimeout);saveFileStatusTimeout=null}await serialized(FILE_STATUS_MAP_LOCK,async()=>{fileMaps.delete(key3);const kvDB=host.services.keyValueDB.kvDB;if(!(null==kvDB?void 0:kvDB.set))return;const persisted=kvDB.get?await kvDB.get(FILE_STATUS_MAP_KEY)||{}:Object.fromEntries(fileMaps),next2={...persisted,...Object.fromEntries(fileMaps)};delete next2[key3];await kvDB.set(FILE_STATUS_MAP_KEY,next2)})}function saveFileStatus(host,immediate=!1){if(immediate){null!==saveFileStatusTimeout&&compatGlobal.clearTimeout(saveFileStatusTimeout);saveFileStatusTimeout=compatGlobal.setTimeout(()=>{saveFileStatusTimeout=null;_saveFileStatus(host)},0)}else null===saveFileStatusTimeout&&(saveFileStatusTimeout=compatGlobal.setTimeout(()=>{saveFileStatusTimeout=null;_saveFileStatus(host)},1e3))}function updateFileMTimeInMap(host,key3,mtime){fileMaps.set(key3,mtime);saveFileStatus(host)}function getFileMTimeFromMap(key3){return fileMaps.get(key3)}async function performFullScan(host,log2,errorManager,showingNoticeOrOptions=!1,ignoreSuspending=!1){var _a13,_b6;const options=normaliseFullScanOptions(showingNoticeOrOptions,ignoreSuspending),showingNotice=null!=(_a13=options.showingNotice)&&_a13,shouldIgnoreSuspending=null!=(_b6=options.ignoreSuspending)&&_b6;if(!canProceedScan(host,errorManager,0,showingNotice,shouldIgnoreSuspending))return!1;log2("Opening the key-value database",LOG_LEVEL_VERBOSE);const isInitialized=await host.services.keyValueDB.kvDB.get("initialized")||!1;showingNotice&&log2("Initializing",LOG_LEVEL_NOTICE,"syncAll");if(isInitialized){log2("Restoring storage state",LOG_LEVEL_VERBOSE);await host.serviceModules.storageAccess.restoreState()}log2("Initialize and checking database files");log2("Checking deleted files");await collectDeletedFiles(host,log2);const scanResult=await synchroniseAllFilesBetweenDBandStorage(host,log2,0,options);log2("Initialized, NOW TRACKING!");isInitialized||await host.services.keyValueDB.kvDB.set("initialized",!0);showingNotice&&log2("Initialize done!",LOG_LEVEL_NOTICE,"syncAll");return scanResult}function useOfflineScanner(host){const log2=createInstanceLogFunction("SF:OfflineScanner",host.services.API),errorManager=new UnresolvedErrorManager(host.services.appLifecycle,host.services.context.events);host.services.vault.scanVault.addHandler(async(showingNotice,ignoreSuspending=!1)=>await performFullScan(host,log2,errorManager,showingNotice,ignoreSuspending))}function metadataIdentityPathKey(path2,handleFilenameCaseSensitive){const vaultPath=stripAllPrefixes(path2);return handleFilenameCaseSensitive?vaultPath:vaultPath.toLowerCase()}function selectUnresolvedMetadataIdentityEntries(entries2,handleFilenameCaseSensitive){return{entries:[...entries2],unresolvedPathKeys:new Set(entries2.filter(({ordinaryPathAvailable})=>!ordinaryPathAvailable).map(({inspection})=>metadataIdentityPathKey(inspection.diagnostic.declaredPath,handleFilenameCaseSensitive)))}}async function executeMetadataIdentityRepair(request2,dependencies){if(!await dependencies.confirm())return{status:MetadataIdentityRepairExecutions_CANCELLED};const result=await dependencies.repair(request2);if(result.status!==MetadataDocumentRepairResults_COMPLETED)return{status:MetadataIdentityRepairExecutions_REPAIR_RESULT,result,scanCompleted:!1};try{const scanCompleted=await dependencies.requestOrdinaryScan();return{status:MetadataIdentityRepairExecutions_REPAIR_RESULT,result,scanCompleted}}catch(scanError){return{status:MetadataIdentityRepairExecutions_REPAIR_RESULT,result,scanCompleted:!1,scanError}}}function paneHatch(paneEl,{addPanel}){addPanel(paneEl,$msg("Setting.TroubleShooting")).then(paneEl2=>{new LiveSyncSetting(paneEl2).setName($msg("Setting.TroubleShooting.Doctor")).setDesc($msg("Setting.TroubleShooting.Doctor.Desc")).addButton(button=>button.setButtonText($msg("Run Doctor")).setCta().setDisabled(!1).onClick(()=>{this.closeSetting();eventHub.emitEvent(EVENT_REQUEST_RUN_DOCTOR,"you wanted(Thank you)!")}));new LiveSyncSetting(paneEl2).setName($msg("Setting.TroubleShooting.ScanBrokenFiles")).setDesc($msg("Setting.TroubleShooting.ScanBrokenFiles.Desc")).addButton(button=>button.setButtonText("Scan for Broken files").setCta().setDisabled(!1).onClick(()=>{this.closeSetting();eventHub.emitEvent(EVENT_REQUEST_RUN_FIX_INCOMPLETE)}));new LiveSyncSetting(paneEl2).setName($msg("Prepare the 'report' to create an issue")).addButton(button=>button.setButtonText($msg("Copy Report to clipboard")).setCta().setDisabled(!1).onClick(async()=>{await this.app.commands.executeCommandById("obsidian-livesync:dump-debug-info")}));new LiveSyncSetting(paneEl2).setName($msg("Copy database information for a file")).setDesc($msg("Copy revision, conflict, and local chunk availability information, including document and chunk identifiers but not file contents.")).addButton(button=>button.setButtonText($msg("Choose file")).onClick(async()=>{await chooseAndCopyFileDatabaseInfo(this.core)}));new LiveSyncSetting(paneEl2).setName($msg("Analyse database usage")).setDesc($msg("Analyse database usage and generate a TSV report for diagnosis yourself. You can paste the generated report with any spreadsheet you like.")).addButton(button=>button.setButtonText($msg("Analyse")).onClick(()=>{eventHub.emitEvent(EVENT_ANALYSE_DB_USAGE)}));new LiveSyncSetting(paneEl2).setName($msg("Reset notification threshold and check the remote database usage")).setDesc($msg("Reset the remote storage size threshold and check the remote storage size again.")).addButton(button=>button.setButtonText($msg("Check")).onClick(()=>{eventHub.emitEvent(EVENT_REQUEST_CHECK_REMOTE_SIZE)}));new LiveSyncSetting(paneEl2).autoWireToggle("writeLogToTheFile")});addPanel(paneEl,"Scram Switches").then(paneEl2=>{new LiveSyncSetting(paneEl2).autoWireToggle("suspendFileWatching");this.addOnSaved("suspendFileWatching",()=>this.services.appLifecycle.askRestart());new LiveSyncSetting(paneEl2).autoWireToggle("suspendParseReplicationResult");this.addOnSaved("suspendParseReplicationResult",()=>this.services.appLifecycle.askRestart())});addPanel(paneEl,"Recovery and Repair").then(paneEl2=>{const resultArea=paneEl2.createDiv({text:"",cls:"sls-repair-results"}),addActionMenu=(parent,label2,actions)=>{0!==actions.length&&this.createEl(parent,"button",{cls:"sls-repair-action-menu"},button=>{(0,import_obsidian.setIcon)(button,"wrench");button.setAttr("aria-label",label2);button.setAttr("title",label2);button.onClickEvent(()=>{const menu=new import_obsidian.Menu;for(const action2 of actions)menu.addItem(item=>{item.setTitle(action2.title);action2.warning&&item.setWarning(!0);item.onClick(()=>{button.disabled=!0;Promise.resolve().then(()=>action2.run()).catch(error=>{Logger(error,LOG_LEVEL_VERBOSE);Logger(`Repair action '${action2.title}' failed`,LOG_LEVEL_NOTICE)}).finally(()=>{button.isConnected&&(button.disabled=!1)})})});const rect=button.getBoundingClientRect();menu.showAtPosition({x:rect.left,y:rect.bottom})})})},addMetadataIdentityResult=entry=>{var _a13;const{diagnostic}=entry.inspection,card=this.createEl(resultArea,"div",{cls:"sls-repair-result"});this.createEl(card,"h6",{text:diagnostic.declaredPath});this.createEl(card,"div",{text:$msg("Metadata entry requires review and was left unchanged"),cls:"sls-repair-status-warning"});this.createEl(card,"div",{text:diagnostic.reason===OfflineScanUnresolvedReasons_DOCUMENT_ID_MISMATCH?$msg("The stored document ID does not match the ID derived from its recorded path."):$msg("The stored document ID and recorded path are handled by different synchronisation features."),cls:"sls-repair-metric"});this.createEl(card,"div",{text:$msg("Stored document ID: ${ID}",{ID:diagnostic.actualDocumentId}),cls:"sls-repair-metric"});void 0!==diagnostic.expectedDocumentId&&this.createEl(card,"div",{text:$msg("Expected document ID: ${ID}",{ID:diagnostic.expectedDocumentId}),cls:"sls-repair-metric"});this.createEl(card,"div",{text:$msg("Source revision: ${REVISION}",{REVISION:null!=(_a13=entry.sourceRevision)?_a13:$msg("Unknown revision")}),cls:"sls-repair-metric"});entry.logicallyDeleted&&this.createEl(card,"div",{text:$msg("🗑️ Logical deletion"),cls:"sls-repair-metric mod-warning"});entry.conflictRevisions.length>0&&this.createEl(card,"div",{text:$msg("⚠️ Conflicts: ${COUNT}",{COUNT:`${entry.conflictRevisions.length}`}),cls:"sls-repair-metric mod-warning"});if(!entry.repairAvailable||void 0===diagnostic.expectedDocumentId||null===entry.sourceRevision){this.createEl(card,"div",{text:$msg("One-step repair is unavailable because this entry is ambiguous, no longer current, or unsafe to change."),cls:"sls-repair-metric mod-warning"});return}this.createEl(card,"div",{text:entry.targetAlreadyPresent?$msg("An exact target is already present; repair can remove the obsolete ID."):$msg("Repair is available for this entry."),cls:"sls-repair-status-ok"});const request2={actualDocumentId:diagnostic.actualDocumentId,expectedDocumentId:diagnostic.expectedDocumentId,sourceRevision:entry.sourceRevision},repairAction=$msg("Repair Metadata ID"),keepAction=$msg("Keep unchanged");addActionMenu(card,$msg("More actions for ${FILE}",{FILE:diagnostic.declaredPath}),[{title:$msg("Repair this Metadata document ID"),warning:!0,run:async()=>{const execution=await executeMetadataIdentityRepair(request2,{confirm:async()=>await this.core.confirm.confirmWithMessage($msg("Repair Metadata document ID"),$msg("This moves one local Metadata entry to the ID derived from its recorded path.\n\n**File:** `${FILE}` \n**Source:** `${SOURCE}@${REVISION}` \n**Target:** `${TARGET}`\n\nThe target is verified before the source is removed. Its CouchDB revision ancestry cannot be preserved.\n\n> [!warning] Before repairing\n> - Back up this device.\n> - If file-name case or path obfuscation was intentionally changed for the whole database, use Rebuild instead.\n> - If other devices share this database, pause them, allow this device to upload the repair, then resume them one at a time.",{FILE:escapeMarkdownValue(diagnostic.declaredPath),SOURCE:escapeMarkdownValue(diagnostic.actualDocumentId),REVISION:escapeMarkdownValue(entry.sourceRevision),TARGET:escapeMarkdownValue(diagnostic.expectedDocumentId)}),[repairAction,keepAction],keepAction,void 0,"vertical")===repairAction,repair:async repairRequest=>await repairMetadataDocumentIdentity(this.core,repairRequest),requestOrdinaryScan:async()=>await this.services.vault.scanVault(!0,!1)});if(execution.status===MetadataIdentityRepairExecutions_CANCELLED)return;const result=execution.result;result.message&&Logger(result.message,LOG_LEVEL_VERBOSE);if(result.status===MetadataDocumentRepairResults_COMPLETED){void 0!==execution.scanError&&Logger(execution.scanError,LOG_LEVEL_VERBOSE);resultArea.replaceChildren();this.createEl(resultArea,"div",{text:execution.scanCompleted?$msg("Metadata document ID repair and the ordinary Vault scan completed. Run this inspection again after synchronisation."):$msg("Metadata document ID repair completed, but the ordinary Vault scan did not run. Keep synchronisation paused, resolve the scan condition, then run 'Scan storage and database again'."),cls:execution.scanCompleted?"sls-repair-status-ok":"sls-repair-metric mod-warning"});return}const resultMessage=result.status===MetadataDocumentRepairResults_STALE||result.status===MetadataDocumentRepairResults_BLOCKED?$msg("The inspected state changed. No repair was performed; run inspection again."):result.targetCreated?$msg("Repair stopped after creating the target. The source was retained. Run inspection again before retrying."):$msg("Repair failed before the source was removed. Run inspection again before retrying.");this.createEl(card,"div",{text:resultMessage,cls:"sls-repair-metric mod-warning"})}}])},findHiddenFile=async path2=>{const addOn=this.core.getAddOn(HiddenFileSync.name);if(!addOn)return!1;const file=(await addOn.scanInternalFiles()).find(entry=>entry.path===path2);if(!file){Logger(`Failed to find the file in the internal files: ${path2}`,LOG_LEVEL_NOTICE);return!1}return{addOn,file}},storeStorageInDatabase=async path2=>{if(path2.startsWith(".")){const hidden=await findHiddenFile(path2);return!!hidden&&Boolean(await hidden.addOn.storeInternalFileToDatabase(hidden.file,!0))}return Boolean(await this.core.fileHandler.storeFileToDB(path2,!0))},storeStorageOnRevision=async(path2,revision,createIfDifferent=!0)=>{if(path2.startsWith(".")){const hidden=await findHiddenFile(path2);return!!hidden&&Boolean(await hidden.addOn.storeInternalFileToDatabaseWithBaseRevision(hidden.file,revision,createIfDifferent))}return Boolean(await this.core.fileHandler.storeFileToDBWithBaseRevision(path2,revision,createIfDifferent))},applyRevisionToStorage=async(path2,revision,force)=>{if(path2.startsWith(".")){const addOn=this.core.getAddOn(HiddenFileSync.name);return!!addOn&&Boolean(await addOn.extractInternalFileRevisionFromDatabase(path2,revision,force))}return Boolean(await this.core.fileHandler.dbToStorageWithSpecificRev(path2,revision,force))},openRevisionComparison=async(path2,selectedRevision)=>{var _a13,_b6;const latest2=await inspectFileRepair(this.core,path2),revision=latest2.revisions.find(({metadata})=>metadata.revision===selectedRevision);if(!latest2.information.storage.exists||!revision||!1===revision.loadedEntry){Logger(`Could not compare ${path2} revision ${selectedRevision}; the Vault file or selected live revision is no longer readable`,LOG_LEVEL_NOTICE);return!1}const vaultText=await createBlob(await this.core.storageAccess.readHiddenFileBinary(path2)).text(),databaseText=await readAsBlob(revision.loadedEntry).text(),dmp=new import_diff_match_patch.diff_match_patch,diff=dmp.diff_main(vaultText,databaseText);dmp.diff_cleanupSemantic(diff);const result={left:{rev:"vault",data:vaultText,ctime:null!=(_a13=latest2.information.storage.ctime)?_a13:0,mtime:null!=(_b6=latest2.information.storage.mtime)?_b6:0},right:{rev:selectedRevision,data:databaseText,ctime:revision.metadata.ctime,mtime:revision.metadata.mtime},diff};new ConflictResolveModal(this.app,path2,result,!1,void 0,{readOnly:!0,title:$msg("Vault and database revision"),localName:$msg("Vault file"),remoteName:$msg("Database revision")}).open();return!0},formatSigned=value=>`${value>=0?"+":""}${value}`,timestampRelationLabel=relation=>{switch(relation){case"vault-newer":return $msg("Vault file is newer");case"database-newer":return $msg("Database revision is newer");case"same-window":return $msg("Within the two-second comparison window");default:return $msg("Timestamp comparison unavailable")}},addRepairResult=inspection=>{var _a13,_b6;const{information,revisions}=inspection,path2=information.path,card=this.createEl(resultArea,"div",{cls:"sls-repair-result"}),refresh=async()=>{card.remove();const refreshed=await inspectFileRepair(this.core,path2);refreshed.requiresAttention?addRepairResult(refreshed):Logger(`Verification no longer reports a problem for ${path2}`,LOG_LEVEL_NOTICE)},runMutation=async(description,mutation)=>{try{const succeeded=await mutation();succeeded||Logger(`${description} failed: ${path2}`,LOG_LEVEL_NOTICE)}finally{await refresh()}},discardLiveBranchAction=revision=>({title:$msg("Discard this branch"),warning:!0,run:async()=>{const confirmed="yes"===await this.core.confirm.askYesNoDialog($msg("Discard database branch ${REVISION} of ${FILE}? This creates a logical deletion for that exact live branch. The current Vault file will not be changed.",{REVISION:revision,FILE:path2}),{title:$msg("Discard branch"),defaultOption:"No"});if(!confirmed)return;const result=await discardLiveBranch(this.core,path2,revision);Logger(`Discard database branch ${revision} of ${path2}: ${result}`,"discarded"===result?LOG_LEVEL_NOTICE:LOG_LEVEL_VERBOSE);await refresh()}}),fileHeader=this.createEl(card,"div",{cls:"sls-repair-header"});this.createEl(fileHeader,"h6",{text:path2});const fileMenuHost=this.createEl(fileHeader,"div");information.storage.exists?this.createEl(card,"div",{text:$msg("📁 Vault: ${SIZE} B · ${TIME}",{TIME:new Date(null!=(_a13=information.storage.mtime)?_a13:0).toLocaleString(),SIZE:`${null!=(_b6=information.storage.size)?_b6:0}`}),cls:"sls-repair-metric"}):this.createEl(card,"div",{text:$msg("📁 Vault: missing"),cls:"sls-repair-metric"});information.database.exists||this.createEl(card,"div",{text:$msg("🗄️ Local DB: missing"),cls:"sls-repair-metric"});if(information.database.conflictCount>0){const winner2=revisions.find(({role})=>"winner"===role),vaultMatchesWinner=void 0!==winner2&&(winner2.metadata.deleted?!information.storage.exists:information.storage.exists&&!0===winner2.contentMatchesStorage),status=this.createEl(card,"div",{cls:"sls-repair-status"});vaultMatchesWinner&&this.createEl(status,"span",{text:$msg("✅ Vault matches winner"),cls:"sls-repair-status-ok"});this.createEl(status,"span",{text:$msg("⚠️ Conflicts: ${COUNT}",{COUNT:`${information.database.conflictCount}`}),cls:"sls-repair-status-warning"})}revisions.forEach(revision=>{var _a14,_b7,_c3,_d2;const{metadata}=revision,revisionEl=this.createEl(card,"div",{cls:"sls-repair-revision"}),revisionHeader=this.createEl(revisionEl,"div",{cls:"sls-repair-header"});this.createEl(revisionHeader,"div",{text:$msg("${ROLE}: ${REVISION}",{ROLE:"winner"===revision.role?$msg("Winner revision"):$msg("Conflict revision"),REVISION:null!=(_a14=metadata.revision)?_a14:$msg("Unknown revision")}),cls:"sls-repair-revision-title"});const revisionMenuHost=this.createEl(revisionHeader,"div"),comparison=getFileRepairRevisionComparison(inspection,revision);if(metadata.deleted)this.createEl(revisionEl,"div",{text:$msg("🗑️ Logical deletion"),cls:"sls-repair-metric"});else if(revision.contentReadable)this.createEl(revisionEl,"div",{text:$msg("📦 DB: recorded ${RECORDED} B · decoded ${DECODED} B · Δsize ${DIFFERENCE} B",{RECORDED:`${comparison.recordedSize}`,DECODED:`${null!=(_b7=comparison.decodedSize)?_b7:0}`,DIFFERENCE:formatSigned(null!=(_c3=comparison.recordedToDecodedSizeDifference)?_c3:0)}),cls:"sls-repair-metric"});else{const missing=metadata.chunks.filter(({embedded,localDatabaseState})=>!embedded&&"available"!==localDatabaseState);this.createEl(revisionEl,"div",{text:$msg("🧩 Missing chunks: ${COUNT}",{COUNT:`${missing.length}`}),cls:"sls-repair-metric mod-warning"});this.createEl(revisionEl,"div",{text:$msg("📦 DB: recorded ${RECORDED} B · decoded unavailable",{RECORDED:`${comparison.recordedSize}`}),cls:"sls-repair-metric"});missing.length>0&&this.createEl(revisionEl,"code",{text:missing.slice(0,3).map(({id})=>id).join(", ")+(missing.length>3?", …":"")})}null!==comparison.vaultSize&&null!==comparison.databaseToVaultSizeDifference&&this.createEl(revisionEl,"div",{text:$msg("📁 Vault: ${VAULT} B · Δsize vs DB ${DIFFERENCE} B",{VAULT:`${comparison.vaultSize}`,DIFFERENCE:formatSigned(comparison.databaseToVaultSizeDifference)}),cls:"sls-repair-metric"});null!==comparison.vaultMtime&&null!==comparison.timestampDifferenceMs&&this.createEl(revisionEl,"div",{text:$msg("🕒 DB ${DATABASE_TIME} · Vault ${VAULT_TIME} · Δtime ${DIFFERENCE} ms (${RELATION})",{DATABASE_TIME:new Date(comparison.databaseMtime).toLocaleString(),VAULT_TIME:new Date(comparison.vaultMtime).toLocaleString(),DIFFERENCE:formatSigned(comparison.timestampDifferenceMs),RELATION:timestampRelationLabel(comparison.timestampRelation)}),cls:"sls-repair-metric"});!0===revision.contentMatchesStorage?this.createEl(revisionEl,"div",{text:$msg("✅ Matches Vault"),cls:"sls-repair-metric"}):!1===revision.contentMatchesStorage&&this.createEl(revisionEl,"div",{text:$msg("⚠️ Differs from Vault"),cls:"sls-repair-metric mod-warning"});const policy2=getFileRepairRevisionActions(inspection,revision),revisionActions=[];metadata.revision&&policy2.compareWithVault&&revisionActions.push({title:$msg("Compare with Vault"),run:async()=>{await openRevisionComparison(path2,metadata.revision)}});metadata.revision&&policy2.applyRevisionToVault&&revisionActions.push({title:$msg("Apply this revision to Vault"),run:async()=>{if(await this.core.storageAccess.isExistsIncludeHidden(path2)){const confirmed="yes"===await this.core.confirm.askYesNoDialog($msg("Apply database revision ${REVISION} to ${FILE}? The current Vault file will be overwritten.",{REVISION:metadata.revision,FILE:path2}),{title:$msg("Apply database revision to Vault"),defaultOption:"No"});if(!confirmed)return}await runMutation(`Apply database revision ${metadata.revision} to the Vault`,()=>applyRevisionToStorage(path2,metadata.revision,!0))}});metadata.revision&&policy2.markAsVaultRevision&&revisionActions.push({title:$msg("Mark this revision as the Vault version"),run:async()=>{await runMutation(`Mark database revision ${metadata.revision} as the Vault version`,()=>storeStorageOnRevision(path2,metadata.revision,!1))}});metadata.revision&&policy2.storeVaultOnBranch&&revisionActions.push({title:$msg("Store Vault file as a child of this revision"),run:async()=>{await runMutation(`Store the Vault file on database revision ${metadata.revision}`,()=>storeStorageOnRevision(path2,metadata.revision))}});metadata.revision&&policy2.applyLogicalDeletionToVault&&revisionActions.push({title:$msg("Apply logical deletion to Vault"),warning:!0,run:async()=>{if(await this.core.storageAccess.isExistsIncludeHidden(path2)){const confirmed="yes"===await this.core.confirm.askYesNoDialog($msg("Apply logical deletion ${REVISION} to ${FILE}? The current Vault file will be removed.",{REVISION:metadata.revision,FILE:path2}),{title:$msg("Apply logical deletion to Vault"),defaultOption:"No"});if(!confirmed)return}await runMutation(`Apply logical deletion ${metadata.revision} to the Vault`,()=>applyRevisionToStorage(path2,metadata.revision,!0))}});metadata.revision&&policy2.retryRevision&&revisionActions.push({title:$msg("Retry reading revision"),run:async()=>{const loaded=await retryReadFileDatabaseRevision(this.core,path2,metadata.revision);Logger(loaded?`Revision ${metadata.revision} of ${path2} is readable after retry`:`Revision ${metadata.revision} of ${path2} remains unreadable`,LOG_LEVEL_NOTICE);await refresh()}});metadata.revision&&policy2.discardBranch&&revisionActions.push(discardLiveBranchAction(metadata.revision));metadata.revision&&policy2.discardRevision&&revisionActions.push({title:$msg("Discard unreadable revision"),warning:!0,run:async()=>{const confirmed="yes"===await this.core.confirm.askYesNoDialog($msg("Discard database revision ${REVISION} of ${FILE}? This creates a logical deletion for that exact live revision. Missing content cannot be recovered by this action.",{REVISION:metadata.revision,FILE:path2}),{title:$msg("Discard unreadable revision"),defaultOption:"No"});if(!confirmed)return;const result=await discardUnreadableLiveRevision(this.core,path2,metadata.revision);Logger(`Discard unreadable revision ${metadata.revision} of ${path2}: ${result}`,"discarded"===result?LOG_LEVEL_NOTICE:LOG_LEVEL_VERBOSE);await refresh()}});addActionMenu(revisionMenuHost,$msg("More actions for revision ${REVISION}",{REVISION:null!=(_d2=metadata.revision)?_d2:$msg("Unknown revision")}),revisionActions)});for(const revision of information.database.unavailableConflictRevisions){const revisionEl=this.createEl(card,"div",{cls:"sls-repair-revision"}),revisionHeader=this.createEl(revisionEl,"div",{cls:"sls-repair-header"});this.createEl(revisionHeader,"div",{text:$msg("${ROLE}: ${REVISION}",{ROLE:$msg("Conflict revision"),REVISION:revision}),cls:"sls-repair-revision-title"});const revisionMenuHost=this.createEl(revisionHeader,"div");this.createEl(revisionEl,"div",{text:$msg("Revision metadata is unavailable on this device"),cls:"mod-warning"});addActionMenu(revisionMenuHost,$msg("More actions for revision ${REVISION}",{REVISION:revision}),[{title:$msg("Retry reading revision"),run:async()=>{await retryReadFileDatabaseRevision(this.core,path2,revision);await refresh()}},discardLiveBranchAction(revision)])}for(const base of information.database.mergeBases)base.contentAvailableLocally||this.createEl(card,"div",{text:base.revision?$msg("Shared ancestor ${REVISION} is not readable on this device. Automatic three-way merging may be unavailable, but the live revisions remain available for explicit review.",{REVISION:base.revision}):$msg("No shared ancestor is available for this conflict. The live revisions remain available for explicit review."),cls:"sls-repair-ancestor-warning"});const winner=revisions.find(({role})=>"winner"===role),fileActions=[];if(null==winner?void 0:winner.loadedEntry){const winnerEntry=winner.loadedEntry;fileActions.push({title:$msg("Show revision history"),run:()=>{eventHub.emitEvent(EVENT_REQUEST_SHOW_HISTORY,{file:path2,fileOnDB:winnerEntry})}})}information.storage.exists&&!information.database.exists&&fileActions.push({title:$msg("Store Vault file as a new local database document"),run:async()=>{await runMutation("Store the Vault file as a new local database document",()=>storeStorageInDatabase(path2))}});fileActions.push({title:$msg("Copy database information"),run:async()=>{await copyFileDatabaseInfo(this.core,path2)}});addActionMenu(fileMenuHost,$msg("More actions for ${FILE}",{FILE:path2}),fileActions)};new LiveSyncSetting(paneEl2).setName($msg("Recreate chunks for current Vault files")).setDesc($msg("Recreate chunks from the files currently present in this Vault. This cannot reconstruct unavailable historical or conflict content.")).addButton(button=>button.setButtonText($msg("Recreate current chunks")).setCta().onClick(async()=>{await this.core.fileHandler.createAllChunks(!0)}));new LiveSyncSetting(paneEl2).setName($msg("Inspect conflicts and file/database differences")).setDesc($msg("Scan Vault files and local-database Metadata for conflicts, missing chunks, identity mismatches, and differences. Each result provides actions for one exact entry or revision.")).addButton(button=>button.setButtonText($msg("Begin inspection")).setDisabled(!1).setCta().onClick(async()=>{resultArea.replaceChildren();Logger("Start inspecting file/database state",LOG_LEVEL_NOTICE,"verify");this.core.localDatabase.clearCaches();const identityEntries=await inspectMetadataDocumentIdentities(this.core),handleFilenameCaseSensitive=this.core.settings.handleFilenameCaseSensitive,unresolvedIdentity=selectUnresolvedMetadataIdentityEntries(identityEntries,handleFilenameCaseSensitive);unresolvedIdentity.entries.forEach(addMetadataIdentityResult);const allPaths=await collectFileDatabaseInfoPaths(this.core);let i3=0;const incProc=()=>{i3++;i3%25==0&&Logger(`Checking ${i3}/${allPaths.length} files \n`,LOG_LEVEL_NOTICE,"verify-processed")},semaphore=Semaphore(10),processes=allPaths.map(async path2=>{try{if(unresolvedIdentity.unresolvedPathKeys.has(metadataIdentityPathKey(path2,handleFilenameCaseSensitive)))return incProc();if(shouldBeIgnored(path2))return incProc();const stat=!!await this.core.storageAccess.isExistsIncludeHidden(path2)&&await this.core.storageAccess.statHidden(path2),fileOnStorage=null!=stat&&stat;if(!await this.services.vault.isTargetFile(path2))return incProc();if(fileOnStorage&&this.services.vault.isFileSizeTooLarge(fileOnStorage.size))return incProc();const releaser=await semaphore.acquire(1);try{const inspection=await inspectFileRepair(this.core,path2),winner=inspection.revisions.find(({role})=>"winner"===role);if(winner&&this.services.vault.isFileSizeTooLarge(winner.metadata.recordedSize))return incProc();inspection.requiresAttention?addRepairResult(inspection):Logger(`Compare: SAME: ${path2}`)}catch(ex){Logger(`Error while processing ${path2}`,LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_VERBOSE)}finally{releaser();incProc()}}catch(ex){Logger(`Error while processing without semaphore ${path2}`,LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_VERBOSE)}});await Promise.all(processes);Logger("done",LOG_LEVEL_NOTICE,"verify")}));new LiveSyncSetting(paneEl2).setName("Resolve All conflicted files by the newer one").setDesc("Resolve all conflicted files by the newer one. Caution: This will overwrite the older one, and cannot resurrect the overwritten one.").addButton(button=>button.setButtonText("Resolve All").setCta().onClick(async()=>{const confirmed="yes"===await this.core.confirm.askYesNoDialog($msg("Resolve every conflict by modification time? This logically deletes every version except the newest one and cannot recover content which is already unavailable."),{title:$msg("Resolve all conflicts by the newest version"),defaultOption:"No"});confirmed&&await this.services.conflict.resolveAllConflictedFilesByNewerOnes()}));new LiveSyncSetting(paneEl2).setName("Check and convert non-path-obfuscated files").setDesc("").addButton(button=>setButtonDestructiveState(button).setButtonText("Perform").setDisabled(!1).onClick(async()=>{var _a13,_b6,_c3;for await(const docName of this.core.localDatabase.findAllDocNames())if(!docName.startsWith("f:")){const idEncoded=await this.services.path.path2id(docName),doc=await this.core.localDatabase.getRaw(docName);if(!doc)continue;if("newnote"!=doc.type&&"plain"!=doc.type)continue;if(null!=(_a13=null==doc?void 0:doc.deleted)&&_a13)continue;const newDoc={...doc};newDoc._id=idEncoded;newDoc.path=docName;delete newDoc._rev;try{const obfuscatedDoc=await this.core.localDatabase.getRaw(idEncoded,{revs_info:!0});null==(_b6=obfuscatedDoc._revs_info)||_b6.shift();const previousRev=null==(_c3=obfuscatedDoc._revs_info)?void 0:_c3.shift();newDoc._rev=previousRev?previousRev.rev:"1-"+`00000000000000000000000000000000${~~(1e9*Math.random())}${~~(1e9*Math.random())}${~~(1e9*Math.random())}${~~(1e9*Math.random())}`.slice(-32);const ret=await this.core.localDatabase.putRaw(newDoc,{force:!0});if(ret.ok){Logger(`${docName} has been converted as conflicted document`,LOG_LEVEL_NOTICE);doc._deleted=!0;(await this.core.localDatabase.putRaw(doc)).ok&&Logger(`Old ${docName} has been deleted`,LOG_LEVEL_NOTICE);await this.services.conflict.queueCheckForIfOpen(docName)}else{Logger(`Converting ${docName} Failed!`,LOG_LEVEL_NOTICE);Logger(ret,LOG_LEVEL_VERBOSE)}}catch(ex){if(isNotFoundError(ex)){if((await this.core.localDatabase.putRaw(newDoc)).ok){Logger(`${docName} has been converted`,LOG_LEVEL_NOTICE);doc._deleted=!0;(await this.core.localDatabase.putRaw(doc)).ok&&Logger(`Old ${docName} has been deleted`,LOG_LEVEL_NOTICE)}}else{Logger(`Something went wrong while converting ${docName}`,LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_VERBOSE)}}}Logger("Converting finished",LOG_LEVEL_NOTICE)}))});addPanel(paneEl,"Reset").then(paneEl2=>{new LiveSyncSetting(paneEl2).setName("Back to non-configured").addButton(button=>button.setButtonText("Back").setDisabled(!1).onClick(async()=>{this.editingSettings.isConfigured=!1;await this.saveAllDirtySettings();this.services.appLifecycle.askRestart()}));new LiveSyncSetting(paneEl2).setName("Delete all customization sync data").addButton(button=>setButtonDestructiveState(button).setButtonText("Delete").setDisabled(!1).onClick(async()=>{Logger("Deleting customization sync data",LOG_LEVEL_NOTICE);const entriesToDelete=await this.core.localDatabase.allDocsRaw({startkey:"ix:",endkey:"ix:􏿿",include_docs:!0}),newData=entriesToDelete.rows.map(e3=>({...e3.doc,_deleted:!0})),r4=await this.core.localDatabase.bulkDocsRaw(newData);Logger(`${r4.length} items have been removed, to confirm how many items are left, please perform it again.`,LOG_LEVEL_NOTICE)}))})}function createEditingSettingsAfterFullReset(editingSettings){return{...editingSettings,...createNewVaultSettings(),isConfigured:!1}}function createCoreSettingsAfterFullReset(){return{...createNewVaultSettings(),isConfigured:!1}}function paneMaintenance(paneEl,{addPanel}){this.createEl(paneEl,"div",{text:"The remote database is locked for synchronization to prevent vault corruption because this device isn't marked as 'resolved'. Please backup your vault, reset the local database, and select 'Mark this device as resolved'. This warning will persist until the device is confirmed as resolved by replication.",cls:"op-warn"},c3=>{this.createEl(c3,"button",{text:"I've made a backup, mark this device 'resolved'",cls:"mod-warning"},e3=>{e3.addEventListener("click",()=>{fireAndForget(async()=>{await this.services.replication.markResolved();this.requestPageRefresh()})})})},visibleOnly(()=>{var _a13,_b6;return null==(_b6=null==(_a13=this.core)?void 0:_a13.replicator)?void 0:_b6.remoteLockedAndDeviceNotAccepted}));this.createEl(paneEl,"div",{text:"To prevent unwanted vault corruption, the remote database has been locked for synchronization. (This device is marked 'resolved') When all your devices are marked 'resolved', unlock the database. This warning kept showing until confirming the device is resolved by the replication",cls:"op-warn"},c3=>this.createEl(c3,"button",{text:"I'm ready, unlock the database",cls:"mod-warning"},e3=>{e3.addEventListener("click",()=>{fireAndForget(async()=>{await this.services.replication.markUnlocked();this.requestPageRefresh()})})}),visibleOnly(()=>{var _a13,_b6;return null==(_b6=null==(_a13=this.core)?void 0:_a13.replicator)?void 0:_b6.remoteLocked}));addPanel(paneEl,"Scram!").then(paneEl2=>{new LiveSyncSetting(paneEl2).setName("Lock Server").setDesc("Lock the remote server to prevent synchronization with other devices.").addButton(button=>setButtonDestructiveState(button).setButtonText("Lock").setDisabled(!1).onClick(async()=>{await this.services.replication.markLocked()})).addOnUpdate(this.onlyOnCouchDBOrMinIO);new LiveSyncSetting(paneEl2).setName("Emergency restart").setDesc("Disables all synchronization and restart.").addButton(button=>setButtonDestructiveState(button).setButtonText("Flag and restart").setDisabled(!1).onClick(async()=>{await this.core.storageAccess.writeFileAuto(FlagFilesOriginal_SUSPEND_ALL,"");this.services.appLifecycle.performRestart()}))});addPanel(paneEl,"Reset Synchronisation information").then(paneEl2=>{new LiveSyncSetting(paneEl2).setName("Reset Synchronisation on This Device").setDesc("Restore or reconstruct local database from remote.").addButton(button=>button.setButtonText("Schedule and Restart").setCta().setDisabled(!1).onClick(async()=>{await this.core.storageAccess.writeFileAuto(FlagFilesHumanReadable_FETCH_ALL,"");this.services.appLifecycle.performRestart()}));new LiveSyncSetting(paneEl2).setName("Overwrite Server Data with This Device's Files").setDesc("Rebuild local and remote database with local files.").addButton(button=>button.setButtonText("Schedule and Restart").setCta().setDisabled(!1).onClick(async()=>{await this.core.storageAccess.writeFileAuto(FlagFilesHumanReadable_REBUILD_ALL,"");this.services.appLifecycle.performRestart()}))});addPanel(paneEl,"Syncing",()=>{},this.onlyOnCouchDBOrMinIO).then(paneEl2=>{new LiveSyncSetting(paneEl2).setName("Resend").setDesc("Resend all chunks to the remote.").addButton(button=>setButtonDestructiveState(button).setButtonText("Send chunks").setDisabled(!1).onClick(async()=>{this.core.replicator instanceof LiveSyncCouchDBReplicator&&await this.core.replicator.sendChunks(this.core.settings,void 0,!0,0)})).addOnUpdate(this.onlyOnCouchDB);new LiveSyncSetting(paneEl2).setName("Reset journal received history").setDesc("Initialise journal received history. On the next sync, every item except this device sent will be downloaded again.").addButton(button=>setButtonDestructiveState(button).setButtonText("Reset received").setDisabled(!1).onClick(async()=>{await this.getMinioJournalSyncClient().updateCheckPointInfo(info3=>({...info3,receivedFiles:new Set,knownIDs:new Set}));Logger("Journal received history has been cleared.",LOG_LEVEL_NOTICE)})).addOnUpdate(this.onlyOnMinIO);new LiveSyncSetting(paneEl2).setName("Reset journal sent history").setDesc("Initialise journal sent history. On the next sync, every item except this device received will be sent again.").addButton(button=>setButtonDestructiveState(button).setButtonText("Reset sent history").setDisabled(!1).onClick(async()=>{await this.getMinioJournalSyncClient().updateCheckPointInfo(info3=>({...info3,lastLocalSeq:0,sentIDs:new Set,sentFiles:new Set}));Logger("Journal sent history has been cleared.",LOG_LEVEL_NOTICE)})).addOnUpdate(this.onlyOnMinIO)});addPanel(paneEl,"Garbage Collection V3 (Beta)",e3=>e3,this.onlyOnCouchDB).then(paneEl2=>{new LiveSyncSetting(paneEl2).setName("Perform Garbage Collection").setDesc("Perform Garbage Collection to remove unused chunks and reduce database size.").addButton(button=>button.setButtonText("Perform Garbage Collection").setDisabled(!1).onClick(()=>{this.closeSetting();eventHub.emitEvent(EVENT_REQUEST_PERFORM_GC_V3)}))});addPanel(paneEl,"Rebuilding Operations (Remote Only)",()=>{},this.onlyOnCouchDBOrMinIO).then(paneEl2=>{new LiveSyncSetting(paneEl2).setName("Perform cleanup").setDesc("Reduces storage space by discarding all non-latest revisions. This requires the same amount of free space on the remote server and the local client.").addButton(button=>button.setButtonText("Perform").setDisabled(!1).onClick(async()=>{const replicator=this.core.replicator;Logger("Cleanup has been began",LOG_LEVEL_NOTICE,"compaction");await replicator.compactRemote(this.editingSettings)?Logger("Cleanup has been completed!",LOG_LEVEL_NOTICE,"compaction"):Logger("Cleanup has been failed!",LOG_LEVEL_NOTICE,"compaction")})).addOnUpdate(this.onlyOnCouchDB);new LiveSyncSetting(paneEl2).setName("Overwrite remote").setDesc("Overwrite remote with local DB and passphrase.").addButton(button=>setButtonDestructiveState(button).setButtonText("Send").setDisabled(!1).onClick(async()=>{await this.rebuildDB("remoteOnly")}));new LiveSyncSetting(paneEl2).setName("Reset all journal counter").setDesc("Initialise all journal history, On the next sync, every item will be received and sent.").addButton(button=>setButtonDestructiveState(button).setButtonText("Reset all").setDisabled(!1).onClick(async()=>{await this.getMinioJournalSyncClient().resetCheckpointInfo();Logger("Journal exchange history has been cleared.",LOG_LEVEL_NOTICE)})).addOnUpdate(this.onlyOnMinIO);new LiveSyncSetting(paneEl2).setName("Purge all journal counter").setDesc("Purge all download/upload cache.").addButton(button=>setButtonDestructiveState(button).setButtonText("Reset all").setDisabled(!1).onClick(()=>{this.getMinioJournalSyncClient().resetAllCaches();Logger("Journal download/upload cache has been cleared.",LOG_LEVEL_NOTICE)})).addOnUpdate(this.onlyOnMinIO);new LiveSyncSetting(paneEl2).setName("Fresh Start Wipe").setDesc("Delete all data on the remote server.").addButton(button=>setButtonDestructiveState(button).setButtonText("Delete").setDisabled(!1).onClick(async()=>{await this.getMinioJournalSyncClient().updateCheckPointInfo(info3=>({...info3,receivedFiles:new Set,knownIDs:new Set,lastLocalSeq:0,sentIDs:new Set,sentFiles:new Set}));await this.resetRemoteBucket();Logger("Deleted all data on remote server",LOG_LEVEL_NOTICE)})).addOnUpdate(this.onlyOnMinIO)});addPanel(paneEl,"Reset").then(paneEl2=>{new LiveSyncSetting(paneEl2).setName($msg("obsidianLiveSyncSettingTab.nameDiscardSettings")).addButton(button=>{setButtonDestructiveState(button).setButtonText($msg("obsidianLiveSyncSettingTab.btnDiscard")).onClick(async()=>{if("yes"===await this.core.confirm.askYesNoDialog($msg("obsidianLiveSyncSettingTab.msgDiscardConfirmation"),{defaultOption:"No"})){this.editingSettings=createEditingSettingsAfterFullReset(this.editingSettings);await this.saveAllDirtySettings();this.core.settings=createCoreSettingsAfterFullReset();await this.services.setting.saveSettingData();await this.services.database.resetDatabase();this.services.appLifecycle.askRestart()}})}).addOnUpdate(visibleOnly(()=>this.isConfiguredAs("isConfigured",!0)));new LiveSyncSetting(paneEl2).setName("Delete local database to reset or uninstall Self-hosted LiveSync").addButton(button=>setButtonDestructiveState(button).setButtonText("Delete").setDisabled(!1).onClick(async()=>{await this.services.database.resetDatabase();await this.services.databaseEvents.initialiseDatabase()}))})}function paneHelp(paneEl,{addPanel}){addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleOnlineTips")).then(panelEl=>{const lifetimeComponent=this.lifetimeComponent;let pageDisposed=!1;lifetimeComponent.register(()=>{pageDisposed=!0});const repo="vrtmrz/obsidian-livesync",topPath=$msg("obsidianLiveSyncSettingTab.linkTroubleshooting"),rawRepoURI=`https://raw.githubusercontent.com/${repo}/main`;this.createEl(panelEl,"div","",el=>{el.createEl("a",{text:$msg("obsidianLiveSyncSettingTab.linkOpenInBrowser")},anchor=>{anchor.href=`https://github.com/${repo}/blob/main${topPath}`;anchor.target="_blank";anchor.rel="noopener"})});const troubleShootEl=this.createEl(panelEl,"div",{text:"",cls:"sls-troubleshoot-preview"}),loadMarkdownPage=async(pathAll,basePathParam="")=>{var _a13,_b6;troubleShootEl.setCssStyles({minHeight:troubleShootEl.clientHeight+"px"});troubleShootEl.empty();const fullPath=pathAll.startsWith("/")?pathAll:`${basePathParam}/${pathAll}`,directoryArr=fullPath.split("/"),filename=directoryArr.pop(),basePath=directoryArr.join("/");let remoteTroubleShootMDSrc="";try{remoteTroubleShootMDSrc=await(0,import_obsidian.request)(`${rawRepoURI}${basePath}/${filename}`)}catch(ex){const err3=LiveSyncError.fromError(ex);remoteTroubleShootMDSrc=`${$msg("obsidianLiveSyncSettingTab.logErrorOccurred")}\n${err3.toString()}`}if(pageDisposed)return;const remoteTroubleShootMD=remoteTroubleShootMDSrc.replace(/\((.*?(.png)|(.jpg))\)/g,`(${rawRepoURI}${basePath}/$1)`);await import_obsidian.MarkdownRenderer.render(this.plugin.app,`<a class='sls-troubleshoot-anchor'></a> [${$msg("obsidianLiveSyncSettingTab.linkTipsAndTroubleshooting")}](${topPath}) [${$msg("obsidianLiveSyncSettingTab.linkPageTop")}](${filename})\n\n${remoteTroubleShootMD}`,troubleShootEl,`${rawRepoURI}`,lifetimeComponent);if(!pageDisposed){null==(_b6=null==(_a13=troubleShootEl.querySelector(".sls-troubleshoot-anchor"))?void 0:_a13.parentElement)||_b6.setCssStyles({position:"sticky",top:"-1em",backgroundColor:"var(--modal-background)"});troubleShootEl.querySelectorAll("a.internal-link").forEach(anchorEl=>{anchorEl.addEventListener("click",evt=>{fireAndForget(async()=>{const uri=anchorEl.getAttr("data-href");if(uri)if(uri.startsWith("#")){evt.preventDefault();const elements=Array.from(troubleShootEl.querySelectorAll("[data-heading]")),target=elements.find(element2=>{var _a14;return(null==(_a14=element2.getAttr("data-heading"))?void 0:_a14.toLowerCase().split(" ").join("-"))===uri.substring(1).toLowerCase()});if(target){target.setCssStyles({scrollMargin:"3em"});target.scrollIntoView({behavior:"instant",block:"start"})}}else{evt.preventDefault();await loadMarkdownPage(uri,basePath);troubleShootEl.setCssStyles({scrollMargin:"1em"});troubleShootEl.scrollIntoView({behavior:"instant",block:"start"})}})})});troubleShootEl.setCssStyles({minHeight:""})}};loadMarkdownPage(topPath)})}function createError(error,reason){function CustomPouchError(reason2){var i3,len,names=Object.getOwnPropertyNames(error);for(i3=0,len=names.length;i3<len;i3++)"function"!=typeof error[names[i3]]&&(this[names[i3]]=error[names[i3]]);void 0===this.stack&&(this.stack=(new Error).stack);void 0!==reason2&&(this.reason=reason2)}CustomPouchError.prototype=PouchError.prototype;return new CustomPouchError(reason)}function generateErrorFromResponse(err3){if("object"!=typeof err3){var data=err3;err3=UNKNOWN_ERROR;err3.data=data}if("error"in err3&&"conflict"===err3.error){err3.name="conflict";err3.status=409}"name"in err3||(err3.name=err3.error||"unknown");"status"in err3||(err3.status=500);"message"in err3||(err3.message=err3.message||err3.reason);"stack"in err3||(err3.stack=(new Error).stack);return err3}function unsafeStringify(arr,offset=0){return(byteToHex[arr[offset+0]]+byteToHex[arr[offset+1]]+byteToHex[arr[offset+2]]+byteToHex[arr[offset+3]]+"-"+byteToHex[arr[offset+4]]+byteToHex[arr[offset+5]]+"-"+byteToHex[arr[offset+6]]+byteToHex[arr[offset+7]]+"-"+byteToHex[arr[offset+8]]+byteToHex[arr[offset+9]]+"-"+byteToHex[arr[offset+10]]+byteToHex[arr[offset+11]]+byteToHex[arr[offset+12]]+byteToHex[arr[offset+13]]+byteToHex[arr[offset+14]]+byteToHex[arr[offset+15]]).toLowerCase()}function rng(){if(!getRandomValues){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");getRandomValues=crypto.getRandomValues.bind(crypto)}return getRandomValues(rnds8)}function createBlob2(parts,properties){var Builder,builder,i3;parts=parts||[];properties=properties||{};try{return new Blob(parts,properties)}catch(e3){if("TypeError"!==e3.name)throw e3;Builder="undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof MSBlobBuilder?MSBlobBuilder:"undefined"!=typeof MozBlobBuilder?MozBlobBuilder:WebKitBlobBuilder;builder=new Builder;for(i3=0;i3<parts.length;i3+=1)builder.append(parts[i3]);return builder.getBlob(properties.type)}}function binaryStringToArrayBuffer(bin){var i3,length=bin.length,buf=new ArrayBuffer(length),arr=new Uint8Array(buf);for(i3=0;i3<length;i3++)arr[i3]=bin.charCodeAt(i3);return buf}function binStringToBluffer(binString,type){return createBlob2([binaryStringToArrayBuffer(binString)],{type})}function b64ToBluffer(b64,type){return binStringToBluffer(thisAtob(b64),type)}function arrayBufferToBinaryString(buffer){var i3,binary="",bytes=new Uint8Array(buffer),length=bytes.byteLength;for(i3=0;i3<length;i3++)binary+=String.fromCharCode(bytes[i3]);return binary}function readAsBinaryString(blob,callback){var reader=new FileReader,hasBinaryString="function"==typeof reader.readAsBinaryString;reader.onloadend=function(e3){var result=e3.target.result||"";if(hasBinaryString)return callback(result);callback(arrayBufferToBinaryString(result))};hasBinaryString?reader.readAsBinaryString(blob):reader.readAsArrayBuffer(blob)}function blobToBinaryString(blobOrBuffer,callback){readAsBinaryString(blobOrBuffer,function(bin){callback(bin)})}function blobToBase64(blobOrBuffer,callback){blobToBinaryString(blobOrBuffer,function(base64){callback(thisBtoa(base64))})}function readAsArrayBuffer(blob,callback){var reader=new FileReader;reader.onloadend=function(e3){var result=e3.target.result||new ArrayBuffer(0);callback(result)};reader.readAsArrayBuffer(blob)}function rawToBase64(raw){return thisBtoa(raw)}function appendBlob(buffer,blob,start,end,callback){(start>0||end<blob.size)&&(blob=blob.slice(start,end));readAsArrayBuffer(blob,function(arrayBuffer){buffer.append(arrayBuffer);callback()})}function appendString(buffer,string,start,end,callback){(start>0||end<string.length)&&(string=string.substring(start,end));buffer.appendBinary(string);callback()}function binaryMd5(data,callback){function next2(){setImmediateShim(loadNextChunk)}function done(){var raw=buffer.end(!0),base64=rawToBase64(raw);callback(base64);buffer.destroy()}function loadNextChunk(){var start=currentChunk*chunkSize2,end=start+chunkSize2;currentChunk++;append2(buffer,data,start,end,currentChunk<chunks?next2:done)}var inputIsString="string"==typeof data,len=inputIsString?data.length:data.size,chunkSize2=Math.min(MD5_CHUNK_SIZE,len),chunks=Math.ceil(len/chunkSize2),currentChunk=0,buffer=inputIsString?new import_spark_md5.default:new import_spark_md5.default.ArrayBuffer,append2=inputIsString?appendString:appendBlob;loadNextChunk()}function stringMd5(string){return import_spark_md5.default.hash(string)}function isBinaryObject(object){return"undefined"!=typeof ArrayBuffer&&object instanceof ArrayBuffer||"undefined"!=typeof Blob&&object instanceof Blob}function cloneBinaryObject(object){return object instanceof ArrayBuffer?object.slice(0):object.slice(0,object.size,object.type)}function isPlainObject(value){var Ctor,proto=Object.getPrototypeOf(value);if(null===proto)return!0;Ctor=proto.constructor;return"function"==typeof Ctor&&Ctor instanceof Ctor&&funcToString.call(Ctor)==objectCtorString}function clone2(object){var newObject,i3,len,value;if(!object||"object"!=typeof object)return object;if(Array.isArray(object)){newObject=[];for(i3=0,len=object.length;i3<len;i3++)newObject[i3]=clone2(object[i3]);return newObject}if(object instanceof Date&&isFinite(object))return object.toISOString();if(isBinaryObject(object))return cloneBinaryObject(object);if(!isPlainObject(object))return object;newObject={};for(i3 in object)if(Object.prototype.hasOwnProperty.call(object,i3)){value=clone2(object[i3]);void 0!==value&&(newObject[i3]=value)}return newObject}function once2(fun){var called=!1;return function(...args){if(called)throw new Error("once called more than once");called=!0;fun.apply(this,args)}}function toPromise(func){return function(...args){var self3,usedCB,promise;args=clone2(args);self3=this;usedCB="function"==typeof args[args.length-1]&&args.pop();promise=new Promise(function(fulfill,reject){var resp,callback;try{callback=once2(function(err3,mesg){err3?reject(err3):fulfill(mesg)});args.push(callback);resp=func.apply(self3,args);resp&&"function"==typeof resp.then&&fulfill(resp)}catch(e3){reject(e3)}});usedCB&&promise.then(function(result){usedCB(null,result)},usedCB);return promise}}function logApiCall(self3,name,args){var logArgs,i3,origCallback;if(self3.constructor.listeners("debug").length){logArgs=["api",self3.name,name];for(i3=0;i3<args.length-1;i3++)logArgs.push(args[i3]);self3.constructor.emit("debug",logArgs);origCallback=args[args.length-1];args[args.length-1]=function(err3,res2){var responseArgs=["api",self3.name,name];responseArgs=responseArgs.concat(err3?["error",err3]:["success",res2]);self3.constructor.emit("debug",responseArgs);origCallback(err3,res2)}}}function adapterFun(name,callback){return toPromise(function(...args){if(this._closed)return Promise.reject(new Error("database is closed"));if(this._destroyed)return Promise.reject(new Error("database is destroyed"));var self3=this;logApiCall(self3,name,args);return this.taskqueue.isReady?callback.apply(this,args):new Promise(function(fulfill,reject){self3.taskqueue.addTask(function(failed2){failed2?reject(failed2):fulfill(self3[name].apply(self3,args))})})})}function pick(obj,arr){var i3,len,prop2,res2={};for(i3=0,len=arr.length;i3<len;i3++){prop2=arr[i3];prop2 in obj&&(res2[prop2]=obj[prop2])}return res2}function identityFunction(x3){return x3}function formatResultForOpenRevsGet(result){return[{ok:result}]}function bulkGet(db,opts,callback){function collapseResultsAndFinish(){var results=[];perDocResults.forEach(function(res2){res2.docs.forEach(function(info3){results.push({id:res2.id,docs:[info3]})})});callback(null,{results})}function checkDone(){++numDone===numDocs&&collapseResultsAndFinish()}function gotResult(docIndex,id,docs){perDocResults[docIndex]={id,docs};checkDone()}function nextBatch(){var upTo,batch;if(!(i3>=allRequests.length)){upTo=Math.min(i3+MAX_NUM_CONCURRENT_REQUESTS,allRequests.length);batch=allRequests.slice(i3,upTo);processBatch(batch,i3);i3+=batch.length}}function processBatch(batch,offset){batch.forEach(function(docId,j2){var formatResult,docIdx=offset+j2,docRequests=requestsById.get(docId),docOpts=pick(docRequests[0],["atts_since","attachments"]);docOpts.open_revs=docRequests.map(function(request2){return request2.rev});docOpts.open_revs=docOpts.open_revs.filter(identityFunction);formatResult=identityFunction;if(0===docOpts.open_revs.length){delete docOpts.open_revs;formatResult=formatResultForOpenRevsGet}["revs","attachments","binary","ajax","latest"].forEach(function(param){param in opts&&(docOpts[param]=opts[param])});db.get(docId,docOpts,function(err3,res2){var result;result=err3?[{error:err3}]:formatResult(res2);gotResult(docIdx,docId,result);nextBatch()})})}var numDocs,numDone,perDocResults,allRequests,i3,requests=opts.docs,requestsById=new Map;requests.forEach(function(request2){requestsById.has(request2.id)?requestsById.get(request2.id).push(request2):requestsById.set(request2.id,[request2])});numDocs=requestsById.size;numDone=0;perDocResults=new Array(numDocs);allRequests=[];requestsById.forEach(function(value,key3){allRequests.push(key3)});i3=0;nextBatch()}function hasLocalStorage(){return hasLocal}function guardedConsole(method){if("undefined"!=typeof console&&"function"==typeof console[method]){var args=Array.prototype.slice.call(arguments,1);console[method].apply(console,args)}}function randomNumber(min2,max3){var ratio,range4,maxTimeout=6e5;min2=parseInt(min2,10)||0;max3=parseInt(max3,10);max3!=max3||max3<=min2?max3=(min2||1)<<1:max3+=1;if(max3>maxTimeout){min2=maxTimeout>>1;max3=maxTimeout}ratio=Math.random();range4=max3-min2;return~~(range4*ratio+min2)}function defaultBackOff(min2){var max3=0;min2||(max3=2e3);return randomNumber(min2,max3)}function explainError(status,str){guardedConsole("info","The above "+status+" is totally normal. "+str)}function tryFilter(filter4,doc,req){try{return!filter4(doc,req)}catch(err3){var msg="Filter function threw: "+err3.toString();return createError(BAD_REQUEST,msg)}}function filterChange(opts){var req={},hasFilter=opts.filter&&"function"==typeof opts.filter;req.query=opts.query_params;return function filter4(change){var filterReturn,att;change.doc||(change.doc={});filterReturn=hasFilter&&tryFilter(opts.filter,change.doc,req);if("object"==typeof filterReturn)return filterReturn;if(filterReturn)return!1;if(opts.include_docs){if(!opts.attachments)for(att in change.doc._attachments)Object.prototype.hasOwnProperty.call(change.doc._attachments,att)&&(change.doc._attachments[att].stub=!0)}else delete change.doc;return!0}}function invalidIdError(id){var err3;id?"string"!=typeof id?err3=createError(INVALID_ID):/^_/.test(id)&&!/^_(design|local)/.test(id)&&(err3=createError(RESERVED_ID)):err3=createError(MISSING_ID);if(err3)throw err3}function isRemote(db){if("boolean"==typeof db._remote)return db._remote;if("function"==typeof db.type){guardedConsole("warn","db.type() is deprecated and will be removed in a future version of PouchDB");return"http"===db.type()}return!1}function listenerCount(ee,type){return"listenerCount"in ee?ee.listenerCount(type):import_events17.default.listenerCount(ee,type)}function parseDesignDocFunctionName(s2){if(!s2)return null;var parts=s2.split("/");return 2===parts.length?parts:1===parts.length?[s2,s2]:null}function normalizeDesignDocFunctionName(s2){var normalized=parseDesignDocFunctionName(s2);return normalized?normalized.join("/"):null}function parseUri(str){for(var key3,value,encoded,m3=parser2.exec(str),uri={},i3=14;i3--;){key3=keys2[i3];value=m3[i3]||"";encoded=-1!==["user","password"].indexOf(key3);uri[key3]=encoded?decodeURIComponent(value):value}uri[qName]={};uri[keys2[12]].replace(qParser,function($0,$1,$2){$1&&(uri[qName][$1]=$2)});return uri}function scopeEval(source2,scope){var key3,keys3=[],values2=[];for(key3 in scope)if(Object.prototype.hasOwnProperty.call(scope,key3)){keys3.push(key3);values2.push(scope[key3])}keys3.push(source2);return Function.apply(null,keys3).apply(null,values2)}function upsert(db,docId,diffFun){return db.get(docId).catch(function(err3){if(404!==err3.status)throw err3;return{}}).then(function(doc){var docRev=doc._rev,newDoc=diffFun(doc);if(!newDoc)return{updated:!1,rev:docRev};newDoc._id=docId;newDoc._rev=docRev;return tryAndPut(db,newDoc,diffFun)})}function tryAndPut(db,doc,diffFun){return db.put(doc).then(function(res2){return{updated:!0,rev:res2.rev}},function(err3){if(409!==err3.status)throw err3;return upsert(db,doc._id,diffFun)})}function rev2(doc,deterministic_revs){if(!deterministic_revs)return v4_default().replace(/-/g,"").toLowerCase();var mutateableDoc=Object.assign({},doc);delete mutateableDoc._rev_tree;return stringMd5(JSON.stringify(mutateableDoc))}function winningRev(metadata){for(var winningId,winningPos,winningDeleted,node,tree,branches,pos,i3,len,deleted,id,toVisit=metadata.rev_tree.slice();node=toVisit.pop();){tree=node.ids;branches=tree[2];pos=node.pos;if(branches.length)for(i3=0,len=branches.length;i3<len;i3++)toVisit.push({pos:pos+1,ids:branches[i3]});else{deleted=!!tree[1].deleted;id=tree[0];if(!winningId||(winningDeleted!==deleted?winningDeleted:winningPos!==pos?winningPos<pos:winningId<id)){winningId=id;winningPos=pos;winningDeleted=deleted}}}return winningPos+"-"+winningId}function traverseRevTree(revs,callback){for(var node,pos,tree,branches,newCtx,i3,len,toVisit=revs.slice();node=toVisit.pop();){pos=node.pos;tree=node.ids;branches=tree[2];newCtx=callback(0===branches.length,pos,tree[0],node.ctx,tree[1]);for(i3=0,len=branches.length;i3<len;i3++)toVisit.push({pos:pos+1,ids:branches[i3],ctx:newCtx})}}function sortByPos(a2,b3){return a2.pos-b3.pos}function collectLeaves(revs){var i3,len,leaves=[];traverseRevTree(revs,function(isLeaf,pos,id,acc,opts){isLeaf&&leaves.push({rev:pos+"-"+id,pos,opts})});leaves.sort(sortByPos).reverse();for(i3=0,len=leaves.length;i3<len;i3++)delete leaves[i3].pos;return leaves}function collectConflicts(metadata){var i3,len,leaf,win=winningRev(metadata),leaves=collectLeaves(metadata.rev_tree),conflicts=[];for(i3=0,len=leaves.length;i3<len;i3++){leaf=leaves[i3];leaf.rev===win||leaf.opts.deleted||conflicts.push(leaf.rev)}return conflicts}function compactTree(metadata){var revs=[];traverseRevTree(metadata.rev_tree,function(isLeaf,pos,revHash,ctx,opts){if("available"===opts.status&&!isLeaf){revs.push(pos+"-"+revHash);opts.status="missing"}});return revs}function findPathToLeaf(revs,targetRev){let path2=[];const toVisit=revs.slice();let node;for(;node=toVisit.pop();){const{pos,ids:tree}=node,rev3=`${pos}-${tree[0]}`,branches=tree[2];path2.push(rev3);if(rev3===targetRev){if(0!==branches.length)throw new Error("The requested revision is not a leaf");return path2.reverse()}(0===branches.length||branches.length>1)&&(path2=[]);for(let i3=0,len=branches.length;i3<len;i3++)toVisit.push({pos:pos+1,ids:branches[i3]})}if(0===path2.length)throw new Error("The requested revision does not exist");return path2.reverse()}function rootToLeaf(revs){for(var node,pos,tree,id,opts,branches,isLeaf,history,i3,len,paths=[],toVisit=revs.slice();node=toVisit.pop();){pos=node.pos;tree=node.ids;id=tree[0];opts=tree[1];branches=tree[2];isLeaf=0===branches.length;history=node.history?node.history.slice():[];history.push({id,opts});isLeaf&&paths.push({pos:pos+1-history.length,ids:history});for(i3=0,len=branches.length;i3<len;i3++)toVisit.push({pos:pos+1,ids:branches[i3],history})}return paths.reverse()}function sortByPos$1(a2,b3){return a2.pos-b3.pos}function binarySearch(arr,item,comparator){for(var mid,low=0,high=arr.length;low<high;){mid=low+high>>>1;comparator(arr[mid],item)<0?low=mid+1:high=mid}return low}function insertSorted(arr,item,comparator){var idx2=binarySearch(arr,item,comparator);arr.splice(idx2,0,item)}function pathToTree(path2,numStemmed){var root44,leaf,i3,len,node,currentLeaf;for(i3=numStemmed,len=path2.length;i3<len;i3++){node=path2[i3];currentLeaf=[node.id,node.opts,[]];if(leaf){leaf[2].push(currentLeaf);leaf=currentLeaf}else root44=leaf=currentLeaf}return root44}function compareTree(a2,b3){return a2[0]<b3[0]?-1:1}function mergeTree(in_tree1,in_tree2){for(var item,tree1,tree2,i3,merged,j2,queue2=[{tree1:in_tree1,tree2:in_tree2}],conflicts=!1;queue2.length>0;){item=queue2.pop();tree1=item.tree1;tree2=item.tree2;(tree1[1].status||tree2[1].status)&&(tree1[1].status="available"===tree1[1].status||"available"===tree2[1].status?"available":"missing");for(i3=0;i3<tree2[2].length;i3++)if(tree1[2][0]){merged=!1;for(j2=0;j2<tree1[2].length;j2++)if(tree1[2][j2][0]===tree2[2][i3][0]){queue2.push({tree1:tree1[2][j2],tree2:tree2[2][i3]});merged=!0}if(!merged){conflicts="new_branch";insertSorted(tree1[2],tree2[2][i3],compareTree)}}else{conflicts="new_leaf";tree1[2][0]=tree2[2][i3]}}return{conflicts,tree:in_tree1}}function doMerge(tree,path2,dontExpand){var res2,i3,len,branch2,t12,t22,diff,candidateParents,trees,item,elements,j2,elementsLen,el,restree=[],conflicts=!1,merged=!1;if(!tree.length)return{tree:[path2],conflicts:"new_leaf"};for(i3=0,len=tree.length;i3<len;i3++){branch2=tree[i3];if(branch2.pos===path2.pos&&branch2.ids[0]===path2.ids[0]){res2=mergeTree(branch2.ids,path2.ids);restree.push({pos:branch2.pos,ids:res2.tree});conflicts=conflicts||res2.conflicts;merged=!0}else if(!0!==dontExpand){t12=branch2.pos<path2.pos?branch2:path2;t22=branch2.pos<path2.pos?path2:branch2;diff=t22.pos-t12.pos;candidateParents=[];trees=[];trees.push({ids:t12.ids,diff,parent:null,parentIdx:null});for(;trees.length>0;){item=trees.pop();if(0!==item.diff){elements=item.ids[2];for(j2=0,elementsLen=elements.length;j2<elementsLen;j2++)trees.push({ids:elements[j2],diff:item.diff-1,parent:item.ids,parentIdx:j2})}else item.ids[0]===t22.ids[0]&&candidateParents.push(item)}el=candidateParents[0];if(el){res2=mergeTree(el.ids,t22.ids);el.parent[2][el.parentIdx]=res2.tree;restree.push({pos:t12.pos,ids:t12.ids});conflicts=conflicts||res2.conflicts;merged=!0}else restree.push(branch2)}else restree.push(branch2)}merged||restree.push(path2);restree.sort(sortByPos$1);return{tree:restree,conflicts:conflicts||"internal_node"}}function stem(tree,depth){var stemmedRevs,result,i3,len,path2,stemmed,node,numStemmed,s2,rev3,paths=rootToLeaf(tree);for(i3=0,len=paths.length;i3<len;i3++){path2=paths[i3];stemmed=path2.ids;if(stemmed.length>depth){stemmedRevs||(stemmedRevs={});numStemmed=stemmed.length-depth;node={pos:path2.pos+numStemmed,ids:pathToTree(stemmed,numStemmed)};for(s2=0;s2<numStemmed;s2++){rev3=path2.pos+s2+"-"+stemmed[s2].id;stemmedRevs[rev3]=!0}}else node={pos:path2.pos,ids:pathToTree(stemmed,0)};result=result?doMerge(result,node,!0).tree:[node]}stemmedRevs&&traverseRevTree(result,function(isLeaf,pos,revHash){delete stemmedRevs[pos+"-"+revHash]});return{tree:result,revs:stemmedRevs?Object.keys(stemmedRevs):[]}}function merge2(tree,path2,depth){var newTree=doMerge(tree,path2),stemmed=stem(newTree.tree,depth);return{tree:stemmed.tree,stemmedRevs:stemmed.revs,conflicts:newTree.conflicts}}function removeLeafFromRevTree(tree,leafRev){return tree.flatMap(path2=>{path2=removeLeafFromPath(path2,leafRev);return path2?[path2]:[]})}function removeLeafFromPath(path2,leafRev){const tree=clone2(path2),toVisit=[tree];let node;for(;node=toVisit.pop();){const{pos,ids:[id,,branches],parent}=node,isLeaf=0===branches.length,hash3=`${pos}-${id}`;if(isLeaf&&hash3===leafRev){if(!parent)return null;parent.ids[2]=parent.ids[2].filter(function(branchNode){return branchNode[0]!==id});return tree}for(let i3=0,len=branches.length;i3<len;i3++)toVisit.push({pos:pos+1,ids:branches[i3],parent:node})}return tree}function revExists(revs,rev3){for(var node,branches,i3,len,toVisit=revs.slice(),splitRev=rev3.split("-"),targetPos=parseInt(splitRev[0],10),targetId=splitRev[1];node=toVisit.pop();){if(node.pos===targetPos&&node.ids[0]===targetId)return!0;branches=node.ids[2];for(i3=0,len=branches.length;i3<len;i3++)toVisit.push({pos:node.pos+1,ids:branches[i3]})}return!1}function getTrees(node){return node.ids}function isDeleted(metadata,rev3){var id,toVisit,tree;rev3||(rev3=winningRev(metadata));id=rev3.substring(rev3.indexOf("-")+1);toVisit=metadata.rev_tree.map(getTrees);for(;tree=toVisit.pop();){if(tree[0]===id)return!!tree[1].deleted;toVisit=toVisit.concat(tree[2])}}function isLocalId(id){return"string"==typeof id&&id.startsWith("_local/")}function latest(rev3,metadata){for(var node,pos,tree,id,opts,branches,isLeaf,history,i3,len,historyNode,historyRev,j2,l2,toVisit=metadata.rev_tree.slice();node=toVisit.pop();){pos=node.pos;tree=node.ids;id=tree[0];opts=tree[1];branches=tree[2];isLeaf=0===branches.length;history=node.history?node.history.slice():[];history.push({id,pos,opts});if(isLeaf)for(i3=0,len=history.length;i3<len;i3++){historyNode=history[i3];historyRev=historyNode.pos+"-"+historyNode.id;if(historyRev===rev3)return pos+"-"+id}for(j2=0,l2=branches.length;j2<l2;j2++)toVisit.push({pos:pos+1,ids:branches[j2],history})}throw new Error("Unable to resolve latest revision for id "+metadata.id+", rev "+rev3)}function pad(str,padWith,upToLength){for(var padding="",targetLength=upToLength-str.length;padding.length<targetLength;)padding+=padWith;return padding}function padLeft(str,padWith,upToLength){var padding=pad(str,padWith,upToLength);return padding+str}function collate(a2,b3){var ai2,bi2;if(a2===b3)return 0;a2=normalizeKey(a2);b3=normalizeKey(b3);ai2=collationIndex(a2);bi2=collationIndex(b3);if(ai2-bi2!==0)return ai2-bi2;switch(typeof a2){case"number":return a2-b3;case"boolean":return a2<b3?-1:1;case"string":return stringCollate(a2,b3)}return Array.isArray(a2)?arrayCollate(a2,b3):objectCollate(a2,b3)}function normalizeKey(key3){var origKey,len,i3,k2,val;switch(typeof key3){case"undefined":return null;case"number":return key3===1/0||key3===-1/0||isNaN(key3)?null:key3;case"object":origKey=key3;if(Array.isArray(key3)){len=key3.length;key3=new Array(len);for(i3=0;i3<len;i3++)key3[i3]=normalizeKey(origKey[i3])}else{if(key3 instanceof Date)return key3.toJSON();if(null!==key3){key3={};for(k2 in origKey)if(Object.prototype.hasOwnProperty.call(origKey,k2)){val=origKey[k2];void 0!==val&&(key3[k2]=normalizeKey(val))}}}}return key3}function indexify(key3){var isArray2,arr,i3,len,result,objKey;if(null!==key3)switch(typeof key3){case"boolean":return key3?1:0;case"number":return numToIndexableString(key3);case"string":return key3.replace(/\u0002/g,"").replace(/\u0001/g,"").replace(/\u0000/g,"");case"object":isArray2=Array.isArray(key3);arr=isArray2?key3:Object.keys(key3);i3=-1;len=arr.length;result="";if(isArray2)for(;++i3<len;)result+=toIndexableString(arr[i3]);else for(;++i3<len;){objKey=arr[i3];result+=toIndexableString(objKey)+toIndexableString(key3[objKey])}return result}return""}function toIndexableString(key3){key3=normalizeKey(key3);return collationIndex(key3)+SEP+indexify(key3)+"\0"}function parseNumber2(str,i3){var num,neg,numAsString,magAsString,magnitude,ch4,originalIdx=i3,zero="1"===str[i3];if(zero){num=0;i3++}else{neg="0"===str[i3];i3++;numAsString="";magAsString=str.substring(i3,i3+MAGNITUDE_DIGITS);magnitude=parseInt(magAsString,10)+MIN_MAGNITUDE;neg&&(magnitude=-magnitude);i3+=MAGNITUDE_DIGITS;for(;;){ch4=str[i3];if("\0"===ch4)break;numAsString+=ch4;i3++}numAsString=numAsString.split(".");num=1===numAsString.length?parseInt(numAsString,10):parseFloat(numAsString[0]+"."+numAsString[1]);neg&&(num-=10);0!==magnitude&&(num=parseFloat(num+"e"+magnitude))}return{num,length:i3-originalIdx}}function pop2(stack2,metaStack){var lastMetaElement,element2,lastElementIndex,key3,obj=stack2.pop();if(metaStack.length){lastMetaElement=metaStack[metaStack.length-1];if(obj===lastMetaElement.element){metaStack.pop();lastMetaElement=metaStack[metaStack.length-1]}element2=lastMetaElement.element;lastElementIndex=lastMetaElement.index;if(Array.isArray(element2))element2.push(obj);else if(lastElementIndex===stack2.length-2){key3=stack2.pop();element2[key3]=obj}else stack2.push(obj)}}function parseIndexableString(str){for(var collationIndex2,parsedNum,parsedStr,ch4,arrayElement,objElement,stack2=[],metaStack=[],i3=0;;){collationIndex2=str[i3++];if("\0"!==collationIndex2)switch(collationIndex2){case"1":stack2.push(null);break;case"2":stack2.push("1"===str[i3]);i3++;break;case"3":parsedNum=parseNumber2(str,i3);stack2.push(parsedNum.num);i3+=parsedNum.length;break;case"4":parsedStr="";for(;;){ch4=str[i3];if("\0"===ch4)break;parsedStr+=ch4;i3++}parsedStr=parsedStr.replace(/\u0001\u0001/g,"\0").replace(/\u0001\u0002/g,"").replace(/\u0002\u0002/g,"");stack2.push(parsedStr);break;case"5":arrayElement={element:[],index:stack2.length};stack2.push(arrayElement.element);metaStack.push(arrayElement);break;case"6":objElement={element:{},index:stack2.length};stack2.push(objElement.element);metaStack.push(objElement);break;default:throw new Error("bad collationIndex or unexpectedly reached end of input: "+collationIndex2)}else{if(1===stack2.length)return stack2.pop();pop2(stack2,metaStack)}}}function arrayCollate(a2,b3){var i3,sort,len=Math.min(a2.length,b3.length);for(i3=0;i3<len;i3++){sort=collate(a2[i3],b3[i3]);if(0!==sort)return sort}return a2.length===b3.length?0:a2.length>b3.length?1:-1}function stringCollate(a2,b3){return a2===b3?0:a2>b3?1:-1}function objectCollate(a2,b3){var i3,sort,ak2=Object.keys(a2),bk2=Object.keys(b3),len=Math.min(ak2.length,bk2.length);for(i3=0;i3<len;i3++){sort=collate(ak2[i3],bk2[i3]);if(0!==sort)return sort;sort=collate(a2[ak2[i3]],b3[bk2[i3]]);if(0!==sort)return sort}return ak2.length===bk2.length?0:ak2.length>bk2.length?1:-1}function collationIndex(x3){var id=["boolean","number","string","object"],idx2=id.indexOf(typeof x3);return~idx2?null===x3?1:Array.isArray(x3)?5:idx2<3?idx2+2:idx2+3:Array.isArray(x3)?5:void 0}function numToIndexableString(num){var expFormat,magnitude,neg,result,magForComparison,magString,factor,factorStr;if(0===num)return"1";expFormat=num.toExponential().split(/e\+?/);magnitude=parseInt(expFormat[1],10);neg=num<0;result=neg?"0":"2";magForComparison=(neg?-magnitude:magnitude)-MIN_MAGNITUDE;magString=padLeft(magForComparison.toString(),"0",MAGNITUDE_DIGITS);result+=SEP+magString;factor=Math.abs(parseFloat(expFormat[0]));neg&&(factor=10-factor);factorStr=factor.toFixed(20);factorStr=factorStr.replace(/\.?0+$/,"");result+=SEP+factorStr;return result}function getFieldFromDoc(doc,parsedField){var i3,len,key3,value=doc;for(i3=0,len=parsedField.length;i3<len;i3++){key3=parsedField[i3];value=value[key3];if(!value)break}return value}function setFieldInDoc(doc,parsedField,value){var i3,len,elem;for(i3=0,len=parsedField.length;i3<len-1;i3++){elem=parsedField[i3];doc=doc[elem]=doc[elem]||{}}doc[parsedField[len-1]]=value}function compare2(left,right){return left<right?-1:left>right?1:0}function parseField(fieldName){var i3,len,ch4,fields=[],current="";for(i3=0,len=fieldName.length;i3<len;i3++){ch4=fieldName[i3];if(i3>0&&"\\"===fieldName[i3-1]&&("$"===ch4||"."===ch4))current=current.substring(0,current.length-1)+ch4;else if("."===ch4){fields.push(current);current=""}else current+=ch4}fields.push(current);return fields}function isCombinationalField(field){return combinationFields.indexOf(field)>-1}function getKey2(obj){return Object.keys(obj)[0]}function getValue(obj){return obj[getKey2(obj)]}function mergeAndedSelectors(selectors){var res2={},first={$or:!0,$nor:!0};selectors.forEach(function(selector){Object.keys(selector).forEach(function(field){var entries2,fieldMatchers,matcher=selector[field];"object"!=typeof matcher&&(matcher={$eq:matcher});if(isCombinationalField(field))if(matcher instanceof Array){if(first[field]){first[field]=!1;res2[field]=matcher;return}entries2=[];res2[field].forEach(function(existing){Object.keys(matcher).forEach(function(key3){var m3=matcher[key3],longest=Math.max(Object.keys(existing).length,Object.keys(m3).length),merged=mergeAndedSelectors([existing,m3]);Object.keys(merged).length<=longest||entries2.push(merged)})});res2[field]=entries2}else res2[field]=mergeAndedSelectors([matcher]);else{fieldMatchers=res2[field]=res2[field]||{};Object.keys(matcher).forEach(function(operator){var value=matcher[operator];if("$gt"===operator||"$gte"===operator)return mergeGtGte(operator,value,fieldMatchers);if("$lt"===operator||"$lte"===operator)return mergeLtLte(operator,value,fieldMatchers);if("$ne"===operator)return mergeNe(value,fieldMatchers);if("$eq"===operator)return mergeEq(value,fieldMatchers);if("$regex"===operator)return mergeRegex(value,fieldMatchers);fieldMatchers[operator]=value})}})});return res2}function mergeGtGte(operator,value,fieldMatchers){if(void 0===fieldMatchers.$eq)if(void 0!==fieldMatchers.$gte){if("$gte"===operator)value>fieldMatchers.$gte&&(fieldMatchers.$gte=value);else if(value>=fieldMatchers.$gte){delete fieldMatchers.$gte;fieldMatchers.$gt=value}}else if(void 0!==fieldMatchers.$gt)if("$gte"===operator){if(value>fieldMatchers.$gt){delete fieldMatchers.$gt;fieldMatchers.$gte=value}}else value>fieldMatchers.$gt&&(fieldMatchers.$gt=value);else fieldMatchers[operator]=value}function mergeLtLte(operator,value,fieldMatchers){if(void 0===fieldMatchers.$eq)if(void 0!==fieldMatchers.$lte){if("$lte"===operator)value<fieldMatchers.$lte&&(fieldMatchers.$lte=value);else if(value<=fieldMatchers.$lte){delete fieldMatchers.$lte;fieldMatchers.$lt=value}}else if(void 0!==fieldMatchers.$lt)if("$lte"===operator){if(value<fieldMatchers.$lt){delete fieldMatchers.$lt;fieldMatchers.$lte=value}}else value<fieldMatchers.$lt&&(fieldMatchers.$lt=value);else fieldMatchers[operator]=value}function mergeNe(value,fieldMatchers){"$ne"in fieldMatchers?fieldMatchers.$ne.push(value):fieldMatchers.$ne=[value]}function mergeEq(value,fieldMatchers){delete fieldMatchers.$gt;delete fieldMatchers.$gte;delete fieldMatchers.$lt;delete fieldMatchers.$lte;delete fieldMatchers.$ne;fieldMatchers.$eq=value}function mergeRegex(value,fieldMatchers){"$regex"in fieldMatchers?fieldMatchers.$regex.push(value):fieldMatchers.$regex=[value]}function mergeAndedSelectorsNested(obj){var prop2,i3,value;for(prop2 in obj){if(Array.isArray(obj))for(i3 in obj)obj[i3].$and&&(obj[i3]=mergeAndedSelectors(obj[i3].$and));value=obj[prop2];"object"==typeof value&&mergeAndedSelectorsNested(value)}return obj}function isAndInSelector(obj,isAnd){var prop2,value;for(prop2 in obj){"$and"===prop2&&(isAnd=!0);value=obj[prop2];"object"==typeof value&&(isAnd=isAndInSelector(value,isAnd))}return isAnd}function massageSelector(input){var fields,i3,field,matcher,result=clone2(input);if(isAndInSelector(result,!1)){result=mergeAndedSelectorsNested(result);"$and"in result&&(result=mergeAndedSelectors(result.$and))}["$or","$nor"].forEach(function(orOrNor){orOrNor in result&&result[orOrNor].forEach(function(subSelector){var i4,field2,matcher2,fields2=Object.keys(subSelector);for(i4=0;i4<fields2.length;i4++){field2=fields2[i4];matcher2=subSelector[field2];"object"==typeof matcher2&&null!==matcher2||(subSelector[field2]={$eq:matcher2})}})});"$not"in result&&(result.$not=mergeAndedSelectors([result.$not]));fields=Object.keys(result);for(i3=0;i3<fields.length;i3++){field=fields[i3];matcher=result[field];"object"==typeof matcher&&null!==matcher||(matcher={$eq:matcher});result[field]=matcher}normalizeArrayOperators(result);return result}function normalizeArrayOperators(selector){Object.keys(selector).forEach(function(field){var matcher=selector[field];Array.isArray(matcher)?matcher.forEach(function(matcherItem){matcherItem&&"object"==typeof matcherItem&&normalizeArrayOperators(matcherItem)}):"$ne"===field?selector.$ne=[matcher]:"$regex"===field?selector.$regex=[matcher]:matcher&&"object"==typeof matcher&&normalizeArrayOperators(matcher)})}function createFieldSorter(sort){function getFieldValuesAsArray(doc){return sort.map(function(sorting){var fieldName=getKey2(sorting),parsedField=parseField(fieldName),docFieldValue=getFieldFromDoc(doc,parsedField);return docFieldValue})}return function(aRow,bRow){var aFieldValues=getFieldValuesAsArray(aRow.doc),bFieldValues=getFieldValuesAsArray(bRow.doc),collation=collate(aFieldValues,bFieldValues);return 0!==collation?collation:compare2(aRow.doc._id,bRow.doc._id)}}function filterInMemoryFields(rows,requestDef,inMemoryFields){var fieldSorter,skip,limit;rows=rows.filter(function(row){return rowFilter(row.doc,requestDef.selector,inMemoryFields)});if(requestDef.sort){fieldSorter=createFieldSorter(requestDef.sort);rows=rows.sort(fieldSorter);"string"!=typeof requestDef.sort[0]&&"desc"===getValue(requestDef.sort[0])&&(rows=rows.reverse())}if("limit"in requestDef||"skip"in requestDef){skip=requestDef.skip||0;limit=("limit"in requestDef?requestDef.limit:rows.length)+skip;rows=rows.slice(skip,limit)}return rows}function rowFilter(doc,selector,inMemoryFields){return inMemoryFields.every(function(field){var matcher=selector[field],parsedField=parseField(field),docFieldValue=getFieldFromDoc(doc,parsedField);return isCombinationalField(field)?matchCominationalSelector(field,matcher,doc):matchSelector(matcher,doc,parsedField,docFieldValue)})}function matchSelector(matcher,doc,parsedField,docFieldValue){return!matcher||("object"==typeof matcher?Object.keys(matcher).every(function(maybeUserOperator){var subParsedField,subDocFieldValue,userValue=matcher[maybeUserOperator];if(0===maybeUserOperator.indexOf("$"))return match2(maybeUserOperator,doc,userValue,parsedField,docFieldValue);subParsedField=parseField(maybeUserOperator);if(void 0===docFieldValue&&"object"!=typeof userValue&&subParsedField.length>0)return!1;subDocFieldValue=getFieldFromDoc(docFieldValue,subParsedField);return"object"==typeof userValue?matchSelector(userValue,doc,parsedField,subDocFieldValue):match2("$eq",doc,userValue,subParsedField,subDocFieldValue)}):matcher===docFieldValue)}function matchCominationalSelector(field,matcher,doc){return"$or"===field?matcher.some(function(orMatchers){return rowFilter(doc,orMatchers,Object.keys(orMatchers))}):"$not"===field?!rowFilter(doc,matcher,Object.keys(matcher)):!matcher.find(function(orMatchers){return rowFilter(doc,orMatchers,Object.keys(orMatchers))})}function match2(userOperator,doc,userValue,parsedField,docFieldValue){if(!matchers[userOperator])throw new Error('unknown operator "'+userOperator+'" - should be one of $eq, $lte, $lt, $gt, $gte, $exists, $ne, $in, $nin, $size, $mod, $regex, $elemMatch, $type, $allMatch or $all');return matchers[userOperator](doc,userValue,parsedField,docFieldValue)}function fieldExists(docFieldValue){return null!=docFieldValue}function fieldIsNotUndefined(docFieldValue){return void 0!==docFieldValue}function modField(docFieldValue,userValue){var divisor,mod;if("number"!=typeof docFieldValue||parseInt(docFieldValue,10)!==docFieldValue)return!1;divisor=userValue[0];mod=userValue[1];return docFieldValue%divisor===mod}function arrayContainsValue(docFieldValue,userValue){return userValue.some(function(val){return docFieldValue instanceof Array?docFieldValue.some(function(docFieldValueItem){return 0===collate(val,docFieldValueItem)}):0===collate(val,docFieldValue)})}function arrayContainsAllValues(docFieldValue,userValue){return userValue.every(function(val){return docFieldValue.some(function(docFieldValueItem){return 0===collate(val,docFieldValueItem)})})}function arraySize(docFieldValue,userValue){return docFieldValue.length===userValue}function regexMatch(docFieldValue,userValue){var re=new RegExp(userValue);return re.test(docFieldValue)}function typeMatch(docFieldValue,userValue){switch(userValue){case"null":return null===docFieldValue;case"boolean":return"boolean"==typeof docFieldValue;case"number":return"number"==typeof docFieldValue;case"string":return"string"==typeof docFieldValue;case"array":return docFieldValue instanceof Array;case"object":return"[object Object]"==={}.toString.call(docFieldValue)}}function matchesSelector(doc,selector){var row,rowsMatched;if("object"!=typeof selector)throw new Error("Selector error: expected a JSON object");selector=massageSelector(selector);row={doc};rowsMatched=filterInMemoryFields([row],{selector},Object.keys(selector));return rowsMatched&&1===rowsMatched.length}function evalFilter(input){return scopeEval('"use strict";\nreturn '+input+";",{})}function evalView(input){var code=["return function(doc) {",' "use strict";'," var emitted = false;"," var emit = function (a, b) {"," emitted = true;"," };"," var view = "+input+";"," view(doc);"," if (emitted) {"," return true;"," }","};"].join("\n");return scopeEval(code,{})}function validate3(opts,callback){if(opts.selector&&opts.filter&&"_selector"!==opts.filter){var filterName="string"==typeof opts.filter?opts.filter:"function";return callback(new Error('selector invalid for filter "'+filterName+'"'))}callback()}function normalize(opts){opts.view&&!opts.filter&&(opts.filter="_view");opts.selector&&!opts.filter&&(opts.filter="_selector");opts.filter&&"string"==typeof opts.filter&&("_view"===opts.filter?opts.view=normalizeDesignDocFunctionName(opts.view):opts.filter=normalizeDesignDocFunctionName(opts.filter))}function shouldFilter(changesHandler,opts){return opts.filter&&"string"==typeof opts.filter&&!opts.doc_ids&&!isRemote(changesHandler.db)}function filter3(changesHandler,opts){var err3,viewName,filterName,callback=opts.complete;if("_view"===opts.filter){if(!opts.view||"string"!=typeof opts.view){err3=createError(BAD_REQUEST,"`view` filter parameter not found or invalid.");return callback(err3)}viewName=parseDesignDocFunctionName(opts.view);changesHandler.db.get("_design/"+viewName[0],function(err4,ddoc){if(changesHandler.isCancelled)return callback(null,{status:"cancelled"});if(err4)return callback(generateErrorFromResponse(err4));var mapFun=ddoc&&ddoc.views&&ddoc.views[viewName[1]]&&ddoc.views[viewName[1]].map;if(!mapFun)return callback(createError(MISSING_DOC,ddoc.views?"missing json key: "+viewName[1]:"missing json key: views"));opts.filter=evalView(mapFun);changesHandler.doChanges(opts)})}else if(opts.selector){opts.filter=function(doc){return matchesSelector(doc,opts.selector)};changesHandler.doChanges(opts)}else{filterName=parseDesignDocFunctionName(opts.filter);changesHandler.db.get("_design/"+filterName[0],function(err4,ddoc){if(changesHandler.isCancelled)return callback(null,{status:"cancelled"});if(err4)return callback(generateErrorFromResponse(err4));var filterFun=ddoc&&ddoc.filters&&ddoc.filters[filterName[1]];if(!filterFun)return callback(createError(MISSING_DOC,ddoc&&ddoc.filters?"missing json key: "+filterName[1]:"missing json key: filters"));opts.filter=evalFilter(filterFun);changesHandler.doChanges(opts)})}}function tryCatchInChangeListener(self3,change,pending3,lastSeq){try{self3.emit("change",change,pending3,lastSeq)}catch(e3){guardedConsole("error",'Error in .on("change", function):',e3)}}function processChange(doc,metadata,opts){var change,changeList=[{rev:doc._rev}];"all_docs"===opts.style&&(changeList=collectLeaves(metadata.rev_tree).map(function(x3){return{rev:x3.rev}}));change={id:metadata.id,changes:changeList,doc};isDeleted(metadata,doc._rev)&&(change.deleted=!0);if(opts.conflicts){change.doc._conflicts=collectConflicts(metadata);change.doc._conflicts.length||delete change.doc._conflicts}return change}function yankError(callback,docId){return function(err3,results){if(err3||results[0]&&results[0].error){err3=err3||results[0];err3.docId=docId;callback(err3)}else callback(null,results.length?results[0]:results)}}function cleanDocs(docs){var i3,doc,atts,j2,att;for(i3=0;i3<docs.length;i3++){doc=docs[i3];if(doc._deleted)delete doc._attachments;else if(doc._attachments){atts=Object.keys(doc._attachments);for(j2=0;j2<atts.length;j2++){att=atts[j2];doc._attachments[att]=pick(doc._attachments[att],["data","digest","content_type","length","revpos","stub"])}}}}function compareByIdThenRev(a2,b3){if(a2._id===b3._id){const aStart=a2._revisions?a2._revisions.start:0,bStart=b3._revisions?b3._revisions.start:0;return aStart-bStart}return a2._id<b3._id?-1:1}function computeHeight(revs){var height={},edges=[];traverseRevTree(revs,function(isLeaf,pos,id,prnt){var rev$$1=pos+"-"+id;isLeaf&&(height[rev$$1]=0);void 0!==prnt&&edges.push({from:prnt,to:rev$$1});return rev$$1});edges.reverse();edges.forEach(function(edge){void 0===height[edge.from]?height[edge.from]=1+height[edge.to]:height[edge.from]=Math.min(height[edge.from],1+height[edge.to])});return height}function allDocsKeysParse(opts){var keys3="limit"in opts?opts.keys.slice(opts.skip,opts.limit+opts.skip):opts.skip>0?opts.keys.slice(opts.skip):opts.keys;opts.keys=keys3;opts.skip=0;delete opts.limit;if(opts.descending){keys3.reverse();opts.descending=!1}}function doNextCompaction(self3){var task=self3._compactionQueue[0],opts=task.opts,callback=task.callback;self3.get("_local/compaction").catch(function(){return!1}).then(function(doc){doc&&doc.last_seq&&(opts.last_seq=doc.last_seq);self3._compact(opts,function(err3,res2){err3?callback(err3):callback(null,res2);nextTick(function(){self3._compactionQueue.shift();self3._compactionQueue.length&&doNextCompaction(self3)})})})}function appendPurgeSeq(db,docId,rev$$1){return db.get("_local/purges").then(function(doc){const purgeSeq=doc.purgeSeq+1;doc.purges.push({docId,rev:rev$$1,purgeSeq});doc.purges.length>self.purged_infos_limit&&doc.purges.splice(0,doc.purges.length-self.purged_infos_limit);doc.purgeSeq=purgeSeq;return doc}).catch(function(err3){if(404!==err3.status)throw err3;return{_id:"_local/purges",purges:[{docId,rev:rev$$1,purgeSeq:0}],purgeSeq:0}}).then(function(doc){return db.put(doc)})}function attachmentNameError(name){return"_"===name.charAt(0)&&name+" is not a valid attachment name, attachment names cannot start with '_'"}function isNotSingleDoc(doc){return null===doc||"object"!=typeof doc||Array.isArray(doc)}function isValidRev(rev$$1){return"string"==typeof rev$$1&&validRevRegex.test(rev$$1)}function parseAdapter(name,opts){var adapters,preferredAdapters,prefix,adapterName,i3,adapter,usePrefix,match3=name.match(/([a-z-]*):\/\/(.*)/);if(match3)return{name:/https?/.test(match3[1])?match3[1]+"://"+match3[2]:match3[2],adapter:match3[1]};adapters=PouchDB.adapters;preferredAdapters=PouchDB.preferredAdapters;prefix=PouchDB.prefix;adapterName=opts.adapter;if(!adapterName)for(i3=0;i3<preferredAdapters.length;++i3){adapterName=preferredAdapters[i3];if(!("idb"===adapterName&&"websql"in adapters&&hasLocalStorage()&&localStorage["_pouch__websqldb_"+prefix+name]))break;guardedConsole("log",'PouchDB is downgrading "'+name+'" to WebSQL to avoid data loss, because it was already opened with WebSQL.')}adapter=adapters[adapterName];usePrefix=!adapter||!("use_prefix"in adapter)||adapter.use_prefix;return{name:usePrefix?prefix+name:name,adapter:adapterName}}function inherits(A2,B2){A2.prototype=Object.create(B2.prototype,{constructor:{value:A2}})}function createClass(parent,init3){let klass=function(...args){if(!(this instanceof klass))return new klass(...args);init3.apply(this,args)};inherits(klass,parent);return klass}function prepareForDestruction(self3){function onDestroyed(from_constructor){self3.removeListener("closed",onClosed);from_constructor||self3.constructor.emit("destroyed",self3.name)}function onClosed(){self3.removeListener("destroyed",onDestroyed);self3.constructor.emit("unref",self3)}self3.once("destroyed",onDestroyed);self3.once("closed",onClosed);self3.constructor.emit("ref",self3)}function safeJsonParse(str){try{return JSON.parse(str)}catch(e3){return import_vuvuzela.default.parse(str)}}function safeJsonStringify(json){try{return JSON.stringify(json)}catch(e3){return import_vuvuzela.default.stringify(json)}}function checkBlobSupport(txn,store,docIdOrCreateDoc){return new Promise(function(resolve){var blob$$1=createBlob2([""]);let req;if("function"==typeof docIdOrCreateDoc){const createDoc=docIdOrCreateDoc,doc=createDoc(blob$$1);req=txn.objectStore(store).put(doc)}else{const docId=docIdOrCreateDoc;req=txn.objectStore(store).put(blob$$1,docId)}req.onsuccess=function(){var matchedChrome=navigator.userAgent.match(/Chrome\/(\d+)/),matchedEdge=navigator.userAgent.match(/Edge\//);resolve(matchedEdge||!matchedChrome||parseInt(matchedChrome[1],10)>=43)};req.onerror=txn.onabort=function(e3){e3.preventDefault();e3.stopPropagation();resolve(!1)}}).catch(function(){return!1})}function toObject(array){return array.reduce(function(obj,item){obj[item]=!0;return obj},{})}function parseRevisionInfo(rev$$1){var idx2,left,right;if(!/^\d+-/.test(rev$$1))return createError(INVALID_REV);idx2=rev$$1.indexOf("-");left=rev$$1.substring(0,idx2);right=rev$$1.substring(idx2+1);return{prefix:parseInt(left,10),id:right}}function makeRevTreeFromRevisions(revisions,opts){var i3,len,pos=revisions.start-revisions.ids.length+1,revisionIds=revisions.ids,ids=[revisionIds[0],opts,[]];for(i3=1,len=revisionIds.length;i3<len;i3++)ids=[revisionIds[i3],{status:"missing"},[ids]];return[{pos,ids}]}function parseDoc(doc,newEdits,dbOpts){var nRevNum,newRevId,revInfo,opts,result,key3,specialKey,error;dbOpts||(dbOpts={deterministic_revs:!0});opts={status:"available"};doc._deleted&&(opts.deleted=!0);if(newEdits){doc._id||(doc._id=uuid());newRevId=rev2(doc,dbOpts.deterministic_revs);if(doc._rev){revInfo=parseRevisionInfo(doc._rev);if(revInfo.error)return revInfo;doc._rev_tree=[{pos:revInfo.prefix,ids:[revInfo.id,{status:"missing"},[[newRevId,opts,[]]]]}];nRevNum=revInfo.prefix+1}else{doc._rev_tree=[{pos:1,ids:[newRevId,opts,[]]}];nRevNum=1}}else{if(doc._revisions){doc._rev_tree=makeRevTreeFromRevisions(doc._revisions,opts);nRevNum=doc._revisions.start;newRevId=doc._revisions.ids[0]}if(!doc._rev_tree){revInfo=parseRevisionInfo(doc._rev);if(revInfo.error)return revInfo;nRevNum=revInfo.prefix;newRevId=revInfo.id;doc._rev_tree=[{pos:nRevNum,ids:[newRevId,opts,[]]}]}}invalidIdError(doc._id);doc._rev=nRevNum+"-"+newRevId;result={metadata:{},data:{}};for(key3 in doc)if(Object.prototype.hasOwnProperty.call(doc,key3)){specialKey="_"===key3[0];if(specialKey&&!reservedWords[key3]){error=createError(DOC_VALIDATION,key3);error.message=DOC_VALIDATION.message+": "+key3;throw error}specialKey&&!dataWords[key3]?result.metadata[key3.slice(1)]=doc[key3]:result.data[key3]=doc[key3]}return result}function parseBase64(data){try{return thisAtob(data)}catch(e3){var err3=createError(BAD_ARG,"Attachment is not a valid base64 string");return{error:err3}}}function preprocessString(att,blobType,callback){var asBinary=parseBase64(att.data);if(asBinary.error)return callback(asBinary.error);att.length=asBinary.length;att.data="blob"===blobType?binStringToBluffer(asBinary,att.content_type):"base64"===blobType?thisBtoa(asBinary):asBinary;binaryMd5(asBinary,function(result){att.digest="md5-"+result;callback()})}function preprocessBlob(att,blobType,callback){binaryMd5(att.data,function(md5){att.digest="md5-"+md5;att.length=att.data.size||att.data.length||0;"binary"===blobType?blobToBinaryString(att.data,function(binString){att.data=binString;callback()}):"base64"===blobType?blobToBase64(att.data,function(b64){att.data=b64;callback()}):callback()})}function preprocessAttachment(att,blobType,callback){if(att.stub)return callback();"string"==typeof att.data?preprocessString(att,blobType,callback):preprocessBlob(att,blobType,callback)}function preprocessAttachments(docInfos,blobType,callback){function done(){docv++;docInfos.length===docv&&(overallErr?callback(overallErr):callback())}var docv,overallErr;if(!docInfos.length)return callback();docv=0;docInfos.forEach(function(docInfo){function processedAttachment(err3){overallErr=err3;recv++;recv===attachments.length&&done()}var key3,attachments=docInfo.data&&docInfo.data._attachments?Object.keys(docInfo.data._attachments):[],recv=0;if(!attachments.length)return done();for(key3 in docInfo.data._attachments)Object.prototype.hasOwnProperty.call(docInfo.data._attachments,key3)&&preprocessAttachment(docInfo.data._attachments[key3],blobType,processedAttachment)})}function updateDoc(revLimit,prev,docInfo,results,i3,cb2,writeDoc,newEdits){var previousWinningRev,previouslyDeleted,deleted,isRoot,newDoc,merged,inConflict,err3,newRev,winningRev$$1,winningRevIsDeleted,delta,newRevIsDeleted;if(revExists(prev.rev_tree,docInfo.metadata.rev)&&!newEdits){results[i3]=docInfo;return cb2()}previousWinningRev=prev.winningRev||winningRev(prev);previouslyDeleted="deleted"in prev?prev.deleted:isDeleted(prev,previousWinningRev);deleted="deleted"in docInfo.metadata?docInfo.metadata.deleted:isDeleted(docInfo.metadata);isRoot=/^1-/.test(docInfo.metadata.rev);if(previouslyDeleted&&!deleted&&newEdits&&isRoot){newDoc=docInfo.data;newDoc._rev=previousWinningRev;newDoc._id=docInfo.metadata.id;docInfo=parseDoc(newDoc,newEdits)}merged=merge2(prev.rev_tree,docInfo.metadata.rev_tree[0],revLimit);inConflict=newEdits&&(previouslyDeleted&&deleted&&"new_leaf"!==merged.conflicts||!previouslyDeleted&&"new_leaf"!==merged.conflicts||previouslyDeleted&&!deleted&&"new_branch"===merged.conflicts);if(inConflict){err3=createError(REV_CONFLICT);results[i3]=err3;return cb2()}newRev=docInfo.metadata.rev;docInfo.metadata.rev_tree=merged.tree;docInfo.stemmedRevs=merged.stemmedRevs||[];prev.rev_map&&(docInfo.metadata.rev_map=prev.rev_map);winningRev$$1=winningRev(docInfo.metadata);winningRevIsDeleted=isDeleted(docInfo.metadata,winningRev$$1);delta=previouslyDeleted===winningRevIsDeleted?0:previouslyDeleted<winningRevIsDeleted?-1:1;newRevIsDeleted=newRev===winningRev$$1?winningRevIsDeleted:isDeleted(docInfo.metadata,newRev);writeDoc(docInfo,winningRev$$1,winningRevIsDeleted,newRevIsDeleted,!0,delta,i3,cb2)}function rootIsMissing(docInfo){return"missing"===docInfo.metadata.rev_tree[0].ids[1].status}function processDocs(revLimit,docInfos,api,fetchedDocs,tx,results,writeDoc,opts,overallCallback){function insertDoc(docInfo,resultsIdx,callback){var inConflict,err3,delta,winningRev$$1=winningRev(docInfo.metadata),deleted=isDeleted(docInfo.metadata,winningRev$$1);if("was_delete"in opts&&deleted){results[resultsIdx]=createError(MISSING_DOC,"deleted");return callback()}inConflict=newEdits&&rootIsMissing(docInfo);if(inConflict){err3=createError(REV_CONFLICT);results[resultsIdx]=err3;return callback()}delta=deleted?0:1;writeDoc(docInfo,winningRev$$1,deleted,deleted,!1,delta,resultsIdx,callback)}function checkAllDocsDone(){++docsDone===docsToDo&&overallCallback&&overallCallback()}var newEdits,idsToDocs,docsDone,docsToDo;revLimit=revLimit||1e3;newEdits=opts.new_edits;idsToDocs=new Map;docsDone=0;docsToDo=docInfos.length;docInfos.forEach(function(currentDoc,resultsIdx){var fun,id;if(currentDoc._id&&isLocalId(currentDoc._id)){fun=currentDoc._deleted?"_removeLocal":"_putLocal";api[fun](currentDoc,{ctx:tx},function(err3,res2){results[resultsIdx]=err3||res2;checkAllDocsDone()})}else{id=currentDoc.metadata.id;if(idsToDocs.has(id)){docsToDo--;idsToDocs.get(id).push([currentDoc,resultsIdx])}else idsToDocs.set(id,[[currentDoc,resultsIdx]])}});idsToDocs.forEach(function(docs,id){function docWritten(){++numDone<docs.length?nextDoc():checkAllDocsDone()}function nextDoc(){var merged,value=docs[numDone],currentDoc=value[0],resultsIdx=value[1];if(fetchedDocs.has(id))updateDoc(revLimit,fetchedDocs.get(id),currentDoc,results,resultsIdx,docWritten,writeDoc,newEdits);else{merged=merge2([],currentDoc.metadata.rev_tree[0],revLimit);currentDoc.metadata.rev_tree=merged.tree;currentDoc.stemmedRevs=merged.stemmedRevs||[];insertDoc(currentDoc,resultsIdx,docWritten)}}var numDone=0;nextDoc()})}function idbError(callback){return function(evt){var message="unknown_error";evt.target&&evt.target.error&&(message=evt.target.error.name||evt.target.error.message);callback(createError(IDB_ERROR,message,evt.type))}}function encodeMetadata(metadata,winningRev$$1,deleted){return{data:safeJsonStringify(metadata),winningRev:winningRev$$1,deletedOrLocal:deleted?"1":"0",seq:metadata.seq,id:metadata.id}}function decodeMetadata(storedObject){if(!storedObject)return null;var metadata=safeJsonParse(storedObject.data);metadata.winningRev=storedObject.winningRev;metadata.deleted="1"===storedObject.deletedOrLocal;metadata.seq=storedObject.seq;return metadata}function decodeDoc(doc){if(!doc)return doc;var idx2=doc._doc_id_rev.lastIndexOf(":");doc._id=doc._doc_id_rev.substring(0,idx2-1);doc._rev=doc._doc_id_rev.substring(idx2+1);delete doc._doc_id_rev;return doc}function readBlobData(body,type,asBlob,callback){asBlob?callback(body?"string"!=typeof body?body:b64ToBluffer(body,type):createBlob2([""],{type})):body?"string"!=typeof body?readAsBinaryString(body,function(binary){callback(thisBtoa(binary))}):callback(body):callback("")}function fetchAttachmentsIfNecessary(doc,opts,txn,cb2){function checkDone(){++numDone===attachments.length&&cb2&&cb2()}function fetchAttachment(doc2,att){var attObj=doc2._attachments[att],digest=attObj.digest,req=txn.objectStore(ATTACH_STORE).get(digest);req.onsuccess=function(e3){attObj.body=e3.target.result.body;checkDone()}}var numDone,attachments=Object.keys(doc._attachments||{});if(!attachments.length)return cb2&&cb2();numDone=0;attachments.forEach(function(att){if(opts.attachments&&opts.include_docs)fetchAttachment(doc,att);else{doc._attachments[att].stub=!0;checkDone()}})}function postProcessAttachments(results,asBlob){return Promise.all(results.map(function(row){if(row.doc&&row.doc._attachments){var attNames=Object.keys(row.doc._attachments);return Promise.all(attNames.map(function(att){var body,type,attObj=row.doc._attachments[att];if("body"in attObj){body=attObj.body;type=attObj.content_type;return new Promise(function(resolve){readBlobData(body,type,asBlob,function(data){row.doc._attachments[att]=Object.assign(pick(attObj,["digest","content_type"]),{data});resolve()})})}}))}}))}function compactRevs(revs,docId,txn){function checkDone(){count--;count||deleteOrphanedAttachments()}function deleteOrphanedAttachments(){possiblyOrphanedDigests.length&&possiblyOrphanedDigests.forEach(function(digest){var countReq=attAndSeqStore.index("digestSeq").count(IDBKeyRange.bound(digest+"::",digest+"::￿",!1,!1));countReq.onsuccess=function(e3){var count2=e3.target.result;count2||attStore.delete(digest)}})}var possiblyOrphanedDigests=[],seqStore=txn.objectStore(BY_SEQ_STORE),attStore=txn.objectStore(ATTACH_STORE),attAndSeqStore=txn.objectStore(ATTACH_AND_SEQ_STORE),count=revs.length;revs.forEach(function(rev3){var index6=seqStore.index("_doc_id_rev"),key3=docId+"::"+rev3;index6.getKey(key3).onsuccess=function(e3){var cursor,seq=e3.target.result;if("number"!=typeof seq)return checkDone();seqStore.delete(seq);cursor=attAndSeqStore.index("seq").openCursor(IDBKeyRange.only(seq));cursor.onsuccess=function(event2){var digest,cursor2=event2.target.result;if(cursor2){digest=cursor2.value.digestSeq.split("::")[0];possiblyOrphanedDigests.push(digest);attAndSeqStore.delete(cursor2.primaryKey);cursor2.continue()}else checkDone()}}})}function openTransactionSafely(idb,stores,mode){try{return{txn:idb.transaction(stores,mode)}}catch(err3){return{error:err3}}}function idbBulkDocs(dbOpts,req,opts,api,idb,callback){function startTransaction(){var stores=[DOC_STORE,BY_SEQ_STORE,ATTACH_STORE,LOCAL_STORE,ATTACH_AND_SEQ_STORE,META_STORE],txnResult=openTransactionSafely(idb,stores,"readwrite");if(txnResult.error)return callback(txnResult.error);txn=txnResult.txn;txn.onabort=idbError(callback);txn.ontimeout=idbError(callback);txn.oncomplete=complete;docStore=txn.objectStore(DOC_STORE);bySeqStore=txn.objectStore(BY_SEQ_STORE);attachStore=txn.objectStore(ATTACH_STORE);attachAndSeqStore=txn.objectStore(ATTACH_AND_SEQ_STORE);metaStore=txn.objectStore(META_STORE);metaStore.get(META_STORE).onsuccess=function(e3){metaDoc=e3.target.result;updateDocCountIfReady()};verifyAttachments(function(err3){if(err3){preconditionErrored=!0;return callback(err3)}fetchExistingDocs()})}function onAllDocsProcessed(){allDocsProcessed=!0;updateDocCountIfReady()}function idbProcessDocs(){processDocs(dbOpts.revs_limit,docInfos,api,fetchedDocs,txn,results,writeDoc,opts,onAllDocsProcessed)}function updateDocCountIfReady(){if(metaDoc&&allDocsProcessed){metaDoc.docCount+=docCountDelta;metaStore.put(metaDoc)}}function fetchExistingDocs(){function checkDone(){++numFetched===docInfos.length&&idbProcessDocs()}function readMetadata(event2){var metadata=decodeMetadata(event2.target.result);metadata&&fetchedDocs.set(metadata.id,metadata);checkDone()}var numFetched,i4,len2,docInfo,req2;if(docInfos.length){numFetched=0;for(i4=0,len2=docInfos.length;i4<len2;i4++){docInfo=docInfos[i4];if(docInfo._id&&isLocalId(docInfo._id))checkDone();else{req2=docStore.get(docInfo.metadata.id);req2.onsuccess=readMetadata}}}}function complete(){if(!preconditionErrored){changesHandler$1.notify(api._meta.name);callback(null,results)}}function verifyAttachment(digest,callback2){var req2=attachStore.get(digest);req2.onsuccess=function(e3){if(e3.target.result)callback2();else{var err3=createError(MISSING_STUB,"unknown stub attachment with digest "+digest);err3.status=412;callback2(err3)}}}function verifyAttachments(finish){function checkDone(){++numDone===digests.length&&finish(err3)}var numDone,err3,digests=[];docInfos.forEach(function(docInfo){docInfo.data&&docInfo.data._attachments&&Object.keys(docInfo.data._attachments).forEach(function(filename){var att=docInfo.data._attachments[filename];att.stub&&digests.push(att.digest)})});if(!digests.length)return finish();numDone=0;digests.forEach(function(digest){verifyAttachment(digest,function(attErr){attErr&&!err3&&(err3=attErr);checkDone()})})}function writeDoc(docInfo,winningRev$$1,winningRevIsDeleted,newRevIsDeleted,isUpdate,delta,resultsIdx,callback2){var doc2,hasAttachments;docInfo.metadata.winningRev=winningRev$$1;docInfo.metadata.deleted=winningRevIsDeleted;doc2=docInfo.data;doc2._id=docInfo.metadata.id;doc2._rev=docInfo.metadata.rev;newRevIsDeleted&&(doc2._deleted=!0);hasAttachments=doc2._attachments&&Object.keys(doc2._attachments).length;if(hasAttachments)return writeAttachments(docInfo,winningRev$$1,winningRevIsDeleted,isUpdate,resultsIdx,callback2);docCountDelta+=delta;updateDocCountIfReady();finishDoc(docInfo,winningRev$$1,winningRevIsDeleted,isUpdate,resultsIdx,callback2)}function finishDoc(docInfo,winningRev$$1,winningRevIsDeleted,isUpdate,resultsIdx,callback2){function afterPutDoc(e3){var metadataToStore,metaDataReq,revsToDelete=docInfo.stemmedRevs||[];isUpdate&&api.auto_compaction&&(revsToDelete=revsToDelete.concat(compactTree(docInfo.metadata)));revsToDelete&&revsToDelete.length&&compactRevs(revsToDelete,docInfo.metadata.id,txn);metadata.seq=e3.target.result;metadataToStore=encodeMetadata(metadata,winningRev$$1,winningRevIsDeleted);metaDataReq=docStore.put(metadataToStore);metaDataReq.onsuccess=afterPutMetadata}function afterPutMetadata(){results[resultsIdx]={ok:!0,id:metadata.id,rev:metadata.rev};fetchedDocs.set(docInfo.metadata.id,docInfo.metadata);insertAttachmentMappings(docInfo,metadata.seq,callback2)}var putReq,doc2=docInfo.data,metadata=docInfo.metadata;doc2._doc_id_rev=metadata.id+"::"+metadata.rev;delete doc2._id;delete doc2._rev;putReq=bySeqStore.put(doc2);putReq.onsuccess=afterPutDoc;putReq.onerror=function afterPutDocError(e3){var index6,getKeyReq;e3.preventDefault();e3.stopPropagation();index6=bySeqStore.index("_doc_id_rev");getKeyReq=index6.getKey(doc2._doc_id_rev);getKeyReq.onsuccess=function(e4){var putReq2=bySeqStore.put(doc2,e4.target.result);putReq2.onsuccess=afterPutDoc}}}function writeAttachments(docInfo,winningRev$$1,winningRevIsDeleted,isUpdate,resultsIdx,callback2){function collectResults(){numDone===attachments.length&&finishDoc(docInfo,winningRev$$1,winningRevIsDeleted,isUpdate,resultsIdx,callback2)}function attachmentSaved(){numDone++;collectResults()}var doc2=docInfo.data,numDone=0,attachments=Object.keys(doc2._attachments);attachments.forEach(function(key3){var data,digest,att=docInfo.data._attachments[key3];if(att.stub){numDone++;collectResults()}else{data=att.data;delete att.data;att.revpos=parseInt(winningRev$$1,10);digest=att.digest;saveAttachment(digest,data,attachmentSaved)}})}function insertAttachmentMappings(docInfo,seq,callback2){function checkDone(){++attsAdded===attsToAdd.length&&callback2()}function add(att){var digest=docInfo.data._attachments[att].digest,req2=attachAndSeqStore.put({seq,digestSeq:digest+"::"+seq});req2.onsuccess=checkDone;req2.onerror=function(e3){e3.preventDefault();e3.stopPropagation();checkDone()}}var i4,attsAdded=0,attsToAdd=Object.keys(docInfo.data._attachments||{});if(!attsToAdd.length)return callback2();for(i4=0;i4<attsToAdd.length;i4++)add(attsToAdd[i4])}function saveAttachment(digest,data,callback2){var getKeyReq=attachStore.count(digest);getKeyReq.onsuccess=function(e3){var newAtt,putReq,count=e3.target.result;if(count)return callback2();newAtt={digest,body:data};putReq=attachStore.put(newAtt);putReq.onsuccess=callback2}}var txn,docStore,bySeqStore,attachStore,attachAndSeqStore,metaStore,docInfoError,metaDoc,i3,len,doc,allDocsProcessed,docCountDelta,results,fetchedDocs,preconditionErrored,blobType,docInfos=req.docs;for(i3=0,len=docInfos.length;i3<len;i3++){doc=docInfos[i3];if(!doc._id||!isLocalId(doc._id)){doc=docInfos[i3]=parseDoc(doc,opts.new_edits,dbOpts);doc.error&&!docInfoError&&(docInfoError=doc)}}if(docInfoError)return callback(docInfoError);allDocsProcessed=!1;docCountDelta=0;results=new Array(docInfos.length);fetchedDocs=new Map;preconditionErrored=!1;blobType=api._meta.blobSupport?"blob":"base64";preprocessAttachments(docInfos,blobType,function(err3){if(err3)return callback(err3);startTransaction()})}function runBatchedCursor(objectStore,keyRange,descending,batchSize,onBatch){function onGetAll(e3){valuesBatch=e3.target.result;keysBatch&&onBatch(keysBatch,valuesBatch,pseudoCursor)}function onGetAllKeys(e3){keysBatch=e3.target.result;valuesBatch&&onBatch(keysBatch,valuesBatch,pseudoCursor)}function onCursor(e3){var cursor=e3.target.result;if(!cursor)return onBatch();onBatch([cursor.key],[cursor.value],cursor)}var useGetAll,keysBatch,valuesBatch,pseudoCursor;-1===batchSize&&(batchSize=1e3);useGetAll="function"==typeof objectStore.getAll&&"function"==typeof objectStore.getAllKeys&&batchSize>1&&!descending;if(useGetAll){pseudoCursor={continue:function continuePseudoCursor(){var lastKey,newKeyRange;if(!keysBatch.length)return onBatch();lastKey=keysBatch[keysBatch.length-1];if(keyRange&&keyRange.upper)try{newKeyRange=IDBKeyRange.bound(lastKey,keyRange.upper,!0,keyRange.upperOpen)}catch(e3){if("DataError"===e3.name&&0===e3.code)return onBatch()}else newKeyRange=IDBKeyRange.lowerBound(lastKey,!0);keyRange=newKeyRange;keysBatch=null;valuesBatch=null;objectStore.getAll(keyRange,batchSize).onsuccess=onGetAll;objectStore.getAllKeys(keyRange,batchSize).onsuccess=onGetAllKeys}};objectStore.getAll(keyRange,batchSize).onsuccess=onGetAll;objectStore.getAllKeys(keyRange,batchSize).onsuccess=onGetAllKeys}else descending?objectStore.openCursor(keyRange,"prev").onsuccess=onCursor:objectStore.openCursor(keyRange).onsuccess=onCursor}function getAll(objectStore,keyRange,onSuccess){if("function"!=typeof objectStore.getAll){var values2=[];objectStore.openCursor(keyRange).onsuccess=function onCursor(e3){var cursor=e3.target.result;if(cursor){values2.push(cursor.value);cursor.continue()}else onSuccess({target:{result:values2}})}}else objectStore.getAll(keyRange).onsuccess=onSuccess}function allDocsKeys(keys3,docStore,onBatch){var valuesBatch=new Array(keys3.length),count=0;keys3.forEach(function(key3,index6){docStore.get(key3).onsuccess=function(event2){event2.target.result?valuesBatch[index6]=event2.target.result:valuesBatch[index6]={key:key3,error:"not_found"};count++;count===keys3.length&&onBatch(keys3,valuesBatch,{})}})}function createKeyRange(start,end,inclusiveEnd,key3,descending){try{if(start&&end)return descending?IDBKeyRange.bound(end,start,!inclusiveEnd,!1):IDBKeyRange.bound(start,end,!1,!inclusiveEnd);if(start)return descending?IDBKeyRange.upperBound(start):IDBKeyRange.lowerBound(start);if(end)return descending?IDBKeyRange.lowerBound(end,!inclusiveEnd):IDBKeyRange.upperBound(end,!inclusiveEnd);if(key3)return IDBKeyRange.only(key3)}catch(e3){return{error:e3}}return null}function idbAllDocs(opts,idb,callback){function fetchDocAsynchronously(metadata,row,winningRev$$1){var key4=metadata.id+"::"+winningRev$$1;docIdRevIndex.get(key4).onsuccess=function onGetDoc(e3){row.doc=decodeDoc(e3.target.result)||{};if(opts.conflicts){var conflicts=collectConflicts(metadata);conflicts.length&&(row.doc._conflicts=conflicts)}fetchAttachmentsIfNecessary(row.doc,opts,txn)}}function allDocsInner(winningRev$$1,metadata){var row={id:metadata.id,key:metadata.id,value:{rev:winningRev$$1}},deleted=metadata.deleted;if(deleted){if(keys3){results.push(row);row.value.deleted=!0;row.doc=null}}else if(skip--<=0){results.push(row);opts.include_docs&&fetchDocAsynchronously(metadata,row,winningRev$$1)}}function processBatch(batchValues){var i3,len,batchValue,metadata,winningRev$$1;for(i3=0,len=batchValues.length;i3<len&&results.length!==limit;i3++){batchValue=batchValues[i3];if(batchValue.error&&keys3)results.push(batchValue);else{metadata=decodeMetadata(batchValue);winningRev$$1=metadata.winningRev;allDocsInner(winningRev$$1,metadata)}}}function onBatch(batchKeys,batchValues,cursor){if(cursor){processBatch(batchValues);results.length<limit&&cursor.continue()}}function onResultsReady(){var returnVal={total_rows:docCount,offset:opts.skip,rows:results};opts.update_seq&&void 0!==updateSeq&&(returnVal.update_seq=updateSeq);callback(null,returnVal)}var keyRange,keyRangeError,stores,txnResult,txn,docStore,seqStore,metaStore,docIdRevIndex,results,docCount,updateSeq,start="startkey"in opts&&opts.startkey,end="endkey"in opts&&opts.endkey,key3="key"in opts&&opts.key,keys3="keys"in opts&&opts.keys,skip=opts.skip||0,limit="number"==typeof opts.limit?opts.limit:-1,inclusiveEnd=!1!==opts.inclusive_end;if(!keys3){keyRange=createKeyRange(start,end,inclusiveEnd,key3,opts.descending);keyRangeError=keyRange&&keyRange.error;if(keyRangeError&&("DataError"!==keyRangeError.name||0!==keyRangeError.code))return callback(createError(IDB_ERROR,keyRangeError.name,keyRangeError.message))}stores=[DOC_STORE,BY_SEQ_STORE,META_STORE];opts.attachments&&stores.push(ATTACH_STORE);txnResult=openTransactionSafely(idb,stores,"readonly");if(txnResult.error)return callback(txnResult.error);txn=txnResult.txn;txn.oncomplete=function onTxnComplete(){opts.attachments?postProcessAttachments(results,opts.binary).then(onResultsReady):onResultsReady()};txn.onabort=idbError(callback);docStore=txn.objectStore(DOC_STORE);seqStore=txn.objectStore(BY_SEQ_STORE);metaStore=txn.objectStore(META_STORE);docIdRevIndex=seqStore.index("_doc_id_rev");results=[];metaStore.get(META_STORE).onsuccess=function(e3){docCount=e3.target.result.docCount};opts.update_seq&&(seqStore.openKeyCursor(null,"prev").onsuccess=e3=>{var cursor=e3.target.result;cursor&&cursor.key&&(updateSeq=cursor.key)});if(!keyRangeError&&0!==limit){if(keys3)return allDocsKeys(keys3,docStore,onBatch);if(-1===limit)return getAll(docStore,keyRange,function onGetAll(e3){var values2=e3.target.result;opts.descending&&(values2=values2.reverse());processBatch(values2)});runBatchedCursor(docStore,keyRange,opts.descending,limit+skip,onBatch)}}function countDocs(txn,cb2){var index6=txn.objectStore(DOC_STORE).index("deletedOrLocal");index6.count(IDBKeyRange.only("0")).onsuccess=function(e3){cb2(e3.target.result)}}function tryCode(fun,err3,res2,PouchDB2){try{fun(err3,res2)}catch(err4){PouchDB2.emit("error",err4)}}function applyNext(){if(!running&&queue.length){running=!0;queue.shift()()}}function enqueueTask(action2,callback,PouchDB2){queue.push(function runAction(){action2(function runCallback(err3,res2){tryCode(callback,err3,res2,PouchDB2);running=!1;nextTick(function runNext(){applyNext()})})});applyNext()}function changes(opts,api,dbName,idb){function onGetMetadata(doc,seq,metadata,cb2){var docIdRev,req;if(metadata.seq!==seq)return cb2();if(metadata.winningRev===doc._rev)return cb2(metadata,doc);docIdRev=doc._id+"::"+metadata.winningRev;req=docIdRevIndex.get(docIdRev);req.onsuccess=function(e3){cb2(metadata,decodeDoc(e3.target.result))}}function fetchWinningDocAndMetadata(doc,seq,cb2){if(docIds&&!docIds.has(doc._id))return cb2();var metadata=docIdsToMetadata.get(doc._id);if(metadata)return onGetMetadata(doc,seq,metadata,cb2);docStore.get(doc._id).onsuccess=function(e3){metadata=decodeMetadata(e3.target.result);docIdsToMetadata.set(doc._id,metadata);onGetMetadata(doc,seq,metadata,cb2)}}function finish(){opts.complete(null,{results,last_seq:lastSeq})}var id,docIds,lastSeq,limit,results,numResults,filter4,docIdsToMetadata,txn,bySeqStore,docStore,docIdRevIndex,objectStores,txnResult,keyRange;opts=clone2(opts);if(opts.continuous){id=dbName+":"+uuid();changesHandler$1.addListener(dbName,id,api,opts);changesHandler$1.notify(dbName);return{cancel:function(){changesHandler$1.removeListener(dbName,id)}}}docIds=opts.doc_ids&&new Set(opts.doc_ids);opts.since=opts.since||0;lastSeq=opts.since;limit="limit"in opts?opts.limit:-1;0===limit&&(limit=1);results=[];numResults=0;filter4=filterChange(opts);docIdsToMetadata=new Map;objectStores=[DOC_STORE,BY_SEQ_STORE];opts.attachments&&objectStores.push(ATTACH_STORE);txnResult=openTransactionSafely(idb,objectStores,"readonly");if(txnResult.error)return opts.complete(txnResult.error);txn=txnResult.txn;txn.onabort=idbError(opts.complete);txn.oncomplete=function onTxnComplete(){!opts.continuous&&opts.attachments?postProcessAttachments(results).then(finish):finish()};bySeqStore=txn.objectStore(BY_SEQ_STORE);docStore=txn.objectStore(DOC_STORE);docIdRevIndex=bySeqStore.index("_doc_id_rev");keyRange=opts.since&&!opts.descending?IDBKeyRange.lowerBound(opts.since,!0):null;runBatchedCursor(bySeqStore,keyRange,opts.descending,limit,function onBatch(batchKeys,batchValues,cursor){function processMetadataAndWinningDoc(metadata,winningDoc){var filtered,change=opts.processChange(winningDoc,metadata,opts);lastSeq=change.seq=metadata.seq;filtered=filter4(change);if("object"==typeof filtered)return Promise.reject(filtered);if(!filtered)return Promise.resolve();numResults++;opts.return_docs&&results.push(change);return opts.attachments&&opts.include_docs?new Promise(function(resolve){fetchAttachmentsIfNecessary(winningDoc,opts,txn,function(){postProcessAttachments([change],opts.binary).then(function(){resolve(change)})})}):Promise.resolve(change)}function onBatchDone(){var i3,len,winningDoc,metadata,promises=[];for(i3=0,len=winningDocs.length;i3<len&&numResults!==limit;i3++){winningDoc=winningDocs[i3];if(winningDoc){metadata=metadatas[i3];promises.push(processMetadataAndWinningDoc(metadata,winningDoc))}}Promise.all(promises).then(function(changes3){for(var i4=0,len2=changes3.length;i4<len2;i4++)changes3[i4]&&opts.onChange(changes3[i4])}).catch(opts.complete);numResults!==limit&&cursor.continue()}var winningDocs,metadatas,numDone;if(cursor&&batchKeys.length){winningDocs=new Array(batchKeys.length);metadatas=new Array(batchKeys.length);numDone=0;batchValues.forEach(function(value,i3){var doc=decodeDoc(value),seq=batchKeys[i3];fetchWinningDocAndMetadata(doc,seq,function(metadata,winningDoc){metadatas[i3]=metadata;winningDocs[i3]=winningDoc;++numDone===batchKeys.length&&onBatchDone()})})}})}function IdbPouch(opts,callback){var api=this;enqueueTask(function(thisCallback){init2(api,opts,thisCallback)},callback,api.constructor)}function init2(api,opts,callback){function enrichCallbackError(callback2){return function(error,result){error&&error instanceof Error&&!error.reason&&idbGlobalFailureError&&(error.reason=idbGlobalFailureError);callback2(error,result)}}function createSchema(db){var attAndSeqStore,docStore=db.createObjectStore(DOC_STORE,{keyPath:"id"});db.createObjectStore(BY_SEQ_STORE,{autoIncrement:!0}).createIndex("_doc_id_rev","_doc_id_rev",{unique:!0});db.createObjectStore(ATTACH_STORE,{keyPath:"digest"});db.createObjectStore(META_STORE,{keyPath:"id",autoIncrement:!1});db.createObjectStore(DETECT_BLOB_SUPPORT_STORE);docStore.createIndex("deletedOrLocal","deletedOrLocal",{unique:!1});db.createObjectStore(LOCAL_STORE,{keyPath:"_id"});attAndSeqStore=db.createObjectStore(ATTACH_AND_SEQ_STORE,{autoIncrement:!0});attAndSeqStore.createIndex("seq","seq");attAndSeqStore.createIndex("digestSeq","digestSeq",{unique:!0})}function addDeletedOrLocalIndex(txn,callback2){var docStore=txn.objectStore(DOC_STORE);docStore.createIndex("deletedOrLocal","deletedOrLocal",{unique:!1});docStore.openCursor().onsuccess=function(event2){var metadata,deleted,cursor=event2.target.result;if(cursor){metadata=cursor.value;deleted=isDeleted(metadata);metadata.deletedOrLocal=deleted?"1":"0";docStore.put(metadata);cursor.continue()}else callback2()}}function createLocalStoreSchema(db){db.createObjectStore(LOCAL_STORE,{keyPath:"_id"}).createIndex("_doc_id_rev","_doc_id_rev",{unique:!0})}function migrateLocalStore(txn,cb2){var localStore=txn.objectStore(LOCAL_STORE),docStore=txn.objectStore(DOC_STORE),seqStore=txn.objectStore(BY_SEQ_STORE),cursor=docStore.openCursor();cursor.onsuccess=function(event2){var metadata,docId,local,rev3,docIdRev,start,end,index6,range4,seqCursor,cursor2=event2.target.result;if(cursor2){metadata=cursor2.value;docId=metadata.id;local=isLocalId(docId);rev3=winningRev(metadata);if(local){docIdRev=docId+"::"+rev3;start=docId+"::";end=docId+"::~";index6=seqStore.index("_doc_id_rev");range4=IDBKeyRange.bound(start,end,!1,!1);seqCursor=index6.openCursor(range4);seqCursor.onsuccess=function(e3){seqCursor=e3.target.result;if(seqCursor){var data=seqCursor.value;data._doc_id_rev===docIdRev&&localStore.put(data);seqStore.delete(seqCursor.primaryKey);seqCursor.continue()}else{docStore.delete(cursor2.primaryKey);cursor2.continue()}}}else cursor2.continue()}else cb2&&cb2()}}function addAttachAndSeqStore(db){var attAndSeqStore=db.createObjectStore(ATTACH_AND_SEQ_STORE,{autoIncrement:!0});attAndSeqStore.createIndex("seq","seq");attAndSeqStore.createIndex("digestSeq","digestSeq",{unique:!0})}function migrateAttsAndSeqs(txn,callback2){var seqStore=txn.objectStore(BY_SEQ_STORE),attStore=txn.objectStore(ATTACH_STORE),attAndSeqStore=txn.objectStore(ATTACH_AND_SEQ_STORE),req2=attStore.count();req2.onsuccess=function(e3){var count=e3.target.result;if(!count)return callback2();seqStore.openCursor().onsuccess=function(e4){var doc,seq,atts,digestMap,j2,att,digests,digest,cursor=e4.target.result;if(!cursor)return callback2();doc=cursor.value;seq=cursor.primaryKey;atts=Object.keys(doc._attachments||{});digestMap={};for(j2=0;j2<atts.length;j2++){att=doc._attachments[atts[j2]];digestMap[att.digest]=!0}digests=Object.keys(digestMap);for(j2=0;j2<digests.length;j2++){digest=digests[j2];attAndSeqStore.put({seq,digestSeq:digest+"::"+seq})}cursor.continue()}}}function migrateMetadata(txn){function decodeMetadataCompat(storedObject){if(!storedObject.data){storedObject.deleted="1"===storedObject.deletedOrLocal;return storedObject}return decodeMetadata(storedObject)}var bySeqStore=txn.objectStore(BY_SEQ_STORE),docStore=txn.objectStore(DOC_STORE),cursor=docStore.openCursor();cursor.onsuccess=function(e3){function onGetMetadataSeq(){var metadataToStore=encodeMetadata(metadata,metadata.winningRev,metadata.deleted),req2=docStore.put(metadataToStore);req2.onsuccess=function(){cursor2.continue()}}var metadata,cursor2=e3.target.result;if(cursor2){metadata=decodeMetadataCompat(cursor2.value);metadata.winningRev=metadata.winningRev||winningRev(metadata);if(metadata.seq)return onGetMetadataSeq();(function fetchMetadataSeq(){var start=metadata.id+"::",end=metadata.id+"::￿",req2=bySeqStore.index("_doc_id_rev").openCursor(IDBKeyRange.bound(start,end)),metadataSeq=0;req2.onsuccess=function(e4){var seq,cursor3=e4.target.result;if(!cursor3){metadata.seq=metadataSeq;return onGetMetadataSeq()}seq=cursor3.primaryKey;seq>metadataSeq&&(metadataSeq=seq);cursor3.continue()}})()}}}var cached,req,dbName=opts.name,idb=null,idbGlobalFailureError=null;api._meta=null;api._remote=!1;api.type=function(){return"idb"};api._id=toPromise(function(callback2){callback2(null,api._meta.instanceId)});api._bulkDocs=function idb_bulkDocs(req2,reqOpts,callback2){idbBulkDocs(opts,req2,reqOpts,api,idb,enrichCallbackError(callback2))};api._get=function idb_get(id,opts2,callback2){function finish(){callback2(err3,{doc,metadata,ctx:txn})}var doc,metadata,err3,txnResult,txn=opts2.ctx;if(!txn){txnResult=openTransactionSafely(idb,[DOC_STORE,BY_SEQ_STORE,ATTACH_STORE],"readonly");if(txnResult.error)return callback2(txnResult.error);txn=txnResult.txn}txn.objectStore(DOC_STORE).get(id).onsuccess=function(e3){var rev3,deleted,objectStore,key3;metadata=decodeMetadata(e3.target.result);if(!metadata){err3=createError(MISSING_DOC,"missing");return finish()}if(opts2.rev)rev3=opts2.latest?latest(opts2.rev,metadata):opts2.rev;else{rev3=metadata.winningRev;deleted=isDeleted(metadata);if(deleted){err3=createError(MISSING_DOC,"deleted");return finish()}}objectStore=txn.objectStore(BY_SEQ_STORE);key3=metadata.id+"::"+rev3;objectStore.index("_doc_id_rev").get(key3).onsuccess=function(e4){doc=e4.target.result;doc&&(doc=decodeDoc(doc));if(!doc){err3=createError(MISSING_DOC,"missing");return finish()}finish()}}};api._getAttachment=function(docId,attachId,attachment,opts2,callback2){var txn,txnResult,digest,type;if(opts2.ctx)txn=opts2.ctx;else{txnResult=openTransactionSafely(idb,[DOC_STORE,BY_SEQ_STORE,ATTACH_STORE],"readonly");if(txnResult.error)return callback2(txnResult.error);txn=txnResult.txn}digest=attachment.digest;type=attachment.content_type;txn.objectStore(ATTACH_STORE).get(digest).onsuccess=function(e3){var body=e3.target.result.body;readBlobData(body,type,opts2.binary,function(blobData){callback2(null,blobData)})}};api._info=function idb_info(callback2){var updateSeq,docCount,txn,txnResult=openTransactionSafely(idb,[META_STORE,BY_SEQ_STORE],"readonly");if(txnResult.error)return callback2(txnResult.error);txn=txnResult.txn;txn.objectStore(META_STORE).get(META_STORE).onsuccess=function(e3){docCount=e3.target.result.docCount};txn.objectStore(BY_SEQ_STORE).openKeyCursor(null,"prev").onsuccess=function(e3){var cursor=e3.target.result;updateSeq=cursor?cursor.key:0};txn.oncomplete=function(){callback2(null,{doc_count:docCount,update_seq:updateSeq,idb_attachment_format:api._meta.blobSupport?"binary":"base64"})}};api._allDocs=function idb_allDocs(opts2,callback2){idbAllDocs(opts2,idb,enrichCallbackError(callback2))};api._changes=function idbChanges2(opts2){return changes(opts2,api,dbName,idb)};api._close=function(callback2){idb.close();cachedDBs.delete(dbName);callback2()};api._getRevisionTree=function(docId,callback2){var txn,req2,txnResult=openTransactionSafely(idb,[DOC_STORE],"readonly");if(txnResult.error)return callback2(txnResult.error);txn=txnResult.txn;req2=txn.objectStore(DOC_STORE).get(docId);req2.onsuccess=function(event2){var doc=decodeMetadata(event2.target.result);doc?callback2(null,doc.rev_tree):callback2(createError(MISSING_DOC))}};api._doCompaction=function(docId,revs,callback2){var txn,docStore,stores=[DOC_STORE,BY_SEQ_STORE,ATTACH_STORE,ATTACH_AND_SEQ_STORE],txnResult=openTransactionSafely(idb,stores,"readwrite");if(txnResult.error)return callback2(txnResult.error);txn=txnResult.txn;docStore=txn.objectStore(DOC_STORE);docStore.get(docId).onsuccess=function(event2){var winningRev$$1,deleted,metadata=decodeMetadata(event2.target.result);traverseRevTree(metadata.rev_tree,function(isLeaf,pos,revHash,ctx,opts2){var rev3=pos+"-"+revHash;-1!==revs.indexOf(rev3)&&(opts2.status="missing")});compactRevs(revs,docId,txn);winningRev$$1=metadata.winningRev;deleted=metadata.deleted;txn.objectStore(DOC_STORE).put(encodeMetadata(metadata,winningRev$$1,deleted))};txn.onabort=idbError(callback2);txn.oncomplete=function(){callback2()}};api._getLocal=function(id,callback2){var tx,req2,txnResult=openTransactionSafely(idb,[LOCAL_STORE],"readonly");if(txnResult.error)return callback2(txnResult.error);tx=txnResult.txn;req2=tx.objectStore(LOCAL_STORE).get(id);req2.onerror=idbError(callback2);req2.onsuccess=function(e3){var doc=e3.target.result;if(doc){delete doc._doc_id_rev;callback2(null,doc)}else callback2(createError(MISSING_DOC))}};api._putLocal=function(doc,opts2,callback2){var oldRev,id,tx,ret,txnResult,oStore,req2;if("function"==typeof opts2){callback2=opts2;opts2={}}delete doc._revisions;oldRev=doc._rev;id=doc._id;doc._rev=oldRev?"0-"+(parseInt(oldRev.split("-")[1],10)+1):"0-1";tx=opts2.ctx;if(!tx){txnResult=openTransactionSafely(idb,[LOCAL_STORE],"readwrite");if(txnResult.error)return callback2(txnResult.error);tx=txnResult.txn;tx.onerror=idbError(callback2);tx.oncomplete=function(){ret&&callback2(null,ret)}}oStore=tx.objectStore(LOCAL_STORE);if(oldRev){req2=oStore.get(id);req2.onsuccess=function(e3){var req3,oldDoc=e3.target.result;if(oldDoc&&oldDoc._rev===oldRev){req3=oStore.put(doc);req3.onsuccess=function(){ret={ok:!0,id:doc._id,rev:doc._rev};opts2.ctx&&callback2(null,ret)}}else callback2(createError(REV_CONFLICT))}}else{req2=oStore.add(doc);req2.onerror=function(e3){callback2(createError(REV_CONFLICT));e3.preventDefault();e3.stopPropagation()};req2.onsuccess=function(){ret={ok:!0,id:doc._id,rev:doc._rev};opts2.ctx&&callback2(null,ret)}}};api._removeLocal=function(doc,opts2,callback2){var tx,txnResult,ret,id,oStore,req2;if("function"==typeof opts2){callback2=opts2;opts2={}}tx=opts2.ctx;if(!tx){txnResult=openTransactionSafely(idb,[LOCAL_STORE],"readwrite");if(txnResult.error)return callback2(txnResult.error);tx=txnResult.txn;tx.oncomplete=function(){ret&&callback2(null,ret)}}id=doc._id;oStore=tx.objectStore(LOCAL_STORE);req2=oStore.get(id);req2.onerror=idbError(callback2);req2.onsuccess=function(e3){var oldDoc=e3.target.result;if(oldDoc&&oldDoc._rev===doc._rev){oStore.delete(id);ret={ok:!0,id,rev:"0-0"};opts2.ctx&&callback2(null,ret)}else callback2(createError(MISSING_DOC))}};api._destroy=function(opts2,callback2){var openReq,req2;changesHandler$1.removeAllListeners(dbName);openReq=openReqList.get(dbName);if(openReq&&openReq.result){openReq.result.close();cachedDBs.delete(dbName)}req2=indexedDB.deleteDatabase(dbName);req2.onsuccess=function(){openReqList.delete(dbName);hasLocalStorage()&&dbName in localStorage&&delete localStorage[dbName];callback2(null,{ok:!0})};req2.onerror=idbError(callback2)};cached=cachedDBs.get(dbName);if(cached){idb=cached.idb;api._meta=cached.global;return nextTick(function(){callback(null,api)})}req=indexedDB.open(dbName,ADAPTER_VERSION);openReqList.set(dbName,req);req.onupgradeneeded=function(e3){var txn,migrations,i3,db=e3.target.result;if(e3.oldVersion<1)return createSchema(db);txn=e3.currentTarget.transaction;e3.oldVersion<3&&createLocalStoreSchema(db);e3.oldVersion<4&&addAttachAndSeqStore(db);migrations=[addDeletedOrLocalIndex,migrateLocalStore,migrateAttsAndSeqs,migrateMetadata];i3=e3.oldVersion;(function next2(){var migration=migrations[i3-1];i3++;migration&&migration(txn,next2)})()};req.onsuccess=function(e3){function completeSetup(){if(void 0!==blobSupport&&storedMetaDoc){api._meta={name:dbName,instanceId,blobSupport};cachedDBs.set(dbName,{idb,global:api._meta});callback(null,api)}}function storeMetaDocIfReady(){if(void 0!==docCount&&void 0!==metaDoc){var instanceKey=dbName+"_id";instanceKey in metaDoc?instanceId=metaDoc[instanceKey]:metaDoc[instanceKey]=instanceId=uuid();metaDoc.docCount=docCount;txn.objectStore(META_STORE).put(metaDoc)}}var txn,storedMetaDoc,metaDoc,docCount,blobSupport,instanceId;idb=e3.target.result;idb.onversionchange=function(){idb.close();cachedDBs.delete(dbName)};idb.onabort=function(e4){guardedConsole("error","Database has a global failure",e4.target.error);idbGlobalFailureError=e4.target.error;idb.close();cachedDBs.delete(dbName)};txn=idb.transaction([META_STORE,DETECT_BLOB_SUPPORT_STORE,DOC_STORE],"readwrite");storedMetaDoc=!1;txn.objectStore(META_STORE).get(META_STORE).onsuccess=function(e4){metaDoc=e4.target.result||{id:META_STORE};storeMetaDocIfReady()};countDocs(txn,function(count){docCount=count;storeMetaDocIfReady()});blobSupportPromise||(blobSupportPromise=checkBlobSupport(txn,DETECT_BLOB_SUPPORT_STORE,"key"));blobSupportPromise.then(function(val){blobSupport=val;completeSetup()});txn.oncomplete=function(){storedMetaDoc=!0;completeSetup()};txn.onabort=idbError(callback)};req.onerror=function(e3){var msg=e3.target.error&&e3.target.error.message;msg?-1!==msg.indexOf("stored database is a higher version")&&(msg=new Error('This DB was created with the newer "indexeddb" adapter, but you are trying to open it with the older "idb" adapter')):msg="Failed to open indexedDB, are you in private browsing mode?";guardedConsole("error",msg);callback(createError(IDB_ERROR,msg))}}function needsSanitise(name,isPath){return isPath?TEST_PATH_INVALID.test(name):TEST_KEY_INVALID.test(name)}function sanitise(name,isPath){const correctCharacters=function(match3){let good="";for(let i3=0;i3<match3.length;i3++){const code=match3.charCodeAt(i3);if(code===IS_DOT&&isPath&&0===i3)good+=".";else{if(code===SLASH&&isPath)continue;good+="_c"+code+"_"}}return good};return isPath?name.replace(PATH_INVALID,correctCharacters):name.replace(KEY_INVALID,correctCharacters)}function needsRewrite(data){for(const key3 of Object.keys(data)){if(needsSanitise(key3))return!0;if(null===data[key3]||"boolean"==typeof data[key3])return!0;if("object"==typeof data[key3])return needsRewrite(data[key3])}}function rewrite(data){if(!needsRewrite(data))return!1;const isArray2=Array.isArray(data),clone3=isArray2?[]:{};Object.keys(data).forEach(function(key3){const safeKey=isArray2?key3:sanitise(key3);null===data[key3]?clone3[safeKey]=IDB_NULL:"boolean"==typeof data[key3]?clone3[safeKey]=data[key3]?IDB_TRUE:IDB_FALSE:"object"==typeof data[key3]?clone3[safeKey]=rewrite(data[key3]):clone3[safeKey]=data[key3]});return clone3}function idbError2(callback){return function(evt){let message="unknown_error";evt.target&&evt.target.error&&(message=evt.target.error.name||evt.target.error.message);callback(createError(IDB_ERROR,message,evt.type))}}function processAttachment(name,src,doc,isBinary,attachmentFormat){delete doc._attachments[name].stub;if("base64"===attachmentFormat){if(isBinary){const att=src.attachments[doc._attachments[name].digest];doc._attachments[name].data=b64ToBluffer(att.data,att.content_type)}else doc._attachments[name].data=src.attachments[doc._attachments[name].digest].data;delete doc._attachments[name].length;return Promise.resolve()}if(isBinary){doc._attachments[name].data=src.attachments[doc._attachments[name].digest].data;return Promise.resolve()}return new Promise(function(resolve){const data=src.attachments[doc._attachments[name].digest].data;readAsBinaryString(data,function(binString){doc._attachments[name].data=thisBtoa(binString);delete doc._attachments[name].length;resolve()})})}function rawIndexFields(ddoc,viewName){const fields=ddoc.views[viewName].options&&ddoc.views[viewName].options.def&&ddoc.views[viewName].options.def.fields||[];return fields.map(function(field){return"string"==typeof field?field:Object.keys(field)[0]})}function isPartialFilterView(ddoc,viewName){return viewName in ddoc.views&&ddoc.views[viewName].options&&ddoc.views[viewName].options.def&&ddoc.views[viewName].options.def.partial_filter_selector}function naturalIndexName(fields){return"_find_idx/"+fields.join("/")}function correctIndexFields(fields){return["deleted"].concat(fields.map(function(field){return["_id","_rev","_deleted","_attachments"].includes(field)?field.substr(1):"data."+sanitise(field,!0)}))}function createIdbVersion(){return versionMultiplier*POUCHDB_IDB_VERSION+(new Date).getTime()}function getPouchDbVersion(version2){return Math.floor(version2/versionMultiplier)}function maintainNativeIndexes(openReq,reject){const docStore=openReq.transaction.objectStore(DOC_STORE2),ddocsReq=docStore.getAll(IDBKeyRange.bound("_design/","_design/￿"));ddocsReq.onsuccess=function(e3){const results=e3.target.result,existingIndexNames=Array.from(docStore.indexNames),expectedIndexes=results.filter(function(row){return 0===row.deleted&&row.revs[row.rev].data.views}).map(function(row){return row.revs[row.rev].data}).reduce(function(indexes2,ddoc){return Object.keys(ddoc.views).reduce(function(acc,viewName){const fields=rawIndexFields(ddoc,viewName);fields&&fields.length>0&&(acc[naturalIndexName(fields)]=correctIndexFields(fields));return acc},indexes2)},{}),expectedIndexNames=Object.keys(expectedIndexes),systemIndexNames=["seq","deleted,id"];existingIndexNames.forEach(function(index6){-1===systemIndexNames.indexOf(index6)&&-1===expectedIndexNames.indexOf(index6)&&docStore.deleteIndex(index6)});const newIndexNames=expectedIndexNames.filter(function(ei){return-1===existingIndexNames.indexOf(ei)});try{newIndexNames.forEach(function(indexName){docStore.createIndex(indexName,expectedIndexes[indexName])})}catch(err3){reject(err3)}}}function upgradePouchDbSchema(dbName,db,tx,pouchdbVersion){if(pouchdbVersion<1){const docStore=db.createObjectStore(DOC_STORE2,{keyPath:"id"});docStore.createIndex("seq","seq",{unique:!0});db.createObjectStore(META_LOCAL_STORE,{keyPath:"id"})}if(pouchdbVersion<2){const docStore=tx.objectStore(DOC_STORE2);docStore.createIndex("deleted,id",["deleted","id"],{unique:!0});dbName.includes("-mrview-")&&docStore.deleteIndex("seq")}}function openDatabase(openDatabases2,api,opts,resolve,reject){const openReq=opts.versionChangedWhileOpen?indexedDB.open(opts.name):indexedDB.open(opts.name,createIdbVersion());openReq.onupgradeneeded=function(e3){if(e3.oldVersion>0&&e3.oldVersion<versionMultiplier)throw new Error('Incorrect adapter: you should specify the "idb" adapter to open this DB');if(0===e3.oldVersion&&e3.newVersion<versionMultiplier){indexedDB.deleteDatabase(opts.name);throw new Error("Database was deleted while open")}const tx=e3.target.transaction,db=e3.target.result,pouchdbVersion=getPouchDbVersion(e3.oldVersion);upgradePouchDbSchema(opts.name,db,tx,pouchdbVersion);maintainNativeIndexes(openReq,reject);if(pouchdbVersion<2){const docStore=openReq.transaction.objectStore(DOC_STORE2),metaStore=openReq.transaction.objectStore(META_LOCAL_STORE),allDocsReq=docStore.openCursor();allDocsReq.onsuccess=event2=>{const cursor=event2.target.result;if(!cursor)return;const doc=cursor.value;if(!isLocalId(doc.id))return cursor.continue();metaStore.put(doc).onsuccess=()=>{cursor.delete(doc).onsuccess=()=>{cursor.continue()}}}}};openReq.onblocked=function(e3){console.error("onblocked, this should never happen",e3)};openReq.onsuccess=function(e3){const idb=e3.target.result;idb.onabort=function(e4){console.error("Database has a global failure",e4.target.error);delete openDatabases2[opts.name];idb.close()};idb.onversionchange=function(){console.log("Database was made stale, closing handle");openDatabases2[opts.name].versionChangedWhileOpen=!0;idb.close()};idb.onclose=function(){console.log("Database was made stale, closing handle");opts.name in openDatabases2&&(openDatabases2[opts.name].versionChangedWhileOpen=!0)};let metadata={id:META_LOCAL_STORE};const txn=idb.transaction([META_LOCAL_STORE],"readwrite");txn.oncomplete=function(){resolve({idb,metadata})};const metaStore=txn.objectStore(META_LOCAL_STORE);metaStore.get(META_LOCAL_STORE).onsuccess=function(e4){metadata=e4.target.result||metadata;let changed=!1;if(!("doc_count"in metadata)){changed=!0;metadata.doc_count=0}if(!("seq"in metadata)){changed=!0;metadata.seq=0}if(!("db_uuid"in metadata)){changed=!0;metadata.db_uuid=uuid()}if("idb_attachment_format"in metadata){if(changed){api.blobSupport=metadata.idb_attachment_format;metaStore.put(metadata)}}else{const createBlobDoc=blob=>({id:"blob-support",blob});checkBlobSupport(txn,META_LOCAL_STORE,createBlobDoc).then(blobSupport=>{api.blobSupport=metadata.idb_attachment_format=blobSupport?"binary":"base64";metaStore.put(metadata)})}}};openReq.onerror=function(e3){reject(e3.target.error)}}function setup(openDatabases2,api,opts){if(!openDatabases2[opts.name]||openDatabases2[opts.name].versionChangedWhileOpen){opts.versionChangedWhileOpen=openDatabases2[opts.name]&&openDatabases2[opts.name].versionChangedWhileOpen;openDatabases2[opts.name]=new Promise(function(resolve,reject){openDatabase(openDatabases2,api,opts,resolve,reject)})}return openDatabases2[opts.name]}function info2(metadata,callback){callback(null,{doc_count:metadata.doc_count,update_seq:metadata.seq})}function get4(txn,id,opts,callback){if(txn.error)return callback(txn.error);txn.txn.objectStore(DOC_STORE2).get(id).onsuccess=function(e3){const doc=e3.target.result;let rev3;rev3=opts.rev?opts.latest?latest(opts.rev,doc):opts.rev:doc&&doc.rev;if(!doc||doc.deleted&&!opts.rev||!(rev3 in doc.revs)){callback(createError(MISSING_DOC,"missing"));return}const result=doc.revs[rev3].data;result._id=doc.id;result._rev=rev3;callback(null,{doc:result,metadata:doc,ctx:txn})}}function getLocal(txn,id,api,callback){if(txn.error)return callback(txn.error);txn.txn.objectStore(META_LOCAL_STORE).get(id).onsuccess=function(e3){const doc=e3.target.result;if(!doc){callback(createError(MISSING_DOC,"missing"));return}const result=doc.revs[doc.rev].data;result._id=doc.id;result._rev=doc.rev;if(result._attachments){const processing=[];for(const name in result._attachments)processing.push(processAttachment(name,doc,result,BINARY_ATTACHMENTS,api.blobSupport));Promise.all(processing).then(()=>callback(null,result)).catch(callback)}else callback(null,result)}}function getAttachment(docId,attachId,attachment,opts,cb2){if(isLocalId(docId)){cb2(createError(MISSING_DOC,"missing"));return}const doc=opts.metadata,data=doc.attachments[attachment.digest].data;if("string"!=typeof data){if(opts.binary)return cb2(null,data);readAsBinaryString(data,function(binString){cb2(null,thisBtoa(binString))})}else opts.binary?cb2(null,b64ToBluffer(data,attachment.content_type)):cb2(null,data)}function bulkDocs(api,req,opts,metadata,dbOpts,idbChanges2,callback){function docsRevsLimit(doc){return isLocalId(doc.id)?1:revsLimit}function rootIsMissing2(doc){return"missing"===doc.rev_tree[0].ids[1].status}function fetchExistingDocs(txn2,docs2){function readDone(e3){e3.target.result&&(oldDocs[e3.target.result.id]=e3.target.result);++fetched===docs2.length&&processDocs2(txn2,docs2,oldDocs)}let fetched=0;const oldDocs={};docs2.forEach(function(doc){const docStore=isLocalId(doc.id)?META_LOCAL_STORE:DOC_STORE2;txn2.objectStore(docStore).get(doc.id).onsuccess=readDone})}function revHasAttachment(doc,rev3,digest){return doc.revs[rev3]&&doc.revs[rev3].data._attachments&&Object.values(doc.revs[rev3].data._attachments).find(function(att){return att.digest===digest})}function processDocs2(txn2,docs2,oldDocs){docs2.forEach(function(doc,i3){let newDoc;if("was_delete"in opts&&!Object.prototype.hasOwnProperty.call(oldDocs,doc.id))newDoc=createError(MISSING_DOC,"deleted");else if(opts.new_edits&&!Object.prototype.hasOwnProperty.call(oldDocs,doc.id)&&rootIsMissing2(doc))newDoc=createError(REV_CONFLICT);else if(Object.prototype.hasOwnProperty.call(oldDocs,doc.id)){newDoc=update2(txn2,doc,oldDocs[doc.id]);if(0==newDoc)return}else{const merged=merge2([],doc.rev_tree[0],docsRevsLimit(doc));doc.rev_tree=merged.tree;doc.stemmedRevs=merged.stemmedRevs;newDoc=doc;newDoc.isNewDoc=!0;newDoc.wasDeleted=doc.revs[doc.rev].deleted?1:0}if(newDoc.error)results[i3]=newDoc;else{oldDocs[newDoc.id]=newDoc;lastWriteIndex=i3;write(txn2,newDoc,i3)}})}function convertDocFormat(doc){const newDoc={id:doc.metadata.id,rev:doc.metadata.rev,rev_tree:doc.metadata.rev_tree,revs:doc.metadata.revs||{}};newDoc.revs[newDoc.rev]={data:doc.data,deleted:doc.metadata.deleted};return newDoc}function update2(txn2,doc,oldDoc){if(doc.rev in oldDoc.revs&&!opts.new_edits)return!1;const isRoot=/^1-/.test(doc.rev);if(oldDoc.deleted&&!doc.deleted&&opts.new_edits&&isRoot){const tmp=doc.revs[doc.rev].data;tmp._rev=oldDoc.rev;tmp._id=oldDoc.id;doc=convertDocFormat(parseDoc(tmp,opts.new_edits,dbOpts))}const merged=merge2(oldDoc.rev_tree,doc.rev_tree[0],docsRevsLimit(doc));doc.stemmedRevs=merged.stemmedRevs;doc.rev_tree=merged.tree;const revs=oldDoc.revs;revs[doc.rev]=doc.revs[doc.rev];doc.revs=revs;doc.attachments=oldDoc.attachments;const inConflict=opts.new_edits&&(oldDoc.deleted&&doc.deleted||!oldDoc.deleted&&"new_leaf"!==merged.conflicts||oldDoc.deleted&&!doc.deleted&&"new_branch"===merged.conflicts||oldDoc.rev===doc.rev);if(inConflict)return createError(REV_CONFLICT);doc.wasDeleted=oldDoc.deleted;return doc}function write(txn2,doc,i3){const winningRev$$1=winningRev(doc),writtenRev=doc.rev,isLocal=isLocalId(doc.id),theDoc=doc.revs[winningRev$$1].data,isNewDoc=doc.isNewDoc;if(rewriteEnabled){const result=rewrite(theDoc);if(result){doc.data=result;delete doc.data._attachments}else doc.data=theDoc}else doc.data=theDoc;doc.rev=winningRev$$1;doc.deleted=doc.revs[winningRev$$1].deleted?1:0;if(!isLocal){doc.seq=++metadata.seq;let delta=0;doc.isNewDoc?delta=doc.deleted?0:1:doc.wasDeleted!==doc.deleted&&(delta=doc.deleted?-1:1);metadata.doc_count+=delta}delete doc.isNewDoc;delete doc.wasDeleted;let revsToDelete=doc.stemmedRevs||[];if(autoCompaction&&!isNewDoc){const result=compactTree(doc);result.length&&(revsToDelete=revsToDelete.concat(result))}revsToDelete.length&&revsToDelete.forEach(function(rev3){delete doc.revs[rev3]});delete doc.stemmedRevs;"attachments"in doc||(doc.attachments={});if(theDoc._attachments)for(const k2 in theDoc._attachments){const attachment=theDoc._attachments[k2];if(attachment.stub){if(!(attachment.digest in doc.attachments)){error=createError(MISSING_STUB);txn2.abort();return}revHasAttachment(doc,writtenRev,attachment.digest)&&(doc.attachments[attachment.digest].revs[writtenRev]=!0)}else{doc.attachments[attachment.digest]=attachment;doc.attachments[attachment.digest].revs={};doc.attachments[attachment.digest].revs[writtenRev]=!0;theDoc._attachments[k2]={stub:!0,digest:attachment.digest,content_type:attachment.content_type,length:attachment.length,revpos:parseInt(writtenRev,10)}}}if(isLocal&&doc.deleted){txn2.objectStore(META_LOCAL_STORE).delete(doc.id).onsuccess=function(){results[i3]={ok:!0,id:doc.id,rev:"0-0"}};updateSeq(i3);return}const docStore=isLocal?META_LOCAL_STORE:DOC_STORE2;txn2.objectStore(docStore).put(doc).onsuccess=function(){results[i3]={ok:!0,id:doc.id,rev:writtenRev};updateSeq(i3)}}function updateSeq(i3){i3===lastWriteIndex&&txn.objectStore(META_LOCAL_STORE).put(metadata)}function preProcessAttachment(attachment){if(attachment.stub)return Promise.resolve(attachment);let binData;if("string"==typeof attachment.data){try{binData=thisAtob(attachment.data)}catch(e3){return Promise.reject(createError(BAD_ARG,"Attachment is not a valid base64 string"))}"binary"===metadata.idb_attachment_format&&(attachment.data=binStringToBluffer(binData,attachment.content_type))}else{binData=attachment.data;if("base64"===metadata.idb_attachment_format)return new Promise(resolve=>{blobToBase64(attachment.data,function(b64){attachment.data=b64;binaryMd5(binData,function(result){attachment.digest="md5-"+result;attachment.length=binData.size||binData.length||0;resolve(attachment)})})})}return new Promise(function(resolve){binaryMd5(binData,function(result){attachment.digest="md5-"+result;attachment.length=binData.size||binData.length||0;resolve(attachment)})})}let txn,error;const results=[],docs=[];let lastWriteIndex;const revsLimit=dbOpts.revs_limit||1e3,rewriteEnabled=-1===dbOpts.name.indexOf("-mrview-"),autoCompaction=dbOpts.auto_compaction;for(let i3=0,len=req.docs.length;i3<len;i3++){let result;try{result=parseDoc(req.docs[i3],opts.new_edits,dbOpts)}catch(err3){result=err3}if(result.error)return callback(result);docs.push(convertDocFormat(result))}(function preProcessAttachments(){const promises=docs.map(function(doc){const data=doc.revs[doc.rev].data;if(!data._attachments)return Promise.resolve(data);const attachments=Object.keys(data._attachments).map(function(k2){data._attachments[k2].name=k2;return preProcessAttachment(data._attachments[k2])});return Promise.all(attachments).then(function(newAttachments){const processed={};newAttachments.forEach(function(attachment){processed[attachment.name]=attachment;delete attachment.name});data._attachments=processed;return data})});return Promise.all(promises)})().then(function(){api._openTransactionSafely([DOC_STORE2,META_LOCAL_STORE],"readwrite",function(err3,_txn){if(err3)return callback(err3);txn=_txn;txn.onabort=function(){callback(error||createError(UNKNOWN_ERROR,"transaction was aborted"))};txn.ontimeout=idbError2(callback);txn.oncomplete=function(){idbChanges2.notify(dbOpts.name);callback(null,results)};fetchExistingDocs(txn,docs)})}).catch(function(err3){callback(err3)})}function allDocsKeys2(keys3,docStore,allDocsInner){const valuesBatch=new Array(keys3.length);let count=0;keys3.forEach(function(key3,index6){docStore.get(key3).onsuccess=function(event2){event2.target.result?valuesBatch[index6]=event2.target.result:valuesBatch[index6]={key:key3,error:"not_found"};count++;count===keys3.length&&valuesBatch.forEach(function(doc){allDocsInner(doc)})}})}function createKeyRange2(start,end,inclusiveStart,inclusiveEnd,key3,descending){try{return key3?IDBKeyRange.only([0,key3]):descending?IDBKeyRange.bound(end,start,!inclusiveEnd,!inclusiveStart):IDBKeyRange.bound(start,end,!inclusiveStart,!inclusiveEnd)}catch(e3){return{error:e3}}}function handleKeyRangeError(opts,metadata,err3,callback){if("DataError"===err3.name&&0===err3.code){const returnVal={total_rows:metadata.doc_count,offset:opts.skip,rows:[]};opts.update_seq&&(returnVal.update_seq=metadata.seq);return callback(null,returnVal)}callback(createError(IDB_ERROR,err3.name,err3.message))}function allDocs(txn,metadata,opts,callback){function include_doc(row,doc){const docData=doc.revs[doc.rev].data;row.doc=docData;row.doc._id=doc.id;row.doc._rev=doc.rev;if(opts.conflicts){const conflicts=collectConflicts(doc);conflicts.length&&(row.doc._conflicts=conflicts)}if(opts.attachments&&docData._attachments)for(const name in docData._attachments)processing.push(processAttachment(name,doc,row.doc,opts.binary,metadata.idb_attachment_format))}function onTxnComplete(){const returnVal={total_rows:metadata.doc_count,offset:0,rows:results};opts.update_seq&&(returnVal.update_seq=metadata.seq);processing.length?Promise.all(processing).then(function(){callback(null,returnVal)}):callback(null,returnVal)}async function fetchResults(){function fetchNextBatch(kr2){return new Promise(resolve=>{dbIndex.getAll(kr2,100).onsuccess=e3=>{const batch=e3.target.result;for(let i3=0;i3<batch.length;++i3){const doc=batch[i3],row={id:doc.id,key:doc.id,value:{rev:doc.rev}};opts.include_docs&&include_doc(row,doc);results.push(row)}if(batch.length>=100){const lastSeenKey=[0,batch[batch.length-1].id],startKey=descending?kr2.upper:lastSeenKey,endKey=descending?lastSeenKey:kr2.upper;if(startKey[1]!==endKey[1]){const incEnd=!descending&&inclusiveEnd,incStart=!!descending;return resolve(createKeyRange2(startKey,endKey,incStart,incEnd,key3,descending))}}return resolve()}})}let kr=keyRange;do{kr=await fetchNextBatch(kr)}while(kr);descending&&results.reverse();return txn.txn.commit()}if(txn.error)return callback(txn.error);if(0===opts.limit){const returnVal={total_rows:metadata.doc_count,offset:opts.skip,rows:[]};opts.update_seq&&(returnVal.update_seq=metadata.seq);return callback(null,returnVal)}const results=[],processing=[],key3="key"in opts&&opts.key,keys3="keys"in opts&&opts.keys;let skip=opts.skip||0,limit="number"==typeof opts.limit?opts.limit:void 0;const inclusiveEnd=!1!==opts.inclusive_end,descending="descending"in opts&&opts.descending?"prev":null,start="startkey"in opts?opts.startkey:descending?"￿":"",end="endkey"in opts?opts.endkey:descending?"":"￿",docStore=txn.txn.objectStore(DOC_STORE2);if(keys3){txn.txn.oncomplete=onTxnComplete;const allDocsInner=doc=>{if(doc.error)return results.push(doc);const row={id:doc.id,key:doc.id,value:{rev:doc.rev}};if(doc.deleted){row.value.deleted=!0;row.doc=null}else opts.include_docs&&include_doc(row,doc);results.push(row)};return allDocsKeys2(keys3,docStore,allDocsInner)}let keyRange=createKeyRange2([0,start],[0,end],!0,inclusiveEnd,key3,descending);if(keyRange.error)return handleKeyRangeError(opts,metadata,keyRange.error,callback);txn.txn.oncomplete=onTxnComplete;const dbIndex=docStore.index("deleted,id");if(skip||limit){let firstKey,limitKey=limit>0;dbIndex.openKeyCursor(keyRange,descending||"next").onsuccess=e3=>{const cursor=e3.target.result;if(skip){if(!cursor)return txn.txn.commit();cursor.advance(skip);skip=0}else{if(void 0===firstKey){firstKey=cursor&&cursor.key;if(!firstKey)return txn.txn.commit()}if(limit){if(limit>1&&cursor){cursor.advance(limit-1);limit=void 0;return}limit=void 0}limitKey&&(limitKey=cursor&&cursor.key);limitKey||(limitKey=descending?keyRange.lower:keyRange.upper);keyRange=createKeyRange2(firstKey,limitKey,!0,inclusiveEnd,key3,descending);if(keyRange.error){txn.txn.abort();return handleKeyRangeError(opts,metadata,keyRange.error,callback)}fetchResults()}}}else fetchResults()}function changes2(txn,idbChanges2,api,dbOpts,opts){if(txn.error)return opts.complete(txn.error);if(opts.continuous){const id=dbOpts.name+":"+uuid();idbChanges2.addListener(dbOpts.name,id,api,opts);idbChanges2.notify(dbOpts.name);return{cancel:function(){idbChanges2.removeListener(dbOpts.name,id)}}}let limit="limit"in opts?opts.limit:-1;0===limit&&(limit=1);const store=txn.txn.objectStore(DOC_STORE2).index("seq"),filter4=filterChange(opts);let received=0,lastSeq=opts.since||0;const results=[],processing=[];let req;req=opts.descending?store.openCursor(null,"prev"):store.openCursor(IDBKeyRange.lowerBound(opts.since,!0));txn.txn.oncomplete=function onTxnComplete(){Promise.all(processing).then(function(){opts.complete(null,{results,last_seq:lastSeq})})};req.onsuccess=function onReqSuccess(e3){if(!e3.target.result)return;const cursor=e3.target.result,doc=cursor.value;doc.data=doc.revs[doc.rev].data;doc.data._id=doc.id;doc.data._rev=doc.rev;doc.deleted&&(doc.data._deleted=!0);if(opts.doc_ids&&-1===opts.doc_ids.indexOf(doc.id))return cursor.continue();const change=opts.processChange(doc.data,doc,opts);change.seq=doc.seq;lastSeq=doc.seq;const filtered=filter4(change);if("object"==typeof filtered)return opts.complete(filtered);if(filtered){received++;opts.return_docs&&results.push(change);if(opts.include_docs&&opts.attachments&&doc.data._attachments){const promises=[];for(const name in doc.data._attachments){const p2=processAttachment(name,doc,change.doc,opts.binary,api.blobSupport);promises.push(p2);processing.push(p2)}Promise.all(promises).then(function(){opts.onChange(change)})}else opts.onChange(change)}received!==limit&&cursor.continue()}}function getRevisionTree(txn,id,callback){if(txn.error)return callback(txn.error);const req=txn.txn.objectStore(DOC_STORE2).get(id);req.onsuccess=function(e3){e3.target.result?callback(null,e3.target.result.rev_tree):callback(createError(MISSING_DOC))}}function doCompaction(txn,id,revs,callback){if(txn.error)return callback(txn.error);const docStore=txn.txn.objectStore(DOC_STORE2);docStore.get(id).onsuccess=function(e3){const doc=e3.target.result;traverseRevTree(doc.rev_tree,function(isLeaf,pos,revHash,ctx,opts){const rev3=pos+"-"+revHash;-1!==revs.indexOf(rev3)&&(opts.status="missing")});const attachments=[];revs.forEach(function(rev3){if(rev3 in doc.revs){if(doc.revs[rev3].data._attachments)for(const k2 in doc.revs[rev3].data._attachments)attachments.push(doc.revs[rev3].data._attachments[k2].digest);delete doc.revs[rev3]}});attachments.forEach(function(digest){revs.forEach(function(rev3){delete doc.attachments[digest].revs[rev3]});Object.keys(doc.attachments[digest].revs).length||delete doc.attachments[digest]});docStore.put(doc)};txn.txn.oncomplete=function(){callback()}}function destroy(dbOpts,openDatabases2,idbChanges2,callback){function doDestroy(){const req=indexedDB.deleteDatabase(dbOpts.name);req.onsuccess=function(){delete openDatabases2[dbOpts.name];callback(null,{ok:!0})}}idbChanges2.removeAllListeners(dbOpts.name);dbOpts.name in openDatabases2?openDatabases2[dbOpts.name].then(function(res2){res2.idb.close();doDestroy()}):doDestroy()}function externaliseRecord(idbDoc){const doc=idbDoc.revs[idbDoc.rev].data;doc._id=idbDoc.id;doc._rev=idbDoc.rev;idbDoc.deleted&&(doc._deleted=!0);return doc}function generateKeyRange(opts){function defined(obj,k2){return void 0!==obj[k2]}function convert(key3,exact){const filterDeleted=[0].concat(key3);return filterDeleted.map(function(k2){if(null===k2&&exact)return IDB_NULL;if(!0===k2)return IDB_TRUE;if(!1===k2)return IDB_FALSE;if(!exact){if(k2===COUCH_COLLATE_LO)return IDB_COLLATE_LO;if(Object.prototype.hasOwnProperty.call(k2,COUCH_COLLATE_HI))return IDB_COLLATE_HI}return k2})}defined(opts,"inclusive_end")||(opts.inclusive_end=!0);defined(opts,"inclusive_start")||(opts.inclusive_start=!0);if(opts.descending){const realEndkey=opts.startkey,realInclusiveEnd=opts.inclusive_start;opts.startkey=opts.endkey;opts.endkey=realEndkey;opts.inclusive_start=opts.inclusive_end;opts.inclusive_end=realInclusiveEnd}try{return defined(opts,"key")?IDBKeyRange.only(convert(opts.key,!0)):defined(opts,"startkey")&&!defined(opts,"endkey")?IDBKeyRange.bound(convert(opts.startkey),[1],!opts.inclusive_start,!0):!defined(opts,"startkey")&&defined(opts,"endkey")?IDBKeyRange.upperBound(convert(opts.endkey),!opts.inclusive_end):defined(opts,"startkey")&&defined(opts,"endkey")?IDBKeyRange.bound(convert(opts.startkey),convert(opts.endkey),!opts.inclusive_start,!opts.inclusive_end):IDBKeyRange.only([0])}catch(err3){console.error("Could not generate keyRange",err3,opts);throw Error("Could not generate key range with "+JSON.stringify(opts))}}function getIndexHandle(pdb,fields,reject){const indexName=naturalIndexName(fields);return new Promise(function(resolve){pdb._openTransactionSafely([DOC_STORE2],"readonly",function(err3,txn){if(err3)return idbError2(reject)(err3);txn.onabort=idbError2(reject);txn.ontimeout=idbError2(reject);const existingIndexNames=Array.from(txn.objectStore(DOC_STORE2).indexNames);-1===existingIndexNames.indexOf(indexName)?pdb._freshen().then(function(){return getIndexHandle(pdb,fields,reject)}).then(resolve):resolve(txn.objectStore(DOC_STORE2).index(indexName))})})}function query(idb,signature,opts,fallback3){const pdb=this,parts=signature.split("/");return new Promise(function(resolve,reject){pdb.get("_design/"+parts[0]).then(function(ddoc){if(isPartialFilterView(ddoc,parts[1]))return fallback3(signature,opts).then(resolve,reject);const fields=rawIndexFields(ddoc,parts[1]);if(!fields)throw new Error("ddoc "+ddoc._id+" with view "+parts[1]+" does not have map.options.def.fields defined.");let skip=opts.skip,limit=Number.isInteger(opts.limit)&&opts.limit;return getIndexHandle(pdb,fields,reject).then(function(indexHandle){const keyRange=generateKeyRange(opts),req=indexHandle.openCursor(keyRange,opts.descending?"prev":"next"),rows=[];req.onerror=idbError2(reject);req.onsuccess=function(e3){const cursor=e3.target.result;if(!cursor||0===limit)return resolve({rows});if(skip){cursor.advance(skip);skip=!1}else{limit&&(limit-=1);rows.push({doc:externaliseRecord(cursor.value)});cursor.continue()}}})}).catch(reject)})}function viewCleanup(idb,fallback3){return fallback3()}function purgeAttachments(doc,revs){if(!doc.attachments)return{};for(let key3 in doc.attachments){const attachment=doc.attachments[key3];for(let rev3 of revs)attachment.revs[rev3]&&delete attachment.revs[rev3];0===Object.keys(attachment.revs).length&&delete doc.attachments[key3]}return doc.attachments}function purge(txn,docId,revs,callback){if(txn.error)return callback(txn.error);const docStore=txn.txn.objectStore(DOC_STORE2),deletedRevs=[];let documentWasRemovedCompletely=!1;docStore.get(docId).onsuccess=e3=>{const doc=e3.target.result;for(const rev3 of revs){doc.rev_tree=removeLeafFromRevTree(doc.rev_tree,rev3);delete doc.revs[rev3];deletedRevs.push(rev3)}if(0!==doc.rev_tree.length){doc.rev=winningRev(doc);doc.data=doc.revs[doc.rev].data;doc.attachments=purgeAttachments(doc,revs);docStore.put(doc)}else{docStore.delete(doc.id);documentWasRemovedCompletely=!0}};txn.txn.oncomplete=function(){callback(null,{ok:!0,deletedRevs,documentWasRemovedCompletely})}}function IndexeddbPouch(dbOpts,callback){dbOpts.view_adapter&&console.log("Please note that the indexeddb adapter manages _find indexes itself, therefore it is not using your specified view_adapter");const api=this;let metadata={};const $=function(fun){return function(){const args=Array.prototype.slice.call(arguments);setup(openDatabases,api,dbOpts).then(function(res2){metadata=res2.metadata;args.unshift(res2.idb);fun.apply(api,args)}).catch(function(err3){const last=args.pop();"function"==typeof last?last(err3):console.error(err3)})}},$p=function(fun){return function(){const args=Array.prototype.slice.call(arguments);return setup(openDatabases,api,dbOpts).then(function(res2){metadata=res2.metadata;args.unshift(res2.idb);return fun.apply(api,args)})}},$t2=function(fun,stores,mode){mode=mode||"readonly";return function(){const args=Array.prototype.slice.call(arguments),txn={};setup(openDatabases,api,dbOpts).then(function(res2){metadata=res2.metadata;txn.txn=res2.idb.transaction(stores,mode)}).catch(function(err3){console.error("Failed to establish transaction safely");console.error(err3);txn.error=err3}).then(function(){args.unshift(txn);fun.apply(api,args)})}};api._openTransactionSafely=function(stores,mode,callback2){$t2(function(txn,callback3){callback3(txn.error,txn.txn)},stores,mode)(callback2)};api._remote=!1;api.type=function(){return ADAPTER_NAME};api._id=$(function(_,cb2){cb2(null,metadata.db_uuid)});api._info=$(function(_,cb2){return info2(metadata,cb2)});api._get=$t2(get4,[DOC_STORE2]);api._getLocal=$t2(function(txn,id,callback2){return getLocal(txn,id,api,callback2)},[META_LOCAL_STORE]);api._bulkDocs=$(function(_,req,opts,callback2){bulkDocs(api,req,opts,metadata,dbOpts,idbChanges,callback2)});api._allDocs=$t2(function(txn,opts,cb2){allDocs(txn,metadata,opts,cb2)},[DOC_STORE2]);api._getAttachment=getAttachment;api._changes=$t2(function(txn,opts){changes2(txn,idbChanges,api,dbOpts,opts)},[DOC_STORE2]);api._getRevisionTree=$t2(getRevisionTree,[DOC_STORE2]);api._doCompaction=$t2(doCompaction,[DOC_STORE2],"readwrite");api._customFindAbstractMapper={query:$p(query),viewCleanup:$p(viewCleanup)};api._destroy=function(opts,callback2){return destroy(dbOpts,openDatabases,idbChanges,callback2)};api._close=$(function(db,cb2){delete openDatabases[dbOpts.name];db.close();cb2()});api._freshen=function(){return new Promise(function(resolve){api._close(function(){$(resolve)()})})};api._purge=$t2(purge,[DOC_STORE2],"readwrite");setTimeout(function(){callback(null,api)})}function pool(promiseFactories,limit){return new Promise(function(resolve,reject){function runNext(){running2++;promiseFactories[current++]().then(onSuccess,onError)}function doNext(){++done===len?err3?reject(err3):resolve():runNextBatch()}function onSuccess(){running2--;doNext()}function onError(thisErr){running2--;err3=err3||thisErr;doNext()}function runNextBatch(){for(;running2<limit&&current<len;)runNext()}var err3,running2=0,current=0,done=0,len=promiseFactories.length;runNextBatch()})}function readAttachmentsAsBlobOrBuffer(row){const doc=row.doc||row.ok,atts=doc&&doc._attachments;atts&&Object.keys(atts).forEach(function(filename){const att=atts[filename];att.data=b64ToBluffer(att.data,att.content_type)})}function encodeDocId(id){return/^_design/.test(id)?"_design/"+encodeURIComponent(id.slice(8)):id.startsWith("_local/")?"_local/"+encodeURIComponent(id.slice(7)):encodeURIComponent(id)}function preprocessAttachments2(doc){return doc._attachments&&Object.keys(doc._attachments)?Promise.all(Object.keys(doc._attachments).map(function(key3){const attachment=doc._attachments[key3];if(attachment.data&&"string"!=typeof attachment.data)return new Promise(function(resolve){blobToBase64(attachment.data,resolve)}).then(function(b64){attachment.data=b64})})):Promise.resolve()}function hasUrlPrefix(opts){if(!opts.prefix)return!1;const protocol=parseUri(opts.prefix).protocol;return"http"===protocol||"https"===protocol}function getHost(name,opts){if(hasUrlPrefix(opts)){const dbName=opts.name.substr(opts.prefix.length),prefix=opts.prefix.replace(/\/?$/,"/");name=prefix+encodeURIComponent(dbName)}const uri=parseUri(name);(uri.user||uri.password)&&(uri.auth={username:uri.user,password:uri.password});const parts=uri.path.replace(/(^\/|\/$)/g,"").split("/");uri.db=parts.pop();-1===uri.db.indexOf("%")&&(uri.db=encodeURIComponent(uri.db));uri.path=parts.join("/");return uri}function genDBUrl(opts,path2){return genUrl(opts,opts.db+"/"+path2)}function genUrl(opts,path2){const pathDel=opts.path?"/":"";return opts.protocol+"://"+opts.host+(opts.port?":"+opts.port:"")+"/"+opts.path+pathDel+path2}function paramsToStr(params){const paramKeys=Object.keys(params);return 0===paramKeys.length?"":"?"+paramKeys.map(key3=>key3+"="+encodeURIComponent(params[key3])).join("&")}function shouldCacheBust(opts){const ua="undefined"!=typeof navigator&&navigator.userAgent?navigator.userAgent.toLowerCase():"",isIE=-1!==ua.indexOf("msie"),isTrident=-1!==ua.indexOf("trident"),isEdge=-1!==ua.indexOf("edge"),isGET=!("method"in opts)||"GET"===opts.method;return(isIE||isTrident||isEdge)&&isGET}function HttpPouch(opts,callback){function adapterFun$$1(name,fun){return adapterFun(name,function(...args){setup2().then(function(){return fun.apply(this,args)}).catch(function(e3){const callback2=args.pop();callback2(e3)})}).bind(api)}async function fetchJSON(url,options){const result={};options=options||{};options.headers=options.headers||new h2;options.headers.get("Content-Type")||options.headers.set("Content-Type","application/json");options.headers.get("Accept")||options.headers.set("Accept","application/json");const response=await ourFetch(url,options);result.ok=response.ok;result.status=response.status;const json=await response.json();result.data=json;if(!result.ok){result.data.status=result.status;const err3=generateErrorFromResponse(result.data);throw err3}Array.isArray(result.data)&&(result.data=result.data.map(function(v2){return v2.error||v2.missing?generateErrorFromResponse(v2):v2}));return result}async function setup2(){if(opts.skip_setup)return Promise.resolve();if(setupPromise)return setupPromise;setupPromise=fetchJSON(dbUrl).catch(function(err3){if(err3&&err3.status&&404===err3.status){explainError(404,"PouchDB is just detecting if the remote exists.");return fetchJSON(dbUrl,{method:"PUT"})}return Promise.reject(err3)}).catch(function(err3){return!(!err3||!err3.status||412!==err3.status)||Promise.reject(err3)});setupPromise.catch(function(){setupPromise=null});return setupPromise}function encodeAttachmentId(attachmentId){return attachmentId.split("/").map(encodeURIComponent).join("/")}const api=this,host=getHost(opts.name,opts),dbUrl=genDBUrl(host,"");opts=clone2(opts);const ourFetch=async function(url,options){options=options||{};options.headers=options.headers||new h2;options.credentials="include";if(opts.auth||host.auth){const nAuth=opts.auth||host.auth,str=nAuth.username+":"+nAuth.password,token=thisBtoa(unescape(encodeURIComponent(str)));options.headers.set("Authorization","Basic "+token)}const headers=opts.headers||{};Object.keys(headers).forEach(function(key3){options.headers.append(key3,headers[key3])});shouldCacheBust(options)&&(url+=(-1===url.indexOf("?")?"?":"&")+"_nonce="+Date.now());const fetchFun=opts.fetch||f3;return await fetchFun(url,options)};let setupPromise;nextTick(function(){callback(null,api)});api._remote=!0;api.type=function(){return"http"};api.id=adapterFun$$1("id",async function(callback2){let result;try{const response=await ourFetch(genUrl(host,""));result=await response.json()}catch(err3){result={}}const uuid2=result&&result.uuid?result.uuid+host.db:genDBUrl(host,"");callback2(null,uuid2)});api.compact=adapterFun$$1("compact",async function(opts2,callback2){if("function"==typeof opts2){callback2=opts2;opts2={}}opts2=clone2(opts2);await fetchJSON(genDBUrl(host,"_compact"),{method:"POST"});(function ping(){api.info(function(err3,res2){res2&&!res2.compact_running?callback2(null,{ok:!0}):setTimeout(ping,opts2.interval||200)})})()});api.bulkGet=adapterFun("bulkGet",function(opts2,callback2){async function doBulkGet(cb2){const params={};opts2.revs&&(params.revs=!0);opts2.attachments&&(params.attachments=!0);opts2.latest&&(params.latest=!0);try{const result=await fetchJSON(genDBUrl(host,"_bulk_get"+paramsToStr(params)),{method:"POST",body:JSON.stringify({docs:opts2.docs})});opts2.attachments&&opts2.binary&&result.data.results.forEach(function(res2){res2.docs.forEach(readAttachmentsAsBlobOrBuffer)});cb2(null,result.data)}catch(error){cb2(error)}}function doBulkGetShim(){function onResult(batchNum){return function(err3,res2){results[batchNum]=res2.results;++numDone===numBatches&&callback2(null,{results:results.flat()})}}const batchSize=MAX_SIMULTANEOUS_REVS,numBatches=Math.ceil(opts2.docs.length/batchSize);let numDone=0;const results=new Array(numBatches);for(let i3=0;i3<numBatches;i3++){const subOpts=pick(opts2,["revs","attachments","binary","latest"]);subOpts.docs=opts2.docs.slice(i3*batchSize,Math.min(opts2.docs.length,(i3+1)*batchSize));bulkGet(self3,subOpts,onResult(i3))}}const self3=this,dbUrl2=genUrl(host,""),supportsBulkGet=supportsBulkGetMap[dbUrl2];"boolean"!=typeof supportsBulkGet?doBulkGet(function(err3,res2){if(err3){supportsBulkGetMap[dbUrl2]=!1;explainError(err3.status,"PouchDB is just detecting if the remote supports the _bulk_get API.");doBulkGetShim()}else{supportsBulkGetMap[dbUrl2]=!0;callback2(null,res2)}}):supportsBulkGet?doBulkGet(callback2):doBulkGetShim()});api._info=async function(callback2){try{await setup2();const response=await ourFetch(genDBUrl(host,"")),info3=await response.json();info3.host=genDBUrl(host,"");callback2(null,info3)}catch(err3){callback2(err3)}};api.fetch=async function(path2,options){await setup2();const url="/"===path2.substring(0,1)?genUrl(host,path2.substring(1)):genDBUrl(host,path2);return ourFetch(url,options)};api.get=adapterFun$$1("get",async function(id,opts2,callback2){function fetchAttachments(doc){async function fetchData(filename){const att=atts[filename],path2=encodeDocId(doc._id)+"/"+encodeAttachmentId(filename)+"?rev="+doc._rev,response=await ourFetch(genDBUrl(host,path2));let blob,data;blob="buffer"in response?await response.buffer():await response.blob();if(opts2.binary){const typeFieldDescriptor=Object.getOwnPropertyDescriptor(blob.__proto__,"type");typeFieldDescriptor&&!typeFieldDescriptor.set||(blob.type=att.content_type);data=blob}else data=await new Promise(function(resolve){blobToBase64(blob,resolve)});delete att.stub;delete att.length;att.data=data}const atts=doc._attachments,filenames=atts&&Object.keys(atts);if(!atts||!filenames.length)return;const promiseFactories=filenames.map(function(filename){return function(){return fetchData(filename)}});return pool(promiseFactories,5)}if("function"==typeof opts2){callback2=opts2;opts2={}}opts2=clone2(opts2);const params={};opts2.revs&&(params.revs=!0);opts2.revs_info&&(params.revs_info=!0);opts2.latest&&(params.latest=!0);if(opts2.open_revs){"all"!==opts2.open_revs&&(opts2.open_revs=JSON.stringify(opts2.open_revs));params.open_revs=opts2.open_revs}opts2.rev&&(params.rev=opts2.rev);opts2.conflicts&&(params.conflicts=opts2.conflicts);opts2.update_seq&&(params.update_seq=opts2.update_seq);id=encodeDocId(id);const url=genDBUrl(host,id+paramsToStr(params));try{const res2=await fetchJSON(url);opts2.attachments&&await function fetchAllAttachments(docOrDocs){return Array.isArray(docOrDocs)?Promise.all(docOrDocs.map(function(doc){if(doc.ok)return fetchAttachments(doc.ok)})):fetchAttachments(docOrDocs)}(res2.data);callback2(null,res2.data)}catch(error){error.docId=id;callback2(error)}});api.remove=adapterFun$$1("remove",async function(docOrId,optsOrRev,opts2,cb2){let doc;if("string"==typeof optsOrRev){doc={_id:docOrId,_rev:optsOrRev};if("function"==typeof opts2){cb2=opts2;opts2={}}}else{doc=docOrId;if("function"==typeof optsOrRev){cb2=optsOrRev;opts2={}}else{cb2=opts2;opts2=optsOrRev}}const rev3=doc._rev||opts2.rev,url=genDBUrl(host,encodeDocId(doc._id))+"?rev="+rev3;try{const result=await fetchJSON(url,{method:"DELETE"});cb2(null,result.data)}catch(error){cb2(error)}});api.getAttachment=adapterFun$$1("getAttachment",async function(docId,attachmentId,opts2,callback2){if("function"==typeof opts2){callback2=opts2;opts2={}}const params=opts2.rev?"?rev="+opts2.rev:"",url=genDBUrl(host,encodeDocId(docId))+"/"+encodeAttachmentId(attachmentId)+params;let contentType;try{const response=await ourFetch(url,{method:"GET"});if(!response.ok)throw response;contentType=response.headers.get("content-type");let blob;blob="undefined"==typeof process||process.browser||"function"!=typeof response.buffer?await response.blob():await response.buffer();if("undefined"!=typeof process&&!process.browser){const typeFieldDescriptor=Object.getOwnPropertyDescriptor(blob.__proto__,"type");typeFieldDescriptor&&!typeFieldDescriptor.set||(blob.type=contentType)}callback2(null,blob)}catch(err3){callback2(err3)}});api.removeAttachment=adapterFun$$1("removeAttachment",async function(docId,attachmentId,rev3,callback2){const url=genDBUrl(host,encodeDocId(docId)+"/"+encodeAttachmentId(attachmentId))+"?rev="+rev3;try{const result=await fetchJSON(url,{method:"DELETE"});callback2(null,result.data)}catch(error){callback2(error)}});api.putAttachment=adapterFun$$1("putAttachment",async function(docId,attachmentId,rev3,blob,type,callback2){if("function"==typeof type){callback2=type;type=blob;blob=rev3;rev3=null}const id=encodeDocId(docId)+"/"+encodeAttachmentId(attachmentId);let url=genDBUrl(host,id);rev3&&(url+="?rev="+rev3);if("string"==typeof blob){let binary;try{binary=thisAtob(blob)}catch(err3){return callback2(createError(BAD_ARG,"Attachment is not a valid base64 string"))}blob=binary?binStringToBluffer(binary,type):""}try{const result=await fetchJSON(url,{headers:new h2({"Content-Type":type}),method:"PUT",body:blob});callback2(null,result.data)}catch(error){callback2(error)}});api._bulkDocs=async function(req,opts2,callback2){req.new_edits=opts2.new_edits;try{await setup2();await Promise.all(req.docs.map(preprocessAttachments2));const result=await fetchJSON(genDBUrl(host,"_bulk_docs"),{method:"POST",body:JSON.stringify(req)});callback2(null,result.data)}catch(error){callback2(error)}};api._put=async function(doc,opts2,callback2){try{await setup2();await preprocessAttachments2(doc);const result=await fetchJSON(genDBUrl(host,encodeDocId(doc._id)),{method:"PUT",body:JSON.stringify(doc)});callback2(null,result.data)}catch(error){error.docId=doc&&doc._id;callback2(error)}};api.allDocs=adapterFun$$1("allDocs",async function(opts2,callback2){if("function"==typeof opts2){callback2=opts2;opts2={}}opts2=clone2(opts2);const params={};let body,method="GET";opts2.conflicts&&(params.conflicts=!0);opts2.update_seq&&(params.update_seq=!0);opts2.descending&&(params.descending=!0);opts2.include_docs&&(params.include_docs=!0);opts2.attachments&&(params.attachments=!0);opts2.key&&(params.key=JSON.stringify(opts2.key));opts2.start_key&&(opts2.startkey=opts2.start_key);opts2.startkey&&(params.startkey=JSON.stringify(opts2.startkey));opts2.end_key&&(opts2.endkey=opts2.end_key);opts2.endkey&&(params.endkey=JSON.stringify(opts2.endkey));void 0!==opts2.inclusive_end&&(params.inclusive_end=!!opts2.inclusive_end);void 0!==opts2.limit&&(params.limit=opts2.limit);void 0!==opts2.skip&&(params.skip=opts2.skip);const paramStr=paramsToStr(params);if(void 0!==opts2.keys){method="POST";body={keys:opts2.keys}}try{const result=await fetchJSON(genDBUrl(host,"_all_docs"+paramStr),{method,body:JSON.stringify(body)});opts2.include_docs&&opts2.attachments&&opts2.binary&&result.data.rows.forEach(readAttachmentsAsBlobOrBuffer);callback2(null,result.data)}catch(error){callback2(error)}});api._changes=function(opts2){const batchSize="batch_size"in opts2?opts2.batch_size:CHANGES_BATCH_SIZE;opts2=clone2(opts2);opts2.continuous&&!("heartbeat"in opts2)&&(opts2.heartbeat=DEFAULT_HEARTBEAT);let requestTimeout3="timeout"in opts2?opts2.timeout:3e4;"timeout"in opts2&&opts2.timeout&&requestTimeout3-opts2.timeout<CHANGES_TIMEOUT_BUFFER&&(requestTimeout3=opts2.timeout+CHANGES_TIMEOUT_BUFFER);"heartbeat"in opts2&&opts2.heartbeat&&requestTimeout3-opts2.heartbeat<CHANGES_TIMEOUT_BUFFER&&(requestTimeout3=opts2.heartbeat+CHANGES_TIMEOUT_BUFFER);const params={};"timeout"in opts2&&opts2.timeout&&(params.timeout=opts2.timeout);const limit=void 0!==opts2.limit&&opts2.limit;let leftToFetch=limit;opts2.style&&(params.style=opts2.style);(opts2.include_docs||opts2.filter&&"function"==typeof opts2.filter)&&(params.include_docs=!0);opts2.attachments&&(params.attachments=!0);opts2.continuous&&(params.feed="longpoll");opts2.seq_interval&&(params.seq_interval=opts2.seq_interval);opts2.conflicts&&(params.conflicts=!0);opts2.descending&&(params.descending=!0);opts2.update_seq&&(params.update_seq=!0);"heartbeat"in opts2&&opts2.heartbeat&&(params.heartbeat=opts2.heartbeat);opts2.filter&&"string"==typeof opts2.filter&&(params.filter=opts2.filter);if(opts2.view&&"string"==typeof opts2.view){params.filter="_view";params.view=opts2.view}if(opts2.query_params&&"object"==typeof opts2.query_params)for(const param_name in opts2.query_params)Object.prototype.hasOwnProperty.call(opts2.query_params,param_name)&&(params[param_name]=opts2.query_params[param_name]);let body,method="GET";if(opts2.doc_ids){params.filter="_doc_ids";method="POST";body={doc_ids:opts2.doc_ids}}else if(opts2.selector){params.filter="_selector";method="POST";body={selector:opts2.selector}}const controller=new AbortController;let lastFetchedSeq;const fetchData=async function(since,callback2){if(opts2.aborted)return;params.since=since;"object"==typeof params.since&&(params.since=JSON.stringify(params.since));opts2.descending?limit&&(params.limit=leftToFetch):params.limit=!limit||leftToFetch>batchSize?batchSize:leftToFetch;const url=genDBUrl(host,"_changes"+paramsToStr(params)),fetchOpts={signal:controller.signal,method,body:JSON.stringify(body)};lastFetchedSeq=since;if(!opts2.aborted)try{await setup2();const result=await fetchJSON(url,fetchOpts);callback2(null,result.data)}catch(error){callback2(error)}},results={results:[]},fetched=function(err3,res2){if(opts2.aborted)return;let raw_results_length=0;if(res2&&res2.results){raw_results_length=res2.results.length;results.last_seq=res2.last_seq;let pending3=null,lastSeq=null;"number"==typeof res2.pending&&(pending3=res2.pending);"string"!=typeof results.last_seq&&"number"!=typeof results.last_seq||(lastSeq=results.last_seq);const req={};req.query=opts2.query_params;res2.results=res2.results.filter(function(c3){leftToFetch--;const ret=filterChange(opts2)(c3);if(ret){opts2.include_docs&&opts2.attachments&&opts2.binary&&readAttachmentsAsBlobOrBuffer(c3);opts2.return_docs&&results.results.push(c3);opts2.onChange(c3,pending3,lastSeq)}return ret})}else if(err3){opts2.aborted=!0;opts2.complete(err3);return}res2&&res2.last_seq&&(lastFetchedSeq=res2.last_seq);const finished=limit&&leftToFetch<=0||res2&&raw_results_length<batchSize||opts2.descending;(!opts2.continuous||limit&&leftToFetch<=0)&&finished?opts2.complete(null,results):nextTick(function(){fetchData(lastFetchedSeq,fetched)})};fetchData(opts2.since||0,fetched);return{cancel:function(){opts2.aborted=!0;controller.abort()}}};api.revsDiff=adapterFun$$1("revsDiff",async function(req,opts2,callback2){if("function"==typeof opts2){callback2=opts2;opts2={}}try{const result=await fetchJSON(genDBUrl(host,"_revs_diff"),{method:"POST",body:JSON.stringify(req)});callback2(null,result.data)}catch(error){callback2(error)}});api._close=function(callback2){callback2()};api._destroy=async function(options,callback2){try{const json=await fetchJSON(genDBUrl(host,""),{method:"DELETE"});callback2(null,json)}catch(error){404===error.status?callback2(null,{ok:!0}):callback2(error)}}}function promisedCallback(promise,callback){callback&&promise.then(function(res2){nextTick(function(){callback(null,res2)})},function(reason){nextTick(function(){callback(reason)})});return promise}function callbackify(fun){return function(...args){var cb2=args.pop(),promise=fun.apply(this,args);"function"==typeof cb2&&promisedCallback(promise,cb2);return promise}}function fin(promise,finalPromiseFactory){return promise.then(function(res2){return finalPromiseFactory().then(function(){return res2})},function(reason){return finalPromiseFactory().then(function(){throw reason})})}function sequentialize(queue2,promiseFactory){return function(){var args=arguments,that=this;return queue2.add(function(){return promiseFactory.apply(that,args)})}}function uniq(arr){var theSet=new Set(arr),result=new Array(theSet.size),index6=-1;theSet.forEach(function(value){result[++index6]=value});return result}function mapToKeysArray(map4){var result=new Array(map4.size),index6=-1;map4.forEach(function(value,key3){result[++index6]=key3});return result}function stringify2(input){if(!input)return"undefined";switch(typeof input){case"function":return input.toString();case"string":return input.toString();default:return JSON.stringify(input)}}function createViewSignature(mapFun,reduceFun){return stringify2(mapFun)+stringify2(reduceFun)+"undefined"}async function createView(sourceDB,viewName,mapFun,reduceFun,temporary,localDocName2){const viewSignature=createViewSignature(mapFun,reduceFun);let cachedViews;if(!temporary){cachedViews=sourceDB._cachedViews=sourceDB._cachedViews||{};if(cachedViews[viewSignature])return cachedViews[viewSignature]}const promiseForView=sourceDB.info().then(async function(info3){const depDbName=info3.db_name+"-mrview-"+(temporary?"temp":stringMd5(viewSignature));await upsert(sourceDB,"_local/"+localDocName2,function diffFunction(doc){doc.views=doc.views||{};let fullViewName=viewName;-1===fullViewName.indexOf("/")&&(fullViewName=viewName+"/"+viewName);const depDbs=doc.views[fullViewName]=doc.views[fullViewName]||{};if(!depDbs[depDbName]){depDbs[depDbName]=!0;return doc}});const res2=await sourceDB.registerDependentDatabase(depDbName),db=res2.db;db.auto_compaction=!0;const view={name:depDbName,db,sourceDB,adapter:sourceDB.adapter,mapFun,reduceFun};let lastSeqDoc;try{lastSeqDoc=await view.db.get("_local/lastSeq")}catch(err3){if(404!==err3.status)throw err3}view.seq=lastSeqDoc?lastSeqDoc.seq:0;cachedViews&&view.db.once("destroyed",function(){delete cachedViews[viewSignature]});return view});cachedViews&&(cachedViews[viewSignature]=promiseForView);return promiseForView}function parseViewName(name){return-1===name.indexOf("/")?[name,name]:name.split("/")}function isGenOne(changes3){return 1===changes3.length&&/^1-/.test(changes3[0].rev)}function emitError(db,e3,data){try{db.emit("error",e3)}catch(err3){guardedConsole("error","The user's map/reduce function threw an uncaught error.\nYou can debug this error by doing:\nmyDatabase.on('error', function (err) { debugger; });\nPlease double-check your map/reduce function.");guardedConsole("error",e3,data)}}function createBuiltInError(name){var message="builtin "+name+" function requires map values to be numbers or number arrays";return new BuiltInError(message)}function sum(values2){var i3,len,num,j2,jLen,jNum,result=0;for(i3=0,len=values2.length;i3<len;i3++){num=values2[i3];if("number"!=typeof num){if(!Array.isArray(num))throw createBuiltInError("_sum");result="number"==typeof result?[result]:result;for(j2=0,jLen=num.length;j2<jLen;j2++){jNum=num[j2];if("number"!=typeof jNum)throw createBuiltInError("_sum");void 0===result[j2]?result.push(jNum):result[j2]+=jNum}}else"number"==typeof result?result+=num:result[0]+=num}return result}function evalFunctionWithEval(func,emit2){return scopeEval("return ("+func.replace(/;\s*$/,"")+");",{emit:emit2,sum,log,isArray,toJSON})}function getBuiltIn(reduceFunString){if(/^_sum/.test(reduceFunString))return builtInReduce__sum;if(/^_count/.test(reduceFunString))return builtInReduce__count;if(/^_stats/.test(reduceFunString))return builtInReduce__stats;if(/^_/.test(reduceFunString))throw new Error(reduceFunString+" is not a supported reduce function.")}function updateCheckpoint(db,id,checkpoint,session,returnValue){return db.get(id).catch(function(err3){if(404===err3.status){"http"!==db.adapter&&"https"!==db.adapter||explainError(404,"PouchDB is just checking if a remote checkpoint exists.");return{session_id:session,_id:id,history:[],replicator:REPLICATOR,version:CHECKPOINT_VERSION}}throw err3}).then(function(doc){if(!returnValue.cancelled&&doc.last_seq!==checkpoint){doc.history=(doc.history||[]).filter(function(item){return item.session_id!==session});doc.history.unshift({last_seq:checkpoint,session_id:session});doc.history=doc.history.slice(0,CHECKPOINT_HISTORY_SIZE);doc.version=CHECKPOINT_VERSION;doc.replicator=REPLICATOR;doc.session_id=session;doc.last_seq=checkpoint;return db.put(doc).catch(function(err3){if(409===err3.status)return updateCheckpoint(db,id,checkpoint,session,returnValue);throw err3})}})}function compareReplicationLogs(srcDoc,tgtDoc){return srcDoc.session_id===tgtDoc.session_id?{last_seq:srcDoc.last_seq,history:srcDoc.history}:compareReplicationHistory(srcDoc.history,tgtDoc.history)}function compareReplicationHistory(sourceHistory,targetHistory){var sourceId,targetId,S2=sourceHistory[0],sourceRest=sourceHistory.slice(1),T2=targetHistory[0],targetRest=targetHistory.slice(1);if(!S2||0===targetHistory.length)return{last_seq:LOWEST_SEQ,history:[]};sourceId=S2.session_id;if(hasSessionId(sourceId,targetHistory))return{last_seq:S2.last_seq,history:sourceHistory};targetId=T2.session_id;return hasSessionId(targetId,sourceRest)?{last_seq:T2.last_seq,history:targetRest}:compareReplicationHistory(sourceRest,targetRest)}function hasSessionId(sessionId,history){var props=history[0],rest=history.slice(1);return!(!sessionId||0===history.length)&&(sessionId===props.session_id||hasSessionId(sessionId,rest))}function isForbiddenError(err3){return"number"==typeof err3.status&&4===Math.floor(err3.status/100)}function sortObjectPropertiesByKey(queryParams){return Object.keys(queryParams).sort(collate).reduce(function(result,key3){result[key3]=queryParams[key3];return result},{})}function fileHasChanged(localDoc,remoteDoc,filename){return!localDoc._attachments||!localDoc._attachments[filename]||localDoc._attachments[filename].digest!==remoteDoc._attachments[filename].digest}function getDocAttachments(db,doc){var filenames=Object.keys(doc._attachments);return Promise.all(filenames.map(function(filename){return db.getAttachment(doc._id,filename,{rev:doc._rev})}))}function getDocAttachmentsFromTargetOrSource(target,src,doc){var doCheckForLocalAttachments=isRemote(src)&&!isRemote(target),filenames=Object.keys(doc._attachments);return doCheckForLocalAttachments?target.get(doc._id).then(function(localDoc){return Promise.all(filenames.map(function(filename){return fileHasChanged(localDoc,doc,filename)?src.getAttachment(doc._id,filename):target.getAttachment(localDoc._id,filename)}))}).catch(function(error){if(404!==error.status)throw error;return getDocAttachments(src,doc)}):getDocAttachments(src,doc)}function createBulkGetOpts(diffs){var requests=[];Object.keys(diffs).forEach(function(id){var missingRevs=diffs[id].missing;missingRevs.forEach(function(missingRev){requests.push({id,rev:missingRev})})});return{docs:requests,revs:!0,latest:!0}}function getDocs(src,target,diffs,state2){diffs=clone2(diffs);var resultDocs=[],ok=!0;return Promise.resolve().then(function getAllDocs(){var bulkGetOpts=createBulkGetOpts(diffs);if(bulkGetOpts.docs.length)return src.bulkGet(bulkGetOpts).then(function(bulkGetResponse){if(state2.cancelled)throw new Error("cancelled");return Promise.all(bulkGetResponse.results.map(function(bulkGetInfo){return Promise.all(bulkGetInfo.docs.map(function(doc){var remoteDoc=doc.ok;doc.error&&(ok=!1);return remoteDoc&&remoteDoc._attachments?getDocAttachmentsFromTargetOrSource(target,src,remoteDoc).then(attachments=>{var filenames=Object.keys(remoteDoc._attachments);attachments.forEach(function(attachment,i3){var att=remoteDoc._attachments[filenames[i3]];delete att.stub;delete att.length;att.data=attachment});return remoteDoc}):remoteDoc}))})).then(function(results){resultDocs=resultDocs.concat(results.flat().filter(Boolean))})})}).then(function returnResult(){return{ok,docs:resultDocs}})}function backOff(opts,returnValue,error,callback){var backOffSet,removeBackOffSetter;if(!1!==opts.retry){"function"!=typeof opts.back_off_function&&(opts.back_off_function=defaultBackOff);returnValue.emit("requestError",error);if("active"===returnValue.state||"pending"===returnValue.state){returnValue.emit("paused",error);returnValue.state="stopped";backOffSet=function backoffTimeSet(){opts.current_back_off=STARTING_BACK_OFF};removeBackOffSetter=function removeBackOffTimeSet(){returnValue.removeListener("active",backOffSet)};returnValue.once("paused",removeBackOffSetter);returnValue.once("active",backOffSet)}opts.current_back_off=opts.current_back_off||STARTING_BACK_OFF;opts.current_back_off=opts.back_off_function(opts.current_back_off);setTimeout(callback,opts.current_back_off)}else{returnValue.emit("error",error);returnValue.removeAllListeners()}}function replicate(src,target,opts,returnValue,result){function initCheckpointer(){return checkpointer?Promise.resolve():index_es_default7(src,target,opts).then(function(res2){repId=res2;var checkpointOpts={};checkpointOpts=!1===opts.checkpoint?{writeSourceCheckpoint:!1,writeTargetCheckpoint:!1}:"source"===opts.checkpoint?{writeSourceCheckpoint:!0,writeTargetCheckpoint:!1}:"target"===opts.checkpoint?{writeSourceCheckpoint:!1,writeTargetCheckpoint:!0}:{writeSourceCheckpoint:!0,writeTargetCheckpoint:!0};checkpointer=new index_es_default6(src,target,repId,returnValue,checkpointOpts)})}function writeDocs(){var docs,bulkOpts;changedDocs=[];if(0!==currentBatch.docs.length){docs=currentBatch.docs;bulkOpts={timeout:opts.timeout};return target.bulkDocs({docs,new_edits:!1},bulkOpts).then(function(res2){var errorsById,errorsNo;if(returnValue.cancelled){completeReplication();throw new Error("cancelled")}errorsById=Object.create(null);res2.forEach(function(res3){res3.error&&(errorsById[res3.id]=res3)});errorsNo=Object.keys(errorsById).length;result.doc_write_failures+=errorsNo;result.docs_written+=docs.length-errorsNo;docs.forEach(function(doc){var errorName,error=errorsById[doc._id];if(error){result.errors.push(error);errorName=(error.name||"").toLowerCase();if("unauthorized"!==errorName&&"forbidden"!==errorName)throw error;returnValue.emit("denied",clone2(error))}else changedDocs.push(doc)})},function(err3){result.doc_write_failures+=docs.length;throw err3})}}function finishBatch(){if(currentBatch.error)throw new Error("There was a problem getting docs.");result.last_seq=last_seq=currentBatch.seq;var outResult=clone2(result);if(changedDocs.length){outResult.docs=changedDocs;if("number"==typeof currentBatch.pending){outResult.pending=currentBatch.pending;delete currentBatch.pending}returnValue.emit("change",outResult)}writingCheckpoint=!0;src.info().then(function(info3){var completed,total_items,task=src.activeTasks.get(taskId);if(currentBatch&&task){completed=task.completed_items||0;total_items=parseInt(info3.update_seq,10)-parseInt(initial_last_seq,10);src.activeTasks.update(taskId,{completed_items:completed+currentBatch.changes.length,total_items})}});return checkpointer.writeCheckpoint(currentBatch.seq,session).then(function(){returnValue.emit("checkpoint",{checkpoint:currentBatch.seq});writingCheckpoint=!1;if(returnValue.cancelled){completeReplication();throw new Error("cancelled")}currentBatch=void 0;getChanges()}).catch(function(err3){onCheckpointError(err3);throw err3})}function getDiffs(){var diff={};currentBatch.changes.forEach(function(change){returnValue.emit("checkpoint",{revs_diff:change});"_user/"!==change.id&&(diff[change.id]=change.changes.map(function(x3){return x3.rev}))});return target.revsDiff(diff).then(function(diffs){if(returnValue.cancelled){completeReplication();throw new Error("cancelled")}currentBatch.diffs=diffs})}function getBatchDocs(){return getDocs(src,target,currentBatch.diffs,returnValue).then(function(got){currentBatch.error=!got.ok;got.docs.forEach(function(doc){delete currentBatch.diffs[doc._id];result.docs_read++;currentBatch.docs.push(doc)})})}function startNextBatch(){if(!returnValue.cancelled&&!currentBatch)if(0!==batches.length){currentBatch=batches.shift();returnValue.emit("checkpoint",{start_next_batch:currentBatch.seq});getDiffs().then(getBatchDocs).then(writeDocs).then(finishBatch).then(startNextBatch).catch(function(err3){abortReplication("batch processing terminated with error",err3)})}else processPendingBatch(!0)}function processPendingBatch(immediate){if(0!==pendingBatch.changes.length){if(immediate||changesCompleted||pendingBatch.changes.length>=batch_size){batches.push(pendingBatch);pendingBatch={seq:0,changes:[],docs:[]};if("pending"===returnValue.state||"stopped"===returnValue.state){returnValue.state="active";returnValue.emit("active")}startNextBatch()}}else if(0===batches.length&&!currentBatch){if(continuous&&changesOpts.live||changesCompleted){returnValue.state="pending";returnValue.emit("paused")}changesCompleted&&completeReplication()}}function abortReplication(reason,err3){if(!replicationCompleted){err3.message||(err3.message=reason);result.ok=!1;result.status="aborting";batches=[];pendingBatch={seq:0,changes:[],docs:[]};completeReplication(err3)}}function completeReplication(fatalError){if(!replicationCompleted){if(returnValue.cancelled){result.status="cancelled";if(writingCheckpoint)return}result.status=result.status||"complete";result.end_time=(new Date).toISOString();result.last_seq=last_seq;replicationCompleted=!0;src.activeTasks.remove(taskId,fatalError);if(fatalError){fatalError=createError(fatalError);fatalError.result=result;var errorName=(fatalError.name||"").toLowerCase();if("unauthorized"===errorName||"forbidden"===errorName){returnValue.emit("error",fatalError);returnValue.removeAllListeners()}else backOff(opts,returnValue,fatalError,function(){replicate(src,target,opts,returnValue)})}else{returnValue.emit("complete",result);returnValue.removeAllListeners()}}}function onChange(change,pending3,lastSeq){var filter4,task,completed;if(returnValue.cancelled)return completeReplication();"number"==typeof pending3&&(pendingBatch.pending=pending3);filter4=filterChange(opts)(change);if(filter4){pendingBatch.seq=change.seq||lastSeq;pendingBatch.changes.push(change);returnValue.emit("checkpoint",{pending_batch:pendingBatch.seq});nextTick(function(){processPendingBatch(0===batches.length&&changesOpts.live)})}else{task=src.activeTasks.get(taskId);if(task){completed=task.completed_items||0;src.activeTasks.update(taskId,{completed_items:++completed})}}}function onChangesComplete(changes3){changesPending=!1;if(returnValue.cancelled)return completeReplication();if(changes3.results.length>0){changesOpts.since=changes3.results[changes3.results.length-1].seq;getChanges();processPendingBatch(!0)}else{var complete=function(){if(continuous){changesOpts.live=!0;getChanges()}else changesCompleted=!0;processPendingBatch(!0)};if(currentBatch||0!==changes3.results.length)complete();else{writingCheckpoint=!0;checkpointer.writeCheckpoint(changes3.last_seq,session).then(function(){writingCheckpoint=!1;result.last_seq=last_seq=changes3.last_seq;if(returnValue.cancelled){completeReplication();throw new Error("cancelled")}complete()}).catch(onCheckpointError)}}}function onChangesError(err3){changesPending=!1;if(returnValue.cancelled)return completeReplication();abortReplication("changes rejected",err3)}function getChanges(){function abortChanges(){changes3.cancel()}function removeListener(){returnValue.removeListener("cancel",abortChanges)}if(!changesPending&&!changesCompleted&&batches.length<batches_limit){changesPending=!0;if(returnValue._changes){returnValue.removeListener("cancel",returnValue._abortChanges);returnValue._changes.cancel()}returnValue.once("cancel",abortChanges);var changes3=src.changes(changesOpts).on("change",onChange);changes3.then(removeListener,removeListener);changes3.then(onChangesComplete).catch(onChangesError);if(opts.retry){returnValue._changes=changes3;returnValue._abortChanges=abortChanges}}}function createTask(checkpoint){return src.info().then(function(info3){var total_items=void 0===opts.since?parseInt(info3.update_seq,10)-parseInt(checkpoint,10):parseInt(info3.update_seq,10);taskId=src.activeTasks.add({name:`${continuous?"continuous ":""}replication from ${info3.db_name}`,total_items});return checkpoint})}function startChanges(){initCheckpointer().then(function(){if(!returnValue.cancelled)return checkpointer.getCheckpoint().then(createTask).then(function(checkpoint){last_seq=checkpoint;initial_last_seq=checkpoint;changesOpts={since:last_seq,limit:batch_size,batch_size,style,doc_ids,selector,return_docs:!0};opts.filter&&("string"!=typeof opts.filter?changesOpts.include_docs=!0:changesOpts.filter=opts.filter);"heartbeat"in opts&&(changesOpts.heartbeat=opts.heartbeat);"timeout"in opts&&(changesOpts.timeout=opts.timeout);opts.query_params&&(changesOpts.query_params=opts.query_params);opts.view&&(changesOpts.view=opts.view);getChanges()});completeReplication()}).catch(function(err3){abortReplication("getCheckpoint rejected with ",err3)})}function onCheckpointError(err3){writingCheckpoint=!1;abortReplication("writeCheckpoint completed with error",err3)}var currentBatch,repId,checkpointer,taskId,changesOpts,batches=[],pendingBatch={seq:0,changes:[],docs:[]},writingCheckpoint=!1,changesCompleted=!1,replicationCompleted=!1,initial_last_seq=0,last_seq=0,continuous=opts.continuous||opts.live||!1,batch_size=opts.batch_size||100,batches_limit=opts.batches_limit||10,style=opts.style||"all_docs",changesPending=!1,doc_ids=opts.doc_ids,selector=opts.selector,changedDocs=[],session=uuid();result=result||{ok:!0,start_time:(new Date).toISOString(),docs_read:0,docs_written:0,doc_write_failures:0,errors:[]};changesOpts={};returnValue.ready(src,target);if(returnValue.cancelled)completeReplication();else{if(!returnValue._addedListeners){returnValue.once("cancel",completeReplication);if("function"==typeof opts.complete){returnValue.once("error",opts.complete);returnValue.once("complete",function(result2){opts.complete(null,result2)})}returnValue._addedListeners=!0}void 0===opts.since?startChanges():initCheckpointer().then(function(){writingCheckpoint=!0;return checkpointer.writeCheckpoint(opts.since,session)}).then(function(){writingCheckpoint=!1;if(returnValue.cancelled)completeReplication();else{last_seq=opts.since;startChanges()}}).catch(onCheckpointError)}}function toPouch(db,opts){var PouchConstructor=opts.PouchConstructor;return"string"==typeof db?new PouchConstructor(db,opts):db}function replicateWrapper(src,target,opts,callback){var replicateRet,srcPouch,targetPouch;if("function"==typeof opts){callback=opts;opts={}}void 0===opts&&(opts={});if(opts.doc_ids&&!Array.isArray(opts.doc_ids))throw createError(BAD_REQUEST,"`doc_ids` filter parameter is not a list.");opts.complete=callback;opts=clone2(opts);opts.continuous=opts.continuous||opts.live;opts.retry="retry"in opts&&opts.retry;opts.PouchConstructor=opts.PouchConstructor||this;replicateRet=new Replication(opts);srcPouch=toPouch(src,opts);targetPouch=toPouch(target,opts);replicate(srcPouch,targetPouch,opts,replicateRet);return replicateRet}function sync(src,target,opts,callback){if("function"==typeof opts){callback=opts;opts={}}void 0===opts&&(opts={});opts=clone2(opts);opts.PouchConstructor=opts.PouchConstructor||this;src=toPouch(src,opts);target=toPouch(target,opts);return new Sync(src,target,opts,callback)}function mergeObjects(arr){const res2={};for(const element2 of arr)Object.assign(res2,element2);return res2}function pick2(obj,arr){const res2={};for(const field of arr){const parsedField=parseField(field),value=getFieldFromDoc(obj,parsedField);void 0!==value&&setFieldInDoc(res2,parsedField,value)}return res2}function oneArrayIsSubArrayOfOther(left,right){for(let i3=0,len=Math.min(left.length,right.length);i3<len;i3++)if(left[i3]!==right[i3])return!1;return!0}function oneArrayIsStrictSubArrayOfOther(left,right){return!(left.length>right.length)&&oneArrayIsSubArrayOfOther(left,right)}function oneSetIsSubArrayOfOther(left,right){left=left.slice();for(const field of right){if(!left.length)break;const leftIdx=left.indexOf(field);if(-1===leftIdx)return!1;left.splice(leftIdx,1)}return!0}function arrayToObject(arr){const res2={};for(const field of arr)res2[field]=!0;return res2}function max2(arr,fun){let max3=null,maxScore=-1;for(const element2 of arr){const score=fun(element2);if(score>maxScore){maxScore=score;max3=element2}}return max3}function arrayEquals(arr1,arr2){if(arr1.length!==arr2.length)return!1;for(let i3=0,len=arr1.length;i3<len;i3++)if(arr1[i3]!==arr2[i3])return!1;return!0}function uniq2(arr){return Array.from(new Set(arr))}function resolveToCallback(fun){return function(...args){const maybeCallback=args[args.length-1];if("function"!=typeof maybeCallback)return fun.apply(this,args);{const fulfilled=maybeCallback.bind(null,null),rejected=maybeCallback.bind(null);fun.apply(this,args.slice(0,-1)).then(fulfilled,rejected)}}}function massageCreateIndexRequest(requestDef){requestDef=clone2(requestDef);requestDef.index||(requestDef.index={});for(const key3 of["type","name","ddoc"])if(requestDef.index[key3]){requestDef[key3]=requestDef.index[key3];delete requestDef.index[key3]}if(requestDef.fields){requestDef.index.fields=requestDef.fields;delete requestDef.fields}requestDef.type||(requestDef.type="json");return requestDef}function isNonNullObject(value){return"object"==typeof value&&null!==value}function checkFieldValueType(name,value,isHttp){let message="",received=value,addReceived=!0;-1!==["$in","$nin","$or","$and","$mod","$nor","$all"].indexOf(name)&&(Array.isArray(value)||(message="Query operator "+name+" must be an array."));-1!==["$not","$elemMatch","$allMatch"].indexOf(name)&&(!Array.isArray(value)&&isNonNullObject(value)||(message="Query operator "+name+" must be an object."));if("$mod"===name&&Array.isArray(value))if(2!==value.length)message="Query operator $mod must be in the format [divisor, remainder], where divisor and remainder are both integers.";else{const divisor=value[0],mod=value[1];if(0===divisor){message="Query operator $mod's divisor cannot be 0, cannot divide by zero.";addReceived=!1}if("number"!=typeof divisor||parseInt(divisor,10)!==divisor){message="Query operator $mod's divisor is not an integer.";received=divisor}if(parseInt(mod,10)!==mod){message="Query operator $mod's remainder is not an integer.";received=mod}}"$exists"===name&&"boolean"!=typeof value&&(message="Query operator $exists must be a boolean.");if("$type"===name){const allowed=["null","boolean","number","string","array","object"],allowedStr='"'+allowed.slice(0,allowed.length-1).join('", "')+'", or "'+allowed[allowed.length-1]+'"';("string"!=typeof value||-1==allowed.indexOf(value))&&(message="Query operator $type must be a string. Supported values: "+allowedStr+".")}"$size"===name&&parseInt(value,10)!==value&&(message="Query operator $size must be a integer.");"$regex"===name&&"string"!=typeof value&&(isHttp?message="Query operator $regex must be a string.":value instanceof RegExp||(message="Query operator $regex must be a string or an instance of a javascript regular expression."));if(message){if(addReceived){const type=null===received?" ":Array.isArray(received)?" array":" "+typeof received,receivedStr=isNonNullObject(received)?JSON.stringify(received,null,"\t"):received;message+=" Received"+type+": "+receivedStr}throw new Error(message)}}function validateSelector(input,isHttp){if(Array.isArray(input))for(const entry of input)isNonNullObject(entry)&&validateSelector(entry,isHttp);else for(const[key3,value]of Object.entries(input)){-1!==requireValidation.indexOf(key3)&&checkFieldValueType(key3,value,isHttp);-1===equalityOperators.indexOf(key3)&&(-1===arrayTypeComparisonOperators.indexOf(key3)&&isNonNullObject(value)&&validateSelector(value,isHttp))}}async function dbFetch(db,path2,opts){if(opts.body){opts.body=JSON.stringify(opts.body);opts.headers=new h2({"Content-type":"application/json"})}const response=await db.fetch(path2,opts),json=await response.json();if(!response.ok){json.status=response.status;const pouchError=createError(json);throw generateErrorFromResponse(pouchError)}return json}async function createIndex(db,requestDef){return await dbFetch(db,"_index",{method:"POST",body:massageCreateIndexRequest(requestDef)})}async function find(db,requestDef){validateSelector(requestDef.selector,!0);return await dbFetch(db,"_find",{method:"POST",body:requestDef})}async function explain(db,requestDef){return await dbFetch(db,"_explain",{method:"POST",body:requestDef})}async function getIndexes(db){return await dbFetch(db,"_index",{method:"GET"})}async function deleteIndex(db,indexDef){const ddoc=indexDef.ddoc,type=indexDef.type||"json",name=indexDef.name;if(!ddoc)throw new Error("you must provide an index's ddoc");if(!name)throw new Error("you must provide an index's name");const url="_index/"+[ddoc,type,name].map(encodeURIComponent).join("/");return await dbFetch(db,url,{method:"DELETE"})}function getDeepValue(value,path2){for(const key3 of path2){value=value[key3];if(void 0===value)return}return value}function createDeepMultiMapper(fields,emit2,selector){return function(doc){if(selector&&!matchesSelector(doc,selector))return;const toEmit=[];for(const field of fields){const value=getDeepValue(doc,parseField(field));if(void 0===value)return;toEmit.push(value)}emit2(toEmit)}}function createDeepSingleMapper(field,emit2,selector){const parsedField=parseField(field);return function(doc){if(selector&&!matchesSelector(doc,selector))return;const value=getDeepValue(doc,parsedField);void 0!==value&&emit2(value)}}function createShallowSingleMapper(field,emit2,selector){return function(doc){selector&&!matchesSelector(doc,selector)||emit2(doc[field])}}function createShallowMultiMapper(fields,emit2,selector){return function(doc){if(selector&&!matchesSelector(doc,selector))return;const toEmit=fields.map(field=>doc[field]);emit2(toEmit)}}function checkShallow(fields){return fields.every(field=>-1===field.indexOf("."))}function createMapper(fields,emit2,selector){const isShallow=checkShallow(fields),isSingle=1===fields.length;return isShallow?isSingle?createShallowSingleMapper(fields[0],emit2,selector):createShallowMultiMapper(fields,emit2,selector):isSingle?createDeepSingleMapper(fields[0],emit2,selector):createDeepMultiMapper(fields,emit2,selector)}function abstractMapper$1(db){return db._customFindAbstractMapper?{query:function addQueryFallback(signature,opts){const fallback3=abstractMapper.query.bind(this);return db._customFindAbstractMapper.query.call(this,signature,opts,fallback3)},viewCleanup:function addViewCleanupFallback(){const fallback3=abstractMapper.viewCleanup.bind(this);return db._customFindAbstractMapper.viewCleanup.call(this,fallback3)}}:abstractMapper}function massageSort(sort){if(!Array.isArray(sort))throw new Error("invalid sort json - should be an array");return sort.map(function(sorting){if("string"==typeof sorting){const obj={};obj[sorting]="asc";return obj}return sorting})}function massageUseIndex(useIndex){let cleanedUseIndex=[];"string"==typeof useIndex?cleanedUseIndex.push(useIndex):cleanedUseIndex=useIndex;return cleanedUseIndex.map(function(name){return name.replace(ddocIdPrefix,"")})}function massageIndexDef(indexDef){indexDef.fields=indexDef.fields.map(function(field){if("string"==typeof field){const obj={};obj[field]="asc";return obj}return field});indexDef.partial_filter_selector&&(indexDef.partial_filter_selector=massageSelector(indexDef.partial_filter_selector));return indexDef}function getKeyFromDoc(doc,index6){return index6.def.fields.map(obj=>{const field=getKey2(obj);return getFieldFromDoc(doc,parseField(field))})}function filterInclusiveStart(rows,targetValue,index6){const indexFields=index6.def.fields;let startAt=0;for(const row of rows){let docKey=getKeyFromDoc(row.doc,index6);if(1===indexFields.length)docKey=docKey[0];else for(;docKey.length>targetValue.length;)docKey.pop();if(Math.abs(collate(docKey,targetValue))>0)break;++startAt}return startAt>0?rows.slice(startAt):rows}function reverseOptions(opts){const newOpts=clone2(opts);delete newOpts.startkey;delete newOpts.endkey;delete newOpts.inclusive_start;delete newOpts.inclusive_end;"endkey"in opts&&(newOpts.startkey=opts.endkey);"startkey"in opts&&(newOpts.endkey=opts.startkey);"inclusive_start"in opts&&(newOpts.inclusive_end=opts.inclusive_start);"inclusive_end"in opts&&(newOpts.inclusive_start=opts.inclusive_end);return newOpts}function validateIndex(index6){const ascFields=index6.fields.filter(function(field){return"asc"===getValue(field)});if(0!==ascFields.length&&ascFields.length!==index6.fields.length)throw new Error("unsupported mixed sorting")}function validateSort(requestDef,index6){if(index6.defaultUsed&&requestDef.sort){const noneIdSorts=requestDef.sort.filter(function(sortItem){return"_id"!==Object.keys(sortItem)[0]}).map(function(sortItem){return Object.keys(sortItem)[0]});if(noneIdSorts.length>0)throw new Error('Cannot sort on field(s) "'+noneIdSorts.join(",")+'" when using the default index')}index6.defaultUsed}function validateFindRequest(requestDef){if("object"!=typeof requestDef.selector)throw new Error("you must provide a selector when you find()")}function getUserFields(selector,sort){const selectorFields=Object.keys(selector),sortFields=sort?sort.map(getKey2):[];let userFields;userFields=selectorFields.length>=sortFields.length?selectorFields:sortFields;if(0===sortFields.length)return{fields:userFields};userFields=userFields.sort(function(left,right){let leftIdx=sortFields.indexOf(left);-1===leftIdx&&(leftIdx=Number.MAX_VALUE);let rightIdx=sortFields.indexOf(right);-1===rightIdx&&(rightIdx=Number.MAX_VALUE);return leftIdx<rightIdx?-1:leftIdx>rightIdx?1:0});return{fields:userFields,sortOrder:sort.map(getKey2)}}async function createIndex$1(db,requestDef){function getMd5(){return md5||(md5=stringMd5(JSON.stringify(requestDef)))}requestDef=massageCreateIndexRequest(requestDef);const originalIndexDef=clone2(requestDef.index);requestDef.index=massageIndexDef(requestDef.index);validateIndex(requestDef.index);let md5;const viewName=requestDef.name||"idx-"+getMd5(),ddocName=requestDef.ddoc||"idx-"+getMd5(),ddocId="_design/"+ddocName;let hasInvalidLanguage=!1,viewExists=!1;db.constructor.emit("debug",["find","creating index",ddocId]);await upsert(db,ddocId,function updateDdoc(doc){doc._rev&&"query"!==doc.language&&(hasInvalidLanguage=!0);doc.language="query";doc.views=doc.views||{};viewExists=!!doc.views[viewName];if(viewExists)return!1;doc.views[viewName]={map:{fields:mergeObjects(requestDef.index.fields),partial_filter_selector:requestDef.index.partial_filter_selector},reduce:"_count",options:{def:originalIndexDef}};return doc});if(hasInvalidLanguage)throw new Error('invalid language for ddoc with id "'+ddocId+'" (should be "query")');const signature=ddocName+"/"+viewName;await abstractMapper$1(db).query.call(db,signature,{limit:0,reduce:!1});return{id:ddocId,name:viewName,result:viewExists?"exists":"created"}}async function getIndexes$1(db){const allDocsRes=await db.allDocs({startkey:"_design/",endkey:"_design/￿",include_docs:!0}),res2={indexes:[{ddoc:null,name:"_all_docs",type:"special",def:{fields:[{_id:"asc"}]}}]};res2.indexes=flatten2(res2.indexes,allDocsRes.rows.filter(function(row){return"query"===row.doc.language}).map(function(row){const viewNames=void 0!==row.doc.views?Object.keys(row.doc.views):[];return viewNames.map(function(viewName){const view=row.doc.views[viewName];return{ddoc:row.id,name:viewName,type:"json",def:massageIndexDef(view.options.def)}})}));res2.indexes.sort(function(left,right){return compare2(left.name,right.name)});res2.total_rows=res2.indexes.length;return res2}function checkFieldInIndex(index6,field){return index6.def.fields.some(key3=>getKey2(key3)===field)}function userOperatorLosesPrecision(selector,field){const matcher=selector[field],userOperator=getKey2(matcher);return"$eq"!==userOperator}function sortFieldsByIndex(userFields,index6){const indexFields=index6.def.fields.map(getKey2);return userFields.slice().sort(function(a2,b3){let aIdx=indexFields.indexOf(a2),bIdx=indexFields.indexOf(b3);-1===aIdx&&(aIdx=Number.MAX_VALUE);-1===bIdx&&(bIdx=Number.MAX_VALUE);return compare2(aIdx,bIdx)})}function getBasicInMemoryFields(index6,selector,userFields){userFields=sortFieldsByIndex(userFields,index6);let needToFilterInMemory=!1;for(let i3=0,len=userFields.length;i3<len;i3++){const field=userFields[i3];if(needToFilterInMemory||!checkFieldInIndex(index6,field))return userFields.slice(i3);i3<len-1&&userOperatorLosesPrecision(selector,field)&&(needToFilterInMemory=!0)}return[]}function getInMemoryFieldsFromNe(selector){const fields=[];for(const[field,matcher]of Object.entries(selector))for(const operator of Object.keys(matcher))"$ne"===operator&&fields.push(field);return fields}function getInMemoryFields(coreInMemoryFields,index6,selector,userFields){const result=flatten2(coreInMemoryFields,getBasicInMemoryFields(index6,selector,userFields),getInMemoryFieldsFromNe(selector));return sortFieldsByIndex(uniq2(result),index6)}function checkIndexFieldsMatch(indexFields,sortOrder,fields){if(sortOrder){const sortMatches=oneArrayIsStrictSubArrayOfOther(sortOrder,indexFields),selectorMatches=oneArrayIsSubArrayOfOther(fields,indexFields);return sortMatches&&selectorMatches}return oneSetIsSubArrayOfOther(fields,indexFields)}function isNonLogicalMatcher(matcher){return-1===logicalMatchers.indexOf(matcher)}function checkFieldsLogicallySound(indexFields,selector){const firstField=indexFields[0],matcher=selector[firstField];if(void 0===matcher)return!0;const isInvalidNe=1===Object.keys(matcher).length&&"$ne"===getKey2(matcher);return!isInvalidNe}function checkIndexMatches(index6,sortOrder,fields,selector){const indexFields=index6.def.fields.map(getKey2),fieldsMatch=checkIndexFieldsMatch(indexFields,sortOrder,fields);return!!fieldsMatch&&checkFieldsLogicallySound(indexFields,selector)}function findMatchingIndexes(selector,userFields,sortOrder,indexes2){return indexes2.filter(function(index6){return checkIndexMatches(index6,sortOrder,userFields,selector)})}function findBestMatchingIndex(selector,userFields,sortOrder,indexes2,useIndex){const matchingIndexes=findMatchingIndexes(selector,userFields,sortOrder,indexes2);if(0===matchingIndexes.length){if(useIndex)throw{error:"no_usable_index",message:"There is no index available for this selector."};const defaultIndex=indexes2[0];defaultIndex.defaultUsed=!0;return defaultIndex}if(1===matchingIndexes.length&&!useIndex)return matchingIndexes[0];const userFieldsMap=arrayToObject(userFields);if(useIndex){const useIndexDdoc="_design/"+useIndex[0],useIndexName=2===useIndex.length&&useIndex[1],index6=matchingIndexes.find(function(index7){return!(!useIndexName||index7.ddoc!==useIndexDdoc||useIndexName!==index7.name)||index7.ddoc===useIndexDdoc});if(!index6)throw{error:"unknown_error",message:"Could not find that index or could not use that index for the query"};return index6}return max2(matchingIndexes,function scoreIndex(index6){const indexFields=index6.def.fields.map(getKey2);let score=0;for(const indexField of indexFields)userFieldsMap[indexField]&&score++;return score})}function getSingleFieldQueryOptsFor(userOperator,userValue){switch(userOperator){case"$eq":return{key:userValue};case"$lte":return{endkey:userValue};case"$gte":return{startkey:userValue};case"$lt":return{endkey:userValue,inclusive_end:!1};case"$gt":return{startkey:userValue,inclusive_start:!1}}return{startkey:COLLATE_LO}}function getSingleFieldCoreQueryPlan(selector,index6){const field=getKey2(index6.def.fields[0]),matcher=selector[field]||{},inMemoryFields=[],userOperators=Object.keys(matcher);let combinedOpts;for(const userOperator of userOperators){isNonLogicalMatcher(userOperator)&&inMemoryFields.push(field);const userValue=matcher[userOperator],newQueryOpts=getSingleFieldQueryOptsFor(userOperator,userValue);combinedOpts=combinedOpts?mergeObjects([combinedOpts,newQueryOpts]):newQueryOpts}return{queryOpts:combinedOpts,inMemoryFields}}function getMultiFieldCoreQueryPlan(userOperator,userValue){switch(userOperator){case"$eq":return{startkey:userValue,endkey:userValue};case"$lte":return{endkey:userValue};case"$gte":return{startkey:userValue};case"$lt":return{endkey:userValue,inclusive_end:!1};case"$gt":return{startkey:userValue,inclusive_start:!1}}}function getMultiFieldQueryOpts(selector,index6){function finish(i3){!1!==inclusiveStart&&startkey.push(COLLATE_LO);!1!==inclusiveEnd&&endkey.push(COLLATE_HI);inMemoryFields=indexFields.slice(i3)}const indexFields=index6.def.fields.map(getKey2);let inMemoryFields=[];const startkey=[],endkey=[];let inclusiveStart,inclusiveEnd;for(let i3=0,len=indexFields.length;i3<len;i3++){const indexField=indexFields[i3],matcher=selector[indexField];if(!matcher||!Object.keys(matcher).length){finish(i3);break}if(Object.keys(matcher).some(isNonLogicalMatcher)){finish(i3);break}if(i3>0){const usingGtlt="$gt"in matcher||"$gte"in matcher||"$lt"in matcher||"$lte"in matcher,previousKeys=Object.keys(selector[indexFields[i3-1]]),previousWasEq=arrayEquals(previousKeys,["$eq"]),previousWasSame=arrayEquals(previousKeys,Object.keys(matcher)),gtltLostSpecificity=usingGtlt&&!previousWasEq&&!previousWasSame;if(gtltLostSpecificity){finish(i3);break}}const userOperators=Object.keys(matcher);let combinedOpts=null;for(const userOperator of userOperators){const userValue=matcher[userOperator],newOpts=getMultiFieldCoreQueryPlan(userOperator,userValue);combinedOpts=combinedOpts?mergeObjects([combinedOpts,newOpts]):newOpts}startkey.push("startkey"in combinedOpts?combinedOpts.startkey:COLLATE_LO);endkey.push("endkey"in combinedOpts?combinedOpts.endkey:COLLATE_HI);"inclusive_start"in combinedOpts&&(inclusiveStart=combinedOpts.inclusive_start);"inclusive_end"in combinedOpts&&(inclusiveEnd=combinedOpts.inclusive_end)}const res2={startkey,endkey};void 0!==inclusiveStart&&(res2.inclusive_start=inclusiveStart);void 0!==inclusiveEnd&&(res2.inclusive_end=inclusiveEnd);return{queryOpts:res2,inMemoryFields}}function shouldShortCircuit(selector){const values2=Object.keys(selector).map(function(key3){return selector[key3]});return values2.some(function(val){return"object"==typeof val&&0===Object.keys(val).length})}function getDefaultQueryPlan(selector){return{queryOpts:{startkey:null},inMemoryFields:[Object.keys(selector)]}}function getCoreQueryPlan(selector,index6){return index6.defaultUsed?getDefaultQueryPlan(selector):1===index6.def.fields.length?getSingleFieldCoreQueryPlan(selector,index6):getMultiFieldQueryOpts(selector,index6)}function planQuery(request2,indexes2){const selector=request2.selector,sort=request2.sort;if(shouldShortCircuit(selector))return Object.assign({},SHORT_CIRCUIT_QUERY,{index:indexes2[0]});const userFieldsRes=getUserFields(selector,sort),userFields=userFieldsRes.fields,sortOrder=userFieldsRes.sortOrder,index6=findBestMatchingIndex(selector,userFields,sortOrder,indexes2,request2.use_index),coreQueryPlan=getCoreQueryPlan(selector,index6),queryOpts=coreQueryPlan.queryOpts,coreInMemoryFields=coreQueryPlan.inMemoryFields,inMemoryFields=getInMemoryFields(coreInMemoryFields,index6,selector,userFields);return{queryOpts,index:index6,inMemoryFields}}function indexToSignature(index6){return index6.ddoc.substring(8)+"/"+index6.name}async function doAllDocs(db,originalOpts){const opts=clone2(originalOpts);if(opts.descending){"endkey"in opts&&"string"!=typeof opts.endkey&&(opts.endkey="");"startkey"in opts&&"string"!=typeof opts.startkey&&(opts.limit=0)}else{"startkey"in opts&&"string"!=typeof opts.startkey&&(opts.startkey="");"endkey"in opts&&"string"!=typeof opts.endkey&&(opts.limit=0)}"key"in opts&&"string"!=typeof opts.key&&(opts.limit=0);if(opts.limit>0&&opts.indexes_count){opts.original_limit=opts.limit;opts.limit+=opts.indexes_count}const res2=await db.allDocs(opts);res2.rows=res2.rows.filter(function(row){return!/^_design\//.test(row.id)});opts.original_limit&&(opts.limit=opts.original_limit);res2.rows=res2.rows.slice(0,opts.limit);return res2}async function queryAllOrIndex(db,opts,indexToUse){return"_all_docs"===indexToUse.name?doAllDocs(db,opts):abstractMapper$1(db).query.call(db,indexToSignature(indexToUse),opts)}async function find$1(db,requestDef,explain2){if(requestDef.selector){validateSelector(requestDef.selector,!1);requestDef.selector=massageSelector(requestDef.selector)}requestDef.sort&&(requestDef.sort=massageSort(requestDef.sort));requestDef.use_index&&(requestDef.use_index=massageUseIndex(requestDef.use_index));"limit"in requestDef||(requestDef.limit=25);validateFindRequest(requestDef);const getIndexesRes=await getIndexes$1(db);db.constructor.emit("debug",["find","planning query",requestDef]);const queryPlan=planQuery(requestDef,getIndexesRes.indexes);db.constructor.emit("debug",["find","query plan",queryPlan]);const indexToUse=queryPlan.index;validateSort(requestDef,indexToUse);let opts=Object.assign({include_docs:!0,reduce:!1,indexes_count:getIndexesRes.total_rows},queryPlan.queryOpts);if("startkey"in opts&&"endkey"in opts&&collate(opts.startkey,opts.endkey)>0)return{docs:[]};const isDescending=requestDef.sort&&"string"!=typeof requestDef.sort[0]&&"desc"===getValue(requestDef.sort[0]);if(isDescending){opts.descending=!0;opts=reverseOptions(opts)}if(!queryPlan.inMemoryFields.length){opts.limit=requestDef.limit;"skip"in requestDef&&(opts.skip=requestDef.skip)}if(explain2)return Promise.resolve(queryPlan,opts);const res2=await queryAllOrIndex(db,opts,indexToUse);!1===opts.inclusive_start&&(res2.rows=filterInclusiveStart(res2.rows,opts.startkey,indexToUse));queryPlan.inMemoryFields.length&&(res2.rows=filterInMemoryFields(res2.rows,requestDef,queryPlan.inMemoryFields));const resp={docs:res2.rows.map(function(row){const doc=row.doc;return requestDef.fields?pick2(doc,requestDef.fields):doc})};indexToUse.defaultUsed&&(resp.warning="No matching index found, create an index to optimize query time.");return resp}async function explain$1(db,requestDef){const queryPlan=await find$1(db,requestDef,!0);return{dbname:db.name,index:queryPlan.index,selector:requestDef.selector,range:{start_key:queryPlan.queryOpts.startkey,end_key:queryPlan.queryOpts.endkey},opts:{use_index:requestDef.use_index||[],bookmark:"nil",limit:requestDef.limit,skip:requestDef.skip,sort:requestDef.sort||{},fields:requestDef.fields,conflicts:!1,r:[49]},limit:requestDef.limit,skip:requestDef.skip||0,fields:requestDef.fields}}async function deleteIndex$1(db,index6){if(!index6.ddoc)throw new Error("you must supply an index.ddoc when deleting");if(!index6.name)throw new Error("you must supply an index.name when deleting");const docId=index6.ddoc,viewName=index6.name;await upsert(db,docId,function deltaFun(doc){if(1===Object.keys(doc.views).length&&doc.views[viewName])return{_id:docId,_deleted:!0};delete doc.views[viewName];return doc});await abstractMapper$1(db).viewCleanup.apply(db);return{ok:!0}}function appendPurgeSeqs(db,docs){return db.get("_local/purges").then(function(doc){for(const[docId,rev$$1]of docs){const purgeSeq=doc.purgeSeq+1;doc.purges.push({docId,rev:rev$$1,purgeSeq});doc.purges.length>db.purged_infos_limit&&doc.purges.splice(0,doc.purges.length-db.purged_infos_limit);doc.purgeSeq=purgeSeq}return doc}).catch(function(err3){if(404!==err3.status)throw err3;return{_id:"_local/purges",purges:docs.map(([docId,rev$$1],idx2)=>({docId,rev:rev$$1,purgeSeq:idx2})),purgeSeq:docs.length}}).then(function(doc){return db.put(doc)})}function getE2EEConfigSummary(setting,showAdvanced=!1){const settingTable=pickEncryptionSettings(setting);return getSummaryFromPartialSettings(settingTable,showAdvanced)}function getSummaryFromPartialSettings(setting,showAdvanced=!1){const outputSummary={};for(const key3 of Object.keys(setting)){const config=getConfig2(key3);if(!config)continue;if(config.isAdvanced&&!showAdvanced)continue;const value="E2EEAlgorithm"!=key3?`${setting[key3]}`:E2EEAlgorithmNames[`${setting[key3]}`],displayValue=config.isHidden?"•".repeat(value.length):escapeStringToHTML(value);outputSummary[config.name]=displayValue}return outputSummary}async function copyMigrationDocs(docName,dbFrom,dbTo){try{const doc=await dbFrom.get(docName);delete doc._rev;await dbTo.put(doc)}catch(e3){if(isNotFoundError(e3))return;throw e3}}async function migrateDatabases(operationName,from,openTo){const dbTo=await openTo();await dbTo.info();Logger(`Opening destination database for migration: ${operationName}.`,LOG_LEVEL_NOTICE,"migration");await dbTo.destroy();Logger(`Destroyed existing destination database for migration: ${operationName}.`,LOG_LEVEL_NOTICE,"migration");const dbTo2=await openTo();await dbTo2.info();Logger(`Re-created destination database for migration: ${operationName}.`,LOG_LEVEL_NOTICE,"migration");const info3=await from.info(),totalDocs=info3.doc_count||0,result=await from.replicate.to(dbTo2,{style:"all_docs"}).on("change",info4=>{Logger(`Replicating... Docs replicated: ${info4.docs_written} / ${totalDocs}`,LOG_LEVEL_NOTICE,"migration")});if(!result.ok)throw new Error(`Replication failed for migration: ${operationName}.`);Logger(`Replication completed for migration: ${operationName}.`,LOG_LEVEL_NOTICE,"migration");await copyMigrationDocs(MILESTONE_DOCID,from,dbTo2);await copyMigrationDocs(NODEINFO_DOCID,from,dbTo2);Logger(`Copied migration documents for migration: ${operationName}.`,LOG_LEVEL_NOTICE,"migration");await dbTo2.close();return!0}function usesLegacyIndexedDBAdapter(settings){return settings.useIndexedDBAdapter}function disableLegacyBulkChunkPreSend(settings){if(!settings.sendChunksBulk)return!1;settings.sendChunksBulk=!1;settings.sendChunksBulkMaxSize=1;return!0}function panePatches(paneEl,{addPanel}){addPanel(paneEl,"Compatibility (Metadata)").then(paneEl2=>{new LiveSyncSetting(paneEl2).autoWireToggle("deleteMetadataOfDeletedFiles");new LiveSyncSetting(paneEl2).autoWireNumeric("automaticallyDeleteMetadataOfDeletedFiles",{onUpdate:visibleOnly(()=>this.isConfiguredAs("deleteMetadataOfDeletedFiles",!0))})});addPanel(paneEl,"Compatibility (Conflict Behaviour)").then(paneEl2=>{new LiveSyncSetting(paneEl2).autoWireToggle("disableMarkdownAutoMerge");new LiveSyncSetting(paneEl2).autoWireToggle("writeDocumentsIfConflicted")});addPanel(paneEl,"Compatibility (Database structure)").then(paneEl2=>{const migrateAllToIndexedDB=async()=>{const dbToName=this.core.localDatabase.dbname+SuffixDatabaseName+ExtraSuffixIndexedDB,options={adapter:"indexeddb",purged_infos_limit:1,auto_compaction:!1,deterministic_revs:!0};if(await migrateDatabases("to IndexedDB",this.core.localDatabase.localDatabase,()=>new index_es_default(dbToName,options))){Logger("Migration to IndexedDB completed. Obsidian will be restarted with new configuration immediately.",LOG_LEVEL_NOTICE);await this.core.services.setting.applyPartial({useIndexedDBAdapter:!0},!0);this.services.appLifecycle.performRestart()}},migrateAllToIDB=async()=>{const dbToName=this.core.localDatabase.dbname+SuffixDatabaseName,options={adapter:"idb",auto_compaction:!1,deterministic_revs:!0};if(await migrateDatabases("to IDB",this.core.localDatabase.localDatabase,()=>new index_es_default(dbToName,options))){Logger("Migration to IDB completed. Obsidian will be restarted with new configuration immediately.",LOG_LEVEL_NOTICE);await this.core.services.setting.applyPartial({useIndexedDBAdapter:!1},!0);this.services.appLifecycle.performRestart()}};{const useIndexedDBAdapter=usesLegacyIndexedDBAdapter(this.editingSettings),infoClass=useIndexedDBAdapter?"op-warn":"op-warn-info";paneEl2.createDiv({text:"The IndexedDB adapter often offers superior performance in certain scenarios, but it has been found to cause memory leaks when used with LiveSync mode. When using LiveSync mode, please use IDB adapter instead.",cls:infoClass});paneEl2.createDiv({text:"Changing this setting requires migrating existing data (a bit time may be taken) and restarting Obsidian. Please make sure to back up your data before proceeding.",cls:"op-warn-info"});const setting=new LiveSyncSetting(paneEl2).setName("Database Adapter").setDesc("Select the database adapter to use. "),el=setting.controlEl.createDiv({});el.setText("Current adapter: "+(useIndexedDBAdapter?"IndexedDB":"IDB"));useIndexedDBAdapter?setting.addButton(button=>{button.setButtonText("Switch to IDB").onClick(async()=>{Logger("Migrating all data to IDB...",LOG_LEVEL_NOTICE);await migrateAllToIDB();Logger("Migration to IDB completed. Please switch the adapter and restart Obsidian.",LOG_LEVEL_NOTICE)})}):setting.addButton(button=>{button.setButtonText("Switch to IndexedDB").onClick(async()=>{Logger("Migrating all data to IndexedDB...",LOG_LEVEL_NOTICE);await migrateAllToIndexedDB();Logger("Migration to IndexedDB completed. Please switch the adapter and restart Obsidian.",LOG_LEVEL_NOTICE)})})}new LiveSyncSetting(paneEl2).autoWireToggle("handleFilenameCaseSensitive",{holdValue:!0})});addPanel(paneEl,"Compatibility (Internal API Usage)").then(paneEl2=>{new LiveSyncSetting(paneEl2).autoWireToggle("watchInternalFileChanges",{invert:!0})});addPanel(paneEl,"Compatibility (Remote Database)").then(paneEl2=>{new LiveSyncSetting(paneEl2).autoWireDropDown("E2EEAlgorithm",{options:E2EEAlgorithmNames})});new LiveSyncSetting(paneEl).autoWireToggle("useDynamicIterationCount",{holdValue:!0,onUpdate:visibleOnly(()=>this.isConfiguredAs("E2EEAlgorithm",E2EEAlgorithms.ForceV1)||this.isConfiguredAs("E2EEAlgorithm",E2EEAlgorithms.V1))});addPanel(paneEl,"Edge case addressing (Database)").then(paneEl2=>{new LiveSyncSetting(paneEl2).autoWireText("additionalSuffixOfDatabaseName",{holdValue:!0}).addApplyButton(["additionalSuffixOfDatabaseName"]);this.addOnSaved("additionalSuffixOfDatabaseName",async key3=>{Logger("Suffix has been changed. Reopening database...",LOG_LEVEL_NOTICE);await this.services.databaseEvents.initialiseDatabase()});new LiveSyncSetting(paneEl2).autoWireDropDown("hashAlg",{options:{"":"Old Algorithm",xxhash32:"xxhash32 (Fast but less collision resistance)",xxhash64:"xxhash64 (Fastest)","mixed-purejs":"PureJS fallback (Fast, W/O WebAssembly)",sha1:"Older fallback (Slow, W/O WebAssembly)"}});this.addOnSaved("hashAlg",async()=>{await this.core.localDatabase._prepareHashFunctions()})});addPanel(paneEl,"Edge case addressing (Behaviour)").then(paneEl2=>{new LiveSyncSetting(paneEl2).autoWireToggle("doNotSuspendOnFetching");new LiveSyncSetting(paneEl2).autoWireToggle("doNotDeleteFolder");new LiveSyncSetting(paneEl2).autoWireToggle("processSizeMismatchedFiles")});addPanel(paneEl,"Edge case addressing (Processing)").then(paneEl2=>{new LiveSyncSetting(paneEl2).autoWireToggle("disableWorkerForGeneratingChunks");new LiveSyncSetting(paneEl2).autoWireToggle("processSmallFilesInUIThread",{onUpdate:visibleOnly(()=>this.isConfiguredAs("disableWorkerForGeneratingChunks",!1))})});addPanel(paneEl,"Compatibility (Trouble addressed)").then(paneEl2=>{new LiveSyncSetting(paneEl2).autoWireToggle("disableCheckingConfigMismatch")});addPanel(paneEl,"Remediation").then(paneEl2=>{const setting=setSettingAdditionalActionsState(new LiveSyncSetting(paneEl2)),dateEl=setting.controlEl.createSpan();setting.addText(text2=>{const updateDateText=()=>{if(0==this.editingSettings.maxMTimeForReflectEvents)dateEl.textContent="No limit configured";else{const date2=new Date(this.editingSettings.maxMTimeForReflectEvents);dateEl.textContent=`Limit: ${date2.toLocaleString()} (${this.editingSettings.maxMTimeForReflectEvents})`}this.requestUpdate()};text2.inputEl.type="datetime-local";if(this.editingSettings.maxMTimeForReflectEvents>0){const date2=new Date(this.editingSettings.maxMTimeForReflectEvents),isoString=date2.toISOString().slice(0,16);text2.setValue(isoString)}else text2.setValue("");text2.onChange(value=>{if(""==value){this.editingSettings.maxMTimeForReflectEvents=0;updateDateText();return}const date2=new Date(value);isNaN(date2.getTime())||(this.editingSettings.maxMTimeForReflectEvents=date2.getTime());updateDateText()});updateDateText();return text2}).setAuto("maxMTimeForReflectEvents").addApplyButton(["maxMTimeForReflectEvents"]);setting.applyButtonComponent&&setButtonAdditionalActionState(setting.applyButtonComponent);this.addOnSaved("maxMTimeForReflectEvents",async key3=>{const reboot=await this.core.confirm.askSelectStringDialogue("Restarting Obsidian is strongly recommended. Until restart, some changes may not take effect, and display may be inconsistent. Are you sure to restart now?",["Restart Now","Later"],{title:"Remediation Setting Changed",defaultAction:"Restart Now"});if("Later"!==reboot){Logger("Remediation setting changed. Restarting Obsidian...",LOG_LEVEL_NOTICE);this.services.appLifecycle.performRestart()}})})}function panePowerUsers(paneEl,{addPanel}){addPanel(paneEl,"CouchDB Connection Tweak",void 0,this.onlyOnCouchDB).then(paneEl2=>{this.createEl(paneEl2,"div",{text:"If you reached the payload size limit when using IBM Cloudant, please decrease batch size and batch limit to a lower value."},void 0,this.onlyOnCouchDB);new LiveSyncSetting(paneEl2).autoWireNumeric("batch_size",{clampMin:2,onUpdate:this.onlyOnCouchDB});new LiveSyncSetting(paneEl2).autoWireNumeric("batches_limit",{clampMin:2,onUpdate:this.onlyOnCouchDB});new LiveSyncSetting(paneEl2).autoWireToggle("useTimeouts",{onUpdate:this.onlyOnCouchDB})});addPanel(paneEl,"Configuration Encryption").then(paneEl2=>{new LiveSyncSetting(paneEl2).setName("Encrypting sensitive configuration items").autoWireDropDown("configPassphraseStore",{options:{"":"Default",LOCALSTORAGE:"Use a custom passphrase",ASK_AT_LAUNCH:"Ask an passphrase at every launch"},holdValue:!0});new LiveSyncSetting(paneEl2).autoWireText("configPassphrase",{isPassword:!0,holdValue:!0}).addOnUpdate(()=>({disabled:!this.isConfiguredAs("configPassphraseStore","LOCALSTORAGE")}));new LiveSyncSetting(paneEl2).addApplyButton(["configPassphrase","configPassphraseStore"])});addPanel(paneEl,"Developer").then(paneEl2=>{new LiveSyncSetting(paneEl2).autoWireToggle("enableDebugTools")})}function InfoTable($$anchor,$$props){var div,div_1;append_styles($$anchor,$$css5);const infoEntries=user_derived(()=>Object.entries(null!==$$props.info&&void 0!==$$props.info?$$props.info:{}));div=root_15();div_1=child(div);each(div_1,21,()=>get2(infoEntries),index,($$anchor2,$$item)=>{var fragment,div_2,div_3,text2,div_4,div_5,text_1,$$array=user_derived(()=>to_array(get2($$item),2));let key3=()=>get2($$array)[0],value=()=>get2($$array)[1];fragment=root6();div_2=first_child(fragment);div_3=child(div_2);text2=child(div_3,!0);reset(div_3);reset(div_2);div_4=sibling(div_2,2);div_5=child(div_4);text_1=child(div_5,!0);reset(div_5);reset(div_4);template_effect(()=>{set_attribute2(div_2,"aria-label",key3());set_text(text2,key3());set_attribute2(div_4,"aria-label",key3());set_text(text_1,value())});append($$anchor2,fragment)});reset(div_1);reset(div);append($$anchor,div)}function InfoPanel($$anchor,$$props){push($$props,!0);const $port=()=>store_get($$props.port,"$port",$$stores),[$$stores,$$cleanup]=setup_stores(),info3=user_derived(()=>{var _a13;return null!==(_a13=null===$port()||void 0===$port()?void 0:$port().info)&&void 0!==_a13?_a13:{}});InfoTable($$anchor,{get info(){return get2(info3)}});pop();$$cleanup()}function migrateLegacyRemoteConfigurationsInPlace(settings,log2){const hasText=value=>"string"==typeof value&&""!==value.trim();settings.remoteConfigurations||(settings.remoteConfigurations={});if(0!==Object.keys(settings.remoteConfigurations).length)return!1;const hasCouchDB=hasText(settings.couchDB_URI),hasS3=hasText(settings.endpoint),hasP2P=hasText(settings.P2P_roomID);if(!hasCouchDB&&!hasS3&&!hasP2P)return!1;null==log2||log2("Migrating existing remote configuration to sls+ format...");const candidates=[{id:"legacy-couchdb",name:"CouchDB Remote",type:"couchdb",enabled:hasCouchDB},{id:"legacy-s3",name:"S3 Remote",type:"s3",enabled:hasS3},{id:"legacy-p2p",name:"P2P Remote",type:"p2p",enabled:hasP2P}];for(const candidate of candidates)if(candidate.enabled)try{const uri=ConnectionStringParser.serialize({type:candidate.type,settings});settings.remoteConfigurations[candidate.id]={id:candidate.id,name:candidate.name,uri,isEncrypted:!1}}catch(e3){null==log2||log2(`Failed to migrate ${candidate.type} configuration!`);null==log2||log2(e3,LOG_LEVEL_VERBOSE)}const createdIds=Object.keys(settings.remoteConfigurations);if(0===createdIds.length)return!1;const preferredId=settings.remoteType===REMOTE_MINIO?"legacy-s3":settings.remoteType===REMOTE_P2P?"legacy-p2p":"legacy-couchdb";settings.activeConfigurationId=settings.remoteConfigurations[preferredId]?preferredId:createdIds[0];return!0}function createRemoteConfigurationId(){return`remote-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function toRemoteConfigurationResult(type,settings){return{type,settings}}function suggestRemoteConfigurationName(configuration){if("couchdb"===configuration.type)try{const host=new URL(configuration.settings.couchDB_URI).host;return host?`CouchDB ${host}`:"CouchDB remote"}catch(e3){return"CouchDB remote"}if("s3"===configuration.type){const bucket=configuration.settings.bucket.trim();if(bucket)return`S3 ${bucket}`;try{const host=new URL(configuration.settings.endpoint).host;return host?`S3 ${host}`:"Object Storage remote"}catch(e3){return"Object Storage remote"}}if("p2p"===configuration.type){const room=configuration.settings.P2P_roomID.trim();return room?`P2P ${room}`:"P2P remote"}return"Remote configuration"}function allocateRemoteConfigurationId(configurations){let id=createRemoteConfigurationId();for(;configurations[id];)id=createRemoteConfigurationId();return id}function allocateRemoteConfigurationName(configurations,baseName,updatingId){const usedNames=new Set(Object.values(configurations).filter(configuration=>configuration.id!==updatingId).map(configuration=>configuration.name));if(!usedNames.has(baseName))return baseName;let suffix=2;for(;usedNames.has(`${baseName} (${suffix})`);)suffix+=1;return`${baseName} (${suffix})`}function upsertRemoteConfigurationInPlace(settings,type,options={}){var _a13,_b6,_c3;if(options.activateForP2P&&"p2p"!==type)throw new Error("Only a P2P remote configuration can be selected for P2P features.");const configurations=null!=(_a13=settings.remoteConfigurations)?_a13:{},requestedId=null==(_b6=options.id)?void 0:_b6.trim(),id=requestedId||allocateRemoteConfigurationId(configurations),existing=configurations[id],serialisable=toRemoteConfigurationResult(type,settings),suggestedName=suggestRemoteConfigurationName(serialisable),requestedName=null==(_c3=options.name)?void 0:_c3.trim(),name=requestedName||(null==existing?void 0:existing.name)||allocateRemoteConfigurationName(configurations,suggestedName,null==existing?void 0:existing.id),configuration={id,name,uri:ConnectionStringParser.serialize(serialisable),isEncrypted:!1};null!=settings.remoteConfigurations||(settings.remoteConfigurations=configurations);configurations[id]=configuration;if(options.activate&&!activateRemoteConfiguration(settings,id))throw new Error(`Failed to activate remote configuration '${id}'.`);if(options.activateForP2P&&!activateP2PRemoteConfiguration(settings,id))throw new Error(`Failed to activate P2P remote configuration '${id}'.`);return configuration}function migrateP2PActiveRemoteConfigurationIdInPlace(settings){var _a13,_b6;if(""!==(null!=(_a13=settings.P2P_ActiveRemoteConfigurationId)?_a13:"").trim())return!1;const activeId=settings.activeConfigurationId;if(!activeId)return!1;const config=null==(_b6=settings.remoteConfigurations)?void 0:_b6[activeId];if(!config)return!1;if(settings.remoteType!==REMOTE_P2P)return!1;try{const parsed=ConnectionStringParser.parse(config.uri);if("p2p"!==parsed.type)return!1}catch(e3){return!1}settings.P2P_ActiveRemoteConfigurationId=activeId;return!0}async function migrateToMultipleRemoteConfigurations(host){const log2=createInstanceLogFunction("SF:RemoteConfig",host.services.API),settings=host.services.setting.currentSettings();if(migrateLegacyRemoteConfigurationsInPlace(settings,log2)){await host.services.setting.saveSettingData();log2(`Successfully migrated ${Object.keys(settings.remoteConfigurations).length} remote configuration(s).`);return!0}return!1}function activateRemoteConfiguration(settings,id){var _a13;const config=null==(_a13=settings.remoteConfigurations)?void 0:_a13[id];if(!config)return!1;settings.activeConfigurationId=id;try{const parsed=ConnectionStringParser.parse(config.uri);if("couchdb"===parsed.type){settings.remoteType=REMOTE_COUCHDB;Object.assign(settings,parsed.settings)}else if("s3"===parsed.type){settings.remoteType=REMOTE_MINIO;Object.assign(settings,parsed.settings)}else if("p2p"===parsed.type){settings.remoteType=REMOTE_P2P;Object.assign(settings,parsed.settings)}return settings}catch(e3){return!1}}function activateP2PRemoteConfiguration(settings,id){var _a13;const config=null==(_a13=settings.remoteConfigurations)?void 0:_a13[id];if(!config)return!1;try{const parsed=ConnectionStringParser.parse(config.uri);if("p2p"!==parsed.type)return!1;const currentRemoteType=settings.remoteType;settings.P2P_ActiveRemoteConfigurationId=id;Object.assign(settings,parsed.settings);settings.remoteType=currentRemoteType;return settings}catch(e3){return!1}}async function commandSwitchActiveRemote(host){var _a13;const settings=host.services.setting.currentSettings(),configs=settings.remoteConfigurations;if(!configs||0===Object.keys(configs).length){host.services.API.addLog("No remote configurations found.",LOG_LEVEL_NOTICE,"remote-config");return}const options=Object.values(configs).map(c3=>({label:`${c3.name} (${c3.id===settings.activeConfigurationId?"Active":"Inactive"})`,value:c3.id})),selectedLabel=await host.services.UI.confirm.askSelectString("Select a remote configuration to activate",options.map(o2=>o2.label));if(selectedLabel){const actualId=null==(_a13=options.find(o2=>o2.label===selectedLabel))?void 0:_a13.value;if(actualId){let updated=!1;await host.services.setting.updateSettings(currentSettings=>{const activated=activateRemoteConfiguration(currentSettings,actualId);if(activated){updated=!0;return activated}return currentSettings});if(updated){host.services.API.addLog(`Switched to remote: ${selectedLabel}`,LOG_LEVEL_NOTICE,"remote-config");await host.services.control.applySettings();await host.services.setting.saveSettingData()}}}}async function commandReplicateWithSpecificRemote(host){const settings=host.services.setting.currentSettings(),configs=settings.remoteConfigurations;if(!configs||0===Object.keys(configs).length){host.services.API.addLog("No remote configurations found.",LOG_LEVEL_NOTICE,"remote-config");return}const selectedName=await host.services.UI.confirm.askSelectString("Select a remote to replicate with",Object.values(configs).map(c3=>c3.name));if(selectedName){const config=Object.values(configs).find(c3=>c3.name===selectedName);if(config)try{let updated=!1;await host.services.setting.updateSettings(currentSettings=>{const activated=activateRemoteConfiguration(currentSettings,config.id);if(activated){updated=!0;return activated}return currentSettings});if(updated){host.services.API.addLog(`Switched to remote: ${selectedName} and starting replication...`,LOG_LEVEL_NOTICE,"remote-config");await host.services.control.applySettings();await host.services.setting.saveSettingData();await host.services.replication.replicate(!0)}}catch(e3){host.services.API.addLog("Failed to parse remote! Detailed information is available in verbose logs.",LOG_LEVEL_NOTICE,"remote-config");host.services.API.addLog(e3,LOG_LEVEL_VERBOSE,"remote-config")}}}function useRemoteConfigurationMigration(host){host.services.appLifecycle.onSettingLoaded.addHandler(async()=>{try{await migrateToMultipleRemoteConfigurations(host)}catch(e3){host.services.API.addLog("Migration failed! Detailed information is available in verbose logs.",LOG_LEVEL_NOTICE,"remote-config");host.services.API.addLog(e3,LOG_LEVEL_VERBOSE,"remote-config")}return!0})}function useRemoteConfiguration(host){host.services.API.addCommand({id:"livesync-switch-remote",name:"Switch active connection",callback:()=>commandSwitchActiveRemote(host)});host.services.API.addCommand({id:"livesync-replicate-with-specific",name:"Sync with a saved connection",callback:()=>commandReplicateWithSpecificRemote(host)});return!0}function setupDialogContext(controls){setContext(CONTEXT_DIALOG_CONTROLS,controls)}function getDialogContext(){return getContext(CONTEXT_DIALOG_CONTROLS)}function DialogHeader($$anchor,$$props){var div,h22,text2,node,consequent;push($$props,!0);append_styles($$anchor,$$css6);const context2=getDialogContext(),translatedTitle=user_derived(()=>translateIfAvailable($$props.title)),translatedSubtitle=user_derived(()=>$$props.subtitle?translateIfAvailable($$props.subtitle):""),modalTitle=user_derived(()=>`${get2(translatedTitle)}${get2(translatedSubtitle)?` - ${get2(translatedSubtitle)}`:""}`);user_effect(()=>{get2(translatedTitle)&&context2.setTitle(get2(modalTitle))});onMount(async()=>{var _a13;context2.setTitle(get2(modalTitle));await tick();null===(_a13=_activeDocument.querySelector(".modal"))||void 0===_a13||_a13.scrollTo(0,0)});div=root_16();h22=child(div);text2=child(h22,!0);reset(h22);node=sibling(h22,2);consequent=$$anchor2=>{var h4=root7(),text_1=child(h4,!0);reset(h4);template_effect(()=>set_text(text_1,get2(translatedSubtitle)));append($$anchor2,h4)};if_block(node,$$render=>{get2(translatedSubtitle)&&$$render(consequent)});reset(div);template_effect(()=>set_text(text2,get2(translatedTitle)));append($$anchor,div);pop()}function Guidance($$anchor,$$props){var div,node,consequent,node_1;push($$props,!0);const cssClass=user_derived(()=>$$props.important?"guidance important":"guidance"),translatedTitle=user_derived(()=>$$props.title?translateIfAvailable($$props.title):"");div=root_17();node=child(div);consequent=$$anchor2=>{var h3=root8(),text2=child(h3,!0);reset(h3);template_effect(()=>set_text(text2,get2(translatedTitle)));append($$anchor2,h3)};if_block(node,$$render=>{get2(translatedTitle)&&$$render(consequent)});node_1=sibling(node,2);snippet(node_1,()=>{var _a13;return null!=(_a13=$$props.children)?_a13:noop2});reset(div);template_effect(()=>set_class(div,1,clsx2(get2(cssClass))));append($$anchor,div);pop()}function InfoNote($$anchor,$$props){var fragment,node,consequent_3;push($$props,!0);const isInfo=prop($$props,"info",3,!0),derivedCssClass=user_derived(()=>$$props.error?"note-error sls-info-note sls-info-note-danger":$$props.warning?"note-important sls-info-note sls-info-note-warning":$$props.caution?"note-important sls-info-note sls-info-note-caution":$$props.notice?"note sls-info-note sls-info-note-notice":isInfo()?"note sls-info-note":"sls-info-note"),signalWordKind=user_derived(()=>$$props.error?"danger":$$props.warning?"warning":$$props.caution?"caution":$$props.notice?"notice":void 0),defaultSignalWord=user_derived(()=>{switch(get2(signalWordKind)){case"danger":return"Ui.Common.Signal.Danger";case"warning":return"Ui.Common.Signal.Warning";case"caution":return"Ui.Common.Signal.Caution";case"notice":return"Ui.Common.Signal.Notice";default:return""}}),signalWordText=user_derived(()=>!1===$$props.signalWord?"":$$props.signalWord?translateIfAvailable($$props.signalWord):get2(defaultSignalWord)?translateIfAvailable(get2(defaultSignalWord)):""),signalWordCssKind=user_derived(()=>null!==get2(signalWordKind)&&void 0!==get2(signalWordKind)?get2(signalWordKind):"custom"),translatedTitle=user_derived(()=>$$props.title?translateIfAvailable($$props.title):""),translatedMessage=user_derived(()=>$$props.message?translateIfAvailable($$props.message):"");fragment=comment();node=first_child(fragment);consequent_3=$$anchor2=>{var node_2,consequent_1,node_3,consequent_2,node_4,div=root_34(),node_1=child(div),consequent=$$anchor3=>{var div_1=root9(),text2=child(div_1,!0);reset(div_1);template_effect(()=>{var _a13;set_class(div_1,1,`sls-signal-word sls-signal-word-${null!=(_a13=get2(signalWordCssKind))?_a13:""}`);set_text(text2,get2(signalWordText))});append($$anchor3,div_1)};if_block(node_1,$$render=>{get2(signalWordText)&&$$render(consequent)});node_2=sibling(node_1,2);consequent_1=$$anchor3=>{var h3=root_18(),text_1=child(h3,!0);reset(h3);template_effect(()=>set_text(text_1,get2(translatedTitle)));append($$anchor3,h3)};if_block(node_2,$$render=>{get2(translatedTitle)&&$$render(consequent_1)});node_3=sibling(node_2,2);consequent_2=$$anchor3=>{var p2=root_24(),text_2=child(p2,!0);reset(p2);template_effect(()=>set_text(text_2,get2(translatedMessage)));append($$anchor3,p2)};if_block(node_3,$$render=>{get2(translatedMessage)&&$$render(consequent_2)});node_4=sibling(node_3,2);snippet(node_4,()=>{var _a13;return null!=(_a13=$$props.children)?_a13:noop2});reset(div);template_effect(()=>{var _a13;return set_class(div,1,(null!=(_a13=$$props.cssClass)?_a13:"")+" "+get2(derivedCssClass))});append($$anchor2,div)};if_block(node,$$render=>{void 0!==$$props.visible&&!0!==$$props.visible||$$render(consequent_3)});append($$anchor,fragment);pop()}function Decision($$anchor,$$props){var button,text2;push($$props,!0);const translatedTitle=user_derived(()=>translateIfAvailable($$props.title));button=root10();text2=child(button,!0);reset(button);template_effect(()=>{var _a13;set_class(button,1,`button ${null!=(_a13=$$props.additionalClasses)?_a13:""} ${$$props.important?"mod-cta":""} ${$$props.destructive?"mod-destructive":""}`);button.disabled=$$props.disabled;set_text(text2,get2(translatedTitle))});delegated("click",button,function onclick(){fireAndForget(async()=>$$props.commit())});append($$anchor,button);pop()}function Question($$anchor,$$props){var div,node,consequent,div_1,node_2;push($$props,!0);append_styles($$anchor,$$css7);const questionGroupID=Math.random().toString(36).substring(2,15);setContext("radioGroup",questionGroupID);div=root_19();node=child(div);consequent=$$anchor2=>{var h3=root11(),node_1=child(h3);snippet(node_1,()=>{var _a13;return null!=(_a13=$$props.question)?_a13:noop2});reset(h3);append($$anchor2,h3)};if_block(node,$$render=>{$$props.question&&$$render(consequent)});div_1=sibling(node,2);node_2=child(div_1);snippet(node_2,()=>{var _a13;return null!=(_a13=$$props.children)?_a13:noop2});reset(div_1);reset(div);append($$anchor,div);pop()}function Option($$anchor,$$props){var div,label2,div_1,input,input_value,span,text2,div_2,node,consequent,consequent_1,node_3;push($$props,!0);append_styles($$anchor,$$css8);const definedGroupContext=getContext("radioGroup");let value=prop($$props,"value",15);const actualGroup=user_derived(()=>null!==$$props.group&&void 0!==$$props.group?$$props.group:definedGroupContext),translatedTitle=user_derived(()=>translateIfAvailable($$props.title));div=root12();label2=child(div);div_1=child(label2);input=child(div_1);remove_input_defaults(input);span=sibling(input,2);text2=child(span,!0);reset(span);reset(div_1);div_2=sibling(div_1,2);node=child(div_2);consequent=$$anchor2=>{var fragment=comment(),node_1=first_child(fragment);snippet(node_1,()=>$$props.noteOnSelected);append($$anchor2,fragment)};consequent_1=$$anchor2=>{var fragment_1=comment(),node_2=first_child(fragment_1);snippet(node_2,()=>$$props.noteOnUnselected);append($$anchor2,fragment_1)};if_block(node,$$render=>{value()===$$props.selectedValue&&$$props.noteOnSelected?$$render(consequent):value()!==$$props.selectedValue&&$$props.noteOnUnselected&&$$render(consequent_1,1)});node_3=sibling(node,2);snippet(node_3,()=>{var _a13;return null!=(_a13=$$props.children)?_a13:noop2});reset(div_2);reset(label2);reset(div);template_effect(()=>{var _a13;set_class(div,1,"option-container "+(value()===$$props.selectedValue?"selected":""),"svelte-1t4v6fm");set_attribute2(input,"name",get2(actualGroup));input_value!==(input_value=$$props.selectedValue)&&(input.value=null!=(_a13=input.__value=$$props.selectedValue)?_a13:"");set_text(text2,get2(translatedTitle))});bind_group([],[],input,()=>{$$props.selectedValue;return value()},value);append($$anchor,div);pop()}function Options($$anchor,$$props){var div,node;push($$props,!0);const questionGroupID=Math.random().toString(36).substring(2,15);setContext("radioGroup",questionGroupID);div=root13();node=child(div);snippet(node,()=>{var _a13;return null!=(_a13=$$props.children)?_a13:noop2});reset(div);append($$anchor,div);pop()}function Instruction($$anchor,$$props){"use strict";var div=root14(),node=child(div);snippet(node,()=>{var _a13;return null!=(_a13=$$props.children)?_a13:noop2});reset(div);append($$anchor,div)}function UserDecisions($$anchor,$$props){var div=root15(),node=child(div),consequent=$$anchor2=>{var fragment=comment(),node_1=first_child(fragment);snippet(node_1,()=>$$props.children);append($$anchor2,fragment)};if_block(node,$$render=>{$$props.children&&$$render(consequent)});reset(div);append($$anchor,div)}function Intro($$anchor,$$props){var fragment,node,node_1,node_2,node_3,node_8;push($$props,!0);let userType=state(proxy(TYPE_CANCELLED)),proceedTitle=user_derived(()=>get2(userType)===TYPE_NEW_USER?$msg("Yes, I want to set up a new synchronisation"):get2(userType)===TYPE_EXISTING_USER?$msg("Yes, I want to add this device to my existing synchronisation"):$msg("Please select an option to proceed"));const canProceed=user_derived(()=>get2(userType)===TYPE_NEW_USER||get2(userType)===TYPE_EXISTING_USER);fragment=root_110();node=first_child(fragment);{let $0=user_derived(()=>$msg("Welcome to Self-hosted LiveSync"));DialogHeader(node,{get title(){return get2($0)}})}node_1=sibling(node,2);Guidance(node_1,{children:($$anchor2,$$slotProps)=>{next();var text2=text();template_effect($0=>set_text(text2,$0),[()=>$msg("We will now guide you through a few questions to simplify the synchronisation setup.")]);append($$anchor2,text2)},$$slots:{default:!0}});node_2=sibling(node_1,2);InfoNote(node_2,{children:($$anchor2,$$slotProps)=>{next();var text_1=text();template_effect($0=>set_text(text_1,$0),[()=>$msg("This first setup has several short steps because it confirms encryption, the connection method, and which device provides the initial data. Once it is complete, additional devices can reuse a Setup URI.")]);append($$anchor2,text_1)},$$slots:{default:!0}});node_3=sibling(node_2,2);Instruction(node_3,{children:($$anchor2,$$slotProps)=>{var node_5,fragment_3=root16(),node_4=first_child(fragment_3);Question(node_4,{children:($$anchor3,$$slotProps2)=>{next();var text_2=text();template_effect($0=>set_text(text_2,$0),[()=>$msg("First, please select the option that best describes your current situation.")]);append($$anchor3,text_2)},$$slots:{default:!0}});node_5=sibling(node_4,2);Options(node_5,{children:($$anchor3,$$slotProps2)=>{var node_7,fragment_5=root16(),node_6=first_child(fragment_5);let $0=user_derived(()=>$msg("I am setting this up for the first time"));Option(node_6,{get selectedValue(){return TYPE_NEW_USER},get title(){return get2($0)},get value(){return get2(userType)},set value($$value){set(userType,$$value,!0)},children:($$anchor4,$$slotProps3)=>{next();var text_3=text();template_effect($02=>set_text(text_3,$02),[()=>$msg("(Select this if you are configuring this device as the first synchronisation device.) This option is suitable if you are new to LiveSync and want to set it up from scratch.")]);append($$anchor4,text_3)},$$slots:{default:!0}});node_7=sibling(node_6,2);{let $0=user_derived(()=>$msg("I am adding a device to an existing synchronisation setup"));Option(node_7,{get selectedValue(){return TYPE_EXISTING_USER},get title(){return get2($0)},get value(){return get2(userType)},set value($$value){set(userType,$$value,!0)},children:($$anchor4,$$slotProps3)=>{next();var text_4=text();template_effect($02=>set_text(text_4,$02),[()=>$msg("(Select this if you are already using synchronisation on another computer or smartphone.) This option is suitable if you are new to LiveSync and want to set it up from scratch.")]);append($$anchor4,text_4)},$$slots:{default:!0}})}append($$anchor3,fragment_5)},$$slots:{default:!0}});append($$anchor2,fragment_3)},$$slots:{default:!0}});node_8=sibling(node_3,2);UserDecisions(node_8,{children:($$anchor2,$$slotProps)=>{var node_10,fragment_8=root16(),node_9=first_child(fragment_8);let $0=user_derived(()=>!get2(canProceed));Decision(node_9,{get title(){return get2(proceedTitle)},get important(){return get2(canProceed)},get disabled(){return get2($0)},commit:()=>$$props.setResult(get2(userType))});node_10=sibling(node_9,2);{let $0=user_derived(()=>$msg("No, please take me back"));Decision(node_10,{get title(){return get2($0)},commit:()=>$$props.setResult(TYPE_CANCELLED)})}append($$anchor2,fragment_8)},$$slots:{default:!0}});append($$anchor,fragment);pop()}function SelectMethodNewUser($$anchor,$$props){var fragment,node,node_1,node_2,node_7;push($$props,!0);let userType=state(proxy(TYPE_CANCELLED)),proceedTitle=user_derived(()=>get2(userType)===TYPE_USE_SETUP_URI?$msg("Proceed with Setup URI"):get2(userType)===TYPE_CONFIGURE_MANUALLY?$msg("Ui.SetupWizard.SelectNew.ProceedManual"):$msg("Please select an option to proceed"));const canProceed=user_derived(()=>get2(userType)===TYPE_USE_SETUP_URI||get2(userType)===TYPE_CONFIGURE_MANUALLY);fragment=root_111();node=first_child(fragment);{let $0=user_derived(()=>$msg("Connection Method"));DialogHeader(node,{get title(){return get2($0)}})}node_1=sibling(node,2);Guidance(node_1,{children:($$anchor2,$$slotProps)=>{next();var text2=text();template_effect($0=>set_text(text2,$0),[()=>$msg("Ui.SetupWizard.SelectNew.Guidance")]);append($$anchor2,text2)},$$slots:{default:!0}});node_2=sibling(node_1,2);Instruction(node_2,{children:($$anchor2,$$slotProps)=>{var node_4,fragment_2=root17(),node_3=first_child(fragment_2);Question(node_3,{children:($$anchor3,$$slotProps2)=>{next();var text_1=text();template_effect($0=>set_text(text_1,$0),[()=>$msg("Ui.SetupWizard.SelectNew.Question")]);append($$anchor3,text_1)},$$slots:{default:!0}});node_4=sibling(node_3,2);Options(node_4,{children:($$anchor3,$$slotProps2)=>{var node_6,fragment_4=root17(),node_5=first_child(fragment_4);let $0=user_derived(()=>$msg("Use a Setup URI (Recommended)"));Option(node_5,{get selectedValue(){return TYPE_USE_SETUP_URI},get title(){return get2($0)},get value(){return get2(userType)},set value($$value){set(userType,$$value,!0)},children:($$anchor4,$$slotProps3)=>{next();var text_2=text();template_effect($02=>set_text(text_2,$02),[()=>$msg("Ui.SetupWizard.SelectNew.SetupUriOptionDesc")]);append($$anchor4,text_2)},$$slots:{default:!0}});node_6=sibling(node_5,2);{let $0=user_derived(()=>$msg("Ui.SetupWizard.SelectNew.ManualOption"));Option(node_6,{get selectedValue(){return TYPE_CONFIGURE_MANUALLY},get title(){return get2($0)},get value(){return get2(userType)},set value($$value){set(userType,$$value,!0)},children:($$anchor4,$$slotProps3)=>{next();var text_3=text();template_effect(($02,$1)=>set_text(text_3,`${null!=$02?$02:""}\n ${null!=$1?$1:""}`),[()=>$msg("Ui.SetupWizard.SelectNew.ManualOptionDesc"),()=>$msg("P2P requires no central data-storage server, but it still uses a signalling relay for peer discovery.")]);append($$anchor4,text_3)},$$slots:{default:!0}})}append($$anchor3,fragment_4)},$$slots:{default:!0}});append($$anchor2,fragment_2)},$$slots:{default:!0}});node_7=sibling(node_2,2);UserDecisions(node_7,{children:($$anchor2,$$slotProps)=>{var node_9,fragment_7=root17(),node_8=first_child(fragment_7);let $0=user_derived(()=>!get2(canProceed));Decision(node_8,{get title(){return get2(proceedTitle)},get important(){return get2(canProceed)},get disabled(){return get2($0)},commit:()=>$$props.setResult(get2(userType))});node_9=sibling(node_8,2);{let $0=user_derived(()=>$msg("Cancel"));Decision(node_9,{get title(){return get2($0)},commit:()=>$$props.setResult(TYPE_CANCELLED)})}append($$anchor2,fragment_7)},$$slots:{default:!0}});append($$anchor,fragment);pop()}function SelectMethodExisting($$anchor,$$props){var fragment,node,node_1,node_2,node_8;push($$props,!0);let userType=state(proxy(TYPE_CANCELLED)),proceedTitle=user_derived(()=>get2(userType)===TYPE_USE_SETUP_URI?$msg("Proceed with Setup URI"):get2(userType)===TYPE_CONFIGURE_MANUALLY?$msg("Ui.SetupWizard.SelectExisting.ProceedManual"):get2(userType)===TYPE_SCAN_QR_CODE?$msg("Scan the QR code displayed on an active device using this device's camera."):$msg("Please select an option to proceed"));const canProceed=user_derived(()=>get2(userType)===TYPE_USE_SETUP_URI||get2(userType)===TYPE_CONFIGURE_MANUALLY||get2(userType)===TYPE_SCAN_QR_CODE);fragment=root_25();node=first_child(fragment);{let $0=user_derived(()=>$msg("Device Setup Method"));DialogHeader(node,{get title(){return get2($0)}})}node_1=sibling(node,2);Guidance(node_1,{children:($$anchor2,$$slotProps)=>{next();var text2=text();template_effect($0=>set_text(text2,$0),[()=>$msg("You are adding this device to an existing synchronisation setup.")]);append($$anchor2,text2)},$$slots:{default:!0}});node_2=sibling(node_1,2);Instruction(node_2,{children:($$anchor2,$$slotProps)=>{var node_4,fragment_2=root_112(),node_3=first_child(fragment_2);Question(node_3,{children:($$anchor3,$$slotProps2)=>{next();var text_1=text();template_effect($0=>set_text(text_1,$0),[()=>$msg("Please select a method to import the settings from another device.")]);append($$anchor3,text_1)},$$slots:{default:!0}});node_4=sibling(node_3,2);Options(node_4,{children:($$anchor3,$$slotProps2)=>{var node_6,node_7,fragment_4=root18(),node_5=first_child(fragment_4);let $0=user_derived(()=>$msg("Use a Setup URI (Recommended)"));Option(node_5,{get selectedValue(){return TYPE_USE_SETUP_URI},get title(){return get2($0)},get value(){return get2(userType)},set value($$value){set(userType,$$value,!0)},children:($$anchor4,$$slotProps3)=>{next();var text_2=text();template_effect($02=>set_text(text_2,$02),[()=>$msg("Paste the Setup URI generated from one of your active devices.")]);append($$anchor4,text_2)},$$slots:{default:!0}});node_6=sibling(node_5,2);{let $0=user_derived(()=>$msg("Scan a QR Code (Recommended for mobile)"));Option(node_6,{get selectedValue(){return TYPE_SCAN_QR_CODE},get title(){return get2($0)},get value(){return get2(userType)},set value($$value){set(userType,$$value,!0)},children:($$anchor4,$$slotProps3)=>{next();var text_3=text();template_effect($02=>set_text(text_3,$02),[()=>$msg("Scan the QR code displayed on an active device using this device's camera.")]);append($$anchor4,text_3)},$$slots:{default:!0}})}node_7=sibling(node_6,2);{let $0=user_derived(()=>$msg("Ui.SetupWizard.SelectExisting.ManualOption"));Option(node_7,{get selectedValue(){return TYPE_CONFIGURE_MANUALLY},get title(){return get2($0)},get value(){return get2(userType)},set value($$value){set(userType,$$value,!0)},children:($$anchor4,$$slotProps3)=>{next();var text_4=text();template_effect($02=>set_text(text_4,$02),[()=>$msg("Ui.SetupWizard.SelectExisting.ManualOptionDesc")]);append($$anchor4,text_4)},$$slots:{default:!0}})}append($$anchor3,fragment_4)},$$slots:{default:!0}});append($$anchor2,fragment_2)},$$slots:{default:!0}});node_8=sibling(node_2,2);UserDecisions(node_8,{children:($$anchor2,$$slotProps)=>{var node_10,fragment_8=root_112(),node_9=first_child(fragment_8);let $0=user_derived(()=>!get2(canProceed));Decision(node_9,{get title(){return get2(proceedTitle)},get important(){return get2(canProceed)},get disabled(){return get2($0)},commit:()=>$$props.setResult(get2(userType))});node_10=sibling(node_9,2);{let $0=user_derived(()=>$msg("Cancel"));Decision(node_10,{get title(){return get2($0)},commit:()=>$$props.setResult(TYPE_CANCELLED)})}append($$anchor2,fragment_8)},$$slots:{default:!0}});append($$anchor,fragment);pop()}function ScanQRCode($$anchor,$$props){var fragment,node,node_1,node_2,node_3;push($$props,!0);fragment=root_113();node=first_child(fragment);{let $0=user_derived(()=>$msg("Scan QR Code"));DialogHeader(node,{get title(){return get2($0)}})}node_1=sibling(node,2);Guidance(node_1,{children:($$anchor2,$$slotProps)=>{next();var text2=text();template_effect($0=>set_text(text2,$0),[()=>$msg("Please follow the steps below to import settings from your existing device.")]);append($$anchor2,text2)},$$slots:{default:!0}});node_2=sibling(node_1,2);Instruction(node_2,{children:($$anchor2,$$slotProps)=>{var li_1,text_2,li_2,text_3,li_3,text_4,ol=root19(),li=child(ol),text_1=child(li,!0);reset(li);li_1=sibling(li,2);text_2=child(li_1,!0);reset(li_1);li_2=sibling(li_1,2);text_3=child(li_2,!0);reset(li_2);li_3=sibling(li_2,2);text_4=child(li_3,!0);reset(li_3);reset(ol);template_effect(($0,$1,$2,$3)=>{set_text(text_1,$0);set_text(text_2,$1);set_text(text_3,$2);set_text(text_4,$3)},[()=>$msg("On this device, please keep this Vault open."),()=>$msg("On the source device, open Obsidian."),()=>$msg("On the source device, from the command palette, run the 'Show settings as a QR code' command."),()=>$msg("On this device, switch to the camera app or use a QR code scanner to scan the displayed QR code.")]);append($$anchor2,ol)},$$slots:{default:!0}});node_3=sibling(node_2,2);UserDecisions(node_3,{children:($$anchor2,$$slotProps)=>{{let $0=user_derived(()=>$msg("Close this dialog"));Decision($$anchor2,{get title(){return get2($0)},important:!0,commit:()=>$$props.setResult(TYPE_CLOSE)})}},$$slots:{default:!0}});append($$anchor,fragment);pop()}function InputRow($$anchor,$$props){var label_1,span,text2,node;push($$props,!0);const translatedLabel=user_derived(()=>translateIfAvailable($$props.label));label_1=root20();span=child(label_1);text2=child(span,!0);reset(span);node=sibling(span,2);snippet(node,()=>{var _a13;return null!=(_a13=$$props.children)?_a13:noop2});reset(label_1);template_effect(()=>set_text(text2,get2(translatedLabel)));append($$anchor,label_1);pop()}function Password($$anchor,$$props){var fragment,input,input_1;push($$props,!0);let value=prop($$props,"value",15),name=prop($$props,"name",3,"password"),placeholder=prop($$props,"placeholder",3,"Enter your password"),disabled=prop($$props,"disabled",3,!1),required=prop($$props,"required",3,!1),showPassword=state(!1);const type=user_derived(()=>get2(showPassword)?"text":"password"),translatedPlaceholder=user_derived(()=>translateIfAvailable(placeholder()));fragment=root21();input=first_child(fragment);remove_input_defaults(input);input_1=sibling(input,2);remove_input_defaults(input_1);template_effect(()=>{set_attribute2(input,"type",get2(type));set_attribute2(input,"name",name());set_attribute2(input,"placeholder",get2(translatedPlaceholder));input.disabled=disabled();input.required=required()});bind_value(input,value);bind_checked(input_1,()=>get2(showPassword),$$value=>set(showPassword,$$value));append($$anchor,fragment);pop()}async function encryptString(source2,passphrase){return source2.startsWith(ENCRYPT_V2_PREFIX)||source2.startsWith(HKDF_SALTED_ENCRYPTED_PREFIX)?source2:await encryptWithEphemeralSalt(source2,passphrase)}async function tryDecryption(trials){for(const trial of trials)try{return await trial()}catch(error){Logger("Decryption trial failed!",LOG_LEVEL_VERBOSE);Logger(error,LOG_LEVEL_VERBOSE)}throw new Error("All decryption trials failed")}async function decryptString(encrypted,passphrase){if(encrypted.startsWith(HKDF_SALTED_ENCRYPTED_PREFIX))return decryptWithEphemeralSalt(encrypted,passphrase);if(encrypted.startsWith(ENCRYPT_V2_PREFIX)||encrypted.startsWith(ENCRYPT_V3_PREFIX)||encrypted.startsWith(ENCRYPT_V1_PREFIX_PROBABLY))return await tryDecryption([async()=>await decrypt3(encrypted,passphrase,!1),async()=>await decrypt3(encrypted,passphrase,!0)]);throw new Error("Unsupported encryption format")}function UseSetupURI($$anchor,$$props){async function processSetupURI(){set(error,"");if(get2(seemsValid))if(get2(passphrase))try{const settingPieces=get2(setupURI).substring(configURIBase.length),encodedConfig=decodeURIComponent(settingPieces),newConf=await JSON.parse(await decryptString(encodedConfig,get2(passphrase)));$$props.setResult(newConf);return}catch(e3){set(error,$msg("Failed to parse Setup-URI."),!0);return}else set(error,$msg("Passphrase is required."),!0)}async function canProceed(){var _a13;return null!==(_a13=await processSetupURI())&&void 0!==_a13&&_a13}var fragment,node,node_1,node_2,node_3,node_4,node_5,node_6,node_7;push($$props,!0);let setupURI=state(""),passphrase=state(""),error=state("");onMount(()=>{if($$props.getInitialData){const initialURI=$$props.getInitialData();initialURI&&set(setupURI,initialURI,!0)}});const seemsValid=user_derived(()=>get2(setupURI).startsWith(configURIBase));fragment=root_35();node=first_child(fragment);{let $0=user_derived(()=>$msg("Enter Setup URI"));DialogHeader(node,{get title(){return get2($0)}})}node_1=sibling(node,2);Guidance(node_1,{children:($$anchor2,$$slotProps)=>{var fragment_1,text2,text_1;next();fragment_1=root22();text2=first_child(fragment_1,!0);text_1=sibling(text2,2);template_effect(($0,$1)=>{set_text(text2,$0);set_text(text_1,` ${null!=$1?$1:""}`)},[()=>$msg("Please enter the Setup URI that was generated during server installation or on another device, along with the vault passphrase."),()=>$msg('Note that you can generate a new Setup URI by running the "Copy settings as a new Setup URI" command in the command palette.')]);append($$anchor2,fragment_1)},$$slots:{default:!0}});node_2=sibling(node_1,2);{let $0=user_derived(()=>$msg("Setup-URI"));InputRow(node_2,{get label(){return get2($0)},children:($$anchor2,$$slotProps)=>{var input=root_114();remove_input_defaults(input);bind_value(input,()=>get2(setupURI),$$value=>set(setupURI,$$value));append($$anchor2,input)},$$slots:{default:!0}})}node_3=sibling(node_2,2);InfoNote(node_3,{get visible(){return get2(seemsValid)},children:($$anchor2,$$slotProps)=>{next();var text_2=text();template_effect($0=>set_text(text_2,$0),[()=>$msg("The Setup-URI is valid and ready to use.")]);append($$anchor2,text_2)},$$slots:{default:!0}});node_4=sibling(node_3,2);{let $0=user_derived(()=>!get2(seemsValid)&&""!=get2(setupURI).trim());InfoNote(node_4,{warning:!0,get visible(){return get2($0)},children:($$anchor2,$$slotProps)=>{next();var text_3=text();template_effect($02=>set_text(text_3,$02),[()=>$msg("The Setup-URI does not appear to be valid. Please check that you have copied it correctly.")]);append($$anchor2,text_3)},$$slots:{default:!0}})}node_5=sibling(node_4,2);{let $0=user_derived(()=>$msg("Passphrase"));InputRow(node_5,{get label(){return get2($0)},children:($$anchor2,$$slotProps)=>{{let $02=user_derived(()=>$msg("Enter your passphrase"));Password($$anchor2,{get placeholder(){return get2($02)},required:!0,get value(){return get2(passphrase)},set value($$value){set(passphrase,$$value,!0)}})}},$$slots:{default:!0}})}node_6=sibling(node_5,2);{let $0=user_derived(()=>""!=get2(error).trim());InfoNote(node_6,{error:!0,get visible(){return get2($0)},children:($$anchor2,$$slotProps)=>{next();var text_4=text();template_effect(()=>set_text(text_4,get2(error)));append($$anchor2,text_4)},$$slots:{default:!0}})}node_7=sibling(node_6,2);UserDecisions(node_7,{children:($$anchor2,$$slotProps)=>{var node_9,fragment_6=root_26(),node_8=first_child(fragment_6);let $0=user_derived(()=>$msg("Test Settings and Continue"));Decision(node_8,{get title(){return get2($0)},important:!0,disabled:!canProceed,commit:()=>processSetupURI()});node_9=sibling(node_8,2);{let $0=user_derived(()=>$msg("Cancel"));Decision(node_9,{get title(){return get2($0)},commit:()=>$$props.setResult(TYPE_CANCELLED)})}append($$anchor2,fragment_6)},$$slots:{default:!0}});append($$anchor,fragment);pop()}function OutroNewUser($$anchor,$$props){var _a13,fragment,node,consequent,alternate;push($$props,!0);const isP2P=user_derived(()=>!0===(null===(_a13=null===$$props.getInitialData||void 0===$$props.getInitialData?void 0:$$props.getInitialData())||void 0===_a13?void 0:_a13.isP2P));fragment=comment();node=first_child(fragment);consequent=$$anchor2=>{var node_2,node_3,node_4,fragment_1=root_27(),node_1=first_child(fragment_1);let $0=user_derived(()=>$msg("Ui.SetupWizard.OutroNewP2PUser.Title"));DialogHeader(node_1,{get title(){return get2($0)}});node_2=sibling(node_1,2);Guidance(node_2,{children:($$anchor3,$$slotProps)=>{var p_1,strong,text_1,text_2,fragment_2=root23(),p2=first_child(fragment_2),text2=child(p2,!0);reset(p2);p_1=sibling(p2,2);strong=child(p_1);text_1=child(strong,!0);reset(strong);text_2=sibling(strong,3);reset(p_1);template_effect(($0,$1,$2)=>{set_text(text2,$0);set_text(text_1,$1);set_text(text_2,` ${null!=$2?$2:""}`)},[()=>$msg("Ui.SetupWizard.OutroNewP2PUser.GuidancePrimary"),()=>$msg("Ui.SetupWizard.OutroNewP2PUser.Important"),()=>$msg("Ui.SetupWizard.OutroNewP2PUser.GuidanceNotice")]);append($$anchor3,fragment_2)},$$slots:{default:!0}});node_3=sibling(node_2,2);Instruction(node_3,{children:($$anchor3,$$slotProps)=>{Question($$anchor3,{children:($$anchor4,$$slotProps2)=>{next();var text_3=text();template_effect($0=>set_text(text_3,$0),[()=>$msg("Ui.SetupWizard.OutroNewP2PUser.Question")]);append($$anchor4,text_3)},$$slots:{default:!0}})},$$slots:{default:!0}});node_4=sibling(node_3,2);UserDecisions(node_4,{children:($$anchor3,$$slotProps)=>{var node_6,fragment_5=root_115(),node_5=first_child(fragment_5);let $0=user_derived(()=>$msg("Ui.SetupWizard.OutroNewP2PUser.Proceed"));Decision(node_5,{get title(){return get2($0)},important:!0,commit:()=>$$props.setResult(TYPE_APPLY)});node_6=sibling(node_5,2);{let $0=user_derived(()=>$msg("No, please take me back"));Decision(node_6,{get title(){return get2($0)},commit:()=>$$props.setResult(TYPE_CANCELLED)})}append($$anchor3,fragment_5)},$$slots:{default:!0}});append($$anchor2,fragment_1)};alternate=$$anchor2=>{var node_8,node_9,node_10,fragment_6=root_27(),node_7=first_child(fragment_6);let $0=user_derived(()=>$msg("Setup Complete: Preparing to Initialise Server"));DialogHeader(node_7,{get title(){return get2($0)}});node_8=sibling(node_7,2);Guidance(node_8,{children:($$anchor3,$$slotProps)=>{var p_3,strong_2,text_6,text_7,fragment_7=root_36(),p_2=first_child(fragment_7),text_4=child(p_2),strong_1=sibling(text_4),text_5=child(strong_1,!0);reset(strong_1);reset(p_2);p_3=sibling(p_2,2);strong_2=child(p_3);text_6=child(strong_2,!0);reset(strong_2);text_7=sibling(strong_2,3);reset(p_3);template_effect(($0,$1,$2,$3)=>{set_text(text_4,`${null!=$0?$0:""} `);set_text(text_5,$1);set_text(text_6,$2);set_text(text_7,` ${null!=$3?$3:""}`)},[()=>$msg("The connection to the server has been configured successfully. As the next step,"),()=>$msg("the synchronisation data on the server will be built based on the current data on this device."),()=>$msg("IMPORTANT"),()=>$msg("After restarting, the data on this device will be uploaded to the server as the 'master copy'. Please be aware that any unintended data currently on the server will be completely overwritten.")]);append($$anchor3,fragment_7)},$$slots:{default:!0}});node_9=sibling(node_8,2);Instruction(node_9,{children:($$anchor3,$$slotProps)=>{Question($$anchor3,{children:($$anchor4,$$slotProps2)=>{next();var text_8=text();template_effect($0=>set_text(text_8,$0),[()=>$msg("Please select the button below to restart and proceed to the final confirmation.")]);append($$anchor4,text_8)},$$slots:{default:!0}})},$$slots:{default:!0}});node_10=sibling(node_9,2);UserDecisions(node_10,{children:($$anchor3,$$slotProps)=>{var node_12,fragment_10=root_115(),node_11=first_child(fragment_10);let $0=user_derived(()=>$msg("Restart and Initialise Server"));Decision(node_11,{get title(){return get2($0)},important:!0,commit:()=>$$props.setResult(TYPE_APPLY)});node_12=sibling(node_11,2);{let $0=user_derived(()=>$msg("No, please take me back"));Decision(node_12,{get title(){return get2($0)},commit:()=>$$props.setResult(TYPE_CANCELLED)})}append($$anchor3,fragment_10)},$$slots:{default:!0}});append($$anchor2,fragment_6)};if_block(node,$$render=>{get2(isP2P)?$$render(consequent):$$render(alternate,-1)});append($$anchor,fragment);pop()}function OutroExistingUser($$anchor,$$props){var _a13,fragment,node,consequent,alternate;push($$props,!0);const isP2P=user_derived(()=>!0===(null===(_a13=null===$$props.getInitialData||void 0===$$props.getInitialData?void 0:$$props.getInitialData())||void 0===_a13?void 0:_a13.isP2P));fragment=comment();node=first_child(fragment);consequent=$$anchor2=>{var node_2,node_3,node_4,fragment_1=root_28(),node_1=first_child(fragment_1);let $0=user_derived(()=>$msg("Setup Complete: Preparing to Fetch from Another Device"));DialogHeader(node_1,{get title(){return get2($0)}});node_2=sibling(node_1,2);Guidance(node_2,{children:($$anchor3,$$slotProps)=>{var p_1,strong,text_1,text_2,fragment_2=root24(),p2=first_child(fragment_2),text2=child(p2,!0);reset(p2);p_1=sibling(p2,2);strong=child(p_1);text_1=child(strong,!0);reset(strong);text_2=sibling(strong,3);reset(p_1);template_effect(($0,$1,$2)=>{set_text(text2,$0);set_text(text_1,$1);set_text(text_2,` ${null!=$2?$2:""}`)},[()=>$msg("The P2P connection has been configured successfully. The initial synchronisation data must now be fetched from an online source device."),()=>$msg("PLEASE NOTE"),()=>$msg("After restarting, select an online source device for the initial Fetch. The local LiveSync database on this device will be rebuilt from that source. Unsynchronised files in this Vault may conflict with the fetched data.")]);append($$anchor3,fragment_2)},$$slots:{default:!0}});node_3=sibling(node_2,2);Instruction(node_3,{children:($$anchor3,$$slotProps)=>{Question($$anchor3,{children:($$anchor4,$$slotProps2)=>{next();var text_3=text();template_effect($0=>set_text(text_3,$0),[()=>$msg("Restart this device, then choose the source device when P2P Rebuild opens.")]);append($$anchor4,text_3)},$$slots:{default:!0}})},$$slots:{default:!0}});node_4=sibling(node_3,2);UserDecisions(node_4,{children:($$anchor3,$$slotProps)=>{var node_6,fragment_5=root_116(),node_5=first_child(fragment_5);let $0=user_derived(()=>$msg("Restart and Select Source Device"));Decision(node_5,{get title(){return get2($0)},important:!0,commit:()=>$$props.setResult(TYPE_APPLY)});node_6=sibling(node_5,2);{let $0=user_derived(()=>$msg("No, please take me back"));Decision(node_6,{get title(){return get2($0)},commit:()=>$$props.setResult(TYPE_CANCELLED)})}append($$anchor3,fragment_5)},$$slots:{default:!0}});append($$anchor2,fragment_1)};alternate=$$anchor2=>{var node_8,node_9,node_10,fragment_6=root_28(),node_7=first_child(fragment_6);let $0=user_derived(()=>$msg("Setup Complete: Preparing to Fetch Synchronisation Data"));DialogHeader(node_7,{get title(){return get2($0)}});node_8=sibling(node_7,2);Guidance(node_8,{children:($$anchor3,$$slotProps)=>{var p_3,strong_2,text_6,text_7,fragment_7=root_37(),p_2=first_child(fragment_7),text_4=child(p_2),strong_1=sibling(text_4),text_5=child(strong_1,!0);reset(strong_1);reset(p_2);p_3=sibling(p_2,2);strong_2=child(p_3);text_6=child(strong_2,!0);reset(strong_2);text_7=sibling(strong_2,3);reset(p_3);template_effect(($0,$1,$2,$3)=>{set_text(text_4,`${null!=$0?$0:""} `);set_text(text_5,$1);set_text(text_6,$2);set_text(text_7,` ${null!=$3?$3:""}`)},[()=>$msg("The connection to the server has been configured successfully. As the next step,"),()=>$msg("the latest synchronisation data will be downloaded from the server to this device."),()=>$msg("PLEASE NOTE"),()=>$msg("After restarting, the database on this device will be rebuilt using data from the server. If there are any unsynchronised files in this vault, conflicts may occur with the server data.")]);append($$anchor3,fragment_7)},$$slots:{default:!0}});node_9=sibling(node_8,2);Instruction(node_9,{children:($$anchor3,$$slotProps)=>{Question($$anchor3,{children:($$anchor4,$$slotProps2)=>{next();var text_8=text();template_effect($0=>set_text(text_8,$0),[()=>$msg("Please select the button below to restart and proceed to the data fetching confirmation.")]);append($$anchor4,text_8)},$$slots:{default:!0}})},$$slots:{default:!0}});node_10=sibling(node_9,2);UserDecisions(node_10,{children:($$anchor3,$$slotProps)=>{var node_12,fragment_10=root_116(),node_11=first_child(fragment_10);let $0=user_derived(()=>$msg("Restart and Fetch Data"));Decision(node_11,{get title(){return get2($0)},important:!0,commit:()=>$$props.setResult(TYPE_APPLY)});node_12=sibling(node_11,2);{let $0=user_derived(()=>$msg("No, please take me back"));Decision(node_12,{get title(){return get2($0)},commit:()=>$$props.setResult(TYPE_CANCELLED)})}append($$anchor3,fragment_10)},$$slots:{default:!0}});append($$anchor2,fragment_6)};if_block(node,$$render=>{get2(isP2P)?$$render(consequent):$$render(alternate,-1)});append($$anchor,fragment);pop()}function OutroAskUserMode($$anchor,$$props){var fragment,node,node_1,node_2,node_7;push($$props,!0);let userType=state(proxy(TYPE_CANCELLED));const canProceed=user_derived(()=>get2(userType)===TYPE_EXISTING||get2(userType)===TYPE_NEW||get2(userType)===TYPE_COMPATIBLE_EXISTING),proceedMessage=user_derived(()=>get2(userType)===TYPE_NEW||get2(userType)===TYPE_EXISTING?$msg("Proceed to the next step."):get2(userType)===TYPE_COMPATIBLE_EXISTING?$msg("Apply the settings"):$msg("Please select an option to proceed"));fragment=root_117();node=first_child(fragment);{let $0=user_derived(()=>$msg("Mostly Complete: Decision Required"));DialogHeader(node,{get title(){return get2($0)}})}node_1=sibling(node,2);Guidance(node_1,{children:($$anchor2,$$slotProps)=>{var fragment_1,text2,strong,text_1;next();fragment_1=root25();text2=first_child(fragment_1);strong=sibling(text2);text_1=child(strong,!0);reset(strong);template_effect(($0,$1)=>{set_text(text2,`${null!=$0?$0:""} `);set_text(text_1,$1)},[()=>$msg("The connection to the server has been configured successfully. As the next step,"),()=>$msg("the local database, that is to say the synchronisation information, must be reconstituted.")]);append($$anchor2,fragment_1)},$$slots:{default:!0}});node_2=sibling(node_1,2);Instruction(node_2,{children:($$anchor2,$$slotProps)=>{var node_4,node_5,node_6,fragment_2=root_117(),node_3=first_child(fragment_2);Question(node_3,{children:($$anchor3,$$slotProps2)=>{next();var text_2=text();template_effect($0=>set_text(text_2,$0),[()=>$msg("Please select your situation.")]);append($$anchor3,text_2)},$$slots:{default:!0}});node_4=sibling(node_3,2);{let $0=user_derived(()=>$msg("I am setting up a new server for the first time / I want to reset my existing server."));Option(node_4,{get title(){return get2($0)},get selectedValue(){return TYPE_NEW},get value(){return get2(userType)},set value($$value){set(userType,$$value,!0)},children:($$anchor3,$$slotProps2)=>{InfoNote($$anchor3,{children:($$anchor4,$$slotProps3)=>{next();var text_3=text();template_effect($02=>set_text(text_3,$02),[()=>$msg("Selecting this option will result in the current data on this device being used to initialise the server. Any existing data on the server will be completely overwritten.")]);append($$anchor4,text_3)},$$slots:{default:!0}})},$$slots:{default:!0}})}node_5=sibling(node_4,2);{let $0=user_derived(()=>$msg("My remote server is already set up. I want to join this device."));Option(node_5,{get title(){return get2($0)},get selectedValue(){return TYPE_EXISTING},get value(){return get2(userType)},set value($$value){set(userType,$$value,!0)},children:($$anchor3,$$slotProps2)=>{InfoNote($$anchor3,{children:($$anchor4,$$slotProps3)=>{next();var text_4=text();template_effect($02=>set_text(text_4,$02),[()=>$msg("Selecting this option will result in this device joining the existing server. You need to fetching the existing synchronisation data from the server to this device.")]);append($$anchor4,text_4)},$$slots:{default:!0}})},$$slots:{default:!0}})}node_6=sibling(node_5,2);{let $0=user_derived(()=>$msg("The remote is already set up, and the configuration is compatible (or got compatible by this operation)."));Option(node_6,{get title(){return get2($0)},get selectedValue(){return TYPE_COMPATIBLE_EXISTING},get value(){return get2(userType)},set value($$value){set(userType,$$value,!0)},children:($$anchor3,$$slotProps2)=>{InfoNote($$anchor3,{warning:!0,children:($$anchor4,$$slotProps3)=>{next();var text_5=text();template_effect($02=>set_text(text_5,$02),[()=>$msg("Unless you are certain, selecting this options is bit dangerous. It assumes that the server configuration is compatible with this device. If this is not the case, data loss may occur. Please ensure you know what you are doing.")]);append($$anchor4,text_5)},$$slots:{default:!0}})},$$slots:{default:!0}})}append($$anchor2,fragment_2)},$$slots:{default:!0}});node_7=sibling(node_2,2);UserDecisions(node_7,{children:($$anchor2,$$slotProps)=>{var node_9,fragment_10=root_29(),node_8=first_child(fragment_10);let $0=user_derived(()=>!get2(canProceed));Decision(node_8,{get title(){return get2(proceedMessage)},important:!0,get disabled(){return get2($0)},commit:()=>$$props.setResult(get2(userType))});node_9=sibling(node_8,2);{let $0=user_derived(()=>$msg("No, please take me back"));Decision(node_9,{get title(){return get2($0)},commit:()=>$$props.setResult(TYPE_CANCELLED)})}append($$anchor2,fragment_10)},$$slots:{default:!0}});append($$anchor,fragment);pop()}function ApplySettingsInitialisation($$anchor,$$props){var _a13,fragment,node,node_1,node_2,node_6;push($$props,!0);const isP2P=user_derived(()=>!0===(null===(_a13=null===$$props.getInitialData||void 0===$$props.getInitialData?void 0:$$props.getInitialData())||void 0===_a13?void 0:_a13.isP2P));let selectedMode=state(proxy(TYPE_CANCELLED));const canProceed=user_derived(()=>get2(selectedMode)===TYPE_FETCH||get2(selectedMode)===TYPE_REBUILD),proceedMessage=user_derived(()=>get2(selectedMode)===TYPE_FETCH?get2(isP2P)?$msg("Ui.SetupWizard.ApplySettingsInitialisation.ProceedFetchP2P"):$msg("Ui.SetupWizard.ApplySettingsInitialisation.ProceedFetch"):get2(selectedMode)===TYPE_REBUILD?get2(isP2P)?$msg("Ui.SetupWizard.ApplySettingsInitialisation.ProceedRebuildP2P"):$msg("Ui.SetupWizard.ApplySettingsInitialisation.ProceedRebuild"):$msg("Ui.SetupWizard.Common.ProceedSelectOption"));fragment=root_38();node=first_child(fragment);{let $0=user_derived(()=>$msg("Ui.SetupWizard.ApplySettingsInitialisation.Title"));DialogHeader(node,{get title(){return get2($0)}})}node_1=sibling(node,2);Guidance(node_1,{children:($$anchor2,$$slotProps)=>{var p2=root26(),text2=child(p2,!0);reset(p2);template_effect($0=>set_text(text2,$0),[()=>$msg("Ui.SetupWizard.ApplySettingsInitialisation.Guidance")]);append($$anchor2,p2)},$$slots:{default:!0}});node_2=sibling(node_1,2);Instruction(node_2,{children:($$anchor2,$$slotProps)=>{var node_4,node_5,fragment_1=root_118(),node_3=first_child(fragment_1);Question(node_3,{children:($$anchor3,$$slotProps2)=>{next();var text_1=text();template_effect($0=>set_text(text_1,$0),[()=>$msg("Ui.SetupWizard.ApplySettingsInitialisation.Question")]);append($$anchor3,text_1)},$$slots:{default:!0}});node_4=sibling(node_3,2);{let $0=user_derived(()=>$msg("Ui.SetupWizard.ApplySettingsInitialisation.FetchOption"));Option(node_4,{get title(){return get2($0)},get selectedValue(){return TYPE_FETCH},get value(){return get2(selectedMode)},set value($$value){set(selectedMode,$$value,!0)},children:($$anchor3,$$slotProps2)=>{InfoNote($$anchor3,{notice:!0,children:($$anchor4,$$slotProps3)=>{next();var text_2=text();template_effect($02=>set_text(text_2,$02),[()=>get2(isP2P)?$msg("Ui.SetupWizard.ApplySettingsInitialisation.FetchOptionP2PDesc"):$msg("Ui.SetupWizard.ApplySettingsInitialisation.FetchOptionDesc")]);append($$anchor4,text_2)},$$slots:{default:!0}})},$$slots:{default:!0}})}node_5=sibling(node_4,2);{let $0=user_derived(()=>get2(isP2P)?$msg("Ui.SetupWizard.ApplySettingsInitialisation.RebuildOptionP2P"):$msg("Ui.SetupWizard.ApplySettingsInitialisation.RebuildOption"));Option(node_5,{get title(){return get2($0)},get selectedValue(){return TYPE_REBUILD},get value(){return get2(selectedMode)},set value($$value){set(selectedMode,$$value,!0)},children:($$anchor3,$$slotProps2)=>{{let $02=user_derived(()=>!get2(isP2P));InfoNote($$anchor3,{get warning(){return get2($02)},get notice(){return get2(isP2P)},children:($$anchor4,$$slotProps3)=>{next();var text_3=text();template_effect($03=>set_text(text_3,$03),[()=>get2(isP2P)?$msg("Ui.SetupWizard.ApplySettingsInitialisation.RebuildOptionP2PDesc"):$msg("Ui.SetupWizard.ApplySettingsInitialisation.RebuildOptionDesc")]);append($$anchor4,text_3)},$$slots:{default:!0}})}},$$slots:{default:!0}})}append($$anchor2,fragment_1)},$$slots:{default:!0}});node_6=sibling(node_2,2);UserDecisions(node_6,{children:($$anchor2,$$slotProps)=>{var node_8,fragment_7=root_210(),node_7=first_child(fragment_7);let $0=user_derived(()=>get2(selectedMode)!==TYPE_REBUILD||get2(isP2P)),$1=user_derived(()=>get2(selectedMode)===TYPE_REBUILD&&!get2(isP2P)),$2=user_derived(()=>!get2(canProceed));Decision(node_7,{get title(){return get2(proceedMessage)},get important(){return get2($0)},get destructive(){return get2($1)},get disabled(){return get2($2)},commit:()=>$$props.setResult(get2(selectedMode))});node_8=sibling(node_7,2);{let $0=user_derived(()=>$msg("Ui.SetupWizard.ApplySettingsInitialisation.Back"));Decision(node_8,{get title(){return get2($0)},commit:()=>$$props.setResult(TYPE_CANCELLED)})}append($$anchor2,fragment_7)},$$slots:{default:!0}});append($$anchor,fragment);pop()}function SetupRemote($$anchor,$$props){var fragment,node,node_1,node_7;push($$props,!0);let userType=state(proxy(TYPE_CANCELLED)),proceedTitle=user_derived(()=>get2(userType)===TYPE_COUCHDB?$msg("Continue to CouchDB setup"):get2(userType)===TYPE_BUCKET?$msg("Ui.SetupWizard.SetupRemote.ProceedBucket"):get2(userType)===TYPE_P2P?$msg("Ui.SetupWizard.SetupRemote.ProceedP2P"):$msg("Please select an option to proceed"));const canProceed=user_derived(()=>get2(userType)===TYPE_COUCHDB||get2(userType)===TYPE_BUCKET||get2(userType)===TYPE_P2P);fragment=root27();node=first_child(fragment);{let $0=user_derived(()=>$msg("Ui.SetupWizard.SetupRemote.Title"));DialogHeader(node,{get title(){return get2($0)}})}node_1=sibling(node,2);Instruction(node_1,{children:($$anchor2,$$slotProps)=>{var node_3,fragment_1=root_119(),node_2=first_child(fragment_1);Question(node_2,{children:($$anchor3,$$slotProps2)=>{next();var text2=text();template_effect($0=>set_text(text2,$0),[()=>$msg("Ui.SetupWizard.SetupRemote.Guidance")]);append($$anchor3,text2)},$$slots:{default:!0}});node_3=sibling(node_2,2);Options(node_3,{children:($$anchor3,$$slotProps2)=>{var node_5,node_6,fragment_3=root27(),node_4=first_child(fragment_3);Option(node_4,{get selectedValue(){return TYPE_COUCHDB},title:"CouchDB",get value(){return get2(userType)},set value($$value){set(userType,$$value,!0)},children:($$anchor4,$$slotProps3)=>{next();var text_1=text();template_effect($0=>set_text(text_1,$0),[()=>$msg("Ui.SetupWizard.SetupRemote.CouchDbOptionDesc")]);append($$anchor4,text_1)},$$slots:{default:!0}});node_5=sibling(node_4,2);{let $0=user_derived(()=>$msg("Ui.SetupWizard.SetupRemote.BucketOption"));Option(node_5,{get selectedValue(){return TYPE_BUCKET},get title(){return get2($0)},get value(){return get2(userType)},set value($$value){set(userType,$$value,!0)},children:($$anchor4,$$slotProps3)=>{next();var text_2=text();template_effect($02=>set_text(text_2,$02),[()=>$msg("Ui.SetupWizard.SetupRemote.BucketOptionDesc")]);append($$anchor4,text_2)},$$slots:{default:!0}})}node_6=sibling(node_5,2);{let $0=user_derived(()=>$msg("Ui.SetupWizard.SetupRemote.P2POption"));Option(node_6,{get selectedValue(){return TYPE_P2P},get title(){return get2($0)},get value(){return get2(userType)},set value($$value){set(userType,$$value,!0)},children:($$anchor4,$$slotProps3)=>{next();var text_3=text();template_effect($02=>set_text(text_3,$02),[()=>$msg("No central data-storage server is required, but a signalling relay is required for peer discovery. Both devices must be online at the same time. Vault data travels through the encrypted P2P connection, not through the signalling relay. Some features may be limited.")]);append($$anchor4,text_3)},$$slots:{default:!0}})}append($$anchor3,fragment_3)},$$slots:{default:!0}});append($$anchor2,fragment_1)},$$slots:{default:!0}});node_7=sibling(node_1,2);UserDecisions(node_7,{children:($$anchor2,$$slotProps)=>{var node_9,fragment_7=root_119(),node_8=first_child(fragment_7);let $0=user_derived(()=>!get2(canProceed));Decision(node_8,{get title(){return get2(proceedTitle)},get important(){return get2(canProceed)},get disabled(){return get2($0)},commit:()=>$$props.setResult(get2(userType))});node_9=sibling(node_8,2);{let $0=user_derived(()=>$msg("No, please take me back"));Decision(node_9,{get title(){return get2($0)},commit:()=>$$props.setResult(TYPE_CANCELLED)})}append($$anchor2,fragment_7)},$$slots:{default:!0}});append($$anchor,fragment);pop()}function ExtraItems($$anchor,$$props){var details,summary,text2,div,node;push($$props,!0);const translatedTitle=user_derived(()=>$$props.title?translateIfAvailable($$props.title):"");details=root28();summary=child(details);text2=child(summary,!0);reset(summary);div=sibling(summary,2);node=child(div);snippet(node,()=>{var _a13;return null!=(_a13=$$props.children)?_a13:noop2});reset(div);reset(details);template_effect(()=>set_text(text2,get2(translatedTitle)));append($$anchor,details);pop()}function isRecord2(value){return"object"==typeof value&&null!==value}function normaliseSection(value){if(!isRecord2(value))return{};const entries2=[];for(const[key3,entry]of Object.entries(value))"string"==typeof entry&&entries2.push([key3,entry]);return Object.fromEntries(entries2)}function normaliseCouchDBConfiguration(value){const source2=isRecord2(value)?value:{};return{admins:normaliseSection(source2.admins),chttpd:normaliseSection(source2.chttpd),chttpd_auth:normaliseSection(source2.chttpd_auth),couchdb:normaliseSection(source2.couchdb),cors:normaliseSection(source2.cors),httpd:normaliseSection(source2.httpd)}}function isGreaterThanOrEqual(baseVersion,version2){const versionParts=`${baseVersion}.0.0.0`.split("."),targetParts=version2.split(".");for(let i3=0;i3<targetParts.length;i3++){const result=versionParts[i3].localeCompare(targetParts[i3],void 0,{numeric:!0});if(result>0)return!0;if(result<0)return!1}return!0}async function updateRemoteSetting(setting,key3,value){const customHeaders=parseHeaderValues(setting.couchDB_CustomHeaders),credential=generateCredentialObject(setting),res2=await requestToCouchDBWithCredentials(setting.couchDB_URI,credential,void 0,key3,value,void 0,customHeaders);return 200==res2.status||(res2.text||"Unknown error")}function getCouchDBServerFixConfirmation(settingKey,expectedValue){return{title:$msg("Change CouchDB server setting"),message:$msg("Change CouchDB server setting '${SETTING}' to '${VALUE}'?",{SETTING:settingKey,VALUE:expectedValue})}}function PanelCouchDBCheck($$anchor,$$props){async function testAndFixSettings(){set(detectedIssues,[],!0);try{const fixResults=await checkConfig($$props.trialRemoteSetting);set(detectedIssues,fixResults,!0)}catch(e3){Logger(e3,LOG_LEVEL_VERBOSE,"setup-couchdb-check");get2(detectedIssues).push({message:$msg("Error during testAndFixSettings: ${reason}",{reason:`${e3}`}),result:"error",classes:[]})}}function isErrorResult(result2){return"result"in result2&&"error"===result2.result}function isFixableError(result2){return isErrorResult(result2)&&"fix"in result2&&"function"==typeof result2.fix}function isSuccessResult(result2){return"result"in result2&&"ok"===result2.result}async function fixIssue(issue){const confirmation=getCouchDBServerFixConfirmation(issue.settingKey,issue.expectedValue),confirmed=await context2.services.confirm.askYesNoDialog(confirmation.message,{title:confirmation.title,defaultOption:"No"});if("yes"===confirmed)try{set(processing,!0);await issue.fix()}catch(e3){Logger(e3,LOG_LEVEL_VERBOSE,"setup-couchdb-fix")}finally{await testAndFixSettings();set(processing,!1)}}var fragment,node_1,div_3,details,summary,node_2,consequent_1,consequent_2,alternate,node_3,consequent_3;push($$props,!0);append_styles($$anchor,$$css9);const result=($$anchor2,issue=noop2)=>{var node,consequent,d4,div=root_120(),div_1=child(div),text2=child(div_1,!0);reset(div_1);node=sibling(div_1,2);consequent=$$anchor3=>{var div_2=root29(),button=child(div_2),text_1=child(button,!0);reset(button);reset(div_2);template_effect($0=>{button.disabled=get2(processing);set_text(text_1,$0)},[()=>$msg("Fix")]);delegated("click",button,()=>fixIssue(issue()));append($$anchor3,div_2)};d4=user_derived(()=>isFixableError(issue()));if_block(node,$$render=>{get2(d4)&&$$render(consequent)});reset(div);template_effect($0=>{set_class(div,1,`check-result ${null!=$0?$0:""}`,"svelte-a38xug");set_text(text2,issue().message)},[()=>isErrorResult(issue())?"error":isSuccessResult(issue())?"success":""]);append($$anchor2,div)},context2=getDialogContext();let detectedIssues=state(proxy([])),processing=state(!1);const errorIssueCount=user_derived(()=>get2(detectedIssues).filter(issue=>isErrorResult(issue)).length),isAllSuccess=user_derived(()=>!(get2(errorIssueCount)>0&&get2(detectedIssues).length>0));fragment=root_39();node_1=first_child(fragment);UserDecisions(node_1,{children:($$anchor2,$$slotProps)=>{{let $0=user_derived(()=>$msg("Check server requirements"));Decision($$anchor2,{get title(){return get2($0)},important:!0,commit:testAndFixSettings})}},$$slots:{default:!0}});div_3=sibling(node_1,2);details=child(div_3);summary=child(details);node_2=child(summary);consequent_1=$$anchor2=>{var text_2=text();template_effect($0=>set_text(text_2,$0),[()=>$msg("No checks have been performed yet.")]);append($$anchor2,text_2)};consequent_2=$$anchor2=>{var text_3=text();template_effect($0=>set_text(text_3,$0),[()=>$msg("All checks passed successfully!")]);append($$anchor2,text_3)};alternate=$$anchor2=>{var text_4=text();template_effect($0=>set_text(text_4,$0),[()=>$msg("${count} issue(s) detected!",{count:`${get2(errorIssueCount)}`})]);append($$anchor2,text_4)};if_block(node_2,$$render=>{0===get2(detectedIssues).length?$$render(consequent_1):get2(isAllSuccess)?$$render(consequent_2,1):$$render(alternate,-1)});reset(summary);node_3=sibling(summary,2);consequent_3=$$anchor2=>{var node_4,fragment_5=root_211(),h3=first_child(fragment_5),text_5=child(h3,!0);reset(h3);node_4=sibling(h3,2);each(node_4,17,()=>get2(detectedIssues),index,($$anchor3,issue)=>{result($$anchor3,()=>get2(issue))});template_effect($0=>set_text(text_5,$0),[()=>$msg("Issue detection log:")]);append($$anchor2,fragment_5)};if_block(node_3,$$render=>{get2(detectedIssues).length>0&&$$render(consequent_3)});reset(details);reset(div_3);template_effect(()=>details.open=!get2(isAllSuccess));append($$anchor,fragment);pop()}function isCouchDBConnectionProbe(value){return"object"==typeof value&&null!==value&&"isMobile"in value&&"function"==typeof value.isMobile&&"connectRemoteCouchDBWithSetting"in value&&"function"==typeof value.connectRemoteCouchDBWithSetting}async function probeCouchDBConnection(replicator,settings,createIfMissing){if(!isCouchDBConnectionProbe(replicator))return{ok:!1,reason:"The CouchDB connection probe is unavailable."};const result=await replicator.connectRemoteCouchDBWithSetting(settings,replicator.isMobile(),createIfMissing,!1);if("string"==typeof result)return{ok:!1,reason:result};try{return{ok:!0}}finally{await result.db.close()}}function isValidCouchDBServerURL(value){try{const url=new URL(value);return("http:"===url.protocol||"https:"===url.protocol)&&""!==url.hostname}catch(e3){return!1}}function SetupRemoteCouchDB($$anchor,$$props){function generateSetting(){const connSetting={...syncSetting},trialSettings={...connSetting},preferredSetting=isCloudantURI(syncSetting.couchDB_URI)?PREFERRED_SETTING_CLOUDANT:PREFERRED_SETTING_SELF_HOSTED,trialRemoteSetting={...DEFAULT_SETTINGS,...preferredSetting,remoteType:RemoteTypes_REMOTE_COUCHDB,...trialSettings};return trialRemoteSetting}async function checkConnection(){try{set(processing,!0);const trialRemoteSetting=generateSetting(),replicator=await context2.services.replicator.getNewReplicator(trialRemoteSetting);if(!replicator)return $msg("Failed to create replicator instance.");try{const result=await probeCouchDBConnection(replicator,trialRemoteSetting,"create-or-connect"===get2(setupMode));return result.ok?"":$msg("Failed to connect to the server: ${reason}",{reason:`${result.reason}`})}catch(e3){return $msg("Failed to connect to the server: ${reason}",{reason:`${e3}`})}}finally{set(processing,!1)}}async function checkAndCommit(){set(error,"");try{set(error,await checkConnection()||"",!0);if(!get2(error)){const setting=generateSetting();$$props.setResult(pickCouchDBSyncSettings(setting));return}}catch(e3){set(error,$msg("Error during connection test: ${reason}",{reason:`${e3}`}),!0);return}}function commit(){const setting=pickCouchDBSyncSettings(generateSetting());$$props.setResult(setting)}function cancel(){$$props.setResult(TYPE_CANCELLED)}var fragment,node,node_1,node_2,node_3,node_4,node_5,node_6,node_7,node_8,node_9,node_10,node_11,node_12,node_21,node_22,node_23,node_24,consequent,alternate;push($$props,!0);const default_setting=pickCouchDBSyncSettings(DEFAULT_SETTINGS);let syncSetting=proxy({...default_setting}),setupMode=state("settings");onMount(()=>{if($$props.getInitialData){const initialData=$$props.getInitialData();if(initialData){set(setupMode,initialData.mode,!0);copyTo(initialData.settings,syncSetting)}}});let error=state("");const context2=getDialogContext();let processing=state(!1);const isURIInsecure=user_derived(()=>!(!syncSetting.couchDB_URI||!syncSetting.couchDB_URI.startsWith("http://"))),isUseJWT=user_derived(()=>syncSetting.useJWT),canProceed=user_derived(()=>isValidCouchDBServerURL(syncSetting.couchDB_URI.trim())&&syncSetting.couchDB_USER.trim().length>0&&syncSetting.couchDB_PASSWORD.trim().length>0&&syncSetting.couchDB_DBNAME.trim().length>0&&(!get2(isUseJWT)||syncSetting.jwtKey.trim().length>0)),testSettings=user_derived(()=>generateSetting()),isURLInvalid=user_derived(()=>""!==syncSetting.couchDB_URI.trim()&&!isValidCouchDBServerURL(syncSetting.couchDB_URI.trim())),primaryActionTitle=user_derived(()=>"create-or-connect"===get2(setupMode)?$msg("Create or connect to database and continue"):"connect-existing"===get2(setupMode)?$msg("Connect to existing database and continue"):$msg("Test connection and save"));fragment=root_142();node=first_child(fragment);{let $0=user_derived(()=>$msg("CouchDB Configuration"));DialogHeader(node,{get title(){return get2($0)}})}node_1=sibling(node,2);Guidance(node_1,{children:($$anchor2,$$slotProps)=>{next();var text2=text();template_effect($0=>set_text(text2,$0),[()=>$msg("Please enter the CouchDB server information below.")]);append($$anchor2,text2)},$$slots:{default:!0}});node_2=sibling(node_1,2);{let $0=user_derived(()=>$msg("URL"));InputRow(node_2,{get label(){return get2($0)},children:($$anchor2,$$slotProps)=>{var input=root30();remove_input_defaults(input);bind_value(input,()=>syncSetting.couchDB_URI,$$value=>syncSetting.couchDB_URI=$$value);append($$anchor2,input)},$$slots:{default:!0}})}node_3=sibling(node_2,2);InfoNote(node_3,{warning:!0,get visible(){return get2(isURIInsecure)},children:($$anchor2,$$slotProps)=>{next();var text_1=text();template_effect($0=>set_text(text_1,$0),[()=>$msg("We can use only Secure (HTTPS) connections on Obsidian Mobile.")]);append($$anchor2,text_1)},$$slots:{default:!0}});node_4=sibling(node_3,2);InfoNote(node_4,{warning:!0,get visible(){return get2(isURLInvalid)},children:($$anchor2,$$slotProps)=>{next();var text_2=text();template_effect($0=>set_text(text_2,$0),[()=>$msg("Enter a complete HTTP or HTTPS URL.")]);append($$anchor2,text_2)},$$slots:{default:!0}});node_5=sibling(node_4,2);{let $0=user_derived(()=>$msg("Username"));InputRow(node_5,{get label(){return get2($0)},children:($$anchor2,$$slotProps)=>{var input_1=root_121();remove_input_defaults(input_1);template_effect($02=>set_attribute2(input_1,"placeholder",$02),[()=>$msg("Enter your username")]);bind_value(input_1,()=>syncSetting.couchDB_USER,$$value=>syncSetting.couchDB_USER=$$value);append($$anchor2,input_1)},$$slots:{default:!0}})}node_6=sibling(node_5,2);{let $0=user_derived(()=>$msg("Password"));InputRow(node_6,{get label(){return get2($0)},children:($$anchor2,$$slotProps)=>{{let $02=user_derived(()=>$msg("Enter your password"));Password($$anchor2,{name:"couchdb-password",get placeholder(){return get2($02)},required:!0,get value(){return syncSetting.couchDB_PASSWORD},set value($$value){syncSetting.couchDB_PASSWORD=$$value}})}},$$slots:{default:!0}})}node_7=sibling(node_6,2);{let $0=user_derived(()=>$msg("Database Name"));InputRow(node_7,{get label(){return get2($0)},children:($$anchor2,$$slotProps)=>{var input_2=root_212();remove_input_defaults(input_2);template_effect($02=>set_attribute2(input_2,"placeholder",$02),[()=>$msg("Enter your database name")]);bind_value(input_2,()=>syncSetting.couchDB_DBNAME,$$value=>syncSetting.couchDB_DBNAME=$$value);append($$anchor2,input_2)},$$slots:{default:!0}})}node_8=sibling(node_7,2);InfoNote(node_8,{children:($$anchor2,$$slotProps)=>{next();var text_3=text();template_effect($0=>set_text(text_3,$0),[()=>$msg("CouchDB validates the database name when you connect. The name must not be empty.")]);append($$anchor2,text_3)},$$slots:{default:!0}});node_9=sibling(node_8,2);{let $0=user_derived(()=>$msg("Use Internal API"));InputRow(node_9,{get label(){return get2($0)},children:($$anchor2,$$slotProps)=>{var input_3=root_310();remove_input_defaults(input_3);bind_checked(input_3,()=>syncSetting.useRequestAPI,$$value=>syncSetting.useRequestAPI=$$value);append($$anchor2,input_3)},$$slots:{default:!0}})}node_10=sibling(node_9,2);InfoNote(node_10,{children:($$anchor2,$$slotProps)=>{next();var text_4=text();template_effect($0=>set_text(text_4,$0),[()=>$msg("If you cannot avoid CORS issues, you might want to try this option. It uses Obsidian's internal API to communicate with the CouchDB server. Not compliant with web standards, but works. Note that this might break in future Obsidian versions.")]);append($$anchor2,text_4)},$$slots:{default:!0}});node_11=sibling(node_10,2);{let $0=user_derived(()=>$msg("Advanced Settings"));ExtraItems(node_11,{get title(){return get2($0)},children:($$anchor2,$$slotProps)=>{{let $02=user_derived(()=>$msg("Custom Headers"));InputRow($$anchor2,{get label(){return get2($02)},children:($$anchor3,$$slotProps2)=>{var textarea=root_44();remove_textarea_child(textarea);bind_value(textarea,()=>syncSetting.couchDB_CustomHeaders,$$value=>syncSetting.couchDB_CustomHeaders=$$value);append($$anchor3,textarea)},$$slots:{default:!0}})}},$$slots:{default:!0}})}node_12=sibling(node_11,2);{let $0=user_derived(()=>$msg("Experimental Settings"));ExtraItems(node_12,{get title(){return get2($0)},children:($$anchor2,$$slotProps)=>{var node_14,node_15,node_16,node_17,node_18,node_19,node_20,fragment_8=root_1110(),node_13=first_child(fragment_8);let $02=user_derived(()=>$msg("Use JWT Authentication"));InputRow(node_13,{get label(){return get2($02)},children:($$anchor3,$$slotProps2)=>{var input_4=root_54();remove_input_defaults(input_4);bind_checked(input_4,()=>syncSetting.useJWT,$$value=>syncSetting.useJWT=$$value);append($$anchor3,input_4)},$$slots:{default:!0}});node_14=sibling(node_13,2);{let $02=user_derived(()=>$msg("JWT Algorithm"));InputRow(node_14,{get label(){return get2($02)},children:($$anchor3,$$slotProps2)=>{var option_1,option_2,option_3,select=root_64(),option=child(select);option.value=option.__value="HS256";option_1=sibling(option);option_1.value=option_1.__value="HS512";option_2=sibling(option_1);option_2.value=option_2.__value="ES256";option_3=sibling(option_2);option_3.value=option_3.__value="ES512";reset(select);template_effect(()=>select.disabled=!get2(isUseJWT));bind_select_value(select,()=>syncSetting.jwtAlgorithm,$$value=>syncSetting.jwtAlgorithm=$$value);append($$anchor3,select)},$$slots:{default:!0}})}node_15=sibling(node_14,2);{let $02=user_derived(()=>$msg("JWT Expiration Duration (minutes)"));InputRow(node_15,{get label(){return get2($02)},children:($$anchor3,$$slotProps2)=>{var input_5=root_73();remove_input_defaults(input_5);template_effect(()=>input_5.disabled=!get2(isUseJWT));bind_value(input_5,()=>`${syncSetting.jwtExpDuration}`,v2=>syncSetting.jwtExpDuration=parseInt(v2)||0);append($$anchor3,input_5)},$$slots:{default:!0}})}node_16=sibling(node_15,2);{let $02=user_derived(()=>$msg("JWT Key"));InputRow(node_16,{get label(){return get2($02)},children:($$anchor3,$$slotProps2)=>{var textarea_1=root_83();remove_textarea_child(textarea_1);template_effect($03=>{set_attribute2(textarea_1,"placeholder",$03);textarea_1.disabled=!get2(isUseJWT)},[()=>$msg("Enter your JWT secret or private key")]);bind_value(textarea_1,()=>syncSetting.jwtKey,$$value=>syncSetting.jwtKey=$$value);append($$anchor3,textarea_1)},$$slots:{default:!0}})}node_17=sibling(node_16,2);InfoNote(node_17,{children:($$anchor3,$$slotProps2)=>{next();var text_5=text();template_effect($02=>set_text(text_5,$02),[()=>$msg("For HS256/HS512 algorithms, provide the shared secret key. For ES256/ES512 algorithms, provide the pkcs8 PEM-formatted private key.")]);append($$anchor3,text_5)},$$slots:{default:!0}});node_18=sibling(node_17,2);{let $02=user_derived(()=>$msg("JWT Key ID (kid)"));InputRow(node_18,{get label(){return get2($02)},children:($$anchor3,$$slotProps2)=>{var input_6=root_93();remove_input_defaults(input_6);template_effect($03=>{set_attribute2(input_6,"placeholder",$03);input_6.disabled=!get2(isUseJWT)},[()=>$msg("Enter your JWT Key ID")]);bind_value(input_6,()=>syncSetting.jwtKid,$$value=>syncSetting.jwtKid=$$value);append($$anchor3,input_6)},$$slots:{default:!0}})}node_19=sibling(node_18,2);{let $02=user_derived(()=>$msg("JWT Subject (sub)"));InputRow(node_19,{get label(){return get2($02)},children:($$anchor3,$$slotProps2)=>{var input_7=root_103();remove_input_defaults(input_7);template_effect($03=>{set_attribute2(input_7,"placeholder",$03);input_7.disabled=!get2(isUseJWT)},[()=>$msg("Enter your JWT Subject (CouchDB Username)")]);bind_value(input_7,()=>syncSetting.jwtSub,$$value=>syncSetting.jwtSub=$$value);append($$anchor3,input_7)},$$slots:{default:!0}})}node_20=sibling(node_19,2);InfoNote(node_20,{warning:!0,children:($$anchor3,$$slotProps2)=>{next();var text_6=text();template_effect($02=>set_text(text_6,$02),[()=>$msg("JWT (JSON Web Token) authentication allows you to securely authenticate with the CouchDB server using tokens. Ensure that your CouchDB server is configured to accept JWTs and that the provided key and settings match the server's configuration. Incidentally, I have not verified it very thoroughly.")]);append($$anchor3,text_6)},$$slots:{default:!0}});append($$anchor2,fragment_8)},$$slots:{default:!0}})}node_21=sibling(node_12,2);InfoNote(node_21,{warning:!0,children:($$anchor2,$$slotProps)=>{next();var text_7=text();template_effect($0=>set_text(text_7,$0),[()=>$msg("This optional check uses Obsidian's internal request API and sends the credentials above to the CouchDB server. Use it only with a server you trust; administrator access may be required.")]);append($$anchor2,text_7)},$$slots:{default:!0}});node_22=sibling(node_21,2);PanelCouchDBCheck(node_22,{get trialRemoteSetting(){return get2(testSettings)}});node_23=sibling(node_22,4);{let $0=user_derived(()=>""!==get2(error));InfoNote(node_23,{error:!0,get visible(){return get2($0)},children:($$anchor2,$$slotProps)=>{next();var text_8=text();template_effect(()=>set_text(text_8,get2(error)));append($$anchor2,text_8)},$$slots:{default:!0}})}node_24=sibling(node_23,2);consequent=$$anchor2=>{var text_9=text();template_effect($0=>set_text(text_9,$0),[()=>$msg("Checking connection... Please wait.")]);append($$anchor2,text_9)};alternate=$$anchor2=>{UserDecisions($$anchor2,{children:($$anchor3,$$slotProps)=>{var node_26,consequent_1,node_29,fragment_15=root_133(),node_25=first_child(fragment_15);let $0=user_derived(()=>!get2(canProceed));Decision(node_25,{get title(){return get2(primaryActionTitle)},important:!0,get disabled(){return get2($0)},commit:()=>checkAndCommit()});node_26=sibling(node_25,2);consequent_1=$$anchor4=>{var node_28,fragment_16=root_123(),node_27=first_child(fragment_16);InfoNote(node_27,{warning:!0,children:($$anchor5,$$slotProps2)=>{next();var text_10=text();template_effect($0=>set_text(text_10,$0),[()=>$msg("Saving without a successful connection test keeps this profile, but automatic synchronisation may fail until the connection is corrected.")]);append($$anchor5,text_10)},$$slots:{default:!0}});node_28=sibling(node_27,2);{let $0=user_derived(()=>$msg("Save without connecting")),$1=user_derived(()=>!get2(canProceed));Decision(node_28,{get title(){return get2($0)},get disabled(){return get2($1)},commit:()=>commit()})}append($$anchor4,fragment_16)};if_block(node_26,$$render=>{"settings"===get2(setupMode)&&$$render(consequent_1)});node_29=sibling(node_26,2);{let $0=user_derived(()=>$msg("Cancel"));Decision(node_29,{get title(){return get2($0)},commit:()=>cancel()})}append($$anchor3,fragment_15)},$$slots:{default:!0}})};if_block(node_24,$$render=>{get2(processing)?$$render(consequent):$$render(alternate,-1)});append($$anchor,fragment);pop()}function SetupRemoteBucket($$anchor,$$props){function generateSetting(){const connSetting={...syncSetting},trialSettings={...connSetting},trialRemoteSetting={...DEFAULT_SETTINGS,...PREFERRED_JOURNAL_SYNC,remoteType:RemoteTypes_REMOTE_MINIO,...trialSettings};return trialRemoteSetting}async function checkConnection(){try{set(processing,!0);const trialRemoteSetting=generateSetting(),replicator=await context2.services.replicator.getNewReplicator(trialRemoteSetting);if(!replicator)return $msg("Failed to create replicator instance.");try{const result=await replicator.tryConnectRemote(trialRemoteSetting,!1);return result?"":$msg("Failed to connect to the server. Please check your settings.")}catch(e3){return $msg("Failed to connect to the server: ${reason}",{reason:`${e3}`})}}finally{set(processing,!1)}}async function checkAndCommit(){set(error,"");try{set(error,await checkConnection()||"",!0);if(!get2(error)){const setting=generateSetting();$$props.setResult(pickBucketSyncSettings(setting));return}}catch(e3){set(error,$msg("Error during connection test: ${reason}",{reason:`${e3}`}),!0);return}}function commit(){const setting=pickBucketSyncSettings(generateSetting());$$props.setResult(setting)}function cancel(){$$props.setResult(TYPE_CANCELLED)}var fragment,node,node_1,node_2,node_3,node_4,node_5,node_6,node_7,node_8,node_9,node_10,node_11,node_12,node_13,node_14,node_15,consequent,alternate;push($$props,!0);const default_setting=pickBucketSyncSettings(DEFAULT_SETTINGS);let syncSetting=proxy({...default_setting});onMount(()=>{if($$props.getInitialData){const initialData=$$props.getInitialData();initialData&&copyTo(initialData,syncSetting)}});let error=state("");const context2=getDialogContext(),isEndpointSecure=user_derived(()=>syncSetting.endpoint.trim().toLowerCase().startsWith("https://")),isEndpointInsecure=user_derived(()=>syncSetting.endpoint.trim().toLowerCase().startsWith("http://")),isEndpointSupplied=user_derived(()=>get2(isEndpointInsecure)||get2(isEndpointSecure)),canProceed=user_derived(()=>""!==syncSetting.accessKey.trim()&&""!==syncSetting.secretKey.trim()&&""!==syncSetting.bucket.trim()&&""!==syncSetting.endpoint.trim()&&""!==syncSetting.region.trim()&&get2(isEndpointSupplied));let processing=state(!1);fragment=root_94();node=first_child(fragment);{let $0=user_derived(()=>$msg("S3/MinIO/R2 Configuration"));DialogHeader(node,{get title(){return get2($0)}})}node_1=sibling(node,2);Guidance(node_1,{children:($$anchor2,$$slotProps)=>{next();var text2=text();template_effect($0=>set_text(text2,$0),[()=>$msg("Please enter the details required to connect to your S3/MinIO/R2 compatible object storage service.")]);append($$anchor2,text2)},$$slots:{default:!0}});node_2=sibling(node_1,2);{let $0=user_derived(()=>$msg("Endpoint URL"));InputRow(node_2,{get label(){return get2($0)},children:($$anchor2,$$slotProps)=>{var input=root31();remove_input_defaults(input);bind_value(input,()=>syncSetting.endpoint,$$value=>syncSetting.endpoint=$$value);append($$anchor2,input)},$$slots:{default:!0}})}node_3=sibling(node_2,2);InfoNote(node_3,{warning:!0,get visible(){return get2(isEndpointInsecure)},children:($$anchor2,$$slotProps)=>{next();var text_1=text();template_effect($0=>set_text(text_1,$0),[()=>$msg("We can use only Secure (HTTPS) connections on Obsidian Mobile.")]);append($$anchor2,text_1)},$$slots:{default:!0}});node_4=sibling(node_3,2);{let $0=user_derived(()=>$msg("Access Key ID"));InputRow(node_4,{get label(){return get2($0)},children:($$anchor2,$$slotProps)=>{var input_1=root_124();remove_input_defaults(input_1);template_effect($02=>set_attribute2(input_1,"placeholder",$02),[()=>$msg("Enter your Access Key ID")]);bind_value(input_1,()=>syncSetting.accessKey,$$value=>syncSetting.accessKey=$$value);append($$anchor2,input_1)},$$slots:{default:!0}})}node_5=sibling(node_4,2);{let $0=user_derived(()=>$msg("Secret Access Key"));InputRow(node_5,{get label(){return get2($0)},children:($$anchor2,$$slotProps)=>{{let $02=user_derived(()=>$msg("Enter your Secret Access Key"));Password($$anchor2,{name:"s3-secret-access-key",get placeholder(){return get2($02)},required:!0,get value(){return syncSetting.secretKey},set value($$value){syncSetting.secretKey=$$value}})}},$$slots:{default:!0}})}node_6=sibling(node_5,2);{let $0=user_derived(()=>$msg("Bucket Name"));InputRow(node_6,{get label(){return get2($0)},children:($$anchor2,$$slotProps)=>{var input_2=root_213();remove_input_defaults(input_2);template_effect($02=>set_attribute2(input_2,"placeholder",$02),[()=>$msg("Enter your Bucket Name")]);bind_value(input_2,()=>syncSetting.bucket,$$value=>syncSetting.bucket=$$value);append($$anchor2,input_2)},$$slots:{default:!0}})}node_7=sibling(node_6,2);{let $0=user_derived(()=>$msg("Region"));InputRow(node_7,{get label(){return get2($0)},children:($$anchor2,$$slotProps)=>{var input_3=root_311();remove_input_defaults(input_3);template_effect($02=>set_attribute2(input_3,"placeholder",$02),[()=>$msg("Enter your Region (e.g., us-east-1, auto for R2)")]);bind_value(input_3,()=>syncSetting.region,$$value=>syncSetting.region=$$value);append($$anchor2,input_3)},$$slots:{default:!0}})}node_8=sibling(node_7,2);{let $0=user_derived(()=>$msg("Use Path-Style Access"));InputRow(node_8,{get label(){return get2($0)},children:($$anchor2,$$slotProps)=>{var input_4=root_45();remove_input_defaults(input_4);bind_checked(input_4,()=>syncSetting.forcePathStyle,$$value=>syncSetting.forcePathStyle=$$value);append($$anchor2,input_4)},$$slots:{default:!0}})}node_9=sibling(node_8,2);{let $0=user_derived(()=>$msg("Folder Prefix"));InputRow(node_9,{get label(){return get2($0)},children:($$anchor2,$$slotProps)=>{var input_5=root_55();remove_input_defaults(input_5);template_effect($02=>set_attribute2(input_5,"placeholder",$02),[()=>$msg("Enter a folder prefix (optional)")]);bind_value(input_5,()=>syncSetting.bucketPrefix,$$value=>syncSetting.bucketPrefix=$$value);append($$anchor2,input_5)},$$slots:{default:!0}})}node_10=sibling(node_9,2);InfoNote(node_10,{children:($$anchor2,$$slotProps)=>{next();var text_2=text();template_effect($0=>set_text(text_2,$0),[()=>$msg("If you want to store the data in a specific folder within the bucket, you can specify a folder prefix here. Otherwise, leave it blank to store data at the root of the bucket.")]);append($$anchor2,text_2)},$$slots:{default:!0}});node_11=sibling(node_10,2);{let $0=user_derived(()=>$msg("Use internal API"));InputRow(node_11,{get label(){return get2($0)},children:($$anchor2,$$slotProps)=>{var input_6=root_65();remove_input_defaults(input_6);bind_checked(input_6,()=>syncSetting.useCustomRequestHandler,$$value=>syncSetting.useCustomRequestHandler=$$value);append($$anchor2,input_6)},$$slots:{default:!0}})}node_12=sibling(node_11,2);InfoNote(node_12,{children:($$anchor2,$$slotProps)=>{next();var text_3=text();template_effect($0=>set_text(text_3,$0),[()=>$msg("If you cannot avoid CORS issues, you might want to try this option. It uses Obsidian's internal API to communicate with the S3 server. Not compliant with web standards, but works. Note that this might break in future Obsidian versions.")]);append($$anchor2,text_3)},$$slots:{default:!0}});node_13=sibling(node_12,2);{let $0=user_derived(()=>$msg("Advanced Settings"));ExtraItems(node_13,{get title(){return get2($0)},children:($$anchor2,$$slotProps)=>{{let $02=user_derived(()=>$msg("Custom Headers"));InputRow($$anchor2,{get label(){return get2($02)},children:($$anchor3,$$slotProps2)=>{var textarea=root_74();remove_textarea_child(textarea);bind_value(textarea,()=>syncSetting.bucketCustomHeaders,$$value=>syncSetting.bucketCustomHeaders=$$value);append($$anchor3,textarea)},$$slots:{default:!0}})}},$$slots:{default:!0}})}node_14=sibling(node_13,2);{let $0=user_derived(()=>""!==get2(error));InfoNote(node_14,{error:!0,get visible(){return get2($0)},children:($$anchor2,$$slotProps)=>{next();var text_4=text();template_effect(()=>set_text(text_4,get2(error)));append($$anchor2,text_4)},$$slots:{default:!0}})}node_15=sibling(node_14,2);consequent=$$anchor2=>{var text_5=text();template_effect($0=>set_text(text_5,$0),[()=>$msg("Checking connection... Please wait.")]);append($$anchor2,text_5)};alternate=$$anchor2=>{UserDecisions($$anchor2,{children:($$anchor3,$$slotProps)=>{var node_17,node_18,fragment_10=root_84(),node_16=first_child(fragment_10);let $0=user_derived(()=>$msg("Test Settings and Continue")),$1=user_derived(()=>!get2(canProceed));Decision(node_16,{get title(){return get2($0)},important:!0,get disabled(){return get2($1)},commit:()=>checkAndCommit()});node_17=sibling(node_16,2);{let $0=user_derived(()=>$msg("Continue anyway"));Decision(node_17,{get title(){return get2($0)},commit:()=>commit()})}node_18=sibling(node_17,2);{let $0=user_derived(()=>$msg("Cancel"));Decision(node_18,{get title(){return get2($0)},commit:()=>cancel()})}append($$anchor3,fragment_10)},$$slots:{default:!0}})};if_block(node_15,$$render=>{get2(processing)?$$render(consequent):$$render(alternate,-1)});append($$anchor,fragment);pop()}async function upsert2(db,id,func){try{const doc=await db.get(id),updated=func(doc),result=await db.put(updated,{});if(result&&result.ok)return updated;throw new Error("Failed to update")}catch(ex){const isNotFound="not_found"===(null==ex?void 0:ex.name)||"missing"===(null==ex?void 0:ex.reason)||"missing"===(null==ex?void 0:ex.message)||"not_found"===(null==ex?void 0:ex.message);if(isNotFound){const seed=func({_id:id}),result=await db.put(seed,{});if(result&&result.ok)return seed;throw new Error("Failed to insert")}throw ex}}function parseSeq(seq){return parseInt(String(seq).split("-")[0],10)}function buildRevsDiffParam(changesResults){var _a13;const param={};for(const{id,changes:changes3}of changesResults)param[id]=[...null!=(_a13=param[id])?_a13:[],...changes3.map(c3=>c3.rev)];return param}function sortBySeq(docs,changesResults){var _a13;const maxSeqById=new Map;for(const{id,seq}of changesResults)maxSeqById.set(id,Math.max(null!=(_a13=maxSeqById.get(id))?_a13:0,parseSeq(seq)));return docs.slice().sort((a2,b3)=>{var _a14,_b6;return(null!=(_a14=maxSeqById.get(a2._id))?_a14:0)-(null!=(_b6=maxSeqById.get(b3._id))?_b6:0)})}async function replicateShim(targetDB,sourceDB,progress,option={}){try{const[targetDBInfo,sourceDBInfo]=await Promise.all([targetDB.info(),sourceDB.info()]),maxNumSeq=parseSeq(sourceDBInfo.update_seq);await serialized(`replication-${targetDBInfo.db_name}-${sourceDBInfo.db_name}`,async()=>{var _a13,_b6,_c3;Logger(`Replication ${sourceDBInfo.db_name} (${sourceDBInfo.update_seq}) → ${targetDBInfo.db_name} (${targetDBInfo.update_seq})`,LOG_LEVEL_VERBOSE);const{db_name:targetName}=targetDBInfo,{db_name:sourceName}=sourceDBInfo,sourceCheckpointID=`_local/replication-checkpoint-mark-${targetName}-${sourceName}`,{mark}=await upsert2(sourceDB,sourceCheckpointID,doc=>{var _a14;return{...doc,mark:option.rewind?String(Date.now()):null!=(_a14=doc.mark)?_a14:String(Date.now())}});Logger(`Replication mark: ${mark}`,LOG_LEVEL_VERBOSE);const targetCheckpointID=`_local/replication-checkpoint-${targetName}-${mark}`,checkpoint=await upsert2(targetDB,targetCheckpointID,doc=>{var _a14;return{...doc,since:null!=(_a14=doc.since)?_a14:""}});let since=checkpoint.since;Logger(`Starting from seq ${since}`,LOG_LEVEL_VERBOSE);const batchSize=null!=(_a13=option.batch_size)?_a13:33;for(;;){const changes3=await sourceDB.changes({since,style:"all_docs",limit:batchSize});if(0===changes3.results.length)break;if(null==(_c3=null==(_b6=option.controller)?void 0:_b6.signal)?void 0:_c3.aborted)break;const changesResults=changes3.results,revsDiffParam=buildRevsDiffParam(changesResults),diff=await targetDB.revsDiff(revsDiffParam),missingRequests=Object.entries(diff).filter(([,entry])=>void 0!==entry.missing).flatMap(([id,entry])=>entry.missing.map(rev3=>({id,rev:rev3})));if(missingRequests.length>0){const bulkGetResult=await sourceDB.bulkGet({docs:missingRequests,revs:!0}),fetchedDocs=bulkGetResult.results.flatMap(r4=>r4.docs).filter(d4=>"ok"in d4).map(d4=>d4.ok);await targetDB.bulkDocs(fetchedDocs,{new_edits:!1});const uniqueIds=[...new Set(changesResults.map(c3=>c3.id))],refreshResult=await targetDB.bulkGet({docs:uniqueIds.map(id=>({id}))}),refreshedDocs=refreshResult.results.flatMap(r4=>r4.docs).filter(d4=>"ok"in d4).map(d4=>d4.ok),orderedDocs=sortBySeq(refreshedDocs,changesResults),lastSeqNum=parseSeq(changes3.last_seq);try{await progress(orderedDocs,{lastSeq:lastSeqNum,maxSeqInBatch:maxNumSeq})}catch(ex){Logger("Progress callback failed during shim-replication",LOG_LEVEL_VERBOSE);Logger(ex,LOG_LEVEL_VERBOSE)}}since=changes3.last_seq;await upsert2(targetDB,targetCheckpointID,doc=>({...doc,since}))}})}catch(ex){Logger("Replication failed",LOG_LEVEL_VERBOSE);Logger(ex,LOG_LEVEL_VERBOSE);throw ex}Logger("Replication completed",LOG_LEVEL_VERBOSE)}async function encrypt5(data,passphrase){return await encryptWithEphemeralSalt(data,passphrase,!0)}async function decrypt5(encryptedData,passphrase){return await decryptWithEphemeralSalt(encryptedData,passphrase)}async function getHashedStringWithCurrentTime(source2){const salt=(~~((new Date).getTime()/1e3/180)).toString(36),salt2=await sha12(salt);return await sha12(salt2+source2)}async function probeP2PSetupConnection(replicator){try{await replicator.setOnSetup();await replicator.allowReconnection();await replicator.open();return{ok:!0}}catch(error){return{ok:!1,reason:error instanceof Error?error.message:String(error)}}}function SetupRemoteP2P($$anchor,$$props){function generateSetting(){const connSetting={...P2P_DEFAULT_SETTINGS,...syncSetting,P2P_Enabled:!0,P2P_maxWirePayloadBytes:normaliseP2PMaxWirePayloadBytes(syncSetting.P2P_maxWirePayloadBytes),P2P_connectionPath:normaliseP2PConnectionPath(syncSetting.P2P_connectionPath)===P2PConnectionPaths_Relay&&get2(hasValidTurnServer)?P2PConnectionPaths_Relay:P2PConnectionPaths_Automatic},trialSettings={...connSetting},trialRemoteSetting={...DEFAULT_SETTINGS,...PREFERRED_BASE,remoteType:RemoteTypes_REMOTE_P2P,...trialSettings};return trialRemoteSetting}async function checkConnection(){try{set(processing,!0);const trialRemoteSetting=generateSetting(),map4=new Map,store={get:key3=>Promise.resolve(map4.get(key3)||null),set:(key3,value)=>{map4.set(key3,value);return Promise.resolve()},delete:key3=>{map4.delete(key3);return Promise.resolve()},keys:()=>Promise.resolve(Array.from(map4.keys())),get db(){return Promise.resolve(this)}},dummyPouch=new index_es_default("dummy"),env={events:context2.context.events,translate:context2.context.translate,settings:trialRemoteSetting,processReplicatedDocs:async _docs=>{},confirm:context2.services.confirm,db:dummyPouch,simpleStore:store,deviceName:syncSetting.P2P_DevicePeerName||"unnamed-device",platform:"setup-wizard"},replicator=new TrysteroReplicator(env);try{const result=await probeP2PSetupConnection(replicator);return result.ok?"":$msg("Failed to connect to the signalling relay: ${reason}",{reason:`${result.reason}`})}finally{try{await replicator.close();await dummyPouch.destroy()}catch(e3){Logger(e3,LOG_LEVEL_VERBOSE,"setup-p2p-cleanup")}}}finally{set(processing,!1)}}function setDefaultRelay(){syncSetting.P2P_relays=P2P_DEFAULT_SETTINGS.P2P_relays}function generateDefaultGroupId(){syncSetting.P2P_roomID=generateP2PRoomId()}async function checkAndCommit(){set(error,"");try{set(error,await checkConnection()||"",!0);if(!get2(error)){const setting=generateSetting();$$props.setResult(pickP2PSyncSettings(setting));return}}catch(e3){set(error,$msg("Error during connection test: ${reason}",{reason:`${e3}`}),!0);return}}function commit(){const setting=pickP2PSyncSettings(generateSetting());$$props.setResult(setting)}function cancel(){$$props.setResult(TYPE_CANCELLED)}var _a13,fragment,node,node_1,node_2,node_3,node_4,node_5,node_6,node_7,node_8,node_9,node_10,node_11,node_12,node_13,node_19,node_25,node_26,consequent,alternate;push($$props,!0);const default_setting=pickP2PSyncSettings(DEFAULT_SETTINGS);let syncSetting=proxy({...default_setting});const context2=getDialogContext();let error=state(""),connectionPathResetNotice=state(!1);const hasValidTurnServer=user_derived(()=>hasValidP2PTurnServerUrl(null!==(_a13=syncSetting.P2P_turnServers)&&void 0!==_a13?_a13:""));onMount(()=>{var _a14;let initialData;if($$props.getInitialData){initialData=$$props.getInitialData();initialData&&copyTo(initialData,syncSetting)}const initialPeerName=(null!==(_a14=null==initialData?void 0:initialData.P2P_DevicePeerName)&&void 0!==_a14?_a14:"").trim();if(""!==initialPeerName)return;const cachedPeerName=context2.services.config.getSmallConfig(SETTING_KEY_P2P_DEVICE_NAME);cachedPeerName&&(syncSetting.P2P_DevicePeerName=cachedPeerName)});user_effect(()=>{if(!get2(hasValidTurnServer)&&syncSetting.P2P_connectionPath===P2PConnectionPaths_Relay){syncSetting.P2P_connectionPath=P2PConnectionPaths_Automatic;set(connectionPathResetNotice,!0)}});let processing=state(!1);const canProceed=user_derived(()=>{var _a14;return""!==syncSetting.P2P_relays.trim()&&""!==syncSetting.P2P_roomID.trim()&&""!==syncSetting.P2P_passphrase.trim()&&""!==(null!==(_a14=syncSetting.P2P_DevicePeerName)&&void 0!==_a14?_a14:"").trim()});fragment=root_152();node=first_child(fragment);{let $0=user_derived(()=>$msg("P2P Configuration"));DialogHeader(node,{get title(){return get2($0)}})}node_1=sibling(node,2);Guidance(node_1,{children:($$anchor2,$$slotProps)=>{next();var text2=text();template_effect($0=>set_text(text2,$0),[()=>$msg("Please enter the Peer-to-Peer Synchronisation information below.")]);append($$anchor2,text2)},$$slots:{default:!0}});node_2=sibling(node_1,2);{let $0=user_derived(()=>$msg("Enabled"));InputRow(node_2,{get label(){return get2($0)},children:($$anchor2,$$slotProps)=>{var input=root32();remove_input_defaults(input);bind_checked(input,()=>syncSetting.P2P_Enabled,$$value=>syncSetting.P2P_Enabled=$$value);append($$anchor2,input)},$$slots:{default:!0}})}node_3=sibling(node_2,2);{let $0=user_derived(()=>$msg("Signalling relay URLs"));InputRow(node_3,{get label(){return get2($0)},children:($$anchor2,$$slotProps)=>{var button,text_1,fragment_2=root_125(),input_1=first_child(fragment_2);remove_input_defaults(input_1);button=sibling(input_1,2);text_1=child(button,!0);reset(button);template_effect($02=>set_text(text_1,$02),[()=>$msg("Use the project's public signalling relay")]);bind_value(input_1,()=>syncSetting.P2P_relays,$$value=>syncSetting.P2P_relays=$$value);delegated("click",button,()=>setDefaultRelay());append($$anchor2,fragment_2)},$$slots:{default:!0}})}node_4=sibling(node_3,2);InfoNote(node_4,{children:($$anchor2,$$slotProps)=>{var fragment_3,text_2,a2,text_3;next();fragment_3=root_214();text_2=first_child(fragment_3);a2=sibling(text_2);text_3=child(a2,!0);reset(a2);next();template_effect(($0,$1,$2)=>{set_text(text_2,`${null!=$0?$0:""}\n ${null!=$1?$1:""} `);set_text(text_3,$2)},[()=>$msg("Peer discovery uses Nostr-compatible signalling relays."),()=>$msg("The project's public signalling relay is a best-effort convenience operated by the project author. It does not store Vault contents, but signalling metadata may be visible to the relay. Availability and log retention are not guaranteed. You can replace it with your own Nostr-compatible relay."),()=>$msg("Learn more about P2P connections")]);append($$anchor2,fragment_3)},$$slots:{default:!0}});node_5=sibling(node_4,2);{let $0=user_derived(()=>$msg("Group ID"));InputRow(node_5,{get label(){return get2($0)},children:($$anchor2,$$slotProps)=>{var button_1,text_4,fragment_4=root_312(),input_2=first_child(fragment_4);remove_input_defaults(input_2);button_1=sibling(input_2,2);text_4=child(button_1,!0);reset(button_1);template_effect($02=>set_text(text_4,$02),[()=>$msg("Generate Random ID")]);bind_value(input_2,()=>syncSetting.P2P_roomID,$$value=>syncSetting.P2P_roomID=$$value);delegated("click",button_1,()=>generateDefaultGroupId());append($$anchor2,fragment_4)},$$slots:{default:!0}})}node_6=sibling(node_5,2);{let $0=user_derived(()=>$msg("Passphrase"));InputRow(node_6,{get label(){return get2($0)},children:($$anchor2,$$slotProps)=>{{let $02=user_derived(()=>$msg("Enter your passphrase"));Password($$anchor2,{name:"p2p-password",get placeholder(){return get2($02)},get value(){return syncSetting.P2P_passphrase},set value($$value){syncSetting.P2P_passphrase=$$value}})}},$$slots:{default:!0}})}node_7=sibling(node_6,2);InfoNote(node_7,{children:($$anchor2,$$slotProps)=>{var fragment_6,text_5,text_6;next();fragment_6=root_46();text_5=first_child(fragment_6,!0);text_6=sibling(text_5,2);template_effect(($0,$1)=>{set_text(text_5,$0);set_text(text_6,` ${null!=$1?$1:""}`)},[()=>$msg("The Group ID and passphrase are used to identify your group of devices. Make sure to use the same Group ID and passphrase on all devices you want to synchronise."),()=>$msg("Note that the Group ID is not limited to the generated format; you can use any string as the Group ID.")]);append($$anchor2,fragment_6)},$$slots:{default:!0}});node_8=sibling(node_7,2);{let $0=user_derived(()=>$msg("Device Peer ID"));InputRow(node_8,{get label(){return get2($0)},children:($$anchor2,$$slotProps)=>{var input_3=root_56();remove_input_defaults(input_3);bind_value(input_3,()=>syncSetting.P2P_DevicePeerName,$$value=>syncSetting.P2P_DevicePeerName=$$value);append($$anchor2,input_3)},$$slots:{default:!0}})}node_9=sibling(node_8,2);{let $0=user_derived(()=>$msg("Auto Start P2P Connection"));InputRow(node_9,{get label(){return get2($0)},children:($$anchor2,$$slotProps)=>{var input_4=root_66();remove_input_defaults(input_4);bind_checked(input_4,()=>syncSetting.P2P_AutoStart,$$value=>syncSetting.P2P_AutoStart=$$value);append($$anchor2,input_4)},$$slots:{default:!0}})}node_10=sibling(node_9,2);InfoNote(node_10,{children:($$anchor2,$$slotProps)=>{next();var text_7=text();template_effect($0=>set_text(text_7,$0),[()=>$msg('If "Auto Start P2P Connection" is enabled, the P2P connection will be started automatically when the plug-in launches.')]);append($$anchor2,text_7)},$$slots:{default:!0}});node_11=sibling(node_10,2);{let $0=user_derived(()=>$msg("Announce changes automatically after connecting"));InputRow(node_11,{get label(){return get2($0)},children:($$anchor2,$$slotProps)=>{var input_5=root_75();remove_input_defaults(input_5);bind_checked(input_5,()=>syncSetting.P2P_AutoBroadcast,$$value=>syncSetting.P2P_AutoBroadcast=$$value);append($$anchor2,input_5)},$$slots:{default:!0}})}node_12=sibling(node_11,2);InfoNote(node_12,{children:($$anchor2,$$slotProps)=>{next();var text_8=text();template_effect($0=>set_text(text_8,$0),[()=>$msg("When enabled, this device notifies connected peers after a local change. The notification contains no Vault data; a peer which follows this device then fetches the change through the encrypted P2P connection.")]);append($$anchor2,text_8)},$$slots:{default:!0}});node_13=sibling(node_12,2);{let $0=user_derived(()=>$msg("Connection compatibility"));ExtraItems(node_13,{get title(){return get2($0)},children:($$anchor2,$$slotProps)=>{var node_15,node_16,node_17,node_18,fragment_9=root_104(),node_14=first_child(fragment_9);let $02=user_derived(()=>$msg("P2P message size"));InputRow(node_14,{get label(){return get2($02)},children:($$anchor3,$$slotProps2)=>{var option_value,option_1,text_10,option_1_value,option_2,text_11,option_2_value,option_3,text_12,option_3_value,select=root_85(),option=child(select),text_9=child(option,!0);reset(option);option_value={};option_1=sibling(option);text_10=child(option_1,!0);reset(option_1);option_1_value={};option_2=sibling(option_1);text_11=child(option_2,!0);reset(option_2);option_2_value={};option_3=sibling(option_2);text_12=child(option_3,!0);reset(option_3);option_3_value={};reset(select);template_effect(($03,$1,$2,$3,$4)=>{var _a14,_b6,_c3,_d2;set_attribute2(select,"aria-label",$03);set_text(text_9,$1);option_value!==(option_value=P2PMessageSizePresets_Standard)&&(option.value=null!=(_a14=option.__value=P2PMessageSizePresets_Standard)?_a14:"");set_text(text_10,$2);option_1_value!==(option_1_value=P2PMessageSizePresets_Reduced)&&(option_1.value=null!=(_b6=option_1.__value=P2PMessageSizePresets_Reduced)?_b6:"");set_text(text_11,$3);option_2_value!==(option_2_value=P2PMessageSizePresets_Conservative)&&(option_2.value=null!=(_c3=option_2.__value=P2PMessageSizePresets_Conservative)?_c3:"");set_text(text_12,$4);option_3_value!==(option_3_value=P2PMessageSizePresets_MaximumCompatibility)&&(option_3.value=null!=(_d2=option_3.__value=P2PMessageSizePresets_MaximumCompatibility)?_d2:"")},[()=>$msg("P2P message size"),()=>$msg("Standard"),()=>$msg("Reduced"),()=>$msg("Conservative"),()=>$msg("Maximum compatibility")]);bind_select_value(select,()=>syncSetting.P2P_maxWirePayloadBytes,$$value=>syncSetting.P2P_maxWirePayloadBytes=$$value);append($$anchor3,select)},$$slots:{default:!0}});node_15=sibling(node_14,2);InfoNote(node_15,{children:($$anchor3,$$slotProps2)=>{next();var text_13=text();template_effect($02=>set_text(text_13,$02),[()=>$msg("Smaller messages can improve compatibility on paths which fragment or drop larger WebRTC messages. This setting limits outgoing P2P messages, so use a compatible profile on each sending device when required.")]);append($$anchor3,text_13)},$$slots:{default:!0}});node_16=sibling(node_15,2);{let $02=user_derived(()=>$msg("Connection path"));InputRow(node_16,{get label(){return get2($02)},children:($$anchor3,$$slotProps2)=>{var option_4_value,option_5,text_15,option_5_value,select_1=root_95(),option_4=child(select_1),text_14=child(option_4,!0);reset(option_4);option_4_value={};option_5=sibling(option_4);text_15=child(option_5,!0);reset(option_5);option_5_value={};reset(select_1);template_effect(($03,$1,$2)=>{var _a14,_b6;set_attribute2(select_1,"aria-label",$03);set_text(text_14,$1);option_4_value!==(option_4_value=P2PConnectionPaths_Automatic)&&(option_4.value=null!=(_a14=option_4.__value=P2PConnectionPaths_Automatic)?_a14:"");option_5.disabled=!get2(hasValidTurnServer);set_text(text_15,$2);option_5_value!==(option_5_value=P2PConnectionPaths_Relay)&&(option_5.value=null!=(_b6=option_5.__value=P2PConnectionPaths_Relay)?_b6:"")},[()=>$msg("Connection path"),()=>$msg("Automatic"),()=>$msg("TURN relay only")]);delegated("change",select_1,()=>set(connectionPathResetNotice,!1));bind_select_value(select_1,()=>syncSetting.P2P_connectionPath,$$value=>syncSetting.P2P_connectionPath=$$value);append($$anchor3,select_1)},$$slots:{default:!0}})}node_17=sibling(node_16,2);InfoNote(node_17,{children:($$anchor3,$$slotProps2)=>{next();var text_16=text();template_effect($02=>set_text(text_16,$02),[()=>$msg("TURN relay only is available when at least one valid TURN server URL is configured under Advanced Settings.")]);append($$anchor3,text_16)},$$slots:{default:!0}});node_18=sibling(node_17,2);InfoNote(node_18,{notice:!0,get visible(){return get2(connectionPathResetNotice)},children:($$anchor3,$$slotProps2)=>{next();var text_17=text();template_effect($02=>set_text(text_17,$02),[()=>$msg("TURN relay only requires at least one valid TURN server URL. Connection path has been restored to Automatic.")]);append($$anchor3,text_17)},$$slots:{default:!0}});append($$anchor2,fragment_9)},$$slots:{default:!0}})}node_19=sibling(node_13,2);{let $0=user_derived(()=>$msg("Advanced Settings"));ExtraItems(node_19,{get title(){return get2($0)},children:($$anchor2,$$slotProps)=>{var node_21,node_22,node_23,node_24,fragment_13=root_104(),node_20=first_child(fragment_13);InfoNote(node_20,{children:($$anchor3,$$slotProps2)=>{next();var text_18=text();template_effect($02=>set_text(text_18,$02),[()=>$msg("TURN server settings are only necessary if you are behind a strict NAT or firewall that prevents direct P2P connections. In most cases, you can leave these fields blank.")]);append($$anchor3,text_18)},$$slots:{default:!0}});node_21=sibling(node_20,2);InfoNote(node_21,{warning:!0,children:($$anchor3,$$slotProps2)=>{var fragment_15,text_19,a_1,text_20;next();fragment_15=root_1111();text_19=first_child(fragment_15);a_1=sibling(text_19);text_20=child(a_1,!0);reset(a_1);next();template_effect(($02,$1)=>{set_text(text_19,`${null!=$02?$02:""} `);set_text(text_20,$1)},[()=>$msg("TURN relays the encrypted WebRTC connection only when a direct path cannot be established. A TURN provider cannot read encrypted Vault contents, but it can observe connection metadata and traffic volume. Use a provider you trust."),()=>$msg("Learn more about signalling and TURN")]);append($$anchor3,fragment_15)},$$slots:{default:!0}});node_22=sibling(node_21,2);{let $02=user_derived(()=>$msg("TURN Server URLs (comma-separated)"));InputRow(node_22,{get label(){return get2($02)},children:($$anchor3,$$slotProps2)=>{var textarea=root_126();remove_textarea_child(textarea);bind_value(textarea,()=>syncSetting.P2P_turnServers,$$value=>syncSetting.P2P_turnServers=$$value);append($$anchor3,textarea)},$$slots:{default:!0}})}node_23=sibling(node_22,2);{let $02=user_derived(()=>$msg("TURN Username"));InputRow(node_23,{get label(){return get2($02)},children:($$anchor3,$$slotProps2)=>{var input_6=root_134();remove_input_defaults(input_6);template_effect($03=>set_attribute2(input_6,"placeholder",$03),[()=>$msg("Enter TURN username")]);bind_value(input_6,()=>syncSetting.P2P_turnUsername,$$value=>syncSetting.P2P_turnUsername=$$value);append($$anchor3,input_6)},$$slots:{default:!0}})}node_24=sibling(node_23,2);{let $02=user_derived(()=>$msg("TURN Credential"));InputRow(node_24,{get label(){return get2($02)},children:($$anchor3,$$slotProps2)=>{{let $03=user_derived(()=>$msg("Enter TURN credential"));Password($$anchor3,{name:"p2p-turn-credential",get placeholder(){return get2($03)},get value(){return syncSetting.P2P_turnCredential},set value($$value){syncSetting.P2P_turnCredential=$$value}})}},$$slots:{default:!0}})}append($$anchor2,fragment_13)},$$slots:{default:!0}})}node_25=sibling(node_19,2);{let $0=user_derived(()=>""!==get2(error));InfoNote(node_25,{error:!0,get visible(){return get2($0)},children:($$anchor2,$$slotProps)=>{next();var text_21=text();template_effect(()=>set_text(text_21,get2(error)));append($$anchor2,text_21)},$$slots:{default:!0}})}node_26=sibling(node_25,2);consequent=$$anchor2=>{var text_22=text();template_effect($0=>set_text(text_22,$0),[()=>$msg("Checking connection... Please wait.")]);append($$anchor2,text_22)};alternate=$$anchor2=>{UserDecisions($$anchor2,{children:($$anchor3,$$slotProps)=>{var node_28,node_29,fragment_20=root_143(),node_27=first_child(fragment_20);let $0=user_derived(()=>$msg("Test Settings and Continue")),$1=user_derived(()=>!get2(canProceed));Decision(node_27,{get title(){return get2($0)},important:!0,get disabled(){return get2($1)},commit:()=>checkAndCommit()});node_28=sibling(node_27,2);{let $0=user_derived(()=>$msg("Continue anyway"));Decision(node_28,{get title(){return get2($0)},commit:()=>commit()})}node_29=sibling(node_28,2);{let $0=user_derived(()=>$msg("Cancel"));Decision(node_29,{get title(){return get2($0)},commit:()=>cancel()})}append($$anchor3,fragment_20)},$$slots:{default:!0}})};if_block(node_26,$$render=>{get2(processing)?$$render(consequent):$$render(alternate,-1)});append($$anchor,fragment);pop()}function SetupRemoteE2EE($$anchor,$$props){function commit(){$$props.setResult(pickEncryptionSettings(encryptionSettings))}var fragment,node,node_1,node_2,node_4,node_5,node_6,node_7,node_8,node_12,node_13;push($$props,!0);let default_encryption={encrypt:!0,passphrase:"",E2EEAlgorithm:DEFAULT_SETTINGS.E2EEAlgorithm,usePathObfuscation:!0},encryptionSettings=proxy({...default_encryption});onMount(()=>{if($$props.getInitialData){const initialData=$$props.getInitialData();initialData&&copyTo(initialData,encryptionSettings)}});let e2eeValid=user_derived(()=>!encryptionSettings.encrypt||encryptionSettings.passphrase.trim().length>=1);fragment=root_86();node=first_child(fragment);{let $0=user_derived(()=>$msg("End-to-End Encryption"));DialogHeader(node,{get title(){return get2($0)}})}node_1=sibling(node,2);Guidance(node_1,{children:($$anchor2,$$slotProps)=>{next();var text2=text();template_effect($0=>set_text(text2,$0),[()=>$msg("Please configure your end-to-end encryption settings.")]);append($$anchor2,text2)},$$slots:{default:!0}});node_2=sibling(node_1,2);{let $0=user_derived(()=>$msg("End-to-End Encryption"));InputRow(node_2,{get label(){return get2($0)},children:($$anchor2,$$slotProps)=>{var node_3,fragment_2=root33(),input=first_child(fragment_2);remove_input_defaults(input);node_3=sibling(input,2);{let $02=user_derived(()=>$msg("Enter your passphrase")),$1=user_derived(()=>!encryptionSettings.encrypt);Password(node_3,{name:"e2ee-passphrase",get placeholder(){return get2($02)},get disabled(){return get2($1)},get required(){return encryptionSettings.encrypt},get value(){return encryptionSettings.passphrase},set value($$value){encryptionSettings.passphrase=$$value}})}bind_checked(input,()=>encryptionSettings.encrypt,$$value=>encryptionSettings.encrypt=$$value);append($$anchor2,fragment_2)},$$slots:{default:!0}})}node_4=sibling(node_2,2);{let $0=user_derived(()=>$msg("Strongly Recommended"));InfoNote(node_4,{get title(){return get2($0)},children:($$anchor2,$$slotProps)=>{var fragment_3,text_1,text_2;next();fragment_3=root_127();text_1=first_child(fragment_3);text_2=sibling(text_1,2);template_effect(($02,$1)=>{set_text(text_1,`${null!=$02?$02:""} `);set_text(text_2,` ${null!=$1?$1:""}`)},[()=>$msg("Enabling end-to-end encryption ensures that your data is encrypted on your device before being sent to the remote server. This means that even if someone gains access to the server, they won't be able to read your data without the passphrase. Make sure to remember your passphrase, as it will be required to decrypt your data on other devices."),()=>$msg("Also, please note that if you are using Peer-to-Peer synchronization, this configuration will be used when you switch to other methods and connect to a remote server in the future.")]);append($$anchor2,fragment_3)},$$slots:{default:!0}})}node_5=sibling(node_4,2);InfoNote(node_5,{warning:!0,children:($$anchor2,$$slotProps)=>{next();var text_3=text();template_effect($0=>set_text(text_3,$0),[()=>$msg("This setting must be the same even when connecting to multiple synchronisation destinations.")]);append($$anchor2,text_3)},$$slots:{default:!0}});node_6=sibling(node_5,2);{let $0=user_derived(()=>$msg("Obfuscate Properties"));InputRow(node_6,{get label(){return get2($0)},children:($$anchor2,$$slotProps)=>{var input_1=root_215();remove_input_defaults(input_1);template_effect(()=>input_1.disabled=!encryptionSettings.encrypt);bind_checked(input_1,()=>encryptionSettings.usePathObfuscation,$$value=>encryptionSettings.usePathObfuscation=$$value);append($$anchor2,input_1)},$$slots:{default:!0}})}node_7=sibling(node_6,2);InfoNote(node_7,{children:($$anchor2,$$slotProps)=>{next();var text_4=text();template_effect($0=>set_text(text_4,$0),[()=>$msg("Obfuscating properties (e.g., path of file, size, creation and modification dates) adds an additional layer of security by making it harder to identify the structure and names of your files and folders on the remote server. This helps protect your privacy and makes it more difficult for unauthorized users to infer information about your data.")]);append($$anchor2,text_4)},$$slots:{default:!0}});node_8=sibling(node_7,2);{let $0=user_derived(()=>$msg("Advanced"));ExtraItems(node_8,{get title(){return get2($0)},children:($$anchor2,$$slotProps)=>{var node_10,node_11,fragment_6=root_57(),node_9=first_child(fragment_6);let $02=user_derived(()=>$msg("Encryption Algorithm"));InputRow(node_9,{get label(){return get2($02)},children:($$anchor3,$$slotProps2)=>{var select=root_47();each(select,21,()=>Object.values(E2EEAlgorithms),index,($$anchor4,alg)=>{var option_value,option=root_313(),text_5=child(option,!0);reset(option);option_value={};template_effect(()=>{var _a13,_b6;set_text(text_5,null!=(_a13=E2EEAlgorithmNames[get2(alg)])?_a13:get2(alg));option_value!==(option_value=get2(alg))&&(option.value=null!=(_b6=option.__value=get2(alg))?_b6:"")});append($$anchor4,option)});reset(select);template_effect(()=>select.disabled=!encryptionSettings.encrypt);bind_select_value(select,()=>encryptionSettings.E2EEAlgorithm,$$value=>encryptionSettings.E2EEAlgorithm=$$value);append($$anchor3,select)},$$slots:{default:!0}});node_10=sibling(node_9,2);InfoNote(node_10,{children:($$anchor3,$$slotProps2)=>{next();var text_6=text();template_effect($02=>set_text(text_6,$02),[()=>$msg("In most cases, you should stick with the default algorithm (${algorithm}), This setting is only required if you have an existing Vault encrypted in a different format.",{algorithm:E2EEAlgorithmNames[DEFAULT_SETTINGS.E2EEAlgorithm]})]);append($$anchor3,text_6)},$$slots:{default:!0}});node_11=sibling(node_10,2);InfoNote(node_11,{warning:!0,children:($$anchor3,$$slotProps2)=>{next();var text_7=text();template_effect($02=>set_text(text_7,$02),[()=>$msg("Changing the encryption algorithm will prevent access to any data previously encrypted with a different algorithm. Ensure that all your devices are configured to use the same algorithm to maintain access to your data.")]);append($$anchor3,text_7)},$$slots:{default:!0}});append($$anchor2,fragment_6)},$$slots:{default:!0}})}node_12=sibling(node_8,2);InfoNote(node_12,{warning:!0,children:($$anchor2,$$slotProps)=>{var p_1,text_9,text_10,fragment_9=root_67(),p2=first_child(fragment_9),text_8=child(p2,!0);reset(p2);p_1=sibling(p2,2);text_9=child(p_1);text_10=sibling(text_9,3);reset(p_1);template_effect(($0,$1,$2)=>{set_text(text_8,$0);set_text(text_9,`${null!=$1?$1:""} `);set_text(text_10,` ${null!=$2?$2:""}`)},[()=>$msg("Please be aware that the End-to-End Encryption passphrase is not validated until the synchronisation process actually commences. This is a security measure designed to protect your data."),()=>$msg("Therefore, we ask that you exercise extreme caution when configuring server information manually. If an incorrect passphrase is entered, the data on the server will become corrupted."),()=>$msg("Please understand that this is intended behaviour.")]);append($$anchor2,fragment_9)},$$slots:{default:!0}});node_13=sibling(node_12,2);UserDecisions(node_13,{children:($$anchor2,$$slotProps)=>{var node_15,fragment_10=root_76(),node_14=first_child(fragment_10);let $0=user_derived(()=>$msg("Proceed")),$1=user_derived(()=>!get2(e2eeValid));Decision(node_14,{get title(){return get2($0)},important:!0,get disabled(){return get2($1)},commit:()=>commit()});node_15=sibling(node_14,2);{let $0=user_derived(()=>$msg("Cancel"));Decision(node_15,{get title(){return get2($0)},commit:()=>$$props.setResult(TYPE_CANCELLED)})}append($$anchor2,fragment_10)},$$slots:{default:!0}});append($$anchor,fragment);pop()}function encodeSettingsToQRCodeData(settings){const fullIndexes=Object.entries(KeyIndexOfSettings);let maxIndex=0;for(const[,index6]of fullIndexes)index6>=0&&index6>maxIndex&&(maxIndex=index6);const settingArr=new Array(maxIndex+1).fill(void 0);for(const[settingKey,index6]of fullIndexes){const settingValue=settings[settingKey];index6<0||(settingArr[index6]=settingValue)}return encodeAnyArray(settingArr)}function decodeSettingsFromQRCodeData(qr){const settingArr=decodeAnyArray(qr),fullIndexes=Object.entries(KeyIndexOfSettings),newSettings={...DEFAULT_SETTINGS},skippedSettings=[];for(const[settingKey,index6]of fullIndexes){if(index6<0)continue;if(index6>=settingArr.length){skippedSettings.push(`${settingKey} (index ${index6})`);continue}const settingValue=settingArr[index6];newSettings[settingKey]=settingValue}skippedSettings.length>0&&Logger(`Warning: ${skippedSettings.length} settings were skipped during QR decode (array length: ${settingArr.length}): ${skippedSettings.slice(0,5).join(", ")}${skippedSettings.length>5?"...":""}`,LOG_LEVEL_VERBOSE);return newSettings}function encodeQR(settingString,format2){const tryEncode=data=>{const qr=(0,import_qrcode_generator.default)(0,"L");qr.addData(data);qr.make();return 0===format2?qr.createSvgTag(3):1===format2?qr.createASCII(3):""},uri=`${configURIBaseQR}${encodeURIComponent(settingString)}`;try{return tryEncode(uri)}catch(ex){Logger("QR Code size exceeded, switching to aggregator mode",LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_VERBOSE);const id=Math.random().toString(36).substring(2,10),data=encodeURIComponent(settingString),chunkSize2=2e3,total=Math.ceil(data.length/chunkSize2),parts=[];for(let i3=0;i3<total;i3++){const chunk=data.substring(i3*chunkSize2,(i3+1)*chunkSize2),partUri=`${AGGREGATOR_URL}#id=${id}&n=${total}&i=${i3}&d=${chunk}`;try{parts.push(tryEncode(partUri))}catch(ex2){Logger(`Failed to encode split QR Code (${(null==ex2?void 0:ex2.message)||String(ex2)})`,LOG_LEVEL_NOTICE);return""}}return{total,parts}}}async function encodeSettingsToSetupURI(settingString,passphrase,removeProperties=["pluginSyncExtendedSetting"],skipDefaultValue=!1){const setting={...settingString};if(skipDefaultValue){const keys3=Object.keys(setting);for(const k2 of keys3)JSON.stringify(k2 in setting?setting[k2]:"")==JSON.stringify(k2 in DEFAULT_SETTINGS?DEFAULT_SETTINGS[k2]:"*")&&delete setting[k2]}for(const prop2 of[...removeProperties])delete setting[prop2];for(const prop2 of necessaryErasureProperties)setting[prop2]="";const encryptedSetting=encodeURIComponent(await encryptString(JSON.stringify(setting),passphrase)),uri=`${configURIBase}${encryptedSetting} `;return uri}function applySettingsWithScheduledInitialisation(scheduler,mode,applySettings){return"fetch"===mode?scheduler.scheduleFetch(applySettings):scheduler.scheduleRebuild(applySettings)}async function applySettingsAndFetchOnActivation(scheduler,wasConfigured,willBeConfigured,applySettings){if(!wasConfigured&&willBeConfigured)return await applySettingsWithScheduledInitialisation(scheduler,"fetch",applySettings);await applySettings();return!0}function isP2PMainRemote(settings){var _a13,_b6;if(settings.remoteType===REMOTE_P2P)return!0;const activeId=null==(_a13=settings.activeConfigurationId)?void 0:_a13.trim(),activeConfiguration=activeId?null==(_b6=settings.remoteConfigurations)?void 0:_b6[activeId]:void 0;if(!activeConfiguration)return!1;try{return"p2p"===ConnectionStringParser.parse(activeConfiguration.uri).type}catch(e3){return!1}}function copySettingsForRemoteProfileUpdate(settings){var _a13;return{...settings,remoteConfigurations:{...null!=(_a13=settings.remoteConfigurations)?_a13:{}}}}function syncActivatedRemoteSettings(target,source2){Object.assign(target,{remoteType:source2.remoteType,activeConfigurationId:source2.activeConfigurationId,...pickBucketSyncSettings(source2),...pickCouchDBSyncSettings(source2),...pickP2PSyncSettings(source2)})}function getSettingsFromEditingSettings(editingSettings){const workObj={...editingSettings},keys3=Object.keys(OnDialogSettingsDefault);for(const k2 of keys3)delete workObj[k2];return workObj}function createRemoteConfigurationId2(){return`remote-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function cloneRemoteConfigurations(configs){return Object.fromEntries(Object.entries(configs||{}).map(([id,config])=>[id,{...config}]))}function serializeRemoteConfiguration(settings){return settings.remoteType===REMOTE_MINIO?ConnectionStringParser.serialize({type:"s3",settings}):settings.remoteType===REMOTE_P2P?ConnectionStringParser.serialize({type:"p2p",settings}):ConnectionStringParser.serialize({type:"couchdb",settings})}function setEmojiButton(button,emoji,tooltip){button.setButtonText(emoji);button.setTooltip(tooltip,{delay:10,placement:"top"});button.buttonEl.addClass("mod-muted");return button}function suggestRemoteConfigurationName2(parsed){if("couchdb"===parsed.type)try{const url=new URL(parsed.settings.couchDB_URI);return`CouchDB ${url.host}`}catch(e3){return"Imported CouchDB"}return"s3"===parsed.type?`S3 ${parsed.settings.bucket||parsed.settings.endpoint}`:`P2P ${parsed.settings.P2P_roomID||"Remote"}`}function paneRemoteConfig(paneEl,{addPanel}){{const E2EEInitialProps={info:getE2EEConfigSummary({...this.editingSettings})},E2EESummaryWritable=writable(E2EEInitialProps),updateE2EESummary=()=>{E2EESummaryWritable.set({info:getE2EEConfigSummary(this.editingSettings)})};addPanel(paneEl,"E2EE Configuration",()=>{}).then(paneEl2=>{const infoPanel=new SveltePanel(InfoPanel,paneEl2,E2EESummaryWritable);this.lifetimeComponent.register(()=>infoPanel.destroy());const setupButton=setSettingAdditionalActionsState(new LiveSyncSetting(paneEl2).setName("Configure E2EE"));setupButton.addButton(button=>setButtonDestructiveState(button).onClick(async()=>{const setupManager=this.core.getModule(SetupManager),originalSettings=getSettingsFromEditingSettings(this.editingSettings);await setupManager.onlyE2EEConfiguration("unknown",originalSettings);updateE2EESummary()}).setButtonText("Configure")).addButton(button=>setButtonDestructiveState(setButtonAdditionalActionState(button)).onClick(async()=>{const setupManager=this.core.getModule(SetupManager),originalSettings=getSettingsFromEditingSettings(this.editingSettings);await setupManager.onConfigureManually(originalSettings,"unknown");updateE2EESummary()}).setButtonText("Configure And Change Remote"));updateE2EESummary()})}addPanel(paneEl,$msg("Connection settings"),()=>{}).then(paneEl2=>{const actions=new LiveSyncSetting(paneEl2).setName($msg("Saved connections")),listContainer=paneEl2.createDiv({cls:"sls-remote-list"}),syncRemoteConfigurationBuffers=()=>{const currentConfigs=cloneRemoteConfigurations(this.core.settings.remoteConfigurations);this.editingSettings.remoteConfigurations=currentConfigs;this.editingSettings.activeConfigurationId=this.core.settings.activeConfigurationId;if(this.initialSettings){this.initialSettings.remoteConfigurations=cloneRemoteConfigurations(currentConfigs);this.initialSettings.activeConfigurationId=this.core.settings.activeConfigurationId}},persistRemoteConfigurations=async(synchroniseActiveRemote=!1)=>{await this.services.setting.updateSettings(currentSettings=>{currentSettings.remoteConfigurations=cloneRemoteConfigurations(this.editingSettings.remoteConfigurations);currentSettings.activeConfigurationId=this.editingSettings.activeConfigurationId;if(synchroniseActiveRemote&&currentSettings.activeConfigurationId){const activated=activateRemoteConfiguration(currentSettings,currentSettings.activeConfigurationId);if(activated)return activated}return currentSettings},!0);if(synchroniseActiveRemote){syncActivatedRemoteSettings(this.editingSettings,this.core.settings);this.initialSettings&&syncActivatedRemoteSettings(this.initialSettings,this.core.settings);await this.saveAllDirtySettings()}syncRemoteConfigurationBuffers();this.requestUpdate()},runRemoteSetup=async(baseSettings,remoteType)=>{const setupManager=this.core.getModule(SetupManager),dialogManager=setupManager.dialogManager;let targetRemoteType=remoteType;if(void 0===targetRemoteType){const method=await dialogManager.openWithExplicitCancel(SetupRemote);if("cancelled"===method)return!1;targetRemoteType="bucket"===method?REMOTE_MINIO:"p2p"===method?REMOTE_P2P:REMOTE_COUCHDB}if(targetRemoteType===REMOTE_MINIO){const bucketConf=await dialogManager.openWithExplicitCancel(SetupRemoteBucket,baseSettings);return"cancelled"!==bucketConf&&"object"==typeof bucketConf&&{...baseSettings,...bucketConf,remoteType:REMOTE_MINIO}}if(targetRemoteType===REMOTE_P2P){const p2pConf=await dialogManager.openWithExplicitCancel(SetupRemoteP2P,baseSettings);return"cancelled"!==p2pConf&&"object"==typeof p2pConf&&{...baseSettings,...p2pConf,remoteType:REMOTE_P2P}}const couchConf=await dialogManager.openWithExplicitCancel(SetupRemoteCouchDB,{settings:baseSettings,mode:"settings"});return"cancelled"!==couchConf&&"object"==typeof couchConf&&{...baseSettings,...couchConf,remoteType:REMOTE_COUCHDB}},createBaseRemoteSettings=()=>({...DEFAULT_SETTINGS,...getSettingsFromEditingSettings(this.editingSettings)}),createNewRemoteSettings=()=>({...DEFAULT_SETTINGS,encrypt:this.editingSettings.encrypt,usePathObfuscation:this.editingSettings.usePathObfuscation,passphrase:this.editingSettings.passphrase,configPassphraseStore:this.editingSettings.configPassphraseStore}),addRemoteConfiguration=async()=>{const name=await this.services.UI.confirm.askString("Remote name","Display name","New Remote");if(!1===name)return;const nextSettings=await runRemoteSetup(createNewRemoteSettings());if(!nextSettings)return;const id=createRemoteConfigurationId2(),configs=cloneRemoteConfigurations(this.editingSettings.remoteConfigurations);configs[id]={id,name:name.trim()||"New Remote",uri:serializeRemoteConfiguration(nextSettings),isEncrypted:!1};this.editingSettings.remoteConfigurations=configs;this.editingSettings.activeConfigurationId||(this.editingSettings.activeConfigurationId=id);await persistRemoteConfigurations(this.editingSettings.activeConfigurationId===id);refreshList()},importRemoteConfiguration=async()=>{const importedURI=await this.services.UI.confirm.askString("Import connection","Paste a connection string","");if(!1===importedURI)return;const trimmedURI=importedURI.trim();if(""===trimmedURI)return;let parsed;try{parsed=ConnectionStringParser.parse(trimmedURI)}catch(ex){this.services.API.addLog("Failed to import remote configuration!",LOG_LEVEL_NOTICE);this.services.API.addLog(ex,LOG_LEVEL_VERBOSE);return}const defaultName=suggestRemoteConfigurationName2(parsed),name=await this.services.UI.confirm.askString("Remote name","Display name",defaultName);if(!1===name)return;const id=createRemoteConfigurationId2(),configs=cloneRemoteConfigurations(this.editingSettings.remoteConfigurations);configs[id]={id,name:name.trim()||defaultName,uri:ConnectionStringParser.serialize(parsed),isEncrypted:!1};this.editingSettings.remoteConfigurations=configs;this.editingSettings.activeConfigurationId||(this.editingSettings.activeConfigurationId=id);await persistRemoteConfigurations(this.editingSettings.activeConfigurationId===id);refreshList()};actions.addButton(button=>setEmojiButton(button,"","Add new connection").onClick(async()=>{await addRemoteConfiguration()}));actions.addButton(button=>setEmojiButton(button,"📥","Import connection").onClick(async()=>{await importRemoteConfiguration()}));const refreshList=()=>{listContainer.empty();const configs=this.editingSettings.remoteConfigurations||{};for(const config of Object.values(configs)){const row=new LiveSyncSetting(listContainer).setName(config.name).setDesc(config.uri.split("@").pop()||"");if(config.id===this.editingSettings.activeConfigurationId){row.nameEl.addClass("sls-active-remote-name");row.nameEl.appendText(" (Active)")}row.addButton(btn=>setEmojiButton(btn,"🔧","Configure").onClick(async()=>{let parsed;try{parsed=ConnectionStringParser.parse(config.uri)}catch(ex){this.services.API.addLog(`Failed to parse remote configuration '${config.id}' for editing!`,LOG_LEVEL_NOTICE);this.services.API.addLog(ex,LOG_LEVEL_VERBOSE);return}const workSettings=createBaseRemoteSettings();"couchdb"===parsed.type?workSettings.remoteType=REMOTE_COUCHDB:"s3"===parsed.type?workSettings.remoteType=REMOTE_MINIO:workSettings.remoteType=REMOTE_P2P;Object.assign(workSettings,parsed.settings);const nextSettings=await runRemoteSetup(workSettings,workSettings.remoteType);if(!nextSettings)return;const nextConfigs=cloneRemoteConfigurations(this.editingSettings.remoteConfigurations);nextConfigs[config.id]={...config,uri:serializeRemoteConfiguration(nextSettings),isEncrypted:!1};this.editingSettings.remoteConfigurations=nextConfigs;await persistRemoteConfigurations(config.id===this.editingSettings.activeConfigurationId);refreshList()}));row.addButton(btn=>btn.setButtonText("✅").setTooltip("Activate",{delay:10,placement:"top"}).setDisabled(config.id===this.editingSettings.activeConfigurationId).onClick(async()=>{this.editingSettings.activeConfigurationId=config.id;await persistRemoteConfigurations(!0);refreshList()}));row.addButton(btn=>setEmojiButton(btn,"…","More actions").onClick(()=>{const menu=(new import_obsidian.Menu).addItem(item=>{item.setTitle("🪪 Rename").onClick(async()=>{const nextName=await this.services.UI.confirm.askString("Remote name","Display name",config.name);if(!1===nextName)return;const nextConfigs=cloneRemoteConfigurations(this.editingSettings.remoteConfigurations);nextConfigs[config.id]={...config,name:nextName.trim()||config.name};this.editingSettings.remoteConfigurations=nextConfigs;await persistRemoteConfigurations();refreshList()})}).addItem(item=>{item.setTitle("📤 Export").onClick(async()=>{await this.services.UI.promptCopyToClipboard(`Remote configuration: ${config.name}`,config.uri)})}).addItem(item=>{item.setTitle("🧬 Duplicate").onClick(async()=>{const nextName=await this.services.UI.confirm.askString("Duplicate remote","Display name",`${config.name} (Copy)`);if(!1===nextName)return;const nextId=createRemoteConfigurationId2(),nextConfigs=cloneRemoteConfigurations(this.editingSettings.remoteConfigurations);nextConfigs[nextId]={...config,id:nextId,name:nextName.trim()||`${config.name} (Copy)`};this.editingSettings.remoteConfigurations=nextConfigs;await persistRemoteConfigurations();refreshList()})}).addSeparator().addItem(item=>{item.setTitle("📡 Fetch remote settings").onClick(async()=>{let parsed;try{parsed=ConnectionStringParser.parse(config.uri)}catch(ex){this.services.API.addLog(`Failed to parse remote configuration '${config.id}' for fetching settings!`,LOG_LEVEL_NOTICE);this.services.API.addLog(ex,LOG_LEVEL_VERBOSE);return}const workSettings=createBaseRemoteSettings();"couchdb"===parsed.type?workSettings.remoteType=REMOTE_COUCHDB:"s3"===parsed.type?workSettings.remoteType=REMOTE_MINIO:workSettings.remoteType=REMOTE_P2P;Object.assign(workSettings,parsed.settings);const newTweaks=await this.services.tweakValue.checkAndAskUseRemoteConfiguration(workSettings);if(!1!==newTweaks.result){this.editingSettings={...this.editingSettings,...newTweaks.result};this.requestUpdate()}})}).addSeparator().addItem(item=>{item.setTitle($msg("🗑 Delete")).onClick(async()=>{const confirmed=await this.services.UI.confirm.askYesNoDialog($msg("Delete remote configuration '${name}'?",{name:config.name}),{title:$msg("Delete Remote Configuration"),defaultOption:"No"});if("yes"!==confirmed)return;const nextConfigs=cloneRemoteConfigurations(this.editingSettings.remoteConfigurations);delete nextConfigs[config.id];this.editingSettings.remoteConfigurations=nextConfigs;let syncActiveRemote=!1;if(this.editingSettings.activeConfigurationId===config.id){const nextActiveId=Object.keys(nextConfigs)[0]||"";this.editingSettings.activeConfigurationId=nextActiveId;syncActiveRemote=""!==nextActiveId}await persistRemoteConfigurations(syncActiveRemote);refreshList()})}),rect=btn.buttonEl.getBoundingClientRect();menu.showAtPosition({x:rect.left,y:rect.bottom})}))}};refreshList()});addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleNotification"),()=>{}).then(paneEl2=>{new LiveSyncSetting(paneEl2).autoWireNumeric("notifyThresholdOfRemoteStorageSize",{})})}function MultipleRegExpControl($$anchor,$$props){function revert(){patterns([...originals()])}function checkRegExp(pattern){return isValidRegExp(pattern)?"✔":"⚠"}function remove(idx2){patterns(patterns()[idx2]="",!0)}function add(){patterns([...patterns(),""])}var ul,node,li_1,label_1,button_1,li_2,button_2,button_3;push($$props,!1);append_styles($$anchor,$$css10);const statusName=mutable_source(),modified=mutable_source(),isInvertedExp=mutable_source();let patterns=prop($$props,"patterns",28,()=>[]),originals=prop($$props,"originals",24,()=>[]),apply2=prop($$props,"apply",8,_=>Promise.resolve());legacy_pre_effect(()=>deep_read_state(patterns()),()=>{set(statusName,patterns().map(e3=>checkRegExp(e3)))});legacy_pre_effect(()=>(deep_read_state(patterns()),deep_read_state(originals())),()=>{set(modified,patterns().map((e3,i3)=>{var _a13;return e3!=(null!==(_a13=null===originals()||void 0===originals()?void 0:originals()[i3])&&void 0!==_a13?_a13:"")?"✏ ":""}))});legacy_pre_effect(()=>(deep_read_state(patterns()),isInvertedRegExp),()=>{set(isInvertedExp,patterns().map(e3=>isInvertedRegExp(e3)))});legacy_pre_effect_reset();init();ul=root_128();node=child(ul);each(node,1,patterns,index,($$anchor2,pattern,idx2)=>{var span,text_1,input,button,li=root34(),label2=child(li),text2=child(label2);reset(label2);span=sibling(label2,2);text_1=child(span,!0);reset(span);input=sibling(span,2);remove_input_defaults(input);button=sibling(input,2);reset(li);template_effect($0=>{var _a13,_b6;set_text(text2,`${null!=(_a13=(get2(modified),untrack(()=>get2(modified)[idx2])))?_a13:""}${null!=(_b6=(get2(statusName),untrack(()=>get2(statusName)[idx2])))?_b6:""}`);set_text(text_1,$0);set_class(input,1,clsx2((get2(modified),untrack(()=>get2(modified)[idx2]))),"svelte-9kxeje")},[()=>(get2(isInvertedExp),deep_read_state($msg),untrack(()=>get2(isInvertedExp)[idx2]?$msg("INVERTED"):""))]);bind_value(input,()=>patterns()[idx2],$$value=>(patterns()[idx2]=$$value,invalidate_inner_signals(()=>patterns())));event("click",button,()=>remove(idx2));append($$anchor2,li)});li_1=sibling(node,2);label_1=child(li_1);button_1=child(label_1);reset(label_1);reset(li_1);li_2=sibling(li_1,2);button_2=child(li_2);button_3=sibling(button_2,2);reset(li_2);reset(ul);template_effect(($0,$1)=>{button_2.disabled=$0;button_3.disabled=$1},[()=>(get2(statusName),get2(modified),untrack(()=>get2(statusName).some(e3=>"⚠"===e3)||get2(modified).every(e3=>""===e3))),()=>(get2(statusName),get2(modified),untrack(()=>get2(statusName).some(e3=>"⚠"===e3)||get2(modified).every(e3=>""===e3)))]);event("click",button_1,()=>add());event("click",button_2,()=>apply2()(patterns()));event("click",button_3,()=>revert());append($$anchor,ul);pop()}function paneSelector(paneEl,{addPanel}){addPanel(paneEl,"Normal Files").then(paneEl2=>{const syncFilesSetting=new LiveSyncSetting(paneEl2).setName("Synchronising files").setDesc("(RegExp) Empty to sync all files. Set filter as a regular expression to limit synchronising files."),syncFilesControl=mount(MultipleRegExpControl,{target:syncFilesSetting.controlEl,props:{patterns:splitCustomRegExpList(this.editingSettings.syncOnlyRegEx,"|[]|"),originals:splitCustomRegExpList(this.editingSettings.syncOnlyRegEx,"|[]|"),apply:async newPatterns=>{this.editingSettings.syncOnlyRegEx=constructCustomRegExpList(newPatterns,"|[]|");await this.saveAllDirtySettings();this.requestPageRefresh()}}});this.lifetimeComponent.register(()=>{unmount(syncFilesControl)});const nonSyncFilesSetting=new LiveSyncSetting(paneEl2).setName("Non-Synchronising files").setDesc("(RegExp) If this is set, any changes to local and remote files that match this will be skipped."),nonSyncFilesControl=mount(MultipleRegExpControl,{target:nonSyncFilesSetting.controlEl,props:{patterns:splitCustomRegExpList(this.editingSettings.syncIgnoreRegEx,"|[]|"),originals:splitCustomRegExpList(this.editingSettings.syncIgnoreRegEx,"|[]|"),apply:async newPatterns=>{this.editingSettings.syncIgnoreRegEx=constructCustomRegExpList(newPatterns,"|[]|");await this.saveAllDirtySettings();this.requestPageRefresh()}}});this.lifetimeComponent.register(()=>{unmount(nonSyncFilesControl)});new LiveSyncSetting(paneEl2).autoWireNumeric("syncMaxSizeInMB",{clampMin:0});new LiveSyncSetting(paneEl2).autoWireToggle("useIgnoreFiles");new LiveSyncSetting(paneEl2).autoWireTextArea("ignoreFiles",{onUpdate:visibleOnly(()=>this.isConfiguredAs("useIgnoreFiles",!0))})});addPanel(paneEl,"Hidden Files",void 0,void 0,LEVEL_ADVANCED).then(paneEl2=>{const targetPatternSetting=new LiveSyncSetting(paneEl2).setName("Target patterns").setDesc("Patterns to match files for syncing"),patTarget=splitCustomRegExpList(this.editingSettings.syncInternalFilesTargetPatterns,","),targetPatternControl=mount(MultipleRegExpControl,{target:targetPatternSetting.controlEl,props:{patterns:patTarget,originals:[...patTarget],apply:async newPatterns=>{this.editingSettings.syncInternalFilesTargetPatterns=constructCustomRegExpList(newPatterns,",");await this.saveAllDirtySettings();this.requestPageRefresh()}}});this.lifetimeComponent.register(()=>{unmount(targetPatternControl)});const defaultSkipPattern="\\/node_modules\\/, \\/\\.git\\/, ^\\.git\\/, \\/obsidian-livesync\\/",defaultSkipPatternXPlat=defaultSkipPattern+",\\/workspace$ ,\\/workspace.json$,\\/workspace-mobile.json$",pat=splitCustomRegExpList(this.editingSettings.syncInternalFilesIgnorePatterns,","),patSetting=new LiveSyncSetting(paneEl2).setName("Ignore patterns").setDesc(""),ignorePatternControl=mount(MultipleRegExpControl,{target:patSetting.controlEl,props:{patterns:pat,originals:[...pat],apply:async newPatterns=>{this.editingSettings.syncInternalFilesIgnorePatterns=constructCustomRegExpList(newPatterns,",");await this.saveAllDirtySettings();this.requestPageRefresh()}}});this.lifetimeComponent.register(()=>{unmount(ignorePatternControl)});const addDefaultPatterns=async patterns=>{const oldList=splitCustomRegExpList(this.editingSettings.syncInternalFilesIgnorePatterns,","),newList=splitCustomRegExpList(patterns,","),allSet=new Set([...oldList,...newList]);this.editingSettings.syncInternalFilesIgnorePatterns=constructCustomRegExpList([...allSet],",");await this.saveAllDirtySettings();this.requestPageRefresh()};new LiveSyncSetting(paneEl2).setName("Add default patterns").addButton(button=>{button.setButtonText("Default").onClick(async()=>{await addDefaultPatterns(defaultSkipPattern)})}).addButton(button=>{button.setButtonText("Cross-platform").onClick(async()=>{await addDefaultPatterns(defaultSkipPatternXPlat)})});const overwritePatterns=new LiveSyncSetting(paneEl2).setName("Overwrite patterns").setDesc("Patterns to match files for overwriting instead of merging"),patTarget2=splitCustomRegExpList(this.editingSettings.syncInternalFileOverwritePatterns,","),overwritePatternControl=mount(MultipleRegExpControl,{target:overwritePatterns.controlEl,props:{patterns:patTarget2,originals:[...patTarget2],apply:async newPatterns=>{this.editingSettings.syncInternalFileOverwritePatterns=constructCustomRegExpList(newPatterns,",");await this.saveAllDirtySettings();this.requestPageRefresh()}}});this.lifetimeComponent.register(()=>{unmount(overwritePatternControl)})})}function paneQuickSetup(paneEl,{addPanel}){addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleQuickSetup")).then(panelEl=>{new LiveSyncSetting(panelEl).setName($msg("obsidianLiveSyncSettingTab.nameConnectSetupURI")).setDesc($msg("obsidianLiveSyncSettingTab.descConnectSetupURI")).addButton(button=>{button.setButtonText($msg("obsidianLiveSyncSettingTab.btnUse")).onClick(()=>{this.requestOpenSetupURI()})});new LiveSyncSetting(panelEl).setName($msg("Rerun Onboarding Wizard")).setDesc($msg("Rerun the onboarding wizard to set up Self-hosted LiveSync again.")).addButton(button=>{button.setButtonText($msg("Rerun Wizard")).onClick(async()=>{await this.rerunOnboardingWizard()})});new LiveSyncSetting(panelEl).setName($msg("obsidianLiveSyncSettingTab.nameEnableLiveSync")).setDesc($msg("obsidianLiveSyncSettingTab.descEnableLiveSync")).addOnUpdate(visibleOnly(()=>!this.isConfiguredAs("isConfigured",!0))).addButton(button=>{button.setButtonText($msg("obsidianLiveSyncSettingTab.btnEnable")).onClick(async()=>{await this.enableLiveSyncFromSettings()})})});addPanel(paneEl,`📲 ${$msg("obsidianLiveSyncSettingTab.titleSetupOtherDevices")}`,void 0,visibleOnly(()=>this.isConfiguredAs("isConfigured",!0))).then(panelEl=>{new LiveSyncSetting(panelEl).setName($msg("obsidianLiveSyncSettingTab.nameCopySetupURI")).setDesc($msg("obsidianLiveSyncSettingTab.descCopySetupURI")).addButton(button=>{button.setButtonText($msg("obsidianLiveSyncSettingTab.btnCopy")).onClick(()=>{this.requestCopySetupURI()})});new LiveSyncSetting(panelEl).setName($msg("Setup.ShowQRCode")).setDesc($msg("Setup.ShowQRCode.Desc")).addButton(button=>{button.setButtonText($msg("Setup.ShowQRCode")).onClick(()=>{this.requestShowSetupQRCode()})})})}function paneSyncSettings(paneEl,{addPanel}){addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleSynchronizationPreset")).then(paneEl2=>{const options=this.editingSettings.remoteType==REMOTE_COUCHDB?{NONE:"",LIVESYNC:$msg("obsidianLiveSyncSettingTab.optionLiveSync"),PERIODIC:$msg("obsidianLiveSyncSettingTab.optionPeriodicWithBatch"),DISABLE:$msg("obsidianLiveSyncSettingTab.optionDisableAllAutomatic")}:{NONE:"",PERIODIC:$msg("obsidianLiveSyncSettingTab.optionPeriodicWithBatch"),DISABLE:$msg("obsidianLiveSyncSettingTab.optionDisableAllAutomatic")};new LiveSyncSetting(paneEl2).autoWireDropDown("preset",{options,holdValue:!0}).addButton(button=>{button.setButtonText($msg("obsidianLiveSyncSettingTab.btnApply"));button.onClick(async()=>{await this.saveAllDirtySettings()})});this.addOnSaved("preset",async currentPreset=>{if(""==currentPreset){Logger($msg("obsidianLiveSyncSettingTab.logSelectAnyPreset"),LOG_LEVEL_NOTICE);return}const presetAllDisabled={batchSave:!1,liveSync:!1,periodicReplication:!1,syncOnSave:!1,syncOnEditorSave:!1,syncOnStart:!1,syncOnFileOpen:!1,syncAfterMerge:!1},presetLiveSync={...presetAllDisabled,liveSync:!0},presetPeriodic={...presetAllDisabled,batchSave:!0,periodicReplication:!0,syncOnSave:!1,syncOnEditorSave:!1,syncOnStart:!0,syncOnFileOpen:!0,syncAfterMerge:!0};if("LIVESYNC"==currentPreset){this.editingSettings={...this.editingSettings,...presetLiveSync};Logger($msg("obsidianLiveSyncSettingTab.logConfiguredLiveSync"),LOG_LEVEL_NOTICE)}else if("PERIODIC"==currentPreset){this.editingSettings={...this.editingSettings,...presetPeriodic};Logger($msg("obsidianLiveSyncSettingTab.logConfiguredPeriodic"),LOG_LEVEL_NOTICE)}else{Logger($msg("obsidianLiveSyncSettingTab.logConfiguredDisabled"),LOG_LEVEL_NOTICE);this.editingSettings={...this.editingSettings,...presetAllDisabled}}await this.saveAllDirtySettings();await this.services.control.applySettings();this.requestCatalogueRefresh()})});addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleSynchronizationMethod")).then(paneEl2=>{const onlyOnNonLiveSync=visibleOnly(()=>!this.isConfiguredAs("syncMode","LIVESYNC")),onlyOnPeriodic=visibleOnly(()=>this.isConfiguredAs("syncMode","PERIODIC")),optionsSyncMode=this.editingSettings.remoteType==REMOTE_COUCHDB?{ONEVENTS:$msg("obsidianLiveSyncSettingTab.optionOnEvents"),PERIODIC:$msg("obsidianLiveSyncSettingTab.optionPeriodicAndEvents"),LIVESYNC:$msg("obsidianLiveSyncSettingTab.optionLiveSync")}:{ONEVENTS:$msg("obsidianLiveSyncSettingTab.optionOnEvents"),PERIODIC:$msg("obsidianLiveSyncSettingTab.optionPeriodicAndEvents")};new LiveSyncSetting(paneEl2).autoWireDropDown("syncMode",{options:optionsSyncMode});this.addOnSaved("syncMode",async value=>{this.editingSettings.liveSync=!1;this.editingSettings.periodicReplication=!1;"LIVESYNC"==value?this.editingSettings.liveSync=!0:"PERIODIC"==value&&(this.editingSettings.periodicReplication=!0);await this.saveSettings(["liveSync","periodicReplication"]);await this.services.control.applySettings();this.requestCatalogueRefresh()});new LiveSyncSetting(paneEl2).autoWireNumeric("periodicReplicationInterval",{clampMax:5e3,onUpdate:onlyOnPeriodic});new LiveSyncSetting(paneEl2).autoWireNumeric("syncMinimumInterval",{onUpdate:onlyOnNonLiveSync});new LiveSyncSetting(paneEl2).autoWireToggle("syncOnSave",{onUpdate:onlyOnNonLiveSync});new LiveSyncSetting(paneEl2).autoWireToggle("syncOnEditorSave",{onUpdate:onlyOnNonLiveSync});new LiveSyncSetting(paneEl2).autoWireToggle("syncOnFileOpen",{onUpdate:onlyOnNonLiveSync});new LiveSyncSetting(paneEl2).autoWireToggle("syncOnStart",{onUpdate:onlyOnNonLiveSync});new LiveSyncSetting(paneEl2).autoWireToggle("syncAfterMerge",{onUpdate:onlyOnNonLiveSync});for(const key3 of["syncOnSave","syncOnEditorSave","syncOnFileOpen","syncOnStart","syncAfterMerge"])this.addOnSaved(key3,()=>this.requestCatalogueRefresh());this.services.API.isMobile()||new LiveSyncSetting(paneEl2).autoWireToggle("keepReplicationActiveInBackground",{onUpdate:visibleOnly(()=>this.isConfiguredAs("syncMode","LIVESYNC")||this.isConfiguredAs("syncMode","PERIODIC"))});new LiveSyncSetting(paneEl2).autoWireToggle("allowSleepDuringSynchronisation");this.services.API.isMobile()||new LiveSyncSetting(paneEl2).autoWireToggle("allowSleepDuringSynchronisationOnDesktop")});addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleUpdateThinning"),void 0,visibleOnly(()=>!this.isConfiguredAs("syncMode","LIVESYNC"))).then(paneEl2=>{new LiveSyncSetting(paneEl2).autoWireToggle("batchSave");new LiveSyncSetting(paneEl2).autoWireNumeric("batchSaveMinimumDelay",{acceptZero:!0,onUpdate:visibleOnly(()=>this.isConfiguredAs("batchSave",!0))});new LiveSyncSetting(paneEl2).autoWireNumeric("batchSaveMaximumDelay",{acceptZero:!0,onUpdate:visibleOnly(()=>this.isConfiguredAs("batchSave",!0))})});addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleDeletionPropagation"),void 0,void 0,LEVEL_ADVANCED).then(paneEl2=>{new LiveSyncSetting(paneEl2).autoWireToggle("doNotDeleteFolder")});addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleConflictResolution"),void 0,void 0,LEVEL_ADVANCED).then(paneEl2=>{new LiveSyncSetting(paneEl2).autoWireToggle("resolveConflictsByNewerFile");new LiveSyncSetting(paneEl2).autoWireToggle("checkConflictOnlyOnOpen");new LiveSyncSetting(paneEl2).autoWireToggle("showMergeDialogOnlyOnActive")});addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleSyncSettingsViaMarkdown"),void 0,void 0,LEVEL_ADVANCED).then(paneEl2=>{new LiveSyncSetting(paneEl2).autoWireText("settingSyncFile",{holdValue:!0}).addApplyButton(["settingSyncFile"]);new LiveSyncSetting(paneEl2).autoWireToggle("writeCredentialsForSettingSync");new LiveSyncSetting(paneEl2).autoWireToggle("notifyAllSettingSyncFile")});addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleHiddenFiles"),void 0,void 0,LEVEL_ADVANCED).then(paneEl2=>{const LABEL_ENABLED=$msg("obsidianLiveSyncSettingTab.labelEnabled"),LABEL_DISABLED=$msg("obsidianLiveSyncSettingTab.labelDisabled"),hiddenFileSyncSetting=new LiveSyncSetting(paneEl2).setName($msg("obsidianLiveSyncSettingTab.nameHiddenFileSynchronization")),hiddenFileSyncSettingEl=hiddenFileSyncSetting.settingEl,hiddenFileSyncSettingDiv=hiddenFileSyncSettingEl.createDiv("");hiddenFileSyncSettingDiv.innerText=this.editingSettings.syncInternalFiles?LABEL_ENABLED:LABEL_DISABLED;this.editingSettings.syncInternalFiles?new LiveSyncSetting(paneEl2).setName($msg("obsidianLiveSyncSettingTab.nameDisableHiddenFileSync")).addButton(button=>{button.setButtonText($msg("obsidianLiveSyncSettingTab.btnDisable")).onClick(async()=>{this.editingSettings.syncInternalFiles=!1;await this.saveAllDirtySettings();this.requestPageRefresh()})}):new LiveSyncSetting(paneEl2).setName($msg("obsidianLiveSyncSettingTab.nameEnableHiddenFileSync")).addButton(button=>{button.setButtonText("Merge").onClick(async()=>{this.closeSetting();await this.services.setting.enableOptionalFeature("MERGE")})}).addButton(button=>{button.setButtonText("Fetch").onClick(async()=>{this.closeSetting();await this.services.setting.enableOptionalFeature("FETCH")})}).addButton(button=>{button.setButtonText("Overwrite").onClick(async()=>{this.closeSetting();await this.services.setting.enableOptionalFeature("OVERWRITE")})});new LiveSyncSetting(paneEl2).autoWireToggle("suppressNotifyHiddenFilesChange",{});new LiveSyncSetting(paneEl2).autoWireToggle("syncInternalFilesBeforeReplication",{onUpdate:visibleOnly(()=>this.isConfiguredAs("watchInternalFileChanges",!0))});new LiveSyncSetting(paneEl2).autoWireNumeric("syncInternalFilesInterval",{clampMin:10,acceptZero:!0})})}function getSettingsRootGroupEntry(id){return SETTINGS_ROOT_GROUP_CATALOGUE[id]}function createSettingsPageCatalogue(){return[{id:"change-log",name:()=>$msg("obsidianLiveSyncSettingTab.panelChangeLog"),icon:"💬",order:100,level:void 0,content:"custom",legacy:paneChangeLog},{id:"quick-setup",name:()=>$msg("obsidianLiveSyncSettingTab.titleQuickSetup"),icon:"🧙‍♂️",order:110,level:void 0,content:"custom",legacy:paneQuickSetup},{id:"general",name:()=>$msg("obsidianLiveSyncSettingTab.panelGeneralSettings"),icon:"⚙️",order:20,level:void 0,content:"custom",legacy:paneGeneral},{id:"remote-configuration",name:()=>$msg("obsidianLiveSyncSettingTab.panelRemoteConfiguration"),icon:"🛰️",order:0,level:void 0,content:"custom",legacy:paneRemoteConfig},{id:"synchronisation",name:()=>$msg("obsidianLiveSyncSettingTab.titleSyncSettings"),icon:"🔄",order:30,level:void 0,content:"custom",legacy:paneSyncSettings},{id:"selector",name:()=>"Selector",icon:"🚦",order:33,level:LEVEL_ADVANCED,content:"custom",legacy:paneSelector},{id:"customisation-sync",name:()=>"Customisation sync",icon:"🔌",order:60,level:LEVEL_ADVANCED,content:"custom",legacy:paneCustomisationSync},{id:"hatch",name:()=>"Hatch",icon:"🧰",order:50,level:void 0,content:"custom",legacy:paneHatch},{id:"advanced",name:()=>"Advanced",icon:"🔧",order:46,level:LEVEL_ADVANCED,content:"native",legacy:paneAdvanced},{id:"power-users",name:()=>"Power users",icon:"💪",order:47,level:LEVEL_POWER_USER,content:"custom",legacy:panePowerUsers},{id:"patches",name:()=>"Patches",icon:"🩹",order:51,level:LEVEL_EDGE_CASE,content:"custom",legacy:panePatches},{id:"maintenance",name:()=>"Maintenance",icon:"🎛️",order:70,level:void 0,content:"custom",legacy:paneMaintenance},{id:"help",name:()=>$msg("obsidianLiveSyncSettingTab.titleHelpAndTroubleshooting"),icon:"❓",order:90,level:void 0,content:"custom",legacy:paneHelp}]}function toSettingDefinition(spec){const metadata=getConfig2(spec.key);if(!metadata)throw new Error(`Missing translated setting metadata for ${spec.key}`);return toObsidianSettingDefinition(spec,metadata,{valueShouldBeInRange:numberRangeMessage})}function createAdvancedSettingDefinitionGroups(context2){return createAdvancedSettingSpecGroups(context2).map(group4=>({type:"group",heading:group4.heading,items:group4.items.map(toSettingDefinition)}))}function createGeneralSettingDefinitionGroups(context2){return createGeneralSettingSpecGroups(context2).map(group4=>({type:"group",heading:group4.heading,items:group4.items.map(toSettingDefinition)}))}function createExtraMenuSettingDefinitions(){return createExtraMenuSettingSpecGroup().items.map(toSettingDefinition)}function loadDocumentHistoryPreference(app,key3){return!!(0,import_obsidian.requireApiVersion)("1.8.7")&&"1"===app.loadLocalStorage(key3)}function saveDocumentHistoryPreference(app,key3,enabled){(0,import_obsidian.requireApiVersion)("1.8.7")&&app.saveLocalStorage(key3,enabled?"1":null)}async function restoreDocumentHistoryRevision(core,path2,sourceRevision,options={}){var _a13,_b6,_c3;const now3=null!=(_a13=options.now)?_a13:Date.now,isPathValid=null!=(_b6=options.isPathValid)?_b6:()=>!0,source2=await core.databaseFileAccess.fetchEntry(path2,sourceRevision,!0,!0);if(!1===source2)return{status:"source-unavailable"};const current=await core.databaseFileAccess.fetchEntryMeta(path2,void 0,!0);if(!1===current||!current._rev)return{status:"current-unavailable"};const body=readAsBlob(source2),storagePath=stripAllPrefixes(current.path);if(storagePath!==current.path||!isPathValid(storagePath))return{status:"unsupported-path"};const file={name:null!=(_c3=storagePath.split("/").pop())?_c3:storagePath,path:storagePath,stat:{ctime:current.ctime,mtime:now3(),size:body.size,type:"file"},body},revision=await core.databaseFileAccess.storeWithLiveBaseRevision(file,current._rev,!0);if(!1===revision)return{status:"database-write-refused"};try{const reflected=await core.fileHandler.dbToStorageWithSpecificRev(storagePath,revision,!0);if(!reflected)return{status:"stored-not-reflected",path:storagePath,revision}}catch(cause){return{status:"stored-not-reflected",path:storagePath,revision,cause}}try{const conflictsRemain=(await core.databaseFileAccess.getConflictedRevs(storagePath)).length>0;return{status:"restored",path:storagePath,revision,conflictsRemain}}catch(conflictCheckError){return{status:"restored",path:storagePath,revision,conflictsRemain:void 0,conflictCheckError}}}function isImage(path2){const ext2=path2.split(".").splice(-1)[0].toLowerCase();return["png","jpg","jpeg","gif","bmp","webp"].includes(ext2)}function isComparableText(path2){const ext2=path2.split(".").splice(-1)[0].toLowerCase();return isPlainText(path2)||["md","mdx","txt","json"].includes(ext2)}function isComparableTextDecode(path2){const ext2=path2.split(".").splice(-1)[0].toLowerCase();return["json"].includes(ext2)}function readDocument(w2){if(0==w2.data.length)return"";if(isImage(w2.path))return new Uint8Array(decodeBinary(w2.data));if("plain"==w2.type||"plain"==w2.datatype)return getDocData(w2.data);if(isComparableTextDecode(w2.path))return readString(new Uint8Array(decodeBinary(w2.data)));if(isComparableText(w2.path))return getDocData(w2.data);try{return readString(new Uint8Array(decodeBinary(w2.data)))}catch(ex){Logger(ex,LOG_LEVEL_VERBOSE)}return getDocData(w2.data)}function GlobalHistory($$anchor,$$props){function mtimeToDate(mtime){return new Date(mtime).toLocaleString()}function getPath2(entry){return core().services.path.getPath(entry)}async function fetchChanges(){var _a13,_b6,_c3;try{const db=core().localDatabase;let result=[];for await(const docA of db.findAllNormalDocs()){if(docA.mtime<get2(range_from_epoch))continue;if(!isAnyNote(docA))continue;const path2=getPath2(docA),isPlain=isPlainText(docA.path),revs=await db.getRaw(docA._id,{revs_info:!0});let p2;const reversedRevs=(null!==(_a13=revs._revs_info)&&void 0!==_a13?_a13:[]).reverse(),DIFF_DELETE4=-1,DIFF_EQUAL4=0,DIFF_INSERT4=1;for(const revInfo of reversedRevs)if("available"==revInfo.status){const doc=!isPlain&&get2(showDiffInfo)||get2(checkStorageDiff)&&revInfo.rev==docA._rev?await db.getDBEntry(path2,{rev:revInfo.rev},!1,!1,!0):await db.getDBEntryMeta(path2,{rev:revInfo.rev},!0);if(!1===doc)continue;const rev3=revInfo.rev,mtime="mtime"in doc?doc.mtime:0;if(get2(range_from_epoch)>mtime)continue;if(get2(range_to_epoch)<mtime)continue;let diffDetail="";if(get2(showDiffInfo)&&!isPlain){const data=getDocData(doc.data);void 0===p2&&(p2=data);if(p2!=data){const dmp=new import_diff_match_patch.diff_match_patch,diff=dmp.diff_main(p2,data);dmp.diff_cleanupSemantic(diff);p2=data;const pxInit={[DIFF_DELETE4]:0,[DIFF_EQUAL4]:0,[DIFF_INSERT4]:0},px=diff.reduce((p3,c3)=>{var _a14;return{...p3,[c3[0]]:(null!==(_a14=p3[c3[0]])&&void 0!==_a14?_a14:0)+c3[1].length}},pxInit);diffDetail=`-${px[DIFF_DELETE4]}, +${px[DIFF_INSERT4]}`}}const isDeleted2=doc._deleted||(null==doc?void 0:doc.deleted)||!1;isDeleted2&&(diffDetail+=" 🗑️");if(rev3==docA._rev&&get2(checkStorageDiff)){const isExist=await core().storageAccess.isExistsIncludeHidden(stripAllPrefixes(getPath2(docA)));if(isExist){const data=await core().storageAccess.readHiddenFileBinary(stripAllPrefixes(getPath2(docA))),d4=readAsBlob(doc),result2=await isDocContentSame(data,d4);diffDetail+=result2?" ⚖️":" ⚠️"}}const docPath=getPath2(doc),[filename,...pathItems]=docPath.split("/").reverse();let chunksStatus="";if(get2(showChunkCorrected)){const chunks=null!==(_b6=null==doc?void 0:doc.children)&&void 0!==_b6?_b6:[],loadedChunks=await db.allDocsRaw({keys:[...chunks]}),totalCount=loadedChunks.rows.length,errorCount=loadedChunks.rows.filter(e3=>"error"in e3).length;chunksStatus=0==errorCount?`✅ ${totalCount}`:`🔎 ${errorCount} ✅ ${totalCount}`}result.push({id:doc._id,rev:doc._rev,path:docPath,dirname:pathItems.reverse().join("/"),filename,mtime,mtimeDisp:mtimeToDate(mtime),size:null!==(_c3=null==doc?void 0:doc.size)&&void 0!==_c3?_c3:0,isDeleted:isDeleted2,changes:diffDetail,chunks:chunksStatus,isPlain})}}return[...result].sort((a2,b3)=>b3.mtime-a2.mtime)}finally{set(loading,!1)}}async function getHistory(showDiffInfo2,showChunkCorrected2,checkStorageDiff2){set(loading,!0);const newDisplay=[],page=await fetchChanges();newDisplay.push(...page);set(history,[...newDisplay])}function nextWeek(){set(dispDateTo,new Date(get2(range_to_epoch)-timezoneOffset+6048e5).toISOString().split("T")[0])}function prevWeek(){set(dispDateFrom,new Date(get2(range_from_epoch)-timezoneOffset-6048e5).toISOString().split("T")[0])}function showHistory(file,rev3){new DocumentHistoryModal(plugin2().app,plugin2().core,plugin2(),file,void 0,rev3).open()}function openFile(file){plugin2().app.workspace.openLinkText(file,file)}var div,div_1,div_2,input,div_3,input_1,div_4,label2,input_2,span,text2,label_1,input_3,span_1,text_1,label_2,input_4,span_2,text_2,node,consequent,table3,tbody,tr,th,text_4,th_1,text_5,th_2,text_6,th_3,text_7,node_1,consequent_1,tr_1,td3,node_2,consequent_2,alternate,node_3,tr_3,td_6,node_7,consequent_6,alternate_3;push($$props,!1);append_styles($$anchor,$$css11);let plugin2=prop($$props,"plugin",8),core=prop($$props,"core",8),showDiffInfo=mutable_source(!1),showChunkCorrected=mutable_source(!1),checkStorageDiff=mutable_source(!1),range_from_epoch=mutable_source(Date.now()-6048e5),range_to_epoch=mutable_source(Date.now()+1728e5);const timezoneOffset=(new Date).getTimezoneOffset();let dispDateFrom=mutable_source(new Date(get2(range_from_epoch)-timezoneOffset).toISOString().split("T")[0]),dispDateTo=mutable_source(new Date(get2(range_to_epoch)-timezoneOffset).toISOString().split("T")[0]),history=mutable_source([]),loading=mutable_source(!1);onMount(async()=>{await getHistory(get2(showDiffInfo),get2(showChunkCorrected),get2(checkStorageDiff))});onDestroy(()=>{});legacy_pre_effect(()=>(get2(dispDateFrom),get2(dispDateTo),get2(showDiffInfo),get2(showChunkCorrected),get2(checkStorageDiff)),()=>{set(range_from_epoch,new Date(get2(dispDateFrom)).getTime()+timezoneOffset);set(range_to_epoch,new Date(get2(dispDateTo)).getTime()+timezoneOffset);getHistory(get2(showDiffInfo),get2(showChunkCorrected),get2(checkStorageDiff))});legacy_pre_effect_reset();init();div=root_96();div_1=sibling(child(div),2);div_2=child(div_1);input=sibling(child(div_2));remove_input_defaults(input);reset(div_2);div_3=sibling(div_2,2);input_1=sibling(child(div_3));remove_input_defaults(input_1);reset(div_3);div_4=sibling(div_3,2);label2=sibling(child(div_4),2);input_2=child(label2);remove_input_defaults(input_2);span=sibling(input_2);text2=child(span,!0);reset(span);reset(label2);label_1=sibling(label2,2);input_3=child(label_1);remove_input_defaults(input_3);span_1=sibling(input_3);text_1=child(span_1,!0);reset(span_1);reset(label_1);label_2=sibling(label_1,2);input_4=child(label_2);remove_input_defaults(input_4);span_2=sibling(input_4);text_2=child(span_2,!0);reset(span_2);reset(label_2);reset(div_4);reset(div_1);node=sibling(div_1,2);consequent=$$anchor2=>{var div_5=root35(),text_3=child(div_5,!0);reset(div_5);template_effect($0=>set_text(text_3,$0),[()=>(deep_read_state($msg),untrack(()=>$msg("Gathering information...")))]);append($$anchor2,div_5)};if_block(node,$$render=>{get2(loading)&&$$render(consequent)});table3=sibling(node,2);tbody=child(table3);tr=child(tbody);th=child(tr);text_4=child(th,!0);reset(th);th_1=sibling(th);text_5=child(th_1,!0);reset(th_1);th_2=sibling(th_1);text_6=child(th_2,!0);reset(th_2);th_3=sibling(th_2);text_7=child(th_3,!0);reset(th_3);node_1=sibling(th_3);consequent_1=$$anchor2=>{var th_4=root_129(),text_8=child(th_4,!0);reset(th_4);template_effect($0=>set_text(text_8,$0),[()=>(deep_read_state($msg),untrack(()=>$msg("Chunks")))]);append($$anchor2,th_4)};if_block(node_1,$$render=>{get2(showChunkCorrected)&&$$render(consequent_1)});reset(tr);tr_1=sibling(tr);td3=child(tr_1);node_2=child(td3);consequent_2=$$anchor2=>{var div_6=root_216();append($$anchor2,div_6)};alternate=$$anchor2=>{var div_7=root_314(),button=child(div_7),text_9=child(button,!0);reset(button);reset(div_7);template_effect($0=>set_text(text_9,$0),[()=>(deep_read_state($msg),untrack(()=>$msg("+1 week")))]);event("click",button,()=>nextWeek());append($$anchor2,div_7)};if_block(node_2,$$render=>{get2(loading)?$$render(consequent_2):$$render(alternate,-1)});reset(td3);reset(tr_1);node_3=sibling(tr_1);each(node_3,1,()=>get2(history),index,($$anchor2,entry)=>{var td_2,div_8,span_3,text_11,node_4,consequent_3,alternate_1,td_3,span_6,node_5,consequent_4,alternate_2,td_4,text_16,node_6,consequent_5,tr_2=root_87(),td_1=child(tr_2),text_10=child(td_1,!0);reset(td_1);td_2=sibling(td_1);div_8=child(td_2);span_3=child(div_8);text_11=child(span_3);reset(span_3);node_4=sibling(span_3,2);consequent_3=$$anchor3=>{var span_4=root_48(),text_12=child(span_4,!0);reset(span_4);template_effect(()=>set_text(text_12,(get2(entry),untrack(()=>get2(entry).filename))));append($$anchor3,span_4)};alternate_1=$$anchor3=>{var span_5=root_58(),a_1=child(span_5),text_13=child(a_1,!0);reset(a_1);reset(span_5);template_effect(()=>set_text(text_13,(get2(entry),untrack(()=>get2(entry).filename))));event("click",a_1,()=>openFile(get2(entry).path));append($$anchor3,span_5)};if_block(node_4,$$render=>{get2(entry),untrack(()=>get2(entry).isDeleted)?$$render(consequent_3):$$render(alternate_1,-1)});reset(div_8);reset(td_2);td_3=sibling(td_2);span_6=child(td_3);node_5=child(span_6);consequent_4=$$anchor3=>{var a_2=root_68(),text_14=child(a_2,!0);reset(a_2);template_effect(()=>set_text(text_14,(get2(entry),untrack(()=>get2(entry).rev))));event("click",a_2,()=>{var _a13;return showHistory(get2(entry).path,(null==(_a13=get2(entry))?void 0:_a13.rev)||"")});append($$anchor3,a_2)};alternate_2=$$anchor3=>{var text_15=text();template_effect(()=>set_text(text_15,(get2(entry),untrack(()=>get2(entry).rev))));append($$anchor3,text_15)};if_block(node_5,$$render=>{get2(entry),untrack(()=>get2(entry).isPlain)?$$render(consequent_4):$$render(alternate_2,-1)});reset(span_6);reset(td_3);td_4=sibling(td_3);text_16=child(td_4,!0);reset(td_4);node_6=sibling(td_4);consequent_5=$$anchor3=>{var td_5=root_77(),text_17=child(td_5,!0);reset(td_5);template_effect(()=>set_text(text_17,(get2(entry),untrack(()=>get2(entry).chunks))));append($$anchor3,td_5)};if_block(node_6,$$render=>{get2(showChunkCorrected)&&$$render(consequent_5)});reset(tr_2);template_effect($0=>{set_text(text_10,(get2(entry),untrack(()=>get2(entry).mtimeDisp)));set_text(text_11,`/${null!=$0?$0:""}`);set_text(text_16,(get2(entry),untrack(()=>get2(entry).changes)))},[()=>(get2(entry),untrack(()=>get2(entry).dirname.split("/").join("/")))]);append($$anchor2,tr_2)});tr_3=sibling(node_3);td_6=child(tr_3);node_7=child(td_6);consequent_6=$$anchor2=>{var div_9=root_216();append($$anchor2,div_9)};alternate_3=$$anchor2=>{var div_10=root_314(),button_1=child(div_10),text_18=child(button_1,!0);reset(button_1);reset(div_10);template_effect($0=>set_text(text_18,$0),[()=>(deep_read_state($msg),untrack(()=>$msg("+1 week")))]);event("click",button_1,()=>prevWeek());append($$anchor2,div_10)};if_block(node_7,$$render=>{get2(loading)?$$render(consequent_6):$$render(alternate_3,-1)});reset(td_6);reset(tr_3);reset(tbody);reset(table3);reset(div);template_effect(($0,$1,$2,$3,$4,$5,$6)=>{input.disabled=get2(loading);input_1.disabled=get2(loading);input_2.disabled=get2(loading);set_text(text2,$0);input_3.disabled=get2(loading);set_text(text_1,$1);input_4.disabled=get2(loading);set_text(text_2,$2);set_text(text_4,$3);set_text(text_5,$4);set_text(text_6,$5);set_text(text_7,$6)},[()=>(deep_read_state($msg),untrack(()=>$msg("Diff"))),()=>(deep_read_state($msg),untrack(()=>$msg("Chunks"))),()=>(deep_read_state($msg),untrack(()=>$msg("File integrity"))),()=>(deep_read_state($msg),untrack(()=>$msg("Date"))),()=>(deep_read_state($msg),untrack(()=>$msg("Path"))),()=>(deep_read_state($msg),untrack(()=>$msg("Rev"))),()=>(deep_read_state($msg),untrack(()=>$msg("Stat")))]);bind_value(input,()=>get2(dispDateFrom),$$value=>set(dispDateFrom,$$value));bind_value(input_1,()=>get2(dispDateTo),$$value=>set(dispDateTo,$$value));bind_checked(input_2,()=>get2(showDiffInfo),$$value=>set(showDiffInfo,$$value));bind_checked(input_3,()=>get2(showChunkCorrected),$$value=>set(showChunkCorrected,$$value));bind_checked(input_4,()=>get2(checkStorageDiff),$$value=>set(checkStorageDiff,$$value));append($$anchor,div);pop()}async function ensureLocalDatabaseMaintenancePrerequisites({operationName,settings,askSelectStringDialogue,applyPartial}){const missing=settings.readChunksOnline?["- Fetch chunks on demand: Off (currently On)"]:[];if(0==missing.length)return!0;const APPLY="Apply and continue",result=await askSelectStringDialogue(`${operationName} requires the following settings:\n\n${missing.join("\n")}\n\nApply these settings and continue?`,[APPLY,"Cancel"],{title:`${operationName} prerequisites`,defaultAction:"Cancel"});if(result!==APPLY)return!1;await applyPartial({readChunksOnline:!1},!0);return!0}function getMultipleBound(handler){const _handler="invoke"in handler?handler.invoke:handler.dispatch,__handler=_handler.bind(handler),func=(...args)=>__handler(...args);func.addHandler=handler.addHandler.bind(handler);func.removeHandler=handler.removeHandler.bind(handler);func.use=handler;return func}function allFunction(name){const handler=new AllHandler(null!=name?name:"handleAllFunc");return getMultipleBound(handler)}function bailFirstFailureFunction(name){const handler=new AllHandler(null!=name?name:"bailFirstFailureFunction");return getMultipleBound(handler)}function allParallelFunction(name){const handler=new ParallelAllHandler(null!=name?name:"allParallelFunction");return getMultipleBound(handler)}function anySuccessFunction(name){const handler=new AnySuccessHandler(null!=name?name:"anySuccessFunction");return getMultipleBound(handler)}function firstResultFunction(name){const handler=new FirstResultHandler(null!=name?name:"firstResultFunction");return getMultipleBound(handler)}function dispatchParallelFunction(name){const handler=new DispatchParallel(null!=name?name:"dispatchParallelFunction");return getMultipleBound(handler)}function bindableFunction(name){const handler=new Binder(null!=name?name:"bindableFunction"),func=(...args)=>handler.invoke(...args);func.setHandler=handler.assign.bind(handler);return func}function lazyBindableFunction(name){const handler=new LazyBinder(null!=name?name:"lazyBindableFunction"),func=async(...args)=>await handler.invoke(...args);func.setHandler=handler.assign.bind(handler);return func}function handlers2(){return{all:name=>allFunction(String(name)),allParallel:name=>allParallelFunction(String(name)),bailFirstFailure:name=>bailFirstFailureFunction(String(name)),anySuccess:name=>anySuccessFunction(String(name)),firstResult:name=>firstResultFunction(String(name)),dispatchParallel:name=>dispatchParallelFunction(String(name)),binder:name=>bindableFunction(String(name)),lazyBinder:name=>lazyBindableFunction(String(name))}}async function runWithOptionalActivity(runner,task,options){return runner?await runner.run(task,options):await task()}function createRemoteConnectionScope(ownerSignal){const controller=new AbortController,combinedSignals=new WeakMap;let detachOwner=()=>{};const abort=reason=>{detachOwner();controller.signal.aborted||controller.abort(reason)};if(null==ownerSignal?void 0:ownerSignal.aborted)abort(ownerSignal.reason);else if(ownerSignal){const onOwnerAbort=()=>abort(ownerSignal.reason);ownerSignal.addEventListener("abort",onOwnerAbort,{once:!0});detachOwner=()=>ownerSignal.removeEventListener("abort",onOwnerAbort)}return{signal:controller.signal,combine:signal=>{if(!signal||signal===controller.signal)return controller.signal;const cached=combinedSignals.get(signal);if(cached)return cached;const combined=combineAbortSignals(signal,controller.signal);combinedSignals.set(signal,combined);return combined},abort}}function combineAbortSignals(first,second){if(first===second)return first;const abortSignalWithAny=AbortSignal;if("function"==typeof abortSignalWithAny.any)return abortSignalWithAny.any([first,second]);const controller=new AbortController,listeners2=new Map,detach=()=>{for(const[signal,listener]of listeners2)signal.removeEventListener("abort",listener);listeners2.clear()},abortFrom=signal=>{detach();controller.signal.aborted||controller.abort(signal.reason)};for(const signal of[first,second]){if(signal.aborted){abortFrom(signal);break}const listener=()=>abortFrom(signal);listeners2.set(signal,listener);signal.addEventListener("abort",listener,{once:!0})}return controller.signal}function createCouchDBConnection(db,info3,scope){let closePromise;return{db,info:info3,close:()=>{null!=closePromise||(closePromise=(async()=>{scope.abort(new Error("Remote connection closed."));await db.close()})());return closePromise}}}function shouldAllowSleepDuringSynchronisation(settings,isMobile){return settings.allowSleepDuringSynchronisation||!isMobile&&settings.allowSleepDuringSynchronisationOnDesktop}function withSleepPreference(dependencies){const activityRunner=dependencies.activityRunner;return activityRunner?{...dependencies,activityRunner:{async run(task,options){const allowSleep=shouldAllowSleepDuringSynchronisation(dependencies.settingService.currentSettings(),dependencies.isMobile());return allowSleep?await task():await activityRunner.run(task,options)}}}:dependencies}function normaliseObsidianSettingsData(data){if("object"==typeof data&&null!==data&&!Array.isArray(data))return data}function requestTimeout2(timeoutInMs=0){return new Promise((_,reject)=>{timeoutInMs&&compatGlobal.setTimeout(()=>{const timeoutError=new Error(`Request did not complete within ${timeoutInMs} ms`);timeoutError.name="TimeoutError";reject(timeoutError)},timeoutInMs)})}function normaliseRequestBody(body){if(void 0===body)return;if("string"==typeof body||body instanceof ArrayBuffer)return body;if(ArrayBuffer.isView(body))return body.buffer instanceof ArrayBuffer&&0===body.byteOffset&&body.byteLength===body.buffer.byteLength?body.buffer:new Uint8Array(body.buffer,body.byteOffset,body.byteLength).slice().buffer;const bodyType=Object.prototype.toString.call(body).slice(8,-1);throw new TypeError(`Obsidian requestUrl does not support the request body type ${bodyType}`)}function openOwnedDialogue(createDialogue,lifecycle){let removeAbortHandler=()=>{};const result=new Promise(resolve=>{const{signal}=lifecycle;if(null==signal?void 0:signal.aborted){resolve(null);return}const dialogue=createDialogue(resolve),abortDialogue=()=>dialogue.close();null==signal||signal.addEventListener("abort",abortDialogue,{once:!0});removeAbortHandler=()=>null==signal?void 0:signal.removeEventListener("abort",abortDialogue);dialogue.open()});return result.finally(()=>removeAbortHandler())}function promptText(app,options,lifecycle={}){return openOwnedDialogue(resolve=>new TextPromptModal(app,{...options,password:!1},resolve),lifecycle)}function promptPassword(app,options,lifecycle={}){return openOwnedDialogue(resolve=>new TextPromptModal(app,{...options,password:!0},resolve),lifecycle)}function pickOne(app,options,lifecycle={}){return openOwnedDialogue(resolve=>new PickOneModal(app,options,resolve),lifecycle)}function confirmAction(app,options,lifecycle={}){return openOwnedDialogue(resolve=>new ActionDialog(app,options,resolve),lifecycle)}function duration(value,name){if(!1===value)return!1;if(!Number.isFinite(value)||value<0)throw new RangeError(`${name} must be a finite non-negative number or false`);return value}function createNoticeEntry(message){const root44=createDiv({cls:"vpk-keyed-notice"});root44.replaceChildren(message);const fragment=document.createDocumentFragment();fragment.append(root44);const entry={notice:new import_obsidian4.Notice(fragment,0),root:root44,hideTimer:void 0,dismissed:!1};root44.addEventListener("click",()=>{entry.dismissed=!0},{capture:!0});return entry}function noticeEntryIsActive(entry){return!entry.dismissed&&entry.root.isConnected}function renderNoticeMessage(entry,message){entry.root.replaceChildren(message)}function createGroupRoot(){const root44=createDiv({cls:"vpk-keyed-notice-group"});root44.setCssStyles({display:"grid",gap:"0.75rem",maxWidth:"100%",overflowWrap:"anywhere"});return root44}function showGroupRoot(root44){const fragment=document.createDocumentFragment();fragment.append(root44);return new import_obsidian4.Notice(fragment,0)}function createGroupEntry(){const root44=createGroupRoot(),entry={notice:showGroupRoot(root44),root:root44,items:new Map,hideTimer:void 0,dismissed:!1};root44.addEventListener("click",()=>{entry.dismissed=!0},{capture:!0});return entry}function groupEntryIsActive(entry){return!entry.dismissed&&entry.root.isConnected}function renderGroup(entry){entry.root.replaceChildren();let index6=0;for(const[itemKey,item]of entry.items){const itemElement=createDiv({cls:"vpk-keyed-notice-group__item"});itemElement.dataset.itemKey=itemKey;itemElement.setCssStyles({display:"grid",gap:"0.5rem",minWidth:"0",paddingTop:0===index6?"0":"0.75rem",...0===index6?{}:{borderTop:"1px solid var(--background-modifier-border)"}});const messageElement=createDiv({cls:"vpk-keyed-notice-group__message",text:item.message});itemElement.append(messageElement);if(void 0!==item.action){const button=createEl("button",{attr:{type:"button"},cls:"vpk-keyed-notice-group__action",text:item.action.label});button.setCssStyles({height:"auto",maxWidth:"100%",minHeight:"max(var(--input-height), 44px)",whiteSpace:"normal",width:"100%"});button.addEventListener("click",item.action.onSelect);itemElement.append(button)}entry.root.append(itemElement);index6+=1}}function confirmWithMessageWithWideButton(plugin2,title,contentMd,buttons,defaultAction,timeout){return new Promise(res2=>{const dialog=new MessageBox(plugin2,title,contentMd,buttons,defaultAction,timeout,!0,result=>res2(result));dialog.open()})}function DialogHost($$anchor,$$props){var div,node;push($$props,!0);append_styles($$anchor,$$css12);const props=rest_props($$props,rest_excludes),contextProps={setTitle:title=>$$props.setTitle(title),closeDialog:()=>$$props.closeDialog(),setResult:result=>$$props.setResult(result),getInitialData:()=>{var _a13;return null===(_a13=props.getInitialData)||void 0===_a13?void 0:_a13.call(props)}};(()=>{var _a13;null===(_a13=props.onSetupContext)||void 0===_a13||_a13.call(props,contextProps)})();const setResultWrapper=result=>{$$props.setResult(result);$$props.closeDialog()},Component3=user_derived(()=>$$props.mountComponent);let thisElement;div=root36();node=child(div);component(node,()=>get2(Component3),($$anchor2,Component_1)=>{Component_1($$anchor2,{setResult:setResultWrapper,get getInitialData(){return $$props.getInitialData}})});reset(div);bind_this(div,$$value=>thisElement=$$value,()=>thisElement);append($$anchor,div);pop()}function DialogueToCopy($$anchor,$$props){function commit(){$$props.setResult("ok")}async function copyToClipboard(){await navigator.clipboard.writeText(get2(dataToCopy));set(copied,!0)}var fragment,node,node_1,node_3,node_4;push($$props,!0);append_styles($$anchor,$$css13);let dataToCopy=state(""),title=state(void 0),copied=state(!1);onMount(()=>{if($$props.getInitialData){const initialData=$$props.getInitialData();if(initialData){set(dataToCopy,initialData.dataToCopy,!0);set(title,initialData.title,!0)}}});fragment=root_130();node=first_child(fragment);{let $0=user_derived(()=>get2(title)||"Data");DialogHeader(node,{get title(){var _a13;return`Your ${null!=(_a13=get2($0))?_a13:""} is ready to be copied`}})}node_1=sibling(node,2);Instruction(node_1,{children:($$anchor2,$$slotProps)=>{{let $0=user_derived(()=>get2(title)||$msg("Data to Copy"));InputRow($$anchor2,{get label(){return get2($0)},children:($$anchor3,$$slotProps2)=>{var button,node_2,consequent,alternate,fragment_2=root37(),textarea=first_child(fragment_2);remove_textarea_child(textarea);button=sibling(textarea,2);node_2=child(button);consequent=$$anchor4=>{var text2=text("📋");append($$anchor4,text2)};alternate=$$anchor4=>{var text_1=text("✔️");append($$anchor4,text_1)};if_block(node_2,$$render=>{get2(copied)?$$render(alternate,-1):$$render(consequent)});reset(button);template_effect(()=>set_value(textarea,get2(dataToCopy)));delegated("click",button,()=>copyToClipboard());append($$anchor3,fragment_2)},$$slots:{default:!0}})}},$$slots:{default:!0}});node_3=sibling(node_1,2);InfoNote(node_3,{get visible(){return get2(copied)},children:($$anchor2,$$slotProps)=>{next();var text_2=text();template_effect(()=>{var _a13;return set_text(text_2,`Your ${null!=(_a13=get2(title)||"data")?_a13:""} has been copied to the clipboard.`)});append($$anchor2,text_2)},$$slots:{default:!0}});node_4=sibling(node_3,2);UserDecisions(node_4,{children:($$anchor2,$$slotProps)=>{Decision($$anchor2,{title:"OK",important:!0,commit})},$$slots:{default:!0}});append($$anchor,fragment);pop()}function resolveDefaultProvider(){var _a13;return"undefined"==typeof navigator?null:null!=(_a13=navigator.wakeLock)?_a13:null}function resolveDefaultDocument(){return"undefined"==typeof document?null:document}function createScreenWakeLockManager(options={}){const provider=void 0===options.provider?resolveDefaultProvider():options.provider,visibilityDocument=void 0===options.document?resolveDefaultDocument():options.document,leases=new Set;let sentinel=null,requestInFlight=null,visibilityListenerInstalled=!1,disposed=!1;const emit2=event2=>{var _a13;try{null==(_a13=options.onEvent)||_a13.call(options,event2)}catch(e3){}},canHold=()=>!disposed&&leases.size>0&&(null===visibilityDocument||"visible"===visibilityDocument.visibilityState),releaseDetachedSentinel=async target=>{if(!target.released)try{await target.release()}catch(error){emit2({type:"wake-lock-error",operation:"release",error,activeLeaseCount:leases.size})}},onSentinelReleased=()=>{if(null===sentinel)return;const releasedSentinel=sentinel;sentinel=null;releasedSentinel.removeEventListener("release",onSentinelReleased);emit2({type:"wake-lock-released",reason:"system",activeLeaseCount:leases.size})},releaseHeldSentinel=async reason=>{const heldSentinel=sentinel;if(null!==heldSentinel){sentinel=null;heldSentinel.removeEventListener("release",onSentinelReleased);await releaseDetachedSentinel(heldSentinel);emit2({type:"wake-lock-released",reason,activeLeaseCount:leases.size})}},ensureHeld=()=>{if(!canHold()||null!==sentinel)return Promise.resolve();if(null===provider){emit2({type:"unsupported",activeLeaseCount:leases.size});return Promise.resolve()}if(null!==requestInFlight)return requestInFlight;emit2({type:"wake-lock-requested",activeLeaseCount:leases.size});let platformRequest;try{platformRequest=provider.request("screen")}catch(error){emit2({type:"wake-lock-error",operation:"request",error,activeLeaseCount:leases.size});return Promise.resolve()}const request2=platformRequest.then(async acquiredSentinel=>{if(canHold()&&!acquiredSentinel.released&&null===sentinel){sentinel=acquiredSentinel;acquiredSentinel.addEventListener("release",onSentinelReleased);emit2({type:"wake-lock-acquired",activeLeaseCount:leases.size})}else await releaseDetachedSentinel(acquiredSentinel)}).catch(error=>{emit2({type:"wake-lock-error",operation:"request",error,activeLeaseCount:leases.size})}).finally(()=>{requestInFlight===request2&&(requestInFlight=null)});requestInFlight=request2;return request2},onVisibilityChange=()=>{"visible"===(null==visibilityDocument?void 0:visibilityDocument.visibilityState)?ensureHeld():releaseHeldSentinel("hidden")},installVisibilityListener=()=>{if(null!==visibilityDocument&&!visibilityListenerInstalled){visibilityDocument.addEventListener("visibilitychange",onVisibilityChange);visibilityListenerInstalled=!0}},removeVisibilityListener=()=>{if(null!==visibilityDocument&&visibilityListenerInstalled){visibilityDocument.removeEventListener("visibilitychange",onVisibilityChange);visibilityListenerInstalled=!1}},releaseLease=async lease=>{if(leases.delete(lease)){lease.markReleased();emit2({type:"lease-released",label:lease.label,activeLeaseCount:leases.size});if(0===leases.size){removeVisibilityListener();await releaseHeldSentinel(disposed?"disposed":"idle")}}},manager={get supported(){return null!==provider},get held(){return null!==sentinel&&!sentinel.released},get activeLeaseCount(){return leases.size},async run(task,acquireOptions={}){const lease=await manager.acquire(acquireOptions);try{return await task()}finally{await lease.dispose()}},async acquire(acquireOptions={}){var _a13,_b6;if(disposed)throw new ScreenWakeLockManagerDisposedError;let abortListener,resolveReleased,released=null!=(_b6=null==(_a13=acquireOptions.signal)?void 0:_a13.aborted)&&_b6;const releasedPromise=new Promise(resolve=>{resolveReleased=resolve}),lease={get released(){return released},label:acquireOptions.label,releasedPromise,markReleased(){var _a14;if(!released){released=!0;if(void 0!==abortListener){null==(_a14=acquireOptions.signal)||_a14.removeEventListener("abort",abortListener);abortListener=void 0}null==resolveReleased||resolveReleased();resolveReleased=void 0}},async dispose(){released||await releaseLease(lease)}};if(released){null==resolveReleased||resolveReleased();resolveReleased=void 0;return lease}leases.add(lease);emit2({type:"lease-acquired",label:lease.label,activeLeaseCount:leases.size});installVisibilityListener();if(void 0!==acquireOptions.signal){abortListener=()=>{lease.dispose()};acquireOptions.signal.addEventListener("abort",abortListener,{once:!0})}await Promise.race([ensureHeld(),lease.releasedPromise]);return lease},async dispose(){if(disposed)return;disposed=!0;removeVisibilityListener();const ownedLeases=[...leases];for(const lease of ownedLeases)await releaseLease(lease);await releaseHeldSentinel("disposed")}};return manager}function getIdbProxyableTypes(){return idbProxyableTypes||(idbProxyableTypes=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function getCursorAdvanceMethods(){return cursorAdvanceMethods||(cursorAdvanceMethods=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}function promisifyRequest(request2){const promise=new Promise((resolve,reject)=>{const unlisten=()=>{request2.removeEventListener("success",success);request2.removeEventListener("error",error)},success=()=>{resolve(wrap(request2.result));unlisten()},error=()=>{reject(request2.error);unlisten()};request2.addEventListener("success",success);request2.addEventListener("error",error)});reverseTransformCache.set(promise,request2);return promise}function cacheDonePromiseForTransaction(tx){if(transactionDoneMap.has(tx))return;const done=new Promise((resolve,reject)=>{const unlisten=()=>{tx.removeEventListener("complete",complete);tx.removeEventListener("error",error);tx.removeEventListener("abort",error)},complete=()=>{resolve();unlisten()},error=()=>{reject(tx.error||new DOMException("AbortError","AbortError"));unlisten()};tx.addEventListener("complete",complete);tx.addEventListener("error",error);tx.addEventListener("abort",error)});transactionDoneMap.set(tx,done)}function replaceTraps(callback){idbProxyTraps=callback(idbProxyTraps)}function wrapFunction(func){return getCursorAdvanceMethods().includes(func)?function(...args){func.apply(unwrap(this),args);return wrap(this.request)}:function(...args){return wrap(func.apply(unwrap(this),args))}}function transformCachableValue(value){if("function"==typeof value)return wrapFunction(value);value instanceof IDBTransaction&&cacheDonePromiseForTransaction(value);return instanceOfAny(value,getIdbProxyableTypes())?new Proxy(value,idbProxyTraps):value}function wrap(value){if(value instanceof IDBRequest)return promisifyRequest(value);if(transformCache.has(value))return transformCache.get(value);const newValue=transformCachableValue(value);if(newValue!==value){transformCache.set(value,newValue);reverseTransformCache.set(newValue,value)}return newValue}function openDB(name,version2,{blocked,upgrade,blocking,terminated}={}){const request2=indexedDB.open(name,version2),openPromise=wrap(request2);upgrade&&request2.addEventListener("upgradeneeded",event2=>{upgrade(wrap(request2.result),event2.oldVersion,event2.newVersion,wrap(request2.transaction),event2)});blocked&&request2.addEventListener("blocked",event2=>blocked(event2.oldVersion,event2.newVersion,event2));openPromise.then(db=>{terminated&&db.addEventListener("close",()=>terminated());blocking&&db.addEventListener("versionchange",event2=>blocking(event2.oldVersion,event2.newVersion,event2))}).catch(()=>{});return openPromise}function deleteDB(name,{blocked}={}){const request2=indexedDB.deleteDatabase(name);blocked&&request2.addEventListener("blocked",event2=>blocked(event2.oldVersion,event2));return wrap(request2).then(()=>{})}function getMethod(target,prop2){if(!(target instanceof IDBDatabase)||prop2 in target||"string"!=typeof prop2)return;if(cachedMethods.get(prop2))return cachedMethods.get(prop2);const targetFuncName=prop2.replace(/FromIndex$/,""),useIndex=prop2!==targetFuncName,isWrite=writeMethods.includes(targetFuncName);if(!(targetFuncName in(useIndex?IDBIndex:IDBObjectStore).prototype)||!isWrite&&!readMethods.includes(targetFuncName))return;const method=async function(storeName,...args){const tx=this.transaction(storeName,isWrite?"readwrite":"readonly");let target2=tx.store;useIndex&&(target2=target2.index(args.shift()));return(await Promise.all([target2[targetFuncName](...args),isWrite&&tx.done]))[0]};cachedMethods.set(prop2,method);return method}async function*iterate(...args){let cursor=this;cursor instanceof IDBCursor||(cursor=await cursor.openCursor(...args));if(!cursor)return;const proxiedCursor=new Proxy(cursor,cursorIteratorTraps);ittrProxiedCursorToOriginalProxy.set(proxiedCursor,cursor);reverseTransformCache.set(proxiedCursor,unwrap(cursor));for(;cursor;){yield proxiedCursor;cursor=await(advanceResults.get(proxiedCursor)||cursor.continue());advanceResults.delete(proxiedCursor)}}function isIteratorProp(target,prop2){return prop2===Symbol.asyncIterator&&instanceOfAny(target,[IDBIndex,IDBObjectStore,IDBCursor])||"iterate"===prop2&&instanceOfAny(target,[IDBIndex,IDBObjectStore])}async function OpenKeyValueDatabase(dbKey){return await serialized(`OpenKeyValueDatabase-${dbKey}`,async()=>{const cachedDB=databaseCache.get(dbKey);if(cachedDB){if(!cachedDB.isDestroyed)return cachedDB;await cachedDB.ensuredDestroyed;databaseCache.delete(dbKey)}const newDB=new IDBKeyValueDatabase(dbKey);try{await newDB.getIsReady();databaseCache.set(dbKey,newDB);return newDB}catch(e3){databaseCache.delete(dbKey);throw e3}})}function isRetryableStreamingFetchFailure(error){return error instanceof StreamingFetchFailure&&error.retryable}function errorMessage(error){return error instanceof Error&&error.message?error.message:String(error)}function asStreamingFetchFailure(error){return error instanceof StreamingFetchFailure?error:new StreamingFetchFailure("protocol",`Fast Fetch encountered an unexpected processing failure: ${errorMessage(error)}`,!1,{cause:error})}function transportFailure(operation2,error){return new StreamingFetchFailure("transport",`Fast Fetch could not ${operation2}: ${errorMessage(error)}`,!0,{cause:error})}function responseFailure(response,operation2){const status=response.status;if(401===status||403===status)return new StreamingFetchFailure("authentication",`Fast Fetch could not ${operation2}: CouchDB returned HTTP ${status}.`,!1,{status});const retryable=408===status||429===status||status>=500;return new StreamingFetchFailure(retryable?"transport":"protocol",`Fast Fetch could not ${operation2}: CouchDB returned HTTP ${status}.`,retryable,{status})}function ensureResponseOK(response,operation2){if(!response.ok)throw responseFailure(response,operation2)}async function fetchResponse(url,init3,operation2){let response;try{response=await _fetch(url,init3)}catch(error){throw transportFailure(operation2,error)}ensureResponseOK(response,operation2);return response}async function readResponseText(response,operation2){try{return await response.text()}catch(error){throw transportFailure(operation2,error)}}async function saveCheckpoint(onCheckpoint,sequence){try{await(null==onCheckpoint?void 0:onCheckpoint(sequence))}catch(error){throw new StreamingFetchFailure("storage",`Fast Fetch could not save its checkpoint: ${errorMessage(error)}`,!1,{cause:error})}}function generatePouchDBBatchWriter(downloadToDB,decryptFunction,onCheckpoint){let batchLastSequence,batchBuffer=[],currentBatchSizeBytes=0;const flush2=async()=>{if(0===batchBuffer.length)return;const documents=batchBuffer,checkpoint=batchLastSequence;let results;try{results=await downloadToDB.bulkDocs(documents,{new_edits:!1})}catch(error){throw new StreamingFetchFailure("storage",`Fast Fetch could not write a batch to the local database: ${errorMessage(error)}`,!1,{cause:error})}const failedResult=results.find(result=>"error"in result&&Boolean(result.error));if(failedResult){const detail=failedResult.message||failedResult.name||"the local database rejected a document";throw new StreamingFetchFailure("storage",`Fast Fetch could not write a batch to the local database: ${detail}`,!1,{cause:failedResult})}void 0!==checkpoint&&await saveCheckpoint(onCheckpoint,checkpoint);batchBuffer=[];currentBatchSizeBytes=0;batchLastSequence=void 0};return{async write(doc,sequence){let decryptedDoc,serialisedDoc;if(doc._deleted)decryptedDoc=doc;else try{decryptedDoc=await decryptFunction(doc)}catch(error){throw new StreamingFetchFailure("decryption",`Fast Fetch could not decrypt a document: ${errorMessage(error)}`,!1,{cause:error})}try{const serialised=JSON.stringify(decryptedDoc);if(void 0===serialised)throw new Error("the decrypted value is not a document");serialisedDoc=serialised}catch(error){throw new StreamingFetchFailure("decryption",`Fast Fetch produced an invalid decrypted document: ${errorMessage(error)}`,!1,{cause:error})}batchBuffer.push(decryptedDoc);currentBatchSizeBytes+=serialisedDoc.length;batchLastSequence=sequence;(batchBuffer.length>=100||currentBatchSizeBytes>=2097152)&&await flush2()},async flushThrough(sequence){await flush2();await saveCheckpoint(onCheckpoint,sequence)},flush:flush2,abort(){batchBuffer=[];currentBatchSizeBytes=0;batchLastSequence=void 0}}}function setParamsToURL(url,params){for(const[key3,value]of Object.entries(params))url.searchParams.set(key3,value);return url}function parseStatusSource(source2){const trimmed=source2.trim();if(!trimmed)throw new StreamingFetchFailure("protocol","Fast Fetch received no changes status from CouchDB.",!1);const candidates=[trimmed,...trimmed.split("\n").reverse().filter(Boolean)];for(const candidate of candidates)try{const parsed=JSON.parse(candidate);if(parsed&&"object"==typeof parsed)return parsed}catch(e3){}throw new StreamingFetchFailure("protocol","Fast Fetch received an invalid changes status from CouchDB.",!1)}function parseChangesFeedLine(line){let parsed;try{parsed=JSON.parse(line)}catch(error){throw new StreamingFetchFailure("protocol","Fast Fetch received a malformed changes-feed row.",!1,{cause:error})}if(!parsed||"object"!=typeof parsed)throw new StreamingFetchFailure("protocol","Fast Fetch received an invalid changes-feed line.",!1);if(!("seq"in parsed)&&"last_seq"in parsed){const lastSequence=parsed.last_seq;if(void 0===lastSequence)throw new StreamingFetchFailure("protocol","Fast Fetch received a changes-feed terminator without a sequence.",!1);return{type:"terminator",lastSequence}}if(!("seq"in parsed))throw new StreamingFetchFailure("protocol","Fast Fetch received a changes-feed row without a sequence.",!1);const change=parsed;if(void 0===change.seq||void 0!==change.doc&&(!change.doc||"object"!=typeof change.doc))throw new StreamingFetchFailure("protocol","Fast Fetch received an invalid changes-feed row.",!1);return{type:"change",change}}async function fetchChangesForInitialSync(downloadToDB,remoteDbUrl,authHeader,decryptFunction,since="0",onProgress,onCheckpoint,customHeaders){let totalFetched=0,totalValidFetched=0,totalBytes=0;const changesBaseParams={feed:"continuous",include_docs:"true",style:"all_docs",conflicts:"true",revs:"true",since:since.toString()},fetchHeaders=new Headers(customHeaders);fetchHeaders.set("Accept","application/json");fetchHeaders.set("Authorization",authHeader);const targetURL=setParamsToURL(new URL(`${remoteDbUrl}/_changes`),{...changesBaseParams,feed:"normal",since:"now",limit:"1",include_docs:"false"}),targetResponse=await fetchResponse(targetURL.toString(),{headers:fetchHeaders},"capture the changes target"),targetStatus=parseStatusSource(await readResponseText(targetResponse,"read the changes target")),progressTargetSeq=targetStatus.last_seq;if(void 0===progressTargetSeq)throw new StreamingFetchFailure("protocol","Fast Fetch could not obtain a changes progress target from CouchDB.",!1);const batchWriter=generatePouchDBBatchWriter(downloadToDB,decryptFunction,onCheckpoint);let docsToFetch=0,lastProgress=0,lastReportTime=Date.now();const reportProgress=(force=!1)=>{if(!(!force&&totalFetched-lastProgress<25&&Date.now()-lastReportTime<2e3)){lastProgress=totalFetched;lastReportTime=Date.now();null==onProgress||onProgress({totalFetched,totalValidFetched,targetSeq:progressTargetSeq,docsToFetch,totalBytes})}},readAvailableChanges=async pageSince=>{const statusURL=setParamsToURL(new URL(`${remoteDbUrl}/_changes`),{...changesBaseParams,feed:"normal",since:pageSince.toString(),limit:"1",include_docs:"false"}),response=await fetchResponse(statusURL.toString(),{method:"GET",headers:fetchHeaders},"read changes status"),status=parseStatusSource(await readResponseText(response,"read changes status"));if(!Array.isArray(status.results))throw new StreamingFetchFailure("protocol","Fast Fetch received changes status without a valid results list.",!1);const pending3=status.pending;if("number"!=typeof pending3||!Number.isSafeInteger(pending3)||pending3<0)throw new StreamingFetchFailure("protocol","Fast Fetch received changes status without a valid pending count.",!1);const available=status.results.length+pending3;if(!Number.isSafeInteger(available))throw new StreamingFetchFailure("protocol","Fast Fetch received a changes count outside the supported range.",!1);return available},fetchPage=async(pageSince,pageLimit)=>{const controller=new AbortController;let reader,buffer="",fetchedRows=0;const processLine=async line=>{const parsed=parseChangesFeedLine(line);if("terminator"===parsed.type){if(0===fetchedRows)throw new StreamingFetchFailure("transport","Fast Fetch received no rows after its status probe reported available changes.",!0);await batchWriter.flush();await saveCheckpoint(onCheckpoint,parsed.lastSequence);reportProgress(!0);return parsed.lastSequence}if(fetchedRows>=pageLimit)throw new StreamingFetchFailure("protocol",`Fast Fetch received more than its ${pageLimit}-row page limit.`,!1);const change=parsed.change;fetchedRows++;totalFetched++;if(change.doc){await batchWriter.write(change.doc,change.seq);totalValidFetched++}else await batchWriter.flushThrough(change.seq);reportProgress()};try{const changesURL=setParamsToURL(new URL(`${remoteDbUrl}/_changes`),{...changesBaseParams,since:pageSince.toString(),limit:pageLimit.toString(),timeout:FAST_FETCH_CHANGES_PAGE_TIMEOUT_MS.toString()}),response=await fetchResponse(changesURL.toString(),{method:"GET",headers:fetchHeaders,signal:controller.signal},"open the changes feed");if(!response.body)throw new StreamingFetchFailure("protocol","Fast Fetch could not read the CouchDB response stream.",!1);const decoder2=new TextDecoder,byteCountingDecoderStream=new TransformStream({transform(chunk,streamController){totalBytes+=chunk.byteLength;const decoded=decoder2.decode(chunk,{stream:!0});decoded&&streamController.enqueue(decoded)},flush(streamController){const decoded=decoder2.decode();decoded&&streamController.enqueue(decoded)}});reader=response.body.pipeThrough(byteCountingDecoderStream).getReader();for(;;){reportProgress();let readResult;try{readResult=await reader.read()}catch(error){throw transportFailure("read the changes feed",error)}if(readResult.done){if(buffer.trim()){const lastSequence=await processLine(buffer);if(void 0!==lastSequence)return lastSequence}await batchWriter.flush();throw new StreamingFetchFailure("transport","The bounded CouchDB changes feed ended without a last_seq terminator.",!0)}buffer+=readResult.value;const lines=buffer.split("\n");buffer=lines.pop()||"";for(const line of lines){if(!line.trim())continue;const lastSequence=await processLine(line);if(void 0!==lastSequence)return lastSequence}}}finally{controller.abort();if(reader){try{await reader.cancel()}catch(e3){}reader.releaseLock()}}};try{let pageSince=since,started=!1;for(;;){const available=await readAvailableChanges(pageSince);docsToFetch=Math.max(docsToFetch,totalFetched+available);if(0===available)break;if(!started){started=!0;Logger(`Starting initial synchronisation. Current sequence: ${since}, Target sequence: ${progressTargetSeq}, Documents to fetch: ${docsToFetch}.`)}const pageLimit=Math.min(FAST_FETCH_CHANGES_PAGE_LIMIT,available),pageTerminator=await fetchPage(pageSince,pageLimit);pageSince=pageTerminator}if(started){Logger("Fast Fetch is caught up and durable in the local database.");reportProgress(!0)}else Logger("No changes remain for Fast Fetch.")}catch(error){const failure=asStreamingFetchFailure(error);if("storage"!==failure.stage)try{await batchWriter.flush()}catch(flushError){batchWriter.abort();throw asStreamingFetchFailure(flushError)}batchWriter.abort();Logger(`Fast Fetch failed during ${failure.stage}.`,LOG_LEVEL_VERBOSE);Logger(failure,LOG_LEVEL_VERBOSE);throw failure}}async function isIncomingTextClearExtension(incomingContent,localContent){const incomingBlob=createBlob(incomingContent),localBlob=createBlob(localContent);if(!isTextBlob(incomingBlob)||!isTextBlob(localBlob))return!1;const incomingText=await incomingBlob.text(),localText=await localBlob.text();return incomingText.startsWith(localText)||incomingText.endsWith(localText)}async function serializedByKeys(keys3,callback){const[key3,...remainingKeys]=keys3;return void 0===key3?await callback():await serialized(key3,()=>serializedByKeys(remainingKeys,callback))}function getParentPath(path2){const lastSeparator=path2.lastIndexOf("/");return lastSeparator<0?"":path2.slice(0,lastSeparator)}function isFolderInfo(info3){return!0===(null==info3?void 0:info3.isFolder)}function toArrayBuffer2(arr){return arr instanceof Uint8Array||arr instanceof DataView?arr.buffer:arr}function TFileToUXFileInfoStub(file,deleted){if(!(file instanceof import_obsidian.TFile))throw new Error("Invalid file type");const ret={name:file.name,path:file.path,isFolder:!1,stat:{size:file.stat.size,mtime:file.stat.mtime,ctime:file.stat.ctime,type:"file"},deleted};return ret}function InternalFileToUXFileInfoStub(filename,deleted){const name=filename.split("/").pop(),ret={name,path:filename,isFolder:!1,stat:void 0,isInternal:!0,deleted};return ret}function TFolderToUXFileInfoStub(file){var _a13;const ret={name:file.name,path:file.path,parent:null==(_a13=file.parent)?void 0:_a13.path,isFolder:!0,children:file.children.map(e3=>TFileToUXFileInfoStub(e3))};return ret}function toIntegerTimestamps(options){if(!options)return options;const sanitized={...options};"number"==typeof sanitized.mtime&&(sanitized.mtime=Math.floor(sanitized.mtime));"number"==typeof sanitized.ctime&&(sanitized.ctime=Math.floor(sanitized.ctime));return sanitized}function setNoticeClass(notice2){0}function __$checkInstanceBinding(instance){const thisName=instance.constructor.name,functions=[];for(const key3 of Object.getOwnPropertyNames(Object.getPrototypeOf(instance)))if(key3.startsWith("_")&&!key3.startsWith("__")){const method=instance[key3];"function"==typeof method&&functions.push(`${thisName}.${key3}`)}const onBindFunctionStr=instance.onBindFunction.toString(),functionsOnBindFunction=[],functionsOnBindFunctionMatch=onBindFunctionStr.match(/this\.(_[a-zA-Z0-9_]+)/g);functionsOnBindFunctionMatch&&functionsOnBindFunction.push(...functionsOnBindFunctionMatch.map(f4=>`${thisName}.${f4.replace(/this\./,"")}`));const setOfThisFunctions=new Set(functions),setOfOnBindFunctions=new Set(functionsOnBindFunction),setAll=new Set([...setOfThisFunctions,...setOfOnBindFunctions]),missingInThis=[...setAll].filter(e3=>!setOfThisFunctions.has(e3)),missingInOnBind=[...setAll].filter(e3=>!setOfOnBindFunctions.has(e3));missingInThis.length>0&&Logger(`[${thisName}] ⚠️ Missing functions in this: ${missingInThis.join(", ")}`);missingInOnBind.length>0&&Logger(`[${thisName}] ⚠️ Missing functions in onBindFunction: ${missingInOnBind.join(", ")}`);0==missingInThis.length&&0==missingInOnBind.length&&Logger(`[${thisName}] All functions are properly bound`,LOG_LEVEL_DEBUG)}function isAcceptedAlwaysFactory(host,log2){return file=>{log2("File is target finally: "+getStoragePathFromUXFileInfo(file),LOG_LEVEL_DEBUG);return Promise.resolve(!0)}}function isAcceptedInFilenameDuplicationFactory(host,log2){const fileCountMapComputed=new Computed({evaluation:async fileEventCount=>{const vaultFiles=(await host.serviceModules.storageAccess.getFileNames()).sort(),fileCountMap={};for(const file of vaultFiles){const lc2=file.toLowerCase();fileCountMap[lc2]?fileCountMap[lc2]++:fileCountMap[lc2]=1}return fileCountMap},requiresUpdate:(args,previousArgs,previousResult)=>!previousResult||(previousResult instanceof Error||(!previousArgs||args[0]!==previousArgs[0]))});return async function isAcceptedInFilenameDuplication(file){const fileCountMap=(await fileCountMapComputed.update(host.services.fileProcessing.totalStorageFileEventCount)).value,filepath=getStoragePathFromUXFileInfo(file),lc2=filepath.toLowerCase();if(host.services.vault.shouldCheckCaseInsensitively()&&lc2 in fileCountMap&&fileCountMap[lc2]>1){log2("File is duplicated (case-insensitive): "+filepath);return!1}log2("File is not duplicated: "+filepath,LOG_LEVEL_DEBUG);return!0}}function isAcceptedByLocalDBFactory(host,log2){const database=host.services.database,databaseEvents=host.services.databaseEvents;let isReady=promiseWithResolvers();databaseEvents.onDatabaseHasReady.addHandler(()=>{isReady.resolve();return Promise.resolve(!0)});databaseEvents.onUnloadDatabase.addHandler(()=>{isReady=promiseWithResolvers();return Promise.resolve(!0)});return async file=>{await isReady.promise;const filepath=getStoragePathFromUXFileInfo(file);if(!await Promise.resolve(database.localDatabase.isTargetFile(filepath))){log2("File is not target by local DB: "+filepath);return!1}log2("File is target by local DB: "+filepath,LOG_LEVEL_DEBUG);return!0}}function isAcceptedByIgnoreFilesFactory(host,log2){let ignoreFiles=[];const ignoreFileCacheMap=new Map,refreshSettings=()=>{const settings=host.services.setting.currentSettings();ignoreFiles=(null==settings?void 0:settings.ignoreFiles.split(",").map(e3=>e3.trim()))||[];return Promise.resolve(!0)},invalidateIgnoreFileCache=path2=>{const key3=path2.toLowerCase();ignoreFileCacheMap.delete(key3)},getIgnoreFile=async path2=>{const key3=path2.toLowerCase(),cached=ignoreFileCacheMap.get(key3);if(void 0!==cached)return cached;try{if(!await host.serviceModules.storageAccess.isExistsIncludeHidden(path2)){log2(`[ignore] Ignore file does not exist: ${path2}`,LOG_LEVEL_DEBUG);ignoreFileCacheMap.set(key3,!1);return!1}const file=await host.serviceModules.storageAccess.readHiddenFileText(path2),gitignore=file.split(/\r?\n/g).map(e3=>e3.replace(/\r$/,"")).map(e3=>e3.trim());ignoreFileCacheMap.set(key3,gitignore);log2(`[ignore] Ignore file loaded: ${path2}`,LOG_LEVEL_VERBOSE);return gitignore}catch(ex){log2(`[ignore] Failed to read ignore file ${path2}`);log2(ex,LOG_LEVEL_VERBOSE);ignoreFileCacheMap.set(key3,void 0);return!1}};host.services.setting.onSettingRealised.addHandler(refreshSettings);host.services.appLifecycle.onLoaded.addHandler(refreshSettings);refreshSettings();return async function isAcceptedByIgnoreFiles(file){const settings=host.services.setting.currentSettings();if(!settings.useIgnoreFiles)return!0;const filepath=getStoragePathFromUXFileInfo(file);invalidateIgnoreFileCache(filepath);log2("Checking ignore files for: "+filepath,LOG_LEVEL_DEBUG);if(!await isAcceptedAll(filepath,ignoreFiles,filename=>getIgnoreFile(filename))){log2("File is ignored by ignore files: "+filepath);return!1}log2("File is not ignored by ignore files: "+filepath,LOG_LEVEL_DEBUG);return!0}}function useTargetFilters(host){const logger2=createInstanceLogFunction("SFTargetFilter",host.services.API),services=host.services,serviceModules=host.serviceModules,_isAcceptedFilenameDuplication=isAcceptedInFilenameDuplicationFactory({services:{context:services.context,vault:services.vault,fileProcessing:services.fileProcessing},serviceModules:{storageAccess:serviceModules.storageAccess}},logger2),_isAcceptedByIgnoreFiles=isAcceptedByIgnoreFilesFactory({services:{context:services.context,setting:services.setting,appLifecycle:services.appLifecycle},serviceModules:{storageAccess:serviceModules.storageAccess}},logger2),_isAcceptedByLocalDB=isAcceptedByLocalDBFactory({services:{context:services.context,database:services.database,databaseEvents:services.databaseEvents},serviceModules:{}},logger2),_isAcceptedAlways=isAcceptedAlwaysFactory(services.context,logger2);services.vault.isTargetFile.addHandler(_isAcceptedFilenameDuplication,10);services.vault.isTargetFile.addHandler(_isAcceptedByIgnoreFiles,20);services.vault.isTargetFile.addHandler(_isAcceptedByLocalDB,30);services.vault.isTargetFile.addHandler(_isAcceptedAlways,100);services.vault.isIgnoredByIgnoreFile.addHandler(async file=>{const result=await _isAcceptedByIgnoreFiles(file);return!result})}async function purgeUnreferencedChunks(db,dryRun,connSetting,performCompact=!1){const info3=await db.info();let resultCount=0;const getSize=function(info22,key3){var _a13,_b6;return Number.parseInt(null!=(_b6=null==(_a13=null==info22?void 0:info22.sizes)?void 0:_a13[key3])?_b6:"0",10)},keySuffix=connSetting?"-remote":"-local";Logger(`${dryRun?"Counting":"Cleaning"} ${connSetting?"remote":"local"} database`,LOG_LEVEL_NOTICE);connSetting&&Logger(`Database active-size: ${sizeToHumanReadable(getSize(info3,"active"))}, external-size:${sizeToHumanReadable(getSize(info3,"external"))}, file-size: ${sizeToHumanReadable(getSize(info3,"file"))}`,LOG_LEVEL_NOTICE);Logger(`Collecting unreferenced chunks on ${info3.db_name}`,LOG_LEVEL_NOTICE,"gc-count-chunk"+keySuffix);const chunks=await collectUnreferencedChunks(db);resultCount=chunks.length;if(0==chunks.length)Logger(`No unreferenced chunks! ${info3.db_name}`,LOG_LEVEL_NOTICE,"gc-count-chunk"+keySuffix);else{Logger(`Number of unreferenced chunks on ${info3.db_name}: ${chunks.length}`,LOG_LEVEL_NOTICE,"gc-count-chunk"+keySuffix);if(dryRun){Logger(`DryRun of cleaning ${connSetting?"remote":"local"} database up: Done`,LOG_LEVEL_NOTICE);return resultCount}if(connSetting){Logger("Cleaning unreferenced chunks on remote",LOG_LEVEL_NOTICE,"gc-purge"+keySuffix);await purgeChunksRemote(connSetting,chunks)}else{Logger("Cleaning unreferenced chunks on local",LOG_LEVEL_NOTICE,"gc-purge"+keySuffix);await purgeChunksLocal(db,chunks)}Logger("Cleaning unreferenced chunks done!",LOG_LEVEL_NOTICE,"gc-purge"+keySuffix)}if(performCompact){Logger("Compacting database...",LOG_LEVEL_NOTICE,"gc-compact"+keySuffix);await db.compact();Logger("Compacting database done",LOG_LEVEL_NOTICE,"gc-compact"+keySuffix)}if(connSetting){const endInfo=await db.info();Logger(`Processed database active-size: ${sizeToHumanReadable(getSize(endInfo,"active"))}, external-size:${sizeToHumanReadable(getSize(endInfo,"external"))}, file-size: ${sizeToHumanReadable(getSize(endInfo,"file"))}`,LOG_LEVEL_NOTICE);Logger(`Reduced sizes: active-size: ${sizeToHumanReadable(getSize(info3,"active")-getSize(endInfo,"active"))}, external-size:${sizeToHumanReadable(getSize(info3,"external")-getSize(endInfo,"external"))}, file-size: ${sizeToHumanReadable(getSize(info3,"file")-getSize(endInfo,"file"))}`,LOG_LEVEL_NOTICE)}Logger(`Cleaning ${connSetting?"remote":"local"} database up: Done`,LOG_LEVEL_NOTICE);return resultCount}function transferChunks(key3,label2,dbFrom,dbTo,items){let totalProcessed=0;const total=items.length;return new QueueProcessor(async batched=>{const requestItems=batched.map(e3=>e3.id),local=await dbTo.allDocs({keys:requestItems}),batch=local.rows.filter(e3=>"error"in e3&&"not_found"==e3.error).map(e3=>e3.key);return batch},{batchSize:50,concurrentLimit:5,suspended:!0,delay:100},items).pipeTo(new QueueProcessor(async chunkIds=>{const docs=await dbFrom.allDocs({keys:chunkIds,include_docs:!0}),filteredDocs=docs.rows.filter(e3=>!("error"in e3)).map(e3=>e3.doc);return filteredDocs},{batchSize:25,concurrentLimit:1,suspended:!0,delay:100})).pipeTo(new QueueProcessor(async docs=>{try{await dbTo.bulkDocs(docs,{new_edits:!1})}catch(ex){Logger(`${label2}: Something went wrong on balancing`,LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_VERBOSE)}finally{totalProcessed+=docs.length;Logger(`${label2}: ${totalProcessed} / ${total}`,LOG_LEVEL_NOTICE,"balance-"+key3)}},{batchSize:100,delay:100,concurrentLimit:2,suspended:!1})).startPipeline().waitForAllDoneAndTerminate()}async function balanceChunkPurgedDBs(local,remote){Logger("Complement missing chunks between databases",LOG_LEVEL_NOTICE);try{const{onlyOnLocal,onlyOnRemote}=await collectUnbalancedChunkIDs(local,remote),localToRemote=transferChunks("l2r","local -> remote",local,remote,onlyOnLocal),remoteToLocal=transferChunks("r2l","remote -> local",remote,local,onlyOnRemote);await Promise.all([localToRemote,remoteToLocal]);Logger("local -> remote: Done",LOG_LEVEL_NOTICE,"balance-l2r");Logger("remote -> local: Done",LOG_LEVEL_NOTICE,"balance-r2l")}catch(ex){Logger("Something went wrong on balancing!",LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_VERBOSE)}Logger("Complement completed!",LOG_LEVEL_NOTICE)}async function purgeChunksLocal(db,docs){await serialized("purge-local",async()=>{try{Logger(`Purging unused ${docs.length} chunks `,LOG_LEVEL_NOTICE,"purge-local-backup");const batchDocsBackup=arrayToChunkedArray(docs,100);let total={ok:0,exist:0,error:0};for(const docsInBatch of batchDocsBackup){const backupDocsFrom=await db.allDocs({keys:docsInBatch.map(e3=>e3.id),include_docs:!0}),backupDocs=backupDocsFrom.rows.filter(e3=>"doc"in e3).map(e3=>{const chunk={...e3.doc};delete chunk._rev;chunk._id=`_local/${chunk._id}`;return chunk}),ret=await db.bulkDocs(backupDocs);total=ret.map(e3=>({ok:"ok"in e3?1:0,exist:"status"in e3&&409==e3.status?1:0,error:"status"in e3&&409!=e3.status?1:0})).reduce((p2,c3)=>({ok:p2.ok+c3.ok,exist:p2.exist+c3.exist,error:p2.error+c3.error}),total);Logger(`Local chunk backed up: new:${total.ok} ,exist:${total.exist}, error:${total.error}`,LOG_LEVEL_NOTICE,"purge-local-backup");const erroredItems=ret.filter(e3=>"error"in e3&&409!=e3.status);for(const item of erroredItems)Logger(`Failed to back up: ${item.id} / ${item.rev}`,LOG_LEVEL_VERBOSE)}}catch(ex){Logger("Could not back up chunks");Logger(ex,LOG_LEVEL_VERBOSE)}Logger(`Purging unused ${docs.length} chunks... `,LOG_LEVEL_NOTICE,"purge-local");const batchDocs=arrayToChunkedArray(docs,100);let totalRemoved=0;for(const docsInBatch of batchDocs){const removed=await db.purgeMulti(docsInBatch.map(e3=>[e3.id,e3.rev])),removedCount=Object.values(removed).filter(e3=>"ok"in e3).length;totalRemoved+=removedCount;Logger(`Purging: ${totalRemoved} / ${docs.length}`,LOG_LEVEL_NOTICE,"purge-local")}Logger(`Purging unused chunks done!: ${totalRemoved} chunks has been deleted.`,LOG_LEVEL_NOTICE,"purge-local")})}async function collectUnbalancedChunkIDs(local,remote){const chunksOnLocal=await collectChunks(local,"INUSE"),chunksOnRemote=await collectChunks(remote,"INUSE"),onlyOnLocal=chunksOnLocal.filter(e3=>!chunksOnRemote.some(ee=>ee.id==e3.id)),onlyOnRemote=chunksOnRemote.filter(e3=>!chunksOnLocal.some(ee=>ee.id==e3.id));return{onlyOnLocal,onlyOnRemote}}async function collectChunks(db,type){const rows=await collectChunksUsage(db),rowF="ALL"==type?rows:rows.filter(e3=>"DANGLING"==type?0==e3.value:0!=e3.value),ids=rowF.flatMap(e3=>e3.key),docs=(await db.allDocs({keys:ids})).rows,items=docs.filter(e3=>!("error"in e3)).map(e3=>({id:e3.id,rev:e3.value.rev}));return items}async function prepareChunkDesignDoc(db){var _a13;const chunkDesignDoc={_id:"_design/chunks",_rev:void 0,ver:2,views:{collectDangling:{map:(function(doc){doc._id.startsWith("h:")?emit([doc._id],0):"children"in doc&&doc.children.forEach(e3=>emit([e3],1))}).toString(),reduce:"_sum"}}};let updateDDoc=!1;try{const old=await db.get(chunkDesignDoc._id);if(null!=(_a13=null==old?void 0:old.ver)?_a13:0<chunkDesignDoc.ver){chunkDesignDoc._rev=old._rev;updateDDoc=!0}}catch(ex){if(!isNotFoundError(ex)){Logger("Failed to make design document for operating chunks");Logger(ex,LOG_LEVEL_VERBOSE);return!1}updateDDoc=!0}try{updateDDoc&&await db.put(chunkDesignDoc)}catch(ex){Logger("Failed to make design document for operating chunks");Logger(ex,LOG_LEVEL_VERBOSE);return!1}return!0}async function collectChunksUsage(db){if(!await prepareChunkDesignDoc(db)){Logger("Could not prepare design document for operating chunks");return[]}const q2=await db.query("chunks/collectDangling",{reduce:!0,group:!0}),rows=q2.rows;return rows}function collectUnreferencedChunks(db){return collectChunks(db,"DANGLING")}async function purgeChunksRemote(setting,docs){await serialized("purge-remote",async()=>{const buffer=function makeChunkedArrayFromArray(items){const chunked=[];for(let i3=0;i3<items.length;i3+=100)chunked.push(items.slice(i3,i3+100));return chunked}(docs);for(const chunkedPayload of buffer){const rets=await _requestToCouchDBFetch(`${setting.couchDB_URI.replace(/\/+$/,"")}/${setting.couchDB_DBNAME}`,setting.couchDB_USER,setting.couchDB_PASSWORD,"_purge",Object.fromEntries(chunkedPayload.map(e3=>[e3.id,[e3.rev]])),"POST");Logger(JSON.stringify(await rets.json()),LOG_LEVEL_VERBOSE)}})}function shortenId(id){return id.length>10?id.substring(0,10):id}function shortenRev(rev3){return rev3?rev3.length>10?rev3.substring(0,10):rev3:"undefined"}function isOnlineAndCanReplicate(errorManager,host,showMessage2){if(!host.services.API.isOnline){errorManager.showError("Network is offline",showMessage2?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO);return Promise.resolve(!1)}errorManager.clearError("Network is offline");return Promise.resolve(!0)}async function canReplicateWithPBKDF2(errorManager,host,showMessage2){const currentSettings=host.services.setting.currentSettings(),errorMessage2=$msg("Replicator.Message.InitialiseFatalError"),replicator=host.services.replicator.getActiveReplicator();if(!replicator){errorManager.showError(errorMessage2,showMessage2?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO);return!1}errorManager.clearError(errorMessage2);const ensureMessage=`${MARK_LOG_NETWORK_ERROR}Failed to initialise the encryption key, preventing replication.`,ensureResult=await replicator.ensurePBKDF2Salt(currentSettings,showMessage2,!1);if(!ensureResult){errorManager.showError(ensureMessage,showMessage2?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO);return!1}errorManager.clearError(ensureMessage);return ensureResult}function localisedConfName(key3){const info3=configurationNames[key3];return info3?`${translateIfAvailable(info3.name)}${statusDisplay(info3.status)}`:""}function valueToString(value){return"boolean"==typeof value?value?"true":"false":"object"==typeof value?JSON.stringify(value):`${value}`}async function prepareDatabaseForUse(host,log2,errorManager,showingNotice=!1,reopenDatabase=!0,ignoreSuspending=!1){const appLifecycle=host.services.appLifecycle;appLifecycle.resetIsReady();if(reopenDatabase&&!await host.services.database.openDatabase({databaseEvents:host.services.databaseEvents,replicator:host.services.replicator}))return!1;if(!host.services.database.isDatabaseReady())return!1;if(!await host.services.vault.scanVault(showingNotice,ignoreSuspending))return!1;if(!await host.services.databaseEvents.onDatabaseInitialised(showingNotice)){errorManager.showError("Initializing database has been failed on some module!",LOG_LEVEL_NOTICE);return!1}errorManager.clearError("Initializing database has been failed on some module!");if(!await host.services.fileProcessing.commitPendingFileEvents())return!1;appLifecycle.markIsReady();return!0}function usePrepareDatabaseForUse(host){createInstanceLogFunction("SF:prepareDatabaseForUse",host.services.API);const errorManager=new UnresolvedErrorManager(host.services.appLifecycle,host.services.context.events);host.services.databaseEvents.initialiseDatabase.addHandler(async(showingNotice=!1,reopenDatabase=!0,ignoreSuspending=!1)=>await prepareDatabaseForUse(host,0,errorManager,showingNotice,reopenDatabase,ignoreSuspending))}function checkUnsuitableValues(setting,regulation=DoctorRegulation){var _a13,_b6;const result={version:regulation.version,rules:{}};for(const key3 in regulation.rules){if(!regulation.rules.hasOwnProperty(key3))continue;const rule=regulation.rules[key3];if(!rule)continue;const value=setting[key3];if(rule.value!==value){if("number"==typeof value&&"min"in rule&&"max"in rule){const min2=null!=(_a13=rule.min)?_a13:Number.MIN_SAFE_INTEGER,max3=null!=(_b6=rule.max)?_b6:Number.MAX_SAFE_INTEGER;if(value>=min2&&value<=max3){Logger(`Rule satisfied: ${key3} is ${value} between ${min2} and ${max3}`);continue}}if(!rule.detectionFunc||rule.detectionFunc(setting)){result.rules[key3]=rule;Logger(`Rule violation: ${key3} is ${value} but should be ${rule.value}`)}else Logger(`Rule condition satisfied: ${key3} is ${value}, and detection function returned false`)}else Logger(`Rule satisfied: ${key3} is ${value}`)}return result}async function performDoctorConsultation(env,settings,{localRebuild=RebuildOptions_ConfirmIfRequired,remoteRebuild=RebuildOptions_ConfirmIfRequired,activateReason="updated",forceRescan=!1}){function getResult(){return{settings,shouldRebuild,shouldRebuildLocal,isModified}}var _a13,_b6,_c3;const translate=env.translate;let shouldRebuild=!1,shouldRebuildLocal=!1,isModified=!1;const r4=checkUnsuitableValues(settings);if(!forceRescan&&r4.version==settings.doctorProcessedVersion){const isIssueFound=Object.keys(r4.rules).length>0,msg=isIssueFound?"Issues found":"No issues found";Logger(`${msg} but marked as to be silent`,LOG_LEVEL_VERBOSE);return getResult()}const issues=Object.entries(r4.rules);if(0==issues.length){Logger(translate("Doctor.Message.NoIssues"),"updated"!==activateReason?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO);return getResult()}{const OPT_YES=`${translate("Doctor.Button.Yes")}`,OPT_NO=`${translate("Doctor.Button.No")}`,OPT_DISMISS=`${translate("Doctor.Button.DismissThisVersion")}`,issues2=Object.keys(r4.rules).map(key3=>`- ${getConfName(key3,translate)}`).join("\n"),msg=await env.confirm.askSelectStringDialogue(translate("Doctor.Dialogue.Main",{activateReason,issues:issues2}),[OPT_YES,OPT_NO,OPT_DISMISS],{title:translate("Doctor.Dialogue.Title"),defaultAction:OPT_YES});if(msg==OPT_DISMISS){settings.doctorProcessedVersion=r4.version;isModified=!0;Logger("Marked as to be silent",LOG_LEVEL_VERBOSE);return{settings,shouldRebuild,shouldRebuildLocal,isModified}}if(msg!=OPT_YES)return getResult();const issueItems=Object.entries(r4.rules);Logger(`${issueItems.length} Issue(s) found `,LOG_LEVEL_VERBOSE);let idx2=0;const applySettings={},OPT_FIX=`${translate("Doctor.Button.Fix")}`,OPT_SKIP=`${translate("Doctor.Button.Skip")}`,OPTION_FIX_WITHOUT_REBUILD=`${translate("Doctor.Button.FixButNoRebuild")}`;let skipped=0;for(const[key3,value]of issueItems){const levelMap={[1]:translate("Doctor.Level.Necessary"),[2]:translate("Doctor.Level.Recommended"),[3]:translate("Doctor.Level.Optional"),[0]:translate("Doctor.Level.Must")},level=value.level?levelMap[value.level]:"Unknown",options=[OPT_FIX];let askRebuild=!1,askRebuildLocal=!1;if(value.requireRebuild)if(remoteRebuild==RebuildOptions_AutomaticAcceptable){askRebuild=!1;shouldRebuild=!0}else if(remoteRebuild==RebuildOptions_ConfirmIfRequired)askRebuild=!0;else if(remoteRebuild==RebuildOptions_SkipEvenIfRequired){askRebuild=!1;shouldRebuild=!1}if(value.requireRebuildLocal)if(localRebuild==RebuildOptions_AutomaticAcceptable){askRebuildLocal=!1;shouldRebuildLocal=!0}else if(localRebuild==RebuildOptions_ConfirmIfRequired)askRebuildLocal=!0;else if(localRebuild==RebuildOptions_SkipEvenIfRequired){askRebuildLocal=!1;shouldRebuildLocal=!1}(askRebuild||askRebuildLocal)&&options.push(OPTION_FIX_WITHOUT_REBUILD);options.push(OPT_SKIP);const note=`${askRebuild?translate("Doctor.Message.RebuildRequired"):""}${askRebuildLocal?translate("Doctor.Message.RebuildLocalRequired"):""}`,ret=await env.confirm.askSelectStringDialogue(translate("Doctor.Dialogue.MainFix",{name:getConfName(key3,translate),current:`${settings[key3]}`,reason:null!=(_c3=null!=(_b6=null==(_a13=value.reasonFunc)?void 0:_a13.call(value,settings,translate))?_b6:value.reason)?_c3:" N/A ",ideal:`${value.valueDisplayFunc?value.valueDisplayFunc(settings):value.value}`,level:`${level}`,note}),options,{title:translate("Doctor.Dialogue.TitleFix",{current:""+ ++idx2,total:`${issueItems.length}`}),defaultAction:OPT_FIX});if(ret==OPT_FIX||ret==OPTION_FIX_WITHOUT_REBUILD){applySettings[key3]=value.value;if(ret==OPT_FIX){shouldRebuild=shouldRebuild||askRebuild||!1;shouldRebuildLocal=shouldRebuildLocal||askRebuildLocal||!1}isModified=!0}else skipped++}Object.keys(applySettings).length>0&&(settings={...settings,...applySettings});if(0==skipped){settings.doctorProcessedVersion=r4.version;isModified=!0}else if("no"==await env.confirm.askYesNoDialog(translate("Doctor.Message.SomeSkipped"),{title:translate("Doctor.Dialogue.TitleAlmostDone"),defaultOption:"No"})){settings.doctorProcessedVersion=r4.version;isModified=!0}}return getResult()}async function openOnboarding(setupManager){return await setupManager.startOnBoarding()}function showOnboardingInvitation(host,setupManager){const message=`${$msg("Welcome to Self-hosted LiveSync")} ${$msg("We will now guide you through a few questions to simplify the synchronisation setup.")} {HERE}`;host.services.UI.confirm.askInPopup("initial-onboarding",message,anchor=>{anchor.href="#";anchor.classList.add("sls-onboarding-invitation-action");anchor.textContent=$msg("Ui.SetupWizard.Invitation.Start");anchor.addEventListener("click",event2=>{event2.preventDefault();fireAndForget(()=>openOnboarding(setupManager))})},ONBOARDING_NOTICE_DURATION_MS)}async function openSetupURI(setupManager){await setupManager.onUseSetupURI("unknown")}async function openP2PSettings(host,setupManager){return await setupManager.onP2PManualSetup("unknown",host.services.setting.currentSettings(),!1)}function useSetupManagerHandlersFeature(host,setupManager){host.services.appLifecycle.onLoaded.addHandler(()=>{host.services.API.addCommand({id:"livesync-opensetupuri",name:"Use the copied setup URI (Formerly Open setup URI)",callback:()=>fireAndForget(openSetupURI(setupManager))});host.services.context.events.onEvent(EVENT_REQUEST_OPEN_SETUP_URI,()=>fireAndForget(()=>openSetupURI(setupManager)));host.services.context.events.onEvent(EVENT_REQUEST_OPEN_P2P_SETTINGS,()=>fireAndForget(()=>openP2PSettings(host,setupManager)));return Promise.resolve(!0)})}function runStartupEntryLifecycle(runtime){if(runtime.configured)return!0;runtime.inviteToOnboarding();return!1}async function runConfiguredStartupLifecycle(runtime){if(!runtime.databaseReady){runtime.reportDatabaseNotReady();return!1}if(!await runtime.hasCompromisedChunks())return!1;if(!await runtime.hasIncompleteDocuments())return!1;await runtime.waitForCompatibilityReview();if(!await runtime.runDoctor())return!1;await runtime.migrateBulkSend();return!0}function tryGetLanguage(onError){if((0,import_obsidian.requireApiVersion)("1.8.7"))try{return(0,import_obsidian.getLanguage)()}catch(e3){onError(e3)}return"en"}function configureReviewAnchor(anchor,label2,review){anchor.href="#";anchor.textContent=label2;anchor.addEventListener("click",event2=>{event2.preventDefault();fireAndForget(review)})}function onNotifyRemoteSizeNotConfiguredFactory(host,log2,mode="notice"){return async()=>{const translate=host.services.context.translate;log2(translate("moduleCheckRemoteSize.logCheckingStorageSizes"),LOG_LEVEL_VERBOSE);const settings=host.services.setting.currentSettings();if(settings.notifyThresholdOfRemoteStorageSize>=0)return!0;const message=translate("moduleCheckRemoteSize.msgSetDBCapacity"),ANSWER_0=translate("moduleCheckRemoteSize.optionNoWarn"),ANSWER_800=translate("moduleCheckRemoteSize.option800MB"),ANSWER_2000=translate("moduleCheckRemoteSize.option2GB"),ASK_ME_NEXT_TIME=translate("moduleCheckRemoteSize.optionAskMeLater");if("notice"===mode){host.services.API.confirm.askInPopup("remote-size-not-configured",translate("moduleCheckRemoteSize.noticeNotConfigured"),anchor=>configureReviewAnchor(anchor,translate("moduleCheckRemoteSize.optionReview"),()=>onNotifyRemoteSizeNotConfiguredFactory(host,log2,"dialogue")()),REMOTE_SIZE_NOTICE_DURATION_MS);return!0}const ret=await host.services.API.confirm.askSelectStringDialogue(message,[ANSWER_0,ANSWER_800,ANSWER_2000,ASK_ME_NEXT_TIME],{defaultAction:ASK_ME_NEXT_TIME,title:translate("moduleCheckRemoteSize.titleDatabaseSizeNotify")});ret==ANSWER_0?await host.services.setting.applyPartial({notifyThresholdOfRemoteStorageSize:0},!0):ret==ANSWER_800?await host.services.setting.applyPartial({notifyThresholdOfRemoteStorageSize:800},!0):ret==ANSWER_2000&&await host.services.setting.applyPartial({notifyThresholdOfRemoteStorageSize:2e3},!0);return!0}}function onNotifyRemoteSizeExceedFactory(host,log2,mode="notice"){return async()=>{const translate=host.services.context.translate,settings=host.services.setting.currentSettings();if(settings.notifyThresholdOfRemoteStorageSize<=0){log2("User has chosen to not receive remote storage size exceed notification.",LOG_LEVEL_INFO);return!0}if(!1===host.services.API.isOnline){log2("Network is offline, skipping remote size exceed check.",LOG_LEVEL_INFO);return!0}const replicator=host.services.replicator.getActiveReplicator(),remoteStat=await(null==replicator?void 0:replicator.getRemoteStatus(host.services.setting.currentSettings()));if(!remoteStat){log2("Failed to get remote status, skipping remote size exceed check.",LOG_LEVEL_INFO);return!0}const estimatedSize=remoteStat.estimatedSize;if(estimatedSize){const maxSize=1024*settings.notifyThresholdOfRemoteStorageSize*1024;if(estimatedSize<=maxSize){log2(translate("moduleCheckRemoteSize.logCurrentStorageSize",{measuredSize:sizeToHumanReadable(estimatedSize)}),LOG_LEVEL_INFO);return!0}const message=translate("moduleCheckRemoteSize.msgDatabaseGrowing",{estimatedSize:sizeToHumanReadable(estimatedSize),maxSize:sizeToHumanReadable(maxSize)}),newMax=100+~~(estimatedSize/1024/1024),ANSWER_ENLARGE_LIMIT=translate("moduleCheckRemoteSize.optionIncreaseLimit",{newMax:newMax.toString()}),ANSWER_REBUILD=translate("moduleCheckRemoteSize.optionRebuildAll"),ANSWER_IGNORE=translate("moduleCheckRemoteSize.optionDismiss");if("notice"===mode){host.services.API.confirm.askInPopup("remote-size-exceeded",translate("moduleCheckRemoteSize.noticeExceeded",{measuredSize:sizeToHumanReadable(estimatedSize),notifySize:sizeToHumanReadable(maxSize)}),anchor=>configureReviewAnchor(anchor,translate("moduleCheckRemoteSize.optionReview"),()=>onNotifyRemoteSizeExceedFactory(host,log2,"dialogue")()),REMOTE_SIZE_NOTICE_DURATION_MS);return!0}const ret=await host.services.API.confirm.askSelectStringDialogue(message,[ANSWER_ENLARGE_LIMIT,ANSWER_REBUILD,ANSWER_IGNORE],{defaultAction:ANSWER_IGNORE,title:translate("moduleCheckRemoteSize.titleDatabaseSizeLimitExceeded")});if(ret==ANSWER_REBUILD){const ret2=await host.services.API.confirm.askYesNoDialog(translate("moduleCheckRemoteSize.msgConfirmRebuild"),{defaultOption:"No"});if("yes"==ret2){await host.services.setting.applyPartial({notifyThresholdOfRemoteStorageSize:-1},!0);await host.serviceModules.rebuilder.scheduleRebuild();return!1}return!0}if(ret==ANSWER_ENLARGE_LIMIT){const newThreshold=100+~~(estimatedSize/1024/1024);log2(translate("moduleCheckRemoteSize.logThresholdEnlarged",{size:newThreshold.toString()}),LOG_LEVEL_NOTICE);await host.services.setting.applyPartial({notifyThresholdOfRemoteStorageSize:newThreshold},!0);return!0}log2(translate("moduleCheckRemoteSize.logExceededWarning",{measuredSize:sizeToHumanReadable(estimatedSize),notifySize:sizeToHumanReadable(1024*settings.notifyThresholdOfRemoteStorageSize*1024)}),LOG_LEVEL_INFO)}return!0}}async function scanAllStat(host,log2,resetThreshold=!1,mode="notice"){resetThreshold&&await host.services.setting.applyPartial({notifyThresholdOfRemoteStorageSize:-1},!0);const onNotifyNotConfigured=onNotifyRemoteSizeNotConfiguredFactory(host,log2,mode),onNotifyExceed=onNotifyRemoteSizeExceedFactory(host,log2,mode);return await onNotifyNotConfigured()&&await onNotifyExceed()}function useCheckRemoteSize(host){const log2=createInstanceLogFunction("SFCheckRemoteSize",host.services.API);host.services.appLifecycle.onScanningStartupIssues.addHandler(()=>scanAllStat(host,log2,!1));host.services.appLifecycle.onInitialise.addHandler(()=>{host.services.API.addCommand({id:"livesync-reset-remote-size-threshold-and-check",name:"Reset notification threshold and check the remote database usage",callback:async()=>{await scanAllStat(host,log2,!0,"dialogue")}});host.services.context.events.onEvent(EVENT_REQUEST_CHECK_REMOTE_SIZE,()=>scanAllStat(host,log2,!0,"dialogue"));return Promise.resolve(!0)})}function Check($$anchor,$$props){var fragment,label2,input,span,text2,div,node,consequent,consequent_1,node_3;push($$props,!0);append_styles($$anchor,$$css14);let value=prop($$props,"value",15);const translatedTitle=user_derived(()=>translateIfAvailable($$props.title));fragment=root38();label2=first_child(fragment);input=child(label2);remove_input_defaults(input);span=sibling(input,2);text2=child(span,!0);reset(span);reset(label2);div=sibling(label2,2);node=child(div);consequent=$$anchor2=>{var fragment_1=comment(),node_1=first_child(fragment_1);snippet(node_1,()=>$$props.noteOnSelected);append($$anchor2,fragment_1)};consequent_1=$$anchor2=>{var fragment_2=comment(),node_2=first_child(fragment_2);snippet(node_2,()=>$$props.noteOnUnselected);append($$anchor2,fragment_2)};if_block(node,$$render=>{value()&&$$props.noteOnSelected?$$render(consequent):!value()&&$$props.noteOnUnselected&&$$render(consequent_1,1)});node_3=sibling(node,2);snippet(node_3,()=>{var _a13;return null!=(_a13=$$props.children)?_a13:noop2});reset(div);template_effect(()=>set_text(text2,get2(translatedTitle)));bind_checked(input,value);append($$anchor,fragment);pop()}function FetchEverything($$anchor,$$props){function commit(){$$props.setResult({vault:get2(vaultType),backup:get2(backupType),extra:{preventFetchingConfig:get2(preventFetchingConfig)}})}var fragment,node,node_1,node_2,node_3,node_10,node_17,node_18;push($$props,!0);let vaultType=state(proxy(TYPE_CANCEL)),backupType=state(proxy(TYPE_CANCEL));const canProceed=user_derived(()=>!(get2(vaultType)!==TYPE_IDENTICAL&&get2(vaultType)!==TYPE_INDEPENDENT&&get2(vaultType)!==TYPE_UNBALANCED||get2(backupType)!==TYPE_BACKUP_DONE&&get2(backupType)!==TYPE_BACKUP_SKIPPED));let preventFetchingConfig=state(!1);fragment=root_69();node=first_child(fragment);{let $0=user_derived(()=>$msg("Reset Synchronisation on This Device"));DialogHeader(node,{get title(){return get2($0)}})}node_1=sibling(node,2);Guidance(node_1,{children:($$anchor2,$$slotProps)=>{next();var text2=text();template_effect($0=>set_text(text2,$0),[()=>$msg("This will rebuild the local database on this device using the most recent data from the server. This action is designed to resolve synchronisation inconsistencies and restore correct functionality.")]);append($$anchor2,text2)},$$slots:{default:!0}});node_2=sibling(node_1,2);{let $0=user_derived(()=>$msg("⚠️ Important Notice"));Guidance(node_2,{important:!0,get title(){return get2($0)},children:($$anchor2,$$slotProps)=>{var text_2,fragment_2=root39(),strong=first_child(fragment_2),text_1=child(strong,!0);reset(strong);text_2=sibling(strong,2);template_effect(($02,$1)=>{set_text(text_1,$02);set_text(text_2,` ${null!=$1?$1:""}`)},[()=>$msg("If you have unsynchronised changes in your Vault on this device, they will likely diverge from the server's versions after the reset. This may result in a large number of file conflicts."),()=>$msg("Furthermore, if conflicts are already present in the server data, they will be synchronised to this device as they are, and you will need to resolve them locally.")]);append($$anchor2,fragment_2)},$$slots:{default:!0}})}node_3=sibling(node_2,4);Instruction(node_3,{children:($$anchor2,$$slotProps)=>{var node_5,fragment_3=root_49(),node_4=first_child(fragment_3);Question(node_4,{children:($$anchor3,$$slotProps2)=>{var text_4,fragment_4=root_131(),strong_1=first_child(fragment_4),text_3=child(strong_1,!0);reset(strong_1);text_4=sibling(strong_1,1,!0);template_effect(($0,$1)=>{set_text(text_3,$0);set_text(text_4,$1)},[()=>$msg("To minimise the creation of new conflicts"),()=>$msg(", please select the option that best describes the current state of your Vault. The application will then check your files in the most appropriate way based on your selection.")]);append($$anchor3,fragment_4)},$$slots:{default:!0}});node_5=sibling(node_4,2);Options(node_5,{children:($$anchor3,$$slotProps2)=>{var node_7,node_8,fragment_5=root_315(),node_6=first_child(fragment_5);let $0=user_derived(()=>$msg("The files in this Vault are almost identical to the server's."));Option(node_6,{get selectedValue(){return TYPE_IDENTICAL},get title(){return get2($0)},get value(){return get2(vaultType)},set value($$value){set(vaultType,$$value,!0)},children:($$anchor4,$$slotProps3)=>{next();var text_5=text();template_effect($02=>set_text(text_5,$02),[()=>$msg("(e.g., immediately after restoring on another computer, or having recovered from a backup)")]);append($$anchor4,text_5)},$$slots:{default:!0}});node_7=sibling(node_6,2);{let $0=user_derived(()=>$msg("This Vault is empty, or contains only new files that are not on the server."));Option(node_7,{get selectedValue(){return TYPE_INDEPENDENT},get title(){return get2($0)},get value(){return get2(vaultType)},set value($$value){set(vaultType,$$value,!0)},children:($$anchor4,$$slotProps3)=>{next();var text_6=text();template_effect($02=>set_text(text_6,$02),[()=>$msg("(e.g., setting up for the first time on a new smartphone, starting from a clean slate)")]);append($$anchor4,text_6)},$$slots:{default:!0}})}node_8=sibling(node_7,2);{let $0=user_derived(()=>$msg("There may be differences between the files in this Vault and the server."));Option(node_8,{get selectedValue(){return TYPE_UNBALANCED},get title(){return get2($0)},get value(){return get2(vaultType)},set value($$value){set(vaultType,$$value,!0)},children:($$anchor4,$$slotProps3)=>{var fragment_8,text_7,node_9;next();fragment_8=root_217();text_7=first_child(fragment_8);node_9=sibling(text_7);InfoNote(node_9,{info:!0,children:($$anchor5,$$slotProps4)=>{next();var text_8=text();template_effect($02=>set_text(text_8,$02),[()=>$msg("In this scenario, Self-hosted LiveSync will recreate metadata for every file and deliberately generate conflicts. Where the file content is identical, these conflicts will be resolved automatically.")]);append($$anchor5,text_8)},$$slots:{default:!0}});template_effect($02=>set_text(text_7,`${null!=$02?$02:""} `),[()=>$msg("(e.g., after editing many files whilst offline)")]);append($$anchor4,fragment_8)},$$slots:{default:!0}})}append($$anchor3,fragment_5)},$$slots:{default:!0}});append($$anchor2,fragment_3)},$$slots:{default:!0}});node_10=sibling(node_3,4);Instruction(node_10,{children:($$anchor2,$$slotProps)=>{var node_12,node_13,fragment_10=root_315(),node_11=first_child(fragment_10);Question(node_11,{children:($$anchor3,$$slotProps2)=>{next();var text_9=text();template_effect($0=>set_text(text_9,$0),[()=>$msg("Have you created a backup before proceeding?")]);append($$anchor3,text_9)},$$slots:{default:!0}});node_12=sibling(node_11,2);InfoNote(node_12,{children:($$anchor3,$$slotProps2)=>{next();var text_10=text();template_effect($0=>set_text(text_10,$0),[()=>$msg("We recommend that you copy your Vault folder to a safe location. This will provide a safeguard in case a large number of conflicts arise, or if you accidentally synchronise with an incorrect destination.")]);append($$anchor3,text_10)},$$slots:{default:!0}});node_13=sibling(node_12,2);Options(node_13,{children:($$anchor3,$$slotProps2)=>{var node_15,node_16,fragment_13=root_315(),node_14=first_child(fragment_13);let $0=user_derived(()=>$msg("I have created a backup of my Vault."));Option(node_14,{get selectedValue(){return TYPE_BACKUP_DONE},get title(){return get2($0)},get value(){return get2(backupType)},set value($$value){set(backupType,$$value,!0)}});node_15=sibling(node_14,2);{let $0=user_derived(()=>$msg("I understand the risks and will proceed without a backup."));Option(node_15,{get selectedValue(){return TYPE_BACKUP_SKIPPED},get title(){return get2($0)},get value(){return get2(backupType)},set value($$value){set(backupType,$$value,!0)}})}node_16=sibling(node_15,2);{let $0=user_derived(()=>$msg("I am unable to create a backup of my Vault."));Option(node_16,{get selectedValue(){return TYPE_UNABLE_TO_BACKUP},get title(){return get2($0)},get value(){return get2(backupType)},set value($$value){set(backupType,$$value,!0)},children:($$anchor4,$$slotProps3)=>{{let $02=user_derived(()=>get2(backupType)===TYPE_UNABLE_TO_BACKUP);InfoNote($$anchor4,{error:!0,get visible(){return get2($02)},children:($$anchor5,$$slotProps4)=>{var text_12,fragment_15=root_59(),strong_2=first_child(fragment_15),text_11=child(strong_2,!0);reset(strong_2);text_12=sibling(strong_2,3);template_effect(($03,$1)=>{set_text(text_11,$03);set_text(text_12,` ${null!=$1?$1:""}`)},[()=>$msg("It is strongly advised to create a backup before proceeding. Continuing without a backup may lead to data loss."),()=>$msg("If you understand the risks and still wish to proceed, select so.")]);append($$anchor5,fragment_15)},$$slots:{default:!0}})}},$$slots:{default:!0}})}append($$anchor3,fragment_13)},$$slots:{default:!0}});append($$anchor2,fragment_10)},$$slots:{default:!0}});node_17=sibling(node_10,2);Instruction(node_17,{children:($$anchor2,$$slotProps)=>{{let $0=user_derived(()=>$msg("Advanced"));ExtraItems($$anchor2,{get title(){return get2($0)},children:($$anchor3,$$slotProps2)=>{{let $02=user_derived(()=>$msg("Use this device's settings"));Check($$anchor3,{get title(){return get2($02)},get value(){return get2(preventFetchingConfig)},set value($$value){set(preventFetchingConfig,$$value,!0)},children:($$anchor4,$$slotProps3)=>{InfoNote($$anchor4,{children:($$anchor5,$$slotProps4)=>{next();var text_13=text();template_effect($03=>set_text(text_13,$03),[()=>$msg("Skips checking and applying synchronisation settings from the remote.")]);append($$anchor5,text_13)},$$slots:{default:!0}})},$$slots:{default:!0}})}},$$slots:{default:!0}})}},$$slots:{default:!0}});node_18=sibling(node_17,2);UserDecisions(node_18,{children:($$anchor2,$$slotProps)=>{var node_20,fragment_20=root_49(),node_19=first_child(fragment_20);let $0=user_derived(()=>$msg("Reset and Resume Synchronisation")),$1=user_derived(()=>!get2(canProceed));Decision(node_19,{get title(){return get2($0)},important:!0,get disabled(){return get2($1)},commit:()=>commit()});node_20=sibling(node_19,2);{let $0=user_derived(()=>$msg("Cancel"));Decision(node_20,{get title(){return get2($0)},commit:()=>$$props.setResult(TYPE_CANCEL)})}append($$anchor2,fragment_20)},$$slots:{default:!0}});append($$anchor,fragment);pop()}function RebuildEverything($$anchor,$$props){function commit(){$$props.setResult({backup:get2(backupType),extra:{preventFetchingConfig:get2(preventFetchingConfig)}})}var _a13,fragment,node,consequent,alternate,node_14,node_21,consequent_1,node_22;push($$props,!0);const isP2P=user_derived(()=>!0===(null===(_a13=null===$$props.getInitialData||void 0===$$props.getInitialData?void 0:$$props.getInitialData())||void 0===_a13?void 0:_a13.isP2P));let backupType=state(proxy(TYPE_CANCEL)),confirmationCheck1=state(!1),confirmationCheck2=state(!1),confirmationCheck3=state(!1);const canProceed=user_derived(()=>{const backupConfirmed=get2(backupType)===TYPE_BACKUP_DONE||get2(backupType)===TYPE_BACKUP_SKIPPED;return get2(isP2P)?backupConfirmed&&get2(confirmationCheck1):backupConfirmed&&get2(confirmationCheck1)&&get2(confirmationCheck2)&&get2(confirmationCheck3)});let preventFetchingConfig=state(!1);fragment=root_510();node=first_child(fragment);consequent=$$anchor2=>{var node_2,node_3,node_4,fragment_1=root40(),node_1=first_child(fragment_1);let $0=user_derived(()=>$msg("Ui.SetupWizard.RebuildEverythingP2P.Title"));DialogHeader(node_1,{get title(){return get2($0)}});node_2=sibling(node_1,2);Guidance(node_2,{children:($$anchor3,$$slotProps)=>{next();var text2=text();template_effect($0=>set_text(text2,$0),[()=>$msg("Ui.SetupWizard.RebuildEverythingP2P.Guidance")]);append($$anchor3,text2)},$$slots:{default:!0}});node_3=sibling(node_2,2);InfoNote(node_3,{children:($$anchor3,$$slotProps)=>{next();var text_1=text();template_effect($0=>set_text(text_1,$0),[()=>$msg("Ui.SetupWizard.RebuildEverythingP2P.Note")]);append($$anchor3,text_1)},$$slots:{default:!0}});node_4=sibling(node_3,2);{let $0=user_derived(()=>$msg("Ui.SetupWizard.RebuildEverythingP2P.ConfirmTitle"));Guidance(node_4,{important:!0,get title(){return get2($0)},children:($$anchor3,$$slotProps)=>{{let $02=user_derived(()=>$msg("Ui.SetupWizard.RebuildEverythingP2P.ConfirmLocalReset"));Check($$anchor3,{get title(){return get2($02)},get value(){return get2(confirmationCheck1)},set value($$value){set(confirmationCheck1,$$value,!0)},children:($$anchor4,$$slotProps2)=>{InfoNote($$anchor4,{children:($$anchor5,$$slotProps3)=>{next();var text_2=text();template_effect($03=>set_text(text_2,$03),[()=>$msg("Ui.SetupWizard.RebuildEverythingP2P.ConfirmLocalResetNote")]);append($$anchor5,text_2)},$$slots:{default:!0}})},$$slots:{default:!0}})}},$$slots:{default:!0}})}append($$anchor2,fragment_1)};alternate=$$anchor2=>{var node_6,node_7,node_8,fragment_7=root40(),node_5=first_child(fragment_7);let $0=user_derived(()=>$msg("Final Confirmation: Overwrite Server Data with This Device's Files"));DialogHeader(node_5,{get title(){return get2($0)}});node_6=sibling(node_5,2);Guidance(node_6,{children:($$anchor3,$$slotProps)=>{var fragment_8,text_3,strong,text_4;next();fragment_8=root_135();text_3=first_child(fragment_8);strong=sibling(text_3);text_4=child(strong,!0);reset(strong);next();template_effect(($0,$1)=>{set_text(text_3,`${null!=$0?$0:""} `);set_text(text_4,$1)},[()=>$msg("This procedure will first delete all existing synchronisation data from the server. Following this, the server data will be completely rebuilt, using the current state of your Vault on this device (including its local database) as"),()=>$msg("the single, authoritative master copy")]);append($$anchor3,fragment_8)},$$slots:{default:!0}});node_7=sibling(node_6,2);InfoNote(node_7,{children:($$anchor3,$$slotProps)=>{next();var text_5=text();template_effect($0=>set_text(text_5,$0),[()=>$msg("You should perform this operation only in exceptional circumstances, such as when the server data is completely corrupted, when changes on all other devices are no longer needed, or when the database size has become unusually large in comparison to the Vault size.")]);append($$anchor3,text_5)},$$slots:{default:!0}});node_8=sibling(node_7,2);{let $0=user_derived(()=>$msg("⚠️ Please Confirm the Following"));Guidance(node_8,{important:!0,get title(){return get2($0)},children:($$anchor3,$$slotProps)=>{var node_12,node_13,fragment_10=root_316(),node_9=first_child(fragment_10);let $02=user_derived(()=>$msg("I understand that all changes made on other smartphones or computers possibly could be lost."));Check(node_9,{get title(){return get2($02)},get value(){return get2(confirmationCheck1)},set value($$value){set(confirmationCheck1,$$value,!0)},children:($$anchor4,$$slotProps2)=>{var node_11,fragment_11=root_218(),node_10=first_child(fragment_11);InfoNote(node_10,{children:($$anchor5,$$slotProps3)=>{next();var text_6=text();template_effect($03=>set_text(text_6,$03),[()=>$msg("There is a way to resolve this on other devices.")]);append($$anchor5,text_6)},$$slots:{default:!0}});node_11=sibling(node_10,2);InfoNote(node_11,{children:($$anchor5,$$slotProps3)=>{next();var text_7=text();template_effect($03=>set_text(text_7,$03),[()=>$msg("Of course, we can back up the data before proceeding.")]);append($$anchor5,text_7)},$$slots:{default:!0}});append($$anchor4,fragment_11)},$$slots:{default:!0}});node_12=sibling(node_9,2);{let $02=user_derived(()=>$msg("I understand that other devices will no longer be able to synchronise, and will need to be reset the synchronisation information."));Check(node_12,{get title(){return get2($02)},get value(){return get2(confirmationCheck2)},set value($$value){set(confirmationCheck2,$$value,!0)},children:($$anchor4,$$slotProps2)=>{InfoNote($$anchor4,{children:($$anchor5,$$slotProps3)=>{next();var text_8=text();template_effect($03=>set_text(text_8,$03),[()=>$msg("by resetting the remote, you will be informed on other devices.")]);append($$anchor5,text_8)},$$slots:{default:!0}})},$$slots:{default:!0}})}node_13=sibling(node_12,2);{let $02=user_derived(()=>$msg("I understand that this action is irreversible once performed."));Check(node_13,{get title(){return get2($02)},get value(){return get2(confirmationCheck3)},set value($$value){set(confirmationCheck3,$$value,!0)}})}append($$anchor3,fragment_10)},$$slots:{default:!0}})}append($$anchor2,fragment_7)};if_block(node,$$render=>{get2(isP2P)?$$render(consequent):$$render(alternate,-1)});node_14=sibling(node,4);Instruction(node_14,{children:($$anchor2,$$slotProps)=>{var node_16,node_17,fragment_16=root_316(),node_15=first_child(fragment_16);Question(node_15,{children:($$anchor3,$$slotProps2)=>{next();var text_9=text();template_effect($0=>set_text(text_9,$0),[()=>$msg("Have you created a backup before proceeding?")]);append($$anchor3,text_9)},$$slots:{default:!0}});node_16=sibling(node_15,2);InfoNote(node_16,{warning:!0,children:($$anchor3,$$slotProps2)=>{next();var text_10=text();template_effect($0=>set_text(text_10,$0),[()=>$msg("This is an extremely powerful operation. We strongly recommend that you copy your Vault folder to a safe location.")]);append($$anchor3,text_10)},$$slots:{default:!0}});node_17=sibling(node_16,2);Options(node_17,{children:($$anchor3,$$slotProps2)=>{var node_19,node_20,fragment_19=root_316(),node_18=first_child(fragment_19);let $0=user_derived(()=>$msg("I have created a backup of my Vault."));Option(node_18,{get selectedValue(){return TYPE_BACKUP_DONE},get title(){return get2($0)},get value(){return get2(backupType)},set value($$value){set(backupType,$$value,!0)}});node_19=sibling(node_18,2);{let $0=user_derived(()=>$msg("I understand the risks and will proceed without a backup."));Option(node_19,{get selectedValue(){return TYPE_BACKUP_SKIPPED},get title(){return get2($0)},get value(){return get2(backupType)},set value($$value){set(backupType,$$value,!0)}})}node_20=sibling(node_19,2);{let $0=user_derived(()=>$msg("I am unable to create a backup of my Vaults."));Option(node_20,{get selectedValue(){return TYPE_UNABLE_TO_BACKUP},get title(){return get2($0)},get value(){return get2(backupType)},set value($$value){set(backupType,$$value,!0)},children:($$anchor4,$$slotProps3)=>{{let $02=user_derived(()=>get2(backupType)===TYPE_UNABLE_TO_BACKUP);InfoNote($$anchor4,{error:!0,get visible(){return get2($02)},children:($$anchor5,$$slotProps4)=>{var strong_1=root_410(),text_11=child(strong_1),text_12=sibling(text_11,2);reset(strong_1);template_effect(($03,$1)=>{set_text(text_11,`${null!=$03?$03:""} `);set_text(text_12,` ${null!=$1?$1:""}`)},[()=>$msg("You should create a new synchronisation destination and rebuild your data there."),()=>$msg("After that, synchronise to a brand new vault on each other device with the new remote one by one.")]);append($$anchor5,strong_1)},$$slots:{default:!0}})}},$$slots:{default:!0}})}append($$anchor3,fragment_19)},$$slots:{default:!0}});append($$anchor2,fragment_16)},$$slots:{default:!0}});node_21=sibling(node_14,2);consequent_1=$$anchor2=>{Instruction($$anchor2,{children:($$anchor3,$$slotProps)=>{{let $0=user_derived(()=>$msg("Advanced"));ExtraItems($$anchor3,{get title(){return get2($0)},children:($$anchor4,$$slotProps2)=>{{let $02=user_derived(()=>$msg("Use this device's settings"));Check($$anchor4,{get title(){return get2($02)},get value(){return get2(preventFetchingConfig)},set value($$value){set(preventFetchingConfig,$$value,!0)},children:($$anchor5,$$slotProps3)=>{InfoNote($$anchor5,{children:($$anchor6,$$slotProps4)=>{next();var text_13=text();template_effect($03=>set_text(text_13,$03),[()=>$msg("Skips checking and applying synchronisation settings from the remote.")]);append($$anchor6,text_13)},$$slots:{default:!0}})},$$slots:{default:!0}})}},$$slots:{default:!0}})}},$$slots:{default:!0}})};if_block(node_21,$$render=>{get2(isP2P)||$$render(consequent_1)});node_22=sibling(node_21,2);UserDecisions(node_22,{children:($$anchor2,$$slotProps)=>{var node_24,fragment_26=root_218(),node_23=first_child(fragment_26);let $0=user_derived(()=>get2(isP2P)?$msg("Ui.SetupWizard.RebuildEverythingP2P.Proceed"):$msg("I Understand, Overwrite Server")),$1=user_derived(()=>!get2(canProceed));Decision(node_23,{get title(){return get2($0)},important:!0,get disabled(){return get2($1)},commit:()=>commit()});node_24=sibling(node_23,2);{let $0=user_derived(()=>$msg("Cancel"));Decision(node_24,{get title(){return get2($0)},commit:()=>$$props.setResult(TYPE_CANCEL)})}append($$anchor2,fragment_26)},$$slots:{default:!0}});append($$anchor,fragment);pop()}function buildSimpleFetchResult(stage1,stage2){if(stage1===SIMPLE_FETCH_STAGE1_DETAILED)return{mode:"detailed",options:{}};if(stage1===SIMPLE_FETCH_STAGE1_REMOTE_WINS&&stage2){if(![SIMPLE_FETCH_STAGE2_REMOTE_DELETE_ALL,SIMPLE_FETCH_STAGE2_REMOTE_DELETE_NONE].includes(stage2))return;return{mode:"remote-only",options:{mode:FullScanModes_DB_APPLY,extraOnRemote:stage2===SIMPLE_FETCH_STAGE2_REMOTE_DELETE_ALL?ExtraOnRemote_DELETE_LOCAL_MISSING:void 0}}}if(stage1===SIMPLE_FETCH_STAGE1_NEWER_WINS&&stage2){if(![SIMPLE_FETCH_STAGE2_NEWER_CLEANUP,SIMPLE_FETCH_STAGE2_NEWER_SYNC_ALL].includes(stage2))return;return{mode:"newer-wins",options:{mode:FullScanModes_NEWER_WINS,extraOnLocal:stage2===SIMPLE_FETCH_STAGE2_NEWER_CLEANUP?ExtraOnLocal_DELETE_DB_DELETED:ExtraOnLocal_APPEND_STORAGE_ONLY}}}}function rememberSimpleFetchMode(host,stage1,stage2){host.services.setting.setSmallConfig(SIMPLE_FETCH_MODE_KEY,JSON.stringify({stage1,stage2}))}function getRememberedSimpleFetchMode(host){const saved=host.services.setting.getSmallConfig(SIMPLE_FETCH_MODE_KEY);if(saved){try{const{stage1,stage2}=JSON.parse(saved);if(stage1){const remembered=buildSimpleFetchResult(stage1,stage2);if(remembered)return remembered}}catch(e3){}host.services.setting.deleteSmallConfig(SIMPLE_FETCH_MODE_KEY)}}function clearRememberedSimpleFetchMode(host){host.services.setting.deleteSmallConfig(SIMPLE_FETCH_MODE_KEY)}async function askSimpleFetchMode(host){const remembered=getRememberedSimpleFetchMode(host);if(remembered)return remembered;const msg=`We are about to retrieve the remote data.\n\nFirstly, how shall we handle the data retrieved from this remote source?\n\n- **${SIMPLE_FETCH_STAGE1_NEWER_WINS}**: Compares the modified time of files and takes the newer one.\n If you have been using Self-hosted LiveSync and have made changes on multiple devices, this option may be suitable for you as it tries to merge changes based on modified time.\n- **${SIMPLE_FETCH_STAGE1_REMOTE_WINS}**: Remote data is the source of truth.\n If you are new to using Self-hosted LiveSync. This option may be easiest to understand and get started with.\n It will overwrite all your local files with the remote data, so please make sure you have a backup if there is any important data in your vault.\n- **${SIMPLE_FETCH_STAGE1_DETAILED}**: Opens the detailed setup wizard.\n If you want to have more control over the synchronisation process, or want to review the changes before applying, you can choose this option to use the detailed flow.\n `,stage1=await host.services.UI.confirm.confirmWithMessage("Data retrieval scheduled",msg,[SIMPLE_FETCH_STAGE1_NEWER_WINS,SIMPLE_FETCH_STAGE1_REMOTE_WINS,SIMPLE_FETCH_STAGE1_DETAILED,SIMPLE_FETCH_STAGE1_CANCEL],SIMPLE_FETCH_STAGE1_NEWER_WINS,0);if(!stage1||stage1===SIMPLE_FETCH_STAGE1_CANCEL)return"cancelled";if(stage1===SIMPLE_FETCH_STAGE1_DETAILED)return buildSimpleFetchResult(stage1);if(stage1===SIMPLE_FETCH_STAGE1_REMOTE_WINS){const msg2=`Since you have chosen to overwrite all local files with remote data, **how would you like to handle local files that are not present in the remote database?**\n\n- **${SIMPLE_FETCH_STAGE2_REMOTE_DELETE_ALL}**: Local-only files and remote-deleted files will be removed.\n This option will make your local vault exactly the same as the remote database, but please make sure you have a backup if there is any important data in your vault.\n- **${SIMPLE_FETCH_STAGE2_REMOTE_DELETE_NONE}**: All existing local files will be preserved.\n This option will keep all your local files, but it may cause duplicates if there are files that exist on local but not on remote. You can clean up these duplicates manually after the synchronisation.`,stage2=await host.services.UI.confirm.confirmWithMessage("How to handle extra existing local files?",msg2,[SIMPLE_FETCH_STAGE2_REMOTE_DELETE_ALL,SIMPLE_FETCH_STAGE2_REMOTE_DELETE_NONE,STAGE2_ABORT],SIMPLE_FETCH_STAGE2_REMOTE_DELETE_NONE,0);if(!stage2)return"cancelled";if(stage2===STAGE2_ABORT)return"aborted";rememberSimpleFetchMode(host,stage1,stage2);return buildSimpleFetchResult(stage1,stage2)}if(stage1===SIMPLE_FETCH_STAGE1_NEWER_WINS){const msg2=`How should files that were deleted on other devices be handled?\n\n- **${SIMPLE_FETCH_STAGE2_NEWER_CLEANUP}**: Delete local files if they were deleted on remote.\n This is useful if you want to keep your vault clean and consistent across devices, but please make sure you have a backup if there is already any important data in your vault.\n- **${SIMPLE_FETCH_STAGE2_NEWER_SYNC_ALL}**: Recreate remote files even if they were deleted on remote.\n This option will keep all your local files, but it may cause duplicates if there are files that exist on local but not on remote. You can clean up these duplicates manually after the synchronisation.\n `,stage2=await host.services.UI.confirm.confirmWithMessage("Conflict & Deletion Options",msg2,[SIMPLE_FETCH_STAGE2_NEWER_CLEANUP,SIMPLE_FETCH_STAGE2_NEWER_SYNC_ALL,STAGE2_ABORT],SIMPLE_FETCH_STAGE2_NEWER_SYNC_ALL,0);if(!stage2)return"cancelled";if(stage2===STAGE2_ABORT)return"aborted";rememberSimpleFetchMode(host,stage1,stage2);return buildSimpleFetchResult(stage1,stage2)}return"cancelled"}async function askAndPerformFastSetupOnScheduledFetchAll(host,log2,cleanupFlag){const result=await askSimpleFetchMode(host);if("cancelled"===result){log2("Fetch cancelled by user.",LOG_LEVEL_NOTICE);clearRememberedSimpleFetchMode(host);return await cancelScheduledInitialisation(host,cleanupFlag)}if("aborted"===result){log2("Fetch exited by user.",LOG_LEVEL_NOTICE);clearRememberedSimpleFetchMode(host);host.services.appLifecycle.performRestart();return!1}if("detailed"===result.mode)return;const settings=host.services.setting.currentSettings();if(!await adjustSettingToRemoteIfNeeded(host,log2,{preventFetchingConfig:!1},settings)){log2("Fetch initialisation cancelled by user.",LOG_LEVEL_NOTICE);clearRememberedSimpleFetchMode(host);return await cancelScheduledInitialisation(host,cleanupFlag)}return await processVaultInitialisation(host,log2,async()=>{await host.serviceModules.rebuilder.$fetchLocalDBFast(!1);new UnresolvedErrorManager(host.services.appLifecycle,host.services.context.events);const syncResult=await synchroniseAllFilesBetweenDBandStorage(host,log2,0,normaliseFullScanOptions({...result.options,showingNotice:!0,omitEvents:!0,ignoreSuspending:!0}));if(!syncResult){const canRelease=await host.services.UI.confirm.askSelectStringDialogue("Some files failed to synchronise. What would you like to do?",[RERUN_PROCESS,RELEASE_FLAG_PROCESS],{defaultAction:RELEASE_FLAG_PROCESS,title:"Synchronisation Issues Detected"});if(canRelease===RERUN_PROCESS){log2("User chose to reboot and re-run the process.",LOG_LEVEL_NOTICE);host.services.appLifecycle.performRestart();return!1}}await host.serviceModules.rebuilder.finishRebuild();await cleanupFlag();clearRememberedSimpleFetchMode(host);log2("Simple fetch and scan operation completed.",LOG_LEVEL_NOTICE);return!0},"keep-on-failure")}async function isFlagFileExist(host,path2){const redFlagExist=await host.serviceModules.storageAccess.isExists(host.serviceModules.storageAccess.normalisePath(path2));return!!redFlagExist}async function deleteFlagFile(host,log2,path2){try{const isFlagged=await host.serviceModules.storageAccess.isExists(host.serviceModules.storageAccess.normalisePath(path2));isFlagged&&await host.serviceModules.storageAccess.delete(path2,!0)}catch(ex){log2(`Could not delete ${path2}`);log2(ex,LOG_LEVEL_VERBOSE)}}async function askAndActivateRemoteDatabase(host,log2){const settings=host.services.setting.currentSettings();if(settings.remoteConfigurations&&Object.keys(settings.remoteConfigurations).length>1){const message="Multiple remote configurations detected. Please select the remote configuration you want to fetch from.",options=Object.entries(settings.remoteConfigurations).map(([id,config])=>{const parsed=ConnectionStringParser.parse(config.uri),displayURI=(config.uri.split("@").pop()||"").substring(0,20)+"...";return{name:`${config.name} - ${parsed.type} (${displayURI})`,id}});options.push({name:REMOTE_KEEP_CURRENT,id:"keep_current"});options.push({name:REMOTE_CANCEL,id:"cancel"});const selections=options.map(option=>option.name),selectedId=await host.services.UI.confirm.askSelectStringDialogue(message,selections,{title:"Select Remote Configuration",defaultAction:REMOTE_KEEP_CURRENT}),selectedConfig=options.find(option=>option.name===selectedId);if(selectedConfig){if("keep_current"===selectedConfig.id){log2("Keeping current remote configuration.",LOG_LEVEL_INFO);return!0}if("cancel"===selectedConfig.id){log2("Remote configuration selection cancelled.",LOG_LEVEL_NOTICE);return!1}const activated=activateRemoteConfiguration(settings,selectedConfig.id);if(activated){await host.services.setting.applyPartial(activated);log2(`Activated remote configuration: ${selectedConfig.name}`,LOG_LEVEL_INFO);return!0}log2(`Failed to activate remote configuration: ${selectedConfig.name}`,LOG_LEVEL_NOTICE);return!1}log2("No remote configuration selected.",LOG_LEVEL_NOTICE);return!1}return!0}function createFetchAllFlagHandler(host,log2){const isFlagActive=async()=>await isFlagFileExist(host,FlagFilesOriginal_FETCH_ALL)||await isFlagFileExist(host,FlagFilesHumanReadable_FETCH_ALL),cleanupFlag=async()=>{await deleteFlagFile(host,log2,FlagFilesOriginal_FETCH_ALL);await deleteFlagFile(host,log2,FlagFilesHumanReadable_FETCH_ALL)},onScheduled=async()=>{const isRemoteActivated=await askAndActivateRemoteDatabase(host,log2);if(!isRemoteActivated)return await cancelScheduledInitialisation(host,cleanupFlag);const useFastSetup=await askAndPerformFastSetupOnScheduledFetchAll(host,log2,cleanupFlag);if(void 0!==useFastSetup)return useFastSetup;const method=await host.services.UI.dialogManager.openWithExplicitCancel(FetchEverything);if("cancelled"===method){log2("Fetch everything cancelled by user.",LOG_LEVEL_NOTICE);return await cancelScheduledInitialisation(host,cleanupFlag)}const{vault,extra}=method,settings=await Promise.resolve(host.services.setting.currentSettings()),makeLocalChunkBeforeSyncAvailable=settings.remoteType!==REMOTE_MINIO,mapVaultStateToAction={identical:{makeLocalChunkBeforeSync:makeLocalChunkBeforeSyncAvailable,makeLocalFilesBeforeSync:!1},independent:{makeLocalChunkBeforeSync:!1,makeLocalFilesBeforeSync:!1},unbalanced:{makeLocalChunkBeforeSync:!1,makeLocalFilesBeforeSync:!0},cancelled:{makeLocalChunkBeforeSync:!1,makeLocalFilesBeforeSync:!1}};if(!await adjustSettingToRemoteIfNeeded(host,log2,extra,settings)){log2("Fetch initialisation cancelled by user.",LOG_LEVEL_NOTICE);return await cancelScheduledInitialisation(host,cleanupFlag)}return await processVaultInitialisation(host,log2,async()=>{const vaultStateToAction=mapVaultStateToAction[vault],{makeLocalChunkBeforeSync,makeLocalFilesBeforeSync}=vaultStateToAction;log2(`Fetching everything with settings: makeLocalChunkBeforeSync=${makeLocalChunkBeforeSync}, makeLocalFilesBeforeSync=${makeLocalFilesBeforeSync}`,LOG_LEVEL_INFO);await host.serviceModules.rebuilder.$fetchLocal(makeLocalChunkBeforeSync,!makeLocalFilesBeforeSync);await cleanupFlag();log2("Fetch everything operation completed. Vault files will be gradually synced.",LOG_LEVEL_NOTICE);return!0})};return{priority:10,check:()=>isFlagActive(),handle:async()=>{const res2=await onScheduled();return!!res2&&await verifyAndUnlockSuspension(host,log2)}}}async function adjustSettingToRemote(host,log2,config,operation2="fetch"){for(;;){const remoteResult=await host.services.tweakValue.fetchRemotePreferred(config);if(remoteResult.status===RemotePreferredTweakStatuses_NOT_CONFIGURED){const useDeviceSettings=$msg("Use this device's settings"),cancelInitialisation=$msg("Cancel");log2(`Remote synchronisation settings are not configured (${remoteResult.reason}).`,LOG_LEVEL_INFO);const choice=await host.services.UI.confirm.askSelectStringDialogue($msg("The selected remote has no saved synchronisation settings. This is normal for a new remote. Use this device's settings, or cancel if you expected existing settings."),[useDeviceSettings,cancelInitialisation],{defaultAction:useDeviceSettings,timeout:0,title:$msg("No Synchronisation Settings Found")});return choice===useDeviceSettings}if(remoteResult.status===RemotePreferredTweakStatuses_UNAVAILABLE){const retryRemoteSettings=$msg("Retry"),useDeviceSettings=$msg("Use this device's settings"),cancelInitialisation=$msg("Cancel");log2("Could not read synchronisation settings from the remote.",LOG_LEVEL_NOTICE);log2(remoteResult.error,LOG_LEVEL_VERBOSE);if("rebuild"===operation2){const choice2=await host.services.UI.confirm.askSelectStringDialogue($msg("Could not read the remote's synchronisation settings. Retry, or continue the overwrite with this device's settings. A working connection is still required."),[retryRemoteSettings,useDeviceSettings,cancelInitialisation],{defaultAction:retryRemoteSettings,timeout:0,title:$msg("Could Not Read Synchronisation Settings")});if(choice2===retryRemoteSettings)continue;return choice2===useDeviceSettings}const choice=await host.services.UI.confirm.askSelectStringDialogue($msg("Could not read the remote's synchronisation settings. Check the connection and credentials, then retry."),[retryRemoteSettings,cancelInitialisation],{defaultAction:retryRemoteSettings,timeout:0,title:$msg("Could Not Read Synchronisation Settings")});if(choice===retryRemoteSettings)continue;return!1}if(remoteResult.status===RemotePreferredTweakStatuses_UNSUPPORTED){log2("Remote synchronisation settings are not supported by this remote type.",LOG_LEVEL_INFO);return!0}const remoteTweaks=remoteResult.values,necessary=extractObject(TweakValuesShouldMatchedTemplate,remoteTweaks),differentItems=Object.entries(necessary).filter(([key3,value])=>config[key3]!==value);0===differentItems.length?log2("Remote configuration matches local configuration. No changes applied.",LOG_LEVEL_NOTICE):await host.services.UI.confirm.askSelectStringDialogue("Your settings differed slightly from the server's. The plug-in has supplemented the incompatible parts with the server settings!",["OK"],{defaultAction:"OK",timeout:0});config={...config,...Object.fromEntries(differentItems)};await host.services.setting.applyExternalSettings(config,!0);log2("Remote configuration applied.",LOG_LEVEL_NOTICE);return!0}}async function adjustSettingToRemoteIfNeeded(host,log2,extra,config,operation2="fetch"){if(null==extra?void 0:extra.preventFetchingConfig)return!0;if(config.remoteType===REMOTE_P2P){log2("Remote configuration fetch skipped (P2P mode).",LOG_LEVEL_INFO);return!0}const canProceed=await adjustSettingToRemote(host,log2,config,operation2);canProceed||log2("Remote configuration not applied.",LOG_LEVEL_NOTICE);return canProceed}async function cancelScheduledInitialisation(host,cleanupFlag){await host.services.setting.applyPartial({suspendFileWatching:!0,suspendParseReplicationResult:!0},!0);await cleanupFlag();host.services.appLifecycle.performRestart();return!1}async function processVaultInitialisation(host,log2,proc,suspensionPolicy="resume"){let completed=!1;try{await host.services.setting.applyPartial({batchSave:!1},!1);await host.services.setting.suspendAllSync();await host.services.setting.suspendExtraSync();await host.services.setting.applyPartial("keep-on-failure"===suspensionPolicy?{suspendFileWatching:!0,suspendParseReplicationResult:!0}:{suspendFileWatching:!0},!0);try{const result=await proc();completed=result;return result}catch(ex){log2("Error during vault initialisation process.",LOG_LEVEL_NOTICE);log2(ex,LOG_LEVEL_VERBOSE);return!1}}catch(ex){log2("Error during vault initialisation.",LOG_LEVEL_NOTICE);log2(ex,LOG_LEVEL_VERBOSE);return!1}finally{"resume"===suspensionPolicy?await host.services.setting.applyPartial({suspendFileWatching:!1},!0):"keep"===suspensionPolicy?await host.services.setting.applyPartial({suspendFileWatching:!0},!0):await host.services.setting.applyPartial({suspendFileWatching:!completed,suspendParseReplicationResult:!completed},!0)}}async function verifyAndUnlockSuspension(host,log2){if(!host.services.setting.currentSettings().suspendFileWatching)return!0;if("yes"!=await host.services.UI.confirm.askYesNoDialog("Do you want to resume file and database processing, and restart obsidian now?",{defaultOption:"Yes",timeout:15}))return!0;await host.services.setting.applyPartial({suspendFileWatching:!1},!0);host.services.appLifecycle.performRestart();return!1}function createRebuildFlagHandler(host,log2){const isFlagActive=async()=>await isFlagFileExist(host,FlagFilesOriginal_REBUILD_ALL)||await isFlagFileExist(host,FlagFilesHumanReadable_REBUILD_ALL),cleanupFlag=async()=>{await deleteFlagFile(host,log2,FlagFilesOriginal_REBUILD_ALL);await deleteFlagFile(host,log2,FlagFilesHumanReadable_REBUILD_ALL)},onScheduled=async()=>{const settings=host.services.setting.currentSettings(),method=await host.services.UI.dialogManager.openWithExplicitCancel(RebuildEverything,{isP2P:isP2PMainRemote(settings)});if("cancelled"===method){log2("Rebuild everything cancelled by user.",LOG_LEVEL_NOTICE);return await cancelScheduledInitialisation(host,cleanupFlag)}const{extra}=method;if(!await adjustSettingToRemoteIfNeeded(host,log2,extra,settings,"rebuild")){log2("Rebuild initialisation cancelled by user.",LOG_LEVEL_NOTICE);return await cancelScheduledInitialisation(host,cleanupFlag)}return await processVaultInitialisation(host,log2,async()=>{await host.serviceModules.rebuilder.$rebuildEverything();await cleanupFlag();log2("Rebuild everything operation completed.",LOG_LEVEL_NOTICE);return!0})};return{priority:20,check:()=>isFlagActive(),handle:async()=>{const res2=await onScheduled();return!!res2&&await verifyAndUnlockSuspension(host)}}}function createSuspendFlagHandler(host,log2){const isFlagActive=async()=>await isFlagFileExist(host,FlagFilesOriginal_SUSPEND_ALL),onScheduled=async()=>{log2("SCRAM is detected. All operations are suspended.",LOG_LEVEL_NOTICE);return await processVaultInitialisation(host,log2,async()=>{log2("All operations are suspended as per SCRAM.\nLogs will be written to the file. This might be a performance impact.",LOG_LEVEL_NOTICE);await host.services.setting.applyPartial({writeLogToTheFile:!0},!0);return Promise.resolve(!1)},"keep")};return{priority:5,check:()=>isFlagActive(),handle:()=>onScheduled()}}function flagHandlerToEventHandler(flagHandler){return async()=>!await flagHandler.check()||await flagHandler.handle()}function useRedFlagFeatures(host){const log2=createInstanceLogFunction("SF:RedFlag",host.services.API),handlerFetch=createFetchAllFlagHandler(host,log2),handlerRebuild=createRebuildFlagHandler(host,log2),handlerSuspend=createSuspendFlagHandler(host,log2);host.services.appLifecycle.onLayoutReady.addHandler(flagHandlerToEventHandler(handlerFetch),handlerFetch.priority);host.services.appLifecycle.onLayoutReady.addHandler(flagHandlerToEventHandler(handlerRebuild),handlerRebuild.priority);host.services.appLifecycle.onLayoutReady.addHandler(flagHandlerToEventHandler(handlerSuspend),handlerSuspend.priority)}async function handleSetupProtocol(setupManager,conf){conf.settings?await setupManager.onUseSetupURI("unknown",`${configURIBase}${encodeURIComponent(conf.settings)}`):conf.settingsQR&&await setupManager.decodeQR(conf.settingsQR)}function registerSetupProtocolHandler(host,log2,setupManager){try{host.services.API.registerProtocolHandler("setuplivesync",async conf=>{await handleSetupProtocol(setupManager,conf)})}catch(e3){log2("Failed to register protocol handler. This feature may not work in some environments.",LOG_LEVEL_NOTICE);log2(e3,LOG_LEVEL_VERBOSE)}}function useSetupProtocolFeature(host,setupManager){const log2=createInstanceLogFunction("SF:SetupProtocol",host.services.API);host.services.appLifecycle.onLoaded.addHandler(()=>{registerSetupProtocolHandler(host,log2,setupManager);return Promise.resolve(!0)})}async function encodeSetupSettingsAsQR(host){const settingString=encodeSettingsToQRCodeData(host.services.setting.currentSettings()),result=encodeQR(settingString,OutputFormat.SVG);if(""===result)return"";if("string"==typeof result){const msg=host.services.context.translate("Setup.QRCode",{qr_image:result});await host.services.UI.confirm.confirmWithMessage("Settings QR Code",msg,["OK"],"OK");return result}{let currentIndex=0;for(;currentIndex<result.total;){const msg=`The setting is too large for a single QR code.\nWe are using the aggregator to combine multiple QR codes.\nYour settings will not be sent to any server; they will be processed only on your device.\nPlease scan this QR code with your mobile's camera, and open the page in your browser.\nAfter all parts are collected, the page will navigate you back to Obsidian with the aggregated settings.\n\nProgress: ${currentIndex+1} / ${result.total}\n${result.parts[currentIndex]}`,buttons=[];currentIndex>0&&buttons.push("Back");if(currentIndex<result.total-1){buttons.push("Next");buttons.push("Cancel")}else buttons.push("Done");const choice=await host.services.UI.confirm.confirmWithMessage("Settings QR Code (Aggregated)",msg,buttons,buttons[-1!==buttons.indexOf("Next")?buttons.indexOf("Next"):buttons.indexOf("Done")]);if("Next"===choice)currentIndex++;else{if("Back"!==choice)break;currentIndex--}}return result.parts[0]}}function useSetupQRCodeFeature(host){host.services.appLifecycle.onLoaded.addHandler(()=>{host.services.API.addCommand({id:"livesync-setting-qr",name:"Show settings as a QR code",checkCallback:checking=>{if(!host.services.setting.currentSettings().isConfigured)return!1;checking||fireAndForget(encodeSetupSettingsAsQR(host));return!0}});host.services.context.events.onEvent(EVENT_REQUEST_SHOW_SETUP_QR,()=>fireAndForget(()=>encodeSetupSettingsAsQR(host)));return Promise.resolve(!0)})}async function askEncryptingPassphrase(host){return await host.services.UI.confirm.askString("Encrypt your settings","The passphrase to encrypt the setup URI","",!0)}async function copySetupURI(host,log2,stripExtra=!0){const encryptingPassphrase=await askEncryptingPassphrase(host);if(!1===encryptingPassphrase)return;const encryptedURI=await encodeSettingsToSetupURI(host.services.setting.currentSettings(),encryptingPassphrase,[...stripExtra?["pluginSyncExtendedSetting"]:[]],!0);await host.services.UI.promptCopyToClipboard("Setup URI",encryptedURI)&&log2("Setup URI copied to clipboard",LOG_LEVEL_NOTICE)}async function copySetupURIFull(host,log2){const encryptingPassphrase=await askEncryptingPassphrase(host);if(!1===encryptingPassphrase)return;const encryptedURI=await encodeSettingsToSetupURI(host.services.setting.currentSettings(),encryptingPassphrase,[],!1);await host.services.UI.promptCopyToClipboard("Setup URI",encryptedURI)&&log2("Setup URI copied to clipboard",LOG_LEVEL_NOTICE)}function useSetupURIFeature(host){const log2=createInstanceLogFunction("SF:SetupURI",host.services.API);host.services.appLifecycle.onLoaded.addHandler(()=>{host.services.API.addCommand({id:"livesync-copysetupuri",name:"Copy settings as a new setup URI",checkCallback:checking=>{if(!host.services.setting.currentSettings().isConfigured)return!1;checking||fireAndForget(copySetupURI(host,log2));return!0}});host.services.API.addCommand({id:"livesync-copysetupuri-short",name:"Copy settings as a new setup URI (With customization sync)",checkCallback:checking=>{const settings=host.services.setting.currentSettings();if(!settings.isConfigured||!settings.usePluginSync)return!1;checking||fireAndForget(copySetupURI(host,log2,!1));return!0}});host.services.API.addCommand({id:"livesync-copysetupurifull",name:"Copy settings as a new setup URI (Full)",checkCallback:checking=>{const settings=host.services.setting.currentSettings();if(!settings.isConfigured||!settings.useAdvancedMode)return!1;checking||fireAndForget(copySetupURIFull(host,log2));return!0}});host.services.context.events.onEvent(EVENT_REQUEST_COPY_SETUP_URI,()=>fireAndForget(()=>copySetupURI(host,log2)));return Promise.resolve(!0)})}function addP2PEventHandlers(source2,events){const current=()=>"function"==typeof source2?source2():source2;events.onEvent(EVENT_ADVERTISEMENT_RECEIVED,peer=>{current().onNewPeer(peer)});events.onEvent(EVENT_DEVICE_LEAVED,peerId=>{current().onPeerLeaved(peerId)});events.onEvent(EVENT_REQUEST_STATUS,()=>{current().requestStatus()});events.onEvent(EVENT_DATABASE_REBUILT,async()=>{await current().open()});events.onEvent(EVENT_PLATFORM_UNLOADED,()=>{current().close()});events.onEvent(EVENT_SETTING_SAVED,async settings=>{const instance=current();settings.P2P_Enabled&&settings.P2P_AutoStart?await instance.open():await instance.close()})}function useP2PReplicatorFeature(host,openReplicationUIFactory,openRebuildUIFactory){let replacementPromise,replicator=new LiveSyncTrysteroReplicator({services:host.services});openReplicationUIFactory&&(replicator.env.openReplicationUI=openReplicationUIFactory(replicator));openRebuildUIFactory&&(replicator.env.openRebuildUI=openRebuildUIFactory(replicator));const activeReplicator={get replicator(){return replicator}};addP2PEventHandlers(()=>activeReplicator.replicator,host.services.context.events);host.services.replicator.getNewReplicator.addHandler(async(settingOverride={})=>{const settings={...host.services.setting.currentSettings(),...settingOverride};if(settings.remoteType==REMOTE_P2P){if(replacementPromise)return await replacementPromise;const operation2=(async()=>{const existingReplicator=replicator;try{await(null==existingReplicator?void 0:existingReplicator.close())}catch(e3){Logger("Error closing existing p2p replicator");Logger(e3,LOG_LEVEL_VERBOSE)}const newReplicator=new LiveSyncTrysteroReplicator({services:host.services});openReplicationUIFactory&&(newReplicator.env.openReplicationUI=openReplicationUIFactory(newReplicator));openRebuildUIFactory&&(newReplicator.env.openRebuildUI=openRebuildUIFactory(newReplicator));replicator=newReplicator;return replicator})();replacementPromise=operation2;try{return await operation2}finally{replacementPromise===operation2&&(replacementPromise=void 0)}}});host.services.appLifecycle.onUnload.addHandler(async()=>{await(null==replicator?void 0:replicator.close());return!0});host.services.appLifecycle.onSuspending.addHandler(async()=>{await(null==replicator?void 0:replicator.close());return!0});host.services.databaseEvents.onDatabaseInitialisation.addHandler(async()=>{await(null==replicator?void 0:replicator.close());return!0});host.services.appLifecycle.onResumed.addHandler(()=>{const settings=host.services.setting.currentSettings();settings.P2P_Enabled&&settings.P2P_AutoStart&&compatGlobal.setTimeout(()=>{null==replicator||replicator.open()},100);return Promise.resolve(!0)});host.services.setting.suspendExtraSync.addHandler(()=>{const s2=host.services.setting.currentSettings();s2.remoteType!==REMOTE_P2P&&(s2.P2P_Enabled=!1);s2.P2P_AutoAccepting=AutoAccepting.NONE;s2.P2P_AutoBroadcast=!1;s2.P2P_AutoStart=!1;s2.P2P_AutoSyncPeers="";s2.P2P_AutoWatchPeers="";return Promise.resolve(!0)});return activeReplicator}function useP2PReplicatorCommands(host,result){host.services.API.addCommand({id:"p2p-establish-connection",name:"P2P Sync : Connect to the Signalling Server",checkCallback:isChecking=>{var _a13,_b6;const replicator=result.replicator;if(!replicator)return!1;if(isChecking)return!(null!=(_b6=null==(_a13=replicator.server)?void 0:_a13.isServing)&&_b6);replicator.open()}});host.services.API.addCommand({id:"p2p-close-connection",name:"P2P Sync : Disconnect from the Signalling Server",checkCallback:isChecking=>{var _a13,_b6;const replicator=result.replicator;if(!replicator)return!1;if(isChecking)return null!=(_b6=null==(_a13=replicator.server)?void 0:_a13.isServing)&&_b6;Logger("Closing P2P Connection",LOG_LEVEL_NOTICE);replicator.close()}})}function P2PServerStatusCard($$anchor,$$props){async function requestServerStatus(){await Promise.resolve($$props.getLiveSyncReplicator().requestStatus());eventHub.emitEvent(EVENT_REQUEST_STATUS)}async function onOpenConnection(){await $$props.getLiveSyncReplicator().makeSureOpened();await requestServerStatus()}async function onDisconnect(){await $$props.getLiveSyncReplicator().close();await requestServerStatus()}function toggleBroadcast(){(null===get2(replicatorStatus)||void 0===get2(replicatorStatus)?void 0:get2(replicatorStatus).isBroadcasting)?$$props.getLiveSyncReplicator().disableBroadcastChanges():$$props.getLiveSyncReplicator().enableBroadcastChanges()}async function toggleDiagRTC(){if(!$$props.core)return;const next2=!get2(useDiagRTC);await $$props.core.services.setting.updateSettings(settings=>{settings.P2P_useDiagRTC=next2;return settings},!0);set(useDiagRTC,next2)}var _a13,_b6,div,h3,text2,div_1,span,text_1,span_1,text_2,div_2,node,consequent,alternate,node_1,consequent_1,node_2,consequent_2,node_3,consequent_3,node_4,consequent_4;push($$props,!0);append_styles($$anchor,$$css15);let showBroadcastToggle=prop($$props,"showBroadcastToggle",3,!0),serverInfo=state(void 0),replicatorStatus=state(void 0);const initialSettings=(()=>null===$$props.core||void 0===$$props.core?void 0:$$props.core.services.setting.currentSettings())();let roomSuffix=state(proxy(extractP2PRoomSuffix(null!==(_a13=null==initialSettings?void 0:initialSettings.P2P_roomID)&&void 0!==_a13?_a13:""))),useDiagRTC=state(proxy(null!==(_b6=null==initialSettings?void 0:initialSettings.P2P_useDiagRTC)&&void 0!==_b6&&_b6));onMount(()=>{const unsubscribe=eventHub.onEvent(EVENT_SERVER_STATUS,status=>{var _a14;set(serverInfo,status,!0);set(roomSuffix,extractP2PRoomSuffix(null!==(_a14=null==status?void 0:status.roomId)&&void 0!==_a14?_a14:""),!0)}),unsubscribeStatus=eventHub.onEvent(EVENT_P2P_REPLICATOR_STATUS,status=>{set(replicatorStatus,status,!0)}),unsubscribeSettings=eventHub.onEvent(EVENT_SETTING_SAVED,settings=>{var _a14,_b7;set(roomSuffix,extractP2PRoomSuffix(null!==(_a14=null==settings?void 0:settings.P2P_roomID)&&void 0!==_a14?_a14:""),!0);set(useDiagRTC,null!==(_b7=null==settings?void 0:settings.P2P_useDiagRTC)&&void 0!==_b7&&_b7,!0)});fireAndForget(async()=>{await delay(100);await requestServerStatus()});return()=>{unsubscribe();unsubscribeStatus();unsubscribeSettings()}});const isConnected=user_derived(()=>null===get2(serverInfo)||void 0===get2(serverInfo)?void 0:get2(serverInfo).isConnected),isBroadcasting=user_derived(()=>{var _a14;return null!==(_a14=null===get2(replicatorStatus)||void 0===get2(replicatorStatus)?void 0:get2(replicatorStatus).isBroadcasting)&&void 0!==_a14&&_a14});div=root_511();h3=child(div);text2=child(h3,!0);reset(h3);div_1=sibling(h3,2);span=child(div_1);text_1=child(span,!0);reset(span);span_1=sibling(span,2);text_2=child(span_1,!0);reset(span_1);reset(div_1);div_2=sibling(div_1,2);node=child(div_2);consequent=$$anchor2=>{var button=root41(),text_3=child(button,!0);reset(button);template_effect($0=>set_text(text_3,$0),[()=>$msg("Open connection")]);delegated("click",button,onOpenConnection);append($$anchor2,button)};alternate=$$anchor2=>{var button_1=root41(),text_4=child(button_1,!0);reset(button_1);template_effect($0=>set_text(text_4,$0),[()=>$msg("Disconnect")]);delegated("click",button_1,onDisconnect);append($$anchor2,button_1)};if_block(node,$$render=>{get2(isConnected)?$$render(alternate,-1):$$render(consequent)});reset(div_2);node_1=sibling(div_2,2);consequent_1=$$anchor2=>{var span_3,text_6,div_4,span_4,text_7,span_5,text_8,div_5,span_6,text_9,span_7,text_10,fragment=root_136(),div_3=first_child(fragment),span_2=child(div_3),text_5=child(span_2,!0);reset(span_2);span_3=sibling(span_2,2);text_6=child(span_3,!0);reset(span_3);reset(div_3);div_4=sibling(div_3,2);span_4=child(div_4);text_7=child(span_4,!0);reset(span_4);span_5=sibling(span_4,2);text_8=child(span_5);reset(span_5);reset(div_4);div_5=sibling(div_4,2);span_6=child(div_5);text_9=child(span_6,!0);reset(span_6);span_7=sibling(span_6,2);text_10=child(span_7,!0);reset(span_7);reset(div_5);template_effect(($0,$1,$2,$3,$4)=>{set_text(text_5,$0);set_attribute2(span_3,"title",$1);set_text(text_6,get2(roomSuffix)||"-");set_text(text_7,$2);set_attribute2(span_5,"title",get2(serverInfo).serverPeerId);set_text(text_8,`${null!=$3?$3:""}...`);set_text(text_9,$4);set_text(text_10,get2(serverInfo).knownAdvertisements.length)},[()=>$msg("Room ID suffix:"),()=>get2(roomSuffix)||$msg("Not configured"),()=>$msg("Peer ID:"),()=>get2(serverInfo).serverPeerId.slice(0,12),()=>$msg("Devices:")]);append($$anchor2,fragment)};if_block(node_1,$$render=>{get2(serverInfo)&&$$render(consequent_1)});node_2=sibling(node_1,2);consequent_2=$$anchor2=>{var button_2,text_12,div_6=root_219(),label2=child(div_6),text_11=child(label2,!0);reset(label2);button_2=sibling(label2,2);text_12=child(button_2,!0);reset(button_2);reset(div_6);template_effect(($0,$1,$2)=>{set_text(text_11,$0);set_class(button_2,1,"broadcast-button "+(get2(isBroadcasting)?"is-on":"is-off"),"svelte-lxgvn4");set_attribute2(button_2,"title",$1);set_text(text_12,$2)},[()=>$msg("Announce changes"),()=>get2(isBroadcasting)?$msg("Stop announcing changes"):$msg("Start announcing changes"),()=>get2(isBroadcasting)?$msg("📡 On"):$msg("📡 Off")]);delegated("click",button_2,toggleBroadcast);append($$anchor2,div_6)};if_block(node_2,$$render=>{showBroadcastToggle()&&$$render(consequent_2)});node_3=sibling(node_2,2);consequent_3=$$anchor2=>{var button_3,text_14,div_7=root_317(),label_1=child(div_7),text_13=child(label_1,!0);reset(label_1);button_3=sibling(label_1,2);text_14=child(button_3,!0);reset(button_3);reset(div_7);template_effect(($0,$1,$2)=>{set_text(text_13,$0);set_class(button_3,1,"broadcast-button "+(get2(useDiagRTC)?"is-on":"is-off"),"svelte-lxgvn4");set_attribute2(button_3,"title",$1);set_text(text_14,$2)},[()=>$msg("🕵️ Diag"),()=>get2(useDiagRTC)?$msg("Diagnostic RTCPeerConnection is enabled"):$msg("Use Diagnostic RTCPeerConnection for statistics"),()=>get2(useDiagRTC)?$msg("On"):$msg("Off")]);delegated("click",button_3,toggleDiagRTC);append($$anchor2,div_7)};if_block(node_3,$$render=>{$$props.core&&$$render(consequent_3)});node_4=sibling(node_3,2);consequent_4=$$anchor2=>{var div_9,div_10,span_8,text_16,span_9,text_17,div_11,span_10,text_18,span_11,text_19,div_12,span_12,text_20,span_13,text_21,div_13,span_14,text_22,span_15,text_23,div_8=root_411(),h4=child(div_8),text_15=child(h4,!0);reset(h4);div_9=sibling(h4,2);div_10=child(div_9);span_8=child(div_10);text_16=child(span_8,!0);reset(span_8);span_9=sibling(span_8,2);text_17=child(span_9,!0);reset(span_9);reset(div_10);div_11=sibling(div_10,2);span_10=child(div_11);text_18=child(span_10,!0);reset(span_10);span_11=sibling(span_10,2);text_19=child(span_11,!0);reset(span_11);reset(div_11);div_12=sibling(div_11,2);span_12=child(div_12);text_20=child(span_12,!0);reset(span_12);span_13=sibling(span_12,2);text_21=child(span_13,!0);reset(span_13);reset(div_12);div_13=sibling(div_12,2);span_14=child(div_13);text_22=child(span_14,!0);reset(span_14);span_15=sibling(span_14,2);text_23=child(span_15,!0);reset(span_15);reset(div_13);reset(div_9);reset(div_8);template_effect(($0,$1,$2,$3,$4)=>{set_text(text_15,$0);set_text(text_16,$1);set_text(text_17,get2(serverInfo).diag.totalNewConnections);set_text(text_18,$2);set_text(text_19,get2(serverInfo).diag.totalSuccessfulConnections);set_text(text_20,$3);set_text(text_21,get2(serverInfo).diag.totalFailedConnections);set_text(text_22,$4);set_text(text_23,get2(serverInfo).diag.totalClosedConnections)},[()=>$msg("Stats"),()=>$msg("Incoming:"),()=>$msg("Connected:"),()=>$msg("Failed:"),()=>$msg("Closed:")]);append($$anchor2,div_8)};if_block(node_4,$$render=>{get2(serverInfo)&&$$render(consequent_4)});reset(div);template_effect(($0,$1,$2)=>{set_text(text2,$0);set_text(text_1,$1);set_class(span_1,1,"status-value "+(get2(isConnected)?"connected":"disconnected"),"svelte-lxgvn4");set_text(text_2,$2)},[()=>$msg("Signalling Status"),()=>$msg("Connection:"),()=>get2(isConnected)?$msg("🟢 Connected"):$msg("🔴 Disconnected")]);append($$anchor,div);pop()}function splitPeerSetting(value){return value.split(",").map(item=>item.trim()).filter(item=>""!==item)}function hasExactP2PPeer(value,peerName){return splitPeerSetting(value).includes(peerName)}function toggleExactP2PPeer(value,peerName){const items=splitPeerSetting(value),existingIndex=items.indexOf(peerName);existingIndex>=0?items.splice(existingIndex,1):items.push(peerName);return[...new Set(items)].join(",")}function togglePersistedP2PPeer(settings,setting,peerName){var _a13;return{[setting]:toggleExactP2PPeer(null!=(_a13=settings[setting])?_a13:"",peerName)}}function P2PServerStatusPane($$anchor,$$props){function markCommunicating(peerId){const expiry=Date.now()+2500;set(communicatingUntil,{...get2(communicatingUntil),[peerId]:expiry},!0);window.setTimeout(()=>{var _a14;if((null!==(_a14=get2(communicatingUntil)[peerId])&&void 0!==_a14?_a14:0)<=Date.now()){const{[peerId]:_removed,...rest}=get2(communicatingUntil);set(communicatingUntil,rest,!0)}},2600)}function listP2PRemoteOptions(remoteConfigurations){return Object.values(null!=remoteConfigurations?remoteConfigurations:{}).map(config=>{var _a14;try{const parsed=ConnectionStringParser.parse(config.uri);if("p2p"!==parsed.type)return;return{id:config.id,name:config.name,roomSuffix:extractP2PRoomSuffix(null!==(_a14=parsed.settings.P2P_roomID)&&void 0!==_a14?_a14:"")}}catch(_b6){return}}).filter(e3=>!!e3)}function refreshP2PRemoteOptions(){var _a14;const settings=$$props.core.services.setting.currentSettings(),options=listP2PRemoteOptions(settings.remoteConfigurations);set(p2pRemoteOptions,options,!0);const currentSelected=null!==(_a14=settings.P2P_ActiveRemoteConfigurationId)&&void 0!==_a14?_a14:"",isCurrentSelectedValid=options.some(option=>option.id===currentSelected);if(0!==options.length){if(""===currentSelected.trim()||!isCurrentSelectedValid){const fallbackId=options[0].id;set(selectedP2PRemoteConfigurationId,fallbackId,!0);currentSelected!==fallbackId&&fireAndForget(()=>applyP2PActiveRemoteSelection(fallbackId));return}set(selectedP2PRemoteConfigurationId,currentSelected,!0)}else set(selectedP2PRemoteConfigurationId,"")}function canEditP2PSettings(){const selected=get2(selectedP2PRemoteConfigurationId).trim();return""!==selected&&get2(p2pRemoteOptions).some(e3=>e3.id===selected)}async function requestServerStatus(){await $$props.getLiveSyncReplicator().requestStatus();eventHub.emitEvent(EVENT_REQUEST_STATUS)}function getAcceptanceStatus(peer){return!0===peer.isTemporaryAccepted?$msg("ACCEPTED (in session)"):!0===peer.isAccepted?$msg("ACCEPTED"):!1===peer.isTemporaryAccepted?$msg("DENIED (in session)"):!1===peer.isAccepted?$msg("DENIED"):$msg("NEW")}function getAcceptanceStatusClass(peer){return!0===peer.isTemporaryAccepted||!0===peer.isAccepted?"accepted":!1===peer.isTemporaryAccepted||!1===peer.isAccepted?"denied":"unknown"}async function applyP2PActiveRemoteSelection(id){set(selectingP2PRemote,!0);try{await $$props.core.services.setting.updateSettings(settings=>{settings.P2P_ActiveRemoteConfigurationId=id;if(""===id.trim())return settings;const activated=activateP2PRemoteConfiguration(settings,id);return activated||settings},!0);refreshP2PRemoteOptions()}finally{set(selectingP2PRemote,!1)}}async function createAndSelectP2PRemote(){var _a14;const setupManager=$$props.core.getModule(SetupManager),dialogManager=setupManager.dialogManager,currentSettings=$$props.core.services.setting.currentSettings(),p2pConf=await dialogManager.openWithExplicitCancel(SetupRemoteP2P,currentSettings);if("cancelled"===p2pConf||"object"!=typeof p2pConf||!p2pConf)return;const p2pSettings=p2pConf,id=createRemoteConfigurationId(),roomSuffix=extractP2PRoomSuffix(null!==(_a14=p2pSettings.P2P_roomID)&&void 0!==_a14?_a14:""),name=roomSuffix?`P2P Remote (${roomSuffix})`:"P2P Remote";await $$props.core.services.setting.updateSettings(settings=>{var _a15;const merged={...settings,...p2pSettings},uri=ConnectionStringParser.serialize({type:"p2p",settings:merged});settings.remoteConfigurations={...null!==(_a15=settings.remoteConfigurations)&&void 0!==_a15?_a15:{},[id]:{id,name,uri,isEncrypted:!1}};settings.P2P_ActiveRemoteConfigurationId=id;const activated=activateP2PRemoteConfiguration(settings,id);return activated||settings},!0);refreshP2PRemoteOptions()}async function updateSelectedP2PRemote(partial){var _a14,_b6;const selectedId=null!==(_b6=null===(_a14=$$props.core.services.setting.currentSettings().P2P_ActiveRemoteConfigurationId)||void 0===_a14?void 0:_a14.trim())&&void 0!==_b6?_b6:"";""!==selectedId&&await $$props.core.services.setting.updateSettings(settings=>{var _a15,_b7;const config=null===(_a15=settings.remoteConfigurations)||void 0===_a15?void 0:_a15[selectedId];if(!config)return settings;let parsed;try{parsed=ConnectionStringParser.parse(config.uri)}catch(_c3){return settings}if("p2p"!==parsed.type)return settings;const mergedP2P={...parsed.settings,...partial},uri=ConnectionStringParser.serialize({type:"p2p",settings:{...settings,...mergedP2P}});settings.remoteConfigurations={...null!==(_b7=settings.remoteConfigurations)&&void 0!==_b7?_b7:{},[selectedId]:{...config,uri,isEncrypted:!1}};Object.assign(settings,partial);const activated=activateP2PRemoteConfiguration(settings,selectedId);return activated||settings},!0)}async function makeDecision(peer,decision,isTemporary){set(decidingPeerId,peer.peerId,!0);try{await $$props.getLiveSyncReplicator().makeDecision({peerId:peer.peerId,name:peer.name,decision,isTemporary});await requestServerStatus()}finally{set(decidingPeerId,null)}}async function revokeDecision(peer){set(decidingPeerId,peer.peerId,!0);try{await $$props.getLiveSyncReplicator().revokeDecision({peerId:peer.peerId,name:peer.name});await requestServerStatus()}finally{set(decidingPeerId,null)}}async function startReplication(peer){set(replicatingPeerId,peer.peerId,!0);try{const pullResult=await $$props.getLiveSyncReplicator().replicateFrom(peer.peerId,!0);(null==pullResult?void 0:pullResult.ok)&&await $$props.getLiveSyncReplicator().requestSynchroniseToPeer(peer.peerId);await requestServerStatus()}finally{set(replicatingPeerId,null)}}function isAccepted2(peer){return!0===peer.isTemporaryAccepted||!0===peer.isAccepted}function isWatching(peerId){var _a14,_b6;return null!==(_b6=null===(_a14=null===get2(replicatorInfo)||void 0===get2(replicatorInfo)?void 0:get2(replicatorInfo).watchingPeers)||void 0===_a14?void 0:_a14.includes(peerId))&&void 0!==_b6&&_b6}function toggleWatch(peerId){canEditP2PSettings()&&(isWatching(peerId)?$$props.getLiveSyncReplicator().unwatchPeer(peerId):$$props.getLiveSyncReplicator().watchPeer(peerId))}function isCommunicating(peerId){var _a14,_b6,_c3;const to=null!==(_a14=null===get2(replicatorInfo)||void 0===get2(replicatorInfo)?void 0:get2(replicatorInfo).replicatingTo)&&void 0!==_a14?_a14:[],from=null!==(_b6=null===get2(replicatorInfo)||void 0===get2(replicatorInfo)?void 0:get2(replicatorInfo).replicatingFrom)&&void 0!==_b6?_b6:[],isLiveCommunicating=to.includes(peerId)||from.includes(peerId),isHeldCommunicating=(null!==(_c3=get2(communicatingUntil)[peerId])&&void 0!==_c3?_c3:0)>Date.now();return isLiveCommunicating||isHeldCommunicating}function isPersistedPeerSettingEnabled(setting,peerName){var _a14;const settings=$$props.core.services.setting.currentSettings();return hasExactP2PPeer(null!==(_a14=settings[setting])&&void 0!==_a14?_a14:"",peerName)}async function togglePersistedPeerSetting(peer,setting){if(!canEditP2PSettings())return;const currentSettings=$$props.core.services.setting.currentSettings();await updateSelectedP2PRemote(togglePersistedP2PPeer(currentSettings,setting,peer.name))}function openPeerMenu(event2,peer){null==peerMenu||peerMenu.hide();peerMenu=(new import_obsidian.Menu).addItem(item=>{item.setTitle($msg("Synchronise when this device connects")).setChecked(isPersistedPeerSettingEnabled("P2P_AutoSyncPeers",peer.name)).onClick(()=>{togglePersistedPeerSetting(peer,"P2P_AutoSyncPeers")})}).addItem(item=>{item.setTitle($msg("Follow whenever this device connects")).setChecked(isPersistedPeerSettingEnabled("P2P_AutoWatchPeers",peer.name)).onClick(()=>{togglePersistedPeerSetting(peer,"P2P_AutoWatchPeers")})}).addItem(item=>{item.setTitle($msg("Include in the P2P synchronisation command")).setChecked(isPersistedPeerSettingEnabled("P2P_SyncOnReplication",peer.name)).onClick(()=>{togglePersistedPeerSetting(peer,"P2P_SyncOnReplication")})});const target=event2.currentTarget,rect=target.getBoundingClientRect();peerMenu.showAtPosition({x:rect.left,y:rect.bottom})}var _a13,div,div_1,h22,text2,div_2,div_3,select,node,consequent,node_1,select_value,button,button_1,node_2,consequent_1,d4,node_3,div_4,div_5,h3,text_4,button_2,text_5,node_4,consequent_5,consequent_6,alternate_1;push($$props,!0);append_styles($$anchor,$$css16);let serverInfo=state(void 0),replicatorInfo=state(void 0),decidingPeerId=state(null),replicatingPeerId=state(null),communicatingUntil=state(proxy({}));const initialSettings=(()=>$$props.core.services.setting.currentSettings())();let peerMenu,p2pRemoteOptions=state(proxy([])),selectedP2PRemoteConfigurationId=state(proxy(null!==(_a13=null==initialSettings?void 0:initialSettings.P2P_ActiveRemoteConfigurationId)&&void 0!==_a13?_a13:"")),selectingP2PRemote=state(!1);onMount(()=>{const unsubscribe=eventHub.onEvent(EVENT_SERVER_STATUS,status=>{set(serverInfo,status,!0)}),unsubscribeReplicatorStatus=eventHub.onEvent(EVENT_P2P_REPLICATOR_STATUS,status=>{set(replicatorInfo,status,!0);for(const peerId of status.replicatingFrom)markCommunicating(peerId);for(const peerId of status.replicatingTo)markCommunicating(peerId)}),unsubscribeReplicatorProgress=eventHub.onEvent(EVENT_P2P_REPLICATOR_PROGRESS,report=>{var _a14,_b6;const rep=report;("fetching"in rep&&(null===(_a14=rep.fetching)||void 0===_a14?void 0:_a14.isActive)||"sending"in rep&&(null===(_b6=rep.sending)||void 0===_b6?void 0:_b6.isActive))&&markCommunicating(rep.peerId)}),unsubscribeSettings=eventHub.onEvent(EVENT_SETTING_SAVED,settings=>{refreshP2PRemoteOptions()}),unsubscribeLayoutReady=eventHub.onEvent(EVENT_LAYOUT_READY,()=>{refreshP2PRemoteOptions();requestServerStatus()});fireAndForget(async()=>{await delay(100);refreshP2PRemoteOptions();await requestServerStatus()});return()=>{unsubscribe();unsubscribeReplicatorStatus();unsubscribeReplicatorProgress();unsubscribeSettings();unsubscribeLayoutReady();null==peerMenu||peerMenu.hide()}});div=root_97();div_1=child(div);h22=child(div_1);text2=child(h22,!0);reset(h22);div_2=sibling(h22,2);div_3=child(div_2);select=child(div_3);node=child(select);consequent=$$anchor2=>{var option_1=root42(),text_1=child(option_1,!0);reset(option_1);option_1.value=option_1.__value="";template_effect($0=>set_text(text_1,$0),[()=>$msg("Select P2P remote...")]);append($$anchor2,option_1)};if_block(node,$$render=>{0===get2(p2pRemoteOptions).length&&$$render(consequent)});node_1=sibling(node);each(node_1,17,()=>get2(p2pRemoteOptions),index,($$anchor2,option)=>{var option_2_value,option_2=root42(),text_2=child(option_2);reset(option_2);option_2_value={};template_effect(()=>{var _a14,_b6;set_text(text_2,`${null!=(_a14=get2(option).name)?_a14:""}${get2(option).roomSuffix?` (${get2(option).roomSuffix})`:""}`);option_2_value!==(option_2_value=get2(option).id)&&(option_2.value=null!=(_b6=option_2.__value=get2(option).id)?_b6:"")});append($$anchor2,option_2)});reset(select);init_select(select);button=sibling(select,2);reset(div_3);button_1=sibling(div_3,2);reset(div_2);reset(div_1);node_2=sibling(div_1,2);consequent_1=$$anchor2=>{var p2=root_137(),text_3=child(p2,!0);reset(p2);template_effect($0=>set_text(text_3,$0),[()=>$msg("Please select an active P2P remote configuration to change P2P sync targets.")]);append($$anchor2,p2)};d4=user_derived(()=>!canEditP2PSettings());if_block(node_2,$$render=>{get2(d4)&&$$render(consequent_1)});node_3=sibling(node_2,2);P2PServerStatusCard(node_3,{get getLiveSyncReplicator(){return $$props.getLiveSyncReplicator},get core(){return $$props.core}});div_4=sibling(node_3,2);div_5=child(div_4);h3=child(div_5);text_4=child(h3,!0);reset(h3);button_2=sibling(h3,2);text_5=child(button_2,!0);reset(button_2);reset(div_5);node_4=sibling(div_5,2);consequent_5=$$anchor2=>{var div_6=root_78();each(div_6,21,()=>get2(serverInfo).knownAdvertisements,peer=>peer.peerId,($$anchor3,peer)=>{var node_5,consequent_2,d_1,div_10,span_2,text_8,div_11,node_6,consequent_3,d_2,alternate,node_7,consequent_4,d_3,div_7=root_610(),div_8=child(div_7),div_9=child(div_8),text_6=child(div_9),span=sibling(text_6),text_7=child(span);reset(span);node_5=sibling(span,2);consequent_2=$$anchor4=>{var span_1=root_220();template_effect(($0,$1)=>{set_attribute2(span_1,"title",$0);set_attribute2(span_1,"aria-label",$1)},[()=>$msg("Communicating"),()=>$msg("Communicating")]);append($$anchor4,span_1)};d_1=user_derived(()=>isCommunicating(get2(peer).peerId));if_block(node_5,$$render=>{get2(d_1)&&$$render(consequent_2)});reset(div_9);div_10=sibling(div_9,2);span_2=child(div_10);text_8=child(span_2,!0);reset(span_2);reset(div_10);reset(div_8);div_11=sibling(div_8,2);node_6=child(div_11);consequent_3=$$anchor4=>{var button_3,text_10,button_4,text_11,button_5,div_13,span_4,text_12,button_6,text_13,fragment=root_318(),div_12=first_child(fragment),span_3=child(div_12),text_9=child(span_3,!0);reset(span_3);button_3=sibling(span_3,2);text_10=child(button_3,!0);reset(button_3);button_4=sibling(button_3,2);text_11=child(button_4,!0);reset(button_4);button_5=sibling(button_4,2);reset(div_12);div_13=sibling(div_12,2);span_4=child(div_13);text_12=child(span_4,!0);reset(span_4);button_6=sibling(span_4,2);text_13=child(button_6,!0);reset(button_6);reset(div_13);template_effect(($0,$1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)=>{set_class(span_3,1,`badge status-chip ${null!=$0?$0:""}`,"svelte-17w5ieg");set_text(text_9,$1);button_3.disabled=null!==get2(replicatingPeerId);set_attribute2(button_3,"title",$2);set_attribute2(button_3,"aria-label",$3);set_text(text_10,get2(replicatingPeerId)===get2(peer).peerId?"⏳":"🔄");button_4.disabled=null!==get2(decidingPeerId);set_text(text_11,$4);set_attribute2(button_5,"title",$5);set_attribute2(button_5,"aria-label",$6);button_5.disabled=$7;set_text(text_12,$8);set_class(button_6,1,`emoji-button ${null!=$9?$9:""}`,"svelte-17w5ieg");set_attribute2(button_6,"title",$10);set_attribute2(button_6,"aria-label",$11);button_6.disabled=$12;set_text(text_13,$13)},[()=>getAcceptanceStatusClass(get2(peer)),()=>getAcceptanceStatus(get2(peer)),()=>get2(replicatingPeerId)===get2(peer).peerId?$msg("Replicating..."):$msg("Replicate now"),()=>get2(replicatingPeerId)===get2(peer).peerId?$msg("Replicating"):$msg("Replicate now"),()=>$msg("Revoke"),()=>$msg("More actions for ${DEVICE}",{DEVICE:get2(peer).name}),()=>$msg("More actions for ${DEVICE}",{DEVICE:get2(peer).name}),()=>!canEditP2PSettings(),()=>$msg("Follow changes"),()=>isWatching(get2(peer).peerId)?"is-watching":"",()=>isWatching(get2(peer).peerId)?$msg("Stop following changes from this device"):$msg("Follow changes from this device"),()=>isWatching(get2(peer).peerId)?$msg("Stop following changes from this device"):$msg("Follow changes from this device"),()=>!canEditP2PSettings(),()=>isWatching(get2(peer).peerId)?"🔔":"🔕"]);delegated("click",button_3,()=>startReplication(get2(peer)));delegated("click",button_4,()=>revokeDecision(get2(peer)));delegated("click",button_5,event2=>openPeerMenu(event2,get2(peer)));delegated("click",button_6,()=>toggleWatch(get2(peer).peerId));append($$anchor4,fragment)};d_2=user_derived(()=>isAccepted2(get2(peer)));alternate=$$anchor4=>{var div_15,span_6,text_15,button_7,button_8,div_16,span_7,text_16,button_9,button_10,fragment_1=root_412(),div_14=first_child(fragment_1),span_5=child(div_14),text_14=child(span_5,!0);reset(span_5);reset(div_14);div_15=sibling(div_14,2);span_6=child(div_15);text_15=child(span_6,!0);reset(span_6);button_7=sibling(span_6,2);button_8=sibling(button_7,2);reset(div_15);div_16=sibling(div_15,2);span_7=child(div_16);text_16=child(span_7,!0);reset(span_7);button_9=sibling(span_7,2);button_10=sibling(button_9,2);reset(div_16);template_effect(($0,$1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)=>{set_class(span_5,1,`badge status-chip ${null!=$0?$0:""}`,"svelte-17w5ieg");set_text(text_14,$1);set_text(text_15,$2);set_attribute2(button_7,"title",$3);set_attribute2(button_7,"aria-label",$4);button_7.disabled=null!==get2(decidingPeerId);set_attribute2(button_8,"title",$5);set_attribute2(button_8,"aria-label",$6);button_8.disabled=null!==get2(decidingPeerId);set_text(text_16,$7);set_attribute2(button_9,"title",$8);set_attribute2(button_9,"aria-label",$9);button_9.disabled=null!==get2(decidingPeerId);set_attribute2(button_10,"title",$10);set_attribute2(button_10,"aria-label",$11);button_10.disabled=null!==get2(decidingPeerId)},[()=>getAcceptanceStatusClass(get2(peer)),()=>getAcceptanceStatus(get2(peer)),()=>$msg("PERMANENT"),()=>$msg("Allow permanently"),()=>$msg("Allow permanently"),()=>$msg("Deny permanently"),()=>$msg("Deny permanently"),()=>$msg("SESSION"),()=>$msg("Allow in session"),()=>$msg("Allow in session"),()=>$msg("Deny in session"),()=>$msg("Deny in session")]);delegated("click",button_7,()=>makeDecision(get2(peer),!0,!1));delegated("click",button_8,()=>makeDecision(get2(peer),!1,!1));delegated("click",button_9,()=>makeDecision(get2(peer),!0,!0));delegated("click",button_10,()=>makeDecision(get2(peer),!1,!0));append($$anchor4,fragment_1)};if_block(node_6,$$render=>{get2(d_2)?$$render(consequent_3):$$render(alternate,-1)});node_7=sibling(node_6,2);consequent_4=$$anchor4=>{var button_11=root_512(),text_17=child(button_11,!0);reset(button_11);template_effect($0=>{button_11.disabled=null!==get2(decidingPeerId);set_text(text_17,$0)},[()=>$msg("Revoke")]);delegated("click",button_11,()=>revokeDecision(get2(peer)));append($$anchor4,button_11)};d_3=user_derived(()=>!isAccepted2(get2(peer))&&(void 0!==get2(peer).isAccepted||void 0!==get2(peer).isTemporaryAccepted));if_block(node_7,$$render=>{get2(d_3)&&$$render(consequent_4)});reset(div_11);reset(div_7);template_effect($0=>{var _a14;set_text(text_6,`${null!=(_a14=get2(peer).name)?_a14:""} : `);set_attribute2(span,"title",get2(peer).peerId);set_text(text_7,`(${null!=$0?$0:""})`);set_text(text_8,get2(peer).platform)},[()=>get2(peer).peerId.slice(0,8)]);append($$anchor3,div_7)});reset(div_6);append($$anchor2,div_6)};consequent_6=$$anchor2=>{var p_1=root_88(),text_18=child(p_1,!0);reset(p_1);template_effect($0=>set_text(text_18,$0),[()=>$msg("No devices available. Waiting for other devices to connect...")]);append($$anchor2,p_1)};alternate_1=$$anchor2=>{var p_2=root_88(),text_19=child(p_2,!0);reset(p_2);template_effect($0=>set_text(text_19,$0),[()=>$msg("Fetching status...")]);append($$anchor2,p_2)};if_block(node_4,$$render=>{get2(serverInfo)&&get2(serverInfo).knownAdvertisements.length>0?$$render(consequent_5):get2(serverInfo)?$$render(consequent_6,1):$$render(alternate_1,-1)});reset(div_4);reset(div);template_effect(($0,$1,$2,$3,$4,$5,$6,$7,$8)=>{var _a14;set_text(text2,$0);select.disabled=get2(selectingP2PRemote);set_attribute2(select,"aria-label",$1);set_attribute2(select,"title",$2);select_value!==(select_value=get2(selectedP2PRemoteConfigurationId))&&(select.value=null!=(_a14=select.__value=get2(selectedP2PRemoteConfigurationId))?_a14:"",select_option(select,get2(selectedP2PRemoteConfigurationId)));set_attribute2(button,"title",$3);set_attribute2(button,"aria-label",$4);set_attribute2(button_1,"title",$5);set_attribute2(button_1,"aria-label",$6);set_text(text_4,$7);set_text(text_5,$8)},[()=>$msg("P2P Status"),()=>$msg("Select active P2P remote"),()=>$msg("Select active P2P remote"),()=>$msg("Create P2P remote"),()=>$msg("Create P2P remote"),()=>$msg("Open P2P Setup..."),()=>$msg("Open P2P Setup..."),()=>$msg("Detected Peers"),()=>$msg("Refresh")]);delegated("change",select,async function onP2PRemoteSelected(event2){const target=event2.currentTarget,id=target.value;set(selectedP2PRemoteConfigurationId,id,!0);await applyP2PActiveRemoteSelection(id)});delegated("click",button,()=>createAndSelectP2PRemote());delegated("click",button_1,function openConnectionSettings(){eventHub.emitEvent(EVENT_REQUEST_OPEN_P2P_SETTINGS)});delegated("click",button_2,requestServerStatus);append($$anchor,div);pop()}function hasP2PConfiguration(settings){var _a13,_b6,_c3;return settings.remoteType===REMOTE_P2P||!0===settings.P2P_Enabled||""!==(null!=(_a13=settings.P2P_roomID)?_a13:"").trim()||""!==(null!=(_b6=settings.P2P_passphrase)?_b6:"").trim()||Object.values(null!=(_c3=settings.remoteConfigurations)?_c3:{}).some(configuration=>{try{return"p2p"===ConnectionStringParser.parse(configuration.uri).type}catch(e3){return!1}})}function useP2PReplicatorUI(host,core,replicator){const api=host.services.API,getReplicator=()=>replicator.replicator,p2pLogCollector=new P2PLogCollector(host.services.context.events),storeP2PStatusLine=reactiveSource("");p2pLogCollector.p2pReplicationLine.onChanged(line=>{storeP2PStatusLine.value=line.value});const p2pParams={get replicator(){return getReplicator()},p2pLogCollector,storeP2PStatusLine},openStatusPane=()=>api.showWindowOnRight?api.showWindowOnRight(VIEW_TYPE_P2P_SERVER_STATUS):api.showWindow(VIEW_TYPE_P2P_SERVER_STATUS),runOpenReplication=()=>{const activeReplicator=replicator.replicator;if(!activeReplicator)return;const settings=host.services.setting.currentSettings();host.services.replicator.runFiniteReplicationActivity(()=>activeReplicator.openReplication(settings,!1,!0,!1),{label:"replication"})};api.registerWindow(LEGACY_VIEW_TYPE_P2P,leaf=>new LegacyP2PStatusPaneView(leaf,core,p2pParams));api.registerWindow(VIEW_TYPE_P2P_SERVER_STATUS,leaf=>new P2PServerStatusPaneView(leaf,core,p2pParams));let ribbonElement;const updateRibbon=settings=>{var _a13,_b6;if(hasP2PConfiguration(settings)){if(ribbonElement)return;ribbonElement=api.addRibbonIcon("waypoints","P2P Status",()=>{openStatusPane()});null==(_a13=null==ribbonElement?void 0:ribbonElement.addClass)||_a13.call(ribbonElement,"livesync-ribbon-p2p-server-status")}else{null==(_b6=null==ribbonElement?void 0:ribbonElement.remove)||_b6.call(ribbonElement);ribbonElement=void 0}};host.services.appLifecycle.onSettingLoaded.addHandler(()=>{updateRibbon(host.services.setting.currentSettings());return Promise.resolve(!0)});host.services.appLifecycle.onInitialise.addHandler(()=>{var _a13;eventHub.onEvent(EVENT_REQUEST_OPEN_P2P,()=>{openStatusPane()});api.addCommand({id:"open-p2p-server-status",name:"P2P Sync : Open P2P Status",checkCallback:checking=>{if(!hasP2PConfiguration(host.services.setting.currentSettings()))return!1;checking||openStatusPane();return!0}});host.services.API.addCommand({id:"replicate-now-by-p2p-default-peer",name:"Replicate P2P to default peer",checkCallback:isChecking=>{var _a14,_b6,_c3;const settings=host.services.setting.currentSettings(),isAvailable=hasP2PConfiguration(settings)&&settings.remoteType!==REMOTE_P2P&&null!=(_c3=null==(_b6=null==(_a14=replicator.replicator)?void 0:_a14.server)?void 0:_b6.isServing)&&_c3;if(!isAvailable)return!1;isChecking||runOpenReplication();return!0}});host.services.API.addCommand({id:"replicate-now-by-p2p",name:"Replicate now by P2P",checkCallback:isChecking=>{var _a14,_b6,_c3;const settings=host.services.setting.currentSettings(),isAvailable=hasP2PConfiguration(settings)&&settings.remoteType!==REMOTE_P2P&&null!=(_c3=null==(_b6=null==(_a14=replicator.replicator)?void 0:_a14.server)?void 0:_b6.isServing)&&_c3;if(!isAvailable)return!1;isChecking||runOpenReplication();return!0}});host.services.API.addCommand({id:"p2p-sync-targets",name:"P2P: Sync with targets",checkCallback:isChecking=>{var _a14,_b6,_c3,_d2;const isAvailable=hasP2PConfiguration(host.services.setting.currentSettings())&&null!=(_c3=null==(_b6=null==(_a14=replicator.replicator)?void 0:_a14.server)?void 0:_b6.isServing)&&_c3;if(!isAvailable)return!1;isChecking||null==(_d2=replicator.replicator)||_d2.replicateFromCommand(!0);return!0}});null==(_a13=host.services.setting.onSettingSaved)||_a13.addHandler(settings=>{updateRibbon(settings);return Promise.resolve(!0)});return Promise.resolve(!0)});host.services.appLifecycle.onLayoutReady.addHandler(async()=>{var _a13;const workspace=null==(_a13=host.services.context.app)?void 0:_a13.workspace;if(!workspace)return!0;const legacyLeaves=workspace.getLeavesOfType(LEGACY_VIEW_TYPE_P2P);await Promise.all(legacyLeaves.map(leaf=>leaf.setViewState({type:VIEW_TYPE_P2P_SERVER_STATUS,active:!1})));return!0});return p2pParams}function isRecord3(value){return"object"==typeof value&&null!==value}function parsePendingReviewRun(serialised){if(!serialised)return{};let value;try{value=JSON.parse(serialised)}catch(e3){return{error:"Review Harness continuation is not valid JSON"}}if(!isRecord3(value))return{error:"Review Harness continuation must be an object"};if(1!==value.formatVersion)return{error:`Unsupported Review Harness continuation version: ${String(value.formatVersion)}`};if("compatibility-review"!==value.scenarioId)return{error:`Unknown Review Harness scenario: ${String(value.scenarioId)}`};if("awaiting-restart"!==value.stage)return{error:`Unknown Review Harness continuation stage: ${String(value.stage)}`};if("string"!=typeof value.requestedAt)return{error:"Review Harness request time must be an ISO date"};const requestedAtMs=Date.parse(value.requestedAt);return Number.isNaN(requestedAtMs)||new Date(requestedAtMs).toISOString()!==value.requestedAt?{error:"Review Harness request time must be an ISO date"}:value.requestId!==`compatibility-review-${value.requestedAt}`?{error:"Review Harness request ID does not match the fixed continuation format"}:{pendingRun:{formatVersion:1,requestId:value.requestId,scenarioId:value.scenarioId,stage:value.stage,requestedAt:value.requestedAt}}}function inspectSettingsLifecycle(input){if(!input.migration)return{status:"failed",detail:"The settings service did not expose migration evidence.",observations:[]};const invalidSyncSettings=PRESERVED_SYNC_SETTING_KEYS.filter(key3=>"boolean"!=typeof input.settings[key3]);if(invalidSyncSettings.length>0)return{status:"failed",detail:`Synchronisation choices are missing or invalid: ${invalidSyncSettings.join(", ")}`,observations:[]};const observations=PRESERVED_SYNC_SETTING_KEYS.map(key3=>`${key3}=${String(input.settings[key3])}`);if(!input.migration.isNewVault)return{status:"passed",detail:`Loaded an existing Vault from settings schema ${input.migration.sourceVersion} to ${input.migration.targetVersion}.`,observations};const mismatchedRecommendations=NEW_VAULT_RECOMMENDATION_KEYS.filter(key3=>input.settings[key3]!==input.newVaultSettings[key3]);return mismatchedRecommendations.length>0?{status:"failed",detail:`The new Vault recommendations differ for: ${mismatchedRecommendations.join(", ")}`,observations}:{status:"passed",detail:"Loaded the current new Vault recommendations without enabling a remote connection.",observations}}function inspectCompatibilityReview(input){var _a13,_b6,_c3;if((null==(_a13=input.migration)?void 0:_a13.requiresSyncReview)&&!input.reviewInitialised)return{status:"failed",detail:"The settings migration requires review, but the compatibility review was not initialised.",observations:[]};const observations=[`migrationReviewRequired=${String(null!=(_c3=null==(_b6=input.migration)?void 0:_b6.requiresSyncReview)&&_c3)}`,`compatibilityReviewInitialised=${String(input.reviewInitialised)}`,`compatibilityPausePending=${String(void 0!==input.pendingPause)}`];if(input.pendingPause){observations.push(`reasonSources=${input.pendingPause.reasons.map(({source:source2})=>source2).join(",")}`);observations.push(`reasonCount=${input.pendingPause.reasons.length}`);observations.push(`resumable=${String(input.pendingPause.resumable)}`)}return{status:"passed",detail:input.pendingPause?"A device-local compatibility review is pending.":"No compatibility review is pending on this device.",observations}}function tableCell(value){return value.replace(/\|/gu,"\\|").replace(/\r?\n/gu,"<br>")}function table2(headers,rows){const header=`| ${headers.map(tableCell).join(" | ")} |`,separator=`| ${headers.map(()=>"---").join(" | ")} |`,body=rows.map(row=>`| ${row.map(tableCell).join(" | ")} |`);return[header,separator,...body].join("\n")}function formatReviewHarnessReport(input){const environment=table2(["Field","Value"],[["Plug-in",input.environment.pluginVersion],["Obsidian",input.environment.obsidianVersion],["Platform",input.environment.platform],["User agent",input.environment.userAgent],["Viewport",input.environment.viewport]]),scenarios=table2(["Scenario","Mode","Status","Detail"],input.scenarios.map(({id,title,mode,status,detail})=>[`${title} (${id})`,mode,status,detail]));return`## Self-hosted LiveSync Review Harness report\n\nGenerated at \`${tableCell(input.generatedAt)}\`.\n\n### Environment\n\n${environment}\n\n### Scenarios\n\n${scenarios}\n\n<details>\n<summary>Event transcript</summary>\n\n\`\`\`json\n${JSON.stringify(input.transcript,null,2)}\n\`\`\`\n</details>\n\nThis report was copied locally and was not transmitted by Self-hosted LiveSync. It intentionally omits Vault identifiers, paths, file names, file contents, remote configuration, and secrets. Review the environment information before posting because a user agent and viewport may identify the device or operating system.\n`}function initialResults(){return Object.fromEntries(REVIEW_HARNESS_SCENARIOS.map(({id})=>[id,idleResult()]))}function inspectP2PComposition(input){if(input.first!==input.second)return{status:"failed",detail:"Two consecutive reads resolved different P2P replicators without a lifecycle transition.",observations:[]};if("object"!=typeof input.first||null===input.first)return{status:"failed",detail:"The P2P composition did not expose a current replicator.",observations:[]};const env="env"in input.first?input.first.env:void 0,services="object"==typeof env&&null!==env&&"services"in env?env.services:void 0;return services!==input.expectedServices?{status:"failed",detail:"The current P2P replicator is not bound to the active Obsidian services.",observations:[]}:{status:"passed",detail:"The live P2P result resolves the current replicator and active Obsidian services.",observations:[]}}async function runReviewHarnessVaultRoundTrip(runtime){if(!await runtime.confirmFixtureAccess())return{status:"cancelled",detail:"Vault fixture access was not approved.",observations:[]};if(runtime.fixtureRootExists())return{status:"failed",detail:"The owned fixture root already exists. It was left untouched.",observations:[]};let fixtureOwned=!1;try{await runtime.createFixtureRoot();fixtureOwned=!0;const file=await runtime.createFile(REVIEW_HARNESS_SOURCE_FILE,CREATED_CONTENT),created=await runtime.readFile(file);if(created!==CREATED_CONTENT)throw new Error("Created fixture content did not round-trip.");await runtime.modifyFile(file,MODIFIED_CONTENT);const modified=await runtime.readFile(file);if(modified!==MODIFIED_CONTENT)throw new Error("Modified fixture content did not round-trip.");await runtime.renameFile(file,REVIEW_HARNESS_RENAMED_FILE);if(runtime.filePath(file)!==REVIEW_HARNESS_RENAMED_FILE)throw new Error("The fixture rename did not update its path.");const renamed=await runtime.readFile(file);if(renamed!==MODIFIED_CONTENT)throw new Error("Renamed fixture content was not preserved.");return{status:"passed",detail:"The owned fixture tree completed its round trip and was removed.",observations:["create","read","modify","rename","read-after-rename","cleanup"]}}finally{fixtureOwned&&await runtime.removeFixtureRoot()}}async function runVaultRoundTrip(plugin2){const vault=plugin2.app.vault;return runReviewHarnessVaultRoundTrip({confirmFixtureAccess:async()=>"yes"===await plugin2.core.services.UI.confirm.askYesNoDialog("This scenario creates, reads, modifies, renames, and removes one owned fixture tree. Use a dedicated test Vault. Continue?",{title:"Review Harness: Vault fixture access",defaultOption:"No"}),fixtureRootExists:()=>null!==vault.getAbstractFileByPath(REVIEW_HARNESS_FIXTURE_ROOT),createFixtureRoot:async()=>{await vault.createFolder(REVIEW_HARNESS_FIXTURE_ROOT)},createFile:(path2,content)=>vault.create(path2,content),readFile:file=>vault.read(file),modifyFile:(file,content)=>vault.modify(file,content),renameFile:(file,path2)=>vault.rename(file,path2),filePath:file=>file.path,removeFixtureRoot:async()=>{const fixtureRoot=vault.getAbstractFileByPath(REVIEW_HARNESS_FIXTURE_ROOT);fixtureRoot&&await plugin2.app.fileManager.trashFile(fixtureRoot)}})}function useReviewHarness(core,plugin2,p2p,compatibilityReview){const services=core.services,runtime={now:()=>new Date,getSettings:()=>services.setting.currentSettings(),getNewVaultSettings:()=>NEW_VAULT_SETTINGS,getSettingsMigrationState:()=>services.setting.getSettingsMigrationState(),isCompatibilityReviewInitialised:()=>compatibilityReview.initialised,getCompatibilityPause:()=>compatibilityReview.pendingPause,openCompatibilityReview:()=>compatibilityReview.openReview(),getP2PComposition:()=>({first:p2p.replicator,second:p2p.replicator,expectedServices:services}),runVaultRoundTrip:()=>runVaultRoundTrip(plugin2),readContinuation:()=>services.setting.getSmallConfig(REVIEW_HARNESS_STATE_KEY),writeContinuation:value=>services.setting.setSmallConfig(REVIEW_HARNESS_STATE_KEY,value),deleteContinuation:()=>services.setting.deleteSmallConfig(REVIEW_HARNESS_STATE_KEY),restart:()=>services.appLifecycle.performRestart(),reportError:error=>services.API.addLog(error,LOG_LEVEL_NOTICE),copyText:async value=>{if(!activeWindow.navigator.clipboard)throw new Error("Clipboard access is unavailable on this device.");await activeWindow.navigator.clipboard.writeText(value)},getEnvironment:()=>({pluginVersion:services.API.getPluginVersion(),obsidianVersion:services.API.getAppVersion(),platform:services.API.getPlatform(),userAgent:activeWindow.navigator.userAgent||"unavailable",viewport:"number"==typeof activeWindow.innerWidth&&"number"==typeof activeWindow.innerHeight?`${activeWindow.innerWidth}x${activeWindow.innerHeight}`:"unavailable"})},controller=new ReviewHarnessController(runtime);let continuationConsumed=!1,registered=!1,openAfterLayout=!1;services.appLifecycle.onSettingLoaded.addHandler(()=>{if(!continuationConsumed){continuationConsumed=!0;controller.consumeContinuation()}const snapshot2=controller.snapshot();openAfterLayout=null!==snapshot2.resumedRequestId||null!==snapshot2.continuationError;if(!services.setting.currentSettings().enableDebugTools||registered)return Promise.resolve(!0);registered=!0;services.API.registerWindow(VIEW_TYPE_REVIEW_HARNESS,leaf=>new ReviewHarnessView(leaf,controller));services.API.addCommand({id:"open-review-harness",name:"Open review harness",callback:()=>{services.API.showWindow(VIEW_TYPE_REVIEW_HARNESS)}});return Promise.resolve(!0)});services.appLifecycle.onLayoutReady.addHandler(()=>{openAfterLayout&&services.setting.currentSettings().enableDebugTools&&services.API.showWindow(VIEW_TYPE_REVIEW_HARNESS);return Promise.resolve(!0)});return controller}function P2POpenReplicationPane($$anchor,$$props){async function requestServerStatus(){await $$props.liveSyncReplicator.requestStatus();eventHub.emitEvent(EVENT_REQUEST_STATUS)}async function handleSync(peerId){try{set(syncingPeerId,peerId,!0);Logger(`Starting sync with ${peerId}`,get2(logLevel));await $$props.onSync(peerId);Logger(`Sync completed with ${peerId}`,get2(logLevel))}catch(e3){Logger(`Error during sync: ${e3 instanceof Error?e3.message:String(e3)}`,get2(logLevel))}finally{set(syncingPeerId,null)}}async function handleSyncThenClose(peerId){try{set(syncingPeerId,peerId,!0);Logger(`Starting sync with ${peerId}`,get2(logLevel));await $$props.onSyncAndClose(peerId);Logger(`Sync completed with ${peerId}`,get2(logLevel))}catch(e3){Logger(`Error during sync: ${e3 instanceof Error?e3.message:String(e3)}`,get2(logLevel))}finally{set(syncingPeerId,null)}}async function disconnect(){try{await $$props.liveSyncReplicator.close();Logger("Signalling connection closed.",get2(logLevel))}catch(e3){Logger(`Failed to close signalling connection: ${e3 instanceof Error?e3.message:String(e3)}`,get2(logLevel))}}async function onCloseAndDisconnect(){await disconnect();$$props.onClose()}function getAcceptanceStatus(peer){return!0===peer.isTemporaryAccepted?$msg("ACCEPTED (in session)"):!0===peer.isAccepted?$msg("ACCEPTED"):!1===peer.isTemporaryAccepted?$msg("DENIED (in session)"):!1===peer.isAccepted?$msg("DENIED"):$msg("NEW")}function getAcceptanceStatusClass(peer){return!0===peer.isTemporaryAccepted||!0===peer.isAccepted?"accepted":!1===peer.isTemporaryAccepted||!1===peer.isAccepted?"denied":"unknown"}var div,node,div_1,h3,text2,node_1,consequent_1,consequent_2,div_8,node_3,consequent_3,alternate_1;push($$props,!0);append_styles($$anchor,$$css17);let rebuildMode=prop($$props,"rebuildMode",3,!1);let serverInfo=state(void 0),syncingPeerId=state(null);const logLevel=user_derived(()=>$$props.showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO);onMount(()=>{const unsubscribe=eventHub.onEvent(EVENT_SERVER_STATUS,status=>{set(serverInfo,status,!0)});fireAndForget(async()=>{await delay(100);await requestServerStatus()});return unsubscribe});div=root_79();node=child(div);P2PServerStatusCard(node,{getLiveSyncReplicator:()=>$$props.liveSyncReplicator,showBroadcastToggle:!1});div_1=sibling(node,2);h3=child(div_1);text2=child(h3,!0);reset(h3);node_1=sibling(h3,2);consequent_1=$$anchor2=>{var div_2=root_319();each(div_2,21,()=>get2(serverInfo).knownAdvertisements,peer=>peer.peerId,($$anchor3,peer)=>{var div_6,span,text_2,span_1,text_3,span_2,text_4,div_7,node_2,consequent,alternate,div_3=root_221(),div_4=child(div_3),div_5=child(div_4),text_1=child(div_5,!0);reset(div_5);div_6=sibling(div_5,2);span=child(div_6);text_2=child(span,!0);reset(span);span_1=sibling(span,2);text_3=child(span_1,!0);reset(span_1);span_2=sibling(span_1,2);text_4=child(span_2,!0);reset(span_2);reset(div_6);reset(div_4);div_7=sibling(div_4,2);node_2=child(div_7);consequent=$$anchor4=>{var button_1,text_6,fragment=root43(),button=first_child(fragment),text_5=child(button,!0);reset(button);button_1=sibling(button,2);text_6=child(button_1,!0);reset(button_1);template_effect(($0,$1)=>{button.disabled=null!==get2(syncingPeerId);set_text(text_5,$0);set_class(button_1,1,"btn "+(rebuildMode()?"btn-primary":"btn-secondary"),"svelte-15bwvlz");button_1.disabled=null!==get2(syncingPeerId);set_text(text_6,$1)},[()=>get2(syncingPeerId)===get2(peer).peerId?$msg("Syncing..."):$msg("Sync"),()=>get2(syncingPeerId)===get2(peer).peerId?$msg("Syncing..."):$msg("Start Sync & Close")]);delegated("click",button,()=>handleSync(get2(peer).peerId));delegated("click",button_1,()=>handleSyncThenClose(get2(peer).peerId));append($$anchor4,fragment)};alternate=$$anchor4=>{var button_2=root_138(),text_7=child(button_2,!0);reset(button_2);template_effect($0=>{set_class(button_2,1,"btn "+(rebuildMode()?"btn-primary":"btn-secondary"),"svelte-15bwvlz");button_2.disabled=null!==get2(syncingPeerId);set_text(text_7,$0)},[()=>get2(syncingPeerId)===get2(peer).peerId?$msg("Syncing..."):$msg("Sync")]);delegated("click",button_2,()=>handleSyncThenClose(get2(peer).peerId));append($$anchor4,button_2)};if_block(node_2,$$render=>{rebuildMode()?$$render(alternate,-1):$$render(consequent)});reset(div_7);reset(div_3);template_effect(($0,$1,$2)=>{set_text(text_1,get2(peer).name);set_text(text_2,get2(peer).platform);set_attribute2(span_1,"title",get2(peer).peerId);set_text(text_3,$0);set_class(span_2,1,`badge status-chip ${null!=$1?$1:""}`,"svelte-15bwvlz");set_text(text_4,$2)},[()=>get2(peer).peerId.slice(0,8),()=>getAcceptanceStatusClass(get2(peer)),()=>getAcceptanceStatus(get2(peer))]);append($$anchor3,div_3)});reset(div_2);append($$anchor2,div_2)};consequent_2=$$anchor2=>{var p2=root_413(),text_8=child(p2,!0);reset(p2);template_effect($0=>set_text(text_8,$0),[()=>$msg("No devices available. Waiting for other devices to connect...")]);append($$anchor2,p2)};if_block(node_1,$$render=>{get2(serverInfo)&&get2(serverInfo).knownAdvertisements.length>0?$$render(consequent_1):get2(serverInfo)&&$$render(consequent_2,1)});reset(div_1);div_8=sibling(div_1,2);node_3=child(div_8);consequent_3=$$anchor2=>{var button_3=root_513(),text_9=child(button_3,!0);reset(button_3);template_effect($0=>{button_3.disabled=null!==get2(syncingPeerId);set_text(text_9,$0)},[()=>$msg("Skip and close")]);delegated("click",button_3,function(...$$args){var _a13;null==(_a13=$$props.onClose)||_a13.apply(this,$$args)});append($$anchor2,button_3)};alternate_1=$$anchor2=>{var button_5,text_11,fragment_1=root_611(),button_4=first_child(fragment_1),text_10=child(button_4,!0);reset(button_4);button_5=sibling(button_4,2);text_11=child(button_5,!0);reset(button_5);template_effect(($0,$1)=>{set_text(text_10,$0);set_text(text_11,$1)},[()=>$msg("Close"),()=>$msg("Close & Disconnect")]);delegated("click",button_4,function(...$$args){var _a13;null==(_a13=$$props.onClose)||_a13.apply(this,$$args)});delegated("click",button_5,onCloseAndDisconnect);append($$anchor2,fragment_1)};if_block(node_3,$$render=>{rebuildMode()?$$render(consequent_3):$$render(alternate_1,-1)});reset(div_8);reset(div);template_effect($0=>set_text(text2,$0),[()=>$msg("Available Peers")]);append($$anchor,div);pop()}function createOpenReplicationUI(app){return replicator=>showResult=>{const logLevel=showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO;return new Promise(resolve=>{let resolved=!1,sessionResult=!1,activeSynchronisations=0,closed=!1;const safeResolve=()=>{if(!resolved){resolved=!0;resolve(sessionResult)}},settleClosedSession=()=>{closed&&0===activeSynchronisations&&safeResolve()},synchronise=async(peerId,closeConnection)=>{var _a13;activeSynchronisations++;try{const pullResult=await replicator.replicateFrom(peerId,showResult);if(!(null==pullResult?void 0:pullResult.ok)){sessionResult=!1;return}const pushResult=await replicator.requestSynchroniseToPeer(peerId);sessionResult=null==(_a13=null==pushResult?void 0:pushResult.ok)||_a13;sessionResult&&closeConnection&&await replicator.close()}catch(e3){Logger(`Error in bidirectional sync with ${peerId}: ${e3 instanceof Error?e3.message:String(e3)}`,logLevel);sessionResult=!1}finally{activeSynchronisations--;settleClosedSession()}},modal=new P2POpenReplicationModal(app,replicator,{onSync:peerId=>synchronise(peerId,!1),onSyncAndClose:peerId=>synchronise(peerId,!0)},showResult,"P2P Replication",()=>{closed=!0;settleClosedSession()});modal.open()})}}function createOpenRebuildUI(app){return replicator=>showResult=>{const logLevel=showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO;return new Promise(resolve=>{let resolved=!1,activeSynchronisations=0,closed=!1,operationCompleted=!1,sessionResult=!1;const safeResolve=val=>{if(!resolved){resolved=!0;resolve(val)}},settleSession=()=>{0===activeSynchronisations&&(closed||operationCompleted)&&safeResolve(sessionResult)},doRebuild=async peerId=>{var _a13;activeSynchronisations++;try{replicator.setOnSetup();Logger(`Rebuilding from peer ${peerId}`,logLevel);const result=await replicator.replicateFrom(peerId,showResult,!0);sessionResult=null!=(_a13=null==result?void 0:result.ok)&&_a13}catch(e3){Logger(`Error in rebuild from ${peerId}: ${e3 instanceof Error?e3.message:String(e3)}`,logLevel);sessionResult=!1}finally{try{replicator.clearOnSetup()}finally{operationCompleted=!0;activeSynchronisations--;settleSession()}}},modal=new P2POpenReplicationModal(app,replicator,{onSync:doRebuild,onSyncAndClose:doRebuild},showResult,"P2P Rebuild",()=>{closed=!0;settleSession()},!0);modal.open()})}}function databaseVersionReason(acknowledgedVersion,currentVersion,isNewVault){if(null===acknowledgedVersion||""===acknowledgedVersion){if(isNewVault)return;return{source:"database-version",state:"missing",currentVersion,resumable:!0}}const parsed=Number(acknowledgedVersion);return Number.isSafeInteger(parsed)?parsed!==currentVersion?parsed<currentVersion?{source:"database-version",state:"upgrade",acknowledgedVersion:parsed,currentVersion,resumable:!0}:{source:"database-version",state:"downgrade",acknowledgedVersion:parsed,currentVersion,resumable:!1}:void 0:{source:"database-version",state:"invalid",currentVersion,resumable:!0}}function evaluateCompatibilityPause(input){var _a13,_b6;const isNewVault=!0===(null==(_a13=input.migrationState)?void 0:_a13.isNewVault),reasons=[],databaseReason=databaseVersionReason(input.acknowledgedVersion,input.currentVersion,isNewVault);databaseReason&&reasons.push(databaseReason);!0===(null==(_b6=input.migrationState)?void 0:_b6.requiresSyncReview)&&reasons.push({source:"settings-schema",sourceVersion:input.migrationState.sourceVersion,currentVersion:input.migrationState.targetVersion,isFromFutureSchema:input.migrationState.isFromFutureSchema,resumable:!input.migrationState.isFromFutureSchema,reviewReasons:input.migrationState.reviewReasons});""!==input.legacyReviewMessage&&0===reasons.length&&reasons.push({source:"legacy-review",message:input.legacyReviewMessage,resumable:!0});return 0===reasons.length?{initialiseAcknowledgedVersion:isNewVault&&(null===input.acknowledgedVersion||""===input.acknowledgedVersion)}:{pause:{reasons,resumable:reasons.every(reason=>reason.resumable)},initialiseAcknowledgedVersion:!1}}function legacyDatabaseCompatibilityVersionKey(vaultName){return`${DATABASE_COMPATIBILITY_LEGACY_VERSION_KEY_PREFIX}${vaultName}`}function useCompatibilityReview(core,ui){const controller=new CompatibilityReviewController(core,ui);core.services.appLifecycle.onSettingLoaded.addHandler(()=>controller.initialise());core.services.appLifecycle.onLayoutReady.addHandler(()=>{fireAndForget(()=>controller.openReview());return Promise.resolve(!0)},COMPATIBILITY_REVIEW_LAYOUT_PRIORITY);core.services.appLifecycle.onUnload.addHandler(()=>{controller.dispose();return Promise.resolve(!0)});core.services.API.addCommand({id:"livesync-review-compatibility-pause",name:"Review why synchronisation is paused",checkCallback:checking=>{if(!controller.pendingPause)return!1;checking||fireAndForget(()=>controller.openReview());return!0}});return controller}function compatibilityReviewSummaryMarkdown(pause){const action2=pause.resumable?"Before resuming, review the compatibility details and update Self-hosted LiveSync on every device which uses this remote database.":"This installation cannot safely acknowledge the detected state. Update Self-hosted LiveSync before attempting to synchronise again.";return`Remote synchronisation is paused on this device because its compatibility state requires attention.\n\n${action2}\n\nYour automatic synchronisation preferences have not been changed. Closing this dialogue keeps synchronisation paused.`}function reasonMarkdown(reason){if("database-version"===reason.source)return"upgrade"===reason.state?`- The last acknowledged internal database version was **${reason.acknowledgedVersion}** and this installation uses **${reason.currentVersion}**.`:"downgrade"===reason.state?`- This installation uses internal database version **${reason.currentVersion}**, but this device previously acknowledged newer version **${reason.acknowledgedVersion}**. An older installation must not resume synchronisation.`:"missing"===reason.state?`- No previously acknowledged internal database version was found for this existing Vault. This can happen when a Vault is copied or restored, or when it is opened with a new Obsidian profile. This installation uses version **${reason.currentVersion}**. An empty local database does not mean that it is safe to resume automatically.`:`- The saved internal database version marker is invalid. This installation uses version **${reason.currentVersion}**.`;if("settings-schema"===reason.source)return reason.isFromFutureSchema?`- The saved settings use schema **${reason.sourceVersion}**, which is newer than schema **${reason.currentVersion}** supported by this installation.`:`- The settings were migrated from schema **${reason.sourceVersion}** to **${reason.currentVersion}** and require review before synchronisation resumes.`;const escapedMessage=reason.message.replace(/[\\`*_{}[\]()<>#+.!|-]/gu,"\\$&");return`- An earlier compatibility review remains pending: ${escapedMessage}`}function compatibilityReviewDetailsMarkdown(pause){const resolution2=pause.resumable?"After all devices have been updated, return to the compatibility review summary and explicitly resume synchronisation. The current internal version will only then be recorded as acknowledged.":"Install a compatible current version of Self-hosted LiveSync. This pause cannot be dismissed by the current installation.";return`## Why synchronisation is paused\n\n${pause.reasons.map(reasonMarkdown).join("\n")}\n\n## What the pause changes\n\n- Remote replication is blocked before work begins.\n- Your saved automatic synchronisation preferences remain unchanged.\n- Closing either dialogue leaves the safety gate active.\n\n## What to do next\n\n${resolution2}`}function createObsidianCompatibilityReviewUi(confirm){return new ObsidianCompatibilityReviewUi(confirm)}function createFileReflectionProvenance(keyValueDB){return new StoredFileReflectionProvenance(keyValueDB.openSimpleStore(FILE_REFLECTION_PROVENANCE_STORE))}var HttpAuthLocation,HttpApiKeyAuthLocation,EndpointURLScheme,AlgorithmId,FieldPosition,SMITHY_CONTEXT_KEY,IniSectionType,RequestHandlerProtocol,getSmithyContext,HttpRequest2,HttpResponse2,VALID_HOST_LABEL_REGEX,isValidHostLabel,normalizeProvider,parseUrl,toEndpointV1,chars,alphabetByEncoding,alphabetByValue,bitsPerLetter,bitsPerByte,maxLetterValue,fromBase64,fromUtf8,toUtf8,decimalToHex,expectNumber,MAX_FLOAT,expectFloat32,expectLong,expectInt32,expectShort,expectByte,expectSizedInt,castInt,expectObject,strictParseDouble,strictParseFloat32,NUMBER_REGEX,parseNumber,limitedParseDouble,parseFloatString,strictParseLong,strictParseShort,strictParseByte,stackTraceWarning,logger,DAYS,MONTHS,RFC3339,RFC3339_WITH_OFFSET,IMF_FIXDATE,RFC_850_DATE,ASC_TIME,parseRfc7231DateTime,buildDate,parseTwoDigitYear,adjustRfc850Year,parseMonthByShortName,DAYS_IN_MONTH,validateDayOfMonth,isLeapYear,parseDateValue,parseMilliseconds,parseOffsetToMilliseconds,stripLeadingZeroes,LazyJsonString,ddd,mmm,time,RFC3339_WITH_OFFSET2,IMF_FIXDATE2,RFC_850_DATE2,ASC_TIME2,months,_parseEpochTimestamp,_parseRfc3339DateTimeWithOffset,_parseRfc7231DateTime,splitHeader,format,NumericValue,SHORT_TO_HEX,HEX_TO_SHORT,TEXT_ENCODER,toUint8Array,isArrayBuffer,getEndpointFromConfig,resolveParamsForS3,DOMAIN_PATTERN,IP_ADDRESS_PATTERN,DOTS_PATTERN,isDnsCompatibleBucketName,isArnBucketName,createConfigValueProvider,resolveParams,serializerMiddlewareOption,endpointMiddlewareOptions,IP_V4_REGEX,isReadableStream,streamCollector,sdkStreamMixin,isBlobInstance,no,Uint8ArrayBlobAdapter,_getRandomValues,v4,generateIdempotencyToken,extendStatics,__assign,__createBinding,__setModuleDefault,ownKeys,_SuppressedError,fromUtf82,fromUtf83,AwsCrc32,Crc32,a_lookUpTable,lookupTable,Int64,HeaderMarshaller,HEADER_VALUE_TYPE,BOOLEAN_TAG,BYTE_TAG,SHORT_TAG,INT_TAG,LONG_TAG,BINARY_TAG,STRING_TAG,TIMESTAMP_TAG,UUID_TAG,UUID_PATTERN,PRELUDE_MEMBER_LENGTH,PRELUDE_LENGTH,CHECKSUM_LENGTH,MINIMUM_MESSAGE_LENGTH,EventStreamCodec,MessageDecoderStream,MessageEncoderStream,SmithyMessageDecoderStream,SmithyMessageEncoderStream,EventStreamMarshaller,eventStreamSerdeProvider,readableStreamToIterable,iterableToReadableStream,EventStreamMarshaller2,isReadableStream2,eventStreamSerdeProvider2,resolveEventStreamSerdeConfig,EventStreamSerde,init_index_browser3,require_spark_md5,require_vuvuzela,require_pouchdb_wrappers,require_transform_pouch,require_qrcode,main_exports,logger_exports,LOG_LEVEL_DEBUG,LOG_LEVEL_VERBOSE,LOG_LEVEL_INFO,LOG_LEVEL_NOTICE,LOG_LEVEL_URGENT,LOG_KIND_INFO,LOG_KIND_DEBUG,LOG_KIND_VERBOSE,LOG_KIND_WARNING,LOG_KIND_ERROR,LEVEL_DEBUG,LEVEL_INFO,LEVEL_NOTICE,LEVEL_URGENT,LEVEL_VERBOSE,defaultLoggerEnv,defaultLogger,_logger,RESULT_TIMED_OUT,VERSIONING_DOCID,MILESTONE_DOCID,NODEINFO_DOCID,SYNCINFO_ID,EntryTypes_NOTE_LEGACY,EntryTypes_NOTE_BINARY,EntryTypes_NOTE_PLAIN,EntryTypes_CHUNK,EntryTypes_CHUNK_PACK,EntryTypes_SYNC_PARAMETERS,CANCELLED,AUTO_MERGED,NOT_CONFLICTED,MISSING_OR_ERROR,LEAVE_TO_SUBSEQUENT,BASE_IS_NEW,TARGET_IS_NEW,EVEN,MAX_DOC_SIZE_BIN,VER,REPLICATION_BUSY_TIMEOUT,SALT_OF_PASSPHRASE,SALT_OF_ID,SEED_MURMURHASH,IDPrefixes_Chunk,PREFIX_OBFUSCATED,PREFIX_ENCRYPTED_CHUNK,AutoAccepting,SETTING_VERSION_INITIAL,SETTING_VERSION_SUPPORT_CASE_INSENSITIVE,CURRENT_SETTING_VERSION,RemoteTypes_REMOTE_COUCHDB,RemoteTypes_REMOTE_MINIO,RemoteTypes_REMOTE_P2P,REMOTE_COUCHDB,REMOTE_MINIO,REMOTE_P2P,P2PConnectionPaths_Automatic,P2PConnectionPaths_Relay,P2PMessageSizePresets_Standard,P2PMessageSizePresets_Reduced,P2PMessageSizePresets_Conservative,P2PMessageSizePresets_MaximumCompatibility,E2EEAlgorithmNames,E2EEAlgorithms,HashAlgorithms_XXHASH64,HashAlgorithms_MIXED_PUREJS,HashAlgorithms_SHA1,HashAlgorithms_LEGACY,ChunkAlgorithmNames,ChunkAlgorithms_V1,ChunkAlgorithms_V2,ChunkAlgorithms_V2Segmenter,ChunkAlgorithms_RabinKarp,MODE_SELECTIVE,MODE_AUTOMATIC,MODE_PAUSED,MODE_SHINY,NetworkWarningStyles_BANNER,NetworkWarningStyles_ICON,NetworkWarningStyles_HIDDEN,PREFERRED_BASE,PREFERRED_SETTING_CLOUDANT,PREFERRED_SETTING_SELF_HOSTED,PREFERRED_JOURNAL_SYNC,P2P_DEFAULT_SETTINGS,SETTINGS_SCHEMA_DEFAULTS,NEW_VAULT_SETTINGS,DEFAULT_SETTINGS,SettingsMigrationReviewCodes_LegacyUpdatePending,SettingsMigrationReviewCodes_FutureSchema,SETTINGS_MIGRATIONS,KeyIndexOfSettings,SETTING_KEY_P2P_DEVICE_NAME,configURIBase,configURIBaseQR,SuffixDatabaseName,ExtraSuffixIndexedDB,LEVEL_ADVANCED,LEVEL_POWER_USER,LEVEL_EDGE_CASE,configurationNames,ProtocolVersions_ADVANCED_E2EE,DOCID_SYNC_PARAMETERS,DOCID_JOURNAL_SYNC_PARAMETERS,DEFAULT_SYNC_PARAMETERS,TweakValuesShouldMatchedTemplate,IncompatibleChanges,CompatibleButLossyChanges,IncompatibleChangesInSpecificPattern,TweakValuesRecommendedTemplate,TweakValuesDefault,TweakValuesTemplate,DEVICE_ID_PREFERRED,RemotePreferredTweakStatuses_AVAILABLE,RemotePreferredTweakStatuses_NOT_CONFIGURED,RemotePreferredTweakStatuses_UNAVAILABLE,RemotePreferredTweakStatuses_UNSUPPORTED,RemotePreferredTweakNotConfiguredReasons_MILESTONE_MISSING,RemotePreferredTweakNotConfiguredReasons_PREFERRED_VALUES_MISSING,PREFIXMD_LOGFILE,PREFIXMD_LOGFILE_UC,FlagFilesOriginal_SUSPEND_ALL,FlagFilesOriginal_REBUILD_ALL,FlagFilesOriginal_FETCH_ALL,FlagFilesHumanReadable_REBUILD_ALL,FlagFilesHumanReadable_FETCH_ALL,FLAGMD_REDFLAG,FLAGMD_REDFLAG2,FLAGMD_REDFLAG2_HR,FLAGMD_REDFLAG3,FLAGMD_REDFLAG3_HR,DatabaseConnectingStatuses,DEFAULT_REPLICATION_STATICS,import_obsidian,import_obsidian2,import_diff_match_patch,normalizePath,_a,_getLanguage,compatGlobal,_fetch,activeDocumentWindow,_activeDocument,_a2,FallbackWeakRef,prefixMapObject,decodePrefixMapObject,prefixMapNumber,decodePrefixMapNumber,ARRAY_MARKER,OBJECT_MARKER,decodeMapConstant,SYMBOL_A,SYMBOL_B,context,topologicalSortCache,_reactiveSourceId,delay,UNRESOLVED,polyfilledFunc,promiseWithResolvers,noop,currentYieldingAnimationFrame,TIMED_OUT_SIGNAL,serializedMap,queueCount,waitingProcessMap,shareSerializedMap,skipDuplicatedMap,GENERIC_COMPATIBILITY_VALUE,GENERIC_COMPATIBILITY_SIGNAL,SlipBoard,globalSlipBoard,tasks,intervals,waitingItems,LRUCache,balanced,maybeMatch,range,escSlash,escOpen,escClose,escComma,escPeriod,escSlashPattern,escOpenPattern,escClosePattern,escCommaPattern,escPeriodPattern,slashPattern,openPattern,closePattern,commaPattern,periodPattern,EXPANSION_MAX,EXPANSION_MAX_LENGTH,MAX_PATTERN_LENGTH,assertValidPattern,posixClasses,braceEscape,regexpEscape,rangesToString,parseClass,unescape2,_root,_hasMagic,_uflag,_parts,_parent,_parentIndex,_negs,_filledNegs,_options,_toString,_emptyExt,_AST_instances,fillNegs_fn,_AST_static,parseAST_fn,canAdoptWithSpace_fn,canAdopt_fn,canAdoptType_fn,adoptWithSpace_fn,adopt_fn,canUsurpType_fn,canUsurp_fn,usurp_fn,flatten_fn,partsToRegExp_fn,parseGlob_fn,_a3,types,isExtglobType,isExtglobAST,adoptionMap,adoptionWithSpaceMap,adoptionAnyMap,usurpMap,startNoTraversal,startNoDot,addPatternStart,justDots,reSpecials,regExpEscape,qmark,star,starNoEmpty,ID,AST,escape,_Minimatch_instances,matchGlobstar_fn,matchGlobStarBodySections_fn,matchOne_fn,minimatch,starDotExtRE,starDotExtTest,starDotExtTestDot,starDotExtTestNocase,starDotExtTestNocaseDot,starDotStarRE,starDotStarTest,starDotStarTestDot,dotStarRE,dotStarTest,starRE,starTest,starTestDot,qmarksRE,qmarksTestNocase,qmarksTestNocaseDot,qmarksTestDot,qmarksTest,qmarksTestNoExt,qmarksTestNoExtDot,defaultPlatform,path_win32,path_posix,sep,GLOBSTAR,qmark2,star2,twoStarDot,twoStarNoDot,filter,ext,defaults,braceExpand,makeRe,match,globMagic,regExpEscape2,Minimatch,webcrypto,isProposalArrayBufferBase64Available,base64ToArrayBuffer,encodeChunkSize,arrayBufferToBase64Single,arrayBufferToBase64,QUANTUM,te,td,base64ToString,regexpBase64,tryConvertBase64ToArrayBuffer,table,revTable,revMap,numMap,isProposalArrayBufferBase64Available2,hexStringToUint8Array,uint8ArrayToHexString,_hashString,matchOpts,matcherCache,isValidRemoteCouchDBURI,_requestToCouchDBFetch,throttle,LiveSyncError,MARK_OPERATOR,MARK_DELETED,MARK_ISARRAY,MARK_SWAPPED,_a4,_b,isIndexDBCmpExist,globalConcurrencyController,map,revMap2,previousValues,CustomRegExp,resolution,collectingChunks,pluginScanningCount,hiddenFilesProcessingCount,hiddenFilesEventCount,logMessages,EventHub,commonlibEnglishMessages,englishMessageTranslator,ServiceContext,ServiceBase,EVENT_LAYOUT_READY,EVENT_PLUGIN_UNLOADED,EVENT_SETTING_SAVED,EVENT_FILE_RENAMED,EVENT_FILE_SAVED,EVENT_DATABASE_REBUILT,EVENT_REQUEST_OPEN_SETUP_URI,EVENT_REQUEST_COPY_SETUP_URI,EVENT_REQUEST_SHOW_SETUP_QR,EVENT_REQUEST_RELOAD_SETTING_TAB,EVENT_REQUEST_OPEN_P2P_SETTINGS,EVENT_REQUEST_OPEN_P2P,EVENT_PLATFORM_UNLOADED,EVENT_ON_UNRESOLVED_ERROR,EVENT_REQUEST_CHECK_REMOTE_SIZE,EVENT_CONFLICT_CANCELLED,EVENT_PLUGIN_LOADED2,EVENT_PLUGIN_UNLOADED2,EVENT_FILE_SAVED2,EVENT_LEAF_ACTIVE_CHANGED2,EVENT_REQUEST_OPEN_SETTINGS,EVENT_REQUEST_OPEN_SETUP_URI2,EVENT_REQUEST_COPY_SETUP_URI2,EVENT_REQUEST_SHOW_SETUP_QR2,EVENT_REQUEST_RELOAD_SETTING_TAB2,EVENT_REQUEST_OPEN_PLUGIN_SYNC_DIALOG2,EVENT_REQUEST_RUN_DOCTOR,EVENT_REQUEST_RUN_FIX_INCOMPLETE,EVENT_ANALYSE_DB_USAGE,EVENT_REQUEST_PERFORM_GC_V3,eventHub,MARK_LOG_SEPARATOR,MARK_LOG_NETWORK_ERROR,AbstractModule,AbstractObsidianModule,PUBLIC_VERSION,_a5,_b2,_c,EACH_ITEM_REACTIVE,EACH_INDEX_REACTIVE,EACH_IS_CONTROLLED,EACH_IS_ANIMATED,EACH_ITEM_IMMUTABLE,PROPS_IS_IMMUTABLE,PROPS_IS_RUNES,PROPS_IS_UPDATED,PROPS_IS_BINDABLE,PROPS_IS_LAZY_INITIAL,TEMPLATE_FRAGMENT,TEMPLATE_USE_IMPORT_NODE,HYDRATION_START,HYDRATION_START_ELSE,HYDRATION_START_FAILED,HYDRATION_END,HYDRATION_ERROR,UNINITIALIZED,FILENAME,NAMESPACE_HTML,true_default,_a6,_b3,node_env,dev_fallback_default,is_array,index_of,includes,array_from,object_keys,define_property,get_descriptor,get_descriptors,object_prototype,array_prototype,get_prototype_of,is_extensible,noop2,_a7,DERIVED,EFFECT,RENDER_EFFECT,MANAGED_EFFECT,BLOCK_EFFECT,BRANCH_EFFECT,ROOT_EFFECT,BOUNDARY_EFFECT,CONNECTED,CLEAN,DIRTY,MAYBE_DIRTY,INERT,DESTROYED,REACTION_RAN,DESTROYING,EFFECT_TRANSPARENT,EAGER_EFFECT,HEAD_EFFECT,EFFECT_PRESERVED,USER_EFFECT,EFFECT_OFFSCREEN,WAS_MARKED,REACTION_IS_UPDATING,ASYNC,ERROR_VALUE,STATE_SYMBOL,LEGACY_PROPS,LOADING_ATTR_SYMBOL,PROXY_PATH_SYMBOL,ATTRIBUTES_CACHE,CLASS_CACHE,STYLE_CACHE,TEXT_CACHE,FORM_RESET_HANDLER,HMR_ANCHOR,STALE_REACTION,IS_XHTML,TEXT_NODE,COMMENT_NODE,bold,normal,hydrating,hydrate_node,async_mode_flag,legacy_mode_flag,tracing_mode_flag,tracing_expressions,component_context,dev_stack,dev_current_component_function,micro_tasks,adjustments,STATUS_MASK,subscriber_queue,legacy_is_updating_store,is_store_binding,IS_UNMOUNTED,_anchor,_hydrate_open,_props,_children,_effect,_main_effect,_pending_effect,_failed_effect,_offscreen_fragment,_local_pending_count,_pending_count,_pending_count_update_queued,_dirty_effects,_maybe_dirty_effects,_effect_pending,_effect_pending_subscriber,_Boundary_instances,hydrate_resolved_content_fn,hydrate_failed_content_fn,hydrate_pending_content_fn,render_fn,resolve_fn,run_fn,update_pending_count_fn,handle_error_fn,flags,Boundary,reactivity_loss_tracker,recent_async_deriveds,OBSOLETE,stack,_started,_prev,_next,_commit_callbacks,_discard_callbacks,_pending,_blocking_pending,_deferred,_roots,_new_effects,_dirty_effects2,_maybe_dirty_effects2,_skipped_branches,_unskipped_branches,_decrement_queued,_Batch_instances,is_deferred_fn,process_fn,traverse_fn,find_earlier_batch_fn,merge_fn,defer_effects_fn,commit_fn,unlink_fn,first_batch,last_batch,current_batch,previous_batch,batch_values,last_scheduled_effect,is_flushing_sync,is_processing,collected_effects,legacy_updates,flush_count,source_stacks,uid,_Batch,Batch,eager_block_effects,eager_effects,old_values,eager_effects_deferred,regex_is_valid_identifier,ARRAY_MUTATING_METHODS,$window,is_firefox,first_child_getter,next_sibling_getter,listening_to_form_reset,captured_signals,is_updating_effect,is_destroying_effect,active_reaction,untracking,active_effect,current_sources,new_deps,skipped_deps,untracked_writes,write_version,read_version,update_version,event_symbol,all_registered_events,root_event_handles,last_propagated_event,_a8,policy,DOM_BOOLEAN_ATTRIBUTES,PASSIVE_EVENTS,STATE_CREATION_RUNES,listeners,mounted_components,_batches,_onscreen,_offscreen,_outroing,_transition,_commit,_discard,BranchManager,all_styles,offscreen_anchor,now,whitespace,IS_CUSTOM_ELEMENT,IS_HTML,LINK_TAG,PROGRESS_TAG,setters_cache,pending2,_listeners,_observer,_options2,_ResizeObserverSingleton_instances,getObserver_fn,_ResizeObserverSingleton,ResizeObserverSingleton,rest_props_handler,spread_props_handler,_events,_instance,Svelte4Component,allMessages,liveSyncProvisionalEnglishMessages,obsidianLangMap,currentLang,missingTranslations,__onMissingTranslations,msgCache,translateLiveSyncMessage,root2,root_1,$$css,SvelteItemView,VIEW_TYPE_LOG,LogPaneView,secp256k1_CURVE,L,L2,lengths,err,isBytes,abytes,u8n,padh,bytesToHex,C__0,C__9,C_A,C_F,C_a,C_f,_ch,hexToBytes,subtle,concatBytes,randomBytes,big,arange,M,modN,invert,callHash,gh,gha,apoint,koblitz,FpIsValid,FpIsValidNot0,FnIsValidNot0,isEven,u8of,getPrefix,lift_x,_Point,Point,G,I,doubleScalarMulUns,bytesToNumBE,sliceBytesNumBE,B256,numTo32b,secretKeyToScalar,highS,getPublicKey,isValidSecretKey,isValidPublicKey,assertRecoveryBit,assertSigFormat,assertSigLength,Signature,bits2int,bits2int_modN,SIG_COMPACT,SIG_RECOVERED,SIG_DER,_sha,hashes,prepMsg,NULL,byte0,byte1,_maxDrbgIters,_drbgErr,hmacDrbg,hmacDrbgAsync,_sign,_verify,setDefaults,_recover,randomSecretKey,createKeygen,getTag,T_AUX,T_NONCE,T_CHALLENGE,taggedHash,taggedHashAsync,extpubSchnorr,bytesModN,challenge,challengeAsync,pubSchnorr,keygenSchnorr,prepSigSchnorr,extractK,createSigSchnorr,E_INVSIG,signSchnorr,signSchnorrAsync,callSyncAsyncFn,_verifSchnorr,verifySchnorr,verifySchnorrAsync,schnorr,W,scalarBits,pwindows,pwindowSize,precompute,Gpows,ctneg,wNAF,libName,alloc,charSet,genId,selfId,all,isBrowser,noOp,candidateType,resetTimer,mkErr,toErrorMessage,toError,encoder,decoder,encodeBytes,decodeBytes,toHex,topicPath,shuffle,getRelays,toJson,fromJson,strToNum,defaultRetryMs,maxRetryMs,socketRetryPeriods,reconnectionLockingPromise,resolver,pauseRelayReconnection,resumeRelayReconnection,makeSocket,createRelayManager,watchOnline,algo,strToSha1,pack,unpack,hashWith,sha1,genKey,deriveRoomNamespace,joinChar,ivJoinChar,encrypt,decrypt,offerTtl,offerLeaseTtlMs,poolSize,OfferPool,overlapRoomPasswordErr,createPasswordHandshake,toHandshakeErrorMessage,createHandshakeManager,iceTimeout,disconnectedCloseDelayMs,iceStateEvent,iceConnectionStateEvent,offerType,answerType,outOfRangePattern,rewriteMdnsCandidatesToLoopback,peer_default,defaultIceServers,TypedArray,typeByteLimit,typeIndex,nonceIndex,tagIndex,progressIndex,payloadIndex,chunkSize,oneByteMax,twoByteMax,buffLowEvent,channelCloseEvent,channelErrorEvent,backpressureWaitTimeoutMs,toByteArray,waitForBufferedAmountLow,createActionWireManager,requestHandlerBufferMs,makeActionError,throwIfAborted,getRequestMetadata,getResponseMetadata,withMetadata,createActionManager,toPendingMediaMeta,makeKeyGetter,createMediaIdentityCache,createMediaManager,unloadEvent,defaultHandshakeTimeoutMs,internalNs,beforeUnloadRoomCleanups,cleanupActiveRoomsOnBeforeUnload,registerBeforeUnloadCleanup,room_default,roomFrameVersion,roomPresenceFrameVersion,wrapRoomFrame,wrapRoomPresenceFrame,unwrapFrame,isPeerUnderlyingStale,getConnectedPeerHealth,SharedPeerManager,offerPostAnswerTtlMs,offerIdSize,disconnectedPeerGraceMs,answeringTtlMs,legacyCandidateKey,offerRelayPlaceholder,signalKeys,toPayload,getString,hasInvalidSignalField,publishCipheredSignalingMessage,makeState,hasTurnServer,getSdpExchangeConnectionError,reportSdpExchangeConnectionFailure,getState,updateStatus,clearAnswering,clearConnectedPeer,clearOfferRelay,clearOfferRelayIfPlaceholder,hasRemoteDescription,resetOfferState,scheduleAnsweringExpiry,flushBufferedCandidates,scheduleOfferExpiry,ensureOffer,handleAnnouncement,handleOffer,handleCandidate,handleAnswer,prunePendingOffer,createSignalHandler,announceIntervalMs,announceWarmupIntervalsMs,passiveActivationGraceMs,sharedPeerIdleMsDefault,strategy_default,signalKeys2,toPayload2,getString2,hasInvalidSignalField2,shouldActivatePassiveRoom,requireContext,subscriptionContext,publishContext,topic_strategy_default,relayManager,defaultRedundancy,tag2,eventMsgType,pubkey,subIdToTopic,msgHandlers,kindCache,maxTopicsPerSubscription,now2,topicToKind,createEvent,batchers,batchAdd,batchRemove,scheduleBatchFlush,flushBatch,resubscribeOnReconnect,joinRoom,getRelaySockets,defaultRelayUrls,DIRECTION_REQUEST,DIRECTION_RESPONSE,DEFAULT_RPC_TIMEOUT,BULK_GET_RPC_TIMEOUT,ResponsePreventedError,DeviceDecisions,StoredMapLike,DB_METHODS,TrysteroReplicatorP2PClient,Computed,encoder2,IncomingChunkBuffer,RpcError,RpcSession,RPC_VERSION_MAJOR,RPC_VERSION_MINOR,RpcRoom,import_events6,noopActiveTasks,PROXY_SCHEME,ConnectionStringParser,epochFNV1a,c1,c2,r1,r2,m,n,DiagRTCFailureReasonCodes_ICE_GATHERING_NOT_COMPLETED,DiagRTCFailureReasonCodes_ICE_CONNECTIVITY_FAILED,DiagRTCFailureReasonCodes_STUN_REQUEST_TIMEOUT,DiagRTCFailureReasonCodes_SIGNALING_NOT_STABLE,DiagRTCFailureReasonCodes_CONNECTION_DROPPED_AFTER_ESTABLISHED,DiagRTCFailureReasonCodes_NETWORK_INTERRUPTED,DiagRTCFailureReasonCodes_UNKNOWN,rtcInstanceCounter,totalNewConnections,totalFailedConnections,totalSuccessfulConnections,totalClosedConnections,RTCConnectionStatuses,connectionStatusSubscribers,failureDiagnosisSubscribers,subscribersByRoom,TRYSTERO_RPC_DEFAULTS,EVENT_SERVER_STATUS,EVENT_ADVERTISEMENT_RECEIVED,EVENT_DEVICE_LEAVED,EVENT_REQUEST_STATUS,EVENT_P2P_CONNECTED,EVENT_P2P_DISCONNECTED,EVENT_P2P_REPLICATOR_STATUS,EVENT_P2P_REPLICATOR_PROGRESS,TrysteroReplicatorP2PServer,P2PLogCollector,REMOTE_OPERATION_ACTIVITY_ICON,REMOTE_REQUEST_ACTIVITY_ICON,REMOTE_REQUEST_ACTIVITY_MINIMUM_VISIBLE_MS,STATUS_COUNTER_PADDING,STATUS_COUNTER_INACTIVE_LINGER_MS,CHeader,PSCHeader,ICHeader,ICHeaderEnd,ICHeaderLength,ICXHeader,PERIODIC_PLUGIN_SWEEP,YieldOperationNumbers,PersistentMap,sameChangePairs,BasicHeaderGenerator,JWTTokenGenerator,AuthorizationHeaderGenerator,_requestToCouchDB,manifestVersion,packageVersion,recentLogEntries,globalLogFunction,logForDump,logForDisplay,updateLogMessage,redactPatterns,showDebugLog,MARK_DONE,ModuleLog,noticeIndex,LiveSyncCommands,PeriodicProcessor,root3,root_12,root_2,root_3,root_4,root_5,root_6,$$css2,JsonResolveModal,PaceMaker,NOT_AVAILABLE,READY_PICK_SIGNAL,READY_POST_SIGNAL,DISPOSE_ERROR,SyncInbox,Inbox,EVENT_PROGRESS,ClerkState,SENTINEL_FINISHED,SENTINEL_FLUSH,ClerkBase,Clerk,ClerkGroup,allRunningProcessors,QueueProcessor,HIDDEN_FILE_NOTICE_GROUP,HIDDEN_FILE_NOTICE_DURATION_MS,HiddenFileSync,t,hashFunc,import_diff_match_patch2,POSTPONED,ConflictResolveModal,root4,root_13,root_22,root_32,root_42,root_52,root_62,root_7,root_8,root_9,root_10,$$css3,root5,root_14,root_23,root_33,root_43,root_53,root_63,root_72,root_82,root_92,root_102,root_11,root_122,root_132,$$css4,PluginDialogModal,d,d2,UPDATED_CONFIGURATION_NOTICE_KEY,DUMMY_HEAD,DUMMY_END,pluginList,pluginIsEnumerating,pluginV2Progress,pluginManifests,pluginManifestStore,PluginDataExDisplayV2,ConfigSync,ModuleInteractiveConflictResolver,ModuleObsidianEvents,checkRemoteVersion,bumpRemoteVersion,checkSyncInfo,SELECTOR_COMPROMISED_CHUNK_1,SELECTOR_COMPROMISED_CHUNK_2,webcrypto2,SALT_STR,SALT,previousPassphrase,encryptionKey,_nonceV3,bufV3,previousDecryptionPassphrase,decryptionKey,UNDEFINED,webcrypto3,IV_LENGTH,PBKDF2_ITERATIONS,HKDF_SALT_LENGTH,PBKDF2_SALT_LENGTH,gcmTagLength,HKDF_ENCRYPTED_PREFIX,HKDF_SALTED_ENCRYPTED_PREFIX,deriveMasterKey,_sessionPBKDFSalt,webcrypto4,ENCRYPT_V1_PREFIX_PROBABLY,ENCRYPT_V2_PREFIX,ENCRYPT_V3_PREFIX,KeyBuffs,decKeyBuffs,KEY_RECYCLE_COUNT,semiStaticFieldBuffer,nonceBuffer,webcrypto5,keyGCCount,decKeyIdx,decKeyMin,_a9,__defProp2,__getOwnPropDesc2,__getOwnPropNames2,__hasOwnProp2,__copyProps2,__reExport,workerSource,EVENT_PLATFORM_UNLOADED2,logger_exports2,SYMBOL_USED,SYMBOL_END_OF_DATA,workerStreams,writers,responseBuf,writerPromise,compatGlobal2,activeDocumentWindow2,tasks2,taskWorkerMap,workers,offPlatformUnloaded,key2,roundRobinIdx,encrypt4,decrypt4,encryptHKDF,decryptHKDF,Encrypt_HKDF_Header,Encrypt_OLD_Header,EncryptionVersions_UNENCRYPTED,EncryptionVersions_ENCRYPTED,EncryptionVersions_HKDF,EncryptionVersions_UNKNOWN,ENCRYPTED_META_PREFIX,MESSAGE_FALLBACK_DECRYPT_FAILED,ENCRYPTION_HKDF_FAILED,DECRYPTION_HKDF_FAILED,DECRYPTION_FALLBACK_FAILED,preprocessOutgoing,enableEncryption,EDEN_ENCRYPTED_KEY,EDEN_ENCRYPTED_KEY_HKDF,LiveSyncAbstractReplicator,PREFIX_TRENCH,PREFIX_EPHEMERAL,PREFIX_PERMANENT,idx,series,indexes,inProgress,failed,Trench,StreamInbox,_handlers,SyncParamsHandlerError,SyncParamsFetchError,SyncParamsNotFoundError,SyncParamsUpdateError,currentVersionRange,selectorOnDemandPull,DEFAULT_ONE_SHOT_CONNECTIVITY_TIMEOUT_MS,OneShotConnectivityPreflightTimeoutError,LiveSyncCouchDBReplicator,_a10,OnDialogSettingsDefault,SettingInformation,setLevelClass,SETTING_WITH_ADDITIONAL_ACTIONS_CLASS,ADDITIONAL_ACTION_CLASS,LiveSyncSetting,ch2,wk,u8,u16,i32,fleb,fdeb,clim,freb,_a11,fl,revfl,_b5,fd,revfd,rev,hMap,flt,fdt,flm,flrm,fdm,fdrm,max,bits,bits16,shft,slc,ec,err2,inflt,wbits,wbits16,hTree,ln,lc,clen,wfblk,wblk,deo,et,dflt,crct,crc,adler,dopt,mrg,wcln,ch,cbfs,wrkr,bInflt,bDflt,gze,guze,zle,zule,pbf,gopt,cbify,astrm,astrmify,b2,b4,b8,wbytes,gzh,gzs,gzl,gzhl,zlh,zls,Deflate,AsyncDeflate,Inflate,AsyncInflate,Gzip,Gunzip,AsyncGunzip,Zlib,Unzlib,AsyncUnzlib,Decompress,fltn,te3,td2,tds,dutf8,dbf,z64e,exfl,wzh,wzf,ZipPassThrough,UnzipPassThrough,x,i,wrappedInflate,wrappedDeflate,replicationFilter,MARK_SHIFT,MARK_SHIFT_COMPRESSED,CheckPointInfoDefault,JournalStorageReadStatuses_AVAILABLE,JournalStorageReadStatuses_NOT_FOUND,JournalStorageReadStatuses_UNAVAILABLE,DatabaseReadLayer,CacheLayer,DEFAULT_CHUNK_DELIVERY_STALL_TIMEOUT_MS,ChunkDeliveryCoordinator,ArrivalWaitLayer,DatabaseWriteLayer,LayeredChunkManager,EVENT_MISSING_CHUNKS,EVENT_MISSING_CHUNK_REMOTE,EVENT_CHUNK_FETCHED,BATCH_SIZE,ChunkFetcher,MAX_CHUNKS_SIZE_ON_UI,ContentSplitterCore,ContentSplitterBase,charNewLine,segmenter,MAX_ITEMS,ContentSplitterRabinKarp,ContentSplitterV1,ContentSplitterV2,ContentSplitters,ContentSplitter,ChangeManager,import_diff_match_patch3,ConflictManager,EntryManager,HashEncryptedPrefix,HashManagerCore,XXHashHashManager,XXHash32RawHashManager,XXHash64HashManager,FallbackWasmHashManager,PureJSHashManager,SHA1HashManager,FallbackPureJSHashManager,HashManagers,HashManager,LiveSyncManagers,REMOTE_CHUNK_FETCHED,LiveSyncLocalDB,RECORD_SPLIT,UNIT_SPLIT,te4,JournalSyncCore,getHttpHandlerExtensionConfiguration,resolveHttpHandlerRuntimeConfig,HttpRequest,HttpResponse,addExpectContinueMiddlewareOptions,getAddExpectContinuePlugin,RequestChecksumCalculation_WHEN_SUPPORTED,RequestChecksumCalculation_WHEN_REQUIRED,DEFAULT_REQUEST_CHECKSUM_CALCULATION,ResponseChecksumValidation_WHEN_SUPPORTED,ResponseChecksumValidation_WHEN_REQUIRED,DEFAULT_RESPONSE_CHECKSUM_VALIDATION,ChecksumAlgorithm,ChecksumLocation,DEFAULT_CHECKSUM_ALGORITHM,getDateHeader,getSkewCorrectedDate,isClockSkewed,getUpdatedSystemClockOffset,throwSigningPropertyError,validateSigningProperties,AwsSdkSigV4Signer,AwsSdkSigV4ASigner,resolveAuthOptions,httpAuthSchemeMiddleware,httpAuthSchemeEndpointRuleSetMiddlewareOptions,getHttpAuthSchemeEndpointRuleSetPlugin,collectBody,deref,operation,schemaDeserializationMiddleware,findHeader,schemaSerializationMiddleware,deserializerMiddlewareOption2,serializerMiddlewareOption3,traitsCache,anno_it,anno_ns,simpleSchemaCacheN,simpleSchemaCacheS,_NormalizedSchema,NormalizedSchema,isMemberSchema,isStaticSchema,_TypeRegistry,TypeRegistry,SerdeContext,HttpProtocol,HttpBindingProtocol,FromStringShapeDeserializer,HttpInterceptingShapeDeserializer,ToStringShapeSerializer,HttpInterceptingShapeSerializer,defaultErrorHandler,defaultSuccessHandler,httpSigningMiddleware,httpSigningMiddlewareOptions,getHttpSigningPlugin,normalizeProvider2,makePagedClientRequest,get3,DefaultIdentityProviderConfig,createIsIdentityExpiredFunction,EXPIRATION_MS,isIdentityExpired,doesIdentityRequireRefresh,memoizeIdentityProvider,ProviderError,memoize,resolveAwsSdkSigV4AConfig,SHORT_TO_HEX2,HEX_TO_SHORT2,ALGORITHM_QUERY_PARAM,CREDENTIAL_QUERY_PARAM,AMZ_DATE_QUERY_PARAM,SIGNED_HEADERS_QUERY_PARAM,EXPIRES_QUERY_PARAM,SIGNATURE_QUERY_PARAM,TOKEN_QUERY_PARAM,AUTH_HEADER,AMZ_DATE_HEADER,DATE_HEADER,GENERATED_HEADERS,SIGNATURE_HEADER,SHA256_HEADER,TOKEN_HEADER,ALWAYS_UNSIGNABLE_HEADERS,PROXY_HEADER_PATTERN,SEC_HEADER_PATTERN,ALGORITHM_IDENTIFIER,EVENT_ALGORITHM_IDENTIFIER,UNSIGNED_PAYLOAD,MAX_CACHE_SIZE,KEY_TYPE_IDENTIFIER,MAX_PRESIGNED_TTL,signingKeyCache,cacheQueue,createScope,getSigningKey,hmac,getCanonicalHeaders,getPayloadHash,HeaderFormatter,HEADER_VALUE_TYPE2,UUID_PATTERN2,Int642,hasHeader,moveHeadersToQuery,prepareRequest,getSmithyContext2,normalizeProvider3,escapeUri2,hexEncode,getCanonicalQuery,iso8601,toDate,SignatureV4Base,SignatureV4,signatureV4aContainer_SignatureV4a,resolveAwsSdkSigV4Config,getAllAliases,getMiddlewareNameWithAliases,constructStack,stepWeights,priorityWeights,Client,SENSITIVE_STRING,Command,ClassBuilder,createAggregatedClient,ServiceException,decorateServiceException,loadConfigsForDefaultMode,knownAlgorithms,getChecksumConfiguration2,resolveChecksumRuntimeConfig2,getRetryConfiguration,resolveRetryRuntimeConfig,getDefaultExtensionConfiguration,resolveDefaultRuntimeConfig,getValueFromTextNode,NoOpLogger,ProtocolLib,SerdeContextConfig,chars2,alphabetByEncoding2,alphabetByValue2,bitsPerLetter2,bitsPerByte2,maxLetterValue2,fromBase642,UnionSerde,collectBodyString,ATTR_ESCAPE_RE,ATTR_ESCAPE_MAP,ELEMENT_ESCAPE_RE,ELEMENT_ESCAPE_MAP,XmlText,XmlNode,parser,XmlShapeDeserializer,parseXmlBody,loadRestXmlErrorCode,XmlShapeSerializer,XmlCodec,AwsRestXmlProtocol,ReadableStreamRef,ChecksumStream2,isReadableStream3,createChecksumStream2,ByteArrayCollector,createBufferedReadable2,getAwsChunkedEncodingStream2,keepAliveSupport,FetchHttpHandler,streamCollector2,ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED2,sdkStreamMixin2,isBlobInstance2,getChecksumAlgorithmForRequest,getChecksumLocationName,hasHeader2,hasHeaderWithPrefix,isStreaming,AwsCrc32c,Crc32c,a_lookupTable,lookupTable2,generateCRC64NVMETable,CRC64_NVME_REVERSED_TABLE,t0,t1,t2,t3,t4,t5,t6,t7,ensureTablesInitialized,Crc64Nvme,crc64NvmeCrtContainer_CrtCrc64Nvme,getCrc32ChecksumAlgorithmFunction,CLIENT_SUPPORTED_ALGORITHMS,PRIORITY_ORDER_ALGORITHMS,selectChecksumAlgorithmFunction,stringHasher,flexibleChecksumsMiddlewareOptions,flexibleChecksumsMiddleware,flexibleChecksumsInputMiddlewareOptions,flexibleChecksumsInputMiddleware,getChecksumAlgorithmListForResponse,isChecksumWithPartNumber,getChecksum,validateChecksumFromResponse,flexibleChecksumsResponseMiddlewareOptions,flexibleChecksumsResponseMiddleware,getFlexibleChecksumsPlugin,resolveFlexibleChecksumsConfig,hostHeaderMiddleware,hostHeaderMiddlewareOptions,getHostHeaderPlugin,loggerMiddleware,loggerMiddlewareOptions,getLoggerPlugin,recursionDetectionMiddlewareOptions,recursionDetectionMiddleware,getRecursionDetectionPlugin,CONTENT_LENGTH_HEADER,DECODED_CONTENT_LENGTH_HEADER,checkContentLengthHeaderMiddlewareOptions,getCheckContentLengthHeaderPlugin,regionRedirectEndpointMiddleware,regionRedirectEndpointMiddlewareOptions,regionRedirectMiddlewareOptions,getRegionRedirectMiddlewarePlugin,s3ExpiresMiddleware,s3ExpiresMiddlewareOptions,getS3ExpiresMiddlewarePlugin,_S3ExpressIdentityCache,S3ExpressIdentityCache,S3ExpressIdentityCacheEntry,_S3ExpressIdentityProviderImpl,S3ExpressIdentityProviderImpl,booleanSelector,SelectorType,S3_EXPRESS_BUCKET_TYPE,S3_EXPRESS_BACKEND,S3_EXPRESS_AUTH_SCHEME,SESSION_TOKEN_QUERY_PARAM,SESSION_TOKEN_HEADER,NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_ENV_NAME,NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_INI_NAME,SignatureV4S3Express,s3ExpressMiddleware,s3ExpressMiddlewareOptions,getS3ExpressPlugin,signS3Express,defaultErrorHandler2,defaultSuccessHandler2,s3ExpressHttpSigningMiddleware,getS3ExpressHttpSigningPlugin,resolveS3Config,THROW_IF_EMPTY_BODY,MAX_BYTES_TO_INSPECT,throw200ExceptionsMiddleware,collectBody2,throw200ExceptionsMiddlewareOptions,getThrow200ExceptionsPlugin,validate,bucketEndpointMiddlewareOptions,validateBucketNameMiddlewareOptions,getValidateBucketNamePlugin,S3RestXmlProtocol,DEFAULT_UA_APP_ID,EndpointCache2,IP_V4_REGEX2,isIpAddress2,VALID_HOST_LABEL_REGEX2,isValidHostLabel2,customEndpointFunctions2,debugId,EndpointError,booleanEquals,getAttrPathList,getAttr,isSet,not,DEFAULT_PORTS,parseURL,stringEquals,substring,uriEncode,endpointFunctions,evaluateTemplate,getReferenceValue,evaluateExpression,callFunction,group,evaluateCondition,evaluateConditions,getEndpointHeaders,getEndpointProperties,getEndpointProperty,group2,getEndpointUrl,evaluateEndpointRule,evaluateErrorRule,evaluateRules,evaluateTreeRule,group3,resolveEndpoint2,isVirtualHostableS3Bucket,ARN_DELIMITER,RESOURCE_DELIMITER,parseArn,partitions_default,selectedPartitionsInfo,selectedUserAgentPrefix,partition,setPartitionInfo,getUserAgentPrefix,awsEndpointFunctions,parseUrl2,isStreamingPayload,NoOpLogger2,CLOCK_SKEW_ERROR_CODES,THROTTLING_ERROR_CODES,TRANSIENT_ERROR_CODES,TRANSIENT_ERROR_STATUS_CODES,NODEJS_TIMEOUT_ERROR_CODES,NODEJS_NETWORK_ERROR_CODES,isRetryableByTrait,isClockSkewCorrectedError,isBrowserNetworkError,isThrottlingError,isTransientError,isServerError,MAXIMUM_RETRY_DELAY,INITIAL_RETRY_TOKENS,NO_RETRY_INCREMENT,INVOCATION_ID_HEADER,REQUEST_HEADER,asSdkError,cooldown,isRetryStrategyV2,getRetryErrorInfo,getRetryErrorType,retryMiddlewareOptions,_DefaultRateLimiter,DefaultRateLimiter,_a12,_Retry,Retry,DefaultRetryBackoffStrategy,DefaultRetryToken,RETRY_MODES,DEFAULT_MAX_ATTEMPTS,DEFAULT_RETRY_MODE,refusal_incompatible,refusal_attempts,refusal_capacity,StandardRetryStrategy,AdaptiveRetryStrategy,ConfiguredRetryStrategy,no2,ACCOUNT_ID_ENDPOINT_REGEX,USER_AGENT,X_AMZ_USER_AGENT,SPACE,UA_NAME_SEPARATOR,UA_NAME_ESCAPE_REGEX,UA_VALUE_ESCAPE_REGEX,UA_ESCAPE_CHAR,BYTE_LIMIT,userAgentMiddleware,escapeUserAgent,getUserAgentMiddlewareOptions,getUserAgentPlugin,ENV_USE_DUALSTACK_ENDPOINT,CONFIG_USE_DUALSTACK_ENDPOINT,DEFAULT_USE_DUALSTACK_ENDPOINT,ENV_USE_FIPS_ENDPOINT,CONFIG_USE_FIPS_ENDPOINT,DEFAULT_USE_FIPS_ENDPOINT,validRegions,checkRegion,isFipsRegion,getRealRegion,resolveRegionConfig,resolveEventStreamSerdeConfig2,CONTENT_LENGTH_HEADER2,contentLengthMiddlewareOptions2,getContentLengthPlugin2,resolveParamsForS32,DOMAIN_PATTERN2,IP_ADDRESS_PATTERN2,DOTS_PATTERN2,isDnsCompatibleBucketName2,isArnBucketName2,createConfigValueProvider2,getEndpointFromConfig2,toEndpointV12,getEndpointFromInstructions2,resolveParams2,endpointMiddleware2,findHeader2,serializerMiddlewareOption4,endpointMiddlewareOptions2,getEndpointPlugin2,resolveEndpointConfig2,CLOCK_SKEW_ERROR_CODES2,THROTTLING_ERROR_CODES2,TRANSIENT_ERROR_CODES2,TRANSIENT_ERROR_STATUS_CODES2,NODEJS_TIMEOUT_ERROR_CODES2,NODEJS_NETWORK_ERROR_CODES2,isRetryableByTrait2,isClockSkewCorrectedError2,isBrowserNetworkError2,isThrottlingError2,isTransientError2,isServerError2,randomUUID,decimalToHex2,v42,asSdkError2,ENV_MAX_ATTEMPTS2,CONFIG_MAX_ATTEMPTS2,resolveRetryConfig2,ENV_RETRY_MODE2,CONFIG_RETRY_MODE2,isStreamingPayload2,retryMiddleware2,isRetryStrategyV22,getRetryErrorInfo2,getRetryErrorType2,retryMiddlewareOptions2,getRetryPlugin2,getRetryAfterHint2,signatureV4CrtContainer_CrtSignerV4,SignatureV4MultiRegion,cs,ct,cu,cv,cw,cx,cy,cz,cA,cB,cC,cD,cE,cF,cG,cH,cI,a,b,c,d3,e2,f,g,h,i2,j,k,l,m2,n2,o,p,q,r3,s,t8,u,v,w,x2,y,z,A,B,C2,D,E,F,G2,H,I2,J,K,L3,M2,N2,O,P2,Q,R,S,T,U,V,W2,X,Y,Z,aa,ab,ac,ad,ae,af,ag,ah,ai,aj,ak,al,am,an,ao,ap,aq,ar,as,at,au,av,aw,ax,ay,az,aA,aB,aC,aD,aE,aF,aG,aH,aI,aJ,aK,aL,aM,aN,aO,aP,aQ,aR,aS,aT,aU,aV,aW,aX,aY,aZ,ba,bb,bc,bd,be,bf,bg,bh,bi,bj,bk,bl,bm,bn,bo,bp,bq,br,bs,bt,bu,bv,bw,bx,by,bz,bA,bB,bC,bD,bE,bF,bG,bH,bI,bJ,bK,bL,bM,bN,bO,bP,bQ,bR,bS,bT,bU,bV,bW,bX,bY,bZ,ca,cb,cc,cd,ce,cf,cg,ch3,ci,cj,ck,cl,cm,cn,co,cp,cq,cr,_data,ruleSet,cache,defaultEndpointResolver,createEndpointRuleSetHttpAuthSchemeParametersProvider,_defaultS3HttpAuthSchemeParametersProvider,defaultS3HttpAuthSchemeParametersProvider,createEndpointRuleSetHttpAuthSchemeProvider,_defaultS3HttpAuthSchemeProvider,defaultS3HttpAuthSchemeProvider,resolveHttpAuthSchemeConfig,resolveClientEndpointParameters,commonParams,S3ServiceException,NoSuchUpload,AccessDenied,ObjectNotInActiveTierError,BucketAlreadyExists,BucketAlreadyOwnedByYou,NoSuchBucket,InvalidObjectState,NoSuchKey,NotFound,EncryptionTypeMismatch,InvalidRequest,InvalidWriteOffset,TooManyParts,IdempotencyParameterMismatch,ObjectAlreadyInActiveTierError,_A,_AAO,_AC,_ACL,_ACL_,_ACLn,_ACP,_ACT,_ACn,_AD,_ADb,_AED,_AF,_AH,_AHl,_AI,_AIMU,_AKI,_AM,_AMU,_AMUO,_AMUR,_AMl,_AO,_AOl,_APA,_APAc,_AQRD,_AR,_ARI,_AS,_ASBD,_ASSEBD,_ASr,_AT,_An,_B,_BA,_BAE,_BAI,_BAOBY,_BET,_BGR,_BI,_BKE,_BLC,_BLN,_BLS,_BLT,_BN,_BNu,_BP,_BPA,_BPP,_BR,_BRy,_BS,_Bo,_Bu,_C,_CA,_CACL,_CB,_CBC,_CBMC,_CBMCR,_CBMTC,_CBMTCR,_CBO,_CBR,_CC,_CCRC,_CCRCC,_CCRCNVME,_CC_,_CD,_CD_,_CDo,_CE,_CE_,_CEo,_CF,_CFC,_CL,_CL_,_CL__,_CLo,_CM,_CMD,_CMU,_CMUO,_CMUOr,_CMUR,_CMURo,_CMURr,_CMUo,_CMUr,_CMh,_CO,_COO,_COR,_CORSC,_CORSR,_CORSRu,_CORo,_CP,_CPL,_CPLo,_CPR,_CPo,_CPom,_CR,_CRSBA,_CR_,_CS,_CSHA,_CSHAh,_CSIM,_CSIMS,_CSINM,_CSIUS,_CSO,_CSR,_CSRo,_CSRr,_CSSSECA,_CSSSECK,_CSSSECKMD,_CSV,_CSVI,_CSVIn,_CSVO,_CSo,_CSr,_CT,_CT_,_CTl,_CTo,_CTom,_CTon,_Co,_Cod,_Com,_Con,_Cont,_Cr,_D,_DAI,_DB,_DBAC,_DBACR,_DBC,_DBCR,_DBE,_DBER,_DBIC,_DBICR,_DBITC,_DBITCR,_DBL,_DBLR,_DBMC,_DBMCR,_DBMCRe,_DBMCe,_DBMTC,_DBMTCR,_DBOC,_DBOCR,_DBP,_DBPR,_DBR,_DBRR,_DBRe,_DBT,_DBTR,_DBW,_DBWR,_DE,_DIM,_DIMS,_DINM,_DIUS,_DM,_DME,_DMR,_DMVI,_DMe,_DN,_DO,_DOO,_DOOe,_DOR,_DORe,_DOT,_DOTO,_DOTR,_DOe,_DOel,_DOele,_DPAB,_DPABR,_DR,_DRe,_DRel,_DRes,_Da,_De,_Del,_Deli,_Des,_Desc,_Det,_E,_EA,_EBC,_EBO,_EC,_ECr,_ED,_EDr,_EE,_EH,_EHx,_EM,_EODM,_EOR,_ES,_ESBO,_ET,_ETL,_ETM,_ETa,_ETn,_ETv,_ETx,_En,_Ena,_End,_Er,_Err,_Ev,_Eve,_Ex,_Exp,_F,_FD,_FHI,_FO,_FR,_FRL,_FRi,_Fi,_Fo,_Fr,_G,_GBA,_GBAC,_GBACO,_GBACOe,_GBACR,_GBACRe,_GBACe,_GBAO,_GBAOe,_GBAR,_GBARe,_GBAe,_GBC,_GBCO,_GBCR,_GBE,_GBEO,_GBER,_GBIC,_GBICO,_GBICR,_GBITC,_GBITCO,_GBITCR,_GBL,_GBLC,_GBLCO,_GBLCR,_GBLO,_GBLOe,_GBLR,_GBLRe,_GBLe,_GBMC,_GBMCO,_GBMCOe,_GBMCR,_GBMCRe,_GBMCRet,_GBMCe,_GBMTC,_GBMTCO,_GBMTCR,_GBMTCRe,_GBNC,_GBNCR,_GBOC,_GBOCO,_GBOCR,_GBP,_GBPO,_GBPR,_GBPS,_GBPSO,_GBPSR,_GBR,_GBRO,_GBRP,_GBRPO,_GBRPR,_GBRR,_GBT,_GBTO,_GBTR,_GBV,_GBVO,_GBVR,_GBW,_GBWO,_GBWR,_GFC,_GJP,_GO,_GOA,_GOAO,_GOAOe,_GOAP,_GOAR,_GOARe,_GOARet,_GOAe,_GOLC,_GOLCO,_GOLCR,_GOLH,_GOLHO,_GOLHR,_GOO,_GOR,_GORO,_GORR,_GORe,_GOT,_GOTO,_GOTOe,_GOTR,_GOTRe,_GOTe,_GPAB,_GPABO,_GPABR,_GR,_GRACP,_GW,_GWACP,_Gr,_Gra,_HB,_HBO,_HBR,_HECRE,_HN,_HO,_HOO,_HOR,_HRC,_I,_IC,_ICL,_ID,_IDn,_IDnv,_IE,_IEn,_IF,_IL,_IM,_IMIT,_IMLMT,_IMS,_IMS_,_IMSf,_IMUR,_IM_,_INM,_INM_,_IOF,_IOS,_IOV,_IP,_IPA,_IPM,_IR,_IRIP,_IS,_ISBD,_ISn,_IT,_ITAO,_ITC,_ITCL,_ITCR,_ITCU,_ITCn,_ITF,_IUS,_IUS_,_IWO,_In,_Ini,_JSON,_JSONI,_JSONO,_JTC,_JTCR,_JTCU,_K,_KC,_KI,_KKA,_KM,_KMSC,_KMSKA,_KMSKI,_KMSMKID,_KPE,_L,_LAMBR,_LAMDBR,_LB,_LBAC,_LBACO,_LBACR,_LBACRi,_LBIC,_LBICO,_LBICR,_LBITC,_LBITCO,_LBITCR,_LBMC,_LBMCO,_LBMCR,_LBO,_LBR,_LBRi,_LC,_LCi,_LDB,_LDBO,_LDBR,_LE,_LEi,_LFA,_LFC,_LFCL,_LFCa,_LH,_LI,_LICR,_LM,_LMCR,_LMT,_LMU,_LMUO,_LMUR,_LMURi,_LM_,_LO,_LOO,_LOR,_LOV,_LOVO,_LOVOi,_LOVR,_LOVRi,_LOVi,_LP,_LPO,_LPR,_LPRi,_LR,_LRAO,_LRF,_LRi,_LVR,_M,_MAO,_MAS,_MB,_MC,_MCL,_MCR,_MCe,_MD,_MDB,_MDf,_ME,_MF,_MFA,_MFAD,_MK,_MM,_MOS,_MP,_MTC,_MTCR,_MTEC,_MU,_MUL,_MUa,_Ma,_Me,_Mes,_Mi,_Mo,_N,_NC,_NCF,_NCT,_ND,_NEKKAS,_NF,_NKM,_NM,_NNV,_NPNM,_NSB,_NSK,_NSU,_NUIM,_NVE,_NVIM,_NVT,_NVTL,_NVTo,_O,_OA,_OAIATE,_OC,_OCR,_OCRw,_OE,_OF,_OI,_OIL,_OL,_OLC,_OLE,_OLEFB,_OLLH,_OLLHS,_OLM,_OLR,_OLRUD,_OLRb,_OLb,_ONIATE,_OO,_OOA,_OP,_OPb,_OS,_OSGT,_OSLT,_OSV,_OSu,_OV,_OVL,_Ob,_Obj,_P,_PABC,_PBA,_PBAC,_PBACR,_PBACRu,_PBACu,_PBAR,_PBARu,_PBAu,_PBC,_PBCR,_PBE,_PBER,_PBIC,_PBICR,_PBITC,_PBITCR,_PBL,_PBLC,_PBLCO,_PBLCR,_PBLR,_PBMC,_PBMCR,_PBNC,_PBNCR,_PBOC,_PBOCR,_PBP,_PBPR,_PBR,_PBRP,_PBRPR,_PBRR,_PBT,_PBTR,_PBV,_PBVR,_PBW,_PBWR,_PC,_PDS,_PE,_PI,_PL,_PN,_PNM,_PO,_POA,_POAO,_POAR,_POLC,_POLCO,_POLCR,_POLH,_POLHO,_POLHR,_POO,_POR,_PORO,_PORR,_PORu,_POT,_POTO,_POTR,_PP,_PPAB,_PPABR,_PS,_Pa,_Par,_Parq,_Pay,_Payl,_Pe,_Po,_Pr,_Pri,_Pro,_Q,_QA,_QC,_QCL,_QCu,_QCue,_QEC,_QF,_Qu,_R,_RART,_RC,_RCC,_RCD,_RCE,_RCL,_RCT,_RCe,_RD,_RE,_RED,_REe,_REec,_RKKID,_RKPW,_RKW,_RM,_RO,_ROO,_ROOe,_ROP,_ROR,_RORe,_ROe,_RP,_RPB,_RPC,_RPe,_RR,_RRAO,_RRF,_RRe,_RRep,_RReq,_RRes,_RRo,_RS,_RSe,_RSen,_RT,_RTV,_RTe,_RUD,_Ra,_Re,_Rec,_Red,_Ret,_Ro,_Ru,_S,_SA,_SAK,_SAs,_SB,_SBD,_SC,_SCA,_SCADE,_SCV,_SCe,_SCt,_SDV,_SE,_SIM,_SIMS,_SINM,_SIUS,_SK,_SKEO,_SKF,_SKe,_SL,_SM,_SOC,_SOCES,_SOCO,_SOCR,_SP,_SPi,_SR,_SS,_SSC,_SSE,_SSEA,_SSEBD,_SSEC,_SSECA,_SSECK,_SSECKMD,_SSEKMS,_SSEKMSE,_SSEKMSEC,_SSEKMSKI,_SSER,_SSERe,_SSES,_ST,_STD,_STDR,_S_,_Sc,_Si,_St,_Sta,_Su,_T,_TA,_TAo,_TB,_TBA,_TBT,_TC,_TCL,_TCo,_TCop,_TD,_TDMOS,_TG,_TGa,_TL,_TLr,_TMP,_TN,_TNa,_TOKF,_TP,_TPC,_TS,_TSa,_Ta,_Tag,_Ti,_Tie,_Tier,_Tim,_To,_Top,_Tr,_Tra,_Ty,_U,_UBMITC,_UBMITCR,_UBMJTC,_UBMJTCR,_UI,_UIM,_UM,_UOE,_UOER,_UOERp,_UP,_UPC,_UPCO,_UPCR,_UPO,_UPR,_URI,_Up,_V,_VC,_VI,_VIM,_Ve,_Ver,_WC,_WGOR,_WGORR,_WOB,_WRL,_Y,_ar,_br,_c2,_ct,_d,_e,_eP,_en,_et,_fo,_h,_hC,_hE,_hH,_hL,_hP,_hPH,_hQ,_hi,_i,_iT,_km,_m,_mb,_mdb,_mk,_mp,_mu,_p,_pN,_pnm,_rcc,_rcd,_rce,_rcl,_rct,_re,_s,_sa,_st,_uI,_uim,_vI,_vim,_x,_xA,_xF,_xN,_xNm,_xaa,_xaad,_xaapa,_xaari,_xaas,_xaba,_xabgr,_xabln,_xablt,_xabn,_xabole,_xabolt,_xabr,_xaca,_xacc,_xacc_,_xacc__,_xacm,_xacrsba,_xacs,_xacs_,_xacs__,_xacsim,_xacsims,_xacsinm,_xacsius,_xacsm,_xacsr,_xacssseca,_xacssseck,_xacssseckM,_xacsvi,_xact,_xact_,_xadm,_xae,_xaebo,_xafec,_xafem,_xafhCC,_xafhCD,_xafhCE,_xafhCL,_xafhCR,_xafhCT,_xafhE,_xafhE_,_xafhLM,_xafhar,_xafhxacc,_xafhxacc_,_xafhxacc__,_xafhxacs,_xafhxacs_,_xafhxadm,_xafhxae,_xafhxamm,_xafhxampc,_xafhxaollh,_xafhxaolm,_xafhxaolrud,_xafhxar,_xafhxarc,_xafhxars,_xafhxasc,_xafhxasse,_xafhxasseakki,_xafhxassebke,_xafhxasseca,_xafhxasseckM,_xafhxatc,_xafhxavi,_xafs,_xagfc,_xagr,_xagra,_xagw,_xagwa,_xaimit,_xaimlmt,_xaims,_xam,_xam_,_xamd,_xamm,_xamos,_xamp,_xampc,_xaoa,_xaollh,_xaolm,_xaolrud,_xaoo,_xaooa,_xaos,_xapnm,_xar,_xarc,_xarop,_xarp,_xarr,_xars,_xars_,_xarsim,_xarsims,_xarsinm,_xarsius,_xart,_xasc,_xasca,_xasdv,_xasebo,_xasse,_xasseakki,_xassebke,_xassec,_xasseca,_xasseck,_xasseckM,_xat,_xatc,_xatd,_xatdmos,_xavi,_xawob,_xawrl,_xs,n0,_s_registry,S3ServiceException$,n0_registry,AccessDenied$,BucketAlreadyExists$,BucketAlreadyOwnedByYou$,EncryptionTypeMismatch$,IdempotencyParameterMismatch$,InvalidObjectState$,InvalidRequest$,InvalidWriteOffset$,NoSuchBucket$,NoSuchKey$,NoSuchUpload$,NotFound$,ObjectAlreadyInActiveTierError$,ObjectNotInActiveTierError$,TooManyParts$,errorTypeRegistries,CopySourceSSECustomerKey,NonEmptyKmsKeyArnString,SessionCredentialValue,SSECustomerKey,SSEKMSEncryptionContext,SSEKMSKeyId,StreamingBlob,AbacStatus$,AbortIncompleteMultipartUpload$,AbortMultipartUploadOutput$,AbortMultipartUploadRequest$,AccelerateConfiguration$,AccessControlPolicy$,AccessControlTranslation$,AnalyticsAndOperator$,AnalyticsConfiguration$,AnalyticsExportDestination$,AnalyticsS3BucketDestination$,BlockedEncryptionTypes$,Bucket$,BucketInfo$,BucketLifecycleConfiguration$,BucketLoggingStatus$,Checksum$,CommonPrefix$,CompletedMultipartUpload$,CompletedPart$,CompleteMultipartUploadOutput$,CompleteMultipartUploadRequest$,Condition$,ContinuationEvent$,CopyObjectOutput$,CopyObjectRequest$,CopyObjectResult$,CopyPartResult$,CORSConfiguration$,CORSRule$,CreateBucketConfiguration$,CreateBucketMetadataConfigurationRequest$,CreateBucketMetadataTableConfigurationRequest$,CreateBucketOutput$,CreateBucketRequest$,CreateMultipartUploadOutput$,CreateMultipartUploadRequest$,CreateSessionOutput$,CreateSessionRequest$,CSVInput$,CSVOutput$,DefaultRetention$,Delete$,DeleteBucketAnalyticsConfigurationRequest$,DeleteBucketCorsRequest$,DeleteBucketEncryptionRequest$,DeleteBucketIntelligentTieringConfigurationRequest$,DeleteBucketInventoryConfigurationRequest$,DeleteBucketLifecycleRequest$,DeleteBucketMetadataConfigurationRequest$,DeleteBucketMetadataTableConfigurationRequest$,DeleteBucketMetricsConfigurationRequest$,DeleteBucketOwnershipControlsRequest$,DeleteBucketPolicyRequest$,DeleteBucketReplicationRequest$,DeleteBucketRequest$,DeleteBucketTaggingRequest$,DeleteBucketWebsiteRequest$,DeletedObject$,DeleteMarkerEntry$,DeleteMarkerReplication$,DeleteObjectOutput$,DeleteObjectRequest$,DeleteObjectsOutput$,DeleteObjectsRequest$,DeleteObjectTaggingOutput$,DeleteObjectTaggingRequest$,DeletePublicAccessBlockRequest$,Destination$,DestinationResult$,Encryption$,EncryptionConfiguration$,EndEvent$,_Error$,ErrorDetails$,ErrorDocument$,EventBridgeConfiguration$,ExistingObjectReplication$,FilterRule$,GetBucketAbacOutput$,GetBucketAbacRequest$,GetBucketAccelerateConfigurationOutput$,GetBucketAccelerateConfigurationRequest$,GetBucketAclOutput$,GetBucketAclRequest$,GetBucketAnalyticsConfigurationOutput$,GetBucketAnalyticsConfigurationRequest$,GetBucketCorsOutput$,GetBucketCorsRequest$,GetBucketEncryptionOutput$,GetBucketEncryptionRequest$,GetBucketIntelligentTieringConfigurationOutput$,GetBucketIntelligentTieringConfigurationRequest$,GetBucketInventoryConfigurationOutput$,GetBucketInventoryConfigurationRequest$,GetBucketLifecycleConfigurationOutput$,GetBucketLifecycleConfigurationRequest$,GetBucketLocationOutput$,GetBucketLocationRequest$,GetBucketLoggingOutput$,GetBucketLoggingRequest$,GetBucketMetadataConfigurationOutput$,GetBucketMetadataConfigurationRequest$,GetBucketMetadataConfigurationResult$,GetBucketMetadataTableConfigurationOutput$,GetBucketMetadataTableConfigurationRequest$,GetBucketMetadataTableConfigurationResult$,GetBucketMetricsConfigurationOutput$,GetBucketMetricsConfigurationRequest$,GetBucketNotificationConfigurationRequest$,GetBucketOwnershipControlsOutput$,GetBucketOwnershipControlsRequest$,GetBucketPolicyOutput$,GetBucketPolicyRequest$,GetBucketPolicyStatusOutput$,GetBucketPolicyStatusRequest$,GetBucketReplicationOutput$,GetBucketReplicationRequest$,GetBucketRequestPaymentOutput$,GetBucketRequestPaymentRequest$,GetBucketTaggingOutput$,GetBucketTaggingRequest$,GetBucketVersioningOutput$,GetBucketVersioningRequest$,GetBucketWebsiteOutput$,GetBucketWebsiteRequest$,GetObjectAclOutput$,GetObjectAclRequest$,GetObjectAttributesOutput$,GetObjectAttributesParts$,GetObjectAttributesRequest$,GetObjectLegalHoldOutput$,GetObjectLegalHoldRequest$,GetObjectLockConfigurationOutput$,GetObjectLockConfigurationRequest$,GetObjectOutput$,GetObjectRequest$,GetObjectRetentionOutput$,GetObjectRetentionRequest$,GetObjectTaggingOutput$,GetObjectTaggingRequest$,GetObjectTorrentOutput$,GetObjectTorrentRequest$,GetPublicAccessBlockOutput$,GetPublicAccessBlockRequest$,GlacierJobParameters$,Grant$,Grantee$,HeadBucketOutput$,HeadBucketRequest$,HeadObjectOutput$,HeadObjectRequest$,IndexDocument$,Initiator$,InputSerialization$,IntelligentTieringAndOperator$,IntelligentTieringConfiguration$,IntelligentTieringFilter$,InventoryConfiguration$,InventoryDestination$,InventoryEncryption$,InventoryFilter$,InventoryS3BucketDestination$,InventorySchedule$,InventoryTableConfiguration$,InventoryTableConfigurationResult$,InventoryTableConfigurationUpdates$,JournalTableConfiguration$,JournalTableConfigurationResult$,JournalTableConfigurationUpdates$,JSONInput$,JSONOutput$,LambdaFunctionConfiguration$,LifecycleExpiration$,LifecycleRule$,LifecycleRuleAndOperator$,LifecycleRuleFilter$,ListBucketAnalyticsConfigurationsOutput$,ListBucketAnalyticsConfigurationsRequest$,ListBucketIntelligentTieringConfigurationsOutput$,ListBucketIntelligentTieringConfigurationsRequest$,ListBucketInventoryConfigurationsOutput$,ListBucketInventoryConfigurationsRequest$,ListBucketMetricsConfigurationsOutput$,ListBucketMetricsConfigurationsRequest$,ListBucketsOutput$,ListBucketsRequest$,ListDirectoryBucketsOutput$,ListDirectoryBucketsRequest$,ListMultipartUploadsOutput$,ListMultipartUploadsRequest$,ListObjectsOutput$,ListObjectsRequest$,ListObjectsV2Output$,ListObjectsV2Request$,ListObjectVersionsOutput$,ListObjectVersionsRequest$,ListPartsOutput$,ListPartsRequest$,LocationInfo$,LoggingEnabled$,MetadataConfiguration$,MetadataConfigurationResult$,MetadataEntry$,MetadataTableConfiguration$,MetadataTableConfigurationResult$,MetadataTableEncryptionConfiguration$,Metrics$,MetricsAndOperator$,MetricsConfiguration$,MultipartUpload$,NoncurrentVersionExpiration$,NoncurrentVersionTransition$,NotificationConfiguration$,NotificationConfigurationFilter$,_Object$,ObjectIdentifier$,ObjectLockConfiguration$,ObjectLockLegalHold$,ObjectLockRetention$,ObjectLockRule$,ObjectPart$,ObjectVersion$,OutputLocation$,OutputSerialization$,Owner$,OwnershipControls$,OwnershipControlsRule$,ParquetInput$,Part$,PartitionedPrefix$,PolicyStatus$,Progress$,ProgressEvent$,PublicAccessBlockConfiguration$,PutBucketAbacRequest$,PutBucketAccelerateConfigurationRequest$,PutBucketAclRequest$,PutBucketAnalyticsConfigurationRequest$,PutBucketCorsRequest$,PutBucketEncryptionRequest$,PutBucketIntelligentTieringConfigurationRequest$,PutBucketInventoryConfigurationRequest$,PutBucketLifecycleConfigurationOutput$,PutBucketLifecycleConfigurationRequest$,PutBucketLoggingRequest$,PutBucketMetricsConfigurationRequest$,PutBucketNotificationConfigurationRequest$,PutBucketOwnershipControlsRequest$,PutBucketPolicyRequest$,PutBucketReplicationRequest$,PutBucketRequestPaymentRequest$,PutBucketTaggingRequest$,PutBucketVersioningRequest$,PutBucketWebsiteRequest$,PutObjectAclOutput$,PutObjectAclRequest$,PutObjectLegalHoldOutput$,PutObjectLegalHoldRequest$,PutObjectLockConfigurationOutput$,PutObjectLockConfigurationRequest$,PutObjectOutput$,PutObjectRequest$,PutObjectRetentionOutput$,PutObjectRetentionRequest$,PutObjectTaggingOutput$,PutObjectTaggingRequest$,PutPublicAccessBlockRequest$,QueueConfiguration$,RecordExpiration$,RecordsEvent$,Redirect$,RedirectAllRequestsTo$,RenameObjectOutput$,RenameObjectRequest$,ReplicaModifications$,ReplicationConfiguration$,ReplicationRule$,ReplicationRuleAndOperator$,ReplicationRuleFilter$,ReplicationTime$,ReplicationTimeValue$,RequestPaymentConfiguration$,RequestProgress$,RestoreObjectOutput$,RestoreObjectRequest$,RestoreRequest$,RestoreStatus$,RoutingRule$,S3KeyFilter$,S3Location$,S3TablesDestination$,S3TablesDestinationResult$,ScanRange$,SelectObjectContentOutput$,SelectObjectContentRequest$,SelectParameters$,ServerSideEncryptionByDefault$,ServerSideEncryptionConfiguration$,ServerSideEncryptionRule$,SessionCredentials$,SimplePrefix$,SourceSelectionCriteria$,SSEKMS$,SseKmsEncryptedObjects$,SSEKMSEncryption$,SSES3$,Stats$,StatsEvent$,StorageClassAnalysis$,StorageClassAnalysisDataExport$,Tag$,Tagging$,TargetGrant$,TargetObjectKeyFormat$,Tiering$,TopicConfiguration$,Transition$,UpdateBucketMetadataInventoryTableConfigurationRequest$,UpdateBucketMetadataJournalTableConfigurationRequest$,UpdateObjectEncryptionRequest$,UpdateObjectEncryptionResponse$,UploadPartCopyOutput$,UploadPartCopyRequest$,UploadPartOutput$,UploadPartRequest$,VersioningConfiguration$,WebsiteConfiguration$,WriteGetObjectResponseRequest$,__Unit,AnalyticsConfigurationList,Buckets,CommonPrefixList,CompletedPartList,CORSRules,DeletedObjects,DeleteMarkers,EncryptionTypeList,Errors,FilterRuleList,Grants,IntelligentTieringConfigurationList,InventoryConfigurationList,InventoryOptionalFields,LambdaFunctionConfigurationList,LifecycleRules,MetricsConfigurationList,MultipartUploadList,NoncurrentVersionTransitionList,ObjectIdentifierList,ObjectList,ObjectVersionList,OwnershipControlsRules,Parts,PartsList,QueueConfigurationList,ReplicationRules,RoutingRules,ServerSideEncryptionRules,TagSet,TargetGrants,TieringList,TopicConfigurationList,TransitionList,UserMetadata,AnalyticsFilter$,MetricsFilter$,ObjectEncryption$,SelectObjectContentEventStream$,AbortMultipartUpload$,CompleteMultipartUpload$,CopyObject$,CreateBucket$,CreateBucketMetadataConfiguration$,CreateBucketMetadataTableConfiguration$,CreateMultipartUpload$,CreateSession$,DeleteBucket$,DeleteBucketAnalyticsConfiguration$,DeleteBucketCors$,DeleteBucketEncryption$,DeleteBucketIntelligentTieringConfiguration$,DeleteBucketInventoryConfiguration$,DeleteBucketLifecycle$,DeleteBucketMetadataConfiguration$,DeleteBucketMetadataTableConfiguration$,DeleteBucketMetricsConfiguration$,DeleteBucketOwnershipControls$,DeleteBucketPolicy$,DeleteBucketReplication$,DeleteBucketTagging$,DeleteBucketWebsite$,DeleteObject$,DeleteObjects$,DeleteObjectTagging$,DeletePublicAccessBlock$,GetBucketAbac$,GetBucketAccelerateConfiguration$,GetBucketAcl$,GetBucketAnalyticsConfiguration$,GetBucketCors$,GetBucketEncryption$,GetBucketIntelligentTieringConfiguration$,GetBucketInventoryConfiguration$,GetBucketLifecycleConfiguration$,GetBucketLocation$,GetBucketLogging$,GetBucketMetadataConfiguration$,GetBucketMetadataTableConfiguration$,GetBucketMetricsConfiguration$,GetBucketNotificationConfiguration$,GetBucketOwnershipControls$,GetBucketPolicy$,GetBucketPolicyStatus$,GetBucketReplication$,GetBucketRequestPayment$,GetBucketTagging$,GetBucketVersioning$,GetBucketWebsite$,GetObject$,GetObjectAcl$,GetObjectAttributes$,GetObjectLegalHold$,GetObjectLockConfiguration$,GetObjectRetention$,GetObjectTagging$,GetObjectTorrent$,GetPublicAccessBlock$,HeadBucket$,HeadObject$,ListBucketAnalyticsConfigurations$,ListBucketIntelligentTieringConfigurations$,ListBucketInventoryConfigurations$,ListBucketMetricsConfigurations$,ListBuckets$,ListDirectoryBuckets$,ListMultipartUploads$,ListObjects$,ListObjectsV2$,ListObjectVersions$,ListParts$,PutBucketAbac$,PutBucketAccelerateConfiguration$,PutBucketAcl$,PutBucketAnalyticsConfiguration$,PutBucketCors$,PutBucketEncryption$,PutBucketIntelligentTieringConfiguration$,PutBucketInventoryConfiguration$,PutBucketLifecycleConfiguration$,PutBucketLogging$,PutBucketMetricsConfiguration$,PutBucketNotificationConfiguration$,PutBucketOwnershipControls$,PutBucketPolicy$,PutBucketReplication$,PutBucketRequestPayment$,PutBucketTagging$,PutBucketVersioning$,PutBucketWebsite$,PutObject$,PutObjectAcl$,PutObjectLegalHold$,PutObjectLockConfiguration$,PutObjectRetention$,PutObjectTagging$,PutPublicAccessBlock$,RenameObject$,RestoreObject$,SelectObjectContent$,UpdateBucketMetadataInventoryTableConfiguration$,UpdateBucketMetadataJournalTableConfiguration$,UpdateObjectEncryption$,UploadPart$,UploadPartCopy$,WriteGetObjectResponse$,CreateSessionCommand,package_default_version,fromUtf84,SHA_1_HASH,SHA_1_HMAC_ALGO,EMPTY_DATA_SHA_1,fallbackWindow,Sha1,subtleCryptoMethods,Sha12,SHA_256_HASH,SHA_256_HMAC_ALGO,EMPTY_DATA_SHA_256,Sha256,BLOCK_SIZE,DIGEST_LENGTH,KEY,INIT,MAX_HASHABLE_LENGTH,RawSha256,Sha2562,Sha2563,createDefaultUserAgentProvider,fallback2,Int643,HeaderMarshaller2,HEADER_VALUE_TYPE3,BOOLEAN_TAG2,BYTE_TAG2,SHORT_TAG2,INT_TAG2,LONG_TAG2,BINARY_TAG2,STRING_TAG2,TIMESTAMP_TAG2,UUID_TAG2,UUID_PATTERN3,PRELUDE_MEMBER_LENGTH2,PRELUDE_LENGTH2,CHECKSUM_LENGTH2,MINIMUM_MESSAGE_LENGTH2,EventStreamCodec2,MessageDecoderStream2,MessageEncoderStream2,SmithyMessageDecoderStream2,SmithyMessageEncoderStream2,EventStreamMarshaller3,readableStreamtoIterable,iterableToReadableStream2,EventStreamMarshaller4,isReadableStream4,eventStreamSerdeProvider3,blobHasher,invalidProvider2,BLOCK_SIZE2,DIGEST_LENGTH2,INIT2,Md5,TEXT_ENCODER2,calculateBodyLength2,DEFAULTS_MODE_OPTIONS,resolveDefaultsModeConfig,useMobileConfiguration,getRuntimeConfig,getRuntimeConfig2,getAwsRegionExtensionConfiguration,resolveAwsRegionExtensionConfiguration,getHttpAuthExtensionConfiguration,resolveHttpAuthRuntimeConfig,resolveRuntimeExtensions,S3Client,AbortMultipartUploadCommand,ssecMiddlewareOptions,getSsecPlugin,CompleteMultipartUploadCommand,CopyObjectCommand,locationConstraintMiddlewareOptions,getLocationConstraintPlugin,CreateBucketCommand,CreateBucketMetadataConfigurationCommand,CreateBucketMetadataTableConfigurationCommand,CreateMultipartUploadCommand,DeleteBucketAnalyticsConfigurationCommand,DeleteBucketCommand,DeleteBucketCorsCommand,DeleteBucketEncryptionCommand,DeleteBucketIntelligentTieringConfigurationCommand,DeleteBucketInventoryConfigurationCommand,DeleteBucketLifecycleCommand,DeleteBucketMetadataConfigurationCommand,DeleteBucketMetadataTableConfigurationCommand,DeleteBucketMetricsConfigurationCommand,DeleteBucketOwnershipControlsCommand,DeleteBucketPolicyCommand,DeleteBucketReplicationCommand,DeleteBucketTaggingCommand,DeleteBucketWebsiteCommand,DeleteObjectCommand,DeleteObjectsCommand,DeleteObjectTaggingCommand,DeletePublicAccessBlockCommand,GetBucketAbacCommand,GetBucketAccelerateConfigurationCommand,GetBucketAclCommand,GetBucketAnalyticsConfigurationCommand,GetBucketCorsCommand,GetBucketEncryptionCommand,GetBucketIntelligentTieringConfigurationCommand,GetBucketInventoryConfigurationCommand,GetBucketLifecycleConfigurationCommand,GetBucketLocationCommand,GetBucketLoggingCommand,GetBucketMetadataConfigurationCommand,GetBucketMetadataTableConfigurationCommand,GetBucketMetricsConfigurationCommand,GetBucketNotificationConfigurationCommand,GetBucketOwnershipControlsCommand,GetBucketPolicyCommand,GetBucketPolicyStatusCommand,GetBucketReplicationCommand,GetBucketRequestPaymentCommand,GetBucketTaggingCommand,GetBucketVersioningCommand,GetBucketWebsiteCommand,GetObjectAclCommand,GetObjectAttributesCommand,GetObjectCommand,GetObjectLegalHoldCommand,GetObjectLockConfigurationCommand,GetObjectRetentionCommand,GetObjectTaggingCommand,GetObjectTorrentCommand,GetPublicAccessBlockCommand,HeadBucketCommand,HeadObjectCommand,ListBucketAnalyticsConfigurationsCommand,ListBucketIntelligentTieringConfigurationsCommand,ListBucketInventoryConfigurationsCommand,ListBucketMetricsConfigurationsCommand,ListBucketsCommand,ListDirectoryBucketsCommand,ListMultipartUploadsCommand,ListObjectsCommand,ListObjectsV2Command,ListObjectVersionsCommand,ListPartsCommand,PutBucketAbacCommand,PutBucketAccelerateConfigurationCommand,PutBucketAclCommand,PutBucketAnalyticsConfigurationCommand,PutBucketCorsCommand,PutBucketEncryptionCommand,PutBucketIntelligentTieringConfigurationCommand,PutBucketInventoryConfigurationCommand,PutBucketLifecycleConfigurationCommand,PutBucketLoggingCommand,PutBucketMetricsConfigurationCommand,PutBucketNotificationConfigurationCommand,PutBucketOwnershipControlsCommand,PutBucketPolicyCommand,PutBucketReplicationCommand,PutBucketRequestPaymentCommand,PutBucketTaggingCommand,PutBucketVersioningCommand,PutBucketWebsiteCommand,PutObjectAclCommand,PutObjectCommand,PutObjectLegalHoldCommand,PutObjectLockConfigurationCommand,PutObjectRetentionCommand,PutObjectTaggingCommand,PutPublicAccessBlockCommand,RenameObjectCommand,RestoreObjectCommand,SelectObjectContentCommand,UpdateBucketMetadataInventoryTableConfigurationCommand,UpdateBucketMetadataJournalTableConfigurationCommand,UpdateObjectEncryptionCommand,UploadPartCommand,UploadPartCopyCommand,WriteGetObjectResponseCommand,paginateListBuckets,paginateListDirectoryBuckets,paginateListObjectsV2,paginateListParts,getCircularReplacer,sleep,waiterServiceDefaults2,WaiterState2,checkExceptions2,exponentialBackoffWithJitter,randomInRange,runPolling,createMessageFromResponse,validateWaiterOptions,abortTimeout,createWaiter2,checkState,waitUntilBucketExists,checkState2,waitUntilBucketNotExists,checkState3,waitUntilObjectExists,checkState4,waitUntilObjectNotExists,commands,paginators,waiters,S3,applyMd5BodyChecksumMiddleware,applyMd5BodyChecksumMiddlewareOptions,hasHeader3,MinioStorageAdapter,LANG_DE,LANG_ES,LANG_FR,LANG_HE,LANG_JA,LANG_RU,LANG_ZH,LANG_KO,LANG_ZH_TW,LANG_DEF,SUPPORTED_I18N_LANGS,updateInformation,EVENT_REQUEST_SHOW_HISTORY,REPORT_WARNING,UnresolvedErrorManager,FilePairProcessResults_COMPLETED,FilePairProcessResults_SKIPPED,FilePairProcessResults_FAILED,MetadataDocumentNamespaces_NORMAL,MetadataDocumentNamespaces_INTERNAL,MetadataDocumentNamespaces_CUSTOMISATION,MetadataDocumentNamespaces_PLUGIN_STORAGE,MetadataDocumentIdentityStatuses_CONSISTENT,MetadataDocumentIdentityStatuses_EXCLUDED,MetadataDocumentIdentityStatuses_UNRESOLVED,OfflineScanUnresolvedReasons_DOCUMENT_ID_MISMATCH,OfflineScanUnresolvedReasons_NAMESPACE_MISMATCH,MetadataDocumentRepairResults_COMPLETED,MetadataDocumentRepairResults_STALE,MetadataDocumentRepairResults_BLOCKED,MetadataDocumentRepairResults_FAILED,FullScanModes_DB_APPLY,FullScanModes_NEWER_WINS,ExtraOnRemote_DELETE_LOCAL_MISSING,ExtraOnLocal_DELETE_DB_DELETED,ExtraOnLocal_DELETE_DB_MISSING,ExtraOnLocal_APPEND_STORAGE_ONLY,fileMaps,FILE_STATUS_MAP_KEY,FILE_STATUS_MAP_LOCK,saveFileStatusTimeout,MetadataIdentityRepairExecutions_CANCELLED,MetadataIdentityRepairExecutions_REPAIR_RESULT,PouchError,MISSING_BULK_DOCS,MISSING_DOC,REV_CONFLICT,INVALID_ID,MISSING_ID,RESERVED_ID,UNKNOWN_ERROR,BAD_ARG,QUERY_PARSE_ERROR,DOC_VALIDATION,BAD_REQUEST,NOT_AN_OBJECT,IDB_ERROR,INVALID_REV,MISSING_STUB,regex_default,validate_default,byteToHex,getRandomValues,rnds8,randomUUID2,native_default,v4_default,thisAtob,thisBtoa,import_spark_md5,setImmediateShim,MD5_CHUNK_SIZE,import_events17,funcToString,objectCtorString,MAX_NUM_CONCURRENT_REQUESTS,hasLocal,nextTick,Changes,hasName,res,keys2,qName,qParser,parser2,uuid,f3,h2,MIN_MAGNITUDE,MAGNITUDE_DIGITS,SEP,combinationFields,matchers,index_browser_es_default,import_events18,Changes2,validRevRegex,AbstractPouchDB,TaskQueue,PouchInternal,PouchDB,ActiveTasks,eventEmitter,version,index_es_default,import_vuvuzela,reservedWords,dataWords,ADAPTER_VERSION,DOC_STORE,BY_SEQ_STORE,ATTACH_STORE,ATTACH_AND_SEQ_STORE,META_STORE,LOCAL_STORE,DETECT_BLOB_SUPPORT_STORE,changesHandler$1,running,queue,cachedDBs,blobSupportPromise,openReqList,index_es_default2,IDB_NULL,IDB_FALSE,IDB_TRUE,TEST_KEY_INVALID,TEST_PATH_INVALID,KEY_INVALID,PATH_INVALID,SLASH,IS_DOT,DOC_STORE2,META_LOCAL_STORE,POUCHDB_IDB_VERSION,versionMultiplier,BINARY_ATTACHMENTS,COUCH_COLLATE_LO,COUCH_COLLATE_HI,IDB_COLLATE_LO,IDB_COLLATE_HI,ADAPTER_NAME,idbChanges,openDatabases,index_es_default3,CHANGES_BATCH_SIZE,MAX_SIMULTANEOUS_REVS,CHANGES_TIMEOUT_BUFFER,DEFAULT_HEARTBEAT,supportsBulkGetMap,index_es_default4,QueryParseError,NotFoundError,BuiltInError,TaskQueue2,persistentQueues,tempViewQueue,CHANGES_BATCH_SIZE2,index_es_default5,log,isArray,toJSON,builtInReduce__sum,builtInReduce__count,builtInReduce__stats,localDocName,abstract,index5,index_browser_es_default2,CHECKPOINT_VERSION,REPLICATOR,CHECKPOINT_HISTORY_SIZE,LOWEST_SEQ,CheckpointerInternal,comparisons,index_es_default6,index_es_default7,import_events19,STARTING_BACK_OFF,Replication,Sync,index_es_default8,nativeFlat,polyFlat,flatten2,requireValidation,arrayTypeComparisonOperators,equalityOperators,abstractMapper,ddocIdPrefix,COLLATE_LO,COLLATE_HI,SHORT_CIRCUIT_QUERY,logicalMatchers,plugin,index_browser_es_default3,import_transform_pouch,SveltePanel,root6,root_15,$$css5,CONTEXT_DIALOG_CONTROLS,SvelteDialogManagerBase,root7,root_16,$$css6,root8,root_17,root9,root_18,root_24,root_34,root10,root11,root_19,$$css7,root12,$$css8,root13,root14,root15,TYPE_IDENTICAL,TYPE_INDEPENDENT,TYPE_UNBALANCED,TYPE_CANCEL,TYPE_BACKUP_DONE,TYPE_BACKUP_SKIPPED,TYPE_UNABLE_TO_BACKUP,TYPE_NEW_USER,TYPE_EXISTING_USER,TYPE_CANCELLED,TYPE_EXISTING,TYPE_NEW,TYPE_COMPATIBLE_EXISTING,TYPE_APPLY,TYPE_FETCH,TYPE_REBUILD,TYPE_USE_SETUP_URI,TYPE_SCAN_QR_CODE,TYPE_CONFIGURE_MANUALLY,TYPE_CLOSE,TYPE_COUCHDB,TYPE_BUCKET,TYPE_P2P,root16,root_110,root17,root_111,root18,root_112,root_25,root19,root_113,root20,root21,root22,root_114,root_26,root_35,root23,root_115,root_27,root_36,root24,root_116,root_28,root_37,root25,root_117,root_29,root26,root_118,root_210,root_38,root27,root_119,root28,checkConfig,root29,root_120,root_211,root_39,$$css9,root30,root_121,root_212,root_310,root_44,root_54,root_64,root_73,root_83,root_93,root_103,root_1110,root_123,root_133,root_142,root31,root_124,root_213,root_311,root_45,root_55,root_65,root_74,root_84,root_94,TrysteroReplicator,root32,root_125,root_214,root_312,root_46,root_56,root_66,root_75,root_85,root_95,root_104,root_1111,root_126,root_134,root_143,root_152,root33,root_127,root_215,root_313,root_47,root_57,root_67,root_76,root_86,import_qrcode_generator,OutputFormat,AGGREGATOR_URL,necessaryErasureProperties,UserMode,SetupManager,root34,root_128,$$css10,SETTINGS_ROOT_GROUP_CATALOGUE,numberRangeMessage,ObsidianLiveSyncSettingTab,ModuleObsidianSettingDialogue,DOCUMENT_HISTORY_PREFERENCE_KEYS_diffOnly,DOCUMENT_HISTORY_PREFERENCE_KEYS_highlightDiff,DocumentHistoryModal,ModuleObsidianDocumentHistory,root35,root_129,root_216,root_314,root_48,root_58,root_68,root_77,root_87,root_96,$$css11,VIEW_TYPE_GLOBAL_HISTORY,GlobalHistoryView,ModuleObsidianGlobalHistory,DB_KEY_SEQ,DB_KEY_CHUNK_SET,DB_KEY_DOC_USAGE_MAP,LocalDatabaseMaintenance,ControlService,PathService,ServiceHub,APIService,Binder,LazyBinder,MultiBinder,DispatchParallel,BooleanHandlerBase,AllHandler,ParallelAllHandler,AnySuccessHandler,FirstResultHandler,InjectableAPIService,AppLifecycleService,AppLifecycleServiceBase,ConflictService,InjectableConflictService,DatabaseEventService,InjectableDatabaseEventService,FileProcessingService,InjectableFileProcessingService,REPLICATION_ON_EVENT_FORECASTED_TIME,ReplicationService,InjectableReplicationService,ReplicatorService,InjectableReplicatorService,TestService,InjectableTestService,TweakValueService,InjectableTweakValueService,VaultService,InjectableVaultService,InjectableServiceHub,ObsidianServiceContext,FetchMethod_webCompat,FetchMethod_native,RemoteService,InjectableRemoteService,ConfigService,ConfigServiceBrowserCompat,KeyValueDBService,ObsidianDatabaseEventService,ObsidianReplicatorService,ObsidianFileProcessingService,ObsidianReplicationService,ObsidianRemoteService,ObsidianConflictService,ObsidianTweakValueService,ObsidianTestService,ObsidianConfigService,ObsidianKeyValueDBService,ObsidianControlService,SettingService,ObsidianSettingService,DatabaseService,ObsidianDatabaseService,ObsHttpHandler,import_obsidian3,TextPromptModal,PickOneModal,ActionDialog,import_obsidian4,KeyedNoticeManager,KeyedNoticeGroupManager,AutoClosableModal,InputStringDialog,PopoverSelectString,MessageBox,ObsidianConfirm,ObsidianAPIService,ObsidianAppLifecycleService,ObsidianPathService,ObsidianVaultService,UIService,rest_excludes,root36,$$css12,svelteDialogRenderer,SvelteDialogSession,SvelteDialogObsidian,ObsidianSvelteDialogManager,root37,root_130,$$css13,ObsidianUIService,ScreenWakeLockManagerDisposedError,instanceOfAny,idbProxyableTypes,cursorAdvanceMethods,transactionDoneMap,transformCache,reverseTransformCache,idbProxyTraps,unwrap,readMethods,writeMethods,cachedMethods,advanceMethodProps,methodMap,advanceResults,ittrProxiedCursorToOriginalProxy,cursorIteratorTraps,databaseCache,IDBKeyValueDatabase,databaseCache2,ObsidianNoticeGroupManager,ObsidianServiceHub,ServiceModuleBase,FAST_FETCH_CHANGES_PAGE_LIMIT,FAST_FETCH_CHANGES_PAGE_TIMEOUT_MS,StreamingFetchFailure,FAST_FETCH_CHECKPOINT_KEY,FAST_FETCH_RETRY_DELAYS,ServiceRebuilder,ServiceDatabaseFileAccessBase,ServiceDatabaseFileAccess,StorageEventManager,ServiceFileAccessBase,ServiceFileAccessObsidian,fileLockPrefix,StorageAccessManager,ServiceFileHandlerBase,ServiceFileHandler,FileAccessBase,ObsidianConversionAdapter,ObsidianPathAdapter,ObsidianStorageAdapter,import_obsidian5,ObsidianTypeGuardAdapter,ObsidianVaultAdapter,ObsidianFileSystemAdapter,FileAccessObsidian,TYPE_SENTINEL_FLUSH,StorageEventManagerBase,ObsidianTypeGuardAdapter2,ObsidianPersistenceAdapter,ObsidianStatusAdapter,ObsidianConverterAdapter,ObsidianWatchAdapter,ObsidianStorageEventManagerAdapter,StorageEventManagerObsidian,WrappedNotice,ModulePeriodicProcess,KV_KEY_REPLICATION_RESULT_PROCESSOR_SNAPSHOT,REPROCESS_BATCH_SIZE,ReplicateResultProcessor,ModuleReplicator,ModuleReplicatorCouchDB,MILSTONE_DOCID,currentVersionRange2,LiveSyncJournalReplicator,ModuleReplicatorMinIO,ModuleConflictChecker,import_diff_match_patch4,ModuleConflictResolver,ModuleResolvingMismatchedTweaks,ModuleLiveSyncMain,ModuleBasicMenu,LiveSyncBaseCore,ModuleObsidianMenu,SETTING_HEADER,SETTING_FOOTER,ModuleObsidianSettingsAsMarkdown,ConditionType,RuleLevel,DoctorRegulationV0_24_16,DoctorRegulationV0_24_30_rules,DoctorRegulationV0_25_0_rules,DoctorRegulationV0_25_27_rules,DoctorRegulationV1_0_0,DoctorRegulation,RebuildOptions_AutomaticAcceptable,RebuildOptions_ConfirmIfRequired,RebuildOptions_SkipEvenIfRequired,ONBOARDING_NOTICE_DURATION_MS,INCOMPLETE_DOCUMENT_NOTICE_GROUP,ModuleMigration,ObsidianLanguageAppliedNotice,enableI18nFeature,REMOTE_SIZE_NOTICE_DURATION_MS,root38,$$css14,root39,root_131,root_217,root_315,root_49,root_59,root_69,root40,root_135,root_218,root_316,root_410,root_510,SIMPLE_FETCH_STAGE1_REMOTE_WINS,SIMPLE_FETCH_STAGE1_NEWER_WINS,SIMPLE_FETCH_STAGE1_DETAILED,SIMPLE_FETCH_STAGE1_CANCEL,SIMPLE_FETCH_STAGE2_REMOTE_DELETE_NONE,SIMPLE_FETCH_STAGE2_REMOTE_DELETE_ALL,SIMPLE_FETCH_STAGE2_NEWER_CLEANUP,SIMPLE_FETCH_STAGE2_NEWER_SYNC_ALL,STAGE2_ABORT,SIMPLE_FETCH_MODE_KEY,RERUN_PROCESS,RELEASE_FLAG_PROCESS,REMOTE_KEEP_CURRENT,REMOTE_CANCEL,LiveSyncTrysteroReplicator,root41,root_136,root_219,root_317,root_411,root_511,$$css15,root42,root_137,root_220,root_318,root_412,root_512,root_610,root_78,root_88,root_97,$$css16,VIEW_TYPE_P2P_SERVER_STATUS,P2PServerStatusPaneView,LEGACY_VIEW_TYPE_P2P,LegacyP2PStatusPaneView,REVIEW_HARNESS_SCENARIOS,REVIEW_HARNESS_STATE_KEY,PRESERVED_SYNC_SETTING_KEYS,NEW_VAULT_RECOMMENDATION_KEYS,idleResult,ReviewHarnessController,VIEW_TYPE_REVIEW_HARNESS,STATUS_LABELS,ReviewHarnessView,REVIEW_HARNESS_FIXTURE_ROOT,REVIEW_HARNESS_SOURCE_FILE,REVIEW_HARNESS_RENAMED_FILE,CREATED_CONTENT,MODIFIED_CONTENT,root43,root_138,root_221,root_319,root_413,root_513,root_611,root_79,$$css17,P2POpenReplicationModal,DATABASE_COMPATIBILITY_VERSION_KEY,DATABASE_COMPATIBILITY_LEGACY_VERSION_KEY_PREFIX,COMPATIBILITY_PAUSE_SETTING_MESSAGE,COMPATIBILITY_REVIEW_LAYOUT_PRIORITY,CompatibilityReviewController,REVIEW_DETAILS,KEEP_PAUSED,RESUME,BACK,ObsidianCompatibilityReviewUi,StoredFileReflectionProvenance,FILE_REFLECTION_PROVENANCE_STORE,ObsidianLiveSyncPlugin,__create=Object.create,__defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__typeError=msg=>{throw TypeError(msg)},__defNormalProp=(obj,key3,value)=>key3 in obj?__defProp(obj,key3,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key3]=value,__esm=(fn,res2,err3)=>function __init(){if(err3)throw err3[0];try{return fn&&(res2=(0,fn[__getOwnPropNames(fn)[0]])(fn=0)),res2}catch(e3){throw err3=[e3],e3}},__commonJS=(cb2,mod)=>function __require(){try{return mod||(0,cb2[__getOwnPropNames(cb2)[0]])((mod={exports:{}}).exports,mod),mod.exports}catch(e3){throw mod=0,e3}},__export=(target,all2)=>{for(var name in all2)__defProp(target,name,{get:all2[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&"object"==typeof from||"function"==typeof from)for(let key3 of __getOwnPropNames(from))__hasOwnProp.call(to,key3)||key3===except||__defProp(to,key3,{get:()=>from[key3],enumerable:!(desc=__getOwnPropDesc(from,key3))||desc.enumerable});return to},__toESM=(mod,isNodeMode,target)=>(target=null!=mod?__create(__getProtoOf(mod)):{},__copyProps(!isNodeMode&&mod&&mod.__esModule?target:__defProp(target,"default",{value:mod,enumerable:!0}),mod)),__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),__publicField=(obj,key3,value)=>__defNormalProp(obj,"symbol"!=typeof key3?key3+"":key3,value),__accessCheck=(obj,member2,msg)=>member2.has(obj)||__typeError("Cannot "+msg),__privateGet=(obj,member2,getter)=>(__accessCheck(obj,member2,"read from private field"),getter?getter.call(obj):member2.get(obj)),__privateAdd=(obj,member2,value)=>member2.has(obj)?__typeError("Cannot add the same private member more than once"):member2 instanceof WeakSet?member2.add(obj):member2.set(obj,value),__privateSet=(obj,member2,value,setter)=>(__accessCheck(obj,member2,"write to private field"),setter?setter.call(obj,value):member2.set(obj,value),value),__privateMethod=(obj,member2,method)=>(__accessCheck(obj,member2,"access private method"),method),require_diff_match_patch=__commonJS({"node_modules/diff-match-patch/index.js"(exports,module2){var diff_match_patch4=function(){this.Diff_Timeout=1;this.Diff_EditCost=4;this.Match_Threshold=.5;this.Match_Distance=1e3;this.Patch_DeleteThreshold=.5;this.Patch_Margin=4;this.Match_MaxBits=32},DIFF_DELETE4=-1,DIFF_INSERT4=1,DIFF_EQUAL4=0;diff_match_patch4.Diff=function(op,text2){return[op,text2]};diff_match_patch4.prototype.diff_main=function(text1,text2,opt_checklines,opt_deadline){var deadline,checklines,commonlength,commonprefix,commonsuffix,diffs;void 0===opt_deadline&&(opt_deadline=this.Diff_Timeout<=0?Number.MAX_VALUE:(new Date).getTime()+1e3*this.Diff_Timeout);deadline=opt_deadline;if(null==text1||null==text2)throw new Error("Null input. (diff_main)");if(text1==text2)return text1?[new diff_match_patch4.Diff(DIFF_EQUAL4,text1)]:[];void 0===opt_checklines&&(opt_checklines=!0);checklines=opt_checklines;commonlength=this.diff_commonPrefix(text1,text2);commonprefix=text1.substring(0,commonlength);text1=text1.substring(commonlength);text2=text2.substring(commonlength);commonlength=this.diff_commonSuffix(text1,text2);commonsuffix=text1.substring(text1.length-commonlength);text1=text1.substring(0,text1.length-commonlength);text2=text2.substring(0,text2.length-commonlength);diffs=this.diff_compute_(text1,text2,checklines,deadline);commonprefix&&diffs.unshift(new diff_match_patch4.Diff(DIFF_EQUAL4,commonprefix));commonsuffix&&diffs.push(new diff_match_patch4.Diff(DIFF_EQUAL4,commonsuffix));this.diff_cleanupMerge(diffs);return diffs};diff_match_patch4.prototype.diff_compute_=function(text1,text2,checklines,deadline){var diffs,longtext,shorttext,i3,hm,text1_a,text1_b,text2_a,text2_b,mid_common,diffs_a,diffs_b;if(!text1)return[new diff_match_patch4.Diff(DIFF_INSERT4,text2)];if(!text2)return[new diff_match_patch4.Diff(DIFF_DELETE4,text1)];longtext=text1.length>text2.length?text1:text2;shorttext=text1.length>text2.length?text2:text1;i3=longtext.indexOf(shorttext);if(-1!=i3){diffs=[new diff_match_patch4.Diff(DIFF_INSERT4,longtext.substring(0,i3)),new diff_match_patch4.Diff(DIFF_EQUAL4,shorttext),new diff_match_patch4.Diff(DIFF_INSERT4,longtext.substring(i3+shorttext.length))];text1.length>text2.length&&(diffs[0][0]=diffs[2][0]=DIFF_DELETE4);return diffs}if(1==shorttext.length)return[new diff_match_patch4.Diff(DIFF_DELETE4,text1),new diff_match_patch4.Diff(DIFF_INSERT4,text2)];hm=this.diff_halfMatch_(text1,text2);if(hm){text1_a=hm[0];text1_b=hm[1];text2_a=hm[2];text2_b=hm[3];mid_common=hm[4];diffs_a=this.diff_main(text1_a,text2_a,checklines,deadline);diffs_b=this.diff_main(text1_b,text2_b,checklines,deadline);return diffs_a.concat([new diff_match_patch4.Diff(DIFF_EQUAL4,mid_common)],diffs_b)}return checklines&&text1.length>100&&text2.length>100?this.diff_lineMode_(text1,text2,deadline):this.diff_bisect_(text1,text2,deadline)};diff_match_patch4.prototype.diff_lineMode_=function(text1,text2,deadline){var linearray,diffs,pointer,count_delete,count_insert,text_delete,text_insert,subDiff,j2,a2=this.diff_linesToChars_(text1,text2);text1=a2.chars1;text2=a2.chars2;linearray=a2.lineArray;diffs=this.diff_main(text1,text2,!1,deadline);this.diff_charsToLines_(diffs,linearray);this.diff_cleanupSemantic(diffs);diffs.push(new diff_match_patch4.Diff(DIFF_EQUAL4,""));pointer=0;count_delete=0;count_insert=0;text_delete="";text_insert="";for(;pointer<diffs.length;){switch(diffs[pointer][0]){case DIFF_INSERT4:count_insert++;text_insert+=diffs[pointer][1];break;case DIFF_DELETE4:count_delete++;text_delete+=diffs[pointer][1];break;case DIFF_EQUAL4:if(count_delete>=1&&count_insert>=1){diffs.splice(pointer-count_delete-count_insert,count_delete+count_insert);pointer=pointer-count_delete-count_insert;subDiff=this.diff_main(text_delete,text_insert,!1,deadline);for(j2=subDiff.length-1;j2>=0;j2--)diffs.splice(pointer,0,subDiff[j2]);pointer+=subDiff.length}count_insert=0;count_delete=0;text_delete="";text_insert="";break}pointer++}diffs.pop();return diffs};diff_match_patch4.prototype.diff_bisect_=function(text1,text2,deadline){var x3,delta,front,k1start,k1end,k2start,k2end,d4,k1,k1_offset,x1,y1,k2_offset,x22,k2,y2,text1_length=text1.length,text2_length=text2.length,max_d=Math.ceil((text1_length+text2_length)/2),v_offset=max_d,v_length=2*max_d,v1=new Array(v_length),v2=new Array(v_length);for(x3=0;x3<v_length;x3++){v1[x3]=-1;v2[x3]=-1}v1[v_offset+1]=0;v2[v_offset+1]=0;delta=text1_length-text2_length;front=delta%2!=0;k1start=0;k1end=0;k2start=0;k2end=0;for(d4=0;d4<max_d&&!((new Date).getTime()>deadline);d4++){for(k1=-d4+k1start;k1<=d4-k1end;k1+=2){k1_offset=v_offset+k1;x1=k1==-d4||k1!=d4&&v1[k1_offset-1]<v1[k1_offset+1]?v1[k1_offset+1]:v1[k1_offset-1]+1;y1=x1-k1;for(;x1<text1_length&&y1<text2_length&&text1.charAt(x1)==text2.charAt(y1);){x1++;y1++}v1[k1_offset]=x1;if(x1>text1_length)k1end+=2;else if(y1>text2_length)k1start+=2;else if(front){k2_offset=v_offset+delta-k1;if(k2_offset>=0&&k2_offset<v_length&&-1!=v2[k2_offset]){x22=text1_length-v2[k2_offset];if(x1>=x22)return this.diff_bisectSplit_(text1,text2,x1,y1,deadline)}}}for(k2=-d4+k2start;k2<=d4-k2end;k2+=2){k2_offset=v_offset+k2;x22=k2==-d4||k2!=d4&&v2[k2_offset-1]<v2[k2_offset+1]?v2[k2_offset+1]:v2[k2_offset-1]+1;y2=x22-k2;for(;x22<text1_length&&y2<text2_length&&text1.charAt(text1_length-x22-1)==text2.charAt(text2_length-y2-1);){x22++;y2++}v2[k2_offset]=x22;if(x22>text1_length)k2end+=2;else if(y2>text2_length)k2start+=2;else if(!front){k1_offset=v_offset+delta-k2;if(k1_offset>=0&&k1_offset<v_length&&-1!=v1[k1_offset]){x1=v1[k1_offset];y1=v_offset+x1-k1_offset;x22=text1_length-x22;if(x1>=x22)return this.diff_bisectSplit_(text1,text2,x1,y1,deadline)}}}}return[new diff_match_patch4.Diff(DIFF_DELETE4,text1),new diff_match_patch4.Diff(DIFF_INSERT4,text2)]};diff_match_patch4.prototype.diff_bisectSplit_=function(text1,text2,x3,y2,deadline){var text1a=text1.substring(0,x3),text2a=text2.substring(0,y2),text1b=text1.substring(x3),text2b=text2.substring(y2),diffs=this.diff_main(text1a,text2a,!1,deadline),diffsb=this.diff_main(text1b,text2b,!1,deadline);return diffs.concat(diffsb)};diff_match_patch4.prototype.diff_linesToChars_=function(text1,text2){function diff_linesToCharsMunge_(text3){for(var line,chars3="",lineStart=0,lineEnd=-1,lineArrayLength=lineArray.length;lineEnd<text3.length-1;){lineEnd=text3.indexOf("\n",lineStart);-1==lineEnd&&(lineEnd=text3.length-1);line=text3.substring(lineStart,lineEnd+1);if(lineHash.hasOwnProperty?lineHash.hasOwnProperty(line):void 0!==lineHash[line])chars3+=String.fromCharCode(lineHash[line]);else{if(lineArrayLength==maxLines){line=text3.substring(lineStart);lineEnd=text3.length}chars3+=String.fromCharCode(lineArrayLength);lineHash[line]=lineArrayLength;lineArray[lineArrayLength++]=line}lineStart=lineEnd+1}return chars3}var maxLines,chars1,chars22,lineArray=[],lineHash={};lineArray[0]="";maxLines=4e4;chars1=diff_linesToCharsMunge_(text1);maxLines=65535;chars22=diff_linesToCharsMunge_(text2);return{chars1,chars2:chars22,lineArray}};diff_match_patch4.prototype.diff_charsToLines_=function(diffs,lineArray){var i3,chars3,text2,j2;for(i3=0;i3<diffs.length;i3++){chars3=diffs[i3][1];text2=[];for(j2=0;j2<chars3.length;j2++)text2[j2]=lineArray[chars3.charCodeAt(j2)];diffs[i3][1]=text2.join("")}};diff_match_patch4.prototype.diff_commonPrefix=function(text1,text2){var pointermin,pointermax,pointermid,pointerstart;if(!text1||!text2||text1.charAt(0)!=text2.charAt(0))return 0;pointermin=0;pointermax=Math.min(text1.length,text2.length);pointermid=pointermax;pointerstart=0;for(;pointermin<pointermid;){if(text1.substring(pointerstart,pointermid)==text2.substring(pointerstart,pointermid)){pointermin=pointermid;pointerstart=pointermin}else pointermax=pointermid;pointermid=Math.floor((pointermax-pointermin)/2+pointermin)}return pointermid};diff_match_patch4.prototype.diff_commonSuffix=function(text1,text2){var pointermin,pointermax,pointermid,pointerend;if(!text1||!text2||text1.charAt(text1.length-1)!=text2.charAt(text2.length-1))return 0;pointermin=0;pointermax=Math.min(text1.length,text2.length);pointermid=pointermax;pointerend=0;for(;pointermin<pointermid;){if(text1.substring(text1.length-pointermid,text1.length-pointerend)==text2.substring(text2.length-pointermid,text2.length-pointerend)){pointermin=pointermid;pointerend=pointermin}else pointermax=pointermid;pointermid=Math.floor((pointermax-pointermin)/2+pointermin)}return pointermid};diff_match_patch4.prototype.diff_commonOverlap_=function(text1,text2){var text_length,best,length,pattern,found,text1_length=text1.length,text2_length=text2.length;if(0==text1_length||0==text2_length)return 0;text1_length>text2_length?text1=text1.substring(text1_length-text2_length):text1_length<text2_length&&(text2=text2.substring(0,text1_length));text_length=Math.min(text1_length,text2_length);if(text1==text2)return text_length;best=0;length=1;for(;;){pattern=text1.substring(text_length-length);found=text2.indexOf(pattern);if(-1==found)return best;length+=found;if(0==found||text1.substring(text_length-length)==text2.substring(0,length)){best=length;length++}}};diff_match_patch4.prototype.diff_halfMatch_=function(text1,text2){function diff_halfMatchI_(longtext2,shorttext2,i3){for(var best_longtext_a,best_longtext_b,best_shorttext_a,best_shorttext_b,prefixLength,suffixLength,seed=longtext2.substring(i3,i3+Math.floor(longtext2.length/4)),j2=-1,best_common="";-1!=(j2=shorttext2.indexOf(seed,j2+1));){prefixLength=dmp.diff_commonPrefix(longtext2.substring(i3),shorttext2.substring(j2));suffixLength=dmp.diff_commonSuffix(longtext2.substring(0,i3),shorttext2.substring(0,j2));if(best_common.length<suffixLength+prefixLength){best_common=shorttext2.substring(j2-suffixLength,j2)+shorttext2.substring(j2,j2+prefixLength);best_longtext_a=longtext2.substring(0,i3-suffixLength);best_longtext_b=longtext2.substring(i3+prefixLength);best_shorttext_a=shorttext2.substring(0,j2-suffixLength);best_shorttext_b=shorttext2.substring(j2+prefixLength)}}return 2*best_common.length>=longtext2.length?[best_longtext_a,best_longtext_b,best_shorttext_a,best_shorttext_b,best_common]:null}var longtext,shorttext,dmp,hm1,hm2,hm,text1_a,text1_b,text2_a,text2_b,mid_common;if(this.Diff_Timeout<=0)return null;longtext=text1.length>text2.length?text1:text2;shorttext=text1.length>text2.length?text2:text1;if(longtext.length<4||2*shorttext.length<longtext.length)return null;dmp=this;hm1=diff_halfMatchI_(longtext,shorttext,Math.ceil(longtext.length/4));hm2=diff_halfMatchI_(longtext,shorttext,Math.ceil(longtext.length/2));if(!hm1&&!hm2)return null;hm=hm2?hm1&&hm1[4].length>hm2[4].length?hm1:hm2:hm1;if(text1.length>text2.length){text1_a=hm[0];text1_b=hm[1];text2_a=hm[2];text2_b=hm[3]}else{text2_a=hm[0];text2_b=hm[1];text1_a=hm[2];text1_b=hm[3]}mid_common=hm[4];return[text1_a,text1_b,text2_a,text2_b,mid_common]};diff_match_patch4.prototype.diff_cleanupSemantic=function(diffs){for(var deletion,insertion,overlap_length1,overlap_length2,changes3=!1,equalities=[],equalitiesLength=0,lastEquality=null,pointer=0,length_insertions1=0,length_deletions1=0,length_insertions2=0,length_deletions2=0;pointer<diffs.length;){if(diffs[pointer][0]==DIFF_EQUAL4){equalities[equalitiesLength++]=pointer;length_insertions1=length_insertions2;length_deletions1=length_deletions2;length_insertions2=0;length_deletions2=0;lastEquality=diffs[pointer][1]}else{diffs[pointer][0]==DIFF_INSERT4?length_insertions2+=diffs[pointer][1].length:length_deletions2+=diffs[pointer][1].length;if(lastEquality&&lastEquality.length<=Math.max(length_insertions1,length_deletions1)&&lastEquality.length<=Math.max(length_insertions2,length_deletions2)){diffs.splice(equalities[equalitiesLength-1],0,new diff_match_patch4.Diff(DIFF_DELETE4,lastEquality));diffs[equalities[equalitiesLength-1]+1][0]=DIFF_INSERT4;equalitiesLength--;equalitiesLength--;pointer=equalitiesLength>0?equalities[equalitiesLength-1]:-1;length_insertions1=0;length_deletions1=0;length_insertions2=0;length_deletions2=0;lastEquality=null;changes3=!0}}pointer++}changes3&&this.diff_cleanupMerge(diffs);this.diff_cleanupSemanticLossless(diffs);pointer=1;for(;pointer<diffs.length;){if(diffs[pointer-1][0]==DIFF_DELETE4&&diffs[pointer][0]==DIFF_INSERT4){deletion=diffs[pointer-1][1];insertion=diffs[pointer][1];overlap_length1=this.diff_commonOverlap_(deletion,insertion);overlap_length2=this.diff_commonOverlap_(insertion,deletion);if(overlap_length1>=overlap_length2){if(overlap_length1>=deletion.length/2||overlap_length1>=insertion.length/2){diffs.splice(pointer,0,new diff_match_patch4.Diff(DIFF_EQUAL4,insertion.substring(0,overlap_length1)));diffs[pointer-1][1]=deletion.substring(0,deletion.length-overlap_length1);diffs[pointer+1][1]=insertion.substring(overlap_length1);pointer++}}else if(overlap_length2>=deletion.length/2||overlap_length2>=insertion.length/2){diffs.splice(pointer,0,new diff_match_patch4.Diff(DIFF_EQUAL4,deletion.substring(0,overlap_length2)));diffs[pointer-1][0]=DIFF_INSERT4;diffs[pointer-1][1]=insertion.substring(0,insertion.length-overlap_length2);diffs[pointer+1][0]=DIFF_DELETE4;diffs[pointer+1][1]=deletion.substring(overlap_length2);pointer++}pointer++}pointer++}};diff_match_patch4.prototype.diff_cleanupSemanticLossless=function(diffs){function diff_cleanupSemanticScore_(one,two){var char1,char2,nonAlphaNumeric1,nonAlphaNumeric2,whitespace1,whitespace2,lineBreak1,lineBreak2,blankLine1,blankLine2;if(!one||!two)return 6;char1=one.charAt(one.length-1);char2=two.charAt(0);nonAlphaNumeric1=char1.match(diff_match_patch4.nonAlphaNumericRegex_);nonAlphaNumeric2=char2.match(diff_match_patch4.nonAlphaNumericRegex_);whitespace1=nonAlphaNumeric1&&char1.match(diff_match_patch4.whitespaceRegex_);whitespace2=nonAlphaNumeric2&&char2.match(diff_match_patch4.whitespaceRegex_);lineBreak1=whitespace1&&char1.match(diff_match_patch4.linebreakRegex_);lineBreak2=whitespace2&&char2.match(diff_match_patch4.linebreakRegex_);blankLine1=lineBreak1&&one.match(diff_match_patch4.blanklineEndRegex_);blankLine2=lineBreak2&&two.match(diff_match_patch4.blanklineStartRegex_);return blankLine1||blankLine2?5:lineBreak1||lineBreak2?4:nonAlphaNumeric1&&!whitespace1&&whitespace2?3:whitespace1||whitespace2?2:nonAlphaNumeric1||nonAlphaNumeric2?1:0}for(var equality1,edit,equality2,commonOffset,commonString,bestEquality1,bestEdit,bestEquality2,bestScore,score,pointer=1;pointer<diffs.length-1;){if(diffs[pointer-1][0]==DIFF_EQUAL4&&diffs[pointer+1][0]==DIFF_EQUAL4){equality1=diffs[pointer-1][1];edit=diffs[pointer][1];equality2=diffs[pointer+1][1];commonOffset=this.diff_commonSuffix(equality1,edit);if(commonOffset){commonString=edit.substring(edit.length-commonOffset);equality1=equality1.substring(0,equality1.length-commonOffset);edit=commonString+edit.substring(0,edit.length-commonOffset);equality2=commonString+equality2}bestEquality1=equality1;bestEdit=edit;bestEquality2=equality2;bestScore=diff_cleanupSemanticScore_(equality1,edit)+diff_cleanupSemanticScore_(edit,equality2);for(;edit.charAt(0)===equality2.charAt(0);){equality1+=edit.charAt(0);edit=edit.substring(1)+equality2.charAt(0);equality2=equality2.substring(1);score=diff_cleanupSemanticScore_(equality1,edit)+diff_cleanupSemanticScore_(edit,equality2);if(score>=bestScore){bestScore=score;bestEquality1=equality1;bestEdit=edit;bestEquality2=equality2}}if(diffs[pointer-1][1]!=bestEquality1){if(bestEquality1)diffs[pointer-1][1]=bestEquality1;else{diffs.splice(pointer-1,1);pointer--}diffs[pointer][1]=bestEdit;if(bestEquality2)diffs[pointer+1][1]=bestEquality2;else{diffs.splice(pointer+1,1);pointer--}}}pointer++}};diff_match_patch4.nonAlphaNumericRegex_=/[^a-zA-Z0-9]/;diff_match_patch4.whitespaceRegex_=/\s/;diff_match_patch4.linebreakRegex_=/[\r\n]/;diff_match_patch4.blanklineEndRegex_=/\n\r?\n$/;diff_match_patch4.blanklineStartRegex_=/^\r?\n\r?\n/;diff_match_patch4.prototype.diff_cleanupEfficiency=function(diffs){for(var changes3=!1,equalities=[],equalitiesLength=0,lastEquality=null,pointer=0,pre_ins=!1,pre_del=!1,post_ins=!1,post_del=!1;pointer<diffs.length;){if(diffs[pointer][0]==DIFF_EQUAL4){if(diffs[pointer][1].length<this.Diff_EditCost&&(post_ins||post_del)){equalities[equalitiesLength++]=pointer;pre_ins=post_ins;pre_del=post_del;lastEquality=diffs[pointer][1]}else{equalitiesLength=0;lastEquality=null}post_ins=post_del=!1}else{diffs[pointer][0]==DIFF_DELETE4?post_del=!0:post_ins=!0;if(lastEquality&&(pre_ins&&pre_del&&post_ins&&post_del||lastEquality.length<this.Diff_EditCost/2&&pre_ins+pre_del+post_ins+post_del==3)){diffs.splice(equalities[equalitiesLength-1],0,new diff_match_patch4.Diff(DIFF_DELETE4,lastEquality));diffs[equalities[equalitiesLength-1]+1][0]=DIFF_INSERT4;equalitiesLength--;lastEquality=null;if(pre_ins&&pre_del){post_ins=post_del=!0;equalitiesLength=0}else{equalitiesLength--;pointer=equalitiesLength>0?equalities[equalitiesLength-1]:-1;post_ins=post_del=!1}changes3=!0}}pointer++}changes3&&this.diff_cleanupMerge(diffs)};diff_match_patch4.prototype.diff_cleanupMerge=function(diffs){var pointer,count_delete,count_insert,text_delete,text_insert,commonlength,changes3;diffs.push(new diff_match_patch4.Diff(DIFF_EQUAL4,""));pointer=0;count_delete=0;count_insert=0;text_delete="";text_insert="";for(;pointer<diffs.length;)switch(diffs[pointer][0]){case DIFF_INSERT4:count_insert++;text_insert+=diffs[pointer][1];pointer++;break;case DIFF_DELETE4:count_delete++;text_delete+=diffs[pointer][1];pointer++;break;case DIFF_EQUAL4:if(count_delete+count_insert>1){if(0!==count_delete&&0!==count_insert){commonlength=this.diff_commonPrefix(text_insert,text_delete);if(0!==commonlength){if(pointer-count_delete-count_insert>0&&diffs[pointer-count_delete-count_insert-1][0]==DIFF_EQUAL4)diffs[pointer-count_delete-count_insert-1][1]+=text_insert.substring(0,commonlength);else{diffs.splice(0,0,new diff_match_patch4.Diff(DIFF_EQUAL4,text_insert.substring(0,commonlength)));pointer++}text_insert=text_insert.substring(commonlength);text_delete=text_delete.substring(commonlength)}commonlength=this.diff_commonSuffix(text_insert,text_delete);if(0!==commonlength){diffs[pointer][1]=text_insert.substring(text_insert.length-commonlength)+diffs[pointer][1];text_insert=text_insert.substring(0,text_insert.length-commonlength);text_delete=text_delete.substring(0,text_delete.length-commonlength)}}pointer-=count_delete+count_insert;diffs.splice(pointer,count_delete+count_insert);if(text_delete.length){diffs.splice(pointer,0,new diff_match_patch4.Diff(DIFF_DELETE4,text_delete));pointer++}if(text_insert.length){diffs.splice(pointer,0,new diff_match_patch4.Diff(DIFF_INSERT4,text_insert));pointer++}pointer++}else if(0!==pointer&&diffs[pointer-1][0]==DIFF_EQUAL4){diffs[pointer-1][1]+=diffs[pointer][1];diffs.splice(pointer,1)}else pointer++;count_insert=0;count_delete=0;text_delete="";text_insert="";break}""===diffs[diffs.length-1][1]&&diffs.pop();changes3=!1;pointer=1;for(;pointer<diffs.length-1;){if(diffs[pointer-1][0]==DIFF_EQUAL4&&diffs[pointer+1][0]==DIFF_EQUAL4)if(diffs[pointer][1].substring(diffs[pointer][1].length-diffs[pointer-1][1].length)==diffs[pointer-1][1]){diffs[pointer][1]=diffs[pointer-1][1]+diffs[pointer][1].substring(0,diffs[pointer][1].length-diffs[pointer-1][1].length);diffs[pointer+1][1]=diffs[pointer-1][1]+diffs[pointer+1][1];diffs.splice(pointer-1,1);changes3=!0}else if(diffs[pointer][1].substring(0,diffs[pointer+1][1].length)==diffs[pointer+1][1]){diffs[pointer-1][1]+=diffs[pointer+1][1];diffs[pointer][1]=diffs[pointer][1].substring(diffs[pointer+1][1].length)+diffs[pointer+1][1];diffs.splice(pointer+1,1);changes3=!0}pointer++}changes3&&this.diff_cleanupMerge(diffs)};diff_match_patch4.prototype.diff_xIndex=function(diffs,loc){var x3,chars1=0,chars22=0,last_chars1=0,last_chars2=0;for(x3=0;x3<diffs.length;x3++){diffs[x3][0]!==DIFF_INSERT4&&(chars1+=diffs[x3][1].length);diffs[x3][0]!==DIFF_DELETE4&&(chars22+=diffs[x3][1].length);if(chars1>loc)break;last_chars1=chars1;last_chars2=chars22}return diffs.length!=x3&&diffs[x3][0]===DIFF_DELETE4?last_chars2:last_chars2+(loc-last_chars1)};diff_match_patch4.prototype.diff_prettyHtml=function(diffs){var x3,op,data,text2,html2=[],pattern_amp=/&/g,pattern_lt=/</g,pattern_gt=/>/g,pattern_para=/\n/g;for(x3=0;x3<diffs.length;x3++){op=diffs[x3][0];data=diffs[x3][1];text2=data.replace(pattern_amp,"&amp;").replace(pattern_lt,"&lt;").replace(pattern_gt,"&gt;").replace(pattern_para,"&para;<br>");switch(op){case DIFF_INSERT4:html2[x3]='<ins style="background:#e6ffe6;">'+text2+"</ins>";break;case DIFF_DELETE4:html2[x3]='<del style="background:#ffe6e6;">'+text2+"</del>";break;case DIFF_EQUAL4:html2[x3]="<span>"+text2+"</span>";break}}return html2.join("")};diff_match_patch4.prototype.diff_text1=function(diffs){var x3,text2=[];for(x3=0;x3<diffs.length;x3++)diffs[x3][0]!==DIFF_INSERT4&&(text2[x3]=diffs[x3][1]);return text2.join("")};diff_match_patch4.prototype.diff_text2=function(diffs){var x3,text2=[];for(x3=0;x3<diffs.length;x3++)diffs[x3][0]!==DIFF_DELETE4&&(text2[x3]=diffs[x3][1]);return text2.join("")};diff_match_patch4.prototype.diff_levenshtein=function(diffs){var x3,op,data,levenshtein=0,insertions=0,deletions=0;for(x3=0;x3<diffs.length;x3++){op=diffs[x3][0];data=diffs[x3][1];switch(op){case DIFF_INSERT4:insertions+=data.length;break;case DIFF_DELETE4:deletions+=data.length;break;case DIFF_EQUAL4:levenshtein+=Math.max(insertions,deletions);insertions=0;deletions=0;break}}levenshtein+=Math.max(insertions,deletions);return levenshtein};diff_match_patch4.prototype.diff_toDelta=function(diffs){var x3,text2=[];for(x3=0;x3<diffs.length;x3++)switch(diffs[x3][0]){case DIFF_INSERT4:text2[x3]="+"+encodeURI(diffs[x3][1]);break;case DIFF_DELETE4:text2[x3]="-"+diffs[x3][1].length;break;case DIFF_EQUAL4:text2[x3]="="+diffs[x3][1].length;break}return text2.join("\t").replace(/%20/g," ")};diff_match_patch4.prototype.diff_fromDelta=function(text1,delta){var x3,param,n3,text2,diffs=[],diffsLength=0,pointer=0,tokens=delta.split(/\t/g);for(x3=0;x3<tokens.length;x3++){param=tokens[x3].substring(1);switch(tokens[x3].charAt(0)){case"+":try{diffs[diffsLength++]=new diff_match_patch4.Diff(DIFF_INSERT4,decodeURI(param))}catch(ex){throw new Error("Illegal escape in diff_fromDelta: "+param)}break;case"-":case"=":n3=parseInt(param,10);if(isNaN(n3)||n3<0)throw new Error("Invalid number in diff_fromDelta: "+param);text2=text1.substring(pointer,pointer+=n3);"="==tokens[x3].charAt(0)?diffs[diffsLength++]=new diff_match_patch4.Diff(DIFF_EQUAL4,text2):diffs[diffsLength++]=new diff_match_patch4.Diff(DIFF_DELETE4,text2);break;default:if(tokens[x3])throw new Error("Invalid diff operation in diff_fromDelta: "+tokens[x3])}}if(pointer!=text1.length)throw new Error("Delta length ("+pointer+") does not equal source text length ("+text1.length+").");return diffs};diff_match_patch4.prototype.match_main=function(text2,pattern,loc){if(null==text2||null==pattern||null==loc)throw new Error("Null input. (match_main)");loc=Math.max(0,Math.min(loc,text2.length));return text2==pattern?0:text2.length?text2.substring(loc,loc+pattern.length)==pattern?loc:this.match_bitap_(text2,pattern,loc):-1};diff_match_patch4.prototype.match_bitap_=function(text2,pattern,loc){function match_bitapScore_(e3,x3){var accuracy=e3/pattern.length,proximity=Math.abs(loc-x3);return dmp.Match_Distance?accuracy+proximity/dmp.Match_Distance:proximity?1:accuracy}var s2,dmp,score_threshold,best_loc,matchmask,bin_min,bin_mid,bin_max,last_rd,d4,start,finish,rd,j2,charMatch,score;if(pattern.length>this.Match_MaxBits)throw new Error("Pattern too long for this browser.");s2=this.match_alphabet_(pattern);dmp=this;score_threshold=this.Match_Threshold;best_loc=text2.indexOf(pattern,loc);if(-1!=best_loc){score_threshold=Math.min(match_bitapScore_(0,best_loc),score_threshold);best_loc=text2.lastIndexOf(pattern,loc+pattern.length);-1!=best_loc&&(score_threshold=Math.min(match_bitapScore_(0,best_loc),score_threshold))}matchmask=1<<pattern.length-1;best_loc=-1;bin_max=pattern.length+text2.length;for(d4=0;d4<pattern.length;d4++){bin_min=0;bin_mid=bin_max;for(;bin_min<bin_mid;){match_bitapScore_(d4,loc+bin_mid)<=score_threshold?bin_min=bin_mid:bin_max=bin_mid;bin_mid=Math.floor((bin_max-bin_min)/2+bin_min)}bin_max=bin_mid;start=Math.max(1,loc-bin_mid+1);finish=Math.min(loc+bin_mid,text2.length)+pattern.length;rd=Array(finish+2);rd[finish+1]=(1<<d4)-1;for(j2=finish;j2>=start;j2--){charMatch=s2[text2.charAt(j2-1)];rd[j2]=0===d4?(rd[j2+1]<<1|1)&charMatch:(rd[j2+1]<<1|1)&charMatch|(last_rd[j2+1]|last_rd[j2])<<1|1|last_rd[j2+1];if(rd[j2]&matchmask){score=match_bitapScore_(d4,j2-1);if(score<=score_threshold){score_threshold=score;best_loc=j2-1;if(!(best_loc>loc))break;start=Math.max(1,2*loc-best_loc)}}}if(match_bitapScore_(d4+1,loc)>score_threshold)break;last_rd=rd}return best_loc};diff_match_patch4.prototype.match_alphabet_=function(pattern){var i3,s2={};for(i3=0;i3<pattern.length;i3++)s2[pattern.charAt(i3)]=0;for(i3=0;i3<pattern.length;i3++)s2[pattern.charAt(i3)]|=1<<pattern.length-i3-1;return s2};diff_match_patch4.prototype.patch_addContext_=function(patch,text2){var pattern,padding,prefix,suffix;if(0!=text2.length){if(null===patch.start2)throw Error("patch not initialized");pattern=text2.substring(patch.start2,patch.start2+patch.length1);padding=0;for(;text2.indexOf(pattern)!=text2.lastIndexOf(pattern)&&pattern.length<this.Match_MaxBits-this.Patch_Margin-this.Patch_Margin;){padding+=this.Patch_Margin;pattern=text2.substring(patch.start2-padding,patch.start2+patch.length1+padding)}padding+=this.Patch_Margin;prefix=text2.substring(patch.start2-padding,patch.start2);prefix&&patch.diffs.unshift(new diff_match_patch4.Diff(DIFF_EQUAL4,prefix));suffix=text2.substring(patch.start2+patch.length1,patch.start2+patch.length1+padding);suffix&&patch.diffs.push(new diff_match_patch4.Diff(DIFF_EQUAL4,suffix));patch.start1-=prefix.length;patch.start2-=prefix.length;patch.length1+=prefix.length+suffix.length;patch.length2+=prefix.length+suffix.length}};diff_match_patch4.prototype.patch_make=function(a2,opt_b,opt_c){var text1,diffs,patches,patch,patchDiffLength,char_count1,char_count2,prepatch_text,postpatch_text,x3,diff_type,diff_text;if("string"==typeof a2&&"string"==typeof opt_b&&void 0===opt_c){text1=a2;diffs=this.diff_main(text1,opt_b,!0);if(diffs.length>2){this.diff_cleanupSemantic(diffs);this.diff_cleanupEfficiency(diffs)}}else if(a2&&"object"==typeof a2&&void 0===opt_b&&void 0===opt_c){diffs=a2;text1=this.diff_text1(diffs)}else if("string"==typeof a2&&opt_b&&"object"==typeof opt_b&&void 0===opt_c){text1=a2;diffs=opt_b}else{if("string"!=typeof a2||"string"!=typeof opt_b||!opt_c||"object"!=typeof opt_c)throw new Error("Unknown call format to patch_make.");text1=a2;diffs=opt_c}if(0===diffs.length)return[];patches=[];patch=new diff_match_patch4.patch_obj;patchDiffLength=0;char_count1=0;char_count2=0;prepatch_text=text1;postpatch_text=text1;for(x3=0;x3<diffs.length;x3++){diff_type=diffs[x3][0];diff_text=diffs[x3][1];if(!patchDiffLength&&diff_type!==DIFF_EQUAL4){patch.start1=char_count1;patch.start2=char_count2}switch(diff_type){case DIFF_INSERT4:patch.diffs[patchDiffLength++]=diffs[x3];patch.length2+=diff_text.length;postpatch_text=postpatch_text.substring(0,char_count2)+diff_text+postpatch_text.substring(char_count2);break;case DIFF_DELETE4:patch.length1+=diff_text.length;patch.diffs[patchDiffLength++]=diffs[x3];postpatch_text=postpatch_text.substring(0,char_count2)+postpatch_text.substring(char_count2+diff_text.length);break;case DIFF_EQUAL4:if(diff_text.length<=2*this.Patch_Margin&&patchDiffLength&&diffs.length!=x3+1){patch.diffs[patchDiffLength++]=diffs[x3];patch.length1+=diff_text.length;patch.length2+=diff_text.length}else if(diff_text.length>=2*this.Patch_Margin&&patchDiffLength){this.patch_addContext_(patch,prepatch_text);patches.push(patch);patch=new diff_match_patch4.patch_obj;patchDiffLength=0;prepatch_text=postpatch_text;char_count1=char_count2}break}diff_type!==DIFF_INSERT4&&(char_count1+=diff_text.length);diff_type!==DIFF_DELETE4&&(char_count2+=diff_text.length)}if(patchDiffLength){this.patch_addContext_(patch,prepatch_text);patches.push(patch)}return patches};diff_match_patch4.prototype.patch_deepCopy=function(patches){var x3,patch,patchCopy,y2,patchesCopy=[];for(x3=0;x3<patches.length;x3++){patch=patches[x3];patchCopy=new diff_match_patch4.patch_obj;patchCopy.diffs=[];for(y2=0;y2<patch.diffs.length;y2++)patchCopy.diffs[y2]=new diff_match_patch4.Diff(patch.diffs[y2][0],patch.diffs[y2][1]);patchCopy.start1=patch.start1;patchCopy.start2=patch.start2;patchCopy.length1=patch.length1;patchCopy.length2=patch.length2;patchesCopy[x3]=patchCopy}return patchesCopy};diff_match_patch4.prototype.patch_apply=function(patches,text2){var nullPadding,delta,results,x3,expected_loc,text1,start_loc,end_loc,text22,diffs,index1,index22,y2,mod;if(0==patches.length)return[text2,[]];patches=this.patch_deepCopy(patches);nullPadding=this.patch_addPadding(patches);text2=nullPadding+text2+nullPadding;this.patch_splitMax(patches);delta=0;results=[];for(x3=0;x3<patches.length;x3++){expected_loc=patches[x3].start2+delta;text1=this.diff_text1(patches[x3].diffs);end_loc=-1;if(text1.length>this.Match_MaxBits){start_loc=this.match_main(text2,text1.substring(0,this.Match_MaxBits),expected_loc);if(-1!=start_loc){end_loc=this.match_main(text2,text1.substring(text1.length-this.Match_MaxBits),expected_loc+text1.length-this.Match_MaxBits);(-1==end_loc||start_loc>=end_loc)&&(start_loc=-1)}}else start_loc=this.match_main(text2,text1,expected_loc);if(-1==start_loc){results[x3]=!1;delta-=patches[x3].length2-patches[x3].length1}else{results[x3]=!0;delta=start_loc-expected_loc;text22=-1==end_loc?text2.substring(start_loc,start_loc+text1.length):text2.substring(start_loc,end_loc+this.Match_MaxBits);if(text1==text22)text2=text2.substring(0,start_loc)+this.diff_text2(patches[x3].diffs)+text2.substring(start_loc+text1.length);else{diffs=this.diff_main(text1,text22,!1);if(text1.length>this.Match_MaxBits&&this.diff_levenshtein(diffs)/text1.length>this.Patch_DeleteThreshold)results[x3]=!1;else{this.diff_cleanupSemanticLossless(diffs);index1=0;for(y2=0;y2<patches[x3].diffs.length;y2++){mod=patches[x3].diffs[y2];mod[0]!==DIFF_EQUAL4&&(index22=this.diff_xIndex(diffs,index1));mod[0]===DIFF_INSERT4?text2=text2.substring(0,start_loc+index22)+mod[1]+text2.substring(start_loc+index22):mod[0]===DIFF_DELETE4&&(text2=text2.substring(0,start_loc+index22)+text2.substring(start_loc+this.diff_xIndex(diffs,index1+mod[1].length)));mod[0]!==DIFF_DELETE4&&(index1+=mod[1].length)}}}}}text2=text2.substring(nullPadding.length,text2.length-nullPadding.length);return[text2,results]};diff_match_patch4.prototype.patch_addPadding=function(patches){var x3,patch,diffs,extraLength,paddingLength=this.Patch_Margin,nullPadding="";for(x3=1;x3<=paddingLength;x3++)nullPadding+=String.fromCharCode(x3);for(x3=0;x3<patches.length;x3++){patches[x3].start1+=paddingLength;patches[x3].start2+=paddingLength}patch=patches[0];diffs=patch.diffs;if(0==diffs.length||diffs[0][0]!=DIFF_EQUAL4){diffs.unshift(new diff_match_patch4.Diff(DIFF_EQUAL4,nullPadding));patch.start1-=paddingLength;patch.start2-=paddingLength;patch.length1+=paddingLength;patch.length2+=paddingLength}else if(paddingLength>diffs[0][1].length){extraLength=paddingLength-diffs[0][1].length;diffs[0][1]=nullPadding.substring(diffs[0][1].length)+diffs[0][1];patch.start1-=extraLength;patch.start2-=extraLength;patch.length1+=extraLength;patch.length2+=extraLength}patch=patches[patches.length-1];diffs=patch.diffs;if(0==diffs.length||diffs[diffs.length-1][0]!=DIFF_EQUAL4){diffs.push(new diff_match_patch4.Diff(DIFF_EQUAL4,nullPadding));patch.length1+=paddingLength;patch.length2+=paddingLength}else if(paddingLength>diffs[diffs.length-1][1].length){extraLength=paddingLength-diffs[diffs.length-1][1].length;diffs[diffs.length-1][1]+=nullPadding.substring(0,extraLength);patch.length1+=extraLength;patch.length2+=extraLength}return nullPadding};diff_match_patch4.prototype.patch_splitMax=function(patches){var x3,bigpatch,start1,start2,precontext,patch,empty2,diff_type,diff_text,postcontext,patch_size=this.Match_MaxBits;for(x3=0;x3<patches.length;x3++)if(!(patches[x3].length1<=patch_size)){bigpatch=patches[x3];patches.splice(x3--,1);start1=bigpatch.start1;start2=bigpatch.start2;precontext="";for(;0!==bigpatch.diffs.length;){patch=new diff_match_patch4.patch_obj;empty2=!0;patch.start1=start1-precontext.length;patch.start2=start2-precontext.length;if(""!==precontext){patch.length1=patch.length2=precontext.length;patch.diffs.push(new diff_match_patch4.Diff(DIFF_EQUAL4,precontext))}for(;0!==bigpatch.diffs.length&&patch.length1<patch_size-this.Patch_Margin;){diff_type=bigpatch.diffs[0][0];diff_text=bigpatch.diffs[0][1];if(diff_type===DIFF_INSERT4){patch.length2+=diff_text.length;start2+=diff_text.length;patch.diffs.push(bigpatch.diffs.shift());empty2=!1}else if(diff_type===DIFF_DELETE4&&1==patch.diffs.length&&patch.diffs[0][0]==DIFF_EQUAL4&&diff_text.length>2*patch_size){patch.length1+=diff_text.length;start1+=diff_text.length;empty2=!1;patch.diffs.push(new diff_match_patch4.Diff(diff_type,diff_text));bigpatch.diffs.shift()}else{diff_text=diff_text.substring(0,patch_size-patch.length1-this.Patch_Margin);patch.length1+=diff_text.length;start1+=diff_text.length;if(diff_type===DIFF_EQUAL4){patch.length2+=diff_text.length;start2+=diff_text.length}else empty2=!1;patch.diffs.push(new diff_match_patch4.Diff(diff_type,diff_text));diff_text==bigpatch.diffs[0][1]?bigpatch.diffs.shift():bigpatch.diffs[0][1]=bigpatch.diffs[0][1].substring(diff_text.length)}}precontext=this.diff_text2(patch.diffs);precontext=precontext.substring(precontext.length-this.Patch_Margin);postcontext=this.diff_text1(bigpatch.diffs).substring(0,this.Patch_Margin);if(""!==postcontext){patch.length1+=postcontext.length;patch.length2+=postcontext.length;0!==patch.diffs.length&&patch.diffs[patch.diffs.length-1][0]===DIFF_EQUAL4?patch.diffs[patch.diffs.length-1][1]+=postcontext:patch.diffs.push(new diff_match_patch4.Diff(DIFF_EQUAL4,postcontext))}empty2||patches.splice(++x3,0,patch)}}};diff_match_patch4.prototype.patch_toText=function(patches){var x3,text2=[];for(x3=0;x3<patches.length;x3++)text2[x3]=patches[x3];return text2.join("")};diff_match_patch4.prototype.patch_fromText=function(textline){var text2,textPointer,patchHeader,m3,patch,sign2,line,patches=[];if(!textline)return patches;text2=textline.split("\n");textPointer=0;patchHeader=/^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/;for(;textPointer<text2.length;){m3=text2[textPointer].match(patchHeader);if(!m3)throw new Error("Invalid patch string: "+text2[textPointer]);patch=new diff_match_patch4.patch_obj;patches.push(patch);patch.start1=parseInt(m3[1],10);if(""===m3[2]){patch.start1--;patch.length1=1}else if("0"==m3[2])patch.length1=0;else{patch.start1--;patch.length1=parseInt(m3[2],10)}patch.start2=parseInt(m3[3],10);if(""===m3[4]){patch.start2--;patch.length2=1}else if("0"==m3[4])patch.length2=0;else{patch.start2--;patch.length2=parseInt(m3[4],10)}textPointer++;for(;textPointer<text2.length;){sign2=text2[textPointer].charAt(0);try{line=decodeURI(text2[textPointer].substring(1))}catch(ex){throw new Error("Illegal escape in patch_fromText: "+line)}if("-"==sign2)patch.diffs.push(new diff_match_patch4.Diff(DIFF_DELETE4,line));else if("+"==sign2)patch.diffs.push(new diff_match_patch4.Diff(DIFF_INSERT4,line));else if(" "==sign2)patch.diffs.push(new diff_match_patch4.Diff(DIFF_EQUAL4,line));else{if("@"==sign2)break;if(""!==sign2)throw new Error('Invalid patch mode "'+sign2+'" in: '+line)}textPointer++}}return patches};diff_match_patch4.patch_obj=function(){this.diffs=[];this.start1=null;this.start2=null;this.length1=0;this.length2=0};diff_match_patch4.patch_obj.prototype.toString=function(){var coords1,coords2,text2,op,x3;coords1=0===this.length1?this.start1+",0":1==this.length1?this.start1+1:this.start1+1+","+this.length1;coords2=0===this.length2?this.start2+",0":1==this.length2?this.start2+1:this.start2+1+","+this.length2;text2=["@@ -"+coords1+" +"+coords2+" @@\n"];for(x3=0;x3<this.diffs.length;x3++){switch(this.diffs[x3][0]){case DIFF_INSERT4:op="+";break;case DIFF_DELETE4:op="-";break;case DIFF_EQUAL4:op=" ";break}text2[x3+1]=op+encodeURI(this.diffs[x3][1])+"\n"}return text2.join("").replace(/%20/g," ")};module2.exports=diff_match_patch4;module2.exports.diff_match_patch=diff_match_patch4;module2.exports.DIFF_DELETE=DIFF_DELETE4;module2.exports.DIFF_INSERT=DIFF_INSERT4;module2.exports.DIFF_EQUAL=DIFF_EQUAL4}}),require_events=__commonJS({"node_modules/events/events.js"(exports,module2){"use strict";function ProcessEmitWarning(warning){console&&console.warn&&console.warn(warning)}function EventEmitter3(){EventEmitter3.init.call(this)}function checkListener(listener){if("function"!=typeof listener)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof listener)}function _getMaxListeners(that){return void 0===that._maxListeners?EventEmitter3.defaultMaxListeners:that._maxListeners}function _addListener(target,type,listener,prepend){var m3,events,existing,w2;checkListener(listener);events=target._events;if(void 0===events){events=target._events=Object.create(null);target._eventsCount=0}else{if(void 0!==events.newListener){target.emit("newListener",type,listener.listener?listener.listener:listener);events=target._events}existing=events[type]}if(void 0===existing){existing=events[type]=listener;++target._eventsCount}else{"function"==typeof existing?existing=events[type]=prepend?[listener,existing]:[existing,listener]:prepend?existing.unshift(listener):existing.push(listener);m3=_getMaxListeners(target);if(m3>0&&existing.length>m3&&!existing.warned){existing.warned=!0;w2=new Error("Possible EventEmitter memory leak detected. "+existing.length+" "+String(type)+" listeners added. Use emitter.setMaxListeners() to increase limit");w2.name="MaxListenersExceededWarning";w2.emitter=target;w2.type=type;w2.count=existing.length;ProcessEmitWarning(w2)}}return target}function onceWrapper(){if(!this.fired){this.target.removeListener(this.type,this.wrapFn);this.fired=!0;return 0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}}function _onceWrap(target,type,listener){var state2={fired:!1,wrapFn:void 0,target,type,listener},wrapped=onceWrapper.bind(state2);wrapped.listener=listener;state2.wrapFn=wrapped;return wrapped}function _listeners2(target,type,unwrap2){var evlistener,events=target._events;if(void 0===events)return[];evlistener=events[type];return void 0===evlistener?[]:"function"==typeof evlistener?unwrap2?[evlistener.listener||evlistener]:[evlistener]:unwrap2?unwrapListeners(evlistener):arrayClone(evlistener,evlistener.length)}function listenerCount2(type){var evlistener,events=this._events;if(void 0!==events){evlistener=events[type];if("function"==typeof evlistener)return 1;if(void 0!==evlistener)return evlistener.length}return 0}function arrayClone(arr,n3){var i3,copy=new Array(n3);for(i3=0;i3<n3;++i3)copy[i3]=arr[i3];return copy}function spliceOne(list,index6){for(;index6+1<list.length;index6++)list[index6]=list[index6+1];list.pop()}function unwrapListeners(arr){var i3,ret=new Array(arr.length);for(i3=0;i3<ret.length;++i3)ret[i3]=arr[i3].listener||arr[i3];return ret}function addErrorHandlerIfEventEmitter(emitter,handler,flags2){"function"==typeof emitter.on&&eventTargetAgnosticAddListener(emitter,"error",handler,flags2)}function eventTargetAgnosticAddListener(emitter,name,listener,flags2){if("function"==typeof emitter.on)flags2.once?emitter.once(name,listener):emitter.on(name,listener);else{if("function"!=typeof emitter.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof emitter);emitter.addEventListener(name,function wrapListener(arg){flags2.once&&emitter.removeEventListener(name,wrapListener);listener(arg)})}}var ReflectOwnKeys,NumberIsNaN,defaultMaxListeners,R2="object"==typeof Reflect?Reflect:null,ReflectApply=R2&&"function"==typeof R2.apply?R2.apply:function ReflectApply2(target,receiver,args){return Function.prototype.apply.call(target,receiver,args)};ReflectOwnKeys=R2&&"function"==typeof R2.ownKeys?R2.ownKeys:Object.getOwnPropertySymbols?function ReflectOwnKeys2(target){return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target))}:function ReflectOwnKeys2(target){return Object.getOwnPropertyNames(target)};NumberIsNaN=Number.isNaN||function NumberIsNaN2(value){return value!=value};module2.exports=EventEmitter3;module2.exports.once=function once3(emitter,name){return new Promise(function(resolve,reject){function errorListener(err3){emitter.removeListener(name,resolver2);reject(err3)}function resolver2(){"function"==typeof emitter.removeListener&&emitter.removeListener("error",errorListener);resolve([].slice.call(arguments))}eventTargetAgnosticAddListener(emitter,name,resolver2,{once:!0});"error"!==name&&addErrorHandlerIfEventEmitter(emitter,errorListener,{once:!0})})};EventEmitter3.EventEmitter=EventEmitter3;EventEmitter3.prototype._events=void 0;EventEmitter3.prototype._eventsCount=0;EventEmitter3.prototype._maxListeners=void 0;defaultMaxListeners=10;Object.defineProperty(EventEmitter3,"defaultMaxListeners",{enumerable:!0,get:function(){return defaultMaxListeners},set:function(arg){if("number"!=typeof arg||arg<0||NumberIsNaN(arg))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+arg+".");defaultMaxListeners=arg}});EventEmitter3.init=function(){if(void 0===this._events||this._events===Object.getPrototypeOf(this)._events){this._events=Object.create(null);this._eventsCount=0}this._maxListeners=this._maxListeners||void 0};EventEmitter3.prototype.setMaxListeners=function setMaxListeners(n3){if("number"!=typeof n3||n3<0||NumberIsNaN(n3))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+n3+".");this._maxListeners=n3;return this};EventEmitter3.prototype.getMaxListeners=function getMaxListeners(){return _getMaxListeners(this)};EventEmitter3.prototype.emit=function emit2(type){var i3,doError,events,er,err3,handler,len,listeners2,args=[];for(i3=1;i3<arguments.length;i3++)args.push(arguments[i3]);doError="error"===type;events=this._events;if(void 0!==events)doError=doError&&void 0===events.error;else if(!doError)return!1;if(doError){args.length>0&&(er=args[0]);if(er instanceof Error)throw er;err3=new Error("Unhandled error."+(er?" ("+er.message+")":""));err3.context=er;throw err3}handler=events[type];if(void 0===handler)return!1;if("function"==typeof handler)ReflectApply(handler,this,args);else{len=handler.length;listeners2=arrayClone(handler,len);for(i3=0;i3<len;++i3)ReflectApply(listeners2[i3],this,args)}return!0};EventEmitter3.prototype.addListener=function addListener(type,listener){return _addListener(this,type,listener,!1)};EventEmitter3.prototype.on=EventEmitter3.prototype.addListener;EventEmitter3.prototype.prependListener=function prependListener(type,listener){return _addListener(this,type,listener,!0)};EventEmitter3.prototype.once=function once4(type,listener){checkListener(listener);this.on(type,_onceWrap(this,type,listener));return this};EventEmitter3.prototype.prependOnceListener=function prependOnceListener(type,listener){checkListener(listener);this.prependListener(type,_onceWrap(this,type,listener));return this};EventEmitter3.prototype.removeListener=function removeListener(type,listener){var list,events,position,i3,originalListener;checkListener(listener);events=this._events;if(void 0===events)return this;list=events[type];if(void 0===list)return this;if(list===listener||list.listener===listener)if(0===--this._eventsCount)this._events=Object.create(null);else{delete events[type];events.removeListener&&this.emit("removeListener",type,list.listener||listener)}else if("function"!=typeof list){position=-1;for(i3=list.length-1;i3>=0;i3--)if(list[i3]===listener||list[i3].listener===listener){originalListener=list[i3].listener;position=i3;break}if(position<0)return this;0===position?list.shift():spliceOne(list,position);1===list.length&&(events[type]=list[0]);void 0!==events.removeListener&&this.emit("removeListener",type,originalListener||listener)}return this};EventEmitter3.prototype.off=EventEmitter3.prototype.removeListener;EventEmitter3.prototype.removeAllListeners=function removeAllListeners(type){var listeners2,i3,keys3,key3,events=this._events;if(void 0===events)return this;if(void 0===events.removeListener){if(0===arguments.length){this._events=Object.create(null);this._eventsCount=0}else void 0!==events[type]&&(0===--this._eventsCount?this._events=Object.create(null):delete events[type]);return this}if(0===arguments.length){keys3=Object.keys(events);for(i3=0;i3<keys3.length;++i3){key3=keys3[i3];"removeListener"!==key3&&this.removeAllListeners(key3)}this.removeAllListeners("removeListener");this._events=Object.create(null);this._eventsCount=0;return this}listeners2=events[type];if("function"==typeof listeners2)this.removeListener(type,listeners2);else if(void 0!==listeners2)for(i3=listeners2.length-1;i3>=0;i3--)this.removeListener(type,listeners2[i3]);return this};EventEmitter3.prototype.listeners=function listeners2(type){return _listeners2(this,type,!0)};EventEmitter3.prototype.rawListeners=function rawListeners(type){return _listeners2(this,type,!1)};EventEmitter3.listenerCount=function(emitter,type){return"function"==typeof emitter.listenerCount?emitter.listenerCount(type):listenerCount2.call(emitter,type)};EventEmitter3.prototype.listenerCount=listenerCount2;EventEmitter3.prototype.eventNames=function eventNames(){return this._eventsCount>0?ReflectOwnKeys(this._events):[]}}}),init_abort=__esm({"node_modules/@smithy/types/dist-es/abort.js"(){}}),init_auth=__esm({"node_modules/@smithy/types/dist-es/auth/auth.js"(){(function(HttpAuthLocation2){HttpAuthLocation2.HEADER="header";HttpAuthLocation2.QUERY="query"})(HttpAuthLocation||(HttpAuthLocation={}))}}),init_HttpApiKeyAuth=__esm({"node_modules/@smithy/types/dist-es/auth/HttpApiKeyAuth.js"(){(function(HttpApiKeyAuthLocation2){HttpApiKeyAuthLocation2.HEADER="header";HttpApiKeyAuthLocation2.QUERY="query"})(HttpApiKeyAuthLocation||(HttpApiKeyAuthLocation={}))}}),init_HttpAuthScheme=__esm({"node_modules/@smithy/types/dist-es/auth/HttpAuthScheme.js"(){}}),init_HttpAuthSchemeProvider=__esm({"node_modules/@smithy/types/dist-es/auth/HttpAuthSchemeProvider.js"(){}}),init_HttpSigner=__esm({"node_modules/@smithy/types/dist-es/auth/HttpSigner.js"(){}}),init_IdentityProviderConfig=__esm({"node_modules/@smithy/types/dist-es/auth/IdentityProviderConfig.js"(){}}),init_auth2=__esm({"node_modules/@smithy/types/dist-es/auth/index.js"(){init_auth();init_HttpApiKeyAuth();init_HttpAuthScheme();init_HttpAuthSchemeProvider();init_HttpSigner();init_IdentityProviderConfig()}}),init_blob_payload_input_types=__esm({"node_modules/@smithy/types/dist-es/blob/blob-payload-input-types.js"(){}}),init_checksum=__esm({"node_modules/@smithy/types/dist-es/checksum.js"(){}}),init_client=__esm({"node_modules/@smithy/types/dist-es/client.js"(){}}),init_command=__esm({"node_modules/@smithy/types/dist-es/command.js"(){}}),init_config=__esm({"node_modules/@smithy/types/dist-es/connection/config.js"(){}}),init_manager=__esm({"node_modules/@smithy/types/dist-es/connection/manager.js"(){}}),init_pool=__esm({"node_modules/@smithy/types/dist-es/connection/pool.js"(){}}),init_connection=__esm({"node_modules/@smithy/types/dist-es/connection/index.js"(){init_config();init_manager();init_pool()}}),init_crypto=__esm({"node_modules/@smithy/types/dist-es/crypto.js"(){}}),init_encode=__esm({"node_modules/@smithy/types/dist-es/encode.js"(){}}),init_endpoint=__esm({"node_modules/@smithy/types/dist-es/endpoint.js"(){(function(EndpointURLScheme2){EndpointURLScheme2.HTTP="http";EndpointURLScheme2.HTTPS="https"})(EndpointURLScheme||(EndpointURLScheme={}))}}),init_EndpointRuleObject=__esm({"node_modules/@smithy/types/dist-es/endpoints/EndpointRuleObject.js"(){}}),init_ErrorRuleObject=__esm({"node_modules/@smithy/types/dist-es/endpoints/ErrorRuleObject.js"(){}}),init_RuleSetObject=__esm({"node_modules/@smithy/types/dist-es/endpoints/RuleSetObject.js"(){}}),init_shared=__esm({"node_modules/@smithy/types/dist-es/endpoints/shared.js"(){}}),init_TreeRuleObject=__esm({"node_modules/@smithy/types/dist-es/endpoints/TreeRuleObject.js"(){}}),init_endpoints=__esm({"node_modules/@smithy/types/dist-es/endpoints/index.js"(){init_EndpointRuleObject();init_ErrorRuleObject();init_RuleSetObject();init_shared();init_TreeRuleObject()}}),init_eventStream=__esm({"node_modules/@smithy/types/dist-es/eventStream.js"(){}}),init_checksum2=__esm({"node_modules/@smithy/types/dist-es/extensions/checksum.js"(){(function(AlgorithmId2){AlgorithmId2.MD5="md5";AlgorithmId2.CRC32="crc32";AlgorithmId2.CRC32C="crc32c";AlgorithmId2.SHA1="sha1";AlgorithmId2.SHA256="sha256"})(AlgorithmId||(AlgorithmId={}));0;0}}),init_defaultClientConfiguration=__esm({"node_modules/@smithy/types/dist-es/extensions/defaultClientConfiguration.js"(){}}),init_defaultExtensionConfiguration=__esm({"node_modules/@smithy/types/dist-es/extensions/defaultExtensionConfiguration.js"(){}}),init_extensions=__esm({"node_modules/@smithy/types/dist-es/extensions/index.js"(){init_defaultClientConfiguration();init_defaultExtensionConfiguration();init_checksum2()}}),init_feature_ids=__esm({"node_modules/@smithy/types/dist-es/feature-ids.js"(){}}),init_http=__esm({"node_modules/@smithy/types/dist-es/http.js"(){(function(FieldPosition2){FieldPosition2[FieldPosition2.HEADER=0]="HEADER";FieldPosition2[FieldPosition2.TRAILER=1]="TRAILER"})(FieldPosition||(FieldPosition={}))}}),init_httpHandlerInitialization=__esm({"node_modules/@smithy/types/dist-es/http/httpHandlerInitialization.js"(){}}),init_apiKeyIdentity=__esm({"node_modules/@smithy/types/dist-es/identity/apiKeyIdentity.js"(){}}),init_awsCredentialIdentity=__esm({"node_modules/@smithy/types/dist-es/identity/awsCredentialIdentity.js"(){}}),init_identity=__esm({"node_modules/@smithy/types/dist-es/identity/identity.js"(){}}),init_tokenIdentity=__esm({"node_modules/@smithy/types/dist-es/identity/tokenIdentity.js"(){}}),init_identity2=__esm({"node_modules/@smithy/types/dist-es/identity/index.js"(){init_apiKeyIdentity();init_awsCredentialIdentity();init_identity();init_tokenIdentity()}}),init_logger=__esm({"node_modules/@smithy/types/dist-es/logger.js"(){}}),init_middleware=__esm({"node_modules/@smithy/types/dist-es/middleware.js"(){SMITHY_CONTEXT_KEY="__smithy_context"}}),init_pagination=__esm({"node_modules/@smithy/types/dist-es/pagination.js"(){}}),init_profile=__esm({"node_modules/@smithy/types/dist-es/profile.js"(){(function(IniSectionType2){IniSectionType2.PROFILE="profile";IniSectionType2.SSO_SESSION="sso-session";IniSectionType2.SERVICES="services"})(IniSectionType||(IniSectionType={}))}}),init_response=__esm({"node_modules/@smithy/types/dist-es/response.js"(){}}),init_retry=__esm({"node_modules/@smithy/types/dist-es/retry.js"(){}}),init_schema=__esm({"node_modules/@smithy/types/dist-es/schema/schema.js"(){}}),init_traits=__esm({"node_modules/@smithy/types/dist-es/schema/traits.js"(){}}),init_schema_deprecated=__esm({"node_modules/@smithy/types/dist-es/schema/schema-deprecated.js"(){}}),init_sentinels=__esm({"node_modules/@smithy/types/dist-es/schema/sentinels.js"(){}}),init_static_schemas=__esm({"node_modules/@smithy/types/dist-es/schema/static-schemas.js"(){}}),init_serde=__esm({"node_modules/@smithy/types/dist-es/serde.js"(){}}),init_shapes=__esm({"node_modules/@smithy/types/dist-es/shapes.js"(){}}),init_signature=__esm({"node_modules/@smithy/types/dist-es/signature.js"(){}}),init_stream=__esm({"node_modules/@smithy/types/dist-es/stream.js"(){}}),init_streaming_blob_common_types=__esm({"node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-common-types.js"(){}}),init_streaming_blob_payload_input_types=__esm({"node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-payload-input-types.js"(){}}),init_streaming_blob_payload_output_types=__esm({"node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-payload-output-types.js"(){}}),init_transfer=__esm({"node_modules/@smithy/types/dist-es/transfer.js"(){(function(RequestHandlerProtocol2){RequestHandlerProtocol2.HTTP_0_9="http/0.9";RequestHandlerProtocol2.HTTP_1_0="http/1.0";RequestHandlerProtocol2.TDS_8_0="tds/8.0"})(RequestHandlerProtocol||(RequestHandlerProtocol={}))}}),init_client_payload_blob_type_narrow=__esm({"node_modules/@smithy/types/dist-es/transform/client-payload-blob-type-narrow.js"(){}}),init_mutable=__esm({"node_modules/@smithy/types/dist-es/transform/mutable.js"(){}}),init_no_undefined=__esm({"node_modules/@smithy/types/dist-es/transform/no-undefined.js"(){}}),init_type_transform=__esm({"node_modules/@smithy/types/dist-es/transform/type-transform.js"(){}}),init_uri=__esm({"node_modules/@smithy/types/dist-es/uri.js"(){}}),init_util=__esm({"node_modules/@smithy/types/dist-es/util.js"(){}}),init_waiter=__esm({"node_modules/@smithy/types/dist-es/waiter.js"(){}}),init_dist_es=__esm({"node_modules/@smithy/types/dist-es/index.js"(){init_abort();init_auth2();init_blob_payload_input_types();init_checksum();init_client();init_command();init_connection();init_crypto();init_encode();init_endpoint();init_endpoints();init_eventStream();init_extensions();init_feature_ids();init_http();init_httpHandlerInitialization();init_identity2();init_logger();init_middleware();init_pagination();init_profile();init_response();init_retry();init_schema();init_traits();init_schema_deprecated();init_sentinels();init_static_schemas();init_serde();init_shapes();init_signature();init_stream();init_streaming_blob_common_types();init_streaming_blob_payload_input_types();init_streaming_blob_payload_output_types();init_transfer();init_client_payload_blob_type_narrow();init_mutable();init_no_undefined();init_type_transform();init_uri();init_util();init_waiter()}}),init_getSmithyContext=__esm({"node_modules/@smithy/core/dist-es/submodules/transport/getSmithyContext.js"(){init_dist_es();getSmithyContext=context2=>context2[SMITHY_CONTEXT_KEY]||(context2[SMITHY_CONTEXT_KEY]={})}}),init_httpRequest=__esm({"node_modules/@smithy/core/dist-es/submodules/transport/httpRequest.js"(){HttpRequest2=class _HttpRequest{constructor(options){__publicField(this,"method");__publicField(this,"protocol");__publicField(this,"hostname");__publicField(this,"port");__publicField(this,"path");__publicField(this,"query");__publicField(this,"headers");__publicField(this,"username");__publicField(this,"password");__publicField(this,"fragment");__publicField(this,"body");this.method=options.method||"GET";this.hostname=options.hostname||"localhost";this.port=options.port;this.query=options.query||{};this.headers=options.headers||{};this.body=options.body;this.protocol=options.protocol?":"!==options.protocol.slice(-1)?`${options.protocol}:`:options.protocol:"https:";this.path=options.path?"/"!==options.path.charAt(0)?`/${options.path}`:options.path:"/";this.username=options.username;this.password=options.password;this.fragment=options.fragment}static clone(request2){const cloned=new _HttpRequest({...request2,headers:{...request2.headers}});cloned.query&&(cloned.query=cloneQuery2(cloned.query));return cloned}static isInstance(request2){if(!request2)return!1;const req=request2;return"method"in req&&"protocol"in req&&"hostname"in req&&"path"in req&&"object"==typeof req.query&&"object"==typeof req.headers}clone(){return _HttpRequest.clone(this)}}}}),init_httpResponse=__esm({"node_modules/@smithy/core/dist-es/submodules/transport/httpResponse.js"(){HttpResponse2=class{constructor(options){__publicField(this,"statusCode");__publicField(this,"reason");__publicField(this,"headers");__publicField(this,"body");this.statusCode=options.statusCode;this.reason=options.reason;this.headers=options.headers||{};this.body=options.body}static isInstance(response){if(!response)return!1;const resp=response;return"number"==typeof resp.statusCode&&"object"==typeof resp.headers}}}}),init_isValidHostLabel=__esm({"node_modules/@smithy/core/dist-es/submodules/transport/isValidHostLabel.js"(){VALID_HOST_LABEL_REGEX=new RegExp("^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$");isValidHostLabel=(value,allowSubDomains=!1)=>{if(!allowSubDomains)return VALID_HOST_LABEL_REGEX.test(value);const labels=value.split(".");for(const label2 of labels)if(!isValidHostLabel(label2))return!1;return!0}}}),init_isValidHostname=__esm({"node_modules/@smithy/core/dist-es/submodules/transport/isValidHostname.js"(){}}),init_normalizeProvider=__esm({"node_modules/@smithy/core/dist-es/submodules/transport/normalizeProvider.js"(){normalizeProvider=input=>{if("function"==typeof input)return input;const promisified=Promise.resolve(input);return()=>promisified}}}),init_parseQueryString=__esm({"node_modules/@smithy/core/dist-es/submodules/transport/parseQueryString.js"(){}}),init_parseUrl=__esm({"node_modules/@smithy/core/dist-es/submodules/transport/parseUrl.js"(){init_parseQueryString();parseUrl=url=>{if("string"==typeof url)return parseUrl(new URL(url));const{hostname,pathname,port,protocol,search}=url;let query3;search&&(query3=parseQueryString(search));return{hostname,port:port?parseInt(port):void 0,protocol,path:pathname,query:query3}}}}),init_toEndpointV1=__esm({"node_modules/@smithy/core/dist-es/submodules/transport/toEndpointV1.js"(){init_parseUrl();toEndpointV1=endpoint=>{if("object"==typeof endpoint){if("url"in endpoint){const v1Endpoint=parseUrl(endpoint.url);if(endpoint.headers){v1Endpoint.headers={};for(const name in endpoint.headers)v1Endpoint.headers[name.toLowerCase()]=endpoint.headers[name].join(", ")}return v1Endpoint}return endpoint}return parseUrl(endpoint)}}}),init_transport=__esm({"node_modules/@smithy/core/dist-es/submodules/transport/index.js"(){init_getSmithyContext();init_httpRequest();init_httpResponse();init_isValidHostLabel();init_isValidHostname();init_normalizeProvider();init_parseQueryString();init_parseUrl();init_toEndpointV1()}}),init_constants_for_browser=__esm({"node_modules/@smithy/core/dist-es/submodules/serde/util-base64/constants-for-browser.js"(){chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";alphabetByEncoding=Object.entries(chars).reduce((acc,[i3,c3])=>{acc[c3]=Number(i3);return acc},{});alphabetByValue=chars.split("");bitsPerLetter=6;bitsPerByte=8;maxLetterValue=63}}),init_fromBase64_browser=__esm({"node_modules/@smithy/core/dist-es/submodules/serde/util-base64/fromBase64.browser.js"(){init_constants_for_browser();fromBase64=input=>{let totalByteLength=input.length/4*3;"=="===input.slice(-2)?totalByteLength-=2:"="===input.slice(-1)&&totalByteLength--;const out=new ArrayBuffer(totalByteLength),dataView=new DataView(out);for(let i3=0;i3<input.length;i3+=4){let bits2=0,bitLength=0;for(let j2=i3,limit=i3+3;j2<=limit;j2++)if("="!==input[j2]){if(!(input[j2]in alphabetByEncoding))throw new TypeError(`Invalid character ${input[j2]} in base64 string.`);bits2|=alphabetByEncoding[input[j2]]<<(limit-j2)*bitsPerLetter;bitLength+=bitsPerLetter}else bits2>>=bitsPerLetter;const chunkOffset=i3/4*3;bits2>>=bitLength%bitsPerByte;const byteLength=Math.floor(bitLength/bitsPerByte);for(let k2=0;k2<byteLength;k2++){const offset=(byteLength-k2-1)*bitsPerByte;dataView.setUint8(chunkOffset+k2,(bits2&255<<offset)>>offset)}}return new Uint8Array(out)}}}),init_fromUtf8_browser=__esm({"node_modules/@smithy/core/dist-es/submodules/serde/util-utf8/fromUtf8.browser.js"(){fromUtf8=input=>(new TextEncoder).encode(input)}}),init_toBase64_browser=__esm({"node_modules/@smithy/core/dist-es/submodules/serde/util-base64/toBase64.browser.js"(){init_fromUtf8_browser();init_constants_for_browser()}}),init_Uint8ArrayBlobAdapter=__esm({"node_modules/@smithy/core/dist-es/submodules/serde/util-stream/blob/Uint8ArrayBlobAdapter.js"(){}}),init_toUtf8_browser=__esm({"node_modules/@smithy/core/dist-es/submodules/serde/util-utf8/toUtf8.browser.js"(){toUtf8=input=>{if("string"==typeof input)return input;if("object"!=typeof input||"number"!=typeof input.byteOffset||"number"!=typeof input.byteLength)throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");return new TextDecoder("utf-8").decode(input)}}}),init_v4=__esm({"node_modules/@smithy/core/dist-es/submodules/serde/uuid/v4.js"(){decimalToHex=Array.from({length:256},(_,i3)=>i3.toString(16).padStart(2,"0"))}}),init_copyDocumentWithTransform=__esm({"node_modules/@smithy/core/dist-es/submodules/serde/copyDocumentWithTransform.js"(){}}),init_parse_utils=__esm({"node_modules/@smithy/core/dist-es/submodules/serde/parse-utils.js"(){0;0;expectNumber=value=>{if(null!=value){if("string"==typeof value){const parsed=parseFloat(value);if(!Number.isNaN(parsed)){String(parsed)!==String(value)&&logger.warn(stackTraceWarning(`Expected number but observed string: ${value}`));return parsed}}if("number"==typeof value)return value;throw new TypeError(`Expected number, got ${typeof value}: ${value}`)}};MAX_FLOAT=Math.ceil(2**127*(2-2**-23));expectFloat32=value=>{const expected=expectNumber(value);if(void 0!==expected&&!Number.isNaN(expected)&&expected!==1/0&&expected!==-1/0&&Math.abs(expected)>MAX_FLOAT)throw new TypeError(`Expected 32-bit float, got ${value}`);return expected};expectLong=value=>{if(null!=value){if(Number.isInteger(value)&&!Number.isNaN(value))return value;throw new TypeError(`Expected integer, got ${typeof value}: ${value}`)}};0;expectInt32=value=>expectSizedInt(value,32);expectShort=value=>expectSizedInt(value,16);expectByte=value=>expectSizedInt(value,8);expectSizedInt=(value,size)=>{const expected=expectLong(value);if(void 0!==expected&&castInt(expected,size)!==expected)throw new TypeError(`Expected ${size}-bit integer, got ${value}`);return expected};castInt=(value,size)=>{switch(size){case 32:return Int32Array.of(value)[0];case 16:return Int16Array.of(value)[0];case 8:return Int8Array.of(value)[0]}};0;expectObject=value=>{if(null==value)return;if("object"==typeof value&&!Array.isArray(value))return value;const receivedType=Array.isArray(value)?"array":typeof value;throw new TypeError(`Expected object, got ${receivedType}: ${value}`)};0;0;strictParseDouble=value=>expectNumber("string"==typeof value?parseNumber(value):value);0;strictParseFloat32=value=>expectFloat32("string"==typeof value?parseNumber(value):value);NUMBER_REGEX=/(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g;parseNumber=value=>{const matches=value.match(NUMBER_REGEX);if(null===matches||matches[0].length!==value.length)throw new TypeError("Expected real number, got implicit NaN");return parseFloat(value)};limitedParseDouble=value=>"string"==typeof value?parseFloatString(value):expectNumber(value);0;0;0;parseFloatString=value=>{switch(value){case"NaN":return NaN;case"Infinity":return 1/0;case"-Infinity":return-1/0;default:throw new Error(`Unable to parse float value: ${value}`)}};strictParseLong=value=>expectLong("string"==typeof value?parseNumber(value):value);0;0;strictParseShort=value=>expectShort("string"==typeof value?parseNumber(value):value);strictParseByte=value=>expectByte("string"==typeof value?parseNumber(value):value);stackTraceWarning=message=>String(new TypeError(message).stack||message).split("\n").slice(0,5).filter(s2=>!s2.includes("stackTraceWarning")).join("\n");logger={warn:console.warn}}}),init_date_utils=__esm({"node_modules/@smithy/core/dist-es/submodules/serde/date-utils.js"(){init_parse_utils();DAYS=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];MONTHS=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];RFC3339=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/);0;RFC3339_WITH_OFFSET=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/);0;IMF_FIXDATE=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/);RFC_850_DATE=new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/);ASC_TIME=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/);parseRfc7231DateTime=value=>{if(null==value)return;if("string"!=typeof value)throw new TypeError("RFC-7231 date-times must be expressed as strings");let match3=IMF_FIXDATE.exec(value);if(match3){const[_,dayStr,monthStr,yearStr,hours,minutes,seconds,fractionalMilliseconds]=match3;return buildDate(strictParseShort(stripLeadingZeroes(yearStr)),parseMonthByShortName(monthStr),parseDateValue(dayStr,"day",1,31),{hours,minutes,seconds,fractionalMilliseconds})}match3=RFC_850_DATE.exec(value);if(match3){const[_,dayStr,monthStr,yearStr,hours,minutes,seconds,fractionalMilliseconds]=match3;return adjustRfc850Year(buildDate(parseTwoDigitYear(yearStr),parseMonthByShortName(monthStr),parseDateValue(dayStr,"day",1,31),{hours,minutes,seconds,fractionalMilliseconds}))}match3=ASC_TIME.exec(value);if(match3){const[_,monthStr,dayStr,hours,minutes,seconds,fractionalMilliseconds,yearStr]=match3;return buildDate(strictParseShort(stripLeadingZeroes(yearStr)),parseMonthByShortName(monthStr),parseDateValue(dayStr.trimLeft(),"day",1,31),{hours,minutes,seconds,fractionalMilliseconds})}throw new TypeError("Invalid RFC-7231 date-time value")};0;buildDate=(year2,month,day,time2)=>{const adjustedMonth=month-1;validateDayOfMonth(year2,adjustedMonth,day);return new Date(Date.UTC(year2,adjustedMonth,day,parseDateValue(time2.hours,"hour",0,23),parseDateValue(time2.minutes,"minute",0,59),parseDateValue(time2.seconds,"seconds",0,60),parseMilliseconds(time2.fractionalMilliseconds)))};parseTwoDigitYear=value=>{const thisYear=(new Date).getUTCFullYear(),valueInThisCentury=100*Math.floor(thisYear/100)+strictParseShort(stripLeadingZeroes(value));return valueInThisCentury<thisYear?valueInThisCentury+100:valueInThisCentury};0;adjustRfc850Year=input=>input.getTime()-(new Date).getTime()>15768e8?new Date(Date.UTC(input.getUTCFullYear()-100,input.getUTCMonth(),input.getUTCDate(),input.getUTCHours(),input.getUTCMinutes(),input.getUTCSeconds(),input.getUTCMilliseconds())):input;parseMonthByShortName=value=>{const monthIdx=MONTHS.indexOf(value);if(monthIdx<0)throw new TypeError(`Invalid month: ${value}`);return monthIdx+1};DAYS_IN_MONTH=[31,28,31,30,31,30,31,31,30,31,30,31];validateDayOfMonth=(year2,month,day)=>{let maxDays=DAYS_IN_MONTH[month];1===month&&isLeapYear(year2)&&(maxDays=29);if(day>maxDays)throw new TypeError(`Invalid day for ${MONTHS[month]} in ${year2}: ${day}`)};isLeapYear=year2=>year2%4==0&&(year2%100!=0||year2%400==0);parseDateValue=(value,type,lower,upper)=>{const dateVal=strictParseByte(stripLeadingZeroes(value));if(dateVal<lower||dateVal>upper)throw new TypeError(`${type} must be between ${lower} and ${upper}, inclusive`);return dateVal};parseMilliseconds=value=>null==value?0:1e3*strictParseFloat32("0."+value);parseOffsetToMilliseconds=value=>{const directionStr=value[0];let direction=1;if("+"==directionStr)direction=1;else{if("-"!=directionStr)throw new TypeError(`Offset direction, ${directionStr}, must be "+" or "-"`);direction=-1}const hour=Number(value.substring(1,3)),minute=Number(value.substring(4,6));return direction*(60*hour+minute)*60*1e3};stripLeadingZeroes=value=>{let idx2=0;for(;idx2<value.length-1&&"0"===value.charAt(idx2);)idx2++;return 0===idx2?value:value.slice(idx2)}}}),init_lazy_json=__esm({"node_modules/@smithy/core/dist-es/submodules/serde/lazy-json.js"(){LazyJsonString=function LazyJsonString2(val){const str=Object.assign(new String(val),{deserializeJSON:()=>JSON.parse(String(val)),toString:()=>String(val),toJSON:()=>String(val)});return str};LazyJsonString.from=object=>object&&"object"==typeof object&&(object instanceof LazyJsonString||"deserializeJSON"in object)?object:"string"==typeof object||Object.getPrototypeOf(object)===String.prototype?LazyJsonString(String(object)):LazyJsonString(JSON.stringify(object));LazyJsonString.fromObject=LazyJsonString.from}}),init_quote_header=__esm({"node_modules/@smithy/core/dist-es/submodules/serde/quote-header.js"(){}}),init_schema_date_utils=__esm({"node_modules/@smithy/core/dist-es/submodules/serde/schema-serde-lib/schema-date-utils.js"(){ddd="(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)(?:[ne|u?r]?s?day)?";mmm="(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)";time="(\\d?\\d):(\\d{2}):(\\d{2})(?:\\.(\\d+))?";0;0;RFC3339_WITH_OFFSET2=new RegExp(/^(\d{4})-(\d\d)-(\d\d)[tT](\d\d):(\d\d):(\d\d)(\.(\d+))?(([-+]\d\d:\d\d)|[zZ])$/);IMF_FIXDATE2=new RegExp(`^${ddd}, (\\d?\\d) ${mmm} (\\d{4}) ${time} GMT$`);RFC_850_DATE2=new RegExp(`^${ddd}, (\\d?\\d)-${mmm}-(\\d\\d) ${time} GMT$`);ASC_TIME2=new RegExp(`^${ddd} ${mmm} ( [1-9]|\\d\\d) ${time} (\\d{4})$`);months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];_parseEpochTimestamp=value=>{if(null==value)return;let num=NaN;if("number"==typeof value)num=value;else if("string"==typeof value){if(!/^-?\d*\.?\d+$/.test(value))throw new TypeError("parseEpochTimestamp - numeric string invalid.");num=Number.parseFloat(value)}else"object"==typeof value&&1===value.tag&&(num=value.value);if(isNaN(num)||Math.abs(num)===1/0)throw new TypeError("Epoch timestamps must be valid finite numbers.");return new Date(Math.round(1e3*num))};_parseRfc3339DateTimeWithOffset=value=>{if(null==value)return;if("string"!=typeof value)throw new TypeError("RFC3339 timestamps must be strings");const matches=RFC3339_WITH_OFFSET2.exec(value);if(!matches)throw new TypeError(`Invalid RFC3339 timestamp format ${value}`);const[,yearStr,monthStr,dayStr,hours,minutes,seconds,,ms,offsetStr]=matches;range3(monthStr,1,12);range3(dayStr,1,31);range3(hours,0,23);range3(minutes,0,59);range3(seconds,0,60);const date2=new Date(Date.UTC(Number(yearStr),Number(monthStr)-1,Number(dayStr),Number(hours),Number(minutes),Number(seconds),Number(ms)?Math.round(1e3*parseFloat(`0.${ms}`)):0));date2.setUTCFullYear(Number(yearStr));if("Z"!=offsetStr.toUpperCase()){const[,sign2,offsetH,offsetM]=/([+-])(\d\d):(\d\d)/.exec(offsetStr)||[void 0,"+",0,0],scalar="-"===sign2?1:-1;date2.setTime(date2.getTime()+scalar*(60*Number(offsetH)*60*1e3+60*Number(offsetM)*1e3))}return date2};_parseRfc7231DateTime=value=>{if(null==value)return;if("string"!=typeof value)throw new TypeError("RFC7231 timestamps must be strings.");let day,month,year2,hour,minute,second,fraction,matches;if(matches=IMF_FIXDATE2.exec(value))[,day,month,year2,hour,minute,second,fraction]=matches;else if(matches=RFC_850_DATE2.exec(value)){[,day,month,year2,hour,minute,second,fraction]=matches;year2=(Number(year2)+1900).toString()}else(matches=ASC_TIME2.exec(value))&&([,month,day,hour,minute,second,fraction,year2]=matches);if(year2&&second){const timestamp=Date.UTC(Number(year2),months.indexOf(month),Number(day),Number(hour),Number(minute),Number(second),fraction?Math.round(1e3*parseFloat(`0.${fraction}`)):0);range3(day,1,31);range3(hour,0,23);range3(minute,0,59);range3(second,0,60);const date2=new Date(timestamp);date2.setUTCFullYear(Number(year2));return date2}throw new TypeError(`Invalid RFC7231 date-time value ${value}.`)}}}),init_split_every=__esm({"node_modules/@smithy/core/dist-es/submodules/serde/split-every.js"(){}}),init_split_header=__esm({"node_modules/@smithy/core/dist-es/submodules/serde/split-header.js"(){splitHeader=value=>{const z2=value.length,values2=[];let prevChar,withinQuotes=!1,anchor=0;for(let i3=0;i3<z2;++i3){const char=value[i3];switch(char){case'"':"\\"!==prevChar&&(withinQuotes=!withinQuotes);break;case",":if(!withinQuotes){values2.push(value.slice(anchor,i3));anchor=i3+1}break;default:}prevChar=char}values2.push(value.slice(anchor));return values2.map(v2=>{v2=v2.trim();const z3=v2.length;if(z3<2)return v2;'"'===v2[0]&&'"'===v2[z3-1]&&(v2=v2.slice(1,z3-1));return v2.replace(/\\"/g,'"')})}}}),init_NumericValue=__esm({"node_modules/@smithy/core/dist-es/submodules/serde/value/NumericValue.js"(){format=/^-?\d*(\.\d+)?$/;NumericValue=class _NumericValue{constructor(string,type){__publicField(this,"string");__publicField(this,"type");this.string=string;this.type=type;if(!format.test(string))throw new Error('@smithy/core/serde - NumericValue must only contain [0-9], at most one decimal point ".", and an optional negation prefix "-".')}toString(){return this.string}static[Symbol.hasInstance](object){if(!object||"object"!=typeof object)return!1;const _nv=object;return _NumericValue.prototype.isPrototypeOf(object)||"bigDecimal"===_nv.type&&format.test(_nv.string)}}}}),init_hex_encoding=__esm({"node_modules/@smithy/core/dist-es/submodules/serde/util-hex-encoding/hex-encoding.js"(){SHORT_TO_HEX={};HEX_TO_SHORT={};for(let i3=0;i3<256;i3++){let encodedByte=i3.toString(16).toLowerCase();1===encodedByte.length&&(encodedByte=`0${encodedByte}`);SHORT_TO_HEX[i3]=encodedByte;HEX_TO_SHORT[encodedByte]=i3}}}),init_calculateBodyLength_browser=__esm({"node_modules/@smithy/core/dist-es/submodules/serde/util-body-length/calculateBodyLength.browser.js"(){TEXT_ENCODER="function"==typeof TextEncoder?new TextEncoder:null;0}}),init_toUint8Array_browser=__esm({"node_modules/@smithy/core/dist-es/submodules/serde/util-utf8/toUint8Array.browser.js"(){init_fromUtf8_browser();toUint8Array=data=>"string"==typeof data?fromUtf8(data):ArrayBuffer.isView(data)?new Uint8Array(data.buffer,data.byteOffset,data.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(data)}}),init_is_array_buffer=__esm({"node_modules/@smithy/core/dist-es/submodules/serde/is-array-buffer/is-array-buffer.js"(){isArrayBuffer=arg=>"function"==typeof ArrayBuffer&&arg instanceof ArrayBuffer||"[object ArrayBuffer]"===Object.prototype.toString.call(arg)}}),init_deserializerMiddleware=__esm({"node_modules/@smithy/core/dist-es/submodules/serde/middleware-serde/deserializerMiddleware.js"(){}}),init_getEndpointFromConfig_browser=__esm({"node_modules/@smithy/core/dist-es/submodules/endpoints/middleware-endpoint/adaptors/getEndpointFromConfig.browser.js"(){getEndpointFromConfig=async serviceId=>{}}}),init_s3=__esm({"node_modules/@smithy/core/dist-es/submodules/endpoints/middleware-endpoint/service-customizations/s3.js"(){resolveParamsForS3=async endpointParams=>{const bucket=(null==endpointParams?void 0:endpointParams.Bucket)||"";"string"==typeof endpointParams.Bucket&&(endpointParams.Bucket=bucket.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?")));if(isArnBucketName(bucket)){if(!0===endpointParams.ForcePathStyle)throw new Error("Path-style addressing cannot be used with ARN buckets")}else(!isDnsCompatibleBucketName(bucket)||-1!==bucket.indexOf(".")&&!String(endpointParams.Endpoint).startsWith("http:")||bucket.toLowerCase()!==bucket||bucket.length<3)&&(endpointParams.ForcePathStyle=!0);if(endpointParams.DisableMultiRegionAccessPoints){endpointParams.disableMultiRegionAccessPoints=!0;endpointParams.DisableMRAP=!0}return endpointParams};DOMAIN_PATTERN=/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/;IP_ADDRESS_PATTERN=/(\d+\.){3}\d+/;DOTS_PATTERN=/\.\./;0;0;isDnsCompatibleBucketName=bucketName=>DOMAIN_PATTERN.test(bucketName)&&!IP_ADDRESS_PATTERN.test(bucketName)&&!DOTS_PATTERN.test(bucketName);isArnBucketName=bucketName=>{const[arn,partition2,service,,,bucket]=bucketName.split(":"),isArn="arn"===arn&&bucketName.split(":").length>=6,isValidArn=Boolean(isArn&&partition2&&service&&bucket);if(isArn&&!isValidArn)throw new Error(`Invalid ARN: ${bucketName} was an invalid ARN.`);return isValidArn}}}),init_service_customizations=__esm({"node_modules/@smithy/core/dist-es/submodules/endpoints/middleware-endpoint/service-customizations/index.js"(){init_s3()}}),init_createConfigValueProvider=__esm({"node_modules/@smithy/core/dist-es/submodules/endpoints/middleware-endpoint/adaptors/createConfigValueProvider.js"(){createConfigValueProvider=(configKey,canonicalEndpointParamKey,config,isClientContextParam=!1)=>{const configProvider=async()=>{var _a13,_b6;let configValue;if(isClientContextParam){const clientContextParams=config.clientContextParams,nestedValue=null==clientContextParams?void 0:clientContextParams[configKey];configValue=null!=(_a13=null!=nestedValue?nestedValue:config[configKey])?_a13:config[canonicalEndpointParamKey]}else configValue=null!=(_b6=config[configKey])?_b6:config[canonicalEndpointParamKey];return"function"==typeof configValue?configValue():configValue};return"credentialScope"===configKey||"CredentialScope"===canonicalEndpointParamKey?async()=>{var _a13;const credentials="function"==typeof config.credentials?await config.credentials():config.credentials,configValue=null!=(_a13=null==credentials?void 0:credentials.credentialScope)?_a13:null==credentials?void 0:credentials.CredentialScope;return configValue}:"accountId"===configKey||"AccountId"===canonicalEndpointParamKey?async()=>{var _a13;const credentials="function"==typeof config.credentials?await config.credentials():config.credentials,configValue=null!=(_a13=null==credentials?void 0:credentials.accountId)?_a13:null==credentials?void 0:credentials.AccountId;return configValue}:"endpoint"===configKey||"endpoint"===canonicalEndpointParamKey?async()=>{if(!1===config.isCustomEndpoint)return;const endpoint=await configProvider();if(endpoint&&"object"==typeof endpoint){if("url"in endpoint)return endpoint.url.href;if("hostname"in endpoint){const{protocol,hostname,port,path:path2}=endpoint;return`${protocol}//${hostname}${port?":"+port:""}${path2}`}}return endpoint}:configProvider}}}),init_toEndpointV12=__esm({"node_modules/@smithy/core/dist-es/submodules/endpoints/middleware-endpoint/adaptors/toEndpointV1.js"(){init_transport()}}),init_getEndpointFromInstructions=__esm({"node_modules/@smithy/core/dist-es/submodules/endpoints/middleware-endpoint/adaptors/getEndpointFromInstructions.js"(){init_service_customizations();init_createConfigValueProvider();init_toEndpointV12();resolveParams=async(commandInput,instructionsSupplier,clientConfig)=>{var _a13;const endpointParams={},instructions=(null==(_a13=null==instructionsSupplier?void 0:instructionsSupplier.getEndpointParameterInstructions)?void 0:_a13.call(instructionsSupplier))||{};for(const[name,instruction]of Object.entries(instructions))switch(instruction.type){case"staticContextParams":endpointParams[name]=instruction.value;break;case"contextParams":endpointParams[name]=commandInput[instruction.name];break;case"clientContextParams":case"builtInParams":endpointParams[name]=await createConfigValueProvider(instruction.name,name,clientConfig,"builtInParams"!==instruction.type)();break;case"operationContextParams":endpointParams[name]=instruction.get(commandInput);break;default:throw new Error("Unrecognized endpoint parameter instruction: "+JSON.stringify(instruction))}0===Object.keys(instructions).length&&Object.assign(endpointParams,clientConfig);"s3"===String(clientConfig.serviceId).toLowerCase()&&await resolveParamsForS3(endpointParams);return endpointParams}}}),init_endpointMiddleware=__esm({"node_modules/@smithy/core/dist-es/submodules/endpoints/middleware-endpoint/endpointMiddleware.js"(){init_transport();init_getEndpointFromInstructions()}}),init_getEndpointPlugin=__esm({"node_modules/@smithy/core/dist-es/submodules/endpoints/middleware-endpoint/getEndpointPlugin.js"(){init_endpointMiddleware();serializerMiddlewareOption={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};endpointMiddlewareOptions={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:serializerMiddlewareOption.name}}}),init_resolveEndpointConfig=__esm({"node_modules/@smithy/core/dist-es/submodules/endpoints/middleware-endpoint/resolveEndpointConfig.js"(){init_transport();init_toEndpointV12()}}),init_BinaryDecisionDiagram=__esm({"node_modules/@smithy/core/dist-es/submodules/endpoints/util-endpoints/bdd/BinaryDecisionDiagram.js"(){}}),init_EndpointCache=__esm({"node_modules/@smithy/core/dist-es/submodules/endpoints/util-endpoints/cache/EndpointCache.js"(){}}),init_EndpointError=__esm({"node_modules/@smithy/core/dist-es/submodules/endpoints/util-endpoints/types/EndpointError.js"(){}}),init_EndpointFunctions=__esm({"node_modules/@smithy/core/dist-es/submodules/endpoints/util-endpoints/types/EndpointFunctions.js"(){}}),init_EndpointRuleObject2=__esm({"node_modules/@smithy/core/dist-es/submodules/endpoints/util-endpoints/types/EndpointRuleObject.js"(){}}),init_ErrorRuleObject2=__esm({"node_modules/@smithy/core/dist-es/submodules/endpoints/util-endpoints/types/ErrorRuleObject.js"(){}}),init_RuleSetObject2=__esm({"node_modules/@smithy/core/dist-es/submodules/endpoints/util-endpoints/types/RuleSetObject.js"(){}}),init_TreeRuleObject2=__esm({"node_modules/@smithy/core/dist-es/submodules/endpoints/util-endpoints/types/TreeRuleObject.js"(){}}),init_shared2=__esm({"node_modules/@smithy/core/dist-es/submodules/endpoints/util-endpoints/types/shared.js"(){}}),init_types=__esm({"node_modules/@smithy/core/dist-es/submodules/endpoints/util-endpoints/types/index.js"(){init_EndpointError();init_EndpointFunctions();init_EndpointRuleObject2();init_ErrorRuleObject2();init_RuleSetObject2();init_TreeRuleObject2();init_shared2()}}),init_customEndpointFunctions=__esm({"node_modules/@smithy/core/dist-es/submodules/endpoints/util-endpoints/utils/customEndpointFunctions.js"(){}}),init_isIpAddress=__esm({"node_modules/@smithy/core/dist-es/submodules/endpoints/util-endpoints/lib/isIpAddress.js"(){IP_V4_REGEX=new RegExp("^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$");0}}),init_decideEndpoint=__esm({"node_modules/@smithy/core/dist-es/submodules/endpoints/util-endpoints/decideEndpoint.js"(){}}),init_resolveEndpoint=__esm({"node_modules/@smithy/core/dist-es/submodules/endpoints/util-endpoints/resolveEndpoint.js"(){}}),init_resolveEndpointRequiredConfig=__esm({"node_modules/@smithy/core/dist-es/submodules/endpoints/middleware-endpoint/resolveEndpointRequiredConfig.js"(){}}),init_index_browser=__esm({"node_modules/@smithy/core/dist-es/submodules/endpoints/index.browser.js"(){init_getEndpointFromConfig_browser();init_getEndpointFromInstructions();init_endpointMiddleware();init_getEndpointPlugin();init_resolveEndpointConfig();init_transport();init_BinaryDecisionDiagram();init_EndpointCache();init_decideEndpoint();init_isIpAddress();init_transport();init_customEndpointFunctions();init_resolveEndpoint();init_types();init_getEndpointFromInstructions();init_toEndpointV12();init_getEndpointPlugin();init_resolveEndpointRequiredConfig();bindGetEndpointFromInstructions(getEndpointFromConfig);bindResolveEndpointConfig(getEndpointFromConfig);bindEndpointMiddleware(getEndpointFromConfig);bindGetEndpointPlugin(getEndpointFromConfig)}}),init_serializerMiddleware=__esm({"node_modules/@smithy/core/dist-es/submodules/serde/middleware-serde/serializerMiddleware.js"(){}}),init_serdePlugin=__esm({"node_modules/@smithy/core/dist-es/submodules/serde/middleware-serde/serdePlugin.js"(){}}),init_ChecksumStream_browser=__esm({"node_modules/@smithy/core/dist-es/submodules/serde/util-stream/checksum/ChecksumStream.browser.js"(){}}),init_stream_type_check=__esm({"node_modules/@smithy/core/dist-es/submodules/serde/util-stream/stream-type-check.js"(){isReadableStream=stream=>{var _a13;return"function"==typeof ReadableStream&&((null==(_a13=null==stream?void 0:stream.constructor)?void 0:_a13.name)===ReadableStream.name||stream instanceof ReadableStream)};0}}),init_createChecksumStream_browser=__esm({"node_modules/@smithy/core/dist-es/submodules/serde/util-stream/checksum/createChecksumStream.browser.js"(){}}),init_createBufferedReadable_browser=__esm({"node_modules/@smithy/core/dist-es/submodules/serde/util-stream/createBufferedReadable.browser.js"(){}}),init_getAwsChunkedEncodingStream_browser=__esm({"node_modules/@smithy/core/dist-es/submodules/serde/util-stream/getAwsChunkedEncodingStream.browser.js"(){}}),init_headStream_browser=__esm({"node_modules/@smithy/core/dist-es/submodules/serde/util-stream/headStream.browser.js"(){}}),init_stream_collector_browser=__esm({"node_modules/@smithy/core/dist-es/submodules/serde/util-stream/stream-collector.browser.js"(){init_fromBase64_browser();streamCollector=async stream=>{var _a13;return"function"==typeof Blob&&stream instanceof Blob||"Blob"===(null==(_a13=stream.constructor)?void 0:_a13.name)?void 0!==Blob.prototype.arrayBuffer?new Uint8Array(await stream.arrayBuffer()):collectBlob(stream):collectStream(stream)}}}),init_sdk_stream_mixin_browser=__esm({"node_modules/@smithy/core/dist-es/submodules/serde/util-stream/sdk-stream-mixin.browser.js"(){init_toBase64_browser();init_hex_encoding();init_toUtf8_browser();init_stream_collector_browser();init_stream_type_check();0;sdkStreamMixin=stream=>{var _a13,_b6;if(!isBlobInstance(stream)&&!isReadableStream(stream)){const name=(null==(_b6=null==(_a13=null==stream?void 0:stream.__proto__)?void 0:_a13.constructor)?void 0:_b6.name)||stream;throw new Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${name}`)}let transformed=!1;const transformToByteArray=async()=>{if(transformed)throw new Error("The stream has already been transformed.");transformed=!0;return await streamCollector(stream)},blobToWebStream=blob=>{if("function"!=typeof blob.stream)throw new Error("Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.\nIf you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body");return blob.stream()};return Object.assign(stream,{transformToByteArray,transformToString:async encoding=>{const buf=await transformToByteArray();if("base64"===encoding)return toBase64(buf);if("hex"===encoding)return toHex2(buf);if(void 0===encoding||"utf8"===encoding||"utf-8"===encoding)return toUtf8(buf);if("function"==typeof TextDecoder)return new TextDecoder(encoding).decode(buf);throw new Error("TextDecoder is not available, please make sure polyfill is provided.")},transformToWebStream:()=>{if(transformed)throw new Error("The stream has already been transformed.");transformed=!0;if(isBlobInstance(stream))return blobToWebStream(stream);if(isReadableStream(stream))return stream;throw new Error(`Cannot transform payload to web stream, got ${stream}`)}})};isBlobInstance=stream=>"function"==typeof Blob&&stream instanceof Blob}}),init_splitStream_browser=__esm({"node_modules/@smithy/core/dist-es/submodules/serde/util-stream/splitStream.browser.js"(){}}),init_index_browser2=__esm({"node_modules/@smithy/core/dist-es/submodules/serde/index.browser.js"(){init_fromBase64_browser();init_toBase64_browser();init_Uint8ArrayBlobAdapter();init_fromUtf8_browser();init_toUtf8_browser();init_v4();init_copyDocumentWithTransform();init_date_utils();init_lazy_json();init_parse_utils();init_quote_header();init_schema_date_utils();init_split_every();init_split_header();init_NumericValue();init_hex_encoding();init_calculateBodyLength_browser();init_toUint8Array_browser();init_is_array_buffer();init_deserializerMiddleware();init_serdePlugin();init_serializerMiddleware();init_ChecksumStream_browser();init_createChecksumStream_browser();init_createBufferedReadable_browser();init_getAwsChunkedEncodingStream_browser();init_headStream_browser();init_sdk_stream_mixin_browser();init_splitStream_browser();init_stream_type_check();no=Symbol.for("node-only");0;0;0;Uint8ArrayBlobAdapter=class extends(bindUint8ArrayBlobAdapter(toUtf8,fromUtf8,toBase64,fromBase64)){};_getRandomValues=array=>crypto.getRandomValues(array);v4=bindV4(_getRandomValues);generateIdempotencyToken=v4}}),init_tslib_es6=__esm({"node_modules/tslib/tslib.es6.mjs"(){extendStatics=function(d4,b3){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d5,b5){d5.__proto__=b5}||function(d5,b5){for(var p2 in b5)Object.prototype.hasOwnProperty.call(b5,p2)&&(d5[p2]=b5[p2])};return extendStatics(d4,b3)};__assign=function(){__assign=Object.assign||function __assign2(t9){var s2,i3,n3,p2;for(i3=1,n3=arguments.length;i3<n3;i3++){s2=arguments[i3];for(p2 in s2)Object.prototype.hasOwnProperty.call(s2,p2)&&(t9[p2]=s2[p2])}return t9};return __assign.apply(this,arguments)};__createBinding=Object.create?function(o2,m3,k2,k22){void 0===k22&&(k22=k2);var desc=Object.getOwnPropertyDescriptor(m3,k2);desc&&!("get"in desc?!m3.__esModule:desc.writable||desc.configurable)||(desc={enumerable:!0,get:function(){return m3[k2]}});Object.defineProperty(o2,k22,desc)}:function(o2,m3,k2,k22){void 0===k22&&(k22=k2);o2[k22]=m3[k2]};__setModuleDefault=Object.create?function(o2,v2){Object.defineProperty(o2,"default",{enumerable:!0,value:v2})}:function(o2,v2){o2.default=v2};ownKeys=function(o2){ownKeys=Object.getOwnPropertyNames||function(o3){var k2,ar2=[];for(k2 in o3)Object.prototype.hasOwnProperty.call(o3,k2)&&(ar2[ar2.length]=k2);return ar2};return ownKeys(o2)};_SuppressedError="function"==typeof SuppressedError?SuppressedError:function(error,suppressed,message){var e3=new Error(message);return e3.name="SuppressedError",e3.error=error,e3.suppressed=suppressed,e3};0}}),init_fromUtf8_browser2=__esm({"node_modules/@aws-crypto/util/node_modules/@smithy/util-utf8/dist-es/fromUtf8.browser.js"(){fromUtf82=input=>(new TextEncoder).encode(input)}}),init_toUint8Array=__esm({"node_modules/@aws-crypto/util/node_modules/@smithy/util-utf8/dist-es/toUint8Array.js"(){init_fromUtf8_browser2();0}}),init_toUtf8_browser2=__esm({"node_modules/@aws-crypto/util/node_modules/@smithy/util-utf8/dist-es/toUtf8.browser.js"(){}}),init_dist_es2=__esm({"node_modules/@aws-crypto/util/node_modules/@smithy/util-utf8/dist-es/index.js"(){init_fromUtf8_browser2();init_toUint8Array();init_toUtf8_browser2()}}),init_convertToBuffer=__esm({"node_modules/@aws-crypto/util/build/module/convertToBuffer.js"(){init_dist_es2();fromUtf83="undefined"!=typeof Buffer&&Buffer.from?function(input){return Buffer.from(input,"utf8")}:fromUtf82}}),init_isEmptyData=__esm({"node_modules/@aws-crypto/util/build/module/isEmptyData.js"(){}}),init_numToUint8=__esm({"node_modules/@aws-crypto/util/build/module/numToUint8.js"(){}}),init_uint32ArrayFrom=__esm({"node_modules/@aws-crypto/util/build/module/uint32ArrayFrom.js"(){}}),init_module=__esm({"node_modules/@aws-crypto/util/build/module/index.js"(){init_convertToBuffer();init_isEmptyData();init_numToUint8();init_uint32ArrayFrom()}}),init_aws_crc32=__esm({"node_modules/@aws-crypto/crc32/build/module/aws_crc32.js"(){init_tslib_es6();init_module();init_module2();AwsCrc32=function(){function AwsCrc322(){this.crc32=new Crc32}AwsCrc322.prototype.update=function(toHash){isEmptyData(toHash)||this.crc32.update(convertToBuffer(toHash))};AwsCrc322.prototype.digest=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a13){return[2,numToUint8(this.crc32.digest())]})})};AwsCrc322.prototype.reset=function(){this.crc32=new Crc32};return AwsCrc322}()}}),init_module2=__esm({"node_modules/@aws-crypto/crc32/build/module/index.js"(){init_tslib_es6();init_module();init_aws_crc32();Crc32=function(){function Crc322(){this.checksum=4294967295}Crc322.prototype.update=function(data){var e_1,_a13,data_1,data_1_1,byte;try{for(data_1=__values(data),data_1_1=data_1.next();!data_1_1.done;data_1_1=data_1.next()){byte=data_1_1.value;this.checksum=this.checksum>>>8^lookupTable[255&(this.checksum^byte)]}}catch(e_1_1){e_1={error:e_1_1}}finally{try{data_1_1&&!data_1_1.done&&(_a13=data_1.return)&&_a13.call(data_1)}finally{if(e_1)throw e_1.error}}return this};Crc322.prototype.digest=function(){return(4294967295^this.checksum)>>>0};return Crc322}();a_lookUpTable=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117];lookupTable=uint32ArrayFrom(a_lookUpTable)}}),init_Int64=__esm({"node_modules/@smithy/core/dist-es/submodules/event-streams/eventstream-codec/Int64.js"(){init_index_browser2();Int64=class _Int64{constructor(bytes){__publicField(this,"bytes");this.bytes=bytes;if(8!==bytes.byteLength)throw new Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(number){if(number>0x8000000000000000||number<-0x8000000000000000)throw new Error(`${number} is too large (or, if negative, too small) to represent as an Int64`);const bytes=new Uint8Array(8);for(let i3=7,remaining=Math.abs(Math.round(number));i3>-1&&remaining>0;i3--,remaining/=256)bytes[i3]=remaining;number<0&&negate(bytes);return new _Int64(bytes)}valueOf(){const bytes=this.bytes.slice(0),negative=128&bytes[0];negative&&negate(bytes);return parseInt(toHex2(bytes),16)*(negative?-1:1)}toString(){return String(this.valueOf())}}}}),init_HeaderMarshaller=__esm({"node_modules/@smithy/core/dist-es/submodules/event-streams/eventstream-codec/HeaderMarshaller.js"(){init_index_browser2();init_Int64();HeaderMarshaller=class{constructor(toUtf82,fromUtf85){__publicField(this,"toUtf8");__publicField(this,"fromUtf8");this.toUtf8=toUtf82;this.fromUtf8=fromUtf85}format(headers){const chunks=[];for(const headerName of Object.keys(headers)){const bytes=this.fromUtf8(headerName);chunks.push(Uint8Array.from([bytes.byteLength]),bytes,this.formatHeaderValue(headers[headerName]))}const out=new Uint8Array(chunks.reduce((carry,bytes)=>carry+bytes.byteLength,0));let position=0;for(const chunk of chunks){out.set(chunk,position);position+=chunk.byteLength}return out}formatHeaderValue(header){switch(header.type){case"boolean":return Uint8Array.from([header.value?0:1]);case"byte":return Uint8Array.from([2,header.value]);case"short":const shortView=new DataView(new ArrayBuffer(3));shortView.setUint8(0,3);shortView.setInt16(1,header.value,!1);return new Uint8Array(shortView.buffer);case"integer":const intView=new DataView(new ArrayBuffer(5));intView.setUint8(0,4);intView.setInt32(1,header.value,!1);return new Uint8Array(intView.buffer);case"long":const longBytes=new Uint8Array(9);longBytes[0]=5;longBytes.set(header.value.bytes,1);return longBytes;case"binary":const binView=new DataView(new ArrayBuffer(3+header.value.byteLength));binView.setUint8(0,6);binView.setUint16(1,header.value.byteLength,!1);const binBytes=new Uint8Array(binView.buffer);binBytes.set(header.value,3);return binBytes;case"string":const utf8Bytes=this.fromUtf8(header.value),strView=new DataView(new ArrayBuffer(3+utf8Bytes.byteLength));strView.setUint8(0,7);strView.setUint16(1,utf8Bytes.byteLength,!1);const strBytes=new Uint8Array(strView.buffer);strBytes.set(utf8Bytes,3);return strBytes;case"timestamp":const tsBytes=new Uint8Array(9);tsBytes[0]=8;tsBytes.set(Int64.fromNumber(header.value.valueOf()).bytes,1);return tsBytes;case"uuid":if(!UUID_PATTERN.test(header.value))throw new Error(`Invalid UUID received: ${header.value}`);const uuidBytes=new Uint8Array(17);uuidBytes[0]=9;uuidBytes.set(fromHex(header.value.replace(/\-/g,"")),1);return uuidBytes}}parse(headers){const out={};let position=0;for(;position<headers.byteLength;){const nameLength=headers.getUint8(position++),name=this.toUtf8(new Uint8Array(headers.buffer,headers.byteOffset+position,nameLength));position+=nameLength;switch(headers.getUint8(position++)){case 0:out[name]={type:BOOLEAN_TAG,value:!0};break;case 1:out[name]={type:BOOLEAN_TAG,value:!1};break;case 2:out[name]={type:BYTE_TAG,value:headers.getInt8(position++)};break;case 3:out[name]={type:SHORT_TAG,value:headers.getInt16(position,!1)};position+=2;break;case 4:out[name]={type:INT_TAG,value:headers.getInt32(position,!1)};position+=4;break;case 5:out[name]={type:LONG_TAG,value:new Int64(new Uint8Array(headers.buffer,headers.byteOffset+position,8))};position+=8;break;case 6:const binaryLength=headers.getUint16(position,!1);position+=2;out[name]={type:BINARY_TAG,value:new Uint8Array(headers.buffer,headers.byteOffset+position,binaryLength)};position+=binaryLength;break;case 7:const stringLength=headers.getUint16(position,!1);position+=2;out[name]={type:STRING_TAG,value:this.toUtf8(new Uint8Array(headers.buffer,headers.byteOffset+position,stringLength))};position+=stringLength;break;case 8:out[name]={type:TIMESTAMP_TAG,value:new Date(new Int64(new Uint8Array(headers.buffer,headers.byteOffset+position,8)).valueOf())};position+=8;break;case 9:const uuidBytes=new Uint8Array(headers.buffer,headers.byteOffset+position,16);position+=16;out[name]={type:UUID_TAG,value:`${toHex2(uuidBytes.subarray(0,4))}-${toHex2(uuidBytes.subarray(4,6))}-${toHex2(uuidBytes.subarray(6,8))}-${toHex2(uuidBytes.subarray(8,10))}-${toHex2(uuidBytes.subarray(10))}`};break;default:throw new Error("Unrecognized header type tag")}}return out}};(function(HEADER_VALUE_TYPE4){HEADER_VALUE_TYPE4[HEADER_VALUE_TYPE4.boolTrue=0]="boolTrue";HEADER_VALUE_TYPE4[HEADER_VALUE_TYPE4.boolFalse=1]="boolFalse";HEADER_VALUE_TYPE4[HEADER_VALUE_TYPE4.byte=2]="byte";HEADER_VALUE_TYPE4[HEADER_VALUE_TYPE4.short=3]="short";HEADER_VALUE_TYPE4[HEADER_VALUE_TYPE4.integer=4]="integer";HEADER_VALUE_TYPE4[HEADER_VALUE_TYPE4.long=5]="long";HEADER_VALUE_TYPE4[HEADER_VALUE_TYPE4.byteArray=6]="byteArray";HEADER_VALUE_TYPE4[HEADER_VALUE_TYPE4.string=7]="string";HEADER_VALUE_TYPE4[HEADER_VALUE_TYPE4.timestamp=8]="timestamp";HEADER_VALUE_TYPE4[HEADER_VALUE_TYPE4.uuid=9]="uuid"})(HEADER_VALUE_TYPE||(HEADER_VALUE_TYPE={}));BOOLEAN_TAG="boolean";BYTE_TAG="byte";SHORT_TAG="short";INT_TAG="integer";LONG_TAG="long";BINARY_TAG="binary";STRING_TAG="string";TIMESTAMP_TAG="timestamp";UUID_TAG="uuid";UUID_PATTERN=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/}}),init_splitMessage=__esm({"node_modules/@smithy/core/dist-es/submodules/event-streams/eventstream-codec/splitMessage.js"(){init_module2();PRELUDE_MEMBER_LENGTH=4;PRELUDE_LENGTH=2*PRELUDE_MEMBER_LENGTH;CHECKSUM_LENGTH=4;MINIMUM_MESSAGE_LENGTH=PRELUDE_LENGTH+2*CHECKSUM_LENGTH}}),init_EventStreamCodec=__esm({"node_modules/@smithy/core/dist-es/submodules/event-streams/eventstream-codec/EventStreamCodec.js"(){init_module2();init_HeaderMarshaller();init_splitMessage();EventStreamCodec=class{constructor(toUtf82,fromUtf85){__publicField(this,"headerMarshaller");__publicField(this,"messageBuffer");__publicField(this,"isEndOfStream");this.headerMarshaller=new HeaderMarshaller(toUtf82,fromUtf85);this.messageBuffer=[];this.isEndOfStream=!1}feed(message){this.messageBuffer.push(this.decode(message))}endOfStream(){this.isEndOfStream=!0}getMessage(){const message=this.messageBuffer.pop(),isEndOfStream=this.isEndOfStream;return{getMessage:()=>message,isEndOfStream:()=>isEndOfStream}}getAvailableMessages(){const messages=this.messageBuffer;this.messageBuffer=[];const isEndOfStream=this.isEndOfStream;return{getMessages:()=>messages,isEndOfStream:()=>isEndOfStream}}encode({headers:rawHeaders,body}){const headers=this.headerMarshaller.format(rawHeaders),length=headers.byteLength+body.byteLength+16,out=new Uint8Array(length),view=new DataView(out.buffer,out.byteOffset,out.byteLength),checksum=new Crc32;view.setUint32(0,length,!1);view.setUint32(4,headers.byteLength,!1);view.setUint32(8,checksum.update(out.subarray(0,8)).digest(),!1);out.set(headers,12);out.set(body,headers.byteLength+12);view.setUint32(length-4,checksum.update(out.subarray(8,length-4)).digest(),!1);return out}decode(message){const{headers,body}=splitMessage(message);return{headers:this.headerMarshaller.parse(headers),body}}formatHeaders(rawHeaders){return this.headerMarshaller.format(rawHeaders)}}}}),init_MessageDecoderStream=__esm({"node_modules/@smithy/core/dist-es/submodules/event-streams/eventstream-codec/MessageDecoderStream.js"(){MessageDecoderStream=class{constructor(options){__publicField(this,"options");this.options=options}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(const bytes of this.options.inputStream){const decoded=this.options.decoder.decode(bytes);yield decoded}}}}}),init_MessageEncoderStream=__esm({"node_modules/@smithy/core/dist-es/submodules/event-streams/eventstream-codec/MessageEncoderStream.js"(){MessageEncoderStream=class{constructor(options){__publicField(this,"options");this.options=options}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(const msg of this.options.messageStream){const encoded=this.options.encoder.encode(msg);yield encoded}this.options.includeEndFrame&&(yield new Uint8Array(0))}}}}),init_SmithyMessageDecoderStream=__esm({"node_modules/@smithy/core/dist-es/submodules/event-streams/eventstream-codec/SmithyMessageDecoderStream.js"(){SmithyMessageDecoderStream=class{constructor(options){__publicField(this,"options");this.options=options}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(const message of this.options.messageStream){const deserialized=await this.options.deserializer(message);void 0!==deserialized&&(yield deserialized)}}}}}),init_SmithyMessageEncoderStream=__esm({"node_modules/@smithy/core/dist-es/submodules/event-streams/eventstream-codec/SmithyMessageEncoderStream.js"(){SmithyMessageEncoderStream=class{constructor(options){__publicField(this,"options");this.options=options}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(const chunk of this.options.inputStream){const payloadBuf=this.options.serializer(chunk);yield payloadBuf}}}}}),init_getChunkedStream=__esm({"node_modules/@smithy/core/dist-es/submodules/event-streams/eventstream-serde-universal/getChunkedStream.js"(){}}),init_getUnmarshalledStream=__esm({"node_modules/@smithy/core/dist-es/submodules/event-streams/eventstream-serde-universal/getUnmarshalledStream.js"(){}}),init_EventStreamMarshaller=__esm({"node_modules/@smithy/core/dist-es/submodules/event-streams/eventstream-serde-universal/EventStreamMarshaller.js"(){init_EventStreamCodec();init_MessageDecoderStream();init_MessageEncoderStream();init_SmithyMessageDecoderStream();init_SmithyMessageEncoderStream();init_getChunkedStream();init_getUnmarshalledStream();EventStreamMarshaller=class{constructor({utf8Encoder,utf8Decoder}){__publicField(this,"eventStreamCodec");__publicField(this,"utfEncoder");this.eventStreamCodec=new EventStreamCodec(utf8Encoder,utf8Decoder);this.utfEncoder=utf8Encoder}deserialize(body,deserializer){const inputStream=getChunkedStream(body);return new SmithyMessageDecoderStream({messageStream:new MessageDecoderStream({inputStream,decoder:this.eventStreamCodec}),deserializer:getMessageUnmarshaller(deserializer,this.utfEncoder)})}serialize(inputStream,serializer){return new MessageEncoderStream({messageStream:new SmithyMessageEncoderStream({inputStream,serializer}),encoder:this.eventStreamCodec,includeEndFrame:!0})}};eventStreamSerdeProvider=options=>new EventStreamMarshaller(options)}}),init_utils=__esm({"node_modules/@smithy/core/dist-es/submodules/event-streams/eventstream-serde/utils.js"(){readableStreamToIterable=readableStream=>({[Symbol.asyncIterator]:async function*(){const reader=readableStream.getReader();try{for(;;){const{done,value}=await reader.read();if(done)return;yield value}}finally{reader.releaseLock()}}});iterableToReadableStream=asyncIterable=>{const iterator=asyncIterable[Symbol.asyncIterator]();return new ReadableStream({async pull(controller){const{done,value}=await iterator.next();if(done)return controller.close();controller.enqueue(value)}})}}}),init_EventStreamMarshaller_browser=__esm({"node_modules/@smithy/core/dist-es/submodules/event-streams/eventstream-serde/EventStreamMarshaller.browser.js"(){init_EventStreamMarshaller();init_utils();EventStreamMarshaller2=class{constructor({utf8Encoder,utf8Decoder}){__publicField(this,"universalMarshaller");this.universalMarshaller=new EventStreamMarshaller({utf8Decoder,utf8Encoder})}deserialize(body,deserializer){const bodyIterable=isReadableStream2(body)?readableStreamToIterable(body):body;return this.universalMarshaller.deserialize(bodyIterable,deserializer)}serialize(input,serializer){const serializedIterable=this.universalMarshaller.serialize(input,serializer);return"function"==typeof ReadableStream?iterableToReadableStream(serializedIterable):serializedIterable}};isReadableStream2=body=>"function"==typeof ReadableStream&&body instanceof ReadableStream;eventStreamSerdeProvider2=options=>new EventStreamMarshaller2(options)}}),init_EventStreamSerdeConfig=__esm({"node_modules/@smithy/core/dist-es/submodules/event-streams/eventstream-serde-config-resolver/EventStreamSerdeConfig.js"(){resolveEventStreamSerdeConfig=input=>Object.assign(input,{eventStreamMarshaller:input.eventStreamSerdeProvider(input)})}}),init_EventStreamSerde=__esm({"node_modules/@smithy/core/dist-es/submodules/event-streams/EventStreamSerde.js"(){init_index_browser2();EventStreamSerde=class{constructor({marshaller,serializer,deserializer,serdeContext,defaultContentType}){__publicField(this,"marshaller");__publicField(this,"serializer");__publicField(this,"deserializer");__publicField(this,"serdeContext");__publicField(this,"defaultContentType");this.marshaller=marshaller;this.serializer=serializer;this.deserializer=deserializer;this.serdeContext=serdeContext;this.defaultContentType=defaultContentType}async serializeEventStream({eventStream,requestSchema,initialRequest}){const marshaller=this.marshaller,eventStreamMember=requestSchema.getEventStreamMember(),unionSchema=requestSchema.getMemberSchema(eventStreamMember),serializer=this.serializer,defaultContentType=this.defaultContentType,initialRequestMarker=Symbol("initialRequestMarker"),eventStreamIterable={async*[Symbol.asyncIterator](){if(initialRequest){const headers={":event-type":{type:"string",value:"initial-request"},":message-type":{type:"string",value:"event"},":content-type":{type:"string",value:defaultContentType}};serializer.write(requestSchema,initialRequest);const body=serializer.flush();yield{[initialRequestMarker]:!0,headers,body}}for await(const page of eventStream)yield page}};return marshaller.serialize(eventStreamIterable,event2=>{if(event2[initialRequestMarker])return{headers:event2.headers,body:event2.body};let unionMember="";for(const key3 in event2)if("__type"!==key3){unionMember=key3;break}const{additionalHeaders,body,eventType,explicitPayloadContentType}=this.writeEventBody(unionMember,unionSchema,event2),headers={":event-type":{type:"string",value:eventType},":message-type":{type:"string",value:"event"},":content-type":{type:"string",value:null!=explicitPayloadContentType?explicitPayloadContentType:defaultContentType},...additionalHeaders};return{headers,body}})}async deserializeEventStream({response,responseSchema,initialResponseContainer}){var _a13;const marshaller=this.marshaller,eventStreamMember=responseSchema.getEventStreamMember(),unionSchema=responseSchema.getMemberSchema(eventStreamMember),memberSchemas=unionSchema.getMemberSchemas(),initialResponseMarker=Symbol("initialResponseMarker"),asyncIterable=marshaller.deserialize(response.body,async event2=>{var _a14,_b6,_c3;let unionMember="";for(const key3 in event2)if("__type"!==key3){unionMember=key3;break}const body=event2[unionMember].body;if("initial-response"===unionMember){const dataObject=await this.deserializer.read(responseSchema,body);delete dataObject[eventStreamMember];return{[initialResponseMarker]:!0,...dataObject}}if(unionMember in memberSchemas){const eventStreamSchema=memberSchemas[unionMember];if(eventStreamSchema.isStructSchema()){const out={};let hasBindings=!1;for(const[name,member2]of eventStreamSchema.structIterator()){const{eventHeader,eventPayload}=member2.getMergedTraits();hasBindings=hasBindings||Boolean(eventHeader||eventPayload);if(eventPayload)member2.isBlobSchema()?out[name]=body:member2.isStringSchema()?out[name]=(null!=(_b6=null==(_a14=this.serdeContext)?void 0:_a14.utf8Encoder)?_b6:toUtf8)(body):member2.isStructSchema()&&(out[name]=await this.deserializer.read(member2,body));else if(eventHeader){const value=null==(_c3=event2[unionMember].headers[name])?void 0:_c3.value;null!=value&&(member2.isNumericSchema()?out[name]=value&&"object"==typeof value&&"bytes"in value?BigInt(value.toString()):Number(value):out[name]=value)}}if(hasBindings)return{[unionMember]:out};if(0===body.byteLength)return{[unionMember]:{}}}return{[unionMember]:await this.deserializer.read(eventStreamSchema,body)}}return{$unknown:event2}}),asyncIterator=asyncIterable[Symbol.asyncIterator](),firstEvent=await asyncIterator.next();if(firstEvent.done)return asyncIterable;if(null==(_a13=firstEvent.value)?void 0:_a13[initialResponseMarker]){if(!responseSchema)throw new Error("@smithy::core/protocols - initial-response event encountered in event stream but no response schema given.");for(const key3 in firstEvent.value)initialResponseContainer[key3]=firstEvent.value[key3]}return{async*[Symbol.asyncIterator](){var _a14;(null==(_a14=null==firstEvent?void 0:firstEvent.value)?void 0:_a14[initialResponseMarker])||(yield firstEvent.value);for(;;){const{done,value}=await asyncIterator.next();if(done)break;yield value}}}}writeEventBody(unionMember,unionSchema,event2){var _a13,_b6,_c3;const serializer=this.serializer;let explicitPayloadContentType,eventType=unionMember,explicitPayloadMember=null;const isKnownSchema=(()=>{const struct=unionSchema.getSchema();return struct[4].includes(unionMember)})(),additionalHeaders={};if(isKnownSchema){const eventSchema=unionSchema.getMemberSchema(unionMember);if(eventSchema.isStructSchema()){for(const[memberName,memberSchema]of eventSchema.structIterator()){const{eventHeader,eventPayload}=memberSchema.getMergedTraits();if(eventPayload)explicitPayloadMember=memberName;else if(eventHeader){const value=event2[unionMember][memberName];let type="binary";memberSchema.isNumericSchema()?type=(-2)**31<=value&&value<=2**31-1?"integer":"long":memberSchema.isTimestampSchema()?type="timestamp":memberSchema.isStringSchema()?type="string":memberSchema.isBooleanSchema()&&(type="boolean");if(null!=value){additionalHeaders[memberName]={type,value};delete event2[unionMember][memberName]}}}if(null!==explicitPayloadMember){const payloadSchema=eventSchema.getMemberSchema(explicitPayloadMember);payloadSchema.isBlobSchema()?explicitPayloadContentType="application/octet-stream":payloadSchema.isStringSchema()&&(explicitPayloadContentType="text/plain");serializer.write(payloadSchema,event2[unionMember][explicitPayloadMember])}else serializer.write(eventSchema,event2[unionMember])}else{if(!eventSchema.isUnitSchema())throw new Error("@smithy/core/event-streams - non-struct member not supported in event stream union.");serializer.write(eventSchema,{})}}else{const[type,value]=event2[unionMember];eventType=type;serializer.write(15,value)}const messageSerialization=null!=(_a13=serializer.flush())?_a13:new Uint8Array,body="string"==typeof messageSerialization?(null!=(_c3=null==(_b6=this.serdeContext)?void 0:_b6.utf8Decoder)?_c3:fromUtf8)(messageSerialization):messageSerialization;return{body,eventType,explicitPayloadContentType,additionalHeaders}}}}}),index_browser_exports={};
/*! Bundled license information:
octagonal-wheels/dist/encoding/encodeobject.js:
(* istanbul ignore if -- @preserve *)
@noble/secp256k1/index.js:
(*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) *)
octagonal-wheels/dist/encryption/hkdf.js:
(* istanbul ignore if -- @preserve *)
(* istanbul ignore next -- @preserve *)
*/__export(index_browser_exports,{EventStreamCodec:()=>EventStreamCodec,EventStreamMarshaller:()=>EventStreamMarshaller2,EventStreamSerde:()=>EventStreamSerde,HeaderMarshaller:()=>HeaderMarshaller,Int64:()=>Int64,MessageDecoderStream:()=>MessageDecoderStream,MessageEncoderStream:()=>MessageEncoderStream,SmithyMessageDecoderStream:()=>SmithyMessageDecoderStream,SmithyMessageEncoderStream:()=>SmithyMessageEncoderStream,UniversalEventStreamMarshaller:()=>EventStreamMarshaller,eventStreamSerdeProvider:()=>eventStreamSerdeProvider2,getChunkedStream:()=>getChunkedStream,getMessageUnmarshaller:()=>getMessageUnmarshaller,getUnmarshalledStream:()=>getUnmarshalledStream,iterableToReadableStream:()=>iterableToReadableStream,readableStreamToIterable:()=>readableStreamToIterable,resolveEventStreamSerdeConfig:()=>resolveEventStreamSerdeConfig,universalEventStreamSerdeProvider:()=>eventStreamSerdeProvider});init_index_browser3=__esm({"node_modules/@smithy/core/dist-es/submodules/event-streams/index.browser.js"(){init_EventStreamCodec();init_HeaderMarshaller();init_Int64();init_MessageDecoderStream();init_MessageEncoderStream();init_SmithyMessageDecoderStream();init_SmithyMessageEncoderStream();init_EventStreamMarshaller_browser();init_utils();init_EventStreamMarshaller();init_getChunkedStream();init_getUnmarshalledStream();init_EventStreamSerdeConfig();init_EventStreamSerde()}});require_spark_md5=__commonJS({"node_modules/spark-md5/spark-md5.js"(exports,module2){(function(factory){if("object"==typeof exports)module2.exports=factory();else if("function"==typeof define&&define.amd)define(factory);else{var glob;try{glob=window}catch(e3){glob=self}glob.SparkMD5=factory()}})(function(undefined2){"use strict";function md5cycle(x3,k2){var a2=x3[0],b3=x3[1],c3=x3[2],d4=x3[3];a2+=(b3&c3|~b3&d4)+k2[0]-680876936|0;a2=(a2<<7|a2>>>25)+b3|0;d4+=(a2&b3|~a2&c3)+k2[1]-389564586|0;d4=(d4<<12|d4>>>20)+a2|0;c3+=(d4&a2|~d4&b3)+k2[2]+606105819|0;c3=(c3<<17|c3>>>15)+d4|0;b3+=(c3&d4|~c3&a2)+k2[3]-1044525330|0;b3=(b3<<22|b3>>>10)+c3|0;a2+=(b3&c3|~b3&d4)+k2[4]-176418897|0;a2=(a2<<7|a2>>>25)+b3|0;d4+=(a2&b3|~a2&c3)+k2[5]+1200080426|0;d4=(d4<<12|d4>>>20)+a2|0;c3+=(d4&a2|~d4&b3)+k2[6]-1473231341|0;c3=(c3<<17|c3>>>15)+d4|0;b3+=(c3&d4|~c3&a2)+k2[7]-45705983|0;b3=(b3<<22|b3>>>10)+c3|0;a2+=(b3&c3|~b3&d4)+k2[8]+1770035416|0;a2=(a2<<7|a2>>>25)+b3|0;d4+=(a2&b3|~a2&c3)+k2[9]-1958414417|0;d4=(d4<<12|d4>>>20)+a2|0;c3+=(d4&a2|~d4&b3)+k2[10]-42063|0;c3=(c3<<17|c3>>>15)+d4|0;b3+=(c3&d4|~c3&a2)+k2[11]-1990404162|0;b3=(b3<<22|b3>>>10)+c3|0;a2+=(b3&c3|~b3&d4)+k2[12]+1804603682|0;a2=(a2<<7|a2>>>25)+b3|0;d4+=(a2&b3|~a2&c3)+k2[13]-40341101|0;d4=(d4<<12|d4>>>20)+a2|0;c3+=(d4&a2|~d4&b3)+k2[14]-1502002290|0;c3=(c3<<17|c3>>>15)+d4|0;b3+=(c3&d4|~c3&a2)+k2[15]+1236535329|0;b3=(b3<<22|b3>>>10)+c3|0;a2+=(b3&d4|c3&~d4)+k2[1]-165796510|0;a2=(a2<<5|a2>>>27)+b3|0;d4+=(a2&c3|b3&~c3)+k2[6]-1069501632|0;d4=(d4<<9|d4>>>23)+a2|0;c3+=(d4&b3|a2&~b3)+k2[11]+643717713|0;c3=(c3<<14|c3>>>18)+d4|0;b3+=(c3&a2|d4&~a2)+k2[0]-373897302|0;b3=(b3<<20|b3>>>12)+c3|0;a2+=(b3&d4|c3&~d4)+k2[5]-701558691|0;a2=(a2<<5|a2>>>27)+b3|0;d4+=(a2&c3|b3&~c3)+k2[10]+38016083|0;d4=(d4<<9|d4>>>23)+a2|0;c3+=(d4&b3|a2&~b3)+k2[15]-660478335|0;c3=(c3<<14|c3>>>18)+d4|0;b3+=(c3&a2|d4&~a2)+k2[4]-405537848|0;b3=(b3<<20|b3>>>12)+c3|0;a2+=(b3&d4|c3&~d4)+k2[9]+568446438|0;a2=(a2<<5|a2>>>27)+b3|0;d4+=(a2&c3|b3&~c3)+k2[14]-1019803690|0;d4=(d4<<9|d4>>>23)+a2|0;c3+=(d4&b3|a2&~b3)+k2[3]-187363961|0;c3=(c3<<14|c3>>>18)+d4|0;b3+=(c3&a2|d4&~a2)+k2[8]+1163531501|0;b3=(b3<<20|b3>>>12)+c3|0;a2+=(b3&d4|c3&~d4)+k2[13]-1444681467|0;a2=(a2<<5|a2>>>27)+b3|0;d4+=(a2&c3|b3&~c3)+k2[2]-51403784|0;d4=(d4<<9|d4>>>23)+a2|0;c3+=(d4&b3|a2&~b3)+k2[7]+1735328473|0;c3=(c3<<14|c3>>>18)+d4|0;b3+=(c3&a2|d4&~a2)+k2[12]-1926607734|0;b3=(b3<<20|b3>>>12)+c3|0;a2+=(b3^c3^d4)+k2[5]-378558|0;a2=(a2<<4|a2>>>28)+b3|0;d4+=(a2^b3^c3)+k2[8]-2022574463|0;d4=(d4<<11|d4>>>21)+a2|0;c3+=(d4^a2^b3)+k2[11]+1839030562|0;c3=(c3<<16|c3>>>16)+d4|0;b3+=(c3^d4^a2)+k2[14]-35309556|0;b3=(b3<<23|b3>>>9)+c3|0;a2+=(b3^c3^d4)+k2[1]-1530992060|0;a2=(a2<<4|a2>>>28)+b3|0;d4+=(a2^b3^c3)+k2[4]+1272893353|0;d4=(d4<<11|d4>>>21)+a2|0;c3+=(d4^a2^b3)+k2[7]-155497632|0;c3=(c3<<16|c3>>>16)+d4|0;b3+=(c3^d4^a2)+k2[10]-1094730640|0;b3=(b3<<23|b3>>>9)+c3|0;a2+=(b3^c3^d4)+k2[13]+681279174|0;a2=(a2<<4|a2>>>28)+b3|0;d4+=(a2^b3^c3)+k2[0]-358537222|0;d4=(d4<<11|d4>>>21)+a2|0;c3+=(d4^a2^b3)+k2[3]-722521979|0;c3=(c3<<16|c3>>>16)+d4|0;b3+=(c3^d4^a2)+k2[6]+76029189|0;b3=(b3<<23|b3>>>9)+c3|0;a2+=(b3^c3^d4)+k2[9]-640364487|0;a2=(a2<<4|a2>>>28)+b3|0;d4+=(a2^b3^c3)+k2[12]-421815835|0;d4=(d4<<11|d4>>>21)+a2|0;c3+=(d4^a2^b3)+k2[15]+530742520|0;c3=(c3<<16|c3>>>16)+d4|0;b3+=(c3^d4^a2)+k2[2]-995338651|0;b3=(b3<<23|b3>>>9)+c3|0;a2+=(c3^(b3|~d4))+k2[0]-198630844|0;a2=(a2<<6|a2>>>26)+b3|0;d4+=(b3^(a2|~c3))+k2[7]+1126891415|0;d4=(d4<<10|d4>>>22)+a2|0;c3+=(a2^(d4|~b3))+k2[14]-1416354905|0;c3=(c3<<15|c3>>>17)+d4|0;b3+=(d4^(c3|~a2))+k2[5]-57434055|0;b3=(b3<<21|b3>>>11)+c3|0;a2+=(c3^(b3|~d4))+k2[12]+1700485571|0;a2=(a2<<6|a2>>>26)+b3|0;d4+=(b3^(a2|~c3))+k2[3]-1894986606|0;d4=(d4<<10|d4>>>22)+a2|0;c3+=(a2^(d4|~b3))+k2[10]-1051523|0;c3=(c3<<15|c3>>>17)+d4|0;b3+=(d4^(c3|~a2))+k2[1]-2054922799|0;b3=(b3<<21|b3>>>11)+c3|0;a2+=(c3^(b3|~d4))+k2[8]+1873313359|0;a2=(a2<<6|a2>>>26)+b3|0;d4+=(b3^(a2|~c3))+k2[15]-30611744|0;d4=(d4<<10|d4>>>22)+a2|0;c3+=(a2^(d4|~b3))+k2[6]-1560198380|0;c3=(c3<<15|c3>>>17)+d4|0;b3+=(d4^(c3|~a2))+k2[13]+1309151649|0;b3=(b3<<21|b3>>>11)+c3|0;a2+=(c3^(b3|~d4))+k2[4]-145523070|0;a2=(a2<<6|a2>>>26)+b3|0;d4+=(b3^(a2|~c3))+k2[11]-1120210379|0;d4=(d4<<10|d4>>>22)+a2|0;c3+=(a2^(d4|~b3))+k2[2]+718787259|0;c3=(c3<<15|c3>>>17)+d4|0;b3+=(d4^(c3|~a2))+k2[9]-343485551|0;b3=(b3<<21|b3>>>11)+c3|0;x3[0]=a2+x3[0]|0;x3[1]=b3+x3[1]|0;x3[2]=c3+x3[2]|0;x3[3]=d4+x3[3]|0}function md5blk(s2){var i3,md5blks=[];for(i3=0;i3<64;i3+=4)md5blks[i3>>2]=s2.charCodeAt(i3)+(s2.charCodeAt(i3+1)<<8)+(s2.charCodeAt(i3+2)<<16)+(s2.charCodeAt(i3+3)<<24);return md5blks}function md5blk_array(a2){var i3,md5blks=[];for(i3=0;i3<64;i3+=4)md5blks[i3>>2]=a2[i3]+(a2[i3+1]<<8)+(a2[i3+2]<<16)+(a2[i3+3]<<24);return md5blks}function md51(s2){var i3,length,tail,tmp,lo,hi,n3=s2.length,state2=[1732584193,-271733879,-1732584194,271733878];for(i3=64;i3<=n3;i3+=64)md5cycle(state2,md5blk(s2.substring(i3-64,i3)));s2=s2.substring(i3-64);length=s2.length;tail=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(i3=0;i3<length;i3+=1)tail[i3>>2]|=s2.charCodeAt(i3)<<(i3%4<<3);tail[i3>>2]|=128<<(i3%4<<3);if(i3>55){md5cycle(state2,tail);for(i3=0;i3<16;i3+=1)tail[i3]=0}tmp=8*n3;tmp=tmp.toString(16).match(/(.*?)(.{0,8})$/);lo=parseInt(tmp[2],16);hi=parseInt(tmp[1],16)||0;tail[14]=lo;tail[15]=hi;md5cycle(state2,tail);return state2}function md51_array(a2){var i3,length,tail,tmp,lo,hi,n3=a2.length,state2=[1732584193,-271733879,-1732584194,271733878];for(i3=64;i3<=n3;i3+=64)md5cycle(state2,md5blk_array(a2.subarray(i3-64,i3)));a2=i3-64<n3?a2.subarray(i3-64):new Uint8Array(0);length=a2.length;tail=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(i3=0;i3<length;i3+=1)tail[i3>>2]|=a2[i3]<<(i3%4<<3);tail[i3>>2]|=128<<(i3%4<<3);if(i3>55){md5cycle(state2,tail);for(i3=0;i3<16;i3+=1)tail[i3]=0}tmp=8*n3;tmp=tmp.toString(16).match(/(.*?)(.{0,8})$/);lo=parseInt(tmp[2],16);hi=parseInt(tmp[1],16)||0;tail[14]=lo;tail[15]=hi;md5cycle(state2,tail);return state2}function rhex(n3){var j2,s2="";for(j2=0;j2<4;j2+=1)s2+=hex_chr[n3>>8*j2+4&15]+hex_chr[n3>>8*j2&15];return s2}function hex(x3){var i3;for(i3=0;i3<x3.length;i3+=1)x3[i3]=rhex(x3[i3]);return x3.join("")}function toUtf82(str){/[\u0080-\uFFFF]/.test(str)&&(str=unescape(encodeURIComponent(str)));return str}function utf8Str2ArrayBuffer(str,returnUInt8Array){var i3,length=str.length,buff=new ArrayBuffer(length),arr=new Uint8Array(buff);for(i3=0;i3<length;i3+=1)arr[i3]=str.charCodeAt(i3);return returnUInt8Array?arr:buff}function arrayBuffer2Utf8Str(buff){return String.fromCharCode.apply(null,new Uint8Array(buff))}function concatenateArrayBuffers(first,second,returnUInt8Array){var result=new Uint8Array(first.byteLength+second.byteLength);result.set(new Uint8Array(first));result.set(new Uint8Array(second),first.byteLength);return returnUInt8Array?result:result.buffer}function hexToBinaryString(hex2){var x3,bytes=[],length=hex2.length;for(x3=0;x3<length-1;x3+=2)bytes.push(parseInt(hex2.substr(x3,2),16));return String.fromCharCode.apply(String,bytes)}function SparkMD5(){this.reset()}var hex_chr=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];"5d41402abc4b2a76b9719d911017c592"!==hex(md51("hello"))&&function(x3,y2){var lsw=(65535&x3)+(65535&y2),msw=(x3>>16)+(y2>>16)+(lsw>>16);return msw<<16|65535&lsw};"undefined"==typeof ArrayBuffer||ArrayBuffer.prototype.slice||function(){function clamp(val,length){val=0|val||0;return val<0?Math.max(val+length,0):Math.min(val,length)}ArrayBuffer.prototype.slice=function(from,to){var num,target,targetArray,sourceArray,length=this.byteLength,begin=clamp(from,length),end=length;to!==undefined2&&(end=clamp(to,length));if(begin>end)return new ArrayBuffer(0);num=end-begin;target=new ArrayBuffer(num);targetArray=new Uint8Array(target);sourceArray=new Uint8Array(this,begin,num);targetArray.set(sourceArray);return target}}();SparkMD5.prototype.append=function(str){this.appendBinary(toUtf82(str));return this};SparkMD5.prototype.appendBinary=function(contents){this._buff+=contents;this._length+=contents.length;var i3,length=this._buff.length;for(i3=64;i3<=length;i3+=64)md5cycle(this._hash,md5blk(this._buff.substring(i3-64,i3)));this._buff=this._buff.substring(i3-64);return this};SparkMD5.prototype.end=function(raw){var i3,ret,buff=this._buff,length=buff.length,tail=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(i3=0;i3<length;i3+=1)tail[i3>>2]|=buff.charCodeAt(i3)<<(i3%4<<3);this._finish(tail,length);ret=hex(this._hash);raw&&(ret=hexToBinaryString(ret));this.reset();return ret};SparkMD5.prototype.reset=function(){this._buff="";this._length=0;this._hash=[1732584193,-271733879,-1732584194,271733878];return this};SparkMD5.prototype.getState=function(){return{buff:this._buff,length:this._length,hash:this._hash.slice()}};SparkMD5.prototype.setState=function(state2){this._buff=state2.buff;this._length=state2.length;this._hash=state2.hash;return this};SparkMD5.prototype.destroy=function(){delete this._hash;delete this._buff;delete this._length};SparkMD5.prototype._finish=function(tail,length){var tmp,lo,hi,i3=length;tail[i3>>2]|=128<<(i3%4<<3);if(i3>55){md5cycle(this._hash,tail);for(i3=0;i3<16;i3+=1)tail[i3]=0}tmp=8*this._length;tmp=tmp.toString(16).match(/(.*?)(.{0,8})$/);lo=parseInt(tmp[2],16);hi=parseInt(tmp[1],16)||0;tail[14]=lo;tail[15]=hi;md5cycle(this._hash,tail)};SparkMD5.hash=function(str,raw){return SparkMD5.hashBinary(toUtf82(str),raw)};SparkMD5.hashBinary=function(content,raw){var hash3=md51(content),ret=hex(hash3);return raw?hexToBinaryString(ret):ret};SparkMD5.ArrayBuffer=function(){this.reset()};SparkMD5.ArrayBuffer.prototype.append=function(arr){var i3,buff=concatenateArrayBuffers(this._buff.buffer,arr,!0),length=buff.length;this._length+=arr.byteLength;for(i3=64;i3<=length;i3+=64)md5cycle(this._hash,md5blk_array(buff.subarray(i3-64,i3)));this._buff=i3-64<length?new Uint8Array(buff.buffer.slice(i3-64)):new Uint8Array(0);return this};SparkMD5.ArrayBuffer.prototype.end=function(raw){var i3,ret,buff=this._buff,length=buff.length,tail=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(i3=0;i3<length;i3+=1)tail[i3>>2]|=buff[i3]<<(i3%4<<3);this._finish(tail,length);ret=hex(this._hash);raw&&(ret=hexToBinaryString(ret));this.reset();return ret};SparkMD5.ArrayBuffer.prototype.reset=function(){this._buff=new Uint8Array(0);this._length=0;this._hash=[1732584193,-271733879,-1732584194,271733878];return this};SparkMD5.ArrayBuffer.prototype.getState=function(){var state2=SparkMD5.prototype.getState.call(this);state2.buff=arrayBuffer2Utf8Str(state2.buff);return state2};SparkMD5.ArrayBuffer.prototype.setState=function(state2){state2.buff=utf8Str2ArrayBuffer(state2.buff,!0);return SparkMD5.prototype.setState.call(this,state2)};SparkMD5.ArrayBuffer.prototype.destroy=SparkMD5.prototype.destroy;SparkMD5.ArrayBuffer.prototype._finish=SparkMD5.prototype._finish;SparkMD5.ArrayBuffer.hash=function(arr,raw){var hash3=md51_array(new Uint8Array(arr)),ret=hex(hash3);return raw?hexToBinaryString(ret):ret};return SparkMD5})}});require_vuvuzela=__commonJS({"node_modules/vuvuzela/index.js"(exports){"use strict";function pop3(obj,stack2,metaStack){var element2,lastElementIndex,key3,lastMetaElement=metaStack[metaStack.length-1];if(obj===lastMetaElement.element){metaStack.pop();lastMetaElement=metaStack[metaStack.length-1]}element2=lastMetaElement.element;lastElementIndex=lastMetaElement.index;if(Array.isArray(element2))element2.push(obj);else if(lastElementIndex===stack2.length-2){key3=stack2.pop();element2[key3]=obj}else stack2.push(obj)}exports.stringify=function stringify3(input){var res2,next2,obj,prefix,val,i3,arrayPrefix,keys3,k2,key3,value,objPrefix,queue2=[];queue2.push({obj:input});res2="";for(;next2=queue2.pop();){obj=next2.obj;prefix=next2.prefix||"";val=next2.val||"";res2+=prefix;if(val)res2+=val;else if("object"!=typeof obj)res2+=void 0===obj?null:JSON.stringify(obj);else if(null===obj)res2+="null";else if(Array.isArray(obj)){queue2.push({val:"]"});for(i3=obj.length-1;i3>=0;i3--){arrayPrefix=0===i3?"":",";queue2.push({obj:obj[i3],prefix:arrayPrefix})}queue2.push({val:"["})}else{keys3=[];for(k2 in obj)obj.hasOwnProperty(k2)&&keys3.push(k2);queue2.push({val:"}"});for(i3=keys3.length-1;i3>=0;i3--){key3=keys3[i3];value=obj[key3];objPrefix=i3>0?",":"";objPrefix+=JSON.stringify(key3)+":";queue2.push({obj:value,prefix:objPrefix})}queue2.push({val:"{"})}}return res2};exports.parse=function(str){for(var collationIndex2,parsedNum,numChar,parsedString,lastCh,numConsecutiveSlashes,ch4,arrayElement,objElement,stack2=[],metaStack=[],i3=0;;){collationIndex2=str[i3++];if("}"!==collationIndex2&&"]"!==collationIndex2&&void 0!==collationIndex2)switch(collationIndex2){case" ":case"\t":case"\n":case":":case",":break;case"n":i3+=3;pop3(null,stack2,metaStack);break;case"t":i3+=3;pop3(!0,stack2,metaStack);break;case"f":i3+=4;pop3(!1,stack2,metaStack);break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"-":parsedNum="";i3--;for(;;){numChar=str[i3++];if(!/[\d\.\-e\+]/.test(numChar)){i3--;break}parsedNum+=numChar}pop3(parseFloat(parsedNum),stack2,metaStack);break;case'"':parsedString="";lastCh=void 0;numConsecutiveSlashes=0;for(;;){ch4=str[i3++];if('"'===ch4&&("\\"!==lastCh||numConsecutiveSlashes%2!=1))break;parsedString+=ch4;lastCh=ch4;"\\"===lastCh?numConsecutiveSlashes++:numConsecutiveSlashes=0}pop3(JSON.parse('"'+parsedString+'"'),stack2,metaStack);break;case"[":arrayElement={element:[],index:stack2.length};stack2.push(arrayElement.element);metaStack.push(arrayElement);break;case"{":objElement={element:{},index:stack2.length};stack2.push(objElement.element);metaStack.push(objElement);break;default:throw new Error("unexpectedly reached end of input: "+collationIndex2)}else{if(1===stack2.length)return stack2.pop();pop3(stack2.pop(),stack2,metaStack)}}}}});require_pouchdb_wrappers=__commonJS({"node_modules/pouchdb-wrappers/index.js"(exports,module2){"use strict";function nodify(promise,callback){promise.then((...args)=>{callback(null,...args)}).catch(err3=>{callback(err3)})}function replacementMethod(base,method){return function(...args){function doMethod(){let callback=null;const minArgs="query"===method?1:0;args.length>minArgs&&"function"==typeof args[args.length-1]&&(callback=args.pop());let prev=base._originals[method].bind(base);for(const handler of base._handlers[method])prev=handler.bind(base,prev);const result=prev(...args);result.then&&callback&&nodify(result,callback);return result}if("changes"!==method&&base.taskqueue&&!base.taskqueue.isReady){const dbReady=new Promise((resolve,reject)=>{base.taskqueue.addTask(error=>{error?reject(error):resolve()})});return dbReady.then(doMethod)}return doMethod()}}var toExport={install:function installWrappers(base,handlers3={}){if(!base._originals||!base._handlers){base._originals={};base._handlers={}}for(const[method,handler]of Object.entries(handlers3)){if(!(method in base))throw new Error(`Method '${method}' does not exist on given base, so it cannot be wrapped.`);method in base._originals||(base._originals[method]=base[method]);if(method in base._handlers)base._handlers[method].unshift(handler);else{base._handlers[method]=[handler];base[method]=replacementMethod(base,method)}}},uninstall:function uninstallWrappers(base,handlers3){if(!base._originals||!base._handlers)throw new Error("No wrapper methods installed, so no methods can be uninstalled.");for(const[method,handler]of Object.entries(handlers3)){const errorMessage2=`Wrapper method for '${method}' not installed: ${handler.toString()}`;if(!(method in base._handlers))throw new Error(errorMessage2);const i3=base._handlers[method].indexOf(handler);if(-1===i3)throw new Error(errorMessage2);base._handlers[method].splice(i3,1)}}};try{module2.exports=toExport}catch(e3){}try{window.PouchDBWrappers=toExport}catch(e3){}}});require_transform_pouch=__commonJS({"node_modules/transform-pouch/index.js"(exports,module2){"use strict";function isntInternalKey(key3){return"_"!==key3[0]}function isUntransformable(doc){return!("string"!=typeof doc._id||!/^_local/.test(doc._id))||!!doc._deleted&&0===Object.keys(doc).filter(isntInternalKey).length}function transform2(config){const incoming=function(doc){return!isUntransformable(doc)&&config.incoming?config.incoming(doc):doc},outgoing=function(doc){return!isUntransformable(doc)&&config.outgoing?config.outgoing(doc):doc},handlers3={async get(orig,...args){const response=await orig(...args);if(Array.isArray(response)){await Promise.all(response.map(async row=>{row.ok&&(row.ok=await outgoing(row.ok))}));return response}return outgoing(response)},async bulkDocs(orig,docs,...args){docs.docs?docs.docs=await Promise.all(docs.docs.map(incoming)):docs=await Promise.all(docs.map(incoming));return orig(docs,...args)},async allDocs(orig,...args){const response=await orig(...args);await Promise.all(response.rows.map(async row=>{row.doc&&(row.doc=await outgoing(row.doc))}));return response},async bulkGet(orig,...args){const mapDoc=async doc=>doc.ok?{ok:await outgoing(doc.ok)}:doc;let{results,...res2}=await orig(...args);results=await Promise.all(results.map(async result=>{const{id,docs}=result;return id&&docs&&Array.isArray(docs)?{id,docs:await Promise.all(docs.map(mapDoc))}:result}));return{results,...res2}},changes(orig,...args){async function modifyChange(change){if(change.doc){change.doc=await outgoing(change.doc);return change}return change}async function modifyChanges(res2){if(res2.results){res2.results=await Promise.all(res2.results.map(modifyChange));return res2}return res2}const changes3=orig(...args),{on:origOn,then:origThen}=changes3;return Object.assign(changes3,{on(event2,listener){const origListener=listener;"change"===event2?listener=async change=>{origListener(await modifyChange(change))}:"complete"===event2&&(listener=async res2=>{origListener(await modifyChanges(res2))});return origOn.call(changes3,event2,listener)},then:(resolve,reject)=>origThen.call(changes3,modifyChanges).then(resolve,reject)})}};if("http"===this.type()){handlers3.put=async function(orig,doc,...args){doc=await incoming(doc);return orig(doc,...args)};handlers3.query=async function(orig,...args){const response=await orig(...args);await Promise.all(response.rows.map(async row=>{row.doc&&(row.doc=await outgoing(row.doc))}));return response}}wrappers.install(this,handlers3)}var wrappers=require_pouchdb_wrappers();module2.exports={transform:transform2,filter:transform2};"undefined"!=typeof window&&window.PouchDB&&window.PouchDB.plugin(exports)}});require_qrcode=__commonJS({"node_modules/qrcode-generator/qrcode.js"(exports,module2){var qrcode2=function(){function qrPolynomial(num,shift){var _num,_this;if(void 0===num.length)throw num.length+"/"+shift;_num=function(){for(var _num2,i3,offset=0;offset<num.length&&0==num[offset];)offset+=1;_num2=new Array(num.length-offset+shift);for(i3=0;i3<num.length-offset;i3+=1)_num2[i3]=num[i3+offset];return _num2}();_this={};_this.getAt=function(index6){return _num[index6]};_this.getLength=function(){return _num.length};_this.multiply=function(e3){var i3,j2,num2=new Array(_this.getLength()+e3.getLength()-1);for(i3=0;i3<_this.getLength();i3+=1)for(j2=0;j2<e3.getLength();j2+=1)num2[i3+j2]^=QRMath.gexp(QRMath.glog(_this.getAt(i3))+QRMath.glog(e3.getAt(j2)));return qrPolynomial(num2,0)};_this.mod=function(e3){var ratio,num2,i3;if(_this.getLength()-e3.getLength()<0)return _this;ratio=QRMath.glog(_this.getAt(0))-QRMath.glog(e3.getAt(0));num2=new Array(_this.getLength());for(i3=0;i3<_this.getLength();i3+=1)num2[i3]=_this.getAt(i3);for(i3=0;i3<e3.getLength();i3+=1)num2[i3]^=QRMath.gexp(QRMath.glog(e3.getAt(i3))+ratio);return qrPolynomial(num2,0).mod(e3)};return _this}var QRMode_MODE_NUMBER,QRMode_MODE_ALPHA_NUM,QRMode_MODE_8BIT_BYTE,QRMode_MODE_KANJI,QRErrorCorrectionLevel,QRMaskPattern_PATTERN000,QRMaskPattern_PATTERN001,QRMaskPattern_PATTERN010,QRMaskPattern_PATTERN011,QRMaskPattern_PATTERN100,QRMaskPattern_PATTERN101,QRMaskPattern_PATTERN110,QRMaskPattern_PATTERN111,QRUtil,QRMath,QRRSBlock,qrBitBuffer,qrNumber,qrAlphaNum,qr8BitByte,qrKanji,byteArrayOutputStream,base64EncodeOutputStream,base64DecodeInputStream,gifImage,createDataURL,qrcode3=function(typeNumber,errorCorrectionLevel){var escapeXml,_createHalfASCII,PAD0=236,PAD1=17,_typeNumber=typeNumber,_errorCorrectionLevel=QRErrorCorrectionLevel[errorCorrectionLevel],_modules=null,_moduleCount=0,_dataCache=null,_dataList=[],_this={},makeImpl=function(test,maskPattern){_moduleCount=4*_typeNumber+17;_modules=function(moduleCount){var row,col,modules=new Array(moduleCount);for(row=0;row<moduleCount;row+=1){modules[row]=new Array(moduleCount);for(col=0;col<moduleCount;col+=1)modules[row][col]=null}return modules}(_moduleCount);setupPositionProbePattern(0,0);setupPositionProbePattern(_moduleCount-7,0);setupPositionProbePattern(0,_moduleCount-7);setupPositionAdjustPattern();setupTimingPattern();setupTypeInfo(test,maskPattern);_typeNumber>=7&&setupTypeNumber(test);null==_dataCache&&(_dataCache=createData(_typeNumber,_errorCorrectionLevel,_dataList));mapData(_dataCache,maskPattern)},setupPositionProbePattern=function(row,col){var r4,c3;for(r4=-1;r4<=7;r4+=1)if(!(row+r4<=-1||_moduleCount<=row+r4))for(c3=-1;c3<=7;c3+=1)col+c3<=-1||_moduleCount<=col+c3||(_modules[row+r4][col+c3]=0<=r4&&r4<=6&&(0==c3||6==c3)||0<=c3&&c3<=6&&(0==r4||6==r4)||2<=r4&&r4<=4&&2<=c3&&c3<=4)},getBestMaskPattern=function(){var i3,lostPoint,minLostPoint=0,pattern=0;for(i3=0;i3<8;i3+=1){makeImpl(!0,i3);lostPoint=QRUtil.getLostPoint(_this);if(0==i3||minLostPoint>lostPoint){minLostPoint=lostPoint;pattern=i3}}return pattern},setupTimingPattern=function(){var r4,c3;for(r4=8;r4<_moduleCount-8;r4+=1)null==_modules[r4][6]&&(_modules[r4][6]=r4%2==0);for(c3=8;c3<_moduleCount-8;c3+=1)null==_modules[6][c3]&&(_modules[6][c3]=c3%2==0)},setupPositionAdjustPattern=function(){var i3,j2,row,col,r4,c3,pos=QRUtil.getPatternPosition(_typeNumber);for(i3=0;i3<pos.length;i3+=1)for(j2=0;j2<pos.length;j2+=1){row=pos[i3];col=pos[j2];if(null==_modules[row][col])for(r4=-2;r4<=2;r4+=1)for(c3=-2;c3<=2;c3+=1)_modules[row+r4][col+c3]=-2==r4||2==r4||-2==c3||2==c3||0==r4&&0==c3}},setupTypeNumber=function(test){var i3,mod,bits2=QRUtil.getBCHTypeNumber(_typeNumber);for(i3=0;i3<18;i3+=1){mod=!test&&1==(bits2>>i3&1);_modules[Math.floor(i3/3)][i3%3+_moduleCount-8-3]=mod}for(i3=0;i3<18;i3+=1){mod=!test&&1==(bits2>>i3&1);_modules[i3%3+_moduleCount-8-3][Math.floor(i3/3)]=mod}},setupTypeInfo=function(test,maskPattern){var i3,mod,data=_errorCorrectionLevel<<3|maskPattern,bits2=QRUtil.getBCHTypeInfo(data);for(i3=0;i3<15;i3+=1){mod=!test&&1==(bits2>>i3&1);i3<6?_modules[i3][8]=mod:i3<8?_modules[i3+1][8]=mod:_modules[_moduleCount-15+i3][8]=mod}for(i3=0;i3<15;i3+=1){mod=!test&&1==(bits2>>i3&1);i3<8?_modules[8][_moduleCount-i3-1]=mod:i3<9?_modules[8][15-i3-1+1]=mod:_modules[8][15-i3-1]=mod}_modules[_moduleCount-8][8]=!test},mapData=function(data,maskPattern){var col,c3,dark,mask,inc=-1,row=_moduleCount-1,bitIndex=7,byteIndex=0,maskFunc=QRUtil.getMaskFunction(maskPattern);for(col=_moduleCount-1;col>0;col-=2){6==col&&(col-=1);for(;;){for(c3=0;c3<2;c3+=1)if(null==_modules[row][col-c3]){dark=!1;byteIndex<data.length&&(dark=1==(data[byteIndex]>>>bitIndex&1));mask=maskFunc(row,col-c3);mask&&(dark=!dark);_modules[row][col-c3]=dark;bitIndex-=1;if(-1==bitIndex){byteIndex+=1;bitIndex=7}}row+=inc;if(row<0||_moduleCount<=row){row-=inc;inc=-inc;break}}}},createBytes=function(buffer,rsBlocks){var r4,dcCount,ecCount,i3,rsPoly,rawPoly,modPoly,modIndex,totalCodeCount,data,index6,offset=0,maxDcCount=0,maxEcCount=0,dcdata=new Array(rsBlocks.length),ecdata=new Array(rsBlocks.length);for(r4=0;r4<rsBlocks.length;r4+=1){dcCount=rsBlocks[r4].dataCount;ecCount=rsBlocks[r4].totalCount-dcCount;maxDcCount=Math.max(maxDcCount,dcCount);maxEcCount=Math.max(maxEcCount,ecCount);dcdata[r4]=new Array(dcCount);for(i3=0;i3<dcdata[r4].length;i3+=1)dcdata[r4][i3]=255&buffer.getBuffer()[i3+offset];offset+=dcCount;rsPoly=QRUtil.getErrorCorrectPolynomial(ecCount);rawPoly=qrPolynomial(dcdata[r4],rsPoly.getLength()-1);modPoly=rawPoly.mod(rsPoly);ecdata[r4]=new Array(rsPoly.getLength()-1);for(i3=0;i3<ecdata[r4].length;i3+=1){modIndex=i3+modPoly.getLength()-ecdata[r4].length;ecdata[r4][i3]=modIndex>=0?modPoly.getAt(modIndex):0}}totalCodeCount=0;for(i3=0;i3<rsBlocks.length;i3+=1)totalCodeCount+=rsBlocks[i3].totalCount;data=new Array(totalCodeCount);index6=0;for(i3=0;i3<maxDcCount;i3+=1)for(r4=0;r4<rsBlocks.length;r4+=1)if(i3<dcdata[r4].length){data[index6]=dcdata[r4][i3];index6+=1}for(i3=0;i3<maxEcCount;i3+=1)for(r4=0;r4<rsBlocks.length;r4+=1)if(i3<ecdata[r4].length){data[index6]=ecdata[r4][i3];index6+=1}return data},createData=function(typeNumber2,errorCorrectionLevel2,dataList){var i3,data,totalDataCount,rsBlocks=QRRSBlock.getRSBlocks(typeNumber2,errorCorrectionLevel2),buffer=qrBitBuffer();for(i3=0;i3<dataList.length;i3+=1){data=dataList[i3];buffer.put(data.getMode(),4);buffer.put(data.getLength(),QRUtil.getLengthInBits(data.getMode(),typeNumber2));data.write(buffer)}totalDataCount=0;for(i3=0;i3<rsBlocks.length;i3+=1)totalDataCount+=rsBlocks[i3].dataCount;if(buffer.getLengthInBits()>8*totalDataCount)throw"code length overflow. ("+buffer.getLengthInBits()+">"+8*totalDataCount+")";buffer.getLengthInBits()+4<=8*totalDataCount&&buffer.put(0,4);for(;buffer.getLengthInBits()%8!=0;)buffer.putBit(!1);for(;!(buffer.getLengthInBits()>=8*totalDataCount);){buffer.put(PAD0,8);if(buffer.getLengthInBits()>=8*totalDataCount)break;buffer.put(PAD1,8)}return createBytes(buffer,rsBlocks)};_this.addData=function(data,mode){mode=mode||"Byte";var newData=null;switch(mode){case"Numeric":newData=qrNumber(data);break;case"Alphanumeric":newData=qrAlphaNum(data);break;case"Byte":newData=qr8BitByte(data);break;case"Kanji":newData=qrKanji(data);break;default:throw"mode:"+mode}_dataList.push(newData);_dataCache=null};_this.isDark=function(row,col){if(row<0||_moduleCount<=row||col<0||_moduleCount<=col)throw row+","+col;return _modules[row][col]};_this.getModuleCount=function(){return _moduleCount};_this.make=function(){var typeNumber2,rsBlocks,buffer,i3,data,totalDataCount;if(_typeNumber<1){typeNumber2=1;for(;typeNumber2<40;typeNumber2++){rsBlocks=QRRSBlock.getRSBlocks(typeNumber2,_errorCorrectionLevel);buffer=qrBitBuffer();for(i3=0;i3<_dataList.length;i3++){data=_dataList[i3];buffer.put(data.getMode(),4);buffer.put(data.getLength(),QRUtil.getLengthInBits(data.getMode(),typeNumber2));data.write(buffer)}totalDataCount=0;for(i3=0;i3<rsBlocks.length;i3++)totalDataCount+=rsBlocks[i3].dataCount;if(buffer.getLengthInBits()<=8*totalDataCount)break}_typeNumber=typeNumber2}makeImpl(!1,getBestMaskPattern())};_this.createTableTag=function(cellSize,margin){var qrHtml,r4,c3;cellSize=cellSize||2;margin=void 0===margin?4*cellSize:margin;qrHtml="";qrHtml+='<table style="';qrHtml+=" border-width: 0px; border-style: none;";qrHtml+=" border-collapse: collapse;";qrHtml+=" padding: 0px; margin: "+margin+"px;";qrHtml+='">';qrHtml+="<tbody>";for(r4=0;r4<_this.getModuleCount();r4+=1){qrHtml+="<tr>";for(c3=0;c3<_this.getModuleCount();c3+=1){qrHtml+='<td style="';qrHtml+=" border-width: 0px; border-style: none;";qrHtml+=" border-collapse: collapse;";qrHtml+=" padding: 0px; margin: 0px;";qrHtml+=" width: "+cellSize+"px;";qrHtml+=" height: "+cellSize+"px;";qrHtml+=" background-color: ";qrHtml+=_this.isDark(r4,c3)?"#000000":"#ffffff";qrHtml+=";";qrHtml+='"/>'}qrHtml+="</tr>"}qrHtml+="</tbody>";qrHtml+="</table>";return qrHtml};_this.createSvgTag=function(cellSize,margin,alt,title){var size,c3,mc,r4,mr,qrSvg,rect,opts={};if("object"==typeof arguments[0]){opts=arguments[0];cellSize=opts.cellSize;margin=opts.margin;alt=opts.alt;title=opts.title}cellSize=cellSize||2;margin=void 0===margin?4*cellSize:margin;alt="string"==typeof alt?{text:alt}:alt||{};alt.text=alt.text||null;alt.id=alt.text?alt.id||"qrcode-description":null;title="string"==typeof title?{text:title}:title||{};title.text=title.text||null;title.id=title.text?title.id||"qrcode-title":null;size=_this.getModuleCount()*cellSize+2*margin;qrSvg="";rect="l"+cellSize+",0 0,"+cellSize+" -"+cellSize+",0 0,-"+cellSize+"z ";qrSvg+='<svg version="1.1" xmlns="http://www.w3.org/2000/svg"';qrSvg+=opts.scalable?"":' width="'+size+'px" height="'+size+'px"';qrSvg+=' viewBox="0 0 '+size+" "+size+'" ';qrSvg+=' preserveAspectRatio="xMinYMin meet"';qrSvg+=title.text||alt.text?' role="img" aria-labelledby="'+escapeXml([title.id,alt.id].join(" ").trim())+'"':"";qrSvg+=">";qrSvg+=title.text?'<title id="'+escapeXml(title.id)+'">'+escapeXml(title.text)+"</title>":"";qrSvg+=alt.text?'<description id="'+escapeXml(alt.id)+'">'+escapeXml(alt.text)+"</description>":"";qrSvg+='<rect width="100%" height="100%" fill="white" cx="0" cy="0"/>';qrSvg+='<path d="';for(r4=0;r4<_this.getModuleCount();r4+=1){mr=r4*cellSize+margin;for(c3=0;c3<_this.getModuleCount();c3+=1)if(_this.isDark(r4,c3)){mc=c3*cellSize+margin;qrSvg+="M"+mc+","+mr+rect}}qrSvg+='" stroke="transparent" fill="black"/>';qrSvg+="</svg>";return qrSvg};_this.createDataURL=function(cellSize,margin){var size,min2,max3;cellSize=cellSize||2;margin=void 0===margin?4*cellSize:margin;size=_this.getModuleCount()*cellSize+2*margin;min2=margin;max3=size-margin;return createDataURL(size,size,function(x3,y2){var c3,r4;if(min2<=x3&&x3<max3&&min2<=y2&&y2<max3){c3=Math.floor((x3-min2)/cellSize);r4=Math.floor((y2-min2)/cellSize);return _this.isDark(r4,c3)?0:1}return 1})};_this.createImgTag=function(cellSize,margin,alt){var size,img;cellSize=cellSize||2;margin=void 0===margin?4*cellSize:margin;size=_this.getModuleCount()*cellSize+2*margin;img="";img+="<img";img+=' src="';img+=_this.createDataURL(cellSize,margin);img+='"';img+=' width="';img+=size;img+='"';img+=' height="';img+=size;img+='"';if(alt){img+=' alt="';img+=escapeXml(alt);img+='"'}img+="/>";return img};escapeXml=function(s2){var i3,c3,escaped="";for(i3=0;i3<s2.length;i3+=1){c3=s2.charAt(i3);switch(c3){case"<":escaped+="&lt;";break;case">":escaped+="&gt;";break;case"&":escaped+="&amp;";break;case'"':escaped+="&quot;";break;default:escaped+=c3;break}}return escaped};_createHalfASCII=function(margin){var size,min2,max3,y2,x3,r12,r22,p2,blocks,blocksLastLineNoMargin,ascii,cellSize=1;margin=void 0===margin?2*cellSize:margin;size=_this.getModuleCount()*cellSize+2*margin;min2=margin;max3=size-margin;blocks={"██":"█","█ ":"▀"," █":"▄"," ":" "};blocksLastLineNoMargin={"██":"▀","█ ":"▀"," █":" "," ":" "};ascii="";for(y2=0;y2<size;y2+=2){r12=Math.floor((y2-min2)/cellSize);r22=Math.floor((y2+1-min2)/cellSize);for(x3=0;x3<size;x3+=1){p2="█";min2<=x3&&x3<max3&&min2<=y2&&y2<max3&&_this.isDark(r12,Math.floor((x3-min2)/cellSize))&&(p2=" ");min2<=x3&&x3<max3&&min2<=y2+1&&y2+1<max3&&_this.isDark(r22,Math.floor((x3-min2)/cellSize))?p2+=" ":p2+="█";ascii+=margin<1&&y2+1>=max3?blocksLastLineNoMargin[p2]:blocks[p2]}ascii+="\n"}return size%2&&margin>0?ascii.substring(0,ascii.length-size-1)+Array(size+1).join("▀"):ascii.substring(0,ascii.length-1)};_this.createASCII=function(cellSize,margin){var size,min2,max3,y2,x3,r4,p2,white,black,ascii,line;cellSize=cellSize||1;if(cellSize<2)return _createHalfASCII(margin);cellSize-=1;margin=void 0===margin?2*cellSize:margin;size=_this.getModuleCount()*cellSize+2*margin;min2=margin;max3=size-margin;white=Array(cellSize+1).join("██");black=Array(cellSize+1).join(" ");ascii="";line="";for(y2=0;y2<size;y2+=1){r4=Math.floor((y2-min2)/cellSize);line="";for(x3=0;x3<size;x3+=1){p2=1;min2<=x3&&x3<max3&&min2<=y2&&y2<max3&&_this.isDark(r4,Math.floor((x3-min2)/cellSize))&&(p2=0);line+=p2?white:black}for(r4=0;r4<cellSize;r4+=1)ascii+=line+"\n"}return ascii.substring(0,ascii.length-1)};_this.renderTo2dContext=function(context2,cellSize){var length,row,col;cellSize=cellSize||2;length=_this.getModuleCount();for(row=0;row<length;row++)for(col=0;col<length;col++){context2.fillStyle=_this.isDark(row,col)?"black":"white";context2.fillRect(row*cellSize,col*cellSize,cellSize,cellSize)}};return _this};qrcode3.stringToBytesFuncs={default:function(s2){var i3,c3,bytes=[];for(i3=0;i3<s2.length;i3+=1){c3=s2.charCodeAt(i3);bytes.push(255&c3)}return bytes}};qrcode3.stringToBytes=qrcode3.stringToBytesFuncs.default;qrcode3.createStringToBytes=function(unicodeData,numChars){var unicodeMap=function(){for(var b0,b1,b22,b3,k2,v2,bin=base64DecodeInputStream(unicodeData),read=function(){var b5=bin.read();if(-1==b5)throw"eof";return b5},count=0,unicodeMap2={};;){b0=bin.read();if(-1==b0)break;b1=read();b22=read();b3=read();k2=String.fromCharCode(b0<<8|b1);v2=b22<<8|b3;unicodeMap2[k2]=v2;count+=1}if(count!=numChars)throw count+" != "+numChars;return unicodeMap2}(),unknownChar="?".charCodeAt(0);return function(s2){var i3,c3,b3,bytes=[];for(i3=0;i3<s2.length;i3+=1){c3=s2.charCodeAt(i3);if(c3<128)bytes.push(c3);else{b3=unicodeMap[s2.charAt(i3)];if("number"==typeof b3)if((255&b3)==b3)bytes.push(b3);else{bytes.push(b3>>>8);bytes.push(255&b3)}else bytes.push(unknownChar)}}return bytes}};QRMode_MODE_NUMBER=1,QRMode_MODE_ALPHA_NUM=2,QRMode_MODE_8BIT_BYTE=4,QRMode_MODE_KANJI=8;QRErrorCorrectionLevel={L:1,M:0,Q:3,H:2};QRMaskPattern_PATTERN000=0,QRMaskPattern_PATTERN001=1,QRMaskPattern_PATTERN010=2,QRMaskPattern_PATTERN011=3,QRMaskPattern_PATTERN100=4,QRMaskPattern_PATTERN101=5,QRMaskPattern_PATTERN110=6,QRMaskPattern_PATTERN111=7;QRUtil=function(){var PATTERN_POSITION_TABLE=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],G15=1335,G18=7973,G15_MASK=21522,_this={},getBCHDigit=function(data){for(var digit=0;0!=data;){digit+=1;data>>>=1}return digit};_this.getBCHTypeInfo=function(data){for(var d4=data<<10;getBCHDigit(d4)-getBCHDigit(G15)>=0;)d4^=G15<<getBCHDigit(d4)-getBCHDigit(G15);return(data<<10|d4)^G15_MASK};_this.getBCHTypeNumber=function(data){for(var d4=data<<12;getBCHDigit(d4)-getBCHDigit(G18)>=0;)d4^=G18<<getBCHDigit(d4)-getBCHDigit(G18);return data<<12|d4};_this.getPatternPosition=function(typeNumber){return PATTERN_POSITION_TABLE[typeNumber-1]};_this.getMaskFunction=function(maskPattern){switch(maskPattern){case QRMaskPattern_PATTERN000:return function(i3,j2){return(i3+j2)%2==0};case QRMaskPattern_PATTERN001:return function(i3,j2){return i3%2==0};case QRMaskPattern_PATTERN010:return function(i3,j2){return j2%3==0};case QRMaskPattern_PATTERN011:return function(i3,j2){return(i3+j2)%3==0};case QRMaskPattern_PATTERN100:return function(i3,j2){return(Math.floor(i3/2)+Math.floor(j2/3))%2==0};case QRMaskPattern_PATTERN101:return function(i3,j2){return i3*j2%2+i3*j2%3==0};case QRMaskPattern_PATTERN110:return function(i3,j2){return(i3*j2%2+i3*j2%3)%2==0};case QRMaskPattern_PATTERN111:return function(i3,j2){return(i3*j2%3+(i3+j2)%2)%2==0};default:throw"bad maskPattern:"+maskPattern}};_this.getErrorCorrectPolynomial=function(errorCorrectLength){var i3,a2=qrPolynomial([1],0);for(i3=0;i3<errorCorrectLength;i3+=1)a2=a2.multiply(qrPolynomial([1,QRMath.gexp(i3)],0));return a2};_this.getLengthInBits=function(mode,type){if(1<=type&&type<10)switch(mode){case QRMode_MODE_NUMBER:return 10;case QRMode_MODE_ALPHA_NUM:return 9;case QRMode_MODE_8BIT_BYTE:return 8;case QRMode_MODE_KANJI:return 8;default:throw"mode:"+mode}else if(type<27)switch(mode){case QRMode_MODE_NUMBER:return 12;case QRMode_MODE_ALPHA_NUM:return 11;case QRMode_MODE_8BIT_BYTE:return 16;case QRMode_MODE_KANJI:return 10;default:throw"mode:"+mode}else{if(!(type<41))throw"type:"+type;switch(mode){case QRMode_MODE_NUMBER:return 14;case QRMode_MODE_ALPHA_NUM:return 13;case QRMode_MODE_8BIT_BYTE:return 16;case QRMode_MODE_KANJI:return 12;default:throw"mode:"+mode}}};_this.getLostPoint=function(qrcode4){var row,col,sameCount,dark,r4,c3,count,darkCount,ratio,moduleCount=qrcode4.getModuleCount(),lostPoint=0;for(row=0;row<moduleCount;row+=1)for(col=0;col<moduleCount;col+=1){sameCount=0;dark=qrcode4.isDark(row,col);for(r4=-1;r4<=1;r4+=1)if(!(row+r4<0||moduleCount<=row+r4))for(c3=-1;c3<=1;c3+=1)col+c3<0||moduleCount<=col+c3||0==r4&&0==c3||dark==qrcode4.isDark(row+r4,col+c3)&&(sameCount+=1);sameCount>5&&(lostPoint+=3+sameCount-5)}for(row=0;row<moduleCount-1;row+=1)for(col=0;col<moduleCount-1;col+=1){count=0;qrcode4.isDark(row,col)&&(count+=1);qrcode4.isDark(row+1,col)&&(count+=1);qrcode4.isDark(row,col+1)&&(count+=1);qrcode4.isDark(row+1,col+1)&&(count+=1);0!=count&&4!=count||(lostPoint+=3)}for(row=0;row<moduleCount;row+=1)for(col=0;col<moduleCount-6;col+=1)qrcode4.isDark(row,col)&&!qrcode4.isDark(row,col+1)&&qrcode4.isDark(row,col+2)&&qrcode4.isDark(row,col+3)&&qrcode4.isDark(row,col+4)&&!qrcode4.isDark(row,col+5)&&qrcode4.isDark(row,col+6)&&(lostPoint+=40);for(col=0;col<moduleCount;col+=1)for(row=0;row<moduleCount-6;row+=1)qrcode4.isDark(row,col)&&!qrcode4.isDark(row+1,col)&&qrcode4.isDark(row+2,col)&&qrcode4.isDark(row+3,col)&&qrcode4.isDark(row+4,col)&&!qrcode4.isDark(row+5,col)&&qrcode4.isDark(row+6,col)&&(lostPoint+=40);darkCount=0;for(col=0;col<moduleCount;col+=1)for(row=0;row<moduleCount;row+=1)qrcode4.isDark(row,col)&&(darkCount+=1);ratio=Math.abs(100*darkCount/moduleCount/moduleCount-50)/5;lostPoint+=10*ratio;return lostPoint};return _this}();QRMath=function(){var i3,_this,EXP_TABLE=new Array(256),LOG_TABLE=new Array(256);for(i3=0;i3<8;i3+=1)EXP_TABLE[i3]=1<<i3;for(i3=8;i3<256;i3+=1)EXP_TABLE[i3]=EXP_TABLE[i3-4]^EXP_TABLE[i3-5]^EXP_TABLE[i3-6]^EXP_TABLE[i3-8];for(i3=0;i3<255;i3+=1)LOG_TABLE[EXP_TABLE[i3]]=i3;_this={};_this.glog=function(n3){if(n3<1)throw"glog("+n3+")";return LOG_TABLE[n3]};_this.gexp=function(n3){for(;n3<0;)n3+=255;for(;n3>=256;)n3-=255;return EXP_TABLE[n3]};return _this}();QRRSBlock=function(){var RS_BLOCK_TABLE=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12,7,37,13],[5,122,98,1,123,99],[7,73,45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]],qrRSBlock=function(totalCount,dataCount){var _this2={};_this2.totalCount=totalCount;_this2.dataCount=dataCount;return _this2},_this={},getRsBlockTable=function(typeNumber,errorCorrectionLevel){switch(errorCorrectionLevel){case QRErrorCorrectionLevel.L:return RS_BLOCK_TABLE[4*(typeNumber-1)+0];case QRErrorCorrectionLevel.M:return RS_BLOCK_TABLE[4*(typeNumber-1)+1];case QRErrorCorrectionLevel.Q:return RS_BLOCK_TABLE[4*(typeNumber-1)+2];case QRErrorCorrectionLevel.H:return RS_BLOCK_TABLE[4*(typeNumber-1)+3];default:return}};_this.getRSBlocks=function(typeNumber,errorCorrectionLevel){var length,list,i3,count,totalCount,dataCount,j2,rsBlock=getRsBlockTable(typeNumber,errorCorrectionLevel);if(void 0===rsBlock)throw"bad rs block @ typeNumber:"+typeNumber+"/errorCorrectionLevel:"+errorCorrectionLevel;length=rsBlock.length/3;list=[];for(i3=0;i3<length;i3+=1){count=rsBlock[3*i3+0];totalCount=rsBlock[3*i3+1];dataCount=rsBlock[3*i3+2];for(j2=0;j2<count;j2+=1)list.push(qrRSBlock(totalCount,dataCount))}return list};return _this}();qrBitBuffer=function(){var _buffer=[],_length=0,_this={getBuffer:function(){return _buffer},getAt:function(index6){var bufIndex=Math.floor(index6/8);return 1==(_buffer[bufIndex]>>>7-index6%8&1)},put:function(num,length){for(var i3=0;i3<length;i3+=1)_this.putBit(1==(num>>>length-i3-1&1))},getLengthInBits:function(){return _length},putBit:function(bit){var bufIndex=Math.floor(_length/8);_buffer.length<=bufIndex&&_buffer.push(0);bit&&(_buffer[bufIndex]|=128>>>_length%8);_length+=1}};return _this};qrNumber=function(data){var strToNum2,chatToNum,_mode=QRMode_MODE_NUMBER,_data2=data,_this={getMode:function(){return _mode},getLength:function(buffer){return _data2.length},write:function(buffer){for(var data2=_data2,i3=0;i3+2<data2.length;){buffer.put(strToNum2(data2.substring(i3,i3+3)),10);i3+=3}i3<data2.length&&(data2.length-i3==1?buffer.put(strToNum2(data2.substring(i3,i3+1)),4):data2.length-i3==2&&buffer.put(strToNum2(data2.substring(i3,i3+2)),7))}};strToNum2=function(s2){var i3,num=0;for(i3=0;i3<s2.length;i3+=1)num=10*num+chatToNum(s2.charAt(i3));return num};chatToNum=function(c3){if("0"<=c3&&c3<="9")return c3.charCodeAt(0)-"0".charCodeAt(0);throw"illegal char :"+c3};return _this};qrAlphaNum=function(data){var getCode,_mode=QRMode_MODE_ALPHA_NUM,_data2=data,_this={getMode:function(){return _mode},getLength:function(buffer){return _data2.length},write:function(buffer){for(var s2=_data2,i3=0;i3+1<s2.length;){buffer.put(45*getCode(s2.charAt(i3))+getCode(s2.charAt(i3+1)),11);i3+=2}i3<s2.length&&buffer.put(getCode(s2.charAt(i3)),6)}};getCode=function(c3){if("0"<=c3&&c3<="9")return c3.charCodeAt(0)-"0".charCodeAt(0);if("A"<=c3&&c3<="Z")return c3.charCodeAt(0)-"A".charCodeAt(0)+10;switch(c3){case" ":return 36;case"$":return 37;case"%":return 38;case"*":return 39;case"+":return 40;case"-":return 41;case".":return 42;case"/":return 43;case":":return 44;default:throw"illegal char :"+c3}};return _this};qr8BitByte=function(data){var _mode=QRMode_MODE_8BIT_BYTE,_bytes=qrcode3.stringToBytes(data),_this={getMode:function(){return _mode},getLength:function(buffer){return _bytes.length},write:function(buffer){for(var i3=0;i3<_bytes.length;i3+=1)buffer.put(_bytes[i3],8)}};return _this};qrKanji=function(data){var _bytes,_this,_mode=QRMode_MODE_KANJI,stringToBytes=qrcode3.stringToBytesFuncs.SJIS;if(!stringToBytes)throw"sjis not supported.";!function(){var test=stringToBytes("友");if(2!=test.length||38726!=(test[0]<<8|test[1]))throw"sjis not supported."}();_bytes=stringToBytes(data);_this={};_this.getMode=function(){return _mode};_this.getLength=function(buffer){return~~(_bytes.length/2)};_this.write=function(buffer){for(var c3,data2=_bytes,i3=0;i3+1<data2.length;){c3=(255&data2[i3])<<8|255&data2[i3+1];if(33088<=c3&&c3<=40956)c3-=33088;else{if(!(57408<=c3&&c3<=60351))throw"illegal char at "+(i3+1)+"/"+c3;c3-=49472}c3=192*(c3>>>8&255)+(255&c3);buffer.put(c3,13);i3+=2}if(i3<data2.length)throw"illegal char at "+(i3+1)};return _this};byteArrayOutputStream=function(){var _bytes=[],_this={writeByte:function(b3){_bytes.push(255&b3)},writeShort:function(i3){_this.writeByte(i3);_this.writeByte(i3>>>8)},writeBytes:function(b3,off,len){off=off||0;len=len||b3.length;for(var i3=0;i3<len;i3+=1)_this.writeByte(b3[i3+off])},writeString:function(s2){for(var i3=0;i3<s2.length;i3+=1)_this.writeByte(s2.charCodeAt(i3))},toByteArray:function(){return _bytes},toString:function(){var i3,s2="";s2+="[";for(i3=0;i3<_bytes.length;i3+=1){i3>0&&(s2+=",");s2+=_bytes[i3]}s2+="]";return s2}};return _this};base64EncodeOutputStream=function(){var _buffer=0,_buflen=0,_length=0,_base64="",_this={},writeEncoded=function(b3){_base64+=String.fromCharCode(encode(63&b3))},encode=function(n3){if(n3<0);else{if(n3<26)return 65+n3;if(n3<52)return n3-26+97;if(n3<62)return n3-52+48;if(62==n3)return 43;if(63==n3)return 47}throw"n:"+n3};_this.writeByte=function(n3){_buffer=_buffer<<8|255&n3;_buflen+=8;_length+=1;for(;_buflen>=6;){writeEncoded(_buffer>>>_buflen-6);_buflen-=6}};_this.flush=function(){var padlen,i3;if(_buflen>0){writeEncoded(_buffer<<6-_buflen);_buffer=0;_buflen=0}if(_length%3!=0){padlen=3-_length%3;for(i3=0;i3<padlen;i3+=1)_base64+="="}};_this.toString=function(){return _base64};return _this};base64DecodeInputStream=function(str){var decode,_str=str,_pos=0,_buffer=0,_buflen=0,_this={read:function(){for(var c3,n3;_buflen<8;){if(_pos>=_str.length){if(0==_buflen)return-1;throw"unexpected end of file./"+_buflen}c3=_str.charAt(_pos);_pos+=1;if("="==c3){_buflen=0;return-1}if(!c3.match(/^\s$/)){_buffer=_buffer<<6|decode(c3.charCodeAt(0));_buflen+=6}}n3=_buffer>>>_buflen-8&255;_buflen-=8;return n3}};decode=function(c3){if(65<=c3&&c3<=90)return c3-65;if(97<=c3&&c3<=122)return c3-97+26;if(48<=c3&&c3<=57)return c3-48+52;if(43==c3)return 62;if(47==c3)return 63;throw"c:"+c3};return _this};gifImage=function(width,height){var bitOutputStream,getLZWRaster,lzwTable,_width=width,_height=height,_data2=new Array(width*height),_this={setPixel:function(x3,y2,pixel){_data2[y2*_width+x3]=pixel},write:function(out){var lzwMinCodeSize,raster,offset;out.writeString("GIF87a");out.writeShort(_width);out.writeShort(_height);out.writeByte(128);out.writeByte(0);out.writeByte(0);out.writeByte(0);out.writeByte(0);out.writeByte(0);out.writeByte(255);out.writeByte(255);out.writeByte(255);out.writeString(",");out.writeShort(0);out.writeShort(0);out.writeShort(_width);out.writeShort(_height);out.writeByte(0);lzwMinCodeSize=2;raster=getLZWRaster(lzwMinCodeSize);out.writeByte(lzwMinCodeSize);offset=0;for(;raster.length-offset>255;){out.writeByte(255);out.writeBytes(raster,offset,255);offset+=255}out.writeByte(raster.length-offset);out.writeBytes(raster,offset,raster.length-offset);out.writeByte(0);out.writeString(";")}};bitOutputStream=function(out){var _out=out,_bitLength=0,_bitBuffer=0,_this2={write:function(data,length){if(data>>>length!=0)throw"length over";for(;_bitLength+length>=8;){_out.writeByte(255&(data<<_bitLength|_bitBuffer));length-=8-_bitLength;data>>>=8-_bitLength;_bitBuffer=0;_bitLength=0}_bitBuffer|=data<<_bitLength;_bitLength+=length},flush:function(){_bitLength>0&&_out.writeByte(_bitBuffer)}};return _this2};getLZWRaster=function(lzwMinCodeSize){var i3,byteOut,bitOut,dataIndex,s2,c3,clearCode=1<<lzwMinCodeSize,endCode=1+(1<<lzwMinCodeSize),bitLength=lzwMinCodeSize+1,table3=lzwTable();for(i3=0;i3<clearCode;i3+=1)table3.add(String.fromCharCode(i3));table3.add(String.fromCharCode(clearCode));table3.add(String.fromCharCode(endCode));byteOut=byteArrayOutputStream();bitOut=bitOutputStream(byteOut);bitOut.write(clearCode,bitLength);dataIndex=0;s2=String.fromCharCode(_data2[dataIndex]);dataIndex+=1;for(;dataIndex<_data2.length;){c3=String.fromCharCode(_data2[dataIndex]);dataIndex+=1;if(table3.contains(s2+c3))s2+=c3;else{bitOut.write(table3.indexOf(s2),bitLength);if(table3.size()<4095){table3.size()==1<<bitLength&&(bitLength+=1);table3.add(s2+c3)}s2=c3}}bitOut.write(table3.indexOf(s2),bitLength);bitOut.write(endCode,bitLength);bitOut.flush();return byteOut.toByteArray()};lzwTable=function(){var _map={},_size=0,_this2={add:function(key3){if(_this2.contains(key3))throw"dup key:"+key3;_map[key3]=_size;_size+=1},size:function(){return _size},indexOf:function(key3){return _map[key3]},contains:function(key3){return void 0!==_map[key3]}};return _this2};return _this};createDataURL=function(width,height,getPixel){var y2,x3,b3,base64,bytes,i3,gif=gifImage(width,height);for(y2=0;y2<height;y2+=1)for(x3=0;x3<width;x3+=1)gif.setPixel(x3,y2,getPixel(x3,y2));b3=byteArrayOutputStream();gif.write(b3);base64=base64EncodeOutputStream();bytes=b3.toByteArray();for(i3=0;i3<bytes.length;i3+=1)base64.writeByte(bytes[i3]);base64.flush();return"data:image/gif;base64,"+base64};return qrcode3}();!function(){qrcode2.stringToBytesFuncs["UTF-8"]=function(s2){return function toUTF8Array(str){var i3,charcode,utf8=[];for(i3=0;i3<str.length;i3++){charcode=str.charCodeAt(i3);if(charcode<128)utf8.push(charcode);else if(charcode<2048)utf8.push(192|charcode>>6,128|63&charcode);else if(charcode<55296||charcode>=57344)utf8.push(224|charcode>>12,128|charcode>>6&63,128|63&charcode);else{i3++;charcode=65536+((1023&charcode)<<10|1023&str.charCodeAt(i3));utf8.push(240|charcode>>18,128|charcode>>12&63,128|charcode>>6&63,128|63&charcode)}}return utf8}(s2)}}();(function(factory){"function"==typeof define&&define.amd?define([],factory):"object"==typeof exports&&(module2.exports=factory())})(function(){return qrcode2})}});main_exports={};__export(main_exports,{default:()=>ObsidianLiveSyncPlugin});module.exports=__toCommonJS(main_exports);logger_exports={};__export(logger_exports,{LEVEL_DEBUG:()=>LEVEL_DEBUG,LEVEL_INFO:()=>LEVEL_INFO,LEVEL_NOTICE:()=>LEVEL_NOTICE,LEVEL_URGENT:()=>LEVEL_URGENT,LEVEL_VERBOSE:()=>LEVEL_VERBOSE,LOG_KIND_DEBUG:()=>LOG_KIND_DEBUG,LOG_KIND_ERROR:()=>LOG_KIND_ERROR,LOG_KIND_INFO:()=>LOG_KIND_INFO,LOG_KIND_VERBOSE:()=>LOG_KIND_VERBOSE,LOG_KIND_WARNING:()=>LOG_KIND_WARNING,LOG_LEVEL_DEBUG:()=>LOG_LEVEL_DEBUG,LOG_LEVEL_INFO:()=>LOG_LEVEL_INFO,LOG_LEVEL_NOTICE:()=>LOG_LEVEL_NOTICE,LOG_LEVEL_URGENT:()=>LOG_LEVEL_URGENT,LOG_LEVEL_VERBOSE:()=>LOG_LEVEL_VERBOSE,Logger:()=>Logger,debug:()=>debug,defaultLogger:()=>defaultLogger,defaultLoggerEnv:()=>defaultLoggerEnv,info:()=>info,notice:()=>notice,setGlobalLogFunction:()=>setGlobalLogFunction,verbose:()=>verbose});LOG_LEVEL_DEBUG=-1;LOG_LEVEL_VERBOSE=16;LOG_LEVEL_INFO=32;LOG_LEVEL_NOTICE=64;LOG_LEVEL_URGENT=128;LOG_KIND_INFO=0;LOG_KIND_DEBUG=1;LOG_KIND_VERBOSE=2;LOG_KIND_WARNING=4;LOG_KIND_ERROR=8;LEVEL_DEBUG=LOG_LEVEL_DEBUG;LEVEL_INFO=LOG_LEVEL_INFO;LEVEL_NOTICE=LOG_LEVEL_NOTICE;LEVEL_URGENT=LOG_LEVEL_URGENT;LEVEL_VERBOSE=LOG_LEVEL_VERBOSE;defaultLoggerEnv={minLogLevel:LOG_LEVEL_INFO};defaultLogger=function defaultLogger2(message,level=LEVEL_INFO,key3){if(level<defaultLoggerEnv.minLogLevel)return;const now3=new Date,timestamp=now3.toLocaleString(),messageContent="string"==typeof message?message:message instanceof Error?`${message.name}:${message.message}`:JSON.stringify(message,null,2),newMessage=`${timestamp}\t${level}\t${messageContent}`;level&LOG_KIND_DEBUG?console.debug(newMessage):level&LOG_KIND_WARNING?console.warn(newMessage):level&LOG_KIND_ERROR?console.error(newMessage):level&LOG_KIND_VERBOSE?console.info(newMessage):console.log(newMessage);message instanceof Error&&console.dir(message.stack)};_logger=defaultLogger;RESULT_TIMED_OUT=Symbol("timed out");0;VERSIONING_DOCID="obsydian_livesync_version";MILESTONE_DOCID="_local/obsydian_livesync_milestone";NODEINFO_DOCID="_local/obsydian_livesync_nodeinfo";SYNCINFO_ID="syncinfo";EntryTypes_NOTE_LEGACY="notes",EntryTypes_NOTE_BINARY="newnote",EntryTypes_NOTE_PLAIN="plain",EntryTypes_CHUNK="leaf",EntryTypes_CHUNK_PACK="chunkpack",EntryTypes_SYNC_PARAMETERS="sync-parameters";0;0;CANCELLED=Symbol("cancelled");AUTO_MERGED=Symbol("auto_merged");NOT_CONFLICTED=Symbol("not_conflicted");MISSING_OR_ERROR=Symbol("missing_or_error");LEAVE_TO_SUBSEQUENT=Symbol("leave_to_subsequent_proc");0;BASE_IS_NEW=Symbol("base");TARGET_IS_NEW=Symbol("target");EVEN=Symbol("even");0;MAX_DOC_SIZE_BIN=102400;VER=12;0;0;0;0;REPLICATION_BUSY_TIMEOUT=3e6;SALT_OF_PASSPHRASE="rHGMPtr6oWw7VSa3W3wpa8fT8U";SALT_OF_ID="a83hrf7fy7sa8g31";SEED_MURMURHASH=305419896;IDPrefixes_Chunk="h:";PREFIX_OBFUSCATED="f:";0;PREFIX_ENCRYPTED_CHUNK="h:+";AutoAccepting=(AutoAccepting2=>{AutoAccepting2[AutoAccepting2.NONE=0]="NONE";AutoAccepting2[AutoAccepting2.ALL=1]="ALL";return AutoAccepting2})(AutoAccepting||{});SETTING_VERSION_INITIAL=0;SETTING_VERSION_SUPPORT_CASE_INSENSITIVE=10;CURRENT_SETTING_VERSION=SETTING_VERSION_SUPPORT_CASE_INSENSITIVE;RemoteTypes_REMOTE_COUCHDB="",RemoteTypes_REMOTE_MINIO="MINIO",RemoteTypes_REMOTE_P2P="ONLY_P2P";REMOTE_COUCHDB=RemoteTypes_REMOTE_COUCHDB;REMOTE_MINIO=RemoteTypes_REMOTE_MINIO;REMOTE_P2P=RemoteTypes_REMOTE_P2P;P2PConnectionPaths_Automatic="automatic",P2PConnectionPaths_Relay="relay";P2PMessageSizePresets_Standard=15360,P2PMessageSizePresets_Reduced=2048,P2PMessageSizePresets_Conservative=1024,P2PMessageSizePresets_MaximumCompatibility=800;E2EEAlgorithmNames={"":"V1: Legacy",v2:"V2: AES-256-GCM With HKDF",forceV1:"Force-V1: Force Legacy (Not recommended)"};E2EEAlgorithms={V1:"",V2:"v2",ForceV1:"forceV1"};HashAlgorithms_XXHASH64="xxhash64",HashAlgorithms_MIXED_PUREJS="mixed-purejs",HashAlgorithms_SHA1="sha1",HashAlgorithms_LEGACY="";ChunkAlgorithmNames={v1:"V1: Legacy",v2:"V2: Simple (Default)","v2-segmenter":"V2.5: Lexical chunks","v3-rabin-karp":"V3: Fine deduplication"};ChunkAlgorithms_V1="v1",ChunkAlgorithms_V2="v2",ChunkAlgorithms_V2Segmenter="v2-segmenter",ChunkAlgorithms_RabinKarp="v3-rabin-karp";MODE_SELECTIVE=0;MODE_AUTOMATIC=1;MODE_PAUSED=2;MODE_SHINY=3;NetworkWarningStyles_BANNER="",NetworkWarningStyles_ICON="icon",NetworkWarningStyles_HIDDEN="hidden";PREFERRED_BASE={syncMaxSizeInMB:50,chunkSplitterVersion:"v3-rabin-karp",usePluginSyncV2:!0,handleFilenameCaseSensitive:!1,E2EEAlgorithm:E2EEAlgorithms.V2};PREFERRED_SETTING_CLOUDANT={...PREFERRED_BASE,customChunkSize:0,sendChunksBulkMaxSize:1,concurrencyOfReadChunksOnline:100,minimumIntervalOfReadChunksOnline:333};PREFERRED_SETTING_SELF_HOSTED={...PREFERRED_BASE,customChunkSize:60,sendChunksBulkMaxSize:1,concurrencyOfReadChunksOnline:30,minimumIntervalOfReadChunksOnline:25};PREFERRED_JOURNAL_SYNC={...PREFERRED_BASE,customChunkSize:10,concurrencyOfReadChunksOnline:30,minimumIntervalOfReadChunksOnline:25};P2P_DEFAULT_SETTINGS={P2P_Enabled:!1,P2P_AutoAccepting:AutoAccepting.NONE,P2P_AppID:"self-hosted-livesync",P2P_roomID:"",P2P_passphrase:"",P2P_relays:"wss://exp-relay.vrtmrz.net/",P2P_AutoBroadcast:!1,P2P_AutoStart:!1,P2P_AutoSyncPeers:"",P2P_AutoWatchPeers:"",P2P_SyncOnReplication:"",P2P_RebuildFrom:"",P2P_AutoAcceptingPeers:"",P2P_AutoDenyingPeers:"",P2P_IsHeadless:!1,P2P_DevicePeerName:"",P2P_turnServers:"",P2P_turnUsername:"",P2P_turnCredential:"",P2P_maxWirePayloadBytes:P2PMessageSizePresets_Standard,P2P_connectionPath:P2PConnectionPaths_Automatic,P2P_useDiagRTC:!1};SETTINGS_SCHEMA_DEFAULTS={remoteType:REMOTE_COUCHDB,useCustomRequestHandler:!1,couchDB_URI:"",couchDB_USER:"",couchDB_PASSWORD:"",couchDB_DBNAME:"",liveSync:!1,syncOnSave:!1,syncOnStart:!1,savingDelay:200,lessInformationInLog:!1,gcDelay:300,versionUpFlash:"",minimumChunkSize:20,longLineThreshold:250,showVerboseLog:!1,suspendFileWatching:!1,trashInsteadDelete:!0,periodicReplication:!1,periodicReplicationInterval:60,syncOnFileOpen:!1,encrypt:!1,passphrase:"",usePathObfuscation:!1,doNotDeleteFolder:!1,resolveConflictsByNewerFile:!1,batchSave:!1,batchSaveMinimumDelay:5,batchSaveMaximumDelay:60,deviceAndVaultName:"",usePluginSettings:!1,showOwnPlugins:!1,showStatusOnEditor:!0,showStatusOnStatusbar:!0,showOnlyIconsOnEditor:!1,hideFileWarningNotice:!1,networkWarningStyle:"",usePluginSync:!1,autoSweepPlugins:!1,autoSweepPluginsPeriodic:!1,notifyPluginOrSettingUpdated:!1,checkIntegrityOnSave:!1,batch_size:25,batches_limit:25,useHistory:!1,disableRequestURI:!1,skipOlderFilesOnSync:!0,checkConflictOnlyOnOpen:!1,showMergeDialogOnlyOnActive:!1,syncInternalFiles:!1,syncInternalFilesBeforeReplication:!1,syncInternalFilesIgnorePatterns:"\\/node_modules\\/, \\/\\.git\\/, \\/obsidian-livesync\\/",syncInternalFilesTargetPatterns:"",syncInternalFilesInterval:60,additionalSuffixOfDatabaseName:"",ignoreVersionCheck:!1,lastReadUpdates:0,deleteMetadataOfDeletedFiles:!1,syncIgnoreRegEx:"",syncOnlyRegEx:"",customChunkSize:0,readChunksOnline:!0,watchInternalFileChanges:!0,automaticallyDeleteMetadataOfDeletedFiles:0,disableMarkdownAutoMerge:!1,writeDocumentsIfConflicted:!1,useDynamicIterationCount:!1,syncAfterMerge:!1,configPassphraseStore:"",encryptedPassphrase:"",encryptedCouchDBConnection:"",permitEmptyPassphrase:!1,remoteConfigurations:{},activeConfigurationId:"",P2P_ActiveRemoteConfigurationId:"",useIndexedDBAdapter:!1,useTimeouts:!1,writeLogToTheFile:!1,doNotPaceReplication:!1,hashCacheMaxCount:300,hashCacheMaxAmount:50,concurrencyOfReadChunksOnline:40,minimumIntervalOfReadChunksOnline:50,hashAlg:"xxhash64",suspendParseReplicationResult:!1,doNotSuspendOnFetching:!1,useIgnoreFiles:!1,ignoreFiles:".gitignore",syncOnEditorSave:!1,keepReplicationActiveInBackground:!1,allowSleepDuringSynchronisation:!1,allowSleepDuringSynchronisationOnDesktop:!0,pluginSyncExtendedSetting:{},syncMaxSizeInMB:50,settingSyncFile:"",writeCredentialsForSettingSync:!1,notifyAllSettingSyncFile:!1,isConfigured:void 0,settingVersion:CURRENT_SETTING_VERSION,enableCompression:!1,accessKey:"",bucket:"",endpoint:"",region:"auto",secretKey:"",useEden:!1,maxChunksInEden:10,maxTotalLengthInEden:1024,maxAgeInEden:10,disableCheckingConfigMismatch:!1,autoAcceptCompatibleTweak:void 0,displayLanguage:"",enableChunkSplitterV2:!1,disableWorkerForGeneratingChunks:!1,processSmallFilesInUIThread:!1,notifyThresholdOfRemoteStorageSize:-1,usePluginSyncV2:!1,usePluginEtc:!1,handleFilenameCaseSensitive:void 0,doNotUseFixedRevisionForChunks:!0,showLongerLogInsideEditor:!1,sendChunksBulk:!1,sendChunksBulkMaxSize:1,useSegmenter:!1,useAdvancedMode:!1,usePowerUserMode:!1,useEdgeCaseMode:!1,enableDebugTools:!1,suppressNotifyHiddenFilesChange:!1,syncMinimumInterval:2e3,...P2P_DEFAULT_SETTINGS,doctorProcessedVersion:"",bucketCustomHeaders:"",couchDB_CustomHeaders:"",useJWT:!1,jwtAlgorithm:"",jwtKey:"",jwtKid:"",jwtSub:"",jwtExpDuration:5,useRequestAPI:!1,bucketPrefix:"",chunkSplitterVersion:ChunkAlgorithms_RabinKarp,E2EEAlgorithm:E2EEAlgorithms.V2,processSizeMismatchedFiles:!1,forcePathStyle:!0,syncInternalFileOverwritePatterns:"",useOnlyLocalChunk:!1,maxMTimeForReflectEvents:0,tweakModified:void 0};NEW_VAULT_SETTINGS={...SETTINGS_SCHEMA_DEFAULTS,...PREFERRED_BASE,remoteConfigurations:{},pluginSyncExtendedSetting:{}};DEFAULT_SETTINGS=SETTINGS_SCHEMA_DEFAULTS;SettingsMigrationReviewCodes_LegacyUpdatePending="legacy-update-review-pending",SettingsMigrationReviewCodes_FutureSchema="settings-schema-newer-than-runtime";SETTINGS_MIGRATIONS=[{toVersion:SETTING_VERSION_SUPPORT_CASE_INSENSITIVE,apply:settings=>settings,reviewReason:(settings,fromVersion)=>settings.versionUpFlash?{code:SettingsMigrationReviewCodes_LegacyUpdatePending,fromVersion,toVersion:SETTING_VERSION_SUPPORT_CASE_INSENSITIVE}:void 0}];KeyIndexOfSettings={remoteType:0,useCustomRequestHandler:1,couchDB_URI:2,couchDB_USER:3,couchDB_PASSWORD:4,couchDB_DBNAME:5,minimumChunkSize:6,longLineThreshold:7,encrypt:8,passphrase:9,usePathObfuscation:10,checkIntegrityOnSave:11,batch_size:12,batches_limit:13,useHistory:14,disableRequestURI:15,checkConflictOnlyOnOpen:16,showMergeDialogOnlyOnActive:17,additionalSuffixOfDatabaseName:18,ignoreVersionCheck:19,deleteMetadataOfDeletedFiles:20,customChunkSize:21,readChunksOnline:22,automaticallyDeleteMetadataOfDeletedFiles:23,useDynamicIterationCount:24,permitEmptyPassphrase:25,useTimeouts:26,doNotPaceReplication:27,hashCacheMaxCount:28,hashCacheMaxAmount:29,concurrencyOfReadChunksOnline:30,minimumIntervalOfReadChunksOnline:31,hashAlg:32,enableCompression:33,accessKey:34,bucket:35,endpoint:36,region:37,secretKey:38,useEden:39,maxChunksInEden:40,maxTotalLengthInEden:41,maxAgeInEden:42,disableCheckingConfigMismatch:43,handleFilenameCaseSensitive:44,doNotUseFixedRevisionForChunks:45,sendChunksBulk:46,sendChunksBulkMaxSize:47,useSegmenter:48,liveSync:49,syncOnSave:50,syncOnStart:51,syncOnFileOpen:52,syncOnEditorSave:53,keepReplicationActiveInBackground:-1,allowSleepDuringSynchronisation:161,allowSleepDuringSynchronisationOnDesktop:162,syncMinimumInterval:54,showVerboseLog:55,lessInformationInLog:56,showLongerLogInsideEditor:57,showStatusOnEditor:58,showStatusOnStatusbar:59,showOnlyIconsOnEditor:60,displayLanguage:61,trashInsteadDelete:62,doNotDeleteFolder:63,batchSave:64,batchSaveMinimumDelay:64,batchSaveMaximumDelay:65,syncMaxSizeInMB:66,useIgnoreFiles:67,ignoreFiles:68,syncOnlyRegEx:69,syncIgnoreRegEx:70,syncAfterMerge:71,resolveConflictsByNewerFile:72,writeDocumentsIfConflicted:73,disableMarkdownAutoMerge:74,configPassphraseStore:75,encryptedPassphrase:76,encryptedCouchDBConnection:77,periodicReplication:78,periodicReplicationInterval:79,syncInternalFiles:80,syncInternalFilesBeforeReplication:81,syncInternalFilesInterval:82,syncInternalFilesIgnorePatterns:83,watchInternalFileChanges:84,suppressNotifyHiddenFilesChange:85,usePluginSync:86,usePluginSettings:87,showOwnPlugins:88,autoSweepPlugins:89,autoSweepPluginsPeriodic:90,notifyPluginOrSettingUpdated:91,deviceAndVaultName:92,usePluginSyncV2:93,usePluginEtc:94,pluginSyncExtendedSetting:95,useAdvancedMode:96,usePowerUserMode:97,useEdgeCaseMode:98,notifyThresholdOfRemoteStorageSize:99,disableWorkerForGeneratingChunks:100,processSmallFilesInUIThread:101,enableChunkSplitterV2:102,savingDelay:103,gcDelay:104,skipOlderFilesOnSync:105,useIndexedDBAdapter:106,enableDebugTools:107,writeLogToTheFile:108,settingSyncFile:109,writeCredentialsForSettingSync:110,notifyAllSettingSyncFile:111,suspendFileWatching:112,suspendParseReplicationResult:113,doNotSuspendOnFetching:114,versionUpFlash:115,settingVersion:116,isConfigured:117,lastReadUpdates:118,doctorProcessedVersion:119,P2P_Enabled:120,P2P_relays:121,P2P_roomID:122,P2P_passphrase:123,P2P_AutoAccepting:124,P2P_AutoStart:125,P2P_AutoBroadcast:126,P2P_AutoSyncPeers:127,P2P_AutoWatchPeers:128,P2P_SyncOnReplication:129,P2P_AppID:130,P2P_RebuildFrom:131,bucketCustomHeaders:132,couchDB_CustomHeaders:133,useJWT:134,jwtAlgorithm:135,jwtKey:136,jwtKid:137,jwtSub:138,jwtExpDuration:139,P2P_AutoAcceptingPeers:140,P2P_AutoDenyingPeers:141,P2P_IsHeadless:-1,syncInternalFilesTargetPatterns:142,useRequestAPI:143,hideFileWarningNotice:144,bucketPrefix:145,chunkSplitterVersion:146,E2EEAlgorithm:147,processSizeMismatchedFiles:148,forcePathStyle:149,P2P_DevicePeerName:-1,P2P_turnServers:150,P2P_turnUsername:151,P2P_turnCredential:152,syncInternalFileOverwritePatterns:153,useOnlyLocalChunk:154,maxMTimeForReflectEvents:155,networkWarningStyle:156,remoteConfigurations:157,activeConfigurationId:158,P2P_ActiveRemoteConfigurationId:159,autoAcceptCompatibleTweak:160,tweakModified:-1,P2P_useDiagRTC:-1,P2P_maxWirePayloadBytes:163,P2P_connectionPath:164};SETTING_KEY_P2P_DEVICE_NAME="p2p_device_name";configURIBase="obsidian://setuplivesync?settings=";configURIBaseQR="obsidian://setuplivesync?settingsQR=";SuffixDatabaseName="-livesync-v2";ExtraSuffixIndexedDB="-indexeddb";LEVEL_ADVANCED="ADVANCED";LEVEL_POWER_USER="POWER_USER";LEVEL_EDGE_CASE="EDGE_CASE";configurationNames={minimumChunkSize:{name:"Minimum Chunk Size (Not Configurable from the UI Now)."},longLineThreshold:{name:"Longest chunk line threshold value (Not Configurable from the UI Now)."},encrypt:{name:"End-to-End Encryption",desc:"Encrypt contents on the remote database. If you use the plugin's synchronization feature, enabling this is recommended."},usePathObfuscation:{name:"Property Encryption",desc:"If enabled, the file properties will be encrypted in the remote database. This is useful for protecting sensitive information in file paths, sizes, and IDs of its chunks. If you are using V1 E2EE, this only obfuscates the file path."},enableCompression:{name:"Data Compression",level:LEVEL_ADVANCED},useEden:{name:"Incubate Chunks in Document",desc:"If enabled, newly created chunks are temporarily kept within the document, and graduated to become independent chunks once stabilised.",status:"BETA"},customChunkSize:{name:"Enhance chunk size"},useDynamicIterationCount:{name:"Use dynamic iteration count",status:"EXPERIMENTAL"},hashAlg:{name:"The Hash algorithm for chunk IDs",status:"EXPERIMENTAL"},enableChunkSplitterV2:{name:"Use splitting-limit-capped chunk splitter",desc:"If enabled, chunks will be split into no more than 100 items. However, dedupe is slightly weaker."},maxChunksInEden:{name:"Maximum Incubating Chunks",desc:"The maximum number of chunks that can be incubated within the document. Chunks exceeding this number will immediately graduate to independent chunks."},maxTotalLengthInEden:{name:"Maximum Incubating Chunk Size",desc:"The maximum total size of chunks that can be incubated within the document. Chunks exceeding this size will immediately graduate to independent chunks."},maxAgeInEden:{name:"Maximum Incubation Period",desc:"The maximum duration for which chunks can be incubated within the document. Chunks exceeding this period will graduate to independent chunks."},usePluginSyncV2:{name:"Per-file-saved customization sync",desc:"If enabled per-filed efficient customization sync will be used. We need a small migration when enabling this. And all devices should be updated to v0.23.18. Once we enabled this, we lost a compatibility with old versions."},handleFilenameCaseSensitive:{name:"Handle files as Case-Sensitive",desc:"If this enabled, All files are handled as case-Sensitive (Previous behaviour)."},doNotUseFixedRevisionForChunks:{name:"Content-derived chunk revisions (obsolete setting)",desc:"Chunk revisions are always derived from their content. This stored key is retained only for compatibility."},useSegmenter:{name:"Use Segmented-splitter",desc:"If this enabled, chunks will be split into semantically meaningful segments. Not all platforms support this feature."},useJWT:{name:"Use JWT instead of Basic Authentication",desc:"If this enabled, JWT will be used for authentication.",isAdvanced:!0},jwtAlgorithm:{name:"JWT Algorithm",desc:"The algorithm used for JWT authentication.",isAdvanced:!0},jwtKey:{name:"Keypair or pre-shared key",desc:"The key (PSK in HSxxx in base64, or private key in ESxxx in PEM) used for JWT authentication.",isAdvanced:!0,isHidden:!0},jwtKid:{name:"Key ID",desc:"The key ID. this should be matched with CouchDB->jwt_keys->ALG:_`kid`.",isAdvanced:!0},jwtExpDuration:{name:"Rotation Duration",desc:"The Rotation duration of token in minutes. Each generated tokens will be valid only within this duration.",isAdvanced:!0},jwtSub:{name:"Subject (whoami)",desc:"The subject for JWT authentication. Mostly username.",isAdvanced:!0},bucketCustomHeaders:{name:"Custom Headers",desc:"Custom headers for requesting the bucket. e.g. `x-custom-header1: value1\n x-custom-header2: value2`",placeHolder:"x-custom-header1: value1\n x-custom-header2: value2"},couchDB_CustomHeaders:{name:"Custom Headers",desc:"Custom headers for requesting the CouchDB. e.g. `x-custom-header1: value1\n x-custom-header2: value2`",placeHolder:"x-custom-header1: value1\n x-custom-header2: value2"},chunkSplitterVersion:{name:"Chunk Splitter",desc:"Now we can choose how to split the chunks; V3 is the most efficient. If you have troubled, please make this Default or Legacy."},E2EEAlgorithm:{name:"End-to-End Encryption Algorithm",desc:"Please use V2, V1 is deprecated and will be removed in the future, It was not a very appropriate algorithm. Only for compatibility V1 is kept.",isAdvanced:!0},P2P_AppID:{name:"Application ID",desc:"The Application ID for P2P connection. This should be same among your devices. Default is 'self-hosted-livesync' and could not be modified from the UI.",isAdvanced:!0},P2P_relays:{name:"Signalling Relays",desc:"The Nostr relay servers to establish connections for P2P connections. Multiple servers can be separated by commas.",placeHolder:"wss://relay1.example.com,wss://relay2.example.com"},P2P_roomID:{name:"Room ID",desc:"The Room ID for P2P connection. This should be same among your devices."},P2P_passphrase:{name:"Passphrase",desc:"The Passphrase for P2P connection. This should be same among your devices.",isHidden:!0},P2P_turnServers:{name:"TURN Servers",desc:"The TURN servers to use for P2P connections. Multiple servers can be separated by commas.",placeHolder:"turn:turn1.example.com,turn:turn2.example.com"},P2P_turnUsername:{name:"TURN Username",desc:"The username for the TURN servers."},P2P_turnCredential:{name:"TURN Credential",desc:"The credential/password for the TURN servers.",isHidden:!0},P2P_maxWirePayloadBytes:{name:"P2P Message Size",desc:"The maximum outgoing RPC wire payload before Commonlib splits it for the P2P transport."},P2P_connectionPath:{name:"Connection Path",desc:"Select the WebRTC route automatically or require a configured TURN relay."},useOnlyLocalChunk:{name:"Use Only Local Chunks",desc:"If enabled, the plugin will not attempt to connect to the remote database even if the chunk was not found locally.",isAdvanced:!0},autoAcceptCompatibleTweak:{name:"Auto-accept compatible tweak mismatches",desc:"Automatically accepts mismatches that are compatible but potentially lossy by comparing tweak modification times.",isAdvanced:!0},tweakModified:{name:"Last tweak modified timestamp",desc:"Internal timestamp for resolving compatible tweak mismatches.",isAdvanced:!0}};ProtocolVersions_ADVANCED_E2EE=2;DOCID_SYNC_PARAMETERS="_local/obsidian_livesync_sync_parameters";DOCID_JOURNAL_SYNC_PARAMETERS="_obsidian_livesync_journal_sync_parameters.json";DEFAULT_SYNC_PARAMETERS={_id:DOCID_SYNC_PARAMETERS,type:EntryTypes_SYNC_PARAMETERS,protocolVersion:ProtocolVersions_ADVANCED_E2EE,pbkdf2salt:""};TweakValuesShouldMatchedTemplate={minimumChunkSize:20,longLineThreshold:250,encrypt:!1,usePathObfuscation:!1,enableCompression:!1,useEden:!1,customChunkSize:0,useDynamicIterationCount:!1,hashAlg:"xxhash64",enableChunkSplitterV2:!1,maxChunksInEden:10,maxTotalLengthInEden:1024,maxAgeInEden:10,usePluginSyncV2:!1,handleFilenameCaseSensitive:!1,useSegmenter:!1,E2EEAlgorithm:E2EEAlgorithms.V2,chunkSplitterVersion:ChunkAlgorithms_RabinKarp};IncompatibleChanges=["encrypt","usePathObfuscation","useDynamicIterationCount","handleFilenameCaseSensitive"];CompatibleButLossyChanges=["hashAlg","customChunkSize","chunkSplitterVersion"];IncompatibleChangesInSpecificPattern=[];TweakValuesRecommendedTemplate={useIgnoreFiles:!1,useCustomRequestHandler:!1,batch_size:25,batches_limit:25,useTimeouts:!1,readChunksOnline:!0,hashCacheMaxCount:300,hashCacheMaxAmount:50,concurrencyOfReadChunksOnline:40,minimumIntervalOfReadChunksOnline:50,ignoreFiles:".gitignore",syncMaxSizeInMB:50,enableChunkSplitterV2:!1,usePluginSyncV2:!0,handleFilenameCaseSensitive:!1,E2EEAlgorithm:E2EEAlgorithms.V2,chunkSplitterVersion:ChunkAlgorithms_RabinKarp};TweakValuesDefault={usePluginSyncV2:!1,E2EEAlgorithm:DEFAULT_SETTINGS.E2EEAlgorithm,chunkSplitterVersion:DEFAULT_SETTINGS.chunkSplitterVersion,tweakModified:DEFAULT_SETTINGS.tweakModified};TweakValuesTemplate={...TweakValuesRecommendedTemplate,...TweakValuesShouldMatchedTemplate,tweakModified:0};DEVICE_ID_PREFERRED="PREFERRED";RemotePreferredTweakStatuses_AVAILABLE="available",RemotePreferredTweakStatuses_NOT_CONFIGURED="not-configured",RemotePreferredTweakStatuses_UNAVAILABLE="unavailable",RemotePreferredTweakStatuses_UNSUPPORTED="unsupported";RemotePreferredTweakNotConfiguredReasons_MILESTONE_MISSING="milestone-missing",RemotePreferredTweakNotConfiguredReasons_PREFERRED_VALUES_MISSING="preferred-values-missing";PREFIXMD_LOGFILE="livesync_log_";PREFIXMD_LOGFILE_UC="LIVESYNC_LOG_";FlagFilesOriginal_SUSPEND_ALL="redflag.md",FlagFilesOriginal_REBUILD_ALL="redflag2.md",FlagFilesOriginal_FETCH_ALL="redflag3.md";FlagFilesHumanReadable_REBUILD_ALL="flag_rebuild.md",FlagFilesHumanReadable_FETCH_ALL="flag_fetch.md";FLAGMD_REDFLAG=FlagFilesOriginal_SUSPEND_ALL;FLAGMD_REDFLAG2=FlagFilesOriginal_REBUILD_ALL;FLAGMD_REDFLAG2_HR=FlagFilesHumanReadable_REBUILD_ALL;FLAGMD_REDFLAG3=FlagFilesOriginal_FETCH_ALL;FLAGMD_REDFLAG3_HR=FlagFilesHumanReadable_FETCH_ALL;DatabaseConnectingStatuses={STARTED:"STARTED",NOT_CONNECTED:"NOT_CONNECTED",PAUSED:"PAUSED",CONNECTED:"CONNECTED",COMPLETED:"COMPLETED",CLOSED:"CLOSED",ERRORED:"ERRORED",JOURNAL_SEND:"JOURNAL_SEND",JOURNAL_RECEIVE:"JOURNAL_RECEIVE"};DEFAULT_REPLICATION_STATICS={sent:0,arrived:0,maxPullSeq:0,maxPushSeq:0,lastSyncPullSeq:0,lastSyncPushSeq:0,syncStatus:DatabaseConnectingStatuses.CLOSED};import_obsidian=require("obsidian");import_obsidian2=require("obsidian");import_diff_match_patch=__toESM(require_diff_match_patch(),1);normalizePath=import_obsidian2.normalizePath;_getLanguage=()=>"en";compatGlobal="undefined"!=typeof window?window:globalThis;_fetch=compatGlobal.fetch.bind(compatGlobal);activeDocumentWindow=compatGlobal;_activeDocument=null!=(_a=activeDocumentWindow.activeDocument)?_a:activeDocumentWindow.document;FallbackWeakRef="WeakRef"in globalThis?globalThis.WeakRef:(_a2=class WeakRef{constructor(target){Object.defineProperty(this,"__target",{enumerable:!0,configurable:!0,writable:!0,value:void 0});this.__target=target}deref(){return this.__target}},Object.defineProperty(_a2,"__",{enumerable:!0,configurable:!0,writable:!0,value:console.warn("WeakRef is not supported in this environment. Using a fallback implementation. This may cause memory leaks. Please consider upgrading your browser or Node.js version. If you are on Android, please consider changing your WebView engine to a newer version. It is on the Developer Settings.")}),_a2);"FinalizationRegistry"in globalThis?globalThis.FinalizationRegistry:class PolyfillFinalizationRegistry{constructor(callback){}register(target,heldValue,unregisterToken){}unregister(unregisterToken){return!0}};prefixMapObject={s:{1:"V",2:"W",3:"X",4:"Y",5:"Z"},o:{1:"v",2:"w",3:"x",4:"y",5:"z"}};decodePrefixMapObject=Object.fromEntries(Object.entries(prefixMapObject).flatMap(([prefix,map4])=>Object.entries(map4).map(([len,char])=>[char,{prefix,len:parseInt(len)}])));prefixMapNumber={n:{1:"a",2:"b",3:"c",4:"d",5:"e"},N:{1:"A",2:"B",3:"C",4:"D",5:"E"}};decodePrefixMapNumber=Object.fromEntries(Object.entries(prefixMapNumber).flatMap(([prefix,map4])=>Object.entries(map4).map(([len,char])=>[char,{prefix,len:parseInt(len)}])));ARRAY_MARKER="_";OBJECT_MARKER="^";decodeMapConstant={u:void 0,n:null,f:!1,t:!0};SYMBOL_A=Symbol("a");SYMBOL_B=Symbol("b");topologicalSortCache=new Map;_reactiveSourceId=0;delay=(ms,result)=>new Promise(res2=>{setTimeout(()=>{res2(result)},ms)});UNRESOLVED=Symbol("UNRESOLVED");polyfilledFunc="withResolvers"in Promise?function nativePromiseWithResolvers(){const p2=Promise.withResolvers(),{promise,resolve,reject}=p2;return{promise,resolve,reject}}:function polyfillPromiseWithResolvers(){let resolve,reject;const promise=new Promise((res2,rej)=>{resolve=res2;reject=rej});return{promise,resolve,reject}};promiseWithResolvers=polyfilledFunc;0;noop=()=>{};TIMED_OUT_SIGNAL=Symbol("timed out");serializedMap=new Map;queueCount=new Map;waitingProcessMap=new Map;shareSerializedMap=new Map;skipDuplicatedMap=new Map;0;0;0;0;0;0;GENERIC_COMPATIBILITY_VALUE="x-compatibility-value";GENERIC_COMPATIBILITY_SIGNAL="x-compatibility-signal";SlipBoard=class{constructor(){Object.defineProperty(this,"_clip",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}isAwaiting(type,key3){return this._clip.has(`${String(type)}:${key3}`)}issueAndProceed(type,key3="",opt){this.isAwaiting(type,key3)||fireAndForget(async()=>{try{const ret=await opt.callback();this.submit(type,key3,ret)}catch(ex){opt.submitAsSuccess?this.submit(type,key3,opt.transformError?opt.transformError(ex):ex):opt.dropSlipWithRisks?this._clip.delete(type):this.reject(type,key3,ex)}});return this.awaitNext(type,key3)}async awaitNext(type,key3="",{timeout,onNotAwaited}={timeout:void 0,onNotAwaited:void 0}){let taskPromise=this._clip.get(`${String(type)}:${key3}`);if(!taskPromise){taskPromise=promiseWithResolvers();taskPromise.promise=taskPromise.promise.then(ret=>ret).finally(()=>{this._clip.delete(`${String(type)}:${key3}`)});this._clip.set(`${String(type)}:${key3}`,taskPromise);onNotAwaited&&fireAndForget(async()=>(await yieldMicrotask(),onNotAwaited()))}if(timeout){const cDelay=cancelableDelay(timeout);return Promise.race([cDelay.promise,taskPromise.promise.then(ret=>ret).finally(()=>cDelay.cancel())])}return await taskPromise.promise}submit(type,key3,data){const taskPromise=this._clip.get(`${String(type)}:${key3}`);taskPromise&&taskPromise.resolve(data)}submitToAll(type,prefix,data){for(const[key3,taskPromise]of this._clip.entries())`${String(key3)}`.startsWith(`${String(type)}:${prefix}`)&&taskPromise.resolve(data)}reject(type,key3="",reason){const taskPromise=this._clip.get(`${String(type)}:${key3}`);taskPromise&&taskPromise.reject(reason)}};globalSlipBoard=new SlipBoard;tasks=new Map;intervals={};waitingItems=new Set;LRUCache=class{constructor(maxCache,maxCacheLength,forwardOnly=!1){Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:new Map([])});Object.defineProperty(this,"revCache",{enumerable:!0,configurable:!0,writable:!0,value:new Map([])});Object.defineProperty(this,"maxCache",{enumerable:!0,configurable:!0,writable:!0,value:200});Object.defineProperty(this,"maxCachedLength",{enumerable:!0,configurable:!0,writable:!0,value:5e7});Object.defineProperty(this,"cachedLength",{enumerable:!0,configurable:!0,writable:!0,value:0});Object.defineProperty(this,"enableReversed",{enumerable:!0,configurable:!0,writable:!0,value:!0});this.maxCache=maxCache||200;this.maxCachedLength=1e6*(maxCacheLength||1);this.enableReversed=!forwardOnly;Logger(`Cache initialized ${this.maxCache} / ${this.maxCachedLength}`,LOG_LEVEL_VERBOSE)}clear(){this.cache.clear();this.revCache.clear()}has(key3){return this.cache.has(key3)}get(key3){const v2=this.cache.get(key3);if(v2){this.cache.delete(key3);this.cache.set(key3,v2);if(this.enableReversed){this.revCache.delete(v2);this.revCache.set(v2,key3)}}return v2}revGet(value){const key3=this.revCache.get(value);if(key3){this.cache.delete(key3);this.revCache.delete(value);this.cache.set(key3,value);this.revCache.set(value,key3)}return key3}set(key3,value){this.cache.set(key3,value);this.enableReversed&&this.revCache.set(value,key3);this.cachedLength+=`${value}`.length;if(this.cache.size>this.maxCache||this.cachedLength>this.maxCachedLength)for(const[key4,value2]of this.cache){this.cache.delete(key4);this.enableReversed&&this.revCache.delete(value2);this.cachedLength-=`${value2}`.length;if(this.cache.size<=this.maxCache&&this.cachedLength<=this.maxCachedLength)break}}};balanced=(a2,b3,str)=>{const ma=a2 instanceof RegExp?maybeMatch(a2,str):a2,mb=b3 instanceof RegExp?maybeMatch(b3,str):b3,r4=null!==ma&&null!=mb&&range(ma,mb,str);return r4&&{start:r4[0],end:r4[1],pre:str.slice(0,r4[0]),body:str.slice(r4[0]+ma.length,r4[1]),post:str.slice(r4[1]+mb.length)}};maybeMatch=(reg,str)=>{const m3=str.match(reg);return m3?m3[0]:null};range=(a2,b3,str)=>{let begs,beg,left,right,result,ai2=str.indexOf(a2),bi2=str.indexOf(b3,ai2+1),i3=ai2;if(ai2>=0&&bi2>0){if(a2===b3)return[ai2,bi2];begs=[];left=str.length;for(;i3>=0&&!result;){if(i3===ai2){begs.push(i3);ai2=str.indexOf(a2,i3+1)}else if(1===begs.length){const r4=begs.pop();void 0!==r4&&(result=[r4,bi2])}else{beg=begs.pop();if(void 0!==beg&&beg<left){left=beg;right=bi2}bi2=str.indexOf(b3,i3+1)}i3=ai2<bi2&&ai2>=0?ai2:bi2}begs.length&&void 0!==right&&(result=[left,right])}return result};escSlash="\0SLASH"+Math.random()+"\0";escOpen="\0OPEN"+Math.random()+"\0";escClose="\0CLOSE"+Math.random()+"\0";escComma="\0COMMA"+Math.random()+"\0";escPeriod="\0PERIOD"+Math.random()+"\0";escSlashPattern=new RegExp(escSlash,"g");escOpenPattern=new RegExp(escOpen,"g");escClosePattern=new RegExp(escClose,"g");escCommaPattern=new RegExp(escComma,"g");escPeriodPattern=new RegExp(escPeriod,"g");slashPattern=/\\\\/g;openPattern=/\\{/g;closePattern=/\\}/g;commaPattern=/\\,/g;periodPattern=/\\\./g;EXPANSION_MAX=1e5;EXPANSION_MAX_LENGTH=4e6;MAX_PATTERN_LENGTH=65536;assertValidPattern=pattern=>{if("string"!=typeof pattern)throw new TypeError("invalid pattern");if(pattern.length>MAX_PATTERN_LENGTH)throw new TypeError("pattern is too long")};posixClasses={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]};braceEscape=s2=>s2.replace(/[[\]\\-]/g,"\\$&");regexpEscape=s2=>s2.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");rangesToString=ranges=>ranges.join("");parseClass=(glob,position)=>{const pos=position;if("["!==glob.charAt(pos))throw new Error("not in a brace expression");const ranges=[],negs=[];let i3=pos+1,sawStart=!1,uflag=!1,escaping=!1,negate4=!1,endPos=pos,rangeStart="";WHILE:for(;i3<glob.length;){const c3=glob.charAt(i3);if("!"!==c3&&"^"!==c3||i3!==pos+1){if("]"===c3&&sawStart&&!escaping){endPos=i3+1;break}sawStart=!0;if("\\"!==c3||escaping){if("["===c3&&!escaping)for(const[cls,[unip,u2,neg]]of Object.entries(posixClasses))if(glob.startsWith(cls,i3)){if(rangeStart)return["$.",!1,glob.length-pos,!0];i3+=cls.length;neg?negs.push(unip):ranges.push(unip);uflag=uflag||u2;continue WHILE}escaping=!1;if(rangeStart){c3>rangeStart?ranges.push(braceEscape(rangeStart)+"-"+braceEscape(c3)):c3===rangeStart&&ranges.push(braceEscape(c3));rangeStart="";i3++}else if(glob.startsWith("-]",i3+1)){ranges.push(braceEscape(c3+"-"));i3+=2}else if(glob.startsWith("-",i3+1)){rangeStart=c3;i3+=2}else{ranges.push(braceEscape(c3));i3++}}else{escaping=!0;i3++}}else{negate4=!0;i3++}}if(endPos<i3)return["",!1,0,!1];if(!ranges.length&&!negs.length)return["$.",!1,glob.length-pos,!0];if(0===negs.length&&1===ranges.length&&/^\\?.$/.test(ranges[0])&&!negate4){const r4=2===ranges[0].length?ranges[0].slice(-1):ranges[0];return[regexpEscape(r4),!1,endPos-pos,!1]}const sranges="["+(negate4?"^":"")+rangesToString(ranges)+"]",snegs="["+(negate4?"":"^")+rangesToString(negs)+"]",comb=ranges.length&&negs.length?"("+sranges+"|"+snegs+")":ranges.length?sranges:snegs;return[comb,uflag,endPos-pos,!0]};unescape2=(s2,{windowsPathsNoEscape=!1,magicalBraces=!0}={})=>magicalBraces?windowsPathsNoEscape?s2.replace(/\[([^/\\])\]/g,"$1"):s2.replace(/((?!\\).|^)\[([^/\\])\]/g,"$1$2").replace(/\\([^/])/g,"$1"):windowsPathsNoEscape?s2.replace(/\[([^/\\{}])\]/g,"$1"):s2.replace(/((?!\\).|^)\[([^/\\{}])\]/g,"$1$2").replace(/\\([^/{}])/g,"$1");types=new Set(["!","?","+","*","@"]);isExtglobType=c3=>types.has(c3);isExtglobAST=c3=>isExtglobType(c3.type);adoptionMap=new Map([["!",["@"]],["?",["?","@"]],["@",["@"]],["*",["*","+","?","@"]],["+",["+","@"]]]);adoptionWithSpaceMap=new Map([["!",["?"]],["@",["?"]],["+",["?","*"]]]);adoptionAnyMap=new Map([["!",["?","@"]],["?",["?","@"]],["@",["?","@"]],["*",["*","+","?","@"]],["+",["+","@","?","*"]]]);usurpMap=new Map([["!",new Map([["!","@"]])],["?",new Map([["*","*"],["+","*"]])],["@",new Map([["!","!"],["?","?"],["@","@"],["*","*"],["+","+"]])],["+",new Map([["?","*"],["*","*"]])]]);startNoTraversal="(?!(?:^|/)\\.\\.?(?:$|/))";startNoDot="(?!\\.)";addPatternStart=new Set(["[","."]);justDots=new Set(["..","."]);reSpecials=new Set("().*{}+?[]^$\\!");regExpEscape=s2=>s2.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");qmark="[^/]";star=qmark+"*?";starNoEmpty=qmark+"+?";ID=0;AST=class{constructor(type,parent,options={}){__privateAdd(this,_AST_instances);__publicField(this,"type");__privateAdd(this,_root);__privateAdd(this,_hasMagic);__privateAdd(this,_uflag,!1);__privateAdd(this,_parts,[]);__privateAdd(this,_parent);__privateAdd(this,_parentIndex);__privateAdd(this,_negs);__privateAdd(this,_filledNegs,!1);__privateAdd(this,_options);__privateAdd(this,_toString);__privateAdd(this,_emptyExt,!1);__publicField(this,"id",++ID);this.type=type;type&&__privateSet(this,_hasMagic,!0);__privateSet(this,_parent,parent);__privateSet(this,_root,__privateGet(this,_parent)?__privateGet(__privateGet(this,_parent),_root):this);__privateSet(this,_options,__privateGet(this,_root)===this?options:__privateGet(__privateGet(this,_root),_options));__privateSet(this,_negs,__privateGet(this,_root)===this?[]:__privateGet(__privateGet(this,_root),_negs));"!"!==type||__privateGet(__privateGet(this,_root),_filledNegs)||__privateGet(this,_negs).push(this);__privateSet(this,_parentIndex,__privateGet(this,_parent)?__privateGet(__privateGet(this,_parent),_parts).length:0)}get depth(){var _a13,_b6;return(null!=(_b6=null==(_a13=__privateGet(this,_parent))?void 0:_a13.depth)?_b6:-1)+1}[Symbol.for("nodejs.util.inspect.custom")](){var _a13;return{"@@type":"AST",id:this.id,type:this.type,root:__privateGet(this,_root).id,parent:null==(_a13=__privateGet(this,_parent))?void 0:_a13.id,depth:this.depth,partsLength:__privateGet(this,_parts).length,parts:__privateGet(this,_parts)}}get hasMagic(){if(void 0!==__privateGet(this,_hasMagic))return __privateGet(this,_hasMagic);for(const p2 of __privateGet(this,_parts))if("string"!=typeof p2&&(p2.type||p2.hasMagic))return __privateSet(this,_hasMagic,!0);return __privateGet(this,_hasMagic)}toString(){return void 0!==__privateGet(this,_toString)?__privateGet(this,_toString):this.type?__privateSet(this,_toString,this.type+"("+__privateGet(this,_parts).map(p2=>String(p2)).join("|")+")"):__privateSet(this,_toString,__privateGet(this,_parts).map(p2=>String(p2)).join(""))}push(...parts){for(const p2 of parts)if(""!==p2){if("string"!=typeof p2&&!(p2 instanceof _a3&&__privateGet(p2,_parent)===this))throw new Error("invalid part: "+p2);__privateGet(this,_parts).push(p2)}}toJSON(){var _a13;const ret=null===this.type?__privateGet(this,_parts).slice().map(p2=>"string"==typeof p2?p2:p2.toJSON()):[this.type,...__privateGet(this,_parts).map(p2=>p2.toJSON())];this.isStart()&&!this.type&&ret.unshift([]);this.isEnd()&&(this===__privateGet(this,_root)||__privateGet(__privateGet(this,_root),_filledNegs)&&"!"===(null==(_a13=__privateGet(this,_parent))?void 0:_a13.type))&&ret.push({});return ret}isStart(){var _a13;if(__privateGet(this,_root)===this)return!0;if(!(null==(_a13=__privateGet(this,_parent))?void 0:_a13.isStart()))return!1;if(0===__privateGet(this,_parentIndex))return!0;const p2=__privateGet(this,_parent);for(let i3=0;i3<__privateGet(this,_parentIndex);i3++){const pp=__privateGet(p2,_parts)[i3];if(!(pp instanceof _a3&&"!"===pp.type))return!1}return!0}isEnd(){var _a13,_b6,_c3;if(__privateGet(this,_root)===this)return!0;if("!"===(null==(_a13=__privateGet(this,_parent))?void 0:_a13.type))return!0;if(!(null==(_b6=__privateGet(this,_parent))?void 0:_b6.isEnd()))return!1;if(!this.type)return null==(_c3=__privateGet(this,_parent))?void 0:_c3.isEnd();const pl=__privateGet(this,_parent)?__privateGet(__privateGet(this,_parent),_parts).length:0;return __privateGet(this,_parentIndex)===pl-1}copyIn(part){"string"==typeof part?this.push(part):this.push(part.clone(this))}clone(parent){const c3=new _a3(this.type,parent);for(const p2 of __privateGet(this,_parts))c3.copyIn(p2);return c3}static fromGlob(pattern,options={}){var _a13;const ast=new _a3(null,void 0,options);__privateMethod(_a13=_a3,_AST_static,parseAST_fn).call(_a13,pattern,ast,0,options,0);return ast}toMMPattern(){if(this!==__privateGet(this,_root))return __privateGet(this,_root).toMMPattern();const glob=this.toString(),[re,body,hasMagic,uflag]=this.toRegExpSource(),anyMagic=hasMagic||__privateGet(this,_hasMagic)||__privateGet(this,_options).nocase&&!__privateGet(this,_options).nocaseMagicOnly&&glob.toUpperCase()!==glob.toLowerCase();if(!anyMagic)return body;const flags2=(__privateGet(this,_options).nocase?"i":"")+(uflag?"u":"");return Object.assign(new RegExp(`^${re}$`,flags2),{_src:re,_glob:glob})}get options(){return __privateGet(this,_options)}toRegExpSource(allowDot){var _a13;const dot=null!=allowDot?allowDot:!!__privateGet(this,_options).dot;if(__privateGet(this,_root)===this){__privateMethod(this,_AST_instances,flatten_fn).call(this);__privateMethod(this,_AST_instances,fillNegs_fn).call(this)}if(!isExtglobAST(this)){const noEmpty=this.isStart()&&this.isEnd()&&!__privateGet(this,_parts).some(s2=>"string"!=typeof s2),src=__privateGet(this,_parts).map(p2=>{var _a14;const[re,_,hasMagic,uflag]="string"==typeof p2?__privateMethod(_a14=_a3,_AST_static,parseGlob_fn).call(_a14,p2,__privateGet(this,_hasMagic),noEmpty):p2.toRegExpSource(allowDot);__privateSet(this,_hasMagic,__privateGet(this,_hasMagic)||hasMagic);__privateSet(this,_uflag,__privateGet(this,_uflag)||uflag);return re}).join("");let start2="";if(this.isStart()&&"string"==typeof __privateGet(this,_parts)[0]){const dotTravAllowed=1===__privateGet(this,_parts).length&&justDots.has(__privateGet(this,_parts)[0]);if(!dotTravAllowed){const aps=addPatternStart,needNoTrav=dot&&aps.has(src.charAt(0))||src.startsWith("\\.")&&aps.has(src.charAt(2))||src.startsWith("\\.\\.")&&aps.has(src.charAt(4)),needNoDot=!dot&&!allowDot&&aps.has(src.charAt(0));start2=needNoTrav?startNoTraversal:needNoDot?startNoDot:""}}let end="";this.isEnd()&&__privateGet(__privateGet(this,_root),_filledNegs)&&"!"===(null==(_a13=__privateGet(this,_parent))?void 0:_a13.type)&&(end="(?:$|\\/)");const final2=start2+src+end;return[final2,unescape2(src),__privateSet(this,_hasMagic,!!__privateGet(this,_hasMagic)),__privateGet(this,_uflag)]}const repeated="*"===this.type||"+"===this.type,start="!"===this.type?"(?:(?!(?:":"(?:";let body=__privateMethod(this,_AST_instances,partsToRegExp_fn).call(this,dot);if(this.isStart()&&this.isEnd()&&!body&&"!"!==this.type){const s2=this.toString(),me=this;__privateSet(me,_parts,[s2]);me.type=null;__privateSet(me,_hasMagic,void 0);return[s2,unescape2(this.toString()),!1,!1]}let bodyDotAllowed=!repeated||allowDot||dot||!startNoDot?"":__privateMethod(this,_AST_instances,partsToRegExp_fn).call(this,!0);bodyDotAllowed===body&&(bodyDotAllowed="");bodyDotAllowed&&(body=`(?:${body})(?:${bodyDotAllowed})*?`);let final="";if("!"===this.type&&__privateGet(this,_emptyExt))final=(this.isStart()&&!dot?startNoDot:"")+starNoEmpty;else{const close="!"===this.type?"))"+(!this.isStart()||dot||allowDot?"":startNoDot)+star+")":"@"===this.type?")":"?"===this.type?")?":"+"===this.type&&bodyDotAllowed?")":"*"===this.type&&bodyDotAllowed?")?":`)${this.type}`;final=start+body+close}return[final,unescape2(body),__privateSet(this,_hasMagic,!!__privateGet(this,_hasMagic)),__privateGet(this,_uflag)]}};_root=new WeakMap;_hasMagic=new WeakMap;_uflag=new WeakMap;_parts=new WeakMap;_parent=new WeakMap;_parentIndex=new WeakMap;_negs=new WeakMap;_filledNegs=new WeakMap;_options=new WeakMap;_toString=new WeakMap;_emptyExt=new WeakMap;_AST_instances=new WeakSet;fillNegs_fn=function(){if(this!==__privateGet(this,_root))throw new Error("should only call on root");if(__privateGet(this,_filledNegs))return this;this.toString();__privateSet(this,_filledNegs,!0);let n3;for(;n3=__privateGet(this,_negs).pop();){if("!"!==n3.type)continue;let p2=n3,pp=__privateGet(p2,_parent);for(;pp;){for(let i3=__privateGet(p2,_parentIndex)+1;!pp.type&&i3<__privateGet(pp,_parts).length;i3++)for(const part of __privateGet(n3,_parts)){if("string"==typeof part)throw new Error("string part in extglob AST??");part.copyIn(__privateGet(pp,_parts)[i3])}p2=pp;pp=__privateGet(p2,_parent)}}return this};_AST_static=new WeakSet;parseAST_fn=function(str,ast,pos,opt,extDepth){var _a13,_b6,_c3,_d2,_e2;const maxDepth=null!=(_a13=opt.maxExtglobRecursion)?_a13:2;let escaping=!1,inBrace=!1,braceStart=-1,braceNeg=!1;if(null===ast.type){let i4=pos,acc2="";for(;i4<str.length;){const c3=str.charAt(i4++);if(escaping||"\\"===c3){escaping=!escaping;acc2+=c3;continue}if(inBrace){i4===braceStart+1?"^"!==c3&&"!"!==c3||(braceNeg=!0):"]"!==c3||i4===braceStart+2&&braceNeg||(inBrace=!1);acc2+=c3;continue}if("["===c3){inBrace=!0;braceStart=i4;braceNeg=!1;acc2+=c3;continue}const doRecurse=!opt.noext&&isExtglobType(c3)&&"("===str.charAt(i4)&&extDepth<=maxDepth;if(doRecurse){ast.push(acc2);acc2="";const ext2=new _a3(c3,ast);i4=__privateMethod(_b6=_a3,_AST_static,parseAST_fn).call(_b6,str,ext2,i4,opt,extDepth+1);ast.push(ext2);continue}acc2+=c3}ast.push(acc2);return i4}let i3=pos+1,part=new _a3(null,ast);const parts=[];let acc="";for(;i3<str.length;){const c3=str.charAt(i3++);if(escaping||"\\"===c3){escaping=!escaping;acc+=c3;continue}if(inBrace){i3===braceStart+1?"^"!==c3&&"!"!==c3||(braceNeg=!0):"]"!==c3||i3===braceStart+2&&braceNeg||(inBrace=!1);acc+=c3;continue}if("["===c3){inBrace=!0;braceStart=i3;braceNeg=!1;acc+=c3;continue}const doRecurse=!opt.noext&&isExtglobType(c3)&&"("===str.charAt(i3)&&(extDepth<=maxDepth||ast&&__privateMethod(_c3=ast,_AST_instances,canAdoptType_fn).call(_c3,c3));if(doRecurse){const depthAdd=ast&&__privateMethod(_d2=ast,_AST_instances,canAdoptType_fn).call(_d2,c3)?0:1;part.push(acc);acc="";const ext2=new _a3(c3,part);part.push(ext2);i3=__privateMethod(_e2=_a3,_AST_static,parseAST_fn).call(_e2,str,ext2,i3,opt,extDepth+depthAdd);continue}if("|"!==c3){if(")"===c3){""===acc&&0===__privateGet(ast,_parts).length&&__privateSet(ast,_emptyExt,!0);part.push(acc);acc="";ast.push(...parts,part);return i3}acc+=c3}else{part.push(acc);acc="";parts.push(part);part=new _a3(null,ast)}}ast.type=null;__privateSet(ast,_hasMagic,void 0);__privateSet(ast,_parts,[str.substring(pos-1)]);return i3};canAdoptWithSpace_fn=function(child2){return __privateMethod(this,_AST_instances,canAdopt_fn).call(this,child2,adoptionWithSpaceMap)};canAdopt_fn=function(child2,map4=adoptionMap){if(!child2||"object"!=typeof child2||null!==child2.type||1!==__privateGet(child2,_parts).length||null===this.type)return!1;const gc=__privateGet(child2,_parts)[0];return!(!gc||"object"!=typeof gc||null===gc.type)&&__privateMethod(this,_AST_instances,canAdoptType_fn).call(this,gc.type,map4)};canAdoptType_fn=function(c3,map4=adoptionAnyMap){var _a13;return!!(null==(_a13=map4.get(this.type))?void 0:_a13.includes(c3))};adoptWithSpace_fn=function(child2,index6){const gc=__privateGet(child2,_parts)[0],blank=new _a3(null,gc,this.options);__privateGet(blank,_parts).push("");gc.push(blank);__privateMethod(this,_AST_instances,adopt_fn).call(this,child2,index6)};adopt_fn=function(child2,index6){const gc=__privateGet(child2,_parts)[0];__privateGet(this,_parts).splice(index6,1,...__privateGet(gc,_parts));for(const p2 of __privateGet(gc,_parts))"object"==typeof p2&&__privateSet(p2,_parent,this);__privateSet(this,_toString,void 0)};canUsurpType_fn=function(c3){const m3=usurpMap.get(this.type);return!!(null==m3?void 0:m3.has(c3))};canUsurp_fn=function(child2){if(!child2||"object"!=typeof child2||null!==child2.type||1!==__privateGet(child2,_parts).length||null===this.type||1!==__privateGet(this,_parts).length)return!1;const gc=__privateGet(child2,_parts)[0];return!(!gc||"object"!=typeof gc||null===gc.type)&&__privateMethod(this,_AST_instances,canUsurpType_fn).call(this,gc.type)};usurp_fn=function(child2){const m3=usurpMap.get(this.type),gc=__privateGet(child2,_parts)[0],nt=null==m3?void 0:m3.get(gc.type);if(!nt)return!1;__privateSet(this,_parts,__privateGet(gc,_parts));for(const p2 of __privateGet(this,_parts))"object"==typeof p2&&__privateSet(p2,_parent,this);this.type=nt;__privateSet(this,_toString,void 0);__privateSet(this,_emptyExt,!1)};flatten_fn=function(){var _a13,_b6;if(isExtglobAST(this)){let iterations=0,done=!1;do{done=!0;for(let i3=0;i3<__privateGet(this,_parts).length;i3++){const c3=__privateGet(this,_parts)[i3];if("object"==typeof c3){__privateMethod(_b6=c3,_AST_instances,flatten_fn).call(_b6);if(__privateMethod(this,_AST_instances,canAdopt_fn).call(this,c3)){done=!1;__privateMethod(this,_AST_instances,adopt_fn).call(this,c3,i3)}else if(__privateMethod(this,_AST_instances,canAdoptWithSpace_fn).call(this,c3)){done=!1;__privateMethod(this,_AST_instances,adoptWithSpace_fn).call(this,c3,i3)}else if(__privateMethod(this,_AST_instances,canUsurp_fn).call(this,c3)){done=!1;__privateMethod(this,_AST_instances,usurp_fn).call(this,c3)}}}}while(!done&&++iterations<10)}else for(const p2 of __privateGet(this,_parts))"object"==typeof p2&&__privateMethod(_a13=p2,_AST_instances,flatten_fn).call(_a13);__privateSet(this,_toString,void 0)};partsToRegExp_fn=function(dot){return __privateGet(this,_parts).map(p2=>{if("string"==typeof p2)throw new Error("string type in extglob ast??");const[re,_,_hasMagic2,uflag]=p2.toRegExpSource(dot);__privateSet(this,_uflag,__privateGet(this,_uflag)||uflag);return re}).filter(p2=>!(this.isStart()&&this.isEnd()&&!p2)).join("|")};parseGlob_fn=function(glob,hasMagic,noEmpty=!1){let escaping=!1,re="",uflag=!1,inStar=!1;for(let i3=0;i3<glob.length;i3++){const c3=glob.charAt(i3);if(escaping){escaping=!1;re+=(reSpecials.has(c3)?"\\":"")+c3}else if("*"!==c3){inStar=!1;if("\\"!==c3){if("["===c3){const[src,needUflag,consumed,magic]=parseClass(glob,i3);if(consumed){re+=src;uflag=uflag||needUflag;i3+=consumed-1;hasMagic=hasMagic||magic;continue}}if("?"!==c3)re+=regExpEscape(c3);else{re+=qmark;hasMagic=!0}}else i3===glob.length-1?re+="\\\\":escaping=!0}else{if(inStar)continue;inStar=!0;re+=noEmpty&&/^[*]+$/.test(glob)?starNoEmpty:star;hasMagic=!0}}return[re,unescape2(glob),!!hasMagic,uflag]};__privateAdd(AST,_AST_static);_a3=AST;escape=(s2,{windowsPathsNoEscape=!1,magicalBraces=!1}={})=>magicalBraces?windowsPathsNoEscape?s2.replace(/[?*()[\]{}]/g,"[$&]"):s2.replace(/[?*()[\]\\{}]/g,"\\$&"):windowsPathsNoEscape?s2.replace(/[?*()[\]]/g,"[$&]"):s2.replace(/[?*()[\]\\]/g,"\\$&");minimatch=(p2,pattern,options={})=>{assertValidPattern(pattern);return!(!options.nocomment&&"#"===pattern.charAt(0))&&new Minimatch(pattern,options).match(p2)};starDotExtRE=/^\*+([^+@!?*[(]*)$/;starDotExtTest=ext2=>f4=>!f4.startsWith(".")&&f4.endsWith(ext2);starDotExtTestDot=ext2=>f4=>f4.endsWith(ext2);starDotExtTestNocase=ext2=>{ext2=ext2.toLowerCase();return f4=>!f4.startsWith(".")&&f4.toLowerCase().endsWith(ext2)};starDotExtTestNocaseDot=ext2=>{ext2=ext2.toLowerCase();return f4=>f4.toLowerCase().endsWith(ext2)};starDotStarRE=/^\*+\.\*+$/;starDotStarTest=f4=>!f4.startsWith(".")&&f4.includes(".");starDotStarTestDot=f4=>"."!==f4&&".."!==f4&&f4.includes(".");dotStarRE=/^\.\*+$/;dotStarTest=f4=>"."!==f4&&".."!==f4&&f4.startsWith(".");starRE=/^\*+$/;starTest=f4=>0!==f4.length&&!f4.startsWith(".");starTestDot=f4=>0!==f4.length&&"."!==f4&&".."!==f4;qmarksRE=/^\?+([^+@!?*[(]*)?$/;qmarksTestNocase=([$0,ext2=""])=>{const noext=qmarksTestNoExt([$0]);if(!ext2)return noext;ext2=ext2.toLowerCase();return f4=>noext(f4)&&f4.toLowerCase().endsWith(ext2)};qmarksTestNocaseDot=([$0,ext2=""])=>{const noext=qmarksTestNoExtDot([$0]);if(!ext2)return noext;ext2=ext2.toLowerCase();return f4=>noext(f4)&&f4.toLowerCase().endsWith(ext2)};qmarksTestDot=([$0,ext2=""])=>{const noext=qmarksTestNoExtDot([$0]);return ext2?f4=>noext(f4)&&f4.endsWith(ext2):noext};qmarksTest=([$0,ext2=""])=>{const noext=qmarksTestNoExt([$0]);return ext2?f4=>noext(f4)&&f4.endsWith(ext2):noext};qmarksTestNoExt=([$0])=>{const len=$0.length;return f4=>f4.length===len&&!f4.startsWith(".")};qmarksTestNoExtDot=([$0])=>{const len=$0.length;return f4=>f4.length===len&&"."!==f4&&".."!==f4};defaultPlatform="object"==typeof process&&process?"object"==typeof process.env&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix";path_win32={sep:"\\"},path_posix={sep:"/"};sep="win32"===defaultPlatform?path_win32.sep:path_posix.sep;minimatch.sep=sep;GLOBSTAR=Symbol("globstar **");minimatch.GLOBSTAR=GLOBSTAR;qmark2="[^/]";star2=qmark2+"*?";twoStarDot="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";twoStarNoDot="(?:(?!(?:\\/|^)\\.).)*?";filter=(pattern,options={})=>p2=>minimatch(p2,pattern,options);minimatch.filter=filter;ext=(a2,b3={})=>Object.assign({},a2,b3);defaults=def=>{if(!def||"object"!=typeof def||!Object.keys(def).length)return minimatch;const orig=minimatch;return Object.assign((p2,pattern,options={})=>orig(p2,pattern,ext(def,options)),{Minimatch:class Minimatch extends orig.Minimatch{constructor(pattern,options={}){super(pattern,ext(def,options))}static defaults(options){return orig.defaults(ext(def,options)).Minimatch}},AST:class AST extends orig.AST{constructor(type,parent,options={}){super(type,parent,ext(def,options))}static fromGlob(pattern,options={}){return orig.AST.fromGlob(pattern,ext(def,options))}},unescape:(s2,options={})=>orig.unescape(s2,ext(def,options)),escape:(s2,options={})=>orig.escape(s2,ext(def,options)),filter:(pattern,options={})=>orig.filter(pattern,ext(def,options)),defaults:options=>orig.defaults(ext(def,options)),makeRe:(pattern,options={})=>orig.makeRe(pattern,ext(def,options)),braceExpand:(pattern,options={})=>orig.braceExpand(pattern,ext(def,options)),match:(list,pattern,options={})=>orig.match(list,pattern,ext(def,options)),sep:orig.sep,GLOBSTAR})};minimatch.defaults=defaults;braceExpand=(pattern,options={})=>{assertValidPattern(pattern);return options.nobrace||!/\{(?:(?!\{).)*\}/.test(pattern)?[pattern]:expand(pattern,{max:options.braceExpandMax})};minimatch.braceExpand=braceExpand;makeRe=(pattern,options={})=>new Minimatch(pattern,options).makeRe();minimatch.makeRe=makeRe;match=(list,pattern,options={})=>{const mm=new Minimatch(pattern,options);list=list.filter(f4=>mm.match(f4));mm.options.nonull&&!list.length&&list.push(pattern);return list};minimatch.match=match;globMagic=/[?*]|[+@!]\(.*?\)|\[|\]/;regExpEscape2=s2=>s2.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");Minimatch=class{constructor(pattern,options={}){__privateAdd(this,_Minimatch_instances);__publicField(this,"options");__publicField(this,"set");__publicField(this,"pattern");__publicField(this,"windowsPathsNoEscape");__publicField(this,"nonegate");__publicField(this,"negate");__publicField(this,"comment");__publicField(this,"empty");__publicField(this,"preserveMultipleSlashes");__publicField(this,"partial");__publicField(this,"globSet");__publicField(this,"globParts");__publicField(this,"nocase");__publicField(this,"isWindows");__publicField(this,"platform");__publicField(this,"windowsNoMagicRoot");__publicField(this,"maxGlobstarRecursion");__publicField(this,"regexp");var _a13;assertValidPattern(pattern);options=options||{};this.options=options;this.maxGlobstarRecursion=null!=(_a13=options.maxGlobstarRecursion)?_a13:200;this.pattern=pattern;this.platform=options.platform||defaultPlatform;this.isWindows="win32"===this.platform;this.windowsPathsNoEscape=!!options.windowsPathsNoEscape||!1===options.allowWindowsEscape;this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/"));this.preserveMultipleSlashes=!!options.preserveMultipleSlashes;this.regexp=null;this.negate=!1;this.nonegate=!!options.nonegate;this.comment=!1;this.empty=!1;this.partial=!!options.partial;this.nocase=!!this.options.nocase;this.windowsNoMagicRoot=void 0!==options.windowsNoMagicRoot?options.windowsNoMagicRoot:!(!this.isWindows||!this.nocase);this.globSet=[];this.globParts=[];this.set=[];this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(const pattern of this.set)for(const part of pattern)if("string"!=typeof part)return!0;return!1}debug(..._){}make(){const pattern=this.pattern,options=this.options;if(!options.nocomment&&"#"===pattern.charAt(0)){this.comment=!0;return}if(!pattern){this.empty=!0;return}this.parseNegate();this.globSet=[...new Set(this.braceExpand())];options.debug&&(this.debug=(...args)=>console.error(...args));this.debug(this.pattern,this.globSet);const rawGlobParts=this.globSet.map(s2=>this.slashSplit(s2));this.globParts=this.preprocess(rawGlobParts);this.debug(this.pattern,this.globParts);let set2=this.globParts.map((s2,_,__)=>{if(this.isWindows&&this.windowsNoMagicRoot){const isUNC=!(""!==s2[0]||""!==s2[1]||"?"!==s2[2]&&globMagic.test(s2[2])||globMagic.test(s2[3])),isDrive=/^[a-z]:/i.test(s2[0]);if(isUNC)return[...s2.slice(0,4),...s2.slice(4).map(ss=>this.parse(ss))];if(isDrive)return[s2[0],...s2.slice(1).map(ss=>this.parse(ss))]}return s2.map(ss=>this.parse(ss))});this.debug(this.pattern,set2);this.set=set2.filter(s2=>-1===s2.indexOf(!1));if(this.isWindows)for(let i3=0;i3<this.set.length;i3++){const p2=this.set[i3];""===p2[0]&&""===p2[1]&&"?"===this.globParts[i3][2]&&"string"==typeof p2[3]&&/^[a-z]:$/i.test(p2[3])&&(p2[2]="?")}this.debug(this.pattern,this.set)}preprocess(globParts){if(this.options.noglobstar)for(const partset of globParts)for(let j2=0;j2<partset.length;j2++)"**"===partset[j2]&&(partset[j2]="*");const{optimizationLevel=1}=this.options;if(optimizationLevel>=2){globParts=this.firstPhasePreProcess(globParts);globParts=this.secondPhasePreProcess(globParts)}else globParts=optimizationLevel>=1?this.levelOneOptimize(globParts):this.adjascentGlobstarOptimize(globParts);return globParts}adjascentGlobstarOptimize(globParts){return globParts.map(parts=>{let gs=-1;for(;-1!==(gs=parts.indexOf("**",gs+1));){let i3=gs;for(;"**"===parts[i3+1];)i3++;i3!==gs&&parts.splice(gs,i3-gs)}return parts})}levelOneOptimize(globParts){return globParts.map(parts=>{parts=parts.reduce((set2,part)=>{const prev=set2[set2.length-1];if("**"===part&&"**"===prev)return set2;if(".."===part&&prev&&".."!==prev&&"."!==prev&&"**"!==prev){set2.pop();return set2}set2.push(part);return set2},[]);return 0===parts.length?[""]:parts})}levelTwoFileOptimize(parts){Array.isArray(parts)||(parts=this.slashSplit(parts));let didSomething=!1;do{didSomething=!1;if(!this.preserveMultipleSlashes){for(let i3=1;i3<parts.length-1;i3++){const p2=parts[i3];if((1!==i3||""!==p2||""!==parts[0])&&("."===p2||""===p2)){didSomething=!0;parts.splice(i3,1);i3--}}if("."===parts[0]&&2===parts.length&&("."===parts[1]||""===parts[1])){didSomething=!0;parts.pop()}}let dd=0;for(;-1!==(dd=parts.indexOf("..",dd+1));){const p2=parts[dd-1];if(p2&&"."!==p2&&".."!==p2&&"**"!==p2&&(!this.isWindows||!/^[a-z]:$/i.test(p2))){didSomething=!0;parts.splice(dd-1,2);dd-=2}}}while(didSomething);return 0===parts.length?[""]:parts}firstPhasePreProcess(globParts){let didSomething=!1;do{didSomething=!1;for(let parts of globParts){let gs=-1;for(;-1!==(gs=parts.indexOf("**",gs+1));){let gss=gs;for(;"**"===parts[gss+1];)gss++;gss>gs&&parts.splice(gs+1,gss-gs);let next2=parts[gs+1];const p2=parts[gs+2],p22=parts[gs+3];if(".."!==next2)continue;if(!p2||"."===p2||".."===p2||!p22||"."===p22||".."===p22)continue;didSomething=!0;parts.splice(gs,1);const other=parts.slice(0);other[gs]="**";globParts.push(other);gs--}if(!this.preserveMultipleSlashes){for(let i3=1;i3<parts.length-1;i3++){const p2=parts[i3];if((1!==i3||""!==p2||""!==parts[0])&&("."===p2||""===p2)){didSomething=!0;parts.splice(i3,1);i3--}}if("."===parts[0]&&2===parts.length&&("."===parts[1]||""===parts[1])){didSomething=!0;parts.pop()}}let dd=0;for(;-1!==(dd=parts.indexOf("..",dd+1));){const p2=parts[dd-1];if(p2&&"."!==p2&&".."!==p2&&"**"!==p2){didSomething=!0;const needDot=1===dd&&"**"===parts[dd+1],splin=needDot?["."]:[];parts.splice(dd-1,2,...splin);0===parts.length&&parts.push("");dd-=2}}}}while(didSomething);return globParts}secondPhasePreProcess(globParts){for(let i3=0;i3<globParts.length-1;i3++)for(let j2=i3+1;j2<globParts.length;j2++){const matched=this.partsMatch(globParts[i3],globParts[j2],!this.preserveMultipleSlashes);if(matched){globParts[i3]=[];globParts[j2]=matched;break}}return globParts.filter(gs=>gs.length)}partsMatch(a2,b3,emptyGSMatch=!1){let ai2=0,bi2=0,result=[],which="";for(;ai2<a2.length&&bi2<b3.length;)if(a2[ai2]===b3[bi2]){result.push("b"===which?b3[bi2]:a2[ai2]);ai2++;bi2++}else if(emptyGSMatch&&"**"===a2[ai2]&&b3[bi2]===a2[ai2+1]){result.push(a2[ai2]);ai2++}else if(emptyGSMatch&&"**"===b3[bi2]&&a2[ai2]===b3[bi2+1]){result.push(b3[bi2]);bi2++}else if("*"!==a2[ai2]||!b3[bi2]||!this.options.dot&&b3[bi2].startsWith(".")||"**"===b3[bi2]){if("*"!==b3[bi2]||!a2[ai2]||!this.options.dot&&a2[ai2].startsWith(".")||"**"===a2[ai2])return!1;if("a"===which)return!1;which="b";result.push(b3[bi2]);ai2++;bi2++}else{if("b"===which)return!1;which="a";result.push(a2[ai2]);ai2++;bi2++}return a2.length===b3.length&&result}parseNegate(){if(this.nonegate)return;const pattern=this.pattern;let negate4=!1,negateOffset=0;for(let i3=0;i3<pattern.length&&"!"===pattern.charAt(i3);i3++){negate4=!negate4;negateOffset++}negateOffset&&(this.pattern=pattern.slice(negateOffset));this.negate=negate4}matchOne(file,pattern,partial=!1){let fileStartIndex=0,patternStartIndex=0;if(this.isWindows){const fileDrive="string"==typeof file[0]&&/^[a-z]:$/i.test(file[0]),fileUNC=!fileDrive&&""===file[0]&&""===file[1]&&"?"===file[2]&&/^[a-z]:$/i.test(file[3]),patternDrive="string"==typeof pattern[0]&&/^[a-z]:$/i.test(pattern[0]),patternUNC=!patternDrive&&""===pattern[0]&&""===pattern[1]&&"?"===pattern[2]&&"string"==typeof pattern[3]&&/^[a-z]:$/i.test(pattern[3]),fdi=fileUNC?3:fileDrive?0:void 0,pdi=patternUNC?3:patternDrive?0:void 0;if("number"==typeof fdi&&"number"==typeof pdi){const[fd2,pd]=[file[fdi],pattern[pdi]];if(fd2.toLowerCase()===pd.toLowerCase()){pattern[pdi]=fd2;patternStartIndex=pdi;fileStartIndex=fdi}}}const{optimizationLevel=1}=this.options;optimizationLevel>=2&&(file=this.levelTwoFileOptimize(file));return pattern.includes(GLOBSTAR)?__privateMethod(this,_Minimatch_instances,matchGlobstar_fn).call(this,file,pattern,partial,fileStartIndex,patternStartIndex):__privateMethod(this,_Minimatch_instances,matchOne_fn).call(this,file,pattern,partial,fileStartIndex,patternStartIndex)}braceExpand(){return braceExpand(this.pattern,this.options)}parse(pattern){assertValidPattern(pattern);const options=this.options;if("**"===pattern)return GLOBSTAR;if(""===pattern)return"";let m3,fastTest=null;(m3=pattern.match(starRE))?fastTest=options.dot?starTestDot:starTest:(m3=pattern.match(starDotExtRE))?fastTest=(options.nocase?options.dot?starDotExtTestNocaseDot:starDotExtTestNocase:options.dot?starDotExtTestDot:starDotExtTest)(m3[1]):(m3=pattern.match(qmarksRE))?fastTest=(options.nocase?options.dot?qmarksTestNocaseDot:qmarksTestNocase:options.dot?qmarksTestDot:qmarksTest)(m3):(m3=pattern.match(starDotStarRE))?fastTest=options.dot?starDotStarTestDot:starDotStarTest:(m3=pattern.match(dotStarRE))&&(fastTest=dotStarTest);const re=AST.fromGlob(pattern,this.options).toMMPattern();fastTest&&"object"==typeof re&&Reflect.defineProperty(re,"test",{value:fastTest});return re}makeRe(){if(this.regexp||!1===this.regexp)return this.regexp;const set2=this.set;if(!set2.length){this.regexp=!1;return this.regexp}const options=this.options,twoStar=options.noglobstar?star2:options.dot?twoStarDot:twoStarNoDot,flags2=new Set(options.nocase?["i"]:[]);let re=set2.map(pattern=>{const pp=pattern.map(p2=>{if(p2 instanceof RegExp)for(const f4 of p2.flags.split(""))flags2.add(f4);return"string"==typeof p2?regExpEscape2(p2):p2===GLOBSTAR?GLOBSTAR:p2._src});pp.forEach((p2,i3)=>{const next2=pp[i3+1],prev=pp[i3-1];if(p2===GLOBSTAR&&prev!==GLOBSTAR)if(void 0===prev)void 0!==next2&&next2!==GLOBSTAR?pp[i3+1]="(?:\\/|"+twoStar+"\\/)?"+next2:pp[i3]=twoStar;else if(void 0===next2)pp[i3-1]=prev+"(?:\\/|\\/"+twoStar+")?";else if(next2!==GLOBSTAR){pp[i3-1]=prev+"(?:\\/|\\/"+twoStar+"\\/)"+next2;pp[i3+1]=GLOBSTAR}});const filtered=pp.filter(p2=>p2!==GLOBSTAR);if(this.partial&&filtered.length>=1){const prefixes=[];for(let i3=1;i3<=filtered.length;i3++)prefixes.push(filtered.slice(0,i3).join("/"));return"(?:"+prefixes.join("|")+")"}return filtered.join("/")}).join("|");const[open,close]=set2.length>1?["(?:",")"]:["",""];re="^"+open+re+close+"$";this.partial&&(re="^(?:\\/|"+open+re.slice(1,-1)+close+")$");this.negate&&(re="^(?!"+re+").+$");try{this.regexp=new RegExp(re,[...flags2].join(""))}catch(e3){this.regexp=!1}return this.regexp}slashSplit(p2){return this.preserveMultipleSlashes?p2.split("/"):this.isWindows&&/^\/\/[^/]+/.test(p2)?["",...p2.split(/\/+/)]:p2.split(/\/+/)}match(f4,partial=this.partial){this.debug("match",f4,this.pattern);if(this.comment)return!1;if(this.empty)return""===f4;if("/"===f4&&partial)return!0;const options=this.options;this.isWindows&&(f4=f4.split("\\").join("/"));const ff2=this.slashSplit(f4);this.debug(this.pattern,"split",ff2);const set2=this.set;this.debug(this.pattern,"set",set2);let filename=ff2[ff2.length-1];if(!filename)for(let i3=ff2.length-2;!filename&&i3>=0;i3--)filename=ff2[i3];for(const pattern of set2){let file=ff2;options.matchBase&&1===pattern.length&&(file=[filename]);const hit=this.matchOne(file,pattern,partial);if(hit)return!!options.flipNegate||!this.negate}return!options.flipNegate&&this.negate}static defaults(def){return minimatch.defaults(def).Minimatch}};_Minimatch_instances=new WeakSet;matchGlobstar_fn=function(file,pattern,partial,fileIndex,patternIndex){const firstgs=pattern.indexOf(GLOBSTAR,patternIndex),lastgs=pattern.lastIndexOf(GLOBSTAR),[head2,body,tail]=partial?[pattern.slice(patternIndex,firstgs),pattern.slice(firstgs+1),[]]:[pattern.slice(patternIndex,firstgs),pattern.slice(firstgs+1,lastgs),pattern.slice(lastgs+1)];if(head2.length){const fileHead=file.slice(fileIndex,fileIndex+head2.length);if(!__privateMethod(this,_Minimatch_instances,matchOne_fn).call(this,fileHead,head2,partial,0,0))return!1;fileIndex+=head2.length;patternIndex+=head2.length}let fileTailMatch=0;if(tail.length){if(tail.length+fileIndex>file.length)return!1;let tailStart=file.length-tail.length;if(__privateMethod(this,_Minimatch_instances,matchOne_fn).call(this,file,tail,partial,tailStart,0))fileTailMatch=tail.length;else{if(""!==file[file.length-1]||fileIndex+tail.length===file.length)return!1;tailStart--;if(!__privateMethod(this,_Minimatch_instances,matchOne_fn).call(this,file,tail,partial,tailStart,0))return!1;fileTailMatch=tail.length+1}}if(!body.length){let sawSome=!!fileTailMatch;for(let i4=fileIndex;i4<file.length-fileTailMatch;i4++){const f4=String(file[i4]);sawSome=!0;if("."===f4||".."===f4||!this.options.dot&&f4.startsWith("."))return!1}return partial||sawSome}const bodySegments=[[[],0]];let currentBody=bodySegments[0],nonGsParts=0;const nonGsPartsSums=[0];for(const b3 of body)if(b3===GLOBSTAR){nonGsPartsSums.push(nonGsParts);currentBody=[[],0];bodySegments.push(currentBody)}else{currentBody[0].push(b3);nonGsParts++}let i3=bodySegments.length-1;const fileLength=file.length-fileTailMatch;for(const b3 of bodySegments)b3[1]=fileLength-(nonGsPartsSums[i3--]+b3[0].length);return!!__privateMethod(this,_Minimatch_instances,matchGlobStarBodySections_fn).call(this,file,bodySegments,fileIndex,0,partial,0,!!fileTailMatch)};matchGlobStarBodySections_fn=function(file,bodySegments,fileIndex,bodyIndex,partial,globStarDepth,sawTail){const bs2=bodySegments[bodyIndex];if(!bs2){for(let i3=fileIndex;i3<file.length;i3++){sawTail=!0;const f4=file[i3];if("."===f4||".."===f4||!this.options.dot&&f4.startsWith("."))return!1}return sawTail}const[body,after]=bs2;for(;fileIndex<=after;){const m3=__privateMethod(this,_Minimatch_instances,matchOne_fn).call(this,file.slice(0,fileIndex+body.length),body,partial,fileIndex,0);if(m3&&globStarDepth<this.maxGlobstarRecursion){const sub=__privateMethod(this,_Minimatch_instances,matchGlobStarBodySections_fn).call(this,file,bodySegments,fileIndex+body.length,bodyIndex+1,partial,globStarDepth+1,sawTail);if(!1!==sub)return sub}const f4=file[fileIndex];if("."===f4||".."===f4||!this.options.dot&&f4.startsWith("."))return!1;fileIndex++}return partial||null};matchOne_fn=function(file,pattern,partial,fileIndex,patternIndex){let fi,pi,pl,fl2;for(fi=fileIndex,pi=patternIndex,fl2=file.length,pl=pattern.length;fi<fl2&&pi<pl;fi++,pi++){this.debug("matchOne loop");let hit,p2=pattern[pi],f4=file[fi];this.debug(pattern,p2,f4);if(!1===p2||p2===GLOBSTAR)return!1;if("string"==typeof p2){hit=f4===p2;this.debug("string match",p2,f4,hit)}else{hit=p2.test(f4);this.debug("pattern match",p2,f4,hit)}if(!hit)return!1}if(fi===fl2&&pi===pl)return!0;if(fi===fl2)return partial;if(pi===pl)return fi===fl2-1&&""===file[fi];throw new Error("wtf?")};minimatch.AST=AST;minimatch.Minimatch=Minimatch;minimatch.escape=escape;minimatch.unescape=unescape2;isProposalArrayBufferBase64Available="undefined"!=typeof Uint8Array&&"function"==typeof Uint8Array.prototype.toBase64&&"function"==typeof Uint8Array.fromBase64;base64ToArrayBuffer=isProposalArrayBufferBase64Available?base64ToArrayBufferNative:function base64ToArrayBufferBrowser(base64){if("string"==typeof base64)return base64ToArrayBufferInternalBrowser(base64);const bufItems=base64.map(e3=>base64ToArrayBufferInternalBrowser(e3)),len=bufItems.reduce((p2,c3)=>p2+c3.byteLength,0),joinedArray=new Uint8Array(len);let offset=0;bufItems.forEach(e3=>{joinedArray.set(new Uint8Array(e3),offset);offset+=e3.byteLength});return joinedArray.buffer};encodeChunkSize=15e7;arrayBufferToBase64Single=isProposalArrayBufferBase64Available?function arrayBufferToBase64SingleNative(buffer){const buf=buffer instanceof Uint8Array?buffer:new Uint8Array(buffer);return Promise.resolve(buf.toBase64())}:async function arrayBufferToBase64SingleBrowser(buffer){const buf=buffer instanceof Uint8Array?buffer:new Uint8Array(buffer);return buf.byteLength<QUANTUM?btoa(String.fromCharCode.apply(null,[...buf])):await arrayBufferToBase64internalBrowser(buf)};arrayBufferToBase64=isProposalArrayBufferBase64Available?function arrayBufferToBase64Native(buffer){const buf=buffer instanceof Uint8Array?buffer:new Uint8Array(buffer),result=buf.toBase64();return Promise.resolve([result])}:async function arrayBufferToBase64Browser(buffer){const buf=buffer instanceof Uint8Array?buffer:new Uint8Array(buffer);if(buf.byteLength<QUANTUM)return[btoa(String.fromCharCode.apply(null,[...buf]))];const bufLen=buf.byteLength,pieces=[];let idx2=0;do{const offset=idx2*encodeChunkSize,pBuf=new DataView(buf.buffer,buf.byteOffset+offset,Math.min(encodeChunkSize,buf.byteLength-offset));pieces.push(await arrayBufferToBase64internalBrowser(pBuf));idx2++}while(idx2*encodeChunkSize<bufLen);return pieces};QUANTUM=32768;te=new TextEncoder;td=new TextDecoder("utf-8",{ignoreBOM:!0});base64ToString=isProposalArrayBufferBase64Available?function base64ToStringNative(base64){try{if("string"!=typeof base64)return base64.map(e3=>base64ToStringNative(e3)).join("");const buffer=base64ToArrayBufferNative(base64),bytes=new Uint8Array(buffer);if(0===bytes.length&&base64.length>0)throw new TypeError("Could not parse the encoded string");return readString(bytes)}catch(ex){Logger("Base64 To String error",LOG_LEVEL_VERBOSE);Logger(ex,LOG_LEVEL_VERBOSE);return"string"!=typeof base64?base64.join(""):base64}}:function base64ToStringBrowser(base64){try{if("string"!=typeof base64)return base64.map(e3=>base64ToStringBrowser(e3)).join("");const binary_string=atob(base64),len=binary_string.length,bytes=new Uint8Array(len);for(let i3=0;i3<len;i3++)bytes[i3]=binary_string.charCodeAt(i3);return readString(bytes)}catch(ex){Logger("Base64 To String error",LOG_LEVEL_VERBOSE);Logger(ex,LOG_LEVEL_VERBOSE);return"string"!=typeof base64?base64.join(""):base64}};regexpBase64=/^[A-Za-z0-9+/]+=*$/;tryConvertBase64ToArrayBuffer=isProposalArrayBufferBase64Available?function tryConvertBase64ToArrayBufferNative(base64){try{const b64F=base64.replace(/\r|\n/g,"");if(!regexpBase64.test(b64F))return!1;const buf=Uint8Array.fromBase64(b64F);return buf.toBase64()===b64F&&(buf.byteLength>0&&buf.buffer)}catch(e3){return!1}}:function tryConvertBase64ToArrayBufferBrowser(base64){try{const b64F=base64.replace(/\r|\n/g,"");if(!regexpBase64.test(b64F))return!1;const binary_string=globalThis.atob(b64F);if(globalThis.btoa(binary_string)!==b64F)return!1;const len=binary_string.length,bytes=new Uint8Array(len);for(let i3=0;i3<len;i3++)bytes[i3]=binary_string.charCodeAt(i3);return bytes.buffer}catch(e3){return!1}};0;table={};revTable={};"undefined"!=typeof TextDecoderStream;[...function*range2(from,to){for(let i3=from;i3<=to;i3++)yield i3}(192,447)].forEach((e3,i3)=>{table[i3]=e3;revTable[e3]=i3});revMap={};numMap={};for(let i3=0;i3<256;i3++){revMap[`00${i3.toString(16)}`.slice(-2)]=i3;numMap[i3]=`00${i3.toString(16)}`.slice(-2)}isProposalArrayBufferBase64Available2="undefined"!=typeof Uint8Array&&"function"==typeof Uint8Array.prototype.toBase64&&"function"==typeof Uint8Array.fromBase64;hexStringToUint8Array=isProposalArrayBufferBase64Available2?function hexStringToUint8ArrayNative(src){return Uint8Array.fromHex(src)}:function hexStringToUint8ArrayBrowser(src){const len=src.length/2,ret=new Uint8Array(len);for(let i3=0;i3<len;i3++)ret[i3]=revMap[src[2*i3]+src[2*i3+1]];return ret};uint8ArrayToHexString=isProposalArrayBufferBase64Available2?function uint8ArrayToHexStringNative(src){return src.toHex()}:function uint8ArrayToHexStringBrowser(src){return[...src].map(e3=>numMap[e3]).join("")};_hashString=function memorizeFuncWithLRUCache(func){const cache2=new LRUCache(100,1e5,!0);return key3=>{const isExists=cache2.has(key3);if(isExists)return cache2.get(key3);const value=func(key3);cache2.set(key3,value);return value}}(async key3=>{const buff=writeString(key3),webcrypto6=await getWebCrypto(),digest=await webcrypto6.subtle.digest("SHA-256",buff);return uint8ArrayToHexString(new Uint8Array(digest))});matchOpts={platform:"linux",dot:!0,flipNegate:!0,nocase:!0};matcherCache=new WeakMap;isValidRemoteCouchDBURI=uri=>!!uri.startsWith("https://")||!!uri.startsWith("http://");_requestToCouchDBFetch=async(baseUri,username,password,path2,body,method)=>{const utf8str=String.fromCharCode.apply(null,[...writeString(`${username}:${password}`)]),encoded=compatGlobal.btoa(utf8str),authHeader="Basic "+encoded,transformedHeaders={authorization:authHeader,"content-type":"application/json"},uri=`${baseUri}/${path2}`,requestParam={url:uri,method:method||(body?"PUT":"GET"),headers:new Headers(transformedHeaders),contentType:"application/json",body:JSON.stringify(body)};return await _fetch(uri,requestParam)};throttle=(func,timeout)=>{let timer,lastTime=0;return(...args)=>{if(lastTime){clearTimeout(timer);const delayTime=timeout-(Date.now()-lastTime);timer=setTimeout(()=>{func(...args);lastTime=Date.now()},delayTime)}else{func(...args);lastTime=Date.now()}}};LiveSyncError=class _LiveSyncError extends Error{constructor(message,options){super(message);__publicField(this,"name",this.constructor.name);__publicField(this,"cause");__publicField(this,"overrideStatus");if(null==options?void 0:options.cause){const actualCause=getErrorCause(options);this.cause=actualCause instanceof Error?actualCause:new Error(`Unknown cause: ${getMessageFromError(actualCause)}`)}void 0!==(null==options?void 0:options.status)&&(this.overrideStatus=options.status)}get status(){if(void 0!==this.overrideStatus)return this.overrideStatus;if(this.cause){const status=getStatusFromError(this.cause);if(void 0!==status)return status}return 500}static isCausedBy(error,errorClass){if(!error)return!1;if(error instanceof errorClass)return!0;if("object"==typeof error&&error&&"cause"in error){const cause=getErrorCause(error);return cause!==error&&_LiveSyncError.isCausedBy(cause,errorClass)}return!1}static fromError(error){if(error instanceof this)return error;const instance=new this(`${this.name}: ${getMessageFromError(error)}`,{cause:error,status:getStatusFromError(error)});error instanceof Error?instance.stack=error.stack:instance.stack=(new Error).stack;return instance}};0;MARK_OPERATOR="";MARK_DELETED=`${MARK_OPERATOR}__DELETED`;MARK_ISARRAY=`${MARK_OPERATOR}__ARRAY`;MARK_SWAPPED=`${MARK_OPERATOR}__SWAP`;0;isIndexDBCmpExist=void 0!==(null==(_b=null==(_a4=compatGlobal)?void 0:_a4.indexedDB)?void 0:_b.cmp);0;globalConcurrencyController=Semaphore(50);map={"\n":"\\n","\r":"\\r","\\":"\\\\"};revMap2={"\\n":"\n","\\r":"\r","\\\\":"\\"};previousValues=new Map;CustomRegExp=class{constructor(regexp,flags2){__publicField(this,"regexp");__publicField(this,"negate");__publicField(this,"pattern");const[negate4,exp]=parseCustomRegExp(regexp);this.pattern=exp;this.regexp=new RegExp(exp,flags2);this.negate=negate4}test(str){return this.negate?!this.regexp.test(str):this.regexp.test(str)}};resolution=2e3;reactiveSource({pending:[],running:[],count:0});collectingChunks=reactiveSource(0);pluginScanningCount=reactiveSource(0);hiddenFilesProcessingCount=reactiveSource(0);hiddenFilesEventCount=reactiveSource(0);logMessages=reactiveSource([]);EventHub=class{constructor(emitter){Object.defineProperty(this,"_emitter",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_assigned",{enumerable:!0,configurable:!0,writable:!0,value:new Map});Object.defineProperty(this,"_allAssigned",{enumerable:!0,configurable:!0,writable:!0,value:new Map});this._emitter=null!=emitter?emitter:new EventTarget}_issueSignal(key3,callback){var _a13;let assigned=this._assigned.get(key3);void 0===assigned&&(assigned=new WeakMap);const controllerRef=assigned.get(callback);let controller=null==controllerRef?void 0:controllerRef.deref();if(!controller||controller.signal.aborted){controller=new AbortController;const refController=new FallbackWeakRef(controller);controller.signal.addEventListener("abort",()=>{var _a14,_b6;null==(_a14=this._assigned.get(key3))||_a14.delete(callback);null==(_b6=this._allAssigned.get(key3))||_b6.delete(refController)},{once:!0});assigned.set(callback,refController);this._assigned.set(key3,assigned);const allAssigned=null!=(_a13=this._allAssigned.get(key3))?_a13:new Set;allAssigned.add(refController);this._allAssigned.set(key3,allAssigned);return controller}return controller}emitEvent(event2,data){this._emitter.dispatchEvent(new CustomEvent(`${event2.toString()}`,{detail:null!=data?data:void 0}))}on(event2,callback,options){const key3=event2,controller=this._issueSignal(key3,callback);this._emitter.addEventListener(key3,e3=>{callback(e3,e3 instanceof CustomEvent?null==e3?void 0:e3.detail:void 0)},{...options,signal:controller.signal});return()=>this.off(event2,callback)}off(event2,callback){var _a13,_b6;const key3=event2;if(callback){const w2=null==(_a13=this._assigned.get(key3))?void 0:_a13.get(callback),controller=null==w2?void 0:w2.deref();null==controller||controller.abort()}else null==(_b6=this._allAssigned.get(key3))||_b6.forEach(w2=>{const controller=w2.deref();null==controller||controller.abort()})}offAll(){for(const[key3]of this._allAssigned)this.off(key3)}onEvent(event2,callback,options){const key3=event2,controller=this._issueSignal(key3,callback);this._emitter.addEventListener(key3,e3=>{callback(e3 instanceof CustomEvent?null==e3?void 0:e3.detail:void 0)},{...options,signal:controller.signal});return()=>this.off(event2,callback)}once(event2,callback){return this.on(event2,callback,{once:!0})}onceEvent(event2,callback){return this.on(event2,(_,data)=>callback(data),{once:!0})}waitFor(event2){return new Promise(resolve=>{this.onceEvent(event2,data=>{resolve(data)})})}};commonlibEnglishMessages={"(BETA) Always overwrite with a newer file":"(BETA) Always overwrite with a newer file","(Beta) Use ignore files":"(Beta) Use ignore files","(Days passed, 0 to disable automatic-deletion)":"(Days passed, 0 to disable automatic-deletion)","(MB) If this is set, changes to local and remote files that are larger than this will be skipped. If the file becomes smaller again, a newer one will be used.":"(MB) If this is set, changes to local and remote files that are larger than this will be skipped. If the file becomes smaller again, a newer one will be used.","(Mega chars)":"(Mega chars)","(Not recommended) If set, credentials will be stored in the file.":"(Not recommended) If set, credentials will be stored in the file.","(Obsolete) Use an old adapter for compatibility":"(Obsolete) Use an old adapter for compatibility","(ex. Read chunks online) If this option is enabled, LiveSync reads chunks online directly instead of replicating them locally. Increasing Custom chunk size is recommended.":"(ex. Read chunks online) If this option is enabled, LiveSync reads chunks online directly instead of replicating them locally. Increasing Custom chunk size is recommended.","Access Key":"Access Key","Active Remote Type":"Active Remote Type","Always prompt merge conflicts":"Always prompt merge conflicts","Application ID":"Application ID","Apply Latest Change if Conflicting":"Apply Latest Change if Conflicting","Apply preset configuration":"Apply preset configuration","Auto-accept compatible tweak mismatches":"Auto-accept compatible tweak mismatches","Automatically Sync all files when opening Obsidian.":"Automatically Sync all files when opening Obsidian.","Automatically accepts mismatches that are compatible but potentially lossy by comparing tweak modification times.":"Automatically accepts mismatches that are compatible but potentially lossy by comparing tweak modification times.","Automatically broadcast changes to connected peers":"Automatically broadcast changes to connected peers","Automatically start P2P connection on launch":"Automatically start P2P connection on launch","Batch database update":"Batch database update","Batch limit":"Batch limit","Batch size":"Batch size","Batch size of on-demand fetching":"Batch size of on-demand fetching","Before v0.17.16, we used an old adapter for the local database. Now the new adapter is preferred. However, it needs local database rebuilding. Please disable this toggle when you have enough time. If leave it enabled, also while fetching from the remote database, you will be asked to disable this.":"Before v0.17.16, we used an old adapter for the local database. Now the new adapter is preferred. However, it needs local database rebuilding. Please disable this toggle when you have enough time. If leave it enabled, also while fetching from the remote database, you will be asked to disable this.","Bucket Name":"Bucket Name","Chunk Splitter":"Chunk Splitter","Chunk revisions are always derived from their content. This stored key is retained only for compatibility.":"Chunk revisions are always derived from their content. This stored key is retained only for compatibility.","Comma separated `.gitignore, .dockerignore`":"Comma separated `.gitignore, .dockerignore`","Content-derived chunk revisions (obsolete setting)":"Content-derived chunk revisions (obsolete setting)","Custom Headers":"Custom Headers","Custom headers for requesting the CouchDB. e.g. `x-custom-header1: value1\n x-custom-header2: value2`":"Custom headers for requesting the CouchDB. e.g. `x-custom-header1: value1\n x-custom-header2: value2`","Custom headers for requesting the bucket. e.g. `x-custom-header1: value1\n x-custom-header2: value2`":"Custom headers for requesting the bucket. e.g. `x-custom-header1: value1\n x-custom-header2: value2`","Data Compression":"Data Compression","Database Name":"Database Name","Database suffix":"Database suffix","Delay conflict resolution of inactive files":"Delay conflict resolution of inactive files","Delay merge conflict prompt for inactive files.":"Delay merge conflict prompt for inactive files.","Delete old metadata of deleted files on start-up":"Delete old metadata of deleted files on start-up","Desktop only; uses more battery and network.":"Desktop only; uses more battery and network.","Device name":"Device name","Disables logging, only shows notifications. Please disable if you report an issue.":"Disables logging, only shows notifications. Please disable if you report an issue.","Display Language":"Display Language","Do not check configuration mismatch before replication":"Do not check configuration mismatch before replication","Do not keep metadata of deleted files.":"Do not keep metadata of deleted files.","Do not split chunks in the background":"Do not split chunks in the background","Do not use internal API":"Do not use internal API","Doctor.Button.DismissThisVersion":"No, and do not ask again until the next release","Doctor.Button.Fix":"Fix it","Doctor.Button.FixButNoRebuild":"Fix it but no rebuild","Doctor.Button.No":"No","Doctor.Button.Skip":"Leave it as is","Doctor.Button.Yes":"Yes","Doctor.Dialogue.Main":"Hi! Config Doctor has been activated because of ${activateReason}!\nAnd, unfortunately some configurations were detected as potential problems.\nPlease be assured. Let's solve them one by one.\n\nTo let you know ahead of time, we will ask you about the following items.\n\n${issues}\n\nShall we get started?","Doctor.Dialogue.MainFix":"\n## ${name}\n\n| Current | Ideal |\n|:---:|:---:|\n| ${current} | ${ideal} |\n\n**Recommendation Level:** ${level}\n\n### Why this has been detected?\n\n${reason}\n\n${note}\n\nFix this to the ideal value?","Doctor.Dialogue.Title":"Self-hosted LiveSync Config Doctor","Doctor.Dialogue.TitleAlmostDone":"Almost done!","Doctor.Dialogue.TitleFix":"Fix issue ${current}/${total}","Doctor.Level.Must":"Must","Doctor.Level.Necessary":"Necessary","Doctor.Level.Optional":"Optional","Doctor.Level.Recommended":"Recommended","Doctor.Message.NoIssues":"No issues detected!","Doctor.Message.RebuildLocalRequired":"Attention! A local database rebuild is required to apply this!","Doctor.Message.RebuildRequired":"Attention! A rebuild is required to apply this!","Doctor.Message.SomeSkipped":"We left some issues as is. Shall I ask you again on next startup?","Doctor.RULES.E2EE_V02500.REASON":"The End-to-End Encryption has got now more robust and faster. Also because, the previous E2EE was found to be compromised in a re-conducted code review. It should be applied as soon as possible. Really apologises for your inconvenience. And, this setting is not forward compatible. All synchronised devices must be updated to v0.25.0 or higher. Rebuilds are not required and will be converted from the new transfer to the new format, However, it is recommended to rebuild whenever possible.","Effectively a directory. Should end with `/`. e.g., `vault-name/`.":"Effectively a directory. Should end with `/`. e.g., `vault-name/`.","Enable Developers' Debug Tools (If available).":"Enable Developers' Debug Tools (If available).","Enable P2P Synchronization":"Enable P2P Synchronization","Enable advanced features":"Enable advanced features","Enable customization sync":"Enable customization sync","Enable edge case treatment features":"Enable edge case treatment features","Enable forcePathStyle":"Enable forcePathStyle","Enable per-file customization sync":"Enable per-file customization sync","Enable poweruser features":"Enable poweruser features","Enable this if your Object Storage doesn't support CORS":"Enable this if your Object Storage doesn't support CORS","Enable this option to automatically apply the most recent change to documents even when it conflicts":"Enable this option to automatically apply the most recent change to documents even when it conflicts","Encrypt contents on the remote database. If you use the plugin's synchronization feature, enabling this is recommended.":"Encrypt contents on the remote database. If you use the plugin's synchronization feature, enabling this is recommended.","Encrypting sensitive configuration items":"Encrypting sensitive configuration items","Encryption passphrase. If changed, you should overwrite the server's database with the new (encrypted) files.":"Encryption passphrase. If changed, you should overwrite the server's database with the new (encrypted) files.","End-to-End Encryption":"End-to-End Encryption","End-to-End Encryption Algorithm":"End-to-End Encryption Algorithm","Endpoint URL":"Endpoint URL","Enhance chunk size":"Enhance chunk size","Fetch chunks on demand":"Fetch chunks on demand","Fetch database with previous behaviour":"Fetch database with previous behaviour","File prefix on the bucket":"File prefix on the bucket",Filename:"Filename","Files with modification times greater than this value (in seconds since the Unix epoch) will not have their events reflected. Set to 0 to disable this limit.":"Files with modification times greater than this value (in seconds since the Unix epoch) will not have their events reflected. Set to 0 to disable this limit.","Forces the file to be synced when opened.":"Forces the file to be synced when opened.","Handle files as Case-Sensitive":"Handle files as Case-Sensitive","How to display network errors when the sync server is unreachable.":"How to display network errors when the sync server is unreachable.","If disabled(toggled), chunks will be split on the UI thread (Previous behaviour).":"If disabled(toggled), chunks will be split on the UI thread (Previous behaviour).","If enabled per-filed efficient customization sync will be used. We need a small migration when enabling this. And all devices should be updated to v0.23.18. Once we enabled this, we lost a compatibility with old versions.":"If enabled per-filed efficient customization sync will be used. We need a small migration when enabling this. And all devices should be updated to v0.23.18. Once we enabled this, we lost a compatibility with old versions.","If enabled, changes will be automatically broadcasted to all connected peers. Notified peers will start fetching the changes.":"If enabled, changes will be automatically broadcasted to all connected peers. Notified peers will start fetching the changes.","If enabled, chunks will be split into no more than 100 items. However, dedupe is slightly weaker.":"If enabled, chunks will be split into no more than 100 items. However, dedupe is slightly weaker.","If enabled, efficient per-file customization sync will be used. A minor migration is required when enabling this feature, and all devices must be updated to v0.23.18. Enabling this feature will result in losing compatibility with older versions.":"If enabled, efficient per-file customization sync will be used. A minor migration is required when enabling this feature, and all devices must be updated to v0.23.18. Enabling this feature will result in losing compatibility with older versions.","If enabled, newly created chunks are temporarily kept within the document, and graduated to become independent chunks once stabilised.":"If enabled, newly created chunks are temporarily kept within the document, and graduated to become independent chunks once stabilised.","If enabled, the P2P connection will be automatically started when the application launches.":"If enabled, the P2P connection will be automatically started when the application launches.","If enabled, the file properties will be encrypted in the remote database. This is useful for protecting sensitive information in file paths, sizes, and IDs of its chunks. If you are using V1 E2EE, this only obfuscates the file path.":"If enabled, the file properties will be encrypted in the remote database. This is useful for protecting sensitive information in file paths, sizes, and IDs of its chunks. If you are using V1 E2EE, this only obfuscates the file path.","If enabled, the file under 1kb will be processed in the UI thread.":"If enabled, the file under 1kb will be processed in the UI thread.","If enabled, the forcePathStyle option will be used for bucket operations.":"If enabled, the forcePathStyle option will be used for bucket operations.","If enabled, the notification of hidden files change will be suppressed.":"If enabled, the notification of hidden files change will be suppressed.","If enabled, the plugin will not attempt to connect to the remote database even if the chunk was not found locally.":"If enabled, the plugin will not attempt to connect to the remote database even if the chunk was not found locally.","If enabled, the request API will be used to avoid `inevitable` CORS problems. This is a workaround and may not work in all cases. PLEASE READ THE DOCUMENTATION BEFORE USING THIS OPTION. This is a less-secure option.":"If enabled, the request API will be used to avoid `inevitable` CORS problems. This is a workaround and may not work in all cases. PLEASE READ THE DOCUMENTATION BEFORE USING THIS OPTION. This is a less-secure option.","If enabled, the ⛔ icon will be shown inside the status instead of the file warnings banner. No details will be shown.":"If enabled, the ⛔ icon will be shown inside the status instead of the file warnings banner. No details will be shown.","If this enabled, All files are handled as case-Sensitive (Previous behaviour).":"If this enabled, All files are handled as case-Sensitive (Previous behaviour).","If this enabled, JWT will be used for authentication.":"If this enabled, JWT will be used for authentication.","If this enabled, chunks will be split into semantically meaningful segments. Not all platforms support this feature.":"If this enabled, chunks will be split into semantically meaningful segments. Not all platforms support this feature.","If this is set, changes to local files which are matched by the ignore files will be skipped. Remote changes are determined using local ignore files.":"If this is set, changes to local files which are matched by the ignore files will be skipped. Remote changes are determined using local ignore files.","If this option is enabled, PouchDB will hold the connection open for 60 seconds, and if no change arrives in that time, close and reopen the socket, instead of holding it open indefinitely. Useful when a proxy limits request duration but can increase resource usage.":"If this option is enabled, PouchDB will hold the connection open for 60 seconds, and if no change arrives in that time, close and reopen the socket, instead of holding it open indefinitely. Useful when a proxy limits request duration but can increase resource usage.","Ignore files":"Ignore files","Incubate Chunks in Document":"Incubate Chunks in Document","Internal timestamp for resolving compatible tweak mismatches.":"Internal timestamp for resolving compatible tweak mismatches.","Interval (sec)":"Interval (sec)","JWT Algorithm":"JWT Algorithm","K.long_p2p_sync":"%{title_p2p_sync}","K.title_p2p_sync":"Peer-to-Peer Sync","Keep empty folder":"Keep empty folder","Keep replication active in the background":"Keep replication active in the background","Key ID":"Key ID","Keypair or pre-shared key":"Keypair or pre-shared key","Last tweak modified timestamp":"Last tweak modified timestamp","LiveSync could not handle multiple vaults which have same name without different prefix, This should be automatically configured.":"LiveSync could not handle multiple vaults which have same name without different prefix, This should be automatically configured.","Longest chunk line threshold value (Not Configurable from the UI Now).":"Longest chunk line threshold value (Not Configurable from the UI Now).","MB (0 to disable).":"MB (0 to disable).","MB per request":"MB per request","Maximum Incubating Chunk Size":"Maximum Incubating Chunk Size","Maximum Incubating Chunks":"Maximum Incubating Chunks","Maximum Incubation Period":"Maximum Incubation Period","Maximum delay for batch database updating":"Maximum delay for batch database updating","Maximum file modification time for reflected file events":"Maximum file modification time for reflected file events","Maximum file size":"Maximum file size","Maximum request size for manually resending chunks":"Maximum request size for manually resending chunks","Memory cache size (by total characters)":"Memory cache size (by total characters)","Memory cache size (by total items)":"Memory cache size (by total items)","Minimum Chunk Size (Not Configurable from the UI Now).":"Minimum Chunk Size (Not Configurable from the UI Now).","Minimum delay for batch database updating":"Minimum delay for batch database updating","Minimum interval for syncing":"Minimum interval for syncing","Move remotely deleted files to the trash, instead of deleting. (This setting is ineffective from Obsidian v1.7.2 onwards, as deletion always respects your Obsidian preferences.)":"Move remotely deleted files to the trash, instead of deleting. (This setting is ineffective from Obsidian v1.7.2 onwards, as deletion always respects your Obsidian preferences.)","Network warning style":"Network warning style",'Not all messages have been translated. And, please revert to "Default" when reporting errors.':'Not all messages have been translated. And, please revert to "Default" when reporting errors.',"Notify all setting files":"Notify all setting files","Notify customized":"Notify customized","Notify when other device has newly customized.":"Notify when other device has newly customized.","Notify when the estimated remote storage size exceeds on start up":"Notify when the estimated remote storage size exceeds on start up","Now we can choose how to split the chunks; V3 is the most efficient. If you have troubled, please make this Default or Legacy.":"Now we can choose how to split the chunks; V3 is the most efficient. If you have troubled, please make this Default or Legacy.","Number of batches to process at a time. Defaults to 40. Minimum is 2. This along with batch size controls how many docs are kept in memory at a time.":"Number of batches to process at a time. Defaults to 40. Minimum is 2. This along with batch size controls how many docs are kept in memory at a time.","Number of changes to sync at a time. Defaults to 50. Minimum is 2.":"Number of changes to sync at a time. Defaults to 50. Minimum is 2.","P2P.AskPassphraseForDecrypt":"The remote peer shared the configuration. Please input the passphrase to decrypt the configuration.","P2P.AskPassphraseForShare":"The remote peer requested this device configuration. Please input the passphrase to share the configuration. You can ignore the request by cancelling this dialogue.","P2P.DisabledButNeed":"%{title_p2p_sync} is disabled. Do you really want to enable it?","P2P.NoAutoSyncPeers":"No auto-sync peers found. Please set peers on the %{long_p2p_sync} pane.","P2P.NoKnownPeers":"No peers has been detected, waiting incoming other peers...","P2P.NotEnabled":"%{title_p2p_sync} is not enabled. We cannot open a new connection.","P2P.ReplicatorInstanceMissing":"P2P Sync replicator is not found, possibly not have been configured or enabled.","P2P.SeemsOffline":"Peer ${name} seems offline, skipped.","P2P.SyncAlreadyRunning":"P2P Sync is already running.","P2P.SyncCompleted":"P2P Sync completed.","P2P.SyncStartedWith":"P2P Sync with ${name} have been started.",Passphrase:"Passphrase","Passphrase of sensitive configuration items":"Passphrase of sensitive configuration items",Password:"Password","Per-file-saved customization sync":"Per-file-saved customization sync","Periodic Sync interval":"Periodic Sync interval","Please select 'Cancel' explicitly to cancel this operation.":"Please select 'Cancel' explicitly to cancel this operation.","Please use V2, V1 is deprecated and will be removed in the future, It was not a very appropriate algorithm. Only for compatibility V1 is kept.":"Please use V2, V1 is deprecated and will be removed in the future, It was not a very appropriate algorithm. Only for compatibility V1 is kept.",Presets:"Presets","Process files even if seems to be corrupted":"Process files even if seems to be corrupted","Process small files in the foreground":"Process small files in the foreground","Property Encryption":"Property Encryption","Reducing the frequency with which on-disk changes are reflected into the DB":"Reducing the frequency with which on-disk changes are reflected into the DB",Region:"Region","Remote server type":"Remote server type","Replicator.Message.Cleaned":"Database cleaning up is in process. replication has been cancelled","Replicator.Message.InitialiseFatalError":"No replicator is available, this is the fatal error.","Replicator.Message.Pending":"Some file events are pending. Replication has been cancelled.","Replicator.Message.SomeModuleFailed":"Replication has been cancelled by some module failure","Replicator.Message.VersionUpFlash":"An update has been detected. Please open the Settings dialogue and check the Change Log. Replication has been cancelled.","Requires restart of Obsidian.":"Requires restart of Obsidian.","Room ID":"Room ID","Rotation Duration":"Rotation Duration","Save settings to a markdown file. You will be notified when new settings arrive. You can set different files by the platform.":"Save settings to a markdown file. You will be notified when new settings arrive. You can set different files by the platform.","Saving will be performed forcefully after this number of seconds.":"Saving will be performed forcefully after this number of seconds.","Scan changes on customization sync":"Scan changes on customization sync","Scan customization automatically":"Scan customization automatically","Scan customization before replicating.":"Scan customization before replicating.","Scan customization every 1 minute.":"Scan customization every 1 minute.","Scan customization periodically":"Scan customization periodically","Scan for hidden files before replication":"Scan for hidden files before replication","Scan hidden files periodically":"Scan hidden files periodically","Seconds, 0 to disable":"Seconds, 0 to disable","Seconds. Saving to the local database will be delayed until this value after we stop typing or saving.":"Seconds. Saving to the local database will be delayed until this value after we stop typing or saving.","Secret Key":"Secret Key","Server URI":"Server URI","Setup.QRCode":'We have generated a QR code to transfer the settings. Please scan the QR code with your phone or other device.\nNote: The QR code is not encrypted, so be careful to open this.\n\n>[!FOR YOUR EYES ONLY]-\n> <div class="sls-qr">${qr_image}</div>',"Should we keep folders that don't have any files inside?":"Should we keep folders that don't have any files inside?","Should we only check for conflicts when a file is opened?":"Should we only check for conflicts when a file is opened?","Should we prompt you about conflicting files when a file is opened?":"Should we prompt you about conflicting files when a file is opened?","Should we prompt you for every single merge, even if we can safely merge automatcially?":"Should we prompt you for every single merge, even if we can safely merge automatcially?","Show only notifications":"Show only notifications","Show status as icons only":"Show status as icons only","Show status icon instead of file warnings banner":"Show status icon instead of file warnings banner","Show status inside the editor":"Show status inside the editor","Show status on the status bar":"Show status on the status bar","Show verbose log. Please enable if you report an issue.":"Show verbose log. Please enable if you report an issue.","Signalling Relays":"Signalling Relays","Starts synchronisation when a file is saved.":"Starts synchronisation when a file is saved.","Stop reflecting database changes to storage files.":"Stop reflecting database changes to storage files.","Stop watching for file changes.":"Stop watching for file changes.","Subject (whoami)":"Subject (whoami)","Suppress notification of hidden files change":"Suppress notification of hidden files change","Suspend database reflecting":"Suspend database reflecting","Suspend file watching":"Suspend file watching","Sync Mode":"Sync Mode","Sync after merging file":"Sync after merging file","Sync automatically after merging files":"Sync automatically after merging files","Sync on Editor Save":"Sync on Editor Save","Sync on File Open":"Sync on File Open","Sync on Save":"Sync on Save","Sync on Startup":"Sync on Startup","TURN Credential":"TURN Credential","TURN Servers":"TURN Servers","TURN Username":"TURN Username","Testing only - Resolve file conflicts by syncing newer copies of the file, this can overwrite modified files. Be Warned.":"Testing only - Resolve file conflicts by syncing newer copies of the file, this can overwrite modified files. Be Warned.","The Application ID for P2P connection. This should be same among your devices. Default is 'self-hosted-livesync' and could not be modified from the UI.":"The Application ID for P2P connection. This should be same among your devices. Default is 'self-hosted-livesync' and could not be modified from the UI.","The Hash algorithm for chunk IDs":"The Hash algorithm for chunk IDs","The Nostr relay servers to establish connections for P2P connections. Multiple servers can be separated by commas.":"The Nostr relay servers to establish connections for P2P connections. Multiple servers can be separated by commas.","The Passphrase for P2P connection. This should be same among your devices.":"The Passphrase for P2P connection. This should be same among your devices.","The Room ID for P2P connection. This should be same among your devices.":"The Room ID for P2P connection. This should be same among your devices.","The Rotation duration of token in minutes. Each generated tokens will be valid only within this duration.":"The Rotation duration of token in minutes. Each generated tokens will be valid only within this duration.","The TURN servers to use for P2P connections. Multiple servers can be separated by commas.":"The TURN servers to use for P2P connections. Multiple servers can be separated by commas.","The algorithm used for JWT authentication.":"The algorithm used for JWT authentication.","The credential/password for the TURN servers.":"The credential/password for the TURN servers.","The delay for consecutive on-demand fetches":"The delay for consecutive on-demand fetches","The key (PSK in HSxxx in base64, or private key in ESxxx in PEM) used for JWT authentication.":"The key (PSK in HSxxx in base64, or private key in ESxxx in PEM) used for JWT authentication.","The key ID. this should be matched with CouchDB->jwt_keys->ALG:_`kid`.":"The key ID. this should be matched with CouchDB->jwt_keys->ALG:_`kid`.","The maximum duration for which chunks can be incubated within the document. Chunks exceeding this period will graduate to independent chunks.":"The maximum duration for which chunks can be incubated within the document. Chunks exceeding this period will graduate to independent chunks.","The maximum number of chunks that can be incubated within the document. Chunks exceeding this number will immediately graduate to independent chunks.":"The maximum number of chunks that can be incubated within the document. Chunks exceeding this number will immediately graduate to independent chunks.","The maximum total size of chunks that can be incubated within the document. Chunks exceeding this size will immediately graduate to independent chunks.":"The maximum total size of chunks that can be incubated within the document. Chunks exceeding this size will immediately graduate to independent chunks.","The minimum interval for automatic synchronisation on event.":"The minimum interval for automatic synchronisation on event.","The subject for JWT authentication. Mostly username.":"The subject for JWT authentication. Mostly username.","The username for the TURN servers.":"The username for the TURN servers.","This passphrase will not be copied to another device. It will be set to `Default` until you configure it again.":"This passphrase will not be copied to another device. It will be set to `Default` until you configure it again.","Unique name between all synchronized devices. To edit this setting, please disable customization sync once.":"Unique name between all synchronized devices. To edit this setting, please disable customization sync once.","Use Custom HTTP Handler":"Use Custom HTTP Handler","Use JWT instead of Basic Authentication":"Use JWT instead of Basic Authentication","Use Only Local Chunks":"Use Only Local Chunks","Use Request API to avoid `inevitable` CORS problem":"Use Request API to avoid `inevitable` CORS problem","Use Segmented-splitter":"Use Segmented-splitter","Use dynamic iteration count":"Use dynamic iteration count","Use splitting-limit-capped chunk splitter":"Use splitting-limit-capped chunk splitter","Use the trash bin":"Use the trash bin","Use timeouts instead of heartbeats":"Use timeouts instead of heartbeats",Username:"Username","Verbose Log":"Verbose Log","Warning! This will have a serious impact on performance. And the logs will not be synchronised under the default name. Please be careful with logs; they often contain your confidential information.":"Warning! This will have a serious impact on performance. And the logs will not be synchronised under the default name. Please be careful with logs; they often contain your confidential information.","When you save a file in the editor, start a sync automatically":"When you save a file in the editor, start a sync automatically","While enabled, it causes very performance impact but debugging replication testing and other features will be enabled. Please disable this if you have not read the source code. Requires restart of Obsidian. Sometimes there is no implementation.":"While enabled, it causes very performance impact but debugging replication testing and other features will be enabled. Please disable this if you have not read the source code. Requires restart of Obsidian. Sometimes there is no implementation.","Write credentials in the file":"Write credentials in the file","Write logs into the file":"Write logs into the file","You can enable this setting to process the files with size mismatches, these files can be created by some APIs or integrations.":"You can enable this setting to process the files with size mismatches, these files can be created by some APIs or integrations.","liveSyncReplicator.beforeLiveSync":"Before LiveSync, start OneShot once...","liveSyncReplicator.cantReplicateLowerValue":"We can't replicate more lower value.","liveSyncReplicator.checkingLastSyncPoint":"Looking for the point last synchronized point.","liveSyncReplicator.couldNotConnectTo":"Could not connect to ${uri} : ${name}\n(${db})","liveSyncReplicator.couldNotConnectToRemoteDb":"Could not connect to remote database: ${d}","liveSyncReplicator.couldNotConnectToServer":"The connection to the remote has been prevented, or failed.","liveSyncReplicator.couldNotConnectToURI":"Could not connect to ${uri}:${dbRet}","liveSyncReplicator.couldNotMarkResolveRemoteDb":"Could not mark resolve remote database.","liveSyncReplicator.liveSyncBegin":"LiveSync begin...","liveSyncReplicator.lockRemoteDb":"Lock remote database to prevent data corruption","liveSyncReplicator.markDeviceResolved":"Mark this device as 'resolved'.","liveSyncReplicator.mismatchedTweakDetected":"Some mismatches have been detected in the configuration between devices. Running a manual replication will attempt to resolve this issue.","liveSyncReplicator.oneShotSyncBegin":"OneShot Sync begin... (${syncMode})","liveSyncReplicator.remoteDbCorrupted":"Remote database is newer or corrupted, make sure to latest version of self-hosted-livesync installed","liveSyncReplicator.remoteDbCreatedOrConnected":"Remote Database Created or Connected","liveSyncReplicator.remoteDbDestroyError":"Something happened on Remote Database Destroy:","liveSyncReplicator.remoteDbDestroyed":"Remote Database Destroyed","liveSyncReplicator.remoteDbMarkedResolved":"Remote database has been marked resolved.","liveSyncReplicator.replicationClosed":"Replication closed","liveSyncReplicator.replicationInProgress":"Replication is already in progress","liveSyncReplicator.retryLowerBatchSize":"Retry with lower batch size:${batch_size}/${batches_limit}","liveSyncReplicator.unlockRemoteDb":"Unlock remote database to prevent data corruption","moduleCheckRemoteSize.logCheckingStorageSizes":"Checking storage sizes","moduleCheckRemoteSize.logCurrentStorageSize":"Remote storage size: ${measuredSize}","moduleCheckRemoteSize.logExceededWarning":"Remote storage size: ${measuredSize} exceeded ${notifySize}","moduleCheckRemoteSize.logThresholdEnlarged":"Threshold has been enlarged to ${size}MB","moduleCheckRemoteSize.msgConfirmRebuild":"This may take a bit of a long time. Do you really want to rebuild everything now?","moduleCheckRemoteSize.msgDatabaseGrowing":"**Your database is getting larger!** But do not worry, we can address it now. The time before running out of space on the remote storage.\n\n| Measured size | Configured size |\n| --- | --- |\n| ${estimatedSize} | ${maxSize} |\n\n> [!MORE]-\n> If you have been using it for many years, there may be unreferenced chunks - that is, garbage - accumulating in the database. Therefore, we recommend rebuilding everything. It will probably become much smaller.\n>\n> If the volume of your vault is simply increasing, it is better to rebuild everything after organizing the files. Self-hosted LiveSync does not delete the actual data even if you delete it to speed up the process. It is roughly [documented](https://github.com/vrtmrz/obsidian-livesync/blob/main/docs/tech_info.md).\n>\n> If you don't mind the increase, you can increase the notification limit by 100MB. This is the case if you are running it on your own server. However, it is better to rebuild everything from time to time.\n>\n\n> [!WARNING]\n> If you perform rebuild everything, make sure all devices are synchronised. The plug-in will merge as much as possible, though.\n","moduleCheckRemoteSize.msgSetDBCapacity":"We can set a maximum database capacity warning, **to take action before running out of space on the remote storage**.\nDo you want to enable this?\n\n> [!MORE]-\n> - 0: Do not warn about storage size.\n> This is recommended if you have enough space on the remote storage especially you have self-hosted. And you can check the storage size and rebuild manually.\n> - 800: Warn if the remote storage size exceeds 800MB.\n> This is recommended if you are using fly.io with 1GB limit or IBM Cloudant.\n> - 2000: Warn if the remote storage size exceeds 2GB.\n\nIf we have reached the limit, we will be asked to enlarge the limit step by step.\n","moduleCheckRemoteSize.noticeExceeded":"Remote storage size is ${measuredSize}, above the configured ${notifySize} notification threshold. {HERE}","moduleCheckRemoteSize.noticeNotConfigured":"Remote storage size notifications are not configured. {HERE}","moduleCheckRemoteSize.option2GB":"2GB (Standard)","moduleCheckRemoteSize.option800MB":"800MB (Cloudant, fly.io)","moduleCheckRemoteSize.optionAskMeLater":"Ask me later","moduleCheckRemoteSize.optionDismiss":"Dismiss","moduleCheckRemoteSize.optionIncreaseLimit":"increase to ${newMax}MB","moduleCheckRemoteSize.optionNoWarn":"No, never warn please","moduleCheckRemoteSize.optionRebuildAll":"Rebuild Everything Now","moduleCheckRemoteSize.optionReview":"Review options","moduleCheckRemoteSize.titleDatabaseSizeLimitExceeded":"Remote storage size exceeded the limit","moduleCheckRemoteSize.titleDatabaseSizeNotify":"Setting up database size notification","moduleLiveSyncMain.logUnloadingPlugin":"Unloading plugin...","moduleLocalDatabase.logWaitingForReady":"Waiting for ready...",password:"password",username:"username","xxhash64 is the current default.":"xxhash64 is the current default."};englishMessageTranslator=(key3,params={})=>{let message=resolveEnglishMessage(key3);for(const[placeholder,value]of Object.entries(params))message=message.replaceAll(`\${${placeholder}}`,value);return message};0;ServiceContext=class{constructor(options={}){__publicField(this,"events");__publicField(this,"translate");var _a13,_b6;this.events=null!=(_a13=options.events)?_a13:createLiveSyncEventHub();this.translate=null!=(_b6=options.translate)?_b6:englishMessageTranslator}};ServiceBase=class{constructor(context2){__publicField(this,"context");this.context=context2}};EVENT_LAYOUT_READY="layout-ready";0;EVENT_PLUGIN_UNLOADED="plugin-unloaded";EVENT_SETTING_SAVED="setting-saved";EVENT_FILE_RENAMED="file-renamed";EVENT_FILE_SAVED="file-saved";0;EVENT_DATABASE_REBUILT="database-rebuilt";0;EVENT_REQUEST_OPEN_SETUP_URI="request-open-setup-uri";EVENT_REQUEST_COPY_SETUP_URI="request-copy-setup-uri";EVENT_REQUEST_SHOW_SETUP_QR="request-show-setup-qr";EVENT_REQUEST_RELOAD_SETTING_TAB="reload-setting-tab";0;0;EVENT_REQUEST_OPEN_P2P_SETTINGS="request-open-p2p-settings";EVENT_REQUEST_OPEN_P2P="request-open-p2p";0;EVENT_PLATFORM_UNLOADED="platform-unloaded";EVENT_ON_UNRESOLVED_ERROR="on-unresolved-error";EVENT_REQUEST_CHECK_REMOTE_SIZE="request-check-remote-size";EVENT_CONFLICT_CANCELLED="conflict-cancelled";EVENT_PLUGIN_LOADED2="plugin-loaded";EVENT_PLUGIN_UNLOADED2="plugin-unloaded";EVENT_FILE_SAVED2="file-saved";EVENT_LEAF_ACTIVE_CHANGED2="leaf-active-changed";EVENT_REQUEST_OPEN_SETTINGS="request-open-settings";EVENT_REQUEST_OPEN_SETUP_URI2="request-open-setup-uri";EVENT_REQUEST_COPY_SETUP_URI2="request-copy-setup-uri";EVENT_REQUEST_SHOW_SETUP_QR2="request-show-setup-qr";EVENT_REQUEST_RELOAD_SETTING_TAB2="reload-setting-tab";EVENT_REQUEST_OPEN_PLUGIN_SYNC_DIALOG2="request-open-plugin-sync-dialog";EVENT_REQUEST_RUN_DOCTOR="request-run-doctor";EVENT_REQUEST_RUN_FIX_INCOMPLETE="request-run-fix-incomplete";EVENT_ANALYSE_DB_USAGE="analyse-db-usage";EVENT_REQUEST_PERFORM_GC_V3="request-perform-gc-v3";eventHub=createLiveSyncEventHub();MARK_LOG_SEPARATOR="";MARK_LOG_NETWORK_ERROR="";AbstractModule=class{constructor(core){this.core=core;this._log=createInstanceLogFunction(this.constructor.name,this.services.API);this.addCommand=this.services.API.addCommand.bind(this.services.API);this.registerView=this.services.API.registerWindow.bind(this.services.API);this.addRibbonIcon=this.services.API.addRibbonIcon.bind(this.services.API);this.registerObsidianProtocolHandler=this.services.API.registerProtocolHandler.bind(this.services.API);Logger(`[${this.constructor.name}] Loaded`,LOG_LEVEL_VERBOSE)}get services(){if(!this.core._services)throw new Error("Services are not ready yet.");return this.core._services}get localDatabase(){return this.core.localDatabase}get settings(){return this.core.settings}set settings(value){this.core.settings=value}getPath(entry){return this.services.path.getPath(entry)}getPathWithoutPrefix(entry){return stripAllPrefixes(this.services.path.getPath(entry))}onBindFunction(core,services){}saveSettings(){return this.core.services.setting.saveSettingData()}addTestResult(key3,value,summary,message){this.services.test.addTestResult(`${this.constructor.name}`,key3,value,summary,message)}testDone(result=!0){return Promise.resolve(result)}testFail(message){this._log(message,LOG_LEVEL_NOTICE);return this.testDone(!1)}isMainReady(){return this.services.appLifecycle.isReady()}isMainSuspended(){return this.services.appLifecycle.isSuspended()}isDatabaseReady(){return this.services.database.isDatabaseReady()}};AbstractObsidianModule=class extends AbstractModule{constructor(plugin2,core){super(core);this.plugin=plugin2}get services(){return this.core.services}get app(){return this.plugin.app}isThisModuleEnabled(){return!0}};0;PUBLIC_VERSION="5";"undefined"!=typeof window&&(null!=(_c=(_b2=null!=(_a5=window.__svelte)?_a5:window.__svelte={}).v)?_c:_b2.v=new Set).add(PUBLIC_VERSION);EACH_ITEM_REACTIVE=1;EACH_INDEX_REACTIVE=2;EACH_IS_CONTROLLED=4;EACH_IS_ANIMATED=8;EACH_ITEM_IMMUTABLE=16;PROPS_IS_IMMUTABLE=1;PROPS_IS_RUNES=2;PROPS_IS_UPDATED=4;PROPS_IS_BINDABLE=8;PROPS_IS_LAZY_INITIAL=16;0;0;0;TEMPLATE_FRAGMENT=1;TEMPLATE_USE_IMPORT_NODE=2;0;0;HYDRATION_START="[";HYDRATION_START_ELSE="[!";HYDRATION_START_FAILED="[?";HYDRATION_END="]";HYDRATION_ERROR={};0;0;0;UNINITIALIZED=Symbol("uninitialized");FILENAME=Symbol("filename");0;NAMESPACE_HTML="http://www.w3.org/1999/xhtml";0;0;0;0;0;true_default=!0;node_env=null==(_b3=null==(_a6=globalThis.process)?void 0:_a6.env)?void 0:_b3.NODE_ENV;dev_fallback_default=node_env&&!node_env.toLowerCase().startsWith("prod");is_array=Array.isArray;index_of=Array.prototype.indexOf;includes=Array.prototype.includes;array_from=Array.from;object_keys=Object.keys;define_property=Object.defineProperty;get_descriptor=Object.getOwnPropertyDescriptor;get_descriptors=Object.getOwnPropertyDescriptors;object_prototype=Object.prototype;array_prototype=Array.prototype;get_prototype_of=Object.getPrototypeOf;is_extensible=Object.isExtensible;Object.prototype.hasOwnProperty;noop2=()=>{};DERIVED=2;EFFECT=4;RENDER_EFFECT=8;MANAGED_EFFECT=1<<24;BLOCK_EFFECT=16;BRANCH_EFFECT=32;ROOT_EFFECT=64;BOUNDARY_EFFECT=128;CONNECTED=512;CLEAN=1024;DIRTY=2048;MAYBE_DIRTY=4096;INERT=8192;DESTROYED=16384;REACTION_RAN=32768;DESTROYING=1<<25;EFFECT_TRANSPARENT=65536;EAGER_EFFECT=1<<17;HEAD_EFFECT=1<<18;EFFECT_PRESERVED=1<<19;USER_EFFECT=1<<20;EFFECT_OFFSCREEN=1<<25;WAS_MARKED=65536;REACTION_IS_UPDATING=1<<21;ASYNC=1<<22;ERROR_VALUE=1<<23;STATE_SYMBOL=Symbol("$state");LEGACY_PROPS=Symbol("legacy props");LOADING_ATTR_SYMBOL=Symbol("");PROXY_PATH_SYMBOL=Symbol("proxy path");ATTRIBUTES_CACHE=Symbol("attributes");CLASS_CACHE=Symbol("class");STYLE_CACHE=Symbol("style");TEXT_CACHE=Symbol("text");FORM_RESET_HANDLER=Symbol("form reset");HMR_ANCHOR=Symbol("hmr anchor");STALE_REACTION=new class StaleReactionError extends Error{constructor(){super(...arguments);__publicField(this,"name","StaleReactionError");__publicField(this,"message","The reaction that called `getAbortSignal()` was re-run or destroyed")}};IS_XHTML=!!(null==(_a7=globalThis.document)?void 0:_a7.contentType)&&globalThis.document.contentType.includes("xml");0;TEXT_NODE=3;COMMENT_NODE=8;0;bold="font-weight: bold";normal="font-weight: normal";hydrating=!1;async_mode_flag=!1;legacy_mode_flag=!1;tracing_mode_flag=!1;0;0;0;tracing_expressions=null;component_context=null;dev_stack=null;dev_current_component_function=null;micro_tasks=[];adjustments=new WeakMap;STATUS_MASK=~(DIRTY|MAYBE_DIRTY|CLEAN);subscriber_queue=[];legacy_is_updating_store=!1;is_store_binding=!1;IS_UNMOUNTED=Symbol("unmounted");flags=EFFECT_TRANSPARENT|EFFECT_PRESERVED;Boundary=class{constructor(node,props,children,transform_error){__privateAdd(this,_Boundary_instances);__publicField(this,"parent");__publicField(this,"is_pending",!1);__publicField(this,"transform_error");__privateAdd(this,_anchor);__privateAdd(this,_hydrate_open,hydrating?hydrate_node:null);__privateAdd(this,_props);__privateAdd(this,_children);__privateAdd(this,_effect);__privateAdd(this,_main_effect,null);__privateAdd(this,_pending_effect,null);__privateAdd(this,_failed_effect,null);__privateAdd(this,_offscreen_fragment,null);__privateAdd(this,_local_pending_count,0);__privateAdd(this,_pending_count,0);__privateAdd(this,_pending_count_update_queued,!1);__privateAdd(this,_dirty_effects,new Set);__privateAdd(this,_maybe_dirty_effects,new Set);__privateAdd(this,_effect_pending,null);__privateAdd(this,_effect_pending_subscriber,createSubscriber(()=>{__privateSet(this,_effect_pending,source(__privateGet(this,_local_pending_count)));dev_fallback_default&&tag(__privateGet(this,_effect_pending),"$effect.pending()");return()=>{__privateSet(this,_effect_pending,null)}}));var _a13,_b6;__privateSet(this,_anchor,node);__privateSet(this,_props,props);__privateSet(this,_children,anchor=>{var effect2=active_effect;effect2.b=this;effect2.f|=BOUNDARY_EFFECT;children(anchor)});this.parent=active_effect.b;this.transform_error=null!=(_b6=null!=transform_error?transform_error:null==(_a13=this.parent)?void 0:_a13.transform_error)?_b6:e3=>e3;__privateSet(this,_effect,block(()=>{if(hydrating){const comment2=__privateGet(this,_hydrate_open);hydrate_next();const server_rendered_pending=comment2.data===HYDRATION_START_ELSE,server_rendered_failed=comment2.data.startsWith(HYDRATION_START_FAILED);if(server_rendered_failed){const serialized_error=JSON.parse(comment2.data.slice(HYDRATION_START_FAILED.length));__privateMethod(this,_Boundary_instances,hydrate_failed_content_fn).call(this,serialized_error)}else server_rendered_pending?__privateMethod(this,_Boundary_instances,hydrate_pending_content_fn).call(this):__privateMethod(this,_Boundary_instances,hydrate_resolved_content_fn).call(this)}else __privateMethod(this,_Boundary_instances,render_fn).call(this)},flags));hydrating&&__privateSet(this,_anchor,hydrate_node)}defer_effect(effect2){defer_effect(effect2,__privateGet(this,_dirty_effects),__privateGet(this,_maybe_dirty_effects))}is_rendered(){return!this.is_pending&&(!this.parent||this.parent.is_rendered())}has_pending_snippet(){return!!__privateGet(this,_props).pending}update_pending_count(d4,batch){__privateMethod(this,_Boundary_instances,update_pending_count_fn).call(this,d4,batch);__privateSet(this,_local_pending_count,__privateGet(this,_local_pending_count)+d4);if(__privateGet(this,_effect_pending)&&!__privateGet(this,_pending_count_update_queued)){__privateSet(this,_pending_count_update_queued,!0);queue_micro_task(()=>{__privateSet(this,_pending_count_update_queued,!1);__privateGet(this,_effect_pending)&&internal_set(__privateGet(this,_effect_pending),__privateGet(this,_local_pending_count))})}}get_effect_pending(){__privateGet(this,_effect_pending_subscriber).call(this);return get2(__privateGet(this,_effect_pending))}error(error){var _a13;if(!__privateGet(this,_props).onerror&&!__privateGet(this,_props).failed)throw error;if(null==(_a13=current_batch)?void 0:_a13.is_fork){__privateGet(this,_main_effect)&&current_batch.skip_effect(__privateGet(this,_main_effect));__privateGet(this,_pending_effect)&&current_batch.skip_effect(__privateGet(this,_pending_effect));__privateGet(this,_failed_effect)&&current_batch.skip_effect(__privateGet(this,_failed_effect));current_batch.oncommit(()=>{__privateMethod(this,_Boundary_instances,handle_error_fn).call(this,error)})}else __privateMethod(this,_Boundary_instances,handle_error_fn).call(this,error)}};_anchor=new WeakMap;_hydrate_open=new WeakMap;_props=new WeakMap;_children=new WeakMap;_effect=new WeakMap;_main_effect=new WeakMap;_pending_effect=new WeakMap;_failed_effect=new WeakMap;_offscreen_fragment=new WeakMap;_local_pending_count=new WeakMap;_pending_count=new WeakMap;_pending_count_update_queued=new WeakMap;_dirty_effects=new WeakMap;_maybe_dirty_effects=new WeakMap;_effect_pending=new WeakMap;_effect_pending_subscriber=new WeakMap;_Boundary_instances=new WeakSet;hydrate_resolved_content_fn=function(){try{__privateSet(this,_main_effect,branch(()=>__privateGet(this,_children).call(this,__privateGet(this,_anchor))))}catch(error){this.error(error)}};hydrate_failed_content_fn=function(error){const failed2=__privateGet(this,_props).failed;failed2&&__privateSet(this,_failed_effect,branch(()=>{failed2(__privateGet(this,_anchor),()=>error,()=>()=>{})}))};hydrate_pending_content_fn=function(){const pending3=__privateGet(this,_props).pending;if(pending3){this.is_pending=!0;__privateSet(this,_pending_effect,branch(()=>pending3(__privateGet(this,_anchor))));queue_micro_task(()=>{var fragment=__privateSet(this,_offscreen_fragment,document.createDocumentFragment()),anchor=create_text();fragment.append(anchor);__privateSet(this,_main_effect,__privateMethod(this,_Boundary_instances,run_fn).call(this,()=>branch(()=>__privateGet(this,_children).call(this,anchor))));if(0===__privateGet(this,_pending_count)){__privateGet(this,_anchor).before(fragment);__privateSet(this,_offscreen_fragment,null);pause_effect(__privateGet(this,_pending_effect),()=>{__privateSet(this,_pending_effect,null)});__privateMethod(this,_Boundary_instances,resolve_fn).call(this,current_batch)}})}};render_fn=function(){try{this.is_pending=this.has_pending_snippet();__privateSet(this,_pending_count,0);__privateSet(this,_local_pending_count,0);__privateSet(this,_main_effect,branch(()=>{__privateGet(this,_children).call(this,__privateGet(this,_anchor))}));if(__privateGet(this,_pending_count)>0){var fragment=__privateSet(this,_offscreen_fragment,document.createDocumentFragment());move_effect(__privateGet(this,_main_effect),fragment);const pending3=__privateGet(this,_props).pending;__privateSet(this,_pending_effect,branch(()=>pending3(__privateGet(this,_anchor))))}else __privateMethod(this,_Boundary_instances,resolve_fn).call(this,current_batch)}catch(error){this.error(error)}};resolve_fn=function(batch){this.is_pending=!1;batch.transfer_effects(__privateGet(this,_dirty_effects),__privateGet(this,_maybe_dirty_effects))};run_fn=function(fn){var previous_effect=active_effect,previous_reaction=active_reaction,previous_ctx=component_context;set_active_effect(__privateGet(this,_effect));set_active_reaction(__privateGet(this,_effect));set_component_context(__privateGet(this,_effect).ctx);try{Batch.ensure();return fn()}catch(e3){handle_error(e3);return null}finally{set_active_effect(previous_effect);set_active_reaction(previous_reaction);set_component_context(previous_ctx)}};update_pending_count_fn=function(d4,batch){var _a13;if(this.has_pending_snippet()){__privateSet(this,_pending_count,__privateGet(this,_pending_count)+d4);if(0===__privateGet(this,_pending_count)){__privateMethod(this,_Boundary_instances,resolve_fn).call(this,batch);__privateGet(this,_pending_effect)&&pause_effect(__privateGet(this,_pending_effect),()=>{__privateSet(this,_pending_effect,null)});if(__privateGet(this,_offscreen_fragment)){__privateGet(this,_anchor).before(__privateGet(this,_offscreen_fragment));__privateSet(this,_offscreen_fragment,null)}}}else this.parent&&__privateMethod(_a13=this.parent,_Boundary_instances,update_pending_count_fn).call(_a13,d4,batch)};handle_error_fn=function(error){var onerror,did_reset,calling_on_error;if(__privateGet(this,_main_effect)){destroy_effect(__privateGet(this,_main_effect));__privateSet(this,_main_effect,null)}if(__privateGet(this,_pending_effect)){destroy_effect(__privateGet(this,_pending_effect));__privateSet(this,_pending_effect,null)}if(__privateGet(this,_failed_effect)){destroy_effect(__privateGet(this,_failed_effect));__privateSet(this,_failed_effect,null)}if(hydrating){set_hydrate_node(__privateGet(this,_hydrate_open));next();set_hydrate_node(skip_nodes())}onerror=__privateGet(this,_props).onerror;let failed2=__privateGet(this,_props).failed;did_reset=!1;calling_on_error=!1;const reset2=()=>{if(did_reset)svelte_boundary_reset_noop();else{did_reset=!0;calling_on_error&&svelte_boundary_reset_onerror();null!==__privateGet(this,_failed_effect)&&pause_effect(__privateGet(this,_failed_effect),()=>{__privateSet(this,_failed_effect,null)});__privateMethod(this,_Boundary_instances,run_fn).call(this,()=>{__privateMethod(this,_Boundary_instances,render_fn).call(this)})}},handle_error_result=transformed_error=>{try{calling_on_error=!0;null==onerror||onerror(transformed_error,reset2);calling_on_error=!1}catch(error2){invoke_error_boundary(error2,__privateGet(this,_effect)&&__privateGet(this,_effect).parent)}failed2&&__privateSet(this,_failed_effect,__privateMethod(this,_Boundary_instances,run_fn).call(this,()=>{try{return branch(()=>{var effect2=active_effect;effect2.b=this;effect2.f|=BOUNDARY_EFFECT;failed2(__privateGet(this,_anchor),()=>transformed_error,()=>reset2)})}catch(error2){invoke_error_boundary(error2,__privateGet(this,_effect).parent);return null}}))};queue_micro_task(()=>{var result;try{result=this.transform_error(error)}catch(e3){invoke_error_boundary(e3,__privateGet(this,_effect)&&__privateGet(this,_effect).parent);return}null!==result&&"object"==typeof result&&"function"==typeof result.then?result.then(handle_error_result,e3=>invoke_error_boundary(e3,__privateGet(this,_effect)&&__privateGet(this,_effect).parent)):handle_error_result(result)})};reactivity_loss_tracker=null;recent_async_deriveds=new Set;OBSOLETE=Symbol("obsolete");stack=[];first_batch=null;last_batch=null;current_batch=null;previous_batch=null;batch_values=null;last_scheduled_effect=null;is_flushing_sync=!1;is_processing=!1;collected_effects=null;legacy_updates=null;flush_count=0;source_stacks=new Set;uid=1;_Batch=class _Batch{constructor(){__privateAdd(this,_Batch_instances);__publicField(this,"id",uid++);__privateAdd(this,_started,!1);__publicField(this,"linked",!0);__privateAdd(this,_prev,null);__privateAdd(this,_next,null);__publicField(this,"async_deriveds",new Map);__publicField(this,"current",new Map);__publicField(this,"previous",new Map);__privateAdd(this,_commit_callbacks,new Set);__privateAdd(this,_discard_callbacks,new Set);__privateAdd(this,_pending,0);__privateAdd(this,_blocking_pending,new Map);__privateAdd(this,_deferred,null);__privateAdd(this,_roots,[]);__privateAdd(this,_new_effects,[]);__privateAdd(this,_dirty_effects2,new Set);__privateAdd(this,_maybe_dirty_effects2,new Set);__privateAdd(this,_skipped_branches,new Map);__privateAdd(this,_unskipped_branches,new Set);__publicField(this,"is_fork",!1);__privateAdd(this,_decrement_queued,!1);if(null===last_batch)first_batch=last_batch=this;else{__privateSet(last_batch,_next,this);__privateSet(this,_prev,last_batch)}last_batch=this}skip_effect(effect2){__privateGet(this,_skipped_branches).has(effect2)||__privateGet(this,_skipped_branches).set(effect2,{d:[],m:[]});__privateGet(this,_unskipped_branches).delete(effect2)}unskip_effect(effect2,callback=e3=>this.schedule(e3)){var e3,tracked=__privateGet(this,_skipped_branches).get(effect2);if(tracked){__privateGet(this,_skipped_branches).delete(effect2);for(e3 of tracked.d){set_signal_status(e3,DIRTY);callback(e3)}for(e3 of tracked.m){set_signal_status(e3,MAYBE_DIRTY);callback(e3)}}__privateGet(this,_unskipped_branches).add(effect2)}capture(source2,value,is_derived=!1){source2.v===UNINITIALIZED||this.previous.has(source2)||this.previous.set(source2,source2.v);if(0===(source2.f&ERROR_VALUE)){this.current.set(source2,[value,is_derived]);null==batch_values||batch_values.set(source2,value)}this.is_fork||(source2.v=value)}activate(){current_batch=this}deactivate(){current_batch=null;batch_values=null}flush(){try{dev_fallback_default&&source_stacks.clear();is_processing=!0;current_batch=this;__privateMethod(this,_Batch_instances,process_fn).call(this)}finally{flush_count=0;last_scheduled_effect=null;collected_effects=null;legacy_updates=null;is_processing=!1;current_batch=null;batch_values=null;old_values.clear();if(dev_fallback_default)for(const source2 of source_stacks)source2.updated=null}}discard(){var _a13;for(const fn of __privateGet(this,_discard_callbacks))fn(this);__privateGet(this,_discard_callbacks).clear();for(const deferred2 of this.async_deriveds.values())deferred2.reject(OBSOLETE);__privateMethod(this,_Batch_instances,unlink_fn).call(this);null==(_a13=__privateGet(this,_deferred))||_a13.resolve()}register_created_effect(effect2){__privateGet(this,_new_effects).push(effect2)}increment(blocking,effect2){var _a13;__privateSet(this,_pending,__privateGet(this,_pending)+1);if(blocking){let blocking_pending_count=null!=(_a13=__privateGet(this,_blocking_pending).get(effect2))?_a13:0;__privateGet(this,_blocking_pending).set(effect2,blocking_pending_count+1)}}decrement(blocking,effect2){var _a13;__privateSet(this,_pending,__privateGet(this,_pending)-1);if(blocking){let blocking_pending_count=null!=(_a13=__privateGet(this,_blocking_pending).get(effect2))?_a13:0;1===blocking_pending_count?__privateGet(this,_blocking_pending).delete(effect2):__privateGet(this,_blocking_pending).set(effect2,blocking_pending_count-1)}if(!__privateGet(this,_decrement_queued)){__privateSet(this,_decrement_queued,!0);queue_micro_task(()=>{__privateSet(this,_decrement_queued,!1);this.linked&&this.flush()})}}transfer_effects(dirty_effects,maybe_dirty_effects){for(const e3 of dirty_effects)__privateGet(this,_dirty_effects2).add(e3);for(const e3 of maybe_dirty_effects)__privateGet(this,_maybe_dirty_effects2).add(e3);dirty_effects.clear();maybe_dirty_effects.clear()}oncommit(fn){__privateGet(this,_commit_callbacks).add(fn)}ondiscard(fn){__privateGet(this,_discard_callbacks).add(fn)}settled(){var _a13;return(null!=(_a13=__privateGet(this,_deferred))?_a13:__privateSet(this,_deferred,deferred())).promise}static ensure(){if(null===current_batch){const batch=current_batch=new _Batch;is_processing||is_flushing_sync||queue_micro_task(()=>{__privateGet(batch,_started)||batch.flush()})}return current_batch}apply(){if(async_mode_flag&&(this.is_fork||null!==__privateGet(this,_prev)||null!==__privateGet(this,_next))){batch_values=new Map;for(const[source2,[value]]of this.current)batch_values.set(source2,value);for(let batch=first_batch;null!==batch;batch=__privateGet(batch,_next))if(batch!==this&&!batch.is_fork){var intersects=!1;if(batch.id<this.id)for(const[source2,[,is_derived]]of batch.current)if(!is_derived&&this.current.has(source2)){intersects=!0;break}if(!intersects)for(const[source2,previous]of batch.previous)batch_values.has(source2)||batch_values.set(source2,previous)}}else batch_values=null}schedule(effect2){var _a13,e3,flags2;last_scheduled_effect=effect2;if((null==(_a13=effect2.b)?void 0:_a13.is_pending)&&0!==(effect2.f&(EFFECT|RENDER_EFFECT|MANAGED_EFFECT))&&0===(effect2.f&REACTION_RAN))effect2.b.defer_effect(effect2);else{e3=effect2;for(;null!==e3.parent;){e3=e3.parent;flags2=e3.f;if(null!==collected_effects&&e3===active_effect){if(async_mode_flag)return;if((null===active_reaction||0===(active_reaction.f&DERIVED))&&!legacy_is_updating_store)return}if(0!==(flags2&(ROOT_EFFECT|BRANCH_EFFECT))){if(0===(flags2&CLEAN))return;e3.f^=CLEAN}}__privateGet(this,_roots).push(e3)}}};_started=new WeakMap;_prev=new WeakMap;_next=new WeakMap;_commit_callbacks=new WeakMap;_discard_callbacks=new WeakMap;_pending=new WeakMap;_blocking_pending=new WeakMap;_deferred=new WeakMap;_roots=new WeakMap;_new_effects=new WeakMap;_dirty_effects2=new WeakMap;_maybe_dirty_effects2=new WeakMap;_skipped_branches=new WeakMap;_unskipped_branches=new WeakMap;_decrement_queued=new WeakMap;_Batch_instances=new WeakSet;is_deferred_fn=function(){var e3,skipped;if(this.is_fork)return!0;for(const effect2 of __privateGet(this,_blocking_pending).keys()){e3=effect2;skipped=!1;for(;null!==e3.parent;){if(__privateGet(this,_skipped_branches).has(e3)){skipped=!0;break}e3=e3.parent}if(!skipped)return!0}return!1};process_fn=function(){var _a13,_b6,_c3,_d2,effects,render_effects,updates,batch,next_batch;__privateSet(this,_started,!0);if(flush_count++>1e3){__privateMethod(this,_Batch_instances,unlink_fn).call(this);infinite_loop_guard()}if(dev_fallback_default)for(const value of this.current.keys())source_stacks.add(value);for(const e3 of __privateGet(this,_dirty_effects2)){__privateGet(this,_maybe_dirty_effects2).delete(e3);set_signal_status(e3,DIRTY);this.schedule(e3)}for(const e3 of __privateGet(this,_maybe_dirty_effects2)){set_signal_status(e3,MAYBE_DIRTY);this.schedule(e3)}const roots=__privateGet(this,_roots);__privateSet(this,_roots,[]);this.apply();effects=collected_effects=[];render_effects=[];updates=legacy_updates=[];for(const root44 of roots)try{__privateMethod(this,_Batch_instances,traverse_fn).call(this,root44,effects,render_effects)}catch(e3){reset_all(root44);__privateMethod(this,_Batch_instances,is_deferred_fn).call(this)||this.discard();throw e3}current_batch=null;if(updates.length>0){batch=_Batch.ensure();for(const e3 of updates)batch.schedule(e3)}collected_effects=null;legacy_updates=null;if(__privateMethod(this,_Batch_instances,is_deferred_fn).call(this)){__privateMethod(this,_Batch_instances,defer_effects_fn).call(this,render_effects);__privateMethod(this,_Batch_instances,defer_effects_fn).call(this,effects);for(const[e3,t9]of __privateGet(this,_skipped_branches))reset_branch(e3,t9);updates.length>0&&__privateMethod(_a13=current_batch,_Batch_instances,process_fn).call(_a13);return}const earlier_batch=__privateMethod(this,_Batch_instances,find_earlier_batch_fn).call(this);if(earlier_batch){__privateMethod(this,_Batch_instances,defer_effects_fn).call(this,render_effects);__privateMethod(this,_Batch_instances,defer_effects_fn).call(this,effects);__privateMethod(_b6=earlier_batch,_Batch_instances,merge_fn).call(_b6,this)}else{__privateGet(this,_dirty_effects2).clear();__privateGet(this,_maybe_dirty_effects2).clear();for(const fn of __privateGet(this,_commit_callbacks))fn(this);__privateGet(this,_commit_callbacks).clear();previous_batch=this;flush_queued_effects(render_effects);flush_queued_effects(effects);previous_batch=null;null==(_c3=__privateGet(this,_deferred))||_c3.resolve();next_batch=current_batch;if(0===__privateGet(this,_pending)&&(0===__privateGet(this,_roots).length||null!==next_batch)){__privateMethod(this,_Batch_instances,unlink_fn).call(this);if(async_mode_flag){__privateMethod(this,_Batch_instances,commit_fn).call(this);current_batch=next_batch}}if(__privateGet(this,_roots).length>0)if(null!==next_batch){const batch2=next_batch;__privateGet(batch2,_roots).push(...__privateGet(this,_roots).filter(r4=>!__privateGet(batch2,_roots).includes(r4)))}else next_batch=this;null!==next_batch&&__privateMethod(_d2=next_batch,_Batch_instances,process_fn).call(_d2)}};traverse_fn=function(root44,effects,render_effects){var effect2,flags2,is_branch,is_skippable_branch,skip,child2,next2;root44.f^=CLEAN;effect2=root44.first;for(;null!==effect2;){flags2=effect2.f;is_branch=0!==(flags2&(BRANCH_EFFECT|ROOT_EFFECT));is_skippable_branch=is_branch&&0!==(flags2&CLEAN);skip=is_skippable_branch||0!==(flags2&INERT)||__privateGet(this,_skipped_branches).has(effect2);if(!skip&&null!==effect2.fn){if(is_branch)effect2.f^=CLEAN;else if(0!==(flags2&EFFECT))effects.push(effect2);else if(async_mode_flag&&0!==(flags2&(RENDER_EFFECT|MANAGED_EFFECT)))render_effects.push(effect2);else if(is_dirty(effect2)){0!==(flags2&BLOCK_EFFECT)&&__privateGet(this,_maybe_dirty_effects2).add(effect2);update_effect(effect2)}child2=effect2.first;if(null!==child2){effect2=child2;continue}}for(;null!==effect2;){next2=effect2.next;if(null!==next2){effect2=next2;break}effect2=effect2.parent}}};find_earlier_batch_fn=function(){for(var batch=__privateGet(this,_prev);null!==batch;){if(!batch.is_fork)for(const[value,[,is_derived]]of this.current)if(batch.current.has(value)&&!is_derived)return batch;batch=__privateGet(batch,_prev)}return null};merge_fn=function(batch){var _a13;for(const[source2,value]of batch.current){!this.previous.has(source2)&&batch.previous.has(source2)&&this.previous.set(source2,batch.previous.get(source2));this.current.set(source2,value)}for(const[effect2,deferred2]of batch.async_deriveds){const d4=this.async_deriveds.get(effect2);d4&&deferred2.promise.then(d4.resolve).catch(d4.reject)}batch.async_deriveds.clear();this.transfer_effects(__privateGet(batch,_dirty_effects2),__privateGet(batch,_maybe_dirty_effects2));const mark=value=>{var flags2,effect2,reactions=value.reactions;if(null!==reactions)for(const reaction of reactions){flags2=reaction.f;if(0!==(flags2&DERIVED))mark(reaction);else{effect2=reaction;if(flags2&(ASYNC|BLOCK_EFFECT)&&!this.async_deriveds.has(effect2)){__privateGet(this,_maybe_dirty_effects2).delete(effect2);set_signal_status(effect2,DIRTY);this.schedule(effect2)}}}};for(const source2 of this.current.keys())mark(source2);this.oncommit(()=>batch.discard());__privateMethod(_a13=batch,_Batch_instances,unlink_fn).call(_a13);current_batch=this;__privateMethod(this,_Batch_instances,process_fn).call(this)};defer_effects_fn=function(effects){for(var i3=0;i3<effects.length;i3+=1)defer_effect(effects[i3],__privateGet(this,_dirty_effects2),__privateGet(this,_maybe_dirty_effects2))};commit_fn=function(){var _a13,is_earlier,sources,batch_value,current,others,marked,checked,source2,current_unequal,root44;for(let batch=first_batch;null!==batch;batch=__privateGet(batch,_next)){is_earlier=batch.id<this.id;sources=[];for(const[source3,[value,is_derived]]of this.current){if(batch.current.has(source3)){batch_value=batch.current.get(source3)[0];if(!is_earlier||value===batch_value)continue;batch.current.set(source3,[value,is_derived])}sources.push(source3)}if(is_earlier)for(const[effect2,deferred2]of this.async_deriveds){const d4=batch.async_deriveds.get(effect2);d4&&deferred2.promise.then(d4.resolve).catch(d4.reject)}current=[...batch.current.keys()].filter(source3=>!batch.current.get(source3)[1]);if(__privateGet(batch,_started)&&0!==current.length){others=current.filter(source3=>!this.current.has(source3));if(0===others.length)is_earlier&&batch.discard();else if(sources.length>0){dev_fallback_default&&!__privateGet(batch,_decrement_queued)&&invariant(0===__privateGet(batch,_roots).length,"Batch has scheduled roots");if(is_earlier)for(const unskipped of __privateGet(this,_unskipped_branches))batch.unskip_effect(unskipped,e3=>{var _a14;0!==(e3.f&(BLOCK_EFFECT|ASYNC))?batch.schedule(e3):__privateMethod(_a14=batch,_Batch_instances,defer_effects_fn).call(_a14,[e3])});batch.activate();marked=new Set;checked=new Map;for(source2 of sources)mark_effects(source2,others,marked,checked);checked=new Map;current_unequal=[...batch.current].filter(([c3,v1])=>{const v2=this.current.get(c3);return!v2||(v2[0]!==v1[0]||v2[1]!==v1[1])}).map(([c3])=>c3);if(current_unequal.length>0)for(const effect2 of __privateGet(this,_new_effects))if(0===(effect2.f&(DESTROYED|INERT|EAGER_EFFECT))&&depends_on(effect2,current_unequal,checked))if(0!==(effect2.f&(ASYNC|BLOCK_EFFECT))){set_signal_status(effect2,DIRTY);batch.schedule(effect2)}else __privateGet(batch,_dirty_effects2).add(effect2);if(__privateGet(batch,_roots).length>0&&!__privateGet(batch,_decrement_queued)){batch.apply();for(root44 of __privateGet(batch,_roots))__privateMethod(_a13=batch,_Batch_instances,traverse_fn).call(_a13,root44,[],[]);__privateSet(batch,_roots,[])}batch.deactivate()}}}};unlink_fn=function(){var prev,next2;if(this.linked){prev=__privateGet(this,_prev);next2=__privateGet(this,_next);null===prev?first_batch=next2:__privateSet(prev,_next,next2);null===next2?last_batch=prev:__privateSet(next2,_prev,prev);this.linked=!1}};Batch=_Batch;eager_block_effects=null;0;0;eager_effects=new Set;old_values=new Map;eager_effects_deferred=!1;regex_is_valid_identifier=/^[a-zA-Z_$][a-zA-Z_$0-9]*$/;ARRAY_MUTATING_METHODS=new Set(["copyWithin","fill","pop","push","reverse","shift","sort","splice","unshift"]);listening_to_form_reset=!1;captured_signals=null;is_updating_effect=!1;is_destroying_effect=!1;active_reaction=null;untracking=!1;active_effect=null;current_sources=null;new_deps=null;skipped_deps=0;untracked_writes=null;write_version=1;read_version=0;update_version=read_version;event_symbol=Symbol("events");all_registered_events=new Set;root_event_handles=new Set;last_propagated_event=null;policy=(null==(_a8=null==globalThis?void 0:globalThis.window)?void 0:_a8.trustedTypes)&&globalThis.window.trustedTypes.createPolicy("svelte-trusted-html",{createHTML:html2=>html2});0;0;0;0;0;0;DOM_BOOLEAN_ATTRIBUTES=["allowfullscreen","async","autofocus","autoplay","checked","controls","default","disabled","formnovalidate","indeterminate","inert","ismap","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","seamless","selected","webkitdirectory","defer","disablepictureinpicture","disableremoteplayback"];0;[...DOM_BOOLEAN_ATTRIBUTES,"formNoValidate","isMap","noModule","playsInline","readOnly","value","volume","defaultValue","defaultChecked","srcObject","noValidate","allowFullscreen","disablePictureInPicture","disableRemotePlayback"];0;PASSIVE_EVENTS=["touchstart","touchmove"];0;0;0;0;STATE_CREATION_RUNES=["$state","$state.raw","$derived","$derived.by"];[...STATE_CREATION_RUNES,"$state.eager","$state.snapshot","$props","$props.id","$bindable","$effect","$effect.pre","$effect.tracking","$effect.root","$effect.pending","$inspect","$inspect().with","$inspect.trace","$host"];0;0;0;listeners=new Map;mounted_components=new WeakMap;BranchManager=class{constructor(anchor,transition2=!0){__publicField(this,"anchor");__privateAdd(this,_batches,new Map);__privateAdd(this,_onscreen,new Map);__privateAdd(this,_offscreen,new Map);__privateAdd(this,_outroing,new Set);__privateAdd(this,_transition,!0);__privateAdd(this,_commit,batch=>{var key3,onscreen,offscreen;if(__privateGet(this,_batches).has(batch)){key3=__privateGet(this,_batches).get(batch);onscreen=__privateGet(this,_onscreen).get(key3);if(onscreen){resume_effect(onscreen);__privateGet(this,_outroing).delete(key3)}else{offscreen=__privateGet(this,_offscreen).get(key3);if(offscreen){resume_effect(offscreen.effect);__privateGet(this,_onscreen).set(key3,offscreen.effect);__privateGet(this,_offscreen).delete(key3);dev_fallback_default&&(offscreen.fragment.lastChild[HMR_ANCHOR]=this.anchor);offscreen.fragment.lastChild.remove();this.anchor.before(offscreen.fragment);onscreen=offscreen.effect}}for(const[b3,k2]of __privateGet(this,_batches)){__privateGet(this,_batches).delete(b3);if(b3===batch)break;const offscreen2=__privateGet(this,_offscreen).get(k2);if(offscreen2){destroy_effect(offscreen2.effect);__privateGet(this,_offscreen).delete(k2)}}for(const[k2,effect2]of __privateGet(this,_onscreen)){if(k2===key3||__privateGet(this,_outroing).has(k2))continue;const on_destroy=()=>{const keys3=Array.from(__privateGet(this,_batches).values());if(keys3.includes(k2)){var fragment=document.createDocumentFragment();move_effect(effect2,fragment);fragment.append(create_text());__privateGet(this,_offscreen).set(k2,{effect:effect2,fragment})}else destroy_effect(effect2);__privateGet(this,_outroing).delete(k2);__privateGet(this,_onscreen).delete(k2)};if(__privateGet(this,_transition)||!onscreen){__privateGet(this,_outroing).add(k2);pause_effect(effect2,on_destroy,!1)}else on_destroy()}}});__privateAdd(this,_discard,batch=>{__privateGet(this,_batches).delete(batch);const keys3=Array.from(__privateGet(this,_batches).values());for(const[k2,branch2]of __privateGet(this,_offscreen))if(!keys3.includes(k2)){destroy_effect(branch2.effect);__privateGet(this,_offscreen).delete(k2)}});this.anchor=anchor;__privateSet(this,_transition,transition2)}ensure(key3,fn){var fragment,target,batch=current_batch,defer=should_defer_append();if(fn&&!__privateGet(this,_onscreen).has(key3)&&!__privateGet(this,_offscreen).has(key3))if(defer){fragment=document.createDocumentFragment();target=create_text();fragment.append(target);__privateGet(this,_offscreen).set(key3,{effect:branch(()=>fn(target)),fragment})}else __privateGet(this,_onscreen).set(key3,branch(()=>fn(this.anchor)));__privateGet(this,_batches).set(batch,key3);if(defer){for(const[k2,effect2]of __privateGet(this,_onscreen))k2===key3?batch.unskip_effect(effect2):batch.skip_effect(effect2);for(const[k2,branch2]of __privateGet(this,_offscreen))k2===key3?batch.unskip_effect(branch2.effect):batch.skip_effect(branch2.effect);batch.oncommit(__privateGet(this,_commit));batch.ondiscard(__privateGet(this,_discard))}else{hydrating&&(this.anchor=hydrate_node);__privateGet(this,_commit).call(this,batch)}}};_batches=new WeakMap;_onscreen=new WeakMap;_offscreen=new WeakMap;_outroing=new WeakMap;_transition=new WeakMap;_commit=new WeakMap;_discard=new WeakMap;if(dev_fallback_default){let throw_rune_error=function(rune){if(!(rune in globalThis)){let value;Object.defineProperty(globalThis,rune,{configurable:!0,get:()=>{if(void 0!==value)return value;rune_outside_svelte(rune)},set:v2=>{value=v2}})}};throw_rune_error("$state");throw_rune_error("$effect");throw_rune_error("$derived");throw_rune_error("$inspect");throw_rune_error("$props");throw_rune_error("$bindable")}all_styles=new Map;0;0;0;0;now=true_default?()=>performance.now():()=>Date.now();0;0;0;0;0;0;0;whitespace=[..." \t\n\r\f \v\ufeff"];0;0;IS_CUSTOM_ELEMENT=Symbol("is custom element");IS_HTML=Symbol("is html");LINK_TAG=IS_XHTML?"link":"LINK";0;0;0;PROGRESS_TAG=IS_XHTML?"progress":"PROGRESS";setters_cache=new Map;0;pending2=new Set;_ResizeObserverSingleton=class _ResizeObserverSingleton{constructor(options){__privateAdd(this,_ResizeObserverSingleton_instances);__privateAdd(this,_listeners,new WeakMap);__privateAdd(this,_observer);__privateAdd(this,_options2);__privateSet(this,_options2,options)}observe(element2,listener){var listeners2=__privateGet(this,_listeners).get(element2)||new Set;listeners2.add(listener);__privateGet(this,_listeners).set(element2,listeners2);__privateMethod(this,_ResizeObserverSingleton_instances,getObserver_fn).call(this).observe(element2,__privateGet(this,_options2));return()=>{var listeners3=__privateGet(this,_listeners).get(element2);listeners3.delete(listener);if(0===listeners3.size){__privateGet(this,_listeners).delete(element2);__privateGet(this,_observer).unobserve(element2)}}}};_listeners=new WeakMap;_observer=new WeakMap;_options2=new WeakMap;_ResizeObserverSingleton_instances=new WeakSet;getObserver_fn=function(){var _a13;return null!=(_a13=__privateGet(this,_observer))?_a13:__privateSet(this,_observer,new ResizeObserver(entries2=>{var entry,listener;for(entry of entries2){_ResizeObserverSingleton.entries.set(entry.target,entry);for(listener of __privateGet(this,_listeners).get(entry.target)||[])listener(entry)}}))};__publicField(_ResizeObserverSingleton,"entries",new WeakMap);ResizeObserverSingleton=_ResizeObserverSingleton;0;0;0;rest_props_handler={get(target,key3){if(!target.exclude.has(key3))return target.props[key3]},set(target,key3){dev_fallback_default&&props_rest_readonly(`${target.name}.${String(key3)}`);return!1},getOwnPropertyDescriptor(target,key3){if(!target.exclude.has(key3))return key3 in target.props?{enumerable:!0,configurable:!0,value:target.props[key3]}:void 0},has:(target,key3)=>!target.exclude.has(key3)&&key3 in target.props,ownKeys:target=>Reflect.ownKeys(target.props).filter(key3=>!target.exclude.has(key3))};0;spread_props_handler={get(target,key3){let i3=target.props.length;for(;i3--;){let p2=target.props[i3];is_function(p2)&&(p2=p2());if("object"==typeof p2&&null!==p2&&key3 in p2)return p2[key3]}},set(target,key3,value){let i3=target.props.length;for(;i3--;){let p2=target.props[i3];is_function(p2)&&(p2=p2());const desc=get_descriptor(p2,key3);if(desc&&desc.set){desc.set(value);return!0}}return!1},getOwnPropertyDescriptor(target,key3){let i3=target.props.length;for(;i3--;){let p2=target.props[i3];is_function(p2)&&(p2=p2());if("object"==typeof p2&&null!==p2&&key3 in p2){const descriptor=get_descriptor(p2,key3);descriptor&&!descriptor.configurable&&(descriptor.configurable=!0);return descriptor}}},has(target,key3){if(key3===STATE_SYMBOL||key3===LEGACY_PROPS)return!1;for(let p2 of target.props){is_function(p2)&&(p2=p2());if(null!=p2&&key3 in p2)return!0}return!1},ownKeys(target){const keys3=[];for(let p2 of target.props){is_function(p2)&&(p2=p2());if(p2){for(const key3 in p2)keys3.includes(key3)||keys3.push(key3);for(const key3 of Object.getOwnPropertySymbols(p2))keys3.includes(key3)||keys3.push(key3)}}return keys3}};Svelte4Component=class{constructor(options){var _a13,_b6,sources,add_source;__privateAdd(this,_events);__privateAdd(this,_instance);sources=new Map;add_source=(key3,value)=>{var s2=mutable_source(value,!1,!1);sources.set(key3,s2);return s2};const props=new Proxy({...options.props||{},$$events:{}},{get(target,prop2){var _a14;return get2(null!=(_a14=sources.get(prop2))?_a14:add_source(prop2,Reflect.get(target,prop2)))},has(target,prop2){var _a14;if(prop2===LEGACY_PROPS)return!0;get2(null!=(_a14=sources.get(prop2))?_a14:add_source(prop2,Reflect.get(target,prop2)));return Reflect.has(target,prop2)},set(target,prop2,value){var _a14;set(null!=(_a14=sources.get(prop2))?_a14:add_source(prop2,value),value);return Reflect.set(target,prop2,value)}});__privateSet(this,_instance,(options.hydrate?hydrate:mount)(options.component,{target:options.target,anchor:options.anchor,props,context:options.context,intro:null!=(_a13=options.intro)&&_a13,recover:options.recover,transformError:options.transformError}));async_mode_flag||(null==(_b6=null==options?void 0:options.props)?void 0:_b6.$$host)&&!1!==options.sync||flushSync();__privateSet(this,_events,props.$$events);for(const key3 of Object.keys(__privateGet(this,_instance)))"$set"!==key3&&"$destroy"!==key3&&"$on"!==key3&&define_property(this,key3,{get(){return __privateGet(this,_instance)[key3]},set(value){__privateGet(this,_instance)[key3]=value},enumerable:!0});__privateGet(this,_instance).$set=next2=>{Object.assign(props,next2)};__privateGet(this,_instance).$destroy=()=>{unmount(__privateGet(this,_instance))}}$set(props){__privateGet(this,_instance).$set(props)}$on(event2,callback){__privateGet(this,_events)[event2]=__privateGet(this,_events)[event2]||[];const cb2=(...args)=>callback.call(this,...args);__privateGet(this,_events)[event2].push(cb2);return()=>{__privateGet(this,_events)[event2]=__privateGet(this,_events)[event2].filter(fn=>fn!==cb2)}}$destroy(){__privateGet(this,_instance).$destroy()}};_events=new WeakMap;_instance=new WeakMap;"function"==typeof HTMLElement&&class extends HTMLElement{constructor($$componentCtor,$$slots,shadow_root_init){super();__publicField(this,"$$ctor");__publicField(this,"$$s");__publicField(this,"$$c");__publicField(this,"$$cn",!1);__publicField(this,"$$d",{});__publicField(this,"$$r",!1);__publicField(this,"$$p_d",{});__publicField(this,"$$l",{});__publicField(this,"$$l_u",new Map);__publicField(this,"$$me");__publicField(this,"$$shadowRoot",null);this.$$ctor=$$componentCtor;this.$$s=$$slots;shadow_root_init&&(this.$$shadowRoot=this.attachShadow(shadow_root_init))}addEventListener(type,listener,options){this.$$l[type]=this.$$l[type]||[];this.$$l[type].push(listener);if(this.$$c){const unsub=this.$$c.$on(type,listener);this.$$l_u.set(listener,unsub)}super.addEventListener(type,listener,options)}removeEventListener(type,listener,options){super.removeEventListener(type,listener,options);if(this.$$c){const unsub=this.$$l_u.get(listener);if(unsub){unsub();this.$$l_u.delete(listener)}}}async connectedCallback(){this.$$cn=!0;if(!this.$$c){let create_slot=function(name){return anchor=>{const slot2=create_element("slot");"default"!==name&&(slot2.name=name);append(anchor,slot2)}};await Promise.resolve();if(!this.$$cn||this.$$c)return;const $$slots={},existing_slots=get_custom_elements_slots(this);for(const name of this.$$s)if(name in existing_slots)if("default"!==name||this.$$d.children)$$slots[name]=create_slot(name);else{this.$$d.children=create_slot(name);$$slots.default=!0}for(const attribute of this.attributes){const name=this.$$g_p(attribute.name);name in this.$$d||(this.$$d[name]=get_custom_element_value(name,attribute.value,this.$$p_d,"toProp"))}for(const key3 in this.$$p_d)if(!(key3 in this.$$d)&&void 0!==this[key3]){this.$$d[key3]=this[key3];delete this[key3]}this.$$c=createClassComponent({component:this.$$ctor,target:this.$$shadowRoot||this,props:{...this.$$d,$$slots,$$host:this}});this.$$me=effect_root(()=>{render_effect(()=>{var _a13;this.$$r=!0;for(const key3 of object_keys(this.$$c)){if(!(null==(_a13=this.$$p_d[key3])?void 0:_a13.reflect))continue;this.$$d[key3]=this.$$c[key3];const attribute_value=get_custom_element_value(key3,this.$$d[key3],this.$$p_d,"toAttribute");null==attribute_value?this.removeAttribute(this.$$p_d[key3].attribute||key3):this.setAttribute(this.$$p_d[key3].attribute||key3,attribute_value)}this.$$r=!1})});for(const type in this.$$l)for(const listener of this.$$l[type]){const unsub=this.$$c.$on(type,listener);this.$$l_u.set(listener,unsub)}this.$$l={}}}attributeChangedCallback(attr2,_oldValue,newValue){var _a13;if(!this.$$r){attr2=this.$$g_p(attr2);this.$$d[attr2]=get_custom_element_value(attr2,newValue,this.$$p_d,"toProp");null==(_a13=this.$$c)||_a13.$set({[attr2]:this.$$d[attr2]})}}disconnectedCallback(){this.$$cn=!1;Promise.resolve().then(()=>{if(!this.$$cn&&this.$$c){this.$$c.$destroy();this.$$me();this.$$c=void 0}})}$$g_p(attribute_name){return object_keys(this.$$p_d).find(key3=>this.$$p_d[key3].attribute===attribute_name||!this.$$p_d[key3].attribute&&key3.toLowerCase()===attribute_name)||attribute_name}};allMessages={", please select the option that best describes the current state of your Vault. The application will then check your files in the most appropriate way based on your selection.":{def:", please select the option that best describes the current state of your Vault. The application will then check your files in the most appropriate way based on your selection.",es:", selecciona la opción que mejor describa el estado actual de tu Vault. La aplicación comprobará entonces tus archivos de la forma más adecuada según tu elección.",ko:", 이 보관함의 현재 상태를 가장 잘 설명하는 옵션을 선택해 주세요. 선택하신 내용에 따라 가장 적절한 방식으로 파일을 확인합니다.","zh-tw":",請選擇最符合你目前 Vault 狀態的選項,應用程式會依你的選擇以最合適的方式檢查你的檔案。"},"(Active)":{def:"(Active)",es:"(Activo)",ja:"(有効)",ko:"(활성)",ru:"(Активна)",zh:"(已启用)","zh-tw":"(已啟用)"},"(BETA) Always overwrite with a newer file":{def:"(BETA) Always overwrite with a newer file",es:"(BETA) Sobrescribir siempre con archivo más nuevo",fr:"(BÊTA) Toujours écraser avec un fichier plus récent",he:"(BETA) תמיד לדרוס עם קובץ חדש יותר",ja:"(ベータ機能) 常に新しいファイルで上書きする",ko:"(베타) 항상 새로운 파일로 덮어쓰기",ru:"(БЕТА) Всегда перезаписывать более новым файлом",zh:"始终使用更新的文件覆盖(测试版)","zh-tw":"BETA)總是以較新的檔案覆寫"},"(Beta) Use ignore files":{def:"(Beta) Use ignore files",es:"(Beta) Usar archivos de ignorar",fr:"(Bêta) Utiliser les fichiers d'exclusion",he:"(בטא) שימוש בקבצי התעלמות",ja:"(ベータ機能) 除外ファイル(ignore)の使用",ko:"(베타) 제외 규칙 파일 사용",ru:"(Бета) Использовать файлы игнорирования",zh:"(测试版)使用忽略文件","zh-tw":"Beta)使用忽略檔案"},"(Days passed, 0 to disable automatic-deletion)":{def:"(Days passed, 0 to disable automatic-deletion)",es:"(Días transcurridos, 0 para desactivar)",fr:"(Jours écoulés, 0 pour désactiver la suppression automatique)",he:"(ימים שעברו; 0 לביטול מחיקה אוטומטית)",ja:"(経過日数、0で自動削除を無効化)",ko:"(지난 일수, 0으로 설정하면 자동 삭제 비활성화)",ru:"(Дней прошло, 0 для отключения автоматического удаления)",zh:"(已过天数,0为禁用自动删除)","zh-tw":"(已過天數,0 表示停用自動刪除)"},"(e.g., after editing many files whilst offline)":{def:"(e.g., after editing many files whilst offline)",es:"(p. ej., tras editar muchos archivos sin conexión)",ko:"(예: 오프라인 상태에서 많은 파일을 편집한 뒤)","zh-tw":"(例如:離線編輯了大量檔案之後)"},"(e.g., immediately after restoring on another computer, or having recovered from a backup)":{def:"(e.g., immediately after restoring on another computer, or having recovered from a backup)",es:"(p. ej., justo después de restaurar en otro ordenador o de recuperar una copia de seguridad)",ko:"(예: 다른 컴퓨터에서 복원한 직후이거나 백업에서 복구한 경우)","zh-tw":"(例如:剛在另一台電腦上還原完成,或剛從備份復原之後)"},"(e.g., setting up for the first time on a new smartphone, starting from a clean slate)":{def:"(e.g., setting up for the first time on a new smartphone, starting from a clean slate)",es:"(p. ej., configurando por primera vez un móvil nuevo, empezando de cero)",ko:"(예: 새 스마트폰에서 처음 설정하여 빈 상태에서 시작하는 경우)","zh-tw":"(例如:第一次在新手機上設定,從全新狀態開始)"},"(ex. Read chunks online) If this option is enabled, LiveSync reads chunks online directly instead of replicating them locally. Increasing Custom chunk size is recommended.":{def:"(ex. Read chunks online) If this option is enabled, LiveSync reads chunks online directly instead of replicating them locally. Increasing Custom chunk size is recommended.",es:"(Ej: Leer chunks online) Lee chunks directamente en línea. Aumente tamaño de chunks personalizados",fr:"(ex. Lire les fragments en ligne) Si cette option est activée, LiveSync lit les fragments directement en ligne au lieu de les répliquer localement. L'augmentation de la taille personnalisée des fragments est recommandée.",he:"(לדוגמה: קריאת נתחים אונליין) אם אפשרות זו מופעלת, LiveSync קורא נתחים ישירות מהשרת מבלי לשכפל אותם מקומית. מומלץ להגדיל את גודל הנתח המותאם אישית.",ja:"(例: チャンクをオンラインで読む) このオプションを有効にすると、LiveSyncはチャンクをローカルに複製せず、直接オンラインで読み込みます。カスタムチャンクサイズを増やすことをお勧めします。",ko:"(예: 청크를 원격에서 읽음) 이 옵션을 활성화하면, LiveSync는 청크를 로컬에 복제하지 않고 원격에서 직접 읽습니다. 커스텀 청크 크기를 키우는 것을 권장합니다.",ru:"(ex. Read chunks online) If this option is enabled, LiveSync reads chunks online directly instead of replicating them locally. Increasing Custom chunk size is recommended.",zh:"(例如,在线读取块)如果启用此选项,LiveSync 将直接在线读取块,而不是在本地复制块。建议增加自定义块大小","zh-tw":"(例如:線上讀取 chunks)啟用此選項後,LiveSync 會直接線上讀取 chunks,而不在本機複寫。建議同時提高自訂 chunk 大小。"},"(MB) If this is set, changes to local and remote files that are larger than this will be skipped. If the file becomes smaller again, a newer one will be used.":{def:"(MB) If this is set, changes to local and remote files that are larger than this will be skipped. If the file becomes smaller again, a newer one will be used.",es:"(MB) Saltar cambios en archivos locales/remotos mayores a este tamaño. Si se reduce, se usará versión nueva",fr:"(Mo) Si cette valeur est définie, les modifications des fichiers locaux et distants plus grands que cette taille seront ignorées. Si le fichier redevient plus petit, une version plus récente sera utilisée.",he:"(MB) אם ערך זה מוגדר, שינויים בקבצים מקומיים ומרוחקים הגדולים מגודל זה יידלגו. אם הקובץ יקטן שוב, ייעשה שימוש בגרסה החדשה יותר.",ja:"(MB) この値を設定すると、これより大きいサイズのローカルファイルやリモートファイルの変更はスキップされます。ファイルが再び小さくなった場合は、新しいものが使用されます。",ko:"(MB) 이 값이 설정되면, 이보다 큰 로컬 및 원격 파일의 변경 사항은 건너뜁니다. 파일이 다시 작아지면 더 새로운 파일이 사용됩니다.",ru:"(MB) If this is set, changes to local and remote files that are larger than this will be skipped. If the file becomes smaller again, a newer one will be used.",zh:"(MB)如果设置了此项,大于此大小的本地和远程文件的更改将被跳过。如果文件再次变小,将使用更新的文件","zh-tw":"MB)若已設定,大於此大小的本機與遠端檔案變更都會被略過。如果檔案之後變小,則會使用較新的版本。"},"(Mega chars)":{def:"(Mega chars)",es:"(Millones de caracteres)",fr:"(Méga caractères)",he:"(מגה תווים)",ja:"(メガ文字)",ko:"(백만 자 단위)",ru:"(Мега символов)",zh:"(百万字符)","zh-tw":"(百萬字元)"},"(Missing)":{def:"(Missing)",es:"(Falta)",ko:"(없음)","zh-tw":"(缺失)"},"(Not recommended) If set, credentials will be stored in the file.":{def:"(Not recommended) If set, credentials will be stored in the file.",es:"(No recomendado) Almacena credenciales en el archivo",fr:"(Non recommandé) Si activé, les identifiants seront stockés dans le fichier.",he:"(לא מומלץ) אם מוגדר, פרטי הגישה יישמרו בקובץ.",ja:"(非推奨) 設定した場合、認証情報がファイルに保存されます。",ko:"(권장하지 않음) 설정한 경우 자격 증명이 파일에 저장됩니다.",ru:"(Not recommended) If set, credentials will be stored in the file.",zh:"(不建议)如果设置,凭据将存储在文件中","zh-tw":"(不建議)若啟用,憑證將儲存在檔案中。"},"(Obsolete) Use an old adapter for compatibility":{def:"(Obsolete) Use an old adapter for compatibility",es:"(Obsoleto) Usar adaptador antiguo",fr:"(Obsolète) Utiliser un ancien adaptateur pour la compatibilité",he:"(מיושן) שימוש במתאם ישן לתאימות לאחור",ja:"(廃止済み)古いアダプターを互換性のために利用",ko:"(사용 중단) 호환성을 위해 이전 어댑터 사용",ru:"(Устарело) Использовать старый адаптер для совместимости",zh:"(已弃用)为兼容性使用旧适配器","zh-tw":"(已淘汰)使用舊版轉接器以維持相容性"},"(RegExp) Empty to sync all files. Set filter as a regular expression to limit synchronising files.":{def:"(RegExp) Empty to sync all files. Set filter as a regular expression to limit synchronising files.",es:"(RegExp) Déjelo vacío para sincronizar todos los archivos. Defina un filtro como expresión regular para limitar los archivos que se sincronizan.",ja:"(正規表現)空欄で全ファイルを同期します。正規表現を指定すると、同期対象のファイルを絞り込めます。",ko:"(정규식) 비워 두면 모든 파일을 동기화합니다. 정규식을 지정하면 동기화할 파일을 제한할 수 있습니다.",ru:"(RegExp) Оставьте пустым, чтобы синхронизировать все файлы. Укажите регулярное выражение, чтобы ограничить синхронизируемые файлы.",zh:"(正则表达式)留空表示同步所有文件。可设置正则表达式来限制需要同步的文件。","zh-tw":"(正則表示式)留空即同步所有檔案。設定正則表示式可限制要同步的檔案。"},"(RegExp) If this is set, any changes to local and remote files that match this will be skipped.":{def:"(RegExp) If this is set, any changes to local and remote files that match this will be skipped.",es:"(RegExp) Si se establece, se omitirá cualquier cambio en archivos locales y remotos que coincida con este patrón.",ja:"(正規表現)設定すると、これに一致するローカル/リモートファイルの変更はすべてスキップされます。",ko:"(정규식) 설정하면 이 패턴과 일치하는 로컬 및 원격 파일 변경은 모두 건너뜁니다.",ru:"(RegExp) Если задано, любые изменения локальных и удалённых файлов, соответствующих этому шаблону, будут пропускаться.",zh:"(正则表达式)如果已设置,则所有匹配此模式的本地和远端文件变更都会被跳过。","zh-tw":"(正則表示式)若已設定,所有符合此模式的本機與遠端檔案變更都會被略過。"},"(Select this if you are already using synchronisation on another computer or smartphone.) This option is suitable if you are new to LiveSync and want to set it up from scratch.":{def:"(Select this if you are already using synchronisation on another computer or smartphone.) This option is suitable if you are new to LiveSync and want to set it up from scratch.",es:"(Seleccione esto si ya utiliza la sincronización en otro ordenador o teléfono). Esta opción es adecuada si desea añadir este dispositivo a una configuración de LiveSync existente。",ja:"(別の PC やスマートフォンですでに同期を利用している場合に選択してください。)この端末を既存の LiveSync 構成に追加する場合に適しています。",ko:"(다른 컴퓨터나 스마트폰에서 이미 동기화를 사용 중이라면 선택하세요.) 이 기기를 기존 LiveSync 구성에 추가하려는 경우에 적합합니다.",ru:"(Выберите этот вариант, если вы уже используете синхронизацию на другом компьютере или смартфоне.) Он подходит, если вы хотите добавить это устройство к уже существующей конфигурации LiveSync。",zh:"(如果你已经在另一台电脑或手机上使用同步,请选择此项。)此选项适合将当前设备加入现有 LiveSync 配置的用户。","zh-tw":"(如果你已經在另一台電腦或手機上使用同步,請選擇此項。)此選項適合將目前裝置加入既有 LiveSync 設定的使用者。"},"(Select this if you are configuring this device as the first synchronisation device.) This option is suitable if you are new to LiveSync and want to set it up from scratch.":{def:"(Select this if you are configuring this device as the first synchronisation device.) This option is suitable if you are new to LiveSync and want to set it up from scratch.",es:"(Seleccione esto si está configurando este dispositivo como el primer dispositivo de sincronización). Esta opción es adecuada si es nuevo en LiveSync y desea configurarlo desde cero。",ja:"(この端末を最初の同期端末として設定する場合に選択してください。)LiveSync を初めて利用し、最初から設定したい場合に適しています。",ko:"(이 기기를 첫 번째 동기화 기기로 설정한다면 선택하세요.) LiveSync를 처음 사용하며 처음부터 설정하려는 경우에 적합합니다.",ru:"(Выберите этот вариант, если настраиваете это устройство как первое устройство синхронизации.) Он подходит, если вы впервые используете LiveSync и хотите настроить всё с нуля。",zh:"(如果你正在将此设备配置为第一台同步设备,请选择此项。)此选项适合初次使用 LiveSync,并希望从头开始配置的用户。","zh-tw":"(如果你正在將此裝置設定為第一台同步裝置,請選擇此項。)此選項適合初次使用 LiveSync,並希望從頭開始設定的使用者。"},"↑: Overwrite Remote":{def:"↑: Overwrite Remote",es:"↑: Sobrescribir remoto",ko:"↑: 원격 덮어쓰기","zh-tw":"↑:覆寫遠端"},"↓: Overwrite Local":{def:"↓: Overwrite Local",es:"↓: Sobrescribir local",ko:"↓: 로컬 덮어쓰기","zh-tw":"↓:覆寫本機"},"⇅: Use newer":{def:"⇅: Use newer",es:"⇅: Usar el más nuevo",ko:"⇅: 더 새로운 쪽 사용","zh-tw":"⇅:使用較新版本"},"+1 week":{def:"+1 week",es:"+1 semana",ko:"+1주","zh-tw":"+1 週"},"> [!INFO]- The connected devices have been detected as follows:\n${devices}":{def:"> [!INFO]- The connected devices have been detected as follows:\n${devices}",es:"> [!INFO]- Se han detectado los siguientes dispositivos conectados:\n${devices}",ja:"> [!INFO]- 次の接続済みデバイスが検出されました:\n${devices}",ko:"> [!INFO]- 다음 연결된 기기가 감지되었습니다:\n${devices}",ru:"> [!INFO]- Обнаружены следующие подключённые устройства:\n${devices}",zh:"> [!INFO]- 已检测到以下已连接设备:\n${devices}","zh-tw":"> [!INFO]- 已偵測到以下已連線裝置:\n${devices}"},"⚠️ Important Notice":{def:"⚠️ Important Notice",es:"⚠️ Aviso importante",ko:"⚠️ 중요 안내","zh-tw":"⚠️ 重要通知"},"⚠️ Please Confirm the Following":{def:"⚠️ Please Confirm the Following",es:"⚠️ Confirma lo siguiente",ko:"⚠️ 다음 내용을 확인해 주세요","zh-tw":"⚠️ 請確認以下事項"},"✔ SELECT":{def:"✔ SELECT",es:"✔ SELECCIONAR",ko:"✔ 선택","zh-tw":"✔ 已選取"},"✔ SYNC":{def:"✔ SYNC",es:"✔ SINCRONIZAR",ko:"✔ 동기화","zh-tw":"✔ 同步中"},"✔ WATCH":{def:"✔ WATCH",es:"✔ OBSERVAR",ko:"✔ 감시","zh-tw":"✔ 監看中"},"📡 Off":{def:"📡 Off",es:"📡 Desactivado",ko:"📡 꺼짐","zh-tw":"📡 關閉"},"📡 On":{def:"📡 On",es:"📡 Activado",ko:"📡 켜짐","zh-tw":"📡 開啟"},"🔴 Disconnected":{def:"🔴 Disconnected",es:"🔴 Desconectado",ko:"🔴 연결 끊김","zh-tw":"🔴 已斷線"},"🕵️ Diag":{def:"🕵️ Diag",es:"🕵️ Diagnóstico",ko:"🕵️ 진단","zh-tw":"🕵️ 診斷"},"🗑 Delete":{def:"🗑 Delete",es:"🗑 Eliminar",ko:"🗑 삭제","zh-tw":"🗑 刪除"},"🟢 Connected":{def:"🟢 Connected",es:"🟢 Conectado",ko:"🟢 연결됨","zh-tw":"🟢 已連線"},"${count} issue(s) detected!":{def:"${count} issue(s) detected!",es:"¡${count} problema(s) detectado(s)!",ko:"${count}개의 문제가 감지되었습니다!","zh-tw":"偵測到 ${count} 個問題!"},"A Setup URI is a single string of text containing your server address and authentication details. Using a URI, if one was generated by your server installation script, provides a simple and secure configuration.":{def:"A Setup URI is a single string of text containing your server address and authentication details. Using a URI, if one was generated by your server installation script, provides a simple and secure configuration.",es:"Un URI de configuración es una única cadena de texto que contiene la dirección del servidor y los datos de autenticación. Si el script de instalación de su servidor generó un URI, usarlo proporciona una configuración sencilla y segura。",ja:"Setup URI は、サーバーアドレスと認証情報を含む 1 本の文字列です。サーバーのインストールスクリプトで生成された URI がある場合は、それを使うと簡単かつ安全に設定できます。",ko:"Setup URI는 서버 주소와 인증 정보를 담은 하나의 문자열입니다. 서버 설치 스크립트가 URI를 생성했다면, 이를 사용해 간단하고 안전하게 구성할 수 있습니다.",ru:"Setup URI — это одна строка текста, содержащая адрес сервера и данные аутентификации. Если URI был создан скриптом установки сервера, его использование обеспечивает простую и безопасную настройку。",zh:"Setup URI 是一段包含服务器地址与认证信息的文本。如果服务器安装脚本已经生成了 URI,使用它可以更简单且更安全地完成配置。","zh-tw":"Setup URI 是一段包含伺服器位址與驗證資訊的文字。如果伺服器安裝腳本已經產生 URI,使用它可以更簡單且更安全地完成設定。"},Accept:{def:"Accept",es:"Aceptar",ko:"수락","zh-tw":"接受"},"Accept in session":{def:"Accept in session",es:"Aceptar en esta sesión",ko:"이 세션에서만 수락","zh-tw":"本次連線接受"},ACCEPTED:{def:"ACCEPTED",es:"ACEPTADO",ko:"수락됨","zh-tw":"已接受"},"ACCEPTED (in session)":{def:"ACCEPTED (in session)",es:"ACEPTADO (en esta sesión)",ko:"수락됨 (이 세션에서만)","zh-tw":"已接受(本次連線)"},"Access Key":{def:"Access Key",es:"Clave de acceso",fr:"Clé d'accès",he:"מפתח גישה",ja:"アクセスキー",ko:"액세스 키",ru:"Ключ доступа",zh:"访问密钥","zh-tw":"Access Key"},"Access Key ID":{def:"Access Key ID",es:"ID de clave de acceso",ko:"액세스 키 ID","zh-tw":"Access Key ID"},Action:{def:"Action",es:"Acción",ko:"작업","zh-tw":"動作"},Activate:{def:"Activate",es:"Activar",ja:"有効化",ko:"활성화",ru:"Активировать",zh:"启用","zh-tw":"啟用"},"Active Remote Configuration":{def:"Active Remote Configuration",es:"Configuración remota activa",fr:"Configuration distante active",he:"תצורת שרת מרוחק פעיל",ko:"활성 원격 구성",ru:"Активная удалённая конфигурация",zh:"生效中的远程配置","zh-tw":"目前啟用的遠端設定"},"Add default patterns":{def:"Add default patterns",es:"Añadir patrones predeterminados",ja:"デフォルトパターンを追加",ko:"기본 패턴 추가",ru:"Добавить шаблоны по умолчанию",zh:"添加默认模式","zh-tw":"新增預設模式"},"Add new connection":{def:"Add new connection",es:"Añadir conexión",ja:"接続を追加",ko:"연결 추가",ru:"Добавить подключение",zh:"新增连接","zh-tw":"新增連線"},"AddOn Module (ConfigSync) has not been loaded. This is very unexpected situation. Please report this issue.":{def:"AddOn Module (ConfigSync) has not been loaded. This is very unexpected situation. Please report this issue.",es:"El módulo complementario (ConfigSync) no se ha cargado. Esta situación es muy inesperada. Informa de este problema.",ko:"애드온 모듈(ConfigSync)이 로드되지 않았습니다. 매우 예기치 못한 상황입니다. 이 문제를 신고해 주세요.","zh-tw":"附加模組(ConfigSync)尚未載入。這是非常異常的情況,請回報此問題。"},"AddOn Module (HiddenFileSync) has not been loaded. This is very unexpected situation. Please report this issue.":{def:"AddOn Module (HiddenFileSync) has not been loaded. This is very unexpected situation. Please report this issue.",es:"El módulo complementario (HiddenFileSync) no se ha cargado. Esta situación es muy inesperada. Informa de este problema.",ko:"애드온 모듈(HiddenFileSync)이 로드되지 않았습니다. 매우 예기치 못한 상황입니다. 이 문제를 신고해 주세요.","zh-tw":"附加模組(HiddenFileSync)尚未載入。這是非常異常的情況,請回報此問題。"},Advanced:{def:"Advanced",es:"Avanzado",ko:"고급","zh-tw":"進階"},"Advanced Settings":{def:"Advanced Settings",es:"Ajustes avanzados",ko:"고급 설정","zh-tw":"進階設定"},"After restarting, the data on this device will be uploaded to the server as the 'master copy'. Please be aware that any unintended data currently on the server will be completely overwritten.":{def:"After restarting, the data on this device will be uploaded to the server as the 'master copy'. Please be aware that any unintended data currently on the server will be completely overwritten.",es:"Tras reiniciar, los datos de este dispositivo se subirán al servidor como «copia maestra». Ten en cuenta que cualquier dato no deseado que haya ahora en el servidor se sobrescribirá por completo.",ko:"재시작하면 이 기기의 데이터가 '원본'으로서 서버에 업로드됩니다. 현재 서버에 있는 의도치 않은 데이터는 모두 완전히 덮어써진다는 점에 유의해 주세요.","zh-tw":"重新啟動後,此裝置上的資料將以「主要複本」的形式上傳到伺服器。請注意,伺服器上任何非預期的現有資料都會被完全覆寫。"},"After restarting, the database on this device will be rebuilt using data from the server. If there are any unsynchronised files in this vault, conflicts may occur with the server data.":{def:"After restarting, the database on this device will be rebuilt using data from the server. If there are any unsynchronised files in this vault, conflicts may occur with the server data.",es:"Tras reiniciar, la base de datos de este dispositivo se reconstruirá con los datos del servidor. Si hay archivos sin sincronizar en este vault, pueden producirse conflictos con los datos del servidor.",ko:"재시작하면 서버의 데이터를 사용해 이 기기의 데이터베이스가 재구축됩니다. 이 보관함에 동기화되지 않은 파일이 있다면 서버 데이터와 충돌이 발생할 수 있습니다.","zh-tw":"重新啟動後,此裝置上的資料庫將使用伺服器的資料重建。如果此 Vault 中有尚未同步的檔案,可能會與伺服器資料發生衝突。"},"After that, synchronise to a brand new vault on each other device with the new remote one by one.":{def:"After that, synchronise to a brand new vault on each other device with the new remote one by one.",es:"Después, sincroniza con un vault totalmente nuevo en cada uno de los demás dispositivos, uno por uno, usando el nuevo remoto.",ko:"그런 다음 다른 기기에서도 하나씩 새 원격을 사용해 완전히 새로운 보관함에 동기화하세요.","zh-tw":"之後,請在其他每個裝置上,逐一使用全新的 Vault 與這個新的遠端進行同步。"},"All checks passed successfully!":{def:"All checks passed successfully!",es:"¡Todas las comprobaciones se han superado correctamente!",ko:"모든 검사를 통과했습니다!","zh-tw":"所有檢查都已成功通過!"},"All devices have the same progress value (${progress}). Your devices seem to be synchronised. And be able to proceed with Garbage Collection.":{def:"All devices have the same progress value (${progress}). Your devices seem to be synchronised. And be able to proceed with Garbage Collection.",es:"Todos los dispositivos tienen el mismo valor de progreso (${progress}). Parece que están sincronizados, por lo que se puede continuar con la recolección de basura.",ja:"すべてのデバイスで進捗値が同じです(${progress})。デバイスは同期されているようなので、Garbage Collection を続行できます。",ko:"모든 기기의 진행 값이 동일합니다(${progress}). 기기들이 동기화된 것으로 보이므로 가비지 컬렉션을 진행할 수 있습니다.",ru:"У всех устройств одинаковое значение прогресса (${progress}). Похоже, ваши устройства синхронизированы, и можно продолжать Garbage Collection.",zh:"所有设备的进度值均相同(${progress})。看起来你的设备已经同步,可以继续执行垃圾回收。","zh-tw":"所有裝置的進度值均相同(${progress})。看起來你的裝置已同步,可以繼續執行垃圾回收。"},"All the same or non-existent":{def:"All the same or non-existent",es:"Todo igual o inexistente",ko:"모두 동일하거나 존재하지 않음","zh-tw":"全部相同或不存在"},"Allow in session":{def:"Allow in session",es:"Permitir en esta sesión",ko:"이 세션에서만 허용","zh-tw":"本次連線允許"},"Allow permanently":{def:"Allow permanently",es:"Permitir permanentemente",ko:"항상 허용","zh-tw":"永久允許"},"Also, please note that if you are using Peer-to-Peer synchronization, this configuration will be used when you switch to other methods and connect to a remote server in the future.":{def:"Also, please note that if you are using Peer-to-Peer synchronization, this configuration will be used when you switch to other methods and connect to a remote server in the future.",es:"Además, si usas sincronización punto a punto, esta configuración se aplicará cuando en el futuro cambies a otros métodos y te conectes a un servidor remoto.",ko:"또한 Peer-to-Peer 동기화를 사용 중이라면, 이 구성은 나중에 다른 방식으로 전환하여 원격 서버에 연결할 때 사용된다는 점에 유의해 주세요.","zh-tw":"另請注意,如果你目前使用 Peer-to-Peer 同步,日後若切換到其他方式並連線到遠端伺服器時,也會沿用這組設定。"},"Always prompt merge conflicts":{def:"Always prompt merge conflicts",es:"Siempre preguntar en conflictos",fr:"Toujours demander pour les conflits de fusion",he:"תמיד להציג בקשת אישור לקונפליקטי מיזוג",ja:"常に競合は手動で解決する",ko:"항상 병합 충돌 알림",ru:"Всегда запрашивать разрешение конфликтов слияния",zh:"始终提示合并冲突","zh-tw":"總是提示合併衝突"},Analyse:{def:"Analyse",es:"Analizar",fr:"Analyser",he:"ניתוח",ko:"분석",ru:"Анализировать",zh:"立即分析","zh-tw":"分析"},"Analyse database usage":{def:"Analyse database usage",es:"Analizar el uso de la base de datos",fr:"Analyser l'utilisation de la base de données",he:"ניתוח שימוש במסד נתונים",ja:"データベース使用状況を分析",ko:"데이터베이스 사용량 분석",ru:"Анализ использования базы данных",zh:"分析数据库使用情况","zh-tw":"分析資料庫使用情況"},"Analyse database usage and generate a TSV report for diagnosis yourself. You can paste the generated report with any spreadsheet you like.":{def:"Analyse database usage and generate a TSV report for diagnosis yourself. You can paste the generated report with any spreadsheet you like.",es:"Analiza el uso de la base de datos y genera un informe TSV para que puedas diagnosticarlo tú mismo. Puedes pegar el informe generado en la hoja de cálculo que prefieras.",fr:"Analyser l'utilisation de la base de données et générer un rapport TSV pour un diagnostic personnel. Vous pouvez coller le rapport généré dans le tableur de votre choix.",he:'נתח שימוש במסד הנתונים וצור דו"ח TSV לאבחון עצמי. ניתן להדביק את הדו"ח שנוצר בכל גיליון אלקטרוני.',ja:"データベース使用状況を分析し、自分で診断できるよう TSV レポートを生成します。生成したレポートは任意のスプレッドシートに貼り付けて確認できます。",ko:"데이터베이스 사용량을 분석하고 직접 진단할 수 있도록 TSV 보고서를 생성합니다. 생성된 보고서는 원하는 스프레드시트에 붙여 넣어 확인할 수 있습니다.",ru:"Проанализируйте использование базы данных и создайте TSV-отчёт для самостоятельной диагностики. Полученный отчёт можно вставить в любую удобную для вас таблицу.",zh:"分析数据库使用情况并生成 TSV 报告以供您自行诊断。您可以将生成的报告粘贴到您喜欢的任何电子表格中。","zh-tw":"分析資料庫使用情況並產生 TSV 報告,方便你自行診斷。你可以將產生的報告貼到任何慣用的試算表中查看。"},"Apply All Selected":{def:"Apply All Selected",es:"Aplicar todo lo seleccionado",ko:"선택 항목 모두 적용","zh-tw":"套用所有已選取項目"},"Apply Latest Change if Conflicting":{def:"Apply Latest Change if Conflicting",es:"Aplicar último cambio en conflictos",fr:"Appliquer la dernière modification en cas de conflit",he:"החל שינוי אחרון בעת קונפליקט",ja:"競合がある場合は最新の変更を適用する",ko:"충돌 시 최신 변경 사항 적용",ru:"Применить последнее изменение при конфликте",zh:"如果冲突则应用最新更改","zh-tw":"發生衝突時套用最新變更"},"Apply preset configuration":{def:"Apply preset configuration",es:"Aplicar configuración predefinida",fr:"Appliquer une configuration prédéfinie",he:"החל תצורה קבועה מראש",ja:"プリセットを適用する",ko:"프리셋 구성 적용",ru:"Применить предустановленную конфигурацию",zh:"应用预设配置","zh-tw":"套用預設配置"},"Apply the settings":{def:"Apply the settings",es:"Aplicar los ajustes",ko:"설정 적용","zh-tw":"套用設定"},"Ask a passphrase at every launch":{def:"Ask a passphrase at every launch",es:"Solicitar la frase de contraseña en cada inicio",ja:"起動のたびにパスフレーズを確認",ko:"시작할 때마다 패스프레이즈 묻기",ru:"Запрашивать парольную фразу при каждом запуске",zh:"每次启动时询问密码短语","zh-tw":"每次啟動時都詢問密語"},"Auto Connect":{def:"Auto Connect",es:"Conexión automática",ko:"자동 연결","zh-tw":"自動連線"},"Auto Start P2P Connection":{def:"Auto Start P2P Connection",es:"Iniciar la conexión P2P automáticamente",ko:"P2P 연결 자동 시작","zh-tw":"自動啟動 P2P 連線"},Automatic:{def:"Automatic",es:"Automático",ko:"자동","zh-tw":"自動"},"Automatically Sync all files when opening Obsidian.":{def:"Automatically Sync all files when opening Obsidian.",es:"Sincronizar automáticamente todos los archivos al abrir Obsidian",fr:"Synchroniser automatiquement tous les fichiers à l'ouverture d'Obsidian.",he:"סנכרן את כל הקבצים אוטומטית עם פתיחת Obsidian.",ja:"Obsidian起動時にすべてのファイルを自動同期します。",ko:"Obsidian을 열 때 모든 파일을 자동으로 동기화합니다.",ru:"Автоматически синхронизировать все файлы при открытии Obsidian.",zh:"打开 Obsidian 时自动同步所有文件","zh-tw":"開啟 Obsidian 時自動同步所有檔案。"},"Available Peers":{def:"Available Peers",es:"Pares disponibles",ko:"사용 가능한 피어","zh-tw":"可用的 Peer"},Back:{def:"Back",es:"Volver",ja:"戻る",ko:"뒤로",ru:"Назад",zh:"返回","zh-tw":"返回"},"Back to non-configured":{def:"Back to non-configured",es:"Volver a no configurado",ja:"未設定状態に戻す",ko:"미구성 상태로 되돌리기",ru:"Вернуть в состояние без настройки",zh:"恢复为未配置状态","zh-tw":"恢復為未設定狀態"},"Batch database update":{def:"Batch database update",es:"Actualización por lotes de BD",fr:"Mise à jour groupée de la base de données",he:"עדכון אצווה למסד נתונים",ja:"データベースのバッチ更新",ko:"일괄 데이터베이스 업데이트",ru:"Пакетное обновление базы данных",zh:"批量数据库更新","zh-tw":"批次更新資料庫"},"Batch limit":{def:"Batch limit",es:"Límite de lotes",fr:"Limite de lot",he:"מגבלת אצווה",ja:"バッチの上限",ko:"배치 개수 제한",ru:"Пакетный лимит",zh:"批量限制","zh-tw":"批次上限"},"Batch size":{def:"Batch size",es:"Tamaño de lote",fr:"Taille de lot",he:"גודל אצווה",ja:"バッチ容量",ko:"배치 크기",ru:"Размер пакета",zh:"批量大小","zh-tw":"批次大小"},"Batch size of on-demand fetching":{def:"Batch size of on-demand fetching",es:"Tamaño de lote para obtención bajo demanda",fr:"Taille de lot pour la récupération à la demande",he:"גודל אצווה במשיכה לפי דרישה",ja:"オンデマンド取得のバッチサイズ",ko:"필요 시 가져오기의 배치 크기",ru:"Размер пакета при запросе по требованию",zh:"按需获取的批量大小","zh-tw":"按需抓取的批次大小"},"Before v0.17.16, we used an old adapter for the local database. Now the new adapter is preferred. However, it needs local database rebuilding. Please disable this toggle when you have enough time. If leave it enabled, also while fetching from the remote database, you will be asked to disable this.":{def:"Before v0.17.16, we used an old adapter for the local database. Now the new adapter is preferred. However, it needs local database rebuilding. Please disable this toggle when you have enough time. If leave it enabled, also while fetching from the remote database, you will be asked to disable this.",es:"Antes de v0.17.16 usábamos adaptador antiguo. Nuevo adaptador requiere reconstruir BD local. Desactive cuando pueda",fr:"Avant la version v0.17.16, nous utilisions un ancien adaptateur pour la base de données locale. Le nouvel adaptateur est désormais recommandé. Cependant, il nécessite une reconstruction de la base locale. Veuillez désactiver cette option lorsque vous aurez suffisamment de temps. Si elle reste activée, il vous sera également demandé de la désactiver lors de la récupération depuis la base distante.",he:"לפני גרסה 0.17.16, השתמשנו במתאם ישן למסד הנתונים המקומי. כעת המתאם החדש מועדף. עם זאת, הדבר מצריך בנייה מחדש של מסד הנתונים המקומי. אנא כבה אפשרות זו כשיש לך זמן פנוי. אם תשאיר אותה מופעלת, גם בעת משיכה ממסד הנתונים המרוחק, תתבקש לכבות אותה.",ja:"v0.17.6までは古いアダプターをローカル用のデータベースに使用していましたが、現在は新しいアダプターを推奨しています。しかし、新しいアダプターに変更するにはローカルデータベースの再構築が必要です。有効のままにしておくと、リモートデータベースからフェッチする場合に、この設定を無効にするかの質問が表示されます。",ko:"v0.17.16 이전에는 로컬 데이터베이스에 이전 어댑터를 사용했습니다. 이제는 새로운 어댑터를 권장합니다. 하지만 로컬 데이터베이스 재구축이 필요합니다. 충분한 시간이 있을 때 이 토글을 비활성화해 주세요. 활성화된 상태로 두면 원격 데이터베이스에서 가져올 때도 이를 비활성화하라는 메시지가 나타납니다.",ru:"Before v0.17.16, we used an old adapter for the local database. Now the new adapter is preferred. However, it needs local database rebuilding. Please disable this toggle when you have enough time. If leave it enabled, also while fetching from the remote database, you will be asked to disable this.",zh:"在 v0.17.16 之前,我们使用旧适配器作为本地数据库。现在首选新适配器。但是,它需要重建本地数据库。请在有足够时间时禁用此开关。如果保持启用状态,并且在从远程数据库获取时,系统将要求您禁用此开关。","zh-tw":"在 v0.17.16 之前,本機資料庫使用的是舊版轉接器。現在建議使用新版轉接器,但需要重建本機資料庫。請在時間充裕時停用此開關。若保持啟用,從遠端資料庫抓取時也會要求你停用此選項。"},"Broadcasting?":{def:"Broadcasting?",es:"¿Difusión?",ko:"브로드캐스트란?","zh-tw":"廣播中?"},"Bucket Name":{def:"Bucket Name",es:"Nombre del bucket",fr:"Nom du bucket",he:"שם דלי (Bucket)",ja:"バケット名",ko:"버킷 이름",ru:"Имя бакета",zh:"存储桶名称","zh-tw":"儲存庫名稱"},"by resetting the remote, you will be informed on other devices.":{def:"by resetting the remote, you will be informed on other devices.",es:"al restablecer el remoto, se te avisará en los demás dispositivos.",ko:"원격을 초기화하면 다른 기기에서 알림을 받게 됩니다.","zh-tw":"重設遠端後,其他裝置上會顯示提示告知此事。"},Cancel:{def:"Cancel",es:"Cancelar",ja:"キャンセル",ko:"취소",ru:"Отмена",zh:"取消","zh-tw":"取消"},"Cancel Garbage Collection":{def:"Cancel Garbage Collection",es:"Cancelar la recolección de basura",ja:"Garbage Collection をキャンセル",ko:"가비지 컬렉션 취소",ru:"Отменить Garbage Collection",zh:"取消垃圾回收","zh-tw":"取消垃圾回收"},"Changing the encryption algorithm will prevent access to any data previously encrypted with a different algorithm. Ensure that all your devices are configured to use the same algorithm to maintain access to your data.":{def:"Changing the encryption algorithm will prevent access to any data previously encrypted with a different algorithm. Ensure that all your devices are configured to use the same algorithm to maintain access to your data.",es:"Cambiar el algoritmo de cifrado impedirá acceder a los datos cifrados previamente con otro algoritmo. Asegúrate de que todos tus dispositivos usen el mismo algoritmo para no perder el acceso a tus datos.",ko:"암호화 알고리즘을 변경하면 이전에 다른 알고리즘으로 암호화된 데이터에는 접근할 수 없게 됩니다. 데이터에 계속 접근할 수 있도록 모든 기기가 동일한 알고리즘을 사용하도록 설정해 주세요.","zh-tw":"變更加密演算法後,先前以其他演算法加密的資料將無法再存取。請確認所有裝置都設定為使用相同的演算法,以維持對資料的存取能力。"},"Changing this setting requires migrating existing data (a bit time may be taken) and restarting Obsidian. Please make sure to back up your data before proceeding.":{def:"Changing this setting requires migrating existing data (a bit time may be taken) and restarting Obsidian. Please make sure to back up your data before proceeding.",es:"Cambiar este ajuste requiere migrar los datos existentes (puede tardar un poco) y reiniciar Obsidian. Asegúrate de hacer una copia de seguridad de tus datos antes de continuar.",ko:"이 설정을 변경하려면 기존 데이터를 마이그레이션하고(시간이 다소 걸릴 수 있습니다) Obsidian을 재시작해야 합니다. 진행하기 전에 반드시 데이터를 백업해 주세요.","zh-tw":"變更此設定需要遷移現有資料(可能需要一些時間),並重新啟動 Obsidian。請務必先備份資料再繼續。"},Check:{def:"Check",es:"Comprobar",fr:"Vérifier",he:"בדוק",ko:"확인",ru:"Проверить",zh:"立即检查","zh-tw":"檢查"},"Check and convert non-path-obfuscated files":{def:"Check and convert non-path-obfuscated files",es:"Comprobar y convertir archivos sin ofuscación de ruta",ja:"パス難読化されていないファイルを確認して変換",ko:"경로 난독화되지 않은 파일 검사 및 변환",ru:"Проверить и преобразовать файлы без обфускации пути",zh:"检查并转换未进行路径混淆的文件","zh-tw":"檢查並轉換未進行路徑混淆的檔案"},"Check for documents that have not been converted to path-obfuscated IDs and convert them if necessary.":{def:"Check for documents that have not been converted to path-obfuscated IDs and convert them if necessary.",es:"Comprueba los documentos que aún no se hayan convertido a identificadores con ruta ofuscada y conviértelos si es necesario.",ja:"まだパス難読化 ID に変換されていないドキュメントを確認し、必要に応じて変換します。",ko:"아직 경로 난독화 ID로 변환되지 않은 문서를 확인하고 필요하면 변환합니다.",ru:"Проверяет документы, которые ещё не были преобразованы в path-obfuscated ID, и при необходимости преобразует их.",zh:"检查尚未转换为路径混淆 ID 的文档,并在需要时将其转换。","zh-tw":"檢查尚未轉換為路徑混淆 ID 的文件,並在需要時進行轉換。"},"Checking connection... Please wait.":{def:"Checking connection... Please wait.",es:"Comprobando la conexión... Espera un momento.",ko:"연결을 확인하는 중입니다... 잠시만 기다려 주세요.","zh-tw":"正在檢查連線⋯ 請稍候。"},Chunks:{def:"Chunks",es:"Fragmentos (chunks)",ko:"청크","zh-tw":"Chunks"},Close:{def:"Close",es:"Cerrar",ko:"닫기","zh-tw":"關閉"},"Close & Disconnect":{def:"Close & Disconnect",es:"Cerrar y desconectar",ko:"닫고 연결 끊기","zh-tw":"關閉並斷線"},"Close this dialog":{def:"Close this dialog",es:"Cerrar este diálogo",ko:"이 대화 상자 닫기","zh-tw":"關閉此對話框"},"Closed:":{def:"Closed:",es:"Cerradas:",ko:"종료됨:","zh-tw":"已關閉:"},"cmdConfigSync.showCustomizationSync":{def:"Show Customization sync",es:"Mostrar sincronización de personalización",fr:"Afficher la synchronisation de personnalisation",he:"הצג סנכרון התאמה אישית",ja:"カスタマイズ同期を表示",ko:"사용자 설정 동기화 표시",ru:"Показать синхронизацию настроек",zh:"显示自定义同步","zh-tw":"顯示自訂同步"},"Comma separated `.gitignore, .dockerignore`":{def:"Comma separated `.gitignore, .dockerignore`",es:"Separados por comas: `.gitignore, .dockerignore`",fr:"Séparés par des virgules `.gitignore, .dockerignore`",he:"רשימה מופרדת בפסיקים `.gitignore, .dockerignore`",ja:"カンマ区切り `.gitignore, .dockerignore`",ko:"쉼표로 구분된 `.gitignore, .dockerignore`",ru:"Через запятую `.gitignore, .dockerignore`",zh:"用逗号分隔,例如 `.gitignore, .dockerignore`","zh-tw":"以逗號分隔,例如 `.gitignore, .dockerignore`"},Command:{def:"Command",es:"Comando",ko:"명령","zh-tw":"命令"},Communicating:{def:"Communicating",es:"Comunicando",ko:"통신 중","zh-tw":"通訊中"},"Compaction in progress on remote database...":{def:"Compaction in progress on remote database...",es:"Compactación en curso en la base de datos remota...",ja:"リモートデータベースでコンパクションを実行中です...",ko:"원격 데이터베이스에서 압축 정리를 진행 중입니다...",ru:"Выполняется компакция удалённой базы данных...",zh:"正在远程数据库上执行压缩...","zh-tw":"正在遠端資料庫上執行壓縮⋯"},"Compaction on remote database completed successfully.":{def:"Compaction on remote database completed successfully.",es:"La compactación de la base de datos remota se ha completado correctamente.",ja:"リモートデータベースでのコンパクションが正常に完了しました。",ko:"원격 데이터베이스 압축 정리가 성공적으로 완료되었습니다.",ru:"Компакция удалённой базы данных успешно завершена.",zh:"远程数据库压缩已成功完成。","zh-tw":"遠端資料庫壓縮已成功完成。"},"Compaction on remote database failed.":{def:"Compaction on remote database failed.",es:"La compactación de la base de datos remota ha fallado.",ja:"リモートデータベースでのコンパクションに失敗しました。",ko:"원격 데이터베이스 압축 정리에 실패했습니다.",ru:"Компакция удалённой базы данных завершилась ошибкой.",zh:"远程数据库压缩失败。","zh-tw":"遠端資料庫壓縮失敗。"},"Compaction on remote database timed out.":{def:"Compaction on remote database timed out.",es:"La compactación de la base de datos remota ha superado el tiempo de espera.",ja:"リモートデータベースでのコンパクションがタイムアウトしました。",ko:"원격 데이터베이스 압축 정리 시간이 초과되었습니다.",ru:"Время ожидания компакции удалённой базы данных истекло.",zh:"远程数据库压缩超时。","zh-tw":"遠端資料庫壓縮逾時。"},"Compare file":{def:"Compare file",es:"Comparar archivo",ko:"파일 비교","zh-tw":"比較檔案"},"Compare the content of files between on local database and storage. If not matched, you will be asked which one you want to keep.":{def:"Compare the content of files between on local database and storage. If not matched, you will be asked which one you want to keep.",es:"Compara el contenido de los archivos entre la base de datos local y el almacenamiento. Si no coinciden, se te preguntará cuál deseas conservar.",ja:"ローカルデータベースとストレージ上のファイル内容を比較します。一致しない場合は、どちらを残すか選択できます。",ko:"로컬 데이터베이스와 저장소 간의 파일 내용을 비교합니다. 일치하지 않으면 어떤 쪽을 유지할지 묻게 됩니다.",ru:"Сравнивает содержимое файлов между локальной базой данных и хранилищем. Если они не совпадут, вам предложат выбрать, какую версию сохранить.",zh:"比较本地数据库与存储中的文件内容;如果不一致,你将被询问要保留哪一份。","zh-tw":"比較本機資料庫與儲存空間中的檔案內容;若不一致,系統會詢問你要保留哪一份。"},"Compatibility (Conflict Behaviour)":{def:"Compatibility (Conflict Behaviour)",es:"Compatibilidad (comportamiento de conflictos)",ja:"互換性(競合時の挙動)",ko:"호환성 (충돌 동작)",ru:"Совместимость (поведение при конфликтах)",zh:"兼容性(冲突行为)","zh-tw":"相容性(衝突行為)"},"Compatibility (Database structure)":{def:"Compatibility (Database structure)",es:"Compatibilidad (estructura de la base de datos)",ja:"互換性(データベース構造)",ko:"호환성 (데이터베이스 구조)",ru:"Совместимость (структура базы данных)",zh:"兼容性(数据库结构)","zh-tw":"相容性(資料庫結構)"},"Compatibility (Internal API Usage)":{def:"Compatibility (Internal API Usage)",es:"Compatibilidad (uso de la API interna)",ja:"互換性(内部 API の利用)",ko:"호환성 (내부 API 사용)",ru:"Совместимость (использование внутреннего API)",zh:"兼容性(内部 API 使用)","zh-tw":"相容性(內部 API 使用)"},"Compatibility (Metadata)":{def:"Compatibility (Metadata)",es:"Compatibilidad (metadatos)",ja:"互換性(メタデータ)",ko:"호환성 (메타데이터)",ru:"Совместимость (метаданные)",zh:"兼容性(元数据)","zh-tw":"相容性(中繼資料)"},"Compatibility (Remote Database)":{def:"Compatibility (Remote Database)",es:"Compatibilidad (base de datos remota)",ja:"互換性(リモートデータベース)",ko:"호환성 (원격 데이터베이스)",ru:"Совместимость (удалённая база данных)",zh:"兼容性(远端数据库)","zh-tw":"相容性(遠端資料庫)"},"Compatibility (Trouble addressed)":{def:"Compatibility (Trouble addressed)",es:"Compatibilidad (problemas corregidos)",ja:"互換性(対処済みの問題)",ko:"호환성 (문제 대응)",ru:"Совместимость (исправленные проблемы)",zh:"兼容性(问题修复)","zh-tw":"相容性(問題修復)"},"Compute revisions for chunks":{def:"Compute revisions for chunks",es:"Calcular revisiones para los chunks",fr:"Calculer les révisions pour les fragments",he:"חשב גרסאות לנתחים",ja:"チャンクの修正(リビジョン)を計算",ko:"청크에 대한 리비전 계산",ru:"Вычислять ревизии для чанков",zh:"为 chunks 计算修订版本(以前的行为)","zh-tw":"為 chunks 計算修訂版本(舊有行為)"},Configuration:{def:"Configuration",es:"Configuración",ko:"구성","zh-tw":"設定"},"Configuration Encryption":{def:"Configuration Encryption",es:"Cifrado de configuración",ja:"設定の暗号化",ko:"구성 암호화",ru:"Шифрование конфигурации",zh:"配置加密","zh-tw":"設定加密"},Configure:{def:"Configure",es:"Configurar",ja:"設定",ko:"설정",ru:"Настроить",zh:"配置","zh-tw":"設定"},"Configure And Change Remote":{def:"Configure And Change Remote",es:"Configurar y cambiar remoto",ja:"リモートを設定して切り替える",ko:"원격 구성 및 변경",ru:"Настроить и переключить удалённое хранилище",zh:"配置并切换远端","zh-tw":"設定並切換遠端"},"Configure E2EE":{def:"Configure E2EE",es:"Configurar E2EE",ja:"E2EE を設定",ko:"E2EE 구성",ru:"Настроить сквозное шифрование",zh:"配置 E2EE","zh-tw":"設定 E2EE"},"Configure Remote":{def:"Configure Remote",es:"Configurar remoto",ja:"リモートを設定",ko:"원격 구성",ru:"Настроить удалённое хранилище",zh:"配置远端","zh-tw":"設定遠端"},"Configure the same server information as your other devices again, manually, very advanced users only.":{def:"Configure the same server information as your other devices again, manually, very advanced users only.",es:"Configure manualmente la misma información del servidor que en sus otros dispositivos. Solo para usuarios muy avanzados。",ja:"他の端末と同じサーバー情報を手動で再入力します。上級者向けの方法です。",ko:"다른 기기와 동일한 서버 정보를 다시 직접 입력합니다. 숙련된 사용자 전용입니다.",ru:"Снова вручную укажите те же параметры сервера, что и на других устройствах. Только для очень опытных пользователей。",zh:"手动重新输入与你其他设备相同的服务器信息。仅适合高级用户。","zh-tw":"手動重新輸入與其他裝置相同的伺服器資訊。僅適合進階使用者。"},Connect:{def:"Connect",es:"Conectar",ko:"연결","zh-tw":"連線"},"Connected to Signaling Server (as Peer ID: ${peerId})":{def:"Connected to Signaling Server (as Peer ID: ${peerId})",es:"Conectado al servidor de señalización (como ID de par: ${peerId})",ko:"시그널링 서버에 연결되었습니다 (피어 ID: ${peerId})","zh-tw":"已連線到訊號伺服器(Peer ID${peerId}"},"Connected:":{def:"Connected:",es:"Conectadas:",ko:"연결됨:","zh-tw":"已連線:"},"Connection Method":{def:"Connection Method",es:"Método de conexión",ja:"接続方法",ko:"연결 방법",ru:"Способ подключения",zh:"连接方式","zh-tw":"連線方式"},"Connection Settings":{def:"Connection Settings",es:"Ajustes de conexión",ko:"연결 설정","zh-tw":"連線設定"},"Connection:":{def:"Connection:",es:"Conexión:",ko:"연결:","zh-tw":"連線:"},"Continue anyway":{def:"Continue anyway",es:"Continuar de todos modos",ko:"무시하고 계속","zh-tw":"仍要繼續"},"Continue to CouchDB setup":{def:"Continue to CouchDB setup",es:"Continuar con la configuración de CouchDB",ja:"CouchDB 設定へ進む",ko:"CouchDB 설정으로 계속",ru:"Перейти к настройке CouchDB",zh:"继续进行 CouchDB 设置","zh-tw":"繼續進行 CouchDB 設定"},"Continue to Peer-to-Peer only setup":{def:"Continue to Peer-to-Peer only setup",es:"Continuar con la configuración solo Peer-to-Peer",ja:"Peer-to-Peer 専用設定へ進む",ko:"Peer-to-Peer 전용 설정으로 계속",ru:"Перейти к настройке только Peer-to-Peer",zh:"继续进行仅 Peer-to-Peer 设置","zh-tw":"繼續進行僅 Peer-to-Peer 設定"},"Continue to S3/MinIO/R2 setup":{def:"Continue to S3/MinIO/R2 setup",es:"Continuar con la configuración de S3/MinIO/R2",ja:"S3/MinIO/R2 設定へ進む",ko:"S3/MinIO/R2 설정으로 계속",ru:"Перейти к настройке S3/MinIO/R2",zh:"继续进行 S3/MinIO/R2 设置","zh-tw":"繼續進行 S3/MinIO/R2 設定"},Copy:{def:"Copy",es:"Copiar",ja:"コピー",ko:"복사",ru:"Копировать",zh:"复制","zh-tw":"複製"},"Copy Report to clipboard":{def:"Copy Report to clipboard",es:"Copiar el informe al portapapeles",fr:"Copier le rapport dans le presse-papiers",he:'העתק דו"ח ללוח',ja:"レポートをクリップボードにコピー",ko:"보고서를 클립보드에 복사",ru:"Копировать отчёт в буфер обмена",zh:"将报告复制到剪贴板","zh-tw":"將報告複製到剪貼簿"},"CouchDB Configuration":{def:"CouchDB Configuration",es:"Configuración de CouchDB",ko:"CouchDB 구성","zh-tw":"CouchDB 設定"},"CouchDB Connection Tweak":{def:"CouchDB Connection Tweak",es:"Ajustes de conexión de CouchDB",ja:"CouchDB 接続の調整",ko:"CouchDB 연결 조정",ru:"Настройки подключения CouchDB",zh:"CouchDB 连接调优","zh-tw":"CouchDB 連線調校"},"Create P2P remote":{def:"Create P2P remote",es:"Crear remoto P2P",ko:"P2P 원격 만들기","zh-tw":"建立 P2P 遠端"},"Cross-platform":{def:"Cross-platform",es:"Multiplataforma",ja:"クロスプラットフォーム",ko:"크로스 플랫폼",ru:"Кроссплатформенные",zh:"跨平台","zh-tw":"跨平台"},"Current adapter: {adapter}":{def:"Current adapter: {adapter}",es:"Adaptador actual: {adapter}",ja:"現在のアダプター: {adapter}",ko:"현재 어댑터: {adapter}",ru:"Текущий адаптер: {adapter}",zh:"当前适配器:{adapter}","zh-tw":"目前的轉接器:{adapter}"},"Custom Headers":{def:"Custom Headers",es:"Encabezados personalizados",ko:"사용자 지정 헤더","zh-tw":"自訂標頭"},"Customization Sync":{def:"Customization Sync",es:"Sincronización de personalización",ja:"カスタマイズ同期",ko:"사용자 설정 동기화",ru:"Синхронизация настроек",zh:"自定义同步","zh-tw":"自訂同步"},"Customization Sync (Beta3)":{def:"Customization Sync (Beta3)",es:"Sincronización de personalización (Beta3)",ja:"カスタマイズ同期 (Beta3)",ko:"사용자 설정 동기화 (Beta3)",ru:"Синхронизация настроек (Beta3)",zh:"自定义同步(Beta3","zh-tw":"自訂同步(Beta3"},"Data Compression":{def:"Data Compression",es:"Compresión de datos",fr:"Compression des données",he:"דחיסת נתונים",ja:"データ圧縮",ko:"데이터 압축",ru:"Сжатие данных",zh:"数据压缩","zh-tw":"資料壓縮"},"Data to Copy":{def:"Data to Copy",es:"Datos a copiar",ko:"복사할 데이터","zh-tw":"要複製的資料"},"Database -> Storage":{def:"Database -> Storage",es:"Base de datos -> Almacenamiento",ko:"데이터베이스 -> 스토리지","zh-tw":"資料庫 -> 儲存空間"},"Database Adapter":{def:"Database Adapter",es:"Adaptador de base de datos",ja:"データベースアダプター",ko:"데이터베이스 어댑터",ru:"Адаптер базы данных",zh:"数据库适配器","zh-tw":"資料庫轉接器"},"Database Name":{def:"Database Name",es:"Nombre de la base de datos",fr:"Nom de la base de données",he:"שם מסד נתונים",ja:"データベース名",ko:"데이터베이스 이름",ru:"Имя базы данных",zh:"数据库名称","zh-tw":"資料庫名稱"},"Database suffix":{def:"Database suffix",es:"Sufijo de base de datos",fr:"Suffixe de la base de données",he:"סיומת מסד נתונים",ja:"データベースの接尾辞(suffix)",ko:"데이터베이스 접미사",ru:"Суффикс базы данных",zh:"数据库后缀","zh-tw":"資料庫後綴"},Date:{def:"Date",es:"Fecha",ko:"날짜","zh-tw":"日期"},Default:{def:"Default",es:"Predeterminado",ja:"デフォルト",ko:"기본값",ru:"По умолчанию",zh:"默认","zh-tw":"預設"},"Delay conflict resolution of inactive files":{def:"Delay conflict resolution of inactive files",es:"Retrasar resolución de conflictos en archivos inactivos",fr:"Différer la résolution des conflits pour les fichiers inactifs",he:"עכב פתרון קונפליקטים לקבצים לא פעילים",ja:"非アクティブなファイルは、競合解決を先送りする",ko:"비활성 파일의 충돌 해결 지연",ru:"Отложить разрешение конфликтов для неактивных файлов",zh:"推迟解决不活动文件","zh-tw":"延後處理非活動檔案的衝突"},"Delay merge conflict prompt for inactive files.":{def:"Delay merge conflict prompt for inactive files.",es:"Retrasar aviso de fusión para archivos inactivos",fr:"Différer l'invite de conflit de fusion pour les fichiers inactifs.",he:"עכב הצגת בקשת מיזוג לקבצים לא פעילים.",ja:"非アクティブなファイルの競合解決のプロンプトの表示を遅延させる",ko:"비활성 파일의 병합 충돌 프롬프트 지연.",ru:"Отложить запрос конфликта слияния для неактивных файлов.",zh:"推迟手动解决不活动文件","zh-tw":"延後顯示非活動檔案的合併衝突提示。"},Delete:{def:"Delete",es:"Eliminar",ja:"削除",ko:"삭제",ru:"Удалить",zh:"删除","zh-tw":"刪除"},"Delete all customization sync data":{def:"Delete all customization sync data",es:"Eliminar todos los datos de sincronización de personalización",ja:"カスタマイズ同期データをすべて削除",ko:"모든 사용자 설정 동기화 데이터 삭제",ru:"Удалить все данные синхронизации настроек",zh:"删除所有自定义同步数据","zh-tw":"刪除所有自訂同步資料"},"Delete all data on the remote server.":{def:"Delete all data on the remote server.",es:"Eliminar todos los datos del servidor remoto.",ja:"リモートサーバー上のすべてのデータを削除します。",ko:"원격 서버의 모든 데이터를 삭제합니다.",ru:"Удалить все данные на удалённом сервере.",zh:"删除远端服务器上的所有数据。","zh-tw":"刪除遠端伺服器上的所有資料。"},"Delete All of":{def:"Delete All of",es:"Eliminar todo de",ko:"모두 삭제할 대상","zh-tw":"刪除全部"},"Delete local database to reset or uninstall Self-hosted LiveSync":{def:"Delete local database to reset or uninstall Self-hosted LiveSync",es:"Eliminar la base de datos local para restablecer o desinstalar Self-hosted LiveSync",ja:"Self-hosted LiveSync をリセットまたはアンインストールするため、ローカルデータベースを削除",ko:"Self-hosted LiveSync를 초기화하거나 제거하기 위해 로컬 데이터베이스를 삭제",ru:"Удалить локальную базу данных, чтобы сбросить или удалить Self-hosted LiveSync",zh:"删除本地数据库以重置或卸载 Self-hosted LiveSync","zh-tw":"刪除本機資料庫以重設或解除安裝 Self-hosted LiveSync"},"Delete old metadata of deleted files on start-up":{def:"Delete old metadata of deleted files on start-up",es:"Borrar metadatos viejos al iniciar",fr:"Supprimer les anciennes métadonnées des fichiers effacés au démarrage",he:"מחק מטה-נתונים ישנים של קבצים שנמחקו בעת הפעלה",ja:"削除済みデータのメタデータをクリーンナップする",ko:"시작 시 삭제된 파일의 오래된 메타데이터 삭제",ru:"Удалять старые метаданные удалённых файлов при запуске",zh:"启动时删除已删除文件的旧元数据","zh-tw":"啟動時刪除已刪除檔案的舊中繼資料"},"Delete Remote Configuration":{def:"Delete Remote Configuration",es:"Eliminar configuración remota",ja:"リモート設定を削除",ko:"원격 구성 삭제",ru:"Удалить удалённую конфигурацию",zh:"删除远端配置","zh-tw":"刪除遠端設定"},"Delete remote configuration '{name}'?":{def:"Delete remote configuration '{name}'?",es:"¿Eliminar la configuración remota '{name}'?",ja:"リモート設定 '{name}' を削除しますか?",ko:"'{name}' 원격 구성을 삭제할까요?",ru:"Удалить удалённую конфигурацию '{name}'?",zh:"要删除远端配置“{name}”吗?","zh-tw":"要刪除遠端設定「{name}」嗎?"},"Delete remote configuration '${name}'?":{def:"Delete remote configuration '${name}'?",es:"¿Eliminar la configuración remota «${name}»?",ko:"'${name}' 원격 구성을 삭제할까요?","zh-tw":"要刪除遠端設定「${name}」嗎?"},DENIED:{def:"DENIED",es:"DENEGADO",ko:"거부됨","zh-tw":"已拒絕"},"DENIED (in session)":{def:"DENIED (in session)",es:"DENEGADO (en esta sesión)",ko:"거부됨 (이 세션에서만)","zh-tw":"已拒絕(本次連線)"},Deny:{def:"Deny",es:"Denegar",ko:"거부","zh-tw":"拒絕"},"Deny in session":{def:"Deny in session",es:"Denegar en esta sesión",ko:"이 세션에서만 거부","zh-tw":"本次連線拒絕"},"Deny permanently":{def:"Deny permanently",es:"Denegar permanentemente",ko:"항상 거부","zh-tw":"永久拒絕"},"Deselect all":{def:"Deselect all",es:"Deseleccionar todo",ko:"선택 모두 해제","zh-tw":"全部取消選取"},desktop:{def:"desktop",es:"equipo de escritorio",ja:"デスクトップ",ko:"데스크톱",ru:"рабочий стол",zh:"桌面设备","zh-tw":"桌面裝置"},"Detected Peers":{def:"Detected Peers",es:"Pares detectados",ko:"감지된 피어","zh-tw":"偵測到的 Peer"},Developer:{def:"Developer",es:"Desarrollador",ja:"開発者",ko:"개발자",ru:"Разработчик",zh:"开发者","zh-tw":"開發者"},Device:{def:"Device",es:"Dispositivo",ja:"デバイス",ko:"기기",ru:"Устройство",zh:"设备","zh-tw":"裝置"},"device name":{def:"device name",es:"nombre del dispositivo",ko:"기기 이름","zh-tw":"裝置名稱"},"Device name":{def:"Device name",es:"Nombre del dispositivo",fr:"Nom de l'appareil",he:"שם מכשיר",ja:"デバイス名",ko:"기기 이름",ru:"Имя устройства",zh:"设备名称","zh-tw":"裝置名稱"},'Device name to identify the device. Please use shorter one for the stable peer detection, i.e., "iphone-16" or "macbook-2021".':{def:'Device name to identify the device. Please use shorter one for the stable peer detection, i.e., "iphone-16" or "macbook-2021".',es:"Nombre para identificar el dispositivo. Usa uno corto para que la detección de pares sea estable, por ejemplo «iphone-16» o «macbook-2021».",ko:'기기를 식별하기 위한 기기 이름입니다. 피어를 안정적으로 감지할 수 있도록 "iphone-16"이나 "macbook-2021"처럼 짧은 이름을 사용해 주세요.',"zh-tw":"用來識別此裝置的裝置名稱。建議使用較短的名稱以穩定偵測 Peer,例如「iphone-16」或「macbook-2021」。"},"Device Peer ID":{def:"Device Peer ID",es:"ID de par del dispositivo",ko:"기기 피어 ID","zh-tw":"裝置 Peer ID"},"Device Setup Method":{def:"Device Setup Method",es:"Método de configuración del dispositivo",ja:"端末の設定方法",ko:"기기 설정 방법",ru:"Способ настройки устройства",zh:"设备设置方式","zh-tw":"裝置設定方式"},"Devices:":{def:"Devices:",es:"Dispositivos:",ko:"기기:","zh-tw":"裝置:"},"Diagnostic RTCPeerConnection is enabled":{def:"Diagnostic RTCPeerConnection is enabled",es:"El RTCPeerConnection de diagnóstico está habilitado",ko:"진단용 RTCPeerConnection이 활성화되어 있습니다","zh-tw":"已啟用 RTCPeerConnection 診斷"},"dialog.yourLanguageAvailable":{def:"Self-hosted LiveSync had translations for your language, so the %{Display language} setting was enabled.\n\nNote: Not all messages are translated. We are waiting for your contributions!\nNote 2: If you create an Issue, **please revert to Default** and then take screenshots, messages and logs. This can be done in the setting dialogue.\nMay you find it easy to use!",es:"Self-hosted LiveSync tenía traducciones para tu idioma, así que se ha activado el ajuste %{Display language}.\n\nNota: no todos los mensajes están traducidos. ¡Esperamos tus contribuciones!\nNota 2: si abres una incidencia, **vuelve antes a Predeterminado** y luego haz las capturas de pantalla y recoge los mensajes y registros. Puedes hacerlo desde el diálogo de ajustes.\n¡Que lo disfrutes!",fr:"Self-hosted LiveSync dispose d'une traduction pour votre langue, le paramètre %{Display language} a donc été activé.\n\nNote : Tous les messages ne sont pas traduits. Nous attendons vos contributions !\nNote 2 : Si vous créez un ticket, **veuillez revenir à Par défaut** puis prendre des captures d'écran, messages et journaux. Cela peut être fait dans la boîte de dialogue des paramètres.\nBonne utilisation !",he:"ל-Self-hosted LiveSync יש תרגום לשפתך, ולכן הגדרת %{Display language} הופעלה.\n\nהערה: לא כל ההודעות מתורגמות. אנחנו ממתינים לתרומותיך!\nהערה 2: אם אתה פותח Issue, **אנא חזור ל-%{lang-def}** ואז צלם צילומי מסך, הודעות ויומנים. ניתן לעשות זאת בדיאלוג ההגדרות.\nנקווה שתמצא/י את הפלאגין נוח לשימוש!",ja:"Self-hosted LiveSync に設定されている言語の翻訳がありましたので、インターフェースの表示言語が適用されました。\n\n注意: 全てのメッセージは翻訳されていません。あなたの貢献をお待ちしています!\nGithubにIssueを作成する際には、 インターフェースの表示言語 を一旦 Default に戻してから、スクショやメッセージ、ログを収集してください。これは設定から変更できます。\n\n便利に使用できれば幸いです。",ko:"Self-hosted LiveSync가 사용 중인 언어의 번역을 제공하므로 표시 언어 설정이 활성화되었습니다.\n\n참고: 모든 메시지가 번역되어 있지는 않습니다. 여러분의 기여를 기다리고 있습니다!\n참고 2: 이슈를 등록할 때는 **기본값 로 되돌린 뒤** 스크린샷과 메시지, 로그를 첨부해 주세요. 설정 대화 상자에서 되돌릴 수 있습니다.\n편하게 사용하실 수 있기를 바랍니다!",ru:"Self-hosted LiveSync имеет переводы для вашего языка, поэтому была включена настройка языка Display language.\n\nПримечание: Не все сообщения переведены. Мы ждём ваших предложений!\nПримечание 2: При создании Issue, пожалуйста, вернитесь к lang-def, затем сделайте скриншоты, сообщения и логи. Это можно сделать в настройках.\nНадеемся, вам будет удобно использовать!",zh:"Self-hosted LiveSync已提供您语言的翻译,因此启用了%{Display language}\n\n注意:并非所有消息都已翻译。我们期待您的贡献!\n注意 2:若您创建问题报告, **请切换回Default** ,然后截取屏幕截图、消息和日志,此操作可在设置对话框中完成\n愿您使用顺心!","zh-tw":"Self-hosted LiveSync 已提供你目前語言的翻譯,因此已啟用顯示語言設定。\n\n注意:並非所有訊息都已完成翻譯,歡迎協助補充!\n注意 2:如果你要回報問題,請先切回預設語言,再附上截圖、訊息與日誌。\n\n希望你使用愉快!"},"dialog.yourLanguageAvailable.btnRevertToDefault":{def:"Keep Default",es:"Mantener Predeterminado",fr:"Conserver Par défaut",he:"השאר %{lang-def}",ja:"Keep Default",ko:"기본값 유지",ru:"Оставить lang-def",zh:"保持Default","zh-tw":"恢復為預設語言"},"dialog.yourLanguageAvailable.Title":{def:" Translation is available!",es:" ¡Hay traducción disponible!",fr:" Une traduction est disponible !",he:" תרגום זמין!",ja:"翻訳が利用可能です!",ko:" 번역을 사용할 수 있습니다!",ru:"Доступен перевод!",zh:" 翻译可用!","zh-tw":"已提供你的語言翻譯!"},Diff:{def:"Diff",es:"Diferencias",ko:"차이","zh-tw":"差異"},Different:{def:"Different",es:"Distinto",ko:"다름","zh-tw":"不同"},"Disables all synchronization and restart.":{def:"Disables all synchronization and restart.",es:"Desactiva toda la sincronización y reinicia la aplicación.",ja:"すべての同期を無効にして再起動します。",ko:"모든 동기화를 비활성화하고 재시작합니다.",ru:"Отключает всю синхронизацию и перезапускает приложение.",zh:"禁用所有同步并重新启动。","zh-tw":"停用所有同步並重新啟動。"},"Disables logging, only shows notifications. Please disable if you report an issue.":{def:"Disables logging, only shows notifications. Please disable if you report an issue.",es:"Desactiva registros, solo muestra notificaciones. Desactívelo si reporta un problema.",fr:"Désactive la journalisation, n'affiche que les notifications. Veuillez désactiver si vous signalez un problème.",he:"מכבה רישום יומן, מציג התראות בלבד. אנא כבה אם אתה מדווח על בעיה.",ja:"ログを無効にし、通知のみを表示します。Issueを報告する場合は無効にしてください。",ko:"로깅을 비활성화하고 알림만 표시합니다. 문제를 신고하는 경우 비활성화해 주세요.",ru:"Отключает логирование, показывает только уведомления. Пожалуйста, отключите при сообщении о проблеме.",zh:"禁用日志记录,仅显示通知。如果您报告问题,请禁用此选项","zh-tw":"停用日誌記錄,只顯示通知。如果你要回報問題,請關閉此選項。"},Disconnect:{def:"Disconnect",es:"Desconectar",ko:"연결 끊기","zh-tw":"斷線"},Dismiss:{def:"Dismiss",es:"Descartar",ko:"닫기","zh-tw":"關閉"},"Display Language":{def:"Display Language",es:"Idioma de visualización",fr:"Langue d'affichage",he:"שפת תצוגה",ja:"インターフェースの表示言語",ko:"표시 언어",ru:"Язык интерфейса",zh:"显示语言","zh-tw":"顯示語言"},"Display name":{def:"Display name",es:"Nombre para mostrar",ja:"表示名",ko:"표시 이름",ru:"Отображаемое имя",zh:"显示名称","zh-tw":"顯示名稱"},"Do not check configuration mismatch before replication":{def:"Do not check configuration mismatch before replication",es:"No verificar incompatibilidades antes de replicar",fr:"Ne pas vérifier les incohérences de configuration avant la réplication",he:"אל תבדוק אי-התאמה בתצורה לפני שכפול",ja:"サーバーから同期する前に設定の不一致を確認しない",ko:"복제 전 구성 불일치 확인 안 함",ru:"Не проверять несовпадение конфигурации перед репликацией",zh:"在复制前不检查配置不匹配","zh-tw":"複寫前不檢查設定是否不一致"},"Do not keep metadata of deleted files.":{def:"Do not keep metadata of deleted files.",es:"No conservar metadatos de archivos borrados",fr:"Ne pas conserver les métadonnées des fichiers supprimés.",he:"אל תשמור מטה-נתונים של קבצים שנמחקו.",ja:"削除済みファイルのメタデータを保持しない",ko:"삭제된 파일의 메타데이터를 보관하지 않습니다.",ru:"Не хранить метаданные удалённых файлов.",zh:"不保留已删除文件的元数据 ","zh-tw":"不保留已刪除檔案的中繼資料。"},"Do not split chunks in the background":{def:"Do not split chunks in the background",es:"No dividir chunks en segundo plano",fr:"Ne pas fragmenter en arrière-plan",he:"אל תפצל נתחים ברקע",ja:"バックグラウンドでチャンクを分割しない",ko:"백그라운드에서 청크 분할 안 함",ru:"Не разделять чанки в фоновом режиме",zh:"不在后台分割 chunks","zh-tw":"不在背景分割 chunks"},"Do not use internal API":{def:"Do not use internal API",es:"No usar API interna",fr:"Ne pas utiliser l'API interne",he:"אל תשתמש ב-API פנימי",ja:"内部APIを使用しない",ko:"내부 API 사용 안 함",ru:"Не использовать внутренний API",zh:"不使用内部 API","zh-tw":"不使用內部 API"},"Doctor.Button.DismissThisVersion":{def:"No, and do not ask again until the next release",es:"No, y no volver a preguntar hasta la próxima versión",fr:"Non, et ne plus demander jusqu'à la prochaine version",he:"לא, ואל תשאל שוב עד לגרסה הבאה",ja:"いいえ、次のリリースまで再度確認しない",ko:"아니요, 다음 릴리스까지 다시 묻지 않음",ru:"Нет, и не спрашивать до следующего выпуска",zh:"拒绝,并且直到下个版本前不再询问","zh-tw":"不要,且到下個版本發布前都不要再問"},"Doctor.Button.Fix":{def:"Fix it",es:"Corregirlo",fr:"Corriger",he:"תקן",ja:"修正する",ko:"수정",ru:"Исправить",zh:"修复","zh-tw":"修正"},"Doctor.Button.FixButNoRebuild":{def:"Fix it but no rebuild",es:"Corregirlo, pero sin reconstruir",fr:"Corriger mais sans reconstruction",he:"תקן ללא בנייה מחדש",ja:"修正するが再構築はしない",ko:"수정하지만 재구축하지 않음",ru:"Исправить без перестроения",zh:"修复但不重建","zh-tw":"修正但不要重建"},"Doctor.Button.No":{def:"No",es:"No",fr:"Non",he:"לא",ja:"いいえ",ko:"아니요",ru:"Нет",zh:"拒绝","zh-tw":"否"},"Doctor.Button.Skip":{def:"Leave it as is",es:"Dejarlo como está",fr:"Laisser tel quel",he:"השאר כפי שהוא",ja:"そのままにする",ko:"그대로 두기",ru:"Оставить как есть",zh:"保持不变","zh-tw":"保持原樣"},"Doctor.Button.Yes":{def:"Yes",es:"Sí",fr:"Oui",he:"כן",ja:"はい",ko:"예",ru:"Да",zh:"确定","zh-tw":"是"},"Doctor.Dialogue.Main":{def:"Hi! Config Doctor has been activated because of ${activateReason}!\nAnd, unfortunately some configurations were detected as potential problems.\nPlease be assured. Let's solve them one by one.\n\nTo let you know ahead of time, we will ask you about the following items.\n\n${issues}\n\nShall we get started?",es:"¡Hola! El Doctor de configuración se ha activado por ${activateReason}.\nPor desgracia, se han detectado algunos ajustes como posibles problemas.\nTranquilo: los resolveremos uno a uno.\n\nPara que lo sepas de antemano, te preguntaremos por los siguientes puntos.\n\n${issues}\n\n¿Empezamos?",fr:"Bonjour ! Config Doctor a été activé en raison de ${activateReason} !\nEt, malheureusement, certaines configurations ont été détectées comme des problèmes potentiels.\nPas d'inquiétude. Résolvons-les un par un.\n\nPour information, nous allons vous interroger sur les éléments suivants.\n\n${issues}\n\nVoulez-vous commencer ?",he:"שלום! רופא התצורה הופעל בגלל ${activateReason}!\nולמרבה הצער, זוהו תצורות שעשויות להיות בעייתיות.\nהיה רגוע/ה. בואו נפתור אותן אחת אחת.\n\nלידיעתך מראש, נשאל אותך על הפריטים הבאים.\n\n${issues}\n\nהאם להתחיל?",ja:"こんにちは!${activateReason}のため、設定診断ツールが起動しました!\n残念ながら、いくつかの設定が潜在的な問題として検出されました。\nご安心ください。一つずつ解決していきましょう。\n\n事前にお知らせしますと、以下の項目についてお尋ねします。\n\n${issues}\n\n始めていいですか?",ko:"안녕하세요! ${activateReason}(으)로 인해 구성 진단 마법사가 실행되었습니다!\n아쉽게도 일부 구성에서 잠재적인 문제가 감지되었습니다.\n걱정하지 마세요. 하나씩 함께 해결해 보겠습니다.\n\n미리 알려드리자면, 다음 항목들에 대해 여쭤보겠습니다.\n\n${issues}\n\n시작할까요?",ru:"Привет! Диагностика настроек активирована из-за activateReason!\nК сожалению, некоторые настройки были обнаружены как потенциальные проблемы.\nНе волнуйтесь. Давайте решим их по очереди.\n\nСообщаем вам заранее, мы спросим о следующих пунктах.\n\nissues\n\nНачнём?",zh:"您好!配置医生已根据您的要求启动(感谢您)!!遗憾的是,检测到部分配置存在潜在问题。请放心,我们将逐一解决这些问题。\n\n提前告知您,我们将就以下事项进行确认:\n\n为数据块计算修订版本(此前行为)\n增强块大小\n\n我们开始处理吗?","zh-tw":"嗨!由於 ${activateReason},設定診斷已啟動!\n很遺憾,偵測到部分設定可能有問題。\n請放心,我們會逐一解決這些問題。\n\n先讓你知道,我們會就以下項目詢問你:\n\n${issues}\n\n要開始了嗎?"},"Doctor.Dialogue.MainFix":{def:"\n## ${name}\n\n| Current | Ideal |\n|:---:|:---:|\n| ${current} | ${ideal} |\n\n**Recommendation Level:** ${level}\n\n### Why this has been detected?\n\n${reason}\n\n${note}\n\nFix this to the ideal value?",es:"\n## ${name}\n\n| Actual | Ideal |\n|:---:|:---:|\n| ${current} | ${ideal} |\n\n**Nivel de recomendación:** ${level}\n\n### ¿Por qué se ha detectado?\n\n${reason}\n\n${note}\n\n¿Ajustarlo al valor ideal?",fr:"\n## ${name}\n\n| Actuel | Idéal |\n|:---:|:---:|\n| ${current} | ${ideal} |\n\n**Niveau de recommandation :** ${level}\n\n### Pourquoi ceci a-t-il été détecté ?\n\n${reason}\n\n${note}\n\nCorriger à la valeur idéale ?",he:"\n## ${name}\n\n| נוכחי | אידאלי |\n|:---:|:---:|\n| ${current} | ${ideal} |\n\n**רמת המלצה:** ${level}\n\n### מדוע זה זוהה?\n\n${reason}\n\n${note}\n\nלתקן לערך האידאלי?",ja:"\n## ${name}\n\n| 現在の値 | 理想値 |\n|:---:|:---:|\n| ${current} | ${ideal} |\n\n**推奨レベル:** ${level}\n\n### 診断理由?\n\n${reason}\n\n${note}\n\nこれを理想値に修正しますか?",ko:"\n## ${name}\n\n| 현재 값 | 이상적인 값 |\n|:---:|:---:|\n| ${current} | ${ideal} |\n\n**권장 수준:** ${level}\n\n### 왜 이것이 감지되었나요?\n\n${reason}\n\n${note}\n\n이상적인 값으로 수정할까요?",ru:"name\n\n| Текущее | Идеальное |\n|:---:|:---:|\n| current | ideal |\n\n**Уровень рекомендации:** level\n\n### Почему это было обнаружено?\n\nreason\n\nnote\n\nИсправить на идеальное значение?",zh:"\n## ${name}\n\n| Current | Ideal |\n|:---:|:---:|\n| ${current} | ${ideal} |\n\n**Recommendation Level:** ${level}\n\n### Why this has been detected?\n\n${reason}\n\n${note}\n\nFix this to the ideal value?","zh-tw":"\n## ${name}\n\n| 目前值 | 建議值 |\n|:---:|:---:|\n| ${current} | ${ideal} |\n\n**建議等級:** ${level}\n\n### 為什麼會偵測到這個問題?\n\n${reason}\n\n${note}\n\n要將此項修正為建議值嗎?"},"Doctor.Dialogue.Title":{def:"Self-hosted LiveSync Config Doctor",es:"Doctor de configuración de Self-hosted LiveSync",fr:"Docteur Config Self-hosted LiveSync",he:"Self-hosted LiveSync Config Doctor",ja:"Self-hosted LiveSync 設定診断ツール",ko:"Self-hosted LiveSync 구성 진단 마법사",ru:"Диагностика Self-hosted LiveSync",zh:"Self-hosted LiveSync 配置诊断","zh-tw":"Self-hosted LiveSync 設定診斷"},"Doctor.Dialogue.TitleAlmostDone":{def:"Almost done!",es:"¡Casi hemos terminado!",fr:"Presque terminé !",he:"כמעט סיימנו!",ja:"あと少しです!",ko:"거의 완료되었습니다!",ru:"Почти готово!",zh:"全部完成!","zh-tw":"快完成了!"},"Doctor.Dialogue.TitleFix":{def:"Fix issue ${current}/${total}",es:"Corregir el problema ${current}/${total}",fr:"Corriger le problème ${current}/${total}",he:"תקן בעיה ${current}/${total}",ja:"問題の修正 ${current}/${total}",ko:"문제 해결 ${current}/${total}",ru:"Исправление проблемы current/total",zh:"修复问题 ${current}/${total}","zh-tw":"修正問題 ${current}/${total}"},"Doctor.Level.Must":{def:"Must",es:"Obligatorio",fr:"Obligatoire",he:"חובה",ja:"必須",ko:"필수",ru:"Обязательно",zh:"必须","zh-tw":"必須"},"Doctor.Level.Necessary":{def:"Necessary",es:"Necesario",fr:"Nécessaire",he:"נדרש",ja:"必要",ko:"필요",ru:"Необходимо",zh:"必要","zh-tw":"必要"},"Doctor.Level.Optional":{def:"Optional",es:"Opcional",fr:"Optionnel",he:"אופציונלי",ja:"任意",ko:"선택사항",ru:"Опционально",zh:"可选","zh-tw":"可選"},"Doctor.Level.Recommended":{def:"Recommended",es:"Recomendado",fr:"Recommandé",he:"מומלץ",ja:"推奨",ko:"권장",ru:"Рекомендуется",zh:"推荐","zh-tw":"建議"},"Doctor.Message.NoIssues":{def:"No issues detected!",es:"¡No se ha detectado ningún problema!",fr:"Aucun problème détecté !",he:"לא זוהו בעיות!",ja:"問題は検出されませんでした!",ko:"문제가 감지되지 않았습니다!",ru:"Проблем не обнаружено!",zh:"未发现问题!","zh-tw":"未偵測到任何問題!"},"Doctor.Message.RebuildLocalRequired":{def:"Attention! A local database rebuild is required to apply this!",es:"¡Atención! Hay que reconstruir la base de datos local para aplicar esto.",fr:"Attention ! Une reconstruction de la base locale est requise pour appliquer ceci !",he:"שים לב! נדרשת בנייה מחדש של מסד הנתונים המקומי כדי להחיל זאת!",ja:"注意!これを適用するにはローカルデータベースの再構築が必要です!",ko:"주의! 이를 적용하려면 로컬 데이터베이스 재구축이 필요합니다!",ru:"Внимание! Для применения требуется перестроение локальной базы данных!",zh:"注意!需要重建本地数据库以应用此项!","zh-tw":"請注意!套用此項需要重建本機資料庫!"},"Doctor.Message.RebuildRequired":{def:"Attention! A rebuild is required to apply this!",es:"¡Atención! Hay que reconstruir para aplicar esto.",fr:"Attention ! Une reconstruction est requise pour appliquer ceci !",he:"שים לב! נדרשת בנייה מחדש כדי להחיל זאת!",ja:"注意!これを適用するには再構築が必要です!",ko:"주의! 이를 적용하려면 재구축이 필요합니다!",ru:"Внимание! Для применения требуется перестроение!",zh:"注意!需要重建才能应用此项!","zh-tw":"請注意!套用此項需要重建!"},"Doctor.Message.SomeSkipped":{def:"We left some issues as is. Shall I ask you again on next startup?",es:"Hemos dejado algunos problemas sin resolver. ¿Quieres que te lo pregunte de nuevo en el próximo inicio?",fr:"Nous avons laissé certains problèmes en l'état. Dois-je vous demander à nouveau au prochain démarrage ?",he:"השארנו כמה בעיות כפי שהן. האם לשאול שוב בהפעלה הבאה?",ja:"いくつかの問題をそのままにしました。次回起動時に再度確認しますか?",ko:"일부 문제를 그대로 두었습니다. 다음 시작 시 다시 질문할까요?",ru:"Некоторые проблемы оставлены как есть. Спросить снова при следующем запуске?",zh:"我们将某些问题留给了以后处理。是否要在下次启动时再次询问您?","zh-tw":"有些問題我們先保持原樣。要在下次啟動時再次詢問你嗎?"},"Doctor.RULES.E2EE_V02500.REASON":{def:"The End-to-End Encryption has got now more robust and faster. Also because, the previous E2EE was found to be compromised in a re-conducted code review. It should be applied as soon as possible. Really apologises for your inconvenience. And, this setting is not forward compatible. All synchronised devices must be updated to v0.25.0 or higher. Rebuilds are not required and will be converted from the new transfer to the new format, However, it is recommended to rebuild whenever possible.",es:"El cifrado de extremo a extremo es ahora más robusto y más rápido. Además, una nueva revisión del código reveló que el E2EE anterior estaba comprometido, por lo que conviene aplicarlo cuanto antes. Lamentamos de veras las molestias. Este ajuste no es compatible con versiones anteriores: todos los dispositivos sincronizados deben actualizarse a la v0.25.0 o superior. No es necesario reconstruir (los datos se convertirán al nuevo formato durante la transferencia), pero se recomienda hacerlo siempre que sea posible.",fr:"Le chiffrement de bout en bout est désormais plus robuste et plus rapide. Aussi parce que le précédent E2EE s'est révélé compromis lors d'une nouvelle revue de code. Il doit être appliqué dès que possible. Nous nous excusons sincèrement pour la gêne occasionnée. Ce paramètre n'est pas compatible avec les versions antérieures. Tous les appareils synchronisés doivent être mis à jour en v0.25.0 ou supérieur. Les reconstructions ne sont pas requises et seront converties du nouveau transfert vers le nouveau format. Il est toutefois recommandé de reconstruire dans la mesure du possible.",he:"ההצפנה מקצה לקצה עודכנה לגרסה חזקה ומהירה יותר. בנוסף, בסקירת קוד שנערכה מחדש הוסבר שההצפנה הקודמת נפרצת. יש להחיל זאת בהקדם האפשרי. מתנצלים על אי הנוחות. שים לב שהגדרה זו אינה תואמת לאחור. כל המכשירים המסונכרנים חייבים להיות מעודכנים לגרסה 0.25.0 ומעלה. אין צורך בבנייה מחדש והנתונים יומרו בהדרגה לפורמט החדש, אך מומלץ לבנות מחדש בהזדמנות הראשונה.",ja:"エンドツーエンド暗号化がより堅牢で高速になりました。また、以前のE2EEは再コードレビューにより脆弱性が発見されました。できるだけ早く適用することをお勧めします。ご不便をおかけして申し訳ありません。また、この設定は下位互換性がありません。すべての同期デバイスをv0.25.0以降にアップデートする必要があります。再構築は必須ではなく、新しい転送から新しいフォーマットに変換されますが、可能な限り再構築をお勧めします。",ko:"종단 간 암호화가 더 견고하고 빨라졌습니다. 또한 다시 진행한 코드 검토에서 이전 E2EE에 취약점이 있는 것으로 확인되었기 때문에, 가능한 한 빨리 적용해 주시기 바랍니다. 불편을 드려 대단히 죄송합니다. 그리고 이 설정은 이전 버전과 호환되지 않습니다. 동기화 중인 모든 기기를 v0.25.0 이상으로 업데이트해야 합니다. 재구축은 필요하지 않으며 새로 전송되는 항목부터 새 형식으로 변환됩니다. 다만 가능하다면 재구축하시기를 권장합니다.",ru:"Сквозное шифрование стало более надёжным и быстрым. Предыдущее E2EE было скомпрометировано. Следует применить как можно скорее.",zh:"The End-to-End Encryption has got now more robust and faster. Also because, the previous E2EE was found to be compromised in a re-conducted code review. It should be applied as soon as possible. Really apologises for your inconvenience. And, this setting is not forward compatible. All synchronised devices must be updated to v0.25.0 or higher. Rebuilds are not required and will be converted from the new transfer to the new format, However, it is recommended to rebuild whenever possible.","zh-tw":"端對端加密現在變得更穩固也更快。此外,先前的 E2EE 在重新進行的程式碼審查中被發現有安全漏洞,應盡快套用此項修正。造成的不便由衷抱歉。另外,此設定不具向前相容性,所有同步的裝置都必須更新到 v0.25.0 或更新版本。不需要重建,資料會在下次傳輸時自動轉換為新格式;不過,若條件允許,仍建議進行重建。"},"Document History":{def:"Document History",es:"Historial del documento",ko:"문서 기록","zh-tw":"文件歷程"},Duplicate:{def:"Duplicate",es:"Duplicar",ja:"複製",ko:"복사본 만들기",ru:"Дублировать",zh:"复制","zh-tw":"複製"},"Duplicate remote":{def:"Duplicate remote",es:"Duplicar remoto",ja:"リモート設定を複製",ko:"원격 구성 복사",ru:"Дублировать удалённую конфигурацию",zh:"复制远端配置","zh-tw":"複製遠端設定"},"E2EE Configuration":{def:"E2EE Configuration",es:"Configuración de E2EE",ja:"E2EE 設定",ko:"E2EE 구성",ru:"Конфигурация сквозного шифрования",zh:"E2EE 配置","zh-tw":"E2EE 設定"},"Edge case addressing (Behaviour)":{def:"Edge case addressing (Behaviour)",es:"Tratamiento de casos límite (comportamiento)",ja:"特殊なケースへの対応(動作)",ko:"특수 상황 처리 (동작)",ru:"Обработка особых случаев (поведение)",zh:"边缘情况处理(行为)","zh-tw":"邊緣情況處理(行為)"},"Edge case addressing (Database)":{def:"Edge case addressing (Database)",es:"Tratamiento de casos límite (base de datos)",ja:"特殊なケースへの対応(データベース)",ko:"특수 상황 처리 (데이터베이스)",ru:"Обработка особых случаев (база данных)",zh:"边缘情况处理(数据库)","zh-tw":"邊緣情況處理(資料庫)"},"Edge case addressing (Processing)":{def:"Edge case addressing (Processing)",es:"Tratamiento de casos límite (procesamiento)",ja:"特殊なケースへの対応(処理)",ko:"특수 상황 처리 (처리)",ru:"Обработка особых случаев (обработка)",zh:"边缘情况处理(处理)","zh-tw":"邊緣情況處理(處理)"},"Emergency restart":{def:"Emergency restart",es:"Reinicio de emergencia",ja:"緊急再起動",ko:"긴급 재시작",ru:"Аварийный перезапуск",zh:"紧急重启","zh-tw":"緊急重新啟動"},"Enable advanced features":{def:"Enable advanced features",es:"Habilitar características avanzadas",fr:"Activer les fonctionnalités avancées",he:"הפעל תכונות מתקדמות",ja:"高度な機能を有効にする",ko:"고급 기능 활성화",ru:"Включить расширенные функции",zh:"启用高级功能","zh-tw":"啟用進階功能"},"Enable customization sync":{def:"Enable customization sync",es:"Habilitar sincronización de personalización",fr:"Activer la synchronisation de personnalisation",he:"הפעל סנכרון התאמה אישית",ja:"カスタマイズ同期を有効",ko:"사용자 설정 동기화 활성화",ru:"Включить синхронизацию настроек",zh:"启用自定义同步","zh-tw":"啟用自訂同步"},"Enable Developers' Debug Tools.":{def:"Enable Developers' Debug Tools.",es:"Habilitar herramientas de depuración",fr:"Activer les outils de débogage pour développeurs.",he:"הפעל כלי ניפוי באגים למפתחים.",ja:"開発者用デバッグツールを有効にする",ko:"개발자 디버그 도구 활성화",ru:"Включить инструменты разработчика.",zh:"启用开发者调试工具 ","zh-tw":"啟用開發者除錯工具。"},"Enable edge case treatment features":{def:"Enable edge case treatment features",es:"Habilitar manejo de casos límite",fr:"Activer les fonctionnalités pour cas particuliers",he:"הפעל תכונות לטיפול במקרי קצה",ja:"エッジケース対応機能を有効にする",ko:"특수 사례 처리 기능 활성화",ru:"Включить функции обработки граничных случаев",zh:"启用边缘情况处理功能","zh-tw":"啟用邊緣情況處理功能"},"Enable P2P Replicator":{def:"Enable P2P Replicator",es:"Habilitar el replicador P2P",ko:"P2P 복제기 활성화","zh-tw":"啟用 P2P 複寫器"},"Enable poweruser features":{def:"Enable poweruser features",es:"Habilitar funciones para usuarios avanzados",fr:"Activer les fonctionnalités pour utilisateurs avancés",he:"הפעל תכונות למשתמש מתקדם",ja:"エキスパート機能を有効にする",ko:"파워 유저 기능 활성화",ru:"Включить функции для опытных пользователей",zh:"启用高级用户功能","zh-tw":"啟用進階使用者功能"},"Enable this if your Object Storage doesn't support CORS":{def:"Enable this if your Object Storage doesn't support CORS",es:"Habilitar si su almacenamiento no soporta CORS",fr:"Activer ceci si votre stockage objet ne prend pas en charge CORS",he:"הפעל אם אחסון האובייקטים שלך לא תומך ב-CORS",ja:"オブジェクトストレージがCORSをサポートしていない場合は有効にしてください",ko:"객체 스토리지가 CORS를 지원하지 않는 경우 활성화하세요",ru:"Включите, если ваше объектное хранилище не поддерживает CORS",zh:"如果您的对象存储不支持 CORS,请启用此功能 ","zh-tw":"如果你的物件儲存不支援 CORS,請啟用此選項"},"Enable this option to automatically apply the most recent change to documents even when it conflicts":{def:"Enable this option to automatically apply the most recent change to documents even when it conflicts",es:"Aplicar cambios recientes automáticamente aunque generen conflictos",fr:"Activer cette option pour appliquer automatiquement la modification la plus récente aux documents même en cas de conflit",he:"הפעל אפשרות זו כדי להחיל אוטומטית את השינוי האחרון במסמכים גם כשיש קונפליקט",ja:"このオプションを有効にすると、競合があっても最新の変更を自動的にドキュメントに適用します",ko:"이 옵션을 활성화하면 충돌이 있어도 문서에 가장 최근 변경 사항을 자동으로 적용합니다",ru:"Включите эту опцию для автоматического применения последних изменений к документам даже при конфликте",zh:"启用此选项可在文档冲突时自动应用最新的更改","zh-tw":"啟用此選項後,即使發生衝突也會自動套用文件的最新變更"},Enabled:{def:"Enabled",es:"Habilitado",ko:"활성화됨","zh-tw":"已啟用"},"Enabling end-to-end encryption ensures that your data is encrypted on your device before being sent to the remote server. This means that even if someone gains access to the server, they won't be able to read your data without the passphrase. Make sure to remember your passphrase, as it will be required to decrypt your data on other devices.":{def:"Enabling end-to-end encryption ensures that your data is encrypted on your device before being sent to the remote server. This means that even if someone gains access to the server, they won't be able to read your data without the passphrase. Make sure to remember your passphrase, as it will be required to decrypt your data on other devices.",es:"Activar el cifrado de extremo a extremo garantiza que tus datos se cifren en tu dispositivo antes de enviarse al servidor remoto. Así, aunque alguien acceda al servidor, no podrá leer tus datos sin la frase de contraseña. Recuérdala bien, porque será necesaria para descifrar tus datos en los demás dispositivos.",ko:"종단 간 암호화를 활성화하면 데이터가 원격 서버로 전송되기 전에 기기에서 암호화됩니다. 따라서 누군가 서버에 접근하더라도 패스프레이즈 없이는 데이터를 읽을 수 없습니다. 다른 기기에서 데이터를 복호화할 때 필요하므로 패스프레이즈를 반드시 기억해 두세요.","zh-tw":"啟用端對端加密後,資料會先在你的裝置上完成加密,再傳送到遠端伺服器。這表示即使有人取得伺服器存取權,沒有密語也無法讀取你的資料。請務必記住你的密語,因為其他裝置在解密資料時也需要它。"},"Encrypt contents on the remote database. If you use the plugin's synchronization feature, enabling this is recommended.":{def:"Encrypt contents on the remote database. If you use the plugin's synchronization feature, enabling this is recommended.",es:"Cifrar contenido en la base de datos remota. Se recomienda habilitar si usa la sincronización del plugin.",fr:"Chiffrer le contenu sur la base de données distante. Si vous utilisez la fonction de synchronisation du plugin, l'activation est recommandée.",he:"הצפן תוכן במסד הנתונים המרוחק. אם אתה משתמש בתכונת הסנכרון של התוסף, מומלץ להפעיל זאת.",ja:"リモートデータベースの暗号化(オンにすることを推奨)",ko:"원격 데이터베이스의 내용을 암호화합니다. 플러그인의 동기화 기능을 사용하는 경우 활성화를 권장합니다.",ru:"Шифровать содержимое на удалённой базе данных. Рекомендуется включить при использовании функции синхронизации плагина.",zh:"加密远程数据库中的内容。如果您使用插件的同步功能,则建议启用此功能 ","zh-tw":"加密遠端資料庫中的內容。如果你使用外掛的同步功能,建議啟用此選項。"},"Encrypting sensitive configuration items":{def:"Encrypting sensitive configuration items",es:"Cifrando elementos sensibles",fr:"Chiffrement des éléments de configuration sensibles",he:"הצפן פריטי תצורה רגישים",ja:"機密性の高い設定項目の暗号化",ko:"민감한 구성 항목 암호화",ru:"Шифрование конфиденциальных настроек",zh:"加密敏感配置项","zh-tw":"加密敏感設定項目"},"Encryption Algorithm":{def:"Encryption Algorithm",es:"Algoritmo de cifrado",ko:"암호화 알고리즘","zh-tw":"加密演算法"},"Encryption phassphrase. If changed, you should overwrite the server's database with the new (encrypted) files.":{def:"Encryption phassphrase. If changed, you should overwrite the server's database with the new (encrypted) files.",es:"Frase de cifrado. Si la cambia, sobrescriba la base del servidor con los nuevos archivos cifrados.",fr:"Phrase secrète de chiffrement. Si modifiée, vous devriez écraser la base de données du serveur avec les nouveaux fichiers (chiffrés).",he:"ביטוי סיסמה להצפנה. אם שונה, יש לדרוס את מסד הנתונים של השרת בקבצים החדשים (המוצפנים).",ja:"暗号化パスフレーズ。変更した場合、新しい(暗号化された)ファイルでサーバーのデータベースを上書きする必要があります。",ko:"암호화에 사용할 패스프레이즈입니다. 변경한 경우, 새로 암호화된 파일로 서버의 데이터베이스를 덮어써야 합니다.",ru:"Парольная фраза шифрования. При изменении нужно перезаписать базу данных сервера новыми (зашифрованными) файлами.",zh:"加密密码。如果更改,您应该用新的(加密的)文件覆盖服务器的数据库 ","zh-tw":"加密密語。如果變更了它,你應以新的(已加密)檔案覆寫伺服器上的資料庫。"},"End-to-End Encryption":{def:"End-to-End Encryption",es:"Cifrado de extremo a extremo",fr:"Chiffrement de bout en bout",he:"הצפנה מקצה לקצה",ja:"E2E暗号化",ko:"종단 간 암호화",ru:"Сквозное шифрование",zh:"端到端加密","zh-tw":"端對端加密"},"Endpoint URL":{def:"Endpoint URL",es:"URL del endpoint",fr:"URL du point de terminaison",he:"כתובת נקודת קצה (Endpoint URL)",ja:"エンドポイントURL",ko:"엔드포인트 URL",ru:"URL конечной точки",zh:"终端URL","zh-tw":"端點 URL"},"Enhance chunk size":{def:"Enhance chunk size",es:"Mejorar tamaño de chunks",fr:"Améliorer la taille des fragments",he:"הגדל גודל נתח",ja:"チャンクサイズを最適化する",ko:"청크 크기 확대",ru:"Улучшить размер чанка",zh:"增大块大小","zh-tw":"擴大 chunk 大小"},"Enter a folder prefix (optional)":{def:"Enter a folder prefix (optional)",es:"Introduce un prefijo de carpeta (opcional)",ko:"폴더 접두사를 입력하세요 (선택 사항)","zh-tw":"輸入資料夾前綴(可選)"},"Enter Server Information":{def:"Enter Server Information",es:"Introducir información del servidor",ja:"サーバー情報の入力",ko:"서버 정보 입력",ru:"Ввести данные сервера",zh:"输入服务器信息","zh-tw":"輸入伺服器資訊"},"Enter Setup URI":{def:"Enter Setup URI",es:"Introducir el Setup URI",ko:"Setup URI 입력","zh-tw":"輸入 Setup URI"},"Enter the server information manually":{def:"Enter the server information manually",es:"Introducir manualmente la información del servidor",ja:"サーバー情報を手動で入力する",ko:"서버 정보를 수동으로 입력",ru:"Ввести данные сервера вручную",zh:"手动输入服务器信息","zh-tw":"手動輸入伺服器資訊"},"Enter TURN credential":{def:"Enter TURN credential",es:"Introduce la credencial de TURN",ko:"TURN 자격 증명을 입력하세요","zh-tw":"輸入 TURN 憑證"},"Enter TURN username":{def:"Enter TURN username",es:"Introduce el usuario de TURN",ko:"TURN 사용자 이름을 입력하세요","zh-tw":"輸入 TURN 使用者名稱"},"Enter your Access Key ID":{def:"Enter your Access Key ID",es:"Introduce tu ID de clave de acceso",ko:"액세스 키 ID를 입력하세요","zh-tw":"輸入你的 Access Key ID"},"Enter your Bucket Name":{def:"Enter your Bucket Name",es:"Introduce el nombre de tu bucket",ko:"버킷 이름을 입력하세요","zh-tw":"輸入你的儲存庫名稱"},"Enter your database name":{def:"Enter your database name",es:"Introduce el nombre de tu base de datos",ko:"데이터베이스 이름을 입력하세요","zh-tw":"輸入你的資料庫名稱"},"Enter your JWT Key ID":{def:"Enter your JWT Key ID",es:"Introduce el ID de tu clave JWT",ko:"JWT 키 ID를 입력하세요","zh-tw":"輸入你的 JWT Key ID"},"Enter your JWT secret or private key":{def:"Enter your JWT secret or private key",es:"Introduce tu secreto JWT o tu clave privada",ko:"JWT 시크릿 또는 개인 키를 입력하세요","zh-tw":"輸入你的 JWT 密鑰或私密金鑰"},"Enter your JWT Subject (CouchDB Username)":{def:"Enter your JWT Subject (CouchDB Username)",es:"Introduce el sujeto JWT (usuario de CouchDB)",ko:"JWT 주체(CouchDB 사용자 이름)를 입력하세요","zh-tw":"輸入你的 JWT SubjectCouchDB 使用者名稱)"},"Enter your passphrase":{def:"Enter your passphrase",es:"Introduce tu frase de contraseña",ko:"패스프레이즈를 입력하세요","zh-tw":"輸入你的密語"},"Enter your password":{def:"Enter your password",es:"Introduce tu contraseña",ko:"비밀번호를 입력하세요","zh-tw":"輸入你的密碼"},"Enter your Region (e.g., us-east-1, auto for R2)":{def:"Enter your Region (e.g., us-east-1, auto for R2)",es:"Introduce tu región (p. ej., us-east-1, o auto para R2)",ko:"리전을 입력하세요 (예: us-east-1, R2는 auto)","zh-tw":"輸入你的區域(例如 us-east-1R2 請用 auto"},"Enter your Secret Access Key":{def:"Enter your Secret Access Key",es:"Introduce tu clave de acceso secreta",ko:"시크릿 액세스 키를 입력하세요","zh-tw":"輸入你的 Secret Access Key"},"Enter your username":{def:"Enter your username",es:"Introduce tu usuario",ko:"사용자 이름을 입력하세요","zh-tw":"輸入你的使用者名稱"},"Error during connection test: ${reason}":{def:"Error during connection test: ${reason}",es:"Error durante la prueba de conexión: ${reason}",ko:"연결 테스트 중 오류가 발생했습니다: ${reason}","zh-tw":"連線測試時發生錯誤:${reason}"},"Error during testAndFixSettings: ${reason}":{def:"Error during testAndFixSettings: ${reason}",es:"Error durante testAndFixSettings: ${reason}",ko:"testAndFixSettings 실행 중 오류가 발생했습니다: ${reason}","zh-tw":"testAndFixSettings 時發生錯誤:${reason}"},"Experimental Settings":{def:"Experimental Settings",es:"Ajustes experimentales",ko:"실험적 설정","zh-tw":"實驗性設定"},Export:{def:"Export",es:"Exportar",ja:"エクスポート",ko:"내보내기",ru:"Экспорт",zh:"导出","zh-tw":"匯出"},"Failed to connect to remote for compaction.":{def:"Failed to connect to remote for compaction.",es:"No se pudo conectar al remoto para la compactación.",ja:"リモートデータベースに接続できず、コンパクションを実行できませんでした。",ko:"압축 정리를 위해 원격 데이터베이스에 연결하지 못했습니다.",ru:"Не удалось подключиться к удалённой базе данных для компакции.",zh:"无法连接到远程数据库以执行压缩。","zh-tw":"無法連線到遠端資料庫以執行壓縮。"},"Failed to connect to remote for compaction. ${reason}":{def:"Failed to connect to remote for compaction. ${reason}",es:"No se pudo conectar al remoto para la compactación. ${reason}",ja:"リモートデータベースに接続できず、コンパクションを実行できませんでした。${reason}",ko:"압축 정리를 위해 원격 데이터베이스에 연결하지 못했습니다. ${reason}",ru:"Не удалось подключиться к удалённой базе данных для компакции. ${reason}",zh:"无法连接到远程数据库以执行压缩。${reason}","zh-tw":"無法連線到遠端資料庫以執行壓縮。${reason}"},"Failed to connect to the server: ${reason}":{def:"Failed to connect to the server: ${reason}",es:"No se pudo conectar al servidor: ${reason}",ko:"서버에 연결하지 못했습니다: ${reason}","zh-tw":"無法連線到伺服器:${reason}"},"Failed to connect to the server. Please check your settings.":{def:"Failed to connect to the server. Please check your settings.",es:"No se pudo conectar al servidor. Revisa tus ajustes.",ko:"서버에 연결하지 못했습니다. 설정을 확인해 주세요.","zh-tw":"無法連線到伺服器,請檢查你的設定。"},"Failed to connect to the signalling relay: ${reason}":{def:"Failed to connect to the signalling relay: ${reason}",es:"No se pudo conectar al relé de señalización: ${reason}",ko:"시그널링 중계 서버에 연결하지 못했습니다: ${reason}","zh-tw":"無法連線到訊號中繼站:${reason}"},"Failed to create replicator instance.":{def:"Failed to create replicator instance.",es:"No se pudo crear la instancia del replicador.",ko:"복제기 인스턴스를 생성하지 못했습니다.","zh-tw":"無法建立複寫器實例。"},"Failed to parse Setup-URI.":{def:"Failed to parse Setup-URI.",es:"No se pudo interpretar el Setup-URI.",ko:"Setup-URI를 해석하지 못했습니다.","zh-tw":"無法解析 Setup URI。"},"Failed to start one-shot replication before Garbage Collection. Garbage Collection Cancelled.":{def:"Failed to start one-shot replication before Garbage Collection. Garbage Collection Cancelled.",es:"No se pudo iniciar la replicación puntual previa a la recolección de basura. Recolección de basura cancelada.",ja:"Garbage Collection 前にワンショットレプリケーションを開始できませんでした。Garbage Collection はキャンセルされました。",ko:"가비지 컬렉션 전에 일회성 복제를 시작하지 못했습니다. 가비지 컬렉션을 취소합니다.",ru:"Не удалось запустить одноразовую репликацию перед Garbage Collection. Garbage Collection отменена.",zh:"无法在垃圾回收前启动一次性复制。垃圾回收已取消。","zh-tw":"無法在垃圾回收前啟動一次性複寫。垃圾回收已取消。"},"Failed to start replication after Garbage Collection.":{def:"Failed to start replication after Garbage Collection.",es:"No se pudo iniciar la replicación después de la recolección de basura.",ja:"Garbage Collection 後にレプリケーションを開始できませんでした。",ko:"가비지 컬렉션 후 복제를 시작하지 못했습니다.",ru:"Не удалось запустить репликацию после Garbage Collection.",zh:"垃圾回收后无法启动复制。","zh-tw":"垃圾回收後無法啟動複寫。"},"Failed:":{def:"Failed:",es:"Fallidas:",ko:"실패:","zh-tw":"失敗:"},Fetch:{def:"Fetch",es:"Obtener",ja:"取得",ko:"가져오기",ru:"Получить",zh:"获取","zh-tw":"抓取"},"Fetch chunks on demand":{def:"Fetch chunks on demand",es:"Obtener chunks bajo demanda",fr:"Récupérer les fragments à la demande",he:"משוך נתחים לפי דרישה",ja:"ユーザーのタイミングでチャンクの更新を確認する",ko:"필요 시 청크 원격 가져오기",ru:"Загружать чанки по требованию",zh:"按需获取块","zh-tw":"按需抓取 chunks"},"Fetch database with previous behaviour":{def:"Fetch database with previous behaviour",es:"Obtener BD con comportamiento anterior",fr:"Récupérer la base de données avec le comportement précédent",he:"משוך מסד נתונים עם התנהגות קודמת",ja:"以前の動作でデータベースを取得",ko:"이전 동작으로 데이터베이스 가져오기",ru:"Загрузить базу данных с предыдущим поведением",zh:"使用以前的行为获取数据库","zh-tw":"以先前的行為抓取資料庫"},"Fetch remote settings":{def:"Fetch remote settings",es:"Obtener ajustes remotos",ja:"リモート設定を取得",ko:"원격 설정 가져오기",ru:"Получить настройки с удалённого хранилища",zh:"获取远端设置","zh-tw":"抓取遠端設定"},FETCHING:{def:"FETCHING",es:"OBTENIENDO",ko:"가져오는 중","zh-tw":"擷取中"},"Fetching status...":{def:"Fetching status...",es:"Obteniendo el estado...",ko:"상태를 가져오는 중입니다...","zh-tw":"正在取得狀態⋯"},"File integrity":{def:"File integrity",es:"Integridad de archivos",ko:"파일 무결성","zh-tw":"檔案完整性"},"File to resolve conflict":{def:"File to resolve conflict",es:"Archivo para resolver el conflicto",ja:"競合を解決するファイル",ko:"충돌을 해결할 파일",ru:"Файл для разрешения конфликта",zh:"选择要解决冲突的文件","zh-tw":"要解決衝突的檔案"},"File to view History":{def:"File to view History",es:"Archivo cuyo historial se va a ver",ko:"기록을 볼 파일","zh-tw":"要檢視歷程的檔案"},Filename:{def:"Filename",es:"Nombre de archivo",fr:"Nom de fichier",he:"שם קובץ",ja:"ファイル名",ko:"파일명",ru:"Имя файла",zh:"文件名","zh-tw":"檔名"},"Final Confirmation: Overwrite Server Data with This Device's Files":{def:"Final Confirmation: Overwrite Server Data with This Device's Files",es:"Confirmación final: sobrescribir los datos del servidor con los archivos de este dispositivo",ko:"최종 확인: 이 기기의 파일로 서버 데이터 덮어쓰기","zh-tw":"最終確認:以此裝置的檔案覆寫伺服器資料"},"First, please select the option that best describes your current situation.":{def:"First, please select the option that best describes your current situation.",es:"Primero, seleccione la opción que describa mejor su situación actual。",ja:"まず、現在の状況に最も近い項目を選択してください。",ko:"먼저 현재 상황에 가장 잘 맞는 항목을 선택해 주세요.",ru:"Сначала выберите вариант, который лучше всего описывает вашу текущую ситуацию。",zh:"首先,请选择最符合你当前情况的选项。","zh-tw":"首先,請選擇最符合你目前情況的選項。"},Fix:{def:"Fix",es:"Corregir",ko:"수정","zh-tw":"修正"},"Flag and restart":{def:"Flag and restart",es:"Marcar y reiniciar",ja:"フラグを立てて再起動",ko:"표시 후 재시작",ru:"Пометить и перезапустить",zh:"标记后重启","zh-tw":"標記後重新啟動"},"Flagged Selective":{def:"Flagged Selective",es:"Selectivo marcado",ko:"플래그 지정 선택적","zh-tw":"已標記選擇性"},"Folder Prefix":{def:"Folder Prefix",es:"Prefijo de carpeta",ko:"폴더 접두사","zh-tw":"資料夾前綴"},"For HS256/HS512 algorithms, provide the shared secret key. For ES256/ES512 algorithms, provide the pkcs8 PEM-formatted private key.":{def:"For HS256/HS512 algorithms, provide the shared secret key. For ES256/ES512 algorithms, provide the pkcs8 PEM-formatted private key.",es:"Para los algoritmos HS256/HS512, indica la clave secreta compartida. Para ES256/ES512, indica la clave privada en formato PEM pkcs8.",ko:"HS256/HS512 알고리즘에는 공유 시크릿 키를, ES256/ES512 알고리즘에는 pkcs8 PEM 형식의 개인 키를 입력하세요.","zh-tw":"HS256/HS512 演算法請提供共用密鑰;ES256/ES512 演算法請提供 pkcs8 PEM 格式的私密金鑰。"},"Forces the file to be synced when opened.":{def:"Forces the file to be synced when opened.",es:"Forzar sincronización al abrir archivo",fr:"Force la synchronisation du fichier à son ouverture.",he:"מכריח סנכרון הקובץ בעת פתיחתו.",ja:"ファイルを開いたときに強制的に同期します。",ko:"파일을 열 때 강제로 동기화합니다.",ru:"Принудительно синхронизировать файл при открытии.",zh:"打开文件时强制同步该文件 ","zh-tw":"開啟檔案時強制同步該檔案。"},"Fresh Start Wipe":{def:"Fresh Start Wipe",es:"Borrado para reinicio completo",ja:"初期化ワイプ",ko:"초기화 후 새로 시작",ru:"Полный сброс для чистого старта",zh:"全新开始清除","zh-tw":"全新開始清除"},"Furthermore, if conflicts are already present in the server data, they will be synchronised to this device as they are, and you will need to resolve them locally.":{def:"Furthermore, if conflicts are already present in the server data, they will be synchronised to this device as they are, and you will need to resolve them locally.",es:"Además, si ya hay conflictos en los datos del servidor, se sincronizarán tal cual a este dispositivo y tendrás que resolverlos localmente.",ko:"또한 서버 데이터에 이미 충돌이 존재한다면 그 상태 그대로 이 기기에 동기화되므로, 로컬에서 직접 해결해야 합니다.","zh-tw":"此外,如果伺服器資料中已存在衝突,這些衝突會原樣同步到此裝置,你需要在本機自行解決。"},"Garbage Collection cancelled by user.":{def:"Garbage Collection cancelled by user.",es:"Recolección de basura cancelada por el usuario.",ja:"ユーザーによって Garbage Collection がキャンセルされました。",ko:"사용자가 가비지 컬렉션을 취소했습니다.",ru:"Пользователь отменил Garbage Collection.",zh:"用户已取消垃圾回收。","zh-tw":"使用者已取消垃圾回收。"},"Garbage Collection completed. Deleted chunks: ${deletedChunks} / ${totalChunks}. Time taken: ${seconds} seconds.":{def:"Garbage Collection completed. Deleted chunks: ${deletedChunks} / ${totalChunks}. Time taken: ${seconds} seconds.",es:"Recolección de basura completada. Chunks eliminados: ${deletedChunks} / ${totalChunks}. Tiempo empleado: ${seconds} segundos.",ja:"Garbage Collection が完了しました。削除したチャンク: ${deletedChunks} / ${totalChunks}。所要時間: ${seconds} 秒。",ko:"가비지 컬렉션이 완료되었습니다. 삭제된 청크: ${deletedChunks} / ${totalChunks}. 소요 시간: ${seconds}초.",ru:"Garbage Collection завершена. Удалено чанков: ${deletedChunks} / ${totalChunks}. Затраченное время: ${seconds} сек.",zh:"垃圾回收完成。已删除 chunks${deletedChunks} / ${totalChunks}。耗时:${seconds} 秒。","zh-tw":"垃圾回收完成。已刪除 chunks${deletedChunks} / ${totalChunks}。耗時:${seconds} 秒。"},"Garbage Collection Confirmation":{def:"Garbage Collection Confirmation",es:"Confirmación de la recolección de basura",ja:"Garbage Collection の確認",ko:"가비지 컬렉션 확인",ru:"Подтверждение Garbage Collection",zh:"垃圾回收确认","zh-tw":"垃圾回收確認"},"Garbage Collection V3 (Beta)":{def:"Garbage Collection V3 (Beta)",es:"Recolección de basura V3 (Beta)",ja:"ガーベジコレクション V3 (Beta)",ko:"가비지 컬렉션 V3 (Beta)",ru:"Сборка мусора V3 (Beta)",zh:"垃圾回收 V3Beta","zh-tw":"垃圾回收 V3Beta"},"Garbage Collection: Found ${unusedChunks} unused chunks to delete.":{def:"Garbage Collection: Found ${unusedChunks} unused chunks to delete.",es:"Recolección de basura: se han encontrado ${unusedChunks} chunks sin usar para eliminar.",ja:"Garbage Collection: 削除対象の未使用チャンクが ${unusedChunks} 件見つかりました。",ko:"가비지 컬렉션: 삭제할 미사용 청크 ${unusedChunks}개를 찾았습니다.",ru:"Garbage Collection: найдено ${unusedChunks} неиспользуемых чанков для удаления.",zh:"垃圾回收:发现 ${unusedChunks} 个未使用的 chunks 待删除。","zh-tw":"垃圾回收:找到 ${unusedChunks} 個未使用的 chunks 可刪除。"},"Garbage Collection: Scanned ${scanned} / ~${docCount}":{def:"Garbage Collection: Scanned ${scanned} / ~${docCount}",es:"Recolección de basura: analizados ${scanned} / ~${docCount}",ja:"Garbage Collection: ${scanned} / ~${docCount} をスキャン済み",ko:"가비지 컬렉션: ${scanned} / ~${docCount} 검사함",ru:"Garbage Collection: просканировано ${scanned} / ~${docCount}",zh:"垃圾回收:已扫描 ${scanned} / ~${docCount}","zh-tw":"垃圾回收:已掃描 ${scanned} / ~${docCount}"},"Garbage Collection: Scanning completed. Total chunks: ${totalChunks}, Used chunks: ${usedChunks}":{def:"Garbage Collection: Scanning completed. Total chunks: ${totalChunks}, Used chunks: ${usedChunks}",es:"Recolección de basura: análisis completado. Chunks totales: ${totalChunks}, chunks en uso: ${usedChunks}",ja:"Garbage Collection: スキャン完了。総チャンク数: ${totalChunks}、使用中チャンク数: ${usedChunks}",ko:"가비지 컬렉션: 검사 완료. 전체 청크 수: ${totalChunks}, 사용 중인 청크 수: ${usedChunks}",ru:"Garbage Collection: сканирование завершено. Всего чанков: ${totalChunks}, используемых чанков: ${usedChunks}",zh:"垃圾回收:扫描完成。总 chunks${totalChunks},已使用 chunks${usedChunks}","zh-tw":"垃圾回收:掃描完成。總 chunks${totalChunks},已使用 chunks${usedChunks}"},"Gathering information...":{def:"Gathering information...",es:"Recopilando información...",ko:"정보를 수집하는 중입니다...","zh-tw":"正在收集資訊⋯"},"Generate Random ID":{def:"Generate Random ID",es:"Generar un ID aleatorio",ko:"임의 ID 생성","zh-tw":"產生隨機 ID"},"Group ID":{def:"Group ID",es:"ID de grupo",ko:"그룹 ID","zh-tw":"群組 ID"},"Handle files as Case-Sensitive":{def:"Handle files as Case-Sensitive",es:"Manejar archivos como sensibles a mayúsculas",fr:"Gérer les fichiers en respectant la casse",he:"טפל בקבצים כתלויי רישיות",ja:"ファイルの大文字・小文字を区別する",ko:"파일을 대소문자 구분으로 처리",ru:"Обрабатывать файлы с учётом регистра",zh:"将文件视为区分大小写","zh-tw":"將檔案視為區分大小寫"},"Have you created a backup before proceeding?":{def:"Have you created a backup before proceeding?",es:"¿Has creado una copia de seguridad antes de continuar?",ko:"진행하기 전에 백업을 만드셨나요?","zh-tw":"你在繼續之前是否已建立備份?"},"Hidden file synchronization have been temporarily disabled. Please enable them after the fetching, if you need them.":{def:"Hidden file synchronization have been temporarily disabled. Please enable them after the fetching, if you need them.",es:"La sincronización de archivos ocultos se ha desactivado temporalmente. Vuelve a activarla después de la obtención si la necesitas.",ko:"숨김 파일 동기화가 일시적으로 비활성화되었습니다. 필요하다면 가져오기가 끝난 뒤에 다시 활성화해 주세요.","zh-tw":"隱藏檔案同步已暫時停用。如有需要,請在抓取完成後重新啟用。"},"Hidden Files":{def:"Hidden Files",es:"Archivos ocultos",ja:"隠しファイル",ko:"숨김 파일",ru:"Скрытые файлы",zh:"隐藏文件","zh-tw":"隱藏檔案"},"Hide completely":{def:"Hide completely",es:"Ocultar por completo",ko:"완전히 숨기기",zh:"完全隐藏","zh-tw":"完全隱藏"},"Hide not applicable items":{def:"Hide not applicable items",es:"Ocultar elementos no aplicables",ko:"해당 없는 항목 숨기기","zh-tw":"隱藏不適用的項目"},"Higher (${local} > ${remote})":{def:"Higher (${local} > ${remote})",es:"Superior (${local} > ${remote})",ko:"더 높음 (${local} > ${remote})","zh-tw":"較高(${local} > ${remote}"},"Highlight diff":{def:"Highlight diff",es:"Resaltar las diferencias",ko:"차이 강조","zh-tw":"醒目顯示差異"},"How to display network errors when the sync server is unreachable.":{def:"How to display network errors when the sync server is unreachable.",es:"Cómo mostrar los errores de red cuando el servidor de sincronización no está disponible.",ja:"同期サーバーに到達できない場合のネットワークエラーの表示方法を設定します。",ko:"동기화 서버에 연결할 수 없을 때 네트워크 오류를 어떻게 표시할지 설정합니다.",ru:"Определяет, как отображать сетевые ошибки, если сервер синхронизации недоступен.",zh:"当同步服务器不可达时,如何显示网络错误。","zh-tw":"當同步伺服器無法連線時,如何顯示網路錯誤。"},"How would you like to configure the connection to your server?":{def:"How would you like to configure the connection to your server?",es:"¿Cómo desea configurar la conexión con su servidor?",ja:"サーバー接続をどのように設定しますか?",ko:"서버 연결을 어떻게 구성하시겠습니까?",ru:"Как вы хотите настроить подключение к серверу?",zh:"你希望如何配置与服务器的连接?","zh-tw":"你希望如何設定與伺服器的連線?"},"However, This should not be enabled if you want to increase your secrecy more.":{def:"However, This should not be enabled if you want to increase your secrecy more.",es:"Sin embargo, esto no debería habilitarse si quieres aumentar aún más tu privacidad.",ko:"다만 기밀성을 더 높이고 싶다면 이 옵션은 활성화하지 않는 것이 좋습니다.","zh-tw":"不過,如果你想加強保密性,不建議啟用此選項。"},"I am adding a device to an existing synchronisation setup":{def:"I am adding a device to an existing synchronisation setup",es:"Estoy agregando un dispositivo a una configuración de sincronización existente",ja:"既存の同期構成に端末を追加します",ko:"기존 동기화 구성에 기기를 추가합니다",ru:"Я добавляю устройство к существующей настройке синхронизации",zh:"我要将设备加入现有同步配置","zh-tw":"我要將裝置加入既有同步設定"},"I am setting this up for the first time":{def:"I am setting this up for the first time",es:"Estoy configurando esto por primera vez",ja:"はじめて設定します",ko:"처음으로 설정합니다",ru:"Я настраиваю это впервые",zh:"我是第一次进行设置","zh-tw":"我是第一次進行設定"},"I am setting up a new server for the first time / I want to reset my existing server.":{def:"I am setting up a new server for the first time / I want to reset my existing server.",es:"Estoy configurando un servidor nuevo por primera vez / quiero restablecer mi servidor actual.",ko:"새 서버를 처음 설정하거나, 기존 서버를 초기화하려고 합니다.","zh-tw":"我是第一次設定新的伺服器/我想要重設現有的伺服器。"},"I am unable to create a backup of my Vault.":{def:"I am unable to create a backup of my Vault.",es:"No puedo crear una copia de seguridad de mi Vault.",ko:"보관함을 백업할 수 없습니다.","zh-tw":"我無法備份我的 Vault。"},"I am unable to create a backup of my Vaults.":{def:"I am unable to create a backup of my Vaults.",es:"No puedo crear una copia de seguridad de mis Vaults.",ko:"보관함들을 백업할 수 없습니다.","zh-tw":"我無法備份我的 Vault。"},"I have created a backup of my Vault.":{def:"I have created a backup of my Vault.",es:"He creado una copia de seguridad de mi Vault.",ko:"보관함을 백업했습니다.","zh-tw":"我已經備份了我的 Vault。"},"I know my server details, let me enter them":{def:"I know my server details, let me enter them",es:"Conozco los datos de mi servidor; permítame introducirlos",ja:"サーバー情報を把握しているので、自分で入力します",ko:"서버 정보를 알고 있으니 직접 입력하겠습니다",ru:"Я знаю параметры сервера, позвольте ввести их вручную",zh:"我知道服务器详情,让我手动输入","zh-tw":"我知道伺服器資訊,讓我手動輸入"},"I understand that all changes made on other smartphones or computers possibly could be lost.":{def:"I understand that all changes made on other smartphones or computers possibly could be lost.",es:"Entiendo que todos los cambios hechos en otros móviles u ordenadores podrían perderse.",ko:"다른 스마트폰이나 컴퓨터에서 변경한 내용이 모두 사라질 수 있다는 점을 이해합니다.","zh-tw":"我了解其他手機或電腦上的所有變更可能會遺失。"},"I understand that other devices will no longer be able to synchronise, and will need to be reset the synchronisation information.":{def:"I understand that other devices will no longer be able to synchronise, and will need to be reset the synchronisation information.",es:"Entiendo que los demás dispositivos ya no podrán sincronizar y que habrá que restablecer su información de sincronización.",ko:"다른 기기는 더 이상 동기화할 수 없게 되며, 동기화 정보를 초기화해야 한다는 점을 이해합니다.","zh-tw":"我了解其他裝置將無法再進行同步,且需要重設其同步資訊。"},"I understand that this action is irreversible once performed.":{def:"I understand that this action is irreversible once performed.",es:"Entiendo que esta acción es irreversible una vez realizada.",ko:"이 작업은 한 번 수행하면 되돌릴 수 없다는 점을 이해합니다.","zh-tw":"我了解此操作一旦執行即無法復原。"},"I understand the risks and will proceed without a backup.":{def:"I understand the risks and will proceed without a backup.",es:"Entiendo los riesgos y continuaré sin copia de seguridad.",ko:"위험을 이해하며 백업 없이 진행하겠습니다.","zh-tw":"我了解風險,並在沒有備份的情況下繼續。"},"I Understand, Overwrite Server":{def:"I Understand, Overwrite Server",es:"Lo entiendo, sobrescribir el servidor",ko:"이해했습니다, 서버 덮어쓰기","zh-tw":"我了解,覆寫伺服器"},'If "Auto Start P2P Connection" is enabled, the P2P connection will be started automatically when the plug-in launches.':{def:'If "Auto Start P2P Connection" is enabled, the P2P connection will be started automatically when the plug-in launches.',es:"Si «Iniciar la conexión P2P automáticamente» está activado, la conexión P2P se iniciará al arrancar el complemento.",ko:'"P2P 연결 자동 시작"이 활성화되어 있으면 플러그인이 시작될 때 P2P 연결이 자동으로 시작됩니다.',"zh-tw":"若啟用「自動啟動 P2P 連線」,外掛啟動時會自動建立 P2P 連線。"},"If disabled(toggled), chunks will be split on the UI thread (Previous behaviour).":{def:"If disabled(toggled), chunks will be split on the UI thread (Previous behaviour).",es:"Si se desactiva, chunks se dividen en hilo UI (comportamiento anterior)",fr:"Si désactivé, les fragments seront découpés sur le thread UI (comportement précédent).",he:"אם מכובה, נתחים יפוצלו בשרשור ממשק המשתמש (התנהגות קודמת).",ja:"無効(トグル)にすると、チャンクはUIスレッドで分割されます(以前の動作)。",ko:"비활성화(토글)되면 청크는 UI 스레드에서 분할됩니다 (이전 동작).",ru:"Если отключено, чанки будут разделяться в основном потоке.",zh:"如果禁用(切换),chunks 将在 UI 线程上分割(以前的行为)","zh-tw":"若停用(關閉)此選項,chunks 會在 UI 執行緒上分割(舊有行為)。"},"If enabled per-filed efficient customization sync will be used. We need a small migration when enabling this. And all devices should be updated to v0.23.18. Once we enabled this, we lost a compatibility with old versions.":{def:"If enabled per-filed efficient customization sync will be used. We need a small migration when enabling this. And all devices should be updated to v0.23.18. Once we enabled this, we lost a compatibility with old versions.",es:"Habilita sincronización eficiente por archivo. Requiere migración y actualizar todos dispositivos a v0.23.18. Pierde compatibilidad con versiones antiguas",fr:"Si activée, la synchronisation de personnalisation efficace par fichier sera utilisée. Une petite migration est nécessaire lors de l'activation. Tous les appareils doivent être à jour en v0.23.18. Une fois cette option activée, la compatibilité avec les anciennes versions est perdue.",he:"אם מופעל, ייעשה שימוש בסנכרון התאמה אישית יעיל לפי קובץ. נדרשת הגירה קטנה בעת ההפעלה. כל המכשירים צריכים להיות מעודכנים לגרסה 0.23.18. לאחר ההפעלה, התאימות לגרסאות ישנות תיפגע.",ja:"有効にすると、ファイルごとの効率的なカスタマイズ同期が使用されます。有効化時に小規模な移行が必要です。また、すべてのデバイスをv0.23.18にアップデートする必要があります。一度有効にすると、古いバージョンとの互換性がなくなります。",ko:"활성화하면 파일별 효율적인 사용자 설정 동기화가 사용됩니다. 이를 활성화할 때 소규모 데이터 구조 전환이 필요합니다. 모든 기기를 v0.23.18로 업데이트해야 합니다. 이를 활성화하면 이전 버전과의 호환성이 사라집니다.",ru:"If enabled per-filed efficient customization sync will be used. We need a small migration when enabling this. And all devices should be updated to v0.23.18. Once we enabled this, we lost a compatibility with old versions.",zh:"如果启用,将使用基于文件的、高效的自定义同步。启用此功能需要进行一次小的迁移。所有设备都应更新到 v0.23.18。一旦启用此功能,我们将失去与旧版本的兼容性","zh-tw":"啟用後會使用以每個檔案為單位的高效率自訂同步。啟用時需要進行一次小型遷移,且所有裝置都應升級到 v0.23.18。啟用後將不再相容舊版本。"},"If enabled, chunks will be split into no more than 100 items. However, dedupe is slightly weaker.":{def:"If enabled, chunks will be split into no more than 100 items. However, dedupe is slightly weaker.",es:"Divide chunks en máximo 100 ítems. Menos eficiente en deduplicación",fr:"Si activée, les fragments seront découpés en 100 éléments au maximum. Cependant, la déduplication est légèrement moins efficace.",he:"אם מופעל, נתחים יפוצלו לא ליותר מ-100 פריטים. עם זאת, ביטול כפילויות יהיה חלש מעט יותר.",ja:"有効にすると、チャンクは最大100項目に分割されます。ただし、重複除去の精度は落ちます。",ko:"활성화하면 청크는 최대 100개 항목으로 분할됩니다. 하지만 중복 제거 기능이 약간 약해집니다.",ru:"Если включено, чанки будут разделены не более чем на 100 элементов.",zh:"如果启用,数据块将被分割成不超过 100 项。但是,去重效果会稍弱","zh-tw":"啟用後,chunks 最多會分成 100 個項目,但去重效果會稍微變弱。"},"If enabled, newly created chunks are temporarily kept within the document, and graduated to become independent chunks once stabilised.":{def:"If enabled, newly created chunks are temporarily kept within the document, and graduated to become independent chunks once stabilised.",es:"Chunks nuevos se mantienen temporalmente en el documento hasta estabilizarse",fr:"Si activée, les fragments nouvellement créés sont temporairement conservés dans le document et promus en fragments indépendants une fois stabilisés.",he:"אם מופעל, נתחים שנוצרו לאחרונה נשמרים זמנית בתוך המסמך, ומוסמכים לנתחים עצמאיים לאחר יציבות.",ja:"有効にすると、新しく作成されたチャンクはドキュメント内に一時的に保持され、安定したら独立したチャンクになります。",ko:"활성화하면 새로 생성된 청크가 문서 안에 임시로 보관되며, 안정화된 뒤에 독립된 청크로 분리됩니다.",ru:"Если включено, вновь созданные чанки временно хранятся в документе.",zh:"如果启用,新创建的数据块将暂时保留在文档中,并在稳定后成为独立数据块","zh-tw":"啟用後,新建立的 chunks 會暫時保留在文件中,待穩定後再獨立出去。"},"If enabled, the ⛔ icon will be shown inside the status instead of the file warnings banner. No details will be shown.":{def:"If enabled, the ⛔ icon will be shown inside the status instead of the file warnings banner. No details will be shown.",es:"Si se activa, se mostrará el icono ⛔ en el estado en lugar del banner de advertencia de archivos. No se mostrarán detalles.",fr:"Si activée, l'icône ⛔ s'affichera dans le statut à la place de la bannière d'avertissements de fichiers. Aucun détail ne sera affiché.",he:"אם מופעל, אייקון ⛔ יוצג בסטטוס במקום פס האזהרות. לא יוצגו פרטים.",ja:"有効にすると、ファイル警告バナーの代わりにステータス内へ ⛔ アイコンのみを表示します。詳細は表示されません。",ko:"활성화하면 파일 경고 배너 대신 상태 영역에 ⛔ 아이콘만 표시됩니다. 자세한 내용은 표시되지 않습니다.",ru:"Если включено, значок будет показан внутри статуса.",zh:"如果启用,状态栏内将显示 ⛔ 图标,而非文件警告横幅,不会显示任何详细信息。","zh-tw":"啟用後,將在狀態列中顯示 ⛔ 圖示,而不是檔案警告橫幅,且不會顯示詳細資訊。"},"If enabled, the file under 1kb will be processed in the UI thread.":{def:"If enabled, the file under 1kb will be processed in the UI thread.",es:"Archivos <1kb se procesan en hilo UI",fr:"Si activée, les fichiers de moins de 1 Ko seront traités sur le thread UI.",he:"אם מופעל, קבצים קטנים מ-1KB יעובדו בשרשור ממשק המשתמש.",ja:"有効にすると、1kb未満のファイルはUIスレッドで処理されます。",ko:"활성화하면 1kb 미만의 파일은 UI 스레드에서 처리됩니다.",ru:"Если включено, файлы меньше 1КБ будут обрабатываться в основном потоке.",zh:"如果启用,小于 1kb 的文件将在 UI 线程中处理","zh-tw":"啟用後,小於 1KB 的檔案會在 UI 執行緒中處理。"},"If enabled, the notification of hidden files change will be suppressed.":{def:"If enabled, the notification of hidden files change will be suppressed.",es:"Si se habilita, se suprimirá la notificación de cambios en archivos ocultos.",fr:"Si activée, les notifications de modifications des fichiers cachés seront supprimées.",he:"אם מופעל, התראות על שינוי בקבצים נסתרים יודחקו.",ja:"有効にすると、隠しファイルの変更通知が抑制されます。",ko:"활성화하면 숨김 파일 변경 알림이 표시되지 않습니다.",ru:"Если включено, уведомление об изменении скрытых файлов будет подавлено.",zh:"如果启用,将不再通知隐藏文件被更改","zh-tw":"啟用後,將不再通知隱藏檔案變更。"},"If this enabled, all chunks will be stored with the revision made from its content. (Previous behaviour)":{def:"If this enabled, all chunks will be stored with the revision made from its content. (Previous behaviour)",es:"Si se habilita, todos los chunks se almacenan con la revisión hecha desde su contenido. (comportamiento anterior)",fr:"Si activée, tous les fragments seront stockés avec la révision issue de leur contenu. (Comportement précédent)",he:"אם מופעל, כל הנתחים יישמרו עם גרסה המבוססת על תוכנם. (התנהגות קודמת)",ja:"有効にすると、すべてのチャンクはコンテンツから作成されたリビジョンと共に保存されます(以前の動作)。",ko:"이 옵션이 활성화되면 모든 청크는 콘텐츠에서 생성된 리비전과 함께 저장됩니다. (이전 동작)",ru:"Если включено, все чанки будут храниться с ревизией из содержимого.",zh:"如果启用,所有 chunks 将使用根据其内容生成的修订版本存储(以前的行为)","zh-tw":"啟用後,所有 chunks 都會以其內容產生的修訂版本儲存(舊有行為)。"},"If this enabled, All files are handled as case-Sensitive (Previous behaviour).":{def:"If this enabled, All files are handled as case-Sensitive (Previous behaviour).",es:"Si se habilita, todos los archivos se manejan como sensibles a mayúsculas (comportamiento anterior)",fr:"Si activée, tous les fichiers sont gérés en respectant la casse (comportement précédent).",he:"אם מופעל, כל הקבצים מטופלים כתלויי רישיות (התנהגות קודמת).",ja:"有効にすると、すべてのファイルは大文字小文字を区別して処理されます(以前の動作)。",ko:"이 옵션이 활성화되면 모든 파일이 대소문자를 구분하여 처리됩니다 (이전 동작).",ru:"Если включено, все файлы обрабатываются с учётом регистра.",zh:"如果启用,所有文件都将视为区分大小写(以前的行为)","zh-tw":"啟用後,所有檔案都會以區分大小寫方式處理(舊有行為)。"},"If this enabled, chunks will be split into semantically meaningful segments. Not all platforms support this feature.":{def:"If this enabled, chunks will be split into semantically meaningful segments. Not all platforms support this feature.",es:"Divide chunks en segmentos semánticos. No todos los sistemas lo soportan",fr:"Si activée, les fragments seront découpés en segments sémantiquement signifiants. Toutes les plateformes ne prennent pas en charge cette fonctionnalité.",he:"אם מופעל, נתחים יפוצלו לחלקים עם משמעות סמנטית. לא כל הפלטפורמות תומכות בתכונה זו.",ja:"有効にすると、チャンクは意味的に有意なセグメントに分割されます。すべてのプラットフォームがこの機能をサポートしているわけではありません。",ko:"이 옵션을 활성화하면 청크가 문단이나 의미 단위로 나뉘어 저장됩니다. 단, 이 기능은 일부 플랫폼에서는 지원되지 않을 수 있습니다.",ru:"Если включено, чанки будут разделены на семантически значимые сегменты.",zh:"如果启用此功能,数据块将被分割成具有语义意义的段落。并非所有平台都支持此功能","zh-tw":"啟用後,chunks 會依語意切分成有意義的區段,並非所有平台都支援此功能。"},"If this is set, changes to local files which are matched by the ignore files will be skipped. Remote changes are determined using local ignore files.":{def:"If this is set, changes to local files which are matched by the ignore files will be skipped. Remote changes are determined using local ignore files.",es:"Saltar cambios en archivos locales que coincidan con ignore files. Cambios remotos usan ignore files locales",fr:"Si défini, les modifications des fichiers locaux correspondant aux fichiers d'exclusion seront ignorées. Les changements distants sont déterminés à l'aide des fichiers d'exclusion locaux.",he:"אם מוגדר, שינויים בקבצים מקומיים התואמים לקבצי ההתעלמות יידלגו. שינויים מרוחקים נקבעים לפי קבצי ההתעלמות המקומיים.",ja:"これを設定すると、除外ファイルに一致するローカルファイルの変更はスキップされます。リモートの変更はローカルの無視ファイルを使用して判定されます。",ko:"이 옵션을 활성화하면, 제외 규칙 파일에 일치하는 로컬 파일의 변경 사항은 건너뜁니다. 원격 변경 여부 또한 로컬의 제외 규칙 파일에 따라 판단됩니다.",ru:"If this is set, changes to local files which are matched by the ignore files will be skipped. Remote changes are determined using local ignore files.",zh:"如果设置了此项,与忽略文件匹配的本地文件的更改将被跳过。远程更改使用本地忽略文件确定","zh-tw":"若已設定,符合忽略檔案規則的本機檔案變更將被略過。遠端變更則依本機忽略檔案來判斷。"},"If this option is enabled, PouchDB will hold the connection open for 60 seconds, and if no change arrives in that time, close and reopen the socket, instead of holding it open indefinitely. Useful when a proxy limits request duration but can increase resource usage.":{def:"If this option is enabled, PouchDB will hold the connection open for 60 seconds, and if no change arrives in that time, close and reopen the socket, instead of holding it open indefinitely. Useful when a proxy limits request duration but can increase resource usage.",es:"Mantiene conexión 60s. Si no hay cambios, reinicia socket. Útil con proxies limitantes",fr:"Si cette option est activée, PouchDB maintiendra la connexion ouverte pendant 60 secondes, et si aucun changement n'arrive durant cette période, fermera et rouvrira la socket au lieu de la garder ouverte indéfiniment. Utile lorsqu'un proxy limite la durée des requêtes, mais peut augmenter l'utilisation des ressources.",he:"אם אפשרות זו מופעלת, PouchDB ישמור את החיבור פתוח ל-60 שניות, ואם אין שינוי בפרק זמן זה, יסגור ויפתח מחדש את השקע, במקום להחזיק אותו פתוח ללא הגבלה. שימושי כשפרוקסי מגביל משך בקשות, אך עשוי להגביר שימוש במשאבים.",ja:"このオプションを有効にすると、PouchDBは接続を60秒間保持し、その間に通信がない場合、一度接続を閉じて再接続します。接続を無期限に保持する代わりにこの動作を行います。プロキシ(Cloudflareなど)がリクエストの持続時間を制限している場合に有用ですが、リソース使用量が増加する可能性があります。",ko:"이 옵션이 활성화되면 PouchDB는 연결을 더이상 무한히 열어두지 않고 60초 동안 유지합니다. 그 시간 내에 변경 사항이 없으면 소켓을 닫고 다시 엽니다. 프록시가 요청 지속 시간을 제한할 때 유용하지만 리소스 사용량이 증가할 수 있습니다.",ru:"If this option is enabled, PouchDB will hold the connection open for 60 seconds, and if no change arrives in that time, close and reopen the socket, instead of holding it open indefinitely. Useful when a proxy limits request duration but can increase resource usage.",zh:"如果启用此选项,PouchDB 将保持连接打开 60 秒,如果在此时间内没有更改到达,则关闭并重新打开套接字,而不是无限期保持打开。当代理限制请求持续时间时有用,但可能会增加资源使用ß","zh-tw":"啟用此選項後,PouchDB 會將連線保持開啟 60 秒;若在這段時間內沒有變更送達,就會關閉並重新開啟該連線,而不是無限期保持開啟。這在代理伺服器限制請求時長時很有用,但可能會增加資源使用量。"},"If you cannot avoid CORS issues, you might want to try this option. It uses Obsidian's internal API to communicate with the CouchDB server. Not compliant with web standards, but works. Note that this might break in future Obsidian versions.":{def:"If you cannot avoid CORS issues, you might want to try this option. It uses Obsidian's internal API to communicate with the CouchDB server. Not compliant with web standards, but works. Note that this might break in future Obsidian versions.",es:"Si no puedes evitar problemas de CORS, prueba esta opción. Usa la API interna de Obsidian para comunicarse con el servidor CouchDB. No cumple los estándares web, pero funciona. Ten en cuenta que podría dejar de funcionar en versiones futuras de Obsidian.",ko:"CORS 문제를 피할 수 없다면 이 옵션을 시도해 볼 수 있습니다. Obsidian의 내부 API를 사용해 CouchDB 서버와 통신합니다. 웹 표준을 따르지는 않지만 동작합니다. 향후 Obsidian 버전에서 동작하지 않을 수 있다는 점에 유의하세요.","zh-tw":"如果你無法避免 CORS 問題,可以試試這個選項。它會使用 Obsidian 的內部 API 與 CouchDB 伺服器通訊,不符合網頁標準,但可以運作。請注意,未來的 Obsidian 版本可能導致此功能失效。"},"If you cannot avoid CORS issues, you might want to try this option. It uses Obsidian's internal API to communicate with the S3 server. Not compliant with web standards, but works. Note that this might break in future Obsidian versions.":{def:"If you cannot avoid CORS issues, you might want to try this option. It uses Obsidian's internal API to communicate with the S3 server. Not compliant with web standards, but works. Note that this might break in future Obsidian versions.",es:"Si no puedes evitar problemas de CORS, prueba esta opción. Usa la API interna de Obsidian para comunicarse con el servidor S3. No cumple los estándares web, pero funciona. Ten en cuenta que podría dejar de funcionar en versiones futuras de Obsidian.",ko:"CORS 문제를 피할 수 없다면 이 옵션을 시도해 볼 수 있습니다. Obsidian의 내부 API를 사용해 S3 서버와 통신합니다. 웹 표준을 따르지는 않지만 동작합니다. 향후 Obsidian 버전에서 동작하지 않을 수 있다는 점에 유의하세요.","zh-tw":"如果你無法避免 CORS 問題,可以試試這個選項。它會使用 Obsidian 的內部 API 與 S3 伺服器通訊,不符合網頁標準,但可以運作。請注意,未來的 Obsidian 版本可能導致此功能失效。"},"If you have unsynchronised changes in your Vault on this device, they will likely diverge from the server's versions after the reset. This may result in a large number of file conflicts.":{def:"If you have unsynchronised changes in your Vault on this device, they will likely diverge from the server's versions after the reset. This may result in a large number of file conflicts.",es:"Si tienes cambios sin sincronizar en el Vault de este dispositivo, es probable que divergan de las versiones del servidor tras el restablecimiento. Esto puede provocar un gran número de conflictos de archivos.",ko:"이 기기의 보관함에 동기화되지 않은 변경 사항이 있다면, 초기화 후 서버의 버전과 어긋나기 쉽습니다. 그 결과 많은 파일에서 충돌이 발생할 수 있습니다.","zh-tw":"如果此裝置的 Vault 中有尚未同步的變更,重設後這些變更很可能會與伺服器上的版本產生分歧,可能導致大量檔案衝突。"},"If you reached the payload size limit when using IBM Cloudant, please decrease batch size and batch limit to a lower value.":{def:"If you reached the payload size limit when using IBM Cloudant, please decrease batch size and batch limit to a lower value.",es:"Si alcanzas el límite de tamaño de carga al usar IBM Cloudant, reduce el tamaño de lote y el límite de lote.",ko:"IBM Cloudant를 사용하다가 페이로드 크기 제한에 도달했다면, 배치 크기와 배치 개수 제한을 더 낮은 값으로 줄여 주세요.","zh-tw":"如果你在使用 IBM Cloudant 時遇到負載大小上限,請調低批次大小與批次上限。"},"If you understand the risks and still wish to proceed, select so.":{def:"If you understand the risks and still wish to proceed, select so.",es:"Si entiendes los riesgos y aun así quieres continuar, indícalo.",ko:"위험을 이해하고도 진행하려면 그렇게 선택해 주세요.","zh-tw":"如果你了解風險,仍希望繼續,請選取此項。"},"If you want to store the data in a specific folder within the bucket, you can specify a folder prefix here. Otherwise, leave it blank to store data at the root of the bucket.":{def:"If you want to store the data in a specific folder within the bucket, you can specify a folder prefix here. Otherwise, leave it blank to store data at the root of the bucket.",es:"Si quieres guardar los datos en una carpeta concreta del bucket, indica aquí un prefijo de carpeta. Si no, déjalo vacío para guardarlos en la raíz del bucket.",ko:"버킷 안의 특정 폴더에 데이터를 저장하려면 여기에 폴더 접두사를 지정할 수 있습니다. 그렇지 않다면 비워 두어 버킷 최상위에 데이터를 저장하세요.","zh-tw":"如果你想把資料存放在儲存庫內特定的資料夾中,可以在此指定資料夾前綴;留空則會將資料存放在儲存庫的根目錄。"},"If you want to use `LiveSync`, you should broadcast changes. All `watching` peers which detects this will start the replication for fetching.":{def:"If you want to use `LiveSync`, you should broadcast changes. All `watching` peers which detects this will start the replication for fetching.",es:"Si quieres usar `LiveSync`, debes difundir los cambios. Todos los pares que estén `observando` y lo detecten iniciarán la replicación para obtenerlos.",ko:"`LiveSync`를 사용하려면 변경 사항을 브로드캐스트해야 합니다. 이를 감지한 모든 `watching` 상태의 피어가 가져오기를 위한 복제를 시작합니다.","zh-tw":"若要使用 `LiveSync`,你需要廣播變更。所有偵測到廣播的「監看中」Peer 都會開始執行複寫以進行擷取。"},Ignore:{def:"Ignore",es:"Ignorar",ko:"무시","zh-tw":"忽略"},"Ignore and Proceed":{def:"Ignore and Proceed",es:"Ignorar y continuar",ja:"無視して続行",ko:"무시하고 계속",ru:"Игнорировать и продолжить",zh:"忽略并继续","zh-tw":"忽略並繼續"},"Ignore files":{def:"Ignore files",es:"Archivos a ignorar",fr:"Fichiers d'exclusion",he:"קבצי התעלמות",ja:"除外ファイル",ko:"제외 규칙 파일",ru:"Файлы для игнорирования",zh:"忽略文件","zh-tw":"忽略檔案"},"Ignore patterns":{def:"Ignore patterns",es:"Patrones de exclusión",ja:"除外パターン",ko:"무시 패턴",ru:"Шаблоны исключения",zh:"忽略模式","zh-tw":"忽略模式"},"Import connection":{def:"Import connection",es:"Importar conexión",ja:"接続をインポート",ko:"연결 가져오기",ru:"Импортировать подключение",zh:"导入连接","zh-tw":"匯入連線"},IMPORTANT:{def:"IMPORTANT",es:"IMPORTANTE",ko:"중요","zh-tw":"重要"},"In most cases, you should stick with the default algorithm (${algorithm}), This setting is only required if you have an existing Vault encrypted in a different format.":{def:"In most cases, you should stick with the default algorithm (${algorithm}), This setting is only required if you have an existing Vault encrypted in a different format.",es:"En la mayoría de los casos deberías mantener el algoritmo predeterminado (${algorithm}). Este ajuste solo es necesario si ya tienes un Vault cifrado en otro formato.",ko:"대부분의 경우 기본 알고리즘(${algorithm})을 그대로 사용하는 것이 좋습니다. 이 설정은 기존 보관함이 다른 형식으로 암호화되어 있는 경우에만 필요합니다.","zh-tw":"在大多數情況下,建議維持使用預設演算法(${algorithm})。只有當你現有的 Vault 是以不同格式加密時,才需要調整這項設定。"},"In this scenario, Self-hosted LiveSync will recreate metadata for every file and deliberately generate conflicts. Where the file content is identical, these conflicts will be resolved automatically.":{def:"In this scenario, Self-hosted LiveSync will recreate metadata for every file and deliberately generate conflicts. Where the file content is identical, these conflicts will be resolved automatically.",es:"En este caso, Self-hosted LiveSync recreará los metadatos de todos los archivos y generará conflictos a propósito. Cuando el contenido del archivo sea idéntico, esos conflictos se resolverán automáticamente.",ko:"이 경우 Self-hosted LiveSync는 모든 파일의 메타데이터를 다시 만들면서 의도적으로 충돌을 발생시킵니다. 파일 내용이 동일한 경우 이러한 충돌은 자동으로 해결됩니다.","zh-tw":"在這種情況下,Self-hosted LiveSync 會為每個檔案重新建立中繼資料,並刻意產生衝突。若檔案內容相同,這些衝突會自動解決。"},"Incoming:":{def:"Incoming:",es:"Entrantes:",ko:"수신:","zh-tw":"收到:"},"Incubate Chunks in Document":{def:"Incubate Chunks in Document",es:"Incubar chunks en documento",fr:"Incuber les fragments dans le document",he:"בשל נתחים בתוך המסמך",ja:"ドキュメント内でチャンクを一時保管する",ko:"문서 내 청크 임시 보관",ru:"Инкубировать чанки в документе",zh:"在文档中孵化块","zh-tw":"在文件中暫存 chunks"},"Initial Action":{def:"Initial Action",es:"Acción inicial",ko:"초기 작업","zh-tw":"初始動作"},"Initialise all journal history, On the next sync, every item will be received and sent.":{def:"Initialise all journal history, On the next sync, every item will be received and sent.",es:"Restablece todo el historial del diario. En la próxima sincronización se recibirán y enviarán todos los elementos.",ja:"すべてのジャーナル履歴を初期化します。次回の同期時に、すべての項目が再受信・再送信されます。",ko:"모든 저널 기록을 초기화합니다. 다음 동기화 때 모든 항목을 다시 받고 다시 보냅니다.",ru:"Инициализирует всю историю журнала. При следующей синхронизации каждый элемент будет заново получен и отправлен.",zh:"初始化所有日志历史。下次同步时,所有项目都会重新接收并发送。","zh-tw":"初始化所有日誌歷史。下次同步時,每個項目都會重新接收與傳送。"},"Initialise journal received history. On the next sync, every item except this device sent will be downloaded again.":{def:"Initialise journal received history. On the next sync, every item except this device sent will be downloaded again.",es:"Inicializa el historial de recepción del diario. En la próxima sincronización se volverán a descargar todos los elementos salvo los enviados por este dispositivo.",ko:"저널 수신 기록을 초기화합니다. 다음 동기화 때 이 기기가 보낸 항목을 제외한 모든 항목을 다시 내려받습니다.","zh-tw":"初始化接收日誌歷程。下次同步時,除了此裝置已送出的項目外,其他項目都會再次下載。"},"Initialise journal sent history. On the next sync, every item except this device received will be sent again.":{def:"Initialise journal sent history. On the next sync, every item except this device received will be sent again.",es:"Inicializa el historial de envío del diario. En la próxima sincronización se volverán a enviar todos los elementos salvo los recibidos por este dispositivo.",ko:"저널 송신 기록을 초기화합니다. 다음 동기화 때 이 기기가 받은 항목을 제외한 모든 항목을 다시 보냅니다.","zh-tw":"初始化傳送日誌歷程。下次同步時,除了此裝置已接收的項目外,其他項目都會再次傳送。"},"Interval (sec)":{def:"Interval (sec)",es:"Intervalo (segundos)",fr:"Intervalle (sec)",he:"מרווח (שניות)",ja:"秒",ko:"간격 (초)",ru:"Интервал (сек)",zh:"间隔(秒)","zh-tw":"間隔(秒)"},INVERTED:{def:"INVERTED",es:"INVERTIDO",ko:"반전됨","zh-tw":"反向"},"Issue detection log:":{def:"Issue detection log:",es:"Registro de detección de problemas:",ko:"문제 감지 로그:","zh-tw":"問題偵測日誌:"},"It is strongly advised to create a backup before proceeding. Continuing without a backup may lead to data loss.":{def:"It is strongly advised to create a backup before proceeding. Continuing without a backup may lead to data loss.",es:"Se recomienda encarecidamente crear una copia de seguridad antes de continuar. Continuar sin copia de seguridad puede provocar pérdida de datos.",ko:"진행하기 전에 백업을 만드시기를 강력히 권장합니다. 백업 없이 진행하면 데이터가 손실될 수 있습니다.","zh-tw":"強烈建議在繼續之前先建立備份。若不備份就繼續,可能導致資料遺失。"},"Just for a minute, please!":{def:"Just for a minute, please!",es:"¡Solo un momento, por favor!",ko:"잠시만 기다려 주세요!","zh-tw":"請稍候片刻!"},"JWT (JSON Web Token) authentication allows you to securely authenticate with the CouchDB server using tokens. Ensure that your CouchDB server is configured to accept JWTs and that the provided key and settings match the server's configuration. Incidentally, I have not verified it very thoroughly.":{def:"JWT (JSON Web Token) authentication allows you to securely authenticate with the CouchDB server using tokens. Ensure that your CouchDB server is configured to accept JWTs and that the provided key and settings match the server's configuration. Incidentally, I have not verified it very thoroughly.",es:"La autenticación JWT (JSON Web Token) permite autenticarse de forma segura con el servidor CouchDB mediante tokens. Asegúrate de que tu servidor CouchDB esté configurado para aceptar JWT y de que la clave y los ajustes indicados coincidan con la configuración del servidor. Por cierto, no lo he verificado a fondo.",ko:"JWT(JSON Web Token) 인증을 사용하면 토큰으로 CouchDB 서버에 안전하게 인증할 수 있습니다. CouchDB 서버가 JWT를 받아들이도록 설정되어 있는지, 그리고 입력한 키와 설정이 서버 구성과 일치하는지 확인해 주세요. 참고로 이 기능은 그리 철저하게 검증되지는 않았습니다.","zh-tw":"JWTJSON Web Token)驗證讓你可以使用權杖安全地登入 CouchDB 伺服器。請確認你的 CouchDB 伺服器已設定為接受 JWT,且提供的金鑰與設定符合伺服器端的設定。附帶一提,這項功能尚未經過非常徹底的驗證。"},"JWT Algorithm":{def:"JWT Algorithm",es:"Algoritmo JWT",ko:"JWT 알고리즘","zh-tw":"JWT 演算法"},"JWT Expiration Duration (minutes)":{def:"JWT Expiration Duration (minutes)",es:"Duración de caducidad del JWT (minutos)",ko:"JWT 만료 시간(분)","zh-tw":"JWT 有效期限(分鐘)"},"JWT Key":{def:"JWT Key",es:"Clave JWT",ko:"JWT 키","zh-tw":"JWT 金鑰"},"JWT Key ID (kid)":{def:"JWT Key ID (kid)",es:"ID de clave JWT (kid)",ko:"JWT 키 ID (kid)","zh-tw":"JWT Key IDkid"},"JWT Subject (sub)":{def:"JWT Subject (sub)",es:"Sujeto JWT (sub)",ko:"JWT 주체 (sub)","zh-tw":"JWT Subjectsub"},"K.exp":{def:"Experimental",es:"Experimental",fr:"Expérimental",he:"ניסיוני",ja:"試験機能",ko:"실험 기능",ru:"Экспериментальная",zh:"实验性","zh-tw":"實驗性"},"K.long_p2p_sync":{def:"Peer-to-Peer Sync",es:"Sincronización punto a punto",fr:"Synchronisation pair-à-pair",he:"%{title_p2p_sync}",ja:"Peer-to-Peer Sync (試験機能)",ko:"피어 투 피어(P2P) 동기화 (실험 기능)",ru:"title_p2p_sync",zh:"Peer-to-Peer同步 (实验性)","zh-tw":"Peer-to-Peer 同步"},"K.P2P":{def:"Peer-to-Peer",es:"par a par",fr:"Pair-à-Pair",he:"%{Peer}-ל-%{Peer}",ja:"Peer-to-Peer",ko:"피어-to-피어",ru:"Peer-к-Peer",zh:"Peer-to-Peer","zh-tw":"Peer-to-Peer"},"K.Peer":{def:"Peer",es:"par",fr:"Pair",he:"עמית",ja:"Peer",ko:"피어",ru:"Устройство",zh:"Peer","zh-tw":"Peer"},"K.ScanCustomization":{def:"Scan customization",es:"Buscar personalizaciones",fr:"Analyser la personnalisation",he:"סרוק התאמה אישית",ja:"Scan customization",ko:"사용자 설정 검색",ru:"Scan customization",zh:"扫描自定义","zh-tw":"掃描自訂項目"},"K.short_p2p_sync":{def:"P2P Sync",es:"Sincronización P2P",fr:"Sync P2P",he:"סנכרון P2P",ja:"P2P Sync (試験機能)",ko:"P2P 동기화",ru:"P2P Синхр.",zh:"P2P同步(实验性)","zh-tw":"P2P 同步"},"K.title_p2p_sync":{def:"Peer-to-Peer Sync",es:"Sincronización punto a punto",fr:"Synchronisation pair-à-pair",he:"סנכרון עמית-לעמית",ja:"Peer-to-Peer Sync",ko:"피어 투 피어(P2P) 동기화",ru:"Синхронизация между устройствами",zh:"Peer-to-Peer同步","zh-tw":"Peer-to-Peer 同步"},"Keep empty folder":{def:"Keep empty folder",es:"Mantener carpetas vacías",fr:"Conserver les dossiers vides",he:"שמור תיקייה ריקה",ja:"空フォルダの維持",ko:"빈 폴더 유지",ru:"Сохранять пустые папки",zh:"保留空文件夹","zh-tw":"保留空資料夾"},lang_def:{def:"Default",es:"Predeterminado",fr:"Par défaut",he:"ברירת מחדל",ja:"Default",ko:"기본값",ru:"По умолчанию",zh:"Default","zh-tw":"預設"},"lang-de":{def:"Deutsche",es:"Alemán",fr:"Deutsche",he:"Deutsche",ja:"Deutsche",ko:"Deutsche",ru:"Deutsch",zh:"Deutsche","zh-tw":"Deutsche"},"lang-def":{def:"Default",es:"Predeterminado",fr:"Par défaut",he:"%{lang_def}",ja:"Default",ko:"기본값",ru:"lang_def",zh:"Default","zh-tw":"預設"},"lang-es":{def:"Español",es:"Español",fr:"Español",he:"Español",ja:"Español",ko:"Español",ru:"Español",zh:"Español","zh-tw":"Español"},"lang-fr":{def:"Français",es:"Français",fr:"Français",he:"Français",ja:"Français",ko:"Français",ru:"Français",zh:"Français","zh-tw":"Français"},"lang-he":{def:"Hebrew",es:"Hebreo",he:"עברית",ko:"עברית","zh-tw":"עברית"},"lang-ja":{def:"日本語",es:"Japonés",fr:"日本語",he:"日本語",ja:"日本語",ko:"日本語",ru:"日本語",zh:"日本語","zh-tw":"日本語"},"lang-ko":{def:"한국어",es:"Coreano",fr:"한국어",he:"한국어",ja:"한국어",ko:"한국어",ru:"한국어",zh:"한국어","zh-tw":"한국어"},"lang-ru":{def:"Русский",es:"Ruso",fr:"Русский",he:"Русский",ja:"Русский",ko:"Русский",ru:"Русский",zh:"Русский","zh-tw":"Русский"},"lang-zh":{def:"简体中文",es:"Chino simplificado",fr:"简体中文",he:"简体中文",ja:"简体中文",ko:"简体中文",ru:"简体中文",zh:"简体中文","zh-tw":"简体中文"},"lang-zh-tw":{def:"繁體中文",es:"Chino tradicional",fr:"繁體中文",he:"繁體中文",ja:"繁體中文",ko:"繁體中文",ru:"繁體中文",zh:"繁體中文","zh-tw":"繁體中文"},Later:{def:"Later",es:"Más tarde",ja:"後で",ko:"나중에",ru:"Позже",zh:"稍后","zh-tw":"稍後"},"Limit: {datetime} ({timestamp})":{def:"Limit: {datetime} ({timestamp})",es:"Límite: {datetime} ({timestamp})",ja:"制限: {datetime} ({timestamp})",ko:"제한: {datetime} ({timestamp})",ru:"Лимит: {datetime} ({timestamp})",zh:"限制:{datetime}{timestamp}","zh-tw":"限制:{datetime}{timestamp}"},live:{def:"live",es:"en vivo",ko:"실시간","zh-tw":"即時監看"},"LiveSync could not handle multiple vaults which have same name without different prefix, This should be automatically configured.":{def:"LiveSync could not handle multiple vaults which have same name without different prefix, This should be automatically configured.",es:"LiveSync no puede manejar múltiples bóvedas con mismo nombre sin prefijo. Se configura automáticamente",fr:"LiveSync ne peut pas gérer plusieurs coffres portant le même nom sans préfixe distinct. Ceci devrait être configuré automatiquement.",he:"LiveSync אינו יכול לטפל במספר כספות עם אותו שם ללא קידומת שונה. הדבר אמור להיות מוגדר אוטומטית.",ja:"LiveSyncは、接頭辞(プレフィックス)のない同名の保管庫(Vault)を扱うことができません。これは自動的に設定されます。",ko:"LiveSync는 접두사로 구분되지 않은 동일한 이름의 보관함을 여러 개 처리할 수 없습니다. 이 값은 자동으로 구성되어야 합니다.",ru:"LiveSync не может обработать несколько хранилищ с одинаковым именем без разных префиксов.",zh:"LiveSync 无法处理具有相同名称但没有不同前缀的多个库。这应该自动配置","zh-tw":"LiveSync 無法處理名稱相同卻沒有不同前綴的多個 Vault,這應該會自動設定。"},"liveSyncReplicator.beforeLiveSync":{def:"Before LiveSync, start OneShot once...",es:"Antes de LiveSync, inicia OneShot...",fr:"Avant LiveSync, lancement d'un OneShot initial...",he:"לפני LiveSync, התחל OneShot פעם אחת...",ja:"LiveSyncの前に、まずOneShotを開始します...",ko:"LiveSync 전에 OneShot을 먼저 시작합니다...",ru:"Перед LiveSync запускаем OneShot...",zh:"在LiveSync前,先启动OneShot一次...","zh-tw":"在 LiveSync 之前,先執行一次 OneShot 同步⋯"},"liveSyncReplicator.cantReplicateLowerValue":{def:"We can't replicate more lower value.",es:"No podemos replicar un valor más bajo.",fr:"Impossible de répliquer une valeur inférieure.",he:"לא ניתן לשכפל ערך נמוך יותר.",ja:"これ以上低い値ではレプリケーション(複製)できません。",ko:"더 낮은 값으로 복제할 수 없습니다.",ru:"Нельзя реплицировать с меньшим значением.",zh:"我们无法复制更小的值","zh-tw":"無法複寫更低的值。"},"liveSyncReplicator.checkingLastSyncPoint":{def:"Looking for the point last synchronized point.",es:"Buscando el último punto sincronizado.",fr:"Recherche du dernier point de synchronisation.",he:"מחפש נקודת הסנכרון האחרונה.",ja:"最後に同期したポイントを探しています。",ko:"마지막으로 동기화된 지점을 찾고 있습니다.",ru:"Поиск последней точки синхронизации.",zh:"查找上次同步点","zh-tw":"正在尋找上次同步的位置。"},"liveSyncReplicator.couldNotConnectTo":{def:"Could not connect to ${uri} : ${name}\n(${db})",es:"No se pudo conectar a ${uri} : ${name}\n(${db})",fr:"Connexion impossible à ${uri} : ${name}\n(${db})",he:"לא ניתן להתחבר אל ${uri} : ${name}\n(${db})",ja:"${uri} : ${name}に接続できませんでした\n(${db})",ko:"${uri}에 연결할 수 없습니다: ${name}\n(${db})",ru:"Не удалось подключиться к uri : name\n(db)",zh:"无法连接到 ${uri} : ${name}\n(${db})","zh-tw":"無法連線到 ${uri} : ${name}\n(${db})"},"liveSyncReplicator.couldNotConnectToRemoteDb":{def:"Could not connect to remote database: ${d}",es:"No se pudo conectar a base de datos remota: ${d}",fr:"Connexion à la base distante impossible : ${d}",he:"לא ניתן להתחבר למסד הנתונים המרוחק: ${d}",ja:"リモートデータベースに接続できませんでした: ${d}",ko:"원격 데이터베이스에 연결할 수 없습니다: ${d}",ru:"Не удалось подключиться к удалённой базе данных: d",zh:"无法连接到远程数据库:${d}","zh-tw":"無法連線到遠端資料庫:${d}"},"liveSyncReplicator.couldNotConnectToServer":{def:"The connection to the remote has been prevented, or failed.",es:"No se pudo conectar al servidor.",fr:"Connexion au serveur impossible.",he:"לא ניתן להתחבר לשרת.",ja:"サーバーに接続できませんでした。",ko:"원격에 대한 연결이 차단되었거나 실패했습니다.",ru:"Не удалось подключиться к серверу.",zh:"无法连接到服务器","zh-tw":"與遠端的連線被阻擋,或連線失敗。"},"liveSyncReplicator.couldNotConnectToURI":{def:"Could not connect to ${uri}:${dbRet}",es:"No se pudo conectar a ${uri}:${dbRet}",fr:"Connexion impossible à ${uri}:${dbRet}",he:"לא ניתן להתחבר אל ${uri}:${dbRet}",ja:"${uri}に接続できませんでした: ${dbRet}",ko:"${uri}에 연결할 수 없습니다: ${dbRet}",ru:"Не удалось подключиться к uri:dbRet",zh:"无法连接到 ${uri}:${dbRet}","zh-tw":"無法連線到 ${uri}:${dbRet}"},"liveSyncReplicator.couldNotMarkResolveRemoteDb":{def:"Could not mark resolve remote database.",es:"No se pudo marcar como resuelta la base de datos remota.",fr:"Impossible de marquer la résolution de la base distante.",he:"לא ניתן לסמן פתרון למסד הנתונים המרוחק.",ja:"リモートデータベースを解決済みとしてマークできませんでした。",ko:"원격 데이터베이스를 해결됨으로 표시할 수 없습니다.",ru:"Не удалось отметить удалённую базу данных как разрешённую.",zh:"无法标记并解决远程数据库","zh-tw":"無法將遠端資料庫標記為已處理。"},"liveSyncReplicator.liveSyncBegin":{def:"LiveSync begin...",es:"Inicio de LiveSync...",fr:"Démarrage de LiveSync...",he:"LiveSync מתחיל...",ja:"LiveSyncを開始...",ko:"LiveSync 시작...",ru:"Начало LiveSync...",zh:"LiveSync 开始...","zh-tw":"LiveSync 開始⋯"},"liveSyncReplicator.lockRemoteDb":{def:"Lock remote database to prevent data corruption",es:"Bloquear base de datos remota para prevenir corrupción de datos",fr:"Verrouillage de la base distante pour éviter la corruption des données",he:"נועל מסד נתונים מרוחק למניעת פגיעה בנתונים",ja:"データ破損を防ぐためリモートデータベースをロック",ko:"데이터 손상을 방지하기 위해 원격 데이터베이스를 잠급니다",ru:"Блокировка удалённой базы данных для предотвращения повреждения данных",zh:"锁定远程数据库以防止数据损坏","zh-tw":"鎖定遠端資料庫以防止資料損毀"},"liveSyncReplicator.markDeviceResolved":{def:"Mark this device as 'resolved'.",es:"Marcar este dispositivo como 'resuelto'.",fr:"Marquer cet appareil comme « résolu ».",he:"סמן מכשיר זה כ'נפתר'.",ja:"このデバイスを『解決済み』としてマーク。",ko:"이 기기를 '해결됨'으로 표시합니다.",ru:"Отметить это устройство как «разрешённое».",zh:"将此设备标记为“已解决”","zh-tw":"將此裝置標記為「已處理」。"},"liveSyncReplicator.mismatchedTweakDetected":{def:"Some mismatches have been detected in the configuration between devices. Running a manual replication will attempt to resolve this issue.",es:"Se han detectado discrepancias en la configuración entre dispositivos. Ejecutar una replicación manual intentará resolverlo.",ko:"기기 간 구성에서 일부 불일치가 감지되었습니다. 수동으로 복제를 실행하면 이 문제를 해결하려고 시도합니다.","zh-tw":"偵測到裝置之間的設定有不一致之處。執行手動複寫將嘗試解決此問題。"},"liveSyncReplicator.oneShotSyncBegin":{def:"OneShot Sync begin... (${syncMode})",es:"Inicio de sincronización OneShot... (${syncMode})",fr:"Démarrage de la synchronisation OneShot... (${syncMode})",he:"סנכרון OneShot מתחיל... (${syncMode})",ja:"OneShot同期を開始... (${syncMode})",ko:"OneShot 동기화 시작... (${syncMode})",ru:"Начало OneShot синхронизации... (syncMode)",zh:"OneShot同步开始...(${syncMode})","zh-tw":"OneShot 同步開始⋯(${syncMode}"},"liveSyncReplicator.remoteDbCorrupted":{def:"Remote database is newer or corrupted, make sure to latest version of self-hosted-livesync installed",es:"La base de datos remota es más nueva o está dañada, asegúrese de tener la última versión de self-hosted-livesync instalada",fr:"La base distante est plus récente ou corrompue, assurez-vous d'avoir installé la dernière version de self-hosted-livesync",he:"מסד הנתונים המרוחק חדש יותר או פגום, ודא שגרסת self-hosted-livesync המותקנת היא העדכנית ביותר",ja:"リモートデータベースが新しいか破損しています。self-hosted-livesyncの最新バージョンがインストールされていることを確認してください",ko:"원격 데이터베이스가 더 최신이거나 손상되었습니다. 최신 버전의 self-hosted-livesync가 설치되어 있는지 확인하세요",ru:"Удалённая база данных новее или повреждена, убедитесь, что установлена последняя версия self-hosted-livesync",zh:"远程数据库较新或已损坏,请确保已安装最新版本的self-hosted-livesync","zh-tw":"遠端資料庫版本較新或已損毀,請確保已安裝最新版本的 Self-hosted LiveSync"},"liveSyncReplicator.remoteDbCreatedOrConnected":{def:"Remote Database Created or Connected",es:"Base de datos remota creada o conectada",fr:"Base distante créée ou connectée",he:"מסד הנתונים המרוחק נוצר או חובר",ja:"リモートデータベースが作成または接続されました",ko:"원격 데이터베이스가 생성되거나 연결되었습니다",ru:"Удалённая база данных создана или подключена",zh:"远程数据库已创建或连接","zh-tw":"遠端資料庫已建立或已連線"},"liveSyncReplicator.remoteDbDestroyed":{def:"Remote Database Destroyed",es:"Base de datos remota destruida",fr:"Base distante détruite",he:"מסד הנתונים המרוחק נהרס",ja:"リモートデータベースが削除されました",ko:"원격 데이터베이스가 삭제되었습니다",ru:"Удалённая база данных уничтожена",zh:"远程数据库已销毁","zh-tw":"遠端資料庫已銷毀"},"liveSyncReplicator.remoteDbDestroyError":{def:"Something happened on Remote Database Destroy:",es:"Algo ocurrió al destruir base de datos remota:",fr:"Un problème est survenu lors de la destruction de la base distante :",he:"אירעה שגיאה בהריסת מסד הנתונים המרוחק:",ja:"リモートデータベースの削除中に問題が発生しました:",ko:"원격 데이터베이스 삭제 중 오류가 발생했습니다:",ru:"Произошла ошибка при уничтожении удалённой базы данных:",zh:"远程数据库销毁时发生错误:","zh-tw":"銷毀遠端資料庫時發生問題:"},"liveSyncReplicator.remoteDbMarkedResolved":{def:"Remote database has been marked resolved.",es:"Base de datos remota marcada como resuelta.",fr:"La base distante a été marquée comme résolue.",he:"מסד הנתונים המרוחק סומן כנפתר.",ja:"リモートデータベースが解決済みとしてマークされました。",ko:"원격 데이터베이스가 해결됨으로 표시되었습니다.",ru:"Удалённая база данных отмечена как разрешённая.",zh:"远程数据库已标记为已解决","zh-tw":"遠端資料庫已標記為已處理。"},"liveSyncReplicator.replicationClosed":{def:"Replication closed",es:"Replicación cerrada",fr:"Réplication fermée",he:"השכפול נסגר",ja:"レプリケーション(複製)が終了しました",ko:"복제가 종료되었습니다",ru:"Репликация закрыта",zh:"同步已关闭","zh-tw":"複寫已關閉"},"liveSyncReplicator.replicationInProgress":{def:"Replication is already in progress",es:"Replicación en curso",fr:"Une réplication est déjà en cours",he:"שכפול כבר מתבצע",ja:"レプリケーション(複製)は既に進行中です",ko:"복제가 이미 진행 중입니다",ru:"Репликация уже выполняется",zh:"同步正在进行中","zh-tw":"複寫已在進行中"},"liveSyncReplicator.retryLowerBatchSize":{def:"Retry with lower batch size:${batch_size}/${batches_limit}",es:"Reintentar con tamaño de lote más bajo:${batch_size}/${batches_limit}",fr:"Nouvelle tentative avec une taille de lot réduite :${batch_size}/${batches_limit}",he:"מנסה שוב עם גודל אצווה קטן יותר:${batch_size}/${batches_limit}",ja:"より小さいバッチサイズで再試行: ${batch_size}/${batches_limit}",ko:"더 작은 배치 크기로 재시도: ${batch_size}/${batches_limit}",ru:"Повтор с меньшим размером пакета: batch_size/batches_limit",zh:"使用更小的批量大小重试:${batch_size}/${batches_limit}","zh-tw":"以較低的批次大小重試:${batch_size}/${batches_limit}"},"liveSyncReplicator.unlockRemoteDb":{def:"Unlock remote database to prevent data corruption",es:"Desbloquear base de datos remota para prevenir corrupción de datos",fr:"Déverrouillage de la base distante pour éviter la corruption des données",he:"מבטל נעילת מסד הנתונים המרוחק למניעת פגיעה בנתונים",ja:"データ破損を防ぐためリモートデータベースをアンロック",ko:"데이터 손상을 방지하기 위해 원격 데이터베이스를 잠금 해제합니다",ru:"Разблокировка удалённой базы данных для предотвращения повреждения данных",zh:"解锁远程数据库以防止数据损坏","zh-tw":"解鎖遠端資料庫以防止資料損毀"},"liveSyncSetting.errorNoSuchSettingItem":{def:"No such setting item: ${key}",es:"No existe el ajuste: ${key}",fr:"Élément de paramètre inexistant : ${key}",he:"פריט הגדרה לא קיים: ${key}",ja:"その設定項目は存在しません: ${key}",ko:"해당 설정 항목이 없습니다: ${key}",ru:"Такого параметра настройки не существует: key",zh:"没有此设置项:${key}","zh-tw":"沒有這個設定項目:${key}"},"liveSyncSetting.originalValue":{def:"Original: ${value}",es:"Original: ${value}",fr:"Original : ${value}",he:"ערך מקורי: ${value}",ja:"元の値: ${value}",ko:"원본: ${value}",ru:"Оригинал: value",zh:"原始值:${value}","zh-tw":"原始值:${value}"},"liveSyncSetting.valueShouldBeInRange":{def:"The value should ${min} < value < ${max}",es:"El valor debe estar entre ${min} y ${max}",fr:"La valeur doit être ${min} < valeur < ${max}",he:"הערך צריך להיות ${min} < ערך < ${max}",ja:"値は ${min} < 値 < ${max} の範囲である必要があります",ko:"값은 ${min} < 값 < ${max} 범위에 있어야 합니다",ru:"Значение должно быть min < значение < max",zh:"值应该在 ${min} < value < ${max} 之间","zh-tw":"值應介於 ${min} < value < ${max}"},"liveSyncSettings.btnApply":{def:"Apply",es:"Aplicar",fr:"Appliquer",he:"החל",ja:"適用",ko:"적용",ru:"Применить",zh:"应用","zh-tw":"套用"},"Local Database Tweak":{def:"Local Database Tweak",es:"Ajustes de la base de datos local",ja:"ローカルデータベースの調整",ko:"로컬 데이터베이스 조정",ru:"Настройки локальной базы данных","zh-tw":"本機資料庫調校"},"Local only":{def:"Local only",es:"Solo local",ko:"로컬에만 있음","zh-tw":"僅本機有"},Lock:{def:"Lock",es:"Bloquear",ja:"ロック",ko:"잠금",ru:"Заблокировать",zh:"锁定","zh-tw":"鎖定"},"Lock Server":{def:"Lock Server",es:"Bloquear servidor",ja:"サーバーをロック",ko:"서버 잠금",ru:"Заблокировать сервер",zh:"锁定服务器","zh-tw":"鎖定伺服器"},"Lock the remote server to prevent synchronization with other devices.":{def:"Lock the remote server to prevent synchronization with other devices.",es:"Bloquea el servidor remoto para impedir la sincronización con otros dispositivos.",ja:"他のデバイスとの同期を防ぐため、リモートサーバーをロックします。",ko:"다른 기기와의 동기화를 방지하기 위해 원격 서버를 잠급니다.",ru:"Блокирует удалённый сервер, чтобы запретить синхронизацию с другими устройствами.",zh:"锁定远端服务器,以阻止其他设备继续同步。","zh-tw":"鎖定遠端伺服器,以防止其他裝置進行同步。"},"logPane.autoScroll":{def:"Auto scroll",es:"Autodesplazamiento",fr:"Défilement automatique",he:"גלילה אוטומטית",ja:"自動スクロール",ko:"자동 스크롤",ru:"Автопрокрутка",zh:"自动滚动","zh-tw":"自動捲動"},"logPane.logWindowOpened":{def:"Log window opened",es:"Ventana de registro abierta",fr:"Fenêtre des journaux ouverte",he:"חלון יומן נפתח",ja:"ログウィンドウが開かれました",ko:"로그 창이 열렸습니다",ru:"Окно лога открыто",zh:"日志窗口已打开","zh-tw":"日誌視窗已開啟"},"logPane.pause":{def:"Pause",es:"Pausar",fr:"Pause",he:"השהה",ja:"一時停止",ko:"일시 정지",ru:"Пауза",zh:"暂停","zh-tw":"暫停"},"logPane.title":{def:"Self-hosted LiveSync Log",es:"Registro de Self-hosted LiveSync",fr:"Journaux Self-hosted LiveSync",he:"יומן Self-hosted LiveSync",ja:"Self-hosted LiveSync ログ",ko:"Self-hosted LiveSync 로그",ru:"Лог Self-hosted LiveSync",zh:"Self-hosted LiveSync 日志","zh-tw":"Self-hosted LiveSync 日誌"},"logPane.wrap":{def:"Wrap",es:"Ajustar",fr:"Retour à la ligne",he:"גלישת שורות",ja:"折り返し",ko:"줄 바꿈",ru:"Перенос",zh:"自动换行","zh-tw":"自動換行"},"Lower (${local} < ${remote})":{def:"Lower (${local} < ${remote})",es:"Inferior (${local} < ${remote})",ko:"더 낮음 (${local} < ${remote})","zh-tw":"較低(${local} < ${remote}"},"Maintenance Commands":{def:"Maintenance Commands",es:"Comandos de mantenimiento",ko:"유지보수 명령","zh-tw":"維護命令"},"Maintenance mode":{def:"Maintenance mode",es:"Modo de mantenimiento",ko:"유지보수 모드","zh-tw":"維護模式"},"Maximum delay for batch database updating":{def:"Maximum delay for batch database updating",es:"Retraso máximo para actualización por lotes",fr:"Délai maximum pour la mise à jour groupée de la base",he:"עיכוב מקסימלי לעדכון אצווה של מסד נתונים",ja:"バッチデータベース更新の最大遅延",ko:"일괄 데이터베이스 업데이트 최대 지연",ru:"Максимальная задержка пакетного обновления базы данных",zh:"批量数据库更新的最大延迟","zh-tw":"批次更新資料庫的最大延遲"},"Maximum file size":{def:"Maximum file size",es:"Tamaño máximo de archivo",fr:"Taille maximale de fichier",he:"גודל קובץ מקסימלי",ja:"最大ファイル容量",ko:"최대 파일 크기",ru:"Максимальный размер файла",zh:"最大文件大小","zh-tw":"最大檔案大小"},"Maximum Incubating Chunk Size":{def:"Maximum Incubating Chunk Size",es:"Tamaño máximo de chunks incubados",fr:"Taille maximale des fragments en incubation",he:"גודל מקסימלי לנתח בבישול",ja:"保持するチャンクの最大サイズ",ko:"임시 보관 청크의 최대 크기",ru:"Максимальный размер инкубируемого чанка",zh:"最大孵化块大小","zh-tw":"最大暫存 chunk 大小"},"Maximum Incubating Chunks":{def:"Maximum Incubating Chunks",es:"Máximo de chunks incubados",fr:"Nombre maximum de fragments en incubation",he:"מספר מקסימלי של נתחים בבישול",ja:"一時保管する最大チャンク数",ko:"임시 보관 청크의 최대 개수",ru:"Максимальное количество инкубируемых чанков",zh:"最大孵化块数","zh-tw":"最大暫存 chunk 數量"},"Maximum Incubation Period":{def:"Maximum Incubation Period",es:"Periodo máximo de incubación",fr:"Période maximale d'incubation",he:"תקופת בישול מקסימלית",ja:"最大保持期限",ko:"청크 임시 보관 최대 기간",ru:"Максимальный период инкубации",zh:"最大孵化期","zh-tw":"最大暫存期間"},"MB (0 to disable).":{def:"MB (0 to disable).",es:"MB (0 para desactivar)",fr:"Mo (0 pour désactiver).",he:"MB (0 לביטול).",ja:"MB (0で無効化)。",ko:"MB (0으로 설정하면 비활성화).",ru:"МБ (0 для отключения).",zh:"MB(0为禁用)","zh-tw":"MB0 表示停用)。"},"Memory cache":{def:"Memory cache",es:"Caché en memoria",ja:"メモリキャッシュ",ko:"메모리 캐시",ru:"Кэш в памяти","zh-tw":"記憶體快取"},"Memory cache size (by total characters)":{def:"Memory cache size (by total characters)",es:"Tamaño caché memoria (por caracteres)",fr:"Taille du cache mémoire (par nombre total de caractères)",he:'גודל מטמון זיכרון (לפי סה"כ תווים)',ja:"全体でキャッシュする文字数",ko:"메모리 캐시 크기 (총 문자 수)",ru:"Размер кэша памяти (по общему количеству символов)",zh:"内存缓存大小(按总字符数)","zh-tw":"記憶體快取大小(依總字元數)"},"Memory cache size (by total items)":{def:"Memory cache size (by total items)",es:"Tamaño caché memoria (por ítems)",fr:"Taille du cache mémoire (par nombre total d'éléments)",he:'גודל מטמון זיכרון (לפי סה"כ פריטים)',ja:"全体のキャッシュサイズ",ko:"메모리 캐시 크기 (총 항목 수)",ru:"Размер кэша памяти (по общему количеству элементов)",zh:"内存缓存大小(按总项目数)","zh-tw":"記憶體快取大小(依總項目數)"},Merge:{def:"Merge",es:"Fusionar",ja:"マージ",ko:"병합",ru:"Объединить",zh:"合并","zh-tw":"合併"},"Minimum delay for batch database updating":{def:"Minimum delay for batch database updating",es:"Retraso mínimo para actualización por lotes",fr:"Délai minimum pour la mise à jour groupée de la base",he:"עיכוב מינימלי לעדכון אצווה של מסד נתונים",ja:"バッチデータベース更新の最小遅延",ko:"일괄 데이터베이스 업데이트 최소 지연",ru:"Минимальная задержка пакетного обновления базы данных",zh:"批量数据库更新的最小延迟","zh-tw":"批次更新資料庫的最小延遲"},"Minimum interval for syncing":{def:"Minimum interval for syncing",es:"Intervalo mínimo de sincronización",fr:"Intervalle minimum pour la synchronisation",he:"מרווח מינימלי לסנכרון",ja:"同期間隔の最小値",ko:"동기화 최소 간격",ru:"Минимальный интервал синхронизации",zh:"同步最小间隔","zh-tw":"同步最小間隔"},Mixed:{def:"Mixed",es:"Mixto",ko:"혼합","zh-tw":"混合"},"moduleCheckRemoteSize.logCheckingStorageSizes":{def:"Checking storage sizes",es:"Comprobando tamaños de almacenamiento",fr:"Vérification des tailles de stockage",he:"בודק גדלי אחסון",ja:"ストレージサイズを確認中",ko:"스토리지 크기 확인 중",ru:"Проверка размеров хранилища",zh:"正在检查存储大小","zh-tw":"正在檢查儲存空間大小"},"moduleCheckRemoteSize.logCurrentStorageSize":{def:"Remote storage size: ${measuredSize}",es:"Tamaño del almacenamiento remoto: ${measuredSize}",fr:"Taille du stockage distant : ${measuredSize}",he:"גודל אחסון מרוחק: ${measuredSize}",ja:"リモートストレージサイズ: ${measuredSize}",ko:"원격 스토리지 크기: ${measuredSize}",ru:"Размер удалённого хранилища: measuredSize",zh:"远程存储大小:${measuredSize}","zh-tw":"遠端儲存空間大小:${measuredSize}"},"moduleCheckRemoteSize.logExceededWarning":{def:"Remote storage size: ${measuredSize} exceeded ${notifySize}",es:"Tamaño del almacenamiento remoto: ${measuredSize} superó ${notifySize}",fr:"Taille du stockage distant : ${measuredSize} a dépassé ${notifySize}",he:"גודל אחסון מרוחק: ${measuredSize} עלה על ${notifySize}",ja:"リモートストレージサイズ: ${measuredSize} が ${notifySize} を超過しました",ko:"원격 스토리지 크기: ${measuredSize}이(가) ${notifySize}을(를) 초과했습니다",ru:"Размер удалённого хранилища: measuredSize превысил notifySize",zh:"远程存储大小:${measuredSize} 超过 ${notifySize}","zh-tw":"遠端儲存空間大小:${measuredSize} 已超過 ${notifySize}"},"moduleCheckRemoteSize.logThresholdEnlarged":{def:"Threshold has been enlarged to ${size}MB",es:"El umbral se ha ampliado a ${size}MB",fr:"Le seuil a été augmenté à ${size} Mo",he:"הסף הורחב ל-${size}MB",ja:"しきい値が ${size}MB に設定されました",ko:"임계값이 ${size}MB로 증가되었습니다",ru:"Порог увеличен до sizeМБ",zh:"阈值已扩大到 ${size}MB","zh-tw":"閾值已提高到 ${size}MB"},"moduleCheckRemoteSize.msgConfirmRebuild":{def:"This may take a bit of a long time. Do you really want to rebuild everything now?",es:"Esto puede llevar un poco de tiempo. ¿Realmente quieres reconstruir todo ahora?",fr:"Cela peut prendre un certain temps. Voulez-vous vraiment tout reconstruire maintenant ?",he:"פעולה זו עשויה לקחת זמן מה. האם אתה בטוח שברצונך לבנות מחדש עכשיו?",ja:"これは少し時間がかかる場合があります。本当に今すべてを再構築しますか?",ko:"시간이 꽤 오래 걸릴 수 있습니다. 정말 지금 모든 것을 재구축하시겠습니까?",ru:"Это может занять некоторое время. Вы действительно хотите перестроить всё сейчас?",zh:"这可能需要一些时间。您真的想现在重建所有内容吗?","zh-tw":"這可能需要一些時間。你確定要現在重建全部內容嗎?"},"moduleCheckRemoteSize.msgDatabaseGrowing":{def:"**Your database is getting larger!** But do not worry, we can address it now. The time before running out of space on the remote storage.\n\n| Measured size | Configured size |\n| --- | --- |\n| ${estimatedSize} | ${maxSize} |\n\n> [!MORE]-\n> If you have been using it for many years, there may be unreferenced chunks - that is, garbage - accumulating in the database. Therefore, we recommend rebuilding everything. It will probably become much smaller.\n>\n> If the volume of your vault is simply increasing, it is better to rebuild everything after organizing the files. Self-hosted LiveSync does not delete the actual data even if you delete it to speed up the process. It is roughly [documented](https://github.com/vrtmrz/obsidian-livesync/blob/main/docs/tech_info.md).\n>\n> If you don't mind the increase, you can increase the notification limit by 100MB. This is the case if you are running it on your own server. However, it is better to rebuild everything from time to time.\n>\n\n> [!WARNING]\n> If you perform rebuild everything, make sure all devices are synchronised. The plug-in will merge as much as possible, though.\n",es:"**¡Tu base de datos está creciendo!** Pero no te preocupes, podemos abordarlo ahora. El tiempo antes de quedarse sin espacio en el almacenamiento remoto.\n\n| Tamaño medido | Tamaño configurado |\n| --- | --- |\n| ${estimatedSize} | ${maxSize} |\n\n> [!MORE]-\n> Si lo has estado utilizando durante muchos años, puede haber fragmentos no referenciados - es decir, basura - acumulándose en la base de datos. Por lo tanto, recomendamos reconstruir todo. Probablemente se volverá mucho más pequeño.\n>\n> Si el volumen de tu bóveda simplemente está aumentando, es mejor reconstruir todo después de organizar los archivos. Self-hosted LiveSync no elimina los datos reales incluso si los eliminas para acelerar el proceso. Está aproximadamente [documentado](https://github.com/vrtmrz/obsidian-livesync/blob/main/docs/tech_info.md).\n>\n> Si no te importa el aumento, puedes aumentar el límite de notificación en 100 MB. Este es el caso si lo estás ejecutando en tu propio servidor. Sin embargo, es mejor reconstruir todo de vez en cuando.\n>\n\n> [!WARNING]\n> Si realizas la reconstrucción completa, asegúrate de que todos los dispositivos estén sincronizados. El complemento fusionará tanto como sea posible, sin embargo.\n",fr:"**Votre base de données grossit !** Pas d'inquiétude, nous pouvons y remédier dès maintenant, avant de manquer d'espace sur le stockage distant.\n\n| Taille mesurée | Taille configurée |\n| --- | --- |\n| ${estimatedSize} | ${maxSize} |\n\n> [!MORE]-\n> Si vous l'utilisez depuis de nombreuses années, il peut y avoir des fragments non référencés — des déchets, en somme — accumulés dans la base. Nous recommandons donc de tout reconstruire. Cela réduira probablement beaucoup la taille.\n>\n> Si le volume de votre coffre augmente simplement, il est préférable de tout reconstruire après avoir organisé les fichiers. Self-hosted LiveSync ne supprime pas réellement les données même si vous les effacez, afin d'accélérer le processus. Ceci est documenté grossièrement [ici](https://github.com/vrtmrz/obsidian-livesync/blob/main/docs/tech_info.md).\n>\n> Si cela ne vous dérange pas, vous pouvez augmenter la limite de notification de 100 Mo. C'est le cas si vous l'exécutez sur votre propre serveur. Il reste toutefois préférable de tout reconstruire de temps en temps.\n>\n\n> [!WARNING]\n> Si vous tout reconstruisez, assurez-vous que tous les appareils sont synchronisés. Le plug-in fusionnera autant que possible cependant.\n",he:"**מסד הנתונים שלך הולך וגדל!** אל תדאג, אנחנו יכולים לטפל בזה עכשיו. הזמן שנשאר עד לאזול המקום באחסון המרוחק.\n\n| גודל נמדד | גודל מוגדר |\n| --- | --- |\n| ${estimatedSize} | ${maxSize} |\n\n> [!MORE]-\n> אם אתה משתמש בפלאגין כבר שנים רבות, ייתכן שנצברו נתחים לא מקושרים — כלומר, זבל — במסד הנתונים. לכן, אנו ממליצים לבנות הכל מחדש. ככל הנראה מסד הנתונים יהיה קטן בהרבה לאחר מכן.\n>\n> אם נפח הכספת שלך פשוט גדל, עדיף לבנות מחדש לאחר ארגון הקבצים. Self-hosted LiveSync אינו מוחק נתונים בפועל גם כאשר אתה מוחק קבצים כדי להאיץ את התהליך. הדבר [מתועד בפירוט](https://github.com/vrtmrz/obsidian-livesync/blob/main/docs/tech_info.md).\n>\n> אם אינך מוטרד מהגידול, ניתן להגדיל את סף ההתראה ב-100MB. הדבר מתאים אם השרת הוא שלך. עם זאת, מומלץ לבנות מחדש מעת לעת.\n>\n\n> [!WARNING]\n> אם תבנה מחדש, ודא שכל המכשירים מסונכרנים. הפלאגין ינסה למזג כמה שניתן.\n",ja:"**データベースが大きくなっています!** でも心配しないでください。リモートストレージの容量が不足する前に対応できます。\n\n| 測定サイズ | 設定サイズ |\n| --- | --- |\n| ${estimatedSize} | ${maxSize} |\n\n> [!MORE]-\n> 長年使用している場合、参照されていないチャンク(つまりゴミ)がデータベースに蓄積している可能性があります。そのため、すべてを再構築することをお勧めします。おそらくかなり小さくなるでしょう。\n>\n> 単純に保管庫の容量が増えている場合は、事前にファイルを整理してからすべてを再構築するのが良いでしょう。Self-hosted LiveSyncは処理速度を上げるため、削除しても実際のデータを削除しません。これはおおまかに[documentation](https://github.com/vrtmrz/obsidian-livesync/blob/main/docs/tech_info.md)に記載されています。\n>\n> 増加を気にしない場合は、通知制限を100MB単位で増やすことができます。これは自分のサーバーで実行している場合に適しています。ただし、定期的にすべてを再構築する方が良いでしょう。\n>\n\n> [!WARNING]\n> すべてを再構築する場合は、すべてのデバイスが同期されていることを確認してください。もちろん、プラグインは可能な限り解決しようと努力はしますけど...\n",ko:"**데이터베이스 용량이 점점 커지고 있습니다!** 하지만 걱정하지 마세요. 지금 대응할 수 있습니다. 원격 스토리지 공간이 부족해지기까지 남은 시간입니다.\n\n| 측정된 크기 | 설정된 한도 |\n| --- | --- |\n| ${estimatedSize} | ${maxSize} |\n\n> [!MORE]-\n> 오랜 기간 사용했다면 참조되지 않는 청크, 즉 쓰레기 데이터가 데이터베이스에 쌓였을 수 있습니다. 이 경우 전체 재구축을 권장합니다. 용량이 훨씬 줄어들 것입니다.\n>\n> 단순히 보관함 용량이 커지고 있는 것이라면, 파일을 정리한 뒤에 전체를 재구축하는 것이 좋습니다. Self-hosted LiveSync는 처리 속도를 위해 파일을 삭제해도 실제 데이터를 바로 지우지 않습니다. 이 내용은 [기술 문서](https://github.com/vrtmrz/obsidian-livesync/blob/main/docs/tech_info.md)에 간략히 정리되어 있습니다.\n>\n> 용량 증가가 괜찮다면 알림 한도를 100MB 단위로 높일 수 있습니다. 직접 서버를 운영하는 경우에 적합한 방법입니다. 다만 가끔은 전체를 재구축해 주는 것이 좋습니다.\n>\n\n> [!WARNING]\n> 전체 재구축을 실행할 때는 모든 기기가 동기화되어 있는지 확인해 주세요. 플러그인이 최대한 병합하려고 시도하기는 합니다.\n",ru:"Ваша база данных увеличивается! Но не волнуйтесь, мы можем решить это сейчас.",zh:"**您的数据库正在变大!** 但别担心,我们现在可以解决它。在远程存储空间用完之前还有时间。\n\n| 测量大小 | 配置大小 |\n| --- | --- |\n| ${estimatedSize} | ${maxSize} |\n\n> [!MORE]-\n> 如果您已经使用了很多年,数据库中可能会积累未引用的 chunks——也就是垃圾。因此,我们建议重建所有内容。它可能会变得小得多。\n>\n> 如果您的库容量只是在增加,最好在整理文件后重建所有内容。即使您为了加速过程删除了文件,Self-hosted LiveSync 也不会删除实际数据。这大致[有文档记录](https://github.com/vrtmrz/obsidian-livesync/blob/main/docs/tech_info.md)。\n>\n> 如果您不介意增加,可以将通知限制增加 100MB。如果您在自己的服务器上运行,就是这种情况。但是,最好还是不时地重建所有内容。\n>\n\n> [!WARNING]\n> 如果您执行重建所有内容,请确保所有设备都已同步。尽管如此,插件会尽可能地合并\n","zh-tw":"**你的資料庫正在變大!** 但不用擔心,我們現在就可以處理。在遠端儲存空間用盡之前還有一些時間。\n\n| 測量大小 | 設定大小 |\n| --- | --- |\n| ${estimatedSize} | ${maxSize} |\n\n> [!MORE]-\n> 如果你已經使用了好幾年,資料庫中可能累積了未被參照的 chunks,也就是垃圾資料。因此,我們建議重建全部內容,通常會讓資料庫變得小很多。\n>\n> 如果你的 Vault 容量只是持續增加,最好先整理檔案再重建全部內容。即使你為了加快速度而刪除了檔案,Self-hosted LiveSync 也不會刪除實際資料,詳情大致記載在[文件](https://github.com/vrtmrz/obsidian-livesync/blob/main/docs/tech_info.md)中。\n>\n> 如果你不在意容量增加,可以將通知上限調高 100MB,這在你自行架設伺服器時較適用。不過,還是建議偶爾重建全部內容。\n>\n\n> [!WARNING]\n> 若要執行重建全部內容,請確保所有裝置都已同步。不過外掛會盡可能地進行合併。"},"moduleCheckRemoteSize.msgSetDBCapacity":{def:"We can set a maximum database capacity warning, **to take action before running out of space on the remote storage**.\nDo you want to enable this?\n\n> [!MORE]-\n> - 0: Do not warn about storage size.\n> This is recommended if you have enough space on the remote storage especially you have self-hosted. And you can check the storage size and rebuild manually.\n> - 800: Warn if the remote storage size exceeds 800MB.\n> This is recommended if you are using fly.io with 1GB limit or IBM Cloudant.\n> - 2000: Warn if the remote storage size exceeds 2GB.\n\nIf we have reached the limit, we will be asked to enlarge the limit step by step.\n",es:"Podemos configurar una advertencia de capacidad máxima de base de datos, **para tomar medidas antes de quedarse sin espacio en el almacenamiento remoto**.\n¿Quieres habilitar esto?\n\n> [!MORE]-\n> - 0: No advertir sobre el tamaño del almacenamiento.\n> Esto es recomendado si tienes suficiente espacio en el almacenamiento remoto, especialmente si lo tienes autoalojado. Y puedes comprobar el tamaño del almacenamiento y reconstruir manualmente.\n> - 800: Advertir si el tamaño del almacenamiento remoto supera los 800 MB.\n> Esto es recomendado si estás usando fly.io con un límite de 1 GB o IBM Cloudant.\n> - 2000: Advertir si el tamaño del almacenamiento remoto supera los 2 GB.\n\nSi hemos alcanzado el límite, se nos pedirá que aumentemos el límite paso a paso.\n",fr:"Nous pouvons définir un avertissement de capacité maximale de la base de données, **afin d'agir avant de manquer d'espace sur le stockage distant**.\nVoulez-vous activer ceci ?\n\n> [!MORE]-\n> - 0 : Ne pas avertir sur la taille de stockage.\n> Recommandé si vous avez suffisamment d'espace sur le stockage distant, surtout en auto-hébergement. Vous pouvez vérifier la taille et reconstruire manuellement.\n> - 800 : Avertir si la taille du stockage distant dépasse 800 Mo.\n> Recommandé si vous utilisez fly.io avec une limite de 1 Go ou IBM Cloudant.\n> - 2000 : Avertir si la taille du stockage distant dépasse 2 Go.\n\nSi la limite est atteinte, il nous sera proposé de l'augmenter étape par étape.\n",he:"ניתן להגדיר אזהרת קיבולת מקסימלית של מסד הנתונים, **כדי לנקוט פעולה לפני שנגמר המקום באחסון המרוחד**.\nהאם להפעיל זאת?\n\n> [!MORE]-\n> - 0: אל תזהיר על גודל האחסון.\n> מומלץ אם יש לך מספיק מקום באחסון המרוחד, בעיקר אם השרת הוא שלך. ניתן לבדוק את גודל האחסון ולבנות מחדש ידנית.\n> - 800: הזהר אם גודל האחסון המרוחד עולה על 800MB.\n> מומלץ אם אתה משתמש ב-fly.io עם מגבלת 1GB או ב-IBM Cloudant.\n> - 2000: הזהר אם גודל האחסון המרוחד עולה על 2GB.\n\nאם הגענו למגבלה, תתבקש להרחיב את הסף בהדרגה.\n",ja:"リモートストレージの容量が不足する前に対策を講じるため、**最大データベース容量の警告**を設定できます。\nこれを有効にしますか?\n\n> [!MORE]-\n> - 0: ストレージサイズについて警告しない。\n> 自宅サーバーなど、リモートストレージに十分な容量がある場合に推奨されます。ストレージサイズを確認し、手動で再構築できます。\n> - 800: リモートストレージサイズが800MBを超えたら警告。\n> 1GB制限のfly.ioやIBM Cloudantを使用している場合に推奨されます。\n> - 2000: リモートストレージサイズが2GBを超えたら警告。\n\n制限に達した場合、段階的に制限を増やすよう求められます。\n",ko:"**원격 스토리지 공간이 부족해지기 전에 미리 조치할 수 있도록** 데이터베이스 용량 경고를 설정할 수 있습니다.\n이 기능을 활성화하시겠습니까?\n\n> [!MORE]-\n> - 0: 스토리지 용량을 경고하지 않습니다.\n> 직접 서버를 운영하는 등 원격 스토리지에 여유 공간이 충분한 경우에 권장합니다. 스토리지 용량을 직접 확인하고 수동으로 재구축할 수 있습니다.\n> - 800: 원격 스토리지 용량이 800MB를 초과하면 경고합니다.\n> 1GB 제한이 있는 fly.io나 IBM Cloudant를 사용하는 경우에 권장합니다.\n> - 2000: 원격 스토리지 용량이 2GB를 초과하면 경고합니다.\n\n한도에 도달하면 한도를 단계적으로 늘릴지 여쭤보겠습니다.\n",ru:"Можно установить предупреждение о максимальной ёмкости базы данных.",zh:"我们可以设置一个最大数据库容量警告,**以便在远程存储空间耗尽前采取行动**。\n您想启用这个功能吗?\n\n> [!MORE]-\n> - 0: 不警告存储大小。\n> 如果您在远程存储(尤其是自托管)上有足够的空间,则推荐此选项。您可以手动检查存储大小并重建。\n> - 800: 如果远程存储大小超过 800MB 则发出警告。\n> 如果您使用的是 fly.io(1GB 限制) 或 IBM Cloudant,则推荐此选项。\n> - 2000: 如果远程存储大小超过 2GB 则发出警告。\n\n如果达到限制,系统会要求我们逐步增大限制\n","zh-tw":"我們可以設定資料庫容量上限警告,**以便在遠端儲存空間用盡之前及早採取行動**。\n你要啟用這個功能嗎?\n\n> [!MORE]-\n> - 0:不警告儲存空間大小。\n> 如果你在遠端儲存空間(尤其是自行架設)有足夠空間,建議選擇此項;你也可以自行手動檢查儲存空間大小並重建。\n> - 800:遠端儲存空間大小超過 800MB 時警告。\n> 如果你使用限制為 1GB 的 fly.io 或 IBM Cloudant,建議選擇此項。\n> - 2000:遠端儲存空間大小超過 2GB 時警告。\n\n如果達到上限,系統會要求逐步提高限制。"},"moduleCheckRemoteSize.noticeExceeded":{def:"Remote storage size is ${measuredSize}, above the configured ${notifySize} notification threshold. {HERE}",es:"El tamaño del almacenamiento remoto es de ${measuredSize}, por encima del umbral de aviso configurado de ${notifySize}. {HERE}",ko:"원격 스토리지 크기 ${measuredSize}이(가) 설정된 알림 임계값 ${notifySize}을(를) 초과했습니다. {HERE}","zh-tw":"遠端儲存空間大小為 ${measuredSize},已超過設定的 ${notifySize} 通知閾值。{HERE}"},"moduleCheckRemoteSize.noticeNotConfigured":{def:"Remote storage size notifications are not configured. {HERE}",es:"Los avisos sobre el tamaño del almacenamiento remoto no están configurados. {HERE}",ko:"원격 스토리지 크기 알림이 설정되어 있지 않습니다. {HERE}","zh-tw":"尚未設定遠端儲存空間大小通知。{HERE}"},"moduleCheckRemoteSize.option2GB":{def:"2GB (Standard)",es:"2GB (Estándar)",fr:"2 Go (Standard)",he:"2GB (סטנדרטי)",ja:"2GB (標準)",ko:"2GB (표준)",ru:"2ГБ (Стандарт)",zh:"2GB (标准)","zh-tw":"2GB(標準)"},"moduleCheckRemoteSize.option800MB":{def:"800MB (Cloudant, fly.io)",es:"800MB (Cloudant, fly.io)",fr:"800 Mo (Cloudant, fly.io)",he:"800MB (Cloudant, fly.io)",ja:"800MB (Cloudant, fly.io)",ko:"800MB (Cloudant, fly.io)",ru:"800МБ (Cloudant, fly.io)",zh:"800MB (Cloudant, fly.io)","zh-tw":"800MBCloudant、fly.io"},"moduleCheckRemoteSize.optionAskMeLater":{def:"Ask me later",es:"Pregúntame más tarde",fr:"Me demander plus tard",he:"שאל מאוחר יותר",ja:"後で確認する",ko:"나중에 물어보기",ru:"Спросить позже",zh:"稍后问我","zh-tw":"稍後再問我"},"moduleCheckRemoteSize.optionDismiss":{def:"Dismiss",es:"Descartar",fr:"Ignorer",he:"דחה",ja:"無視",ko:"무시",ru:"Отклонить",zh:"忽略","zh-tw":"忽略"},"moduleCheckRemoteSize.optionIncreaseLimit":{def:"increase to ${newMax}MB",es:"aumentar a ${newMax}MB",fr:"augmenter à ${newMax} Mo",he:"הגדל ל-${newMax}MB",ja:"${newMax}MBに設定",ko:"${newMax}MB로 증가",ru:"увеличить до newMaxМБ",zh:"增加到 ${newMax}MB","zh-tw":"提高到 ${newMax}MB"},"moduleCheckRemoteSize.optionNoWarn":{def:"No, never warn please",es:"No, nunca advertir por favor",fr:"Non, ne jamais avertir",he:"לא, אל תזהיר בכלל",ja:"いいえ、警告しないでください",ko:"아니요, 경고하지 마세요",ru:"Нет, не уведомлять",zh:"不,请永远不要警告","zh-tw":"不,請永遠不要警告"},"moduleCheckRemoteSize.optionRebuildAll":{def:"Rebuild Everything Now",es:"Reconstruir todo ahora",fr:"Tout reconstruire maintenant",he:"בנה הכל מחדש עכשיו",ja:"今すべてを再構築",ko:"지금 모든 것 재구축",ru:"Перестроить всё сейчас",zh:"立即重建所有内容","zh-tw":"立即重建全部內容"},"moduleCheckRemoteSize.optionReview":{def:"Review options",es:"Revisar las opciones",ko:"옵션 검토","zh-tw":"檢視選項"},"moduleCheckRemoteSize.titleDatabaseSizeLimitExceeded":{def:"Remote storage size exceeded the limit",es:"El tamaño del almacenamiento remoto superó el límite",fr:"Taille du stockage distant au-delà de la limite",he:"גודל האחסון המרוחד חרג מהמגבלה",ja:"リモートストレージサイズが制限を超過しました",ko:"원격 스토리지 크기가 제한을 초과했습니다",ru:"Размер удалённого хранилища превысил лимит",zh:"远程存储大小超出限制","zh-tw":"遠端儲存空間大小已超過限制"},"moduleCheckRemoteSize.titleDatabaseSizeNotify":{def:"Setting up database size notification",es:"Configuración de notificación de tamaño de base de datos",fr:"Configuration de la notification de taille de base",he:"הגדרת התראה על גודל מסד נתונים",ja:"データベースサイズ通知の設定",ko:"데이터베이스 크기 알림 설정",ru:"Настройка уведомления о размере базы данных",zh:"设置数据库大小通知","zh-tw":"設定資料庫大小通知"},"moduleInputUIObsidian.defaultTitleConfirmation":{def:"Confirmation",es:"Confirmación",fr:"Confirmation",he:"אישור",ja:"確認",ko:"확인",ru:"Подтверждение",zh:"确认","zh-tw":"確認"},"moduleInputUIObsidian.defaultTitleSelect":{def:"Select",es:"Seleccionar",fr:"Sélection",he:"בחר",ja:"選択",ko:"선택",ru:"Выбор",zh:"选择","zh-tw":"選擇"},"moduleInputUIObsidian.optionNo":{def:"No",es:"No",fr:"Non",he:"לא",ja:"いいえ",ko:"아니요",ru:"Нет",zh:"否","zh-tw":"否"},"moduleInputUIObsidian.optionYes":{def:"Yes",es:"Sí",fr:"Oui",he:"כן",ja:"はい",ko:"예",ru:"Да",zh:"是","zh-tw":"是"},"moduleLiveSyncMain.logAdditionalSafetyScan":{def:"Additional safety scan...",es:"Escanéo de seguridad adicional...",fr:"Analyse de sécurité supplémentaire...",he:"סריקת בטיחות נוספת...",ja:"追加の安全スキャン中...",ko:"추가 안전 검사 중...",ru:"Дополнительная проверка безопасности...",zh:"额外的安全扫描...","zh-tw":"額外的安全掃描⋯"},"moduleLiveSyncMain.logLoadingPlugin":{def:"Loading plugin...",es:"Cargando complemento...",fr:"Chargement du plugin...",he:"טוען תוסף...",ja:"プラグインをロード中...",ko:"플러그인 로딩 중...",ru:"Загрузка плагина...",zh:"正在加载插件...","zh-tw":"正在載入外掛⋯"},"moduleLiveSyncMain.logPluginInitCancelled":{def:"Plugin initialisation was cancelled by a module",es:"La inicialización del complemento fue cancelada por un módulo",fr:"L'initialisation du plugin a été annulée par un module",he:"אתחול התוסף בוטל על ידי מודול",ja:"プラグインの初期化がモジュールによってキャンセルされました",ko:"모듈에 의해 플러그인 초기화가 취소되었습니다",ru:"Инициализация плагина отменена модулем",zh:"插件初始化被某个模块取消","zh-tw":"外掛初始化被某個模組取消"},"moduleLiveSyncMain.logPluginVersion":{def:"Self-hosted LiveSync v${manifestVersion} ${packageVersion}",es:"Self-hosted LiveSync v${manifestVersion} ${packageVersion}",fr:"Self-hosted LiveSync v${manifestVersion} ${packageVersion}",he:"Self-hosted LiveSync גרסה ${manifestVersion} ${packageVersion}",ja:"Self-hosted LiveSync v${manifestVersion} ${packageVersion}",ko:"Self-hosted LiveSync v${manifestVersion} ${packageVersion}",ru:"Self-hosted LiveSync vmanifestVersion packageVersion",zh:"Self-hosted LiveSync v${manifestVersion} ${packageVersion}"},"moduleLiveSyncMain.logReadChangelog":{def:"LiveSync has updated, please read the changelog!",es:"LiveSync se ha actualizado, ¡por favor lee el registro de cambios!",fr:"LiveSync a été mis à jour, veuillez lire le journal des modifications !",he:"LiveSync עודכן, אנא קרא את יומן השינויים!",ja:"LiveSyncが更新されました。変更履歴をお読みください!",ko:"LiveSync가 업데이트되었습니다. 변경사항을 읽어보세요!",ru:"LiveSync обновлён, пожалуйста, прочитайте список изменений!",zh:"LiveSync 已更新,请阅读更新日志!","zh-tw":"LiveSync 已更新,請閱讀更新日誌!"},"moduleLiveSyncMain.logSafetyScanCompleted":{def:"Additional safety scan completed",es:"Escanéo de seguridad adicional completado",fr:"Analyse de sécurité supplémentaire terminée",he:"סריקת הבטיחות הנוספת הושלמה",ja:"追加の安全スキャンが完了しました",ko:"추가 안전 검사가 완료되었습니다",ru:"Дополнительная проверка безопасности завершена",zh:"额外的安全扫描完成","zh-tw":"額外的安全掃描已完成"},"moduleLiveSyncMain.logSafetyScanFailed":{def:"Additional safety scan has failed on a module",es:"El escaneo de seguridad adicional ha fallado en un módulo",fr:"L'analyse de sécurité supplémentaire a échoué sur un module",he:"סריקת הבטיחות הנוספת נכשלה במודול",ja:"モジュールで追加の安全スキャンが失敗しました",ko:"모듈에서 추가 안전 검사가 실패했습니다",ru:"Дополнительная проверка безопасности не удалась в модуле",zh:"额外的安全扫描在某个模块上失败","zh-tw":"額外的安全掃描在某個模組上失敗"},"moduleLiveSyncMain.logUnloadingPlugin":{def:"Unloading plugin...",es:"Descargando complemento...",fr:"Déchargement du plugin...",he:"מסיר תוסף...",ja:"プラグインをアンロード中...",ko:"플러그인 언로딩 중...",ru:"Выгрузка плагина...",zh:"正在卸载插件...","zh-tw":"正在卸載外掛⋯"},"moduleLiveSyncMain.logVersionUpdate":{def:"LiveSync has been updated, In case of breaking updates, all automatic synchronization has been temporarily disabled. Ensure that all devices are up to date before enabling.",es:"LiveSync se ha actualizado, en caso de actualizaciones que rompan, toda la sincronización automática se ha desactivado temporalmente. Asegúrate de que todos los dispositivos estén actualizados antes de habilitar.",fr:"LiveSync a été mis à jour. En cas de mises à jour non rétrocompatibles, toute synchronisation automatique a été temporairement désactivée. Assurez-vous que tous les appareils sont à jour avant d'activer.",he:"LiveSync עודכן. במקרה של עדכונים משמעותיים, כל הסנכרון האוטומטי הושבת זמנית. ודא שכל המכשירים מעודכנים לפני ההפעלה.",ja:"LiveSyncが更新されました。互換性のない更新の場合、すべての自動同期が一時的に無効化されています。有効にする前に、すべてのデバイスが最新の状態であることを確認してください。",ko:"LiveSync가 업데이트되었습니다. 호환성 문제가 있는 업데이트의 경우 모든 자동 동기화가 일시적으로 비활성화되었습니다. 활성화하기 전에 모든 기기가 최신 상태인지 확인하세요.",ru:"LiveSync обновлён. В случае критических изменений автоматическая синхронизация временно отключена. Убедитесь, что все устройства обновлены перед включением.",zh:"LiveSync 已更新,如果存在破坏性更新,所有自动同步已暂时禁用。请确保所有设备都更新到最新版本后再启用","zh-tw":"LiveSync 已更新。為避免破壞性更新造成問題,已暫時停用所有自動同步。請確保所有裝置都已更新到最新版本後再啟用。"},"moduleLiveSyncMain.msgScramEnabled":{def:"Self-hosted LiveSync has been configured to ignore some events. Is this correct?\n\n| Type | Status | Note |\n|:---:|:---:|---|\n| Storage Events | ${fileWatchingStatus} | Every modification will be ignored |\n| Database Events | ${parseReplicationStatus} | Every synchronised change will be postponed |\n\nDo you want to resume them and restart Obsidian?\n\n> [!DETAILS]-\n> These flags are set by the plug-in while rebuilding, or fetching. If the process ends abnormally, it may be kept unintended.\n> If you are not sure, you can try to rerun these processes. Make sure to back your vault up.\n",es:"Self-hosted LiveSync se ha configurado para ignorar algunos eventos. ¿Es esto correcto?\n\n| Tipo | Estado | Nota |\n|:---:|:---:|---|\n| Eventos de almacenamiento | ${fileWatchingStatus} | Se ignorará cada modificación |\n| Eventos de base de datos | ${parseReplicationStatus} | Cada cambio sincronizado se pospondrá |\n\n¿Quieres reanudarlos y reiniciar Obsidian?\n\n> [!DETAILS]-\n> Estas banderas son establecidas por el complemento mientras se reconstruye o se obtiene. Si el proceso termina de forma anormal, puede mantenerse sin querer.\n> Si no estás seguro, puedes intentar volver a ejecutar estos procesos. Asegúrate de hacer una copia de seguridad de tu bóveda.\n",fr:"Self-hosted LiveSync a été configuré pour ignorer certains événements. Est-ce correct ?\n\n| Type | Statut | Note |\n|:---:|:---:|---|\n| Événements de stockage | ${fileWatchingStatus} | Toute modification sera ignorée |\n| Événements de base | ${parseReplicationStatus} | Tout changement synchronisé sera reporté |\n\nVoulez-vous les reprendre et redémarrer Obsidian ?\n\n> [!DETAILS]-\n> Ces indicateurs sont définis par le plug-in lors d'une reconstruction ou d'une récupération. Si le processus se termine anormalement, ils peuvent rester activés involontairement.\n> Si vous n'êtes pas certain, vous pouvez relancer ces processus. Veillez à sauvegarder votre coffre.\n",he:"Self-hosted LiveSync הוגדר להתעלם מאירועים מסוימים. האם זה נכון?\n\n| סוג | סטטוס | הערה |\n|:---:|:---:|---|\n| אירועי אחסון | ${fileWatchingStatus} | כל שינוי יתעלם |\n| אירועי מסד נתונים | ${parseReplicationStatus} | כל שינוי מסונכרן יידחה |\n\nהאם לחדש אותם ולהפעיל מחדש את Obsidian?\n\n> [!DETAILS]-\n> דגלים אלה מוגדרים על ידי הפלאגין במהלך בנייה מחדש או משיכה. אם התהליך הסתיים בצורה לא תקינה, ייתכן שהם נשארו כלא מכוון.\n> אם אינך בטוח, ניתן לנסות להריץ מחדש את התהליכים. ודא שיש לך גיבוי של הכספת.\n",ja:"Self-hosted LiveSyncは一部のイベントを無視するように設定されています。これは正しいですか?\n\n| タイプ | ステータス | メモ |\n|:---:|:---:|---|\n| ストレージイベント | ${fileWatchingStatus} | すべての変更が無視されます |\n| データベースイベント | ${parseReplicationStatus} | すべての同期された変更が延期されます |\n\nこれらを再開してObsidianを再起動しますか?\n\n> [!DETAILS]-\n> これらのフラグは、プラグインが再構築またはフェッチ中に設定されます。プロセスが異常終了した場合、意図せず保持されることがあります。\n> 不明な場合は、これらのプロセスを再実行してみてください。必ず保管庫をバックアップしてください。\n",ko:"Self-hosted LiveSync가 일부 이벤트를 무시하도록 설정되어 있습니다. 이 설정이 맞습니까?\n\n| 유형 | 상태 | 설명 |\n|:---:|:---:|---|\n| 스토리지 이벤트 | ${fileWatchingStatus} | 모든 수정 사항이 무시됩니다 |\n| 데이터베이스 이벤트 | ${parseReplicationStatus} | 모든 동기화 변경이 지연됩니다 |\n\n이벤트 감지를 다시 활성화하고 Obsidian을 재시작하시겠습니까?\n\n> [!DETAILS]-\n> 이 플래그는 플러그인이 재구축하거나 가져오는 동안 설정한 것입니다. 처리가 비정상적으로 종료되면 의도치 않게 남아 있을 수 있습니다.\n> 확실하지 않다면 해당 처리를 다시 실행해 보세요. 반드시 보관함을 백업해 두시기 바랍니다.\n",ru:"Self-hosted LiveSync has been configured to ignore some events. Is this correct?\n\n| Type | Status | Note |\n|:---:|:---:|---|\n| Storage Events | ${fileWatchingStatus} | Every modification will be ignored |\n| Database Events | ${parseReplicationStatus} | Every synchronised change will be postponed |\n\nDo you want to resume them and restart Obsidian?\n\n> [!DETAILS]-\n> These flags are set by the plug-in while rebuilding, or fetching. If the process ends abnormally, it may be kept unintended.\n> If you are not sure, you can try to rerun these processes. Make sure to back your vault up.\n",zh:"Self-hosted LiveSync 已被配置为忽略某些事件。这样对吗?\n\n| 类型 | 状态 | 说明 |\n|:---:|:---:|---|\n| 存储事件 | ${fileWatchingStatus} | 所有修改都将被忽略 |\n| 数据库事件 | ${parseReplicationStatus} | 所有同步的更改都将被推迟 |\n\n您想恢复它们并重启 Obsidian 吗?\n\n> [!DETAILS]-\n> 这些标志是在重建或获取时由插件设置的。如果过程异常结束,它们可能会被无意中保留。\n> 如果您不确定,可以尝试重新运行这些过程。请确保备份您的库。\n","zh-tw":"Self-hosted LiveSync 已設定為忽略某些事件。這樣正確嗎?\n\n| 類型 | 狀態 | 說明 |\n|:---:|:---:|---|\n| 儲存空間事件 | ${fileWatchingStatus} | 所有修改都會被忽略 |\n| 資料庫事件 | ${parseReplicationStatus} | 所有已同步的變更都會被延後 |\n\n你想要恢復它們並重新啟動 Obsidian 嗎?\n\n> [!DETAILS]-\n> 這些標記是外掛在重建或抓取時設定的。如果程序異常結束,可能會非預期地留存下來。\n> 如果你不確定,可以嘗試重新執行這些程序。請務必先備份你的 Vault。\n"},"moduleLiveSyncMain.optionKeepLiveSyncDisabled":{def:"Keep LiveSync disabled",es:"Mantener LiveSync desactivado",fr:"Garder LiveSync désactivé",he:"השאר LiveSync מנוטרל",ja:"LiveSyncを無効のままにする",ko:"LiveSync 비활성화 유지",ru:"Оставить LiveSync отключённым",zh:"保持 LiveSync 禁用","zh-tw":"保持 LiveSync 停用"},"moduleLiveSyncMain.optionResumeAndRestart":{def:"Resume and restart Obsidian",es:"Reanudar y reiniciar Obsidian",fr:"Reprendre et redémarrer Obsidian",he:"חדש והפעל מחדש את Obsidian",ja:"再開してObsidianを再起動",ko:"재개 후 Obsidian 재시작",ru:"Продолжить и перезапустить Obsidian",zh:"恢复并重启 Obsidian","zh-tw":"恢復並重新啟動 Obsidian"},"moduleLiveSyncMain.titleScramEnabled":{def:"Scram Enabled",es:"Scram habilitado",fr:"Mode Scram activé",he:"מצב בלימה פעיל",ja:"緊急停止(Scram)が有効",ko:"긴급 정지 활성화됨",ru:"Экстренная остановка включена",zh:"紧急停止已启用","zh-tw":"已啟用緊急處置"},"moduleLocalDatabase.logWaitingForReady":{def:"Waiting for ready...",es:"Esperando a que la base de datos esté lista...",fr:"En attente de disponibilité...",he:"ממתין לכשירות...",ja:"しばらくお待ちください...",ko:"준비 대기 중...",ru:"Ожидание готовности...",zh:"等待就绪...","zh-tw":"正在等待就緒⋯"},"moduleLog.showLog":{def:"Show Log",es:"Mostrar registro",fr:"Afficher le journal",he:"הצג יומן",ja:"ログを表示",ko:"로그 표시",ru:"Показать лог",zh:"显示日志","zh-tw":"顯示日誌"},"moduleMigration.fix0256.buttons.checkItLater":{def:"Check it later",es:"Comprobarlo más tarde",fr:"Vérifier plus tard",he:"בדוק מאוחר יותר",ja:"後で確認する",ko:"나중에 확인",ru:"Проверить позже",zh:"稍后检查","zh-tw":"稍後再檢查"},"moduleMigration.fix0256.buttons.DismissForever":{def:"I have fixed it, and do not ask again",es:"Ya lo he corregido, no volver a preguntar",fr:"J'ai corrigé, et ne plus demander",he:"תיקנתי, ואל תשאל שוב",ja:"修正済み、今後確認しない",ko:"이미 해결했으니 다시 묻지 않기",ru:"Исправлено, больше не спрашивать",zh:"我已经修复了,不再询问","zh-tw":"我已修正,不要再詢問"},"moduleMigration.fix0256.buttons.fix":{def:"Fix",es:"Corregir",fr:"Corriger",he:"תקן",ja:"修正",ko:"수정",ru:"Исправить",zh:"修复","zh-tw":"修正"},"moduleMigration.fix0256.message":{def:'Due to a recent bug (in v0.25.6), some files may not have been saved correctly in the sync database.\nWe have scanned our files and found some that need to be fixed.\n\n**Files ready to be fixed:**\n\n${files}\n\nThese files have size-matched original file on the storage, and are likely to be recoverable.\nWe can use them to fix the database, please click the "Fix" button below to fix them.\n\n${messageUnrecoverable}\n\nIf you want to run it again, you can do so from Hatch.\n',es:"Debido a un error reciente (en la v0.25.6), puede que algunos archivos no se hayan guardado correctamente en la base de datos de sincronización.\nHemos analizado tus archivos y hemos encontrado algunos que hay que corregir.\n\n**Archivos que se pueden corregir:**\n\n${files}\n\nEstos archivos tienen en el almacenamiento un original cuyo tamaño coincide, por lo que es probable que se puedan recuperar.\nPodemos usarlos para corregir la base de datos: pulsa el botón «Corregir» de abajo.\n\n${messageUnrecoverable}\n\nSi quieres volver a ejecutarlo, puedes hacerlo desde Hatch.\n",fr:"En raison d'un bug récent (en v0.25.6), certains fichiers peuvent ne pas avoir été enregistrés correctement dans la base de synchronisation.\nNous avons analysé vos fichiers et trouvé ceux à corriger.\n\n**Fichiers prêts à être corrigés :**\n\n${files}\n\nCes fichiers ont un original de taille correspondante sur le stockage, et sont probablement récupérables.\nNous pouvons les utiliser pour corriger la base, veuillez cliquer sur le bouton « Corriger » ci-dessous pour les réparer.\n\n${messageUnrecoverable}\n\nSi vous voulez relancer l'opération, vous pouvez le faire depuis Hatch.\n",he:'בשל באג אחרון (בגרסה 0.25.6), ייתכן שחלק מהקבצים לא נשמרו כהלכה במסד הנתונים לסנכרון.\nסרקנו את הקבצים ומצאנו כאלה שיש לתקן.\n\n**קבצים מוכנים לתיקון:**\n\n${files}\n\nלקבצים אלה יש קובץ מקורי תואם גודל באחסון, וסביר שניתן לשחזרם.\nניתן להשתמש בהם לתיקון מסד הנתונים. לחץ על כפתור "תקן" למטה לתיקון.\n\n${messageUnrecoverable}\n\nאם ברצונך להריץ שוב, ניתן לעשות זאת מ-Hatch.\n',ja:"最近のバグ(v0.25.6)により、一部のファイルが同期データベースに正しく保存されていない可能性があります。\nファイルをスキャンし、修正が必要なものが見つかりました。\n\n**修正準備ができたファイル:**\n\n${files}\n\nこれらのファイルはストレージ上の元ファイルとサイズが一致しており、復元可能です。\n「修正」ボタンをクリックしてデータベースを修正できます。\n\n${messageUnrecoverable}\n\n再実行したい場合は、Hatchから実行できます。\n",ko:'최근 버그(v0.25.6)로 인해 일부 파일이 동기화 데이터베이스에 올바르게 저장되지 않았을 수 있습니다.\n파일을 검사한 결과 수정이 필요한 파일을 발견했습니다.\n\n**수정할 수 있는 파일:**\n\n${files}\n\n이 파일들은 스토리지에 크기가 일치하는 원본이 있어 복구할 수 있을 것으로 보입니다.\n이를 이용해 데이터베이스를 고칠 수 있으니, 아래 "수정" 버튼을 눌러 주세요.\n\n${messageUnrecoverable}\n\n다시 실행하려면 Hatch에서 실행할 수 있습니다.\n',ru:"Из-за недавней ошибки некоторые файлы могут быть неправильно сохранены.",zh:"由于最近的一个 bug(在 v0.25.6 版本中),某些文件可能未正确保存到同步数据库中\n我们已经扫描了文件,并发现一些需要修复的文件\n\n**准备修复的文件:**\n\n${files}\n\n这些文件在存储中与原文件的大小匹配,可能是可恢复的\n我们可以使用它们修复数据库,请点击下方的“修复”按钮进行修复\n\n${messageUnrecoverable}\n\n\n如果你希望再次执行此操作,可以前往 Hatch 页面进行操作\n","zh-tw":"由於近期的一個問題(存在於 v0.25.6),部分檔案可能未正確儲存到同步資料庫中。\n我們已掃描你的檔案,並找出一些需要修正的項目。\n\n**可以修正的檔案:**\n\n${files}\n\n這些檔案在儲存空間中有大小相符的原始檔案,很可能可以復原。\n我們可以用它們修正資料庫,請點選下方的「修正」按鈕進行修正。\n\n${messageUnrecoverable}\n\n如果你想再次執行,可以從 Hatch 頁面操作。\n"},"moduleMigration.fix0256.messageUnrecoverable":{def:"**Files cannot be fixed on this device:**\n\n${filesNotRecoverable}\n\nThese files have inconsistent metadata, and cannot be fixed on this device (mostly we cannot determine which is correct).\nTo restore them, please check your other devices (also by this feature) or restore them manually from a backup.\n",es:"**Archivos que no se pueden corregir en este dispositivo:**\n\n${filesNotRecoverable}\n\nEstos archivos tienen metadatos inconsistentes y no se pueden corregir en este dispositivo (por lo general no podemos determinar cuál es el correcto).\nPara restaurarlos, comprueba tus otros dispositivos (también con esta función) o restáuralos manualmente desde una copia de seguridad.\n",fr:"**Fichiers non réparables sur cet appareil :**\n\n${filesNotRecoverable}\n\nCes fichiers ont des métadonnées incohérentes et ne peuvent être corrigés sur cet appareil (le plus souvent, nous ne pouvons déterminer lequel est correct).\nPour les restaurer, vérifiez vos autres appareils (par cette même fonction) ou restaurez-les manuellement depuis une sauvegarde.\n",he:"**קבצים שלא ניתן לתקן במכשיר זה:**\n\n${filesNotRecoverable}\n\nלקבצים אלה יש מטה-נתונים לא עקביים, ולא ניתן לתקנם במכשיר זה (לרוב לא ניתן לקבוע מה נכון). לשחזורם, אנא בדוק מכשירים אחרים שלך (גם בתכונה זו) או שחזר ידנית מגיבוי.\n",ja:"**このデバイスで修正できないファイル:**\n\n${filesNotRecoverable}\n\nこれらのファイルはメタデータに不整合があり、このデバイスでは修正できません(ほとんどの場合、どちらが正しいか判定できません)。\n復元するには、他のデバイスで確認するか、バックアップから手動で復元してください。\n",ko:"**이 기기에서는 수정할 수 없는 파일:**\n\n${filesNotRecoverable}\n\n이 파일들은 메타데이터가 일치하지 않아 이 기기에서는 수정할 수 없습니다(대부분 어느 쪽이 올바른지 판단할 수 없습니다).\n복원하려면 다른 기기에서 이 기능으로 확인해 보시거나, 백업에서 직접 복원해 주세요.\n",ru:"Файлы не могут быть исправлены на этом устройстве:",zh:"**无法在此设备上修复的文件:**\n\n${filesNotRecoverable}\n\n这些文件的元数据不一致,无法在此设备上修复(大多数情况下我们无法确定哪一个是正确的)\n要恢复它们,请检查你的其他设备(同样使用此功能),或从备份中手动恢复\n","zh-tw":"**無法在此裝置上修正的檔案:**\n\n${filesNotRecoverable}\n\n這些檔案的中繼資料不一致,無法在此裝置上修正(多數情況下我們無法判斷哪一份才正確)。\n若要復原它們,請檢查你的其他裝置(同樣使用此功能),或從備份手動復原。\n"},"moduleMigration.fix0256.title":{def:"Broken files has been detected",es:"Se han detectado archivos dañados",fr:"Fichiers corrompus détectés",he:"זוהו קבצים פגומים",ja:"破損ファイルが検出されました",ko:"손상된 파일이 감지되었습니다",ru:"Обнаружены повреждённые файлы",zh:"检测到损坏的文件","zh-tw":"已偵測到損壞的檔案"},"moduleMigration.insecureChunkExist.buttons.fetch":{def:"I already rebuilt the remote. Fetch from the remote",es:"Ya he reconstruido el remoto. Obtener desde el remoto",fr:"J'ai déjà reconstruit le distant. Récupérer depuis le distant",he:"כבר בניתי מחדש את השרת המרוחק. משוך מהשרת המרוחד",ja:"リモートを既に再構築した。リモートからフェッチ",ko:"원격을 이미 재구축했습니다. 원격에서 가져오기",ru:"Я уже перестроил удалённую. Загрузить с удалённой",zh:"我已经重建了远程数据库,将从远程获取","zh-tw":"我已重建遠端,從遠端抓取"},"moduleMigration.insecureChunkExist.buttons.later":{def:"I will do it later",es:"Lo haré más tarde",fr:"Je le ferai plus tard",he:"אטפל בזה מאוחר יותר",ja:"後で行う",ko:"나중에 하기",ru:"Сделаю позже",zh:"我稍后再做","zh-tw":"我稍後再處理"},"moduleMigration.insecureChunkExist.buttons.rebuild":{def:"Rebuild Everything",es:"Reconstruir todo",fr:"Tout reconstruire",he:"בנה הכל מחדש",ja:"すべてを再構築",ko:"모두 재구축",ru:"Перестроить всё",zh:"重建所有内容","zh-tw":"重建全部"},"moduleMigration.insecureChunkExist.laterMessage":{def:"We strongly recommend to treat this as soon as possible!",es:"¡Te recomendamos encarecidamente solucionarlo cuanto antes!",fr:"Nous recommandons fortement de traiter ceci dès que possible !",he:"אנו ממליצים בחום לטפל בזה בהקדם האפשרי!",ja:"できるだけ早く対処することを強くお勧めします!",ko:"가능한 한 빨리 조치하시기를 강력히 권장합니다!",ru:"Мы настоятельно рекомендуем обработать это как можно скорее!",zh:"我们强烈建议尽快处理此问题!","zh-tw":"我們強烈建議盡快處理此問題!"},"moduleMigration.insecureChunkExist.message":{def:"Some chunks are not securely stored and are not encrypted in databases.\n**Please rebuild the database to fix this issue**.\n\nIf your Remote Database is not configured with SSL, or using less-secure credentials, **you are at risk of exposing sensitive data**.\n\nNote: Please upgrade your Self-hosted LiveSync v0.25.6 or higher on all your devices, and back your vault up surely.\nNote2: Rebuild Everything and Fetch consumes a bit of time and traffic, please do it in off-peak hours and ensure a stable network connection.\n",es:"Algunos chunks no se almacenan de forma segura y no están cifrados en las bases de datos.\n**Reconstruye la base de datos para solucionarlo**.\n\nSi tu base de datos remota no está configurada con SSL o usa credenciales poco seguras, **corres el riesgo de exponer datos sensibles**.\n\nNota: actualiza Self-hosted LiveSync a la v0.25.6 o superior en todos tus dispositivos y haz una copia de seguridad fiable de tu vault.\nNota 2: reconstruir todo y obtener los datos consume algo de tiempo y de tráfico; hazlo en horas de poco uso y con una conexión de red estable.\n",fr:"Certains fragments ne sont pas stockés de façon sécurisée et ne sont pas chiffrés dans les bases.\n**Veuillez reconstruire la base pour corriger ce problème.**\n\nSi votre base distante n'est pas configurée avec SSL, ou utilise des identifiants peu sûrs, **vous risquez d'exposer des données sensibles**.\n\nNote : Veuillez mettre à jour Self-hosted LiveSync en v0.25.6 ou supérieur sur tous vos appareils, et sauvegardez votre coffre avec soin.\nNote 2 : Tout reconstruire et Récupérer consomme un peu de temps et de bande passante, veuillez le faire hors des heures de pointe et avec une connexion réseau stable.\n",he:"חלק מהנתחים לא מאוחסנים בצורה מאובטחת ואינם מוצפנים במסד הנתונים.\n**אנא בנה מחדש את מסד הנתונים כדי לתקן בעיה זו**.\n\nאם מסד הנתונים המרוחד אינו מוגדר עם SSL, או משתמש בפרטי גישה פחות מאובטחים, **אתה בסיכון של חשיפת מידע רגיש**.\n\nהערה: אנא שדרג את Self-hosted LiveSync לגרסה 0.25.6 ומעלה על כל מכשיריך, וגבה את הכספת שלך.\nהערה 2: בנייה מחדש ומשיכה דורשות זמן ותעבורת רשת. אנא עשה זאת בשעות שיא נמוך וודא חיבור רשת יציב.\n",ja:"一部のチャンクが安全に保存されておらず、データベースで暗号化されていません。\n**この問題を修正するにはデータベースを再構築してください**。\n\nリモートデータベースがSSLで設定されていない、または安全性の低い認証情報を使用している場合、**機密データが漏洩するリスクがあります**。\n\n注意: すべてのデバイスでSelf-hosted LiveSync v0.25.6以降にアップグレードし、必ず保管庫をバックアップしてください。\n注意2: すべてを再構築とフェッチは時間とトラフィックを消費します。オフピーク時間に安定したネットワークで実行してください。\n",ko:"일부 청크가 데이터베이스에 안전하게 저장되지 않았으며 암호화되어 있지 않습니다.\n**이 문제를 해결하려면 데이터베이스를 재구축해 주세요.**\n\n원격 데이터베이스에 SSL이 설정되어 있지 않거나 보안이 취약한 자격 증명을 사용하고 있다면, **민감한 데이터가 노출될 위험이 있습니다.**\n\n참고: 모든 기기의 Self-hosted LiveSync를 v0.25.6 이상으로 업그레이드하고, 보관함을 반드시 백업해 주세요.\n참고 2: 모두 재구축과 가져오기는 시간과 트래픽을 다소 소모하므로, 사용량이 적은 시간대에 안정적인 네트워크 환경에서 진행해 주세요.\n",ru:"Некоторые чанки хранятся небезопасно. Пожалуйста, перестройте базу данных.",zh:"一些块未安全存储,并且在数据库中未加密\n**请重建数据库以修复此问题**.\n\n如果你的远程数据库未配置 SSL,或者使用了不安全的凭据 **你可能面临暴露敏感数据的风险**.\n\n注意:请在所有设备上将 Self-hosted LiveSync 升级到 v0.25.6 或更高版本,并确保备份你的保险库\n\n注意2:重建所有内容和获取操作会消耗一些时间和流量,请在非高峰时段进行,并确保网络连接稳定\n","zh-tw":"部分 chunks 未安全儲存,在資料庫中也未加密。\n**請重建資料庫以修正此問題**。\n\n如果你的遠端資料庫未設定 SSL,或使用了安全性較低的憑證,**敏感資料就有外洩風險**。\n\n注意:請將所有裝置上的 Self-hosted LiveSync 升級到 v0.25.6 或更新版本,並確實備份你的 Vault。\n注意 2:重建全部與抓取會耗用一些時間與流量,請在離峰時段進行,並確保網路連線穩定。\n"},"moduleMigration.insecureChunkExist.title":{def:"Insecure chunks found!",es:"¡Se han encontrado chunks no seguros!",fr:"Fragments non sécurisés détectés !",he:"נמצאו נתחים לא מאובטחים!",ja:"安全でないチャンクが見つかりました!",ko:"안전하지 않은 청크가 발견되었습니다!",ru:"Обнаружены небезопасные чанки!",zh:"发现不安全的块!","zh-tw":"發現不安全的 chunks"},"moduleMigration.logBulkSendCorrupted":{def:"Send chunks in bulk has been enabled, however, this feature had been corrupted. Sorry for your inconvenience. Automatically disabled.",es:"El envío de fragmentos en bloque se ha habilitado, sin embargo, esta función se ha corrompido. Disculpe las molestias. Deshabilitado automáticamente.",fr:"L'envoi groupé de fragments a été activé, mais cette fonctionnalité était corrompue. Désolé pour la gêne. Désactivée automatiquement.",he:"שליחת נתחים באצווה הופעלה, אך תכונה זו הייתה פגועה. מתנצלים על אי הנוחות. נוטרלה אוטומטית.",ja:"チャンクの一括送信が有効にされていましたが、この機能に問題がありました。ご不便をおかけして申し訳ありません。自動的に無効化されました。",ko:"청크 일괄 전송이 활성화되었지만, 이 기능에 문제가 있었습니다. 불편을 드려 죄송합니다. 자동으로 비활성화되었습니다.",ru:"Отправка чанков пакетами была включена, но эта функция была повреждена. Приносим извинения. Автоматически отключено.",zh:"已启用批量发送 chunks,但此功能已损坏。给您带来不便,我们深表歉意。已自动禁用","zh-tw":"已啟用批次傳送 chunks,但此功能已損壞。造成不便,敬請見諒。已自動停用。"},"moduleMigration.logFetchRemoteTweakFailed":{def:"Failed to fetch remote tweak values",es:"Error al obtener los valores de ajuste remoto",fr:"Échec de la récupération des valeurs d'ajustement distantes",he:"נכשל במשיכת ערכי כיוונון מרוחקים",ja:"リモートの調整値の取得に失敗しました",ko:"원격 조정 값을 가져오는데 실패했습니다",ru:"Не удалось загрузить удалённые настройки",zh:"获取远程调整值失败","zh-tw":"無法取得遠端調校值"},"moduleMigration.logLocalDatabaseNotReady":{def:"Something went wrong! The local database is not ready",es:"¡Algo salió mal! La base de datos local no está lista",fr:"Un problème est survenu ! La base locale n'est pas prête",he:"משהו השתבש! מסד הנתונים המקומי אינו מוכן",ja:"何か問題が発生しました!ローカルデータベースが準備できていません",ko:"문제가 발생했습니다! 로컬 데이터베이스가 준비되지 않았습니다",ru:"Что-то пошло не так! Локальная база данных не готова",zh:"出错了!本地数据库尚未准备好","zh-tw":"發生問題!本機資料庫尚未就緒"},"moduleMigration.logMigratedSameBehaviour":{def:"Migrated to db:${current} with the same behaviour as before",es:"Migrado a db:${current} con el mismo comportamiento que antes",fr:"Migration vers db:${current} avec le même comportement qu'auparavant",he:"הוגר ל-db:${current} עם אותה התנהגות כמקודם",ja:"以前と同じ動作でdb:${current}に移行しました",ko:"이전과 동일하게 동작하도록 db:${current}(으)로 마이그레이션했습니다",ru:"Миграция на db:current с тем же поведением, что и раньше",zh:"已迁移到 db:${current},行为与之前相同","zh-tw":"已遷移到 db:${current},行為與先前相同"},"moduleMigration.logMigrationFailed":{def:"Migration failed or cancelled from ${old} to ${current}",es:"La migración falló o se canceló de ${old} a ${current}",fr:"Migration échouée ou annulée de ${old} vers ${current}",he:"הגירה נכשלה או בוטלה מ-${old} ל-${current}",ja:"${old}から${current}への移行が失敗またはキャンセルされました",ko:"${old}에서 ${current}로의 데이터 구조 전환이 실패했거나 중단되었습니다",ru:"Миграция не удалась или отменена с old на current",zh:"从 ${old} 到 ${current} 的迁移失败或已取消","zh-tw":"從 ${old} 遷移到 ${current} 失敗或已取消"},"moduleMigration.logRedflag2CreationFail":{def:"Failed to create redflag2",es:"Error al crear redflag2",fr:"Échec de création de redflag2",he:"יצירת redflag2 נכשלה",ja:"redflag2の作成に失敗しました",ko:"redflag2 생성에 실패했습니다",ru:"Не удалось создать redflag2",zh:"创建 redflag2 失败","zh-tw":"無法建立 redflag2"},"moduleMigration.logRemoteTweakUnavailable":{def:"Could not get remote tweak values",es:"No se pudieron obtener los valores de ajuste remoto",fr:"Impossible d'obtenir les valeurs d'ajustement distantes",he:"לא ניתן לקבל ערכי כיוונון מרוחקים",ja:"リモートの調整値を取得できませんでした",ko:"원격 조정 값을 가져올 수 없습니다",ru:"Не удалось получить удалённые настройки",zh:"无法获取远程调整值","zh-tw":"無法取得遠端調校值"},"moduleMigration.logSetupCancelled":{def:"The setup has been cancelled, Self-hosted LiveSync waiting for your setup!",es:"La configuración ha sido cancelada, ¡Self-hosted LiveSync está esperando tu configuración!",fr:"La configuration a été annulée, Self-hosted LiveSync attend votre configuration !",he:"ההגדרה בוטלה, Self-hosted LiveSync ממתין להגדרתך!",ja:"セットアップがキャンセルされました。Self-hosted LiveSyncはセットアップを待っています!",ko:"설정이 취소되었습니다. Self-hosted LiveSync가 설정을 기다리고 있습니다!",ru:"Настройка отменена, Self-hosted LiveSync ожидает вашей настройки!",zh:"设置已取消,Self-hosted LiveSync 正在等待您的设置!","zh-tw":"設定已取消,Self-hosted LiveSync 正在等候你完成設定!"},"moduleMigration.msgFetchRemoteAgain":{def:"As you may already know, the self-hosted LiveSync has changed its default behaviour and database structure.\n\nAnd thankfully, with your time and efforts, the remote database appears to have already been migrated. Congratulations!\n\nHowever, we need a bit more. The configuration of this device is not compatible with the remote database. We will need to fetch the remote database again. Should we fetch from the remote again now?\n\n___Note: We cannot synchronise until the configuration has been changed and the database has been fetched again.___\n___Note2: The chunks are completely immutable, we can fetch only the metadata and difference.___",es:"Como ya sabrás, Self-hosted LiveSync ha cambiado su comportamiento predeterminado y la estructura de la base de datos.\n\nAfortunadamente, con tu tiempo y esfuerzo, la base de datos remota parece haber sido ya migrada. ¡Felicidades!\n\nSin embargo, necesitamos un poco más. La configuración de este dispositivo no es compatible con la base de datos remota. Necesitaremos volver a obtener la base de datos remota. ¿Debemos obtenerla nuevamente ahora?\n\n___Nota: No podemos sincronizar hasta que la configuración haya sido cambiada y la base de datos haya sido obtenida nuevamente.___\n___Nota2: Los fragmentos son completamente inmutables, solo podemos obtener los metadatos y diferencias.___",fr:"Comme vous le savez peut-être déjà, Self-hosted LiveSync a modifié son comportement par défaut et la structure de sa base de données.\n\nEt, grâce à votre temps et vos efforts, la base distante semble déjà avoir été migrée. Félicitations !\n\nCependant, il faut encore un peu plus. La configuration de cet appareil n'est pas compatible avec la base distante. Nous devrons récupérer à nouveau la base distante. Devons-nous récupérer depuis le distant maintenant ?\n\n___Note : Nous ne pouvons pas synchroniser tant que la configuration n'a pas été modifiée et que la base n'a pas été récupérée à nouveau.___\n___Note 2 : Les fragments sont complètement immuables, nous ne pouvons récupérer que les métadonnées et les différences.___",he:"כפי שייתכן שכבר ידוע לך, Self-hosted LiveSync שינה את התנהגות ברירת המחדל ומבנה מסד הנתונים.\n\nובזכות זמנך ומאמציך, מסד הנתונים המרוחד נראה כבר הוגר. ברכות!\n\nעם זאת, נדרש עוד קצת. תצורת מכשיר זה אינה תואמת למסד הנתונים המרוחד. נצטרך למשוך את מסד הנתונים המרוחד שוב. האם למשוך מהשרת המרוחד עכשיו?\n\n___הערה: לא ניתן לסנכרן עד שהתצורה תשתנה ומסד הנתונים יימשך שוב.___\n___הערה 2: הנתחים הם בלתי-ניתנים לשינוי לחלוטין, ניתן למשוך רק את המטה-נתונים וההפרש.___",ja:"ご存知のとおり、self-hosted LiveSyncはデフォルトの動作とデータベース構造を変更しました。\n\nご協力のおかげで、リモートデータベースはすでに移行されているようです。おめでとうございます!\n\nしかし、もう少し必要です。このデバイスの設定はリモートデータベースと互換性がありません。リモートデータベースを再度フェッチする必要があります。今すぐリモートから再フェッチしますか?\n\n___注意: 設定が変更され、データベースが再フェッチされるまで同期できません。___\n___注意2: チャンクは完全に不変なので、メタデータと差分のみフェッチできます。___",ko:"이미 알고 계시겠지만, Self-hosted LiveSync의 기본 동작 방식과 데이터베이스 구조가 변경되었습니다.\n\n다행히도 여러분의 노력 덕분에 원격 데이터베이스는 이미 성공적으로 데이터 구조 전환이 완료된 것으로 보입니다. 축하드립니다!\n\n하지만 아직 일부 추가 작업이 필요합니다. 이 기기의 설정이 원격 데이터베이스와 호환되지 않으므로, 원격 데이터를 다시 가져와야 합니다. 지금 원격 데이터베이스를 다시 가져오시겠습니까?\n\n___참고: 설정이 변경되고 데이터베이스를 다시 불러오기 전까지는 동기화가 불가능합니다.___\n___참고2: 청크는 변경이 불가능한 구조이므로, 메타데이터와 차이점만 가져올 수 있습니다.___",ru:"Удалённая база данных, похоже, уже была мигрирована. Конфигурация этого устройства несовместима.",zh:"您可能已经知道,Self-hosted LiveSync 更改了其默认行为和数据库结构。\n\n值得庆幸的是,在您的时间和努力下,远程数据库似乎已经迁移完成。恭喜!\n\n但是,我们还需要一点点操作。此设备的配置与远程数据库不兼容。我们需要再次从远程数据库获取。我们现在应该再次从远程获取吗?\n\n___注意:在更改配置并再次获取数据库之前,我们无法进行同步。___\n___注意2:chunks 是完全不可变的,我们只能获取元数据和差异","zh-tw":"你可能已經知道,Self-hosted LiveSync 變更了預設行為與資料庫結構。\n\n值得慶幸的是,在你的努力下,遠端資料庫似乎已經完成遷移。恭喜!\n\n不過,還需要再多做一點。此裝置的設定與遠端資料庫不相容,我們需要再次從遠端資料庫抓取。現在要再次從遠端抓取嗎?\n\n___注意:在變更設定並再次抓取資料庫之前,我們無法進行同步。___\n___注意 2:chunks 完全不可變,我們只需要抓取中繼資料與差異部分。___"},"moduleMigration.msgSinceV02321":{def:"Since v0.23.21, the self-hosted LiveSync has changed the default behaviour and database structure. The following changes have been made:\n\n1. **Case sensitivity of filenames**\n The handling of filenames is now case-insensitive. This is a beneficial change for most platforms, other than Linux and iOS, which do not manage filename case sensitivity effectively.\n (On These, a warning will be displayed for files with the same name but different cases).\n\n2. **Revision handling of the chunks**\n Chunks are immutable, which allows their revisions to be fixed. This change will enhance the performance of file saving.\n\n___However, to enable either of these changes, both remote and local databases need to be rebuilt. This process takes a few minutes, and we recommend doing it when you have ample time.___\n\n- If you wish to maintain the previous behaviour, you can skip this process by using `${KEEP}`.\n- If you do not have enough time, please choose `${DISMISS}`. You will be prompted again later.\n- If you have rebuilt the database on another device, please select `${DISMISS}` and try synchronizing again. Since a difference has been detected, you will be prompted again.",es:"Desde la versión v0.23.21, Self-hosted LiveSync ha cambiado el comportamiento predeterminado y la estructura de la base de datos. Se han realizado los siguientes cambios:\n\n1. **Sensibilidad a mayúsculas de los nombres de archivo**\n El manejo de los nombres de archivo ahora no distingue entre mayúsculas y minúsculas. Este cambio es beneficioso para la mayoría de las plataformas, excepto Linux y iOS, que no gestionan efectivamente la sensibilidad a mayúsculas de los nombres de archivo.\n (En estos, se mostrará una advertencia para archivos con el mismo nombre pero diferentes mayúsculas).\n\n2. **Manejo de revisiones de los fragmentos**\n Los fragmentos son inmutables, lo que permite que sus revisiones sean fijas. Este cambio mejorará el rendimiento al guardar archivos.\n\n___Sin embargo, para habilitar cualquiera de estos cambios, es necesario reconstruir tanto las bases de datos remota como la local. Este proceso toma unos minutos, y recomendamos hacerlo cuando tengas tiempo suficiente.___\n\n- Si deseas mantener el comportamiento anterior, puedes omitir este proceso usando `${KEEP}`.\n- Si no tienes suficiente tiempo, por favor elige `${DISMISS}`. Se te pedirá nuevamente más tarde.\n- Si has reconstruido la base de datos en otro dispositivo, selecciona `${DISMISS}` e intenta sincronizar nuevamente. Dado que se ha detectado una diferencia, se te solicitará nuevamente.",fr:"Depuis la v0.23.21, Self-hosted LiveSync a modifié son comportement par défaut et la structure de sa base. Les changements suivants ont été effectués :\n\n1. **Sensibilité à la casse des noms de fichiers**\n La gestion des noms de fichiers est désormais insensible à la casse. C'est un changement bénéfique pour la plupart des plateformes, hormis Linux et iOS, qui ne gèrent pas efficacement la casse des noms de fichiers.\n (Sur celles-ci, un avertissement s'affichera pour les fichiers portant le même nom avec une casse différente).\n\n2. **Gestion des révisions des fragments**\n Les fragments sont immuables, ce qui permet de fixer leurs révisions. Ce changement améliore les performances d'enregistrement des fichiers.\n\n___Cependant, pour activer l'un ou l'autre de ces changements, les bases locale et distante doivent être reconstruites. Ce processus prend quelques minutes, et nous recommandons de le faire quand vous avez le temps.___\n\n- Si vous souhaitez conserver le comportement précédent, vous pouvez ignorer ce processus via `${KEEP}`.\n- Si vous n'avez pas le temps, choisissez `${DISMISS}`. Vous serez invité à nouveau plus tard.\n- Si vous avez reconstruit la base sur un autre appareil, sélectionnez `${DISMISS}` et réessayez la synchronisation. Une différence étant détectée, vous serez invité à nouveau.",he:"מאז גרסה 0.23.21, Self-hosted LiveSync שינה את התנהגות ברירת המחדל ומבנה מסד הנתונים. השינויים הבאים בוצעו:\n\n1. **תלות רישיות בשמות קבצים**\n הטיפול בשמות קבצים הוא כעת ללא תלות רישיות. זהו שינוי מועיל לרוב הפלטפורמות,\n פרט ל-Linux ו-iOS שאינן מנהלות תלות רישיות בקבצים ביעילות.\n (בפלטפורמות אלה, תוצג אזהרה עבור קבצים עם אותו שם אך רישיות שונה).\n\n2. **טיפול בגרסאות של נתחים**\n נתחים הם בלתי-ניתנים לשינוי, מה שמאפשר גרסאות קבועות. שינוי זה ישפר את\n ביצועי שמירת הקבצים.\n\n___עם זאת, כדי להפעיל אחד מהשינויים הללו, יש לבנות מחדש גם את מסד הנתונים המרוחד וגם את המקומי. תהליך זה לוקח כמה דקות, ואנו ממליצים לעשות זאת כשיש לך זמן פנוי.___\n\n- אם ברצונך לשמור את ההתנהגות הקודמת, ניתן לדלג על תהליך זה באמצעות `${KEEP}`.\n- אם אין לך מספיק זמן, אנא בחר `${DISMISS}`. תקבל תזכורת בהמשך.\n- אם בנית מחדש את מסד הנתונים במכשיר אחר, אנא בחר `${DISMISS}` ונסה לסנכרן שוב. מאחר שזוהה הפרש, תקבל תזכורת שוב.",ja:"v0.23.21以降、self-hosted LiveSyncはデフォルトの動作とデータベース構造を変更しました。以下の変更が行われました:\n\n1. **ファイル名の大文字小文字の区別**\n ファイル名の処理が大文字小文字を区別しなくなりました。これは、ファイル名の大文字小文字を効果的に管理しないLinuxとiOS以外のほとんどのプラットフォームにとって有益な変更です。\n (これらの環境では、同じ名前で大文字小文字が異なるファイルに対して警告が表示されます)。\n\n2. **チャンクのリビジョン処理**\n チャンクは不変であり、リビジョンを固定できます。この変更により、ファイル保存のパフォーマンスが向上します。\n\n___しかし、これらの変更を有効にするには、リモートとローカルの両方のデータベースを再構築する必要があります。このプロセスは数分かかります。時間に余裕があるときに行うことをお勧めします。___\n\n- 以前の動作を維持したい場合は、`${KEEP}`を使用してこのプロセスをスキップできます。\n- 時間がない場合は、`${DISMISS}`を選択してください。後で再度確認されます。\n- 別のデバイスでデータベースを再構築した場合は、`${DISMISS}`を選択して再度同期してみてください。差異が検出されたため、再度確認されます。",ko:"v0.23.21부터 Self-hosted LiveSync의 기본 동작 방식과 데이터베이스 구조가 변경되었습니다. 변경 내용은 다음과 같습니다:\n\n1. **파일명의 대소문자 구분**\n 이제 파일명을 대소문자 구분 없이 처리합니다. 파일명의 대소문자를 제대로 관리하지 못하는 Linux와 iOS를 제외한 대부분의 플랫폼에서 유리한 변경입니다.\n (해당 플랫폼에서는 이름이 같고 대소문자만 다른 파일에 대해 경고가 표시됩니다)\n\n2. **청크의 리비전 처리**\n 청크는 변경 불가능하므로 리비전을 고정할 수 있습니다. 이 변경으로 파일 저장 성능이 향상됩니다.\n\n___다만 이 변경 중 어느 하나라도 적용하려면 원격과 로컬 데이터베이스를 모두 재구축해야 합니다. 이 과정은 몇 분이 걸리므로 시간이 충분할 때 진행하시기를 권장합니다.___\n\n- 기존 동작을 유지하려면 `${KEEP}`을 선택해 이 과정을 건너뛸 수 있습니다.\n- 시간이 충분하지 않다면 `${DISMISS}`를 선택해 주세요. 나중에 다시 여쭤보겠습니다.\n- 다른 기기에서 이미 데이터베이스를 재구축했다면 `${DISMISS}`를 선택한 뒤 다시 동기화해 보세요. 차이가 감지되면 다시 안내해 드립니다.",ru:"Начиная с v0.23.21, self-hosted LiveSync изменил поведение и структуру базы данных.",zh:"自 v0.23.21 起,Self-hosted LiveSync 更改了默认行为和数据库结构。进行了以下更改:\n\n1. **文件名的区分大小写**\n现在处理文件名时不区分大小写。这对于大多数平台来说是一个有益的更改,除了 Linux 和 iOS,它们不能有效地管理文件名的大小写敏感性。\n(在这些平台上,对于名称相同但大小写不同的文件将显示警告)。\n\n2. **chunks 的版本处理**\nchunks 是不可变的,这使得它们的版本可以固定。此更改将提高文件保存的性能。\n\n___然而,要启用这些更改中的任何一个,都需要重建远程和本地数据库。这个过程需要几分钟,我们建议您在有充足时间时进行。___\n\n- 如果您希望保持以前的行为,可以使用 `${KEEP}` 跳过此过程。\n- 如果您没有足够的时间,请选择 `${DISMISS}`。稍后会再次提示您。\n- 如果您已在另一台设备上重建了数据库,请选择 `${DISMISS}` 并尝试再次同步。由于检测到差异,系统会再次提示您","zh-tw":"自 v0.23.21 起,Self-hosted LiveSync 變更了預設行為與資料庫結構,進行了以下變更:\n\n1. **檔名的大小寫敏感性**\n 現在處理檔名時不區分大小寫。這對多數平台是有益的變更,除了 Linux 與 iOS,它們無法有效處理檔名的大小寫敏感性。\n (在這些平台上,檔名相同但大小寫不同的檔案會顯示警告。)\n\n2. **chunks 的版本處理**\n chunks 是不可變的,因此可以固定其版本。這項變更會提升檔案儲存的效能。\n\n___不過,若要啟用這兩項變更中的任何一項,都需要重建遠端與本機資料庫。這個過程需要幾分鐘,建議在時間充裕時進行。___\n\n- 如果你想維持先前的行為,可以使用 `${KEEP}` 略過此程序。\n- 如果你目前沒有足夠的時間,請選擇 `${DISMISS}`,之後會再次提示你。\n- 如果你已在其他裝置上重建過資料庫,請選擇 `${DISMISS}` 並再次嘗試同步;由於偵測到差異,系統會再次提示你。"},"moduleMigration.optionAdjustRemote":{def:"Adjust to remote",es:"Ajustar al remoto",fr:"Ajuster au distant",he:"התאם לשרת המרוחד",ja:"リモートに合わせる",ko:"원격에 맞추기",ru:"Настроить под удалённую",zh:"调整到远程设置","zh-tw":"調整為遠端設定"},"moduleMigration.optionDecideLater":{def:"Decide it later",es:"Decidirlo más tarde",fr:"Décider plus tard",he:"החלט מאוחר יותר",ja:"後で決める",ko:"나중에 결정하기",ru:"Решить позже",zh:"稍后决定","zh-tw":"稍後再決定"},"moduleMigration.optionEnableBoth":{def:"Enable both",es:"Habilitar ambos",fr:"Activer les deux",he:"הפעל את שניהם",ja:"両方を有効にする",ko:"둘 다 활성화",ru:"Включить оба",zh:"启用两者","zh-tw":"兩者都啟用"},"moduleMigration.optionEnableFilenameCaseInsensitive":{def:"Enable only #1",es:"Habilitar solo #1",fr:"Activer seulement #1",he:"הפעל רק #1",ja:"#1のみ有効にする",ko:"#1만 활성화",ru:"Включить только #1",zh:"仅启用 #1","zh-tw":"僅啟用"},"moduleMigration.optionEnableFixedRevisionForChunks":{def:"Enable only #2",es:"Habilitar solo #2",fr:"Activer seulement #2",he:"הפעל רק #2",ja:"#2のみ有効にする",ko:"#2만 활성화",ru:"Включить только #2",zh:"仅启用 #2","zh-tw":"僅啟用"},"moduleMigration.optionKeepPreviousBehaviour":{def:"Keep previous behaviour",es:"Mantener comportamiento anterior",fr:"Conserver le comportement précédent",he:"שמור על התנהגות קודמת",ja:"以前の動作を維持",ko:"이전 동작 유지",ru:"Сохранить предыдущее поведение",zh:"保持以前的行为","zh-tw":"保留先前的行為"},"moduleMigration.optionNoAskAgain":{def:"No, please ask again",es:"No, por favor pregúntame de nuevo",fr:"Non, demandez à nouveau",he:"לא, אנא שאל שוב",ja:"いいえ、後で確認する",ko:"아니요 (나중에 다시 물어보기)",ru:"Нет, спросить снова",zh:"不,请稍后再次询问","zh-tw":"不,請稍後再問我"},"moduleMigration.optionYesFetchAgain":{def:"Yes, fetch again",es:"Sí, obtener de nuevo",fr:"Oui, récupérer à nouveau",he:"כן, משוך שוב",ja:"はい、再フェッチする",ko:"예 (다시 가져오기)",ru:"Да, загрузить снова",zh:"是的,再次获取","zh-tw":"是,再次抓取"},"moduleMigration.titleCaseSensitivity":{def:"Case Sensitivity",es:"Distinción de mayúsculas y minúsculas",fr:"Sensibilité à la casse",he:"תלות רישיות",ja:"大文字小文字の区別",ko:"대소문자 구분",ru:"Чувствительность к регистру",zh:"大小写敏感性","zh-tw":"大小寫敏感性"},"moduleObsidianMenu.replicate":{def:"Replicate",es:"Replicar",fr:"Répliquer",he:"שכפל",ja:"レプリケート",ko:"복제",ru:"Реплицировать",zh:"复制","zh-tw":"複寫"},"More actions":{def:"More actions",es:"Más acciones",ja:"その他の操作",ko:"추가 작업",ru:"Другие действия",zh:"更多操作","zh-tw":"更多操作"},"Mostly Complete: Decision Required":{def:"Mostly Complete: Decision Required",es:"Casi terminado: se requiere una decisión",ko:"거의 완료: 결정이 필요합니다","zh-tw":"大致完成:需要你做出決定"},"Move remotely deleted files to the trash, instead of deleting.":{def:"Move remotely deleted files to the trash, instead of deleting.",es:"Mover archivos borrados remotos a papelera en lugar de eliminarlos",fr:"Déplacer les fichiers supprimés à distance vers la corbeille, au lieu de les supprimer.",he:"העבר קבצים שנמחקו מרחוק לאשפה, במקום למחוק.",ja:"リモートで削除されたファイルを削除せずにゴミ箱に移動する。",ko:"원격에서 삭제된 파일을 삭제하는 대신 휴지통으로 이동합니다.",ru:"Перемещать удалённые на удалённом сервере файлы в корзину вместо удаления.",zh:"将远程删除的文件移至回收站,而不是直接删除","zh-tw":"將遠端刪除的檔案移至垃圾桶,而非直接刪除。"},"My remote server is already set up. I want to join this device.":{def:"My remote server is already set up. I want to join this device.",es:"Mi servidor remoto ya está configurado. Quiero añadir este dispositivo.",ko:"원격 서버가 이미 설정되어 있습니다. 이 기기를 참여시키고 싶습니다.","zh-tw":"我的遠端伺服器已經設定完成,我想讓這台裝置加入。"},Name:{def:"Name",es:"Nombre",ko:"이름","zh-tw":"名稱"},"Network warning style":{def:"Network warning style",es:"Estilo de advertencia de red",ja:"ネットワーク警告の表示方式",ko:"네트워크 경고 표시 방식",ru:"Стиль сетевого предупреждения",zh:"网络警告样式","zh-tw":"網路警告樣式"},NEW:{def:"NEW",es:"NUEVO",ko:"신규","zh-tw":"新"},"New Remote":{def:"New Remote",es:"Nuevo remoto",ja:"新しいリモート",ko:"새 원격",ru:"Новое удалённое хранилище",zh:"新建远端","zh-tw":"新增遠端"},"Newer (${diff})":{def:"Newer (${diff})",es:"Más nuevo (${diff})",ko:"더 새로움 (${diff})","zh-tw":"較新(${diff}"},"No checks have been performed yet.":{def:"No checks have been performed yet.",es:"Todavía no se ha realizado ninguna comprobación.",ko:"아직 검사를 수행하지 않았습니다.","zh-tw":"尚未執行任何檢查。"},"No connected device information found. Cancelling Garbage Collection.":{def:"No connected device information found. Cancelling Garbage Collection.",es:"No se ha encontrado información de dispositivos conectados. Se cancela la recolección de basura.",ja:"接続済みデバイスの情報が見つかりませんでした。Garbage Collection をキャンセルします。",ko:"연결된 기기 정보를 찾을 수 없습니다. 가비지 컬렉션을 취소합니다.",ru:"Не найдена информация о подключённых устройствах. Garbage Collection отменяется.",zh:"未找到已连接设备的信息。正在取消垃圾回收。","zh-tw":"找不到已連線裝置的資訊。正在取消垃圾回收。"},"No Connection":{def:"No Connection",es:"Sin conexión",ko:"연결 없음","zh-tw":"沒有連線"},"No devices available. Waiting for other devices to connect...":{def:"No devices available. Waiting for other devices to connect...",es:"No hay dispositivos disponibles. Esperando a que se conecten otros dispositivos...",ko:"사용 가능한 기기가 없습니다. 다른 기기가 연결되기를 기다리는 중입니다...","zh-tw":"目前沒有可用的裝置,正在等待其他裝置連線⋯"},"No Items.":{def:"No Items.",es:"Sin elementos.",ko:"항목이 없습니다.","zh-tw":"沒有項目。"},"No limit configured":{def:"No limit configured",es:"Sin límite configurado",ja:"制限は設定されていません",ko:"제한이 설정되지 않음",ru:"Лимит не задан",zh:"未配置限制","zh-tw":"尚未設定限制"},"NO PREVIEW":{def:"NO PREVIEW",es:"SIN VISTA PREVIA",ko:"미리 보기 없음","zh-tw":"無預覽"},"No, please take me back":{def:"No, please take me back",es:"No, volver atrás",ja:"いいえ、前に戻ります",ko:"아니요, 이전으로 돌아가겠습니다",ru:"Нет, верните меня назад",zh:"不,返回上一步","zh-tw":"不,返回上一步"},"Node ID":{def:"Node ID",es:"ID de nodo",ja:"ノード ID",ko:"노드 ID",ru:"ID узла",zh:"节点 ID","zh-tw":"節點 ID"},"Node Information Missing":{def:"Node Information Missing",es:"Falta la información del nodo",ja:"ノード情報がありません",ko:"노드 정보 누락",ru:"Отсутствует информация об узле",zh:"节点信息缺失","zh-tw":"節點資訊缺失"},"Non-Synchronising files":{def:"Non-Synchronising files",es:"Archivos no sincronizados",ja:"同期しないファイル",ko:"동기화하지 않는 파일",ru:"Несинхронизируемые файлы",zh:"不同步的文件","zh-tw":"不同步的檔案"},"Normal Files":{def:"Normal Files",es:"Archivos normales",ja:"通常ファイル",ko:"일반 파일",ru:"Обычные файлы",zh:"普通文件","zh-tw":"一般檔案"},'Not all messages have been translated. And, please revert to "Default" when reporting errors.':{def:'Not all messages have been translated. And, please revert to "Default" when reporting errors.',es:'No todos los mensajes están traducidos. Por favor, vuelva a "Predeterminado" al reportar errores.',fr:"Tous les messages n'ont pas été traduits. Et veuillez revenir à « Par défaut » lorsque vous signalez des erreurs.",he:'לא כל ההודעות תורגמו. בנוסף, אנא חזור ל"ברירת מחדל" בעת דיווח על שגיאות.',ja:'すべてのメッセージが翻訳されているわけではありません。また、Issue報告の際にはいったん"Default"に戻してください',ko:'모든 메시지가 번역되지 않았습니다. 오류 신고 시 "기본값"으로 되돌려 주세요.',ru:"Не все сообщения переведены. И, пожалуйста, вернитесь к «По умолчанию» при сообщении об ошибках.",zh:'并非所有消息都已翻译。请在报告错误时恢复为"默认"',"zh-tw":"並非所有訊息都已翻譯完成。回報錯誤時,請先切回「預設」語言。"},"Not configured":{def:"Not configured",es:"Sin configurar",ko:"구성되지 않음","zh-tw":"尚未設定"},"Not now":{def:"Not now",es:"Ahora no",ko:"나중에","zh-tw":"暫不處理"},"Note that the Group ID is not limited to the generated format; you can use any string as the Group ID.":{def:"Note that the Group ID is not limited to the generated format; you can use any string as the Group ID.",es:"El ID de grupo no está limitado al formato generado: puedes usar cualquier cadena de texto.",ko:"그룹 ID는 생성된 형식으로 제한되지 않으며, 어떤 문자열이든 그룹 ID로 사용할 수 있습니다.","zh-tw":"請注意,群組 ID 不限於自動產生的格式,你可以使用任何字串作為群組 ID。"},'Note that you can generate a new Setup URI by running the "Copy settings as a new Setup URI" command in the command palette.':{def:'Note that you can generate a new Setup URI by running the "Copy settings as a new Setup URI" command in the command palette.',es:"Puedes generar un Setup URI nuevo ejecutando el comando «Copy settings as a new Setup URI» en la paleta de comandos.",ko:'명령 팔레트에서 "Copy settings as a new Setup URI" 명령을 실행하면 새 Setup URI를 생성할 수 있습니다.',"zh-tw":"請注意,你可以在命令面板中執行「將設定複製為新的 Setup URI」命令來產生新的 Setup URI。"},"Notify all setting files":{def:"Notify all setting files",es:"Notificar todos los archivos de configuración",fr:"Notifier tous les fichiers de paramètres",he:"הודע על כל קבצי ההגדרות",ja:"すべての設定を通知",ko:"모든 설정 파일 알림",ru:"Уведомлять обо всех файлах настроек",zh:"通知所有设置文件","zh-tw":"通知所有設定檔"},"Notify customized":{def:"Notify customized",es:"Notificar personalizaciones",fr:"Notifier les personnalisations",he:"הודע על התאמות אישיות",ja:"カスタマイズが行われたら通知する",ko:"사용자 설정 알림",ru:"Уведомлять о настройках",zh:"通知自定义设置","zh-tw":"通知自訂內容"},"Notify when other device has newly customized.":{def:"Notify when other device has newly customized.",es:"Notificar cuando otro dispositivo personalice",fr:"Notifier lorsqu'un autre appareil a une nouvelle personnalisation.",he:"הודע כאשר מכשיר אחר הוסיף התאמה אישית חדשה.",ja:"別の端末がカスタマイズを行なったら通知する",ko:"다른 기기에서 새로운 사용자 설정이 있을 때 알림을 받습니다.",ru:"Уведомлять, когда другое устройство изменило настройки.",zh:"当其他设备有新的自定义设置时通知 ","zh-tw":"當其他裝置有新的自訂內容時通知。"},"Notify when the estimated remote storage size exceeds on start up":{def:"Notify when the estimated remote storage size exceeds on start up",es:"Notificar cuando el tamaño estimado del almacenamiento remoto exceda al iniciar",fr:"Notifier quand la taille estimée du stockage distant est dépassée au démarrage",he:"הודע כשגודל האחסון המרוחד המשוער עולה על הסף בעת הפעלה",ja:"起動時に予想リモートストレージサイズを超えたら通知",ko:"시작 시 예상 원격 스토리지 크기가 초과되면 알림",ru:"Уведомлять, когда оценочный размер удалённого хранилища превышает при запуске",zh:"启动时当估计的远程存储大小超出时通知","zh-tw":"啟動時,若預估的遠端儲存空間大小超出限制則通知"},"Number of batches to process at a time. Defaults to 40. Minimum is 2. This along with batch size controls how many docs are kept in memory at a time.":{def:"Number of batches to process at a time. Defaults to 40. Minimum is 2. This along with batch size controls how many docs are kept in memory at a time.",es:"Número de lotes a procesar. Default 40, mínimo 2. Controla documentos en memoria",fr:"Nombre de lots à traiter à la fois. Par défaut 40. Minimum 2. Ceci, avec la taille de lot, contrôle le nombre de documents conservés en mémoire à la fois.",he:"מספר האצוות לעיבוד בכל פעם. ברירת מחדל 40, מינימום 2. יחד עם גודל האצווה קובע כמה מסמכים נשמרים בזיכרון בו-זמנית.",ja:"1度に処理するバッチの数。デフォルトは40、最小は2。この数値は、どれだけの容量の書類がメモリに保存されるかも定義します。",ko:"한 번에 처리할 배치 개수입니다. 기본값은 40이고 최소값은 2입니다. 배치 크기와 함께 한 번에 메모리에 보관되는 문서 수를 결정합니다.",ru:"Number of batches to process at a time. Defaults to 40. Minimum is 2. This along with batch size controls how many docs are kept in memory at a time.",zh:"一次处理的批量数量。默认为 40。最小为 2。此设置与批量大小一起控制一次在内存中保留多少文档","zh-tw":"一次處理的批次數量。預設為 40,最小為 2。此設定會與批次大小共同決定一次可保留在記憶體中的文件數量。"},"Number of changes to sync at a time. Defaults to 50. Minimum is 2.":{def:"Number of changes to sync at a time. Defaults to 50. Minimum is 2.",es:"Número de cambios a sincronizar simultáneamente. Default 50, mínimo 2",fr:"Nombre de modifications à synchroniser à la fois. Par défaut 50. Minimum 2.",he:"מספר השינויים לסנכרון בכל פעם. ברירת מחדל 50, מינימום 2.",ja:"一度に同期する変更の数。デフォルトは50、最小は2。",ko:"한 번에 동기화할 변경 사항의 수입니다. 기본값은 50입니다. 최소값은 2입니다.",ru:"Количество изменений для синхронизации за раз. По умолчанию 50. Минимум 2.",zh:"一次同步的更改数量。默认为 50。最小为 2。","zh-tw":"一次同步的變更數量。預設為 50,最小為 2。"},"Obfuscate Properties":{def:"Obfuscate Properties",es:"Ofuscar propiedades",ko:"속성 난독화","zh-tw":"混淆屬性"},"Obfuscating properties (e.g., path of file, size, creation and modification dates) adds an additional layer of security by making it harder to identify the structure and names of your files and folders on the remote server. This helps protect your privacy and makes it more difficult for unauthorized users to infer information about your data.":{def:"Obfuscating properties (e.g., path of file, size, creation and modification dates) adds an additional layer of security by making it harder to identify the structure and names of your files and folders on the remote server. This helps protect your privacy and makes it more difficult for unauthorized users to infer information about your data.",es:"Ofuscar las propiedades (p. ej., la ruta del archivo, el tamaño y las fechas de creación y modificación) añade una capa extra de seguridad, ya que dificulta identificar la estructura y los nombres de tus archivos y carpetas en el servidor remoto. Esto ayuda a proteger tu privacidad y hace más difícil que usuarios no autorizados deduzcan información sobre tus datos.",ko:"속성(예: 파일 경로, 크기, 생성 및 수정 날짜)을 난독화하면 원격 서버에서 파일과 폴더의 구조 및 이름을 파악하기 어려워져 보안이 한층 강화됩니다. 이는 개인 정보를 보호하는 데 도움이 되며, 권한 없는 사용자가 데이터에 대한 정보를 추측하기 어렵게 만듭니다.","zh-tw":"混淆屬性(例如檔案路徑、大小、建立時間與修改時間)可以額外增加一層安全保護,讓遠端伺服器上的檔案與資料夾結構及名稱更難被辨識。這有助於保護你的隱私,也讓未授權使用者更難推測你的資料資訊。"},"Obsidian version":{def:"Obsidian version",es:"Versión de Obsidian",ja:"Obsidian バージョン",ko:"Obsidian 버전",ru:"Версия Obsidian",zh:"Obsidian 版本","zh-tw":"Obsidian 版本"},"obsidianLiveSyncSettingTab.btnApply":{def:"Apply",es:"Aplicar",fr:"Appliquer",he:"החל",ja:"適用",ko:"적용",ru:"Применить",zh:"应用","zh-tw":"套用"},"obsidianLiveSyncSettingTab.btnCheck":{def:"Check",es:"Verificar",fr:"Vérifier",he:"בדוק",ja:"確認",ko:"확인",ru:"Проверить",zh:"检查","zh-tw":"檢查"},"obsidianLiveSyncSettingTab.btnCopy":{def:"Copy",es:"Copiar",fr:"Copier",he:"העתק",ja:"コピー",ko:"복사",ru:"Копировать",zh:"复制","zh-tw":"複製"},"obsidianLiveSyncSettingTab.btnDisable":{def:"Disable",es:"Desactivar",fr:"Désactiver",he:"נטרל",ja:"無効化",ko:"비활성화",ru:"Отключить",zh:"禁用","zh-tw":"停用"},"obsidianLiveSyncSettingTab.btnDiscard":{def:"Discard",es:"Descartar",fr:"Abandonner",he:"ביטול שינויים",ja:"破棄",ko:"폐기",ru:"Отменить",zh:"丢弃","zh-tw":"捨棄"},"obsidianLiveSyncSettingTab.btnEnable":{def:"Enable",es:"Activar",fr:"Activer",he:"הפעל",ja:"有効化",ko:"활성화",ru:"Включить",zh:"启用","zh-tw":"啟用"},"obsidianLiveSyncSettingTab.btnFix":{def:"Fix",es:"Corregir",fr:"Corriger",he:"תקן",ja:"修正",ko:"수정",ru:"Исправить",zh:"修复","zh-tw":"修正"},"obsidianLiveSyncSettingTab.btnGotItAndUpdated":{def:"I got it and updated.",es:"Lo entendí y actualicé.",fr:"J'ai compris et mis à jour.",he:"הבנתי ועדכנתי.",ja:"理解しました、更新しました。",ko:"알겠습니다. 업데이트했습니다.",ru:"Понял и обновил.",zh:"我明白了并且已更新","zh-tw":"我知道了,且已更新。"},"obsidianLiveSyncSettingTab.btnStart":{def:"Start",es:"Iniciar",fr:"Démarrer",he:"התחל",ja:"開始",ko:"시작",ru:"Старт",zh:"开始","zh-tw":"開始"},"obsidianLiveSyncSettingTab.btnTest":{def:"Test",es:"Probar",fr:"Tester",he:"בדוק",ja:"テスト",ko:"테스트",ru:"Тест",zh:"测试","zh-tw":"測試"},"obsidianLiveSyncSettingTab.btnUse":{def:"Use",es:"Usar",fr:"Utiliser",he:"השתמש",ja:"使用",ko:"사용",ru:"Использовать",zh:"使用","zh-tw":"使用"},"obsidianLiveSyncSettingTab.buttonFetch":{def:"Fetch",es:"Obtener",fr:"Récupérer",he:"משוך",ja:"フェッチ",ko:"가져오기",ru:"Загрузить",zh:"获取","zh-tw":"抓取"},"obsidianLiveSyncSettingTab.defaultLanguage":{def:"Default",es:"Predeterminado",fr:"Par défaut",he:"ברירת מחדל",ja:"デフォルト",ko:"기본값",ru:"По умолчанию",zh:"默认语言","zh-tw":"預設語言"},"obsidianLiveSyncSettingTab.descConnectSetupURI":{def:"This is the recommended method to set up Self-hosted LiveSync with a Setup URI.",es:"Este es el método recomendado para configurar Self-hosted LiveSync con una URI de configuración.",fr:"Méthode recommandée pour configurer Self-hosted LiveSync avec une URI de configuration.",he:"זוהי השיטה המומלצת להגדרת Self-hosted LiveSync עם Setup URI.",ja:"セットアップURIを使用してSelf-hosted LiveSyncをセットアップする推奨方法です。",ko:"이것은 Setup URI로 Self-hosted LiveSync를 설정하는 권장 방법입니다.",ru:"Это рекомендуемый способ настройки Self-hosted LiveSync с помощью Setup URI.",zh:"这是使用设置 URI 设置 Self-hosted LiveSync 的推荐方法","zh-tw":"這是使用 Setup URI 設定 Self-hosted LiveSync 的建議方式。"},"obsidianLiveSyncSettingTab.descCopySetupURI":{def:"Perfect for setting up a new device!",es:"¡Perfecto para configurar un nuevo dispositivo!",fr:"Parfait pour configurer un nouvel appareil !",he:"מושלם להגדרת מכשיר חדש!",ja:"新しいデバイスのセットアップにおすすめ!",ko:"새 기기 설정에 완벽합니다!",ru:"Идеально подходит для настройки нового устройства!",zh:"非常适合设置新设备!","zh-tw":"設定新裝置時非常方便!"},"obsidianLiveSyncSettingTab.descEnableLiveSync":{def:"Only enable this after configuring either of the above two options or completing all configuration manually.",es:"Solo habilita esto después de configurar cualquiera de las dos opciones anteriores o completar toda la configuración manualmente.",fr:"N'activez ceci qu'après avoir configuré l'une des deux options ci-dessus ou terminé toute la configuration manuellement.",he:"הפעל רק לאחר הגדרת אחת משתי האפשרויות לעיל, או לאחר השלמת כל ההגדרות ידנית.",ja:"上記の2つのオプションのいずれかを設定するか、すべての設定を手動で完了した後にのみ有効にしてください。",ko:"위의 두 옵션 중 하나를 구성하거나 모든 구성을 수동으로 완료한 후에만 활성화하세요.",ru:"Включайте это только после настройки одного из двух вариантов выше или после полного ручного завершения всей конфигурации.",zh:"仅在配置了上述两个选项之一或手动完成所有配置后启用此选项","zh-tw":"請先完成上述兩個選項之一,或手動完成所有設定,再啟用此選項。"},"obsidianLiveSyncSettingTab.descFetchConfigFromRemote":{def:"Fetch necessary settings from already configured remote server.",es:"Obtener las configuraciones necesarias del servidor remoto ya configurado.",fr:"Récupérer les paramètres nécessaires depuis un serveur distant déjà configuré.",he:"משוך הגדרות נדרשות מהשרת המרוחד שהוגדר כבר.",ja:"既に設定済みのリモートサーバーから必要な設定を取得します。",ko:"이미 구성된 원격 서버에서 필요한 설정을 가져옵니다.",ru:"Получить необходимые настройки с уже настроенного удалённого сервера.",zh:"从已配置的远程服务器获取必要的设置","zh-tw":"從已設定完成的遠端伺服器抓取必要的設定。"},"obsidianLiveSyncSettingTab.descManualSetup":{def:"Not recommended, but useful if you don't have a Setup URI",es:"No recomendado, pero útil si no tienes una URI de configuración",fr:"Non recommandé, mais utile si vous n'avez pas d'URI de configuration",he:"לא מומלץ, אך שימושי אם אין לך Setup URI",ja:"推奨しませんが、セットアップURIがない場合に便利です",ko:"권장하지 않지만 Setup URI가 없는 경우에 유용합니다",ru:"Не рекомендуется, но полезно, если у вас нет Setup URI.",zh:"不推荐,但如果您没有设置 URI 则很有用","zh-tw":"不建議使用,但如果你沒有 Setup URI 會很有用"},"obsidianLiveSyncSettingTab.descTestDatabaseConnection":{def:"Open database connection. If the remote database is not found and you have permission to create a database, the database will be created.",es:"Abrir conexión a la base de datos. Si no se encuentra la base de datos remota y tienes permiso para crear una base de datos, se creará la base de datos.",fr:"Ouvrir la connexion à la base de données. Si la base distante est introuvable et que vous avez l'autorisation de créer une base, elle sera créée.",he:"פתח חיבור למסד נתונים. אם מסד הנתונים המרוחד לא נמצא ויש לך הרשאה ליצור אחד, הוא ייצור.",ja:"データベース接続を開きます。リモートデータベースが見つからず、データベースを作成する権限がある場合は、データベースが作成されます。",ko:"데이터베이스 연결을 엽니다. 원격 데이터베이스를 찾을 수 없고 데이터베이스 생성 권한이 있는 경우, 데이터베이스가 생성됩니다.",ru:"Открыть подключение к базе данных. Если удалённая база данных не найдена и у вас есть право на её создание, база будет создана.",zh:"打开数据库连接。如果未找到远程数据库并且您有创建数据库的权限,则将创建数据库","zh-tw":"開啟資料庫連線。如果找不到遠端資料庫,且你有建立資料庫的權限,將會建立該資料庫。"},"obsidianLiveSyncSettingTab.descValidateDatabaseConfig":{def:"Checks and fixes any potential issues with the database config.",es:"Verifica y soluciona cualquier problema potencial con la configuración de la base de datos.",fr:"Vérifie et corrige les problèmes potentiels de la configuration de la base.",he:"בודק ומתקן בעיות אפשריות בתצורת מסד הנתונים.",ja:"データベース設定の潜在的な問題を確認し、修正します。",ko:"데이터베이스 구성의 잠재적 문제를 확인하고 수정합니다.",ru:"Проверяет и исправляет любые потенциальные проблемы в конфигурации базы данных.",zh:"检查并修复数据库配置中的任何潜在问题","zh-tw":"檢查並修正資料庫設定中任何潛在的問題。"},"obsidianLiveSyncSettingTab.errAccessForbidden":{def:"❗ Access forbidden.",es:"Acceso prohibido.",fr:"❗ Accès interdit.",he:"❗ גישה נדחתה.",ja:"❗ アクセスが禁止されています。",ko:"❗ 액세스가 금지되었습니다.",ru:"❗ Доступ запрещён.",zh:"❗ 访问被禁止","zh-tw":"❗ 存取被拒。"},"obsidianLiveSyncSettingTab.errCannotContinueTest":{def:"We could not continue the test.",es:"No se pudo continuar con la prueba.",fr:"Impossible de poursuivre le test.",he:"לא ניתן להמשיך בבדיקה.",ja:"テストを続行できませんでした。",ko:"테스트를 계속할 수 없습니다.",ru:"Мы не можем продолжить тест.",zh:"我们无法继续测试。","zh-tw":"無法繼續進行測試。"},"obsidianLiveSyncSettingTab.errCorsCredentials":{def:"❗ cors.credentials is wrong",es:"❗ cors.credentials es incorrecto",fr:"❗ cors.credentials est incorrect",he:"❗ cors.credentials שגוי",ja:"❗ cors.credentialsが不正です",ko:"❗ cors.credentials가 잘못되었습니다",ru:"❗ cors.credentials неверно",zh:"❗ cors.credentials 设置错误","zh-tw":"❗ cors.credentials 設定錯誤"},"obsidianLiveSyncSettingTab.errCorsNotAllowingCredentials":{def:"❗ CORS is not allowing credentials",es:"CORS no permite credenciales",fr:"❗ CORS n'autorise pas les identifiants",he:"❗ CORS אינו מאפשר פרטי גישה",ja:"❗ CORSが認証情報を許可していません",ko:"❗ CORS에서 자격 증명을 허용하지 않습니다",ru:"❗ CORS не разрешает учётные данные",zh:"❗ CORS 不允许凭据","zh-tw":"❗ CORS 不允許憑證"},"obsidianLiveSyncSettingTab.errCorsOrigins":{def:"❗ cors.origins is wrong",es:"❗ cors.origins es incorrecto",fr:"❗ cors.origins est incorrect",he:"❗ cors.origins שגוי",ja:"❗ cors.originsが不正です",ko:"❗ cors.origins가 잘못되었습니다",ru:"❗ cors.origins неверно",zh:"❗ cors.origins 设置错误","zh-tw":"❗ cors.origins 設定錯誤"},"obsidianLiveSyncSettingTab.errEnableCors":{def:"❗ httpd.enable_cors is wrong",es:"❗ httpd.enable_cors es incorrecto",fr:"❗ httpd.enable_cors est incorrect",he:"❗ httpd.enable_cors שגוי",ja:"❗ httpd.enable_corsが不正です",ko:"❗ httpd.enable_cors가 잘못되었습니다",ru:"❗ httpd.enable_cors неверно",zh:"❗ httpd.enable_cors 设置错误","zh-tw":"❗ httpd.enable_cors 設定錯誤"},"obsidianLiveSyncSettingTab.errEnableCorsChttpd":{def:"❗ chttpd.enable_cors is wrong",es:"❗ chttpd.enable_cors es incorrecto",fr:"❗ chttpd.enable_cors est incorrect",he:"❗ chttpd.enable_cors שגוי",ja:"❗ chttpd.enable_corsが不正です",ko:"❗ chttpd.enable_cors가 잘못되었습니다",ru:"❗ chttpd.enable_cors неверно",zh:"❗ chttpd.enable_cors 设置错误","zh-tw":"❗ chttpd.enable_cors 設定錯誤"},"obsidianLiveSyncSettingTab.errMaxDocumentSize":{def:"❗ couchdb.max_document_size is low)",es:"❗ couchdb.max_document_size es bajo)",fr:"❗ couchdb.max_document_size est trop bas)",he:"❗ couchdb.max_document_size נמוך)",ja:"❗ couchdb.max_document_sizeが低すぎます",ko:"❗ couchdb.max_document_size가 낮습니다)",ru:"❗ couchdb.max_document_size низкое",zh:"❗ couchdb.max_document_size 设置过低)","zh-tw":"❗ couchdb.max_document_size 設定過低"},"obsidianLiveSyncSettingTab.errMaxRequestSize":{def:"❗ chttpd.max_http_request_size is low)",es:"❗ chttpd.max_http_request_size es bajo)",fr:"❗ chttpd.max_http_request_size est trop bas)",he:"❗ chttpd.max_http_request_size נמוך)",ja:"❗ chttpd.max_http_request_sizeが低すぎます",ko:"❗ chttpd.max_http_request_size가 낮습니다)",ru:"❗ chttpd.max_http_request_size низкое",zh:"❗ chttpd.max_http_request_size 设置过低)","zh-tw":"❗ chttpd.max_http_request_size 設定過低"},"obsidianLiveSyncSettingTab.errMissingWwwAuth":{def:"❗ httpd.WWW-Authenticate is missing",es:"❗ httpd.WWW-Authenticate falta",fr:"❗ httpd.WWW-Authenticate est manquant",he:"❗ httpd.WWW-Authenticate חסר",ja:"❗ httpd.WWW-Authenticateが不足しています",ko:"❗ httpd.WWW-Authenticate가 누락되었습니다",ru:"❗ httpd.WWW-Authenticate отсутствует",zh:"❗ 缺少 httpd.WWW-Authenticate 设置","zh-tw":"❗ 缺少 httpd.WWW-Authenticate 設定"},"obsidianLiveSyncSettingTab.errRequireValidUser":{def:"❗ chttpd.require_valid_user is wrong.",es:"❗ chttpd.require_valid_user es incorrecto.",fr:"❗ chttpd.require_valid_user est incorrect.",he:"❗ chttpd.require_valid_user שגוי.",ja:"❗ chttpd.require_valid_userが不正です。",ko:"❗ chttpd.require_valid_user가 잘못되었습니다.",ru:"❗ chttpd.require_valid_user неверно.",zh:"❗ chttpd.require_valid_user 设置错误","zh-tw":"❗ chttpd.require_valid_user 設定錯誤。"},"obsidianLiveSyncSettingTab.errRequireValidUserAuth":{def:"❗ chttpd_auth.require_valid_user is wrong.",es:"❗ chttpd_auth.require_valid_user es incorrecto.",fr:"❗ chttpd_auth.require_valid_user est incorrect.",he:"❗ chttpd_auth.require_valid_user שגוי.",ja:"❗ chttpd_auth.require_valid_userが不正です。",ko:"❗ chttpd_auth.require_valid_user가 잘못되었습니다.",ru:"❗ chttpd_auth.require_valid_user неверно.",zh:"❗ chttpd_auth.require_valid_user 设置错误","zh-tw":"❗ chttpd_auth.require_valid_user 設定錯誤。"},"obsidianLiveSyncSettingTab.labelDisabled":{def:"⏹️ : Disabled",es:"⏹️ : Desactivado",fr:"⏹️ : Désactivé",he:"⏹️ : מנוטרל",ja:"⏹️ : 無効",ko:"⏹️ : 비활성화됨",ru:"⏹️ : Отключено",zh:"⏹️:已禁用","zh-tw":"⏹️ : 已停用"},"obsidianLiveSyncSettingTab.labelEnabled":{def:"🔁 : Enabled",es:"🔁 : Activado",fr:"🔁 : Activé",he:"🔁 : מופעל",ja:"🔁 : 有効",ko:"🔁 : 활성화됨",ru:"🔁 : Включено",zh:"🔁:已启用","zh-tw":"🔁 : 已啟用"},"obsidianLiveSyncSettingTab.levelAdvanced":{def:" (Advanced)",es:" (avanzado)",fr:" (Avancé)",he:" (מתקדם)",ja:" (上級)",ko:" (고급)",ru:" (Расширенные)",zh:"(进阶)","zh-tw":"(進階)"},"obsidianLiveSyncSettingTab.levelEdgeCase":{def:" (Edge Case)",es:" (excepción)",fr:" (Cas particulier)",he:" (מקרה קצה)",ja:" (エッジケース)",ko:" (특수 사례)",ru:" (Граничные случаи)",zh:"(边缘情况)","zh-tw":"(邊緣情況)"},"obsidianLiveSyncSettingTab.levelPowerUser":{def:" (Power User)",es:" (experto)",fr:" (Utilisateur avancé)",he:" (משתמש מתקדם)",ja:" (エキスパート)",ko:" (파워 유저)",ru:" (Опытный пользователь)",zh:"(高级用户)","zh-tw":"(進階使用者)"},"obsidianLiveSyncSettingTab.linkOpenInBrowser":{def:"Open in browser",es:"Abrir en el navegador",fr:"Ouvrir dans le navigateur",he:"פתח בדפדפן",ja:"ブラウザで開く",ko:"브라우저에서 열기",ru:"Открыть в браузере",zh:"在浏览器中打开","zh-tw":"在瀏覽器中開啟"},"obsidianLiveSyncSettingTab.linkPageTop":{def:"Page Top",es:"Ir arriba",fr:"Haut de la page",he:"ראש העמוד",ja:"ページトップ",ko:"페이지 상단",ru:"В начало страницы",zh:"页面顶部","zh-tw":"回到頁首"},"obsidianLiveSyncSettingTab.linkTipsAndTroubleshooting":{def:"Tips and Troubleshooting",es:"Consejos y solución de problemas",fr:"Conseils et dépannage",he:"טיפים ופתרון בעיות",ja:"ヒントとトラブルシューティング",ko:"팁 및 문제 해결",ru:"Советы и устранение неполадок",zh:"提示和故障排除","zh-tw":"提示與疑難排解"},"obsidianLiveSyncSettingTab.linkTroubleshooting":{def:"/docs/troubleshooting.md",es:"/docs/es/troubleshooting.md",fr:"/docs/troubleshooting.md",he:"/docs/troubleshooting.md",ja:"/docs/troubleshooting.md",ko:"/docs/troubleshooting.md",ru:"/docs/troubleshooting.md",zh:"/docs/troubleshooting.md"},"obsidianLiveSyncSettingTab.logCannotUseCloudant":{def:"This feature cannot be used with IBM Cloudant.",es:"Esta función no se puede utilizar con IBM Cloudant.",fr:"Cette fonctionnalité ne peut pas être utilisée avec IBM Cloudant.",he:"לא ניתן להשתמש בתכונה זו עם IBM Cloudant.",ja:"この機能はIBM Cloudantでは使用できません。",ko:"이 기능은 IBM Cloudant와 함께 사용할 수 없습니다.",ru:"Эта функция недоступна для IBM Cloudant.",zh:"此功能不能与 IBM Cloudant 一起使用 ","zh-tw":"此功能無法與 IBM Cloudant 一併使用。"},"obsidianLiveSyncSettingTab.logCheckingConfigDone":{def:"Checking configuration done",es:"Verificación de configuración completada",fr:"Vérification de la configuration terminée",he:"בדיקת התצורה הושלמה",ja:"設定の確認が完了しました",ko:"구성 확인 완료",ru:"Проверка конфигурации завершена",zh:"配置检查完成","zh-tw":"設定檢查完成"},"obsidianLiveSyncSettingTab.logCheckingConfigFailed":{def:"Checking configuration failed",es:"La verificación de configuración falló",fr:"Échec de la vérification de la configuration",he:"בדיקת התצורה נכשלה",ja:"設定の確認に失敗しました",ko:"구성 확인 실패",ru:"Проверка конфигурации не удалась",zh:"配置检查失败","zh-tw":"設定檢查失敗"},"obsidianLiveSyncSettingTab.logCheckingDbConfig":{def:"Checking database configuration",es:"Verificando la configuración de la base de datos",fr:"Vérification de la configuration de la base",he:"בודק תצורת מסד נתונים",ja:"データベース設定を確認中",ko:"데이터베이스 구성 확인 중",ru:"Проверка конфигурации базы данных",zh:"正在检查数据库配置","zh-tw":"正在檢查資料庫設定"},"obsidianLiveSyncSettingTab.logCheckPassphraseFailed":{def:"ERROR: Failed to check passphrase with the remote server:\n${db}.",es:"ERROR: Error al comprobar la frase de contraseña con el servidor remoto:\n${db}.",fr:"ERREUR : Échec de la vérification de la phrase secrète avec le serveur distant :\n${db}.",he:"שגיאה: בדיקת ביטוי הסיסמה עם השרת המרוחד נכשלה:\n${db}.",ja:"エラー: リモートサーバーとのパスフレーズ確認に失敗しました:\n${db}。",ko:"오류: 원격 서버와 패스프레이즈 확인에 실패했습니다:\n${db}.",ru:"ОШИБКА: Не удалось проверить пароль с удалённым сервером: db.",zh:"错误:无法使用远程服务器检查密码:\n${db}","zh-tw":"錯誤:無法透過遠端伺服器檢查密語:\n${db}。"},"obsidianLiveSyncSettingTab.logConfiguredDisabled":{def:"Configured synchronization mode: DISABLED",es:"Modo de sincronización configurado: DESACTIVADO",fr:"Mode de synchronisation configuré : DÉSACTIVÉ",he:"מצב סנכרון שהוגדר: מנוטרל",ja:"設定された同期モード: 無効",ko:"구성된 동기화 모드: 비활성화됨",ru:"Настроенный режим синхронизации: ОТКЛЮЧЕН",zh:"已配置的同步模式:已禁用","zh-tw":"已設定的同步模式:已停用"},"obsidianLiveSyncSettingTab.logConfiguredLiveSync":{def:"Configured synchronization mode: LiveSync",es:"Modo de sincronización configurado: Sincronización en Vivo",fr:"Mode de synchronisation configuré : LiveSync",he:"מצב סנכרון שהוגדר: LiveSync",ja:"設定された同期モード: LiveSync",ko:"구성된 동기화 모드: LiveSync",ru:"Настроенный режим синхронизации: LiveSync",zh:"已配置的同步模式:LiveSync","zh-tw":"已設定的同步模式:LiveSync"},"obsidianLiveSyncSettingTab.logConfiguredPeriodic":{def:"Configured synchronization mode: Periodic",es:"Modo de sincronización configurado: Periódico",fr:"Mode de synchronisation configuré : Périodique",he:"מצב סנכרון שהוגדר: תקופתי",ja:"設定された同期モード: 定期",ko:"구성된 동기화 모드: 주기적",ru:"Настроенный режим синхронизации: Периодический",zh:"已配置的同步模式:定期同步","zh-tw":"已設定的同步模式:定期同步"},"obsidianLiveSyncSettingTab.logCouchDbConfigFail":{def:"CouchDB Configuration: ${title} failed",es:"Configuración de CouchDB: ${title} falló",fr:"Configuration CouchDB : échec de ${title}",he:"תצורת CouchDB: ${title} נכשלה",ja:"CouchDB設定: ${title} 失敗",ko:"CouchDB 구성: ${title} 실패",ru:"Конфигурация CouchDB: title не удалась",zh:"CouchDB 配置:${title} 失败","zh-tw":"CouchDB 設定:${title} 失敗"},"obsidianLiveSyncSettingTab.logCouchDbConfigSet":{def:"CouchDB Configuration: ${title} -> Set ${key} to ${value}",es:"Configuración de CouchDB: ${title} -> Establecer ${key} en ${value}",fr:"Configuration CouchDB : ${title} -> ${key} défini à ${value}",he:"תצורת CouchDB: ${title} -> הגדר ${key} ל-${value}",ja:"CouchDB設定: ${title} -> ${key}を${value}に設定",ko:"CouchDB 구성: ${title} -> ${key}을(를) ${value}(으)로 설정",ru:"Конфигурация CouchDB: title -> Установить key в value",zh:"CouchDB 配置:${title} -> 设置 ${key} 为 ${value}","zh-tw":"CouchDB 設定:${title} -> 將 ${key} 設為 ${value}"},"obsidianLiveSyncSettingTab.logCouchDbConfigUpdated":{def:"CouchDB Configuration: ${title} successfully updated",es:"Configuración de CouchDB: ${title} actualizado correctamente",fr:"Configuration CouchDB : ${title} mise à jour avec succès",he:"תצורת CouchDB: ${title} עודכנה בהצלחה",ja:"CouchDB設定: ${title} 正常に更新されました",ko:"CouchDB 구성: ${title} 성공적으로 업데이트됨",ru:"Конфигурация CouchDB: title успешно обновлена",zh:"CouchDB 配置:${title} 成功更新","zh-tw":"CouchDB 設定:${title} 已成功更新"},"obsidianLiveSyncSettingTab.logDatabaseConnected":{def:"Database connected",es:"Base de datos conectada",fr:"Base de données connectée",he:"מסד הנתונים מחובר",ja:"データベースに接続しました",ko:"데이터베이스 연결됨",ru:"База данных подключена",zh:"数据库已连接","zh-tw":"資料庫已連線"},"obsidianLiveSyncSettingTab.logEncryptionNoPassphrase":{def:"You cannot enable encryption without a passphrase",es:"No puedes habilitar el cifrado sin una frase de contraseña",fr:"Impossible d'activer le chiffrement sans phrase secrète",he:"לא ניתן להפעיל הצפנה ללא ביטוי סיסמה",ja:"パスフレーズなしでは暗号化を有効にできません",ko:"패스프레이즈 없이는 암호화를 활성화할 수 없습니다",ru:"Вы не можете включить шифрование без парольной фразы",zh:"没有密码无法启用加密","zh-tw":"沒有密語就無法啟用加密"},"obsidianLiveSyncSettingTab.logEncryptionNoSupport":{def:"Your device does not support encryption.",es:"Tu dispositivo no admite el cifrado.",fr:"Votre appareil ne prend pas en charge le chiffrement.",he:"המכשיר שלך אינו תומך בהצפנה.",ja:"お使いのデバイスは暗号化をサポートしていません。",ko:"기기가 암호화를 지원하지 않습니다.",ru:"Ваше устройство не поддерживает шифрование.",zh:"您的设备不支持加密 ","zh-tw":"你的裝置不支援加密。"},"obsidianLiveSyncSettingTab.logErrorOccurred":{def:"An error occurred!!",es:"¡Ocurrió un error!",fr:"Une erreur s'est produite !!",he:"אירעה שגיאה!!",ja:"エラーが発生しました!!",ko:"오류가 발생했습니다!",ru:"Произошла ошибка!!",zh:"发生错误!!","zh-tw":"發生錯誤!!"},"obsidianLiveSyncSettingTab.logEstimatedSize":{def:"Estimated size: ${size}",es:"Tamaño estimado: ${size}",fr:"Taille estimée : ${size}",he:"גודל משוער: ${size}",ja:"推定サイズ: ${size}",ko:"예상 크기: ${size}",ru:"Примерный размер: size",zh:"估计大小:${size}","zh-tw":"預估大小:${size}"},"obsidianLiveSyncSettingTab.logPassphraseInvalid":{def:"Passphrase is not valid, please fix it.",es:"La frase de contraseña no es válida, por favor corrígela.",fr:"La phrase secrète est invalide, veuillez la corriger.",he:"ביטוי הסיסמה אינו תקין, אנא תקן אותו.",ja:"パスフレーズが無効です、修正してください。",ko:"패스프레이즈가 유효하지 않습니다. 수정해 주세요.",ru:"Парольная фраза недействительна, пожалуйста, исправьте.",zh:"密码无效,请修正","zh-tw":"密語無效,請修正。"},"obsidianLiveSyncSettingTab.logPassphraseNotCompatible":{def:"ERROR: Passphrase is not compatible with the remote server! Please check it again!",es:"ERROR: ¡La frase de contraseña no es compatible con el servidor remoto! ¡Por favor, revísala de nuevo!",fr:"ERREUR : la phrase secrète n'est pas compatible avec le serveur distant ! Veuillez vérifier à nouveau !",he:"שגיאה: ביטוי הסיסמה אינו תואם לשרת המרוחד! אנא בדוק שוב!",ja:"エラー: パスフレーズがリモートサーバーと適合しません!再度確認してください!",ko:"오류: 패스프레이즈가 원격 서버와 호환되지 않습니다! 다시 확인해 주세요!",ru:"ОШИБКА: Парольная фраза несовместима с удалённым сервером!",zh:"错误:密码与远程服务器不兼容!请再次检查!","zh-tw":"錯誤:密語與遠端伺服器不符!請再檢查一次!"},"obsidianLiveSyncSettingTab.logRebuildNote":{def:"Syncing has been disabled, fetch and re-enabled if desired.",es:"La sincronización ha sido desactivada, obtén y vuelve a activar si lo deseas.",fr:"La synchronisation a été désactivée, récupérez et réactivez si souhaité.",he:"הסנכרון הושבת, משוך והפעל מחדש אם רצוי.",ja:"同期が無効になりました。必要に応じてフェッチして再有効化してください。",ko:"동기화가 비활성화되었습니다. 원하는 경우 가져오기 후 다시 활성화하세요.",ru:"Синхронизация отключена, загрузите и включите снова при желании.",zh:"同步已禁用,如果需要,请获取并重新启用","zh-tw":"同步已停用;如有需要,請先抓取再重新啟用。"},"obsidianLiveSyncSettingTab.logSelectAnyPreset":{def:"Select any preset.",es:"Selecciona cualquier preestablecido.",fr:"Sélectionnez un préréglage.",he:"בחר קביעה מראש כלשהי.",ja:"プリセットを選択してください。",ko:"프리셋을 선택하세요.",ru:"Выберите любой пресет.",zh:"请选择任一预设。","zh-tw":"請選擇任一預設項目。"},"obsidianLiveSyncSettingTab.logServerConfigurationCheck":{def:"obsidianLiveSyncSettingTab.logServerConfigurationCheck",ko:"--서버 구성 확인--"},"obsidianLiveSyncSettingTab.msgAreYouSureProceed":{def:"Are you sure to proceed?",es:"¿Estás seguro de proceder?",fr:"Êtes-vous sûr de vouloir continuer ?",he:"האם אתה בטוח שברצונך להמשיך?",ja:"本当に続行しますか?",ko:"정말로 진행하시겠습니까?",ru:"Вы уверены, что хотите продолжить?",zh:"您确定要继续吗?","zh-tw":"你確定要繼續嗎?"},"obsidianLiveSyncSettingTab.msgChangesNeedToBeApplied":{def:"Changes need to be applied!",es:"¡Los cambios deben aplicarse!",fr:"Des modifications doivent être appliquées !",he:"יש להחיל שינויים!",ja:"変更を適用する必要があります!",ko:"변경사항을 적용해야 합니다!",ru:"Изменения нужно применить!",zh:"需要应用更改!","zh-tw":"需要套用變更!"},"obsidianLiveSyncSettingTab.msgConfigCheck":{def:"--Config check--",es:"--Verificación de configuración--",fr:"--Vérification de la configuration--",he:"--בדיקת תצורה--",ja:"--設定確認--",ko:"--구성 확인--",ru:"--Проверка конфигурации--",zh:"--配置检查--","zh-tw":"--設定檢查--"},"obsidianLiveSyncSettingTab.msgConfigCheckFailed":{def:"The configuration check has failed. Do you want to continue anyway?",es:"La verificación de configuración ha fallado. ¿Quieres continuar de todos modos?",fr:"La vérification de la configuration a échoué. Voulez-vous continuer malgré tout ?",he:"בדיקת התצורה נכשלה. האם ברצונך להמשיך בכל זאת?",ja:"設定確認に失敗しました。それでも続行しますか?",ko:"구성 확인에 실패했습니다. 그래도 계속하시겠습니까?",ru:"Проверка конфигурации не удалась. Вы всё равно хотите продолжить?",zh:"配置检查失败。仍要继续吗?","zh-tw":"設定檢查失敗。仍要繼續嗎?"},"obsidianLiveSyncSettingTab.msgConnectionCheck":{def:"--Connection check--",es:"--Verificación de conexión--",fr:"--Vérification de la connexion--",he:"--בדיקת חיבור--",ja:"--接続確認--",ko:"--연결 확인--",ru:"--Проверка подключения--",zh:"--连接检查--","zh-tw":"--連線檢查--"},"obsidianLiveSyncSettingTab.msgConnectionProxyNote":{def:"If you're having trouble with the Connection-check (even after checking config), please check your reverse proxy configuration.",es:"Si tienes problemas con la verificación de conexión (incluso después de verificar la configuración), por favor verifica la configuración de tu proxy reverso.",fr:"Si vous rencontrez des problèmes de vérification de connexion (même après avoir vérifié la configuration), veuillez vérifier votre configuration de reverse proxy.",he:"אם אתה נתקל בבעיות עם בדיקת החיבור (גם לאחר בדיקת התצורה), אנא בדוק את הגדרות ה-reverse proxy שלך.",ja:"設定確認後も接続確認に問題がある場合は、リバースプロキシの設定を確認してください。",ko:"구성 확인 후에도 연결 확인에 문제가 있는 경우, 리버스 프록시 구성을 확인해 주세요.",ru:"Если у вас проблемы с проверкой подключения, проверьте конфигурацию обратного прокси.",zh:"如果您在连接检查时遇到问题(即使检查了配置后),请检查您的反向代理配置","zh-tw":"如果連線檢查仍有問題(即使設定已經檢查過),請檢查你的反向代理設定。"},"obsidianLiveSyncSettingTab.msgCurrentOrigin":{def:"Current origin: ${origin}",es:"Origen actual: {origin}",fr:"Origine actuelle : ${origin}",he:"מקור נוכחי: ${origin}",ja:"現在のオリジン: ${origin}",ko:"현재 출처: ${origin}",ru:"Текущий origin: origin",zh:"当前源: {origin}","zh-tw":"目前來源:${origin}"},"obsidianLiveSyncSettingTab.msgDiscardConfirmation":{def:"Do you really want to discard existing settings and databases?",es:"¿Realmente deseas descartar las configuraciones y bases de datos existentes?",fr:"Voulez-vous vraiment abandonner les paramètres et bases existants ?",he:"האם אתה בטוח שברצונך לבטל הגדרות ומסדי נתונים קיימים?",ja:"本当に既存の設定とデータベースを破棄しますか?",ko:"정말로 기존 설정과 데이터베이스를 삭제하시겠습니까?",ru:"Вы действительно хотите отменить существующие настройки и базы данных?",zh:"您真的要丢弃现有的设置和数据库吗?","zh-tw":"你真的要捨棄現有的設定與資料庫嗎?"},"obsidianLiveSyncSettingTab.msgDone":{def:"--Done--",es:"--Hecho--",fr:"--Terminé--",he:"--הסתיים--",ja:"--完了--",ko:"--완료--",ru:"--Готово--",zh:"--完成--","zh-tw":"--完成--"},"obsidianLiveSyncSettingTab.msgEnableCors":{def:"Set httpd.enable_cors",es:"Configurar httpd.enable_cors",fr:"Définir httpd.enable_cors",he:"הגדר httpd.enable_cors",ja:"httpd.enable_corsを設定",ko:"httpd.enable_cors 설정",ru:"Установить httpd.enable_cors",zh:"设置 httpd.enable_cors","zh-tw":"設定 httpd.enable_cors"},"obsidianLiveSyncSettingTab.msgEnableCorsChttpd":{def:"Set chttpd.enable_cors",es:"Establecer chttpd.enable_cors",fr:"Définir chttpd.enable_cors",he:"הגדר chttpd.enable_cors",ja:"chttpd.enable_corsを設定",ko:"chttpd.enable_cors 설정",ru:"Установить chttpd.enable_cors",zh:"设置 chttpd.enable_cors","zh-tw":"設定 chttpd.enable_cors"},"obsidianLiveSyncSettingTab.msgEnableEncryptionRecommendation":{def:"We recommend enabling End-To-End Encryption, and Path Obfuscation. Are you sure you want to continue without encryption?",es:"Recomendamos habilitar el cifrado de extremo a extremo y la obfuscación de ruta. ¿Estás seguro de querer continuar sin cifrado?",fr:"Nous recommandons d'activer le chiffrement de bout en bout et l'obfuscation des chemins. Êtes-vous sûr de vouloir continuer sans chiffrement ?",he:"אנו ממליצים להפעיל הצפנה מקצה לקצה ואת ערפול הנתיב. האם אתה בטוח שברצונך להמשיך ללא הצפנה?",ja:"エンドツーエンド暗号化とパス難読化を有効にすることをお勧めします。暗号化なしで続行してもよろしいですか?",ko:"종단 간 암호화와 경로 난독화를 활성화하는 것을 권장합니다. 정말로 암호화 없이 계속하시겠습니까?",ru:"Мы рекомендуем включить сквозное шифрование. Вы уверены, что хотите продолжить без шифрования?",zh:"建议启用端到端加密和路径混淆。你确定要在未加密的情况下继续吗?","zh-tw":"我們建議啟用端對端加密與路徑混淆。你確定要在未加密的情況下繼續嗎?"},"obsidianLiveSyncSettingTab.msgFetchConfigFromRemote":{def:"Do you want to fetch the config from the remote server?",es:"¿Quieres obtener la configuración del servidor remoto?",fr:"Voulez-vous récupérer la configuration depuis le serveur distant ?",he:"האם ברצונך למשוך את התצורה מהשרת המרוחד?",ja:"リモートサーバーから設定を取得しますか?",ko:"원격 서버에서 구성을 가져오시겠습니까?",ru:"Вы хотите загрузить конфигурацию с удалённого сервера?",zh:"要从远端服务器获取配置吗?","zh-tw":"要從遠端伺服器抓取設定嗎?"},"obsidianLiveSyncSettingTab.msgIfConfigNotPersistent":{def:"If the server configuration is not persistent (e.g., running on docker), the values here may change. Once you are able to connect, please update the settings in the server's local.ini.",es:"Si la configuración del servidor no es persistente (por ejemplo, ejecutándose en docker), los valores aquí pueden cambiar. Una vez que puedas conectarte, por favor actualiza las configuraciones en el local.ini del servidor.",fr:"Si la configuration du serveur n'est pas persistante (par ex. fonctionnant sur Docker), les valeurs peuvent changer. Une fois la connexion établie, mettez à jour les paramètres dans le local.ini du serveur.",he:"אם תצורת השרת אינה קבועה (למשל, פועלת ב-docker), הערכים כאן עשויים להשתנות. לאחר שתצליח להתחבר, אנא עדכן את ההגדרות ב-local.ini של השרת.",ja:"サーバー設定が永続的でない場合(例: Dockerで実行中)、ここの値は変更される可能性があります。接続できるようになったら、サーバーのlocal.iniの設定を更新してください。",ko:"서버 설정이 영구적으로 저장되지 않는 환경(예: Docker에서 실행 중)에서는 이곳의 값들이 변경될 수 있습니다. 연결이 가능해지면 서버의 local.ini 파일에서 설정을 수동으로 업데이트해 주세요.",ru:"Если конфигурация сервера непостоянна, значения здесь могут измениться.",zh:"如果服务器配置不是持久的(例如,在 docker 上运行),此处的值可能会更改。一旦能够连接,请更新服务器 local.ini 中的设置","zh-tw":"如果伺服器設定並非持久保存(例如在 Docker 上執行),這裡的值可能會變動。一旦能夠連線,請更新伺服器 local.ini 中的設定。"},"obsidianLiveSyncSettingTab.msgInvalidPassphrase":{def:"Your encryption passphrase might be invalid. Are you sure you want to continue?",es:"Tu frase de contraseña de cifrado podría ser inválida. ¿Estás seguro de querer continuar?",fr:"Votre phrase secrète de chiffrement peut être invalide. Êtes-vous sûr de vouloir continuer ?",he:"ביטוי הסיסמה להצפנה שלך עשוי להיות לא תקין. האם אתה בטוח שברצונך להמשיך?",ja:"暗号化パスフレーズが無効かもしれません。続行してもよろしいですか?",ko:"암호화 패스프레이즈가 유효하지 않을 수 있습니다. 정말로 계속하시겠습니까?",ru:"Ваша парольная фраза шифрования может быть недействительна.",zh:"你的加密密码短语可能无效。你确定要继续吗?","zh-tw":"你的加密密語可能無效。你確定要繼續嗎?"},"obsidianLiveSyncSettingTab.msgNewVersionNote":{def:"Here due to an upgrade notification? Please review the version history. If you're satisfied, click the button. A new update will prompt this again.",es:"¿Aquí debido a una notificación de actualización? Por favor, revise el historial de versiones. Si está satisfecho, haga clic en el botón. Una nueva actualización volverá a mostrar esto.",fr:"Arrivé ici suite à une notification de mise à jour ? Consultez l'historique des versions. Si vous êtes satisfait, cliquez sur le bouton. Une nouvelle mise à jour reproposera ceci.",he:"הגעת כאן בשל הודעת שדרוג? אנא עיין בהיסטוריית הגרסאות. אם אתה מרוצה, לחץ על הכפתור. עדכון חדש יציג זאת שוב.",ja:"アップグレード通知でここに来ましたか?バージョン履歴を確認してください。納得したらボタンをクリックしてください。新しい更新があると再度確認されます。",ko:"업그레이드 알림으로 여기에 오셨나요? 버전 기록을 검토해 주세요. 만족하신다면 버튼을 클릭하세요. 새로운 업데이트 시 다시 안내됩니다.",ru:"Вы пришли из-за уведомления об обновлении? Просмотрите историю версий.",zh:"因为升级通知来到这里?请查看版本历史。如果您满意,请点击按钮。新的更新将再次提示此信息","zh-tw":"因為升級通知才來到這裡嗎?請查看版本歷程。若你已確認無誤,請點選按鈕。下次更新時會再次提示。"},"obsidianLiveSyncSettingTab.msgNonHTTPSInfo":{def:"Configured as non-HTTPS URI. Be warned that this may not work on mobile devices.",es:"Configurado como URI que no es HTTPS. Ten en cuenta que esto puede no funcionar en dispositivos móviles.",fr:"Configuré avec une URI non HTTPS. Attention, ceci peut ne pas fonctionner sur les appareils mobiles.",he:"מוגדר כ-URI שאינו HTTPS. שים לב שהדבר עשוי שלא לפעול על מכשירים ניידים.",ja:"非HTTPS URIとして設定されています。モバイルデバイスでは動作しない可能性があります。",ko:"비 HTTPS URI로 구성되었습니다. 모바일 기기에서는 작동하지 않을 수 있으니 주의하세요.",ru:"Настроено как не-HTTPS URI. Это может не работать на мобильных устройствах.",zh:"配置为非 HTTPS URI。请注意,这可能在移动设备上无法工作","zh-tw":"已設定為非 HTTPS 的 URI。請注意,這在行動裝置上可能無法運作。"},"obsidianLiveSyncSettingTab.msgNonHTTPSWarning":{def:"Cannot connect to non-HTTPS URI. Please update your config and try again.",es:"No se puede conectar a URI que no sean HTTPS. Por favor, actualiza tu configuración y vuelve a intentarlo.",fr:"Connexion impossible à une URI non HTTPS. Mettez à jour votre configuration et réessayez.",he:"לא ניתן להתחבר ל-URI שאינו HTTPS. אנא עדכן את התצורה ונסה שוב.",ja:"非HTTPS URIに接続できません。設定を更新して再試行してください。",ko:"비 HTTPS URI에 연결할 수 없습니다. 구성을 업데이트하고 다시 시도해 주세요.",ru:"Не удаётся подключиться к не-HTTPS URI. Обновите конфигурацию.",zh:"无法连接到非 HTTPS URI。请更新您的配置并重试","zh-tw":"無法連線到非 HTTPS 的 URI,請更新你的設定後再試一次。"},"obsidianLiveSyncSettingTab.msgNotice":{def:"---Notice---",es:"---Aviso---",fr:"---Avis---",he:"---הודעה---",ja:"---お知らせ---",ko:"---공지사항---",ru:"---Уведомление---",zh:"---注意---","zh-tw":"---注意---"},"obsidianLiveSyncSettingTab.msgObjectStorageWarning":{def:"WARNING: This feature is a Work In Progress, so please keep in mind the following:\n- Append only architecture. A rebuild is required to shrink the storage.\n- A bit fragile.\n- When first syncing, all history will be transferred from the remote. Be mindful of data caps and slow speeds.\n- Only differences are synced live.\n\nIf you run into any issues, or have ideas about this feature, please create a issue on GitHub.\nI appreciate you for your great dedication.",es:"ADVERTENCIA: Esta característica está en desarrollo, así que por favor ten en cuenta lo siguiente:\n- Arquitectura de solo anexado. Se requiere una reconstrucción para reducir el almacenamiento.\n- Un poco frágil.\n- Al sincronizar por primera vez, todo el historial será transferido desde el remoto. Ten en cuenta los límites de datos y las velocidades lentas.\n- Solo las diferencias se sincronizan en vivo.\n\nSi encuentras algún problema o tienes ideas sobre esta característica, por favor crea un issue en GitHub.\nAprecio mucho tu gran dedicación.",fr:"AVERTISSEMENT : cette fonctionnalité est en cours de développement, gardez à l'esprit ce qui suit :\n- Architecture en ajout seul. Une reconstruction est nécessaire pour réduire le stockage.\n- Un peu fragile.\n- Lors de la première synchronisation, tout l'historique sera transféré depuis le distant. Attention aux limites de données et aux débits lents.\n- Seules les différences sont synchronisées en direct.\n\nSi vous rencontrez des problèmes ou avez des idées sur cette fonctionnalité, merci d'ouvrir un ticket sur GitHub.\nMerci pour votre grand dévouement.",he:"אזהרה: תכונה זו בשלב פיתוח, לכן שים לב לנקודות הבאות:\n- ארכיטקטורת הוספה בלבד. נדרשת בנייה מחדש לצמצום האחסון.\n- קצת רגיש.\n- בסנכרון הראשון, כל ההיסטוריה תועבר מהשרת המרוחד. שים לב למגבלות נתונים ומהירות.\n- רק הפרשים מסונכרנים בזמן אמת.\n\nאם נתקלת בבעיות, או שיש לך רעיונות לגבי תכונה זו, אנא פתח Issue ב-GitHub.\nאנחנו מעריכים את ההקדשה הגדולה שלך.",ja:"警告: この機能は開発中です。以下の点にご注意ください:\n- 追記専用アーキテクチャ。ストレージを縮小するには再構築が必要です。\n- やや不安定です。\n- 初回同期時、すべての履歴がリモートから転送されます。データ制限と速度に注意してください。\n- ライブ同期は差分のみです。\n\n問題があれば、またはこの機能についてアイデアがあれば、GitHubにIssueを作成してください。\nご協力に感謝します。",ko:"경고: 이 기능은 아직 개발 중이므로 다음 사항을 유의해 주세요:\n- 추가 전용 구조로 동작합니다. 저장 용량을 줄이려면 재구축이 필요합니다.\n- 다소 불안정합니다.\n- 최초 동기화 시 모든 기록이 원격에서 전송됩니다. 데이터 사용량 제한과 느린 속도에 유의해 주세요.\n- 실시간 동기화는 변경분만 처리합니다.\n\n문제가 발생했거나 이 기능에 대한 아이디어가 있다면 GitHub에 이슈를 등록해 주세요.\n큰 관심에 깊이 감사드립니다.",ru:"ПРЕДУПРЕЖДЕНИЕ: Эта функция в разработке.",zh:"警告:此功能仍在开发中,请注意以下几点:\n- 仅追加架构。需要重建才能缩小存储空间。\n- 有点脆弱。\n- 首次同步时,所有历史记录将从远程传输。注意数据上限和慢速。\n- 只有差异会实时同步。\n\n如果您遇到任何问题,或对此功能有任何想法,请在 GitHub 上创建 issue。\n感谢您的巨大贡献","zh-tw":"警告:此功能仍在開發中,請注意以下事項:\n- 僅附加架構。需要重建才能縮小儲存空間。\n- 較不穩定。\n- 首次同步時,所有歷史記錄都會從遠端傳輸,請留意流量上限與速度較慢的情況。\n- 之後只會即時同步差異部分。\n\n如果你遇到任何問題,或對此功能有任何想法,請到 GitHub 建立 issue。\n感謝你的大力支持。"},"obsidianLiveSyncSettingTab.msgOriginCheck":{def:"Origin check: ${org}",es:"Verificación de origen: {org}",fr:"Vérification d'origine : ${org}",he:"בדיקת מקור: ${org}",ja:"オリジン確認: ${org}",ko:"출처 확인: ${org}",ru:"Проверка origin: org",zh:"源检查: {org}","zh-tw":"來源檢查:${org}"},"obsidianLiveSyncSettingTab.msgRebuildRequired":{def:"Rebuilding Databases are required to apply the changes.. Please select the method to apply the changes.\n\n<details>\n<summary>Legends</summary>\n\n| Symbol | Meaning |\n|: ------ :| ------- |\n| ⇔ | Up to Date |\n| ⇄ | Synchronise to balance |\n| ⇐,⇒ | Transfer to overwrite |\n| ⇠,⇢ | Transfer to overwrite from other side |\n\n</details>\n\n## ${OPTION_REBUILD_BOTH}\nAt a glance: 📄 ⇒¹ 💻 ⇒² 🛰️ ⇢ⁿ 💻 ⇄ⁿ⁺¹ 📄\nReconstruct both the local and remote databases using existing files from this device.\nThis causes a lockout other devices, and they need to perform fetching.\n## ${OPTION_FETCH}\nAt a glance: 📄 ⇄² 💻 ⇐¹ 🛰️ ⇔ 💻 ⇔ 📄\nInitialise the local database and reconstruct it using data fetched from the remote database.\nThis case includes the case which you have rebuilt the remote database.\n## ${OPTION_ONLY_SETTING}\nStore only the settings. **Caution: This may lead to data corruption**; database reconstruction is generally necessary.",es:"Es necesario reconstruir las bases de datos para aplicar los cambios. Por favor selecciona el método para aplicar los cambios.\n\n<details>\n<summary>Legendas</summary>\n\n| Símbolo | Significado |\n|: ------ :| ------- |\n| ⇔ | Actualizado |\n| ⇄ | Sincronizar para equilibrar |\n| ⇐,⇒ | Transferir para sobrescribir |\n| ⇠,⇢ | Transferir para sobrescribir desde otro lado |\n\n</details>\n\n## ${OPTION_REBUILD_BOTH}\nA simple vista: 📄 ⇒¹ 💻 ⇒² 🛰️ ⇢ⁿ 💻 ⇄ⁿ⁺¹ 📄\nReconstruir tanto la base de datos local como la remota utilizando los archivos existentes de este dispositivo.\nEsto bloquea a otros dispositivos, y necesitan realizar la obtención.\n## ${OPTION_FETCH}\nA simple vista: 📄 ⇄² 💻 ⇐¹ 🛰️ ⇔ 💻 ⇔ 📄\nInicializa la base de datos local y la reconstruye utilizando los datos obtenidos de la base de datos remota.\nEste caso incluye el caso en el que has reconstruido la base de datos remota.\n## ${OPTION_ONLY_SETTING}\nAlmacena solo la configuración. **Precaución: esto puede provocar corrupción de datos**; generalmente es necesario reconstruir la base de datos.",fr:"La reconstruction des bases de données est nécessaire pour appliquer les changements. Veuillez sélectionner la méthode d'application.\n\n<details>\n<summary>Légende</summary>\n\n| Symbole | Signification |\n|: ------ :| ------- |\n| ⇔ | À jour |\n| ⇄ | Synchroniser pour équilibrer |\n| ⇐,⇒ | Transférer pour écraser |\n| ⇠,⇢ | Transférer pour écraser depuis l'autre côté |\n\n</details>\n\n## ${OPTION_REBUILD_BOTH}\nEn bref : 📄 ⇒¹ 💻 ⇒² 🛰️ ⇢ⁿ 💻 ⇄ⁿ⁺¹ 📄\nReconstruit les bases locale et distante à partir des fichiers existants de cet appareil.\nCeci provoque un verrouillage des autres appareils, qui devront effectuer une récupération.\n## ${OPTION_FETCH}\nEn bref : 📄 ⇄² 💻 ⇐¹ 🛰️ ⇔ 💻 ⇔ 📄\nInitialise la base locale et la reconstruit à partir des données récupérées depuis la base distante.\nCe cas inclut également celui où vous avez reconstruit la base distante.\n## ${OPTION_ONLY_SETTING}\nNe stocker que les paramètres. **Attention : cela peut entraîner une corruption des données** ; une reconstruction de la base est généralement nécessaire.",he:"נדרשת בנייה מחדש של מסדי הנתונים כדי להחיל את השינויים. אנא בחר את השיטה.\n\n<details>\n<summary>מקרא</summary>\n\n| סמל | משמעות |\n|: ------ :| ------- |\n| ⇔ | מעודכן |\n| ⇄ | סנכרן לאיזון |\n| ⇐,⇒ | העבר לדריסה |\n| ⇠,⇢ | העבר לדריסה מהצד השני |\n\n</details>\n\n## ${OPTION_REBUILD_BOTH}\nבמבט: 📄 ⇒¹ 💻 ⇒² 🛰️ ⇢ⁿ 💻 ⇄ⁿ⁺¹ 📄\nבנה מחדש גם את מסד הנתונים המקומי וגם המרוחד תוך שימוש בקבצים קיימים ממכשיר זה.\nפעולה זו תנעל מכשירים אחרים שיצטרכו לבצע משיכה.\n## ${OPTION_FETCH}\nבמבט: 📄 ⇄² 💻 ⇐¹ 🛰️ ⇔ 💻 ⇔ 📄\nאתחל את מסד הנתונים המקומי ובנה אותו מחדש תוך שימוש בנתונים שנמשכו ממסד הנתונים המרוחד.\nכולל את המקרה שבו בנית מחדש את מסד הנתונים המרוחד.\n## ${OPTION_ONLY_SETTING}\nשמור רק את ההגדרות. **זהירות: עלול לגרום לפגיעה בנתונים**; בנייה מחדש של מסד הנתונים נדרשת בדרך כלל.",ja:"変更を適用するにはデータベースの再構築が必要です。変更を適用する方法を選択してください。\n\n<details>\n<summary>凡例</summary>\n\n| 記号 | 意味 |\n|: ------ :| ------- |\n| ⇔ | 最新 |\n| ⇄ | 同期してバランスを取る |\n| ⇐,⇒ | 上書きするため転送 |\n| ⇠,⇢ | 反対側から上書きするため転送 |\n\n</details>\n\n## ${OPTION_REBUILD_BOTH}\n概要: 📄 ⇒¹ 💻 ⇒² 🛰️ ⇢ⁿ 💻 ⇄ⁿ⁺¹ 📄\nこのデバイスの既存ファイルを使用してローカルとリモートの両方のデータベースを再構築します。\n他のデバイスはロックアウトされ、フェッチが必要です。\n## ${OPTION_FETCH}\n概要: 📄 ⇄² 💻 ⇐¹ 🛰️ ⇔ 💻 ⇔ 📄\nローカルデータベースを初期化し、リモートデータベースから取得したデータを使用して再構築します。\nリモートデータベースを再構築した場合も含まれます。\n## ${OPTION_ONLY_SETTING}\n設定のみを保存します。**注意: データ破損につながる可能性があります**。通常、データベースの再構築が必要です。",ko:"변경 사항을 적용하려면 데이터베이스를 재구축해야 합니다. 변경 사항을 적용할 방법을 선택해 주세요.\n\n<details>\n<summary>범례</summary>\n\n| 기호 | 의미 |\n|: ------ :| ------- |\n| ⇔ | 최신 상태 |\n| ⇄ | 양쪽을 맞추는 동기화 |\n| ⇐,⇒ | 덮어쓰기 전송 |\n| ⇠,⇢ | 반대편에서 덮어쓰기 전송 |\n\n</details>\n\n## ${OPTION_REBUILD_BOTH}\n한눈에 보기: 📄 ⇒¹ 💻 ⇒² 🛰️ ⇢ⁿ 💻 ⇄ⁿ⁺¹ 📄\n이 기기의 기존 파일을 사용해 로컬과 원격 데이터베이스를 모두 재구축합니다.\n이 경우 다른 기기는 잠기며, 가져오기를 수행해야 합니다.\n## ${OPTION_FETCH}\n한눈에 보기: 📄 ⇄² 💻 ⇐¹ 🛰️ ⇔ 💻 ⇔ 📄\n로컬 데이터베이스를 초기화한 뒤, 원격 데이터베이스에서 가져온 데이터로 재구축합니다.\n원격 데이터베이스를 이미 재구축한 경우도 여기에 해당합니다.\n## ${OPTION_ONLY_SETTING}\n설정만 저장합니다. **주의: 데이터가 손상될 수 있습니다.** 일반적으로는 데이터베이스 재구축이 필요합니다.",ru:"Требуется перестроение баз данных для применения изменений.",zh:"需要重建数据库以应用更改。请选择应用更改的方法。\n\n<details>\n<summary>图例</summary>\n\n| 符号 | 含义 |\n|: ------ :| ------- |\n| ⇔ | 最新 |\n| ⇄ | 同步以平衡 |\n| ⇐,⇒ | 传输以覆盖 |\n| ⇠,⇢ | 从另一侧传输以覆盖 |\n\n</details>\n\n## ${OPTION_REBUILD_BOTH}\n概览:📄 ⇒¹ 💻 ⇒² 🛰️ ⇢ⁿ 💻 ⇄ⁿ⁺¹ 📄\n使用此设备的现有文件重建本地和远程数据库。\n这将导致其他设备被锁定,并且它们需要执行获取操作。\n## ${OPTION_FETCH}\n概览:📄 ⇄² 💻 ⇐¹ 🛰️ ⇔ 💻 ⇔ 📄\n初始化本地数据库并使用从远程数据库获取的数据重建它。\n这种情况包括您已经重建了远程数据库的情况。\n## ${OPTION_ONLY_SETTING}\n仅存储设置。**注意:这可能导致数据损坏**;通常需要重建数据库","zh-tw":"需要重建資料庫才能套用變更。請選擇套用變更的方式。\n\n<details>\n<summary>圖例</summary>\n\n| 符號 | 含意 |\n|: ------ :| ------- |\n| ⇔ | 已是最新 |\n| ⇄ | 同步以取得一致 |\n| ⇐,⇒ | 傳輸並覆寫 |\n| ⇠,⇢ | 從另一端傳輸並覆寫 |\n\n</details>\n\n## ${OPTION_REBUILD_BOTH}\n概覽: 📄 ⇒¹ 💻 ⇒² 🛰️ ⇢ⁿ 💻 ⇄ⁿ⁺¹ 📄\n以此裝置上現有的檔案重建本機與遠端資料庫。\n這會鎖定其他裝置,它們必須執行抓取。\n## ${OPTION_FETCH}\n概覽: 📄 ⇄² 💻 ⇐¹ 🛰️ ⇔ 💻 ⇔ 📄\n初始化本機資料庫,並以從遠端資料庫抓取的資料重建。\n這也涵蓋你已重建遠端資料庫的情況。\n## ${OPTION_ONLY_SETTING}\n僅儲存設定。**注意:這可能導致資料損毀**;通常仍需要重建資料庫。"},"obsidianLiveSyncSettingTab.msgSetCorsCredentials":{def:"Set cors.credentials",es:"Configurar cors.credentials",fr:"Définir cors.credentials",he:"הגדר cors.credentials",ja:"cors.credentialsを設定",ko:"cors.credentials 설정",ru:"Установить cors.credentials",zh:"设置 cors.credentials","zh-tw":"設定 cors.credentials"},"obsidianLiveSyncSettingTab.msgSetCorsOrigins":{def:"Set cors.origins",es:"Configurar cors.origins",fr:"Définir cors.origins",he:"הגדר cors.origins",ja:"cors.originsを設定",ko:"cors.origins 설정",ru:"Установить cors.origins",zh:"设置 cors.origins","zh-tw":"設定 cors.origins"},"obsidianLiveSyncSettingTab.msgSetMaxDocSize":{def:"Set couchdb.max_document_size",es:"Configurar couchdb.max_document_size",fr:"Définir couchdb.max_document_size",he:"הגדר couchdb.max_document_size",ja:"couchdb.max_document_sizeを設定",ko:"couchdb.max_document_size 설정",ru:"Установить couchdb.max_document_size",zh:"设置 couchdb.max_document_size","zh-tw":"設定 couchdb.max_document_size"},"obsidianLiveSyncSettingTab.msgSetMaxRequestSize":{def:"Set chttpd.max_http_request_size",es:"Configurar chttpd.max_http_request_size",fr:"Définir chttpd.max_http_request_size",he:"הגדר chttpd.max_http_request_size",ja:"chttpd.max_http_request_sizeを設定",ko:"chttpd.max_http_request_size 설정",ru:"Установить chttpd.max_http_request_size",zh:"设置 chttpd.max_http_request_size","zh-tw":"設定 chttpd.max_http_request_size"},"obsidianLiveSyncSettingTab.msgSetRequireValidUser":{def:"Set chttpd.require_valid_user = true",es:"Configurar chttpd.require_valid_user = true",fr:"Définir chttpd.require_valid_user = true",he:"הגדר chttpd.require_valid_user = true",ja:"chttpd.require_valid_user = trueを設定",ko:"chttpd.require_valid_user = true로 설정",ru:"Установить chttpd.require_valid_user = true",zh:"设置 chttpd.require_valid_user = true","zh-tw":"設定 chttpd.require_valid_user = true"},"obsidianLiveSyncSettingTab.msgSetRequireValidUserAuth":{def:"Set chttpd_auth.require_valid_user = true",es:"Configurar chttpd_auth.require_valid_user = true",fr:"Définir chttpd_auth.require_valid_user = true",he:"הגדר chttpd_auth.require_valid_user = true",ja:"chttpd_auth.require_valid_user = trueを設定",ko:"chttpd_auth.require_valid_user = true로 설정",ru:"Установить chttpd_auth.require_valid_user = true",zh:"设置 chttpd_auth.require_valid_user = true","zh-tw":"設定 chttpd_auth.require_valid_user = true"},"obsidianLiveSyncSettingTab.msgSettingModified":{def:'The setting "${setting}" was modified from another device. Click {HERE} to reload settings. Click elsewhere to ignore changes.',es:'La configuración "${setting}" fue modificada desde otro dispositivo. Haz clic {HERE} para recargar la configuración. Haz clic en otro lugar para ignorar los cambios.',fr:"Le paramètre « ${setting} » a été modifié depuis un autre appareil. Cliquez sur {HERE} pour recharger les paramètres. Cliquez ailleurs pour ignorer les modifications.",he:'ההגדרה "${setting}" שונתה ממכשיר אחר. לחץ על {HERE} לטעינה מחדש של ההגדרות. לחץ במקום אחר להתעלמות מהשינויים.',ja:'設定"${setting}"が別のデバイスから変更されました。{HERE}をクリックして設定を再読み込みしてください。変更を無視するには他の場所をクリックしてください。',ko:'"${setting}" 설정이 다른 기기에서 수정되었습니다. 설정을 다시 로드하려면 {HERE}를 클릭하세요. 변경사항을 무시하려면 다른 곳을 클릭하세요.',ru:"Настройка setting была изменена с другого устройства.",zh:'设置 "${setting}" 已从另一台设备修改。点击 {HERE} 重新加载设置。点击其他地方忽略更改',"zh-tw":"設定「${setting}」已由另一台裝置修改。點選 {HERE} 可重新載入設定,點選其他位置則忽略變更。"},"obsidianLiveSyncSettingTab.msgSettingsUnchangeableDuringSync":{def:'These settings are unable to be changed during synchronization. Please disable all syncing in the "Sync Settings" to unlock.',es:'Estas configuraciones no se pueden cambiar durante la sincronización. Por favor, deshabilita toda la sincronización en las "Configuraciones de Sincronización" para desbloquear.',fr:"Ces paramètres ne peuvent pas être modifiés durant la synchronisation. Désactivez toute synchronisation dans « Paramètres de synchronisation » pour déverrouiller.",he:'הגדרות אלה אינן ניתנות לשינוי במהלך סנכרון. אנא נטרל את כל הסנכרון ב"הגדרות סנכרון" כדי לבטל נעילה.',ja:'これらの設定は同期中に変更できません。ロックを解除するには、"同期設定"ですべての同期を無効にしてください。',ko:'동기화 중에는 이 설정들을 변경할 수 없습니다. 잠금을 해제하려면 "동기화 설정"에서 모든 동기화를 비활성화해 주세요.',ru:"Эти настройки нельзя изменить во время синхронизации.",zh:"这些设置在同步期间无法更改。请在“同步设置”中禁用所有同步以解锁","zh-tw":"同步期間無法變更這些設定。請在「同步設定」中停用所有同步以解鎖。"},"obsidianLiveSyncSettingTab.msgSetWwwAuth":{def:"Set httpd.WWW-Authenticate",es:"Configurar httpd.WWW-Authenticate",fr:"Définir httpd.WWW-Authenticate",he:"הגדר httpd.WWW-Authenticate",ja:"httpd.WWW-Authenticateを設定",ko:"httpd.WWW-Authenticate 설정",ru:"Установить httpd.WWW-Authenticate",zh:"设置 httpd.WWW-Authenticate","zh-tw":"設定 httpd.WWW-Authenticate"},"obsidianLiveSyncSettingTab.nameApplySettings":{def:"Apply Settings",es:"Aplicar configuraciones",fr:"Appliquer les paramètres",he:"החל הגדרות",ja:"設定を適用",ko:"설정 적용",ru:"Применить настройки",zh:"应用设置","zh-tw":"套用設定"},"obsidianLiveSyncSettingTab.nameConnectSetupURI":{def:"Connect with Setup URI",es:"Conectar con URI de configuración",fr:"Se connecter avec une URI de configuration",he:"התחבר עם Setup URI",ja:"セットアップURIで接続",ko:"Setup URI로 연결",ru:"Подключиться через Setup URI",zh:"使用设置 URI 连接","zh-tw":"使用 Setup URI 連線"},"obsidianLiveSyncSettingTab.nameCopySetupURI":{def:"Copy the current settings to a Setup URI",es:"Copiar la configuración actual a una URI de configuración",fr:"Copier les paramètres actuels vers une URI de configuration",he:"העתק הגדרות נוכחיות ל-Setup URI",ja:"現在の設定をセットアップURIにコピー",ko:"현재 설정을 Setup URI로 복사",ru:"Копировать текущие настройки в Setup URI",zh:"将当前设置复制为设置 URI","zh-tw":"將目前設定複製為 Setup URI"},"obsidianLiveSyncSettingTab.nameDisableHiddenFileSync":{def:"Disable Hidden files sync",es:"Desactivar sincronización de archivos ocultos",fr:"Désactiver la synchronisation des fichiers cachés",he:"נטרל סנכרון קבצים נסתרים",ja:"隠しファイル同期を無効化",ko:"숨김 파일 동기화 비활성화",ru:"Отключить синхронизацию скрытых файлов",zh:"禁用隐藏文件同步","zh-tw":"停用隱藏檔案同步"},"obsidianLiveSyncSettingTab.nameDiscardSettings":{def:"Discard existing settings and databases",es:"Descartar configuraciones y bases de datos existentes",fr:"Abandonner les paramètres et bases existants",he:"בטל הגדרות ומסדי נתונים קיימים",ja:"既存の設定とデータベースを破棄",ko:"기존 설정 및 데이터베이스 삭제",ru:"Отменить существующие настройки и базы данных",zh:"丢弃现有设置和数据库","zh-tw":"捨棄現有的設定與資料庫"},"obsidianLiveSyncSettingTab.nameEnableHiddenFileSync":{def:"Enable Hidden files sync",es:"Activar sincronización de archivos ocultos",fr:"Activer la synchronisation des fichiers cachés",he:"הפעל סנכרון קבצים נסתרים",ja:"隠しファイル同期を有効化",ko:"숨김 파일 동기화 활성화",ru:"Включить синхронизацию скрытых файлов",zh:"启用隐藏文件同步","zh-tw":"啟用隱藏檔案同步"},"obsidianLiveSyncSettingTab.nameEnableLiveSync":{def:"Enable LiveSync",es:"Activar LiveSync",fr:"Activer LiveSync",he:"הפעל LiveSync",ja:"LiveSyncを有効化",ko:"LiveSync 활성화",ru:"Включить LiveSync",zh:"启用 LiveSync","zh-tw":"啟用 LiveSync"},"obsidianLiveSyncSettingTab.nameHiddenFileSynchronization":{def:"Hidden file synchronization",es:"Sincronización de archivos ocultos",fr:"Synchronisation des fichiers cachés",he:"סנכרון קבצים נסתרים",ja:"隠しファイル同期",ko:"숨김 파일 동기화",ru:"Синхронизация скрытых файлов",zh:"隐藏文件同步","zh-tw":"隱藏檔案同步"},"obsidianLiveSyncSettingTab.nameManualSetup":{def:"Manual Setup",es:"Configuración manual",fr:"Configuration manuelle",he:"הגדרה ידנית",ja:"手動セットアップ",ko:"수동 설정",ru:"Ручная настройка",zh:"手动设置","zh-tw":"手動設定"},"obsidianLiveSyncSettingTab.nameTestConnection":{def:"Test Connection",es:"Probar conexión",fr:"Tester la connexion",he:"בדוק חיבור",ja:"接続テスト",ko:"연결 테스트",ru:"Тест подключения",zh:"测试连接","zh-tw":"測試連線"},"obsidianLiveSyncSettingTab.nameTestDatabaseConnection":{def:"Test Database Connection",es:"Probar Conexión de Base de Datos",fr:"Tester la connexion à la base de données",he:"בדוק חיבור למסד נתונים",ja:"データベース接続テスト",ko:"데이터베이스 연결 테스트",ru:"Тест подключения к базе данных",zh:"测试数据库连接","zh-tw":"測試資料庫連線"},"obsidianLiveSyncSettingTab.nameValidateDatabaseConfig":{def:"Validate Database Configuration",es:"Validar Configuración de la Base de Datos",fr:"Valider la configuration de la base de données",he:"אמת תצורת מסד נתונים",ja:"データベース設定を検証",ko:"데이터베이스 구성 검증",ru:"Проверить конфигурацию базы данных",zh:"验证数据库配置","zh-tw":"驗證資料庫設定"},"obsidianLiveSyncSettingTab.okAdminPrivileges":{def:"✔ You have administrator privileges.",es:"✔ Tienes privilegios de administrador.",fr:"✔ Vous disposez des privilèges administrateur.",he:"✔ יש לך הרשאות מנהל.",ja:"✔ 管理者権限があります。",ko:"✔ 관리자 권한이 있습니다.",ru:"✔ У вас есть права администратора.",zh:"✔ 您拥有管理员权限","zh-tw":"✔ 你具有管理者權限。"},"obsidianLiveSyncSettingTab.okCorsCredentials":{def:"✔ cors.credentials is ok.",es:"✔ cors.credentials está correcto.",fr:"✔ cors.credentials est correct.",he:"✔ cors.credentials תקין.",ja:"✔ cors.credentialsは正常です。",ko:"✔ cors.credentials가 정상입니다.",ru:"✔ cors.credentials в порядке.",zh:"✔ cors.credentials 设置正确","zh-tw":"✔ cors.credentials 設定正確。"},"obsidianLiveSyncSettingTab.okCorsCredentialsForOrigin":{def:"CORS credentials OK",es:"CORS credenciales OK",fr:"Identifiants CORS OK",he:"CORS credentials תקין",ja:"CORS認証情報OK",ko:"CORS 자격 증명 정상",ru:"CORS учётные данные в порядке",zh:"CORS 凭据正常","zh-tw":"CORS 憑證正常"},"obsidianLiveSyncSettingTab.okCorsOriginMatched":{def:"✔ CORS origin OK",es:"✔ Origen de CORS correcto",fr:"✔ Origine CORS OK",he:"✔ CORS origin תקין",ja:"✔ CORSオリジンOK",ko:"✔ CORS 출처 정상",ru:"✔ CORS origin в порядке",zh:"✔ CORS 源正常","zh-tw":"✔ CORS 來源正常"},"obsidianLiveSyncSettingTab.okCorsOrigins":{def:"✔ cors.origins is ok.",es:"✔ cors.origins está correcto.",fr:"✔ cors.origins est correct.",he:"✔ cors.origins תקין.",ja:"✔ cors.originsは正常です。",ko:"✔ cors.origins가 정상입니다.",ru:"✔ cors.origins в порядке.",zh:"✔ cors.origins 设置正确","zh-tw":"✔ cors.origins 設定正確。"},"obsidianLiveSyncSettingTab.okEnableCors":{def:"✔ httpd.enable_cors is ok.",es:"✔ httpd.enable_cors está correcto.",fr:"✔ httpd.enable_cors est correct.",he:"✔ httpd.enable_cors תקין.",ja:"✔ httpd.enable_corsは正常です。",ko:"✔ httpd.enable_cors가 정상입니다.",ru:"✔ httpd.enable_cors в порядке.",zh:"✔ httpd.enable_cors 设置正确","zh-tw":"✔ httpd.enable_cors 設定正確。"},"obsidianLiveSyncSettingTab.okEnableCorsChttpd":{def:"✔ chttpd.enable_cors is ok.",es:"✔ chttpd.enable_cors es correcto.",fr:"✔ chttpd.enable_cors est correct.",he:"✔ chttpd.enable_cors תקין.",ja:"✔ chttpd.enable_corsは正常です。",ko:"✔ chttpd.enable_cors가 정상입니다.",ru:"✔ chttpd.enable_cors в порядке.",zh:"✔ chttpd.enable_cors is ok.","zh-tw":"✔ chttpd.enable_cors 設定正確。"},"obsidianLiveSyncSettingTab.okMaxDocumentSize":{def:"✔ couchdb.max_document_size is ok.",es:"✔ couchdb.max_document_size está correcto.",fr:"✔ couchdb.max_document_size est correct.",he:"✔ couchdb.max_document_size תקין.",ja:"✔ couchdb.max_document_sizeは正常です。",ko:"✔ couchdb.max_document_size가 정상입니다.",ru:"✔ couchdb.max_document_size в порядке.",zh:"✔ couchdb.max_document_size 设置正确","zh-tw":"✔ couchdb.max_document_size 設定正確。"},"obsidianLiveSyncSettingTab.okMaxRequestSize":{def:"✔ chttpd.max_http_request_size is ok.",es:"✔ chttpd.max_http_request_size está correcto.",fr:"✔ chttpd.max_http_request_size est correct.",he:"✔ chttpd.max_http_request_size תקין.",ja:"✔ chttpd.max_http_request_sizeは正常です。",ko:"✔ chttpd.max_http_request_size가 정상입니다.",ru:"✔ chttpd.max_http_request_size в порядке.",zh:"✔ chttpd.max_http_request_size 设置正确","zh-tw":"✔ chttpd.max_http_request_size 設定正確。"},"obsidianLiveSyncSettingTab.okRequireValidUser":{def:"✔ chttpd.require_valid_user is ok.",es:"✔ chttpd.require_valid_user está correcto.",fr:"✔ chttpd.require_valid_user est correct.",he:"✔ chttpd.require_valid_user תקין.",ja:"✔ chttpd.require_valid_userは正常です。",ko:"✔ chttpd.require_valid_user가 정상입니다.",ru:"✔ chttpd.require_valid_user в порядке.",zh:"✔ chttpd.require_valid_user 设置正确","zh-tw":"✔ chttpd.require_valid_user 設定正確。"},"obsidianLiveSyncSettingTab.okRequireValidUserAuth":{def:"✔ chttpd_auth.require_valid_user is ok.",es:"✔ chttpd_auth.require_valid_user está correcto.",fr:"✔ chttpd_auth.require_valid_user est correct.",he:"✔ chttpd_auth.require_valid_user תקין.",ja:"✔ chttpd_auth.require_valid_userは正常です。",ko:"✔ chttpd_auth.require_valid_user가 정상입니다.",ru:"✔ chttpd_auth.require_valid_user в порядке.",zh:"✔ chttpd_auth.require_valid_user 设置正确","zh-tw":"✔ chttpd_auth.require_valid_user 設定正確。"},"obsidianLiveSyncSettingTab.okWwwAuth":{def:"✔ httpd.WWW-Authenticate is ok.",es:"✔ httpd.WWW-Authenticate está correcto.",fr:"✔ httpd.WWW-Authenticate est correct.",he:"✔ httpd.WWW-Authenticate תקין.",ja:"✔ httpd.WWW-Authenticateは正常です。",ko:"✔ httpd.WWW-Authenticate가 정상입니다.",ru:"✔ httpd.WWW-Authenticate в порядке.",zh:"✔ httpd.WWW-Authenticate 设置正确","zh-tw":"✔ httpd.WWW-Authenticate 設定正確。"},"obsidianLiveSyncSettingTab.optionApply":{def:"Apply",es:"Aplicar",fr:"Appliquer",he:"החל",ja:"適用",ko:"적용",ru:"Применить",zh:"应用","zh-tw":"套用"},"obsidianLiveSyncSettingTab.optionCancel":{def:"Cancel",es:"Cancelar",fr:"Annuler",he:"ביטול",ja:"キャンセル",ko:"취소",ru:"Отмена",zh:"取消","zh-tw":"取消"},"obsidianLiveSyncSettingTab.optionCouchDB":{def:"CouchDB",es:"CouchDB",fr:"CouchDB",he:"CouchDB",ja:"CouchDB",ko:"CouchDB",ru:"CouchDB",zh:"CouchDB","zh-tw":"CouchDB"},"obsidianLiveSyncSettingTab.optionDisableAllAutomatic":{def:"Disable all automatic",es:"Desactivar lo automático",fr:"Désactiver toute automatisation",he:"נטרל את כל האוטומטי",ja:"すべての自動を無効化",ko:"모든 자동 비활성화",ru:"Отключить всё автоматическое",zh:"禁用所有自动同步","zh-tw":"停用所有自動同步"},"obsidianLiveSyncSettingTab.optionFetchFromRemote":{def:"Fetch from Remote",es:"Obtener del remoto",fr:"Récupérer depuis le distant",he:"משוך מהשרת המרוחד",ja:"リモートからフェッチ",ko:"원격에서 가져오기",ru:"Загрузить с удалённого",zh:"从远程获取","zh-tw":"從遠端抓取"},"obsidianLiveSyncSettingTab.optionHere":{def:"HERE",es:"AQUÍ",fr:"ICI",he:"כאן",ja:"ここ",ko:"여기",ru:"ЗДЕСЬ",zh:"这里","zh-tw":"這裡"},"obsidianLiveSyncSettingTab.optionLiveSync":{def:"LiveSync",es:"Sincronización LiveSync",fr:"LiveSync",he:"LiveSync",ja:"LiveSync 同期",ko:"LiveSync",ru:"Синхронизация LiveSync",zh:"LiveSync 同步","zh-tw":"LiveSync 同步"},"obsidianLiveSyncSettingTab.optionMinioS3R2":{def:"Minio,S3,R2",es:"Minio,S3,R2",fr:"Minio, S3, R2",he:"Minio,S3,R2",ja:"Minio,S3,R2",ko:"MinIO, S3, R2",ru:"Minio,S3,R2",zh:"Minio, S3, R2","zh-tw":"Minio、S3、R2"},"obsidianLiveSyncSettingTab.optionOkReadEverything":{def:"OK, I have read everything.",es:"OK, he leído todo.",fr:"OK, j'ai tout lu.",he:"בסדר, קראתי הכל.",ja:"OK、すべて読みました。",ko:"네, 모든 것을 읽었습니다.",ru:"ОК, я всё прочитал.",zh:"好的,我已经阅读了所有内容 ","zh-tw":"好,我已全部閱讀完畢。"},"obsidianLiveSyncSettingTab.optionOnEvents":{def:"On events",es:"En eventos",fr:"Sur événements",he:"על אירועים",ja:"イベント時",ko:"이벤트 시",ru:"По событиям",zh:"事件触发时","zh-tw":"事件觸發時"},"obsidianLiveSyncSettingTab.optionPeriodicAndEvents":{def:"Periodic and on events",es:"Periódico y en eventos",fr:"Périodique et sur événements",he:"תקופתי ועל אירועים",ja:"定期およびイベント時",ko:"주기적 및 이벤트 시",ru:"Периодически и по событиям",zh:"定期与事件触发","zh-tw":"定期與事件觸發"},"obsidianLiveSyncSettingTab.optionPeriodicWithBatch":{def:"Periodic w/ batch",es:"Periódico con lote",fr:"Périodique avec lot",he:"תקופתי עם אצווה",ja:"バッチ付き定期",ko:"주기적 w/ 일괄",ru:"Периодически с пакетами",zh:"定期(批处理)","zh-tw":"定期(批次)"},"obsidianLiveSyncSettingTab.optionRebuildBoth":{def:"Rebuild Both from This Device",es:"Reconstructuir ambos desde este dispositivo",fr:"Tout reconstruire depuis cet appareil",he:"בנה שניהם מחדש ממכשיר זה",ja:"このデバイスから両方を再構築",ko:"이 기기에서 둘 다 재구축",ru:"Перестроить оба с этого устройства",zh:"从此设备重建两者","zh-tw":"從此裝置重建兩端"},"obsidianLiveSyncSettingTab.optionSaveOnlySettings":{def:"(Danger) Save Only Settings",es:"(Peligro) Guardar solo configuración",fr:"(Danger) N'enregistrer que les paramètres",he:"(סכנה) שמור הגדרות בלבד",ja:"(危険) 設定のみ保存",ko:"(위험) 설정만 저장",ru:"(Опасно) Сохранить только настройки",zh:"(危险)仅保存设置","zh-tw":"(危險)僅儲存設定"},"obsidianLiveSyncSettingTab.panelChangeLog":{def:"Change Log",es:"Registro de cambios",fr:"Journal des modifications",he:"יומן שינויים",ja:"変更履歴",ko:"변경 로그",ru:"История изменений",zh:"更新日志","zh-tw":"變更紀錄"},"obsidianLiveSyncSettingTab.panelGeneralSettings":{def:"General Settings",es:"Configuraciones Generales",fr:"Paramètres généraux",he:"הגדרות כלליות",ja:"一般設定",ko:"일반 설정",ru:"Основные настройки",zh:"常规设置","zh-tw":"一般設定"},"obsidianLiveSyncSettingTab.panelPrivacyEncryption":{def:"Privacy & Encryption",es:"Privacidad y Cifrado",fr:"Confidentialité et chiffrement",he:"פרטיות והצפנה",ja:"プライバシーと暗号化",ko:"개인정보 보호 및 암호화",ru:"Конфиденциальность и шифрование",zh:"隐私与加密","zh-tw":"隱私與加密"},"obsidianLiveSyncSettingTab.panelRemoteConfiguration":{def:"Remote Configuration",es:"Configuración remota",fr:"Configuration distante",he:"תצורת שרת מרוחד",ja:"リモート設定",ko:"원격 구성",ru:"Удалённая конфигурация",zh:"远程配置","zh-tw":"遠端設定"},"obsidianLiveSyncSettingTab.panelSetup":{def:"Setup",es:"Configuración",fr:"Configuration",he:"הגדרה",ja:"セットアップ",ko:"설정",ru:"Настройка",zh:"设置","zh-tw":"設定"},"obsidianLiveSyncSettingTab.serverVersion":{def:"Server info: ${info}",es:"Información del servidor: ${info}",fr:"Infos serveur : ${info}",he:"פרטי שרת: ${info}",ja:"サーバー情報: ${info}",ko:"서버 정보: ${info}",ru:"Информация о сервере: info",zh:"服务器信息: ${info}","zh-tw":"伺服器資訊:${info}"},"obsidianLiveSyncSettingTab.titleActiveRemoteServer":{def:"Active Remote Server",es:"Servidor remoto activo",fr:"Serveur distant actif",he:"שרת מרוחד פעיל",ja:"アクティブなリモートサーバー",ko:"활성 원격 서버",ru:"Активный удалённый сервер",zh:"活动远程服务器","zh-tw":"使用中的遠端伺服器"},"obsidianLiveSyncSettingTab.titleAdvancedSettings":{def:"Advanced settings"},"obsidianLiveSyncSettingTab.titleAppearance":{def:"Appearance",es:"Apariencia",fr:"Apparence",he:"מראה",ja:"外観",ko:"모양",ru:"Внешний вид",zh:"外观","zh-tw":"外觀"},"obsidianLiveSyncSettingTab.titleConflictResolution":{def:"Conflict resolution",es:"Resolución de conflictos",fr:"Résolution des conflits",he:"פתרון קונפליקטים",ja:"競合解決",ko:"충돌 해결",ru:"Разрешение конфликтов",zh:"冲突处理","zh-tw":"衝突處理"},"obsidianLiveSyncSettingTab.titleCouchDB":{def:"CouchDB",es:"Servidor CouchDB",fr:"CouchDB",he:"CouchDB",ja:"CouchDB サーバー",ko:"CouchDB",ru:"Сервер CouchDB",zh:"CouchDB 服务器","zh-tw":"CouchDB 伺服器"},"obsidianLiveSyncSettingTab.titleDeletionPropagation":{def:"Deletion Propagation",es:"Propagación de eliminación",fr:"Propagation des suppressions",he:"הפצת מחיקות",ja:"削除の伝播",ko:"삭제 전파",ru:"Распространение удалений",zh:"删除传播","zh-tw":"刪除傳播"},"obsidianLiveSyncSettingTab.titleEncryptionNotEnabled":{def:"Encryption is not enabled",es:"El cifrado no está habilitado",fr:"Le chiffrement n'est pas activé",he:"ההצפנה אינה מופעלת",ja:"暗号化が有効になっていません",ko:"암호화가 활성화되지 않음",ru:"Шифрование не включено",zh:"尚未启用加密","zh-tw":"尚未啟用加密"},"obsidianLiveSyncSettingTab.titleEncryptionPassphraseInvalid":{def:"Encryption Passphrase Invalid",es:"La frase de contraseña de cifrado es inválida",fr:"Phrase secrète de chiffrement invalide",he:"ביטוי סיסמה להצפנה לא תקין",ja:"暗号化パスフレーズが無効です",ko:"암호화 패스프레이즈 유효하지 않음",ru:"Парольная фраза шифрования недействительна",zh:"加密密码短语无效","zh-tw":"加密密語無效"},"obsidianLiveSyncSettingTab.titleExtraFeatures":{def:"Enable extra and advanced features",es:"Habilitar funciones extras y avanzadas",fr:"Activer les fonctionnalités supplémentaires et avancées",he:"הפעל תכונות נוספות ומתקדמות",ja:"追加および上級機能を有効化",ko:"추가 및 고급 기능 활성화",ru:"Включить дополнительные и расширенные функции",zh:"启用额外和高级功能","zh-tw":"啟用額外與進階功能"},"obsidianLiveSyncSettingTab.titleExtraFeaturesGroup":{def:"Extra features"},"obsidianLiveSyncSettingTab.titleExtraMenus":{def:"Extra menus"},"obsidianLiveSyncSettingTab.titleFetchConfig":{def:"Fetch Config",es:"Obtener configuración",fr:"Récupérer la configuration",he:"משוך תצורה",ja:"設定を取得",ko:"구성 가져오기",ru:"Загрузить конфигурацию",zh:"获取配置","zh-tw":"抓取設定"},"obsidianLiveSyncSettingTab.titleFetchConfigFromRemote":{def:"Fetch config from remote server",es:"Obtener configuración del servidor remoto",fr:"Récupérer la configuration depuis le serveur distant",he:"משוך תצורה מהשרת המרוחד",ja:"リモートサーバーから設定を取得",ko:"원격 서버에서 구성 가져오기",ru:"Загрузить конфигурацию с удалённого сервера",zh:"从远程服务器获取配置","zh-tw":"從遠端伺服器抓取設定"},"obsidianLiveSyncSettingTab.titleFetchSettings":{def:"Fetch Settings",es:"Obtener configuraciones",fr:"Récupérer les paramètres",he:"משוך הגדרות",ja:"設定の取得",ko:"설정 가져오기",ru:"Загрузить настройки",zh:"获取设置","zh-tw":"抓取設定"},"obsidianLiveSyncSettingTab.titleHelpAndInformation":{def:"Help and information"},"obsidianLiveSyncSettingTab.titleHelpAndTroubleshooting":{def:"Help and troubleshooting"},"obsidianLiveSyncSettingTab.titleHiddenFiles":{def:"Hidden Files",es:"Archivos ocultos",fr:"Fichiers cachés",he:"קבצים נסתרים",ja:"隠しファイル",ko:"숨김 파일",ru:"Скрытые файлы",zh:"隐藏文件","zh-tw":"隱藏檔案"},"obsidianLiveSyncSettingTab.titleLogging":{def:"Logging",es:"Registro",fr:"Journalisation",he:"רישום יומן",ja:"ログ",ko:"로깅",ru:"Логирование",zh:"日志","zh-tw":"記錄"},"obsidianLiveSyncSettingTab.titleMaintenanceAndRecovery":{def:"Maintenance and recovery"},"obsidianLiveSyncSettingTab.titleMinioS3R2":{def:"Minio,S3,R2",es:"MinIO, S3, R2",fr:"Minio, S3, R2",he:"Minio,S3,R2",ja:"MinIO、S3、R2",ko:"MinIO, S3, R2",ru:"MinIO, S3, R2",zh:"MinIO、S3、R2","zh-tw":"MinIO、S3、R2"},"obsidianLiveSyncSettingTab.titleNotification":{def:"Notification",es:"Notificación",fr:"Notification",he:"התראה",ja:"通知",ko:"알림",ru:"Уведомления",zh:"通知","zh-tw":"通知"},"obsidianLiveSyncSettingTab.titleOnlineTips":{def:"Online Tips",es:"Consejos en línea",fr:"Conseils en ligne",he:"טיפים אונליין",ja:"オンラインヒント",ko:"온라인 팁",ru:"Онлайн советы",zh:"在线提示","zh-tw":"線上提示"},"obsidianLiveSyncSettingTab.titleQuickSetup":{def:"Quick Setup",es:"Configuración rápida",fr:"Configuration rapide",he:"הגדרה מהירה",ja:"クイックセットアップ",ko:"빠른 설정",ru:"Быстрая настройка",zh:"快速设置","zh-tw":"快速設定"},"obsidianLiveSyncSettingTab.titleRebuildRequired":{def:"Rebuild Required",es:"Reconstrucción necesaria",fr:"Reconstruction requise",he:"נדרשת בנייה מחדש",ja:"再構築が必要",ko:"재구축 필요",ru:"Требуется перестроение",zh:"需要重建","zh-tw":"需要重建"},"obsidianLiveSyncSettingTab.titleRemoteConfigCheckFailed":{def:"Remote Configuration Check Failed",es:"La verificación de configuración remota falló",fr:"Échec de la vérification de la configuration distante",he:"בדיקת תצורת שרת מרוחד נכשלה",ja:"リモート設定の確認に失敗",ko:"원격 구성 확인 실패",ru:"Проверка удалённой конфигурации не удалась",zh:"远端配置检查失败","zh-tw":"遠端設定檢查失敗"},"obsidianLiveSyncSettingTab.titleRemoteServer":{def:"Remote Server",es:"Servidor remoto",fr:"Serveur distant",he:"שרת מרוחד",ja:"リモートサーバー",ko:"원격 서버",ru:"Удалённый сервер",zh:"远端服务器","zh-tw":"遠端伺服器"},"obsidianLiveSyncSettingTab.titleReset":{def:"Reset",es:"Reiniciar",fr:"Réinitialiser",he:"אתחול",ja:"リセット",ko:"재설정",ru:"Сброс",zh:"重置","zh-tw":"重設"},"obsidianLiveSyncSettingTab.titleSetupOtherDevices":{def:"Set up other devices",es:"Para configurar otros dispositivos",fr:"Pour configurer d'autres appareils",he:"להגדרת מכשירים אחרים",ja:"他のデバイスのセットアップ",ko:"다른 기기 설정",ru:"Для настройки других устройств",zh:"设置其他设备","zh-tw":"設定其他裝置"},"obsidianLiveSyncSettingTab.titleSynchronisation":{def:"Synchronisation"},"obsidianLiveSyncSettingTab.titleSynchronizationMethod":{def:"Synchronization Method",es:"Método de sincronización",fr:"Méthode de synchronisation",he:"שיטת סנכרון",ja:"同期方法",ko:"동기화 방법",ru:"Метод синхронизации",zh:"同步方式","zh-tw":"同步方式"},"obsidianLiveSyncSettingTab.titleSynchronizationPreset":{def:"Synchronization Preset",es:"Preestablecimiento de sincronización",fr:"Préréglage de synchronisation",he:"קבוע מראש לסנכרון",ja:"同期プリセット",ko:"동기화 프리셋",ru:"Пресет синхронизации",zh:"同步预设","zh-tw":"同步預設"},"obsidianLiveSyncSettingTab.titleSyncSettings":{def:"Sync Settings",es:"Configuraciones de Sincronización",fr:"Paramètres de synchronisation",he:"הגדרות סנכרון",ja:"同期設定",ko:"동기화 설정",ru:"Настройки синхронизации",zh:"同步设置","zh-tw":"同步設定"},"obsidianLiveSyncSettingTab.titleSyncSettingsViaMarkdown":{def:"Sync Settings via Markdown",es:"Configuración de sincronización a través de Markdown",fr:"Synchroniser les paramètres via Markdown",he:"סנכרון הגדרות דרך Markdown",ja:"Markdown経由で設定を同期",ko:"마크다운을 통한 설정 동기화",ru:"Синхронизация настроек через Markdown",zh:"通过 Markdown 同步设置","zh-tw":"透過 Markdown 同步設定"},"obsidianLiveSyncSettingTab.titleUpdateThinning":{def:"Update Thinning",es:"Actualización de adelgazamiento",fr:"Lissage des mises à jour",he:"דילול עדכונים",ja:"更新の間引き",ko:"업데이트 솎아내기",ru:"Оптимизация обновлений",zh:"更新精简","zh-tw":"更新精簡"},"obsidianLiveSyncSettingTab.warnCorsOriginUnmatched":{def:"⚠ CORS Origin is unmatched ${from}->${to}",es:"⚠ El origen de CORS no coincide: {from}->{to}",fr:"⚠ L'origine CORS ne correspond pas ${from}->${to}",he:"⚠ CORS Origin אינו תואם ${from}->${to}",ja:"⚠ CORS Originが一致しません ${from}->${to}",ko:"⚠ CORS 출처가 일치하지 않습니다 ${from}->${to}",ru:"⚠ CORS Origin не совпадает from->to",zh:"⚠ CORS 源不匹配 {from}->{to}","zh-tw":"⚠ CORS 來源不相符 ${from}->${to}"},"obsidianLiveSyncSettingTab.warnNoAdmin":{def:"⚠ You do not have administrator privileges.",es:"⚠ No tienes privilegios de administrador.",fr:"⚠ Vous n'avez pas les privilèges administrateur.",he:"⚠ אין לך הרשאות מנהל.",ja:"⚠ 管理者権限がありません。",ko:"⚠ 관리자 권한이 없습니다.",ru:"⚠ У вас нет прав администратора.",zh:"⚠ 您没有管理员权限","zh-tw":"⚠ 你沒有管理者權限。"},"Of course, we can back up the data before proceeding.":{def:"Of course, we can back up the data before proceeding.",es:"Por supuesto, se puede hacer una copia de seguridad de los datos antes de continuar.",ko:"물론 진행하기 전에 데이터를 백업할 수 있습니다.","zh-tw":"當然,你也可以在繼續之前先備份資料。"},Off:{def:"Off",es:"Desactivado",ko:"꺼짐","zh-tw":"關閉"},Ok:{def:"Ok",es:"Aceptar",ja:"OK",ko:"확인",ru:"ОК",zh:"确定","zh-tw":"確定"},"Old Algorithm":{def:"Old Algorithm",es:"Algoritmo antiguo",ja:"旧アルゴリズム",ko:"이전 알고리즘",ru:"Старый алгоритм",zh:"旧算法","zh-tw":"舊演算法"},"Older (${diff})":{def:"Older (${diff})",es:"Más antiguo (${diff})",ko:"더 오래됨 (${diff})","zh-tw":"較舊(${diff}"},"Older fallback (Slow, W/O WebAssembly)":{def:"Older fallback (Slow, W/O WebAssembly)",es:"Alternativa anterior (lenta, sin WebAssembly)",ja:"旧フォールバック (低速、WebAssembly なし)",ko:"이전 대체 방식 (느림, WebAssembly 없음)",ru:"Старый вариант fallback (медленный, без WebAssembly)",zh:"旧版回退(较慢,无 WebAssembly","zh-tw":"舊版回退(較慢,無 WebAssembly"},On:{def:"On",es:"Activado",ko:"켜짐","zh-tw":"開啟"},"On the source device, from the command palette, run the 'Show settings as a QR code' command.":{def:"On the source device, from the command palette, run the 'Show settings as a QR code' command.",es:"En el dispositivo de origen, ejecuta desde la paleta de comandos «Show settings as a QR code».",ko:"원본 기기에서 명령 팔레트를 열고 'Show settings as a QR code' 명령을 실행합니다.","zh-tw":"在來源裝置上,於命令面板執行「將設定顯示為 QR 碼」命令。"},"On the source device, open Obsidian.":{def:"On the source device, open Obsidian.",es:"En el dispositivo de origen, abre Obsidian.",ko:"원본 기기에서 Obsidian을 엽니다.","zh-tw":"在來源裝置上開啟 Obsidian。"},"On this device, please keep this Vault open.":{def:"On this device, please keep this Vault open.",es:"En este dispositivo, mantén este Vault abierto.",ko:"이 기기에서는 이 보관함을 계속 열어 두세요.","zh-tw":"在這台裝置上,請保持此 Vault 開啟。"},"On this device, switch to the camera app or use a QR code scanner to scan the displayed QR code.":{def:"On this device, switch to the camera app or use a QR code scanner to scan the displayed QR code.",es:"En este dispositivo, cambia a la aplicación de cámara o usa un lector de QR para escanear el código mostrado.",ko:"이 기기에서 카메라 앱으로 전환하거나 QR 코드 스캐너를 사용해 화면에 표시된 QR 코드를 스캔합니다.","zh-tw":"在這台裝置上切換到相機 App,或使用 QR 碼掃描器掃描顯示出的 QR 碼。"},Open:{def:"Open",es:"Abrir",ja:"開く",ko:"열기",ru:"Открыть",zh:"打开","zh-tw":"開啟"},"Open connection":{def:"Open connection",es:"Abrir conexión",ko:"연결 열기","zh-tw":"開啟連線"},"Open P2P Setup...":{def:"Open P2P Setup...",es:"Abrir la configuración P2P...",ko:"P2P 설정 열기...","zh-tw":"開啟 P2P 設定⋯"},"Open the dialog":{def:"Open the dialog",es:"Abrir el diálogo",ja:"ダイアログを開く",ko:"대화상자 열기",ru:"Открыть диалог",zh:"打开对话框","zh-tw":"開啟對話框"},"Other files":{def:"Other files",es:"Otros archivos",ko:"기타 파일","zh-tw":"其他檔案"},Overwrite:{def:"Overwrite",es:"Sobrescribir",ja:"上書き",ko:"덮어쓰기",ru:"Перезаписать",zh:"覆盖","zh-tw":"覆寫"},"Overwrite patterns":{def:"Overwrite patterns",es:"Patrones de sobrescritura",ja:"上書きパターン",ko:"덮어쓰기 패턴",ru:"Шаблоны перезаписи",zh:"覆盖模式","zh-tw":"覆寫模式"},"Overwrite remote":{def:"Overwrite remote",es:"Sobrescribir remoto",ja:"リモートを上書き",ko:"원격 덮어쓰기",ru:"Перезаписать удалённое хранилище",zh:"覆盖远端","zh-tw":"覆寫遠端"},"Overwrite remote with local DB and passphrase.":{def:"Overwrite remote with local DB and passphrase.",es:"Sobrescribe el remoto con la base de datos local y la frase de contraseña.",ja:"ローカル DB とパスフレーズでリモートを上書きします。",ko:"로컬 DB와 패스프레이즈로 원격을 덮어씁니다.",ru:"Перезаписать удалённое хранилище локальной БД и парольной фразой.",zh:"使用本地数据库和密码短语覆盖远端。","zh-tw":"使用本機資料庫與密語覆寫遠端。"},"Overwrite Server Data with This Device's Files":{def:"Overwrite Server Data with This Device's Files",es:"Sobrescribir los datos del servidor con los archivos de este dispositivo",ja:"このデバイスのファイルでサーバーデータを上書き",ko:"이 기기의 파일로 서버 데이터를 덮어쓰기",ru:"Перезаписать данные сервера файлами с этого устройства",zh:"用本设备文件覆盖服务器数据","zh-tw":"以此裝置的檔案覆寫伺服器資料"},"P2P Configuration":{def:"P2P Configuration",es:"Configuración P2P",ko:"P2P 구성","zh-tw":"P2P 設定"},"P2P Status":{def:"P2P Status",es:"Estado P2P",ko:"P2P 상태","zh-tw":"P2P 狀態"},"P2P.AskPassphraseForDecrypt":{def:"The remote peer shared the configuration. Please input the passphrase to decrypt the configuration.",es:"El par remoto ha compartido la configuración. Introduce la frase de contraseña para descifrarla.",fr:"Le pair distant a partagé la configuration. Veuillez saisir la phrase secrète pour déchiffrer la configuration.",he:"העמית המרוחד שיתף את התצורה. אנא הזן את ביטוי הסיסמה לפענוח התצורה.",ja:"リモートピアから設定が共有されました。設定を復号するためのパスフレーズを入力してください。",ko:"원격 피어가 구성을 공유했습니다. 구성을 복호화하려면 패스프레이즈를 입력해 주세요.",ru:"Удалённое устройство предоставило конфигурацию. Введите пароль для расшифровки.",zh:"远程对等方共享了配置,请输入密码短语以解密配置","zh-tw":"遠端 Peer 已分享設定。請輸入密語以解密該設定。"},"P2P.AskPassphraseForShare":{def:"The remote peer requested this device configuration. Please input the passphrase to share the configuration. You can ignore the request by cancelling this dialogue.",es:"El par remoto ha solicitado la configuración de este dispositivo. Introduce la frase de contraseña para compartirla. Puedes ignorar la solicitud cancelando este diálogo.",fr:"Le pair distant a demandé la configuration de cet appareil. Veuillez saisir la phrase secrète pour partager la configuration. Vous pouvez ignorer la demande en annulant cette boîte de dialogue.",he:"העמית המרוחד ביקש את תצורת מכשיר זה. אנא הזן את ביטוי הסיסמה לשיתוף התצורה. ניתן להתעלם מהבקשה על ידי ביטול הדיאלוג.",ja:"リモートピアからこのデバイスの設定が要求されました。設定を共有するためのパスフレーズを入力してください。このダイアログをキャンセルすることでリクエストを無視できます。",ko:"원격 피어가 이 기기의 구성을 요청했습니다. 구성을 공유하려면 패스프레이즈를 입력해 주세요. 이 대화상자를 취소하여 요청을 무시할 수 있습니다.",ru:"Удалённое устройство запрашивает эту конфигурацию. Введите пароль для передачи.",zh:"远程对等方请求此设备配置,请输入密码短语以共享配置。你可以通过取消此对话框来忽略此请求","zh-tw":"遠端 Peer 請求取得此裝置的設定。請輸入密語以分享設定。你可以取消此對話框以忽略該請求。"},"P2P.DisabledButNeed":{def:"Peer-to-Peer Sync is disabled. Do you really want to enable it?",es:"Sincronización punto a punto está desactivada. ¿Seguro que quieres activarla?",fr:"Synchronisation pair-à-pair est désactivé. Voulez-vous vraiment l'activer ?",he:"%{title_p2p_sync} מנוטרל. האם אתה בטוח שברצונך להפעיל?",ja:"Peer-to-Peer Syncは無効になっています。本当に有効にしますか?",ko:"피어 투 피어(P2P) 동기화가 비활성화되어 있습니다. 정말로 활성화하시겠습니까?",ru:"title_p2p_sync отключён. Вы действительно хотите включить?",zh:"Peer-to-Peer同步 已禁用。你确定要启用它吗?","zh-tw":"Peer-to-Peer 同步目前已停用。你確定要啟用它嗎?"},"P2P.FailedToOpen":{def:"Failed to open P2P connection to the signalling server.",es:"No se pudo abrir la conexión P2P con el servidor de señalización.",fr:"Échec d'ouverture de la connexion P2P vers le serveur de signalisation.",he:"לא ניתן לפתוח חיבור P2P לשרת האותות.",ja:"シグナリングサーバーへのP2P接続を開けませんでした。",ko:"시그널링 서버에 P2P 연결을 열 수 없습니다.",ru:"Не удалось открыть P2P подключение к серверу сигнализации.",zh:"无法打开 P2P 连接到信令服务器","zh-tw":"無法開啟與訊號伺服器的 P2P 連線。"},"P2P.NoAutoSyncPeers":{def:"No auto-sync peers found. Please set peers on the Peer-to-Peer Sync pane.",es:"No se han encontrado pares de sincronización automática. Configúralos en el panel de Sincronización punto a punto.",fr:"Aucun pair de synchronisation automatique trouvé. Veuillez définir des pairs dans le panneau Synchronisation pair-à-pair.",he:"לא נמצאו עמיתים לסנכרון אוטומטי. אנא הגדר עמיתים בלוח %{long_p2p_sync}.",ja:"自動同期ピアが見つかりません。Peer-to-Peer Sync (試験機能)ペインでピアを設定してください。",ko:"자동 동기화 피어를 찾을 수 없습니다. 피어 투 피어(P2P) 동기화 (실험 기능) 창에서 피어를 설정해 주세요.",ru:"Автосинхронизируемые устройства не найдены.",zh:"未找到自动同步的对等方,请在 Peer-to-Peer同步 (实验性) 面板中设置对等方","zh-tw":"找不到自動同步的 Peer。請到「Peer-to-Peer 同步」面板設定 Peer。"},"P2P.NoKnownPeers":{def:"No peers has been detected, waiting incoming other peers...",es:"No se ha detectado ningún par; esperando a que se conecten otros...",fr:"Aucun pair détecté, en attente d'autres pairs entrants...",he:"לא זוהו עמיתים, ממתין לעמיתים נכנסים...",ja:"ピアが検出されていません。他のピアからの接続を待機中...",ko:"피어가 감지되지 않았습니다. 다른 피어의 접속을 기다리고 있습니다...",ru:"Устройства не обнаружены, ожидаем другие устройства...",zh:"未检测到对等方,正在等待其他对等方的连接...","zh-tw":"尚未偵測到任何 Peer,正在等待其他 Peer 連入⋯"},"P2P.Note.description":{def:" This replicator allows us to synchronise our vault with other devices\nusing a peer-to-peer connection. We can use this to synchronise our vault with our other devices without using a cloud service.\nThis replicator is based on Trystero. It also uses a signalling server to establish a connection between devices. The signalling server is used to exchange connection information between devices. It does (or,should) not know or store any of our data.\n\nThe signalling server can be hosted by anyone. This is just a Nostr relay. For the sake of simplicity and checking the behaviour of the replicator, an instance of the signalling server is hosted by vrtmrz. You can use the experimental server provided by vrtmrz, or you can use any other server.\n\nBy the way, even if the signalling server does not store our data, it can see the connection information of some of our devices. Please be aware of this. Also, be cautious when using the server provided by someone else.",es:" Este replicador permite sincronizar el vault con otros dispositivos\nmediante una conexión punto a punto. Así se puede sincronizar con nuestros otros dispositivos sin usar un servicio en la nube.\nEl replicador se basa en Trystero. Usa además un servidor de señalización para establecer la conexión entre dispositivos. Ese servidor sirve para intercambiar la información de conexión y no conoce (ni debería almacenar) ninguno de nuestros datos.\n\nCualquiera puede alojar el servidor de señalización: es simplemente un relé Nostr. Por comodidad y para poder comprobar el comportamiento del replicador, vrtmrz aloja una instancia. Puedes usar ese servidor experimental o cualquier otro.\n\nPor cierto, aunque el servidor de señalización no almacene nuestros datos, sí puede ver la información de conexión de algunos de nuestros dispositivos. Tenlo en cuenta y ten precaución al usar un servidor de terceros.",fr:" Ce réplicateur permet de synchroniser notre coffre avec d'autres\nappareils via une connexion pair-à-pair. Nous pouvons l'utiliser pour synchroniser notre coffre avec nos autres appareils sans recourir à un service cloud.\nCe réplicateur est basé sur Trystero. Il utilise également un serveur de signalisation pour établir une connexion entre les appareils. Le serveur de signalisation sert à échanger les informations de connexion entre appareils. Il ne connaît (ou ne devrait connaître) ni ne stocke aucune de nos données.\n\nLe serveur de signalisation peut être hébergé par n'importe qui. Il s'agit simplement d'un relais Nostr. Par souci de simplicité et pour vérifier le comportement du réplicateur, une instance du serveur de signalisation est hébergée par vrtmrz. Vous pouvez utiliser le serveur expérimental fourni par vrtmrz, ou tout autre serveur.\n\nAu passage, même si le serveur de signalisation ne stocke pas nos données, il peut voir les informations de connexion de certains de nos appareils. Soyez-en conscient. Soyez également prudent avec un serveur fourni par quelqu'un d'autre.",he:" רפליקטור זה מאפשר לסנכרן את הכספת עם מכשירים אחרים באמצעות חיבור עמית-לעמית.\nניתן להשתמש בזה לסנכרון הכספת עם מכשירים אחרים ללא שירות ענן.\nרפליקטור זה מבוסס על Trystero. הוא משתמש גם בשרת אותות לביסוס חיבור בין מכשירים. שרת האותות משמש להחלפת מידע חיבור בין מכשירים. הוא אינו (ולא אמור) לדעת או לאחסן את הנתונים שלנו.\n\nשרת האותות יכול להיות מאוחסן על ידי כל אחד. זהו ממסר Nostr בלבד. לצורך פשטות ובדיקת התנהגות הרפליקטור, vrtmrz מאחסן עותק של שרת האותות. ניתן להשתמש בשרת הניסיוני של vrtmrz, או בכל שרת אחר.\n\nאגב, גם אם שרת האותות אינו מאחסן נתונים, הוא יכול לראות מידע חיבור של חלק ממכשיריך. אנא שים לב לכך. כמו כן, היה זהיר בשימוש בשרת של מישהו אחר.",ja:"このレプリケーターは、ピアツーピア接続を使用して、Vaultを他のデバイスと同期することができます。クラウドサービスを使用せずに、他のデバイスとVaultを同期することができます。\nこのレプリケーターはTrysteroをベースにしています。デバイス間の接続を確立するためにシグナリングサーバーを使用します。シグナリングサーバーはデバイス間で接続情報を交換するために使用されます。私たちのデータを知ったり保存したりすることはありません(または、そうあるべきではありません)。\n\nシグナリングサーバーは誰でもホストできます。これは単なるNostrリレーです。簡便さとレプリケーターの動作確認のために、vrtmrzがシグナリングサーバーのインスタンスをホストしています。vrtmrzが提供する実験用サーバーを使用することも、他のサーバーを使用することもできます。\n\nなお、シグナリングサーバーが私たちのデータを保存しなくても、一部のデバイスの接続情報を見ることができます。これにご注意ください。また、他の人が提供するサーバーを使用する場合は注意してください。",ko:" 이 복제기는 피어 투 피어 연결을 이용해 다른 기기와 보관함을 동기화할 수 있게 해 줍니다.\n클라우드 서비스를 사용하지 않고도 다른 기기와 보관함을 동기화할 수 있습니다.\n이 복제기는 Trystero를 기반으로 합니다. 기기 간 연결을 맺기 위해 시그널링 서버도 사용합니다. 시그널링 서버는 기기 사이의 연결 정보를 교환하는 데 쓰이며, 사용자의 데이터는 알지도 저장하지도 않습니다(또는 그래야 합니다).\n\n시그널링 서버는 누구나 운영할 수 있습니다. 단순한 Nostr 릴레이일 뿐입니다. 편의를 위해, 그리고 복제기의 동작을 확인할 수 있도록 vrtmrz가 시그널링 서버 인스턴스를 하나 운영하고 있습니다. vrtmrz가 제공하는 실험용 서버를 사용해도 되고, 다른 서버를 사용해도 됩니다.\n\n참고로, 시그널링 서버가 데이터를 저장하지 않더라도 일부 기기의 연결 정보는 볼 수 있습니다. 이 점을 유의해 주세요. 또한 다른 사람이 제공하는 서버를 사용할 때는 주의하시기 바랍니다.",ru:"Этот репликатор позволяет синхронизировать хранилище с другими устройствами с использованием однорангового соединения.",zh:" This replicator allows us to synchronise our vault with other devices\nusing a peer-to-peer connection. We can use this to synchronise our vault with our other devices without using a cloud service.\nThis replicator is based on Trystero. It also uses a signaling server to establish a connection between devices. The signaling server is used to exchange connection information between devices. It does (or,should) not know or store any of our data.\n\nThe signaling server can be hosted by anyone. This is just a Nostr relay. For the sake of simplicity and checking the behaviour of the replicator, an instance of the signaling server is hosted by vrtmrz. You can use the experimental server provided by vrtmrz, or you can use any other server.\n\nBy the way, even if the signaling server does not store our data, it can see the connection information of some of our devices. Please be aware of this. Also, be cautious when using the server provided by someone else.","zh-tw":"這個複寫器讓我們能透過 Peer-to-Peer 連線,將 Vault 與其他裝置同步,\n不需要透過雲端服務就能與其他裝置同步 Vault。\n此複寫器以 Trystero 為基礎,同樣需要透過訊號伺服器建立裝置之間的連線。訊號伺服器僅用於在裝置間交換連線資訊,它不會(也不應該)得知或儲存我們的任何資料。\n\n訊號伺服器可以由任何人架設,本質上只是一個 Nostr 中繼站。為了簡化操作並驗證複寫器的行為,vrtmrz 提供了一個訊號伺服器的執行實例。你可以使用 vrtmrz 提供的這個實驗性伺服器,也可以使用任何其他伺服器。\n\n另外,即使訊號伺服器不會儲存我們的資料,它仍能看到部分裝置的連線資訊,請留意這點。若使用他人提供的伺服器,也請格外謹慎。"},"P2P.Note.important_note":{def:"Peer-to-Peer Replicator.",es:"Replicador punto a punto.",fr:"Réplicateur pair-à-pair.",he:"רפליקטור עמית-לעמית.",ja:"ピアツーピアレプリケーターの実験的実装",ko:"피어 투 피어 복제기입니다.",ru:"P2P репликатор.",zh:"The Experimental Implementation of the Peer-to-Peer Replicator.","zh-tw":"Peer-to-Peer 複寫器。"},"P2P.Note.important_note_sub":{def:"This feature is still on the bleeding edge. Please be aware that ensure your data is backed up before using this feature. And, we would be so happy if you could contribute to the development of this feature.",es:"Esta función sigue siendo muy experimental. Asegúrate de tener una copia de seguridad de tus datos antes de usarla. Y nos alegraría mucho que quisieras contribuir a su desarrollo.",fr:"Cette fonctionnalité est encore en tout début de développement. Veillez à sauvegarder vos données avant de l'utiliser. Nous serions très heureux si vous contribuiez au développement de cette fonctionnalité.",he:"תכונה זו עדיין בשלב מתקדם. ודא שהנתונים שלך מגובים לפני השימוש. ונשמח אם תוכל לתרום לפיתוח תכונה זו.",ja:"この機能はまだ実験段階です。期待通りに動作しない可能性があることにご注意ください。さらに、バグ、セキュリティの問題、その他の問題がある可能性があります。この機能は自己責任でご使用ください。この機能の開発にご協力ください。",ko:"이 기능은 아직 실험 단계입니다. 사용하기 전에 반드시 데이터를 백업해 주세요. 그리고 이 기능의 개발에 기여해 주신다면 매우 감사하겠습니다.",ru:"Эта функция всё ещё на стадии разработки. Пожалуйста, убедитесь, что ваши данные зарезервированы.",zh:"This feature is still in the experimental stage. Please be aware that this feature may not work as expected. Furthermore, it may have some bugs, security issues, and other issues. Please use this feature at your own risk. Please contribute to the development of this feature.","zh-tw":"此功能仍處於最前沿的實驗階段。使用前請務必確保資料已備份。如果你願意協助開發這項功能,我們會非常感激。"},"P2P.Note.Summary":{def:"What is this feature? (and some important notes, please read once)",es:"¿Qué es esta función? (incluye notas importantes; léelas al menos una vez)",fr:"Qu'est-ce que cette fonctionnalité ? (et quelques notes importantes, à lire)",he:"מהי תכונה זו? (ועוד הערות חשובות, נא לקרוא פעם אחת)",ja:"この機能について(重要な注意事項を含む、一度お読みください)",ko:"이 기능은 무엇인가요? (설명과 참고사항이 적혀있습니다. 한 번 읽어보세요!)",ru:"Что это за функция? (важные замечания)",zh:"What is this feature? (and some important notes, please read once)","zh-tw":"這是什麼功能?(有些重要事項,請務必先閱讀一次)"},"P2P.NotEnabled":{def:"Peer-to-Peer Sync is not enabled. We cannot open a new connection.",es:"Sincronización punto a punto no está activada. No se puede abrir una conexión nueva.",fr:"Synchronisation pair-à-pair n'est pas activé. Nous ne pouvons pas ouvrir de nouvelle connexion.",he:"%{title_p2p_sync} אינו מופעל. לא ניתן לפתוח חיבור חדש.",ja:"Peer-to-Peer Syncが有効になっていません。新しい接続を開くことができません。",ko:"피어 투 피어(P2P) 동기화가 활성화되지 않았습니다. 새로운 연결을 열 수 없습니다.",ru:"title_p2p_sync не включён. Мы не можем открыть новое подключение.",zh:"Peer-to-Peer同步 is not enabled. We cannot open a new connection.","zh-tw":"Peer-to-Peer 同步尚未啟用,無法開啟新連線。"},"P2P.P2PReplication":{def:"Peer-to-Peer Replication",es:"Replicación par a par",fr:"Réplication Pair-à-Pair",he:"שכפול %{P2P}",ja:"Peer-to-Peerレプリケーション(複製)",ko:"피어-to-피어 복제",ru:"P2P Репликация",zh:"Peer-to-Peer Replication","zh-tw":"Peer-to-Peer 複寫"},"P2P.PaneTitle":{def:"Peer-to-Peer Sync",es:"Sincronización punto a punto",fr:"Synchronisation pair-à-pair",he:"%{long_p2p_sync}",ja:"Peer-to-Peer Sync (試験機能)",ko:"피어 투 피어(P2P) 동기화 (실험 기능)",ru:"long_p2p_sync",zh:"Peer-to-Peer同步 (实验性)","zh-tw":"Peer-to-Peer 同步"},"P2P.ReplicatorInstanceMissing":{def:"P2P Sync replicator is not found, possibly not have been configured or enabled.",es:"No se encuentra el replicador de sincronización P2P; puede que no esté configurado o activado.",fr:"Le réplicateur Sync P2P est introuvable, peut-être non configuré ou non activé.",he:"רפליקטור סנכרון P2P לא נמצא, ייתכן שלא הוגדר או הופעל.",ja:"P2P同期レプリケーターが見つかりません。設定または有効化されていない可能性があります。",ko:"P2P 동기화 복제기를 찾을 수 없습니다. 구성되지 않았거나 활성화되지 않았을 수 있습니다.",ru:"P2P Sync репликатор не найден, возможно, не настроен.",zh:"P2P Sync replicator is not found, possibly not have been configured or enabled.","zh-tw":"找不到 P2P 同步複寫器,可能尚未設定或啟用。"},"P2P.SeemsOffline":{def:"Peer ${name} seems offline, skipped.",es:"El par ${name} parece estar desconectado; se omite.",fr:"Le pair ${name} semble hors ligne, ignoré.",he:"העמית ${name} נראה לא מחובר, מדלג.",ja:"ピア${name}はオフラインのようです。スキップしました。",ko:"피어 ${name}이(가) 오프라인인 것 같습니다. 건너뜁니다.",ru:"Устройство name офлайн, пропущено.",zh:"Peer ${name} seems offline, skipped.","zh-tw":"Peer ${name} 似乎已離線,已略過。"},"P2P.SyncAlreadyRunning":{def:"P2P Sync is already running.",es:"La sincronización P2P ya está en marcha.",fr:"La Sync P2P est déjà en cours.",he:"סנכרון P2P כבר פועל.",ja:"P2P同期はすでに実行中です。",ko:"P2P 동기화가 이미 실행 중입니다.",ru:"P2P Sync уже запущен.",zh:"P2P Sync is already running.","zh-tw":"P2P 同步已在執行中。"},"P2P.SyncCompleted":{def:"P2P Sync completed.",es:"Sincronización P2P completada.",fr:"Sync P2P terminée.",he:"סנכרון P2P הושלם.",ja:"P2P同期が完了しました。",ko:"P2P 동기화가 완료되었습니다.",ru:"P2P Sync завершён.",zh:"P2P Sync completed.","zh-tw":"P2P 同步已完成。"},"P2P.SyncStartedWith":{def:"P2P Sync with ${name} have been started.",es:"Se ha iniciado la sincronización P2P con ${name}.",fr:"La Sync P2P avec ${name} a démarré.",he:"סנכרון P2P עם ${name} התחיל.",ja:"${name}とのP2P同期を開始しました。",ko:"${name}과의 P2P 동기화가 시작되었습니다.",ru:"P2P Sync с name начат.",zh:"P2P Sync with ${name} have been started.","zh-tw":"已開始與 ${name} 的 P2P 同步。"},"paneMaintenance.markDeviceResolvedAfterBackup":{def:"paneMaintenance.markDeviceResolvedAfterBackup",es:"Marcar el dispositivo como resuelto después de hacer una copia de seguridad",ja:"バックアップ後にこのデバイスを解決済みにする",ko:"백업 후 이 기기를 해결됨으로 표시",ru:"Пометить устройство как обработанное после резервного копирования",zh:"请在完成备份后将此设备标记为已处理。","zh-tw":"請在完成備份後將此裝置標記為已處理。"},"paneMaintenance.remoteLockedAndDeviceNotAccepted":{def:"paneMaintenance.remoteLockedAndDeviceNotAccepted",es:"La base de datos remota está bloqueada y este dispositivo aún no ha sido aceptado.",ja:"リモートデータベースはロックされており、このデバイスはまだ承認されていません。",ko:"원격 데이터베이스가 잠겨 있으며 이 기기는 아직 승인되지 않았습니다.",ru:"Удалённая база данных заблокирована, и это устройство ещё не одобрено.",zh:"远端数据库已锁定,且此设备尚未被接受。","zh-tw":"遠端資料庫已鎖定,且此裝置尚未被接受。"},"paneMaintenance.remoteLockedResolvedDevice":{def:"paneMaintenance.remoteLockedResolvedDevice",es:"La base de datos remota está bloqueada, pero este dispositivo ya fue aceptado.",ja:"リモートデータベースはロックされていますが、このデバイスはすでに承認されています。",ko:"원격 데이터베이스가 잠겨 있지만 이 기기는 이미 승인되었습니다.",ru:"Удалённая база данных заблокирована, но это устройство уже одобрено.",zh:"远端数据库已锁定,但此设备已被接受。","zh-tw":"遠端資料庫已鎖定,但此裝置已被接受。"},"paneMaintenance.unlockDatabaseReady":{def:"paneMaintenance.unlockDatabaseReady",es:"Desbloquear la base de datos",ja:"データベースのロックを解除",ko:"데이터베이스 잠금 해제",ru:"Разблокировать базу данных",zh:"现在可以解锁数据库。","zh-tw":"現在可以解鎖資料庫。"},Passphrase:{def:"Passphrase",es:"Frase de contraseña",fr:"Phrase secrète",he:"ביטוי סיסמה",ja:"パスフレーズ",ko:"패스프레이즈",ru:"Парольная фраза",zh:"密码","zh-tw":"密語"},"Passphrase is required.":{def:"Passphrase is required.",es:"Se requiere la frase de contraseña.",ko:"패스프레이즈가 필요합니다.","zh-tw":"必須輸入密語。"},"Passphrase of sensitive configuration items":{def:"Passphrase of sensitive configuration items",es:"Frase para elementos sensibles",fr:"Phrase secrète des éléments de configuration sensibles",he:"ביטוי סיסמה לפריטי תצורה רגישים",ja:"機密性の高い設定項目にパスフレーズを使用",ko:"민감한 구성 항목의 패스프레이즈",ru:"Парольная фраза для конфиденциальных настроек",zh:"敏感配置项的密码","zh-tw":"敏感設定項目的密語"},password:{def:"password",es:"contraseña",fr:"mot de passe",he:"סיסמה",ja:"パスワード",ko:"비밀번호",ru:"пароль",zh:"密码","zh-tw":"密碼"},Password:{def:"Password",es:"Contraseña",fr:"Mot de passe",he:"סיסמה",ja:"パスワード",ko:"비밀번호",ru:"Пароль",zh:"密码","zh-tw":"密碼"},"Paste a connection string":{def:"Paste a connection string",es:"Pegar cadena de conexión",ja:"接続文字列を貼り付ける",ko:"연결 문자열 붙여넣기",ru:"Вставить строку подключения",zh:"粘贴连接字符串","zh-tw":"貼上連線字串"},"Paste the Setup URI generated from one of your active devices.":{def:"Paste the Setup URI generated from one of your active devices.",es:"Pegue el URI de configuración generado desde uno de sus dispositivos activos。",ja:"稼働中の端末で生成した Setup URI を貼り付けてください。",ko:"사용 중인 기기 중 하나에서 생성한 Setup URI를 붙여 넣으세요.",ru:"Вставьте Setup URI, созданный на одном из ваших активных устройств。",zh:"粘贴从一台已在使用的设备上生成的 Setup URI。","zh-tw":"貼上從一台已在使用裝置上產生的 Setup URI。"},Path:{def:"Path",es:"Ruta",ko:"경로","zh-tw":"路徑"},"Path Obfuscation":{def:"Path Obfuscation",es:"Ofuscación de rutas",fr:"Obfuscation des chemins",he:"ערפול נתיב",ja:"パスの難読化",ko:"경로 난독화",ru:"Обфускация путей",zh:"路径混淆","zh-tw":"路徑混淆"},"Patterns to match files for overwriting instead of merging":{def:"Patterns to match files for overwriting instead of merging",es:"Patrones para identificar archivos que se sobrescribirán en lugar de fusionarse",ja:"マージではなく上書きするファイルを判定するパターン",ko:"병합 대신 덮어쓸 파일을 판별하는 패턴",ru:"Шаблоны для файлов, которые нужно перезаписывать вместо объединения",zh:"用于匹配需覆盖而非合并文件的模式","zh-tw":"用於匹配需覆寫而非合併檔案的模式"},"Patterns to match files for syncing":{def:"Patterns to match files for syncing",es:"Patrones para identificar archivos que se sincronizarán",ja:"同期対象ファイルを判定するパターン",ko:"동기화할 파일을 판별하는 패턴",ru:"Шаблоны для файлов, которые нужно синхронизировать",zh:"用于匹配同步文件的模式","zh-tw":"用於匹配同步檔案的模式"},"Peer ID:":{def:"Peer ID:",es:"ID de par:",ko:"피어 ID:","zh-tw":"Peer ID"},"Peer to Peer Replicator":{def:"Peer to Peer Replicator",es:"Replicador Punto a Punto",ko:"Peer to Peer 복제기","zh-tw":"Peer to Peer 複寫器"},"Peer-to-Peer only":{def:"Peer-to-Peer only",es:"Solo Peer-to-Peer",ja:"Peer-to-Peer のみ",ko:"Peer-to-Peer 전용",ru:"Только Peer-to-Peer",zh:"仅 Peer-to-Peer","zh-tw":"僅 Peer-to-Peer"},"Peer-to-Peer Synchronisation":{def:"Peer-to-Peer Synchronisation",es:"Sincronización entre pares",ja:"ピアツーピア同期",ko:"피어 투 피어(P2P) 동기화",ru:"Одноранговая синхронизация",zh:"点对点同步","zh-tw":"Peer-to-Peer 同步"},Peers:{def:"Peers",es:"Pares",ko:"피어","zh-tw":"Peer"},"Per-file-saved customization sync":{def:"Per-file-saved customization sync",es:"Sincronización de personalización por archivo",fr:"Synchronisation de personnalisation enregistrée par fichier",he:"סנכרון התאמה אישית שנשמר לפי קובץ",ja:"ファイルごとのカスタマイズ同期",ko:"파일별 저장 사용자 설정 동기화",ru:"Синхронизация настроек для каждого файла",zh:"按文件保存的自定义同步","zh-tw":"以每個檔案儲存的自訂同步"},Perform:{def:"Perform",es:"Ejecutar",ja:"実行",ko:"실행",ru:"Выполнить",zh:"执行","zh-tw":"執行"},"Perform cleanup":{def:"Perform cleanup",es:"Ejecutar limpieza",ja:"クリーンアップを実行",ko:"정리 실행",ru:"Выполнить очистку",zh:"执行清理","zh-tw":"執行清理"},"Perform Garbage Collection":{def:"Perform Garbage Collection",es:"Ejecutar recolección de basura",ja:"ガーベジコレクションを実行",ko:"가비지 컬렉션 실행",ru:"Выполнить сборку мусора",zh:"执行垃圾回收","zh-tw":"執行垃圾回收"},"Perform Garbage Collection to remove unused chunks and reduce database size.":{def:"Perform Garbage Collection to remove unused chunks and reduce database size.",es:"Ejecuta la recolección de basura para eliminar chunks no usados y reducir el tamaño de la base de datos.",ja:"未使用のチャンクを削除し、データベースサイズを削減するためにガーベジコレクションを実行します。",ko:"사용하지 않는 청크를 제거하고 데이터베이스 크기를 줄이기 위해 가비지 컬렉션을 실행합니다.",ru:"Выполняет сборку мусора, чтобы удалить неиспользуемые чанки и уменьшить размер базы данных.",zh:"执行垃圾回收以清理未使用的 chunks 并减小数据库体积。","zh-tw":"執行垃圾回收以移除未使用的 chunks 並減少資料庫大小。"},"Periodic Sync interval":{def:"Periodic Sync interval",es:"Intervalo de sincronización periódica",fr:"Intervalle de synchronisation périodique",he:"מרווח סנכרון תקופתי",ja:"定時同期の感覚",ko:"주기적 동기화 간격",ru:"Интервал периодической синхронизации",zh:"定期同步间隔","zh-tw":"定期同步間隔"},PERMANENT:{def:"PERMANENT",es:"PERMANENTE",ko:"영구","zh-tw":"永久"},"Pick a file to resolve conflict":{def:"Pick a file to resolve conflict",es:"Elegir un archivo para resolver el conflicto",ja:"競合を解決するファイルを選択",ko:"충돌을 해결할 파일 선택",ru:"Выбрать файл для разрешения конфликта",zh:"选择要解决冲突的文件","zh-tw":"選擇要解決衝突的檔案"},"Pick a file to show history":{def:"Pick a file to show history",es:"Elige un archivo para ver su historial",ko:"기록을 표시할 파일 선택","zh-tw":"選擇要顯示歷程的檔案"},"Please be aware that the End-to-End Encryption passphrase is not validated until the synchronisation process actually commences. This is a security measure designed to protect your data.":{def:"Please be aware that the End-to-End Encryption passphrase is not validated until the synchronisation process actually commences. This is a security measure designed to protect your data.",es:"Ten en cuenta que la frase de contraseña del cifrado de extremo a extremo no se valida hasta que comienza realmente la sincronización. Es una medida de seguridad para proteger tus datos.",ko:"종단 간 암호화 패스프레이즈는 동기화가 실제로 시작되기 전까지 검증되지 않는다는 점에 유의해 주세요. 이는 데이터를 보호하기 위한 보안 조치입니다.","zh-tw":"請注意,端對端加密的密語要到同步程序實際開始時才會進行驗證。這是為了保護你資料而設計的安全措施。"},"Please configure your end-to-end encryption settings.":{def:"Please configure your end-to-end encryption settings.",es:"Configura los ajustes de cifrado de extremo a extremo.",ko:"종단 간 암호화 설정을 구성해 주세요.","zh-tw":"請設定你的端對端加密選項。"},"Please disable 'Read chunks online' in settings to use Garbage Collection.":{def:"Please disable 'Read chunks online' in settings to use Garbage Collection.",es:"Desactiva «Leer chunks en línea» en los ajustes para poder usar la recolección de basura.",ja:"Garbage Collection を使うには、設定で「Read chunks online」を無効にしてください。",ko:"가비지 컬렉션을 사용하려면 설정에서 'Read chunks online'을 비활성화해 주세요.",ru:"Чтобы использовать Garbage Collection, отключите в настройках «Read chunks online».",zh:"要使用垃圾回收,请在设置中禁用“Read chunks online”。","zh-tw":"若要使用垃圾回收,請在設定中停用「Read chunks online」。"},"Please enable 'Compute revisions for chunks' in settings to use Garbage Collection.":{def:"Please enable 'Compute revisions for chunks' in settings to use Garbage Collection.",es:"Activa «Calcular revisiones para los chunks» en los ajustes para poder usar la recolección de basura.",ja:"Garbage Collection を使うには、設定で「Compute revisions for chunks」を有効にしてください。",ko:"가비지 컬렉션을 사용하려면 설정에서 'Compute revisions for chunks'를 활성화해 주세요.",ru:"Чтобы использовать Garbage Collection, включите в настройках «Compute revisions for chunks».",zh:"要使用垃圾回收,请在设置中启用“Compute revisions for chunks”。","zh-tw":"若要使用垃圾回收,請在設定中啟用「Compute revisions for chunks」。"},"Please enter the CouchDB server information below.":{def:"Please enter the CouchDB server information below.",es:"Introduce a continuación los datos del servidor CouchDB.",ko:"아래에 CouchDB 서버 정보를 입력해 주세요.","zh-tw":"請在下方輸入 CouchDB 伺服器資訊。"},"Please enter the details required to connect to your S3/MinIO/R2 compatible object storage service.":{def:"Please enter the details required to connect to your S3/MinIO/R2 compatible object storage service.",es:"Introduce los datos necesarios para conectarte a tu servicio de almacenamiento de objetos compatible con S3/MinIO/R2.",ko:"S3/MinIO/R2 호환 오브젝트 스토리지 서비스에 연결하는 데 필요한 정보를 입력해 주세요.","zh-tw":"請輸入連線到你的 S3/MinIO/R2 相容物件儲存服務所需的詳細資訊。"},"Please enter the Peer-to-Peer Synchronisation information below.":{def:"Please enter the Peer-to-Peer Synchronisation information below.",es:"Introduce a continuación los datos de la sincronización punto a punto.",ko:"아래에 Peer-to-Peer 동기화 정보를 입력해 주세요.","zh-tw":"請在下方輸入 Peer-to-Peer 同步資訊。"},"Please enter the Setup URI that was generated during server installation or on another device, along with the vault passphrase.":{def:"Please enter the Setup URI that was generated during server installation or on another device, along with the vault passphrase.",es:"Introduce el Setup URI generado durante la instalación del servidor o en otro dispositivo, junto con la frase de contraseña del vault.",ko:"서버 설치 과정이나 다른 기기에서 생성된 Setup URI를 보관함 패스프레이즈와 함께 입력해 주세요.","zh-tw":"請輸入在伺服器安裝期間或其他裝置上產生的 Setup URI,以及 Vault 的密語。"},"Please follow the steps below to import settings from your existing device.":{def:"Please follow the steps below to import settings from your existing device.",es:"Sigue los pasos siguientes para importar los ajustes desde tu dispositivo actual.",ko:"기존 기기에서 설정을 가져오려면 아래 단계를 따라 주세요.","zh-tw":"請依照以下步驟,從現有裝置匯入設定。"},"PLEASE NOTE":{def:"PLEASE NOTE",es:"TEN EN CUENTA",ko:"유의 사항","zh-tw":"請注意"},"Please select 'Cancel' explicitly to cancel this operation.":{def:"Please select 'Cancel' explicitly to cancel this operation.",es:"Selecciona «Cancelar» de forma explícita para cancelar esta operación.",ja:"この操作を中止するには、明示的に「キャンセル」を選択してください。",ko:'이 작업을 취소하려면 반드시 "취소"를 명시적으로 선택해 주세요.',ru:"Чтобы отменить эту операцию, явно выберите «Отмена».",zh:"如需取消此操作,请明确选择“取消”。","zh-tw":"若要取消此操作,請明確選擇「取消」。"},"Please select a method to import the settings from another device.":{def:"Please select a method to import the settings from another device.",es:"Seleccione un método para importar la configuración desde otro dispositivo。",ja:"別の端末から設定を取り込む方法を選択してください。",ko:"다른 기기에서 설정을 가져올 방법을 선택해 주세요.",ru:"Выберите способ импорта настроек с другого устройства。",zh:"请选择一种从其他设备导入设置的方法。","zh-tw":"請選擇一種從其他裝置匯入設定的方法。"},"Please select an active P2P remote configuration to change P2P sync targets.":{def:"Please select an active P2P remote configuration to change P2P sync targets.",es:"Selecciona una configuración remota P2P activa para cambiar los destinos de sincronización P2P.",ko:"P2P 동기화 대상을 변경하려면 활성 P2P 원격 구성을 선택해 주세요.","zh-tw":"請選擇一個已啟用的 P2P 遠端設定,以變更 P2P 同步目標。"},"Please select an option to proceed":{def:"Please select an option to proceed",es:"Seleccione una opción para continuar",ja:"続行するには項目を選択してください",ko:"계속하려면 항목을 선택해 주세요",ru:"Чтобы продолжить, выберите вариант",zh:"请选择一个选项以继续","zh-tw":"請選擇一個選項以繼續"},"Please select the button below to restart and proceed to the data fetching confirmation.":{def:"Please select the button below to restart and proceed to the data fetching confirmation.",es:"Pulsa el botón de abajo para reiniciar y pasar a la confirmación de la obtención de datos.",ko:"아래 버튼을 선택하면 재시작 후 데이터 가져오기 확인 단계로 진행합니다.","zh-tw":"請點選下方按鈕以重新啟動,並前往資料擷取確認步驟。"},"Please select the button below to restart and proceed to the final confirmation.":{def:"Please select the button below to restart and proceed to the final confirmation.",es:"Pulsa el botón de abajo para reiniciar y pasar a la confirmación final.",ko:"아래 버튼을 선택하면 재시작 후 최종 확인 단계로 진행합니다.","zh-tw":"請點選下方按鈕以重新啟動,並前往最終確認步驟。"},"Please select the type of server to which you are connecting.":{def:"Please select the type of server to which you are connecting.",es:"Seleccione el tipo de servidor al que se está conectando。",ja:"接続するサーバーの種類を選択してください。",ko:"연결할 서버 유형을 선택해 주세요.",ru:"Выберите тип сервера, к которому вы подключаетесь。",zh:"请选择你要连接的服务器类型。","zh-tw":"請選擇你要連線的伺服器類型。"},"Please select your situation.":{def:"Please select your situation.",es:"Selecciona tu situación.",ko:"현재 상황을 선택해 주세요.","zh-tw":"請選擇符合你情況的選項。"},"Please set device name to identify this device. This name should be unique among your devices. While not configured, we cannot enable this feature.":{def:"Please set device name to identify this device. This name should be unique among your devices. While not configured, we cannot enable this feature.",es:"Define un nombre para identificar este dispositivo. Debe ser único entre tus dispositivos. Mientras no esté configurado, no podremos habilitar esta función.",ja:"このデバイスを識別するためのデバイス名を設定してください。この名前は各デバイスで一意である必要があります。設定されるまで、この機能は有効にできません。",ko:"이 기기를 식별할 기기 이름을 설정해 주세요. 이 이름은 기기 간에 고유해야 합니다. 설정하기 전까지는 이 기능을 활성화할 수 없습니다.",ru:"Укажите имя устройства для идентификации этого устройства. Имя должно быть уникальным среди ваших устройств. Пока оно не задано, мы не можем включить эту функцию.",zh:"请设置设备名称以标识此设备。该名称在你的所有设备之间应保持唯一;未配置前无法启用此功能。","zh-tw":"請設定用來識別此裝置的裝置名稱。此名稱在你所有裝置中應該是唯一的。尚未設定時,無法啟用此功能。"},"Please set this device name":{def:"Please set this device name",es:"Define el nombre de este dispositivo",ja:"このデバイス名を設定してください",ko:"이 기기의 이름을 설정해 주세요",ru:"Укажите имя этого устройства",zh:"请设置此设备名称","zh-tw":"請設定此裝置名稱"},"Please understand that this is intended behaviour.":{def:"Please understand that this is intended behaviour.",es:"Comprende que este es el comportamiento previsto.",ko:"이는 의도된 동작이라는 점을 이해해 주세요.","zh-tw":"請理解這是預期中的行為。"},"Plug-in version":{def:"Plug-in version",es:"Versión del complemento",ja:"プラグインバージョン",ko:"플러그인 버전",ru:"Версия плагина",zh:"插件版本","zh-tw":"外掛版本"},Plugins:{def:"Plugins",es:"Complementos",ko:"플러그인","zh-tw":"外掛"},"Prepare the 'report' to create an issue":{def:"Prepare the 'report' to create an issue",es:"Preparar el «informe» para abrir una incidencia",fr:"Préparer le « rapport » pour créer un ticket",he:"הכן 'דו\"ח' ליצירת Issue",ja:"Issue 作成用の「レポート」を準備",ko:"이슈 생성을 위한 '보고서' 준비",ru:"Подготовить «отчёт» для создания Issue",zh:"准备 '报告' 以创建问题单","zh-tw":"準備建立 Issue 用的「報告」"},Presets:{def:"Presets",es:"Preconfiguraciones",fr:"Préréglages",he:"קביעות מראש",ja:"プリセット",ko:"프리셋",ru:"Пресеты",zh:"预设","zh-tw":"預設集"},"Prevent fetching configuration from server":{def:"Prevent fetching configuration from server",es:"Impedir la obtención de la configuración desde el servidor",ko:"서버에서 구성 가져오기 방지","zh-tw":"阻止從伺服器擷取設定"},Proceed:{def:"Proceed",es:"Continuar",ko:"진행","zh-tw":"繼續"},"Proceed Garbage Collection":{def:"Proceed Garbage Collection",es:"Continuar con la recolección de basura",ja:"Garbage Collection を続行",ko:"가비지 컬렉션 계속",ru:"Продолжить Garbage Collection",zh:"继续执行垃圾回收","zh-tw":"繼續執行垃圾回收"},"Proceed to the next step.":{def:"Proceed to the next step.",es:"Continuar al paso siguiente.",ko:"다음 단계로 진행합니다.","zh-tw":"繼續前往下一步。"},"Proceed with Setup URI":{def:"Proceed with Setup URI",es:"Continuar con el URI de configuración",ja:"Setup URI で続行",ko:"Setup URI로 계속",ru:"Продолжить с Setup URI",zh:"继续使用 Setup URI","zh-tw":"繼續使用 Setup URI"},"Proceeding with Garbage Collection, ignoring missing nodes.":{def:"Proceeding with Garbage Collection, ignoring missing nodes.",es:"Se continúa con la recolección de basura, ignorando los nodos ausentes.",ja:"不足しているノードを無視して Garbage Collection を続行します。",ko:"누락된 노드를 무시하고 가비지 컬렉션을 계속 진행합니다.",ru:"Продолжаем Garbage Collection, игнорируя отсутствующие узлы.",zh:"正在继续执行垃圾回收,并忽略缺失节点。","zh-tw":"正在繼續執行垃圾回收,並忽略缺失節點。"},"Proceeding with Garbage Collection.":{def:"Proceeding with Garbage Collection.",es:"Se continúa con la recolección de basura.",ja:"Garbage Collection を実行します。",ko:"가비지 컬렉션을 진행합니다.",ru:"Запускаем Garbage Collection.",zh:"正在执行垃圾回收。","zh-tw":"正在執行垃圾回收。"},"Process small files in the foreground":{def:"Process small files in the foreground",es:"Procesar archivos pequeños en primer plano",fr:"Traiter les petits fichiers au premier plan",he:"עבד קבצים קטנים בחזית",ja:"小さいファイルを最前面で処理",ko:"포그라운드에서 작은 파일 처리",ru:"Обрабатывать маленькие файлы в основном потоке",zh:"在前台处理小文件","zh-tw":"在前景處理小型檔案"},Progress:{def:"Progress",es:"Progreso",ja:"進捗",ko:"진행 상태",ru:"Прогресс",zh:"进度","zh-tw":"進度"},"Property Encryption":{def:"Property Encryption",es:"Cifrado de propiedades",fr:"Chiffrement des propriétés",he:"הצפנת מאפיינים",ko:"속성 암호화",ru:"Шифрование свойств",zh:"属性加密","zh-tw":"屬性加密"},"PureJS fallback (Fast, W/O WebAssembly)":{def:"PureJS fallback (Fast, W/O WebAssembly)",es:"Alternativa PureJS (rápida, sin WebAssembly)",ja:"PureJS フォールバック (高速、WebAssembly なし)",ko:"PureJS 대체 방식 (빠름, WebAssembly 없음)",ru:"Вариант PureJS (быстрый, без WebAssembly)",zh:"PureJS 回退(快速,无 WebAssembly","zh-tw":"PureJS 回退(快速,無 WebAssembly"},"Purge all download/upload cache.":{def:"Purge all download/upload cache.",es:"Purga toda la caché de descarga y carga.",ja:"ダウンロード/アップロードキャッシュをすべて削除します。",ko:"모든 다운로드/업로드 캐시를 제거합니다.",ru:"Очистить весь кэш загрузки/выгрузки.",zh:"清除所有下载/上传缓存。","zh-tw":"清除所有下載/上傳快取。"},"Purge all journal counter":{def:"Purge all journal counter",es:"Purgar todos los contadores del diario",ja:"すべてのジャーナルカウンターを削除",ko:"모든 저널 카운터 삭제",ru:"Очистить все счётчики журнала",zh:"清除所有日志计数器","zh-tw":"清除所有日誌計數器"},"Rebuild local and remote database with local files.":{def:"Rebuild local and remote database with local files.",es:"Reconstruye la base de datos local y remota usando los archivos locales.",ja:"ローカルファイルを使ってローカルとリモートのデータベースを再構築します。",ko:"로컬 파일로 로컬 및 원격 데이터베이스를 다시 구축합니다.",ru:"Перестроить локальную и удалённую базы данных на основе локальных файлов.",zh:"使用本地文件重建本地和远端数据库。","zh-tw":"以本機檔案重建本機與遠端資料庫。"},"Rebuilding Operations (Remote Only)":{def:"Rebuilding Operations (Remote Only)",es:"Operaciones de reconstrucción (solo remoto)",ja:"再構築操作 (リモートのみ)",ko:"재구축 작업 (원격 전용)",ru:"Операции перестроения (только удалённое хранилище)",zh:"重建操作(仅远端)","zh-tw":"重建作業(僅遠端)"},"Recovery and Repair":{def:"Recovery and Repair",es:"Recuperación y reparación",ko:"복구 및 수리","zh-tw":"修復與修補"},"Recreate all":{def:"Recreate all",es:"Recrear todo",ja:"すべて再作成",ko:"모두 다시 생성",ru:"Пересоздать всё",zh:"全部重建","zh-tw":"全部重建"},"Recreate missing chunks for all files":{def:"Recreate missing chunks for all files",es:"Recrear fragmentos faltantes para todos los archivos",ja:"すべてのファイルの不足チャンクを再作成",ko:"모든 파일의 누락된 청크 다시 생성",ru:"Пересоздать отсутствующие чанки для всех файлов",zh:"为所有文件重建缺失的 chunks","zh-tw":"為所有檔案重建遺失的 chunks"},"RedFlag.Fetch.Method.Desc":{def:"How do you want to fetch?\n- Create a local database once before fetching.\n **Low Traffic**, **High CPU**, **Low Risk**\n Recommended if ...\n - Files possibly inconsistent\n - Files were not so much\n- Create local file chunks before fetching.\n **Low Traffic**, **Moderate CPU**, **Low to Moderate Risk**\n Recommended if ...\n - Files probably consistent\n - You have a lot of files.\n- Fetch everything from the remote.\n **High Traffic**, **Low CPU**, **Low to Moderate Risk**\n\n>[!INFO]- Details\n> ## Create a local database once before fetching.\n> **Low Traffic**, **High CPU**, **Low Risk**\n> This option first creates a local database using existing local files before fetching data from the remote source.\n> If matching files exist both locally and remotely, only the differences between them will be transferred.\n> However, files present in both locations will initially be handled as conflicted files. They will be resolved automatically if they are not actually conflicted, but this process may take time.\n> This is generally the safest method, minimizing data loss risk.\n> ## Create local file chunks before fetching.\n> **Low Traffic**, **Moderate CPU**, **Low to Moderate Risk** (depending operation)\n> This option first creates chunks from local files for the database, then fetches data. Consequently, only chunks missing locally are transferred. However, all metadata is taken from the remote source.\n> Local files are then compared against this metadata at launch. The content considered newer will overwrite the older one (by modified time). This outcome is then synchronised back to the remote database.\n> This is generally safe if local files are genuinely the latest timestamp. However, it can cause problems if a file has a newer timestamp but older content (like the initial `welcome.md`).\n> This uses less CPU and faster than \"Create a local database once before fetching\", but it may lead to data loss if not used carefully.\n> ## Fetch everything from the remote.\n> **High Traffic**, **Low CPU**, **Low to Moderate Risk** (depending operation)\n> All things will be fetched from the remote.\n> Similar to the Create local file chunks before fetching, but all chunks are fetched from the remote source.\n> This is the most traditional way to fetch, typically consuming the most network traffic and time. It also carries a similar risk of overwriting remote files to the 'Create local file chunks before fetching' option.\n> However, it is often considered the most stable method because it is the longest-established and most straightforward approach.",es:"¿Cómo quieres obtener los datos?\n- Crear una base de datos local antes de obtener los datos.\n **Poco tráfico**, **mucha CPU**, **riesgo bajo**\n Recomendado si...\n - Los archivos podrían ser inconsistentes\n - No hay demasiados archivos\n- Crear los chunks de los archivos locales antes de obtener los datos.\n **Poco tráfico**, **CPU moderada**, **riesgo bajo o moderado**\n Recomendado si...\n - Los archivos son probablemente consistentes\n - Tienes muchos archivos\n- Obtener todo del remoto.\n **Mucho tráfico**, **poca CPU**, **riesgo bajo o moderado**\n\n>[!INFO]- Detalles\n> ## Crear una base de datos local antes de obtener los datos.\n> **Poco tráfico**, **mucha CPU**, **riesgo bajo**\n> Esta opción crea primero una base de datos local a partir de los archivos locales existentes antes de obtener los datos del remoto.\n> Si un archivo existe tanto en local como en remoto, solo se transferirán las diferencias.\n> Sin embargo, los archivos presentes en ambos sitios se tratarán inicialmente como archivos en conflicto. Se resolverán automáticamente si en realidad no lo están, pero el proceso puede tardar.\n> En general es el método más seguro y el que menos riesgo de pérdida de datos conlleva.\n> ## Crear los chunks de los archivos locales antes de obtener los datos.\n> **Poco tráfico**, **CPU moderada**, **riesgo bajo o moderado** (según la operación)\n> Esta opción crea primero los chunks de los archivos locales para la base de datos y después obtiene los datos. Así solo se transfieren los chunks que faltan en local. Aun así, todos los metadatos se toman del remoto.\n> Al iniciar, los archivos locales se comparan con esos metadatos. El contenido considerado más reciente sobrescribirá al más antiguo (según la fecha de modificación) y el resultado se sincroniza de vuelta a la base de datos remota.\n> Es seguro si los archivos locales son realmente los de fecha más reciente, pero puede dar problemas si un archivo tiene una fecha más nueva y un contenido más antiguo (como el `welcome.md` inicial).\n> Usa menos CPU y es más rápido que «Crear una base de datos local antes de obtener los datos», pero puede provocar pérdida de datos si no se usa con cuidado.\n> ## Obtener todo del remoto.\n> **Mucho tráfico**, **poca CPU**, **riesgo bajo o moderado** (según la operación)\n> Se obtiene todo del remoto.\n> Similar a Crear los chunks de los archivos locales antes de obtener los datos, pero todos los chunks se descargan del remoto.\n> Es la forma más tradicional de obtener los datos y normalmente la que más tráfico y tiempo consume. Conlleva un riesgo de sobrescribir archivos remotos parecido al de «Crear los chunks de los archivos locales antes de obtener los datos».\n> Aun así, suele considerarse el método más estable, por ser el más antiguo y directo.",fr:"Comment voulez-vous récupérer ?\n- Créer une base locale avant de récupérer.\n **Trafic faible**, **CPU élevé**, **Risque faible**\n Recommandé si ...\n - Fichiers possiblement incohérents\n - Fichiers peu nombreux\n- Créer des fragments de fichiers locaux avant de récupérer.\n **Trafic faible**, **CPU modéré**, **Risque faible à modéré**\n Recommandé si ...\n - Fichiers probablement cohérents\n - Vous avez beaucoup de fichiers.\n- Tout récupérer depuis le distant.\n **Trafic élevé**, **CPU faible**, **Risque faible à modéré**\n\n>[!INFO]- Détails\n> ## Créer une base locale avant de récupérer.\n> **Trafic faible**, **CPU élevé**, **Risque faible**\n> Cette option crée d'abord une base locale à partir des fichiers locaux existants avant de récupérer les données depuis la source distante.\n> Si des fichiers correspondants existent à la fois localement et à distance, seules les différences entre eux seront transférées.\n> Toutefois, les fichiers présents aux deux emplacements seront initialement traités comme en conflit. Ils seront résolus automatiquement s'ils ne le sont pas réellement, mais ce processus peut prendre du temps.\n> C'est généralement la méthode la plus sûre, minimisant le risque de perte de données.\n> ## Créer des fragments de fichiers locaux avant de récupérer.\n> **Trafic faible**, **CPU modéré**, **Risque faible à modéré** (selon l'opération)\n> Cette option crée d'abord des fragments à partir des fichiers locaux pour la base, puis récupère les données. Par conséquent, seuls les fragments manquants localement sont transférés. Cependant, toutes les métadonnées sont prises de la source distante.\n> Les fichiers locaux sont ensuite comparés à ces métadonnées au lancement. Le contenu considéré comme plus récent écrasera le plus ancien (selon la date de modification). Le résultat est ensuite synchronisé vers la base distante.\n> C'est généralement sûr si les fichiers locaux ont bien l'horodatage le plus récent. Cela peut toutefois poser problème si un fichier a un horodatage plus récent mais un contenu plus ancien (comme le `welcome.md` initial).\n> Cette méthode utilise moins de CPU et est plus rapide que « Créer une base locale avant de récupérer », mais peut entraîner une perte de données si elle n'est pas utilisée avec précaution.\n> ## Tout récupérer depuis le distant.\n> **Trafic élevé**, **CPU faible**, **Risque faible à modéré** (selon l'opération)\n> Tout sera récupéré depuis le distant.\n> Similaire à Créer des fragments de fichiers locaux avant de récupérer, mais tous les fragments sont récupérés depuis la source distante.\n> C'est la façon la plus traditionnelle de récupérer, consommant généralement le plus de trafic réseau et de temps. Elle comporte également un risque similaire d'écraser les fichiers distants à l'option « Créer des fragments de fichiers locaux avant de récupérer ».\n> Elle est toutefois souvent considérée comme la méthode la plus stable car c'est la plus ancienne et la plus directe.",he:'כיצד ברצונך למשוך?\n- %{RedFlag.Fetch.Method.FetchSafer}.\n **תעבורה נמוכה**, **מעבד גבוה**, **סיכון נמוך**\n מומלץ אם...\n - קבצים עשויים להיות לא עקביים\n - אין הרבה קבצים\n- %{RedFlag.Fetch.Method.FetchSmoother}.\n **תעבורה נמוכה**, **מעבד בינוני**, **סיכון נמוך עד בינוני**\n מומלץ אם...\n - הקבצים ככל הנראה עקביים\n - יש לך הרבה קבצים.\n- %{RedFlag.Fetch.Method.FetchTraditional}.\n **תעבורה גבוהה**, **מעבד נמוך**, **סיכון נמוך עד בינוני**\n\n>[!INFO]- פרטים\n> ## %{RedFlag.Fetch.Method.FetchSafer}.\n> **תעבורה נמוכה**, **מעבד גבוה**, **סיכון נמוך**\n> אפשרות זו יוצרת תחילה מסד נתונים מקומי תוך שימוש בקבצים מקומיים קיימים לפני משיכת נתונים מהמקור המרוחד.\n> אם קיימים קבצים תואמים גם מקומית וגם מרחוק, רק ההפרשים ביניהם יועברו.\n> עם זאת, קבצים הקיימים בשני המקומות יטופלו תחילה כקבצים מתנגשים. הם ייפתרו אוטומטית אם לא מתנגשים בפועל, אך תהליך זה עשוי לקחת זמן.\n> זוהי בדרך כלל השיטה הבטוחה ביותר, ממזערת סיכון לאובדן נתונים.\n> ## %{RedFlag.Fetch.Method.FetchSmoother}.\n> **תעבורה נמוכה**, **מעבד בינוני**, **סיכון נמוך עד בינוני** (תלוי בפעולה)\n> אפשרות זו יוצרת תחילה נתחים מקבצים מקומיים למסד הנתונים, ואז מושכת נתונים. כתוצאה מכך, רק נתחים חסרים מקומית מועברים. עם זאת, כל המטה-נתונים נלקחים מהמקור המרוחד.\n> קבצים מקומיים נבדקים לאחר מכן מול מטה-נתונים אלה בעת ההפעלה. התוכן שנחשב חדש יותר ידרוס את הישן יותר (לפי זמן שינוי).\n> בדרך כלל בטוח אם הקבצים המקומיים הם אכן חדשים ביותר. עם זאת, עלול לגרום לבעיות אם לקובץ יש חותמת זמן חדשה יותר אך תוכן ישן יותר (כמו `welcome.md` ראשוני).\n> שיטה זו משתמשת בפחות מעבד ומהירה יותר מ-"%{RedFlag.Fetch.Method.FetchSafer}", אך עלולה להוביל לאובדן נתונים אם לא משתמשים בה בזהירות.\n> ## %{RedFlag.Fetch.Method.FetchTraditional}.\n> **תעבורה גבוהה**, **מעבד נמוך**, **סיכון נמוך עד בינוני** (תלוי בפעולה)\n> הכל יימשך מהשרת המרוחד.\n> דומה ל-%{RedFlag.Fetch.Method.FetchSmoother}, אך כל הנתחים נמשכים מהמקור המרוחד.\n> זוהי הדרך המסורתית ביותר למשיכה, צורכת בדרך כלל את רוב תעבורת הרשת והזמן.\n> עם זאת, היא נחשבת לעתים קרובות לשיטה היציבה ביותר מכיוון שהיא הוותיקה והישירה ביותר.',ja:"どのようにフェッチしますか?\n- フェッチ前にローカルデータベースを作成\n **低トラフィック**, **高CPU負荷**, **低リスク**\n 推奨条件...\n - ファイルの整合性に不安がある\n - ファイル数がそれほど多くない\n- フェッチ前にローカルファイルチャンクを作成\n **低トラフィック**, **中程CPU負荷**, **低~中リスク**\n 推奨条件...\n - ファイルがおそらく整合している\n - ファイル数が多い\n- リモートからすべてをフェッチ\n **高トラフィック**, **低CPU負荷**, **低~中リスク**\n\n>[!INFO]- 詳細\n> ## フェッチ前にローカルデータベースを作成\n> **低トラフィック**, **高CPU負荷**, **低リスク**\n> このオプションは、リモートからデータをフェッチする前に、既存のローカルファイルを使用してローカルデータベースを作成します。\n> ローカルとリモートの両方に一致するファイルがある場合、差分のみが転送されます。\n> ただし、両方の場所に存在するファイルは最初は競合ファイルとして処理されます。実際に競合していなければ自動的に解決されますが、この処理には時間がかかる場合があります。\n> これは一般的に最も安全な方法で、データ損失のリスクを最小限に抑えます。\n> ## フェッチ前にローカルファイルチャンクを作成\n> **低トラフィック**, **中程CPU負荷**, **低~中リスク**(操作による)\n> このオプションは、最初にローカルファイルからデータベース用のチャンクを作成し、その後データをフェッチします。そのため、ローカルにないチャンクのみが転送されます。ただし、すべてのメタデータはリモートから取得されます。\n> ローカルファイルは起動時にこのメタデータと比較されます。新しいと判断されたコンテンツ(更新日時による)が古いものを上書きします。この結果はリモートデータベースに同期されます。\n> ローカルファイルが本当に最新のタイムスタンプであれば一般的に安全です。ただし、ファイルのタイムスタンプが新しくてもコンテンツが古い場合(初期の`welcome.md`など)は問題が発生する可能性があります。\n> これは\"フェッチ前にローカルデータベースを作成\"よりCPU使用量が少なく高速ですが、注意しないとデータ損失につながる可能性があります。\n> ## リモートからすべてをフェッチ\n> **高トラフィック**, **低CPU負荷**, **低~中リスク**(操作による)\n> すべてのデータがリモートからフェッチされます。\n> フェッチ前にローカルファイルチャンクを作成と似ていますが、すべてのチャンクがリモートからフェッチされます。\n> これは最も従来のフェッチ方法で、通常最もネットワークトラフィックと時間を消費します。'フェッチ前にローカルファイルチャンクを作成'オプションと同様のリモートファイル上書きのリスクがあります。\n> ただし、最も歴史があり簡単なアプローチであるため、最も安定した方法と見なされることが多いです。",ko:"어떻게 가져오시겠습니까?\n- 가져오기 전에 로컬 데이터베이스를 한 번 생성.\n **낮은 트래픽**, **높은 CPU**, **낮은 위험**\n 다음의 경우에 권장합니다.\n - 파일이 일관되지 않을 가능성이 있음\n - 파일이 그리 많지 않음\n- 가져오기 전에 로컬 파일 청크 생성.\n **낮은 트래픽**, **보통 CPU**, **낮음~보통 위험**\n 다음의 경우에 권장합니다.\n - 파일이 대체로 일관됨\n - 파일이 많음\n- 원격에서 모든 것 가져오기.\n **높은 트래픽**, **낮은 CPU**, **낮음~보통 위험**\n\n>[!INFO]- 자세히\n> ## 가져오기 전에 로컬 데이터베이스를 한 번 생성.\n> **낮은 트래픽**, **높은 CPU**, **낮은 위험**\n> 원격에서 데이터를 가져오기 전에 기존 로컬 파일로 로컬 데이터베이스를 먼저 만듭니다.\n> 로컬과 원격 양쪽에 일치하는 파일이 있으면 둘 사이의 차이만 전송됩니다.\n> 다만 양쪽에 모두 있는 파일은 처음에 충돌 파일로 처리됩니다. 실제로 충돌하지 않는다면 자동으로 해결되지만, 이 과정에 시간이 걸릴 수 있습니다.\n> 일반적으로 가장 안전한 방법이며 데이터 손실 위험이 가장 낮습니다.\n> ## 가져오기 전에 로컬 파일 청크 생성.\n> **낮은 트래픽**, **보통 CPU**, **낮음~보통 위험** (작업에 따라 다름)\n> 먼저 로컬 파일로 데이터베이스용 청크를 만든 다음 데이터를 가져옵니다. 따라서 로컬에 없는 청크만 전송됩니다. 다만 메타데이터는 모두 원격에서 가져옵니다.\n> 그다음 시작 시점에 로컬 파일을 이 메타데이터와 비교합니다. 수정 시각을 기준으로 더 새롭다고 판단된 내용이 오래된 쪽을 덮어씁니다. 그 결과는 다시 원격 데이터베이스로 동기화됩니다.\n> 로컬 파일이 실제로 가장 최신 타임스탬프를 가지고 있다면 대체로 안전합니다. 하지만 타임스탬프는 더 새롭지만 내용은 더 오래된 파일(처음 만들어지는 `welcome.md` 같은)이 있으면 문제가 생길 수 있습니다.\n> \"가져오기 전에 로컬 데이터베이스를 한 번 생성\"보다 CPU를 적게 쓰고 더 빠르지만, 주의해서 사용하지 않으면 데이터가 손실될 수 있습니다.\n> ## 원격에서 모든 것 가져오기.\n> **높은 트래픽**, **낮은 CPU**, **낮음~보통 위험** (작업에 따라 다름)\n> 모든 것을 원격에서 가져옵니다.\n> 가져오기 전에 로컬 파일 청크 생성와 비슷하지만, 모든 청크를 원격에서 가져옵니다.\n> 가장 전통적인 가져오기 방식으로, 보통 네트워크 트래픽과 시간을 가장 많이 소모합니다. 또한 '가져오기 전에 로컬 파일 청크 생성' 옵션과 마찬가지로 원격 파일을 덮어쓸 위험이 있습니다.\n> 다만 가장 오래되고 단순한 방식이기 때문에 가장 안정적인 방법으로 여겨지는 경우가 많습니다.",ru:"Как вы хотите загрузить?",zh:"How do you want to fetch?\n- Create a local database once before fetching.\n **Low Traffic**, **High CPU**, **Low Risk**\n Recommended if ...\n - Files possibly inconsistent\n - Files were not so much\n- Create local file chunks before fetching.\n **Low Traffic**, **Moderate CPU**, **Low to Moderate Risk**\n Recommended if ...\n - Files probably consistent\n - You have a lot of files.\n- Fetch everything from the remote.\n **High Traffic**, **Low CPU**, **Low to Moderate Risk**\n\n>[!INFO]- Details\n> ## Create a local database once before fetching.\n> **Low Traffic**, **High CPU**, **Low Risk**\n> This option first creates a local database using existing local files before fetching data from the remote source.\n> If matching files exist both locally and remotely, only the differences between them will be transferred.\n> However, files present in both locations will initially be handled as conflicted files. They will be resolved automatically if they are not actually conflicted, but this process may take time.\n> This is generally the safest method, minimizing data loss risk.\n> ## Create local file chunks before fetching.\n> **Low Traffic**, **Moderate CPU**, **Low to Moderate Risk** (depending operation)\n> This option first creates chunks from local files for the database, then fetches data. Consequently, only chunks missing locally are transferred. However, all metadata is taken from the remote source.\n> Local files are then compared against this metadata at launch. The content considered newer will overwrite the older one (by modified time). This outcome is then synchronised back to the remote database.\n> This is generally safe if local files are genuinely the latest timestamp. However, it can cause problems if a file has a newer timestamp but older content (like the initial `welcome.md`).\n> This uses less CPU and faster than \"Create a local database once before fetching\", but it may lead to data loss if not used carefully.\n> ## Fetch everything from the remote.\n> **High Traffic**, **Low CPU**, **Low to Moderate Risk** (depending operation)\n> All things will be fetched from the remote.\n> Similar to the Create local file chunks before fetching, but all chunks are fetched from the remote source.\n> This is the most traditional way to fetch, typically consuming the most network traffic and time. It also carries a similar risk of overwriting remote files to the 'Create local file chunks before fetching' option.\n> However, it is often considered the most stable method because it is the longest-established and most straightforward approach.","zh-tw":"你想要如何抓取?\n- 先建立一次本機資料庫,再抓取。\n **低流量**、**高 CPU 使用率**、**低風險**\n 建議情況:\n - 檔案可能不一致\n - 檔案數量不多\n- 先建立本機檔案的 chunks,再抓取。\n **低流量**、**中等 CPU 使用率**、**低至中等風險**\n 建議情況:\n - 檔案應該是一致的\n - 你有大量檔案\n- 從遠端抓取所有內容。\n **高流量**、**低 CPU 使用率**、**低至中等風險**\n\n>[!INFO]- 詳細說明\n> ## 先建立一次本機資料庫,再抓取。\n> **低流量**、**高 CPU 使用率**、**低風險**\n> 這個選項會先使用現有的本機檔案建立本機資料庫,再從遠端來源抓取資料。\n> 若本機與遠端都存在相符的檔案,只會傳輸兩者之間的差異部分。\n> 不過,兩邊都存在的檔案一開始會被當作衝突檔案處理。若實際上並無衝突,會自動解決,但這個過程可能需要一些時間。\n> 這通常是最安全的方式,能將資料遺失的風險降到最低。\n> ## 先建立本機檔案的 chunks,再抓取。\n> **低流量**、**中等 CPU 使用率**、**低至中等風險**(依操作而異)\n> 這個選項會先從本機檔案為資料庫建立 chunks,再抓取資料。因此只會傳輸本機缺少的 chunks,但所有中繼資料都會取自遠端來源。\n> 啟動時本機檔案會與這份中繼資料比對,內容較新的一方(依修改時間判斷)會覆寫較舊的一方,其結果會同步回遠端資料庫。\n> 如果本機檔案的時間戳記確實是最新的,這通常是安全的;但如果某個檔案時間戳記較新卻內容較舊(例如初始的 `welcome.md`),可能會出問題。\n> 這比「先建立一次本機資料庫,再抓取」耗用更少 CPU、速度也更快,但若不小心使用可能導致資料遺失。\n> ## 從遠端抓取所有內容。\n> **高流量**、**低 CPU 使用率**、**低至中等風險**(依操作而異)\n> 所有內容都會從遠端抓取。\n> 與「先建立本機檔案的 chunks,再抓取」類似,但所有 chunks 都是從遠端來源抓取。\n> 這是最傳統的抓取方式,通常會耗用最多的網路流量與時間,覆寫遠端檔案的風險也與「先建立本機檔案的 chunks,再抓取」選項相近。\n> 不過,由於這是歷史最久、最直接的做法,通常被認為是最穩定的方式。"},"RedFlag.Fetch.Method.FetchSafer":{def:"Create a local database once before fetching",es:"Crear una base de datos local antes de obtener los datos",fr:"Créer une base locale avant de récupérer",he:"צור מסד נתונים מקומי לפני המשיכה",ja:"フェッチ前にローカルデータベースを作成",ko:"가져오기 전에 로컬 데이터베이스를 한 번 생성",ru:"Создать локальную базу данных перед загрузкой",zh:"Create a local database once before fetching","zh-tw":"先建立一次本機資料庫,再抓取"},"RedFlag.Fetch.Method.FetchSmoother":{def:"Create local file chunks before fetching",es:"Crear los chunks de los archivos locales antes de obtener los datos",fr:"Créer des fragments de fichiers locaux avant de récupérer",he:"צור נתחי קבצים מקומיים לפני המשיכה",ja:"フェッチ前にローカルファイルチャンクを作成",ko:"가져오기 전에 로컬 파일 청크 생성",ru:"Создать локальные чанки перед загрузкой",zh:"Create local file chunks before fetching","zh-tw":"先建立本機檔案的 chunks,再抓取"},"RedFlag.Fetch.Method.FetchTraditional":{def:"Fetch everything from the remote",es:"Obtener todo del remoto",fr:"Tout récupérer depuis le distant",he:"משוך הכל מהשרת המרוחד",ja:"リモートからすべてをフェッチ",ko:"원격에서 모든 것 가져오기",ru:"Загрузить всё с удалённого",zh:"Fetch everything from the remote","zh-tw":"從遠端抓取所有內容"},"RedFlag.Fetch.Method.Title":{def:"How do you want to fetch?",es:"¿Cómo quieres obtener los datos?",fr:"Comment voulez-vous récupérer ?",he:"כיצד ברצונך למשוך?",ja:"どのようにフェッチしますか?",ko:"어떻게 가져오시겠습니까?",ru:"Как вы хотите загрузить?",zh:"How do you want to fetch?","zh-tw":"你想要如何抓取?"},"RedFlag.FetchRemoteConfig.Buttons.Cancel":{def:"No, use local settings",es:"No, usar los ajustes locales",fr:"Non, utiliser les paramètres locaux",he:"לא, השתמש בהגדרות המקומיות",ja:"いいえ、ローカル設定を使用",ko:"아니요, 로컬 설정을 사용합니다",ru:"Нет, использовать локальные настройки",zh:"No, use local settings","zh-tw":"不用,使用本機設定"},"RedFlag.FetchRemoteConfig.Buttons.Fetch":{def:"Yes, fetch and apply remote settings",es:"Sí, obtener y aplicar los ajustes remotos",fr:"Oui, récupérer et appliquer les paramètres distants",he:"כן, משוך והחל הגדרות מרוחקות",ja:"はい、リモート設定を取得して適用",ko:"예, 원격 설정을 가져와 적용합니다",ru:"Да, загрузить и применить удалённые настройки",zh:"Yes, fetch and apply remote settings","zh-tw":"要,抓取並套用遠端設定"},"RedFlag.FetchRemoteConfig.Message":{def:"Do you want to fetch and apply remotely stored preference settings to the device?",es:"¿Quieres obtener y aplicar en este dispositivo los ajustes de preferencias guardados en el remoto?",fr:"Voulez-vous récupérer et appliquer les préférences stockées à distance sur cet appareil ?",he:"האם ברצונך למשוך ולהחיל הגדרות שמורות מרחוק על מכשיר זה?",ja:"リモートに保存された設定を取得して、このデバイスに適用しますか?",ko:"원격에 저장된 환경 설정을 가져와 이 기기에 적용하시겠습니까?",ru:"Вы хотите загрузить и применить удалённые настройки?",zh:"Do you want to fetch and apply remotely stored preference settings to the device?","zh-tw":"要將遠端儲存的偏好設定抓取並套用到此裝置嗎?"},"RedFlag.FetchRemoteConfig.Title":{def:"Fetch Remote Configuration",es:"Obtener la configuración remota",fr:"Récupérer la configuration distante",he:"משוך תצורה מרוחקת",ja:"リモート設定の取得",ko:"원격 구성 가져오기",ru:"Загрузить удалённую конфигурацию",zh:"Fetch Remote Configuration","zh-tw":"抓取遠端設定"},"Reduces storage space by discarding all non-latest revisions. This requires the same amount of free space on the remote server and the local client.":{def:"Reduces storage space by discarding all non-latest revisions. This requires the same amount of free space on the remote server and the local client.",es:"Reduce el espacio de almacenamiento descartando todas las revisiones que no sean la última. Requiere la misma cantidad de espacio libre en el servidor remoto y en el cliente local.",ja:"最新版以外のすべてのリビジョンを破棄して、使用容量を削減します。実行には、リモートサーバーとローカルクライアントの両方に同程度の空き容量が必要です。",ko:"최신 버전이 아닌 모든 리비전을 제거하여 저장 공간을 줄입니다. 이 작업을 수행하려면 원격 서버와 로컬 클라이언트에 동일한 양의 여유 공간이 필요합니다.",zh:"通过丢弃所有非最新版本来减少存储空间。这需要远程服务器和本地客户端具备相同数量的可用空间。","zh-tw":"透過捨棄所有非最新版本減少儲存空間占用。執行此操作時,遠端伺服器與本機用戶端都需要具備相同數量的可用空間。"},"Reducing the frequency with which on-disk changes are reflected into the DB":{def:"Reducing the frequency with which on-disk changes are reflected into the DB",es:"Reducir frecuencia de actualizaciones de disco a BD",fr:"Réduire la fréquence à laquelle les modifications sur disque sont reflétées dans la base",he:"הפחת את תדירות השתקפות שינויים בדיסק למסד הנתונים",ja:"ローカルでの変更がデータベースに反映される頻度を下げる(所定の回数まとめて同期する、逐一反映しない)",ko:"디스크 변경 사항이 데이터베이스에 반영되는 빈도를 줄입니다",ru:"Уменьшение частоты отражения изменений с диска в БД",zh:"降低将磁盘上的更改反映到数据库中的频率","zh-tw":"降低磁碟變更反映到資料庫的頻率"},Refresh:{def:"Refresh",es:"Actualizar",ko:"새로 고침","zh-tw":"重新整理"},Region:{def:"Region",es:"Región",fr:"Région",he:"אזור",ja:"リージョン",ko:"지역",ru:"Регион",zh:"区域","zh-tw":"區域"},"Relay settings":{def:"Relay settings",es:"Ajustes del relé",ko:"중계 서버 설정","zh-tw":"中繼站設定"},Reload:{def:"Reload",es:"Recargar",ko:"다시 불러오기","zh-tw":"重新載入"},Remediation:{def:"Remediation",es:"Remediación",ja:"是正",ko:"복구 조치",ru:"Исправление",zh:"修复设置","zh-tw":"修復設定"},"Remediation Setting Changed":{def:"Remediation Setting Changed",es:"La configuración de remediación cambió",ja:"是正設定が変更されました",ko:"복구 설정이 변경됨",ru:"Настройки исправления изменены",zh:"修复设置已更改","zh-tw":"修復設定已變更"},"Remote Database Tweak (In sunset)":{def:"Remote Database Tweak (In sunset)",es:"Ajustes de base de datos remota (en retirada)",ja:"リモートデータベースの調整 (廃止予定)",ko:"원격 데이터베이스 조정 (폐기 예정)",ru:"Настройки удалённой базы данных (устаревает)",zh:"远端数据库调优(逐步淘汰)","zh-tw":"遠端資料庫調校(即將淘汰)"},"Remote Databases":{def:"Remote Databases",es:"Bases de datos remotas",ja:"リモートデータベース",ko:"원격 데이터베이스",ru:"Удалённые базы данных",zh:"远端数据库","zh-tw":"遠端資料庫"},"Remote name":{def:"Remote name",es:"Nombre del remoto",ja:"リモート名",ko:"원격 이름",ru:"Имя удалённого хранилища",zh:"远端名称","zh-tw":"遠端名稱"},"Remote only":{def:"Remote only",es:"Solo remoto",ko:"원격에만 있음","zh-tw":"僅遠端有"},"Remote server type":{def:"Remote server type",es:"Tipo de servidor remoto",fr:"Type de serveur distant",he:"סוג שרת מרוחד",ja:"リモートの種別",ko:"원격 서버 유형",ru:"Тип удалённого сервера",zh:"远程服务器类型","zh-tw":"遠端伺服器類型"},"Remote Type":{def:"Remote Type",es:"Tipo de remoto",fr:"Type de distant",he:"סוג מרוחד",ja:"同期方式",ko:"원격 유형",ru:"Удалённый тип",zh:"远程类型","zh-tw":"遠端類型"},Rename:{def:"Rename",es:"Renombrar",ja:"名前を変更",ko:"이름 바꾸기",ru:"Переименовать",zh:"重命名","zh-tw":"重新命名"},"Replicate now":{def:"Replicate now",es:"Replicar ahora",ko:"지금 복제","zh-tw":"立即複寫"},Replicating:{def:"Replicating",es:"Replicando",ko:"복제 중","zh-tw":"複寫中"},"Replicating...":{def:"Replicating...",es:"Replicando...",ko:"복제 중입니다...","zh-tw":"複寫中⋯"},"Replicator.Dialogue.Locked.Action.Dismiss":{def:"Cancel for reconfirmation",es:"Cancelar para volver a confirmarlo",fr:"Annuler pour reconfirmer",he:"ביטול לאישור מחדש",ja:"再確認のためキャンセル",ko:"재확인을 위해 취소",ru:"Отмена для подтверждения",zh:"Cancel for reconfirmation","zh-tw":"取消,稍後再確認"},"Replicator.Dialogue.Locked.Action.Fetch":{def:"Reset Synchronisation on This Device",es:"Restablecer la sincronización en este dispositivo",fr:"Réinitialiser la synchronisation sur cet appareil",he:"אפס סנכרון במכשיר זה",ja:"このデバイスの同期をリセット",ko:"이 기기의 동기화 재설정",ru:"Сбросить синхронизацию на этом устройстве",zh:"Reset Synchronisation on This Device","zh-tw":"重設此裝置上的同步"},"Replicator.Dialogue.Locked.Action.Unlock":{def:"Unlock the remote database",es:"Desbloquear la base de datos remota",fr:"Déverrouiller la base distante",he:"בטל נעילת מסד הנתונים המרוחד",ja:"リモートデータベースのロックを解除",ko:"원격 데이터베이스 잠금 해제",ru:"Разблокировать удалённую базу данных",zh:"Unlock the remote database","zh-tw":"解鎖遠端資料庫"},"Replicator.Dialogue.Locked.Message":{def:"Remote database is locked. This is due to a rebuild on one of the terminals.\nThe device is therefore asked to withhold the connection to avoid database corruption.\n\nThere are three options that we can do:\n\n- Reset Synchronisation on This Device\n The most preferred and reliable way. This will dispose the local database once, and reset all synchronisation information from the remote database again, In most case, we can perform this safely. However, it takes some time and should be done in stable network.\n- Unlock the remote database\n This method can only be used if we are already reliably synchronised by other replication methods. This does not simply mean that we have the same files. If you are not sure, you should avoid it.\n- Cancel for reconfirmation\n This will cancel the operation. And we will asked again on next request.\n",es:"La base de datos remota está bloqueada porque se ha reconstruido en uno de los dispositivos.\nPor eso se pide a este dispositivo que no se conecte, para evitar corromper la base de datos.\n\nHay tres opciones posibles:\n\n- Restablecer la sincronización en este dispositivo\n La más recomendable y fiable. Descarta la base de datos local y vuelve a tomar toda la información de sincronización del remoto. En la mayoría de los casos se puede hacer sin riesgo, aunque lleva algo de tiempo y conviene hacerlo con una red estable.\n- Desbloquear la base de datos remota\n Solo se puede usar si ya estamos sincronizados de forma fiable por otros métodos de replicación. Esto no significa simplemente tener los mismos archivos. Si no estás seguro, evítala.\n- Cancelar para volver a confirmarlo\n Cancela la operación. Se volverá a preguntar en la próxima solicitud.\n",fr:"La base distante est verrouillée. Ceci est dû à une reconstruction sur l'un des terminaux.\nL'appareil est donc prié de suspendre la connexion pour éviter la corruption de la base.\n\nTrois options sont possibles :\n\n- Réinitialiser la synchronisation sur cet appareil\n La méthode la plus recommandée et fiable. Elle supprime la base locale puis réinitialise toutes les informations de synchronisation depuis la base distante. Dans la plupart des cas, c'est sûr. Cela prend cependant du temps et devrait se faire sur un réseau stable.\n- Déverrouiller la base distante\n Cette méthode ne peut être utilisée que si nous sommes déjà synchronisés de manière fiable par d'autres méthodes de réplication. Cela ne signifie pas simplement que nous avons les mêmes fichiers. Dans le doute, évitez.\n- Annuler pour reconfirmer\n Ceci annule l'opération. Vous serez à nouveau interrogé à la prochaine requête.\n",he:"מסד הנתונים המרוחד נעול. הסיבה היא בנייה מחדש באחד הטרמינלים.\nלכן המכשיר מתבקש להמנע מחיבור כדי למנוע פגיעה במסד הנתונים.\n\nקיימות שלוש אפשרויות:\n\n- %{Replicator.Dialogue.Locked.Action.Fetch}\n הדרך המועדפת והאמינה ביותר. פעולה זו תמחק את מסד הנתונים המקומי פעם,\n ותאפס את כל מידע הסנכרון ממסד הנתונים המרוחד מחדש. ברוב המקרים ניתן\n לעשות זאת בבטחה. עם זאת, דורשת זמן ויש לבצע ברשת יציבה.\n- %{Replicator.Dialogue.Locked.Action.Unlock}\n ניתן להשתמש בשיטה זו רק אם כבר מסונכרנים באופן אמין בשיטות שכפול\n אחרות. פשוט לא מספיק שיש אותם קבצים. אם אינך בטוח, הימנע מכך.\n- %{Replicator.Dialogue.Locked.Action.Dismiss}\n פעולה זו תבטל את הפעולה. תתבקש שוב בבקשה הבאה.\n",ja:"リモートデータベースがロックされています。これはいずれかの端末での再構築が原因です。\nデータベースの破損を避けるため、このデバイスは接続を保留するよう求められています。\n\n3つのオプションがあります:\n\n- このデバイスの同期をリセット\n 最も推奨される信頼性の高い方法です。ローカルデータベースを一度破棄し、リモートデータベースからすべての同期情報を再取得します。ほとんどの場合、これは安全に実行できます。ただし、時間がかかり、安定したネットワークで実行する必要があります。\n- リモートデータベースのロックを解除\n この方法は、他のレプリケーション(複製)方法ですでに確実に同期されている場合のみ使用できます。単に同じファイルがあるという意味ではありません。確信がない場合は避けてください。\n- 再確認のためキャンセル\n 操作をキャンセルします。次回のリクエスト時に再度確認されます。\n",ko:"원격 데이터베이스가 잠겨 있습니다. 이는 일부 터미널에서 데이터베이스를 재구축했기 때문입니다.\n따라서 현재 기기는 데이터베이스 손상을 방지하기 위해 연결을 일시적으로 보류해야 합니다.\n\n선택할 수 있는 세 가지 방법이 있습니다:\n\n- 이 기기의 동기화 재설정\n 가장 권장되고 신뢰할 수 있는 방법입니다. 로컬 데이터베이스를 초기화한 뒤, 원격 데이터베이스의 전체 데이터를 다시 가져옵니다. 대부분의 경우 안전하게 수행할 수 있으나, 시간이 다소 걸리며 안정적인 네트워크 환경에서 진행해야 합니다.\n- 원격 데이터베이스 잠금 해제\n 이 방법은 다른 동기화 방식으로 이미 완전하고 안정적으로 동기화된 경우에만 사용할 수 있습니다. 단순히 파일이 같다는 의미가 아니므로, 확신이 없다면 사용을 피하는 것이 좋습니다.\n- 재확인을 위해 취소\n 이번 작업을 취소하고, 다음 요청 시 다시 안내받습니다.\n",ru:"Удалённая база данных заблокирована. Это связано с перестроением на одном из устройств.",zh:"Remote database is locked. This is due to a rebuild on one of the terminals.\nThe device is therefore asked to withhold the connection to avoid database corruption.\n\nThere are three options that we can do:\n\n- Reset Synchronisation on This Device\n The most preferred and reliable way. This will dispose the local database once, and fetch all from the remote database again, In most case, we can perform this safely. However, it takes some time and should be done in stable network.\n- Unlock the remote database\n This method can only be used if we are already reliably synchronised by other replication methods. This does not simply mean that we have the same files. If you are not sure, you should avoid it.\n- Cancel for reconfirmation\n This will cancel the operation. And we will asked again on next request.\n","zh-tw":"遠端資料庫已鎖定,這是因為其中一台裝置執行過重建。\n因此系統要求此裝置暫停連線,以避免資料庫損毀。\n\n我們有三種做法:\n\n- 重設此裝置上的同步\n 最建議且最可靠的方式。這會先捨棄本機資料庫,再從遠端資料庫重設所有同步資訊。多數情況下都能安全執行,但會花上一些時間,且應在網路穩定時進行。\n- 解鎖遠端資料庫\n 只有在已透過其他複寫方式可靠同步的情況下才能使用此方式。這不只是指雙方擁有相同的檔案。如果你不確定,請避免使用。\n- 取消,稍後再確認\n 這會取消此操作,下次請求時會再次詢問。\n"},"Replicator.Dialogue.Locked.Message.Fetch":{def:"Fetch all has been scheduled. Plug-in will be restarted to perform it.",es:"Se ha programado la obtención completa. El complemento se reiniciará para llevarla a cabo.",fr:"Tout récupérer a été planifié. Le plug-in sera redémarré pour l'exécuter.",he:"משיכה מלאה תוזמנה. הפלאגין יופעל מחדש לביצועה.",ja:"全フェッチがスケジュールされました。プラグインは実行のために再起動されます。",ko:"모든 것 가져오기가 예약되었습니다. 이를 수행하기 위해 플러그인이 재시작됩니다.",ru:"Загрузка всего запланирована. Плагин будет перезапущен.",zh:"Fetch all has been scheduled. Plug-in will be restarted to perform it.","zh-tw":"已排定執行全部抓取。外掛將重新啟動以執行此作業。"},"Replicator.Dialogue.Locked.Message.Unlocked":{def:"The remote database has been unlocked. Please retry the operation.",es:"La base de datos remota se ha desbloqueado. Vuelve a intentar la operación.",fr:"La base distante a été déverrouillée. Veuillez réessayer l'opération.",he:"מסד הנתונים המרוחד בוטל נעילתו. אנא נסה שוב את הפעולה.",ja:"リモートデータベースのロックが解除されました。操作を再試行してください。",ko:"원격 데이터베이스 잠금이 해제되었습니다. 작업을 다시 시도해 주세요.",ru:"Удалённая база данных разблокирована. Повторите операцию.",zh:"The remote database has been unlocked. Please retry the operation.","zh-tw":"遠端資料庫已解鎖,請重試該操作。"},"Replicator.Dialogue.Locked.Title":{def:"Locked",es:"Bloqueada",fr:"Verrouillée",he:"נעול",ja:"ロック中",ko:"잠김",ru:"Заблокировано",zh:"Locked","zh-tw":"已鎖定"},"Replicator.Message.Cleaned":{def:"Database cleaning up is in process. replication has been cancelled",es:"Se está limpiando la base de datos; la replicación se ha cancelado",fr:"Nettoyage de la base en cours. La réplication a été annulée",he:"ניקוי מסד הנתונים בתהליך. השכפול בוטל",ja:"データベースのクリーナップ中です。レプリケーション(複製)はキャンセルされました。",ko:"데이터베이스 정리가 진행 중입니다. 복제가 취소되었습니다",ru:"Очистка базы данных в процессе. Репликация отменена",zh:"Database cleaning up is in process. replication has been cancelled","zh-tw":"資料庫正在清理中,複寫已取消"},"Replicator.Message.InitialiseFatalError":{def:"No replicator is available, this is the fatal error.",es:"No hay ningún replicador disponible; se trata de un error grave.",fr:"Aucun réplicateur disponible, il s'agit d'une erreur fatale.",he:"אין רפליקטור זמין, זוהי שגיאה קריטית.",ja:"レプリケーターが利用できません。これは致命的なエラーです。",ko:"사용 가능한 복제기가 없습니다. 치명적인 오류입니다.",ru:"Репликатор недоступен, это фатальная ошибка.",zh:"No replicator is available, this is the fatal error.","zh-tw":"沒有可用的複寫器,這是嚴重錯誤。"},"Replicator.Message.Pending":{def:"Some file events are pending. Replication has been cancelled.",es:"Hay eventos de archivo pendientes. La replicación se ha cancelado.",fr:"Des événements de fichier sont en attente. La réplication a été annulée.",he:"חלק מאירועי הקבצים ממתינים. השכפול בוטל.",ja:"ファイルイベントが保留中です。レプリケーション(複製)はキャンセルされました。",ko:"일부 파일 이벤트가 대기 중입니다. 복제가 취소되었습니다.",ru:"Некоторые события файлов ожидают. Репликация отменена.",zh:"Some file events are pending. Replication has been cancelled.","zh-tw":"有部分檔案事件尚待處理,複寫已取消。"},"Replicator.Message.SomeModuleFailed":{def:"Replication has been cancelled by some module failure",es:"La replicación se ha cancelado por el fallo de algún módulo",fr:"La réplication a été annulée suite à l'échec d'un module",he:"השכפול בוטל בשל כשל במודול",ja:"一部のモジュールの失敗によりレプリケーション(複製)がキャンセルされました。",ko:"일부 모듈 실패로 복제가 취소되었습니다",ru:"Репликация отменена из-за сбоя модуля",zh:"Replication has been cancelled by some module failure","zh-tw":"複寫因某個模組失敗而取消"},"Replicator.Message.VersionUpFlash":{def:"Remote synchronisation is paused for compatibility review. Run the 'Review why synchronisation is paused' command for details and available actions.",es:"Se ha detectado una actualización. Abre el diálogo de ajustes y consulta el registro de cambios. La replicación se ha cancelado.",fr:"Une mise à jour a été détectée. Veuillez ouvrir la boîte de dialogue des paramètres et consulter le journal des modifications. La réplication a été annulée.",he:"זוהה עדכון. אנא פתח את דיאלוג ההגדרות ובדוק את יומן השינויים. השכפול בוטל.",ja:"更新が検出されました。設定ダイアログを開いて変更ログを確認してください。レプリケーション(複製)はキャンセルされました。",ko:"업데이트가 감지되었습니다. 설정 대화 상자를 열어 변경 로그를 확인해 주세요. 복제가 취소되었습니다.",ru:"Обновление обнаружено. Откройте настройки и проверьте историю изменений.",zh:"An update has been detected. Please open the Settings dialogue and check the Change Log. Replication has been cancelled.","zh-tw":"偵測到更新。請開啟設定對話框並查看變更紀錄,複寫已取消。"},"Requires restart of Obsidian":{def:"Requires restart of Obsidian",es:"Requiere reiniciar Obsidian",fr:"Nécessite un redémarrage d'Obsidian",he:"דורש הפעלה מחדש של Obsidian",ja:"Obsidianの再起動が必要です",ko:"Obsidian 재시작 필요",ru:"Требуется перезапуск Obsidian",zh:"需要重启 Obsidian","zh-tw":"需要重新啟動 Obsidian"},"Requires restart of Obsidian.":{def:"Requires restart of Obsidian.",es:"Requiere reiniciar Obsidian",fr:"Nécessite un redémarrage d'Obsidian.",he:"דורש הפעלה מחדש של Obsidian.",ja:"Obsidianの再起動が必要です。",ko:"Obsidian 재시작이 필요합니다.",ru:"Требуется перезапуск Obsidian.",zh:"需要重启 Obsidian ","zh-tw":"需要重新啟動 Obsidian。"},"Rerun Onboarding Wizard":{def:"Rerun Onboarding Wizard",es:"Volver a ejecutar el asistente de configuración inicial",fr:"Relancer l'assistant d'intégration",he:"הרץ שוב את אשף ההכוונה",ja:"オンボーディングウィザードを再実行",ko:"온보딩 마법사 다시 실행",ru:"Перезапустить мастер настройки",zh:"重新运行引导向导","zh-tw":"重新執行導覽精靈"},"Rerun the onboarding wizard to set up Self-hosted LiveSync again.":{def:"Rerun the onboarding wizard to set up Self-hosted LiveSync again.",es:"Vuelve a ejecutar el asistente de configuración inicial para configurar Self-hosted LiveSync de nuevo.",fr:"Relancer l'assistant d'intégration pour reconfigurer Self-hosted LiveSync.",he:"הרץ שוב את אשף ההכוונה להגדרת Self-hosted LiveSync מחדש.",ja:"オンボーディングウィザードを再実行して、Self-hosted LiveSync をもう一度設定します。",ko:"온보딩 마법사를 다시 실행하여 Self-hosted LiveSync를 다시 설정합니다.",ru:"Перезапустить мастер настройки для повторной настройки Self-hosted LiveSync.",zh:"重新运行引导向导以再次设置 Self-hosted LiveSync。","zh-tw":"重新執行導覽精靈以再次設定 Self-hosted LiveSync。"},"Rerun Wizard":{def:"Rerun Wizard",es:"Volver a ejecutar el asistente",fr:"Relancer l'assistant",he:"הרץ שוב את האשף",ja:"ウィザードを再実行",ko:"마법사 다시 실행",ru:"Перезапустить мастер",zh:"重新运行向导","zh-tw":"重新執行精靈"},Resend:{def:"Resend",es:"Reenviar",ja:"再送信",ko:"다시 보내기",ru:"Повторно отправить",zh:"重新发送","zh-tw":"重新傳送"},"Resend all chunks to the remote.":{def:"Resend all chunks to the remote.",es:"Reenvía todos los chunks al remoto.",ja:"すべてのチャンクをリモートへ再送信します。",ko:"모든 청크를 원격으로 다시 보냅니다.",ru:"Повторно отправить все чанки в удалённое хранилище.",zh:"将所有 chunks 重新发送到远端。","zh-tw":"將所有 chunks 重新傳送到遠端。"},Reset:{def:"Reset",es:"Restablecer",ja:"リセット",ko:"재설정",ru:"Сброс",zh:"重置","zh-tw":"重設"},"Reset all":{def:"Reset all",es:"Restablecer todo",ja:"すべてリセット",ko:"모두 재설정",ru:"Сбросить всё",zh:"全部重置","zh-tw":"全部重設"},"Reset all journal counter":{def:"Reset all journal counter",es:"Restablecer todos los contadores del diario",ja:"すべてのジャーナルカウンターをリセット",ko:"모든 저널 카운터 재설정",ru:"Сбросить все счётчики журнала",zh:"重置所有日志计数器","zh-tw":"重設所有日誌計數器"},"Reset and Resume Synchronisation":{def:"Reset and Resume Synchronisation",es:"Restablecer y reanudar la sincronización",ko:"동기화 초기화 후 재개","zh-tw":"重設並恢復同步"},"Reset journal received history":{def:"Reset journal received history",es:"Restablecer historial de recepción del diario",ja:"ジャーナル受信履歴をリセット",ko:"저널 수신 기록 재설정",ru:"Сбросить историю полученных записей журнала",zh:"重置日志接收历史","zh-tw":"重設日誌接收歷史"},"Reset journal sent history":{def:"Reset journal sent history",es:"Restablecer historial de envío del diario",ja:"ジャーナル送信履歴をリセット",ko:"저널 송신 기록 재설정",ru:"Сбросить историю отправленных записей журнала",zh:"重置日志发送历史","zh-tw":"重設日誌傳送歷史"},"Reset notification threshold and check the remote database usage":{def:"Reset notification threshold and check the remote database usage",es:"Restablecer el umbral de aviso y comprobar el uso de la base de datos remota",fr:"Réinitialiser le seuil de notification et vérifier l'utilisation de la base distante",he:"אפס סף התראה ובדוק שימוש במסד הנתונים המרוחד",ja:"通知しきい値をリセットしてリモートデータベース使用量を確認",ko:"알림 임계값을 초기화하고 원격 데이터베이스 사용량 확인",ru:"Сбросить порог уведомления и проверить использование удалённой базы данных",zh:"重置通知阈值并检查远程数据库使用情况","zh-tw":"重設通知閾值並檢查遠端資料庫使用情況"},"Reset received":{def:"Reset received",es:"Restablecer recepción",ja:"受信履歴をリセット",ko:"수신 기록 재설정",ru:"Сбросить полученные",zh:"重置接收记录","zh-tw":"重設接收紀錄"},"Reset sent history":{def:"Reset sent history",es:"Restablecer historial de envío",ja:"送信履歴をリセット",ko:"송신 기록 재설정",ru:"Сбросить историю отправки",zh:"重置发送历史","zh-tw":"重設傳送歷史"},"Reset Synchronisation information":{def:"Reset Synchronisation information",es:"Restablecer información de sincronización",ja:"同期情報をリセット",ko:"동기화 정보 재설정",ru:"Сбросить информацию о синхронизации",zh:"重置同步信息","zh-tw":"重設同步資訊"},"Reset Synchronisation on This Device":{def:"Reset Synchronisation on This Device",es:"Restablecer sincronización en este dispositivo",ja:"このデバイスの同期状態をリセット",ko:"이 기기의 동기화 재설정",ru:"Сбросить синхронизацию на этом устройстве",zh:"重置此设备上的同步","zh-tw":"重設此裝置上的同步"},"Reset the remote storage size threshold and check the remote storage size again.":{def:"Reset the remote storage size threshold and check the remote storage size again.",es:"Restablece el umbral de tamaño del almacenamiento remoto y vuelve a comprobar su tamaño.",fr:"Réinitialiser le seuil de taille du stockage distant et vérifier à nouveau la taille du stockage distant.",he:"אפס את סף גודל האחסון המרוחד ובדוק שוב את גודל האחסון המרוחד.",ja:"リモートストレージ容量のしきい値をリセットし、リモートストレージ容量を再確認します。",ko:"원격 저장소 크기 임계값을 초기화하고 원격 저장소 크기를 다시 확인합니다.",ru:"Сбросить порог размера удалённого хранилища и проверить размер хранилища снова.",zh:"重置远程存储大小阈值并再次检查远程存储大小。","zh-tw":"重設遠端儲存空間大小閾值,並再次檢查遠端儲存空間大小。"},"Resolve All":{def:"Resolve All",es:"Resolver todo",ja:"すべて解決",ko:"모두 해결",ru:"Разрешить всё",zh:"全部处理","zh-tw":"全部處理"},"Resolve all conflicted files":{def:"Resolve all conflicted files",es:"Resolver todos los archivos en conflicto",ja:"競合しているすべてのファイルを解決",ko:"충돌한 모든 파일 해결",ru:"Разрешить все конфликтующие файлы",zh:"解决所有冲突文件","zh-tw":"解決所有衝突檔案"},"Resolve All conflicted files by the newer one":{def:"Resolve All conflicted files by the newer one",es:"Resolver todos los archivos en conflicto con la versión más reciente",ja:"競合したすべてのファイルを新しい方で解決",ko:"충돌한 모든 파일을 최신 버전으로 해결",ru:"Разрешить все конфликтующие файлы в пользу более новой версии",zh:"将所有冲突文件解析为较新的版本","zh-tw":"將所有衝突檔案統一為較新的版本"},"Resolve all conflicted files by the newer one. Caution: This will overwrite the older one, and cannot resurrect the overwritten one.":{def:"Resolve all conflicted files by the newer one. Caution: This will overwrite the older one, and cannot resurrect the overwritten one.",es:"Resuelve todos los archivos en conflicto conservando la versión más reciente. Precaución: esto sobrescribirá la versión anterior y no podrá recuperarse.",ja:"競合しているすべてのファイルを新しい方の内容で解決します。注意:古い方は上書きされ、復元できません。",ko:"충돌한 모든 파일을 더 최신 버전으로 해결합니다. 주의: 이전 버전은 덮어써지며 복원할 수 없습니다.",ru:"Разрешает все конфликтующие файлы в пользу более новой версии. Внимание: старая версия будет перезаписана и её нельзя будет восстановить.",zh:"将所有冲突文件统一保留较新的版本。注意:这会覆盖较旧的版本,且被覆盖的内容无法恢复。","zh-tw":"將所有衝突檔案統一保留較新的版本。注意:這會覆寫較舊的版本,且被覆寫的內容無法復原。"},"Restart and Fetch Data":{def:"Restart and Fetch Data",es:"Reiniciar y obtener los datos",ko:"재시작 후 데이터 가져오기","zh-tw":"重新啟動並擷取資料"},"Restart and Initialise Server":{def:"Restart and Initialise Server",es:"Reiniciar e inicializar el servidor",ko:"재시작 후 서버 초기화","zh-tw":"重新啟動並初始化伺服器"},"Restart Now":{def:"Restart Now",es:"Reiniciar ahora",ja:"今すぐ再起動",ko:"지금 재시작",ru:"Перезапустить сейчас",zh:"立即重启","zh-tw":"立即重新啟動"},"Restarting Obsidian is strongly recommended. Until restart, some changes may not take effect, and display may be inconsistent. Are you sure to restart now?":{def:"Restarting Obsidian is strongly recommended. Until restart, some changes may not take effect, and display may be inconsistent. Are you sure to restart now?",es:"Se recomienda encarecidamente reiniciar Obsidian. Hasta que lo hagas, puede que algunos cambios no surtan efecto y que la interfaz se muestre de forma inconsistente. ¿Seguro que quieres reiniciar ahora?",ko:"Obsidian을 재시작하는 것을 강력히 권장합니다. 재시작하기 전까지는 일부 변경 사항이 적용되지 않거나 화면이 일관되지 않게 표시될 수 있습니다. 지금 재시작하시겠습니까?","zh-tw":"強烈建議重新啟動 Obsidian。在重新啟動之前,部分變更可能尚未生效,顯示也可能不一致。你確定要現在重新啟動嗎?"},"Restore or reconstruct local database from remote.":{def:"Restore or reconstruct local database from remote.",es:"Restaura o reconstruye la base de datos local desde el remoto.",ja:"リモートからローカルデータベースを復元または再構築します。",ko:"원격에서 로컬 데이터베이스를 복원하거나 재구축합니다.",ru:"Восстановить или перестроить локальную базу данных из удалённой.",zh:"从远端恢复或重建本地数据库。","zh-tw":"從遠端還原或重建本機資料庫。"},Rev:{def:"Rev",es:"Rev",ko:"리비전","zh-tw":"版本"},"Revert changes":{def:"Revert changes",es:"Revertir cambios",ko:"변경 사항 되돌리기","zh-tw":"還原變更"},Revoke:{def:"Revoke",es:"Revocar",ko:"철회","zh-tw":"撤銷"},"Room ID":{def:"Room ID",es:"ID de sala",ko:"룸 ID","zh-tw":"房間 ID"},"Room ID suffix:":{def:"Room ID suffix:",es:"Sufijo del ID de sala:",ko:"룸 ID 접미사:","zh-tw":"房間 ID 後綴:"},"Run Doctor":{def:"Run Doctor",es:"Ejecutar el Doctor",fr:"Lancer le Docteur",he:"הפעל Doctor",ja:"診断を実行",ko:"진단 실행",ru:"Запустить диагностику",zh:"立即诊断","zh-tw":"執行診斷"},"S3/MinIO/R2 Configuration":{def:"S3/MinIO/R2 Configuration",es:"Configuración de S3/MinIO/R2",ko:"S3/MinIO/R2 구성","zh-tw":"S3/MinIO/R2 設定"},"S3/MinIO/R2 Object Storage":{def:"S3/MinIO/R2 Object Storage",es:"Almacenamiento de objetos S3/MinIO/R2",ja:"S3/MinIO/R2 オブジェクトストレージ",ko:"S3/MinIO/R2 객체 스토리지",ru:"Объектное хранилище S3/MinIO/R2",zh:"S3/MinIO/R2 对象存储","zh-tw":"S3/MinIO/R2 物件儲存"},Same:{def:"Same",es:"Igual",ko:"동일","zh-tw":"相同"},"Same or local only":{def:"Same or local only",es:"Igual o solo local",ko:"동일하거나 로컬에만 있음","zh-tw":"相同或僅本機有"},"Save and Apply":{def:"Save and Apply",es:"Guardar y aplicar",ko:"저장 후 적용","zh-tw":"儲存並套用"},"Save settings to a markdown file. You will be notified when new settings arrive. You can set different files by the platform.":{def:"Save settings to a markdown file. You will be notified when new settings arrive. You can set different files by the platform.",es:"Guardar configuración en archivo markdown. Se notificarán nuevos ajustes. Puede definir diferentes archivos por plataforma",fr:"Enregistrer les paramètres dans un fichier markdown. Vous serez notifié à l'arrivée de nouveaux paramètres. Vous pouvez définir des fichiers différents selon la plateforme.",he:"שמור הגדרות לקובץ Markdown. תיודע כשהגדרות חדשות יגיעו. ניתן להגדיר קבצים שונים לפי פלטפורמה.",ja:"Markdownファイルに設定を保存します。新しい設定が到着すると通知されます。プラットフォームごとに異なるファイルを設定できます。",ko:"설정을 마크다운 파일에 저장합니다. 새로운 설정이 도착하면 알림을 받게 됩니다. 플랫폼별로 다른 파일을 설정할 수 있습니다.",ru:"Save settings to a markdown file. You will be notified when new settings arrive. You can set different files by the platform.",zh:"将设置保存到一个 Markdown 文件中。当新设置到达时,您将收到通知。您可以根据平台设置不同的文件 ","zh-tw":"將設定儲存到 Markdown 檔案中。有新設定送達時會通知你,可依平台設定不同的檔案。"},"Saving will be performed forcefully after this number of seconds.":{def:"Saving will be performed forcefully after this number of seconds.",es:"Guardado forzado tras esta cantidad de segundos",fr:"L'enregistrement sera forcé au bout de ce nombre de secondes.",he:"השמירה תתבצע בכפייה לאחר מספר שניות זה.",ja:"この秒数後に強制的に保存されます。",ko:"이 시간(초) 후에 강제로 저장이 수행됩니다.",ru:"Сохранение будет принудительно выполнено после этого количества секунд.",zh:"在此秒数后将强制执行保存 ","zh-tw":"經過這個秒數後,會強制執行儲存。"},"Scan a QR Code (Recommended for mobile)":{def:"Scan a QR Code (Recommended for mobile)",es:"Escanear un código QR (recomendado para móviles)",ja:"QR コードをスキャンする(モバイル推奨)",ko:"QR 코드 스캔(모바일 권장)",ru:"Сканировать QR-код (рекомендуется для мобильных устройств)",zh:"扫描二维码(移动端推荐)","zh-tw":"掃描 QR Code(行動裝置推薦)"},"Scan changes":{def:"Scan changes",es:"Buscar cambios",ko:"변경 사항 검사","zh-tw":"掃描變更"},"Scan changes on customization sync":{def:"Scan changes on customization sync",es:"Escanear cambios en sincronización de personalización",fr:"Analyser les modifications de synchronisation de personnalisation",he:"סרוק שינויים בסנכרון התאמה אישית",ja:"カスタマイズされた同期時に、変更をスキャンする",ko:"사용자 설정 동기화 시 변경 사항 검색",ru:"Сканировать изменения при синхронизации настроек",zh:"在自定义同步时扫描更改","zh-tw":"在自訂同步時掃描變更"},"Scan customization automatically":{def:"Scan customization automatically",es:"Escanear personalización automáticamente",fr:"Analyser automatiquement la personnalisation",he:"סרוק התאמה אישית אוטומטית",ja:"自動的にカスタマイズをスキャン",ko:"사용자 설정 자동 검색",ru:"Сканировать настройки автоматически",zh:"自动扫描自定义设置","zh-tw":"自動掃描自訂內容"},"Scan customization before replicating.":{def:"Scan customization before replicating.",es:"Escanear personalización antes de replicar",fr:"Analyser la personnalisation avant de répliquer.",he:"סרוק התאמה אישית לפני שכפול.",ja:"レプリケーション(複製)前に、カスタマイズをスキャン",ko:"복제하기 전에 사용자 설정을 검색합니다.",ru:"Сканировать настройки перед репликацией.",zh:"在复制前扫描自定义设置 ","zh-tw":"複寫前掃描自訂內容。"},"Scan customization every 1 minute.":{def:"Scan customization every 1 minute.",es:"Escanear personalización cada 1 minuto",fr:"Analyser la personnalisation toutes les 1 minute.",he:"סרוק התאמה אישית כל דקה.",ja:"カスタマイズのスキャンを1分ごとに行う",ko:"1분마다 사용자 설정을 검색합니다.",ru:"Сканировать настройки каждую минуту.",zh:"每1分钟扫描自定义设置 ","zh-tw":"每 1 分鐘掃描自訂內容。"},"Scan customization periodically":{def:"Scan customization periodically",es:"Escanear personalización periódicamente",fr:"Analyser la personnalisation périodiquement",he:"סרוק התאמה אישית תקופתית",ja:"定期的にカスタマイズをスキャン",ko:"주기적으로 사용자 설정 검색",ru:"Сканировать настройки периодически",zh:"定期扫描自定义设置","zh-tw":"定期掃描自訂內容"},"Scan for Broken files":{def:"Scan for Broken files",es:"Buscar archivos dañados",ja:"破損ファイルをスキャン",ko:"손상된 파일 검사",zh:"扫描损坏文件","zh-tw":"掃描損壞檔案"},"Scan for hidden files before replication":{def:"Scan for hidden files before replication",es:"Escanear archivos ocultos antes de replicar",fr:"Analyser les fichiers cachés avant réplication",he:"סרוק קבצים נסתרים לפני שכפול",ja:"レプリケーション(複製)開始前に、隠しファイルのスキャンを行う",ko:"복제 전 숨김 파일 검사",ru:"Сканировать скрытые файлы перед репликацией",zh:"复制前扫描隐藏文件","zh-tw":"複寫前掃描隱藏檔案"},"Scan hidden files periodically":{def:"Scan hidden files periodically",es:"Escanear archivos ocultos periódicamente",fr:"Analyser les fichiers cachés périodiquement",he:"סרוק קבצים נסתרים תקופתית",ja:"定期的に隠しファイルのスキャンを行う",ko:"주기적으로 숨김 파일 검사",ru:"Сканировать скрытые файлы периодически",zh:"定期扫描隐藏文件","zh-tw":"定期掃描隱藏檔案"},"Scan QR Code":{def:"Scan QR Code",es:"Escanear código QR",ko:"QR 코드 스캔","zh-tw":"掃描 QR 碼"},"Scan the QR code displayed on an active device using this device's camera.":{def:"Scan the QR code displayed on an active device using this device's camera.",es:"Escanee con la cámara de este dispositivo el código QR mostrado en un dispositivo activo。",ja:"稼働中の端末に表示された QR コードを、この端末のカメラで読み取ってください。",ko:"이 기기의 카메라로 사용 중인 기기에 표시된 QR 코드를 스캔하세요.",ru:"Отсканируйте QR-код, показанный на активном устройстве, с помощью камеры этого устройства。",zh:"使用当前设备的摄像头扫描另一台已在使用设备上显示的二维码。","zh-tw":"使用目前裝置的相機掃描另一台已在使用裝置上顯示的 QR Code。"},"Schedule and Restart":{def:"Schedule and Restart",es:"Programar y reiniciar",ja:"予約して再起動",ko:"예약 후 재시작",ru:"Запланировать и перезапустить",zh:"安排并重启","zh-tw":"排程後重新啟動"},"Scram Switches":{def:"Scram Switches",es:"Interruptores de emergencia",ja:"緊急対応スイッチ",ko:"긴급 정지 스위치",zh:"紧急开关","zh-tw":"緊急處置開關"},"Scram!":{def:"Scram!",es:"Medidas de emergencia",ja:"緊急停止",ko:"긴급 정지",ru:"Экстренные меры",zh:"紧急处置","zh-tw":"緊急處置"},"Seconds, 0 to disable":{def:"Seconds, 0 to disable",es:"Segundos, 0 para desactivar",fr:"Secondes, 0 pour désactiver",he:"שניות, 0 לביטול",ja:"秒数、0で無効",ko:"초 단위, 0으로 설정하면 비활성화",ru:"Секунд, 0 для отключения",zh:"秒,0为禁用","zh-tw":"秒,0 表示停用"},"Seconds. Saving to the local database will be delayed until this value after we stop typing or saving.":{def:"Seconds. Saving to the local database will be delayed until this value after we stop typing or saving.",es:"Segundos. Guardado en BD local se retrasará hasta este valor tras dejar de escribir/guardar",fr:"Secondes. L'enregistrement dans la base locale sera différé de cette valeur après l'arrêt de la frappe ou de l'enregistrement.",he:"שניות. השמירה למסד הנתונים המקומי תתעכב בערך זה לאחר הפסקת הקלדה או שמירה.",ja:"秒。入力や保存を停止してからこの値の間、ローカルデータベースへの保存が遅延されます。",ko:"초 단위입니다. 타이핑이나 저장을 중단한 후 이 시간동안 로컬 데이터베이스 저장이 지연됩니다.",ru:"Секунды. Сохранение в локальную базу данных будет отложено.",zh:"秒。在我们停止输入或保存后,保存到本地数据库将延迟此值 ","zh-tw":"秒。停止輸入或儲存後,寫入本機資料庫的動作會延遲這個秒數。"},"Secret Access Key":{def:"Secret Access Key",es:"Clave de acceso secreta",ko:"시크릿 액세스 키","zh-tw":"Secret Access Key"},"Secret Key":{def:"Secret Key",es:"Clave secreta",fr:"Clé secrète",he:"מפתח סודי",ja:"シークレットキー",ko:"시크릿 키",ru:"Секретный ключ",zh:"Secret Key","zh-tw":"Secret Key"},"Select active P2P remote":{def:"Select active P2P remote",es:"Seleccionar el remoto P2P activo",ko:"활성 P2P 원격 선택","zh-tw":"選擇啟用中的 P2P 遠端"},"Select All Shiny":{def:"Select All Shiny",es:"Seleccionar todo lo nuevo",ko:"새 항목 모두 선택","zh-tw":"全選最新項目"},"Select Flagged Shiny":{def:"Select Flagged Shiny",es:"Seleccionar lo nuevo marcado",ko:"플래그된 새 항목 선택","zh-tw":"全選已標記的最新項目"},"Select P2P remote...":{def:"Select P2P remote...",es:"Seleccionar remoto P2P...",ko:"P2P 원격 선택...","zh-tw":"選擇 P2P 遠端⋯"},"Select the database adapter to use.":{def:"Select the database adapter to use.",es:"Selecciona el adaptador de base de datos que se usará.",ja:"使用するデータベースアダプターを選択します。",ko:"사용할 데이터베이스 어댑터를 선택합니다.",ru:"Выберите используемый адаптер базы данных.",zh:"选择要使用的数据库适配器。","zh-tw":"選擇要使用的資料庫轉接器。"},"Selecting this option will result in the current data on this device being used to initialise the server. Any existing data on the server will be completely overwritten.":{def:"Selecting this option will result in the current data on this device being used to initialise the server. Any existing data on the server will be completely overwritten.",es:"Al elegir esta opción, los datos actuales de este dispositivo se usarán para inicializar el servidor. Cualquier dato existente en el servidor se sobrescribirá por completo.",ko:"이 옵션을 선택하면 이 기기의 현재 데이터로 서버를 초기화합니다. 서버에 있는 기존 데이터는 모두 완전히 덮어써집니다.","zh-tw":"選擇此選項會使用此裝置目前的資料來初始化伺服器,伺服器上任何現有資料都會被完全覆寫。"},"Selecting this option will result in this device joining the existing server. You need to fetching the existing synchronisation data from the server to this device.":{def:"Selecting this option will result in this device joining the existing server. You need to fetching the existing synchronisation data from the server to this device.",es:"Al elegir esta opción, este dispositivo se unirá al servidor existente. Tendrás que obtener del servidor los datos de sincronización ya existentes.",ko:"이 옵션을 선택하면 이 기기가 기존 서버에 참여합니다. 서버에 있는 기존 동기화 데이터를 이 기기로 가져와야 합니다.","zh-tw":"選擇此選項會讓此裝置加入現有的伺服器,你需要將伺服器上現有的同步資料擷取到此裝置。"},Selective:{def:"Selective",es:"Selectivo",ko:"선택적","zh-tw":"選擇性"},Send:{def:"Send",es:"Enviar",ja:"送信",ko:"보내기",ru:"Отправить",zh:"发送","zh-tw":"傳送"},"Send chunks":{def:"Send chunks",es:"Enviar chunks",ja:"チャンクを送信",ko:"청크 보내기",ru:"Отправить чанки",zh:"发送 chunks","zh-tw":"傳送 chunks"},SENDING:{def:"SENDING",es:"ENVIANDO",ko:"전송 중","zh-tw":"傳送中"},"Server URI":{def:"Server URI",es:"URI del servidor",fr:"URI du serveur",he:"כתובת שרת (URI)",ja:"URI",ko:"서버 URI",ru:"URI сервера",zh:"服务器 URI","zh-tw":"伺服器 URI"},SESSION:{def:"SESSION",es:"SESIÓN",ko:"세션","zh-tw":"本次連線"},"Setting.GenerateKeyPair.Desc":{def:'We have generated a key pair!\n\nNote: This key pair will never be shown again. Please save it in a safe place. If you have lost it, you need to generate a new key pair.\nNote 2: The public key is in spki format, and the Private key is in pkcs8 format. For the sake of convenience, newlines are converted to `\\n` in public key.\nNote 3: The public key should be configured in the remote database, and the private key should be configured in local devices.\n\n>[!FOR YOUR EYES ONLY]-\n> <div class="sls-keypair">\n>\n> ### Public Key\n> ```\n${public_key}\n> ```\n>\n> ### Private Key\n> ```\n${private_key}\n> ```\n>\n> </div>\n\n>[!Both for copying]-\n>\n> <div class="sls-keypair">\n>\n> ```\n${public_key}\n${private_key}\n> ```\n>\n> </div>\n\n',es:'Hemos generado un par de claves.\n\nNota: Este par de claves no volverá a mostrarse. Guárdalo en un lugar seguro. Si lo pierdes, tendrás que generar uno nuevo.\nNota 2: La clave pública está en formato spki y la clave privada en formato pkcs8. Para mayor comodidad, los saltos de línea de la clave pública se convierten en `\\n`.\nNota 3: La clave pública debe configurarse en la base de datos remota y la clave privada en los dispositivos locales.\n\n>[!SOLO PARA TUS OJOS]-\n> <div class="sls-keypair">\n>\n> ### Clave pública\n> ```\n${public_key}\n> ```\n>\n> ### Clave privada\n> ```\n${private_key}\n> ```\n>\n> </div>\n\n>[!Ambas para copiar]-\n>\n> <div class="sls-keypair">\n>\n> ```\n${public_key}\n${private_key}\n> ```\n>\n> </div>',fr:'Nous avons généré une paire de clés !\n\nNote : cette paire de clés ne sera plus jamais affichée. Veuillez la conserver dans un endroit sûr. Si vous la perdez, vous devrez générer une nouvelle paire.\nNote 2 : la clé publique est au format spki, et la clé privée au format pkcs8. Pour plus de commodité, les retours à la ligne sont convertis en `\\n` dans la clé publique.\nNote 3 : la clé publique doit être configurée dans la base distante, et la clé privée sur les appareils locaux.\n\n>[!POUR VOS YEUX SEULEMENT]-\n> <div class="sls-keypair">\n>\n> ### Clé publique\n> ```\n${public_key}\n> ```\n>\n> ### Clé privée\n> ```\n${private_key}\n> ```\n>\n> </div>\n\n>[!Les deux pour copier]-\n>\n> <div class="sls-keypair">\n>\n> ```\n${public_key}\n${private_key}\n> ```\n>\n> </div>\n\n',he:'יצרנו זוג מפתחות!\n\nהערה: זוג מפתחות זה לא יוצג שוב. אנא שמור אותו במקום בטוח. אם אבד לך, יהיה צורך לייצר זוג מפתחות חדש.\nהערה 2: המפתח הציבורי הוא בפורמט spki, והמפתח הפרטי הוא בפורמט pkcs8. לנוחות, שורות חדשות ממוירות ל-`\\n` במפתח הציבורי.\nהערה 3: יש להגדיר את המפתח הציבורי במסד הנתונים המרוחד, ואת המפתח הפרטי במכשירים המקומיים.\n\n>[!FOR YOUR EYES ONLY]-\n> <div class="sls-keypair">\n>\n> ### מפתח ציבורי\n> ```\n${public_key}\n> ```\n>\n> ### מפתח פרטי\n> ```\n${private_key}\n> ```\n>\n> </div>\n\n>[!Both for copying]-\n>\n> <div class="sls-keypair">\n>\n> ```\n${public_key}\n${private_key}\n> ```\n>\n> </div>\n\n',ja:'キーペアを生成しました!\n\n注意: このキーペアは再度表示されません。安全な場所に保存してください。紛失した場合は、新しいキーペアを生成する必要があります。\n注意2: 公開鍵はspki形式、秘密鍵はpkcs8形式です。利便性のため、公開鍵の改行は`\\n`に変換されています。\n注意3: 公開鍵はリモートデータベースに、秘密鍵はローカルデバイスに設定してください。\n\n>[!FOR YOUR EYES ONLY]-\n> <div class="sls-keypair">\n>\n> ### 公開鍵\n> ```\n${public_key}\n> ```\n>\n> ### 秘密鍵\n> ```\n${private_key}\n> ```\n>\n> </div>\n\n>[!Both for copying]-\n>\n> <div class="sls-keypair">\n>\n> ```\n${public_key}\n${private_key}\n> ```\n>\n> </div>\n\n',ko:'키 페어를 생성했습니다!\n\n참고: 이 키 페어는 다시 표시되지 않습니다. 안전한 곳에 저장해 주세요. 분실하면 새 키 페어를 생성해야 합니다.\n참고 2: 공개 키는 spki 형식이고, 개인 키는 pkcs8 형식입니다. 편의를 위해 공개 키의 줄 바꿈은 `\\n`으로 변환됩니다.\n참고 3: 공개 키는 원격 데이터베이스에, 개인 키는 로컬 기기에 설정해야 합니다.\n\n>[!FOR YOUR EYES ONLY]-\n> <div class="sls-keypair">\n>\n> ### 공개 키\n> ```\n${public_key}\n> ```\n>\n> ### 개인 키\n> ```\n${private_key}\n> ```\n>\n> </div>\n\n>[!Both for copying]-\n>\n> <div class="sls-keypair">\n>\n> ```\n${public_key}\n${private_key}\n> ```\n>\n> </div>\n\n',ru:"Мы сгенерировали пару ключей!",zh:'我们已经生成了一组密钥对!\n\n注意:这组密钥对之后将不会再次显示。请务必妥善保管;如果丢失,你需要重新生成新的密钥对。\n注意 2:公钥采用 spki 格式,私钥采用 pkcs8 格式。为方便复制,公钥中的换行会被转换为 `\\n`。\n注意 3:公钥应配置在远端数据库中,私钥应配置在本地设备上。\n\n>[!仅限本人查看]-\n> <div class="sls-keypair">\n>\n> ### 公钥\n> ```\n${public_key}\n> ```\n>\n> ### 私钥\n> ```\n${private_key}\n> ```\n>\n> </div>\n\n>[!整段复制]-\n>\n> <div class="sls-keypair">\n>\n> ```\n${public_key}\n${private_key}\n> ```\n>\n> </div>',"zh-tw":'我們已產生新的金鑰對!\n\n注意:此金鑰對之後將不會再次顯示。請務必妥善保存;若遺失,必須重新產生新的金鑰對。\n注意 2:公鑰採用 spki 格式,私鑰採用 pkcs8 格式。為了方便複製,公鑰中的換行會轉換為 `\\n`。\n注意 3:公鑰應設定在遠端資料庫中,私鑰則應設定在本機裝置上。\n\n>[!僅供本人查看]-\n> <div class="sls-keypair">\n>\n> ### 公鑰\n> ```\n${public_key}\n> ```\n>\n> ### 私鑰\n> ```\n${private_key}\n> ```\n>\n> </div>\n\n>[!便於整段複製]-\n>\n> <div class="sls-keypair">\n>\n> ```\n${public_key}\n${private_key}\n> ```\n>\n> </div>'},"Setting.GenerateKeyPair.Title":{def:"New key pair has been generated!",es:"¡Se ha generado un nuevo par de claves!",fr:"Une nouvelle paire de clés a été générée !",he:"זוג מפתחות חדש נוצר!",ja:"新しいキーペアが生成されました!",ko:"새 키 페어가 생성되었습니다!",ru:"Новая пара ключей сгенерирована!",zh:"已生成新的密钥对!","zh-tw":"已產生新的金鑰對!"},"Setting.TroubleShooting":{def:"TroubleShooting",es:"Resolución de problemas",fr:"Dépannage",he:"פתרון בעיות",ja:"トラブルシューティング",ko:"문제 해결",ru:"Устранение неполадок",zh:"故障排除","zh-tw":"疑難排解"},"Setting.TroubleShooting.Doctor":{def:"Setting Doctor",es:"Doctor de ajustes",fr:"Docteur des paramètres",he:"Doctor הגדרות",ja:"設定診断ツール",ko:"설정 진단 마법사",ru:"Диагностика настроек",zh:"设置诊断","zh-tw":"設定診斷"},"Setting.TroubleShooting.Doctor.Desc":{def:"Detects non optimal settings. (Same as during migration)",es:"Detecta ajustes no óptimos. (Igual que durante la migración)",fr:"Détecte les paramètres non optimaux. (Identique à la migration)",he:"מזהה הגדרות לא אופטימליות. (זהה לפעולה במהלך הגירה)",ja:"最適でない設定を検出します。(マイグレーション時と同じ)",ko:"최적화되지 않은 설정을 감지합니다. (데이터 구조 전환 시와 동일)",ru:"Обнаруживает неоптимальные настройки.",zh:"检测系统中不合理的设置。(与迁移期间逻辑相同)","zh-tw":"偵測不理想的設定。(與遷移期間相同)"},"Setting.TroubleShooting.ScanBrokenFiles":{def:"Scan for broken files",es:"Buscar archivos dañados",fr:"Analyser les fichiers corrompus",he:"סרוק קבצים פגומים",ja:"破損ファイルのスキャン",ko:"손상된 파일 검사",ru:"Сканировать повреждённые файлы",zh:"扫描损坏或异常的文件","zh-tw":"掃描損壞檔案"},"Setting.TroubleShooting.ScanBrokenFiles.Desc":{def:"Scans for files that are not stored correctly in the database.",es:"Busca archivos que no se hayan guardado correctamente en la base de datos.",fr:"Analyse les fichiers qui ne sont pas stockés correctement dans la base.",he:"סורק קבצים שלא נשמרו כהלכה במסד הנתונים.",ja:"データベースに正しく保存されていないファイルをスキャンします。",ko:"데이터베이스에 올바르게 저장되지 않은 파일을 검사합니다.",ru:"Сканирует файлы, которые неправильно хранятся в базе данных.",zh:"扫描数据库中未正确存储的文件。","zh-tw":"掃描未正確儲存在資料庫中的檔案。"},"SettingTab.Message.AskRebuild":{def:"Your changes require fetching from the remote database. Do you want to proceed?",es:"Tus cambios requieren obtener los datos de la base de datos remota. ¿Quieres continuar?",fr:"Vos modifications nécessitent une récupération depuis la base distante. Voulez-vous continuer ?",he:"השינויים שלך מצריכים משיכה ממסד הנתונים המרוחד. האם להמשיך?",ja:"変更にはリモートデータベースからのフェッチが必要です。続行しますか?",ko:"변경 사항을 적용하려면 원격 데이터베이스에서 가져와야 합니다. 계속 진행하시겠습니까?",ru:"Ваши изменения требуют загрузки из удалённой базы данных. Хотите продолжить?",zh:"Your changes require fetching from the remote database. Do you want to proceed?","zh-tw":"你的變更需要從遠端資料庫抓取,要繼續嗎?"},"Setup Complete: Preparing to Fetch Synchronisation Data":{def:"Setup Complete: Preparing to Fetch Synchronisation Data",es:"Configuración completada: preparando la obtención de los datos de sincronización",ko:"설정 완료: 동기화 데이터를 가져올 준비 중","zh-tw":"設定完成:準備擷取同步資料"},"Setup Complete: Preparing to Initialise Server":{def:"Setup Complete: Preparing to Initialise Server",es:"Configuración completada: preparando la inicialización del servidor",ko:"설정 완료: 서버를 초기화할 준비 중","zh-tw":"設定完成:準備初始化伺服器"},"Setup URI dialog cancelled.":{def:"Setup URI dialog cancelled.",es:"Se ha cancelado el diálogo del Setup URI.",ja:"Setup URI ダイアログはキャンセルされました。",ko:"Setup URI 대화 상자가 취소되었습니다.",ru:"Диалог Setup URI был отменён.",zh:"Setup URI 对话框已取消。","zh-tw":"Setup URI 對話框已取消。"},"Setup-URI":{def:"Setup-URI",es:"Setup-URI",ko:"Setup-URI","zh-tw":"Setup URI"},"Setup.Apply.Buttons.ApplyAndFetch":{def:"Apply and Fetch",es:"Aplicar y obtener",fr:"Appliquer et récupérer",he:"החל ומשוך",ja:"適用してフェッチ",ko:"적용 후 가져오기",ru:"Применить и загрузить",zh:"Apply and Fetch","zh-tw":"套用並抓取"},"Setup.Apply.Buttons.ApplyAndMerge":{def:"Apply and Merge",es:"Aplicar y combinar",fr:"Appliquer et fusionner",he:"החל ומזג",ja:"適用してマージ",ko:"적용 후 병합",ru:"Применить и объединить",zh:"Apply and Merge","zh-tw":"套用並合併"},"Setup.Apply.Buttons.ApplyAndRebuild":{def:"Apply and Rebuild",es:"Aplicar y reconstruir",fr:"Appliquer et reconstruire",he:"החל ובנה מחדש",ja:"適用して再構築",ko:"적용 후 재구축",ru:"Применить и перестроить",zh:"Apply and Rebuild","zh-tw":"套用並重建"},"Setup.Apply.Buttons.Cancel":{def:"Discard and Cancel",es:"Descartar y cancelar",fr:"Abandonner et annuler",he:"בטל ובטל",ja:"破棄してキャンセル",ko:"폐기하고 취소",ru:"Отменить и отменить",zh:"Discard and Cancel","zh-tw":"捨棄並取消"},"Setup.Apply.Buttons.OnlyApply":{def:"Only Apply",es:"Solo aplicar",fr:"Appliquer seulement",he:"החל בלבד",ja:"適用のみ",ko:"적용만 하기",ru:"Только применить",zh:"Only Apply","zh-tw":"僅套用"},"Setup.Apply.Message":{def:"The new configuration is ready. Let us proceed to apply it.\nThere are several ways to apply this:\n\n- Apply and Fetch\n Configure this device as a new client. After applying, synchronise from the remote server.\n- Apply and Merge\n Configure on a device that already has the file. It processes the local files and transfers the differences. Conflicts may arise.\n- Apply and Rebuild\n Rebuild the remote using local files. This is typically done if the server becomes corrupted or we wish to start from scratch.\n Other devices will be locked and required to re-fetch.\n- Only Apply\n Apply only. Conflicts may arise if a rebuild is required.",es:"La nueva configuración está lista. Vamos a aplicarla.\nHay varias formas de hacerlo:\n\n- Aplicar y obtener\n Configura este dispositivo como cliente nuevo. Tras aplicarla, sincroniza desde el servidor remoto.\n- Aplicar y combinar\n Para un dispositivo que ya tiene los archivos. Procesa los archivos locales y transfiere las diferencias. Pueden surgir conflictos.\n- Aplicar y reconstruir\n Reconstruye el remoto a partir de los archivos locales. Se hace normalmente si el servidor se ha corrompido o si se quiere empezar de cero.\n Los demás dispositivos quedarán bloqueados y tendrán que volver a obtener los datos.\n- Solo aplicar\n Solo aplica la configuración. Pueden surgir conflictos si hace falta reconstruir.",fr:"La nouvelle configuration est prête. Procédons à son application.\nPlusieurs manières de l'appliquer :\n\n- Appliquer et récupérer\n Configurer cet appareil comme nouveau client. Après application, synchroniser depuis le serveur distant.\n- Appliquer et fusionner\n Configurer sur un appareil qui possède déjà les fichiers. Traite les fichiers locaux et transfère les différences. Des conflits peuvent apparaître.\n- Appliquer et reconstruire\n Reconstruire le distant à partir des fichiers locaux. Typiquement effectué si le serveur est corrompu ou si l'on souhaite repartir de zéro.\n Les autres appareils seront verrouillés et devront refaire une récupération.\n- Appliquer seulement\n Appliquer uniquement. Des conflits peuvent apparaître si une reconstruction est nécessaire.",he:"התצורה החדשה מוכנה. בואו נמשיך להחיל אותה.\nישנן מספר דרכים להחיל זאת:\n\n- החל ומשוך\n הגדר מכשיר זה כלקוח חדש. לאחר ההחלה, סנכרן מהשרת המרוחד.\n- החל ומזג\n הגדר על מכשיר שכבר יש בו קבצים. מעבד קבצים מקומיים ומעביר הפרשים. עלולים\n לקום קונפליקטים.\n- החל ובנה מחדש\n בנה את השרת המרוחד מחדש תוך שימוש בקבצים מקומיים. נעשה בדרך כלל אם השרת\n מושחת או אם רוצים להתחיל מאפס. מכשירים אחרים יינעלו ויצטרכו למשוך מחדש.\n- החל בלבד\n החל בלבד. עלולים לקום קונפליקטים אם נדרשת בנייה מחדש.",ja:"新しい設定の準備ができました。適用に進みましょう。\n適用方法はいくつかあります:\n\n- 適用してフェッチ\n このデバイスを新しいクライアントとして設定します。適用後、リモートサーバーから同期します。\n- 適用してマージ\n 既にファイルがあるデバイスで設定します。ローカルファイルを処理し、差分を転送します。競合が発生する場合があります。\n- 適用して再構築\n ローカルファイルを使用してリモートを再構築します。これは通常、サーバーが破損した場合や最初からやり直したい場合に行います。\n 他のデバイスはロックされ、再フェッチが必要になります。\n- 適用のみ\n 適用のみを行います。再構築が必要な場合、競合が発生する可能性があります。",ko:"새 구성이 준비되었습니다. 이제 적용해 보겠습니다.\n적용 방법은 여러 가지가 있습니다:\n\n- 적용 후 가져오기\n 이 기기를 새 클라이언트로 구성합니다. 적용한 뒤 원격 서버에서 동기화합니다.\n- 적용 후 병합\n 이미 파일이 있는 기기에서 구성합니다. 로컬 파일을 처리한 뒤 차이만 전송합니다. 충돌이 발생할 수 있습니다.\n- 적용 후 재구축\n 로컬 파일로 원격을 재구축합니다. 보통 서버가 손상되었거나 처음부터 다시 시작하려는 경우에 사용합니다.\n 다른 기기는 잠기며 다시 가져오기를 수행해야 합니다.\n- 적용만 하기\n 적용만 합니다. 재구축이 필요한 경우 충돌이 발생할 수 있습니다.",ru:"Новая конфигурация готова. Есть несколько способов применить её.",zh:"The new configuration is ready. Let us proceed to apply it.\nThere are several ways to apply this:\n\n- Apply and Fetch\n Configure this device as a new client. After applying, synchronise from the remote server.\n- Apply and Merge\n Configure on a device that already has the file. It processes the local files and transfers the differences. Conflicts may arise.\n- Apply and Rebuild\n Rebuild the remote using local files. This is typically done if the server becomes corrupted or we wish to start from scratch.\n Other devices will be locked and required to re-fetch.\n- Only Apply\n Apply only. Conflicts may arise if a rebuild is required.","zh-tw":"新的設定已經就緒,接下來要套用它。\n有幾種套用方式:\n\n- 套用並抓取\n 將此裝置設定為新的用戶端。套用後會從遠端伺服器同步。\n- 套用並合併\n 在已經有檔案的裝置上設定。會處理本機檔案並傳輸差異部分,可能會產生衝突。\n- 套用並重建\n 使用本機檔案重建遠端。通常在伺服器損毀或想要從頭開始時執行。\n 其他裝置會被鎖定,需要重新抓取。\n- 僅套用\n 只套用設定。若需要重建,可能會產生衝突。"},"Setup.Apply.Title":{def:"Apply new configuration from the ${method}",es:"Aplicar la nueva configuración de ${method}",fr:"Appliquer la nouvelle configuration depuis ${method}",he:"החל תצורה חדשה מה-${method}",ja:"${method}からの新しい設定を適用",ko:"${method}에서 가져온 새 구성 적용",ru:"Применить новую конфигурацию из method",zh:"Apply new configuration from the ${method}","zh-tw":"從 ${method} 套用新設定"},"Setup.Apply.WarningRebuildRecommended":{def:"NOTE: after adjusting the settings, it has been determined that a rebuild is required; Just Import is not recommended.",es:"NOTA: tras ajustar la configuración se ha determinado que hace falta reconstruir; no se recomienda «solo importar».",fr:"NOTE : après ajustement des paramètres, il a été déterminé qu'une reconstruction est requise ; un simple import n'est pas recommandé.",he:"שים לב: לאחר כוונון ההגדרות, נקבע שנדרשת בנייה מחדש; ייבוא בלבד אינו מומלץ.",ja:"注意: 設定の調整後、再構築が必要と判断されました。インポートのみは推奨されません。",ko:"참고: 설정을 조정한 결과 재구축이 필요한 것으로 판단되었습니다. 적용만 하는 것은 권장하지 않습니다.",ru:"ПРИМЕЧАНИЕ: после настройки изменений определено, что требуется перестроение.",zh:"NOTE: after adjusting the settings, it has been determined that a rebuild is required; Just Import is not recommended.","zh-tw":"注意:調整設定後判斷需要重建;不建議僅匯入設定。"},"Setup.Doctor.Buttons.No":{def:"No, please use the settings in the URI as is",es:"No, usar los ajustes del URI tal cual",fr:"Non, utiliser les paramètres de l'URI tels quels",he:"לא, אנא השתמש בהגדרות ה-URI כפי שהן",ja:"いいえ、URIの設定をそのまま使用",ko:"아니요, URI에 담긴 설정을 그대로 사용합니다",ru:"Нет, использовать настройки из URI как есть",zh:"No, please use the settings in the URI as is","zh-tw":"不用,請直接使用 URI 中的設定"},"Setup.Doctor.Buttons.Yes":{def:"Yes, please consult the doctor",es:"Sí, consultar al doctor",fr:"Oui, consulter le docteur",he:"כן, אנא יעץ ל-Doctor",ja:"はい、診断ツールに相談する",ko:"예, 설정 진단 마법사를 실행합니다",ru:"Да, пожалуйста, запустить диагностику",zh:"Yes, please consult the doctor","zh-tw":"要,請諮詢診斷"},"Setup.Doctor.Message":{def:"Self-hosted LiveSync has gradually become longer in history and some recommended settings have changed.\n\nNow, setup is a very good time to do this.\n\nDo you want to run Doctor to check if the imported settings are optimal compared to the latest state?",es:"Self-hosted LiveSync tiene ya una historia larga y algunos ajustes recomendados han cambiado.\n\nLa configuración inicial es un momento muy bueno para revisarlos.\n\n¿Quieres ejecutar el Doctor para comprobar si los ajustes importados son los óptimos respecto al estado actual?",fr:"Self-hosted LiveSync s'est progressivement étoffé et certains paramètres recommandés ont évolué.\n\nLa configuration est un bon moment pour le faire.\n\nVoulez-vous lancer le Docteur pour vérifier si les paramètres importés sont optimaux par rapport au dernier état ?",he:"Self-hosted LiveSync הפך ארוך יותר בהיסטוריה שלו וחלק מההגדרות המומלצות השתנו.\n\nעכשיו, הגדרה היא זמן מצוין לכך.\n\nהאם ברצונך להפעיל את Doctor כדי לבדוק אם ההגדרות המיובאות אופטימליות בהשוואה למצב הנוכחי?",ja:"Self-hosted LiveSyncは徐々に歴史が長くなり、一部の推奨設定が変更されています。\n\nセットアップは、これを行う非常に良い機会です。\n\nインポートされた設定が最新の状態と比較して最適かどうかを確認するために、診断ツールを実行しますか?",ko:"Self-hosted LiveSync는 오랜 기간에 걸쳐 발전해 왔고, 그동안 권장 설정도 일부 바뀌었습니다.\n\n지금 설정 단계가 이를 점검하기에 아주 좋은 시점입니다.\n\n가져온 설정이 최신 기준에 비추어 최적인지 확인하도록 설정 진단 마법사를 실행하시겠습니까?",ru:"Self-hosted LiveSync постепенно набрал историю и некоторые рекомендуемые настройки изменились.",zh:"Self-hosted LiveSync has gradually become longer in history and some recommended settings have changed.\n\nNow, setup is a very good time to do this.\n\nDo you want to run Doctor to check if the imported settings are optimal compared to the latest state?","zh-tw":"Self-hosted LiveSync 的歷史逐漸變長,部分建議設定也隨之改變。\n\n現在正是進行這項檢查的好時機。\n\n要執行設定診斷,檢查匯入的設定是否符合最新建議嗎?"},"Setup.Doctor.Title":{def:"Do you want to consult the doctor?",es:"¿Quieres consultar al doctor?",fr:"Voulez-vous consulter le docteur ?",he:"האם ברצונך להתייעץ עם ה-Doctor?",ja:"診断ツールに相談しますか?",ko:"설정 진단 마법사를 실행할까요?",ru:"Хотите запустить диагностику?",zh:"Do you want to consult the doctor?","zh-tw":"要諮詢設定診斷嗎?"},"Setup.FetchRemoteConf.Buttons.Fetch":{def:"Yes, please fetch the configuration",es:"Sí, obtener la configuración",fr:"Oui, récupérer la configuration",he:"כן, אנא משוך את התצורה",ja:"はい、設定を取得",ko:"예, 구성을 가져옵니다",ru:"Да, загрузить конфигурацию",zh:"Yes, please fetch the configuration","zh-tw":"要,請抓取設定"},"Setup.FetchRemoteConf.Buttons.Skip":{def:"No, please use the settings in the URI",es:"No, usar los ajustes del URI",fr:"Non, utiliser les paramètres de l'URI",he:"לא, אנא השתמש בהגדרות ב-URI",ja:"いいえ、URIの設定を使用",ko:"아니요, URI에 담긴 설정을 사용합니다",ru:"Нет, использовать настройки из URI",zh:"No, please use the settings in the URI","zh-tw":"不用,請使用 URI 中的設定"},"Setup.FetchRemoteConf.Message":{def:"If we have already synchronised once with another device, the remote database stores the suitable configuration values between the synchronised devices. The plug-in would like to retrieve them for robust configuration.\n\nHowever, we have to make sure the one thing. Are we currently in a situation where we can access the network safely and retrieve the settings?\n\nNote: Mostly, you are safe to do this, that your remote database is hosted with a SSL certificate, and your network is not compromised.",es:"Si ya hemos sincronizado alguna vez con otro dispositivo, la base de datos remota guarda los valores de configuración adecuados para los dispositivos sincronizados. El complemento querría recuperarlos para lograr una configuración más sólida.\n\nAntes hay que asegurar una cosa: ¿estamos en una situación en la que se puede acceder a la red de forma segura y recuperar los ajustes?\n\nNota: normalmente puedes hacerlo sin riesgo si tu base de datos remota se sirve con un certificado SSL y tu red no está comprometida.",fr:"Si nous avons déjà synchronisé une fois avec un autre appareil, la base distante stocke les valeurs de configuration adaptées entre les appareils synchronisés. Le plug-in souhaiterait les récupérer pour une configuration robuste.\n\nMais il faut s'assurer d'une chose. Sommes-nous actuellement dans une situation où nous pouvons accéder au réseau en toute sécurité et récupérer les paramètres ?\n\nNote : le plus souvent, c'est sûr si votre base distante est hébergée avec un certificat SSL et si votre réseau n'est pas compromis.",he:"אם סנכרנו כבר פעם עם מכשיר אחר, מסד הנתונים המרוחד מאחסן ערכי תצורה מתאימים בין המכשירים המסונכרנים. הפלאגין ירצה לאחזר אותם לתצורה חזקה יותר.\n\nעם זאת, עלינו לוודא דבר אחד. האם אנחנו כרגע במצב שבו ניתן לגשת לרשת בבטחה ולאחזר את ההגדרות?\nהערה: ברוב המקרים, אתה בטוח לעשות זאת, כל עוד מסד הנתונים המרוחד שלך מאוחסן עם תעודת SSL, ורשתך אינה פגומה.",ja:"既に他のデバイスと同期したことがある場合、リモートデータベースには同期されたデバイス間の適切な設定値が保存されています。プラグインは堅牢な設定のためにそれらを取得したいと考えています。\n\nただし、1つ確認が必要です。現在、ネットワークに安全にアクセスして設定を取得できる状況ですか?\n\n注意: リモートデータベースがSSL証明書でホストされており、ネットワークが侵害されていなければ、ほとんどの場合安全に実行できます。",ko:"다른 기기와 이미 한 번이라도 동기화했다면, 원격 데이터베이스에 동기화된 기기 사이에 적합한 구성 값이 저장되어 있습니다. 플러그인은 더 견고한 구성을 위해 이 값을 가져오려고 합니다.\n\n다만 한 가지 확인이 필요합니다. 지금 네트워크에 안전하게 접근해 설정을 가져올 수 있는 상황인가요?\n\n참고: 원격 데이터베이스가 SSL 인증서로 보호되어 있고 네트워크가 안전하다면, 대부분의 경우 그대로 진행해도 괜찮습니다.",ru:"Если мы уже синхронизировались с другим устройством, удалённая база данных хранит подходящие значения конфигурации.",zh:"If we have already synchronised once with another device, the remote database stores the suitable configuration values between the synchronised devices. The plug-in would like to retrieve them for robust configuration.\n\nHowever, we have to make sure the one thing. Are we currently in a situation where we can access the network safely and retrieve the settings?\n\nNote: Mostly, you are safe to do this, that your remote database is hosted with a SSL certificate, and your network is not compromised.","zh-tw":"如果我們已經與其他裝置同步過一次,遠端資料庫會儲存這些已同步裝置之間適用的設定值。外掛想要取得這些值,以取得更穩健的設定。\n\n不過,我們需要先確認一件事:目前是否處於能安全存取網路並取得設定的情況?\n\n注意:多數情況下這樣做是安全的,只要你的遠端資料庫使用 SSL 憑證,且網路沒有遭到入侵。"},"Setup.FetchRemoteConf.Title":{def:"Fetch configuration from remote database?",es:"¿Obtener la configuración de la base de datos remota?",fr:"Récupérer la configuration depuis la base distante ?",he:"אחזר תצורה ממסד הנתונים המרוחד?",ja:"リモートデータベースから設定を取得しますか?",ko:"원격 데이터베이스에서 구성을 가져올까요?",ru:"Загрузить конфигурацию с удалённой базы данных?",zh:"Fetch configuration from remote database?","zh-tw":"要從遠端資料庫抓取設定嗎?"},"Setup.QRCode":{def:'We have generated a QR code to transfer the settings. Please scan the QR code with your phone or other device.\nNote: The QR code is not encrypted, so be careful to open this.\n\n>[!FOR YOUR EYES ONLY]-\n> <div class="sls-qr">${qr_image}</div>',es:'Hemos generado un código QR para transferir los ajustes. Escanéalo con tu móvil u otro dispositivo.\nNota: el código QR no está cifrado, así que ten cuidado al abrirlo.\n\n>[!SOLO PARA TUS OJOS]-\n> <div class="sls-qr">${qr_image}</div>',fr:"Nous avons généré un QR code pour transférer les paramètres. Scannez-le avec votre téléphone ou un autre appareil.\nNote : le QR code n'est pas chiffré, soyez prudent en l'affichant.\n\n>[!POUR VOS YEUX SEULEMENT]-\n> <div class=\"sls-qr\">${qr_image}</div>",he:'יצרנו קוד QR להעברת ההגדרות. אנא סרוק את קוד ה-QR עם הטלפון או מכשיר אחר.\nהערה: קוד ה-QR אינו מוצפן, אז היה זהיר בפתיחתו.\n\n>[!FOR YOUR EYES ONLY]-\n> <div class="sls-qr">${qr_image}</div>',ja:'設定を転送するためのQRコードを生成しました。スマートフォンや他のデバイスでQRコードをスキャンしてください。\n注意: QRコードは暗号化されていないため、開く際は注意してください。\n\n>[!FOR YOUR EYES ONLY]-\n> <div class="sls-qr">${qr_image}</div>',ko:'설정을 전송하기 위한 QR 코드를 생성했습니다. 휴대폰이나 다른 기기로 QR 코드를 스캔해 주세요.\n참고: QR 코드는 암호화되지 않았으므로 열 때 주의하세요.\n\n>[!FOR YOUR EYES ONLY]-\n> <div class="sls-qr">${qr_image}</div>',ru:"Мы сгенерировали QR-код для передачи настроек. Отсканируйте QR-код телефоном.",zh:'We have generated a QR code to transfer the settings. Please scan the QR code with your phone or other device.\nNote: The QR code is not encrypted, so be careful to open this.\n\n>[!FOR YOUR EYES ONLY]-\n> <div class="sls-qr">${qr_image}</div>',"zh-tw":'我們已產生用於傳遞設定的 QR 碼,請用你的手機或其他裝置掃描這個 QR 碼。\n注意:這個 QR 碼未經加密,開啟時請務必小心。\n\n>[!僅供本人查看]-\n> <div class="sls-qr">${qr_image}</div>'},"Setup.RemoteE2EE.AdvancedTitle":{def:"Advanced",es:"Avanzado",ja:"詳細設定",ko:"고급",ru:"Дополнительно",zh:"高级","zh-tw":"進階"},"Setup.RemoteE2EE.AlgorithmWarning":{def:"Changing the encryption algorithm will prevent access to any data previously encrypted with a different algorithm. Ensure that all your devices are configured to use the same algorithm to maintain access to your data.",es:"Cambiar el algoritmo de cifrado impedirá el acceso a cualquier dato cifrado anteriormente con otro algoritmo. Asegúrate de que todos tus dispositivos estén configurados para usar el mismo algoritmo y así mantener el acceso a tus datos.",ja:"暗号化アルゴリズムを変更すると、別のアルゴリズムで暗号化された既存データにはアクセスできなくなります。すべての端末で同じアルゴリズムを使うよう設定し、データにアクセスできる状態を維持してください。",ko:"암호화 알고리즘을 변경하면 다른 알고리즘으로 암호화된 기존 데이터에 접근할 수 없게 됩니다. 모든 기기에서 동일한 알고리즘을 사용하도록 설정해 데이터 접근성을 유지하세요.",ru:"Изменение алгоритма шифрования лишит доступа к данным, которые ранее были зашифрованы другим алгоритмом. Убедитесь, что все ваши устройства настроены на использование одного и того же алгоритма, чтобы сохранить доступ к данным.",zh:"更改加密算法会导致之前使用其他算法加密的数据无法访问。请确保所有设备都配置为使用同一算法,以保持对数据的访问能力。","zh-tw":"變更加密演算法後,先前以其他演算法加密的資料將無法再存取。請確認所有裝置都設定為使用相同演算法,以維持對資料的存取能力。"},"Setup.RemoteE2EE.ButtonCancel":{def:"Cancel",es:"Cancelar",ja:"キャンセル",ko:"취소",ru:"Отмена",zh:"取消","zh-tw":"取消"},"Setup.RemoteE2EE.ButtonProceed":{def:"Proceed",es:"Continuar",ja:"進む",ko:"진행",ru:"Продолжить",zh:"继续","zh-tw":"繼續"},"Setup.RemoteE2EE.DefaultAlgorithmDesc":{def:"In most cases, you should stick with the default algorithm (${algorithm}). This setting is only required if you have an existing Vault encrypted in a different format.",es:"En la mayoría de los casos, debes mantener el algoritmo predeterminado (${algorithm}). Este ajuste solo es necesario si ya tienes un Vault cifrado con un formato diferente.",ja:"ほとんどの場合は、既定のアルゴリズム(${algorithm})をそのまま使用してください。この設定が必要になるのは、既存の Vault が別の形式で暗号化されている場合のみです。",ko:"대부분의 경우 기본 알고리즘(${algorithm})을 그대로 사용하는 것이 좋습니다. 이 설정은 기존 보관함이 다른 형식으로 암호화되어 있는 경우에만 필요합니다.",ru:"В большинстве случаев следует оставить алгоритм по умолчанию (${algorithm}). Этот параметр нужен только в том случае, если у вас уже есть Vault, зашифрованный в другом формате.",zh:"在大多数情况下,你应继续使用默认算法(${algorithm})。只有当你已有一个采用不同格式加密的 Vault 时,才需要调整此设置。","zh-tw":"在大多數情況下,建議維持使用預設演算法(${algorithm})。只有當你現有的 Vault 是以不同格式加密時,才需要調整這項設定。"},"Setup.RemoteE2EE.Guidance":{def:"Please configure your end-to-end encryption settings.",es:"Configura tus ajustes de cifrado de extremo a extremo.",ja:"エンドツーエンド暗号化の設定を行ってください。",ko:"종단 간 암호화 설정을 구성해 주세요.",ru:"Пожалуйста, настройте параметры сквозного шифрования.",zh:"请配置你的端到端加密设置。","zh-tw":"請設定你的端對端加密選項。"},"Setup.RemoteE2EE.LabelEncrypt":{def:"End-to-End Encryption",es:"Cifrado de extremo a extremo",ja:"エンドツーエンド暗号化",ko:"종단 간 암호화",ru:"Сквозное шифрование",zh:"端到端加密","zh-tw":"端對端加密"},"Setup.RemoteE2EE.LabelEncryptionAlgorithm":{def:"Encryption Algorithm",es:"Algoritmo de cifrado",ja:"暗号化アルゴリズム",ko:"암호화 알고리즘",ru:"Алгоритм шифрования",zh:"加密算法","zh-tw":"加密演算法"},"Setup.RemoteE2EE.LabelObfuscateProperties":{def:"Obfuscate Properties",es:"Ofuscar propiedades",ja:"プロパティを難読化",ko:"속성 난독화",ru:"Обфусцировать свойства",zh:"混淆属性","zh-tw":"混淆屬性"},"Setup.RemoteE2EE.MultiDestinationWarning":{def:"This setting must be the same even when connecting to multiple synchronisation destinations.",es:"Este ajuste debe ser el mismo incluso cuando te conectes a varios destinos de sincronización.",ja:"複数の同期先へ接続する場合でも、この設定は同一である必要があります。",ko:"여러 동기화 대상에 연결하는 경우에도 이 설정은 동일해야 합니다.",ru:"Этот параметр должен быть одинаковым даже при подключении к нескольким направлениям синхронизации.",zh:"即使连接到多个同步目标,此设置也必须保持一致。","zh-tw":"即使連線到多個同步目標,這項設定也必須保持一致。"},"Setup.RemoteE2EE.ObfuscatePropertiesDesc":{def:"Obfuscating properties (e.g., path of file, size, creation and modification dates) adds an additional layer of security by making it harder to identify the structure and names of your files and folders on the remote server. This helps protect your privacy and makes it more difficult for unauthorized users to infer information about your data.",es:"Ofuscar propiedades (por ejemplo, la ruta del archivo, el tamaño y las fechas de creación y modificación) añade una capa adicional de seguridad al dificultar la identificación de la estructura y los nombres de tus archivos y carpetas en el servidor remoto. Esto ayuda a proteger tu privacidad y dificulta que usuarios no autorizados deduzcan información sobre tus datos.",ja:"プロパティ(ファイルパス、サイズ、作成日時、更新日時など)を難読化すると、リモートサーバー上のファイルやフォルダーの構造や名前を特定しにくくできるため、追加の保護層になります。これによりプライバシーが守られ、権限のない第三者がデータに関する情報を推測しにくくなります。",ko:"속성(예: 파일 경로, 크기, 생성일 및 수정일)을 난독화하면 원격 서버에서 파일과 폴더의 구조 및 이름을 식별하기 어렵게 만들어 보안을 한층 강화할 수 있습니다. 이는 개인 정보를 보호하고 권한 없는 사용자가 데이터에 관한 정보를 추론하기 어렵게 만듭니다.",ru:"Обфускация свойств (например, пути к файлу, размера, дат создания и изменения) добавляет дополнительный уровень защиты, затрудняя определение структуры и названий ваших файлов и папок на удалённом сервере. Это помогает защитить вашу конфиденциальность и усложняет для посторонних вывод информации о ваших данных.",zh:"混淆属性(例如文件路径、大小、创建和修改日期)可以增加一层额外保护,使远程服务器上的文件与文件夹结构及名称更难被识别。这有助于保护你的隐私,也让未授权用户更难推断你的数据相关信息。","zh-tw":"混淆屬性(例如檔案路徑、大小、建立時間與修改時間)可以額外增加一層安全保護,讓遠端伺服器上的檔案與資料夾結構及名稱更難被辨識。這有助於保護你的隱私,也讓未授權使用者更難推測你的資料資訊。"},"Setup.RemoteE2EE.PassphraseValidationLine1":{def:"Please be aware that the End-to-End Encryption passphrase is not validated until the synchronisation process actually commences. This is a security measure designed to protect your data.",es:"Ten en cuenta que la frase de contraseña del cifrado de extremo a extremo no se valida hasta que el proceso de sincronización comienza realmente. Esta es una medida de seguridad diseñada para proteger tus datos.",ja:"エンドツーエンド暗号化のパスフレーズは、実際に同期処理が開始されるまで検証されない点にご注意ください。これはデータを保護するためのセキュリティ対策です。",ko:"종단 간 암호화 패스프레이즈는 실제 동기화가 시작되기 전까지 검증되지 않는다는 점에 유의하세요. 데이터를 보호하기 위한 보안 조치입니다.",ru:"Обратите внимание: парольная фраза для сквозного шифрования не проверяется до фактического начала процесса синхронизации. Это сделано в целях безопасности ваших данных.",zh:"请注意,在同步过程真正开始之前,端到端加密密码短语不会被校验。这是一项用于保护你数据的安全措施。","zh-tw":"請注意,端對端加密的密語要到同步程序實際開始時才會進行驗證。這是為了保護你資料而設計的安全措施。"},"Setup.RemoteE2EE.PassphraseValidationLine2":{def:"Therefore, we ask that you exercise extreme caution when configuring server information manually. If an incorrect passphrase is entered, the data on the server will become corrupted. Please understand that this is intended behaviour.",es:"Por lo tanto, te pedimos que tengas muchísimo cuidado al configurar manualmente la información del servidor. Si introduces una frase de contraseña incorrecta, los datos del servidor se corromperán. Ten en cuenta que este comportamiento es intencionado.",ja:"そのため、サーバー情報を手動で設定する際は細心の注意を払ってください。誤ったパスフレーズを入力すると、サーバー上のデータが破損します。これは意図された動作ですので、あらかじめご理解ください。",ko:"따라서 서버 정보를 수동으로 구성할 때는 각별히 주의해 주세요. 잘못된 패스프레이즈를 입력하면 서버의 데이터가 손상됩니다. 이는 의도된 동작이니 반드시 이해하고 진행해 주세요.",ru:"Поэтому при ручной настройке информации о сервере требуется предельная осторожность. Если будет введена неверная парольная фраза, данные на сервере будут повреждены. Пожалуйста, учтите, что это ожидаемое поведение.",zh:"因此,在手动配置服务器信息时请务必格外小心。如果输入了错误的密码短语,服务器上的数据将会损坏。请理解这属于预期行为。","zh-tw":"因此,在手動設定伺服器資訊時請務必格外小心。如果輸入了錯誤的密語,伺服器上的資料將會損毀。請理解這是系統的預期行為。"},"Setup.RemoteE2EE.PlaceholderPassphrase":{def:"Enter your passphrase",es:"Introduce tu frase de contraseña",ja:"パスフレーズを入力してください",ko:"패스프레이즈를 입력하세요",ru:"Введите парольную фразу",zh:"输入你的密码短语","zh-tw":"輸入你的密語"},"Setup.RemoteE2EE.StronglyRecommendedLine1":{def:"Enabling end-to-end encryption ensures that your data is encrypted on your device before being sent to the remote server. This means that even if someone gains access to the server, they won't be able to read your data without the passphrase. Make sure to remember your passphrase, as it will be required to decrypt your data on other devices.",es:"Al habilitar el cifrado de extremo a extremo, tus datos se cifran en tu dispositivo antes de enviarse al servidor remoto. Esto significa que, incluso si alguien obtiene acceso al servidor, no podrá leer tus datos sin la frase de contraseña. Asegúrate de recordarla, ya que también será necesaria para descifrar tus datos en otros dispositivos.",ja:"エンドツーエンド暗号化を有効にすると、データはリモートサーバーへ送信される前にこの端末上で暗号化されます。つまり、たとえ誰かがサーバーへアクセスできても、パスフレーズがなければデータを読むことはできません。他の端末でデータを復号する際にも必要になるため、パスフレーズは必ず覚えておいてください。",ko:"종단 간 암호화를 활성화하면 데이터가 원격 서버로 전송되기 전에 이 기기에서 암호화됩니다. 즉, 누군가 서버에 접근하더라도 패스프레이즈 없이는 데이터를 읽을 수 없습니다. 다른 기기에서 데이터를 복호화할 때도 필요하므로 패스프레이즈를 반드시 기억해 두세요.",ru:"При включении сквозного шифрования ваши данные шифруются на устройстве до отправки на удалённый сервер. Это означает, что даже если кто-то получит доступ к серверу, он не сможет прочитать ваши данные без парольной фразы. Обязательно запомните парольную фразу, так как она потребуется для расшифровки данных на других устройствах.",zh:"启用端到端加密后,数据会先在你的设备上加密,再发送到远程服务器。这意味着即使有人获得了服务器访问权限,没有密码短语也无法读取你的数据。请务必记住你的密码短语,因为在其他设备上解密数据时也需要它。","zh-tw":"啟用端對端加密後,資料會先在你的裝置上完成加密,再傳送到遠端伺服器。這表示即使有人取得伺服器存取權,沒有密語也無法讀取你的資料。請務必記住你的密語,因為其他裝置在解密資料時也需要它。"},"Setup.RemoteE2EE.StronglyRecommendedLine2":{def:"Also, please note that if you are using Peer-to-Peer synchronization, this configuration will be used when you switch to other methods and connect to a remote server in the future.",es:"Además, ten en cuenta que si estás usando sincronización Peer-to-Peer, esta configuración se utilizará cuando más adelante cambies a otros métodos y te conectes a un servidor remoto.",ja:"また、Peer-to-Peer 同期を使用している場合でも、将来ほかの方式へ切り替えてリモートサーバーへ接続するときには、この設定が使われます。",ko:"또한 Peer-to-Peer 동기화를 사용 중이더라도, 나중에 다른 방식으로 전환하여 원격 서버에 연결하면 이 설정이 그대로 사용됩니다.",ru:"Также обратите внимание: если вы используете синхронизацию Peer-to-Peer, эта конфигурация будет использована, когда вы позже переключитесь на другие методы и подключитесь к удалённому серверу.",zh:"另外请注意,如果你正在使用 Peer-to-Peer 同步,当你以后切换到其他同步方式并连接远程服务器时,也会使用这组配置。","zh-tw":"另外請注意,即使你目前使用的是 Peer-to-Peer 同步,日後若切換到其他方式並連線到遠端伺服器時,也會沿用這組設定。"},"Setup.RemoteE2EE.StronglyRecommendedTitle":{def:"Strongly Recommended",es:"Muy recomendable",ja:"強く推奨",ko:"강력 권장",ru:"Настоятельно рекомендуется",zh:"强烈推荐","zh-tw":"強烈建議"},"Setup.RemoteE2EE.Title":{def:"End-to-End Encryption",es:"Cifrado de extremo a extremo",ja:"エンドツーエンド暗号化",ko:"종단 간 암호화",ru:"Сквозное шифрование",zh:"端到端加密","zh-tw":"端對端加密"},"Setup.ScanQRCode.ButtonClose":{def:"Close this dialog",es:"Cerrar este diálogo",ja:"このダイアログを閉じる",ko:"이 대화 상자 닫기",ru:"Закрыть это окно",zh:"关闭此对话框","zh-tw":"關閉此對話框"},"Setup.ScanQRCode.Guidance":{def:"Please follow the steps below to import settings from your existing device.",es:"Sigue los pasos de abajo para importar los ajustes desde tu dispositivo actual.",ja:"既存の端末から設定を取り込むには、以下の手順に従ってください。",ko:"기존 기기에서 설정을 가져오려면 아래 단계를 따라 주세요.",ru:"Чтобы импортировать настройки с существующего устройства, выполните следующие шаги.",zh:"请按照以下步骤从现有设备导入设置。","zh-tw":"請依照以下步驟,從現有裝置匯入設定。"},"Setup.ScanQRCode.Step1":{def:"On this device, please keep this Vault open.",es:"En este dispositivo, mantén este Vault abierto.",ja:"この端末では、この Vault を開いたままにしてください。",ko:"이 기기에서는 이 보관함을 계속 열어 두세요.",ru:"На этом устройстве оставьте данный Vault открытым.",zh:"在这台设备上,请保持此 Vault 处于打开状态。","zh-tw":"在這台裝置上,請保持此 Vault 開啟。"},"Setup.ScanQRCode.Step2":{def:"On the source device, open Obsidian.",es:"En el dispositivo de origen, abre Obsidian.",ja:"元の端末で Obsidian を開きます。",ko:"원본 기기에서 Obsidian을 엽니다.",ru:"На исходном устройстве откройте Obsidian.",zh:"在源设备上打开 Obsidian。","zh-tw":"在來源裝置上開啟 Obsidian。"},"Setup.ScanQRCode.Step3":{def:"On the source device, from the command palette, run the 'Show settings as a QR code' command.",es:'En el dispositivo de origen, ejecuta desde la paleta de comandos la orden "Mostrar ajustes como código QR".',ja:"元の端末でコマンドパレットから「設定を QR コードとして表示」を実行します。",ko:'원본 기기에서 명령 팔레트를 열고 "설정을 QR 코드로 표시" 명령을 실행합니다.',ru:"На исходном устройстве в палитре команд выполните команду «Показать настройки как QR-код».",zh:"在源设备上,从命令面板运行“将设置显示为二维码”命令。","zh-tw":"在來源裝置上,從命令面板執行「將設定顯示為 QR 碼」命令。"},"Setup.ScanQRCode.Step4":{def:"On this device, switch to the camera app or use a QR code scanner to scan the displayed QR code.",es:"En este dispositivo, cambia a la cámara o usa un escáner QR para escanear el código mostrado.",ja:"この端末でカメラアプリに切り替えるか QR コードスキャナーを使って、表示された QR コードを読み取ってください。",ko:"이 기기에서 카메라 앱으로 전환하거나 QR 코드 스캐너를 사용해 표시된 QR 코드를 스캔하세요.",ru:"На этом устройстве откройте приложение камеры или используйте сканер QR-кодов, чтобы считать показанный QR-код.",zh:"在这台设备上,切换到相机应用或使用二维码扫描器扫描显示出的二维码。","zh-tw":"在這台裝置上切換到相機 App,或使用 QR 碼掃描器掃描顯示出的 QR 碼。"},"Setup.ScanQRCode.Title":{def:"Scan QR Code",es:"Escanear código QR",ja:"QRコードをスキャン",ko:"QR 코드 스캔",ru:"Сканировать QR-код",zh:"扫描二维码","zh-tw":"掃描 QR 碼"},"Setup.ShowQRCode":{def:"Show QR code",es:"Mostrar el código QR",fr:"Afficher le QR code",he:"הצג קוד QR",ja:"QRコードを表示",ko:"QR 코드 표시",ru:"Показать QR код",zh:"使用QR码","zh-tw":"顯示 QR 碼"},"Setup.ShowQRCode.Desc":{def:"Show QR code to transfer the settings.",es:"Muestra un código QR para transferir los ajustes.",fr:"Afficher le QR code pour transférer les paramètres.",he:"הצג קוד QR להעברת ההגדרות.",ja:"設定を転送するためのQRコードを表示します。",ko:"설정을 전송하기 위한 QR 코드를 표시합니다.",ru:"Показать QR код для передачи настроек.",zh:"使用QR码来传递配置","zh-tw":"顯示 QR 碼以傳遞設定。"},"Setup.UseSetupURI.ButtonCancel":{def:"Cancel",es:"Cancelar",ja:"キャンセル",ko:"취소",ru:"Отмена",zh:"取消","zh-tw":"取消"},"Setup.UseSetupURI.ButtonProceed":{def:"Test Settings and Continue",es:"Probar ajustes y continuar",ja:"設定をテストして続行",ko:"설정 테스트 후 계속",ru:"Проверить настройки и продолжить",zh:"测试设置并继续","zh-tw":"測試設定並繼續"},"Setup.UseSetupURI.ErrorFailedToParse":{def:"Failed to parse the Setup URI. Please check the URI and passphrase.",es:"No se pudo procesar la URI de configuración. Revisa la URI y la frase de contraseña.",ja:"Setup URI を解析できませんでした。URI とパスフレーズを確認してください。",ko:"Setup URI를 해석하지 못했습니다. URI와 패스프레이즈를 확인해 주세요.",ru:"Не удалось обработать Setup URI. Проверьте URI и парольную фразу.",zh:"无法解析 Setup URI,请检查 URI 和密码短语。","zh-tw":"無法解析 Setup URI,請檢查 URI 與密語。"},"Setup.UseSetupURI.ErrorPassphraseRequired":{def:"Please enter the vault passphrase.",es:"Introduce la frase de contraseña del Vault.",ja:"Vault のパスフレーズを入力してください。",ko:"보관함 패스프레이즈를 입력해 주세요.",ru:"Пожалуйста, введите парольную фразу Vault.",zh:"请输入 Vault 密码短语。","zh-tw":"請輸入 Vault 的密語。"},"Setup.UseSetupURI.GuidanceLine1":{def:"Please enter the Setup URI that was generated during server installation or on another device, along with the vault passphrase.",es:"Introduce la URI de configuración que se generó durante la instalación del servidor o en otro dispositivo, junto con la frase de contraseña del Vault.",ja:"サーバーのセットアップ時または別の端末で生成された Setup URI と、Vault のパスフレーズを入力してください。",ko:"서버 설치 중에 또는 다른 기기에서 생성한 Setup URI와 보관함 패스프레이즈를 입력해 주세요.",ru:"Введите Setup URI, созданный во время установки сервера или на другом устройстве, а также парольную фразу Vault.",zh:"请输入在服务器安装期间或另一台设备上生成的 Setup URI,以及 Vault 密码短语。","zh-tw":"請輸入在伺服器安裝期間或其他裝置上產生的 Setup URI,以及 Vault 的密語。"},"Setup.UseSetupURI.GuidanceLine2":{def:'Note that you can generate a new Setup URI by running the "Copy settings as a new Setup URI" command in the command palette.',es:'Ten en cuenta que puedes generar una nueva URI de configuración ejecutando el comando "Copiar ajustes como nueva URI de configuración" desde la paleta de comandos.',ja:"コマンドパレットで「設定を新しい Setup URI としてコピー」を実行すると、新しい Setup URI を生成できます。",ko:'명령 팔레트에서 "설정을 새 Setup URI로 복사" 명령을 실행하면 새 Setup URI를 생성할 수 있습니다.',ru:"Новый Setup URI можно создать, выполнив в палитре команд команду «Скопировать настройки как новый Setup URI».",zh:"你可以在命令面板中运行“将设置复制为新的 Setup URI”命令来生成新的 Setup URI。","zh-tw":"你可以在命令面板中執行「將設定複製為新的 Setup URI」命令來產生新的 Setup URI。"},"Setup.UseSetupURI.InvalidInfo":{def:"The Setup URI is invalid. Please check it and try again.",es:"La URI de configuración no es válida. Revísala e inténtalo de nuevo.",ja:"Setup URI が無効です。内容を確認して再試行してください。",ko:"Setup URI가 올바르지 않습니다. 확인한 뒤 다시 시도해 주세요.",ru:"Setup URI некорректен. Проверьте его и попробуйте снова.",zh:"Setup URI 无效,请检查后重试。","zh-tw":"Setup URI 無效,請檢查後再試一次。"},"Setup.UseSetupURI.LabelPassphrase":{def:"Vault passphrase",es:"Frase de contraseña del Vault",ja:"Vault のパスフレーズ",ko:"보관함 패스프레이즈",ru:"Парольная фраза Vault",zh:"Vault 密码短语","zh-tw":"Vault 密語"},"Setup.UseSetupURI.LabelSetupURI":{def:"Setup URI",es:"URI de configuración",ja:"Setup URI",ko:"Setup URI",ru:"Setup URI",zh:"Setup URI","zh-tw":"Setup URI"},"Setup.UseSetupURI.PlaceholderPassphrase":{def:"Enter your vault passphrase",es:"Introduce la frase de contraseña del Vault",ja:"Vault のパスフレーズを入力してください",ko:"보관함 패스프레이즈를 입력하세요",ru:"Введите парольную фразу Vault",zh:"输入 Vault 密码短语","zh-tw":"輸入 Vault 密語"},"Setup.UseSetupURI.Title":{def:"Enter Setup URI",es:"Introducir URI de configuración",ja:"Setup URI を入力",ko:"Setup URI 입력",ru:"Ввести Setup URI",zh:"输入 Setup URI","zh-tw":"輸入 Setup URI"},"Setup.UseSetupURI.ValidInfo":{def:"The Setup URI is valid and ready to use.",es:"La URI de configuración es válida y está lista para usarse.",ja:"Setup URI は有効で、使用できます。",ko:"Setup URI가 유효하며 사용할 준비가 되었습니다.",ru:"Setup URI корректен и готов к использованию.",zh:"Setup URI 有效,可以使用。","zh-tw":"Setup URI 有效,可以使用。"},"Should we keep folders that don't have any files inside?":{def:"Should we keep folders that don't have any files inside?",es:"¿Mantener carpetas vacías?",fr:"Conserver les dossiers ne contenant aucun fichier ?",he:"האם לשמור תיקיות שאין בהן קבצים?",ja:"中にファイルがないフォルダーを保持しますか?",ko:"내부에 파일이 없는 폴더를 유지하시겠습니까?",ru:"Сохранять папки без файлов?",zh:"我们是否应该保留内部没有任何文件的文件夹?","zh-tw":"是否要保留內部沒有任何檔案的資料夾?"},"Should we only check for conflicts when a file is opened?":{def:"Should we only check for conflicts when a file is opened?",es:"¿Solo comprobar conflictos al abrir archivo?",fr:"Ne vérifier les conflits qu'à l'ouverture d'un fichier ?",he:"האם לבדוק קונפליקטים רק בעת פתיחת קובץ?",ja:"ファイルを開いたときのみ競合をチェックしますか?",ko:"파일을 열 때만 충돌을 확인하시겠습니까?",ru:"Проверять конфликты только при открытии файла?",zh:"我们是否应该仅在文件打开时检查冲突?","zh-tw":"是否只在開啟檔案時才檢查衝突?"},"Should we prompt you about conflicting files when a file is opened?":{def:"Should we prompt you about conflicting files when a file is opened?",es:"¿Notificar sobre conflictos al abrir archivo?",fr:"Vous demander au sujet des fichiers en conflit à l'ouverture d'un fichier ?",he:"האם להציג בקשה לגבי קבצים מתנגשים בעת פתיחת קובץ?",ja:"ファイルを開いたときに競合ファイルについて確認を求めますか?",ko:"파일을 열 때 충돌하는 파일에 대해 알림을 표시하시겠습니까?",ru:"Спрашивать о конфликтующих файлах при открытии файла?",zh:"当文件打开时,是否提示冲突文件?","zh-tw":"開啟檔案時,是否要提示衝突檔案?"},"Should we prompt you for every single merge, even if we can safely merge automatcially?":{def:"Should we prompt you for every single merge, even if we can safely merge automatcially?",es:"¿Preguntar en cada fusión aunque sea automática?",fr:"Vous demander pour chaque fusion, même si nous pouvons fusionner automatiquement en toute sécurité ?",he:"האם להציג בקשת אישור לכל מיזוג יחיד, גם אם ניתן למזג בבטחה אוטומטית?",ja:"自動的に安全にマージできる場合でも、すべてのマージについて確認を求めますか?",ko:"안전하게 자동 병합할 수 있는 경우에도 모든 병합에 대해 알림을 받으시겠습니까?",ru:"Спрашивать о каждом слиянии, даже если мы можем безопасно слить автоматически?",zh:"即使我们可以安全地自动合并,是否也应该为每一次合并提示您?","zh-tw":"即使可以安全地自動合併,是否仍要在每次合併時提示你?"},"Show full banner":{def:"Show full banner",es:"Mostrar banner completo",ja:"完全なバナーを表示",ko:"전체 배너 표시",ru:"Показывать полный баннер",zh:"显示完整横幅","zh-tw":"顯示完整橫幅"},"Show history":{def:"Show history",es:"Mostrar el historial",ko:"기록 표시","zh-tw":"顯示歷程"},"Show icon only":{def:"Show icon only",es:"Mostrar solo el icono",ko:"아이콘만 표시",zh:"仅显示图标","zh-tw":"僅顯示圖示"},"Show only notifications":{def:"Show only notifications",es:"Mostrar solo notificaciones",fr:"N'afficher que les notifications",he:"הצג התראות בלבד",ja:"通知のみ表示",ko:"알림만 표시",ru:"Показывать только уведомления",zh:"仅显示通知","zh-tw":"僅顯示通知"},"Show status as icons only":{def:"Show status as icons only",es:"Mostrar estado solo con íconos",fr:"N'afficher le statut que sous forme d'icônes",he:"הצג סטטוס כאייקונים בלבד",ja:"ステータス表示をアイコンのみにする",ko:"아이콘으로만 상태 표시",ru:"Показывать статус только иконками",zh:"仅以图标显示状态","zh-tw":"僅以圖示顯示狀態"},"Show status icon instead of file warnings banner":{def:"Show status icon instead of file warnings banner",es:"Mostrar icono de estado en lugar del banner de advertencia de archivos",fr:"Afficher l'icône de statut au lieu de la bannière d'avertissements",he:"הצג אייקון סטטוס במקום פס אזהרות הקובץ",ja:"ファイル警告バナーの代わりにステータスアイコンを表示",ko:"파일 경고 배너 대신 상태 아이콘 표시",ru:"Показывать иконку статуса вместо предупреждения о файлах",zh:"显示状态图标,而非文件警告横幅","zh-tw":"以狀態圖示取代檔案警告橫幅"},"Show status inside the editor":{def:"Show status inside the editor",es:"Mostrar estado dentro del editor",fr:"Afficher le statut dans l'éditeur",he:"הצג סטטוס בתוך העורך",ja:"ステータスをエディタ内に表示",ko:"편집기 내부에 상태 표시",ru:"Показывать статус внутри редактора",zh:"在编辑器内显示状态","zh-tw":"在編輯器內顯示狀態"},"Show status on the status bar":{def:"Show status on the status bar",es:"Mostrar estado en la barra de estado",fr:"Afficher le statut dans la barre d'état",he:"הצג סטטוס בשורת המצב",ja:"ステータスバーに、ステータスを表示",ko:"상태 표시줄에 상태 표시",ru:"Показывать статус в строке состояния",zh:"在状态栏上显示状态","zh-tw":"在狀態列顯示狀態"},"Show verbose log. Please enable if you report an issue.":{def:"Show verbose log. Please enable if you report an issue.",es:"Mostrar registro detallado. Actívelo si reporta un problema.",fr:"Afficher un journal verbeux. À activer si vous signalez un problème.",he:"הצג יומן מפורט. אנא הפעל אם אתה מדווח על בעיה.",ja:"エラー以外の詳細ログ項目も表示する。問題が発生した場合は有効にしてください。",ko:"자세한 로그를 표시합니다. 문제를 신고하는 경우 활성화해 주세요.",ru:"Показывать подробный лог. Пожалуйста, включите при сообщении о проблеме.",zh:"显示详细日志。如果您报告问题,请启用此选项 ","zh-tw":"顯示詳細日誌。如果你要回報問題,請啟用此選項。"},"Signaling Server Connection":{def:"Signaling Server Connection",es:"Conexión al servidor de señalización",ko:"시그널링 서버 연결","zh-tw":"訊號伺服器連線"},"Signalling Status":{def:"Signalling Status",es:"Estado de la señalización",ko:"시그널링 상태","zh-tw":"訊號狀態"},"Skip and close":{def:"Skip and close",es:"Omitir y cerrar",ko:"건너뛰고 닫기","zh-tw":"略過並關閉"},Snippets:{def:"Snippets",es:"Fragmentos",ko:"스니펫","zh-tw":"程式碼片段"},"Some devices have differing progress values (max: ${maxProgress}, min: ${minProgress}).\nThis may indicate that some devices have not completed synchronisation, which could lead to conflicts. Strongly recommend confirming that all devices are synchronised before proceeding.":{def:"Some devices have differing progress values (max: ${maxProgress}, min: ${minProgress}).\nThis may indicate that some devices have not completed synchronisation, which could lead to conflicts. Strongly recommend confirming that all devices are synchronised before proceeding.",es:"Algunos dispositivos tienen valores de progreso distintos (máx.: ${maxProgress}, mín.: ${minProgress}).\nEsto puede indicar que algunos no han terminado de sincronizar, lo que podría provocar conflictos. Se recomienda encarecidamente confirmar que todos los dispositivos están sincronizados antes de continuar.",ja:"一部のデバイスで進捗値が異なっています(最大: ${maxProgress}、最小: ${minProgress})。\nこれは一部のデバイスで同期が完了していない可能性を示しており、競合の原因になることがあります。続行する前に、すべてのデバイスが同期済みであることを確認することを強くおすすめします。",ko:"일부 기기의 진행 값이 다릅니다(최대: ${maxProgress}, 최소: ${minProgress}).\n이는 일부 기기가 동기화를 완료하지 않았음을 의미할 수 있으며, 충돌로 이어질 수 있습니다. 계속 진행하기 전에 모든 기기가 동기화되었는지 반드시 확인하는 것을 강력히 권장합니다.",ru:"У некоторых устройств различаются значения прогресса (макс.: ${maxProgress}, мин.: ${minProgress}).\nЭто может означать, что некоторые устройства ещё не завершили синхронизацию, что может привести к конфликтам. Настоятельно рекомендуется перед продолжением убедиться, что все устройства синхронизированы.",zh:"某些设备的进度值不同(最大:${maxProgress},最小:${minProgress})。\n这可能表示某些设备尚未完成同步,从而可能引发冲突。强烈建议在继续之前先确认所有设备都已同步。","zh-tw":"某些裝置的進度值不同(最大:${maxProgress},最小:${minProgress})。\n這可能表示某些裝置尚未完成同步,進而可能導致衝突。強烈建議在繼續之前先確認所有裝置都已同步。"},"Start Broadcasting":{def:"Start Broadcasting",es:"Iniciar difusión",ko:"브로드캐스트 시작","zh-tw":"開始廣播"},"Start change-broadcasting on Connect":{def:"Start change-broadcasting on Connect",es:"Iniciar la difusión de cambios al conectar",ko:"연결 시 변경 사항 브로드캐스트 시작","zh-tw":"連線後自動開始廣播變更"},"Start Sync & Close":{def:"Start Sync & Close",es:"Iniciar sincronización y cerrar",ko:"동기화 시작 후 닫기","zh-tw":"開始同步並關閉"},"Starts synchronisation when a file is saved.":{def:"Starts synchronisation when a file is saved.",es:"Inicia sincronización al guardar un archivo",fr:"Démarre la synchronisation à l'enregistrement d'un fichier.",he:"מתחיל סנכרון כאשר קובץ נשמר.",ja:"ファイルが保存されたときに同期を開始します。",ko:"파일이 저장될 때 동기화를 시작합니다.",ru:"Запускать синхронизацию при сохранении файла.",zh:"当文件保存时启动同步 ","zh-tw":"儲存檔案時啟動同步。"},Stat:{def:"Stat",es:"Estado",ko:"상태","zh-tw":"狀態"},Stats:{def:"Stats",es:"Estadísticas",ko:"통계","zh-tw":"統計"},"Stop ⚡":{def:"Stop ⚡",es:"Detener ⚡",ko:"중지 ⚡","zh-tw":"停止 ⚡"},"Stop Broadcasting":{def:"Stop Broadcasting",es:"Detener difusión",ko:"브로드캐스트 중지","zh-tw":"停止廣播"},"Stop reflecting database changes to storage files.":{def:"Stop reflecting database changes to storage files.",es:"Dejar de reflejar cambios de BD en archivos",fr:"Arrêter de répercuter les modifications de la base vers les fichiers de stockage.",he:"הפסק לשקף שינויי מסד נתונים לקבצי אחסון.",ja:"データベースの変更をストレージファイルに反映させない",ko:"데이터베이스 변경 사항을 스토리지 파일에 반영하는 것을 중단합니다.",ru:"Остановить отражение изменений базы данных в файлы хранилища.",zh:"停止将数据库更改反映到存储文件 ","zh-tw":"停止將資料庫變更反映到儲存空間的檔案。"},"Stop watching for file changes.":{def:"Stop watching for file changes.",es:"Dejar de monitorear cambios en archivos",fr:"Arrêter la surveillance des modifications de fichiers.",he:"הפסק לעקוב אחר שינויי קבצים.",ja:"監視の停止",ko:"파일 변경 사항 감시를 중단합니다.",ru:"Остановить отслеживание изменений файлов.",zh:"停止监视文件更改 ","zh-tw":"停止監看檔案變更。"},"Storage -> Database":{def:"Storage -> Database",es:"Almacenamiento -> Base de datos",ko:"스토리지 -> 데이터베이스","zh-tw":"儲存空間 -> 資料庫"},"Strongly Recommended":{def:"Strongly Recommended",es:"Muy recomendado",ko:"적극 권장","zh-tw":"強烈建議"},"Suppress notification of hidden files change":{def:"Suppress notification of hidden files change",es:"Suprimir notificaciones de cambios en archivos ocultos",fr:"Supprimer les notifications de modification des fichiers cachés",he:"דחוק התראת שינוי קבצים נסתרים",ja:"隠しファイルの変更通知を抑制",ko:"숨김 파일 변경 알림 억제",ru:"Подавлять уведомления об изменении скрытых файлов",zh:"暂停隐藏文件更改的通知","zh-tw":"抑制隱藏檔案變更的通知"},"Suspend database reflecting":{def:"Suspend database reflecting",es:"Suspender reflejo de base de datos",fr:"Suspendre la répercussion dans la base",he:"השהה שיקוף מסד נתונים",ja:"データベース反映の一時停止",ko:"데이터베이스 반영 일시 중단",ru:"Приостановить отражение базы данных",zh:"暂停数据库反映","zh-tw":"暫停資料庫反映"},"Suspend file watching":{def:"Suspend file watching",es:"Suspender monitorización de archivos",fr:"Suspendre la surveillance des fichiers",he:"השהה מעקב קבצים",ja:"監視の一時停止",ko:"파일 감시 일시 중단",ru:"Приостановить отслеживание файлов",zh:"暂停文件监视","zh-tw":"暫停檔案監看"},"Switch to IDB":{def:"Switch to IDB",es:"Cambiar a IDB",ja:"IDB に切り替える",ko:"IDB로 전환",ru:"Переключиться на IDB",zh:"切换到 IDB","zh-tw":"切換至 IDB"},"Switch to IndexedDB":{def:"Switch to IndexedDB",es:"Cambiar a IndexedDB",ja:"IndexedDB に切り替える",ko:"IndexedDB로 전환",ru:"Переключиться на IndexedDB",zh:"切换到 IndexedDB","zh-tw":"切換至 IndexedDB"},Sync:{def:"Sync",es:"Sincronizar",ko:"동기화","zh-tw":"同步"},"Sync after merging file":{def:"Sync after merging file",es:"Sincronizar tras fusionar archivo",fr:"Synchroniser après fusion d'un fichier",he:"סנכרן לאחר מיזוג קובץ",ja:"ファイルがマージ(統合)された時に同期",ko:"파일 병합 후 동기화",ru:"Синхронизировать после слияния файла",zh:"合并文件后同步","zh-tw":"合併檔案後同步"},"Sync automatically after merging files":{def:"Sync automatically after merging files",es:"Sincronizar automáticamente tras fusionar archivos",fr:"Synchroniser automatiquement après fusion des fichiers",he:"סנכרן אוטומטית לאחר מיזוג קבצים",ja:"ファイルのマージ後に自動的に同期",ko:"파일 병합 후 자동으로 동기화",ru:"Синхронизировать автоматически после слияния файлов",zh:"合并文件后自动同步","zh-tw":"合併檔案後自動同步"},"Sync Mode":{def:"Sync Mode",es:"Modo de sincronización",fr:"Mode de synchronisation",he:"מצב סנכרון",ja:"同期モード",ko:"동기화 모드",ru:"Режим синхронизации",zh:"同步模式","zh-tw":"同步模式"},"Sync on Editor Save":{def:"Sync on Editor Save",es:"Sincronizar al guardar en editor",fr:"Synchroniser à l'enregistrement dans l'éditeur",he:"סנכרן בשמירת עורך",ja:"エディタでの保存時に、同期されます",ko:"편집기 저장 시 동기화",ru:"Синхронизация при сохранении в редакторе",zh:"编辑器保存时同步","zh-tw":"編輯器儲存時同步"},"Sync on File Open":{def:"Sync on File Open",es:"Sincronizar al abrir archivo",fr:"Synchroniser à l'ouverture d'un fichier",he:"סנכרן בפתיחת קובץ",ja:"ファイルを開いた時に同期",ko:"파일 열기 시 동기화",ru:"Синхронизация при открытии файла",zh:"打开文件时同步","zh-tw":"開啟檔案時同步"},"Sync on Save":{def:"Sync on Save",es:"Sincronizar al guardar",fr:"Synchroniser à l'enregistrement",he:"סנכרן בשמירה",ja:"保存時に同期",ko:"저장 시 동기화",ru:"Синхронизация при сохранении",zh:"保存时同步","zh-tw":"儲存時同步"},"Sync on Startup":{def:"Sync on Startup",es:"Sincronizar al iniciar",fr:"Synchroniser au démarrage",he:"סנכרן בהפעלה",ja:"起動時同期",ko:"시작 시 동기화",ru:"Синхронизация при запуске",zh:"启动时同步","zh-tw":"啟動時同步"},"Sync once":{def:"Sync once",es:"Sincronizar una vez",ko:"한 번 동기화","zh-tw":"同步一次"},"Synchronisation utilising journal files. You must have set up an S3/MinIO/R2 compatible object storage.":{def:"Synchronisation utilising journal files. You must have set up an S3/MinIO/R2 compatible object storage.",es:"Sincronización mediante archivos de registro. Debe haber configurado un almacenamiento de objetos compatible con S3/MinIO/R2。",ja:"ジャーナルファイルを利用する同期方式です。S3/MinIO/R2 互換のオブジェクトストレージを事前に構成しておく必要があります。",ko:"저널 파일을 활용하는 동기화 방식입니다. S3/MinIO/R2 호환 객체 스토리지를 미리 구성해 두어야 합니다.",ru:"Синхронизация с использованием файлов журнала. Необходимо заранее настроить объектное хранилище, совместимое с S3/MinIO/R2。",zh:"通过日志文件进行同步。你需要事先部署好兼容 S3/MinIO/R2 的对象存储服务。","zh-tw":"透過日誌檔進行同步。你需要事先部署好相容 S3/MinIO/R2 的物件儲存服務。"},"Synchronising files":{def:"Synchronising files",es:"Archivos sincronizados",ja:"同期するファイル",ko:"동기화할 파일",ru:"Синхронизируемые файлы",zh:"同步文件","zh-tw":"同步中的檔案"},Syncing:{def:"Syncing",es:"Sincronización",ja:"同期",ko:"동기화",ru:"Синхронизация",zh:"同步中","zh-tw":"同步中"},"Syncing...":{def:"Syncing...",es:"Sincronizando...",ko:"동기화 중입니다...","zh-tw":"同步中⋯"},"Target patterns":{def:"Target patterns",es:"Patrones objetivo",ja:"対象パターン",ko:"대상 패턴",ru:"Целевые шаблоны",zh:"目标模式","zh-tw":"目標模式"},"Test Settings and Continue":{def:"Test Settings and Continue",es:"Probar los ajustes y continuar",ko:"설정 테스트 후 계속","zh-tw":"測試設定並繼續"},"Testing only - Resolve file conflicts by syncing newer copies of the file, this can overwrite modified files. Be Warned.":{def:"Testing only - Resolve file conflicts by syncing newer copies of the file, this can overwrite modified files. Be Warned.",es:"Solo pruebas - Resolver conflictos sincronizando copias nuevas (puede sobrescribir modificaciones)",fr:"Test uniquement - Résout les conflits de fichiers en synchronisant les copies plus récentes, ce qui peut écraser des fichiers modifiés. Prudence.",he:"לבדיקה בלבד - פתור קונפליקטי קבצים על ידי סנכרון עותקים חדשים יותר של הקובץ, פעולה זו עלולה לדרוס קבצים שונו. היה מוזהר.",ja:"テスト用 - ファイルの新しいコピーを同期してファイル競合を解決します。これにより変更されたファイルが上書きされる可能性があります。注意してください。",ko:"테스트 전용 - 파일의 새로운 사본을 동기화하여 파일 충돌을 해결하며, 수정된 파일을 덮어쓸 수 있습니다. 주의하세요.",ru:"Только для тестирования - разрешать конфликты файлов синхронизацией новых копий.",zh:"仅供测试 - 通过同步文件的较新副本来解决文件冲突,这可能会覆盖修改过的文件。请注意 ","zh-tw":"僅供測試 —— 透過同步較新的檔案版本解決衝突,這可能會覆寫已修改的檔案,請注意。"},"The connection to the server has been configured successfully. As the next step,":{def:"The connection to the server has been configured successfully. As the next step,",es:"La conexión con el servidor se ha configurado correctamente. Como paso siguiente,",ko:"서버 연결이 성공적으로 구성되었습니다. 다음 단계로,","zh-tw":"與伺服器的連線已成功設定完成。接下來,"},"The delay for consecutive on-demand fetches":{def:"The delay for consecutive on-demand fetches",es:"Retraso entre obtenciones consecutivas",fr:"Le délai entre récupérations consécutives à la demande",he:"העיכוב עבור משיכות לפי דרישה עוקבות",ja:"連続したオンデマンドフェッチの遅延",ko:"연속 청크 요청 간 대기 시간",ru:"Задержка для последовательных запросов по требованию",zh:"连续按需获取的延迟","zh-tw":"連續按需抓取之間的延遲"},"The files in this Vault are almost identical to the server's.":{def:"The files in this Vault are almost identical to the server's.",es:"Los archivos de este Vault son casi idénticos a los del servidor.",ko:"이 보관함의 파일은 서버의 파일과 거의 동일합니다.","zh-tw":"此 Vault 中的檔案幾乎與伺服器上的相同。"},"The following accepted nodes are missing its node information:\n- ${missingNodes}\n\nThis indicates that they have not been connected for some time or have been left on an older version.\nIt is preferable to update all devices if possible. If you have any devices that are no longer in use, you can clear all accepted nodes by locking the remote once.":{def:"The following accepted nodes are missing its node information:\n- ${missingNodes}\n\nThis indicates that they have not been connected for some time or have been left on an older version.\nIt is preferable to update all devices if possible. If you have any devices that are no longer in use, you can clear all accepted nodes by locking the remote once.",es:"A los siguientes nodos aceptados les falta su información de nodo:\n- ${missingNodes}\n\nEsto indica que llevan tiempo sin conectarse o que se han quedado en una versión antigua.\nSi es posible, conviene actualizar todos los dispositivos. Si tienes dispositivos que ya no usas, puedes borrar todos los nodos aceptados bloqueando el remoto una vez.",ja:"次の承認済みノードにはノード情報がありません:\n- ${missingNodes}\n\nこれは、それらがしばらく接続されていないか、古いバージョンのままになっていることを示しています。\n可能であれば、まずすべてのデバイスを更新することをおすすめします。すでに使用していないデバイスがある場合は、リモートを一度ロックすることで承認済みノードをすべてクリアできます。",ko:"다음 승인된 노드에는 노드 정보가 없습니다:\n- ${missingNodes}\n\n이는 해당 노드가 한동안 연결되지 않았거나 이전 버전에 머물러 있음을 의미합니다.\n가능하다면 먼저 모든 기기를 업데이트하는 것이 좋습니다. 더 이상 사용하지 않는 기기가 있다면 원격을 한 번 잠가 승인된 노드를 모두 정리할 수 있습니다.",ru:"Для следующих принятых узлов отсутствует информация об узле:\n- ${missingNodes}\n\nЭто означает, что они давно не подключались или остались на старой версии.\nПо возможности рекомендуется сначала обновить все устройства. Если у вас есть устройства, которые больше не используются, вы можете очистить список всех принятых узлов, один раз заблокировав удалённую базу.",zh:"以下已接受节点缺少节点信息:\n- ${missingNodes}\n\n这表示它们已有一段时间未连接,或仍停留在较旧版本。\n如有可能,建议先更新所有设备。如果有已不再使用的设备,可以先锁定一次远程端以清除全部已接受节点。","zh-tw":"以下已接受節點缺少節點資訊:\n- ${missingNodes}\n\n這表示它們已有一段時間未連線,或仍停留在較舊版本。\n如有可能,建議先更新所有裝置。如果有已不再使用的裝置,可以先鎖定一次遠端端以清除全部已接受節點。"},"The Group ID and passphrase are used to identify your group of devices. Make sure to use the same Group ID and passphrase on all devices you want to synchronise.":{def:"The Group ID and passphrase are used to identify your group of devices. Make sure to use the same Group ID and passphrase on all devices you want to synchronise.",es:"El ID de grupo y la frase de contraseña identifican tu grupo de dispositivos. Usa el mismo ID de grupo y la misma frase de contraseña en todos los dispositivos que quieras sincronizar.",ko:"그룹 ID와 패스프레이즈는 기기 그룹을 식별하는 데 사용됩니다. 동기화하려는 모든 기기에서 동일한 그룹 ID와 패스프레이즈를 사용해야 합니다.","zh-tw":"群組 ID 與密語用於識別你的裝置群組。請確保所有要同步的裝置都使用相同的群組 ID 與密語。"},"The Hash algorithm for chunk IDs":{def:"The Hash algorithm for chunk IDs",es:"Algoritmo hash para IDs de chunks",fr:"L'algorithme de hachage pour les identifiants de fragments",he:"אלגוריתם Hash עבור מזהי נתחים",ja:"チャンクIDのハッシュアルゴリズム",ko:"청크 ID용 해시 알고리즘",ru:"Хэш-алгоритм для ID чанков",zh:"块 ID 的哈希算法(实验性)","zh-tw":"chunk ID 的雜湊演算法"},"The IndexedDB adapter often offers superior performance in certain scenarios, but it has been found to cause memory leaks when used with LiveSync mode. When using LiveSync mode, please use IDB adapter instead.":{def:"The IndexedDB adapter often offers superior performance in certain scenarios, but it has been found to cause memory leaks when used with LiveSync mode. When using LiveSync mode, please use IDB adapter instead.",es:"El adaptador IndexedDB suele ofrecer mejor rendimiento en ciertos casos, pero se ha comprobado que provoca fugas de memoria con el modo LiveSync. Si usas el modo LiveSync, utiliza en su lugar el adaptador IDB.",ko:"IndexedDB 어댑터는 특정 상황에서 더 나은 성능을 보이는 경우가 많지만, LiveSync 모드에서 사용하면 메모리 누수를 일으키는 것으로 확인되었습니다. LiveSync 모드를 사용할 때는 IDB 어댑터를 사용해 주세요.","zh-tw":"IndexedDB 轉接器在某些情況下通常能提供較佳效能,但在 LiveSync 模式下已發現可能導致記憶體洩漏。使用 LiveSync 模式時,請改用 IDB 轉接器。"},"the latest synchronisation data will be downloaded from the server to this device.":{def:"the latest synchronisation data will be downloaded from the server to this device.",es:"se descargarán a este dispositivo los datos de sincronización más recientes del servidor.",ko:"서버의 최신 동기화 데이터를 이 기기로 내려받습니다.","zh-tw":"最新的同步資料將從伺服器下載到此裝置。"},"the local database, that is to say the synchronisation information, must be reconstituted.":{def:"the local database, that is to say the synchronisation information, must be reconstituted.",es:"hay que reconstruir la base de datos local, es decir, la información de sincronización.",ko:"로컬 데이터베이스, 즉 동기화 정보를 다시 구성해야 합니다.","zh-tw":"本機資料庫,也就是同步資訊,必須重新建立。"},"The maximum duration for which chunks can be incubated within the document. Chunks exceeding this period will graduate to independent chunks.":{def:"The maximum duration for which chunks can be incubated within the document. Chunks exceeding this period will graduate to independent chunks.",es:"Duración máxima para incubar chunks. Excedentes se independizan",fr:"La durée maximale pendant laquelle les fragments peuvent être incubés dans le document. Les fragments dépassant cette période seront promus en fragments indépendants.",he:"משך הזמן המקסימלי שנתחים יכולים להישמר זמנית בתוך המסמך. נתחים שחורגים מתקופה זו יהפכו לנתחים עצמאיים.",ja:"ドキュメント内でチャンクを保持できる最大期間。この期間を超えたチャンクは独立したチャンクに昇格します。",ko:"청크를 문서 안에 임시 보관할 수 있는 최대 기간입니다. 이 기간을 넘긴 청크는 독립된 청크로 분리됩니다.",ru:"The maximum duration for which chunks can be incubated within the document. Chunks exceeding this period will graduate to independent chunks.",zh:"文档中可以孵化的数据块的最大持续时间。超过此时间的数据块将成为独立数据块 ","zh-tw":"chunks 可在文件中暫存的最長時間。超過此時間的 chunks 會立即成為獨立 chunks。"},"The maximum number of chunks that can be incubated within the document. Chunks exceeding this number will immediately graduate to independent chunks.":{def:"The maximum number of chunks that can be incubated within the document. Chunks exceeding this number will immediately graduate to independent chunks.",es:"Número máximo de chunks que pueden incubarse en el documento. Excedentes se independizan",fr:"Le nombre maximum de fragments pouvant être incubés dans le document. Les fragments dépassant ce nombre seront immédiatement promus en fragments indépendants.",he:"המספר המקסימלי של נתחים שיכולים להישמר זמנית בתוך המסמך. נתחים שחורגים ממספר זה יהפכו מיד לנתחים עצמאיים.",ja:"ドキュメント内で保持できるチャンクの最大数。この数を超えたチャンクは即座に独立したチャンクに昇格します。",ko:"문서 안에 임시 보관할 수 있는 청크의 최대 개수입니다. 이 개수를 넘긴 청크는 즉시 독립된 청크로 분리됩니다.",ru:"The maximum number of chunks that can be incubated within the document. Chunks exceeding this number will immediately graduate to independent chunks.",zh:"文档中可以孵化的数据块的最大数量。超过此数量的数据块将立即成为独立数据块 ","zh-tw":"文件中可暫存的 chunks 最大數量。超過此數量的 chunks 會立即成為獨立 chunks。"},"The maximum total size of chunks that can be incubated within the document. Chunks exceeding this size will immediately graduate to independent chunks.":{def:"The maximum total size of chunks that can be incubated within the document. Chunks exceeding this size will immediately graduate to independent chunks.",es:"Tamaño total máximo de chunks incubados. Excedentes se independizan",fr:"La taille totale maximale des fragments pouvant être incubés dans le document. Les fragments dépassant cette taille seront immédiatement promus en fragments indépendants.",he:"הגודל הכולל המקסימלי של נתחים שיכולים להישמר זמנית בתוך המסמך. נתחים שחורגים מגודל זה יהפכו מיד לנתחים עצמאיים.",ja:"ドキュメント内で保持できるチャンクの最大合計サイズ。このサイズを超えたチャンクは即座に独立したチャンクに昇格します。",ko:"문서 안에 임시 보관할 수 있는 청크의 최대 총 크기입니다. 이 크기를 넘긴 청크는 즉시 독립된 청크로 분리됩니다.",ru:"The maximum total size of chunks that can be incubated within the document. Chunks exceeding this size will immediately graduate to independent chunks.",zh:"文档中可以孵化的数据块的最大总大小。超过此大小的数据块将立即成为独立数据块 ","zh-tw":"文件中可暫存的 chunks 總大小上限。超過此大小的 chunks 會立即成為獨立 chunks。"},"The minimum interval for automatic synchronisation on event.":{def:"The minimum interval for automatic synchronisation on event.",es:"Intervalo mínimo para la sincronización automática al producirse un evento.",fr:"L'intervalle minimum pour la synchronisation automatique sur événement.",he:"מרווח הזמן המינימלי לסנכרון אוטומטי על אירוע.",ja:"イベント発生時の自動同期における最小間隔です。",ko:"이벤트 발생 시 자동 동기화의 최소 간격입니다.",ru:"Минимальный интервал автоматической синхронизации по событию.",zh:"基于事件自动同步的最小间隔。","zh-tw":"事件觸發自動同步的最小間隔。"},"The remote is already set up, and the configuration is compatible (or got compatible by this operation).":{def:"The remote is already set up, and the configuration is compatible (or got compatible by this operation).",es:"El remoto ya está configurado y la configuración es compatible (o pasa a serlo con esta operación).",ko:"원격은 이미 설정되어 있으며, 구성도 호환됩니다(또는 이번 작업으로 호환되었습니다).","zh-tw":"遠端已經設定完成,且設定相容(或透過此操作變得相容)。"},"The Setup-URI does not appear to be valid. Please check that you have copied it correctly.":{def:"The Setup-URI does not appear to be valid. Please check that you have copied it correctly.",es:"El Setup-URI no parece válido. Comprueba que lo hayas copiado correctamente.",ko:"Setup-URI가 유효하지 않은 것으로 보입니다. 올바르게 복사했는지 확인해 주세요.","zh-tw":"這個 Setup URI 似乎無效,請檢查是否複製正確。"},"The Setup-URI is valid and ready to use.":{def:"The Setup-URI is valid and ready to use.",es:"El Setup-URI es válido y está listo para usarse.",ko:"Setup-URI가 유효하며 사용할 준비가 되었습니다.","zh-tw":"Setup URI 有效,可以使用。"},"the single, authoritative master copy":{def:"the single, authoritative master copy",es:"la única copia maestra de referencia",ko:"유일하고 확실한 원본이 됩니다","zh-tw":"唯一且具權威性的主要複本"},"the synchronisation data on the server will be built based on the current data on this device.":{def:"the synchronisation data on the server will be built based on the current data on this device.",es:"los datos de sincronización del servidor se construirán a partir de los datos actuales de este dispositivo.",ko:"이 기기의 현재 데이터를 바탕으로 서버의 동기화 데이터를 구축합니다.","zh-tw":"伺服器上的同步資料將依此裝置目前的資料建立。"},Themes:{def:"Themes",es:"Temas",ko:"테마","zh-tw":"主題"},"There is a way to resolve this on other devices.":{def:"There is a way to resolve this on other devices.",es:"Hay una forma de resolver esto en los demás dispositivos.",ko:"다른 기기에서 이를 해결할 방법이 있습니다.","zh-tw":"在其他裝置上有辦法可以處理這個情況。"},"There may be differences between the files in this Vault and the server.":{def:"There may be differences between the files in this Vault and the server.",es:"Puede haber diferencias entre los archivos de este Vault y los del servidor.",ko:"이 보관함의 파일과 서버의 파일 사이에 차이가 있을 수 있습니다.","zh-tw":"此 Vault 中的檔案可能與伺服器上的有所不同。"},"Therefore, we ask that you exercise extreme caution when configuring server information manually. If an incorrect passphrase is entered, the data on the server will become corrupted.":{def:"Therefore, we ask that you exercise extreme caution when configuring server information manually. If an incorrect passphrase is entered, the data on the server will become corrupted.",es:"Por tanto, extrema la precaución al configurar manualmente los datos del servidor. Si introduces una frase de contraseña incorrecta, los datos del servidor se corromperán.",ko:"따라서 서버 정보를 수동으로 구성할 때에는 각별히 주의해 주시기 바랍니다. 잘못된 패스프레이즈를 입력하면 서버의 데이터가 손상됩니다.","zh-tw":"因此,在手動設定伺服器資訊時請務必格外小心。如果輸入了錯誤的密語,伺服器上的資料將會損毀。"},"This can isolate your connections between devices. Use the same Room ID for the same devices.":{def:"This can isolate your connections between devices. Use the same Room ID for the same devices.",es:"Esto permite aislar tus conexiones entre dispositivos. Usa el mismo ID de sala para los mismos dispositivos.",ko:"이를 통해 기기 간 연결을 서로 격리할 수 있습니다. 같은 기기들끼리는 동일한 룸 ID를 사용하세요.","zh-tw":"這可以將你的裝置連線彼此隔離。同一群裝置請使用相同的房間 ID。"},"This device":{def:"This device",es:"Este dispositivo",ko:"이 기기","zh-tw":"此裝置"},"This device name":{def:"This device name",es:"Nombre de este dispositivo",ko:"이 기기의 이름","zh-tw":"此裝置名稱"},"This feature enables direct synchronisation between devices. No server is required, but both devices must be online at the same time for synchronisation to occur, and some features may be limited. Internet connection is only required to signalling (detecting peers) and not for data transfer.":{def:"This feature enables direct synchronisation between devices. No server is required, but both devices must be online at the same time for synchronisation to occur, and some features may be limited. Internet connection is only required to signalling (detecting peers) and not for data transfer.",es:"Esta función permite la sincronización directa entre dispositivos. No requiere servidor, pero ambos dispositivos deben estar en línea al mismo tiempo para que la sincronización se produzca, y algunas funciones pueden ser limitadas. La conexión a Internet solo se necesita para la señalización (detección de pares), no para la transferencia de datos。",ja:"この機能では端末同士を直接同期できます。サーバーは不要ですが、同期を行うには両端末が同時にオンラインである必要があり、一部機能は制限されます。インターネット接続はシグナリング(ピア検出)にのみ必要で、データ転送自体には使われません。",ko:"기기 간에 직접 동기화하는 기능입니다. 서버는 필요 없지만 동기화가 이루어지려면 두 기기가 동시에 온라인 상태여야 하며, 일부 기능은 제한될 수 있습니다. 인터넷 연결은 시그널링(피어 탐지)에만 필요하고 데이터 전송에는 필요하지 않습니다.",ru:"Эта функция обеспечивает прямую синхронизацию между устройствами. Сервер не требуется, но для синхронизации оба устройства должны быть одновременно в сети, а некоторые функции могут быть ограничены. Подключение к Интернету нужно только для сигнализации (обнаружения пиров), а не для передачи данных。",zh:"此功能可在设备之间直接同步,无需服务器;但同步时两台设备必须同时在线,且部分功能可能受限。互联网连接仅用于信令(发现对端),不用于数据传输。","zh-tw":"此功能可在裝置之間直接同步,無需伺服器;但同步時兩台裝置必須同時在線,且部分功能可能受限。網際網路連線僅用於訊號交換(偵測對端),不用於資料傳輸。"},"This is an advanced option for users who do not have a URI or who wish to configure detailed settings.":{def:"This is an advanced option for users who do not have a URI or who wish to configure detailed settings.",es:"Esta es una opción avanzada para usuarios que no disponen de un URI o que desean configurar parámetros detallados。",ja:"URI を持っていない場合や、詳細設定を手動で行いたいユーザー向けの上級者オプションです。",ko:"URI가 없거나 세부 설정을 직접 구성하려는 사용자를 위한 고급 옵션입니다.",ru:"Это расширенный вариант для пользователей, у которых нет URI или которые хотят вручную задать подробные параметры。",zh:"这是面向没有 URI 或希望手动配置详细参数的高级选项。","zh-tw":"這是面向沒有 URI 或希望手動設定詳細參數的進階選項。"},"This is an extremely powerful operation. We strongly recommend that you copy your Vault folder to a safe location.":{def:"This is an extremely powerful operation. We strongly recommend that you copy your Vault folder to a safe location.",es:"Esta es una operación extremadamente potente. Te recomendamos encarecidamente copiar la carpeta de tu Vault a un lugar seguro.",ko:"이는 매우 강력한 작업입니다. 보관함 폴더를 안전한 위치에 복사해 두시기를 강력히 권장합니다.","zh-tw":"這是威力極強的操作。我們強烈建議你先將 Vault 資料夾複製到安全的位置。"},"This is the most suitable synchronisation method for the design. All functions are available. You must have set up a CouchDB instance.":{def:"This is the most suitable synchronisation method for the design. All functions are available. You must have set up a CouchDB instance.",es:"Este es el método de sincronización más adecuado para el diseño. Todas las funciones están disponibles. Debe tener configurada una instancia de CouchDB。",ja:"この設計に最も適した同期方式です。すべての機能が利用できます。CouchDB インスタンスを事前に構成しておく必要があります。",ko:"이 설계에 가장 적합한 동기화 방식입니다. 모든 기능을 사용할 수 있습니다. CouchDB 인스턴스를 미리 구성해 두어야 합니다.",ru:"Это наиболее подходящий для данной архитектуры способ синхронизации. Доступны все функции. Необходимо заранее развернуть экземпляр CouchDB。",zh:"这是最符合当前设计的同步方式,所有功能均可用。你需要事先部署好 CouchDB 实例。","zh-tw":"這是最符合目前設計的同步方式,所有功能皆可使用。你需要事先部署好 CouchDB 實例。"},"This passphrase will not be copied to another device. It will be set to `Default` until you configure it again.":{def:"This passphrase will not be copied to another device. It will be set to `Default` until you configure it again.",es:"Esta frase no se copia a otros dispositivos. Usará `Default` hasta reconfigurar",fr:"Cette phrase secrète ne sera pas copiée vers un autre appareil. Elle sera définie à `Default` jusqu'à ce que vous la configuriez à nouveau.",he:"ביטוי סיסמה זה לא יועתק למכשיר אחר. הוא יוגדר ל-`Default` עד שתגדיר אותו שוב.",ja:"このパスフレーズは他のデバイスにコピーされません。再度設定するまで`Default`に設定されます。",ko:"이 패스프레이즈는 다른 기기로 복사되지 않습니다. 다시 구성할 때까지 `기본값`으로 설정됩니다.",ru:"This passphrase will not be copied to another device. It will be set to `Default` until you configure it again.",zh:"此密码不会复制到另一台设备。在您再次配置之前,它将设置为 `Default` ","zh-tw":"此密語不會複製到其他裝置。在你重新設定之前,會維持為 `Default`。"},"This password is used to encrypt the connection. Use something long enough.":{def:"This password is used to encrypt the connection. Use something long enough.",es:"Esta contraseña se usa para cifrar la conexión. Usa algo suficientemente largo.",ko:"이 비밀번호는 연결을 암호화하는 데 사용됩니다. 충분히 긴 값을 사용하세요.","zh-tw":"此密碼用於加密連線,請使用足夠長的字串。"},"This procedure will first delete all existing synchronisation data from the server. Following this, the server data will be completely rebuilt, using the current state of your Vault on this device (including its local database) as":{def:"This procedure will first delete all existing synchronisation data from the server. Following this, the server data will be completely rebuilt, using the current state of your Vault on this device (including its local database) as",es:"Este procedimiento eliminará primero todos los datos de sincronización existentes en el servidor. A continuación, los datos del servidor se reconstruirán por completo usando el estado actual del Vault de este dispositivo (incluida su base de datos local) como",ko:"이 절차는 먼저 서버에서 기존 동기화 데이터를 모두 삭제합니다. 그다음 이 기기에 있는 보관함의 현재 상태(로컬 데이터베이스 포함)를 바탕으로 서버 데이터를 완전히 재구축합니다. 즉, 이 기기의 데이터가","zh-tw":"此程序將先刪除伺服器上所有現有的同步資料。之後,將以此裝置目前的 Vault 狀態(包含其本機資料庫)為"},"This setting must be the same even when connecting to multiple synchronisation destinations.":{def:"This setting must be the same even when connecting to multiple synchronisation destinations.",es:"Este ajuste debe ser el mismo incluso si te conectas a varios destinos de sincronización.",ko:"이 설정은 여러 동기화 대상에 연결하는 경우에도 동일해야 합니다.","zh-tw":"即使連線到多個同步目標,這項設定也必須保持一致。"},"This Vault is empty, or contains only new files that are not on the server.":{def:"This Vault is empty, or contains only new files that are not on the server.",es:"Este Vault está vacío o solo contiene archivos nuevos que no están en el servidor.",ko:"이 보관함은 비어 있거나, 서버에 없는 새 파일만 포함하고 있습니다.","zh-tw":"此 Vault 是空的,或只包含伺服器上沒有的新檔案。"},"This will rebuild the local database on this device using the most recent data from the server. This action is designed to resolve synchronisation inconsistencies and restore correct functionality.":{def:"This will rebuild the local database on this device using the most recent data from the server. This action is designed to resolve synchronisation inconsistencies and restore correct functionality.",es:"Esto reconstruirá la base de datos local de este dispositivo con los datos más recientes del servidor. La acción está pensada para resolver inconsistencias de sincronización y restaurar el funcionamiento correcto.",ko:"서버의 최신 데이터를 사용해 이 기기의 로컬 데이터베이스를 재구축합니다. 이 작업은 동기화 불일치를 해결하고 정상적인 동작을 복구하기 위한 것입니다.","zh-tw":"這會使用伺服器上最新的資料,重建此裝置上的本機資料庫。此操作旨在解決同步不一致的問題,並恢復正常功能。"},"This will recreate chunks for all files. If there were missing chunks, this may fix the errors.":{def:"This will recreate chunks for all files. If there were missing chunks, this may fix the errors.",es:"Esto recreará los fragmentos de todos los archivos. Si faltaban fragmentos, esto puede corregir los errores.",ja:"すべてのファイルについてチャンクを再作成します。欠損しているチャンクがあった場合、エラーが解消される可能性があります。",ko:"모든 파일의 청크를 다시 생성합니다. 누락된 청크가 있었다면 이 작업으로 오류가 해결될 수 있습니다.",ru:"Это пересоздаст чанки для всех файлов. Если какие-то чанки отсутствовали, это может исправить ошибки.",zh:"这会为所有文件重新生成 chunks。如果之前存在缺失的 chunks,这可能修复相关错误。","zh-tw":"這會為所有檔案重新建立 chunks。若先前有遺失的 chunks,這可能修復相關錯誤。"},"To minimise the creation of new conflicts":{def:"To minimise the creation of new conflicts",es:"Para minimizar la creación de nuevos conflictos",ko:"새로운 충돌 발생을 최소화하기 위해","zh-tw":"為了盡量減少新增衝突"},"Transfer Tweak":{def:"Transfer Tweak",es:"Ajustes de transferencia",ja:"転送の調整",ko:"전송 조정",ru:"Настройки передачи","zh-tw":"傳輸調校"},"TURN Credential":{def:"TURN Credential",es:"Credencial de TURN",ko:"TURN 자격 증명","zh-tw":"TURN 憑證"},"TURN server settings are only necessary if you are behind a strict NAT or firewall that prevents direct P2P connections. In most cases, you can leave these fields blank.":{def:"TURN server settings are only necessary if you are behind a strict NAT or firewall that prevents direct P2P connections. In most cases, you can leave these fields blank.",es:"Los ajustes del servidor TURN solo son necesarios si estás detrás de un NAT estricto o de un cortafuegos que impide las conexiones P2P directas. En la mayoría de los casos puedes dejar estos campos vacíos.",ko:"TURN 서버 설정은 직접적인 P2P 연결을 막는 엄격한 NAT나 방화벽 뒤에 있는 경우에만 필요합니다. 대부분의 경우 이 항목들은 비워 두어도 됩니다.","zh-tw":"只有在你身處嚴格的 NAT 或防火牆之後、無法建立直接 P2P 連線時,才需要設定 TURN 伺服器。多數情況下這些欄位可以留空。"},"TURN Server URLs (comma-separated)":{def:"TURN Server URLs (comma-separated)",es:"URL de servidores TURN (separadas por comas)",ko:"TURN 서버 URL (쉼표로 구분)","zh-tw":"TURN 伺服器網址(以逗號分隔)"},"TURN Username":{def:"TURN Username",es:"Usuario de TURN",ko:"TURN 사용자 이름","zh-tw":"TURN 使用者名稱"},"TweakMismatchResolve.Action.DisableAutoAcceptCompatible":{def:"Disable auto-accept",es:"Desactivar la aceptación automática",ko:"자동 수용 비활성화","zh-tw":"停用自動接受"},"TweakMismatchResolve.Action.Dismiss":{def:"Dismiss",es:"Descartar",fr:"Ignorer",he:"דחה",ja:"無視",ko:"무시",ru:"Отмена",zh:"Dismiss","zh-tw":"不處理"},"TweakMismatchResolve.Action.EnableAutoAcceptCompatible":{def:"Enable auto-accept",es:"Activar la aceptación automática",ko:"자동 수용 활성화","zh-tw":"啟用自動接受"},"TweakMismatchResolve.Action.UseConfigured":{def:"Use configured settings",es:"Usar los ajustes configurados",fr:"Utiliser les paramètres configurés",he:"השתמש בהגדרות המוגדרות",ja:"設定済みの設定を使用",ko:"구성된 설정 사용",ru:"Использовать настроенные параметры",zh:"Use configured settings","zh-tw":"採用已設定的值"},"TweakMismatchResolve.Action.UseMine":{def:"Update remote database settings",es:"Actualizar los ajustes de la base de datos remota",fr:"Mettre à jour les paramètres de la base distante",he:"עדכן הגדרות מסד הנתונים המרוחד",ja:"リモートデータベースの設定を更新",ko:"원격 데이터베이스 설정 업데이트",ru:"Обновить настройки удалённой базы данных",zh:"Update remote database settings","zh-tw":"更新遠端資料庫設定"},"TweakMismatchResolve.Action.UseMineAcceptIncompatible":{def:"Update remote database settings but keep as is",es:"Actualizar los ajustes de la base de datos remota, pero dejarlo como está",fr:"Mettre à jour la base distante mais garder en l'état",he:"עדכן הגדרות מסד הנתונים המרוחד אך השאר כפי שהוא",ja:"リモートデータベースの設定を更新するがそのまま維持",ko:"원격 데이터베이스 설정 업데이트하지만 그대로 유지",ru:"Обновить настройки, но оставить как есть",zh:"Update remote database settings but keep as is","zh-tw":"更新遠端資料庫設定,但保持現狀"},"TweakMismatchResolve.Action.UseMineWithRebuild":{def:"Update remote database settings and rebuild again",es:"Actualizar los ajustes de la base de datos remota y reconstruir de nuevo",fr:"Mettre à jour la base distante et reconstruire",he:"עדכן הגדרות מסד הנתונים המרוחד ובנה מחדש",ja:"リモートデータベースの設定を更新して再構築",ko:"원격 데이터베이스 설정 업데이트하고 다시 재구축",ru:"Обновить настройки и перестроить снова",zh:"Update remote database settings and rebuild again","zh-tw":"更新遠端資料庫設定並再次重建"},"TweakMismatchResolve.Action.UseRemote":{def:"Apply settings to this device",es:"Aplicar los ajustes a este dispositivo",fr:"Appliquer les paramètres à cet appareil",he:"החל הגדרות על מכשיר זה",ja:"このデバイスに設定を適用",ko:"이 기기에 설정 적용",ru:"Применить настройки к этому устройству",zh:"Apply settings to this device","zh-tw":"將設定套用到此裝置"},"TweakMismatchResolve.Action.UseRemoteAcceptIncompatible":{def:"Apply settings to this device, but and ignore incompatibility",es:"Aplicar los ajustes a este dispositivo e ignorar la incompatibilidad",fr:"Appliquer à cet appareil, mais ignorer l'incompatibilité",he:"החל הגדרות על מכשיר זה, אך התעלם מאי-תאימות",ja:"このデバイスに設定を適用し、非互換性を無視",ko:"이 기기에 설정 적용하지만 호환성 문제 무시",ru:"Применить настройки, но игнорировать несовместимость",zh:"Apply settings to this device, but and ignore incompatibility","zh-tw":"將設定套用到此裝置,並忽略不相容之處"},"TweakMismatchResolve.Action.UseRemoteWithRebuild":{def:"Apply settings to this device, and fetch again",es:"Aplicar los ajustes a este dispositivo y volver a obtener los datos",fr:"Appliquer à cet appareil et récupérer à nouveau",he:"החל הגדרות על מכשיר זה ומשוך שוב",ja:"このデバイスに設定を適用し、再フェッチ",ko:"이 기기에 설정 적용하고 다시 가져오기",ru:"Применить настройки и загрузить снова",zh:"Apply settings to this device, and fetch again","zh-tw":"將設定套用到此裝置,並再次抓取"},"TweakMismatchResolve.Message.AutoAcceptCompatibleUndefined":{def:"\nIt appears that the settings differ for each device. You can now automatically apply compatible changes to these configurations.\nWould you like to enable this `auto-accept` setting?",es:"\nParece que los ajustes son distintos en cada dispositivo. Ahora se pueden aplicar automáticamente los cambios compatibles a estas configuraciones.\n¿Quieres activar la aceptación automática (`auto-accept`)?",ko:"\n기기마다 설정이 다른 것으로 보입니다. 이제 호환되는 변경 사항은 자동으로 적용할 수 있습니다.\n이 `자동 수용` 설정을 활성화하시겠습니까?","zh-tw":"\n看起來各裝置的設定並不相同。現在可以讓相容的變更自動套用到這些設定。\n你要啟用這個「自動接受」設定嗎?"},"TweakMismatchResolve.Message.Main":{def:"\nThe settings in the remote database are as follows. These values are configured by other devices, which are synchronised with this device at least once.\n\nIf you want to use these settings, please select Use configured settings.\nIf you want to keep the settings of this device, please select Dismiss.\n\n${table}\n\n>[!TIP]\n> If you want to synchronise all settings, please use `Sync settings via markdown` after applying minimal configuration with this feature.\n\n${additionalMessage}",es:"\nLos ajustes de la base de datos remota son los siguientes. Los han configurado otros dispositivos que se han sincronizado con este al menos una vez.\n\nSi quieres usar estos ajustes, selecciona Usar los ajustes configurados.\nSi prefieres conservar los de este dispositivo, selecciona Descartar.\n\n${table}\n\n>[!TIP]\n> Si quieres sincronizar todos los ajustes, usa «Sync settings via markdown» después de aplicar la configuración mínima con esta función.\n\n${additionalMessage}",fr:"\nLes paramètres de la base distante sont les suivants. Ces valeurs sont configurées par d'autres appareils, synchronisés au moins une fois avec celui-ci.\n\nPour utiliser ces paramètres, sélectionnez Utiliser les paramètres configurés.\nPour conserver les paramètres de cet appareil, sélectionnez Ignorer.\n\n${table}\n\n>[!ASTUCE]\n> Pour synchroniser tous les paramètres, utilisez « Synchroniser les paramètres via markdown » après application de la configuration minimale avec cette fonctionnalité.\n\n${additionalMessage}",he:"\nההגדרות במסד הנתונים המרוחד הן כדלקמן. ערכים אלה הוגדרו על ידי מכשירים אחרים, אשר סונכרנו עם מכשיר זה לפחות פעם אחת.\n\nאם ברצונך להשתמש בהגדרות אלה, אנא בחר %{TweakMismatchResolve.Action.UseConfigured}.\nאם ברצונך לשמור את הגדרות מכשיר זה, אנא בחר %{TweakMismatchResolve.Action.Dismiss}.\n\n${table}\n\n>[!TIP]\n> אם ברצונך לסנכרן את כל ההגדרות, אנא השתמש ב-`סנכרון הגדרות דרך Markdown` לאחר החלת תצורה מינימלית עם תכונה זו.\n\n${additionalMessage}",ja:"\nリモートデータベースの設定は以下の通りです。これらの値は、このデバイスと少なくとも1回同期された他のデバイスによって設定されています。\n\nこれらの設定を使用する場合は、設定済みの設定を使用を選択してください。\nこのデバイスの設定を維持する場合は、無視を選択してください。\n\n${table}\n\n>[!TIP]\n> すべての設定を同期したい場合は、この機能で最小限の設定を適用した後、`Sync settings via markdown`を使用してください。\n\n${additionalMessage}",ko:"\n원격 데이터베이스의 설정은 다음과 같습니다. 이 값들은 이 기기와 최소 한 번 동기화된 다른 기기에서 구성된 것입니다.\n\n이 설정을 사용하려면 구성된 설정 사용를 선택해 주세요.\n이 기기의 설정을 유지하려면 무시를 선택해 주세요.\n\n${table}\n\n>[!TIP]\n> 모든 설정을 동기화하려면 이 기능으로 최소 구성을 적용한 후 `마크다운을 통한 설정 동기화`를 사용해 주세요.\n\n${additionalMessage}",ru:"Настройки в удалённой базе данных следующие. Эти значения настроены другими устройствами.",zh:"\nThe settings in the remote database are as follows. These values are configured by other devices, which are synchronised with this device at least once.\n\nIf you want to use these settings, please select Use configured settings.\nIf you want to keep the settings of this device, please select Dismiss.\n\n${table}\n\n>[!TIP]\n> If you want to synchronise all settings, please use `Sync settings via markdown` after applying minimal configuration with this feature.\n\n${additionalMessage}","zh-tw":"\n遠端資料庫中的設定如下。這些值由其他裝置所設定,而那些裝置至少與此裝置同步過一次。\n\n如果你想使用這些設定,請選擇「採用已設定的值」。\n如果你想保留此裝置的設定,請選擇「不處理」。\n\n${table}\n\n>[!TIP]\n> 如果你想同步所有設定,請先用此功能套用最小設定,再使用 `Sync settings via markdown`。\n\n${additionalMessage}"},"TweakMismatchResolve.Message.MainTweakResolving":{def:"Your configuration has not been matched with the one on the remote server.\n\nFollowing configuration should be matched:\n\n${table}\n\nLet us know your decision.\n\n${additionalMessage}",es:"Tu configuración no coincide con la del servidor remoto.\n\nLa siguiente configuración debería coincidir:\n\n${table}\n\nIndícanos qué decides.\n\n${additionalMessage}",fr:"Votre configuration ne correspond pas à celle du serveur distant.\n\nLa configuration suivante devrait correspondre :\n\n${table}\n\nFaites-nous part de votre décision.\n\n${additionalMessage}",he:"התצורה שלך אינה תואמת לזו שבשרת המרוחד.\n\nיש להתאים את התצורות הבאות:\n\n${table}\n\nאנא הודע לנו על החלטתך.\n\n${additionalMessage}",ja:"設定がリモートサーバーの設定と一致しません。\n\n以下の設定が一致している必要があります:\n\n${table}\n\n判断をお知らせください。\n\n${additionalMessage}",ko:"구성이 원격 서버의 것과 일치하지 않습니다.\n\n다음 구성이 일치해야 합니다:\n\n${table}\n\n결정을 알려주세요.\n\n${additionalMessage}",ru:"Ваша конфигурация не совпадает с удалённым сервером.",zh:"Your configuration has not been matched with the one on the remote server.\n\nFollowing configuration should be matched:\n\n${table}\n\nLet us know your decision.\n\n${additionalMessage}","zh-tw":"你的設定與遠端伺服器上的設定不一致。\n\n以下設定需要保持一致:\n\n${table}\n\n請告訴我們你的決定。\n\n${additionalMessage}"},"TweakMismatchResolve.Message.mineUpdated":{def:"The device configuration have been adjusted.",es:"Se ha ajustado la configuración del dispositivo.",ko:"이 기기의 구성이 조정되었습니다.","zh-tw":"此裝置的設定已調整。"},"TweakMismatchResolve.Message.remoteUpdated":{def:"The configuration stored remotely has been updated.",es:"Se ha actualizado la configuración almacenada en el remoto.",ko:"원격에 저장된 구성이 업데이트되었습니다.","zh-tw":"遠端儲存的設定已更新。"},"TweakMismatchResolve.Message.UseRemote.WarningRebuildRecommended":{def:"\n>[!NOTICE]\n> Some changes are compatible but may consume extra storage and transfer volumes. A rebuild is recommended. However, a rebuild may not be performed at present, but may be implemented in future maintenance.\n> ***Please ensure that you have time and are connected to a stable network to apply!***",es:"\n>[!NOTICE]\n> Algunos cambios son compatibles, pero pueden consumir almacenamiento y transferencia de más. Se recomienda reconstruir. De momento puede que no se reconstruya, pero podría hacerse en un mantenimiento futuro.\n> ***Asegúrate de tener tiempo y una red estable antes de aplicarlo.***",fr:"\n>[!AVIS]\n> Certains changements sont compatibles mais peuvent consommer du stockage et du trafic supplémentaires. Une reconstruction est recommandée. Cependant, elle peut ne pas être effectuée maintenant, mais pourra l'être lors d'une maintenance future.\n> ***Assurez-vous d'avoir du temps et une connexion stable pour appliquer !***",he:"\n>[!NOTICE]\n> חלק מהשינויים תואמים אך עלולים לצרוך אחסון ותעבורה נוספים. מומלצת בנייה מחדש. עם זאת, ייתכן שבנייה מחדש לא תתבצע כעת, אך תיושם בתחזוקה עתידית.\n> ***ודא שיש לך זמן ושאתה מחובר לרשת יציבה לפני ההחלה!***",ja:"\n>[!NOTICE]\n> 一部の変更は互換性がありますが、追加のストレージと転送量を消費する可能性があります。再構築をお勧めします。ただし、再構築は現時点では実行されない場合がありますが、将来のメンテナンスで実装される可能性があります。\n> ***適用には時間と安定したネットワーク接続が必要です!***",ko:"\n>[!NOTICE]\n> 일부 변경사항은 호환 가능하지만 추가 스토리지 및 전송량을 소모할 수 있습니다. 재구축을 권장합니다. 하지만 현재 재구축을 수행하지 않더라도 향후 유지보수에서 구현될 수 있습니다.\n> ***시간적 여유가 있고 안정적인 네트워크에 연결된 상태에서 적용해 주세요!***",ru:"Некоторые изменения совместимы, но могут потребовать дополнительного хранилища. Рекомендуется перестроение.",zh:"\n>[!NOTICE]\n> Some changes are compatible but may consume extra storage and transfer volumes. A rebuild is recommended. However, a rebuild may not be performed at present, but may be implemented in future maintenance.\n> ***Please ensure that you have time and are connected to a stable network to apply!***","zh-tw":"\n>[!NOTICE]\n> 部分變更雖然相容,但可能耗用額外的儲存空間與傳輸量,建議進行重建。不過目前可能不會執行重建,未來的維護作業可能會實作。\n> ***請確認你有足夠時間且網路連線穩定,再進行套用!***"},"TweakMismatchResolve.Message.UseRemote.WarningRebuildRequired":{def:"\n>[!WARNING]\n> Some remote configurations are not compatible with the local database of this device. Rebuilding the local database will be required.\n> ***Please ensure that you have time and are connected to a stable network to apply!***",es:"\n>[!WARNING]\n> Algunas configuraciones remotas no son compatibles con la base de datos local de este dispositivo. Habrá que reconstruirla.\n> ***Asegúrate de tener tiempo y una red estable antes de aplicarlo.***",fr:"\n>[!AVERTISSEMENT]\n> Certaines configurations distantes ne sont pas compatibles avec la base locale de cet appareil. Une reconstruction de la base locale sera requise.\n> ***Assurez-vous d'avoir du temps et une connexion stable pour appliquer !***",he:"\n>[!WARNING]\n> חלק מהתצורות המרוחקות אינן תואמות למסד הנתונים המקומי של מכשיר זה. נדרשת בנייה מחדש של מסד הנתונים המקומי.\n> ***ודא שיש לך זמן ושאתה מחובר לרשת יציבה לפני ההחלה!***",ja:"\n>[!WARNING]\n> 一部のリモート設定はこのデバイスのローカルデータベースと互換性がありません。ローカルデータベースの再構築が必要です。\n> ***適用には時間と安定したネットワーク接続が必要です!***",ko:"\n>[!WARNING]\n> 일부 원격 구성이 이 기기의 로컬 데이터베이스와 호환되지 않습니다. 로컬 데이터베이스 재구축이 필요합니다.\n> ***시간적 여유가 있고 안정적인 네트워크에 연결된 상태에서 적용해 주세요!***",ru:"Некоторые удалённые конфигурации несовместимы с локальной базой данных. Требуется перестроение.",zh:"\n>[!WARNING]\n> Some remote configurations are not compatible with the local database of this device. Rebuilding the local database will be required.\n> ***Please ensure that you have time and are connected to a stable network to apply!***","zh-tw":"\n>[!WARNING]\n> 部分遠端設定與此裝置的本機資料庫不相容,將需要重建本機資料庫。\n> ***請確認你有足夠時間且網路連線穩定,再進行套用!***"},"TweakMismatchResolve.Message.WarningIncompatibleRebuildRecommended":{def:"\n>[!NOTICE]\n> We have detected that some of the values are different to make incompatible the local database with the remote database.\n> Some changes are compatible but may consume extra storage and transfer volumes. A rebuild is recommended. However, a rebuild may not be performed at present, but may be implemented in future maintenance.\n> If you want to rebuild, it takes a few minutes or more. **Make sure it is safe to perform it now.**",es:"\n>[!NOTICE]\n> Hemos detectado que algunos valores difieren de forma que hacen incompatible la base de datos local con la remota.\n> Algunos cambios son compatibles, pero pueden consumir almacenamiento y transferencia de más. Se recomienda reconstruir. De momento puede que no se reconstruya, pero podría hacerse en un mantenimiento futuro.\n> Si decides reconstruir, tardará unos minutos o más. **Asegúrate de que es seguro hacerlo ahora.**",fr:"\n>[!AVIS]\n> Nous avons détecté que certaines valeurs diffèrent et rendent la base locale incompatible avec la base distante.\n> Certains changements sont compatibles mais peuvent consommer du stockage et du trafic supplémentaires. Une reconstruction est recommandée. Cependant, elle peut ne pas être effectuée maintenant, mais pourra l'être lors d'une maintenance future.\n> Si vous souhaitez reconstruire, cela prend quelques minutes ou plus. **Assurez-vous qu'il est sûr de le faire maintenant.**",he:"\n>[!NOTICE]\n> זיהינו שחלק מהערכים שונים, מה שגורם לאי-תאימות בין מסד הנתונים המקומי למרוחד.\n> חלק מהשינויים תואמים אך עלולים לצרוך אחסון ותעבורה נוספים. מומלצת בנייה מחדש. עם זאת, ייתכן שבנייה מחדש לא תתבצע כעת, אך תיושם בתחזוקה עתידית.\n> אם ברצונך לבנות מחדש, הדבר ייקח כמה דקות או יותר. **ודא שבטוח לבצע זאת עכשיו.**",ja:"\n>[!NOTICE]\n> ローカルデータベースとリモートデータベースの非互換性を引き起こす値の違いが検出されました。\n> 一部の変更は互換性がありますが、追加のストレージと転送量を消費する可能性があります。再構築をお勧めします。ただし、再構築は現時点では実行されない場合がありますが、将来のメンテナンスで実装される可能性があります。\n> 再構築を行う場合は数分以上かかります。**今実行しても安全か確認してください。**",ko:"\n>[!NOTICE]\n> 로컬 데이터베이스와 원격 데이터베이스가 호환되지 않도록 만드는 값들이 다른 것을 감지했습니다.\n> 일부 변경사항은 호환 가능하지만 추가 스토리지 및 전송량을 소모할 수 있습니다. 재구축을 권장합니다. 하지만 현재 재구축을 수행하지 않더라도 향후 유지보수에서 구현될 수 있습니다.\n> 재구축을 원한다면 몇 분 이상 소요됩니다. **지금 수행해도 안전한지 확인해 주세요.**",ru:"Обнаружены значения, несовместимые с удалённой базой данных. Рекомендуется перестроение.",zh:"\n>[!NOTICE]\n> We have detected that some of the values are different to make incompatible the local database with the remote database.\n> Some changes are compatible but may consume extra storage and transfer volumes. A rebuild is recommended. However, a rebuild may not be performed at present, but may be implemented in future maintenance.\n> If you want to rebuild, it takes a few minutes or more. **Make sure it is safe to perform it now.**","zh-tw":"\n>[!NOTICE]\n> 我們偵測到部分值不同,會使本機資料庫與遠端資料庫不相容。\n> 部分變更雖然相容,但可能耗用額外的儲存空間與傳輸量,建議進行重建。不過目前可能不會執行重建,未來的維護作業可能會實作。\n> 如果你要重建,會花上數分鐘甚至更久。**請確認現在執行是安全的。**"},"TweakMismatchResolve.Message.WarningIncompatibleRebuildRequired":{def:"\n>[!WARNING]\n> We have detected that some of the values are different to make incompatible the local database with the remote database.\n> Either local or remote rebuilds are required. Both of them takes a few minutes or more. **Make sure it is safe to perform it now.**",es:"\n>[!WARNING]\n> Hemos detectado que algunos valores difieren de forma que hacen incompatible la base de datos local con la remota.\n> Hay que reconstruir la local o la remota. Ambas cosas tardan unos minutos o más. **Asegúrate de que es seguro hacerlo ahora.**",fr:"\n>[!AVERTISSEMENT]\n> Nous avons détecté que certaines valeurs diffèrent et rendent la base locale incompatible avec la base distante.\n> Une reconstruction locale ou distante est nécessaire. L'une comme l'autre prend quelques minutes ou plus. **Assurez-vous qu'il est sûr de le faire maintenant.**",he:"\n>[!WARNING]\n> זיהינו שחלק מהערכים שונים, מה שגורם לאי-תאימות בין מסד הנתונים המקומי למרוחד.\n> נדרשת בנייה מחדש של המסד המקומי או המרוחד. שניהם ייקחו כמה דקות או יותר. **ודא שבטוח לבצע זאת עכשיו.**",ja:"\n>[!WARNING]\n> ローカルデータベースとリモートデータベースの非互換性を引き起こす値の違いが検出されました。\n> ローカルまたはリモートの再構築が必要です。どちらも数分以上かかります。**今実行しても安全か確認してください。**",ko:"\n>[!WARNING]\n> 로컬 데이터베이스와 원격 데이터베이스가 호환되지 않도록 만드는 값들이 다른 것을 감지했습니다.\n> 로컬 또는 원격 재구축이 필요합니다. 둘 다 몇 분 이상 소요됩니다. **지금 수행해도 안전한지 확인해 주세요.**",ru:"Обнаружены значения, несовместимые с удалённой базой данных. Требуется перестроение.",zh:"\n>[!WARNING]\n> We have detected that some of the values are different to make incompatible the local database with the remote database.\n> Either local or remote rebuilds are required. Both of them takes a few minutes or more. **Make sure it is safe to perform it now.**","zh-tw":"\n>[!WARNING]\n> 我們偵測到部分值不同,會使本機資料庫與遠端資料庫不相容。\n> 需要重建本機或遠端其中一方,兩者都會花上數分鐘甚至更久。**請確認現在執行是安全的。**"},"TweakMismatchResolve.Table":{def:"| Value name | This device | On Remote |\n|: --- |: ---- :|: ---- :|\n${rows}\n\n",es:"| Nombre del valor | Este dispositivo | En el remoto |\n|: --- |: ---- :|: ---- :|\n${rows}\n\n",fr:"| Nom de la valeur | Cet appareil | Sur le distant |\n|: --- |: ---- :|: ---- :|\n${rows}\n\n",he:"| שם ערך | מכשיר זה | מרוחד |\n|: --- |: ---- :|: ---- :|\n${rows}\n\n",ja:"| 値の名前 | このデバイス | リモート |\n|: --- |: ---- :|: ---- :|\n${rows}\n\n",ko:"| 값 이름 | 이 기기 | 원격 |\n|: --- |: ---- :|: ---- :|\n${rows}\n\n",ru:"| Имя значения | Это устройство | На удалённом |\n|: --- |: ---- :|: ---- :|",zh:"| Value name | This device | On Remote |\n|: --- |: ---- :|: ---- :|\n${rows}\n\n","zh-tw":"| 設定項目 | 此裝置 | 遠端 |\n|: --- |: ---- :|: ---- :|\n${rows}\n\n"},"TweakMismatchResolve.Table.Row":{def:"| ${name} | ${self} | ${remote} |",es:"| ${name} | ${self} | ${remote} |",fr:"| ${name} | ${self} | ${remote} |",he:"| ${name} | ${self} | ${remote} |",ja:"| ${name} | ${self} | ${remote} |",ko:"| ${name} | ${self} | ${remote} |",ru:"| name | self | remote |",zh:"| ${name} | ${self} | ${remote} |","zh-tw":"| ${name} | ${self} | ${remote} |"},"TweakMismatchResolve.Title":{def:"Configuration Mismatch Detected",es:"Se ha detectado una discrepancia de configuración",fr:"Incohérence de configuration détectée",he:"זוהתה אי-התאמה בתצורה",ja:"設定の不一致が検出されました",ko:"구성 불일치 감지",ru:"Обнаружено несоответствие конфигурации",zh:"Configuration Mismatch Detected","zh-tw":"偵測到設定不一致"},"TweakMismatchResolve.Title.AutoAcceptCompatible":{def:"Auto-Accept Available",es:"Aceptación automática disponible",ko:"자동 수용 사용 가능","zh-tw":"可使用自動接受"},"TweakMismatchResolve.Title.TweakResolving":{def:"Configuration Mismatch Detected",es:"Se ha detectado una discrepancia de configuración",fr:"Incohérence de configuration détectée",he:"זוהתה אי-התאמה בתצורה",ja:"設定の不一致が検出されました",ko:"구성 불일치 감지",ru:"Обнаружено несоответствие конфигурации",zh:"Configuration Mismatch Detected","zh-tw":"偵測到設定不一致"},"TweakMismatchResolve.Title.UseRemoteConfig":{def:"Use Remote Configuration",es:"Usar la configuración remota",fr:"Utiliser la configuration distante",he:"השתמש בתצורה המרוחקת",ja:"リモート設定を使用",ko:"원격 구성 사용",ru:"Использовать удалённую конфигурацию",zh:"Use Remote Configuration","zh-tw":"使用遠端設定"},"Ui.Common.Signal.Caution":{def:"CAUTION",es:"PRECAUCIÓN",ko:"주의",zh:"注意","zh-tw":"注意"},"Ui.Common.Signal.Danger":{def:"DANGER",es:"PELIGRO",ko:"위험",zh:"危险","zh-tw":"危險"},"Ui.Common.Signal.Notice":{def:"NOTICE",es:"AVISO",ko:"알림",zh:"提示","zh-tw":"提示"},"Ui.Common.Signal.Warning":{def:"WARNING",es:"ADVERTENCIA",ko:"경고",zh:"警告","zh-tw":"警告"},"Ui.Settings.Advanced.LocalDatabaseTweak":{def:"Local Database Tweak",es:"Ajuste fino de la base de datos local",ko:"로컬 데이터베이스 조정",zh:"本地数据库调整","zh-tw":"本機資料庫調校"},"Ui.Settings.Advanced.MemoryCache":{def:"Memory Cache",es:"Caché en memoria",ko:"메모리 캐시",zh:"内存缓存","zh-tw":"記憶體快取"},"Ui.Settings.Advanced.TransferTweak":{def:"Transfer Tweak",es:"Ajuste fino de la transferencia",ko:"전송 조정",zh:"传输调整","zh-tw":"傳輸調校"},"Ui.Settings.Common.Analyse":{def:"Analyse",es:"Analizar",ko:"분석",zh:"分析","zh-tw":"分析"},"Ui.Settings.Common.Back":{def:"Back",es:"Volver",ko:"뒤로",zh:"返回","zh-tw":"返回"},"Ui.Settings.Common.Check":{def:"Check",es:"Comprobar",ko:"확인",zh:"检查","zh-tw":"檢查"},"Ui.Settings.Common.Configure":{def:"Configure",es:"Configurar",ko:"설정",zh:"配置","zh-tw":"設定"},"Ui.Settings.Common.Continue":{def:"Continue",es:"Continuar",ko:"계속",zh:"继续","zh-tw":"繼續"},"Ui.Settings.Common.Delete":{def:"Delete",es:"Eliminar",ko:"삭제",zh:"删除","zh-tw":"刪除"},"Ui.Settings.Common.Fetch":{def:"Fetch",es:"Obtener",ko:"가져오기",zh:"获取","zh-tw":"抓取"},"Ui.Settings.Common.Lock":{def:"Lock",es:"Bloquear",ko:"잠금",zh:"锁定","zh-tw":"鎖定"},"Ui.Settings.Common.Merge":{def:"Merge",es:"Combinar",ko:"병합",zh:"合并","zh-tw":"合併"},"Ui.Settings.Common.Open":{def:"Open",es:"Abrir",ko:"열기",zh:"打开","zh-tw":"開啟"},"Ui.Settings.Common.Overwrite":{def:"Overwrite",es:"Sobrescribir",ko:"덮어쓰기",zh:"覆盖","zh-tw":"覆寫"},"Ui.Settings.Common.Perform":{def:"Perform",es:"Ejecutar",ko:"실행",zh:"执行","zh-tw":"執行"},"Ui.Settings.Common.ResetAll":{def:"Reset all",es:"Restablecer todo",ko:"모두 재설정",zh:"全部重置","zh-tw":"全部重設"},"Ui.Settings.Common.ResolveAll":{def:"Resolve All",es:"Resolver todo",ko:"모두 해결",zh:"全部解决","zh-tw":"全部處理"},"Ui.Settings.Common.Scan":{def:"Scan",es:"Analizar",ko:"검사",zh:"扫描","zh-tw":"掃描"},"Ui.Settings.Common.Send":{def:"Send",es:"Enviar",ko:"보내기",zh:"发送","zh-tw":"傳送"},"Ui.Settings.Common.Use":{def:"Use",es:"Usar",ko:"사용",zh:"使用","zh-tw":"使用"},"Ui.Settings.Common.VerifyAll":{def:"Verify all",es:"Verificar todo",ko:"모두 검증",zh:"全部校验","zh-tw":"全部驗證"},"Ui.Settings.CustomizationSync.OpenDesc":{def:"Open the dialog",es:"Abre el diálogo",ko:"대화상자 열기",zh:"打开此对话框","zh-tw":"開啟對話框"},"Ui.Settings.CustomizationSync.Panel":{def:"Customization Sync",es:"Sincronización de personalizaciones",ko:"사용자 설정 동기화",zh:"自定义同步","zh-tw":"自訂同步"},"Ui.Settings.CustomizationSync.WarnChangeDeviceName":{def:"We cannot change the device name while this feature is enabled. Please disable this feature to change the device name.",es:"No se puede cambiar el nombre del dispositivo mientras esta función esté activada. Desactívala para poder cambiarlo.",ko:"이 기능이 활성화되어 있는 동안에는 기기 이름을 변경할 수 없습니다. 기기 이름을 변경하려면 이 기능을 비활성화하세요.",zh:"启用此功能时无法修改设备名称。请先关闭此功能,再修改设备名称。","zh-tw":"啟用此功能時無法變更裝置名稱。請先停用此功能,才能變更裝置名稱。"},"Ui.Settings.CustomizationSync.WarnSetDeviceName":{def:"Please set device name to identify this device. This name should be unique among your devices. While not configured, we cannot enable this feature.",es:"Establece un nombre para identificar este dispositivo. Debe ser único entre tus dispositivos. Mientras no esté configurado, no se puede activar esta función.",ko:"이 기기를 식별할 기기 이름을 설정해 주세요. 이 이름은 기기 간에 고유해야 합니다. 설정하기 전까지는 이 기능을 활성화할 수 없습니다.",zh:"请先设置用于标识此设备的设备名称。该名称应在你的设备之间保持唯一。未设置前无法启用此功能。","zh-tw":"請設定用來識別此裝置的裝置名稱。此名稱在你所有裝置中應該是唯一的。尚未設定時,無法啟用此功能。"},"Ui.Settings.Hatch.AnalyseDatabaseUsage":{def:"Analyse database usage",es:"Analizar el uso de la base de datos",ko:"데이터베이스 사용량 분석",zh:"分析数据库使用情况","zh-tw":"分析資料庫使用情況"},"Ui.Settings.Hatch.AnalyseDatabaseUsageDesc":{def:"Analyse database usage and generate a TSV report for diagnosis yourself. You can paste the generated report with any spreadsheet you like.",es:"Analiza el uso de la base de datos y genera un informe TSV para que puedas diagnosticarlo tú mismo. Puedes pegar el informe generado en la hoja de cálculo que prefieras.",ko:"데이터베이스 사용량을 분석하고 직접 진단할 수 있도록 TSV 보고서를 생성합니다. 생성된 보고서는 원하는 스프레드시트에 붙여 넣어 확인할 수 있습니다.",zh:"分析数据库使用情况,并生成 TSV 报告供你自行诊断。你可以将生成的报告粘贴到任意电子表格工具中查看。","zh-tw":"分析資料庫使用情況並產生 TSV 報告,方便你自行診斷。你可以將產生的報告貼到任何慣用的試算表中查看。"},"Ui.Settings.Hatch.BackToNonConfigured":{def:"Back to non-configured",es:"Volver al estado sin configurar",ko:"미구성 상태로 되돌리기",zh:"返回未配置状态","zh-tw":"恢復為未設定狀態"},"Ui.Settings.Hatch.ConvertNonObfuscated":{def:"Check and convert non-path-obfuscated files",es:"Comprobar y convertir los archivos sin ruta ofuscada",ko:"경로 난독화되지 않은 파일 검사 및 변환",zh:"检查并转换未进行路径混淆的文件","zh-tw":"檢查並轉換未進行路徑混淆的檔案"},"Ui.Settings.Hatch.ConvertNonObfuscatedDesc":{def:"Check the local database for files that were stored without path obfuscation and convert them when needed.",es:"Comprueba si la base de datos local contiene archivos guardados sin ofuscación de ruta y los convierte si hace falta.",ko:"경로 난독화 없이 저장된 파일이 있는지 로컬 데이터베이스를 확인하고, 필요하면 변환합니다.",zh:"检查本地数据库中未按路径混淆方式存储的文件,并在需要时将其转换为正确格式。","zh-tw":"檢查本機資料庫中未以路徑混淆方式儲存的檔案,並在需要時進行轉換。"},"Ui.Settings.Hatch.CopyIssueReport":{def:"Copy Report to clipboard",es:"Copiar el informe al portapapeles",ko:"보고서를 클립보드에 복사",zh:"复制报告到剪贴板","zh-tw":"將報告複製到剪貼簿"},"Ui.Settings.Hatch.DatabaseLabel":{def:"Database: ${details}",es:"Base de datos: ${details}",ko:"데이터베이스: ${details}",zh:"数据库:${details}","zh-tw":"資料庫:${details}"},"Ui.Settings.Hatch.DatabaseToStorage":{def:"Database -> Storage",es:"Base de datos -> Almacenamiento",ko:"데이터베이스 -> 스토리지",zh:"数据库 -> 存储","zh-tw":"資料庫 -> 儲存空間"},"Ui.Settings.Hatch.DeleteCustomizationSyncData":{def:"Delete all customization sync data",es:"Eliminar todos los datos de la sincronización de personalizaciones",ko:"모든 사용자 설정 동기화 데이터 삭제",zh:"删除所有自定义同步数据","zh-tw":"刪除所有自訂同步資料"},"Ui.Settings.Hatch.GeneratedReport":{def:"Generated report",es:"Informe generado",ko:"생성된 보고서",zh:"已生成的报告","zh-tw":"已產生的報告"},"Ui.Settings.Hatch.Missing":{def:"Missing",es:"Falta",ko:"누락됨",zh:"缺失","zh-tw":"缺失"},"Ui.Settings.Hatch.ModifiedSize":{def:"Modified: ${modified}, Size: ${size}",es:"Modificado: ${modified}, tamaño: ${size}",ko:"수정: ${modified}, 크기: ${size}",zh:"修改时间:${modified},大小:${size}","zh-tw":"修改時間:${modified},大小:${size}"},"Ui.Settings.Hatch.ModifiedSizeActual":{def:"Modified: ${modified}, Size: ${size} (actual size: ${actualSize})",es:"Modificado: ${modified}, tamaño: ${size} (tamaño real: ${actualSize})",ko:"수정: ${modified}, 크기: ${size} (실제 크기: ${actualSize})",zh:"修改时间:${modified},大小:${size}(实际大小:${actualSize}","zh-tw":"修改時間:${modified},大小:${size}(實際大小:${actualSize}"},"Ui.Settings.Hatch.PrepareIssueReport":{def:"Prepare the 'report' to create an issue",es:"Preparar el «informe» para abrir una incidencia",ko:"이슈 생성을 위한 '보고서' 준비",zh:"准备用于提交问题的报告","zh-tw":"準備建立 Issue 用的「報告」"},"Ui.Settings.Hatch.RecoveryAndRepair":{def:"Recovery and Repair",es:"Recuperación y reparación",ko:"복구 및 수리",zh:"恢复与修复","zh-tw":"修復與修補"},"Ui.Settings.Hatch.RecreateAll":{def:"Recreate all",es:"Recrear todo",ko:"모두 다시 생성",zh:"全部重建","zh-tw":"全部重建"},"Ui.Settings.Hatch.RecreateMissingChunks":{def:"Recreate missing chunks for all files",es:"Recrear los chunks que faltan de todos los archivos",ko:"모든 파일의 누락된 청크 다시 생성",zh:"为所有文件重新创建缺失的数据块","zh-tw":"為所有檔案重建遺失的 chunks"},"Ui.Settings.Hatch.RecreateMissingChunksDesc":{def:"This will recreate chunks for all files. If there were missing chunks, this may fix the errors.",es:"Recrea los chunks de todos los archivos. Si faltaban chunks, esto puede corregir los errores.",ko:"모든 파일의 청크를 다시 생성합니다. 누락된 청크가 있었다면 이 작업으로 오류가 해결될 수 있습니다.",zh:"此操作会为所有文件重新创建数据块。如果存在缺失的数据块,可能会修复相关错误。","zh-tw":"這會為所有檔案重新建立 chunks。若先前有遺失的 chunks,這可能修復相關錯誤。"},"Ui.Settings.Hatch.ResetPanel":{def:"Reset",es:"Restablecer",ko:"재설정",zh:"重置","zh-tw":"重設"},"Ui.Settings.Hatch.ResetRemoteUsage":{def:"Reset notification threshold and check the remote database usage",es:"Restablecer el umbral de aviso y comprobar el uso de la base de datos remota",ko:"알림 임계값을 초기화하고 원격 데이터베이스 사용량 확인",zh:"重置通知阈值并检查远程数据库使用情况","zh-tw":"重設通知閾值並檢查遠端資料庫使用情況"},"Ui.Settings.Hatch.ResetRemoteUsageDesc":{def:"Reset the remote storage size threshold and check the remote storage size again.",es:"Restablece el umbral de tamaño del almacenamiento remoto y vuelve a comprobar su tamaño.",ko:"원격 저장소 크기 임계값을 초기화하고 원격 저장소 크기를 다시 확인합니다.",zh:"重置远程存储大小阈值,并再次检查远程存储大小。","zh-tw":"重設遠端儲存空間大小閾值,並再次檢查遠端儲存空間大小。"},"Ui.Settings.Hatch.ResolveAllConflictedFiles":{def:"Resolve all conflicted files by the newer one",es:"Resolver todos los archivos en conflicto con el más reciente",ko:"충돌한 모든 파일을 최신 버전으로 해결",zh:"使用较新的版本解决所有冲突文件","zh-tw":"將所有衝突檔案統一為較新的版本"},"Ui.Settings.Hatch.ResolveAllConflictedFilesDesc":{def:"Resolve all conflicted files by the newer one. Caution: This will overwrite the older one, and cannot resurrect the overwritten one.",es:"Resuelve todos los archivos en conflicto quedándose con el más reciente. Atención: esto sobrescribe el más antiguo y no se puede recuperar.",ko:"충돌한 모든 파일을 더 최신 버전으로 해결합니다. 주의: 이전 버전은 덮어써지며 복원할 수 없습니다.",zh:"使用较新的版本解决所有冲突文件。注意:此操作会覆盖较旧版本,且无法恢复被覆盖的内容。","zh-tw":"將所有衝突檔案統一保留較新的版本。注意:這會覆寫較舊的版本,且被覆寫的內容無法復原。"},"Ui.Settings.Hatch.RunDoctor":{def:"Run Doctor",es:"Ejecutar el Doctor",ko:"진단 실행",zh:"运行诊断","zh-tw":"執行診斷"},"Ui.Settings.Hatch.ScanBrokenFiles":{def:"Scan for broken files",es:"Buscar archivos dañados",ko:"손상된 파일 검사",zh:"扫描损坏文件","zh-tw":"掃描損壞檔案"},"Ui.Settings.Hatch.ScramSwitches":{def:"Scram Switches",es:"Interruptores de emergencia",ko:"긴급 정지 스위치",zh:"紧急开关","zh-tw":"緊急處置開關"},"Ui.Settings.Hatch.ShowHistory":{def:"Show history",es:"Mostrar el historial",ko:"기록 표시",zh:"查看历史","zh-tw":"顯示歷程"},"Ui.Settings.Hatch.StorageLabel":{def:"Storage: ${details}",es:"Almacenamiento: ${details}",ko:"스토리지: ${details}",zh:"存储:${details}","zh-tw":"儲存空間:${details}"},"Ui.Settings.Hatch.StorageToDatabase":{def:"Storage -> Database",es:"Almacenamiento -> Base de datos",ko:"스토리지 -> 데이터베이스",zh:"存储 -> 数据库","zh-tw":"儲存空間 -> 資料庫"},"Ui.Settings.Hatch.VerifyAndRepairAllFiles":{def:"Verify and repair all files",es:"Verificar y reparar todos los archivos",ko:"모든 파일 검증 및 복구",zh:"校验并修复所有文件","zh-tw":"驗證並修復所有檔案"},"Ui.Settings.Hatch.VerifyAndRepairAllFilesDesc":{def:"Compare the content of files between the local database and storage. If they do not match, you will be asked which one to keep.",es:"Compara el contenido de los archivos entre la base de datos local y el almacenamiento. Si no coinciden, se te preguntará cuál conservar.",ko:"로컬 데이터베이스와 스토리지의 파일 내용을 비교합니다. 일치하지 않으면 어느 쪽을 유지할지 묻습니다.",zh:"比较本地数据库与存储中的文件内容。如果内容不一致,系统会询问你保留哪一份。","zh-tw":"比較本機資料庫與儲存空間中的檔案內容;若不一致,系統會詢問你要保留哪一份。"},"Ui.Settings.Maintenance.Cleanup":{def:"Perform cleanup",es:"Realizar limpieza",ko:"정리 실행",zh:"执行清理","zh-tw":"執行清理"},"Ui.Settings.Maintenance.CleanupDesc":{def:"Reduces storage space by discarding all non-latest revisions. This requires the same amount of free space on the remote server and the local client.",es:"Reduce el espacio de almacenamiento descartando todas las revisiones que no sean la última. Requiere la misma cantidad de espacio libre en el servidor remoto y en el cliente local.",ko:"최신 버전이 아닌 모든 리비전을 제거하여 저장 공간을 줄입니다. 이 작업을 수행하려면 원격 서버와 로컬 클라이언트에 동일한 양의 여유 공간이 필요합니다.",zh:"丢弃所有非最新修订版本,以减少存储空间占用。此操作要求远程服务器和本地客户端都具备同等大小的可用空间。","zh-tw":"透過捨棄所有非最新版本減少儲存空間占用。執行此操作時,遠端伺服器與本機用戶端都需要具備相同數量的可用空間。"},"Ui.Settings.Maintenance.DeleteLocalDatabase":{def:"Delete local database to reset or uninstall Self-hosted LiveSync",es:"Eliminar la base de datos local para restablecer o desinstalar Self-hosted LiveSync",ko:"Self-hosted LiveSync를 초기화하거나 제거하기 위해 로컬 데이터베이스를 삭제",zh:"删除本地数据库以重置或卸载 Self-hosted LiveSync","zh-tw":"刪除本機資料庫以重設或解除安裝 Self-hosted LiveSync"},"Ui.Settings.Maintenance.EmergencyRestart":{def:"Emergency restart",es:"Reinicio de emergencia",ko:"긴급 재시작",zh:"紧急重启","zh-tw":"緊急重新啟動"},"Ui.Settings.Maintenance.EmergencyRestartDesc":{def:"Disable all synchronisation and restart.",es:"Desactiva toda la sincronización y reinicia.",ko:"모든 동기화를 비활성화하고 재시작합니다.",zh:"禁用所有同步并重新启动。","zh-tw":"停用所有同步並重新啟動。"},"Ui.Settings.Maintenance.FreshStartWipe":{def:"Fresh Start Wipe",es:"Borrado para empezar de cero",ko:"초기화 후 새로 시작",zh:"全新开始清空","zh-tw":"全新開始清除"},"Ui.Settings.Maintenance.FreshStartWipeDesc":{def:"Delete all data on the remote server.",es:"Elimina todos los datos del servidor remoto.",ko:"원격 서버의 모든 데이터를 삭제합니다.",zh:"删除远程服务器上的所有数据。","zh-tw":"刪除遠端伺服器上的所有資料。"},"Ui.Settings.Maintenance.GarbageCollection":{def:"Garbage Collection V3 (Beta)",es:"Recolección de basura V3 (beta)",ko:"가비지 컬렉션 V3 (Beta)",zh:"垃圾回收 V3(测试版)","zh-tw":"垃圾回收 V3Beta"},"Ui.Settings.Maintenance.GarbageCollectionAction":{def:"Perform Garbage Collection",es:"Realizar la recolección de basura",ko:"가비지 컬렉션 실행",zh:"执行垃圾回收","zh-tw":"執行垃圾回收"},"Ui.Settings.Maintenance.GarbageCollectionDesc":{def:"Perform Garbage Collection to remove unused chunks and reduce database size.",es:"Realiza una recolección de basura para eliminar los chunks sin usar y reducir el tamaño de la base de datos.",ko:"사용하지 않는 청크를 제거하고 데이터베이스 크기를 줄이기 위해 가비지 컬렉션을 실행합니다.",zh:"执行垃圾回收以移除未使用的数据块并减少数据库大小。","zh-tw":"執行垃圾回收以移除未使用的 chunks 並減少資料庫大小。"},"Ui.Settings.Maintenance.LockServer":{def:"Lock Server",es:"Bloquear el servidor",ko:"서버 잠금",zh:"锁定服务器","zh-tw":"鎖定伺服器"},"Ui.Settings.Maintenance.LockServerDesc":{def:"Lock the remote server to prevent synchronisation with other devices.",es:"Bloquea el servidor remoto para impedir la sincronización con otros dispositivos.",ko:"다른 기기와 동기화되지 않도록 원격 서버를 잠급니다.",zh:"锁定远程服务器,防止与其他设备继续同步。","zh-tw":"鎖定遠端伺服器,以防止其他裝置進行同步。"},"Ui.Settings.Maintenance.OverwriteRemote":{def:"Overwrite remote",es:"Sobrescribir el remoto",ko:"원격 덮어쓰기",zh:"覆盖远程端","zh-tw":"覆寫遠端"},"Ui.Settings.Maintenance.OverwriteRemoteDesc":{def:"Overwrite remote with local DB and passphrase.",es:"Sobrescribe el remoto con la base de datos local y la frase de contraseña.",ko:"로컬 DB와 패스프레이즈로 원격을 덮어씁니다.",zh:"使用本地数据库和密码短语覆盖远程端数据。","zh-tw":"使用本機資料庫與密語覆寫遠端。"},"Ui.Settings.Maintenance.OverwriteServerData":{def:"Overwrite Server Data with This Device's Files",es:"Sobrescribir los datos del servidor con los archivos de este dispositivo",ko:"이 기기의 파일로 서버 데이터를 덮어쓰기",zh:"用此设备的文件覆盖服务器数据","zh-tw":"以此裝置的檔案覆寫伺服器資料"},"Ui.Settings.Maintenance.OverwriteServerDataDesc":{def:"Rebuild the local and remote database with files from this device.",es:"Reconstruye la base de datos local y la remota con los archivos de este dispositivo.",ko:"이 기기의 파일로 로컬과 원격 데이터베이스를 재구축합니다.",zh:"使用此设备上的文件重建本地和远程数据库。","zh-tw":"使用此裝置上的檔案重建本機與遠端資料庫。"},"Ui.Settings.Maintenance.PurgeAllJournalCounter":{def:"Purge all journal counter",es:"Purgar todos los contadores del diario",ko:"모든 저널 카운터 삭제",zh:"清空全部日志计数器","zh-tw":"清除所有日誌計數器"},"Ui.Settings.Maintenance.PurgeAllJournalCounterDesc":{def:"Purge all download and upload caches.",es:"Purga todas las cachés de descarga y de subida.",ko:"모든 다운로드 및 업로드 캐시를 제거합니다.",zh:"清空所有下载与上传缓存。","zh-tw":"清除所有下載與上傳快取。"},"Ui.Settings.Maintenance.RebuildingOperations":{def:"Rebuilding Operations (Remote Only)",es:"Operaciones de reconstrucción (solo remoto)",ko:"재구축 작업 (원격 전용)",zh:"重建操作(仅远程端)","zh-tw":"重建作業(僅遠端)"},"Ui.Settings.Maintenance.Resend":{def:"Resend",es:"Reenviar",ko:"다시 보내기",zh:"重新发送","zh-tw":"重新傳送"},"Ui.Settings.Maintenance.ResendDesc":{def:"Resend all chunks to the remote.",es:"Reenvía todos los chunks al remoto.",ko:"모든 청크를 원격으로 다시 보냅니다.",zh:"将所有数据块重新发送到远程端。","zh-tw":"將所有 chunks 重新傳送到遠端。"},"Ui.Settings.Maintenance.Reset":{def:"Reset",es:"Restablecer",ko:"재설정",zh:"重置","zh-tw":"重設"},"Ui.Settings.Maintenance.ResetAllJournalCounter":{def:"Reset all journal counter",es:"Restablecer todos los contadores del diario",ko:"모든 저널 카운터 재설정",zh:"重置全部日志计数器","zh-tw":"重設所有日誌計數器"},"Ui.Settings.Maintenance.ResetAllJournalCounterDesc":{def:"Initialise all journal history. On the next sync, every item will be received and sent again.",es:"Inicializa todo el historial del diario. En la próxima sincronización se volverán a recibir y enviar todos los elementos.",ko:"모든 저널 기록을 초기화합니다. 다음 동기화 때 모든 항목을 다시 주고받습니다.",zh:"初始化全部日志历史。下次同步时,所有项目都会重新接收并重新发送。","zh-tw":"初始化所有日誌歷史。下次同步時,每個項目都會重新接收並再次傳送。"},"Ui.Settings.Maintenance.ResetJournalReceived":{def:"Reset journal received history",es:"Restablecer el historial de recepción del diario",ko:"저널 수신 기록 재설정",zh:"重置日志接收历史","zh-tw":"重設日誌接收歷史"},"Ui.Settings.Maintenance.ResetJournalReceivedDesc":{def:"Initialise journal received history. On the next sync, every item except those sent by this device will be downloaded again.",es:"Inicializa el historial de recepción del diario. En la próxima sincronización se volverán a descargar todos los elementos salvo los enviados por este dispositivo.",ko:"저널 수신 기록을 초기화합니다. 다음 동기화 때 이 기기가 보낸 항목을 제외한 모든 항목을 다시 내려받습니다.",zh:"初始化日志接收历史。下次同步时,除当前设备发送的项目外,其余项目都会重新下载。","zh-tw":"初始化接收日誌歷程。下次同步時,除了此裝置已送出的項目外,其他項目都會再次下載。"},"Ui.Settings.Maintenance.ResetJournalSent":{def:"Reset journal sent history",es:"Restablecer el historial de envío del diario",ko:"저널 송신 기록 재설정",zh:"重置日志发送历史","zh-tw":"重設日誌傳送歷史"},"Ui.Settings.Maintenance.ResetJournalSentDesc":{def:"Initialise journal sent history. On the next sync, every item except those received by this device will be sent again.",es:"Inicializa el historial de envío del diario. En la próxima sincronización se volverán a enviar todos los elementos salvo los recibidos por este dispositivo.",ko:"저널 송신 기록을 초기화합니다. 다음 동기화 때 이 기기가 받은 항목을 제외한 모든 항목을 다시 보냅니다.",zh:"初始化日志发送历史。下次同步时,除当前设备已接收的项目外,其余项目都会重新发送。","zh-tw":"初始化傳送日誌歷程。下次同步時,除了此裝置已接收的項目外,其他項目都會再次傳送。"},"Ui.Settings.Maintenance.ResetLocalSyncInfo":{def:"Reset Synchronisation information",es:"Restablecer la información de sincronización",ko:"동기화 정보 재설정",zh:"重置同步信息","zh-tw":"重設同步資訊"},"Ui.Settings.Maintenance.ResetLocalSyncInfoDesc":{def:"Restore or reconstruct local database from remote.",es:"Restaura o reconstruye la base de datos local a partir del remoto.",ko:"원격에서 로컬 데이터베이스를 복원하거나 재구축합니다.",zh:"从远程端恢复或重建本地数据库。","zh-tw":"從遠端還原或重建本機資料庫。"},"Ui.Settings.Maintenance.ResetReceived":{def:"Reset received",es:"Restablecer lo recibido",ko:"수신 기록 재설정",zh:"重置接收记录","zh-tw":"重設接收紀錄"},"Ui.Settings.Maintenance.ResetSentHistory":{def:"Reset sent history",es:"Restablecer el historial de envíos",ko:"송신 기록 재설정",zh:"重置发送记录","zh-tw":"重設傳送歷史"},"Ui.Settings.Maintenance.ResetThisDevice":{def:"Reset Synchronisation on This Device",es:"Restablecer la sincronización en este dispositivo",ko:"이 기기의 동기화 재설정",zh:"重置此设备上的同步状态","zh-tw":"重設此裝置上的同步"},"Ui.Settings.Maintenance.ScheduleAndRestart":{def:"Schedule and Restart",es:"Programar y reiniciar",ko:"예약 후 재시작",zh:"计划执行并重启","zh-tw":"排程後重新啟動"},"Ui.Settings.Maintenance.Scram":{def:"Scram!",es:"¡Parada de emergencia!",ko:"긴급 정지",zh:"紧急处理","zh-tw":"緊急處置"},"Ui.Settings.Maintenance.SendChunks":{def:"Send chunks",es:"Enviar los chunks",ko:"청크 보내기",zh:"发送数据块","zh-tw":"傳送 chunks"},"Ui.Settings.Maintenance.Syncing":{def:"Syncing",es:"Sincronización",ko:"동기화",zh:"同步","zh-tw":"同步中"},"Ui.Settings.Maintenance.WarningLockedReadyAction":{def:"I am ready, unlock the database",es:"Estoy listo, desbloquear la base de datos",ko:"준비되었습니다. 데이터베이스 잠금 해제",zh:"我已准备好,立即解锁数据库","zh-tw":"我已準備好,解鎖資料庫"},"Ui.Settings.Maintenance.WarningLockedReadyText":{def:"To prevent unwanted vault corruption, the remote database has been locked for synchronisation. (This device is marked as 'resolved'.) When all your devices are marked as 'resolved', unlock the database. This warning will continue to appear until replication confirms the device is resolved.",es:"Para evitar que el vault se corrompa, la base de datos remota se ha bloqueado para la sincronización. (Este dispositivo está marcado como «resuelto».) Cuando todos tus dispositivos estén marcados como «resueltos», desbloquea la base de datos. Este aviso seguirá apareciendo hasta que la replicación confirme que el dispositivo está resuelto.",ko:"의도치 않은 보관함 손상을 막기 위해 원격 데이터베이스가 동기화 잠금 상태입니다. (이 기기는 '해결됨'으로 표시되어 있습니다.) 모든 기기가 '해결됨'으로 표시되면 데이터베이스 잠금을 해제하세요. 이 경고는 복제를 통해 기기가 해결되었음이 확인될 때까지 계속 표시됩니다.",zh:"为防止意外的数据仓库损坏,远程数据库已被锁定,暂停同步。(此设备已被标记为“已确认”)当你的所有设备都标记为“已确认”后,再解锁数据库。在复制过程确认此设备已完成确认之前,此警告会持续显示。","zh-tw":"為避免 Vault 發生非預期的損毀,遠端資料庫已鎖定同步。(此裝置已標記為「已處理」。)當你所有的裝置都標記為「已處理」後,即可解鎖資料庫。在複寫程序確認此裝置已處理完畢之前,這則警告會持續顯示。"},"Ui.Settings.Maintenance.WarningLockedResolveAction":{def:"I have made a backup, mark this device as resolved",es:"He hecho una copia de seguridad, marcar este dispositivo como resuelto",ko:"백업했습니다. 이 기기를 해결됨으로 표시",zh:"我已完成备份,将此设备标记为“已确认”","zh-tw":"我已完成備份,將此裝置標記為已處理"},"Ui.Settings.Maintenance.WarningLockedResolveText":{def:"The remote database is locked for synchronisation to prevent vault corruption because this device is not marked as 'resolved'. Please back up your vault, reset the local database, and select 'Mark this device as resolved'. This warning will persist until replication confirms the device is resolved.",es:"La base de datos remota está bloqueada para la sincronización a fin de evitar que el vault se corrompa, porque este dispositivo no está marcado como «resuelto». Haz una copia de seguridad de tu vault, restablece la base de datos local y selecciona «Marcar este dispositivo como resuelto». Este aviso seguirá apareciendo hasta que la replicación confirme que el dispositivo está resuelto.",ko:"이 기기가 '해결됨'으로 표시되어 있지 않아, 보관함 손상을 막기 위해 원격 데이터베이스가 동기화 잠금 상태입니다. 보관함을 백업하고 로컬 데이터베이스를 재설정한 뒤 '이 기기를 해결됨으로 표시'를 선택해 주세요. 이 경고는 복제를 통해 기기가 해결되었음이 확인될 때까지 계속 표시됩니다.",zh:"为防止数据仓库损坏,由于此设备尚未标记为“已确认”,远程数据库已被锁定,暂停同步。请先备份你的仓库、重置本地数据库,然后选择“将此设备标记为已确认”。在复制过程确认此设备已完成确认之前,此警告会持续显示。","zh-tw":"由於此裝置尚未標記為「已處理」,為避免 Vault 損毀,遠端資料庫已鎖定同步。請先備份你的 Vault、重設本機資料庫,然後選擇「將此裝置標記為已處理」。在複寫程序確認此裝置已處理完畢之前,這則警告會持續顯示。"},"Ui.Settings.Maintenance.WriteRedFlagAndRestart":{def:"Flag and restart",es:"Marcar y reiniciar",ko:"표시 후 재시작",zh:"标记并重启","zh-tw":"標記後重新啟動"},"Ui.Settings.Patches.CompatibilityConflict":{def:"Compatibility (Conflict Behaviour)",es:"Compatibilidad (comportamiento ante conflictos)",ko:"호환성 (충돌 동작)",zh:"兼容性(冲突行为)","zh-tw":"相容性(衝突行為)"},"Ui.Settings.Patches.CompatibilityDatabase":{def:"Compatibility (Database structure)",es:"Compatibilidad (estructura de la base de datos)",ko:"호환성 (데이터베이스 구조)",zh:"兼容性(数据库结构)","zh-tw":"相容性(資料庫結構)"},"Ui.Settings.Patches.CompatibilityInternalApi":{def:"Compatibility (Internal API Usage)",es:"Compatibilidad (uso de la API interna)",ko:"호환성 (내부 API 사용)",zh:"兼容性(内部 API 使用)","zh-tw":"相容性(內部 API 使用)"},"Ui.Settings.Patches.CompatibilityMetadata":{def:"Compatibility (Metadata)",es:"Compatibilidad (metadatos)",ko:"호환성 (메타데이터)",zh:"兼容性(元数据)","zh-tw":"相容性(中繼資料)"},"Ui.Settings.Patches.CompatibilityRemote":{def:"Compatibility (Remote Database)",es:"Compatibilidad (base de datos remota)",ko:"호환성 (원격 데이터베이스)",zh:"兼容性(远程数据库)","zh-tw":"相容性(遠端資料庫)"},"Ui.Settings.Patches.CompatibilityTrouble":{def:"Compatibility (Trouble addressed)",es:"Compatibilidad (problemas resueltos)",ko:"호환성 (문제 대응)",zh:"兼容性(已处理问题)","zh-tw":"相容性(問題修復)"},"Ui.Settings.Patches.CurrentAdapter":{def:"Current adapter: ${adapter}",es:"Adaptador actual: ${adapter}",ko:"현재 어댑터: ${adapter}",zh:"当前适配器:${adapter}","zh-tw":"目前的轉接器:${adapter}"},"Ui.Settings.Patches.DatabaseAdapter":{def:"Database Adapter",es:"Adaptador de base de datos",ko:"데이터베이스 어댑터",zh:"数据库适配器","zh-tw":"資料庫轉接器"},"Ui.Settings.Patches.DatabaseAdapterDesc":{def:"Select the database adapter to use.",es:"Selecciona el adaptador de base de datos que se va a usar.",ko:"사용할 데이터베이스 어댑터를 선택합니다.",zh:"选择要使用的数据库适配器。","zh-tw":"選擇要使用的資料庫轉接器。"},"Ui.Settings.Patches.EdgeCaseBehaviour":{def:"Edge case addressing (Behaviour)",es:"Casos límite (comportamiento)",ko:"특수 상황 처리 (동작)",zh:"边界情况处理(行为)","zh-tw":"邊緣情況處理(行為)"},"Ui.Settings.Patches.EdgeCaseDatabase":{def:"Edge case addressing (Database)",es:"Casos límite (base de datos)",ko:"특수 상황 처리 (데이터베이스)",zh:"边界情况处理(数据库)","zh-tw":"邊緣情況處理(資料庫)"},"Ui.Settings.Patches.EdgeCaseProcessing":{def:"Edge case addressing (Processing)",es:"Casos límite (procesamiento)",ko:"특수 상황 처리 (처리)",zh:"边界情况处理(处理流程)","zh-tw":"邊緣情況處理(處理)"},"Ui.Settings.Patches.IndexedDbWarning":{def:"The IndexedDB adapter often offers superior performance in certain scenarios, but it has been found to cause memory leaks when used with LiveSync mode. When using LiveSync mode, please use the IDB adapter instead.",es:"El adaptador IndexedDB suele ofrecer mejor rendimiento en ciertos casos, pero se ha comprobado que provoca fugas de memoria con el modo LiveSync. Si usas el modo LiveSync, utiliza en su lugar el adaptador IDB.",ko:"IndexedDB 어댑터는 특정 상황에서 더 나은 성능을 보이는 경우가 많지만, LiveSync 모드에서 사용하면 메모리 누수를 일으키는 것으로 확인되었습니다. LiveSync 모드를 사용할 때는 IDB 어댑터를 사용해 주세요.",zh:"IndexedDB 适配器在某些场景下通常具有更好的性能,但在 LiveSync 模式下已发现可能导致内存泄漏。使用 LiveSync 模式时,请改用 IDB 适配器。","zh-tw":"IndexedDB 轉接器在某些情況下通常能提供較佳效能,但在 LiveSync 模式下已發現可能導致記憶體洩漏。使用 LiveSync 模式時,請改用 IDB 轉接器。"},"Ui.Settings.Patches.MigratingToIdb":{def:"Migrating all data to IDB...",es:"Migrando todos los datos a IDB...",ko:"모든 데이터를 IDB로 마이그레이션하는 중...",zh:"正在将所有数据迁移到 IDB...","zh-tw":"正在將所有資料遷移到 IDB⋯"},"Ui.Settings.Patches.MigratingToIndexedDb":{def:"Migrating all data to IndexedDB...",es:"Migrando todos los datos a IndexedDB...",ko:"모든 데이터를 IndexedDB로 마이그레이션하는 중...",zh:"正在将所有数据迁移到 IndexedDB...","zh-tw":"正在將所有資料遷移到 IndexedDB⋯"},"Ui.Settings.Patches.MigrationIdbCompleted":{def:"Migration to IDB completed. Obsidian will be restarted with the new configuration immediately.",es:"Migración a IDB completada. Obsidian se reiniciará de inmediato con la nueva configuración.",ko:"IDB로 마이그레이션이 완료되었습니다. 새 구성을 적용하기 위해 Obsidian이 곧 재시작됩니다.",zh:"已完成迁移到 IDB。Obsidian 将立即使用新配置重新启动。","zh-tw":"已完成遷移到 IDB。Obsidian 將立即以新設定重新啟動。"},"Ui.Settings.Patches.MigrationIdbCompletedFollowUp":{def:"Migration to IDB completed. Please switch the adapter and restart Obsidian.",es:"Migración a IDB completada. Cambia el adaptador y reinicia Obsidian.",ko:"IDB로 마이그레이션이 완료되었습니다. 어댑터를 전환하고 Obsidian을 재시작해 주세요.",zh:"已完成迁移到 IDB。请切换适配器并重新启动 Obsidian。","zh-tw":"已完成遷移到 IDB。請切換轉接器並重新啟動 Obsidian。"},"Ui.Settings.Patches.MigrationIndexedDbCompleted":{def:"Migration to IndexedDB completed. Obsidian will be restarted with the new configuration immediately.",es:"Migración a IndexedDB completada. Obsidian se reiniciará de inmediato con la nueva configuración.",ko:"IndexedDB로 마이그레이션이 완료되었습니다. 새 구성을 적용하기 위해 Obsidian이 곧 재시작됩니다.",zh:"已完成迁移到 IndexedDB。Obsidian 将立即使用新配置重新启动。","zh-tw":"已完成遷移到 IndexedDB。Obsidian 將立即以新設定重新啟動。"},"Ui.Settings.Patches.MigrationIndexedDbCompletedFollowUp":{def:"Migration to IndexedDB completed. Please switch the adapter and restart Obsidian.",es:"Migración a IndexedDB completada. Cambia el adaptador y reinicia Obsidian.",ko:"IndexedDB로 마이그레이션이 완료되었습니다. 어댑터를 전환하고 Obsidian을 재시작해 주세요.",zh:"已完成迁移到 IndexedDB。请切换适配器并重新启动 Obsidian。","zh-tw":"已完成遷移到 IndexedDB。請切換轉接器並重新啟動 Obsidian。"},"Ui.Settings.Patches.MigrationWarning":{def:"Changing this setting requires migrating existing data, which may take some time, and restarting Obsidian. Please make sure to back up your data before proceeding.",es:"Cambiar este ajuste requiere migrar los datos existentes, lo que puede tardar un rato, y reiniciar Obsidian. Asegúrate de hacer una copia de seguridad de tus datos antes de continuar.",ko:"이 설정을 변경하려면 기존 데이터를 마이그레이션하고(시간이 다소 걸릴 수 있습니다) Obsidian을 재시작해야 합니다. 진행하기 전에 반드시 데이터를 백업해 주세요.",zh:"修改此设置需要迁移现有数据(可能需要一些时间)并重新启动 Obsidian。请先备份你的数据后再继续。","zh-tw":"變更此設定需要遷移現有資料(可能需要一些時間),並重新啟動 Obsidian。請務必先備份資料再繼續。"},"Ui.Settings.Patches.OperationToIdb":{def:"to IDB",es:"a IDB",ko:"IDB로",zh:"迁移到 IDB","zh-tw":"遷移到 IDB"},"Ui.Settings.Patches.OperationToIndexedDb":{def:"to IndexedDB",es:"a IndexedDB",ko:"IndexedDB로",zh:"迁移到 IndexedDB","zh-tw":"遷移到 IndexedDB"},"Ui.Settings.Patches.Remediation":{def:"Remediation",es:"Remediación",ko:"복구 조치",zh:"修正","zh-tw":"修復設定"},"Ui.Settings.Patches.RemediationChanged":{def:"Remediation Setting Changed",es:"Se ha cambiado el ajuste de remediación",ko:"복구 설정이 변경됨",zh:"修正设置已更改","zh-tw":"修復設定已變更"},"Ui.Settings.Patches.RemediationNoLimit":{def:"No limit configured",es:"Sin límite configurado",ko:"제한이 설정되지 않음",zh:"未设置限制","zh-tw":"尚未設定限制"},"Ui.Settings.Patches.RemediationRestarting":{def:"Remediation setting changed. Restarting Obsidian...",es:"Se ha cambiado el ajuste de remediación. Reiniciando Obsidian...",ko:"복구 조치 설정이 변경되었습니다. Obsidian을 재시작하는 중...",zh:"修正设置已更改,正在重新启动 Obsidian...","zh-tw":"修復設定已變更,正在重新啟動 Obsidian⋯"},"Ui.Settings.Patches.RemediationRestartLater":{def:"Later",es:"Más tarde",ko:"나중에",zh:"稍后","zh-tw":"稍後"},"Ui.Settings.Patches.RemediationRestartMessage":{def:"Restarting Obsidian is strongly recommended. Until restart, some changes may not take effect, and the display may be inconsistent. Are you sure you want to restart now?",es:"Se recomienda encarecidamente reiniciar Obsidian. Hasta que lo hagas, puede que algunos cambios no surtan efecto y que la interfaz se muestre de forma inconsistente. ¿Seguro que quieres reiniciar ahora?",ko:"Obsidian을 재시작하는 것을 강력히 권장합니다. 재시작하기 전까지는 일부 변경 사항이 적용되지 않거나 화면이 일관되지 않게 표시될 수 있습니다. 지금 재시작하시겠습니까?",zh:"强烈建议重新启动 Obsidian。在重启之前,部分更改可能不会生效,界面显示也可能不一致。确定要现在重启吗?","zh-tw":"強烈建議重新啟動 Obsidian。在重新啟動之前,部分變更可能不會生效,畫面顯示也可能不一致。你確定要現在重新啟動嗎?"},"Ui.Settings.Patches.RemediationRestartNow":{def:"Restart Now",es:"Reiniciar ahora",ko:"지금 재시작",zh:"立即重启","zh-tw":"立即重新啟動"},"Ui.Settings.Patches.RemediationSuffixChanged":{def:"Suffix has been changed. Reopening database...",es:"El sufijo ha cambiado. Reabriendo la base de datos...",ko:"접미사가 변경되었습니다. 데이터베이스를 다시 여는 중...",zh:"后缀已更改,正在重新打开数据库...","zh-tw":"後綴已變更,正在重新開啟資料庫⋯"},"Ui.Settings.Patches.RemediationWithValue":{def:"Limit: ${date} (${timestamp})",es:"Límite: ${date} (${timestamp})",ko:"제한: ${date} (${timestamp})",zh:"限制:${date}${timestamp}","zh-tw":"限制:${date}${timestamp}"},"Ui.Settings.Patches.RemoteDatabaseSunset":{def:"Remote Database Tweak (In sunset)",es:"Ajuste fino de la base de datos remota (en desuso)",ko:"원격 데이터베이스 조정 (폐기 예정)",zh:"远程数据库调整(即将弃用)","zh-tw":"遠端資料庫調校(即將淘汰)"},"Ui.Settings.Patches.SwitchToIDB":{def:"Switch to IDB",es:"Cambiar a IDB",ko:"IDB로 전환",zh:"切换到 IDB","zh-tw":"切換至 IDB"},"Ui.Settings.Patches.SwitchToIndexedDb":{def:"Switch to IndexedDB",es:"Cambiar a IndexedDB",ko:"IndexedDB로 전환",zh:"切换到 IndexedDB","zh-tw":"切換至 IndexedDB"},"Ui.Settings.PowerUsers.ConfigurationEncryption":{def:"Configuration Encryption",es:"Cifrado de la configuración",ko:"구성 암호화",zh:"配置加密","zh-tw":"設定加密"},"Ui.Settings.PowerUsers.ConnectionTweak":{def:"CouchDB Connection Tweak",es:"Ajuste fino de la conexión con CouchDB",ko:"CouchDB 연결 조정",zh:"CouchDB 连接调整","zh-tw":"CouchDB 連線調校"},"Ui.Settings.PowerUsers.ConnectionTweakDesc":{def:"If you reached the payload size limit when using IBM Cloudant, please decrease batch size and batch limit to a lower value.",es:"Si alcanzas el límite de tamaño de carga al usar IBM Cloudant, reduce el tamaño de lote y el límite de lote.",ko:"IBM Cloudant를 사용하다가 페이로드 크기 제한에 도달했다면, 배치 크기와 배치 개수 제한을 더 낮은 값으로 줄여 주세요.",zh:"如果你在使用 IBM Cloudant 时遇到负载大小限制,请将 batch size 和 batch limit 调低。","zh-tw":"如果你在使用 IBM Cloudant 時遇到負載大小上限,請調低批次大小與批次上限。"},"Ui.Settings.PowerUsers.Default":{def:"Default",es:"Predeterminado",ko:"기본값",zh:"默认","zh-tw":"預設"},"Ui.Settings.PowerUsers.Developer":{def:"Developer",es:"Desarrollo",ko:"개발자",zh:"开发者","zh-tw":"開發者"},"Ui.Settings.PowerUsers.EncryptSensitiveConfig":{def:"Encrypt sensitive configuration items",es:"Cifrar los elementos sensibles de la configuración",ko:"민감한 구성 항목 암호화",zh:"加密敏感配置项","zh-tw":"加密敏感設定項目"},"Ui.Settings.PowerUsers.PromptPassphraseEveryLaunch":{def:"Ask for a passphrase at every launch",es:"Solicitar la frase de contraseña en cada inicio",ko:"시작할 때마다 패스프레이즈 묻기",zh:"每次启动时询问密码短语","zh-tw":"每次啟動時都詢問密語"},"Ui.Settings.PowerUsers.UseCustomPassphrase":{def:"Use a custom passphrase",es:"Usar una frase de contraseña personalizada",ko:"사용자 지정 패스프레이즈 사용",zh:"使用自定义密码短语","zh-tw":"使用自訂密語"},"Ui.Settings.Remote.Activate":{def:"Activate",es:"Activar",ko:"활성화",zh:"启用","zh-tw":"啟用"},"Ui.Settings.Remote.ActiveSuffix":{def:" (Active)",es:" (activo)",ko:" (활성)",zh:"(当前启用)","zh-tw":"(已啟用)"},"Ui.Settings.Remote.AddConnection":{def:"Add new connection",es:"Añadir conexión",ko:"연결 추가",zh:"新增连接","zh-tw":"新增連線"},"Ui.Settings.Remote.AddRemoteDefaultName":{def:"New Remote",es:"Remoto nuevo",ko:"새 원격",zh:"新远程端","zh-tw":"新增遠端"},"Ui.Settings.Remote.ConfigureAndChangeRemote":{def:"Configure and change remote",es:"Configurar y cambiar el remoto",ko:"원격 구성 및 변경",zh:"配置并切换远程端","zh-tw":"設定並切換遠端"},"Ui.Settings.Remote.ConfigureE2EE":{def:"Configure E2EE",es:"Configurar el E2EE",ko:"E2EE 구성",zh:"配置端到端加密","zh-tw":"設定 E2EE"},"Ui.Settings.Remote.ConfigureRemote":{def:"Configure Remote",es:"Configurar el remoto",ko:"원격 구성",zh:"配置远程端","zh-tw":"設定遠端"},"Ui.Settings.Remote.DeleteRemoteConfirm":{def:"Delete remote configuration '${name}'?",es:"¿Eliminar la configuración remota «${name}»?",ko:"'${name}' 원격 구성을 삭제할까요?",zh:"确定要删除远程配置“${name}”吗?","zh-tw":"要刪除遠端設定「${name}」嗎?"},"Ui.Settings.Remote.DeleteRemoteTitle":{def:"Delete Remote Configuration",es:"Eliminar la configuración remota",ko:"원격 구성 삭제",zh:"删除远程配置","zh-tw":"刪除遠端設定"},"Ui.Settings.Remote.DisplayName":{def:"Display name",es:"Nombre visible",ko:"표시 이름",zh:"显示名称","zh-tw":"顯示名稱"},"Ui.Settings.Remote.DuplicateRemote":{def:"Duplicate remote",es:"Duplicar el remoto",ko:"원격 구성 복사",zh:"复制远程配置","zh-tw":"複製遠端設定"},"Ui.Settings.Remote.DuplicateRemoteSuffix":{def:"${name} (Copy)",es:"${name} (copia)",ko:"${name} (사본)",zh:"${name}(副本)","zh-tw":"${name}(複製)"},"Ui.Settings.Remote.E2EEConfiguration":{def:"E2EE Configuration",es:"Configuración del E2EE",ko:"E2EE 구성",zh:"端到端加密配置","zh-tw":"E2EE 設定"},"Ui.Settings.Remote.Export":{def:"Export",es:"Exportar",ko:"내보내기",zh:"导出","zh-tw":"匯出"},"Ui.Settings.Remote.FetchRemoteSettings":{def:"Fetch remote settings",es:"Obtener los ajustes remotos",ko:"원격 설정 가져오기",zh:"获取远程设置","zh-tw":"抓取遠端設定"},"Ui.Settings.Remote.ImportConnection":{def:"Import connection",es:"Importar conexión",ko:"연결 가져오기",zh:"导入连接","zh-tw":"匯入連線"},"Ui.Settings.Remote.ImportConnectionPrompt":{def:"Paste a connection string",es:"Pega una cadena de conexión",ko:"연결 문자열 붙여넣기",zh:"粘贴连接字符串","zh-tw":"貼上連線字串"},"Ui.Settings.Remote.ImportedCouchDb":{def:"Imported CouchDB",es:"CouchDB importado",ko:"가져온 CouchDB",zh:"已导入的 CouchDB","zh-tw":"已匯入的 CouchDB"},"Ui.Settings.Remote.ImportedRemote":{def:"Remote",es:"Remoto",ko:"원격",zh:"远程端","zh-tw":"遠端"},"Ui.Settings.Remote.MoreActions":{def:"More actions",es:"Más acciones",ko:"추가 작업",zh:"更多操作","zh-tw":"更多操作"},"Ui.Settings.Remote.PeerToPeerPanel":{def:"Peer-to-Peer Synchronisation",es:"Sincronización punto a punto",ko:"피어 투 피어(P2P) 동기화",zh:"点对点同步","zh-tw":"Peer-to-Peer 同步"},"Ui.Settings.Remote.RemoteConfigurationPrefix":{def:"Remote configuration",es:"Configuración remota",ko:"원격 구성",zh:"远程配置","zh-tw":"遠端設定"},"Ui.Settings.Remote.RemoteDatabases":{def:"Remote Databases",es:"Bases de datos remotas",ko:"원격 데이터베이스",zh:"远程数据库","zh-tw":"遠端資料庫"},"Ui.Settings.Remote.RemoteName":{def:"Remote name",es:"Nombre del remoto",ko:"원격 이름",zh:"远程名称","zh-tw":"遠端名稱"},"Ui.Settings.Remote.RemoteNameCouchDb":{def:"CouchDB ${host}",es:"CouchDB ${host}",ko:"CouchDB ${host}",zh:"CouchDB ${host}","zh-tw":"CouchDB ${host}"},"Ui.Settings.Remote.RemoteNameP2P":{def:"P2P ${room}",es:"P2P ${room}",ko:"P2P ${room}",zh:"P2P ${room}","zh-tw":"P2P ${room}"},"Ui.Settings.Remote.RemoteNameS3":{def:"S3 ${bucket}",es:"S3 ${bucket}",ko:"S3 ${bucket}",zh:"S3 ${bucket}","zh-tw":"S3 ${bucket}"},"Ui.Settings.Remote.Rename":{def:"Rename",es:"Cambiar el nombre",ko:"이름 바꾸기",zh:"重命名","zh-tw":"重新命名"},"Ui.Settings.Selector.AddDefaultPatterns":{def:"Add default patterns",es:"Añadir patrones predeterminados",ko:"기본 패턴 추가",zh:"添加默认模式","zh-tw":"新增預設模式"},"Ui.Settings.Selector.CrossPlatform":{def:"Cross-platform",es:"Multiplataforma",ko:"크로스 플랫폼",zh:"跨平台","zh-tw":"跨平台"},"Ui.Settings.Selector.Default":{def:"Default",es:"Predeterminado",ko:"기본값",zh:"默认","zh-tw":"預設"},"Ui.Settings.Selector.HiddenFiles":{def:"Hidden Files",es:"Archivos ocultos",ko:"숨김 파일",zh:"隐藏文件","zh-tw":"隱藏檔案"},"Ui.Settings.Selector.IgnorePatterns":{def:"Ignore patterns",es:"Patrones de exclusión",ko:"무시 패턴",zh:"忽略模式","zh-tw":"忽略模式"},"Ui.Settings.Selector.NonSynchronisingFiles":{def:"Non-Synchronising files",es:"Archivos que no se sincronizan",ko:"동기화하지 않는 파일",zh:"不同步文件","zh-tw":"不同步的檔案"},"Ui.Settings.Selector.NonSynchronisingFilesDesc":{def:"(RegExp) If this is set, any changes to local and remote files that match this will be skipped.",es:"(RegExp) Si se establece, se omitirá cualquier cambio en archivos locales y remotos que coincida con este patrón.",ko:"(정규식) 설정하면 이 패턴과 일치하는 로컬 및 원격 파일 변경은 모두 건너뜁니다.",zh:"RegExp)如果设置了该项,则本地和远程中匹配这些规则的文件变更将被跳过。","zh-tw":"(正則表示式)若已設定,所有符合此模式的本機與遠端檔案變更都會被略過。"},"Ui.Settings.Selector.NormalFiles":{def:"Normal Files",es:"Archivos normales",ko:"일반 파일",zh:"普通文件","zh-tw":"一般檔案"},"Ui.Settings.Selector.OverwritePatterns":{def:"Overwrite patterns",es:"Patrones de sobrescritura",ko:"덮어쓰기 패턴",zh:"覆盖模式","zh-tw":"覆寫模式"},"Ui.Settings.Selector.OverwritePatternsDesc":{def:"Patterns to match files for overwriting instead of merging",es:"Patrones de los archivos que se sobrescriben en lugar de combinarse",ko:"병합 대신 덮어쓸 파일을 판별하는 패턴",zh:"匹配后将执行覆盖而非合并的文件模式","zh-tw":"用於匹配需覆寫而非合併檔案的模式"},"Ui.Settings.Selector.SynchronisingFiles":{def:"Synchronising files",es:"Archivos que se sincronizan",ko:"동기화할 파일",zh:"同步文件","zh-tw":"同步中的檔案"},"Ui.Settings.Selector.SynchronisingFilesDesc":{def:"(RegExp) Empty to sync all files. Set a regular expression filter to limit synchronised files.",es:"(RegExp) Déjalo vacío para sincronizar todos los archivos. Define un filtro como expresión regular para limitar los archivos sincronizados.",ko:"(정규식) 비워 두면 모든 파일을 동기화합니다. 정규식 필터를 지정하면 동기화할 파일을 제한할 수 있습니다.",zh:"RegExp)留空则同步所有文件。可设置正则表达式以限制需要同步的文件。","zh-tw":"(正則表示式)留空即同步所有檔案。設定正則表示式篩選器可限制要同步的檔案。"},"Ui.Settings.Selector.TargetPatterns":{def:"Target patterns",es:"Patrones de inclusión",ko:"대상 패턴",zh:"目标模式","zh-tw":"目標模式"},"Ui.Settings.Selector.TargetPatternsDesc":{def:"Patterns to match files for syncing",es:"Patrones de los archivos que se van a sincronizar",ko:"동기화할 파일을 판별하는 패턴",zh:"用于匹配需要同步文件的模式","zh-tw":"用於匹配同步檔案的模式"},"Ui.Settings.Setup.RerunWizardButton":{def:"Rerun Wizard",es:"Volver a ejecutar el asistente",ko:"마법사 다시 실행",zh:"重新运行向导","zh-tw":"重新執行精靈"},"Ui.Settings.Setup.RerunWizardDesc":{def:"Rerun the onboarding wizard to set up Self-hosted LiveSync again.",es:"Vuelve a ejecutar el asistente de configuración inicial para configurar Self-hosted LiveSync de nuevo.",ko:"온보딩 마법사를 다시 실행하여 Self-hosted LiveSync를 다시 설정합니다.",zh:"重新运行引导向导,再次设置 Self-hosted LiveSync。","zh-tw":"重新執行導覽精靈以再次設定 Self-hosted LiveSync。"},"Ui.Settings.Setup.RerunWizardName":{def:"Rerun Onboarding Wizard",es:"Volver a ejecutar el asistente de configuración inicial",ko:"온보딩 마법사 다시 실행",zh:"重新运行引导向导","zh-tw":"重新執行導覽精靈"},"Ui.Settings.SyncSettings.Fetch":{def:"Fetch",es:"Obtener",ko:"가져오기",zh:"获取","zh-tw":"抓取"},"Ui.Settings.SyncSettings.Merge":{def:"Merge",es:"Combinar",ko:"병합",zh:"合并","zh-tw":"合併"},"Ui.Settings.SyncSettings.Overwrite":{def:"Overwrite",es:"Sobrescribir",ko:"덮어쓰기",zh:"覆盖","zh-tw":"覆寫"},"Ui.SetupWizard.ApplySettingsInitialisation.ApplyWithoutInitialisation":{def:"Apply without Initialisation"},"Ui.SetupWizard.ApplySettingsInitialisation.Back":{def:"Review another way to apply these settings"},"Ui.SetupWizard.ApplySettingsInitialisation.BypassGuidance":{def:"Applying these settings alone can make this device incompatible with its existing synchronisation data. Use this only when you have confirmed that reconstruction is unnecessary."},"Ui.SetupWizard.ApplySettingsInitialisation.BypassTitle":{def:"Apply Settings without Initialisation?"},"Ui.SetupWizard.ApplySettingsInitialisation.ContinueFetch":{def:"Continue with Fetch"},"Ui.SetupWizard.ApplySettingsInitialisation.FetchOption":{def:"Reset Synchronisation on This Device"},"Ui.SetupWizard.ApplySettingsInitialisation.FetchOptionDesc":{def:"After restarting, rebuild this device's local database from the current remote synchronisation data. Files in the Vault will then be reconciled with that data."},"Ui.SetupWizard.ApplySettingsInitialisation.FetchOptionP2PDesc":{def:"After restarting, select an online source device. This device's local LiveSync database will be rebuilt from that source."},"Ui.SetupWizard.ApplySettingsInitialisation.Guidance":{def:"These setting changes alter how synchronisation data is interpreted. Apply them together with an initialisation operation after restart."},"Ui.SetupWizard.ApplySettingsInitialisation.KeepEditing":{def:"Keep Editing"},"Ui.SetupWizard.ApplySettingsInitialisation.ProceedFetch":{def:"Restart and Fetch Synchronisation Data"},"Ui.SetupWizard.ApplySettingsInitialisation.ProceedFetchP2P":{def:"Restart and Select a Source Device"},"Ui.SetupWizard.ApplySettingsInitialisation.ProceedRebuild":{def:"Restart and Overwrite Server Data"},"Ui.SetupWizard.ApplySettingsInitialisation.ProceedRebuildP2P":{def:"Restart and Prepare This Device"},"Ui.SetupWizard.ApplySettingsInitialisation.Question":{def:"Which existing data should be used after restart?"},"Ui.SetupWizard.ApplySettingsInitialisation.RebuildOption":{def:"Overwrite Server Data with This Device's Files"},"Ui.SetupWizard.ApplySettingsInitialisation.RebuildOptionDesc":{def:"Rebuild the local and remote databases from the files currently in this Vault. Other synchronising devices must reset their local synchronisation afterwards."},"Ui.SetupWizard.ApplySettingsInitialisation.RebuildOptionP2P":{def:"Prepare This Device from This Vault"},"Ui.SetupWizard.ApplySettingsInitialisation.RebuildOptionP2PDesc":{def:"Rebuild this device's local LiveSync database from the files currently in this Vault. This does not overwrite another device."},"Ui.SetupWizard.ApplySettingsInitialisation.RemoteVerificationGuidance":{def:"The configured remote could not be verified with the current credentials and encryption settings. Continuing may make the Fetch fail after restart."},"Ui.SetupWizard.ApplySettingsInitialisation.RemoteVerificationTitle":{def:"Remote Synchronisation Data Could Not Be Verified"},"Ui.SetupWizard.ApplySettingsInitialisation.Title":{def:"Apply Settings and Reinitialise Synchronisation"},"Ui.SetupWizard.Common.Back":{def:"No, please take me back",es:"No, volver atrás",ko:"아니요, 이전으로 돌아가겠습니다",zh:"不,带我返回","zh-tw":"不,返回上一步"},"Ui.SetupWizard.Common.Cancel":{def:"Cancel",es:"Cancelar",ko:"취소",zh:"取消","zh-tw":"取消"},"Ui.SetupWizard.Common.ProceedSelectOption":{def:"Please select an option to proceed",es:"Selecciona una opción para continuar",ko:"계속하려면 항목을 선택해 주세요",zh:"请选择一个选项后继续","zh-tw":"請選擇一個選項以繼續"},"Ui.SetupWizard.Intro.ExistingOption":{def:"I am adding a device to an existing synchronisation setup",es:"Estoy añadiendo un dispositivo a una configuración de sincronización existente",ko:"기존 동기화 구성에 기기를 추가합니다",zh:"将此设备加入已有同步配置","zh-tw":"我要將裝置加入既有同步設定"},"Ui.SetupWizard.Intro.ExistingOptionDesc":{def:"Select this if you are already using synchronisation on another computer or smartphone. Use this option to connect this device to that existing setup.",es:"Elige esto si ya usas la sincronización en otro ordenador o móvil. Usa esta opción para conectar este dispositivo a esa configuración existente.",ko:"다른 컴퓨터나 스마트폰에서 이미 동기화를 사용 중이라면 선택하세요. 이 기기를 기존 구성에 연결할 때 사용합니다.",zh:"如果你已经在另一台电脑或手机上使用同步,请选择此项。此选项用于将当前设备连接到既有同步配置。","zh-tw":"如果你已經在另一台電腦或手機上使用同步,請選擇此項。此選項用於將此裝置連接到既有的同步設定。"},"Ui.SetupWizard.Intro.Guidance":{def:"We will now guide you through a few questions to simplify the synchronisation setup.",es:"Te guiaremos con unas cuantas preguntas para simplificar la configuración de la sincronización.",ko:"동기화 설정을 간단히 마칠 수 있도록 몇 가지 질문으로 안내해 드리겠습니다.",zh:"接下来我们会通过几个问题,帮助你更轻松地完成同步配置。","zh-tw":"接下來我們會透過幾個問題,引導你更輕鬆地完成同步設定。"},"Ui.SetupWizard.Intro.NewOption":{def:"I am setting this up for the first time",es:"Lo estoy configurando por primera vez",ko:"처음으로 설정합니다",zh:"首次设置同步","zh-tw":"我是第一次進行設定"},"Ui.SetupWizard.Intro.NewOptionDesc":{def:"Select this if you are configuring this device as the first synchronisation device.",es:"Elige esto si estás configurando este dispositivo como el primero de la sincronización.",ko:"이 기기를 첫 번째 동기화 기기로 설정한다면 선택하세요.",zh:"如果你正把这台设备作为第一台同步设备进行配置,请选择此项。","zh-tw":"如果你正在將此裝置設定為第一台同步裝置,請選擇此項。"},"Ui.SetupWizard.Intro.ProceedExisting":{def:"Yes, I want to add this device to my existing synchronisation",es:"Sí, quiero añadir este dispositivo a mi sincronización existente",ko:"예, 이 기기를 기존 동기화 구성에 추가하겠습니다",zh:"是的,我要将此设备加入现有同步","zh-tw":"是的,我要把這台裝置加入既有同步"},"Ui.SetupWizard.Intro.ProceedNew":{def:"Yes, I want to set up a new synchronisation",es:"Sí, quiero configurar una sincronización nueva",ko:"예, 새 동기화를 설정하겠습니다",zh:"是的,我要开始新的同步配置","zh-tw":"是的,我要設定新的同步"},"Ui.SetupWizard.Intro.Question":{def:"First, please select the option that best describes your current situation.",es:"Primero, selecciona la opción que mejor describa tu situación actual.",ko:"먼저 현재 상황에 가장 잘 맞는 항목을 선택해 주세요.",zh:"首先,请选择最符合你当前情况的选项。","zh-tw":"首先,請選擇最符合你目前情況的選項。"},"Ui.SetupWizard.Intro.Title":{def:"Welcome to Self-hosted LiveSync",es:"Bienvenido a Self-hosted LiveSync",ko:"Self-hosted LiveSync에 오신 것을 환영합니다",zh:"欢迎使用 Self-hosted LiveSync","zh-tw":"歡迎使用 Self-hosted LiveSync"},"Ui.SetupWizard.Invitation.Start":{def:"Start setup",es:"Comenzar la configuración",ko:"설정 시작","zh-tw":"開始設定"},"Ui.SetupWizard.OutroAskUserMode.CompatibleOption":{def:"The remote is already set up, and the configuration is compatible (or became compatible through this operation).",es:"El remoto ya está configurado y la configuración es compatible (o pasa a serlo con esta operación).",ko:"원격이 이미 설정되어 있고, 구성도 호환됩니다(또는 이번 작업으로 호환되었습니다).",zh:"远程端已配置完成,且当前配置兼容(或已通过本次操作变为兼容)。","zh-tw":"遠端已經設定完成,且設定相容(或透過此操作變得相容)。"},"Ui.SetupWizard.OutroAskUserMode.CompatibleOptionDesc":{def:"Unless you are certain, selecting this option is risky. It assumes the server configuration is compatible with this device. If that is not the case, data loss may occur. Please make sure you understand the consequences.",es:"Si no estás seguro, elegir esta opción es arriesgado. Da por supuesto que la configuración del servidor es compatible con este dispositivo. Si no lo es, puede haber pérdida de datos. Asegúrate de entender las consecuencias.",ko:"확신이 없다면 이 옵션을 선택하는 것은 위험합니다. 서버 구성이 이 기기와 호환된다고 가정하기 때문에, 그렇지 않을 경우 데이터가 손실될 수 있습니다. 결과를 충분히 이해한 뒤에 선택해 주세요.",zh:"除非你非常确定,否则选择此项存在风险。它假定服务器配置与当前设备兼容。如果事实并非如此,可能会导致数据丢失。请确认你了解后果。","zh-tw":"除非你很確定,否則選擇此選項有風險。這個選項假設伺服器設定與此裝置相容;若並非如此,可能導致資料遺失。請確保你了解這麼做的後果。"},"Ui.SetupWizard.OutroAskUserMode.ExistingOption":{def:"My remote server is already set up. I want to join this device.",es:"Mi servidor remoto ya está configurado. Quiero añadir este dispositivo.",ko:"원격 서버가 이미 설정되어 있습니다. 이 기기를 참여시키려고 합니다.",zh:"远程服务器已经配置完成,我想让此设备加入同步。","zh-tw":"我的遠端伺服器已經設定完成,我想讓這台裝置加入。"},"Ui.SetupWizard.OutroAskUserMode.ExistingOptionDesc":{def:"Selecting this option will make this device join the existing server. You need to fetch the existing synchronisation data from the server to this device.",es:"Al elegir esta opción, este dispositivo se unirá al servidor existente. Tendrás que obtener del servidor los datos de sincronización ya existentes.",ko:"이 옵션을 선택하면 이 기기가 기존 서버에 참여합니다. 서버에 있는 기존 동기화 데이터를 이 기기로 가져와야 합니다.",zh:"选择此项后,此设备会加入已有服务器。你需要将服务器上的现有同步数据获取到此设备。","zh-tw":"選擇此選項會讓此裝置加入現有的伺服器,你需要將伺服器上現有的同步資料擷取到此裝置。"},"Ui.SetupWizard.OutroAskUserMode.Guidance":{def:"The connection to the server has been configured successfully. As the next step, the local database, in other words the synchronisation information, must be rebuilt.",es:"La conexión con el servidor se ha configurado correctamente. Como paso siguiente hay que reconstruir la base de datos local, es decir, la información de sincronización.",ko:"서버 연결이 정상적으로 구성되었습니다. 다음 단계로, 로컬 데이터베이스 즉 동기화 정보를 재구축해야 합니다.",zh:"服务器连接已成功配置。下一步需要重建本地数据库,也就是同步状态信息。","zh-tw":"與伺服器的連線已成功設定完成。接下來,本機資料庫,也就是同步資訊,必須重新建立。"},"Ui.SetupWizard.OutroAskUserMode.NewOption":{def:"I am setting up a new server for the first time / I want to reset my existing server.",es:"Estoy configurando un servidor nuevo por primera vez / quiero restablecer mi servidor actual.",ko:"서버를 처음 설정합니다 / 기존 서버를 초기화하려고 합니다.",zh:"我是第一次配置新服务器 / 我想重置现有服务器。","zh-tw":"我是第一次設定新的伺服器/我想要重設現有的伺服器。"},"Ui.SetupWizard.OutroAskUserMode.NewOptionDesc":{def:"Selecting this option will initialise the server using the current data on this device. Any existing data on the server will be completely overwritten.",es:"Al elegir esta opción, el servidor se inicializará con los datos actuales de este dispositivo. Cualquier dato existente en el servidor se sobrescribirá por completo.",ko:"이 옵션을 선택하면 이 기기의 현재 데이터로 서버를 초기화합니다. 서버에 있던 기존 데이터는 완전히 덮어써집니다.",zh:"选择此项后,服务器会使用当前设备上的数据进行初始化。服务器上的现有数据将被完全覆盖。","zh-tw":"選擇此選項會使用此裝置目前的資料來初始化伺服器,伺服器上任何現有資料都會被完全覆寫。"},"Ui.SetupWizard.OutroAskUserMode.ProceedApplySettings":{def:"Apply the settings",es:"Aplicar los ajustes",ko:"설정 적용",zh:"应用这些设置","zh-tw":"套用設定"},"Ui.SetupWizard.OutroAskUserMode.ProceedNext":{def:"Proceed to the next step.",es:"Continuar al paso siguiente.",ko:"다음 단계로 진행합니다.",zh:"继续下一步","zh-tw":"繼續前往下一步。"},"Ui.SetupWizard.OutroAskUserMode.Question":{def:"Please select your situation.",es:"Selecciona tu situación.",ko:"현재 상황을 선택해 주세요.",zh:"请选择你的当前情况。","zh-tw":"請選擇符合你情況的選項。"},"Ui.SetupWizard.OutroAskUserMode.Title":{def:"Mostly Complete: Decision Required",es:"Casi terminado: se requiere una decisión",ko:"거의 완료: 선택이 필요합니다",zh:"即将完成:还需要做出选择","zh-tw":"大致完成:需要你做出決定"},"Ui.SetupWizard.OutroNewP2PUser.GuidanceNotice":{def:"P2P has no central server copy to overwrite. This step prepares only this device; keep it online when another device fetches its initial data.",es:"En P2P no hay una copia en un servidor central que sobrescribir. Este paso prepara solo este dispositivo; mantenlo conectado cuando otro dispositivo obtenga sus datos iniciales.",ko:"P2P에는 덮어쓸 중앙 서버 사본이 없습니다. 이 단계는 이 기기만 준비하며, 다른 기기가 초기 데이터를 가져올 때는 이 기기를 온라인 상태로 유지해 주세요.","zh-tw":"P2P 沒有中央伺服器複本可覆寫。此步驟只會準備這台裝置;當其他裝置擷取初始資料時,請讓這台裝置保持連線。"},"Ui.SetupWizard.OutroNewP2PUser.GuidancePrimary":{def:"The peer-to-peer connection has been configured successfully. Next, the local LiveSync database will be built from the current files in this Vault.",es:"La conexión punto a punto se ha configurado correctamente. A continuación, la base de datos local de LiveSync se construirá a partir de los archivos actuales de este Vault.",ko:"Peer-to-Peer 연결이 정상적으로 구성되었습니다. 다음 단계로, 이 보관함의 현재 파일을 사용해 로컬 LiveSync 데이터베이스를 만듭니다.","zh-tw":"Peer-to-Peer 連線已成功設定完成。接下來,將依此 Vault 目前的檔案建立本機 LiveSync 資料庫。"},"Ui.SetupWizard.OutroNewP2PUser.Important":{def:"PLEASE NOTE",es:"TEN EN CUENTA",ko:"유의해 주세요","zh-tw":"請注意"},"Ui.SetupWizard.OutroNewP2PUser.Proceed":{def:"Restart and Prepare This Device",es:"Reiniciar y preparar este dispositivo",ko:"재시작하고 이 기기 준비","zh-tw":"重新啟動並準備此裝置"},"Ui.SetupWizard.OutroNewP2PUser.Question":{def:"Please select the button below to restart and proceed to the local initialisation confirmation.",es:"Pulsa el botón de abajo para reiniciar y pasar a la confirmación de la inicialización local.",ko:"재시작하고 로컬 초기화 확인 단계로 넘어가려면 아래 버튼을 선택해 주세요.","zh-tw":"請點選下方按鈕以重新啟動,並前往本機初始化確認步驟。"},"Ui.SetupWizard.OutroNewP2PUser.Title":{def:"Setup Complete: Preparing This P2P Device",es:"Configuración completada: preparando este dispositivo P2P",ko:"설정 완료: 이 P2P 기기 준비","zh-tw":"設定完成:準備此 P2P 裝置"},"Ui.SetupWizard.OutroNewUser.GuidancePrimary":{def:"The connection to the server has been configured successfully. As the next step, the synchronisation data on the server will be built from the current data on this device.",es:"La conexión con el servidor se ha configurado correctamente. Como paso siguiente, los datos de sincronización del servidor se construirán a partir de los datos actuales de este dispositivo.",ko:"서버 연결이 정상적으로 구성되었습니다. 다음 단계로, 이 기기의 현재 데이터를 사용해 서버의 동기화 데이터를 만듭니다.",zh:"服务器连接已成功配置。下一步将根据当前设备上的数据,在服务器端建立同步数据。","zh-tw":"與伺服器的連線已成功設定完成。接下來,伺服器上的同步資料將依此裝置目前的資料建立。"},"Ui.SetupWizard.OutroNewUser.GuidanceWarning":{def:"After restarting, the data on this device will be uploaded to the server as the master copy. Please note that any unintended data currently on the server will be completely overwritten.",es:"Tras reiniciar, los datos de este dispositivo se subirán al servidor como copia maestra. Ten en cuenta que cualquier dato no deseado que haya ahora en el servidor se sobrescribirá por completo.",ko:"재시작하면 이 기기의 데이터가 원본으로서 서버에 업로드됩니다. 현재 서버에 있는 데이터는 의도치 않은 것이라도 완전히 덮어써지므로 유의해 주세요.",zh:"重启后,当前设备上的数据会作为主副本上传到服务器。请注意,服务器上现有的非预期数据将被完全覆盖。","zh-tw":"重新啟動後,此裝置上的資料將以主要複本的形式上傳到伺服器。請注意,伺服器上任何非預期的現有資料都會被完全覆寫。"},"Ui.SetupWizard.OutroNewUser.Important":{def:"IMPORTANT",es:"IMPORTANTE",ko:"중요",zh:"重要","zh-tw":"重要"},"Ui.SetupWizard.OutroNewUser.Proceed":{def:"Restart and Initialise Server",es:"Reiniciar e inicializar el servidor",ko:"재시작하고 서버 초기화",zh:"重启并初始化服务器","zh-tw":"重新啟動並初始化伺服器"},"Ui.SetupWizard.OutroNewUser.Question":{def:"Please select the button below to restart and proceed to the final confirmation.",es:"Pulsa el botón de abajo para reiniciar y pasar a la confirmación final.",ko:"재시작하고 마지막 확인 단계로 넘어가려면 아래 버튼을 선택해 주세요.",zh:"请选择下方按钮,重启并进入最终确认步骤。","zh-tw":"請點選下方按鈕以重新啟動,並前往最終確認步驟。"},"Ui.SetupWizard.OutroNewUser.Title":{def:"Setup Complete: Preparing to Initialise Server",es:"Configuración completada: preparando la inicialización del servidor",ko:"설정 완료: 서버 초기화 준비",zh:"设置完成:准备初始化服务器","zh-tw":"設定完成:準備初始化伺服器"},"Ui.SetupWizard.RebuildEverythingP2P.ConfirmLocalReset":{def:"I understand that this resets only this device's local synchronisation database.",es:"Entiendo que esto restablece únicamente la base de datos de sincronización local de este dispositivo.",ko:"이 작업이 이 기기의 로컬 동기화 데이터베이스만 초기화한다는 것을 이해했습니다.","zh-tw":"我了解這只會重設此裝置的本機同步資料庫。"},"Ui.SetupWizard.RebuildEverythingP2P.ConfirmLocalResetNote":{def:"The files currently in this Vault are used to rebuild it.",es:"Se usarán los archivos que hay ahora en este Vault para reconstruirla.",ko:"현재 이 보관함에 있는 파일을 사용해 재구축합니다.","zh-tw":"此 Vault 目前的檔案將用於重建它。"},"Ui.SetupWizard.RebuildEverythingP2P.ConfirmTitle":{def:"⚠️ Please Confirm the Following",es:"⚠️ Confirma lo siguiente",ko:"⚠️ 다음 내용을 확인해 주세요","zh-tw":"⚠️ 請確認以下事項"},"Ui.SetupWizard.RebuildEverythingP2P.Guidance":{def:"This procedure will discard the local LiveSync database on this device and rebuild it from the current files in this Vault. It does not delete or overwrite data on another device.",es:"Este procedimiento descartará la base de datos local de LiveSync de este dispositivo y la reconstruirá a partir de los archivos actuales de este Vault. No elimina ni sobrescribe datos de otro dispositivo.",ko:"이 절차는 이 기기의 로컬 LiveSync 데이터베이스를 삭제하고, 이 보관함의 현재 파일로 재구축합니다. 다른 기기의 데이터는 삭제하거나 덮어쓰지 않습니다.","zh-tw":"此程序會捨棄此裝置上的本機 LiveSync 資料庫,並依此 Vault 目前的檔案重新建立。它不會刪除或覆寫其他裝置上的資料。"},"Ui.SetupWizard.RebuildEverythingP2P.Note":{def:"Keep this device online after initialisation so that another device can fetch the Vault from it.",es:"Mantén este dispositivo conectado después de la inicialización para que otro dispositivo pueda obtener el Vault desde él.",ko:"초기화 후에도 다른 기기가 이 기기에서 보관함을 가져올 수 있도록 이 기기를 온라인 상태로 유지해 주세요.","zh-tw":"初始化完成後請讓此裝置保持連線,以便其他裝置能從它擷取 Vault。"},"Ui.SetupWizard.RebuildEverythingP2P.Proceed":{def:"I Understand, Prepare This Device",es:"Lo entiendo, preparar este dispositivo",ko:"이해했습니다, 이 기기 준비","zh-tw":"我了解,準備此裝置"},"Ui.SetupWizard.RebuildEverythingP2P.Title":{def:"Final Confirmation: Prepare This Device for P2P",es:"Confirmación final: preparar este dispositivo para P2P",ko:"최종 확인: P2P를 위한 이 기기 준비","zh-tw":"最終確認:為 P2P 準備此裝置"},"Ui.SetupWizard.SelectExisting.Guidance":{def:"You are adding this device to an existing synchronisation setup.",es:"Estás añadiendo este dispositivo a una configuración de sincronización existente.",ko:"이 기기를 기존 동기화 구성에 추가합니다.",zh:"你正在将此设备加入已有同步配置。","zh-tw":"你正在將此裝置加入既有同步設定中。"},"Ui.SetupWizard.SelectExisting.ManualOption":{def:"Configure a remote manually",es:"Configurar un remoto manualmente",ko:"서버 정보를 수동으로 입력",zh:"手动输入服务器信息","zh-tw":"手動設定遠端"},"Ui.SetupWizard.SelectExisting.ManualOptionDesc":{def:"Configure the same remote as your other devices again manually. This is intended only for advanced users.",es:"Vuelve a configurar manualmente el mismo remoto que en tus otros dispositivos. Está pensado solo para usuarios avanzados.",ko:"다른 기기와 동일한 서버 정보를 다시 직접 입력합니다. 숙련된 사용자 전용입니다.",zh:"手动重新配置与你其他设备相同的服务器信息。此方式仅适用于高级用户。","zh-tw":"手動重新設定與你其他裝置相同的遠端,僅適合進階使用者。"},"Ui.SetupWizard.SelectExisting.ProceedManual":{def:"Proceed with manual configuration",es:"Continuar con la configuración manual",ko:"서버 정보를 알고 있으니 직접 입력하겠습니다",zh:"我知道服务器信息,让我手动输入","zh-tw":"繼續進行手動設定"},"Ui.SetupWizard.SelectExisting.ProceedQr":{def:"Scan the QR code displayed on an active device using this device's camera.",es:"Escanea con la cámara de este dispositivo el código QR mostrado en un dispositivo activo.",ko:"이 기기의 카메라로 사용 중인 기기에 표시된 QR 코드를 스캔하세요.",zh:"使用本设备摄像头扫描活动设备上显示的二维码","zh-tw":"使用目前裝置的相機掃描另一台已在使用裝置上顯示的 QR Code。"},"Ui.SetupWizard.SelectExisting.ProceedSetupUri":{def:"Proceed with Setup URI",es:"Continuar con el Setup URI",ko:"Setup URI로 계속",zh:"使用 Setup URI 继续","zh-tw":"繼續使用 Setup URI"},"Ui.SetupWizard.SelectExisting.QrOption":{def:"Scan a QR Code (Recommended for mobile)",es:"Escanear un código QR (recomendado en móvil)",ko:"QR 코드 스캔(모바일 권장)",zh:"扫描二维码(移动端推荐)","zh-tw":"掃描 QR Code(行動裝置推薦)"},"Ui.SetupWizard.SelectExisting.QrOptionDesc":{def:"Scan the QR code displayed on an active device using this device's camera.",es:"Escanea con la cámara de este dispositivo el código QR mostrado en un dispositivo activo.",ko:"이 기기의 카메라로 사용 중인 기기에 표시된 QR 코드를 스캔하세요.",zh:"使用本设备摄像头扫描活动设备上显示的二维码。","zh-tw":"使用目前裝置的相機掃描另一台已在使用裝置上顯示的 QR Code。"},"Ui.SetupWizard.SelectExisting.Question":{def:"Please select a method to import the settings from another device.",es:"Selecciona un método para importar los ajustes desde otro dispositivo.",ko:"다른 기기에서 설정을 가져올 방법을 선택해 주세요.",zh:"请选择一种从其他设备导入设置的方法。","zh-tw":"請選擇一種從其他裝置匯入設定的方法。"},"Ui.SetupWizard.SelectExisting.SetupUriOption":{def:"Use a Setup URI (Recommended)",es:"Usar un Setup URI (recomendado)",ko:"Setup URI 사용(권장)",zh:"使用 Setup URI(推荐)","zh-tw":"使用 Setup URI(推薦)"},"Ui.SetupWizard.SelectExisting.SetupUriOptionDesc":{def:"Paste the Setup URI generated from one of your active devices.",es:"Pega el Setup URI generado en uno de tus dispositivos activos.",ko:"사용 중인 기기 중 하나에서 생성한 Setup URI를 붙여 넣으세요.",zh:"粘贴从某台已启用设备生成的 Setup URI。","zh-tw":"貼上從一台已在使用裝置上產生的 Setup URI。"},"Ui.SetupWizard.SelectExisting.Title":{def:"Device Setup Method",es:"Método de configuración del dispositivo",ko:"기기 설정 방법",zh:"设备设置方式","zh-tw":"裝置設定方式"},"Ui.SetupWizard.SelectNew.Guidance":{def:"We will now configure the synchronisation connection.",es:"Vamos a configurar la conexión de sincronización.",ko:"이제 서버 구성을 진행하겠습니다.",zh:"接下来将继续配置服务器连接信息。","zh-tw":"接下來我們將設定同步連線。"},"Ui.SetupWizard.SelectNew.ManualOption":{def:"Configure a remote manually",es:"Configurar un remoto manualmente",ko:"서버 정보를 수동으로 입력",zh:"手动输入服务器信息","zh-tw":"手動設定遠端"},"Ui.SetupWizard.SelectNew.ManualOptionDesc":{def:"This is an advanced option for users who do not have a Setup URI or who want to configure detailed settings. You can also use it for P2P synchronisation instead of CouchDB or S3-compatible Object Storage.",es:"Es una opción avanzada para quienes no tienen un Setup URI o quieren ajustar la configuración en detalle. También puedes usarla para la sincronización P2P en lugar de CouchDB o de un almacenamiento de objetos compatible con S3.",ko:"Setup URI가 없거나 세부 설정을 직접 구성하려는 사용자를 위한 고급 옵션입니다.",zh:"如果你没有 Setup URI,或希望自行配置更详细的参数,可选择此高级选项。","zh-tw":"這是進階選項,適合沒有 Setup URI 或想要詳細設定的使用者。你也可以用它來設定 P2P 同步,取代 CouchDB 或 S3 相容物件儲存。"},"Ui.SetupWizard.SelectNew.ProceedManual":{def:"Proceed with manual configuration",es:"Continuar con la configuración manual",ko:"서버 정보를 알고 있으니 직접 입력하겠습니다",zh:"我知道服务器信息,让我手动输入","zh-tw":"繼續進行手動設定"},"Ui.SetupWizard.SelectNew.ProceedSetupUri":{def:"Proceed with Setup URI",es:"Continuar con el Setup URI",ko:"Setup URI로 계속",zh:"使用 Setup URI 继续","zh-tw":"繼續使用 Setup URI"},"Ui.SetupWizard.SelectNew.Question":{def:"How would you like to configure this synchronisation connection?",es:"¿Cómo quieres configurar esta conexión de sincronización?",ko:"서버 연결을 어떻게 구성하시겠습니까?",zh:"你希望如何配置服务器连接?","zh-tw":"你希望如何設定這個同步連線?"},"Ui.SetupWizard.SelectNew.SetupUriOption":{def:"Use a Setup URI (Recommended)",es:"Usar un Setup URI (recomendado)",ko:"Setup URI 사용(권장)",zh:"使用 Setup URI(推荐)","zh-tw":"使用 Setup URI(推薦)"},"Ui.SetupWizard.SelectNew.SetupUriOptionDesc":{def:"A Setup URI is a single string containing connection and authentication details. When one is available from a setup script, it provides a simple and secure configuration method.",es:"Un Setup URI es una única cadena que contiene los datos de conexión y autenticación. Cuando un script de instalación te proporciona uno, es la forma más sencilla y segura de configurarlo.",ko:"Setup URI는 서버 주소와 인증 정보를 담은 하나의 문자열입니다. 서버 설치 스크립트가 URI를 생성했다면, 간단하고 안전하게 구성할 수 있는 방법입니다.",zh:"Setup URI 是一段包含服务器地址和认证信息的文本。如果你的服务器安装脚本已经生成了它,这是最简单且安全的配置方式。","zh-tw":"Setup URI 是一段包含連線與驗證資訊的字串。如果安裝腳本已經產生了它,使用它是一種簡單且安全的設定方式。"},"Ui.SetupWizard.SelectNew.Title":{def:"Connection Method",es:"Método de conexión",ko:"연결 방법",zh:"连接方式","zh-tw":"連線方式"},"Ui.SetupWizard.SetupRemote.BucketOption":{def:"S3-compatible Object Storage",es:"Almacenamiento de objetos compatible con S3",ko:"S3/MinIO/R2 객체 스토리지",zh:"S3/MinIO/R2 对象存储","zh-tw":"S3 相容物件儲存"},"Ui.SetupWizard.SetupRemote.BucketOptionDesc":{def:"Synchronisation using journal files. You must already have an S3-compatible Object Storage service set up, such as Amazon S3, MinIO, or Cloudflare R2.",es:"Sincronización mediante archivos de diario. Necesitas tener ya un servicio de almacenamiento de objetos compatible con S3, como Amazon S3, MinIO o Cloudflare R2.",ko:"저널 파일을 사용하는 동기화 방식입니다. S3/MinIO/R2 호환 객체 스토리지 서비스를 미리 구성해 두어야 합니다.",zh:"使用日志文件进行同步。你需要先准备好兼容 S3/MinIO/R2 的对象存储服务。","zh-tw":"使用日誌檔進行同步。你需要事先準備好相容 S3 的物件儲存服務,例如 Amazon S3、MinIO 或 Cloudflare R2。"},"Ui.SetupWizard.SetupRemote.CouchDbOptionDesc":{def:"This is the most suitable synchronisation method for the current design. All features are available. You must already have a CouchDB instance set up.",es:"Es el método de sincronización más adecuado para el diseño actual y ofrece todas las funciones. Necesitas tener ya una instancia de CouchDB en marcha.",ko:"현재 설계에 가장 적합한 동기화 방식입니다. 모든 기능을 사용할 수 있습니다. CouchDB 인스턴스를 미리 구성해 두어야 합니다.",zh:"这是当前设计下最适合的同步方式,所有功能都可用。你需要先准备好 CouchDB 实例。","zh-tw":"這是目前設計下最適合的同步方式,所有功能皆可使用。你需要事先準備好 CouchDB 實例。"},"Ui.SetupWizard.SetupRemote.Guidance":{def:"Select the remote type for this synchronisation setup.",es:"Selecciona el tipo de remoto para esta configuración de sincronización.",ko:"연결할 서버 유형을 선택해 주세요.",zh:"请选择你要连接的服务器类型。","zh-tw":"請選擇這次同步設定要使用的遠端類型。"},"Ui.SetupWizard.SetupRemote.P2POption":{def:"Peer-to-Peer (P2P)",es:"Punto a punto (P2P)",ko:"Peer-to-Peer 전용",zh:"仅点对点","zh-tw":"Peer-to-PeerP2P"},"Ui.SetupWizard.SetupRemote.P2POptionDesc":{def:"This enables direct synchronisation between devices. No server is required, but both devices must be online at the same time and some features may be limited. Internet connectivity is required only for signalling, not for data transfer.",es:"Permite la sincronización directa entre dispositivos. No hace falta servidor, pero ambos dispositivos deben estar conectados a la vez y algunas funciones pueden estar limitadas. Solo se necesita internet para la señalización, no para transferir los datos.",ko:"기기 간에 직접 동기화하는 방식입니다. 서버는 필요 없지만 두 기기가 동시에 온라인 상태여야 하며, 일부 기능은 제한될 수 있습니다. 인터넷 연결은 시그널링에만 필요하고 데이터 전송에는 필요하지 않습니다.",zh:"启用设备之间的直接同步。无需服务器,但两台设备必须同时在线,且部分功能可能受限。互联网连接仅用于信令,不用于传输数据。","zh-tw":"此功能可在裝置之間直接同步,無需伺服器;但同步時兩台裝置必須同時在線,且部分功能可能受限。網際網路連線僅用於訊號交換(偵測對端),不用於資料傳輸。"},"Ui.SetupWizard.SetupRemote.ProceedBucket":{def:"Continue to Object Storage setup",es:"Continuar con la configuración del almacenamiento de objetos",ko:"S3/MinIO/R2 설정으로 계속",zh:"继续配置 S3/MinIO/R2","zh-tw":"繼續進行物件儲存設定"},"Ui.SetupWizard.SetupRemote.ProceedCouchDb":{def:"Continue to CouchDB setup",es:"Continuar con la configuración de CouchDB",ko:"CouchDB 설정으로 계속",zh:"继续配置 CouchDB","zh-tw":"繼續進行 CouchDB 設定"},"Ui.SetupWizard.SetupRemote.ProceedP2P":{def:"Continue to P2P setup",es:"Continuar con la configuración de P2P",ko:"Peer-to-Peer 전용 설정으로 계속",zh:"继续配置仅点对点模式","zh-tw":"繼續進行 P2P 設定"},"Ui.SetupWizard.SetupRemote.Title":{def:"Choose a synchronisation remote",es:"Elige un remoto de sincronización",ko:"서버 정보 입력",zh:"输入服务器信息","zh-tw":"選擇同步遠端"},"Unique name between all synchronized devices. To edit this setting, please disable customization sync once.":{def:"Unique name between all synchronized devices. To edit this setting, please disable customization sync once.",es:"Nombre único entre dispositivos sincronizados. Para editarlo, desactive sincronización de personalización",fr:"Nom unique parmi tous les appareils synchronisés. Pour modifier ce paramètre, désactivez d'abord la synchronisation de personnalisation.",he:"שם ייחודי בין כל המכשירים המסונכרנים. כדי לערוך הגדרה זו, אנא נטרל את סנכרון ההתאמה האישית פעם אחת.",ja:"同期するすべての端末間で重複しない(一意の)名前。この設定を変更する場合、カスタマイズ同期を無効にしてください。",ko:"모든 동기화된 기기 간 고유 이름입니다. 이 설정을 편집하려면 사용자 설정 동기화를 한 번 비활성화해 주세요.",ru:"Уникальное имя между всеми синхронизируемыми устройствами.",zh:"所有同步设备之间的唯一名称。要编辑此设置,请首先禁用自定义同步","zh-tw":"所有同步裝置之間的唯一名稱。若要編輯此設定,請先停用自訂同步一次。"},"Unless you are certain, selecting this options is bit dangerous. It assumes that the server configuration is compatible with this device. If this is not the case, data loss may occur. Please ensure you know what you are doing.":{def:"Unless you are certain, selecting this options is bit dangerous. It assumes that the server configuration is compatible with this device. If this is not the case, data loss may occur. Please ensure you know what you are doing.",es:"Si no estás seguro, elegir esta opción es algo arriesgado. Da por supuesto que la configuración del servidor es compatible con este dispositivo. Si no lo es, puede haber pérdida de datos. Asegúrate de saber lo que haces.",ko:"확신이 없다면 이 옵션을 선택하는 것은 다소 위험합니다. 이 옵션은 서버 구성이 이 기기와 호환된다고 가정합니다. 그렇지 않은 경우 데이터가 손실될 수 있습니다. 무엇을 하려는지 충분히 이해한 상태에서 진행해 주세요.","zh-tw":"除非你很確定,否則選擇此選項有一定風險。這個選項假設伺服器設定與此裝置相容;若並非如此,可能導致資料遺失。請確保你了解自己在做什麼。"},"Updating list...":{def:"Updating list...",es:"Actualizando lista...",ko:"목록을 갱신하는 중입니다...","zh-tw":"正在更新清單⋯"},URL:{def:"URL",es:"URL",ko:"URL","zh-tw":"URL"},"Use a custom passphrase":{def:"Use a custom passphrase",es:"Usar una frase de contraseña personalizada",ja:"カスタムパスフレーズを使う",ko:"사용자 지정 패스프레이즈 사용",ru:"Использовать пользовательскую парольную фразу",zh:"使用自定义密码短语","zh-tw":"使用自訂密語"},"Use a Setup URI (Recommended)":{def:"Use a Setup URI (Recommended)",es:"Usar un URI de configuración (recomendado)",ja:"Setup URI を使う(推奨)",ko:"Setup URI 사용(권장)",ru:"Использовать Setup URI (рекомендуется)",zh:"使用 Setup URI(推荐)","zh-tw":"使用 Setup URI(推薦)"},"Use Custom HTTP Handler":{def:"Use Custom HTTP Handler",es:"Usar manejador HTTP personalizado",fr:"Utiliser un gestionnaire HTTP personnalisé",he:"השתמש ב-HTTP Handler מותאם אישית",ja:"カスタムHTTPハンドラーの利用",ko:"커스텀 HTTP 핸들러 사용",ru:"Использовать пользовательский HTTP обработчик",zh:"使用自定义 HTTP 处理程序","zh-tw":"使用自訂 HTTP 處理程式"},"Use Diagnostic RTCPeerConnection for statistics":{def:"Use Diagnostic RTCPeerConnection for statistics",es:"Usar el RTCPeerConnection de diagnóstico para las estadísticas",ko:"통계에 진단용 RTCPeerConnection 사용","zh-tw":"啟用 RTCPeerConnection 診斷以取得統計資訊"},"Use dynamic iteration count":{def:"Use dynamic iteration count",es:"Usar conteo de iteraciones dinámico",fr:"Utiliser un compteur d'itérations dynamique",he:"השתמש בספירת איטרציות דינמית",ja:"動的な繰り返し回数",ko:"동적 반복 횟수 사용",ru:"Использовать динамическое количество итераций",zh:"使用动态迭代次数","zh-tw":"使用動態迭代次數"},"Use internal API":{def:"Use internal API",es:"Usar la API interna",ko:"내부 API 사용","zh-tw":"使用內部 API"},"Use Internal API":{def:"Use Internal API",es:"Usar la API interna",ko:"내부 API 사용","zh-tw":"使用內部 API"},"Use JWT Authentication":{def:"Use JWT Authentication",es:"Usar autenticación JWT",ko:"JWT 인증 사용","zh-tw":"使用 JWT 驗證"},"Use Path-Style Access":{def:"Use Path-Style Access",es:"Usar acceso de tipo ruta (path-style)",ko:"경로 방식(Path-Style) 접근 사용","zh-tw":"使用路徑樣式存取"},"Use Random Number":{def:"Use Random Number",es:"Usar número aleatorio",ko:"임의의 숫자 사용","zh-tw":"使用隨機數字"},"Use Segmented-splitter":{def:"Use Segmented-splitter",es:"Usar divisor segmentado",fr:"Utiliser le découpeur segmenté",he:"השתמש ב-Segmented-splitter",ja:"セグメント分割を使用",ko:"의미 기반 분할 사용",ru:"Использовать сегментный разделитель",zh:"使用分段分割器","zh-tw":"使用分段式分割器"},"Use splitting-limit-capped chunk splitter":{def:"Use splitting-limit-capped chunk splitter",es:"Usar divisor de chunks con límite",fr:"Utiliser le découpeur de fragments plafonné",he:"השתמש ב-chunk splitter עם מגבלת פיצול",ja:"分割制限付きチャンク分割を使用",ko:"분할 제한 상한 청크 분할기 사용",ru:"Использовать разделитель чанков с ограничением",zh:"使用分割限制上限的块分割器","zh-tw":"使用有分割上限的 chunk 分割器"},"Use the trash bin":{def:"Use the trash bin",es:"Usar papelera",fr:"Utiliser la corbeille",he:"השתמש בסל האשפה",ja:"ゴミ箱を使用",ko:"휴지통 사용",ru:"Использовать корзину",zh:"使用回收站","zh-tw":"使用垃圾桶"},"Use timeouts instead of heartbeats":{def:"Use timeouts instead of heartbeats",es:"Usar timeouts en lugar de latidos",fr:"Utiliser des délais d'attente au lieu de battements",he:"השתמש בפסק זמן במקום פעימות לב",ja:"ハートビートの代わりにタイムアウトを使用",ko:"하트비트 대신 타임아웃 사용",ru:"Использовать таймауты вместо пульса",zh:"使用超时而不是心跳","zh-tw":"使用逾時取代心跳偵測"},"Use vrtmrz's relay":{def:"Use vrtmrz's relay",es:"Usar el relé de vrtmrz",ko:"vrtmrz의 중계 서버 사용","zh-tw":"使用 vrtmrz 提供的中繼站"},username:{def:"username",es:"nombre de usuario",fr:"nom d'utilisateur",he:"שם משתמש",ja:"ユーザー名",ko:"사용자명",ru:"имя пользователя",zh:"用户名","zh-tw":"使用者名稱"},Username:{def:"Username",es:"Usuario",fr:"Nom d'utilisateur",he:"שם משתמש",ja:"ユーザー名",ko:"사용자명",ru:"Имя пользователя",zh:"用户名","zh-tw":"使用者名稱"},"Verbose Log":{def:"Verbose Log",es:"Registro detallado",fr:"Journal verbeux",he:"יומן מפורט",ja:"エラー以外のログ項目",ko:"자세한 로그",ru:"Подробный лог",zh:"详细日志","zh-tw":"詳細日誌"},"Verify all":{def:"Verify all",es:"Verificar todo",ja:"すべて検証",ko:"모두 검증",ru:"Проверить всё",zh:"全部校验","zh-tw":"全部驗證"},"Verify and repair all files":{def:"Verify and repair all files",es:"Verificar y reparar todos los archivos",ja:"すべてのファイルを検証して修復",ko:"모든 파일 검증 및 복구",ru:"Проверить и восстановить все файлы",zh:"校验并修复所有文件","zh-tw":"驗證並修復所有檔案"},"Warning! This will have a serious impact on performance. And the logs will not be synchronised under the default name. Please be careful with logs; they often contain your confidential information.":{def:"Warning! This will have a serious impact on performance. And the logs will not be synchronised under the default name. Please be careful with logs; they often contain your confidential information.",es:"¡Advertencia! Impacta rendimiento. Los logs no se sincronizan con nombre predeterminado. Contienen información confidencial",fr:"Attention ! Ceci aura un impact important sur les performances. De plus, les journaux ne seront pas synchronisés sous le nom par défaut. Soyez prudent avec les journaux ; ils contiennent souvent des informations confidentielles.",he:"אזהרה! לכך תהיה השפעה רצינית על הביצועים. בנוסף, היומנים לא יסונכרנו תחת השם ברירת המחדל. אנא היה זהיר עם יומנים; הם לרוב מכילים מידע סודי שלך.",ja:"警告!これはパフォーマンスに重大な影響を与えます。また、ログはデフォルト名では同期されません。ログには機密情報が含まれることが多いため、注意してください。",ko:"경고! 이는 성능에 심각한 영향을 미칩니다. 로그는 기본 이름으로 동기화되지 않습니다. 로그에는 종종 기밀 정보가 포함되어 있으므로 주의해 주세요.",ru:"Warning! This will have a serious impact on performance. And the logs will not be synchronised under the default name. Please be careful with logs; they often contain your confidential information.",zh:"警告!这将严重影响性能。并且日志不会以默认名称同步。请小心处理日志;它们通常包含您的敏感信息 ","zh-tw":"警告!這會嚴重影響效能,而且日誌不會以預設名稱同步。請小心處理日誌,因為它們通常包含你的機密資訊。"},WATCHING:{def:"WATCHING",es:"OBSERVANDO",ko:"감시 중","zh-tw":"監看中"},'We can not use "/" to the device name':{def:'We can not use "/" to the device name',es:'No se puede usar "/" en el nombre del dispositivo',ko:'기기 이름에는 "/"를 사용할 수 없습니다',"zh-tw":"裝置名稱不可使用「/」"},"We can use only Secure (HTTPS) connections on Obsidian Mobile.":{def:"We can use only Secure (HTTPS) connections on Obsidian Mobile.",es:"En Obsidian Mobile solo se pueden usar conexiones seguras (HTTPS).",ko:"Obsidian 모바일에서는 보안(HTTPS) 연결만 사용할 수 있습니다.","zh-tw":"在 Obsidian Mobile 上只能使用安全連線(HTTPS)。"},"We cannot change the device name while this feature is enabled. Please disable this feature to change the device name.":{def:"We cannot change the device name while this feature is enabled. Please disable this feature to change the device name.",es:"No podemos cambiar el nombre del dispositivo mientras esta función esté habilitada. Deshabilita la función para cambiarlo.",ja:"この機能が有効な間はデバイス名を変更できません。変更するにはこの機能を無効にしてください。",ko:"이 기능이 활성화되어 있는 동안에는 기기 이름을 변경할 수 없습니다. 기기 이름을 변경하려면 이 기능을 비활성화하세요.",ru:"Невозможно изменить имя устройства, пока эта функция включена. Отключите её, чтобы изменить имя устройства.",zh:"启用此功能时无法更改设备名称。如需修改设备名称,请先禁用此功能。","zh-tw":"啟用此功能時無法變更裝置名稱。若要變更裝置名稱,請先停用此功能。"},"We have to configure the device name":{def:"We have to configure the device name",es:"Hay que configurar el nombre del dispositivo",ko:"기기 이름을 설정해야 합니다","zh-tw":"我們必須先設定裝置名稱"},"We recommend that you copy your Vault folder to a safe location. This will provide a safeguard in case a large number of conflicts arise, or if you accidentally synchronise with an incorrect destination.":{def:"We recommend that you copy your Vault folder to a safe location. This will provide a safeguard in case a large number of conflicts arise, or if you accidentally synchronise with an incorrect destination.",es:"Te recomendamos copiar la carpeta de tu Vault a un lugar seguro. Así tendrás una salvaguarda en caso de que surjan muchos conflictos o de que sincronices por error con un destino incorrecto.",ko:"보관함 폴더를 안전한 위치에 복사해 두시기를 권장합니다. 충돌이 대량으로 발생하거나 실수로 잘못된 대상과 동기화한 경우에 대비할 수 있습니다.","zh-tw":"我們建議你先將 Vault 資料夾複製到安全的位置。萬一發生大量衝突,或不小心同步到錯誤的目標,這可以作為一層保障。"},"We will now guide you through a few questions to simplify the synchronisation setup.":{def:"We will now guide you through a few questions to simplify the synchronisation setup.",es:"Ahora le guiaremos con unas pocas preguntas para simplificar la configuración de la sincronización。",ja:"これからいくつかの質問に沿って、同期設定を簡単に進めます。",ko:"동기화 설정을 간단히 마칠 수 있도록 몇 가지 질문으로 안내해 드리겠습니다.",ru:"Сейчас мы зададим несколько вопросов, чтобы упростить настройку синхронизации。",zh:"接下来我们会通过几个问题,引导你更轻松地完成同步设置。","zh-tw":"接下來我們會透過幾個問題,引導你更輕鬆地完成同步設定。"},"We will now proceed with the server configuration.":{def:"We will now proceed with the server configuration.",es:"Ahora continuaremos con la configuración del servidor。",ja:"次にサーバー設定を進めます。",ko:"이제 서버 구성을 진행하겠습니다.",ru:"Теперь перейдём к настройке сервера。",zh:"接下来将继续进行服务器配置。","zh-tw":"接下來將繼續進行伺服器設定。"},"Welcome to Self-hosted LiveSync":{def:"Welcome to Self-hosted LiveSync",es:"Bienvenido a Self-hosted LiveSync",ja:"Self-hosted LiveSync へようこそ",ko:"Self-hosted LiveSync에 오신 것을 환영합니다",ru:"Добро пожаловать в Self-hosted LiveSync",zh:"欢迎使用 Self-hosted LiveSync","zh-tw":"歡迎使用 Self-hosted LiveSync"},"When you save a file in the editor, start a sync automatically":{def:"When you save a file in the editor, start a sync automatically",es:"Iniciar sincronización automática al guardar en editor",fr:"À l'enregistrement d'un fichier dans l'éditeur, démarrer automatiquement une synchronisation",he:"כאשר אתה שומר קובץ בעורך, התחל סנכרון אוטומטית",ja:"エディタでファイルを保存すると、自動的に同期を開始します",ko:"편집기에서 파일을 저장할 때 자동으로 동기화를 시작합니다",ru:"Когда вы сохраняете файл в редакторе, автоматически запускать синхронизацию",zh:"当您在编辑器中保存文件时,自动开始同步","zh-tw":"在編輯器中儲存檔案時,自動開始同步"},"Write credentials in the file":{def:"Write credentials in the file",es:"Escribir credenciales en archivo",fr:"Écrire les identifiants dans le fichier",he:"כתוב פרטי גישה בקובץ",ja:"認証情報のファイル内保存",ko:"파일에 자격 증명 저장",ru:"Записывать учётные данные в файл",zh:"将凭据写入文件","zh-tw":"將憑證寫入檔案"},"Write logs into the file":{def:"Write logs into the file",es:"Escribir logs en archivo",fr:"Écrire les journaux dans le fichier",he:"כתוב יומנים לקובץ",ja:"ファイルにログを記録",ko:"파일에 로그 기록",ru:"Записывать логи в файл",zh:"将日志写入文件","zh-tw":"將日誌寫入檔案"},"xxhash32 (Fast but less collision resistance)":{def:"xxhash32 (Fast but less collision resistance)",es:"xxhash32 (rápido, pero con menor resistencia a colisiones)",ja:"xxhash32 (高速ですが衝突耐性は低め)",ko:"xxhash32 (빠르지만 충돌 저항성은 낮음)",ru:"xxhash32 (быстрый, но с меньшей устойчивостью к коллизиям)",zh:"xxhash32(速度快,但抗碰撞能力较弱)","zh-tw":"xxhash32(速度快,但抗碰撞能力較弱)"},"xxhash64 (Fastest)":{def:"xxhash64 (Fastest)",es:"xxhash64 (el más rápido)",ja:"xxhash64 (最速)",ko:"xxhash64 (가장 빠름)",ru:"xxhash64 (самый быстрый)",zh:"xxhash64(最快)","zh-tw":"xxhash64(最快)"},"Yes, I want to add this device to my existing synchronisation":{def:"Yes, I want to add this device to my existing synchronisation",es:"Sí, quiero añadir este dispositivo a mi sincronización existente",ja:"はい、この端末を既存の同期に追加します",ko:"예, 이 기기를 기존 동기화 구성에 추가하겠습니다",ru:"Да, я хочу добавить это устройство к существующей синхронизации",zh:"是的,我要把这台设备加入现有同步","zh-tw":"是的,我要把這台裝置加入既有同步"},"Yes, I want to set up a new synchronisation":{def:"Yes, I want to set up a new synchronisation",es:"Sí, quiero configurar una nueva sincronización",ja:"はい、新しい同期を設定します",ko:"예, 새 동기화를 설정하겠습니다",ru:"Да, я хочу настроить новую синхронизацию",zh:"是的,我要配置新的同步","zh-tw":"是的,我要設定新的同步"},"You are adding this device to an existing synchronisation setup.":{def:"You are adding this device to an existing synchronisation setup.",es:"Está añadiendo este dispositivo a una configuración de sincronización existente。",ja:"この端末を既存の同期構成に追加しようとしています。",ko:"이 기기를 기존 동기화 구성에 추가합니다.",ru:"Вы добавляете это устройство к существующей настройке синхронизации。",zh:"你正在将此设备加入到现有同步配置中。","zh-tw":"你正在將此裝置加入既有同步設定中。"},"You can configure in the Obsidian Plugin Settings.":{def:"You can configure in the Obsidian Plugin Settings.",es:"Puedes configurarlo en los ajustes del complemento de Obsidian.",ko:"Obsidian 플러그인 설정에서 구성할 수 있습니다.","zh-tw":"你可以在 Obsidian 外掛設定中進行設定。"},"You should create a new synchronisation destination and rebuild your data there.":{def:"You should create a new synchronisation destination and rebuild your data there.",es:"Deberías crear un nuevo destino de sincronización y reconstruir allí tus datos.",ko:"새로운 동기화 대상을 만들고 그곳에서 데이터를 재구축해야 합니다.","zh-tw":"你應該建立一個新的同步目標,並在該處重建你的資料。"},"You should perform this operation only in exceptional circumstances, such as when the server data is completely corrupted, when changes on all other devices are no longer needed, or when the database size has become unusually large in comparison to the Vault size.":{def:"You should perform this operation only in exceptional circumstances, such as when the server data is completely corrupted, when changes on all other devices are no longer needed, or when the database size has become unusually large in comparison to the Vault size.",es:"Solo deberías realizar esta operación en circunstancias excepcionales: cuando los datos del servidor estén completamente corruptos, cuando ya no necesites los cambios de los demás dispositivos o cuando el tamaño de la base de datos sea inusualmente grande respecto al del Vault.",ko:"이 작업은 서버 데이터가 완전히 손상된 경우, 다른 모든 기기의 변경 사항이 더 이상 필요하지 않은 경우, 또는 데이터베이스 크기가 보관함 크기에 비해 비정상적으로 커진 경우처럼 예외적인 상황에서만 수행해야 합니다.","zh-tw":"只有在特殊情況下才應執行此操作,例如伺服器資料已完全損毀、其他所有裝置上的變更都已不再需要,或資料庫大小相對於 Vault 大小已變得異常龐大時。"},"Compute revisions for chunks (Previous behaviour)":{es:"Calcular revisiones para chunks (comportamiento anterior)"},"Setup.> [!INFO]- The connected devices have been detected as follows:\n${devices}":{es:"> [!INFO]- Se detectaron los siguientes dispositivos conectados:\n${devices}"},"Setup.All devices have the same progress value (${progress}). Your devices seem to be synchronised. And be able to proceed with Garbage Collection.":{es:"Todos los dispositivos tienen el mismo valor de progreso (${progress}). Parece que tus dispositivos están sincronizados y se puede continuar con la recolección de basura."},"Setup.Cancel Garbage Collection":{es:"Cancelar la recolección de basura"},"Setup.Compaction in progress on remote database...":{es:"La compactación está en curso en la base de datos remota..."},"Setup.Compaction on remote database completed successfully.":{es:"La compactación en la base de datos remota se completó correctamente."},"Setup.Compaction on remote database failed.":{es:"La compactación en la base de datos remota falló."},"Setup.Compaction on remote database timed out.":{es:"La compactación en la base de datos remota agotó el tiempo de espera."},"Setup.Device":{es:"Dispositivo"},"Setup.Failed to connect to remote for compaction.":{es:"No se pudo conectar a la base de datos remota para la compactación."},"Setup.Failed to connect to remote for compaction. ${reason}":{es:"No se pudo conectar a la base de datos remota para la compactación. ${reason}"},"Setup.Failed to start one-shot replication before Garbage Collection. Garbage Collection Cancelled.":{es:"No se pudo iniciar la replicación de una sola vez antes de la recolección de basura. La recolección de basura se canceló."},"Setup.Failed to start replication after Garbage Collection.":{es:"No se pudo iniciar la replicación después de la recolección de basura."},"Setup.Garbage Collection cancelled by user.":{es:"El usuario canceló la recolección de basura."},"Setup.Garbage Collection completed. Deleted chunks: ${deletedChunks} / ${totalChunks}. Time taken: ${seconds} seconds.":{es:"Recolección de basura completada. Chunks eliminados: ${deletedChunks} / ${totalChunks}. Tiempo empleado: ${seconds} segundos."},"Setup.Garbage Collection Confirmation":{es:"Confirmación de recolección de basura"},"Setup.Garbage Collection: Found ${unusedChunks} unused chunks to delete.":{es:"Recolección de basura: se encontraron ${unusedChunks} chunks no usados para eliminar."},"Setup.Garbage Collection: Scanned ${scanned} / ~${docCount}":{es:"Recolección de basura: escaneados ${scanned} / ~${docCount}"},"Setup.Garbage Collection: Scanning completed. Total chunks: ${totalChunks}, Used chunks: ${usedChunks}":{es:"Recolección de basura: escaneo completado. Chunks totales: ${totalChunks}, chunks usados: ${usedChunks}"},"Setup.Ignore and Proceed":{es:"Ignorar y continuar"},"Setup.No connected device information found. Cancelling Garbage Collection.":{es:"No se encontró información de dispositivos conectados. Cancelando la recolección de basura."},"Setup.Node ID":{es:"ID del nodo"},"Setup.Node Information Missing":{es:"Falta información del nodo"},"Setup.Obsidian version":{es:"Versión de Obsidian"},"Setup.optionNoSetupUri":{es:"No, no tengo"},"Setup.optionRemindNextLaunch":{es:"Recordármelo en el próximo inicio"},"Setup.optionSetupWizard":{es:"Llévame al asistente de configuración"},"Setup.optionYesFetchAgain":{es:"Sí, obtener nuevamente"},"Setup.Please disable 'Read chunks online' in settings to use Garbage Collection.":{es:'Desactiva "Read chunks online" en los ajustes para usar la recolección de basura.'},"Setup.Please enable 'Compute revisions for chunks' in settings to use Garbage Collection.":{es:'Activa "Compute revisions for chunks" en los ajustes para usar la recolección de basura.'},"Setup.Please select 'Cancel' explicitly to cancel this operation.":{es:'Selecciona explícitamente "Cancelar" para cancelar esta operación.'},"Setup.Plug-in version":{es:"Versión del complemento"},"Setup.Proceed Garbage Collection":{es:"Continuar con la recolección de basura"},"Setup.Proceeding with Garbage Collection, ignoring missing nodes.":{es:"Continuando con la recolección de basura e ignorando los nodos faltantes."},"Setup.Proceeding with Garbage Collection.":{es:"Continuando con la recolección de basura."},"Setup.Progress":{es:"Progreso"},"Setup.Setup URI dialog cancelled.":{es:"Se canceló el diálogo de Setup URI."},"Setup.Some devices have differing progress values (max: ${maxProgress}, min: ${minProgress}).\nThis may indicate that some devices have not completed synchronisation, which could lead to conflicts. Strongly recommend confirming that all devices are synchronised before proceeding.":{es:"Algunos dispositivos tienen valores de progreso diferentes (máx.: ${maxProgress}, mín.: ${minProgress}).\nEsto puede indicar que algunos dispositivos no han completado la sincronización, lo que podría causar conflictos. Se recomienda encarecidamente confirmar que todos los dispositivos estén sincronizados antes de continuar."},"Setup.The following accepted nodes are missing its node information:\n- ${missingNodes}\n\nThis indicates that they have not been connected for some time or have been left on an older version.\nIt is preferable to update all devices if possible. If you have any devices that are no longer in use, you can clear all accepted nodes by locking the remote once.":{es:"Los siguientes nodos aceptados no tienen información del nodo:\n- ${missingNodes}\n\nEsto indica que no se han conectado desde hace algún tiempo o que se han quedado en una versión anterior.\nSi es posible, es preferible actualizar todos los dispositivos. Si tienes dispositivos que ya no se usan, puedes borrar todos los nodos aceptados bloqueando el remoto una vez."},"Setup.titleCaseSensitivity":{es:"Sensibilidad a mayúsculas"},"Setup.titleRecommendSetupUri":{es:"Recomendación de uso de URI de configuración"},"Setup.titleWelcome":{es:"Bienvenido a Self-hosted LiveSync"},"(Not recommended) If set, credentials will be stored in the file":{ru:"(Не рекомендуется) Если установлено, учётные данные будут сохранены в файле"},"Before v0.17.16, we used an old adapter for the local database. Now the new adapter is preferred. However, it needs local database rebuilding.":{ru:"До v0.17.16 мы использовали старый адаптер для локальной базы данных. Теперь предпочтителен новый адаптер. Однако требуется перестроение локальной базы данных."},descConnectSetupURI:{ru:"Это рекомендуемый способ настройки Self-hosted LiveSync с помощью Setup URI."},descCopySetupURI:{ru:"Идеально для настройки нового устройства!"},descEnableLiveSync:{ru:"Включайте это только после настройки одного из двух вариантов выше."},descFetchConfigFromRemote:{ru:"Загрузить необходимые настройки с уже настроенного удалённого сервера."},descManualSetup:{ru:"Не рекомендуется, но полезно, если у вас нет Setup URI"},descTestDatabaseConnection:{ru:"Открыть подключение к базе данных."},descValidateDatabaseConfig:{ru:"Проверяет и исправляет потенциальные проблемы с конфигурацией базы данных."},"If enabled per-filed efficient customization sync will be used. We need a small migration when enabling this.":{ru:"Если включено, будет использоваться эффективная синхронизация настроек для каждого файла."},"If this is set, changes to local files which are matched by the ignore files will be skipped.":{ru:"Если установлено, изменения файлов из списка игнорирования будут пропущены."},"If this option is enabled, PouchDB will hold the connection open for 60 seconds, and if no change arrives in that time, close and reopen the socket, instead of holding it open indefinitely.":{ru:"Если эта опция включена, PouchDB будет держать соединение открытым 60 секунд."},"Number of batches to process at a time. Defaults to 40. Minimum is 2.":{ru:"Количество пакетов для обработки за раз. По умолчанию 40. Минимум 2."},"Save settings to a markdown file.":{ru:"Сохранить настройки в файл markdown."},"The maximum duration for which chunks can be incubated within the document.":{ru:"Максимальная продолжительность инкубации чанков в документе."},"The maximum number of chunks that can be incubated within the document.":{ru:"Максимальное количество инкубируемых чанков в документе."},"The maximum total size of chunks that can be incubated within the document.":{ru:"Максимальный общий размер инкубируемых чанков в документе."},"This passphrase will not be copied to another device. It will be set to until you configure it again.":{ru:"Эта парольная фраза не будет скопирована на другое устройство."},"Warning! This will have a serious impact on performance. And the logs will not be synchronised under the default name.":{ru:"Внимание! Это серьёзно повлияет на производительность."}};liveSyncProvisionalEnglishMessages={"This first setup has several short steps because it confirms encryption, the connection method, and which device provides the initial data. Once it is complete, additional devices can reuse a Setup URI.":"This first setup has several short steps because it confirms encryption, the connection method, and which device provides the initial data. Once it is complete, additional devices can reuse a Setup URI.","Setup Complete: Preparing to Fetch from Another Device":"Setup Complete: Preparing to Fetch from Another Device","The P2P connection has been configured successfully. The initial synchronisation data must now be fetched from an online source device.":"The P2P connection has been configured successfully. The initial synchronisation data must now be fetched from an online source device.","After restarting, select an online source device for the initial Fetch. The local LiveSync database on this device will be rebuilt from that source. Unsynchronised files in this Vault may conflict with the fetched data.":"After restarting, select an online source device for the initial Fetch. The local LiveSync database on this device will be rebuilt from that source. Unsynchronised files in this Vault may conflict with the fetched data.","Restart this device, then choose the source device when P2P Rebuild opens.":"Restart this device, then choose the source device when P2P Rebuild opens.","Restart and Select Source Device":"Restart and Select Source Device","P2P Status pane":"P2P Status pane","No central data-storage server is required, but a signalling relay is required for peer discovery. Both devices must be online at the same time. Vault data travels through the encrypted P2P connection, not through the signalling relay. Some features may be limited.":"No central data-storage server is required, but a signalling relay is required for peer discovery. Both devices must be online at the same time. Vault data travels through the encrypted P2P connection, not through the signalling relay. Some features may be limited.","P2P requires no central data-storage server, but it still uses a signalling relay for peer discovery.":"P2P requires no central data-storage server, but it still uses a signalling relay for peer discovery.","Signalling relay URLs":"Signalling relay URLs","Peer discovery uses Nostr-compatible signalling relays.":"Peer discovery uses Nostr-compatible signalling relays.","Use the project's public signalling relay":"Use the project's public signalling relay","The project's public signalling relay is a best-effort convenience operated by the project author. It does not store Vault contents, but signalling metadata may be visible to the relay. Availability and log retention are not guaranteed. You can replace it with your own Nostr-compatible relay.":"The project's public signalling relay is a best-effort convenience operated by the project author. It does not store Vault contents, but signalling metadata may be visible to the relay. Availability and log retention are not guaranteed. You can replace it with your own Nostr-compatible relay.","Learn more about P2P connections":"Learn more about P2P connections","Learn more about signalling and TURN":"Learn more about signalling and TURN","TURN relays the encrypted WebRTC connection only when a direct path cannot be established. A TURN provider cannot read encrypted Vault contents, but it can observe connection metadata and traffic volume. Use a provider you trust.":"TURN relays the encrypted WebRTC connection only when a direct path cannot be established. A TURN provider cannot read encrypted Vault contents, but it can observe connection metadata and traffic volume. Use a provider you trust.","Connection compatibility":"Connection compatibility","P2P message size":"P2P message size",Standard:"Standard",Reduced:"Reduced",Conservative:"Conservative","Maximum compatibility":"Maximum compatibility","Smaller messages can improve compatibility on paths which fragment or drop larger WebRTC messages. This setting limits outgoing P2P messages, so use a compatible profile on each sending device when required.":"Smaller messages can improve compatibility on paths which fragment or drop larger WebRTC messages. This setting limits outgoing P2P messages, so use a compatible profile on each sending device when required.","Connection path":"Connection path","TURN relay only":"TURN relay only","TURN relay only is available when at least one valid TURN server URL is configured under Advanced Settings.":"TURN relay only is available when at least one valid TURN server URL is configured under Advanced Settings.","TURN relay only requires at least one valid TURN server URL. Connection path has been restored to Automatic.":"TURN relay only requires at least one valid TURN server URL. Connection path has been restored to Automatic.","Announce changes":"Announce changes","Announce changes automatically after connecting":"Announce changes automatically after connecting","When enabled, this device notifies connected peers after a local change. The notification contains no Vault data; a peer which follows this device then fetches the change through the encrypted P2P connection.":"When enabled, this device notifies connected peers after a local change. The notification contains no Vault data; a peer which follows this device then fetches the change through the encrypted P2P connection.","Stop announcing changes":"Stop announcing changes","Start announcing changes":"Start announcing changes","Follow changes":"Follow changes","Stop following changes from this device":"Stop following changes from this device","Follow changes from this device":"Follow changes from this device","Synchronise when this device connects":"Synchronise when this device connects","Follow whenever this device connects":"Follow whenever this device connects","Include in the P2P synchronisation command":"Include in the P2P synchronisation command","More actions for ${DEVICE}":"More actions for ${DEVICE}","Create or connect to database and continue":"Create or connect to database and continue","Connect to existing database and continue":"Connect to existing database and continue","Test connection and save":"Test connection and save","Save without connecting":"Save without connecting","Use this device's settings":"Use this device's settings",Retry:"Retry","No Synchronisation Settings Found":"No Synchronisation Settings Found","The selected remote has no saved synchronisation settings. This is normal for a new remote. Use this device's settings, or cancel if you expected existing settings.":"The selected remote has no saved synchronisation settings. This is normal for a new remote. Use this device's settings, or cancel if you expected existing settings.","Could Not Read Synchronisation Settings":"Could Not Read Synchronisation Settings","Could not read the remote's synchronisation settings. Check the connection and credentials, then retry.":"Could not read the remote's synchronisation settings. Check the connection and credentials, then retry.","Could not read the remote's synchronisation settings. Retry, or continue the overwrite with this device's settings. A working connection is still required.":"Could not read the remote's synchronisation settings. Retry, or continue the overwrite with this device's settings. A working connection is still required.","Skips checking and applying synchronisation settings from the remote.":"Skips checking and applying synchronisation settings from the remote.","Enter a complete HTTP or HTTPS URL.":"Enter a complete HTTP or HTTPS URL.","CouchDB validates the database name when you connect. The name must not be empty.":"CouchDB validates the database name when you connect. The name must not be empty.","Saving without a successful connection test keeps this profile, but automatic synchronisation may fail until the connection is corrected.":"Saving without a successful connection test keeps this profile, but automatic synchronisation may fail until the connection is corrected.","This optional check uses Obsidian's internal request API and sends the credentials above to the CouchDB server. Use it only with a server you trust; administrator access may be required.":"This optional check uses Obsidian's internal request API and sends the credentials above to the CouchDB server. Use it only with a server you trust; administrator access may be required.","Check server requirements":"Check server requirements","Change CouchDB server setting":"Change CouchDB server setting","Change CouchDB server setting '${SETTING}' to '${VALUE}'?":"Change CouchDB server setting '${SETTING}' to '${VALUE}'?","This file has unresolved conflicts.":"This file has unresolved conflicts.","This file has ${COUNT} unresolved versions. They will be reviewed one pair at a time.":"This file has ${COUNT} unresolved versions. They will be reviewed one pair at a time.","Sync now":"Sync now","Apply pending changes now":"Apply pending changes now","Copy database information for the active file":"Copy database information for the active file","Copy database information for a file":"Copy database information for a file","Copy revision, conflict, and local chunk availability information, including document and chunk identifiers but not file contents.":"Copy revision, conflict, and local chunk availability information, including document and chunk identifiers but not file contents.","Choose file":"Choose file","Choose a file to inspect":"Choose a file to inspect","Database information for ${FILE}":"Database information for ${FILE}","All revisions and chunk availability below are a snapshot of this device's local database; the remote is not queried. Review the Vault-relative path, document identifier, content-derived chunk identifiers, and metadata before sharing this report. File contents are omitted.":"All revisions and chunk availability below are a snapshot of this device's local database; the remote is not queried. Review the Vault-relative path, document identifier, content-derived chunk identifiers, and metadata before sharing this report. File contents are omitted.","📁 Vault: ${SIZE} B · ${TIME}":"📁 Vault: ${SIZE} B · ${TIME}","📁 Vault: missing":"📁 Vault: missing","🗄️ Local DB: missing":"🗄️ Local DB: missing","Vault and database revision":"Vault and database revision","Vault file":"Vault file","Database revision":"Database revision","Vault file is newer":"Vault file is newer","Database revision is newer":"Database revision is newer","Within the two-second comparison window":"Within the two-second comparison window","Timestamp comparison unavailable":"Timestamp comparison unavailable","${ROLE}: ${REVISION}":"${ROLE}: ${REVISION}","Winner revision":"Winner revision","Conflict revision":"Conflict revision","Unknown revision":"Unknown revision","🗑️ Logical deletion":"🗑️ Logical deletion","Readable on this device; recorded size ${RECORDED}, decoded size ${ACTUAL}":"Readable on this device; recorded size ${RECORDED}, decoded size ${ACTUAL}","🧩 Missing chunks: ${COUNT}":"🧩 Missing chunks: ${COUNT}","📦 DB: recorded ${RECORDED} B · decoded ${DECODED} B · Δsize ${DIFFERENCE} B":"📦 DB: recorded ${RECORDED} B · decoded ${DECODED} B · Δsize ${DIFFERENCE} B","📦 DB: recorded ${RECORDED} B · decoded unavailable":"📦 DB: recorded ${RECORDED} B · decoded unavailable","📁 Vault: ${VAULT} B · Δsize vs DB ${DIFFERENCE} B":"📁 Vault: ${VAULT} B · Δsize vs DB ${DIFFERENCE} B","🕒 DB ${DATABASE_TIME} · Vault ${VAULT_TIME} · Δtime ${DIFFERENCE} ms (${RELATION})":"🕒 DB ${DATABASE_TIME} · Vault ${VAULT_TIME} · Δtime ${DIFFERENCE} ms (${RELATION})","✅ Matches Vault":"✅ Matches Vault","⚠️ Differs from Vault":"⚠️ Differs from Vault","✅ Vault matches winner":"✅ Vault matches winner","⚠️ Conflicts: ${COUNT}":"⚠️ Conflicts: ${COUNT}","Compare with Vault":"Compare with Vault","Apply this revision to Vault":"Apply this revision to Vault","Apply database revision ${REVISION} to ${FILE}? The current Vault file will be overwritten.":"Apply database revision ${REVISION} to ${FILE}? The current Vault file will be overwritten.","Apply database revision to Vault":"Apply database revision to Vault","Mark this revision as the Vault version":"Mark this revision as the Vault version","Store Vault file as a child of this revision":"Store Vault file as a child of this revision","Apply logical deletion to Vault":"Apply logical deletion to Vault","Apply logical deletion ${REVISION} to ${FILE}? The current Vault file will be removed.":"Apply logical deletion ${REVISION} to ${FILE}? The current Vault file will be removed.","Retry reading revision":"Retry reading revision","Discard this branch":"Discard this branch","Discard branch":"Discard branch","Discard database branch ${REVISION} of ${FILE}? This creates a logical deletion for that exact live branch. The current Vault file will not be changed.":"Discard database branch ${REVISION} of ${FILE}? This creates a logical deletion for that exact live branch. The current Vault file will not be changed.","Discard unreadable revision":"Discard unreadable revision","Discard database revision ${REVISION} of ${FILE}? This creates a logical deletion for that exact live revision. Missing content cannot be recovered by this action.":"Discard database revision ${REVISION} of ${FILE}? This creates a logical deletion for that exact live revision. Missing content cannot be recovered by this action.","Revision metadata is unavailable on this device":"Revision metadata is unavailable on this device","Shared ancestor ${REVISION} is not readable on this device. Automatic three-way merging may be unavailable, but the live revisions remain available for explicit review.":"Shared ancestor ${REVISION} is not readable on this device. Automatic three-way merging may be unavailable, but the live revisions remain available for explicit review.","No shared ancestor is available for this conflict. The live revisions remain available for explicit review.":"No shared ancestor is available for this conflict. The live revisions remain available for explicit review.","More actions for revision ${REVISION}":"More actions for revision ${REVISION}","More actions for ${FILE}":"More actions for ${FILE}","Show revision history":"Show revision history","Store Vault file as a new local database document":"Store Vault file as a new local database document","Copy database information":"Copy database information","Recreate chunks for current Vault files":"Recreate chunks for current Vault files","Recreate chunks from the files currently present in this Vault. This cannot reconstruct unavailable historical or conflict content.":"Recreate chunks from the files currently present in this Vault. This cannot reconstruct unavailable historical or conflict content.","Recreate current chunks":"Recreate current chunks","Resolve every conflict by modification time? This logically deletes every version except the newest one and cannot recover content which is already unavailable.":"Resolve every conflict by modification time? This logically deletes every version except the newest one and cannot recover content which is already unavailable.","Resolve all conflicts by the newest version":"Resolve all conflicts by the newest version","Inspect conflicts and file/database differences":"Inspect conflicts and file/database differences","Scan Vault files and local-database Metadata for conflicts, missing chunks, identity mismatches, and differences. Each result provides actions for one exact entry or revision.":"Scan Vault files and local-database Metadata for conflicts, missing chunks, identity mismatches, and differences. Each result provides actions for one exact entry or revision.","Begin inspection":"Begin inspection","Metadata entry requires review and was left unchanged":"Metadata entry requires review and was left unchanged","The stored document ID does not match the ID derived from its recorded path.":"The stored document ID does not match the ID derived from its recorded path.","The stored document ID and recorded path are handled by different synchronisation features.":"The stored document ID and recorded path are handled by different synchronisation features.","Stored document ID: ${ID}":"Stored document ID: ${ID}","Expected document ID: ${ID}":"Expected document ID: ${ID}","Source revision: ${REVISION}":"Source revision: ${REVISION}","One-step repair is unavailable because this entry is ambiguous, no longer current, or unsafe to change.":"One-step repair is unavailable because this entry is ambiguous, no longer current, or unsafe to change.","An exact target is already present; repair can remove the obsolete ID.":"An exact target is already present; repair can remove the obsolete ID.","Repair is available for this entry.":"Repair is available for this entry.","Repair this Metadata document ID":"Repair this Metadata document ID","Repair Metadata ID":"Repair Metadata ID","Keep unchanged":"Keep unchanged","Repair Metadata document ID":"Repair Metadata document ID","This moves one local Metadata entry to the ID derived from its recorded path.\n\n**File:** `${FILE}` \n**Source:** `${SOURCE}@${REVISION}` \n**Target:** `${TARGET}`\n\nThe target is verified before the source is removed. Its CouchDB revision ancestry cannot be preserved.\n\n> [!warning] Before repairing\n> - Back up this device.\n> - If file-name case or path obfuscation was intentionally changed for the whole database, use Rebuild instead.\n> - If other devices share this database, pause them, allow this device to upload the repair, then resume them one at a time.":"This moves one local Metadata entry to the ID derived from its recorded path.\n\n**File:** `${FILE}` \n**Source:** `${SOURCE}@${REVISION}` \n**Target:** `${TARGET}`\n\nThe target is verified before the source is removed. Its CouchDB revision ancestry cannot be preserved.\n\n> [!warning] Before repairing\n> - Back up this device.\n> - If file-name case or path obfuscation was intentionally changed for the whole database, use Rebuild instead.\n> - If other devices share this database, pause them, allow this device to upload the repair, then resume them one at a time.","Metadata document ID repair and the ordinary Vault scan completed. Run this inspection again after synchronisation.":"Metadata document ID repair and the ordinary Vault scan completed. Run this inspection again after synchronisation.","Metadata document ID repair completed, but the ordinary Vault scan did not run. Keep synchronisation paused, resolve the scan condition, then run 'Scan storage and database again'.":"Metadata document ID repair completed, but the ordinary Vault scan did not run. Keep synchronisation paused, resolve the scan condition, then run 'Scan storage and database again'.","The inspected state changed. No repair was performed; run inspection again.":"The inspected state changed. No repair was performed; run inspection again.","Repair stopped after creating the target. The source was retained. Run inspection again before retrying.":"Repair stopped after creating the target. The source was retained. Run inspection again before retrying.","Repair failed before the source was removed. Run inspection again before retrying.":"Repair failed before the source was removed. Run inspection again before retrying.","Connection settings":"Connection settings","Saved connections":"Saved connections"};obsidianLangMap={de:"de",es:"es",ja:"ja",ko:"ko",ru:"ru",zh:"zh","zh-cn":"zh","zh-hans":"zh","zh-tw":"zh-tw","zh-hk":"zh-tw","zh-mo":"zh-tw","zh-hant":"zh-tw"};currentLang=resolveLanguage("");missingTranslations=[];__onMissingTranslations=key3=>notice(key3,LOG_KIND_WARNING);msgCache=new Map;translateLiveSyncMessage=(key3,params)=>isLiveSyncMessageKey(key3)?$msg(key3,void 0===params?void 0:{...params}):englishMessageTranslator(key3,params);root2=from_html("<pre> </pre>");root_1=from_html('<div class="logpane svelte-o3lsbg"><div class="control svelte-o3lsbg"><div class="row svelte-o3lsbg"><label class="svelte-o3lsbg"><input type="checkbox" class="svelte-o3lsbg"/> <span class="svelte-o3lsbg"> </span></label> <label class="svelte-o3lsbg"><input type="checkbox" class="svelte-o3lsbg"/> <span class="svelte-o3lsbg"> </span></label> <label class="svelte-o3lsbg"><input type="checkbox" class="svelte-o3lsbg"/> <span class="svelte-o3lsbg"> </span></label> <span class="spacer svelte-o3lsbg"></span> <button class="svelte-o3lsbg">Close</button></div></div> <div class="log svelte-o3lsbg"></div></div>');$$css={hash:"svelte-o3lsbg",code:".svelte-o3lsbg {box-sizing:border-box;}.logpane.svelte-o3lsbg {display:flex;height:100%;flex-direction:column;}.log.svelte-o3lsbg {overflow-y:scroll;user-select:text;-webkit-user-select:text;padding-bottom:2em;}.log.svelte-o3lsbg > pre:where(.svelte-o3lsbg) {margin:0;}.log.svelte-o3lsbg > pre.wrap-right:where(.svelte-o3lsbg) {word-break:break-all;max-width:100%;width:100%;white-space:normal;}.row.svelte-o3lsbg {display:flex;flex-direction:row;justify-content:flex-end;}.row.svelte-o3lsbg > label:where(.svelte-o3lsbg) {display:flex;align-items:center;min-width:5em;margin-right:1em;}"};delegate(["click"]);SvelteItemView=class extends import_obsidian.ItemView{async onOpen(){await super.onOpen();this.contentEl.empty();await this._dismountComponent();this.component=await this.instantiateComponent(this.contentEl)}async _dismountComponent(){if(this.component){await unmount(this.component);this.component=void 0}}async onClose(){await super.onClose();if(this.component){await unmount(this.component);this.component=void 0}}};VIEW_TYPE_LOG="log-log";LogPaneView=class extends SvelteItemView{constructor(leaf,plugin2){super(leaf);this.icon="view-log";this.title="";this.navigation=!1;this.plugin=plugin2}instantiateComponent(target){return mount(LogPane,{target,props:{close:()=>{this.leaf.detach()}}})}getIcon(){return"view-log"}getViewType(){return VIEW_TYPE_LOG}getDisplayText(){return $msg("logPane.title")}};secp256k1_CURVE=Object.freeze({p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt("1"),a:BigInt("0"),b:BigInt("7"),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")});var{p:P,n:N,Gx,Gy,b:_b4}=secp256k1_CURVE;L=32;L2=64;lengths={publicKey:L+1,publicKeyUncompressed:L2+1,signature:L2,seed:L+L/2};err=(message="",E2=Error)=>{const e3=new E2(message),{captureStackTrace}=Error;"function"==typeof captureStackTrace&&captureStackTrace(e3,err);throw e3};isBytes=a2=>a2 instanceof Uint8Array||ArrayBuffer.isView(a2)&&"Uint8Array"===a2.constructor.name&&1===a2.BYTES_PER_ELEMENT;abytes=(value,length,title="")=>{const bytes=isBytes(value),len=null==value?void 0:value.length,needsLen=void 0!==length;if(!bytes||needsLen&&len!==length){const prefix=title&&`"${title}" `,ofLen=needsLen?` of length ${length}`:"",got=bytes?`length=${len}`:"type="+typeof value,msg=prefix+"expected Uint8Array"+ofLen+", got "+got;return err(msg,bytes?RangeError:TypeError)}return value};u8n=len=>new Uint8Array(len);padh=(n3,pad2)=>n3.toString(16).padStart(pad2,"0");bytesToHex=b3=>{let hex="";for(const e3 of abytes(b3))hex+=padh(e3,2);return hex};C__0=48,C__9=57,C_A=65,C_F=70,C_a=97,C_f=102;_ch=ch4=>ch4>=C__0&&ch4<=C__9?ch4-C__0:ch4>=C_A&&ch4<=C_F?ch4-(C_A-10):ch4>=C_a&&ch4<=C_f?ch4-(C_a-10):void 0;hexToBytes=hex=>{const e3="hex invalid";if("string"!=typeof hex)return err(e3);const hl=hex.length,al2=hl/2;if(hl%2)return err(e3);const array=u8n(al2);for(let ai2=0,hi=0;ai2<al2;ai2++,hi+=2){const n1=_ch(hex.charCodeAt(hi)),n22=_ch(hex.charCodeAt(hi+1));if(void 0===n1||void 0===n22)return err(e3);array[ai2]=16*n1+n22}return array};subtle=()=>{var _a13,_b6;return null!=(_b6=null==(_a13=null==globalThis?void 0:globalThis.crypto)?void 0:_a13.subtle)?_b6:err("crypto.subtle must be defined, consider polyfill")};concatBytes=(...arrs)=>{let len=0;for(const a2 of arrs)len+=abytes(a2).length;const r4=u8n(len);let pad2=0;for(const a2 of arrs)r4.set(a2,pad2),pad2+=a2.length;return r4};randomBytes=(len=L)=>(null==globalThis?void 0:globalThis.crypto).getRandomValues(u8n(len));big=BigInt;arange=(n3,min2,max3,msg="bad number: out of range")=>"bigint"!=typeof n3?err(msg,TypeError):min2<=n3&&n3<max3?n3:err(msg,RangeError);M=(a2,b3=P)=>{const r4=a2%b3;return r4>=BigInt("0")?r4:b3+r4};modN=a2=>M(a2,N);invert=(num,md)=>{(num===BigInt("0")||md<=BigInt("0"))&&err("no inverse n="+num+" mod="+md);let a2=M(num,md),b3=md,x3=BigInt("0"),y2=BigInt("1"),u2=BigInt("1"),v2=BigInt("0");for(;a2!==BigInt("0");){const q2=b3/a2,r4=b3%a2,m3=x3-u2*q2,n3=y2-v2*q2;b3=a2,a2=r4,x3=u2,y2=v2,u2=m3,v2=n3}return b3===BigInt("1")?M(x3,md):err("no inverse")};callHash=name=>{const fn=hashes[name];"function"!=typeof fn&&err("hashes."+name+" not set");return fn};gh=(name,a2,b3)=>abytes(callHash(name)(a2,b3),L,"digest");gha=(name,a2,b3)=>Promise.resolve(callHash(name)(a2,b3)).then(r4=>abytes(r4,L,"digest"));0;apoint=p2=>p2 instanceof Point?p2:err("Point expected");koblitz=x3=>M(M(x3*x3)*x3+_b4);FpIsValid=n3=>arange(n3,BigInt("0"),P);FpIsValidNot0=n3=>arange(n3,BigInt("1"),P);FnIsValidNot0=n3=>arange(n3,BigInt("1"),N);isEven=y2=>!(y2&BigInt("1"));u8of=n3=>Uint8Array.of(n3);getPrefix=y2=>u8of(isEven(y2)?2:3);lift_x=x3=>{const c3=koblitz(FpIsValidNot0(x3));let r4=BigInt("1");for(let num=c3,e3=(P+BigInt("1"))/BigInt("4");e3>BigInt("0");e3>>=BigInt("1")){e3&BigInt("1")&&(r4=r4*num%P);num=num*num%P}M(r4*r4)!==c3&&err("sqrt invalid");return isEven(r4)?r4:M(-r4)};0;_Point=class _Point{constructor(X2,Y2,Z2){__publicField(this,"X");__publicField(this,"Y");__publicField(this,"Z");this.X=FpIsValid(X2);this.Y=FpIsValidNot0(Y2);this.Z=FpIsValid(Z2);Object.freeze(this)}static CURVE(){return secp256k1_CURVE}static fromAffine(ap2){const{x:x3,y:y2}=ap2;return x3===BigInt("0")&&y2===BigInt("0")?I:new _Point(x3,y2,BigInt("1"))}static fromBytes(bytes){abytes(bytes);const{publicKey:comp,publicKeyUncompressed:uncomp}=lengths;let p2;const length=bytes.length,head2=bytes[0],tail=bytes.subarray(1),x3=sliceBytesNumBE(tail,0,L);if(length===comp&&(2===head2||3===head2)){let y2=lift_x(x3);3===head2&&(y2=M(-y2));p2=new _Point(x3,y2,BigInt("1"))}length===uncomp&&4===head2&&(p2=new _Point(x3,sliceBytesNumBE(tail,L,L2),BigInt("1")));return p2?p2.assertValidity():err("bad point: not on curve")}static fromHex(hex){return _Point.fromBytes(hexToBytes(hex))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}equals(other){const{X:X1,Y:Y1,Z:Z1}=this,{X:X2,Y:Y2,Z:Z2}=apoint(other),X1Z2=M(X1*Z2),X2Z1=M(X2*Z1),Y1Z2=M(Y1*Z2),Y2Z1=M(Y2*Z1);return X1Z2===X2Z1&&Y1Z2===Y2Z1}is0(){return this.equals(I)}negate(){return new _Point(this.X,M(-this.Y),this.Z)}double(){return this.add(this)}add(other){const{X:X1,Y:Y1,Z:Z1}=this,{X:X2,Y:Y2,Z:Z2}=apoint(other),a2=BigInt("0"),b3=_b4;let X3=BigInt("0"),Y3=BigInt("0"),Z3=BigInt("0");const b32=M(b3*BigInt("3"));let t02=M(X1*X2),t12=M(Y1*Y2),t22=M(Z1*Z2),t32=M(X1+Y1),t42=M(X2+Y2);t32=M(t32*t42);t42=M(t02+t12);t32=M(t32-t42);t42=M(X1+Z1);let t52=M(X2+Z2);t42=M(t42*t52);t52=M(t02+t22);t42=M(t42-t52);t52=M(Y1+Z1);X3=M(Y2+Z2);t52=M(t52*X3);X3=M(t12+t22);t52=M(t52-X3);Z3=M(a2*t42);X3=M(b32*t22);Z3=M(X3+Z3);X3=M(t12-Z3);Z3=M(t12+Z3);Y3=M(X3*Z3);t12=M(t02+t02);t12=M(t12+t02);t22=M(a2*t22);t42=M(b32*t42);t12=M(t12+t22);t22=M(t02-t22);t22=M(a2*t22);t42=M(t42+t22);t02=M(t12*t42);Y3=M(Y3+t02);t02=M(t52*t42);X3=M(t32*X3);X3=M(X3-t02);t02=M(t32*t12);Z3=M(t52*Z3);Z3=M(Z3+t02);return new _Point(X3,Y3,Z3)}subtract(other){return this.add(apoint(other).negate())}multiply(n3,safe=!0){if(!safe&&n3===BigInt("0"))return I;FnIsValidNot0(n3);if(n3===BigInt("1"))return this;if(this.equals(G))return wNAF(n3).p;let p2=I,f4=G;for(let d4=this;n3>BigInt("0");d4=d4.double(),n3>>=BigInt("1"))n3&BigInt("1")?p2=p2.add(d4):safe&&(f4=f4.add(d4));return p2}multiplyUnsafe(scalar){return this.multiply(scalar,!1)}toAffine(){const{X:x3,Y:y2,Z:z2}=this;if(this.equals(I))return{x:BigInt("0"),y:BigInt("0")};if(z2===BigInt("1"))return{x:x3,y:y2};const iz=invert(z2,P);M(z2*iz)!==BigInt("1")&&err("inverse invalid");return{x:M(x3*iz),y:M(y2*iz)}}assertValidity(){const{x:x3,y:y2}=this.toAffine();FpIsValidNot0(x3);FpIsValidNot0(y2);return M(y2*y2)===koblitz(x3)?this:err("bad point: not on curve")}toBytes(isCompressed=!0){const{x:x3,y:y2}=this.assertValidity().toAffine(),x32b=numTo32b(x3);return isCompressed?concatBytes(getPrefix(y2),x32b):concatBytes(u8of(4),x32b,numTo32b(y2))}toHex(isCompressed){return bytesToHex(this.toBytes(isCompressed))}};__publicField(_Point,"BASE");__publicField(_Point,"ZERO");Point=_Point;G=new Point(Gx,Gy,BigInt("1"));I=new Point(BigInt("0"),BigInt("1"),BigInt("0"));Point.BASE=G;Point.ZERO=I;doubleScalarMulUns=(R2,u1,u2)=>G.multiply(u1,!1).add(R2.multiply(u2,!1)).assertValidity();bytesToNumBE=b3=>big("0x"+(bytesToHex(b3)||"0"));sliceBytesNumBE=(b3,from,to)=>bytesToNumBE(b3.subarray(from,to));B256=BigInt("2")**BigInt("256");numTo32b=num=>hexToBytes(padh(arange(num,BigInt("0"),B256),L2));secretKeyToScalar=secretKey2=>{const num=bytesToNumBE(abytes(secretKey2,L,"secret key"));return arange(num,BigInt("1"),N,"invalid secret key: outside of range")};highS=n3=>n3>N>>BigInt("1");getPublicKey=(privKey,isCompressed=!0)=>G.multiply(secretKeyToScalar(privKey)).toBytes(isCompressed);isValidSecretKey=secretKey2=>{try{return!!secretKeyToScalar(secretKey2)}catch(error){return!1}};isValidPublicKey=(publicKey2,isCompressed)=>{const{publicKey:comp,publicKeyUncompressed}=lengths;try{const l2=publicKey2.length;return(!0!==isCompressed||l2===comp)&&((!1!==isCompressed||l2===publicKeyUncompressed)&&!!Point.fromBytes(publicKey2))}catch(error){return!1}};assertRecoveryBit=recovery=>[0,1,2,3].includes(recovery)?recovery:err("invalid recovery id");assertSigFormat=format2=>{format2===SIG_DER&&err('Signature format "der" is not supported: switch to noble-curves');null!=format2&&format2!==SIG_COMPACT&&format2!==SIG_RECOVERED&&err("Signature format must be one of: compact, recovered, der")};assertSigLength=(sig,format2=SIG_COMPACT)=>{assertSigFormat(format2);const len=lengths.signature+Number(format2===SIG_RECOVERED);sig.length!==len&&err(`Signature format "${format2}" expects Uint8Array with length ${len}`)};Signature=class _Signature{constructor(r4,s2,recovery){__publicField(this,"r");__publicField(this,"s");__publicField(this,"recovery");this.r=FnIsValidNot0(r4);this.s=FnIsValidNot0(s2);null!=recovery&&(this.recovery=assertRecoveryBit(recovery));Object.freeze(this)}static fromBytes(b3,format2=SIG_COMPACT){assertSigLength(b3,format2);let rec;if(format2===SIG_RECOVERED){rec=b3[0];b3=b3.subarray(1)}const r4=sliceBytesNumBE(b3,0,L),s2=sliceBytesNumBE(b3,L,L2);return new _Signature(r4,s2,rec)}addRecoveryBit(bit){return new _Signature(this.r,this.s,bit)}hasHighS(){return highS(this.s)}toBytes(format2=SIG_COMPACT){assertSigFormat(format2);const{r:r4,s:s2,recovery}=this,res2=concatBytes(numTo32b(r4),numTo32b(s2));return format2===SIG_RECOVERED?concatBytes(u8of(assertRecoveryBit(recovery)),res2):res2}};bits2int=bytes=>{bytes.length>8192&&err("input is too large");const delta=8*bytes.length-256,num=bytesToNumBE(bytes);return delta>0?num>>big(delta):num};bits2int_modN=bytes=>modN(bits2int(abytes(bytes)));SIG_COMPACT="compact";SIG_RECOVERED="recovered";SIG_DER="der";_sha="SHA-256";hashes={hmacSha256Async:async(key3,message)=>{const s2=subtle(),k2=await s2.importKey("raw",key3,{name:"HMAC",hash:{name:_sha}},!1,["sign"]);return u8n(await s2.sign("HMAC",k2,message))},hmacSha256:void 0,sha256Async:async msg=>u8n(await subtle().digest(_sha,msg)),sha256:void 0};prepMsg=(msg,opts,async_)=>{const message=abytes(msg,void 0,"message");return opts.prehash?async_?gha("sha256Async",message):gh("sha256",message):message};NULL=u8n(0);byte0=u8of(0);byte1=u8of(1);_maxDrbgIters=1e3;_drbgErr="drbg: tried max amount of iterations";hmacDrbg=(seed,pred)=>{let v2=u8n(L),k2=u8n(L),i3=0;const reset2=()=>{v2.fill(1);k2.fill(0)},h3=(...b3)=>gh("hmacSha256",k2,concatBytes(v2,...b3)),reseed=(seed2=NULL)=>{k2=h3(byte0,seed2);v2=h3();if(0!==seed2.length){k2=h3(byte1,seed2);v2=h3()}},gen=()=>{i3++>=_maxDrbgIters&&err(_drbgErr);v2=h3();return v2};reset2();reseed(seed);let res2;for(;!(res2=pred(gen()));)reseed();reset2();return res2};hmacDrbgAsync=async(seed,pred)=>{let v2=u8n(L),k2=u8n(L),i3=0;const reset2=()=>{v2.fill(1);k2.fill(0)},h3=(...b3)=>gha("hmacSha256Async",k2,concatBytes(v2,...b3)),reseed=async(seed2=NULL)=>{k2=await h3(byte0,seed2);v2=await h3();if(0!==seed2.length){k2=await h3(byte1,seed2);v2=await h3()}},gen=async()=>{i3++>=_maxDrbgIters&&err(_drbgErr);v2=await h3();return v2};reset2();await reseed(seed);let res2;for(;!(res2=pred(await gen()));)await reseed();reset2();return res2};_sign=(messageHash,secretKey2,opts,hmacDrbg2)=>{let{lowS,extraEntropy}=opts;const int2octets=numTo32b,h1i=bits2int_modN(messageHash),h1o=int2octets(h1i),d4=secretKeyToScalar(secretKey2),seedArgs=[int2octets(d4),h1o];if(null!=extraEntropy&&!1!==extraEntropy){const e3=!0===extraEntropy?randomBytes(L):extraEntropy;seedArgs.push(abytes(e3,void 0,"extraEntropy"))}const seed=concatBytes(...seedArgs),m3=h1i;return hmacDrbg2(seed,kBytes=>{const k2=bits2int(kBytes);if(!(BigInt("1")<=k2&&k2<N))return;const ik=invert(k2,N),q2=G.multiply(k2).toAffine(),r4=modN(q2.x);if(r4===BigInt("0"))return;const s2=modN(ik*modN(m3+r4*d4));if(s2===BigInt("0"))return;let recovery=(q2.x===r4?0:2)|Number(q2.y&BigInt("1")),normS=s2;if(lowS&&highS(s2)){normS=modN(-s2);recovery^=1}const sig=new Signature(r4,normS,recovery);return sig.toBytes(opts.format)})};_verify=(sig,messageHash,publicKey2,opts={})=>{const{lowS,format:format2}=opts;sig instanceof Signature&&err("Signature must be in Uint8Array, use .toBytes()");assertSigLength(sig,format2);abytes(publicKey2,void 0,"publicKey");try{const{r:r4,s:s2}=Signature.fromBytes(sig,format2),h3=bits2int_modN(messageHash),P3=Point.fromBytes(publicKey2);if(lowS&&highS(s2))return!1;const is2=invert(s2,N),u1=modN(h3*is2),u2=modN(r4*is2),R2=doubleScalarMulUns(P3,u1,u2).toAffine(),v2=modN(R2.x);return v2===r4}catch(error){return!1}};setDefaults=opts=>{var _a13,_b6,_c3,_d2;return{lowS:null==(_a13=opts.lowS)||_a13,prehash:null==(_b6=opts.prehash)||_b6,format:null!=(_c3=opts.format)?_c3:SIG_COMPACT,extraEntropy:null!=(_d2=opts.extraEntropy)&&_d2}};0;0;0;0;_recover=(signature,messageHash)=>{const sig=Signature.fromBytes(signature,"recovered"),{r:r4,s:s2,recovery}=sig;assertRecoveryBit(recovery);const h3=bits2int_modN(abytes(messageHash,void 0,"msgHash")),radj=2===recovery||3===recovery?r4+N:r4;FpIsValidNot0(radj);const head2=getPrefix(big(recovery)),Rb=concatBytes(head2,numTo32b(radj)),R2=Point.fromBytes(Rb),ir=invert(radj,N),u1=modN(-h3*ir),u2=modN(s2*ir),point=doubleScalarMulUns(R2,u1,u2);return point.toBytes()};0;0;0;randomSecretKey=seed=>{seed=void 0===seed?randomBytes(lengths.seed):seed;abytes(seed);if(seed.length<lengths.seed||seed.length>1024)return err("expected 48-1024b",RangeError);const num=M(bytesToNumBE(seed),N-BigInt("1"));return numTo32b(num+BigInt("1"))};createKeygen=getPublicKey2=>seed=>{const secretKey2=randomSecretKey(seed);return{secretKey:secretKey2,publicKey:getPublicKey2(secretKey2)}};0;0;0;getTag=tag3=>Uint8Array.from("BIP0340/"+tag3,c3=>c3.charCodeAt(0));T_AUX="aux";T_NONCE="nonce";T_CHALLENGE="challenge";taggedHash=(tag3,...messages)=>{const tagH=gh("sha256",getTag(tag3));return gh("sha256",concatBytes(tagH,tagH,...messages))};taggedHashAsync=(tag3,...messages)=>gha("sha256Async",getTag(tag3)).then(tagH=>gha("sha256Async",concatBytes(tagH,tagH,...messages)));extpubSchnorr=priv=>{const d_=secretKeyToScalar(priv),p2=G.multiply(d_),{x:x3,y:y2}=p2.assertValidity().toAffine(),d4=isEven(y2)?d_:modN(-d_),px=numTo32b(x3);return{d:d4,px}};bytesModN=bytes=>modN(bytesToNumBE(bytes));challenge=(...args)=>bytesModN(taggedHash(T_CHALLENGE,...args));challengeAsync=async(...args)=>bytesModN(await taggedHashAsync(T_CHALLENGE,...args));pubSchnorr=secretKey2=>extpubSchnorr(secretKey2).px;keygenSchnorr=createKeygen(pubSchnorr);prepSigSchnorr=(message,secretKey2,auxRand)=>{const{px,d:d4}=extpubSchnorr(secretKey2);return{m:abytes(message),px,d:d4,a:abytes(auxRand,L)}};extractK=rand=>{const k_=bytesModN(rand);k_===BigInt("0")&&err("sign failed: k is zero");const{px,d:d4}=extpubSchnorr(numTo32b(k_));return{rx:px,k:d4}};createSigSchnorr=(k2,px,e3,d4)=>concatBytes(px,numTo32b(modN(k2+e3*d4)));E_INVSIG="invalid signature produced";signSchnorr=(message,secretKey2,auxRand=randomBytes(L))=>{const{m:m3,px,d:d4,a:a2}=prepSigSchnorr(message,secretKey2,auxRand),aux=taggedHash(T_AUX,a2),t9=numTo32b(d4^bytesToNumBE(aux)),rand=taggedHash(T_NONCE,t9,px,m3),{rx,k:k2}=extractK(rand),e3=challenge(rx,px,m3),sig=createSigSchnorr(k2,rx,e3,d4);verifySchnorr(sig,m3,px)||err(E_INVSIG);return sig};signSchnorrAsync=async(message,secretKey2,auxRand=randomBytes(L))=>{const{m:m3,px,d:d4,a:a2}=prepSigSchnorr(message,secretKey2,auxRand),aux=await taggedHashAsync(T_AUX,a2),t9=numTo32b(d4^bytesToNumBE(aux)),rand=await taggedHashAsync(T_NONCE,t9,px,m3),{rx,k:k2}=extractK(rand),e3=await challengeAsync(rx,px,m3),sig=createSigSchnorr(k2,rx,e3,d4);await verifySchnorrAsync(sig,m3,px)||err(E_INVSIG);return sig};callSyncAsyncFn=(res2,later)=>res2 instanceof Promise?res2.then(later):later(res2);_verifSchnorr=(signature,message,publicKey2,challengeFn)=>{const sig=abytes(signature,L2,"signature"),msg=abytes(message,void 0,"message"),pub=abytes(publicKey2,L,"publicKey");try{const x3=bytesToNumBE(pub),y2=lift_x(x3),P_=new Point(x3,y2,BigInt("1")).assertValidity(),px=numTo32b(P_.toAffine().x),r4=sliceBytesNumBE(sig,0,L);arange(r4,BigInt("1"),P);const s2=sliceBytesNumBE(sig,L,L2);arange(s2,BigInt("1"),N);const i3=concatBytes(numTo32b(r4),px,msg);return callSyncAsyncFn(challengeFn(i3),e3=>{const{x:x4,y:y3}=doubleScalarMulUns(P_,s2,modN(-e3)).toAffine();return!(!isEven(y3)||x4!==r4)})}catch(error){return!1}};verifySchnorr=(s2,m3,p2)=>_verifSchnorr(s2,m3,p2,challenge);verifySchnorrAsync=async(s2,m3,p2)=>_verifSchnorr(s2,m3,p2,challengeAsync);schnorr=Object.freeze({keygen:keygenSchnorr,getPublicKey:pubSchnorr,sign:signSchnorr,verify:verifySchnorr,signAsync:signSchnorrAsync,verifyAsync:verifySchnorrAsync});W=8;scalarBits=256;pwindows=Math.ceil(scalarBits/W)+1;pwindowSize=2**(W-1);precompute=()=>{const points=[];let p2=G,b3=p2;for(let w2=0;w2<pwindows;w2++){b3=p2;points.push(b3);for(let i3=1;i3<pwindowSize;i3++){b3=b3.add(p2);points.push(b3)}p2=b3.double()}return points};Gpows=void 0;ctneg=(cnd,p2)=>{const n3=p2.negate();return cnd?n3:p2};wNAF=n3=>{const comp=Gpows||(Gpows=precompute());let p2=I,f4=G;const pow_2_w=2**W,maxNum=pow_2_w,mask=big(pow_2_w-1),shiftBy=big(W);for(let w2=0;w2<pwindows;w2++){let wbits2=Number(n3&mask);n3>>=shiftBy;if(wbits2>pwindowSize){wbits2-=maxNum;n3+=BigInt("1")}const off=w2*pwindowSize,offF=off,offP=off+Math.abs(wbits2)-1,isEven2=w2%2!=0,isNeg=wbits2<0;0===wbits2?f4=f4.add(ctneg(isEven2,comp[offF])):p2=p2.add(ctneg(isNeg,comp[offP]))}n3!==BigInt("0")&&err("invalid wnaf");return{p:p2,f:f4}};var{floor,min,sin}=Math;libName="Trystero";alloc=(n3,f4)=>Array(n3).fill(void 0).map(f4);charSet="0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz";genId=n3=>alloc(n3,()=>{var _a13;return null!=(_a13=charSet[floor(62*Math.random())])?_a13:""}).join("");selfId=genId(20);all=Promise.all.bind(Promise);isBrowser="undefined"!=typeof window;var{entries,fromEntries,keys,values}=Object;noOp=()=>{};candidateType="candidate";resetTimer=timer=>{null!==timer&&clearTimeout(timer);return null};mkErr=msg=>new Error(`${libName}: ${msg}`);toErrorMessage=(reason,fallback3)=>reason instanceof Error&&reason.message?reason.message:"string"==typeof reason&&reason?reason:toJson(null!=reason?reason:fallback3);toError=(reason,fallback3)=>reason instanceof Error?reason:mkErr(toErrorMessage(reason,fallback3));encoder=new TextEncoder;decoder=new TextDecoder;encodeBytes=txt=>encoder.encode(txt);decodeBytes=buffer=>decoder.decode(buffer);toHex=buffer=>buffer.reduce((a2,c3)=>a2+c3.toString(16).padStart(2,"0"),"");topicPath=(...parts)=>parts.join("@");shuffle=(xs,seed)=>{const a2=[...xs],rand=()=>{const x3=1e4*sin(seed++);return x3-floor(x3)};let i3=a2.length;for(;i3;){const j2=floor(rand()*i3--),tmp=a2[i3];a2[i3]=a2[j2];a2[j2]=tmp}return a2};getRelays=(config,defaults2,defaultN,deriveFromAppId=!1)=>{var _a13,_b6,_c3;return(null==(_a13=config.relayConfig)?void 0:_a13.urls)||(deriveFromAppId?shuffle(defaults2,strToNum(config.appId)):defaults2).slice(0,null!=(_c3=null==(_b6=config.relayConfig)?void 0:_b6.redundancy)?_c3:defaultN)};toJson=JSON.stringify;fromJson=s2=>{try{return JSON.parse(s2)}catch(e3){throw mkErr(`failed to parse JSON: ${s2}`)}};strToNum=(str,limit=Number.MAX_SAFE_INTEGER)=>str.split("").reduce((a2,c3)=>a2+c3.charCodeAt(0),0)%limit;defaultRetryMs=3333;maxRetryMs=6e4;socketRetryPeriods={};reconnectionLockingPromise=null;resolver=null;pauseRelayReconnection=()=>{reconnectionLockingPromise||(reconnectionLockingPromise=new Promise(resolve=>{resolver=resolve}).finally(()=>{resolver=null;reconnectionLockingPromise=null}))};resumeRelayReconnection=()=>{null==resolver||resolver()};makeSocket=(url,onMessage,onReconnect)=>{const client={};let didOpen=!1,isReconnectPending=!1,resolveReady=noOp;client.ready=new Promise(res2=>resolveReady=res2);const init3=()=>{isReconnectPending=!1;const socket=new WebSocket(url);socket.onclose=()=>{var _a13;if(isReconnectPending)return;isReconnectPending=!0;if(reconnectionLockingPromise){reconnectionLockingPromise.then(init3);return}const period=null!=(_a13=socketRetryPeriods[url])?_a13:socketRetryPeriods[url]=defaultRetryMs;setTimeout(init3,Math.random()*period);socketRetryPeriods[url]=min(2*period,maxRetryMs)};socket.onmessage=e3=>onMessage(String(e3.data));client.socket=socket;client.url=socket.url;socket.onopen=()=>{const isReconnect=didOpen;didOpen=!0;resolveReady(client);socketRetryPeriods[url]=defaultRetryMs;isReconnect&&(null==onReconnect||onReconnect())};client.send=data=>{1===socket.readyState&&socket.send(data)}};init3();return client};0;createRelayManager=getSocket=>{const relays={},keysByRelay=new WeakMap,keyOf=relay=>{const key3=keysByRelay.get(relay);if(!key3)throw mkErr("relay bookkeeping missing registration for relay client");return key3},store=(key3,relay)=>{relays[key3]=relay;keysByRelay.set(relay,key3);return relay};return{register:(key3,createRelay)=>{const relay=relays[key3];return relay||store(key3,createRelay())},keyOf,scoped:()=>{const store2={},forKey=key3=>{var _a13;return null!=(_a13=store2[key3])?_a13:store2[key3]={}};return{forKey,forRelay:relay=>forKey(keyOf(relay))}},getSockets:()=>fromEntries(entries(relays).flatMap(([key3,relay])=>{const socket=getSocket(relay);return socket?[[key3,socket]]:[]}))}};watchOnline=()=>{if(isBrowser){const controller=new AbortController;addEventListener("online",resumeRelayReconnection,{signal:controller.signal});addEventListener("offline",pauseRelayReconnection,{signal:controller.signal});return()=>controller.abort()}return noOp};algo="AES-GCM";strToSha1={};pack=buff=>btoa(String.fromCharCode.apply(null,Array.from(new Uint8Array(buff))));unpack=packed=>{const str=atob(packed);return new Uint8Array(str.length).map((_,i3)=>str.charCodeAt(i3)).buffer};hashWith=async(algorithm,str)=>new Uint8Array(await crypto.subtle.digest(algorithm,encodeBytes(str)));sha1=async str=>{var _a13;return null!=(_a13=strToSha1[str])?_a13:strToSha1[str]=Array.from(await hashWith("SHA-1",str)).map(b3=>b3.toString(36)).join("")};genKey=async(secret,appId,roomId)=>crypto.subtle.importKey("raw",await crypto.subtle.digest({name:"SHA-256"},encodeBytes(`${secret}:${appId}:${roomId}`)),{name:algo},!1,["encrypt","decrypt"]);deriveRoomNamespace=async(appId,roomId)=>toHex(await hashWith("SHA-256",`${libName}:${appId}:${roomId}`));joinChar="$";ivJoinChar=",";encrypt=async(keyP,plaintext)=>{const iv=crypto.getRandomValues(new Uint8Array(16));return iv.join(ivJoinChar)+joinChar+pack(await crypto.subtle.encrypt({name:algo,iv},await keyP,encodeBytes(plaintext)))};decrypt=async(keyP,raw)=>{var _a13;const[iv,c3]=raw.split(joinChar);return decodeBytes(await crypto.subtle.decrypt({name:algo,iv:new Uint8Array(null!=(_a13=null==iv?void 0:iv.split(ivJoinChar).map(Number))?_a13:[])},await keyP,unpack(null!=c3?c3:"")))};offerTtl=57333;offerLeaseTtlMs=18e4;poolSize=20;OfferPool=class{constructor(makeOffer){__publicField(this,"makeOffer");__publicField(this,"pool",[]);__publicField(this,"pooled",new Set);__publicField(this,"leased",new Map);__publicField(this,"recycling",new Set);__publicField(this,"cleanupTimer",null);__publicField(this,"active",!1);this.makeOffer=makeOffer}get isActive(){return this.active}warmup(){this.pool=[];this.pooled.clear();alloc(poolSize,this.makeOffer).forEach(p2=>this.push(p2));this.active=!0;this.cleanupTimer=setInterval(()=>{this.pool=this.pool.filter(peer=>{if(peer.isDead){this.pooled.delete(peer);return!1}return!0})},offerTtl)}push(peer){if(!(peer.isDead||this.pooled.has(peer)||this.leased.has(peer))){this.pool.push(peer);this.pooled.add(peer)}}shift(n3){const peers=[];for(;peers.length<n3&&this.pool.length>0;){const peer=this.pool.shift();if(!peer)break;this.pooled.delete(peer);peers.push(peer)}return peers}claimLeased(peer){const timer=this.leased.get(peer);if(timer){resetTimer(timer);this.leased.delete(peer)}}recycle(peer){if(!peer.isDead&&!this.recycling.has(peer))if(peer.connection.remoteDescription)peer.destroy();else if(this.active){this.recycling.add(peer);peer.setHandlers({connect:noOp,close:noOp,error:noOp});peer.getOffer(!0).then(offer=>{offer&&"offer"===offer.type&&!peer.isDead&&this.active?this.push(peer):peer.destroy()}).catch(()=>peer.destroy()).finally(()=>this.recycling.delete(peer))}else peer.destroy()}reclaimLeased(peer){const timer=this.leased.get(peer);if(timer){resetTimer(timer);this.leased.delete(peer);this.recycle(peer)}}lease(peer){this.claimLeased(peer);this.leased.set(peer,setTimeout(()=>{this.leased.delete(peer);this.recycle(peer)},offerLeaseTtlMs))}checkout(n3,leaseOffers,encryptOffer){const peers=this.shift(n3),missing=Math.max(0,n3-peers.length);missing>0&&peers.push(...alloc(missing,this.makeOffer));const toRecord=async(candidate,didRetry=!1)=>{try{const offer=await encryptOffer(candidate);if(leaseOffers){this.lease(candidate);return{peer:candidate,offer,claim:()=>this.claimLeased(candidate),reclaim:()=>this.reclaimLeased(candidate)}}return{peer:candidate,offer}}catch(err3){this.claimLeased(candidate);this.pooled.delete(candidate);candidate.destroy();if(!didRetry)return toRecord(this.makeOffer(),!0);throw err3}};return all(peers.map(peer=>toRecord(peer)))}getOffers(n3,encryptOffer){return this.checkout(n3,!0,encryptOffer)}destroy(){this.active=!1;if(this.cleanupTimer){clearInterval(this.cleanupTimer);this.cleanupTimer=null}this.pool.forEach(peer=>peer.destroy());this.pool=[];this.pooled.clear();this.leased.forEach((timeout,peer)=>{resetTimer(timeout);peer.destroy()});this.leased.clear();this.recycling.forEach(peer=>peer.destroy());this.recycling.clear()}};overlapRoomPasswordErr=mkErr("incorrect password for overlapping room");createPasswordHandshake=(password,appId,roomId)=>{const hashChallenge=challenge2=>hashWith("SHA-256",`${challenge2}:${password}:${appId}:${roomId}`).then(toHex),run4=async(send,receive,isInitiator)=>{if(!password)return;if(isInitiator){const challenge2=genId(36);await send({__trystero_pw:"challenge",c:challenge2});const{data:data2}=await receive();if(!data2||"object"!=typeof data2||"response"!==data2.__trystero_pw||"string"!=typeof data2.h)throw overlapRoomPasswordErr;const expected=await hashChallenge(challenge2);if(data2.h!==expected)throw overlapRoomPasswordErr;return}const{data}=await receive();if(!data||"object"!=typeof data||"challenge"!==data.__trystero_pw||"string"!=typeof data.c)throw overlapRoomPasswordErr;await send({__trystero_pw:"response",h:await hashChallenge(data.c)})};return{run:run4,compose:userHandshake=>password||userHandshake?async(peerId,send,receive,isInitiator)=>{await run4(send,receive,isInitiator);await(null==userHandshake?void 0:userHandshake(peerId,send,receive,isInitiator))}:void 0}};toHandshakeErrorMessage=error=>{const message=toErrorMessage(error,"unknown error");return message.startsWith("handshake ")?message:`handshake failed: ${message}`};createHandshakeManager=({onPeerHandshake,onHandshakeError,handshakeTimeoutMs,sendHandshakeData,sendHandshakeReady,onActivate,onFailure})=>{const peerStates={},maybeActivatePeer=(id,peer)=>{const state2=peerStates[id];if(!(!state2||peer&&state2.peer!==peer||state2.isActive)&&state2.didLocalHandshakePass&&state2.didReceiveRemoteReady){state2.isActive=!0;state2.handshakeTimer=resetTimer(state2.handshakeTimer);onActivate(id,state2.peer)}},failPeerHandshake=(id,peer,reason)=>{const state2=peerStates[id];if(!state2||state2.peer!==peer)return;const error=toHandshakeErrorMessage(reason);null==onHandshakeError||onHandshakeError(id,error);onFailure(id,peer,mkErr(error))},markLocalHandshakePassed=(id,peer)=>{const state2=peerStates[id];if(state2&&state2.peer===peer&&!state2.isActive){state2.didLocalHandshakePass=!0;sendHandshakeReady("",id).catch(err3=>failPeerHandshake(id,peer,mkErr(`failed sending handshake readiness: ${toErrorMessage(err3,"unknown send failure")}`)));maybeActivatePeer(id,peer)}};return{addPeer:(id,peer)=>{peerStates[id]={peer,isActive:!1,didLocalHandshakePass:!1,didReceiveRemoteReady:!1,handshakeTimer:null,pendingHandshakePayloads:[],handshakeWaiters:[]}},clearPeer:(id,error)=>{const state2=peerStates[id];if(state2){state2.handshakeTimer=resetTimer(state2.handshakeTimer);state2.pendingHandshakePayloads.length=0;state2.handshakeWaiters.splice(0).forEach(waiter=>waiter.reject(error));delete peerStates[id]}},canReceiveFromPeer:(id,receiveWhilePending)=>{const state2=peerStates[id];return Boolean(state2&&(state2.isActive||receiveWhilePending))},start:(id,peer)=>{const state2=peerStates[id];if(!state2||state2.peer!==peer)return;state2.handshakeTimer=setTimeout(()=>failPeerHandshake(id,peer,mkErr(`handshake timed out after ${handshakeTimeoutMs}ms`)),handshakeTimeoutMs);const isInitiator=selfId<id;Promise.resolve(null==onPeerHandshake?void 0:onPeerHandshake(id,async(data,metadata)=>{await sendHandshakeData(data,id,metadata)},()=>new Promise((resolve,reject)=>{const current=peerStates[id];if(!current||current.peer!==peer){reject(mkErr("peer disconnected during handshake"));return}const payload=current.pendingHandshakePayloads.shift();payload?resolve(payload):current.handshakeWaiters.push({resolve,reject:error=>reject(error)})}),isInitiator)).then(()=>markLocalHandshakePassed(id,peer)).catch(err3=>failPeerHandshake(id,peer,toError(err3,"handshake failed")))},receiveHandshakeData:(data,id,metadata)=>{const state2=peerStates[id];if(!state2||state2.isActive)return;const payload=void 0===metadata?{data}:{data,metadata},pending3=state2.handshakeWaiters.shift();pending3?pending3.resolve(payload):state2.pendingHandshakePayloads.push(payload)},receiveHandshakeReady:id=>{const state2=peerStates[id];if(state2&&!state2.isActive){state2.didReceiveRemoteReady=!0;maybeActivatePeer(id)}}}};iceTimeout=15e3;disconnectedCloseDelayMs=5e3;iceStateEvent="icegatheringstatechange";iceConnectionStateEvent="iceconnectionstatechange";offerType="offer";answerType="answer";outOfRangePattern=/out of range/i;rewriteMdnsCandidatesToLoopback=sdp=>sdp.replace(/ (\S+\.local) (\d+) typ host/g," 127.0.0.1 $2 typ host");peer_default=(initiator,{trickleIce,rtcConfig,rtcPolyfill,turnConfig,_test_only_mdnsHostFallbackToLoopback})=>{const pc=new(null!=rtcPolyfill?rtcPolyfill:RTCPeerConnection)({iceServers:defaultIceServers.concat(null!=turnConfig?turnConfig:[]),...rtcConfig}),handlers3={},pendingSignals=[],pendingData=[],shouldTrickleIce=!1!==trickleIce,pendingRemoteCandidates=[],pendingTracks=[];let makingOffer=!1,isSettingRemoteAnswerPending=!1,dataChannel=null,disconnectedCloseTimer=null,didEmitClose=!1;const clearDisconnectedCloseTimer=()=>disconnectedCloseTimer=resetTimer(disconnectedCloseTimer),emitClose=()=>{var _a13;if(!didEmitClose){didEmitClose=!0;clearDisconnectedCloseTimer();null==(_a13=handlers3.close)||_a13.call(handlers3)}},emitSignal=signal=>{handlers3.signal?handlers3.signal(signal):pendingSignals.push(signal)},appendSignalHandler=handler=>{const previousSignalHandler=handlers3.signal;handlers3.signal=signal=>{null==previousSignalHandler||previousSignalHandler(signal);handler(signal)};pendingSignals.length>0&&pendingSignals.splice(0).forEach(signal=>{var _a13;return null==(_a13=handlers3.signal)?void 0:_a13.call(handlers3,signal)})},normalizeSdp=sdp=>_test_only_mdnsHostFallbackToLoopback?rewriteMdnsCandidatesToLoopback(sdp):sdp,normalizeCandidate=candidate=>{if(!_test_only_mdnsHostFallbackToLoopback||"string"!=typeof candidate.candidate)return candidate;const normalizedCandidate=rewriteMdnsCandidatesToLoopback(candidate.candidate);return normalizedCandidate===candidate.candidate?candidate:{...candidate,candidate:normalizedCandidate}},localDescriptionSignal=peerConnection=>{var _a13,_b6,_c3,_d2;return{type:null!=(_b6=null==(_a13=peerConnection.localDescription)?void 0:_a13.type)?_b6:offerType,sdp:normalizeSdp(null!=(_d2=null==(_c3=peerConnection.localDescription)?void 0:_c3.sdp)?_d2:"")}},getRemoteUfrag=()=>{var _a13,_b6,_c3;const sdp=null==(_a13=pc.remoteDescription)?void 0:_a13.sdp;return sdp&&null!=(_c3=null==(_b6=sdp.match(/a=ice-ufrag:([^\s]+)/))?void 0:_b6[1])?_c3:null},getRemoteMediaSectionCount=()=>{var _a13,_b6,_c3;return(null!=(_c3=null==(_b6=null==(_a13=pc.remoteDescription)?void 0:_a13.sdp)?void 0:_b6.match(/^m=/gm))?_c3:[]).length},canApplyRemoteCandidate=candidate=>{if(!pc.remoteDescription)return!1;const remoteMLineCount=getRemoteMediaSectionCount();if("number"==typeof candidate.sdpMLineIndex&&remoteMLineCount>0&&candidate.sdpMLineIndex>=remoteMLineCount)return!1;const remoteUfrag=getRemoteUfrag();return!remoteUfrag||!candidate.usernameFragment||candidate.usernameFragment===remoteUfrag},addIceCandidateSafe=async candidate=>{try{await pc.addIceCandidate(candidate);return!0}catch(err3){if(err3 instanceof Error&&outOfRangePattern.test(err3.message)&&"number"==typeof candidate.sdpMLineIndex)return!1;throw err3}},flushPendingRemoteCandidates=async()=>{if(!pc.remoteDescription||0===pendingRemoteCandidates.length)return;const queuedCandidates=pendingRemoteCandidates.splice(0),stillPending=[];for(const candidate of queuedCandidates)canApplyRemoteCandidate(candidate)&&await addIceCandidateSafe(candidate)||stillPending.push(candidate);stillPending.length>0&&pendingRemoteCandidates.push(...stillPending)},addRemoteCandidate=async candidate=>{canApplyRemoteCandidate(candidate)&&await addIceCandidateSafe(candidate)||pendingRemoteCandidates.push(candidate)},setupDataChannel=channel=>{channel.binaryType="arraybuffer";channel.bufferedAmountLowThreshold=65535;channel.onmessage=e3=>{const data=e3.data;handlers3.data?handlers3.data(data):pendingData.push(data)};channel.onopen=()=>{var _a13;return null==(_a13=handlers3.connect)?void 0:_a13.call(handlers3)};channel.onclose=emitClose;channel.onerror=({error})=>{var _a13;return null==(_a13=handlers3.error)?void 0:_a13.call(handlers3,toError(error,"data channel error"))}},waitForIceGathering=async peerConnection=>{let timeout=null;try{await Promise.race([new Promise(res2=>{const checkState5=()=>{if("complete"===peerConnection.iceGatheringState){peerConnection.removeEventListener(iceStateEvent,checkState5);res2()}};peerConnection.addEventListener(iceStateEvent,checkState5);checkState5()}),new Promise(res2=>{timeout=setTimeout(res2,iceTimeout)})])}finally{resetTimer(timeout)}return localDescriptionSignal(peerConnection)},emitLocalDescriptionSignal=async()=>{const signal=shouldTrickleIce?localDescriptionSignal(pc):await waitForIceGathering(pc);emitSignal(signal);return signal};if(initiator){dataChannel=pc.createDataChannel("data");setupDataChannel(dataChannel)}else pc.ondatachannel=({channel})=>{dataChannel=channel;setupDataChannel(channel)};const createOffer=async(restartIce=!1)=>{var _a13,_b6;if("closed"!==pc.connectionState)try{makingOffer=!0;if(restartIce){"stable"!==pc.signalingState&&"closed"!==pc.signalingState&&(null==(_a13=pc.localDescription)?void 0:_a13.type)===offerType&&await pc.setLocalDescription({type:"rollback"});"function"==typeof pc.restartIce&&pc.restartIce()}await pc.setLocalDescription(restartIce?await pc.createOffer({iceRestart:!0}):void 0);return await emitLocalDescriptionSignal()}catch(err3){null==(_b6=handlers3.error)||_b6.call(handlers3,toError(err3,"failed to create local offer"))}finally{makingOffer=!1}};pc.onnegotiationneeded=async()=>createOffer(!1);pc.onicecandidate=({candidate})=>{if(!shouldTrickleIce||!candidate)return;const candidatePayload=normalizeCandidate("function"==typeof candidate.toJSON?candidate.toJSON():{candidate:candidate.candidate,sdpMid:candidate.sdpMid,sdpMLineIndex:candidate.sdpMLineIndex,usernameFragment:candidate.usernameFragment});emitSignal({type:candidateType,sdp:JSON.stringify(candidatePayload)})};const handleConnectionStateChange=()=>{"failed"!==pc.connectionState&&"closed"!==pc.connectionState&&"failed"!==pc.iceConnectionState&&"closed"!==pc.iceConnectionState?"connected"!==pc.connectionState&&"connecting"!==pc.connectionState&&"connected"!==pc.iceConnectionState&&"completed"!==pc.iceConnectionState&&"checking"!==pc.iceConnectionState?"disconnected"!==pc.connectionState&&"disconnected"!==pc.iceConnectionState||disconnectedCloseTimer||(disconnectedCloseTimer=setTimeout(()=>{disconnectedCloseTimer=null;"disconnected"!==pc.connectionState&&"disconnected"!==pc.iceConnectionState||emitClose()},disconnectedCloseDelayMs)):clearDisconnectedCloseTimer():emitClose()};pc.onconnectionstatechange=handleConnectionStateChange;pc.addEventListener(iceConnectionStateEvent,handleConnectionStateChange);pc.ontrack=e3=>{var _a13,_b6;const stream=e3.streams[0];if(stream){if(!handlers3.track&&!handlers3.stream){pendingTracks.push({track:e3.track,stream});return}null==(_a13=handlers3.track)||_a13.call(handlers3,e3.track,stream);null==(_b6=handlers3.stream)||_b6.call(handlers3,stream)}};pc.onremovestream=e3=>{var _a13;return null==(_a13=handlers3.stream)?void 0:_a13.call(handlers3,e3.stream)};const offerPromise=initiator?new Promise(res2=>appendSignalHandler(signal=>{signal.type===offerType&&res2(signal)})):Promise.resolve();initiator&&queueMicrotask(()=>{var _a13;makingOffer||"stable"!==pc.signalingState||pc.localDescription||"closed"===pc.connectionState||null==(_a13=pc.onnegotiationneeded)||_a13.call(pc,new Event("negotiationneeded"))});return{created:Date.now(),connection:pc,get channel(){return dataChannel},get isDead(){return"closed"===pc.connectionState},getOffer:async(restartIce=!1)=>{var _a13;if(initiator)return restartIce?createOffer(!0):(null==(_a13=pc.localDescription)?void 0:_a13.type)===offerType?shouldTrickleIce?localDescriptionSignal(pc):waitForIceGathering(pc):offerPromise},async signal(sdp){var _a13,_b6,_c3;if("candidate"!==sdp.type){if("open"!==(null==dataChannel?void 0:dataChannel.readyState)||(null==(_b6=sdp.sdp)?void 0:_b6.includes("a=rtpmap")))try{const rtcSdp={...sdp,sdp:normalizeSdp(sdp.sdp)};if(sdp.type===offerType){if(makingOffer||"stable"!==pc.signalingState&&!isSettingRemoteAnswerPending){if(initiator)return;await all([pc.setLocalDescription({type:"rollback"}),pc.setRemoteDescription(rtcSdp)])}else await pc.setRemoteDescription(rtcSdp);await flushPendingRemoteCandidates();await pc.setLocalDescription();return await emitLocalDescriptionSignal()}if(sdp.type===answerType){isSettingRemoteAnswerPending=!0;try{await pc.setRemoteDescription(rtcSdp);await flushPendingRemoteCandidates()}finally{isSettingRemoteAnswerPending=!1}}}catch(err3){null==(_c3=handlers3.error)||_c3.call(handlers3,toError(err3,"failed to apply remote signal"))}}else try{const candidate=JSON.parse(sdp.sdp);candidate&&"object"==typeof candidate&&await addRemoteCandidate(normalizeCandidate(candidate))}catch(err3){null==(_a13=handlers3.error)||_a13.call(handlers3,toError(err3,"failed to parse remote candidate"))}},sendData:data=>null==dataChannel?void 0:dataChannel.send(data),destroy:()=>{clearDisconnectedCloseTimer();null==dataChannel||dataChannel.close();pc.close();makingOffer=!1;isSettingRemoteAnswerPending=!1;emitClose()},setHandlers:newHandlers=>{const{signal,...restHandlers}=newHandlers;Object.assign(handlers3,restHandlers);handlers3.data&&pendingData.length>0&&pendingData.splice(0).forEach(data=>{var _a13;return null==(_a13=handlers3.data)?void 0:_a13.call(handlers3,data)});signal&&appendSignalHandler(signal);(handlers3.track||handlers3.stream)&&pendingTracks.length>0&&pendingTracks.splice(0).forEach(({track,stream})=>{var _a13,_b6;null==(_a13=handlers3.track)||_a13.call(handlers3,track,stream);null==(_b6=handlers3.stream)||_b6.call(handlers3,stream)})},offerPromise,addStream:stream=>stream.getTracks().forEach(track=>pc.addTrack(track,stream)),removeStream:stream=>pc.getSenders().filter(sender=>sender.track&&stream.getTracks().includes(sender.track)).forEach(sender=>pc.removeTrack(sender)),addTrack:(track,stream)=>pc.addTrack(track,stream),removeTrack:track=>{const sender=pc.getSenders().find(s2=>s2.track===track);sender&&pc.removeTrack(sender)},replaceTrack:(oldTrack,newTrack)=>{const sender=pc.getSenders().find(s2=>s2.track===oldTrack);if(sender)return sender.replaceTrack(newTrack)}}};defaultIceServers=[...alloc(3,(_,i3)=>`stun:stun${i3||""}.l.google.com:19302`),"stun:stun.cloudflare.com:3478"].map(url=>({urls:url}));TypedArray=Object.getPrototypeOf(Uint8Array);typeByteLimit=32;typeIndex=0;nonceIndex=32;tagIndex=34;progressIndex=35;payloadIndex=36;chunkSize=16384-payloadIndex;oneByteMax=255;twoByteMax=65535;buffLowEvent="bufferedamountlow";channelCloseEvent="close";channelErrorEvent="error";backpressureWaitTimeoutMs=1e4;toByteArray=value=>value instanceof ArrayBuffer?new Uint8Array(value):new Uint8Array(value.buffer,value.byteOffset,value.byteLength);waitForBufferedAmountLow=(channel,timeoutMs=backpressureWaitTimeoutMs)=>"open"!==channel.readyState||channel.bufferedAmount<=channel.bufferedAmountLowThreshold?Promise.resolve("open"===channel.readyState):new Promise(res2=>{let settled2=!1,timeout=null;const finish=didDrain=>{if(!settled2){settled2=!0;channel.removeEventListener(buffLowEvent,onBufferLow);channel.removeEventListener(channelCloseEvent,onCloseOrError);channel.removeEventListener(channelErrorEvent,onCloseOrError);resetTimer(timeout);res2(didDrain)}},onBufferLow=()=>finish(!0),onCloseOrError=()=>finish(!1);channel.addEventListener(buffLowEvent,onBufferLow);channel.addEventListener(channelCloseEvent,onCloseOrError);channel.addEventListener(channelErrorEvent,onCloseOrError);timeout=setTimeout(()=>finish(!1),timeoutMs);"open"===channel.readyState?channel.bufferedAmount<=channel.bufferedAmountLowThreshold&&finish(!0):finish(!1)});createActionWireManager=({getPeer,getPeerIds,canReceiveFromPeer,throwIfAborted:throwIfAborted2})=>{const actions={},actionsCache={},pendingTransmissions={},pendingActionPayloads={},iterate2=(targets,f4,{includePending=!1}={})=>(targets?Array.isArray(targets)?targets:[targets]:getPeerIds(includePending)).flatMap(id=>{const peer=getPeer(id,includePending);if(!peer){console.warn(`${libName}: no peer with id ${id} found`);return[]}return[Promise.resolve(f4(id,peer))]});return{makeInternalAction:(type,options={})=>{const cached=actionsCache[type];if(actions[type]&&cached){const cachedOptions=actions[type].options;if(cachedOptions.sendToPending!==Boolean(options.sendToPending)||cachedOptions.receiveWhilePending!==Boolean(options.receiveWhilePending))throw mkErr(`action type "${type}" cannot be redefined`);return cached}if(!type)throw mkErr("action type argument is required");const typeBytes=encodeBytes(type);if(typeBytes.byteLength>typeByteLimit)throw mkErr(`action type string "${type}" (${typeBytes.byteLength}b) exceeds byte limit (${typeByteLimit}). Hint: choose a shorter name.`);const normalizedOptions={sendToPending:Boolean(options.sendToPending),receiveWhilePending:Boolean(options.receiveWhilePending)},typeBytesPadded=new Uint8Array(typeByteLimit);typeBytesPadded.set(typeBytes);let nonce=0;actions[type]={onComplete:noOp,onProgress:noOp,setOnComplete:f4=>{actions[type].onComplete=f4;const pending3=pendingActionPayloads[type];if(null==pending3?void 0:pending3.length){delete pendingActionPayloads[type];pending3.forEach(({payload,peerId,metadata})=>f4(payload,peerId,metadata))}},setOnProgress:f4=>{actions[type].onProgress=f4},send:async(data,targets,meta,onProgress,signal)=>{throwIfAborted2(signal);const dataType=typeof data;if("undefined"===dataType)throw mkErr("action data cannot be undefined");const isJson="string"!==dataType,isBlob3=data instanceof Blob,isBinary=isBlob3||data instanceof ArrayBuffer||data instanceof TypedArray,hasMeta=void 0!==meta,buffer=isBinary?toByteArray(isBlob3?await data.arrayBuffer():data):encodeBytes(isJson?toJson(data):data),metaEncoded=hasMeta?encodeBytes(toJson(meta)):null,chunkTotal=Math.ceil(buffer.byteLength/chunkSize)+(hasMeta?1:0)||1,chunks=alloc(chunkTotal,(_,i3)=>{var _a13;const isLast=i3===chunkTotal-1,isMeta=Boolean(hasMeta&&0===i3),chunk=new Uint8Array(payloadIndex+(isMeta?null!=(_a13=null==metaEncoded?void 0:metaEncoded.byteLength)?_a13:0:isLast?buffer.byteLength-chunkSize*(chunkTotal-(hasMeta?2:1)):chunkSize));chunk.set(typeBytesPadded);chunk.set([nonce>>8,nonce&oneByteMax],nonceIndex);chunk.set([Number(isLast)|Number(isMeta)<<1|Number(isBinary)<<2|Number(isJson)<<3],tagIndex);chunk.set([Math.round((i3+1)/chunkTotal*oneByteMax)],progressIndex);chunk.set(hasMeta?isMeta?null!=metaEncoded?metaEncoded:new Uint8Array:buffer.subarray((i3-1)*chunkSize,i3*chunkSize):buffer.subarray(i3*chunkSize,(i3+1)*chunkSize),payloadIndex);return chunk});nonce=nonce+1&twoByteMax;await all(iterate2(targets,async(id,peer)=>{var _a13;const{channel}=peer;let chunkN=0;for(;chunkN<chunkTotal;){throwIfAborted2(signal);const chunk=chunks[chunkN];if(!chunk)break;if(channel&&channel.bufferedAmount>channel.bufferedAmountLowThreshold){const didDrain=await waitForBufferedAmountLow(channel);throwIfAborted2(signal);if(!didDrain)break}const currentPeer=getPeer(id,normalizedOptions.sendToPending);if(!currentPeer||currentPeer!==peer)break;peer.sendData(chunk);chunkN++;const progressByte=null!=(_a13=chunk[progressIndex])?_a13:oneByteMax;null==onProgress||onProgress(progressByte/oneByteMax,id,meta)}},{includePending:normalizedOptions.sendToPending}));return[]},options:normalizedOptions};return actionsCache[type]={send:actions[type].send,onMessage:actions[type].setOnComplete,onProgress:actions[type].setOnProgress}},handleData:(id,data)=>{var _a13,_b6,_c3,_d2,_f,_h2,_i2,_j;const buffer=new Uint8Array(data),type=decodeBytes(buffer.subarray(typeIndex,nonceIndex)).replaceAll("\0",""),action2=actions[type];if(!canReceiveFromPeer(id,Boolean(null==action2?void 0:action2.options.receiveWhilePending)))return;const nonce=(null!=(_a13=buffer[nonceIndex])?_a13:0)<<8|(null!=(_b6=buffer[33])?_b6:0),tag3=null!=(_c3=buffer[tagIndex])?_c3:0,progress=null!=(_d2=buffer[progressIndex])?_d2:0,payload=buffer.subarray(payloadIndex),isLast=Boolean(1&tag3),isMeta=Boolean(2&tag3),isBinary=Boolean(4&tag3),isJson=Boolean(8&tag3);null!=pendingTransmissions[id]||(pendingTransmissions[id]={});null!=(_f=pendingTransmissions[id])[type]||(_f[type]={});const target=null!=(_i2=(_h2=pendingTransmissions[id][type])[nonce])?_i2:_h2[nonce]={chunks:[]};isMeta?target.meta=fromJson(decodeBytes(payload)):target.chunks.push(payload);null==action2||action2.onProgress(progress/oneByteMax,id,target.meta);if(!isLast)return;const full=new Uint8Array(target.chunks.reduce((a2,c3)=>a2+c3.byteLength,0));target.chunks.reduce((a2,c3)=>{full.set(c3,a2);return a2+c3.byteLength},0);delete pendingTransmissions[id][type][nonce];const payloadValue=isBinary?full:isJson?fromJson(decodeBytes(full)):decodeBytes(full);action2?action2.onComplete(payloadValue,id,target.meta):(null!=(_j=pendingActionPayloads[type])?_j:pendingActionPayloads[type]=[]).push({payload:payloadValue,peerId:id,...void 0===target.meta?{}:{metadata:target.meta}})},clearPeer:id=>{delete pendingTransmissions[id]}}};requestHandlerBufferMs=500;makeActionError=(kind,message)=>{const error=mkErr(message);error.kind=kind;error.name="aborted"===kind?"AbortError":error.name;return error};throwIfAborted=signal=>{if(null==signal?void 0:signal.aborted)throw makeActionError("aborted","operation aborted")};getRequestMetadata=metadata=>metadata&&"object"==typeof metadata&&!Array.isArray(metadata)&&"string"==typeof metadata.r?{r:metadata.r,...Object.hasOwn(metadata,"m")?{m:metadata.m}:{}}:null;getResponseMetadata=metadata=>metadata&&"object"==typeof metadata&&!Array.isArray(metadata)&&"string"==typeof metadata.r?{r:metadata.r,..."string"==typeof metadata.e?{e:metadata.e}:{}}:null;withMetadata=(context2,metadata)=>void 0===metadata?context2:{...context2,metadata};createActionManager=({getPeer,getPeerIds,canReceiveFromPeer})=>{const publicActions={},pendingRequestWaiters={},wire=createActionWireManager({getPeer,getPeerIds,canReceiveFromPeer,throwIfAborted}),makeInternalAction=wire.makeInternalAction,handleData=wire.handleData,clearPendingRequestWaiter=requestId=>{const waiter=pendingRequestWaiters[requestId];if(waiter){resetTimer(waiter.timer);waiter.signal&&waiter.abortHandler&&waiter.signal.removeEventListener("abort",waiter.abortHandler);delete pendingRequestWaiters[requestId]}},rejectPendingRequestsForPeer=(id,error)=>{entries(pendingRequestWaiters).forEach(([requestId,waiter])=>{if(waiter.peerId===id){clearPendingRequestWaiter(requestId);waiter.reject(error)}})},responseAction=makeInternalAction("@_response");responseAction.onMessage((payload,id,metadata)=>{const parsed=getResponseMetadata(metadata);if(!parsed)return;const waiter=pendingRequestWaiters[parsed.r];if(waiter&&waiter.peerId===id){clearPendingRequestWaiter(parsed.r);void 0===parsed.e?waiter.resolve(payload):waiter.reject(makeActionError("rejected",parsed.e))}});return{makeAction:(type,config)=>{var _a13,_b6,_c3,_d2;if(config&&"onRequest"in config&&"request"!==config.kind)throw mkErr('request actions must use kind: "request"');const kind=null!=(_a13=null==config?void 0:config.kind)?_a13:"message",rawAction=makeInternalAction(type),existingState=publicActions[type];if(existingState){if(existingState.kind!==kind)throw mkErr(`action type "${type}" cannot be redefined`);return existingState.action}const state2={kind,action:null,pendingMessages:[],pendingRequests:[],onReceiveProgress:null!=(_b6=null==config?void 0:config.onReceiveProgress)?_b6:null},toProgressHandler=(handler,metadata)=>handler?(progress,peerId)=>handler(progress,withMetadata({peerId},metadata)):void 0,setReceiveProgress=handler=>{state2.onReceiveProgress=handler};rawAction.onProgress((progress,peerId,metadata)=>{var _a14;const requestMetadata="request"===state2.kind?getRequestMetadata(metadata):null;null==(_a14=state2.onReceiveProgress)||_a14.call(state2,progress,withMetadata({peerId},requestMetadata?requestMetadata.m:metadata))});if("message"===kind){let onMessage=null!=(_c3=null==config?void 0:config.onMessage)?_c3:null;const flushMessages=()=>{if(!onMessage)return;const handler=onMessage;state2.pendingMessages.splice(0).forEach(({payload,peerId,metadata})=>{Promise.resolve().then(()=>handler(payload,withMetadata({peerId},metadata))).catch(err3=>console.error(`${libName} action handler error:`,err3))})},action3={send:async(data,options={})=>{await rawAction.send(data,options.target,options.metadata,toProgressHandler(options.onProgress,options.metadata),options.signal)},get onMessage(){return onMessage},set onMessage(handler){onMessage=handler;flushMessages()},get onReceiveProgress(){return state2.onReceiveProgress},set onReceiveProgress(handler){setReceiveProgress(handler)}};rawAction.onMessage((payload,peerId,metadata)=>{if(!onMessage){state2.pendingMessages.push(void 0===metadata?{payload,peerId}:{payload,peerId,metadata});return}const handler=onMessage;Promise.resolve().then(()=>handler(payload,withMetadata({peerId},metadata))).catch(err3=>console.error(`${libName} action handler error:`,err3))});state2.action=action3;publicActions[type]=state2;flushMessages();return action3}let onRequest=null!=(_d2=null==config?void 0:config.onRequest)?_d2:null;const removePendingIncomingRequest=request2=>{resetTimer(request2.timer);const i3=state2.pendingRequests.indexOf(request2);i3>-1&&state2.pendingRequests.splice(i3,1)},sendRequestError=(peerId,requestId,error)=>{responseAction.send(null,peerId,{r:requestId,e:toErrorMessage(error,"request failed")})},respondToIncomingRequest=(request2,handler)=>{removePendingIncomingRequest(request2);Promise.resolve().then(()=>handler(request2.payload,{peerId:request2.peerId,...void 0===request2.metadata?{}:{metadata:request2.metadata},signal:request2.controller.signal})).then(async response=>{if(void 0===response)throw mkErr("request handler returned undefined");await responseAction.send(response,request2.peerId,{r:request2.requestId})}).catch(err3=>sendRequestError(request2.peerId,request2.requestId,err3)).finally(()=>request2.controller.abort())},flushRequests=()=>{onRequest&&state2.pendingRequests.slice().forEach(request2=>respondToIncomingRequest(request2,onRequest))},queueIncomingRequest=(payload,peerId,metadata,requestId)=>{if(onRequest){respondToIncomingRequest({payload,peerId,...void 0===metadata?{}:{metadata},requestId,controller:new AbortController,timer:null},onRequest);return}const request2={payload,peerId,...void 0===metadata?{}:{metadata},requestId,controller:new AbortController,timer:setTimeout(()=>{removePendingIncomingRequest(request2);request2.controller.abort();sendRequestError(peerId,requestId,"request handler unavailable")},requestHandlerBufferMs)};state2.pendingRequests.push(request2)},requestOne=async(data,options)=>{const{target,metadata,onProgress,signal,timeoutMs}=options;throwIfAborted(signal);if(!getPeer(target,!1))throw makeActionError("disconnected",`no active peer with id ${target}`);const requestId=genId(20),handledResponsePromise=new Promise((resolve,reject)=>{const waiter={peerId:target,resolve,reject,timer:null,...void 0===signal?{}:{signal}},rejectAsAborted=()=>{clearPendingRequestWaiter(requestId);reject(makeActionError("aborted","operation aborted"))};if(signal){waiter.abortHandler=rejectAsAborted;signal.addEventListener("abort",rejectAsAborted,{once:!0})}pendingRequestWaiters[requestId]=waiter}).catch(err3=>{throw err3});try{await rawAction.send(data,target,void 0===metadata?{r:requestId}:{r:requestId,m:metadata},toProgressHandler(onProgress,metadata),signal);const waiter=pendingRequestWaiters[requestId];waiter&&void 0!==timeoutMs&&(waiter.timer=setTimeout(()=>{clearPendingRequestWaiter(requestId);waiter.reject(makeActionError("timeout","request timed out"))},timeoutMs));return await handledResponsePromise}catch(err3){clearPendingRequestWaiter(requestId);throw err3}},action2={request:requestOne,requestMany:async(data,options)=>{throwIfAborted(options.signal);return await all(options.targets.map(async target=>{var _a14,_b7;try{const result={peerId:target,status:"fulfilled",value:await requestOne(data,{target,...void 0===options.metadata?{}:{metadata:options.metadata},...void 0===options.timeoutMs?{}:{timeoutMs:options.timeoutMs},...void 0===options.onProgress?{}:{onProgress:options.onProgress},...void 0===options.signal?{}:{signal:options.signal}})};null==(_a14=options.onResult)||_a14.call(options,result);return result}catch(err3){const error=toError(err3,"request failed");if("aborted"===error.kind||!error.kind)throw error;const result="timeout"===error.kind?{peerId:target,status:"timeout"}:"disconnected"===error.kind?{peerId:target,status:"disconnected"}:{peerId:target,status:"rejected",error};null==(_b7=options.onResult)||_b7.call(options,result);return result}}))},get onRequest(){return onRequest},set onRequest(handler){onRequest=handler;flushRequests()},get onReceiveProgress(){return state2.onReceiveProgress},set onReceiveProgress(handler){setReceiveProgress(handler)}};rawAction.onMessage((payload,peerId,metadata)=>{const requestMetadata=getRequestMetadata(metadata);requestMetadata&&queueIncomingRequest(payload,peerId,requestMetadata.m,requestMetadata.r)});state2.action=action2;publicActions[type]=state2;flushRequests();return action2},makeInternalAction,handleData,clearPeer:(id,error)=>{wire.clearPeer(id);rejectPendingRequestsForPeer(id,makeActionError("disconnected",toErrorMessage(error,"peer disconnected")))}}};toPendingMediaMeta=value=>value&&"object"==typeof value&&!Array.isArray(value)&&"string"==typeof value.k?{key:value.k,..."string"==typeof value.s?{streamId:value.s}:{},..."string"==typeof value.t?{trackId:value.t}:{},...Object.hasOwn(value,"m")?{metadata:value.m}:{}}:null;makeKeyGetter=map4=>item=>{let key3=map4.get(item);if(!key3){key3=genId(20);map4.set(item,key3)}return key3};createMediaIdentityCache=()=>{const localStreamKeys=new WeakMap,localTrackKeys=new WeakMap,remoteStreamsByKey=new Map,remoteStreamsById=new Map,remoteTracksByKey=new Map,remoteTracksById=new Map;return{getStreamKey:makeKeyGetter(localStreamKeys),getTrackKey:makeKeyGetter(localTrackKeys),rememberRemoteStream:(key3,stream,streamId)=>{remoteStreamsByKey.set(key3,stream);streamId&&remoteStreamsById.set(streamId,stream)},getRemoteStream:(key3,streamId)=>{var _a13;return null!=(_a13=remoteStreamsByKey.get(key3))?_a13:streamId?remoteStreamsById.get(streamId):void 0},rememberRemoteTrack:(key3,track,stream,trackId,streamId)=>{const ref={track,stream};remoteTracksByKey.set(key3,ref);trackId&&remoteTracksById.set(trackId,ref);streamId&&remoteStreamsById.set(streamId,stream)},getRemoteTrack:(key3,trackId)=>{var _a13;return null!=(_a13=remoteTracksByKey.get(key3))?_a13:trackId?remoteTracksById.get(trackId):void 0},clearRemote:()=>{remoteStreamsByKey.clear();remoteStreamsById.clear();remoteTracksByKey.clear();remoteTracksById.clear()}}};createMediaManager=({iterate:iterate2,isActive,getSharedMediaPeer})=>{const pendingStreamMetas={},pendingTrackMetas={},localMedia=createMediaIdentityCache(),listeners2={onPeerStream:null,onPeerTrack:null},emitStream=(id,key3,stream,metadata)=>{var _a13,_b6,_c3;if(isActive(id)){null==(_b6=null==(_a13=getSharedMediaPeer(id))?void 0:_a13.__trysteroMedia)||_b6.rememberRemoteStream(key3,stream,"string"==typeof stream.id?stream.id:void 0);null==(_c3=listeners2.onPeerStream)||_c3.call(listeners2,stream,id,metadata)}},emitTrack=(id,key3,track,stream,metadata)=>{var _a13,_b6,_c3;if(isActive(id)){null==(_b6=null==(_a13=getSharedMediaPeer(id))?void 0:_a13.__trysteroMedia)||_b6.rememberRemoteTrack(key3,track,stream,"string"==typeof track.id?track.id:void 0,"string"==typeof stream.id?stream.id:void 0);null==(_c3=listeners2.onPeerTrack)||_c3.call(listeners2,track,stream,id,metadata)}},applyMediaOp=(targets,key3,metadata,sendMeta,op,mediaIds={})=>{const payload={k:key3,...mediaIds,...void 0===metadata?{}:{m:metadata}};return iterate2(targets,async(id,peer)=>{await sendMeta(payload,id);op(peer)})};return{addStream:(stream,options,sendMeta)=>applyMediaOp(options.target,localMedia.getStreamKey(stream),options.metadata,sendMeta,peer=>peer.addStream(stream),{s:stream.id}),removeStream:(stream,target)=>{iterate2(target,(_,peer)=>peer.removeStream(stream))},addTrack:(track,stream,options,sendMeta)=>applyMediaOp(options.target,localMedia.getTrackKey(track),options.metadata,sendMeta,peer=>peer.addTrack(track,stream),{s:stream.id,t:track.id}),removeTrack:(track,target)=>{iterate2(target,(_,peer)=>peer.removeTrack(track))},replaceTrack:(oldTrack,newTrack,options,sendMeta)=>applyMediaOp(options.target,localMedia.getTrackKey(newTrack),options.metadata,sendMeta,peer=>peer.replaceTrack(oldTrack,newTrack),{t:oldTrack.id}),receiveStreamMeta:(meta,id)=>{var _a13,_b6,_c3;if(!isActive(id))return;const parsed=toPendingMediaMeta(meta);if(!parsed)return;const cached=null==(_b6=null==(_a13=getSharedMediaPeer(id))?void 0:_a13.__trysteroMedia)?void 0:_b6.getRemoteStream(parsed.key,parsed.streamId);cached?emitStream(id,parsed.key,cached,parsed.metadata):(null!=(_c3=pendingStreamMetas[id])?_c3:pendingStreamMetas[id]=[]).push(parsed)},receiveTrackMeta:(meta,id)=>{var _a13,_b6,_c3;if(!isActive(id))return;const parsed=toPendingMediaMeta(meta);if(!parsed)return;const cached=null==(_b6=null==(_a13=getSharedMediaPeer(id))?void 0:_a13.__trysteroMedia)?void 0:_b6.getRemoteTrack(parsed.key,parsed.trackId);cached?emitTrack(id,parsed.key,cached.track,cached.stream,parsed.metadata):(null!=(_c3=pendingTrackMetas[id])?_c3:pendingTrackMetas[id]=[]).push(parsed)},receiveRemoteStream:(id,stream)=>{var _a13;if(!isActive(id))return;const next2=null==(_a13=pendingStreamMetas[id])?void 0:_a13.shift();next2&&emitStream(id,next2.key,stream,next2.metadata)},receiveRemoteTrack:(id,track,stream)=>{var _a13;if(!isActive(id))return;const next2=null==(_a13=pendingTrackMetas[id])?void 0:_a13.shift();next2&&emitTrack(id,next2.key,track,stream,next2.metadata)},clearPeer:id=>{delete pendingStreamMetas[id];delete pendingTrackMetas[id]},get onPeerStream(){return listeners2.onPeerStream},set onPeerStream(handler){listeners2.onPeerStream=handler},get onPeerTrack(){return listeners2.onPeerTrack},set onPeerTrack(handler){listeners2.onPeerTrack=handler}}};unloadEvent="beforeunload";defaultHandshakeTimeoutMs=1e4;internalNs=ns=>"@_"+ns;beforeUnloadRoomCleanups=new Set;cleanupActiveRoomsOnBeforeUnload=()=>beforeUnloadRoomCleanups.forEach(cleanup=>cleanup());registerBeforeUnloadCleanup=cleanup=>{beforeUnloadRoomCleanups.add(cleanup);1===beforeUnloadRoomCleanups.size&&addEventListener(unloadEvent,cleanupActiveRoomsOnBeforeUnload);return()=>{beforeUnloadRoomCleanups.delete(cleanup);beforeUnloadRoomCleanups.size||removeEventListener(unloadEvent,cleanupActiveRoomsOnBeforeUnload)}};room_default=(onPeer,onPeerLeave,onSelfLeave,{onPeerHandshake,onHandshakeError,handshakeTimeoutMs=defaultHandshakeTimeoutMs,isPassive=!1}={})=>{const peerMap={},activePeerMap={},pendingPongs={},listeners2={onPeerJoin:null,onPeerLeave:null};let unregisterBeforeUnloadCleanup=noOp,handshakeManager=null;const iterate2=(targets,f4,{includePending=!1}={})=>(targets?Array.isArray(targets)?targets:[targets]:keys(includePending?peerMap:activePeerMap)).flatMap(id=>{const peer=includePending?peerMap[id]:activePeerMap[id];if(!peer){console.warn(`${libName}: no peer with id ${id} found`);return[]}return[Promise.resolve(f4(id,peer))]}),mediaManager=createMediaManager({iterate:(targets,f4)=>iterate2(targets,(id,peer)=>f4(id,peer)),isActive:id=>Boolean(activePeerMap[id]),getSharedMediaPeer:id=>{var _a13;return null!=(_a13=peerMap[id])?_a13:null}}),actionManager=createActionManager({getPeer:(id,includePending)=>(includePending?peerMap:activePeerMap)[id],getPeerIds:includePending=>keys(includePending?peerMap:activePeerMap),canReceiveFromPeer:(id,receiveWhilePending)=>Boolean(null==handshakeManager?void 0:handshakeManager.canReceiveFromPeer(id,receiveWhilePending))}),makeActionInternal=actionManager.makeInternalAction,handleData=actionManager.handleData,makeAction=actionManager.makeAction,clearPeerState=(id,reason=mkErr("peer disconnected"))=>{var _a13;const err3=toError(reason,"peer disconnected");null==handshakeManager||handshakeManager.clearPeer(id,err3);delete peerMap[id];delete activePeerMap[id];actionManager.clearPeer(id,err3);null==(_a13=pendingPongs[id])||_a13.splice(0).forEach(waiter=>waiter.reject(err3));delete pendingPongs[id];mediaManager.clearPeer(id)},exitPeer=(id,peer,reason)=>{var _a13;const current=peerMap[id];if(!current)return;if(peer&&current!==peer)return;const wasActive=Boolean(activePeerMap[id]);clearPeerState(id,reason);current.destroy();wasActive&&(null==(_a13=listeners2.onPeerLeave)||_a13.call(listeners2,id));onPeerLeave(id)},leave=async()=>{await leaveAction.send("");await new Promise(res2=>setTimeout(res2,99));entries(peerMap).forEach(([id,peer])=>{peer.destroy();clearPeerState(id,mkErr("room left"))});unregisterBeforeUnloadCleanup();onSelfLeave()},pingAction=makeActionInternal(internalNs("ping")),pongAction=makeActionInternal(internalNs("pong")),signalAction=makeActionInternal(internalNs("signal")),streamMetaAction=makeActionInternal(internalNs("stream")),trackMetaAction=makeActionInternal(internalNs("track")),leaveAction=makeActionInternal(internalNs("leave"),{sendToPending:!0,receiveWhilePending:!0}),handshakeDataAction=makeActionInternal(internalNs("hsdata"),{sendToPending:!0,receiveWhilePending:!0}),handshakeReadyAction=makeActionInternal(internalNs("hsready"),{sendToPending:!0,receiveWhilePending:!0});handshakeManager=createHandshakeManager({...void 0===onPeerHandshake?{}:{onPeerHandshake},...void 0===onHandshakeError?{}:{onHandshakeError},handshakeTimeoutMs,sendHandshakeData:handshakeDataAction.send,sendHandshakeReady:handshakeReadyAction.send,onActivate:(id,peer)=>{var _a13;activePeerMap[id]=peer;null==(_a13=listeners2.onPeerJoin)||_a13.call(listeners2,id)},onFailure:(id,peer,reason)=>exitPeer(id,peer,reason)});pingAction.onMessage((_,id)=>pongAction.send("",id));pongAction.onMessage((_,id)=>{var _a13;const queue2=pendingPongs[id];null==(_a13=null==queue2?void 0:queue2.shift())||_a13.resolve();queue2&&!queue2.length&&delete pendingPongs[id]});signalAction.onMessage((sdp,id)=>{var _a13;activePeerMap[id]&&(null==(_a13=peerMap[id])||_a13.signal(sdp))});streamMetaAction.onMessage((meta,id)=>mediaManager.receiveStreamMeta(meta,id));trackMetaAction.onMessage((meta,id)=>mediaManager.receiveTrackMeta(meta,id));leaveAction.onMessage((_,id)=>exitPeer(id,void 0,mkErr("peer left room")));handshakeDataAction.onMessage((data,id,metadata)=>null==handshakeManager?void 0:handshakeManager.receiveHandshakeData(data,id,metadata));handshakeReadyAction.onMessage((_,id)=>null==handshakeManager?void 0:handshakeManager.receiveHandshakeReady(id));onPeer((peer,id)=>{const existingPeer=peerMap[id];if(existingPeer){if(existingPeer===peer)return;existingPeer.destroy();clearPeerState(id,mkErr("peer replaced"))}peerMap[id]=peer;null==handshakeManager||handshakeManager.addPeer(id,peer);peer.setHandlers({data:d4=>handleData(id,d4),stream:stream=>mediaManager.receiveRemoteStream(id,stream),track:(track,stream)=>mediaManager.receiveRemoteTrack(id,track,stream),signal:sdp=>{activePeerMap[id]&&signalAction.send(sdp,id)},close:()=>exitPeer(id,peer,mkErr("peer disconnected")),error:err3=>{console.error(`${libName} peer error:`,err3);exitPeer(id,peer,err3)}});null==handshakeManager||handshakeManager.start(id,peer)});isBrowser&&(unregisterBeforeUnloadCleanup=registerBeforeUnloadCleanup(()=>leave().catch(noOp)));return{makeAction,leave,ping:async id=>{if(!activePeerMap[id])throw mkErr(`no active peer with id ${id}`);const start=Date.now();await new Promise((resolve,reject)=>{var _a13;const queue2=null!=(_a13=pendingPongs[id])?_a13:pendingPongs[id]=[],clearFromQueue=()=>{const currentQueue=pendingPongs[id];if(!currentQueue)return;const i3=currentQueue.indexOf(waiter);i3>-1&&currentQueue.splice(i3,1);currentQueue.length||delete pendingPongs[id]},waiter={resolve:()=>{clearFromQueue();resolve()},reject:reason=>{clearFromQueue();reject(reason)}};queue2.push(waiter);pingAction.send("",id).catch(err3=>waiter.reject(toError(err3,"peer disconnected")))});return Date.now()-start},isPassive:()=>isPassive,getPeers:()=>fromEntries(entries(activePeerMap).map(([id,peer])=>[id,peer.connection])),addStream:(stream,options={})=>mediaManager.addStream(stream,options,streamMetaAction.send),removeStream:(stream,options={})=>{mediaManager.removeStream(stream,options.target)},addTrack:(track,stream,options={})=>mediaManager.addTrack(track,stream,options,trackMetaAction.send),removeTrack:(track,options={})=>{mediaManager.removeTrack(track,options.target)},replaceTrack:(oldTrack,newTrack,options={})=>mediaManager.replaceTrack(oldTrack,newTrack,options,trackMetaAction.send),get onPeerJoin(){return listeners2.onPeerJoin},set onPeerJoin(handler){listeners2.onPeerJoin=handler;handler&&keys(activePeerMap).forEach(peerId=>handler(peerId))},get onPeerLeave(){return listeners2.onPeerLeave},set onPeerLeave(handler){listeners2.onPeerLeave=handler},get onPeerStream(){return mediaManager.onPeerStream},set onPeerStream(handler){mediaManager.onPeerStream=handler},get onPeerTrack(){return mediaManager.onPeerTrack},set onPeerTrack(handler){mediaManager.onPeerTrack=handler}}};roomFrameVersion=1;roomPresenceFrameVersion=2;wrapRoomFrame=(roomToken,data)=>{const tokenBytes=encodeBytes(roomToken),frame=new Uint8Array(3+tokenBytes.byteLength+data.byteLength);frame[0]=roomFrameVersion;frame[1]=tokenBytes.byteLength>>>8&255;frame[2]=255&tokenBytes.byteLength;frame.set(tokenBytes,3);frame.set(data,3+tokenBytes.byteLength);return frame};wrapRoomPresenceFrame=(roomToken,isPresent)=>{const tokenBytes=encodeBytes(roomToken),frame=new Uint8Array(4+tokenBytes.byteLength);frame[0]=roomPresenceFrameVersion;frame[1]=Number(isPresent);frame[2]=tokenBytes.byteLength>>>8&255;frame[3]=255&tokenBytes.byteLength;frame.set(tokenBytes,4);return frame};unwrapFrame=data=>{var _a13,_b6,_c3,_d2;const buffer=new Uint8Array(data);if(buffer.byteLength<3)return null;if(buffer[0]===roomFrameVersion){const tokenSize2=(null!=(_a13=buffer[1])?_a13:0)<<8|(null!=(_b6=buffer[2])?_b6:0),headerSize2=3+tokenSize2;return tokenSize2<=0||buffer.byteLength<headerSize2?null:{type:"room",roomToken:decodeBytes(buffer.subarray(3,headerSize2)),payload:buffer.subarray(headerSize2).slice().buffer}}if(buffer[0]!==roomPresenceFrameVersion||buffer.byteLength<4)return null;const tokenSize=(null!=(_c3=buffer[2])?_c3:0)<<8|(null!=(_d2=buffer[3])?_d2:0),headerSize=4+tokenSize;return tokenSize<=0||buffer.byteLength<headerSize?null:{type:"presence",roomToken:decodeBytes(buffer.subarray(4,headerSize)),isPresent:1===buffer[1]}};isPeerUnderlyingStale=peer=>{const{connection,channel}=peer;return peer.isDead||"closed"===connection.connectionState||"failed"===connection.connectionState||"closed"===connection.iceConnectionState||"failed"===connection.iceConnectionState||"closing"===(null==channel?void 0:channel.readyState)||"closed"===(null==channel?void 0:channel.readyState)};getConnectedPeerHealth=peer=>{if(isPeerUnderlyingStale(peer))return"stale";const{channel}=peer;return channel&&"open"===channel.readyState?"live":"transient"};SharedPeerManager=class{constructor(){__publicField(this,"byApp",{});__publicField(this,"roomPresenceHandlers",{})}getMap(appId){var _a13,_b6;return null!=(_b6=(_a13=this.byApp)[appId])?_b6:_a13[appId]={}}get(appId,peerId){var _a13;return null==(_a13=this.byApp[appId])?void 0:_a13[peerId]}isPeerStale(peer){return isPeerUnderlyingStale(peer)}getHealth(peer){return this.isPeerStale(peer)?"stale":"live"}setRoomPresenceHandler(appId,handler){this.roomPresenceHandlers[appId]=handler;return()=>{this.roomPresenceHandlers[appId]===handler&&delete this.roomPresenceHandlers[appId]}}sendRoomPresence(shared,roomToken,isPresent){shared.isClosing||shared.peer.isDead||shared.peer.sendData(wrapRoomPresenceFrame(roomToken,isPresent))}clear(appId,peerId,{destroyPeer}){const map4=this.byApp[appId],shared=null==map4?void 0:map4[peerId];if(!shared||shared.isClosing)return;shared.idleTimer=resetTimer(shared.idleTimer);shared.isClosing=!0;destroyPeer&&!shared.peer.isDead&&shared.peer.destroy();const bindings=values(shared.bindings);shared.bindings={};shared.bindingsByToken={};shared.controlRoomId=null;delete map4[peerId];bindings.forEach(binding=>{var _a13,_b6;null==(_b6=(_a13=binding.handlers).close)||_b6.call(_a13);binding.pendingData.length=0;binding.pendingSendData.length=0;binding.pendingTracks.length=0});shared.media.clearRemote();shared.pendingDataByToken.clear();shared.remoteRoomTokens.clear();0===keys(map4).length&&delete this.byApp[appId]}register(appId,peerId,peer,idleMs){const map4=this.getMap(appId),existing=map4[peerId];if(existing){existing.idleTimer=resetTimer(existing.idleTimer);if(existing.peer===peer)return existing;this.clear(appId,peerId,{destroyPeer:!0})}const shared={appId,peerId,peer,bindings:{},bindingsByToken:{},pendingDataByToken:new Map,remoteRoomTokens:new Set,idleTimer:null,controlRoomId:null,streamOwners:new Map,trackOwners:new Map,media:createMediaIdentityCache(),idleMs,isClosing:!1};peer.setHandlers({data:data=>this.dispatchData(shared,data),signal:signal=>this.dispatchSignal(shared,signal),close:()=>this.clear(appId,peerId,{destroyPeer:!1}),error:err3=>{console.error(`${libName} peer error:`,err3);this.clear(appId,peerId,{destroyPeer:!1})},track:(track,stream)=>this.dispatchTrack(shared,track,stream)});map4[peerId]=shared;return shared}bind(roomId,roomTokenPromise,shared,{onDetach}){const existingBinding=shared.bindings[roomId];if(existingBinding){shared.idleTimer=resetTimer(shared.idleTimer);return{proxy:existingBinding.proxy,isNew:!1}}const binding={roomId,roomToken:null,roomTokenPromise,handlers:{},pendingData:[],pendingSendData:[],pendingTracks:[],detach:noOp,proxy:{}},detachBinding=()=>{var _a14;if(shared.bindings[roomId]){this.pruneRoomOwnership(shared,roomId);delete shared.bindings[roomId];binding.roomToken&&shared.bindingsByToken[binding.roomToken]===binding&&delete shared.bindingsByToken[binding.roomToken];shared.controlRoomId===roomId&&(shared.controlRoomId=null!=(_a14=keys(shared.bindings)[0])?_a14:null);onDetach();this.scheduleIdleTimer(shared)}},proxy2={created:shared.peer.created,get connection(){return shared.peer.connection},get channel(){return shared.peer.channel},get isDead(){return shared.peer.isDead},getOffer:restartIce=>shared.peer.getOffer(restartIce),signal:sdp=>shared.peer.signal(sdp),sendData:data=>{binding.roomToken?shared.peer.sendData(wrapRoomFrame(binding.roomToken,data)):binding.pendingSendData.push(data)},destroy:()=>detachBinding(),setHandlers:newHandlers=>{const{signal,...rest}=newHandlers;Object.assign(binding.handlers,rest);signal&&(binding.handlers.signal=signal);this.flushBindingQueues(binding)},offerPromise:shared.peer.offerPromise,addStream:stream=>{var _a14;const owners=null!=(_a14=shared.streamOwners.get(stream))?_a14:new Set,shouldAttach=0===owners.size;owners.add(roomId);shared.streamOwners.set(stream,owners);shouldAttach&&shared.peer.addStream(stream)},removeStream:stream=>{const owners=shared.streamOwners.get(stream);if(owners){owners.delete(roomId);if(0===owners.size){shared.streamOwners.delete(stream);shared.peer.removeStream(stream)}}},addTrack:(track,stream)=>{var _a14,_b6;const entry=null!=(_a14=shared.trackOwners.get(track))?_a14:{stream,rooms:new Set},shouldAttach=0===entry.rooms.size;entry.stream=stream;entry.rooms.add(roomId);shared.trackOwners.set(track,entry);return shouldAttach?shared.peer.addTrack(track,stream):null!=(_b6=shared.peer.connection.getSenders().find(s2=>s2.track===track))?_b6:shared.peer.addTrack(track,stream)},removeTrack:track=>{const entry=shared.trackOwners.get(track);if(entry){entry.rooms.delete(roomId);if(0===entry.rooms.size){shared.trackOwners.delete(track);shared.peer.removeTrack(track)}}},replaceTrack:(oldTrack,newTrack)=>{var _a14;const oldEntry=shared.trackOwners.get(oldTrack);if(oldEntry){shared.trackOwners.delete(oldTrack);const nextEntry=null!=(_a14=shared.trackOwners.get(newTrack))?_a14:{stream:oldEntry.stream,rooms:new Set};oldEntry.rooms.forEach(room=>nextEntry.rooms.add(room));shared.trackOwners.set(newTrack,nextEntry)}return shared.peer.replaceTrack(oldTrack,newTrack)},__trysteroMedia:shared.media};binding.proxy=proxy2;binding.detach=detachBinding;shared.bindings[roomId]=binding;null!=shared.controlRoomId||(shared.controlRoomId=roomId);shared.idleTimer=resetTimer(shared.idleTimer);roomTokenPromise.then(roomToken=>{if(shared.isClosing||shared.bindings[roomId]!==binding)return;binding.roomToken=roomToken;shared.bindingsByToken[roomToken]=binding;const pendingData=shared.pendingDataByToken.get(roomToken);if(null==pendingData?void 0:pendingData.length){binding.pendingData.push(...pendingData);shared.pendingDataByToken.delete(roomToken)}binding.pendingSendData.splice(0).forEach(payload=>shared.peer.sendData(wrapRoomFrame(roomToken,payload)));this.flushBindingQueues(binding)});return{proxy:proxy2,isNew:!0}}pruneRoomOwnership(shared,roomIdToRemove){shared.streamOwners.forEach((rooms,stream)=>{rooms.delete(roomIdToRemove);if(0===rooms.size){shared.streamOwners.delete(stream);shared.peer.removeStream(stream)}});shared.trackOwners.forEach((entry,track)=>{entry.rooms.delete(roomIdToRemove);if(0===entry.rooms.size){shared.trackOwners.delete(track);shared.peer.removeTrack(track)}})}scheduleIdleTimer(shared){if(!(shared.isClosing||keys(shared.bindings).length>0)){shared.idleTimer=resetTimer(shared.idleTimer);shared.idleTimer=setTimeout(()=>{var _a13;const current=null==(_a13=this.byApp[shared.appId])?void 0:_a13[shared.peerId];!current||keys(current.bindings).length>0||this.clear(shared.appId,shared.peerId,{destroyPeer:!0})},shared.idleMs)}}getSignalBinding(shared){if(shared.controlRoomId){const selected=shared.bindings[shared.controlRoomId];if(null==selected?void 0:selected.handlers.signal)return selected}const fallback3=values(shared.bindings).find(binding=>Boolean(binding.handlers.signal));if(!fallback3)return null;shared.controlRoomId=fallback3.roomId;return fallback3}flushBindingQueues(binding){const{handlers:handlers3}=binding;handlers3.data&&binding.pendingData.length>0&&binding.pendingData.splice(0).forEach(payload=>{var _a13;return null==(_a13=handlers3.data)?void 0:_a13.call(handlers3,payload)});(handlers3.track||handlers3.stream)&&binding.pendingTracks.length&&binding.pendingTracks.splice(0).forEach(({track,stream})=>{var _a13,_b6;null==(_a13=handlers3.track)||_a13.call(handlers3,track,stream);null==(_b6=handlers3.stream)||_b6.call(handlers3,stream)})}dispatchData(shared,data){var _a13,_b6,_c3;const decoded=unwrapFrame(data);if(!decoded)return;if("presence"===decoded.type){decoded.isPresent?shared.remoteRoomTokens.add(decoded.roomToken):shared.remoteRoomTokens.delete(decoded.roomToken);null==(_b6=(_a13=this.roomPresenceHandlers)[shared.appId])||_b6.call(_a13,shared.peerId,decoded.roomToken,decoded.isPresent);return}const binding=shared.bindingsByToken[decoded.roomToken];if(!binding){const pending3=null!=(_c3=shared.pendingDataByToken.get(decoded.roomToken))?_c3:[];pending3.push(decoded.payload);shared.pendingDataByToken.set(decoded.roomToken,pending3);return}binding.handlers.data?binding.handlers.data(decoded.payload):binding.pendingData.push(decoded.payload)}dispatchSignal(shared,signal){var _a13,_b6,_c3;null==(_c3=null==(_a13=this.getSignalBinding(shared))?void 0:(_b6=_a13.handlers).signal)||_c3.call(_b6,signal)}dispatchTrack(shared,track,stream){values(shared.bindings).forEach(binding=>{var _a13,_b6,_c3,_d2;if(binding.handlers.track||binding.handlers.stream){null==(_b6=(_a13=binding.handlers).track)||_b6.call(_a13,track,stream);null==(_d2=(_c3=binding.handlers).stream)||_d2.call(_c3,stream)}else binding.pendingTracks.push({track,stream})})}};offerPostAnswerTtlMs=23333;offerIdSize=12;disconnectedPeerGraceMs=7533;answeringTtlMs=23333;legacyCandidateKey="__legacy__";offerRelayPlaceholder="offer-placeholder";signalKeys=["offer","answer","candidate"];toPayload=msg=>{if("string"==typeof msg)try{const parsed=fromJson(msg);return parsed&&"object"==typeof parsed?parsed:null}catch(e3){return null}return msg&&"object"==typeof msg?msg:null};getString=(payload,key3)=>"string"==typeof payload[key3]&&payload[key3]?payload[key3]:void 0;hasInvalidSignalField=payload=>signalKeys.some(key3=>key3 in payload&&("string"!=typeof payload[key3]||""===payload[key3]));publishCipheredSignalingMessage=(ctx,signal,peerTopic,signalPeer,buildPayload,stillValid)=>{ctx.toCipher(signal).then(encryptedSignal=>{!ctx.isLeaving()&&stillValid()&&signalPeer(peerTopic,toJson(buildPayload(encryptedSignal.sdp)))})};makeState=()=>({status:"idle",offerPeer:null,offerId:null,offerSdp:null,offerInitPromise:null,offerAnswered:!1,offerRelays:[],offerSignalRelays:[],offerSignalBacklog:[],offerRelayTimers:[],offerExpiryTimer:null,connectedPeer:null,connectedPeerUnhealthySinceMs:null,answeringExpiryTimer:null,answeringPeer:null,answerSent:!1,connectionErrorReported:!1,pendingCandidates:{}});hasTurnServer=config=>{var _a13,_b6,_c3;return[...null!=(_a13=config.turnConfig)?_a13:[],...null!=(_c3=null==(_b6=config.rtcConfig)?void 0:_b6.iceServers)?_c3:[]].some(({urls})=>(Array.isArray(urls)?urls:[urls]).some(url=>/^turns?:/i.test(url)))};getSdpExchangeConnectionError=(peerId,config)=>`could not connect to peer ${peerId} after exchanging SDP; ${hasTurnServer(config)?"check that your TURN server URLs and credentials are reachable by both peers":"configure TURN servers with turnConfig or rtcConfig.iceServers"}`;reportSdpExchangeConnectionFailure=(ctx,state2,peerId)=>{var _a13;if(!(ctx.isLeaving()||state2.connectedPeer||state2.connectionErrorReported)){state2.connectionErrorReported=!0;null==(_a13=ctx.onJoinError)||_a13.call(ctx,{error:getSdpExchangeConnectionError(peerId,ctx.config),appId:ctx.appId,peerId,roomId:ctx.roomId})}};getState=(peerStates,peerId)=>{var _a13;return null!=(_a13=peerStates[peerId])?_a13:peerStates[peerId]=makeState()};updateStatus=state2=>{state2.connectedPeer?state2.status="connected":state2.answeringPeer?state2.status="answering":state2.offerPeer||state2.offerRelays.some(Boolean)?state2.status="offering":state2.status="idle"};clearAnswering=(state2,peer)=>{if(state2.answeringPeer===peer){state2.answeringExpiryTimer=resetTimer(state2.answeringExpiryTimer);state2.answeringPeer=null;state2.answerSent=!1;updateStatus(state2)}};clearConnectedPeer=(state2,peerId,_reason)=>{if(state2.connectedPeer){state2.connectedPeer.isDead||state2.connectedPeer.destroy();state2.connectedPeer=null;state2.connectedPeerUnhealthySinceMs=null;updateStatus(state2)}};clearOfferRelay=(state2,relayId)=>{state2.offerRelayTimers[relayId]=resetTimer(state2.offerRelayTimers[relayId]);if(state2.offerRelays[relayId]){state2.offerRelays[relayId]=void 0;updateStatus(state2)}};clearOfferRelayIfPlaceholder=(state2,relayId)=>{(null==state2?void 0:state2.offerRelays[relayId])===offerRelayPlaceholder&&clearOfferRelay(state2,relayId)};hasRemoteDescription=peer=>{if(peer.isDead||"closed"===peer.connection.connectionState)return!0;try{return Boolean(peer.connection.remoteDescription)}catch(e3){return!0}};resetOfferState=(state2,offerPool)=>{const previousOfferAnswered=state2.offerAnswered;state2.offerExpiryTimer=resetTimer(state2.offerExpiryTimer);state2.offerInitPromise=null;state2.offerRelays.forEach((_,relayId)=>clearOfferRelay(state2,relayId));state2.offerRelays=[];state2.offerSignalRelays=[];state2.offerRelayTimers=[];state2.offerSignalBacklog=[];state2.offerPeer&&state2.offerPeer!==state2.connectedPeer&&(previousOfferAnswered||hasRemoteDescription(state2.offerPeer)?state2.offerPeer.isDead||state2.offerPeer.destroy():offerPool.recycle(state2.offerPeer));state2.offerPeer=null;state2.offerId=null;state2.offerSdp=null;state2.offerAnswered=!1;state2.connectionErrorReported=!1;updateStatus(state2)};scheduleAnsweringExpiry=(ctx,state2,peerId,peer)=>{resetTimer(state2.answeringExpiryTimer);state2.answeringExpiryTimer=setTimeout(()=>{const current=ctx.peerStates[peerId];if(current&&!current.connectedPeer&&current.answeringPeer===peer){current.answerSent&&reportSdpExchangeConnectionFailure(ctx,current,peerId);peer.destroy();clearAnswering(current,peer);ctx.checkDeactivate()}},answeringTtlMs)};flushBufferedCandidates=async(state2,peer,offerId)=>{const bufferKeys=offerId?[offerId,legacyCandidateKey]:[legacyCandidateKey];for(const key3 of bufferKeys){const buffered=state2.pendingCandidates[key3];if(null==buffered?void 0:buffered.length){delete state2.pendingCandidates[key3];for(const candidate of buffered)await peer.signal(candidate)}}};scheduleOfferExpiry=(ctx,state2,peerId,ttlMs=offerTtl)=>{resetTimer(state2.offerExpiryTimer);const offerId=state2.offerId;state2.offerExpiryTimer=setTimeout(()=>{const current=ctx.peerStates[peerId];if(current&&!current.connectedPeer&&current.offerId===offerId){current.offerAnswered&&reportSdpExchangeConnectionFailure(ctx,current,peerId);resetOfferState(current,ctx.offerPool);ctx.checkDeactivate()}},ttlMs)};ensureOffer=(ctx,state2,peerId,relayId)=>{if(state2.offerPeer&&state2.offerId&&state2.offerSdp)return Promise.resolve({peer:state2.offerPeer,offer:state2.offerSdp,offerId:state2.offerId});if(state2.offerInitPromise)return state2.offerInitPromise;state2.offerInitPromise=(async()=>{const firstOffer=(await ctx.offerPool.checkout(1,!1,ctx.encryptOffer))[0];if(!firstOffer)throw mkErr("failed to allocate offer peer");const{peer,offer}=firstOffer;state2.offerPeer=peer;state2.offerId=genId(offerIdSize);state2.offerSdp=offer;state2.offerAnswered=!1;state2.connectionErrorReported=!1;state2.offerSignalBacklog=[];updateStatus(state2);const onOfferPeerClosedOrError=()=>{if(state2.offerPeer===peer&&!state2.connectedPeer){state2.offerAnswered&&reportSdpExchangeConnectionFailure(ctx,state2,peerId);resetOfferState(state2,ctx.offerPool)}ctx.disconnectPeer(peer,peerId);ctx.checkDeactivate()};peer.setHandlers({connect:()=>ctx.connectPeer(peer,peerId,relayId),signal:signal=>{if(state2.offerPeer===peer){state2.offerSignalBacklog.push(signal);state2.offerSignalRelays.forEach(sendSignal2=>null==sendSignal2?void 0:sendSignal2(signal))}},close:onOfferPeerClosedOrError,error:onOfferPeerClosedOrError});scheduleOfferExpiry(ctx,state2,peerId);return{peer,offer,offerId:state2.offerId}})().finally(()=>state2.offerInitPromise=null);return state2.offerInitPromise};handleAnnouncement=async(ctx,relayId,peerId,shared,signalPeer)=>{var _a13;if(shared){ctx.attachSharedPeerToRoom(peerId,shared);return}const state2=ctx.peerStates[peerId];if(!state2||state2.connectedPeer||state2.answeringPeer||state2.offerAnswered){clearOfferRelayIfPlaceholder(state2,relayId);return}if(state2.offerRelays[relayId]!==offerRelayPlaceholder)return;const[peerTopic,offerInfo]=await all([sha1(topicPath(ctx.rootTopicPlaintext,peerId)),ensureOffer(ctx,state2,peerId,relayId)]);if(ctx.isLeaving())return;if(state2.connectedPeer||state2.answeringPeer||state2.offerAnswered||state2.offerRelays[relayId]!==offerRelayPlaceholder){clearOfferRelayIfPlaceholder(state2,relayId);return}state2.offerRelayTimers[relayId]=resetTimer(state2.offerRelayTimers[relayId]);state2.offerRelays[relayId]=!0;updateStatus(state2);state2.offerRelayTimers[relayId]=setTimeout(()=>prunePendingOffer(ctx,peerId,relayId),.9*(null!=(_a13=ctx.announceIntervals[relayId])?_a13:ctx.announceIntervalMs));let didSendOffer=!1;state2.offerSignalRelays[relayId]=signal=>{didSendOffer&&(ctx.isLeaving()||state2.connectedPeer||state2.offerPeer!==offerInfo.peer||state2.offerId!==offerInfo.offerId||"candidate"!==signal.type||publishCipheredSignalingMessage(ctx,signal,peerTopic,signalPeer,sdp=>({peerId:selfId,offerId:offerInfo.offerId,candidate:sdp,...ctx.isPassive?{passive:!0}:{}}),()=>!state2.connectedPeer&&state2.offerPeer===offerInfo.peer&&state2.offerId===offerInfo.offerId))};signalPeer(peerTopic,toJson({peerId:selfId,offerId:offerInfo.offerId,offer:offerInfo.offer,...ctx.isPassive?{passive:!0}:{}}));didSendOffer=!0;state2.offerSignalBacklog.forEach(signal=>{var _a14,_b6;return null==(_b6=(_a14=state2.offerSignalRelays)[relayId])?void 0:_b6.call(_a14,signal)})};handleOffer=async(ctx,relayId,peerId,offer,offerId,hasOutgoingOfferHint,signalPeer)=>{var _a13;const state2=getState(ctx.peerStates,peerId);if(state2.answeringPeer||state2.offerAnswered)return;const hasTrackedOutgoingOffer=Boolean(state2.offerPeer||state2.offerRelays.some(Boolean));if((hasTrackedOutgoingOffer||hasOutgoingOfferHint)&&selfId<peerId)return;hasTrackedOutgoingOffer&&resetOfferState(state2,ctx.offerPool);const answerPeer=ctx.initPeer(!1,ctx.config);state2.answeringPeer=answerPeer;state2.answerSent=!1;state2.connectionErrorReported=!1;scheduleAnsweringExpiry(ctx,state2,peerId,answerPeer);updateStatus(state2);const onAnswerPeerClosedOrError=()=>{state2.answeringPeer===answerPeer&&!state2.connectedPeer&&state2.answerSent&&reportSdpExchangeConnectionFailure(ctx,state2,peerId);clearAnswering(state2,answerPeer);ctx.disconnectPeer(answerPeer,peerId);ctx.checkDeactivate()};answerPeer.setHandlers({connect:()=>ctx.connectPeer(answerPeer,peerId,relayId),close:onAnswerPeerClosedOrError,error:onAnswerPeerClosedOrError});let plainOffer;try{plainOffer=await ctx.toPlain({type:"offer",sdp:offer})}catch(e3){clearAnswering(state2,answerPeer);null==(_a13=ctx.onJoinError)||_a13.call(ctx,{error:"incorrect room password when decrypting offer",appId:ctx.appId,peerId,roomId:ctx.roomId});return}if(answerPeer.isDead){clearAnswering(state2,answerPeer);return}const peerTopic=await sha1(topicPath(ctx.rootTopicPlaintext,peerId));if(!ctx.isLeaving()){answerPeer.setHandlers({signal:signal=>{ctx.isLeaving()||state2.answeringPeer!==answerPeer||answerPeer.isDead||"answer"!==signal.type&&"candidate"!==signal.type||publishCipheredSignalingMessage(ctx,signal,peerTopic,signalPeer,sdp=>{const payloadToSend={peerId:selfId};if("answer"===signal.type){state2.answerSent=!0;payloadToSend.answer=sdp}else payloadToSend.candidate=sdp;offerId&&(payloadToSend.offerId=offerId);ctx.isPassive&&(payloadToSend.passive=!0);return payloadToSend},()=>state2.answeringPeer===answerPeer&&!answerPeer.isDead)}});await answerPeer.signal(plainOffer);await flushBufferedCandidates(state2,answerPeer,offerId)}};handleCandidate=async(ctx,peerId,candidate,offerId,peer)=>{var _a13,_b6,_c3,_d2;let plainCandidate;try{plainCandidate=await ctx.toPlain({type:candidateType,sdp:candidate})}catch(e3){return}const state2=getState(ctx.peerStates,peerId),offerPeerMatch=offerId&&(null==state2?void 0:state2.offerPeer)&&state2.offerId===offerId?state2.offerPeer:null,answeringPeer=null!=(_a13=null==state2?void 0:state2.answeringPeer)?_a13:null,fallbackOfferPeer=!offerId&&(null==state2?void 0:state2.offerPeer)?state2.offerPeer:null,targetPeer=peer&&!peer.isDead?peer:null!=(_b6=null!=offerPeerMatch?offerPeerMatch:answeringPeer)?_b6:fallbackOfferPeer;if(!targetPeer||targetPeer.isDead){const pendingKey=null!=offerId?offerId:legacyCandidateKey;(null!=(_d2=(_c3=state2.pendingCandidates)[pendingKey])?_d2:_c3[pendingKey]=[]).push(plainCandidate);return}targetPeer.signal(plainCandidate)};handleAnswer=async(ctx,relayId,peerId,answer,offerId,peer)=>{var _a13;let plainAnswer;try{plainAnswer=await ctx.toPlain({type:"answer",sdp:answer})}catch(e3){null==(_a13=ctx.onJoinError)||_a13.call(ctx,{error:"incorrect room password when decrypting answer",appId:ctx.appId,peerId,roomId:ctx.roomId});return}if(peer){ctx.offerPool.claimLeased(peer);peer.setHandlers({connect:()=>ctx.connectPeer(peer,peerId,relayId),close:()=>ctx.disconnectPeer(peer,peerId)});peer.signal(plainAnswer)}else{const state2=ctx.peerStates[peerId];if(!state2||!state2.offerPeer||state2.offerAnswered||offerId&&state2.offerId&&offerId!==state2.offerId||state2.offerPeer.isDead)return;state2.offerAnswered=!0;scheduleOfferExpiry(ctx,state2,peerId,offerPostAnswerTtlMs);state2.offerPeer.signal(plainAnswer)}};prunePendingOffer=(ctx,peerId,relayId)=>{const state2=ctx.peerStates[peerId];if(state2&&!state2.connectedPeer&&state2.offerRelays[relayId]){clearOfferRelay(state2,relayId);ctx.checkDeactivate()}};createSignalHandler=ctx=>relayId=>async(topic,msg,signalPeer)=>{var _a13,_b6,_c3;if(ctx.isLeaving())return;const payload=toPayload(msg);if(!payload||hasInvalidSignalField(payload))return;const peerId=null!=(_a13=getString(payload,"peerId"))?_a13:"",offer=getString(payload,"offer"),answer=getString(payload,"answer"),candidate=getString(payload,"candidate"),offerId=getString(payload,"offerId"),peer=payload.peer,hasOutgoingOfferHint=!0===payload.hasOutgoingOffer,remoteIsPassive=!0===payload.passive;if(!peerId||peerId===selfId)return;const[rootTopic,selfTopic]=await all([ctx.rootTopicP,ctx.selfTopicP]);if(ctx.isLeaving())return;if(topic!==rootTopic&&topic!==selfTopic)return;if(ctx.isPassive&&remoteIsPassive)return;if(ctx.isPassive&&!ctx.isActive&&!answer&&!candidate){ctx.isActive=!0;null==(_b6=ctx.requeueAnnounce)||_b6.call(ctx)}if(ctx.isPassive&&!ctx.isActive)return;const state2=ctx.peerStates[peerId],connectedPeer=null==state2?void 0:state2.connectedPeer;if(connectedPeer&&state2){const health=getConnectedPeerHealth(connectedPeer);if("live"===health){state2.connectedPeerUnhealthySinceMs=null;return}if("stale"===health)clearConnectedPeer(state2,peerId,"message-from-stale-peer");else{const nowMs=Date.now(),unhealthySinceMs=null!=(_c3=state2.connectedPeerUnhealthySinceMs)?_c3:nowMs;state2.connectedPeerUnhealthySinceMs=unhealthySinceMs;if(nowMs-unhealthySinceMs<disconnectedPeerGraceMs)return;clearConnectedPeer(state2,peerId,"message-from-prolonged-disconnect")}}let shared=ctx.sharedPeers.get(ctx.appId,peerId);if(shared&&"stale"===ctx.sharedPeers.getHealth(shared.peer)){ctx.sharedPeers.clear(ctx.appId,peerId,{destroyPeer:!0});shared=void 0}const isAnnouncement=Boolean(peerId&&!offer&&!answer&&!candidate);if(isAnnouncement&&!shared){const announcePeerState=getState(ctx.peerStates,peerId),shouldLeadOffer=selfId<peerId;if(announcePeerState.answeringPeer||announcePeerState.connectedPeer||announcePeerState.offerAnswered)return;if(!shouldLeadOffer&&!announcePeerState.offerPeer){const peerSelfTopic=await sha1(topicPath(ctx.rootTopicPlaintext,peerId));ctx.isLeaving()||announcePeerState.connectedPeer||signalPeer(peerSelfTopic,toJson({peerId:selfId}));return}if(announcePeerState.offerRelays[relayId])return;announcePeerState.offerRelays[relayId]=offerRelayPlaceholder;updateStatus(announcePeerState)}if(!shared||!(offer||answer||candidate))return isAnnouncement?handleAnnouncement(ctx,relayId,peerId,shared,signalPeer):offer?handleOffer(ctx,relayId,peerId,offer,offerId,hasOutgoingOfferHint,signalPeer):candidate?handleCandidate(ctx,peerId,candidate,offerId,peer):answer?handleAnswer(ctx,relayId,peerId,answer,offerId,peer):void 0;shared.bindings[ctx.roomId]||ctx.attachSharedPeerToRoom(peerId,shared)};announceIntervalMs=5333;announceWarmupIntervalsMs=[233,533,1333];passiveActivationGraceMs=7533;sharedPeerIdleMsDefault=123333;strategy_default=({init:init3,subscribe:subscribe2,announce,deactivate})=>{const occupiedRooms={},roomRegistrations={},roomIdsByToken={},roomPresenceHandlerCleanups={},sharedPeers=new SharedPeerManager,hasActiveRooms=()=>values(occupiedRooms).some(rooms=>keys(rooms).length>0),getRoomRegistrations=appId=>{var _a13;return null!=(_a13=roomRegistrations[appId])?_a13:roomRegistrations[appId]={}},getRoomIdsByToken=appId=>{var _a13;return null!=(_a13=roomIdsByToken[appId])?_a13:roomIdsByToken[appId]={}},advertiseRoomPresence=(shared,roomToken,isPresent)=>{"live"===sharedPeers.getHealth(shared.peer)&&sharedPeers.sendRoomPresence(shared,roomToken,isPresent)},advertiseKnownRoomsToShared=(appId,shared)=>{var _a13;entries(null!=(_a13=roomRegistrations[appId])?_a13:{}).forEach(([roomId,registration])=>{if(!registration.shouldAdvertise())return;const{roomToken,roomTokenPromise}=registration;roomToken?advertiseRoomPresence(shared,roomToken,!0):roomTokenPromise.then(token=>{var _a14;(null==(_a14=roomRegistrations[appId])?void 0:_a14[roomId])===registration&&registration.roomToken===token&&(sharedPeers.get(appId,shared.peerId)!==shared||shared.isClosing||registration.shouldAdvertise()&&advertiseRoomPresence(shared,token,!0))})})},advertiseRoomPresenceToAll=(appId,roomToken,isPresent)=>values(sharedPeers.getMap(appId)).forEach(shared=>advertiseRoomPresence(shared,roomToken,isPresent)),ensureRoomPresenceHandler=appId=>{roomPresenceHandlerCleanups[appId]||(roomPresenceHandlerCleanups[appId]=sharedPeers.setRoomPresenceHandler(appId,(peerId,roomToken,isPresent)=>{var _a13,_b6,_c3;if(!isPresent)return;const shared=sharedPeers.get(appId,peerId),roomId=null==(_a13=roomIdsByToken[appId])?void 0:_a13[roomToken];shared&&roomId&&(null==(_c3=null==(_b6=roomRegistrations[appId])?void 0:_b6[roomId])||_c3.attachSharedPeerToRoom(peerId,shared))}))},cleanupRoomPresenceHandler=appId=>{var _a13;if(!(occupiedRooms[appId]&&keys(occupiedRooms[appId]).length>0)){null==(_a13=roomPresenceHandlerCleanups[appId])||_a13.call(roomPresenceHandlerCleanups);delete roomPresenceHandlerCleanups[appId];delete roomRegistrations[appId];delete roomIdsByToken[appId]}};let didInit=!1,initPromises=[],offerPool=null,cleanupWatchOnline=noOp;return(config,roomId,callbacks)=>{var _a13,_b6,_c3,_d2,_e2;if(!config)throw mkErr("requires a config map as the first argument");if(callbacks&&"object"!=typeof callbacks)throw mkErr("third argument must be a callbacks object");const{appId}=config,onJoinError=null==callbacks?void 0:callbacks.onJoinError,onPeerHandshake=null==callbacks?void 0:callbacks.onPeerHandshake,handshakeTimeoutMs=null==callbacks?void 0:callbacks.handshakeTimeoutMs;if(!appId)throw mkErr("config map is missing appId field");if(!roomId)throw mkErr("roomId argument required");if(void 0!==handshakeTimeoutMs&&(!Number.isFinite(handshakeTimeoutMs)||handshakeTimeoutMs<=0))throw mkErr("handshakeTimeoutMs must be a positive number");if(null==(_a13=occupiedRooms[appId])?void 0:_a13[roomId])return occupiedRooms[appId][roomId];ensureRoomPresenceHandler(appId);const rootTopicPlaintext=topicPath(libName,appId,roomId),rootTopicP=sha1(rootTopicPlaintext),selfTopicP=sha1(topicPath(rootTopicPlaintext,selfId)),key3=genKey(null!=(_b6=config.password)?_b6:"",appId,roomId),roomNamespacePromise=deriveRoomNamespace(appId,roomId),sharedPeerIdleMs=null!=(_c3=config._test_only_sharedPeerIdleMs)?_c3:sharedPeerIdleMsDefault;let didLeaveRoom=!1;const withKey=f4=>async signal=>({type:signal.type,sdp:await f4(key3,signal.sdp)}),toPlain=withKey(decrypt),toCipher=withKey(encrypt),sharedPeerMap=sharedPeers.getMap(appId);offerPool||(offerPool=new OfferPool(()=>peer_default(!0,config)));const pool2=offerPool,encryptOffer=async peer=>{const plainOffer=await peer.getOffer(Date.now()-peer.created>offerTtl);if(!plainOffer||"offer"!==plainOffer.type)throw mkErr("failed to get offer for peer");return(await toCipher(plainOffer)).sdp},attachSharedPeerToRoom=(peerId,shared)=>{const state2=getState(ctx.peerStates,peerId);state2.answeringExpiryTimer=resetTimer(state2.answeringExpiryTimer);state2.answeringPeer=null;const{proxy:proxy2,isNew}=sharedPeers.bind(roomId,roomNamespacePromise,shared,{onDetach:()=>{const current=ctx.peerStates[peerId];if((null==current?void 0:current.connectedPeer)===shared.peer){current.connectedPeer=null;current.connectedPeerUnhealthySinceMs=null;updateStatus(current)}}});state2.connectedPeer=shared.peer;state2.connectedPeerUnhealthySinceMs=null;updateStatus(state2);isNew&&onPeerConnect(proxy2,peerId);resetOfferState(state2,pool2)},isPassive=Boolean(config.passive);let passiveActivationTimeout,roomRegistration=null,deactivateRelayAnnouncements=noOp;const checkDeactivate=()=>{if(!isPassive||!ctx.isActive)return;let hasActiveWork=!1;entries(ctx.peerStates).forEach(([peerId,state2])=>{state2.connectedPeer||state2.answeringPeer||state2.offerInitPromise||state2.offerPeer||state2.offerRelays.some(Boolean)?hasActiveWork=!0:"idle"===state2.status&&delete ctx.peerStates[peerId]});if(!hasActiveWork){ctx.isActive=!1;passiveActivationTimeout=resetTimer(passiveActivationTimeout);announceTimeouts.forEach(resetTimer);announceTimeouts.length=0;deactivateRelayAnnouncements();(null==roomRegistration?void 0:roomRegistration.roomToken)&&advertiseRoomPresenceToAll(appId,roomRegistration.roomToken,!1)}},ctx={appId,roomId,config,peerStates:{},rootTopicPlaintext,rootTopicP,selfTopicP,toPlain,toCipher,isLeaving:()=>didLeaveRoom,isPassive,isActive:!isPassive,onJoinError,sharedPeers,offerPool:pool2,encryptOffer,initPeer:peer_default,connectPeer:(peer,peerId,_relayId)=>{if(didLeaveRoom){peer.destroy();return}const state2=getState(ctx.peerStates,peerId);if(state2.connectedPeer){const shared2=sharedPeerMap[peerId];if(shared2&&state2.connectedPeer===shared2.peer&&shared2.bindings[roomId])return;state2.connectedPeer===peer||peer.isDead||peer.destroy();return}let shared=sharedPeerMap[peerId];if(shared&&"stale"===sharedPeers.getHealth(shared.peer)){sharedPeers.clear(appId,peerId,{destroyPeer:!0});shared=void 0}if(shared&&shared.peer!==peer){peer.isDead||peer.destroy();attachSharedPeerToRoom(peerId,shared);return}const isNewShared=!shared;shared||(shared=sharedPeers.register(appId,peerId,peer,sharedPeerIdleMs));attachSharedPeerToRoom(peerId,shared);isNewShared&&advertiseKnownRoomsToShared(appId,shared)},disconnectPeer:(peer,peerId)=>{if(didLeaveRoom)return;const state2=ctx.peerStates[peerId];if((null==state2?void 0:state2.connectedPeer)===peer){clearConnectedPeer(state2,peerId,"close-event");checkDeactivate()}},attachSharedPeerToRoom,checkDeactivate,announceIntervals:[],announceIntervalMs},strategyContext={config,appId,roomId,isPassive},handleMessage=createSignalHandler(ctx);if(!didInit){const initRes=init3(config);initPromises=(Array.isArray(initRes)?initRes:[initRes]).map(value=>Promise.resolve(value));didInit=!0;cleanupWatchOnline=(null==(_d2=config.relayConfig)?void 0:_d2.manualReconnection)?noOp:watchOnline()}isPassive||pool2.isActive||pool2.warmup();ctx.announceIntervals=initPromises.map(()=>announceIntervalMs);const announceAttemptCounts=initPromises.map(()=>0),announceErrorStreaks=initPromises.map(()=>0),announceTimeouts=[],unsubFns=initPromises.map(async(relayP,i3)=>subscribe2(await relayP,await rootTopicP,await selfTopicP,handleMessage(i3),n3=>pool2.getOffers(n3,encryptOffer),strategyContext));all([rootTopicP,selfTopicP]).then(([rootTopic,selfTopic])=>{if(didLeaveRoom)return;const queueAnnounce=async(relay,i3)=>{var _a14,_b7,_c4,_d3;if(didLeaveRoom)return;if(isPassive&&!ctx.isActive)return;const extra=isPassive?{passive:!0}:void 0;let ms;try{ms=await announce(relay,rootTopic,selfTopic,extra,strategyContext);announceErrorStreaks[i3]=0}catch(error){const errorStreak=null!=(_a14=announceErrorStreaks[i3])?_a14:0;0===errorStreak&&!1!==(null==(_b7=config.relayConfig)?void 0:_b7.warnOnRelayFailure)&&console.warn(`${libName}: announce failed - ${toErrorMessage(error,"")}`);announceErrorStreaks[i3]=errorStreak+1}if(didLeaveRoom||isPassive&&!ctx.isActive)return;"number"==typeof ms&&(ctx.announceIntervals[i3]=ms);const announceAttempt=null!=(_c4=announceAttemptCounts[i3])?_c4:0;announceAttemptCounts[i3]=announceAttempt+1;const currentInterval=null!=(_d3=ctx.announceIntervals[i3])?_d3:announceIntervalMs,warmupDelay=announceWarmupIntervalsMs[announceAttempt];announceTimeouts[i3]=setTimeout(()=>{queueAnnounce(relay,i3)},"number"==typeof warmupDelay?Math.min(currentInterval,warmupDelay):currentInterval)};deactivateRelayAnnouncements=()=>{deactivate&&initPromises.forEach(async relayP=>{const relay=await relayP;didLeaveRoom||deactivate(relay,rootTopic,selfTopic,strategyContext)})};ctx.requeueAnnounce=()=>{announceTimeouts.forEach(resetTimer);announceTimeouts.length=0;passiveActivationTimeout=resetTimer(passiveActivationTimeout);pool2.isActive||pool2.warmup();(null==roomRegistration?void 0:roomRegistration.roomToken)&&advertiseRoomPresenceToAll(appId,roomRegistration.roomToken,!0);passiveActivationTimeout=setTimeout(checkDeactivate,passiveActivationGraceMs);initPromises.forEach(async(relayP,i3)=>{const relay=await relayP;if(relay&&!didLeaveRoom){announceAttemptCounts[i3]=0;queueAnnounce(relay,i3)}})};unsubFns.forEach(async(didSub,i3)=>{await didSub;if(didLeaveRoom)return;const relay=await initPromises[i3];!relay||didLeaveRoom||isPassive&&!ctx.isActive||queueAnnounce(relay,i3)})});let onPeerConnect=noOp;const{compose}=createPasswordHandshake(null!=(_e2=config.password)?_e2:"",appId,roomId),composedPeerHandshake=compose(onPeerHandshake),roomOptions={...composedPeerHandshake?{onPeerHandshake:composedPeerHandshake}:{},...void 0===handshakeTimeoutMs?{}:{handshakeTimeoutMs},isPassive,onHandshakeError:(peerId,error)=>null==onJoinError?void 0:onJoinError({error:error.replace(/^handshake failed: /,""),appId,peerId,roomId})};null!=occupiedRooms[appId]||(occupiedRooms[appId]={});const appRoomRegistrations=getRoomRegistrations(appId),joinedRoom=room_default(f4=>onPeerConnect=f4,id=>{if(didLeaveRoom)return;const state2=ctx.peerStates[id];if(null==state2?void 0:state2.connectedPeer){state2.connectedPeer=null;updateStatus(state2);checkDeactivate()}},()=>{var _a14,_b7;didLeaveRoom=!0;onPeerConnect=noOp;const registration=null==(_a14=roomRegistrations[appId])?void 0:_a14[roomId];if(null==registration?void 0:registration.roomToken){advertiseRoomPresenceToAll(appId,registration.roomToken,!1);null==(_b7=roomIdsByToken[appId])||delete _b7[registration.roomToken];roomIdsByToken[appId]&&!keys(roomIdsByToken[appId]).length&&delete roomIdsByToken[appId]}if(roomRegistrations[appId]){delete roomRegistrations[appId][roomId];keys(roomRegistrations[appId]).length||delete roomRegistrations[appId]}entries(ctx.peerStates).forEach(([peerId,state2])=>{state2.answeringExpiryTimer=resetTimer(state2.answeringExpiryTimer);if(state2.connectedPeer&&!state2.connectedPeer.isDead){const shared=sharedPeerMap[peerId];shared&&shared.peer===state2.connectedPeer||state2.connectedPeer.destroy()}state2.answeringPeer&&!state2.answeringPeer.isDead&&state2.answeringPeer.destroy();resetOfferState(state2,pool2);state2.connectedPeer=null;state2.answeringPeer=null;updateStatus(state2)});if(occupiedRooms[appId]){delete occupiedRooms[appId][roomId];0===keys(occupiedRooms[appId]).length&&delete occupiedRooms[appId]}announceTimeouts.forEach(resetTimer);passiveActivationTimeout=resetTimer(passiveActivationTimeout);unsubFns.forEach(async f4=>{(await f4)()});if(!hasActiveRooms()){didInit=!1;pool2.destroy();offerPool=null;cleanupWatchOnline();cleanupRoomPresenceHandler(appId)}},roomOptions);roomRegistration={roomToken:null,roomTokenPromise:roomNamespacePromise,attachSharedPeerToRoom,shouldAdvertise:()=>!isPassive||ctx.isActive};appRoomRegistrations[roomId]=roomRegistration;roomNamespacePromise.then(roomToken=>{var _a14;const registration=roomRegistration;if(registration&&!didLeaveRoom&&(null==(_a14=roomRegistrations[appId])?void 0:_a14[roomId])===registration){registration.roomToken=roomToken;getRoomIdsByToken(appId)[roomToken]=roomId;values(sharedPeerMap).forEach(shared=>{shared.remoteRoomTokens.has(roomToken)&&attachSharedPeerToRoom(shared.peerId,shared)});isPassive&&!ctx.isActive||advertiseRoomPresenceToAll(appId,roomToken,!0)}});return occupiedRooms[appId][roomId]=joinedRoom}};signalKeys2=["offer","answer","candidate"];toPayload2=msg=>{if("string"==typeof msg)try{const parsed=fromJson(msg);return parsed&&"object"==typeof parsed?parsed:null}catch(e3){return null}return msg};getString2=(payload,key3)=>"string"==typeof payload[key3]&&payload[key3]?payload[key3]:void 0;hasInvalidSignalField2=payload=>signalKeys2.some(key3=>key3 in payload&&("string"!=typeof payload[key3]||""===payload[key3]));shouldActivatePassiveRoom=msg=>{const payload=toPayload2(msg);if(!payload||hasInvalidSignalField2(payload))return!1;const peerId=getString2(payload,"peerId");return Boolean(peerId&&peerId!==selfId&&!0!==payload.passive&&!getString2(payload,"answer")&&!getString2(payload,"candidate"))};requireContext=context2=>{if(!context2)throw mkErr("topic strategy missing room context");return context2};subscriptionContext=(context2,kind,rootTopic,selfTopic)=>({kind,appId:context2.appId,roomId:context2.roomId,rootTopic,selfTopic});publishContext=(context2,kind,rootTopic,selfTopic)=>({kind,appId:context2.appId,roomId:context2.roomId,rootTopic,selfTopic});topic_strategy_default=({init:init3,subscribeTopic,publishTopic,unpublishTopic})=>strategy_default({init:init3,subscribe:async(relay,rootTopic,selfTopic,onMessage,_getOffers,rawContext)=>{const context2=requireContext(rawContext),signalPeer=(peerTopic,signal)=>publishTopic(relay,peerTopic,signal,publishContext(context2,"signal",rootTopic,selfTopic));let selfCleanup=null,selfCleanupDone=!1,selfSubscriptionP=null,didCleanup=!1;const cleanupSelf=cleanup=>{if(!selfCleanupDone){selfCleanupDone=!0;cleanup()}},ensureSelfSubscription=()=>{selfSubscriptionP||(selfSubscriptionP=Promise.resolve(subscribeTopic(relay,selfTopic,(topic,msg)=>{didCleanup||onMessage(topic,msg,signalPeer)},subscriptionContext(context2,"self",rootTopic,selfTopic))).then(cleanup=>{selfCleanup=cleanup;didCleanup&&cleanupSelf(cleanup)}));return selfSubscriptionP};context2.isPassive||await ensureSelfSubscription();const rootCleanup=await subscribeTopic(relay,rootTopic,async(topic,msg)=>{if(!didCleanup){context2.isPassive&&shouldActivatePassiveRoom(msg)&&await ensureSelfSubscription();didCleanup||await onMessage(topic,msg,signalPeer)}},subscriptionContext(context2,"root",rootTopic,selfTopic));return()=>{didCleanup=!0;selfCleanup&&cleanupSelf(selfCleanup);rootCleanup()}},announce:(relay,rootTopic,selfTopic,extraPayload,rawContext)=>{const context2=requireContext(rawContext);return publishTopic(relay,rootTopic,toJson({peerId:selfId,...extraPayload}),publishContext(context2,"announce",rootTopic,selfTopic))},...unpublishTopic?{deactivate:(relay,rootTopic,selfTopic,rawContext)=>unpublishTopic(relay,rootTopic,publishContext(requireContext(rawContext),"announce",rootTopic,selfTopic))}:{}});relayManager=createRelayManager(client=>client.socket);defaultRedundancy=5;tag2="x";eventMsgType="EVENT";var{secretKey,publicKey}=schnorr.keygen();pubkey=toHex(publicKey);subIdToTopic={};msgHandlers={};kindCache={};maxTopicsPerSubscription=250;now2=()=>Math.floor(Date.now()/1e3);topicToKind=topic=>{var _a13;return null!=(_a13=kindCache[topic])?_a13:kindCache[topic]=strToNum(topic,1e4)+2e4};createEvent=async(topic,content)=>{const payload={kind:topicToKind(topic),tags:[[tag2,topic]],created_at:now2(),content,pubkey},id=await hashWith("SHA-256",toJson([0,payload.pubkey,payload.created_at,payload.kind,payload.tags,payload.content]));return toJson([eventMsgType,{...payload,id:toHex(id),sig:toHex(await schnorr.signAsync(id,secretKey))}])};0;batchers={};batchAdd=(client,topic,handler)=>{var _a13,_b6;const batcher=null!=(_b6=batchers[_a13=client.url])?_b6:batchers[_a13]={subIds:[],topics:new Map,updateTimer:null};batcher.topics.set(topic,handler);scheduleBatchFlush(client,batcher)};batchRemove=(client,topic)=>{const batcher=batchers[client.url];if(batcher){batcher.topics.delete(topic);if(0===batcher.topics.size){if(null!==batcher.updateTimer){clearTimeout(batcher.updateTimer);batcher.updateTimer=null}batcher.subIds.forEach(subId=>client.send(toJson(["CLOSE",subId])));delete batchers[client.url]}else scheduleBatchFlush(client,batcher)}};scheduleBatchFlush=(client,batcher)=>{null===batcher.updateTimer&&(batcher.updateTimer=setTimeout(()=>{batcher.updateTimer=null;flushBatch(client)},0))};flushBatch=client=>{const batcher=batchers[client.url];if(!batcher||0===batcher.topics.size)return;const topics=[...batcher.topics.keys()],chunks=[],since=now2();for(let i3=0;i3<topics.length;i3+=maxTopicsPerSubscription)chunks.push(topics.slice(i3,i3+maxTopicsPerSubscription));for(;batcher.subIds.length>chunks.length;){const subId=batcher.subIds.pop();subId&&client.send(toJson(["CLOSE",subId]))}chunks.forEach((chunk,i3)=>{var _a13,_b6;const subId=null!=(_b6=(_a13=batcher.subIds)[i3])?_b6:_a13[i3]=genId(64);client.send(toJson(["REQ",subId,{kinds:[...new Set(chunk.map(topicToKind))],since,["#x"]:chunk}]))})};resubscribeOnReconnect=client=>{const batcher=batchers[client.url];batcher&&batcher.topics.size>0&&flushBatch(client)};joinRoom=topic_strategy_default({init:config=>getRelays(config,defaultRelayUrls,defaultRedundancy,!0).map(url=>{const client=relayManager.register(url,()=>makeSocket(url,data=>{var _a13,_b6,_c3;const[msgType,subId,payload,relayMsg]=fromJson(data);if(msgType!==eventMsgType){const prefix=`${libName}: relay failure from ${client.url} - `;!1!==(null==(_a13=config.relayConfig)?void 0:_a13.warnOnRelayFailure)&&("NOTICE"===msgType?console.warn(prefix+subId):"OK"!==msgType||payload||console.warn(prefix+relayMsg));return}if(payload&&"object"==typeof payload&&"content"in payload){const{content}=payload,handler=msgHandlers[subId];if(handler){handler(null!=(_b6=subIdToTopic[subId])?_b6:"",content);return}const batcher=batchers[client.url];if((null==batcher?void 0:batcher.subIds.includes(subId))&&payload.tags){const topicTag=payload.tags.find(t9=>t9[0]===tag2);(null==topicTag?void 0:topicTag[1])&&(null==(_c3=batcher.topics.get(topicTag[1]))||_c3(topicTag[1],content))}}},()=>resubscribeOnReconnect(client)));return client.ready}),subscribeTopic:(client,topic,onMessage)=>{batchAdd(client,topic,(topic2,data)=>{onMessage(topic2,data)});return()=>{batchRemove(client,topic)}},publishTopic:async(client,topic,msg)=>client.send(await createEvent(topic,"string"==typeof msg?msg:toJson(msg)))});getRelaySockets=relayManager.getSockets;defaultRelayUrls=["basspistol.org","bucket.coracle.social","chorus.almostmachines.dev","chorus.pjv.me","communities.nos.social","ftp.halifax.rwth-aachen.de/nostr","hol.is","hornetstorage.net/relay","koru.bitcointxoko.org","nos.lol","nostr-01.uid.ovh","nostr-01.yakihonne.com","nostr-relay.corb.net","nostr.data.haus","nostr.islandarea.net","nostr.sathoarder.com","nostr.self-determined.de","nostr.tegila.com.br","nostr.vulpem.com","purplerelay.com","relay-can.zombi.cloudrodion.com","relay-rpi.edufeed.org","relay.agorist.space","relay.angor.io","relay.artio.inf.unibe.ch","relay.binaryrobot.com","relay.damus.io","relay.froth.zone","relay.libernet.app","relay.mostr.pub","relay.mostro.network","relay.nostr.place","relay.nostrdice.com","relay.notoshi.win","relay.sigit.io","relay02.lnfi.network","relay2.angor.io","schnorr.me","slick.mjex.me","social.amanah.eblessing.co","staging.yabu.me","strfry.openhoofd.nl","strfry.shock.network","testnet-relay.samt.st","top.testrelay.top","x.kojira.io","yabu.me/v2"].map(url=>"wss://"+url);DIRECTION_REQUEST="request";DIRECTION_RESPONSE="response";DEFAULT_RPC_TIMEOUT=3e4;BULK_GET_RPC_TIMEOUT=4e4;ResponsePreventedError=class extends Error{constructor(message){super(`Response prevented: ${message}`)}};DeviceDecisions=(DeviceDecisions2=>{DeviceDecisions2.ACCEPT="accepted";DeviceDecisions2.REJECT="rejected";DeviceDecisions2.IGNORE="ignore";return DeviceDecisions2})(DeviceDecisions||{});0;0;StoredMapLike=class{constructor(store,prefix=""){__publicField(this,"_store");__publicField(this,"_cache",new Map);__publicField(this,"_prefix","");this._store=store}addPrefix(key3){return`${this._prefix}-${key3}`}async get(key3){if(this._cache.has(key3))return this._cache.get(key3);const value=await this._store.get(this.addPrefix(key3));void 0!==value&&this._cache.set(key3,value);return value}async set(key3,value){try{const ret=await this._store.set(this.addPrefix(key3),value);this._cache.set(key3,value);return ret}catch(e3){this._cache.delete(key3);throw e3}}async delete(key3){try{const ret=await this._store.delete(this.addPrefix(key3));this._cache.delete(key3);return ret}catch(e3){this._cache.delete(key3);throw e3}}async has(key3){if(this._cache.has(key3))return!0;const e3=await this._store.keys(this.addPrefix(key3),key3);return e3.length>0}};DB_METHODS=new Set(["info","changes","revsDiff","bulkDocs","bulkGet","put","get"]);TrysteroReplicatorP2PClient=class{constructor(server,connectedPeerId){__publicField(this,"_server");__publicField(this,"_connectedPeerId");__publicField(this,"_remoteDB");this._server=server;this._connectedPeerId=connectedPeerId;this._remoteDB=this._bindRemoteDB()}get remoteDB(){return this._remoteDB}_bindRemoteDB(){return{info:this.bindRemoteFunction("info"),changes:this.bindRemoteFunction("changes"),revsDiff:this.bindRemoteFunction("revsDiff"),bulkDocs:this.bindRemoteFunction("bulkDocs"),bulkGet:this.bindRemoteFunction("bulkGet",BULK_GET_RPC_TIMEOUT),put:this.bindRemoteFunction("put"),get:this.bindRemoteFunction("get")}}_sendRPC(type,args,timeout=DEFAULT_RPC_TIMEOUT){var _a13;const room=null==(_a13=this._server)?void 0:_a13.rpcRoom;if(!room)throw new Error("Not connected to any room");const session=room.session(this._connectedPeerId);return session.call(toRpcMethodName(type),args,timeout)}__onResponse(_data2){}bindRemoteFunction(type,timeout=DEFAULT_RPC_TIMEOUT){return async(...args)=>{var _a13;const room=null==(_a13=this._server)?void 0:_a13.rpcRoom;if(!room)throw new Error("Not connected to any room");return await room.session(this._connectedPeerId).call(toRpcMethodName(type),args,timeout)}}async invokeRemoteFunction(type,args,timeout=DEFAULT_RPC_TIMEOUT){var _a13;const room=null==(_a13=this._server)?void 0:_a13.rpcRoom;if(!room)throw new Error("Not connected to any room");return await room.session(this._connectedPeerId).call(toRpcMethodName(type),args,timeout)}bindRemoteObjectFunctions(key3,timeout=DEFAULT_RPC_TIMEOUT){return async(...args)=>{var _a13;const room=null==(_a13=this._server)?void 0:_a13.rpcRoom;if(!room)throw new Error("Not connected to any room");return await room.session(this._connectedPeerId).call(toRpcMethodName(key3.toString()),args,timeout)}}async invokeRemoteObjectFunction(key3,args,timeout=DEFAULT_RPC_TIMEOUT){var _a13;const room=null==(_a13=this._server)?void 0:_a13.rpcRoom;if(!room)throw new Error("Not connected to any room");return await room.session(this._connectedPeerId).call(toRpcMethodName(key3.toString()),args,timeout)}close(){this._remoteDB=void 0;this._server=void 0}};Computed=class{constructor(params){Object.defineProperty(this,"_previousArgs",{enumerable:!0,configurable:!0,writable:!0,value:null});Object.defineProperty(this,"_previousResult",{enumerable:!0,configurable:!0,writable:!0,value:null});Object.defineProperty(this,"_evaluation",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_isEqual",{enumerable:!0,configurable:!0,writable:!0,value:(a2,b3)=>this._areArgsEqual(a2,b3)});Object.defineProperty(this,"_shouldForceUpdate",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_updating",{enumerable:!0,configurable:!0,writable:!0,value:Promise.resolve()});this._evaluation=params.evaluation;this._shouldForceUpdate=params.requiresUpdate||(()=>!1);params.isEqual&&(this._isEqual=params.isEqual)}updateValue(...args){return new Promise((resolve,reject)=>{this._updating=this._updating.then(async()=>{try{const forceUpdate=await this._shouldForceUpdate(args,this._previousArgs,this._previousResult);if(!forceUpdate&&this._previousArgs&&this._isEqual(args,this._previousArgs))return resolve(!1);try{this._previousResult=await this._evaluation(...args)}catch(error){const err3=error instanceof Error?error:new Error(String(error));this._previousResult=err3}finally{this._previousArgs=args}return resolve(!0)}catch(error){return reject(error)}})})}reset(){this._previousArgs=null;this._previousResult=null}async update(...args){await this.updateValue(...args);return this}get value(){if(this._previousResult instanceof Error)throw this._previousResult;return this._previousResult}_areArgsEqual(args1,args2){return JSON.stringify(args1)===JSON.stringify(args2)}};encoder2=new TextEncoder;IncomingChunkBuffer=class{constructor(total){__publicField(this,"total");__publicField(this,"parts",new Map);this.total=total}add(index6,payload){index6<0||index6>=this.total||this.parts.set(index6,payload)}missingIndices(){const missing=[];for(let i3=0;i3<this.total;i3++)this.parts.has(i3)||missing.push(i3);return missing}isComplete(){return this.parts.size===this.total}toPayload(){let acc="";for(let i3=0;i3<this.total;i3++){const part=this.parts.get(i3);if(void 0===part)throw new Error(`Missing chunk ${i3}`);acc+=part}return acc}};RpcError=class extends Error{constructor(code,message,details){super(message);__publicField(this,"code");__publicField(this,"details");this.name="RpcError";this.code=code;this.details=details}toShape(){return{code:this.code,message:this.message,details:this.details}}};RpcSession=class{constructor(room,peerId){__publicField(this,"peerId");__publicField(this,"room");this.room=room;this.peerId=peerId}async call(method,args=[],timeoutMs){if(!this.peerId)throw new RpcError("NOT_CONNECTED","Peer is not connected");return await this.room.invoke(this.peerId,method,args,timeoutMs)}createProxy(namespace){const session=this;return new Proxy({},{get(_target,propKey){if("string"==typeof propKey)return async(...args)=>await session.call(`${namespace}.${propKey}`,args)}})}};RPC_VERSION_MAJOR=1;RPC_VERSION_MINOR=0;RpcRoom=class{constructor(options){__publicField(this,"options");__publicField(this,"pending",new Map);__publicField(this,"inboundCalls",new Map);__publicField(this,"methods",new Map);__publicField(this,"sessions",new Map);__publicField(this,"outgoingChunkMap",new Map);__publicField(this,"incomingChunkMap",new Map);__publicField(this,"incomingChunkTimers",new Map);__publicField(this,"peerVersion",new Map);__publicField(this,"disposers",[]);var _a13,_b6;this.options={maxWirePayloadBytes:null!=(_a13=options.maxWirePayloadBytes)?_a13:32768,chunkMissingRetryMs:null!=(_b6=options.chunkMissingRetryMs)?_b6:350,...options};this.disposers.push(this.options.transport.onMessage((msg,peerId)=>{this.onWireMessage(msg,peerId)}));this.options.transport.onPeerJoin&&this.disposers.push(this.options.transport.onPeerJoin(peerId=>{this.sendEnvelope(peerId,{kind:"handshake",versionMajor:RPC_VERSION_MAJOR,versionMinor:RPC_VERSION_MINOR})}));this.options.transport.onPeerLeave&&this.disposers.push(this.options.transport.onPeerLeave(peerId=>{this.sessions.delete(peerId);this.peerVersion.delete(peerId)}))}close(){this.disposers.splice(0).forEach(dispose=>dispose());this.pending.forEach(pending3=>pending3.reject(new RpcError("NOT_CONNECTED","Room closed")));this.pending.clear();this.inboundCalls.clear();this.methods.clear();this.sessions.clear();this.outgoingChunkMap.clear();this.incomingChunkMap.clear();this.incomingChunkTimers.forEach(h3=>compatGlobal.clearTimeout(h3));this.incomingChunkTimers.clear()}session(peerId){const existing=this.sessions.get(peerId);if(existing)return existing;const s2=new RpcSession(this,peerId);this.sessions.set(peerId,s2);return s2}register(method,handler,options={}){var _a13;if(!validNamespacedMethod(method))throw new RpcError("PROTOCOL_ERROR",`Method must be namespaced: ${method}`);this.methods.set(method,{handler,serial:null!=(_a13=options.serial)&&_a13,queue:Promise.resolve()})}async invoke(peerId,method,args,timeoutMs=3e4){if(!validNamespacedMethod(method))throw new RpcError("PROTOCOL_ERROR",`Method must be namespaced: ${method}`);const requestId=newId("req"),p2=new Promise((resolve,reject)=>{const pending3={resolve,reject};timeoutMs>0&&(pending3.timeoutHandle=compatGlobal.setTimeout(()=>{this.pending.delete(requestId);reject(new RpcError("TIMEOUT",`RPC timed out: ${method}`))},timeoutMs));this.pending.set(requestId,pending3)});await this.sendEnvelope(peerId,{kind:"request",requestId,method,args});return await p2}async cancel(peerId,requestId){await this.sendEnvelope(peerId,{kind:"cancel",requestId})}async sendEnvelope(peerId,envelope){const serialized2=JSON.stringify(envelope);if(estimateBytes(serialized2)<=this.options.maxWirePayloadBytes){await this.options.transport.send({wire:"raw",payload:serialized2},peerId);return}const streamId=newId("stream"),chunks=splitIntoChunks(serialized2,this.options.maxWirePayloadBytes);this.outgoingChunkMap.set(streamId,{peerId,chunks});for(let i3=0;i3<chunks.length;i3++)await this.options.transport.send({wire:"chunk",streamId,index:i3,total:chunks.length,payload:chunks[i3]},peerId)}scheduleMissingAck(streamId,peerId){const existing=this.incomingChunkTimers.get(streamId);existing&&compatGlobal.clearTimeout(existing);const handle=compatGlobal.setTimeout(()=>{const state2=this.incomingChunkMap.get(streamId);if(!state2||state2.isComplete())return;const missing=state2.missingIndices();this.options.transport.send({wire:"chunk-ack",streamId,missing},peerId)},this.options.chunkMissingRetryMs);this.incomingChunkTimers.set(streamId,handle)}async onWireMessage(message,peerId){if("raw"===message.wire){await this.onEnvelopePayload(message.payload,peerId);return}if("chunk"===message.wire){let state22=this.incomingChunkMap.get(message.streamId);if(!state22){state22=new IncomingChunkBuffer(message.total);this.incomingChunkMap.set(message.streamId,state22)}state22.add(message.index,message.payload);this.scheduleMissingAck(message.streamId,peerId);if(state22.isComplete()){const timer=this.incomingChunkTimers.get(message.streamId);timer&&compatGlobal.clearTimeout(timer);this.incomingChunkTimers.delete(message.streamId);this.incomingChunkMap.delete(message.streamId);await this.options.transport.send({wire:"chunk-ack",streamId:message.streamId,missing:[]},peerId);await this.onEnvelopePayload(state22.toPayload(),peerId)}return}const state2=this.outgoingChunkMap.get(message.streamId);if(state2)if(0!==message.missing.length)for(const index6 of message.missing){const payload=state2.chunks[index6];void 0!==payload&&await this.options.transport.send({wire:"chunk",streamId:message.streamId,index:index6,total:state2.chunks.length,payload},state2.peerId)}else this.outgoingChunkMap.delete(message.streamId)}async onEnvelopePayload(payload,peerId){var _a13,_b6,_c3,_d2,_e2,_f,_g,_h2,_i2,_j;let envelope;try{envelope=JSON.parse(payload)}catch(ex){null==(_b6=(_a13=this.options).onProtocolWarning)||_b6.call(_a13,"Invalid payload",peerId);null==(_d2=(_c3=this.options).onProtocolWarning)||_d2.call(_c3,String(ex),peerId);return}if("handshake"===envelope.kind){this.peerVersion.set(peerId,{major:envelope.versionMajor,minor:envelope.versionMinor});envelope.versionMajor!==RPC_VERSION_MAJOR&&(null==(_f=(_e2=this.options).onProtocolWarning)||_f.call(_e2,`RPC major mismatch: local=${RPC_VERSION_MAJOR}, remote=${envelope.versionMajor}`,peerId));return}if("cancel"===envelope.kind){const ctx2=this.inboundCalls.get(envelope.requestId);ctx2&&(ctx2.cancelled=!0);return}if("response"===envelope.kind){const pending3=this.pending.get(envelope.requestId);if(!pending3)return;this.pending.delete(envelope.requestId);pending3.timeoutHandle&&compatGlobal.clearTimeout(pending3.timeoutHandle);!0===envelope.ok?pending3.resolve(envelope.data):pending3.reject(new RpcError(envelope.error.code,envelope.error.message,envelope.error.details));return}const accepted=await(null==(_h2=(_g=this.options).canAcceptRequest)?void 0:_h2.call(_g,peerId,envelope.method));if(!1===accepted)return;const version2=this.peerVersion.get(peerId);if(version2&&version2.major!==RPC_VERSION_MAJOR){await this.sendEnvelope(peerId,{kind:"response",requestId:envelope.requestId,ok:!1,error:{code:"REMOTE_ERROR",message:`RPC major mismatch: local=${RPC_VERSION_MAJOR}, remote=${version2.major}`}});return}version2&&version2.minor!==RPC_VERSION_MINOR&&(null==(_j=(_i2=this.options).onProtocolWarning)||_j.call(_i2,`RPC minor mismatch: local=${RPC_VERSION_MINOR}, remote=${version2.minor}`,peerId));const method=this.methods.get(envelope.method);if(!method){await this.sendEnvelope(peerId,{kind:"response",requestId:envelope.requestId,ok:!1,error:{code:"REMOTE_ERROR",message:`Method not found: ${envelope.method}`}});return}const ctx={cancelled:!1};this.inboundCalls.set(envelope.requestId,ctx);const runner=async()=>{try{if(ctx.cancelled)throw new RpcError("CANCELLED","Invocation cancelled");const data=await method.handler(peerId,...envelope.args);if(ctx.cancelled)throw new RpcError("CANCELLED","Invocation cancelled");await this.sendEnvelope(peerId,{kind:"response",requestId:envelope.requestId,ok:!0,data})}catch(ex){await this.sendEnvelope(peerId,{kind:"response",requestId:envelope.requestId,ok:!1,error:asRpcErrorShape(ex)})}finally{this.inboundCalls.delete(envelope.requestId)}};if(method.serial){method.queue=method.queue.then(runner,runner);await method.queue}else await runner()}};import_events6=__toESM(require_events(),1);noopActiveTasks={add:_task=>null,get:_id=>null,update:(_id,_update)=>{},remove:(_id,_err)=>{},list:()=>[]};(class extends import_events6.default{constructor(session,name,ns="pdb"){super();__publicField(this,"name");__publicField(this,"activeTasks",noopActiveTasks);__publicField(this,"session");__publicField(this,"ns");this.session=session;this.name=name;this.ns=ns}async callDB(method,args=[]){try{return await this.session.call(`${this.ns}.${method}`,args)}catch(err3){if(err3 instanceof RpcError&&"REMOTE_ERROR"===err3.code){const d4=err3.details;if((null==d4?void 0:d4.name)||(null==d4?void 0:d4.status)){const pouchErr=new Error(err3.message);d4.name&&(pouchErr.name=d4.name);d4.status&&(pouchErr.status=d4.status);d4.reason&&(pouchErr.reason=d4.reason);throw pouchErr}}throw err3}}info(){return this.callDB("info")}id(){return this.callDB("id")}changes(opts){const emitter=new import_events6.default;let cancelled=!1;const promise=this.callDB("changes",[{...opts,live:!1}]).then(info3=>{var _a13;if(cancelled)return info3;for(const change of null!=(_a13=info3.results)?_a13:[]){if(cancelled)break;emitter.emit("change",change)}cancelled||emitter.emit("complete",info3);return info3});promise.catch(err3=>{cancelled||emitter.emit("error",err3)});emitter.cancel=()=>{cancelled=!0;emitter.removeAllListeners()};emitter.then=(onfulfilled,onrejected)=>promise.then(onfulfilled,onrejected);emitter.catch=onrejected=>promise.catch(onrejected);return emitter}get(id,opts){return this.callDB("get",[id,null!=opts?opts:{}])}put(doc,opts){return this.callDB("put",[doc,null!=opts?opts:{}])}bulkGet(opts){return this.callDB("bulkGet",[opts])}bulkDocs(docs,opts){return this.callDB("bulkDocs",[docs,null!=opts?opts:{}])}revsDiff(diff){return this.callDB("revsDiff",[diff])}allDocs(opts){return this.callDB("allDocs",[null!=opts?opts:{}])}});PROXY_SCHEME="https";ConnectionStringParser=class{static parse(uriString){const match3=uriString.match(/^sls\+([^:]+):/);if(!match3)throw new Error(`Unsupported URI: ${uriString}`);const subscheme=match3[1];if("p2p"===subscheme)return{type:"p2p",settings:this.parseP2P(uriString)};const{url}=parseSlsUri(uriString);switch(subscheme){case"http":case"https":return{type:"couchdb",settings:this.parseCouchDB(url,subscheme)};case"s3":return{type:"s3",settings:this.parseS3(url)};default:throw new Error(`Unsupported protocol: sls+${subscheme}`)}}static serialize(config){switch(config.type){case"couchdb":return this.serializeCouchDB(config.settings);case"s3":return this.serializeS3(config.settings);case"p2p":return this.serializeP2P(config.settings);default:throw new Error(`Unsupported type: ${config.type}`)}}static parseCouchDB(url,originalScheme){return{couchDB_URI:`${originalScheme}://${url.host}${"/"===url.pathname?"":url.pathname}`,couchDB_USER:decodeURIComponent(url.username),couchDB_PASSWORD:decodeURIComponent(url.password),couchDB_DBNAME:url.searchParams.get("db")||"",couchDB_CustomHeaders:url.searchParams.get("headers")||"",useJWT:"true"===url.searchParams.get("useJWT"),jwtAlgorithm:url.searchParams.get("jwtAlg")||"",jwtKey:url.searchParams.get("jwtKey")||"",jwtKid:url.searchParams.get("jwtKid")||"",jwtSub:url.searchParams.get("jwtSub")||"",jwtExpDuration:parseInt(url.searchParams.get("jwtExp")||"5"),useRequestAPI:"true"===url.searchParams.get("useRequestAPI")}}static serializeCouchDB(settings){const url=new URL(settings.couchDB_URI),subscheme=url.protocol.replace(":",""),newUrl=new URL(`${PROXY_SCHEME}://${url.host}${url.pathname}`);newUrl.username=encodeURIComponent(settings.couchDB_USER);newUrl.password=encodeURIComponent(settings.couchDB_PASSWORD);newUrl.searchParams.set("db",settings.couchDB_DBNAME);settings.couchDB_CustomHeaders&&newUrl.searchParams.set("headers",settings.couchDB_CustomHeaders);if(settings.useJWT){newUrl.searchParams.set("useJWT","true");newUrl.searchParams.set("jwtAlg",settings.jwtAlgorithm);settings.jwtKey&&newUrl.searchParams.set("jwtKey",settings.jwtKey);settings.jwtKid&&newUrl.searchParams.set("jwtKid",settings.jwtKid);settings.jwtSub&&newUrl.searchParams.set("jwtSub",settings.jwtSub);newUrl.searchParams.set("jwtExp",`${settings.jwtExpDuration||5}`)}settings.useRequestAPI&&newUrl.searchParams.set("useRequestAPI","true");return withSlsScheme(newUrl,subscheme)}static parseS3(url){const endpoint=url.searchParams.get("endpoint")||`https://${url.host}`;return{accessKey:decodeURIComponent(url.username),secretKey:decodeURIComponent(url.password),endpoint,bucket:url.searchParams.get("bucket")||"",region:url.searchParams.get("region")||"auto",bucketPrefix:url.searchParams.get("prefix")||"",useCustomRequestHandler:"true"===url.searchParams.get("useProxy"),bucketCustomHeaders:url.searchParams.get("headers")||"",forcePathStyle:"false"!==url.searchParams.get("pathStyle")}}static serializeS3(settings){const url=new URL(settings.endpoint),newUrl=new URL(`${PROXY_SCHEME}://${url.host}`);newUrl.username=encodeURIComponent(settings.accessKey);newUrl.password=encodeURIComponent(settings.secretKey);newUrl.searchParams.set("endpoint",settings.endpoint);newUrl.searchParams.set("bucket",settings.bucket);newUrl.searchParams.set("region",settings.region);settings.bucketPrefix&&newUrl.searchParams.set("prefix",settings.bucketPrefix);settings.bucketCustomHeaders&&newUrl.searchParams.set("headers",settings.bucketCustomHeaders);settings.useCustomRequestHandler&&newUrl.searchParams.set("useProxy","true");settings.forcePathStyle||newUrl.searchParams.set("pathStyle","false");return withSlsScheme(newUrl,"s3")}static parseP2P(uriString){const match3=uriString.match(/^sls\+p2p:\/\/([^?#]+)(?:\?([^#]*))?(?:#(.*))?$/);if(!match3)throw new Error(`Invalid P2P URI: ${uriString}`);const authority=match3[1],queryString=match3[2]||"";let userinfo="",host=authority;const lastAtIndex=authority.lastIndexOf("@");if(-1!==lastAtIndex){userinfo=authority.slice(0,lastAtIndex);host=authority.slice(lastAtIndex+1)}let password="";if(userinfo){const colonIndex=userinfo.indexOf(":");-1!==colonIndex&&(password=userinfo.slice(colonIndex+1))}const searchParams=new URLSearchParams(queryString);return{P2P_Enabled:"false"!==searchParams.get("enabled"),P2P_roomID:decodeURIComponent(host),P2P_passphrase:decodeURIComponent(password),P2P_relays:searchParams.get("relays")||"",P2P_AppID:searchParams.get("appId")||"self-hosted-livesync",P2P_AutoStart:"true"===searchParams.get("autoStart"),P2P_AutoBroadcast:"true"===searchParams.get("autoBroadcast"),P2P_turnServers:searchParams.get("turnServers")||"",P2P_turnUsername:searchParams.get("turnUser")||"",P2P_turnCredential:searchParams.get("turnPass")||"",P2P_maxWirePayloadBytes:normaliseP2PMaxWirePayloadBytes(Number(searchParams.get("maxWirePayloadBytes"))),P2P_connectionPath:normaliseP2PConnectionPath(searchParams.get("connectionPath"))}}static serializeP2P(settings){const searchParams=new URLSearchParams;settings.P2P_Enabled||searchParams.set("enabled","false");searchParams.set("relays",settings.P2P_relays);searchParams.set("appId",settings.P2P_AppID);settings.P2P_AutoStart&&searchParams.set("autoStart","true");settings.P2P_AutoBroadcast&&searchParams.set("autoBroadcast","true");settings.P2P_turnServers&&searchParams.set("turnServers",settings.P2P_turnServers);settings.P2P_turnUsername&&searchParams.set("turnUser",settings.P2P_turnUsername);settings.P2P_turnCredential&&searchParams.set("turnPass",settings.P2P_turnCredential);searchParams.set("maxWirePayloadBytes",String(normaliseP2PMaxWirePayloadBytes(settings.P2P_maxWirePayloadBytes)));searchParams.set("connectionPath",normaliseP2PConnectionPath(settings.P2P_connectionPath));const credentials=settings.P2P_passphrase?`:${encodeURIComponent(settings.P2P_passphrase)}@`:"",host=encodeURIComponent(settings.P2P_roomID),query3=searchParams.toString()?`?${searchParams.toString()}`:"";return`sls+p2p://${credentials}${host}${query3}`}};epochFNV1a=2166136261;c1=3432918353;c2=461845907;r1=15;r2=13;m=5;n=3864292196;new TextEncoder;DiagRTCFailureReasonCodes_ICE_GATHERING_NOT_COMPLETED="ICE_GATHERING_NOT_COMPLETED",DiagRTCFailureReasonCodes_ICE_CONNECTIVITY_FAILED="ICE_CONNECTIVITY_FAILED",DiagRTCFailureReasonCodes_STUN_REQUEST_TIMEOUT="STUN_REQUEST_TIMEOUT",DiagRTCFailureReasonCodes_SIGNALING_NOT_STABLE="SIGNALING_NOT_STABLE",DiagRTCFailureReasonCodes_CONNECTION_DROPPED_AFTER_ESTABLISHED="CONNECTION_DROPPED_AFTER_ESTABLISHED",DiagRTCFailureReasonCodes_NETWORK_INTERRUPTED="NETWORK_INTERRUPTED",DiagRTCFailureReasonCodes_UNKNOWN="UNKNOWN";rtcInstanceCounter=0;totalNewConnections=0;totalFailedConnections=0;totalSuccessfulConnections=0;totalClosedConnections=0;RTCConnectionStatuses=new Map;connectionStatusSubscribers=[];failureDiagnosisSubscribers=[];subscribersByRoom=new WeakMap;0;0;TRYSTERO_RPC_DEFAULTS={maxWirePayloadBytes:15360,chunkMissingRetryMs:150};EVENT_SERVER_STATUS="p2p-server-status";0;0;EVENT_ADVERTISEMENT_RECEIVED="p2p-advertisement-received";EVENT_DEVICE_LEAVED="p2p-device-leaved";EVENT_REQUEST_STATUS="p2p-request-status";0;EVENT_P2P_CONNECTED="p2p-connected";EVENT_P2P_DISCONNECTED="p2p-disconnected";EVENT_P2P_REPLICATOR_STATUS="p2p-replicator-status";EVENT_P2P_REPLICATOR_PROGRESS="p2p-replicator-progress";TrysteroReplicatorP2PServer=class{constructor(env,_serverPeerId=selfId){__publicField(this,"_env");__publicField(this,"_room");__publicField(this,"_serverPeerId");__publicField(this,"_activeRoomId","");__publicField(this,"___send");__publicField(this,"assignedFunctions",new Map);__publicField(this,"clients",new Map);__publicField(this,"_bindingObjects",[]);__publicField(this,"_rpcRoom");__publicField(this,"_peerStatusEventCleanup");__publicField(this,"_peerFailureAnalysisCleanup");__publicField(this,"_diagStats",{totalNewConnections:0,totalFailedConnections:0,totalSuccessfulConnections:0,totalClosedConnections:0,details:{}});__publicField(this,"_sendAdvertisement");__publicField(this,"_knownAdvertisements",new Map);__publicField(this,"acceptedPeers");__publicField(this,"temporaryAcceptedPeers",new Map);__publicField(this,"_acceptablePeers",new Computed({evaluation:settings=>{var _a13;return`${null!=(_a13=null==settings?void 0:settings.P2P_AutoAcceptingPeers)?_a13:""}`.split(",").map(e3=>e3.trim()).filter(e3=>!!e3).map(e3=>e3.startsWith("~")?new RegExp(e3.substring(1),"i"):new RegExp(`^${e3}$`,"i"))}}));__publicField(this,"_shouldDenyPeers",new Computed({evaluation:settings=>{var _a13;return`${null!=(_a13=null==settings?void 0:settings.P2P_AutoDenyingPeers)?_a13:""}`.split(",").map(e3=>e3.trim()).filter(e3=>!!e3).map(e3=>e3.startsWith("~")?new RegExp(e3.substring(1),"i"):new RegExp(`^${e3}$`,"i"))}}));this._env=env;this._serverPeerId=_serverPeerId;this._env.events.onEvent(EVENT_PLATFORM_UNLOADED,()=>{this.shutdown()});this.acceptedPeers=new StoredMapLike(this._env.simpleStore,"p2p-device-decisions")}_peerConnectionEventCleanup(){if(this._peerStatusEventCleanup){this._peerStatusEventCleanup();this._peerStatusEventCleanup=void 0}if(this._peerFailureAnalysisCleanup){this._peerFailureAnalysisCleanup();this._peerFailureAnalysisCleanup=void 0}}get isDisposed(){return!this._room}get isServing(){return void 0!==this._room}async ensureLeaved(){var _a13;if(this._room){try{await(null==(_a13=this._room)?void 0:_a13.leave())}catch(ex){Logger("Some error has been occurred while leaving the room, but possibly can be ignored",LOG_LEVEL_VERBOSE);Logger(ex,LOG_LEVEL_VERBOSE)}this._room=void 0;this._env.events.emitEvent(EVENT_P2P_DISCONNECTED)}}async setRoom(room){var _a13;await(null==(_a13=this._room)?void 0:_a13.leave());this._room=room}async shutdown(){var _a13;try{await this.close();await this.ensureLeaved();null==(_a13=this._rpcRoom)||_a13.close();this._rpcRoom=void 0}catch(ex){Logger("Some error has been occurred while shutting down the server",LOG_LEVEL_INFO);Logger(ex,LOG_LEVEL_VERBOSE)}}async dispatchConnectionStatus(){const adsTasks=[...this.knownAdvertisements].map(async e3=>{const isAccepted2=await this.acceptedPeers.get(e3.name),isTemporaryAccepted=this.temporaryAcceptedPeers.get(e3.peerId);return{...e3,isAccepted:isAccepted2,isTemporaryAccepted}}),ads=await Promise.all(adsTasks);this._env.events.emitEvent(EVENT_SERVER_STATUS,{isConnected:this.isServing,knownAdvertisements:ads,serverPeerId:this.serverPeerId,roomId:this._activeRoomId,diag:this._diagStats})}async makeDecision(decision){decision.decision?decision.isTemporary?this.temporaryAcceptedPeers.set(decision.peerId,!0):await this.acceptedPeers.set(decision.name,!0):decision.isTemporary?this.temporaryAcceptedPeers.set(decision.peerId,!1):await this.acceptedPeers.set(decision.name,!1);await this.dispatchConnectionStatus()}async revokeDecision(decision){this.temporaryAcceptedPeers.delete(decision.peerId);await this.acceptedPeers.delete(decision.name);await this.dispatchConnectionStatus()}get room(){return this._room}get serverPeerId(){return this._serverPeerId}get db(){return this._env.db}get confirm(){return this._env.confirm}get settings(){return this._env.settings}get isEnabled(){return this.settings.P2P_Enabled}get deviceInfo(){return{currentPeerId:this._serverPeerId,name:this._env.deviceName,platform:this._env.platform,version:"0.0.0"}}sendAdvertisement(peerId){if(!this.isEnabled)return;const devInfo=this.deviceInfo,data={peerId:devInfo.currentPeerId,name:devInfo.name,platform:devInfo.platform};if(this._sendAdvertisement){Logger(`peerId: ${this.serverPeerId} Sending Advertisement to ${null!=peerId?peerId:"All"}`,LOG_LEVEL_VERBOSE);this._sendAdvertisement(data,peerId)}}get knownAdvertisements(){return[...this._knownAdvertisements.values()]}onAdvertisement(data,peerId){if(this.isEnabled){Logger(`Advertisement from ${peerId}`,LOG_LEVEL_VERBOSE);if(peerId!==this.serverPeerId&&data.peerId!==this.serverPeerId&&data.peerId===peerId){this._knownAdvertisements.set(peerId,data);this.dispatchConnectionStatus();this._env.events.emitEvent(EVENT_ADVERTISEMENT_RECEIVED,data)}}}confirmUserToAccept(peerId){return shareRunningResult(`confirmUserToAccept-${peerId}`,()=>this._confirmUserToAccept(peerId))}_confirmUserToAccept(peerId){const peerInfo=this._knownAdvertisements.get(peerId);if(!peerInfo)throw new Error("Unknown Peer");const peerName=peerInfo.name,message=`Are you sure to establish connection to ${peerName} (${peerId})?\nYou can chose as follows:\n- Accept: Accept all connections from this peer.\n- Ignore: Reject all connections from this peer.\n- Accept Temporarily: Accept the connection for this session only.\n- Ignore Temporarily: Reject the connection for this session only.\n\n>[!INFO] You can revoke your decision from the Peer-to-Peer Replicator Pane.`,OPTIONS=["Accept","Ignore","Accept Temporarily","Ignore Temporarily"];return this.confirm.askSelectStringDialogue(message,OPTIONS,{title:"P2P Connection Request",defaultAction:"Ignore Temporarily",timeout:30}).then(decision=>{if("Accept Temporarily"===decision){this.temporaryAcceptedPeers.set(peerId,!0);this.dispatchConnectionStatus();return!0}if("Ignore Temporarily"===decision){this.temporaryAcceptedPeers.set(peerId,!1);this.dispatchConnectionStatus();return!1}if("Accept"===decision){this.temporaryAcceptedPeers.delete(peerId);this.acceptedPeers.set(peerName,!0);this.dispatchConnectionStatus();return!0}if("Ignore"===decision){this.temporaryAcceptedPeers.delete(peerId);this.acceptedPeers.set(peerName,!1);this.dispatchConnectionStatus();return!1}throw new ResponsePreventedError("User Accepting failed")})}async isAcceptablePeer(peerId){if(!this.isEnabled)return;const peerInfo=this._knownAdvertisements.get(peerId);if(!peerInfo)return!1;const peerName=peerInfo.name;if(this.temporaryAcceptedPeers.has(peerId))return this.temporaryAcceptedPeers.get(peerId);const accepted=await this.acceptedPeers.get(peerName);if(null!=accepted)return accepted;const isAcceptable=(await this._acceptablePeers.update(this.settings)).value.some(e3=>e3.test(peerName)),isDeny=(await this._shouldDenyPeers.update(this.settings)).value.some(e3=>e3.test(peerName));if(isAcceptable){if(isDeny)return!1;this.temporaryAcceptedPeers.set(peerId,!0);this.dispatchConnectionStatus();return!0}return!this.settings.P2P_IsHeadless&&await this.confirmUserToAccept(peerId)}async __send(data,peerId){if(this.isEnabled)if(await this.isAcceptablePeer(peerId)){if(this.___send)return await this.___send(data,peerId);Logger("Cannot send response, no send function")}else{Logger(`Invalid Message to ${peerId}`,LOG_LEVEL_VERBOSE);Logger(data,LOG_LEVEL_VERBOSE)}}async processArrivedRPC(data,peerId){if(this.isEnabled){if(!data.type.startsWith("!")){const isAcceptable=await this.isAcceptablePeer(peerId);if(!isAcceptable)throw new Error(`Not acceptable peer ${peerId}`)}if(data.direction===DIRECTION_RESPONSE)this.__onResponse(data,peerId);else{if(data.direction!==DIRECTION_REQUEST)throw new Error(`Invalid Message from ${peerId}`);await this.__onRequest(data,peerId)}}}_onPeerJoin(peerId){if(this._room){Logger(`Peer joined: ${peerId}`,LOG_LEVEL_VERBOSE);this.sendAdvertisement(peerId)}else Logger(`Received peer join event from ${peerId}, but no active room. Ignoring.`,LOG_LEVEL_VERBOSE)}_onPeerLeave(peerId){Logger(`Peer left: ${peerId}`,LOG_LEVEL_VERBOSE);this._knownAdvertisements.delete(peerId);this._env.events.emitEvent(EVENT_DEVICE_LEAVED,peerId);this.dispatchConnectionStatus()}onAfterJoinRoom(){var _a13;Logger("Initializing...",LOG_LEVEL_VERBOSE);const room=this.room;if(!room)throw new Error("This server has been already disconnected");const rpcAction=room.makeAction("rpc2"),transport={send:(message,peerId)=>rpcAction.send(message,{target:peerId}),onMessage:handler=>{rpcAction.onMessage=(data,{peerId})=>{handler(data,peerId)};return()=>{rpcAction.onMessage=null}},onPeerJoin:handler=>subscribeTrysteroPeerEvents(room,{onJoin:peerId=>{this._onPeerJoin(peerId);handler(peerId)}}),onPeerLeave:handler=>subscribeTrysteroPeerEvents(room,{onLeave:peerId=>{this._onPeerLeave(peerId);handler(peerId)}})};null==(_a13=this._rpcRoom)||_a13.close();this._rpcRoom=new RpcRoom({...resolveTrysteroRpcOptions(this.settings),transport,canAcceptRequest:async(peerId,method)=>method===toRpcMethodName("!reqAuth")||!0===await this.isAcceptablePeer(peerId),onProtocolWarning:(message,peerId)=>{Logger(`RPC Protocol warning${peerId?` from ${peerId}`:""}: ${message}`,LOG_LEVEL_VERBOSE)}});const advertisementAction=room.makeAction("ad");this._sendAdvertisement=(data,peerId)=>advertisementAction.send(data,peerId?{target:peerId}:void 0);advertisementAction.onMessage=(data,{peerId})=>{this.onAdvertisement(data,peerId)};this._env.events.emitEvent(EVENT_P2P_CONNECTED);this.dispatchConnectionStatus()}async startService(bindings=[]){if(!this.isEnabled){Logger(this._env.translate("P2P.NotEnabled"),LOG_LEVEL_NOTICE);return}const servingDB=createHostingDB(this._env);this._bindingObjects=[...bindings,servingDB];this._bindingObjects.forEach(b3=>{this.serveObject(b3)});await Promise.resolve(this.sendAdvertisement())}async start(bindings=[]){await this.shutdown();if(!this.settings.P2P_Enabled){Logger(this._env.translate("P2P.NotEnabled"),LOG_LEVEL_NOTICE);return}const options=generateJoinRoomOptions(this.settings),roomId=this.settings.P2P_roomID;this._peerConnectionEventCleanup();this._peerStatusEventCleanup=subscribeConnectionStatus(status=>{this._diagStats=status;this.dispatchConnectionStatus()});this._peerFailureAnalysisCleanup=subscribeFailureDiagnosis(status=>{Logger(`[P2P] Connection failure detected: ${status.userMessage}`,LOG_LEVEL_NOTICE)});const room=joinRoom(options,roomId,{handshakeTimeoutMs:3e4,onJoinError:error=>{Logger("Some peer Failed to join Trystero room");Logger(error,LOG_LEVEL_VERBOSE)}});await this.setRoom(room);this._activeRoomId=roomId;this.onAfterJoinRoom();this.dispatchConnectionStatus();await this.startService(bindings)}serveFunction(type,func){var _a13;this.assignedFunctions.set(type,func);null==(_a13=this._rpcRoom)||_a13.register(toRpcMethodName(type),async(peerId,...args)=>await Promise.resolve(func.apply(this,[peerId,...args])))}serveObject(obj){const keys3=Object.keys(obj);keys3.forEach(key3=>{var _a13;if(key3.toString().startsWith("_"))return;const func=obj[key3].bind(obj);this.assignedFunctions.set(key3.toString(),func);null==(_a13=this._rpcRoom)||_a13.register(toRpcMethodName(key3.toString()),async(_peerId,...args)=>await Promise.resolve(func(...args)))})}__onResponse(data,peerId){const peer=this.clients.get(peerId);peer?peer.__onResponse(data):Logger(`Response from unknown peer ${peerId}`,LOG_LEVEL_VERBOSE)}async __onRequest(data,peerId){try{const func=this.assignedFunctions.get(data.type);if("function"!=typeof func)throw new Error(`Cannot serve function ${data.type}, no function provided or I am only a client`);const r4=await Promise.resolve(func.apply(this,data.args));await this.__send({type:data.type,seq:data.seq,direction:DIRECTION_RESPONSE,data:r4},peerId)}catch(e3){if(e3 instanceof ResponsePreventedError){Logger(`Serving function: [FAILED] ${data.type}: Response prevented.`,LOG_LEVEL_VERBOSE);return}Logger(`Serving function: [FAILED] ${data.type} sending back the failure information`,LOG_LEVEL_VERBOSE);Logger(e3 instanceof Error?e3.message:e3,LOG_LEVEL_VERBOSE);await this.__send({type:data.type,seq:data.seq,direction:DIRECTION_RESPONSE,data:void 0,error:e3},peerId)}}async close(){var _a13;this.assignedFunctions.clear();this.clients.forEach(client=>client.close());this.clients.clear();null==(_a13=this._rpcRoom)||_a13.close();this._rpcRoom=void 0;await this.ensureLeaved();this._activeRoomId="";this._knownAdvertisements.clear();this._peerConnectionEventCleanup();await this.dispatchConnectionStatus()}getConnection(peerId){if(this.clients.has(peerId))return this.clients.get(peerId);if(!this._knownAdvertisements.has(peerId))throw new Error(`Unknown Peer ${peerId}`);const client=new TrysteroReplicatorP2PClient(this,peerId);this.clients.set(peerId,client);return client}get rpcRoom(){return this._rpcRoom}};P2PLogCollector=class{constructor(events){__publicField(this,"p2pReplicationResult",new Map);__publicField(this,"p2pReplicationLine",reactiveSource(""));events.onEvent(EVENT_ADVERTISEMENT_RECEIVED,data=>{this.p2pReplicationResult.set(data.peerId,{peerId:data.peerId,peerName:data.name,fetching:{current:0,max:0,isActive:!1},sending:{current:0,max:0,isActive:!1}});this.updateP2PReplicationLine()});events.onEvent(EVENT_P2P_CONNECTED,()=>{this.p2pReplicationResult.clear();this.updateP2PReplicationLine()});events.onEvent(EVENT_P2P_DISCONNECTED,()=>{this.p2pReplicationResult.clear();this.updateP2PReplicationLine()});events.onEvent(EVENT_DEVICE_LEAVED,peerId=>{this.p2pReplicationResult.delete(peerId);this.updateP2PReplicationLine()});events.onEvent(EVENT_P2P_REPLICATOR_PROGRESS,data=>{const prev=this.p2pReplicationResult.get(data.peerId)||{peerId:data.peerId,peerName:data.peerName,fetching:{current:0,max:0,isActive:!1},sending:{current:0,max:0,isActive:!1}};"fetching"in data&&(data.fetching.isActive?prev.fetching=data.fetching:prev.fetching.isActive=!1);"sending"in data&&(data.sending.isActive?prev.sending=data.sending:prev.sending.isActive=!1);this.p2pReplicationResult.set(data.peerId,prev);this.updateP2PReplicationLine()})}updateP2PReplicationLine(){const p2pReplicationResultX=[...this.p2pReplicationResult.values()].sort((a2,b3)=>a2.peerId.localeCompare(b3.peerId)),renderProgress=(current,max3)=>current==max3?`${current}`:`${current} (${max3})`,line=p2pReplicationResultX.map(e3=>`${e3.fetching.isActive||e3.sending.isActive?"⚡":"💤"} ${e3.peerName} ↑ ${renderProgress(e3.sending.current,e3.sending.max)} ↓ ${renderProgress(e3.fetching.current,e3.fetching.max)} `).join("\n");this.p2pReplicationLine.value=line}};REMOTE_OPERATION_ACTIVITY_ICON="📲";REMOTE_REQUEST_ACTIVITY_ICON="🌐";REMOTE_REQUEST_ACTIVITY_MINIMUM_VISIBLE_MS=150;STATUS_COUNTER_PADDING="".repeat(10);STATUS_COUNTER_INACTIVE_LINGER_MS=3e3;CHeader="h:";PSCHeader="ps:";0;ICHeader="i:";ICHeaderEnd="i;";ICHeaderLength=ICHeader.length;ICXHeader="ix:";PERIODIC_PLUGIN_SWEEP=60;0;YieldOperationNumbers=100;PersistentMap=class{flush(){this._save()}_save(){localStorage.setItem(this._key,JSON.stringify([...this._map.entries()]))}_load(suppliedEntries=[]){var _a13;try{const savedSource=null!=(_a13=localStorage.getItem(this._key))?_a13:"",sourceToParse=""===savedSource?"[]":savedSource,obj=JSON.parse(sourceToParse);this._map=new Map([...obj,...suppliedEntries])}catch(ex){console.log(`Map read error : ${this._key}`);console.dir(ex);this._map=new Map([...suppliedEntries])}return Promise.resolve()}_queueSave(){this._setCount--;if(this._setCount<0){this._setCount=YieldOperationNumbers;scheduleTask(`save-map-${this._key}`,0,()=>this._save())}scheduleTask(`save-map-${this._key}`,150,()=>this._save())}delete(key3){const ret=this._map.delete(key3);this._queueSave();return ret}has(key3){return this._map.has(key3)}set(key3,value){this._map.set(key3,value);this._queueSave();return this}clear(){this._map=new Map;this._save()}get(key3,defValue){const v2=this._map.get(key3);return void 0===v2?defValue:v2}constructor(key3,entries2){Object.defineProperty(this,"_setCount",{enumerable:!0,configurable:!0,writable:!0,value:YieldOperationNumbers});Object.defineProperty(this,"_map",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_key",{enumerable:!0,configurable:!0,writable:!0,value:void 0});this._key=key3;this._map=new Map(null!=entries2?entries2:[]);this._load(entries2)}};BasicHeaderGenerator=class{constructor(){__publicField(this,"_header",new Computed({evaluation:source2=>{if("username"in source2){const userNameAndPassword=source2.username&&source2.password?`${source2.username}:${source2.password}`:"";return`Basic ${btoa(userNameAndPassword)}`}return""}}))}async getBasicHeader(auth){return(await this._header.update(auth)).value}};JWTTokenGenerator=class{constructor(){__publicField(this,"_currentCryptoKey",new Computed({evaluation:async auth=>await this._importKey(auth)}));__publicField(this,"_jwt",new Computed({evaluation:async params=>{const encodedHeader=btoa(JSON.stringify(params.header)),encodedPayload=btoa(JSON.stringify(params.payload)),buff=`${encodedHeader}.${encodedPayload}`.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,""),key3=(await this._currentCryptoKey.update(params.credentials)).value;let token="";if("ES256"==params.header.alg||"ES512"==params.header.alg){const digestAlg="ES256"==params.header.alg?"SHA-256":"SHA-512",jwt=await crypto.subtle.sign({name:"ECDSA",hash:{name:digestAlg}},key3,writeString(buff));token=(await arrayBufferToBase64Single2(jwt)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}else{if("HS256"!=params.header.alg&&"HS512"!=params.header.alg)throw new Error("JWT algorithm is not supported.");{const jwt=await crypto.subtle.sign({name:"HMAC",hash:{name:params.header.alg}},key3,writeString(buff));token=(await arrayBufferToBase64Single2(jwt)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}}return{...params,token:`${buff}.${token}`}}}));__publicField(this,"_jwtParams",new Computed({evaluation(source2){const kid=source2.jwtKid||void 0,sub=(source2.jwtSub||"").trim();if(""==sub)throw new Error("JWT sub is empty");const algorithm=source2.jwtAlgorithm||"";if(!algorithm)throw new Error("JWT algorithm is not configured.");if("HS256"!=algorithm&&"HS512"!=algorithm&&"ES256"!=algorithm&&"ES512"!=algorithm)throw new Error("JWT algorithm is not supported.");const header={alg:source2.jwtAlgorithm||"HS256",typ:"JWT",kid},iat=~~((new Date).getTime()/1e3),exp=iat+60*(source2.jwtExpDuration||5),payload={exp,iat,sub:source2.jwtSub||"","_couchdb.roles":["_admin"]};return{header,payload,credentials:source2}},requiresUpdate(args,previousArgs,previous){if(!previous||previous instanceof Error)return!0;const ttl=previous.payload.exp-previous.payload.iat,margin20p=.1*ttl,margin=Math.min(10,Math.max(margin20p,60)),d4=~~((new Date).getTime()/1e3)+margin;return previous.payload.exp<d4}}))}_importKey(auth){if("HS256"==auth.jwtAlgorithm||"HS512"==auth.jwtAlgorithm){const key3=(auth.jwtKey||"").trim();if(""==key3)throw new Error("JWT key is empty");const binaryDerString=compatGlobal.atob(key3),binaryDer=new Uint8Array(binaryDerString.length);for(let i3=0;i3<binaryDerString.length;i3++)binaryDer[i3]=binaryDerString.charCodeAt(i3);const hashName="HS256"==auth.jwtAlgorithm?"SHA-256":"SHA-512";return crypto.subtle.importKey("raw",binaryDer,{name:"HMAC",hash:{name:hashName}},!0,["sign"])}if("ES256"==auth.jwtAlgorithm||"ES512"==auth.jwtAlgorithm){const pem=auth.jwtKey.replace(/-----BEGIN [^-]+-----/,"").replace(/-----END [^-]+-----/,"").replace(/\s+/g,""),binaryDerString=compatGlobal.atob(pem),binaryDer=new Uint8Array(binaryDerString.length);for(let i3=0;i3<binaryDerString.length;i3++)binaryDer[i3]=binaryDerString.charCodeAt(i3);const namedCurve="ES256"==auth.jwtAlgorithm?"P-256":"P-521",param={name:"ECDSA",namedCurve};return crypto.subtle.importKey("pkcs8",binaryDer,param,!0,["sign"])}throw new Error("Supplied JWT algorithm is not supported.")}async getJWT(auth){const params=(await this._jwtParams.update(auth)).value,jwt=(await this._jwt.update(params)).value;return jwt}async getBearerToken(auth){const jwt=await this.getJWT(auth);return`Bearer ${jwt.token}`}};AuthorizationHeaderGenerator=class{constructor(){__publicField(this,"_basicHeader",new BasicHeaderGenerator);__publicField(this,"_jwtHeader",new JWTTokenGenerator)}async getAuthorizationHeader(auth){return"username"in auth?await this._basicHeader.getBasicHeader(auth):"jwtAlgorithm"in auth?await this._jwtHeader.getBearerToken(auth):""}};0;0;_requestToCouchDB=async(baseUri,credentials,origin2,path2,body,method,customHeaders)=>{const authHeaderGen=new AuthorizationHeaderGenerator,authHeader=await authHeaderGen.getAuthorizationHeader(credentials),transformedHeaders={authorization:authHeader,origin:origin2,...customHeaders},uri=`${baseUri.replace(/\/+$/,"")}/${path2}`,requestParam={url:uri,method:method||(body?"PUT":"GET"),headers:transformedHeaders,contentType:"application/json",body:body?JSON.stringify(body):void 0};return await(0,import_obsidian.requestUrl)(requestParam)};0;0;0;manifestVersion="1.0.21";packageVersion="1.0.21";recentLogEntries=reactiveSource([]);globalLogFunction=(message,level,key3)=>{const messageX=message instanceof Error?new LiveSyncError("[Error Logged]: "+message.message,{cause:message}):"string"==typeof message?message:JSON.stringify(message),entry={message:messageX,level,key:key3};recentLogEntries.value=[...recentLogEntries.value,entry]};setGlobalLogFunction(globalLogFunction);logForDump=[];logForDisplay=[];updateLogMessage=(0,import_obsidian.debounce)(()=>{logMessages.value=[...logForDisplay]},25);redactPatterns=[/PBKDF2 salt \(Security Seed\):.*$/];showDebugLog=!1;MARK_DONE="";ModuleLog=class extends AbstractObsidianModule{constructor(){super(...arguments);this.statusLog=reactiveSource("");this.activeFileStatus=reactiveSource("");this.notifies={};this.p2pLogCollector=new P2PLogCollector(this.services.context.events);this.nextFrameQueue=void 0;this.logLines=[]}observeForLogs(){const registerDisplay=display=>{this.plugin.register(()=>display.dispose());return display},labelReplication=registerDisplay(createPaddedCounterLabel(this.services.replication.replicationResultCount,"📥")),labelDBCount=registerDisplay(createPaddedCounterLabel(this.services.replication.databaseQueueCount,"📄")),labelStorageCount=registerDisplay(createPaddedCounterLabel(this.services.replication.storageApplyingCount,"💾")),labelChunkCount=registerDisplay(createPaddedCounterLabel(collectingChunks,"🧩")),labelPluginScanCount=registerDisplay(createPaddedCounterLabel(pluginScanningCount,"🔌")),labelConflictProcessCount=registerDisplay(createPaddedCounterLabel(this.services.conflict.conflictProcessQueueCount,"🔩")),hiddenFilesCount=reactive(()=>hiddenFilesEventCount.value-hiddenFilesProcessingCount.value),labelHiddenFilesCount=registerDisplay(createPaddedCounterLabel(hiddenFilesCount,"⚙️")),queueCountLabelX=reactive(()=>`${labelReplication.value}${labelDBCount.value}${labelStorageCount.value}${labelChunkCount.value}${labelPluginScanCount.value}${labelHiddenFilesCount.value}${labelConflictProcessCount.value}`),queueCountLabel=()=>queueCountLabelX.value,trackedRequestCount=reactive(()=>getTrackedRequestCount(this.services.API.requestCount.value,this.services.API.responseCount.value)),displayedTrackedRequestCount=registerDisplay(createMinimumVisibleActivityCount(trackedRequestCount,REMOTE_REQUEST_ACTIVITY_MINIMUM_VISIBLE_MS)),requestingStatLabel=computed(()=>formatRemoteActivityStatusLabel({remoteOperationCount:Math.max(0,this.services.replicator.boundedRemoteActivityCount.value),trackedRequestCount:displayedTrackedRequestCount.value})),replicationStatLabel=computed(()=>{const e3=this.services.replicator.replicationStatics.value,sent=e3.sent,arrived=e3.arrived,maxPullSeq=e3.maxPullSeq,maxPushSeq=e3.maxPushSeq,lastSyncPullSeq=e3.lastSyncPullSeq,lastSyncPushSeq=e3.lastSyncPushSeq;let pushLast="",pullLast="",w2="";const labels={CONNECTED:"⚡",JOURNAL_SEND:"📦↑",JOURNAL_RECEIVE:"📦↓"};switch(e3.syncStatus){case"CLOSED":case"COMPLETED":case"NOT_CONNECTED":w2="⏹";break;case"STARTED":w2="🌀";break;case"PAUSED":w2="💤";break;case"CONNECTED":case"JOURNAL_SEND":case"JOURNAL_RECEIVE":w2=labels[e3.syncStatus]||"⚡";pushLast=0==lastSyncPushSeq?"":lastSyncPushSeq>=maxPushSeq?" (LIVE)":` (${maxPushSeq-lastSyncPushSeq})`;pullLast=0==lastSyncPullSeq?"":lastSyncPullSeq>=maxPullSeq?" (LIVE)":` (${maxPullSeq-lastSyncPullSeq})`;break;case"ERRORED":w2="⚠";break;default:w2="?"}return{w:w2,sent,pushLast,arrived,pullLast}}),labelProc=registerDisplay(createPaddedCounterLabel(this.services.fileProcessing.processing,"⏳")),labelPend=registerDisplay(createPaddedCounterLabel(this.services.fileProcessing.totalQueued,"🛫")),labelInBatchDelay=registerDisplay(createPaddedCounterLabel(this.services.fileProcessing.batched,"📬")),waitingLabel=computed(()=>`${labelProc.value}${labelPend.value}${labelInBatchDelay.value}`),statusLineLabel=computed(()=>{const{w:w2,sent,pushLast,arrived,pullLast}=replicationStatLabel(),queued=queueCountLabel(),waiting=waitingLabel(),networkActivity=requestingStatLabel(),p2p=this.p2pLogCollector.p2pReplicationLine.value;return{message:`${networkActivity}Sync: ${w2} ↑ ${sent}${pushLast} ↓ ${arrived}${pullLast}${waiting}${queued}${""==p2p?"":"\n"+p2p}`}}),statusBarLabels=reactive(()=>{const scheduleMessage=this.services.appLifecycle.isReloadingScheduled()?"WARNING! RESTARTING OBSIDIAN IS SCHEDULED!\n":"",{message}=statusLineLabel(),fileStatus=this.activeFileStatus.value,status=scheduleMessage+this.statusLog.value,fileStatusIcon=""+(fileStatus&&this.settings.hideFileWarningNotice?" ⛔ SKIP":"");return{message:`${message}${fileStatusIcon}`,status}});this.statusBarLabels=statusBarLabels;const applyToDisplay=throttle(label2=>{this.applyStatusBarText()},20);statusBarLabels.onChanged(label2=>applyToDisplay(label2.value));this.activeFileStatus.onChanged(()=>this.updateMessageArea())}_everyOnload(){eventHub.onEvent(EVENT_LEAF_ACTIVE_CHANGED2,()=>this.onActiveLeafChange());eventHub.onceEvent(EVENT_LAYOUT_READY,()=>this.onActiveLeafChange());eventHub.onEvent(EVENT_ON_UNRESOLVED_ERROR,()=>this.updateMessageArea());return Promise.resolve(!0)}adjustStatusDivPosition(){const mdv=this.app.workspace.getMostRecentLeaf();if(mdv&&this.statusDiv){this.statusDiv.remove();const container=mdv.view.containerEl;container.appendChild(this.statusDiv)}}async getActiveFileStatus(){const reason=[],reasonWarn=[],thisFile=this.app.workspace.getActiveFile();if(!thisFile)return"";const validPath=isValidPath(thisFile.path);if(validPath){const validOnWindows=isValidFilenameInWidows(thisFile.name),validOnDarwin=isValidFilenameInDarwin(thisFile.name),validOnAndroid=isValidFilenameInAndroid(thisFile.name),labels=[];validOnWindows||labels.push("🪟");validOnDarwin||labels.push("🍎");validOnAndroid||labels.push("🤖");labels.length>0&&reasonWarn.push("Some platforms may be unable to process this file correctly: "+labels.join(" "))}else reason.push("This file has an invalid path under the current settings");if(this.services.vault.shouldCheckCaseInsensitively()){const f4=(await this.core.storageAccess.getFiles()).map(e3=>e3.path).filter(e3=>e3.toLowerCase()==thisFile.path.toLowerCase());f4.length>1&&reason.push("There are multiple files with the same name (case-insensitive match)")}await this.services.vault.isTargetFile(thisFile.path)||reason.push("This file is ignored by the ignore rules");this.services.vault.isFileSizeTooLarge(thisFile.stat.size)&&reason.push("This file size exceeds the configured limit");const result=reason.length>0?"Not synchronised: "+reason.join(", "):"",warnResult=reasonWarn.length>0?"Warning: "+reasonWarn.join(", "):"";return[result,warnResult].filter(e3=>e3).join("\n")}async setFileStatus(){const fileStatus=await this.getActiveFileStatus();this.activeFileStatus.value=fileStatus}async updateMessageArea(){var _a13,_b6;if(!this.messageArea)return;const showStatusOnEditor=null!=(_b6=null==(_a13=this.settings)?void 0:_a13.showStatusOnEditor)&&_b6;this.statusDiv&&this.statusDiv.setCssStyles({display:showStatusOnEditor?"":"none"});if(!showStatusOnEditor){this.messageArea.innerText="";return}const messageLines=[],fileStatus=this.activeFileStatus.value;fileStatus&&!this.settings.hideFileWarningNotice&&messageLines.push(fileStatus);const messages=(await this.services.appLifecycle.getUnresolvedMessages()).flat().filter(e3=>e3),stringMessages=messages.filter(m3=>"string"==typeof m3),networkMessages=stringMessages.filter(m3=>m3.startsWith(MARK_LOG_NETWORK_ERROR)),otherMessages=stringMessages.filter(m3=>!m3.startsWith(MARK_LOG_NETWORK_ERROR));messageLines.push(...otherMessages);this.settings.networkWarningStyle!==NetworkWarningStyles_ICON&&this.settings.networkWarningStyle!==NetworkWarningStyles_HIDDEN?messageLines.push(...networkMessages):this.settings.networkWarningStyle===NetworkWarningStyles_ICON&&networkMessages.length>0&&messageLines.push("🔗❌");this.messageArea.innerText=messageLines.map(e3=>`⚠️ ${e3}`).join("\n")}onActiveLeafChange(){fireAndForget(async()=>{this.adjustStatusDivPosition();await this.setFileStatus()})}applyStatusBarText(){if(!this.nextFrameQueue){this.nextFrameQueue=compatGlobal.requestAnimationFrame(()=>{var _a13,_b6,_c3,_d2;this.nextFrameQueue=void 0;const{message,status}=this.statusBarLabels.value,newMsg=message;let newLog=(null==(_a13=this.settings)?void 0:_a13.showOnlyIconsOnEditor)?"":status;const moduleTagEnd=newLog.indexOf(`]${MARK_LOG_SEPARATOR}`);-1!=moduleTagEnd&&(newLog=newLog.substring(moduleTagEnd+MARK_LOG_SEPARATOR.length+1));null==(_b6=this.statusBar)||_b6.setText(newMsg.split("\n")[0]);this.statusDiv&&this.statusDiv.setCssStyles({display:(null==(_c3=this.settings)?void 0:_c3.showStatusOnEditor)?"":"none"});if((null==(_d2=this.settings)?void 0:_d2.showStatusOnEditor)&&this.statusDiv){if(this.settings.showLongerLogInsideEditor){const now3=(new Date).getTime();this.logLines=this.logLines.filter(e3=>e3.ttl>now3);const minimumNext=this.logLines.reduce((a2,b3)=>a2<b3.ttl?a2:b3.ttl,Number.MAX_SAFE_INTEGER);this.logLines.length>0&&compatGlobal.setTimeout(()=>this.applyStatusBarText(),minimumNext-now3);const recent=this.logLines.map(e3=>e3.message),recentLogs=recent.reverse().join("\n");isDirty("recentLogs",recentLogs)&&(this.logHistory.innerText=recentLogs)}isDirty("newMsg",newMsg)&&(this.statusLine.innerText=newMsg);isDirty("newLog",newLog)&&(this.logMessage.innerText=newLog)}});scheduleTask("log-hide",3e3,()=>{this.statusLog.value=""})}}_allStartOnUnload(){var _a13;for(const key3 of Object.keys(this.notifies))this.services.context.notices.hide(`log:${key3}`);this.notifies={};this.statusDiv&&this.statusDiv.remove();null==(_a13=compatGlobal.document.querySelectorAll(".livesync-status"))||_a13.forEach(e3=>e3.remove());return Promise.resolve(!0)}_everyOnloadStart(){(0,import_obsidian.addIcon)("view-log",'<g transform="matrix(1.28 0 0 1.28 -131 -411)" fill="currentColor" fill-rule="evenodd">\n <path d="m103 330h76v12h-76z"/>\n <path d="m106 346v44h70v-44zm45 16h-20v-8h20z"/>\n </g>');this.addRibbonIcon("view-log",$msg("moduleLog.showLog"),()=>{this.services.API.showWindow(VIEW_TYPE_LOG)}).addClass("livesync-ribbon-showlog");this.addCommand({id:"view-log",name:"Show log",callback:()=>{this.services.API.showWindow(VIEW_TYPE_LOG)}});this.addCommand({id:"dump-debug-info",name:"Generate full report for opening the issue with debug info",callback:async()=>{const recentLog=[...logForDump],report=await generateReport(this.services.setting.currentSettings(),this.core),info3={...report,recentLog:recentLog.map(redactLog)},yaml=`\`\`\`\`\n# ---- Debug Info Dump ----\n${(0,import_obsidian.stringifyYaml)(info3)}\n\`\`\`\``;await this.services.UI.promptCopyToClipboard("Debug info",yaml)&&new import_obsidian.Notice("Debug info copied to clipboard. You can paste it in the issue. Be careful as it may contain sensitive information, review it before sharing.")}});this.registerView(VIEW_TYPE_LOG,leaf=>new LogPaneView(leaf,this.plugin));return Promise.resolve(!0)}_everyOnloadAfterLoadSettings(){var _a13,_b6,_c3;recentLogEntries.onChanged(entries2=>{if(0===entries2.value.length)return;const newEntries=[...entries2.value];recentLogEntries.value=[];newEntries.forEach(e3=>this.__addLog(e3.message,e3.level,e3.key))});eventHub.onEvent(EVENT_FILE_RENAMED,data=>{this.setFileStatus()});const w2=compatGlobal.document.querySelectorAll(".livesync-status");w2.forEach(e3=>e3.remove());this.observeForLogs();if(this.settings.showStatusOnEditor){this.statusDiv=this.app.workspace.containerEl.createDiv({cls:"livesync-status"});this.statusLine=this.statusDiv.createDiv({cls:"livesync-status-statusline"});this.messageArea=this.statusDiv.createDiv({cls:"livesync-status-messagearea"});this.logMessage=this.statusDiv.createDiv({cls:"livesync-status-logmessage"});this.logHistory=this.statusDiv.createDiv({cls:"livesync-status-loghistory"});this.statusDiv.setCssStyles({display:(null==(_a13=this.settings)?void 0:_a13.showStatusOnEditor)?"":"none"})}eventHub.onEvent(EVENT_LAYOUT_READY,()=>this.adjustStatusDivPosition());if(null==(_b6=this.settings)?void 0:_b6.showStatusOnStatusbar){this.statusBar=this.services.API.addStatusBarItem();null==(_c3=this.statusBar)||_c3.addClass("syncstatusbar")}this.adjustStatusDivPosition();this._log("Log module loaded",LOG_LEVEL_INFO);this._log("Verbose log",LOG_LEVEL_VERBOSE);return Promise.resolve(!0)}writeLogToTheFile(now3,vaultName,newMessage){fireAndForget(()=>serialized("writeLog",async()=>{const time2=now3.toISOString().split("T")[0],logDate=`${PREFIXMD_LOGFILE}${time2}.md`,file=await this.core.storageAccess.isExists(normalizePath(logDate));file||await this.core.storageAccess.appendHiddenFile(normalizePath(logDate),"```\n");await this.core.storageAccess.appendHiddenFile(normalizePath(logDate),vaultName+":"+newMessage+"\n")}))}__addLog(message,level=LOG_LEVEL_INFO,key3=""){var _a13,_b6;if(level==LOG_LEVEL_DEBUG&&!showDebugLog)return;let memoOnly=!1;level<=LOG_LEVEL_INFO&&this.settings&&this.settings.lessInformationInLog&&(memoOnly=!0);this.settings&&!this.settings.showVerboseLog&&level==LOG_LEVEL_VERBOSE&&(memoOnly=!0);const vaultName=this.services.vault.getVaultName(),now3=new Date,timestamp=now3.toLocaleString();let errorInfo="";if(message instanceof Error)if(message instanceof LiveSyncError)if(message.cause&&message.cause instanceof Error){const causedError=message.cause;errorInfo=`${null==causedError?void 0:causedError.name}:${null==causedError?void 0:causedError.message}\n[StackTrace]: ${message.stack}\n[CausedBy]: ${null==causedError?void 0:causedError.stack}`}else errorInfo=`${message.name}:${message.message}\n[StackTrace]: ${message.stack}`;else{const thisStack=(new Error).stack;errorInfo=`${message.name}:${message.message}\n[StackTrace]: ${message.stack}\n[LogCallStack]: ${thisStack}`}const messageContent="string"==typeof message?message:message instanceof Error?`${errorInfo}`:JSON.stringify(message,null,2),newMessage=timestamp+"->"+messageContent;(null==(_a13=this.settings)?void 0:_a13.writeLogToTheFile)&&this.writeLogToTheFile(now3,vaultName,newMessage);addLog(newMessage);if(!memoOnly){addDisplayLog(newMessage);(null==(_b6=this.settings)?void 0:_b6.showOnlyIconsOnEditor)||(this.statusLog.value=messageContent);this.logLines.push({ttl:now3.getTime()+3e3,message:newMessage});if(level>=LOG_LEVEL_NOTICE){key3||(key3=messageContent);key3 in this.notifies?key3==messageContent&&this.notifies[key3].count++:this.notifies[key3]={count:0};const timeout=5e3,shouldExpire=!key3.startsWith("keepalive-")||-1!==messageContent.indexOf(MARK_DONE),noticeMessage=key3==messageContent&&this.notifies[key3].count>0?`(${this.notifies[key3].count}):${messageContent}`:messageContent;this.services.context.notices.show(`log:${key3}`,noticeMessage,{durationMs:!!shouldExpire&&timeout});shouldExpire&&scheduleTask(`notify-${key3}`,timeout,()=>{delete this.notifies[key3]})}}}onBindFunction(core,services){services.API.addLog.setHandler(globalLogFunction);services.appLifecycle.onInitialise.addHandler(this._everyOnloadStart.bind(this));services.appLifecycle.onSettingLoaded.addHandler(this._everyOnloadAfterLoadSettings.bind(this));services.appLifecycle.onLoaded.addHandler(this._everyOnload.bind(this));services.appLifecycle.onBeforeUnload.addHandler(this._allStartOnUnload.bind(this))}};noticeIndex=0;LiveSyncCommands=class{constructor(core){this._verbose=(msg,key3)=>{this._log(msg,LOG_LEVEL_VERBOSE,key3)};this._info=(msg,key3)=>{this._log(msg,LOG_LEVEL_INFO,key3)};this._notice=(msg,key3)=>{this._log(msg,LOG_LEVEL_NOTICE,key3)};this._progress=(prefix="",level=LOG_LEVEL_NOTICE)=>{const key3="keepalive-progress-"+noticeIndex++;return{log:msg=>{this._log(prefix+msg,level,key3)},once:msg=>{this._log(prefix+msg,level)},done:(msg="Done")=>{this._log(prefix+msg+MARK_DONE,level,key3)}}};this._debug=(msg,key3)=>{this._log(msg,LOG_LEVEL_VERBOSE,key3)};this.core=core;this.onBindFunction(this.core,this.core.services);this._log=createInstanceLogFunction(this.constructor.name,this.services.API)}get app(){return this.services.context.app}get settings(){return this.core.settings}get localDatabase(){return this.core.localDatabase}get services(){return this.core.services}async path2id(filename,prefix){return await this.services.path.path2id(filename,prefix)}getPath(entry){return this.services.path.getPath(entry)}_isMainReady(){return this.services.appLifecycle.isReady()}_isMainSuspended(){return this.services.appLifecycle.isSuspended()}_isDatabaseReady(){return this.services.database.isDatabaseReady()}onBindFunction(core,services){}};PeriodicProcessor=class{constructor(core,process2){this._timer=void 0;this._core=core;this._process=process2;eventHub.onceEvent(EVENT_PLUGIN_UNLOADED2,()=>{this.disable()})}async process(){try{await this._process()}catch(ex){Logger(ex)}}enable(interval){this.disable();0!=interval&&(this._timer=this._core.services.API.setInterval(()=>fireAndForget(async()=>{var _a13,_b6;await this.process();(null==(_b6=null==(_a13=this._core.services)?void 0:_a13.control)?void 0:_b6.hasUnloaded())&&this.disable()}),interval))}disable(){if(void 0!==this._timer){this._core.services.API.clearInterval(this._timer);this._timer=void 0}}};root3=from_html('<div class="message svelte-1ah3y1j"> </div> <div class="buttons svelte-1ah3y1j"><button class="svelte-1ah3y1j"> </button></div>',1);root_12=from_html('<label><input type="radio" name="disp" class="sls-setting-tab svelte-1ah3y1j"/> <div class="sls-setting-menu-btn svelte-1ah3y1j"> </div></label>');root_2=from_html("<span> </span>");root_3=from_html('<div class="op-scrollable json-source ls-dialog svelte-1ah3y1j"></div>');root_4=from_html('<button class="svelte-1ah3y1j">Cancel</button>');root_5=from_html('<div class="options svelte-1ah3y1j"></div> <!> <div class="infos svelte-1ah3y1j"><table class="svelte-1ah3y1j"><tbody class="svelte-1ah3y1j"><tr class="svelte-1ah3y1j"><th class="svelte-1ah3y1j"> </th><td class="svelte-1ah3y1j"><!> </td><td class="svelte-1ah3y1j"> </td></tr><tr class="svelte-1ah3y1j"><th class="svelte-1ah3y1j"> </th><td class="svelte-1ah3y1j"><!> </td><td class="svelte-1ah3y1j"> </td></tr></tbody></table></div> <div class="buttons svelte-1ah3y1j"><!> <button class="svelte-1ah3y1j">Apply</button></div>',1);root_6=from_html('<h2 class="svelte-1ah3y1j"> </h2> <!>',1);$$css2={hash:"svelte-1ah3y1j",code:".spacer.svelte-1ah3y1j {flex-grow:1;}.infos.svelte-1ah3y1j {display:flex;justify-content:space-between;margin:4px 0.5em;}.deleted.svelte-1ah3y1j {text-decoration:line-through;}.svelte-1ah3y1j {box-sizing:border-box;}.scroller.svelte-1ah3y1j {display:flex;flex-direction:column;overflow-y:scroll;max-height:60vh;user-select:text;-webkit-user-select:text;}.json-source.svelte-1ah3y1j {white-space:pre;height:auto;overflow:auto;min-height:var(--font-ui-medium);flex-grow:1;}"};delegate(["click"]);JsonResolveModal=class extends import_obsidian.Modal{constructor(app,filename,docs,callback,nameA,nameB,defaultSelect,keepOrder,hideLocal,title="Conflicted Setting"){super(app);this.title="Conflicted Setting";this.callback=callback;this.filename=filename;this.docs=docs;this.nameA=nameA||"";this.nameB=nameB||"";this.keepOrder=keepOrder||!1;this.defaultSelect=defaultSelect||"";this.title=title;this.hideLocal=null!=hideLocal&&hideLocal;waitForSignal(`cancel-internal-conflict:${filename}`).then(()=>this.close())}async UICallback(keepRev,mergedStr){this.callback&&await this.callback(keepRev,mergedStr);this.close();this.callback=void 0}onOpen(){const{contentEl}=this;this.titleEl.setText(this.title);contentEl.empty();null==this.component&&(this.component=mount(JsonResolvePane,{target:contentEl,props:{docs:this.docs,filename:this.filename,nameA:this.nameA,nameB:this.nameB,defaultSelect:this.defaultSelect,keepOrder:this.keepOrder,hideLocal:this.hideLocal,callback:(keepRev,mergedStr)=>this.UICallback(keepRev,mergedStr)}}))}onClose(){const{contentEl}=this;contentEl.empty();null!=this.callback&&this.callback(void 0);if(null!=this.component){unmount(this.component);this.component=void 0}}};PaceMaker=class{constructor(interval){Object.defineProperty(this,"_interval",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_minimumNext",{enumerable:!0,configurable:!0,writable:!0,value:void 0});this._interval=interval}changeInterval(interval){if(interval!==this._interval){this._interval=interval;this._minimumNext=void 0}}mark(now3=Date.now()){void 0===this._minimumNext?this._minimumNext=now3+this._interval:this._minimumNext=Math.max(this._minimumNext+this._interval,now3+this._interval)}_getPaced(doMark){const now3=Date.now(),prevMinimum=this._minimumNext;doMark&&this.mark(now3);if(void 0!==prevMinimum){const shouldWait=prevMinimum-now3;if(shouldWait>0)return new Promise(resolve=>setTimeout(()=>{resolve()},shouldWait))}return Promise.resolve()}get paced(){return this._getPaced(!0)}get pacedSinceMark(){return this._getPaced(!1)}};NOT_AVAILABLE=Symbol("NotAvailable");READY_PICK_SIGNAL=Symbol("lockReady");READY_POST_SIGNAL=Symbol("lockFull");DISPOSE_ERROR="Inbox has been disposed";SyncInbox=class{constructor(capacity){Object.defineProperty(this,"_capacity",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_buffer",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_writeIdx",{enumerable:!0,configurable:!0,writable:!0,value:0});Object.defineProperty(this,"_readIdx",{enumerable:!0,configurable:!0,writable:!0,value:0});Object.defineProperty(this,"_wrapAroundCount",{enumerable:!0,configurable:!0,writable:!0,value:0});Object.defineProperty(this,"_isDisposed",{enumerable:!0,configurable:!0,writable:!0,value:!1});Object.defineProperty(this,"_disposedPromise",{enumerable:!0,configurable:!0,writable:!0,value:promiseWithResolvers()});if(capacity<=0)throw new Error("Capacity must be greater than 0");this._capacity=~~capacity;let i3=256;for(;i3<capacity+1;)i3*=2;i3--;this._wrapAroundCount=i3;this._buffer=new Array(i3);this._writeIdx=0;this._readIdx=0}get size(){return this._writeIdx-this._readIdx}get free(){return this._capacity-this.size}get isRunningOut(){return this._writeIdx==this._readIdx}get isFull(){return 0==this.free}get isReady(){return this.free>0}get isDisposed(){return this._isDisposed}get onDisposed(){return this._disposedPromise.promise}__fixIdx(){if(this._readIdx>this._wrapAroundCount){this._readIdx=this._readIdx&this._wrapAroundCount;this._writeIdx=this._writeIdx&this._wrapAroundCount}}get state(){return{processed:this._writeIdx,size:this.size,free:this.free,isFull:this.isFull,isRunningOut:this.isRunningOut,isReady:this.isReady}}dispose(){this._readIdx=0;this._writeIdx=0;this._capacity=0;this._buffer.length=1;this._buffer[0]=void 0;this._wrapAroundCount=1;this._isDisposed=!0;this._disposedPromise.resolve()}__onPosted(){this.__onProgress()}__onPicked(){this.__onProgress()}__onProgress(){this.__fixIdx()}tryPost(item){if(this.isFull)return!1;this._writeIdx++;this._buffer[this._writeIdx&this._wrapAroundCount]=item;this.__onPosted();return!0}tryCancelPost(){if(0==this.size)return NOT_AVAILABLE;const pointingIdx=this._writeIdx&this._wrapAroundCount,item=this._buffer[pointingIdx];this._buffer[pointingIdx]=void 0;this._writeIdx--;this.__fixIdx();return item}tryPick(){if(this.isRunningOut)return NOT_AVAILABLE;this._readIdx++;const pointingIdx=this._readIdx&this._wrapAroundCount,item=this._buffer[pointingIdx];this._buffer[pointingIdx]=void 0;this.__onPicked();return item}};Inbox=class extends SyncInbox{constructor(capacity){super(capacity);Object.defineProperty(this,"_lockFull",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_lockReady",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}async _waitForFree(){for(;0==this.free;){this._lockFull||(this._lockFull=promiseWithResolvers());return await this._lockFull.promise}return READY_POST_SIGNAL}_notifyFree(){var _a13;null==(_a13=this._lockFull)||_a13.resolve(READY_POST_SIGNAL);this._lockFull=void 0}async _waitForReady(){for(;this.isRunningOut;){this._lockReady||(this._lockReady=promiseWithResolvers());return await this._lockReady.promise}return READY_PICK_SIGNAL}_notifyReady(){var _a13;null==(_a13=this._lockReady)||_a13.resolve(READY_PICK_SIGNAL);this._lockReady=void 0}__onPosted(){super.__onPosted();this._notifyReady()}__onPicked(){super.__onPicked();this._notifyFree()}dispose(){super.dispose();if(this._lockFull){this._lockFull.reject(new Error(DISPOSE_ERROR));this._lockFull=void 0}if(this._lockReady){this._lockReady.reject(new Error(DISPOSE_ERROR));this._lockReady=void 0}}async post(item,timeout,cancellation){if(this._isDisposed)throw new Error(DISPOSE_ERROR);do{if(cancellation&&cancellation.length>0&&await isSomeResolved(cancellation))return!1;const result=this.tryPost(item);if(result)return!0;let p2;const tasks3=[this._waitForFree(),...timeout?[(p2=cancelableDelay(timeout)).promise]:[],...cancellation||[]],r4=await Promise.race(tasks3);null==p2||p2.cancel();if(r4!==READY_POST_SIGNAL)return!1}while(!this._isDisposed);return!1}async pick(timeout,cancellation){if(this._isDisposed)throw new Error(DISPOSE_ERROR);do{if(cancellation&&cancellation.length>0&&await isSomeResolved(cancellation))return NOT_AVAILABLE;const item=this.tryPick();if(item!==NOT_AVAILABLE)return item;let p2;const tasks3=[this._waitForReady(),...timeout?[(p2=cancelableDelay(timeout)).promise]:[],...cancellation||[]],r4=await Promise.race(tasks3);null==p2||p2.cancel();if(r4!==READY_PICK_SIGNAL)return NOT_AVAILABLE}while(!this.isDisposed);return NOT_AVAILABLE}};EVENT_PROGRESS="progress";0;(function(ClerkState2){ClerkState2.IDLE="idle";ClerkState2.DISPOSED="disposed";ClerkState2.WORKING="working";ClerkState2.STALLED="not-started"})(ClerkState||(ClerkState={}));SENTINEL_FINISHED=Symbol("finished");SENTINEL_FLUSH=Symbol("flush");ClerkBase=class{get state(){return this._state}constructor(params){Object.defineProperty(this,"_inbox",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_state",{enumerable:!0,configurable:!0,writable:!0,value:ClerkState.STALLED});Object.defineProperty(this,"_totalProcessed",{enumerable:!0,configurable:!0,writable:!0,value:0});Object.defineProperty(this,"_totalSuccess",{enumerable:!0,configurable:!0,writable:!0,value:0});Object.defineProperty(this,"_totalFailed",{enumerable:!0,configurable:!0,writable:!0,value:0});Object.defineProperty(this,"_totalFetched",{enumerable:!0,configurable:!0,writable:!0,value:0});Object.defineProperty(this,"_disposed",{enumerable:!0,configurable:!0,writable:!0,value:!1});Object.defineProperty(this,"_disposePromise",{enumerable:!0,configurable:!0,writable:!0,value:promiseWithResolvers()});Object.defineProperty(this,"_onProgress",{enumerable:!0,configurable:!0,writable:!0,value:void 0});const{name,assigned}=params;this._inbox=assigned;this._name=null!=name?name:this.constructor.name;yieldMicrotask().then(()=>this._mainLoop());this._inbox.onDisposed.then(()=>this.dispose())}get stateDetail(){const hasStarted=0!=this._totalFetched,hasAnyUnprocessed=this._totalFetched!=this._totalProcessed,inboxDetail=this._inbox.state,hasAnyInInbox=0!=inboxDetail.size,isBusy=hasAnyInInbox||hasAnyUnprocessed;return{totalFetched:this._totalFetched,inboxDetail:this._inbox.state,totalProcessed:this._totalProcessed,state:this._state,hasStarted,isBusy}}onProgress(){var _a13;try{null==(_a13=this._onProgress)||_a13.call(this,this.stateDetail)}catch(e3){}}setOnProgress(callback){this._onProgress=callback}async _mainLoop(){var _a13;this._state=ClerkState.STALLED;this.onProgress();await yieldMicrotask();do{this._state=ClerkState.IDLE;this.onProgress();try{const item=await this._inbox.pick(void 0,[this._disposePromise.promise]);if(item===SENTINEL_FLUSH||item===SENTINEL_FINISHED){await(null==(_a13=this._onSentinel)?void 0:_a13.call(this,item));continue}if(item===NOT_AVAILABLE){if(this._inbox.isDisposed){this._state=ClerkState.DISPOSED;break}continue}this._totalFetched++;this._state=ClerkState.WORKING;this.onProgress();try{await this._onPick(item);this._totalSuccess++}catch(ex){this._totalFailed++;Logger("Error on processing job on clerk");Logger(ex,LOG_LEVEL_VERBOSE)}this._totalProcessed++;this.onProgress()}catch(ex){if(ex instanceof Error&&ex.message!==DISPOSE_ERROR){Logger("Error on picking item on clerk");Logger(ex,LOG_LEVEL_VERBOSE)}}}while(!this._inbox.isDisposed&&!this._disposed);this._state=ClerkState.IDLE;this._disposed?this._state=ClerkState.DISPOSED:this.dispose();this.onProgress()}dispose(){this._disposePromise.resolve();this._disposed=!0;this._state=ClerkState.DISPOSED}get onDisposed(){return this._disposePromise.promise}};Clerk=class extends ClerkBase{async _onPick(item){return await this._job(item)}constructor(params){super(params);Object.defineProperty(this,"_job",{enumerable:!0,configurable:!0,writable:!0,value:void 0});this._job=params.job}};ClerkGroup=class{constructor(params){var _a13;Object.defineProperty(this,"_clerks",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_nameBase",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_assigned",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_hiredCount",{enumerable:!0,configurable:!0,writable:!0,value:0});Object.defineProperty(this,"_job",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_instantiate",{enumerable:!0,configurable:!0,writable:!0,value:void 0});const{assigned,job,instantiate,initialMemberCount}=params;this._assigned=assigned;this._instantiate=instantiate;this._job=job;this._nameBase=null!=(_a13=params.name)?_a13:this.constructor.name;this._clerks=[];for(let i3=0;i3<initialMemberCount;i3++)this.hireMember({assigned,job})}hireMember(params){const name=`${this._nameBase}-${this._hiredCount++}`,clerk=this._instantiate({name,assigned:params.assigned,job:params.job});this._clerks.push(clerk)}fireMember(){const clerk=this._clerks.pop();null==clerk||clerk.dispose()}adjustMemberCount(count){const diff=count-this._clerks.length;if(diff>0)for(let i3=0;i3<diff;i3++)this.hireMember({assigned:this._assigned,job:this._job});else if(diff<0)for(let i3=0;i3<-diff;i3++)this.fireMember()}get stateDetail(){const states=this._clerks.map(clerk=>clerk.stateDetail),totalFetched=states.reduce((acc,state2)=>acc+state2.totalFetched,0),totalProcessed=states.reduce((acc,state2)=>acc+state2.totalProcessed,0),isBusy=states.some(state2=>state2.isBusy),hasStarted=states.some(state2=>state2.hasStarted),inboxDetail=this._assigned.state;return{totalFetched,totalProcessed,inboxDetail,isBusy,hasStarted,state:ClerkState.IDLE}}get freeMembers(){return this._clerks.filter(clerk=>clerk.state===ClerkState.IDLE).length}dispose(){this._clerks.forEach(clerk=>clerk.dispose())}};0;0;0;0;allRunningProcessors=new Set([]);QueueProcessor=class{get nowProcessing(){return this.processingEntities}get totalNowProcessing(){var _a13;return this.nowProcessing+((null==(_a13=this._pipeTo)?void 0:_a13.totalNowProcessing)||0)}get remaining(){return this._queue.length+this.processingEntities+this.waitingEntries}get totalRemaining(){var _a13;return this.remaining+((null==(_a13=this._pipeTo)?void 0:_a13.totalRemaining)||0)}updateStatus(setFunc){setFunc();this._updateReactiveSource()}suspend(){this._isSuspended=!0;this._hub.emitEvent("tickSuspended");return this}resume(){this._isSuspended=!1;this._hub.emitEvent("tickResumed");return this}resumePipeLine(){var _a13;null==(_a13=this._pipeTo)||_a13.resumePipeLine();this.resume();return this}startPipeline(){this.root.resumePipeLine();return this}get root(){return void 0===this._root?this:this._root}_initEventHub(){this._hub.onEvent("tickResumed",()=>this._run())}async _waitFor(keys3,timeout){const items=keys3.map(key3=>{const p2=promiseWithResolvers(),releaser=this._hub.onEvent(key3,()=>{p2.resolve(key3)});p2.promise=p2.promise.finally(()=>{releaser()});return p2}),timer=timeout?cancelableDelay(timeout):void 0,tasks3=[...items.map(i3=>i3.promise),...timer?[timer.promise]:[]],ret=await Promise.race(tasks3);items.forEach(i3=>i3.resolve(void 0));return ret}_triggerTickDelay(){this._delayTimer||(this._delayTimer=setTimeout(()=>{this._hub.emitEvent("tickDelayTimeout");this._delayTimer=void 0}))}_clearTickDelay(){if(this._delayTimer){clearTimeout(this._delayTimer);this._delayTimer=void 0}}_notifyIfIdle(){return this.root.__notifyIfIdle()}__notifyIfIdle(){0!=this._processCount||this._canCollectBatch()||this._hub.emitEvent("idle");this._pipeTo&&this._pipeTo.__notifyIfIdle()}_onTick(){if(this._canCollectBatch())if(this._nextProcessNeedsImmediate){this._clearTickDelay();this._nextProcessNeedsImmediate=!1;this._hub.emitEvent("tickImmediate")}else if(this._queue.length>this.yieldThreshold){this._clearTickDelay();this._hub.emitEvent("yielded")}else{if(!this.delay){this._clearTickDelay();this._hub.emitEvent("tickDelayTimeout");return}this._delayTimer||this._triggerTickDelay()}else{this._notifyIfIdle();this._clearTickDelay();this._hub.emitEvent("tickEmpty")}}constructor(processor,params,items,enqueueProcessor){var _a13,_b6,_c3,_d2,_e2,_f,_g;Object.defineProperty(this,"_queue",{enumerable:!0,configurable:!0,writable:!0,value:[]});Object.defineProperty(this,"_processor",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_enqueueProcessor",{enumerable:!0,configurable:!0,writable:!0,value:(queue2,entity)=>(queue2.push(entity),queue2)});Object.defineProperty(this,"_isSuspended",{enumerable:!0,configurable:!0,writable:!0,value:!0});Object.defineProperty(this,"_nextProcessNeedsImmediate",{enumerable:!0,configurable:!0,writable:!0,value:!1});Object.defineProperty(this,"_pipeTo",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_root",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_remainingReactiveSource",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_totalRemainingReactiveSource",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_processingEntitiesReactiveSource",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_keepResultUntilDownstreamConnected",{enumerable:!0,configurable:!0,writable:!0,value:!1});Object.defineProperty(this,"_keptResult",{enumerable:!0,configurable:!0,writable:!0,value:[]});Object.defineProperty(this,"_runOnUpdateBatch",{enumerable:!0,configurable:!0,writable:!0,value:()=>{}});Object.defineProperty(this,"concurrentLimit",{enumerable:!0,configurable:!0,writable:!0,value:1});Object.defineProperty(this,"batchSize",{enumerable:!0,configurable:!0,writable:!0,value:1});Object.defineProperty(this,"yieldThreshold",{enumerable:!0,configurable:!0,writable:!0,value:1});Object.defineProperty(this,"delay",{enumerable:!0,configurable:!0,writable:!0,value:0});Object.defineProperty(this,"maintainDelay",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"interval",{enumerable:!0,configurable:!0,writable:!0,value:0});Object.defineProperty(this,"processingEntities",{enumerable:!0,configurable:!0,writable:!0,value:0});Object.defineProperty(this,"waitingEntries",{enumerable:!0,configurable:!0,writable:!0,value:0});Object.defineProperty(this,"_hub",{enumerable:!0,configurable:!0,writable:!0,value:new EventHub});Object.defineProperty(this,"_delayTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_intervalPaceMaker",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_processingBatches",{enumerable:!0,configurable:!0,writable:!0,value:new Set});Object.defineProperty(this,"addProcessingBatch",{enumerable:!0,configurable:!0,writable:!0,value:value=>{const r4=this._processingBatches.add(value);this._updateBatchProcessStatus();return r4}});Object.defineProperty(this,"deleteProcessingBatch",{enumerable:!0,configurable:!0,writable:!0,value:value=>{const r4=this._processingBatches.delete(value);this._updateBatchProcessStatus();return r4}});Object.defineProperty(this,"_processing",{enumerable:!0,configurable:!0,writable:!0,value:!1});Object.defineProperty(this,"_collected",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_clerks",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_processCount",{enumerable:!0,configurable:!0,writable:!0,value:0});this._root=this;this._processor=processor;this.batchSize=null!=(_a13=null==params?void 0:params.batchSize)?_a13:1;this.yieldThreshold=null!=(_c3=null!=(_b6=null==params?void 0:params.yieldThreshold)?_b6:null==params?void 0:params.batchSize)?_c3:0;this.concurrentLimit=null!=(_d2=null==params?void 0:params.concurrentLimit)?_d2:1;this.delay=null!=(_e2=null==params?void 0:params.delay)?_e2:0;this.maintainDelay=null!=(_f=null==params?void 0:params.maintainDelay)&&_f;this.interval=null!=(_g=null==params?void 0:params.interval)?_g:0;(null==params?void 0:params.keepResultUntilDownstreamConnected)&&(this._keepResultUntilDownstreamConnected=params.keepResultUntilDownstreamConnected);(null==params?void 0:params.remainingReactiveSource)&&(this._remainingReactiveSource=null==params?void 0:params.remainingReactiveSource);(null==params?void 0:params.totalRemainingReactiveSource)&&(this._totalRemainingReactiveSource=null==params?void 0:params.totalRemainingReactiveSource);(null==params?void 0:params.processingEntitiesReactiveSource)&&(this._processingEntitiesReactiveSource=null==params?void 0:params.processingEntitiesReactiveSource);void 0!==(null==params?void 0:params.suspended)&&(this._isSuspended=null==params?void 0:params.suspended);enqueueProcessor&&this.replaceEnqueueProcessor(enqueueProcessor);void 0!==(null==params?void 0:params.pipeTo)&&this.pipeTo(params.pipeTo);this._intervalPaceMaker=new PaceMaker(this.interval);items&&this.enqueueAll(items);allRunningProcessors.add(this);this._initClerks();this._initEventHub();this.resume()}replaceEnqueueProcessor(processor){this._enqueueProcessor=processor;return this}modifyQueue(processor){this._queue=processor(this._queue);this._onTick()}clearQueue(){this._queue=[];this._onTick()}onUpdateProgress(proc){this._runOnUpdateBatch=proc;return this}pipeTo(pipeTo){this._pipeTo=pipeTo;this._pipeTo._root=this.root;if(this._keptResult.length>0){const temp=[...this._keptResult];this._keptResult=[];this._pipeTo.enqueueAll(temp)}return pipeTo}isIdle(){return this._isIdle()&&(!this._pipeTo||this._pipeTo.isIdle())}_isIdle(){return 0==this.totalRemaining}async _waitForIdle(){if(this._isSuspended)return Promise.resolve();if(this._isIdle())return Promise.resolve();do{const r4=await this._waitFor(["tickEmpty","tick","tickSuspended","suspended","idle"]);if("tickSuspended"===r4)break;if("suspended"==r4)break;if("tickEmpty"==r4)break;if("idle"==r4)break}while(!this._isIdle());return Promise.resolve()}idleDetectors(){const thisPromise=this._waitForIdle();return this._pipeTo?[thisPromise,...this._pipeTo.idleDetectors()]:[thisPromise]}get isSuspended(){var _a13;return this._isSuspended||(null==(_a13=this._pipeTo)?void 0:_a13.isSuspended)||!1}_updateReactiveSource(){this.root.updateReactiveSource()}updateReactiveSource(){this._pipeTo&&this._pipeTo.updateReactiveSource();this._remainingReactiveSource&&(this._remainingReactiveSource.value=this.remaining);this._totalRemainingReactiveSource&&(this._totalRemainingReactiveSource.value=this.totalRemaining);this._processingEntitiesReactiveSource&&(this._processingEntitiesReactiveSource.value=this.nowProcessing)}_updateBatchProcessStatus(){this._updateReactiveSource();this._runOnUpdateBatch()}_collectBatch(){return this._queue.splice(0,this.batchSize)}_canCollectBatch(){return 0!==this._queue.length}enqueue(entity){this._queue=this._enqueueProcessor(this._queue,entity);this._updateBatchProcessStatus();this._onTick();return this}enqueueAll(entities){let queue2=this._queue;for(const v2 of entities)queue2=this._enqueueProcessor(queue2,v2);this._queue=queue2;this._updateBatchProcessStatus();this._onTick();return this}requestNextFlush(){this._nextProcessNeedsImmediate=!0;this._onTick()}async _waitForSuspended(){}flush(){if(this._isSuspended)return Promise.resolve(!1);this.requestNextFlush();return this.waitForAllDownstream()}async waitForAllDownstream(timeout){const baseTasks=[];timeout&&baseTasks.push(delay(timeout,RESULT_TIMED_OUT));do{const idleTasks=this.idleDetectors(),tasks3=[...baseTasks,Promise.all(idleTasks)],ret=await Promise.race(tasks3);if(ret===RESULT_TIMED_OUT)return!1}while(!this.isIdle());return!0}waitForAllProcessed(timeout){this.root.startPipeline();return this.root.waitForAllDownstream(timeout)}async waitForAllDoneAndTerminate(timeout){this.root.startPipeline();const r4=await this.root.waitForAllDownstream(timeout);this.terminateAll();return r4}async _runProcessor(items){const ret=await this._processor(items);ret&&(this._pipeTo?this._pipeTo.enqueueAll(ret):this._keepResultUntilDownstreamConnected&&this._keptResult.push(...ret))}async*pump(){do{const ticked=await this._waitFor(["tickImmediate","yielded","tickSuspended","tickDelayTimeout","tickSuspended"]);L2:do{const items=this._collectBatch();if(0==items.length)break L2;yield items}while(this._canCollectBatch());if("tickSuspended"==ticked)break}while(!this._isSuspended)}_initClerks(){this._collected=new Inbox(2*this.concurrentLimit);this._clerks=new ClerkGroup({assigned:this._collected,job:async items=>{const batchLength=items.length;this.updateStatus(()=>{this.processingEntities+=batchLength;this.waitingEntries-=batchLength});await this._intervalPaceMaker.paced;this._processCount++;try{await this._runProcessor(items)}catch(ex){Logger("Processor error!");Logger(ex,LOG_LEVEL_VERBOSE)}this.updateStatus(()=>{this.processingEntities-=batchLength});this._processCount--;0==this._processCount&&this._notifyIfIdle()},initialMemberCount:this.concurrentLimit,instantiate:params=>new Clerk(params)})}async _process(){if(!this._processing&&!this._isSuspended)try{this._processing=!0;do{const batchPump=this.pump();for await(const batch of batchPump){if(!batch||0===batch.length){this._hub.emitEvent("tickEmpty");continue}const batchLength=batch.length;this.updateStatus(()=>{this.waitingEntries+=batchLength});await this._collected.post(batch)}}while(!this._isSuspended);this._hub.emitEvent("suspended")}finally{this._processing=!1}}_run(){this._isSuspended||this._processing||fireAndForget(()=>this._process())}terminateAll(){this.root.terminate()}terminate(){if(this._pipeTo){this._pipeTo.terminate();this._pipeTo=void 0}this._isSuspended=!0;this._enqueueProcessor=()=>[];this._processor=()=>Promise.resolve([]);this.clearQueue();this._hub.emitEvent("tickSuspended");this._hub.emitEvent("tickSuspended");this._hub.emitEvent("tickSuspended");this._collected.dispose();this._clerks.dispose();this._queue.length=0;allRunningProcessors.delete(this)}};HIDDEN_FILE_NOTICE_GROUP="hidden-file-changes";HIDDEN_FILE_NOTICE_DURATION_MS=2e4;HiddenFileSync=class extends LiveSyncCommands{constructor(){super(...arguments);this.periodicInternalFileScanProcessor=new PeriodicProcessor(this.core,async()=>this.isThisModuleEnabled()&&this._isDatabaseReady()&&await this.scanAllStorageChanges(!1));this.semaphore=Semaphore(10);this.pendingConflictChecks=new Set;this.conflictResolutionProcessor=new QueueProcessor(async paths=>{var _a13,_b6,_c3;const path2=paths[0];try{const id=await this.path2id(path2,ICHeader),doc=await this.localDatabase.getRaw(id,{conflicts:!0});if(void 0===doc._conflicts){this.finishConflictCheck(path2);return[]}if(0==doc._conflicts.length){this.finishConflictCheck(path2);return[]}this._log(`Hidden file conflicted:${path2}`);const conflicts=doc._conflicts.sort((a2,b3)=>Number(a2.split("-")[0])-Number(b3.split("-")[0])),revA=doc._rev,revB=conflicts[0];if(path2.endsWith(".json")){const conflictedRev=conflicts[0],conflictedRevNo=Number(conflictedRev.split("-")[0]),revFrom=await this.localDatabase.getRaw(id,{revs_info:!0}),commonBase=null!=(_c3=null==(_b6=null==(_a13=revFrom._revs_info)?void 0:_a13.filter(e3=>"available"==e3.status&&Number(e3.rev.split("-")[0])<conflictedRevNo).first())?void 0:_b6.rev)?_c3:"",result=await this.localDatabase.managers.conflictManager.mergeObject(doc.path,commonBase,doc._rev,conflictedRev);if(result){this._log(`Object merge:${path2}`,LOG_LEVEL_INFO);const filename=stripAllPrefixes(path2);await this.ensureDir(filename);const stat=await this.writeFile(filename,result);if(!stat)throw new Error(`conflictResolutionProcessor: Failed to stat file ${filename}`);await this.storeInternalFileToDatabase({path:filename,...stat});await this.extractInternalFileFromDatabase(filename);await this.localDatabase.removeRevision(id,revB);this.requeueConflictCheck(path2);return[]}this._log("Object merge is not applicable.",LOG_LEVEL_VERBOSE);const regExp=getFileRegExp(this.settings,"syncInternalFileOverwritePatterns");if(regExp.some(r4=>r4.test(stripAllPrefixes(path2)))){this._log(`Overwrite rule applied for conflicted hidden file: ${path2}`,LOG_LEVEL_INFO);await this.resolveByNewerEntry(id,path2,doc,revA,revB);return[]}return[{path:path2,revA,revB,id,doc}]}await this.resolveByNewerEntry(id,path2,doc,revA,revB);return[]}catch(ex){this.finishConflictCheck(path2);this._log(`Failed to resolve conflict (Hidden): ${path2}`);this._log(ex,LOG_LEVEL_VERBOSE);return[]}},{suspended:!1,batchSize:1,concurrentLimit:5,delay:10,keepResultUntilDownstreamConnected:!0,yieldThreshold:10,pipeTo:new QueueProcessor(async results=>{const{id,doc,path:path2,revA,revB}=results[0],prefixedPath=addPrefix(path2,ICHeader),docAMerge=await this.localDatabase.getDBEntry(prefixedPath,{rev:revA}),docBMerge=await this.localDatabase.getDBEntry(prefixedPath,{rev:revB});try{if(0!=docAMerge&&0!=docBMerge){await this.showJSONMergeDialogAndMerge(docAMerge,docBMerge)?this.requeueConflictCheck(path2):this.finishConflictCheck(path2);return}await this.resolveByNewerEntry(id,path2,doc,revA,revB)}catch(ex){this.finishConflictCheck(path2);throw ex}},{suspended:!1,batchSize:1,concurrentLimit:1,delay:10,keepResultUntilDownstreamConnected:!1,yieldThreshold:10})});this.cacheFileRegExps=new Map;this.cacheCustomisationSyncIgnoredFiles=new Map;this.queuedNotificationFiles=new Set}isThisModuleEnabled(){return this.core.settings.syncInternalFiles}get kvDB(){return this.core.kvDB}getConflictedDoc(path2,rev3){return this.core.localDatabase.managers.conflictManager.getConflictedDoc(path2,rev3)}onunload(){var _a13;null==(_a13=this.periodicInternalFileScanProcessor)||_a13.disable()}onload(){this.services.API.addCommand({id:"livesync-sync-internal",name:"(re)initialise hidden files between storage and database",checkCallback:checking=>{if(!this.isManualCommandAvailable())return!1;checking||this.initialiseInternalFileSync("safe",!0);return!0}});this.services.API.addCommand({id:"livesync-scaninternal-storage",name:"Scan hidden file changes on the storage",checkCallback:checking=>{if(!this.isManualCommandAvailable())return!1;checking||this.scanAllStorageChanges(!0);return!0}});this.services.API.addCommand({id:"livesync-scaninternal-database",name:"Scan hidden file changes on the local database",checkCallback:checking=>{if(!this.isManualCommandAvailable())return!1;checking||this.scanAllDatabaseChanges(!0);return!0}});this.services.API.addCommand({id:"livesync-internal-scan-offline-changes",name:"Scan and apply all offline hidden-file changes",checkCallback:checking=>{if(!this.isManualCommandAvailable())return!1;checking||this.applyOfflineChanges(!0);return!0}});eventHub.onEvent(EVENT_SETTING_SAVED,()=>{this.updateSettingCache()})}async _everyOnDatabaseInitialized(showNotice){this._fileInfoLastProcessed=await autosaveCache(this.kvDB,"hidden-file-lastProcessed");this._databaseInfoLastProcessed=await autosaveCache(this.kvDB,"hidden-file-lastProcessed-database");this._fileInfoLastKnown=await autosaveCache(this.kvDB,"hidden-file-lastKnown");if(this.isThisModuleEnabled())if(0==this._fileInfoLastProcessed.size&&0==this._fileInfoLastProcessed.size){this._log("No cache found. Performing startup scan.",LOG_LEVEL_VERBOSE);await this.performStartupScan(!0)}else await this.performStartupScan(showNotice);return!0}async _everyBeforeReplicate(showNotice){this.isThisModuleEnabled()&&this._isDatabaseReady()&&this.settings.syncInternalFilesBeforeReplication&&!this.settings.watchInternalFileChanges&&await this.scanAllStorageChanges(showNotice);return!0}_everyOnloadAfterLoadSettings(){this.updateSettingCache();return Promise.resolve(!0)}updateSettingCache(){this.cacheCustomisationSyncIgnoredFiles.clear();this.cacheFileRegExps.clear()}isReady(){return!!this._isMainReady()&&(!this._isMainSuspended()&&!!this.isThisModuleEnabled())}isManualCommandAvailable(){return this.settings.useAdvancedMode&&this.isReady()&&this._isDatabaseReady()}async performStartupScan(showNotice){await this.applyOfflineChanges(showNotice)}async _everyOnResumeProcess(){var _a13;null==(_a13=this.periodicInternalFileScanProcessor)||_a13.disable();if(this._isMainSuspended())return!0;this.isThisModuleEnabled()&&await this.performStartupScan(!1);this.periodicInternalFileScanProcessor.enable(this.isThisModuleEnabled()&&this.settings.syncInternalFilesInterval?1e3*this.settings.syncInternalFilesInterval:0);return!0}_everyRealizeSettingSyncMode(){var _a13;null==(_a13=this.periodicInternalFileScanProcessor)||_a13.disable();if(this._isMainSuspended())return Promise.resolve(!0);if(!this.services.appLifecycle.isReady())return Promise.resolve(!0);this.periodicInternalFileScanProcessor.enable(this.isThisModuleEnabled()&&this.settings.syncInternalFilesInterval?1e3*this.settings.syncInternalFilesInterval:0);this.cacheFileRegExps.clear();return Promise.resolve(!0)}async _anyProcessOptionalFileEvent(path2){return this.isReady()&&await this.trackStorageFileModification(path2)||!1}_anyGetOptionalConflictCheckMethod(path2){if(isInternalMetadata(path2)){this.queueConflictCheck(path2);return Promise.resolve(!0)}return Promise.resolve(!1)}async _anyProcessOptionalSyncFiles(doc){if(isInternalMetadata(doc._id)){if(this.isThisModuleEnabled()){const filename=this.getPath(doc),unprefixedPath=stripAllPrefixes(filename);if(!await this.isTargetFile(stripAllPrefixes(unprefixedPath))){this._log(`Skipped processing sync file:${unprefixedPath} (Not Hidden File Sync target)`,LOG_LEVEL_VERBOSE);return!0}await this.processReplicationResult(doc)||this._log(`Failed to process sync file:${unprefixedPath}`,LOG_LEVEL_NOTICE)}return!0}return!1}async loadFileWithInfo(path2){var _a13,_b6;const stat=await this.core.storageAccess.statHidden(path2);if(!stat)return{name:null!=(_a13=path2.split("/").pop())?_a13:"",path:path2,stat:{size:0,mtime:0,ctime:0,type:"file"},isInternal:!0,deleted:!0,body:createBlob(new Uint8Array(0))};const content=await this.core.storageAccess.readHiddenFileAuto(path2);return{name:null!=(_b6=path2.split("/").pop())?_b6:"",path:path2,stat,isInternal:!0,deleted:!1,body:createBlob(content)}}statToKey(stat){var _a13,_b6;return`${null!=(_a13=null==stat?void 0:stat.mtime)?_a13:0}-${null!=(_b6=null==stat?void 0:stat.size)?_b6:0}`}docToKey(doc){return`${doc.mtime}-${doc.size}-${doc._rev}-${doc._deleted||doc.deleted?"-0":"-1"}`}async fileToStatKey(file,stat=null){stat||(stat=await this.core.storageAccess.statHidden(file));return this.statToKey(stat)}updateLastProcessedFile(file,keySrc){const key3="string"==typeof keySrc?keySrc:this.statToKey(keySrc),splitted=key3.split("-");"0"!=splitted[0]&&this._fileInfoLastKnown.set(file,Number(splitted[0]));this._fileInfoLastProcessed.set(file,key3)}async updateLastProcessedAsActualFile(file,stat){stat||(stat=await this.core.storageAccess.statHidden(file));this._fileInfoLastProcessed.set(file,this.statToKey(stat))}resetLastProcessedFile(targetFiles){if(targetFiles)for(const key3 of targetFiles)this._fileInfoLastProcessed.delete(key3);else{this._log("Delete all processed mark.",LOG_LEVEL_VERBOSE);this._fileInfoLastProcessed.clear()}}getLastProcessedFileMTime(file){const key3=this._fileInfoLastKnown.get(file);return key3||0}getLastProcessedFileKey(file){return this._fileInfoLastProcessed.get(file)}getLastProcessedDatabaseKey(file){return this._databaseInfoLastProcessed.get(file)}updateLastProcessedDatabase(file,keySrc){const key3="string"==typeof keySrc?keySrc:this.docToKey(keySrc);this._databaseInfoLastProcessed.set(file,key3)}updateLastProcessed(path2,db,stat){this.updateLastProcessedDatabase(path2,db);this.updateLastProcessedFile(path2,this.statToKey(stat));const dbMTime=getComparingMTime(db),storageMTime=getComparingMTime(stat);0==dbMTime||0==storageMTime?this.services.path.unmarkChanges(path2):this.services.path.markChangesAreSame(path2,getComparingMTime(db),getComparingMTime(stat))}updateLastProcessedDeletion(path2,db){this.services.path.unmarkChanges(path2);db&&this.updateLastProcessedDatabase(path2,db);this.updateLastProcessedFile(path2,this.statToKey(null))}async ensureDir(path2){const isExists=await this.core.storageAccess.isExistsIncludeHidden(path2);isExists||await this.core.storageAccess.ensureDir(path2)}async writeFile(path2,data,opt){await this.core.storageAccess.writeHiddenFileAuto(path2,data,opt);const stat=await this.core.storageAccess.statHidden(path2);return stat}async __removeFile(path2){try{if(!await this.core.storageAccess.isExistsIncludeHidden(path2))return"ALREADY";if(await this.core.storageAccess.removeHidden(path2))return"OK"}catch(ex){this._log(`Failed to remove file:${path2}`);this._log(ex,LOG_LEVEL_VERBOSE)}return!1}async triggerEvent(path2){try{await this.core.storageAccess.triggerHiddenFile(path2)}catch(ex){this._log("Failed to call internal API(reconcileInternalFile)",LOG_LEVEL_VERBOSE);this._log(ex,LOG_LEVEL_VERBOSE)}}async updateLastProcessedAsActualDatabase(file,doc){const dbPath=addPrefix(file,ICHeader);doc||(doc=await this.localDatabase.getDBEntryMeta(dbPath));doc&&this._databaseInfoLastProcessed.set(file,this.docToKey(doc))}resetLastProcessedDatabase(targetFiles){if(targetFiles)for(const key3 of targetFiles)this._databaseInfoLastProcessed.delete(key3);else{this._log("Delete all processed mark.",LOG_LEVEL_VERBOSE);this._databaseInfoLastProcessed.clear()}}async adoptCurrentStorageFilesAsProcessed(targetFiles){const allFiles=await this.scanInternalFileNames(),files=targetFiles?allFiles.filter(e3=>targetFiles.some(t9=>-1!==e3.indexOf(t9))):allFiles;for(const file of files)await this.updateLastProcessedAsActualFile(file)}async adoptCurrentDatabaseFilesAsProcessed(targetFiles){const allFiles=await this.getAllDatabaseFiles(),files=targetFiles?allFiles.filter(e3=>targetFiles.some(t9=>-1!==e3.path.indexOf(t9))):allFiles;for(const file of files){const path2=stripAllPrefixes(this.getPath(file));await this.updateLastProcessedAsActualDatabase(path2,file)}}async serializedForEvent(file,fn){hiddenFilesEventCount.value++;const rel=await this.semaphore.acquire();try{return await serialized(`hidden-file-event:${file}`,async()=>{hiddenFilesProcessingCount.value++;try{return await fn()}finally{hiddenFilesProcessingCount.value--}})}finally{rel();hiddenFilesEventCount.value--}}async useStorageFiles(files,showNotice=!1,onlyNew=!1){return await this.trackScannedStorageChanges(files,showNotice,onlyNew,!0)}async trackScannedStorageChanges(processFiles,showNotice=!1,onlyNew=!1,forceWriteAll=!1,includeDeleted=!0){const logLevel=getLogLevel(showNotice),p2=this._progress("[⚙ Storage -> DB ]\n",logLevel),notifyProgress=onlyInNTimes(100,progress=>p2.log(`${progress}/${processFiles.length}`)),processes=processFiles.map(async(file,i3)=>{try{await this.trackStorageFileModification(file,onlyNew,forceWriteAll,includeDeleted);notifyProgress()}catch(ex){p2.once(`Failed to process storage change file:${file}`);this._log(ex,LOG_LEVEL_VERBOSE)}});await Promise.all(processes);p2.done()}async scanAllStorageChanges(showNotice=!1,onlyNew=!1,forceWriteAll=!1,includeDeleted=!0){return await skipIfDuplicated("scanAllStorageChanges",async()=>{const logLevel=getLogLevel(showNotice),p2=this._progress("[⚙ Scanning Storage -> DB ]\n",logLevel);p2.log("Scanning storage files...");const knownNames=[...this._fileInfoLastProcessed.keys()],existNames=await this.scanInternalFileNames(),files=new Set([...knownNames,...existNames]);this._log(`Known/Exist ${knownNames.length}/${existNames.length}, Totally ${files.size} files.`,LOG_LEVEL_VERBOSE);const taskNameAndMeta=[...files].map(async e3=>[e3,await this.core.storageAccess.statHidden(e3)]),nameAndMeta=await Promise.all(taskNameAndMeta),processFiles=nameAndMeta.filter(([path2,stat])=>{if(forceWriteAll)return!0;const key3=this.getLastProcessedFileKey(path2),newKey=this.statToKey(stat);return key3!=newKey}).map(([path2,stat])=>path2),staticsMessage=`[Storage hidden file statics]\nKnown files: ${knownNames.length}\nActual files: ${existNames.length}\nAll files: ${files.size}\nOffline Changed files: ${processFiles.length}`;p2.once(staticsMessage);await this.trackScannedStorageChanges(processFiles,showNotice,onlyNew,forceWriteAll,includeDeleted);p2.done()})}async trackStorageFileModification(path2,onlyNew=!1,forceWrite=!1,includeDeleted=!0){if(!await this.isTargetFile(path2)){this._log(`Storage file tracking: Hidden file skipped: ${path2} is filtered out by the defined patterns.`,LOG_LEVEL_VERBOSE);return!1}try{return await this.serializedForEvent(path2,async()=>{let stat=await this.core.storageAccess.statHidden(path2);if(null!=stat&&"file"!=stat.type)return!1;const key3=await this.fileToStatKey(path2,stat),lastKey=this.getLastProcessedFileKey(path2);if(lastKey==key3){this._log(`${path2} Already processed.`,LOG_LEVEL_DEBUG);return!0}const cache2=await this.loadFileWithInfo(path2),cacheMTime=getComparingMTime(cache2.stat),statMtime=getComparingMTime(stat);if(cacheMTime!=statMtime){this._log(`Hidden file:${path2} is changed.`,LOG_LEVEL_VERBOSE);stat=cache2.stat}this.updateLastProcessedFile(path2,stat);const lastIsNotFound=!lastKey||lastKey.endsWith("-0-0"),nowIsNotFound=cache2.deleted,type=lastIsNotFound&&nowIsNotFound?"invalid":nowIsNotFound?"delete":"modified";if("invalid"==type)return!1;const storageMTimeActual=getComparingMTime(stat),storageMTime=0==storageMTimeActual?this.getLastProcessedFileMTime(path2):storageMTimeActual;if(onlyNew){const prefixedFileName=addPrefix(path2,ICHeader),filesOnDB=await this.localDatabase.getDBEntryMeta(prefixedFileName),dbMTime=getComparingMTime(filesOnDB,includeDeleted),diff=compareMTime(storageMTime,dbMTime);if(diff!=TARGET_IS_NEW){this._log(`Hidden file:${path2} is not new.`,LOG_LEVEL_VERBOSE);filesOnDB&&stat&&this.updateLastProcessed(path2,filesOnDB,stat);return!0}}if("delete"==type){this._log(`Deletion detected: ${path2}`);const result=await this.deleteInternalFileOnDatabase(path2,forceWrite);return result}if("modified"==type){this._log(`Modification detected:${path2}`,LOG_LEVEL_VERBOSE);const result=await this.storeInternalFileToDatabase(cache2,forceWrite),resultText=void 0===result?"Nothing changed":result?"Updated":"Failed";this._log(`${resultText}: ${path2} ${resultText}`,LOG_LEVEL_VERBOSE);return result}})}catch(ex){this._log(`Failed to process hidden file:${path2}`);this._log(ex,LOG_LEVEL_VERBOSE)}return!0}queueConflictCheck(path2){if(!this.pendingConflictChecks.has(path2)){this.pendingConflictChecks.add(path2);this.conflictResolutionProcessor.enqueue(path2)}}finishConflictCheck(path2){this.pendingConflictChecks.delete(path2)}requeueConflictCheck(path2){this.finishConflictCheck(path2);this.queueConflictCheck(path2)}async resolveConflictOnInternalFiles(){const conflicted=this.localDatabase.findEntries(ICHeader,ICHeaderEnd,{conflicts:!0});this.conflictResolutionProcessor.suspend();try{for await(const doc of conflicted)"_conflicts"in doc&&isInternalMetadata(doc._id)&&this.queueConflictCheck(doc.path)}catch(ex){this._log("something went wrong on resolving all conflicted internal files");this._log(ex,LOG_LEVEL_VERBOSE)}await this.conflictResolutionProcessor.startPipeline().waitForAllProcessed()}async resolveByNewerEntry(id,path2,currentDoc,currentRev,conflictedRev){var _a13;const conflictedDoc=await this.localDatabase.getRaw(id,{rev:conflictedRev}),mtimeCurrent=getComparingMTime(currentDoc,!0),mtimeConflicted=getComparingMTime(conflictedDoc,!0),delRev=mtimeCurrent<mtimeConflicted?currentRev:conflictedRev;await this.localDatabase.removeRevision(id,delRev);this._log(`Older one has been deleted:${path2}`);const cc2=await this.localDatabase.getRaw(id,{conflicts:!0});if(0===(null==(_a13=cc2._conflicts)?void 0:_a13.length)){await this.extractInternalFileFromDatabase(stripAllPrefixes(path2));this.finishConflictCheck(path2)}else this.requeueConflictCheck(path2)}showJSONMergeDialogAndMerge(docA,docB){return new Promise(res2=>{this._log("Opening data-merging dialog",LOG_LEVEL_VERBOSE);const docs=[docA,docB],strippedPath=stripAllPrefixes(docA.path),storageFilePath=strippedPath,storeFilePath=strippedPath,displayFilename=`${storeFilePath}`;sendSignal(`cancel-internal-conflict:${docA.path}`);const modal=new JsonResolveModal(this.app,storageFilePath,[docA,docB],async(keep,result)=>{var _a13,_b6;try{let needFlush=!1;if(!result&&!keep){this._log(`Skipped merging: ${displayFilename}`);res2(!1);return}if(result||keep)for(const doc of docs)if(doc._rev!=keep&&await this.localDatabase.deleteDBEntry(this.getPath(doc),{rev:doc._rev})){this._log(`Conflicted revision has been deleted: ${displayFilename}`);needFlush=!0}if(!keep&&result){const isExists=await this.core.storageAccess.isExistsIncludeHidden(storageFilePath);isExists||await this.core.storageAccess.ensureDir(storageFilePath);const stat=await this.writeFile(storageFilePath,result);if(!stat)throw new Error("Stat failed");const mtime=getComparingMTime(stat);await this.storeInternalFileToDatabase({path:storageFilePath,mtime,ctime:null!=(_a13=null==stat?void 0:stat.ctime)?_a13:mtime,size:null!=(_b6=null==stat?void 0:stat.size)?_b6:0},!0);await this.triggerEvent(storageFilePath);this._log(`STORAGE <-- DB:${displayFilename}: written (hidden,merged)`)}needFlush&&(await this.extractInternalFileFromDatabase(storeFilePath,!1)?this._log(`STORAGE --\x3e DB:${displayFilename}: extracted (hidden,merged)`):this._log(`STORAGE --\x3e DB:${displayFilename}: extracted (hidden,merged) Failed`));res2(!0)}catch(ex){this._log("Could not merge conflicted json");this._log(ex,LOG_LEVEL_VERBOSE);res2(!1)}});modal.open()})}getDocProps(doc){const id=doc._id,shortenedId=id.substring(0,10),prefixedPath=this.getPath(doc),path2=stripAllPrefixes(prefixedPath),rev3=doc._rev,revDisplay=rev3?displayRev(rev3):"0-NOREVS",shortenedPath=path2.substring(0,10),isDeleted2=doc._deleted||doc.deleted||!1;return{id,rev:rev3,revDisplay,prefixedPath,path:path2,isDeleted:isDeleted2,shortenedId,shortenedPath}}async processReplicationResult(doc){const info3=this.getDocProps(doc),path2=info3.path,headerLine=`Tracking DB ${info3.path} (${info3.revDisplay}) :`,ret=await this.trackDatabaseFileModification(path2,headerLine);this._log(`${headerLine} Done: ${info3.shortenedId})`,LOG_LEVEL_VERBOSE);return ret}parseRegExpSettings(){const regExpKey=`${this.core.settings.syncInternalFilesTargetPatterns}||${this.core.settings.syncInternalFilesIgnorePatterns}`;let ignoreFilter,targetFilter;if(this.cacheFileRegExps.has(regExpKey)){const cached=this.cacheFileRegExps.get(regExpKey);ignoreFilter=cached[1];targetFilter=cached[0]}else{ignoreFilter=getFileRegExp(this.core.settings,"syncInternalFilesIgnorePatterns");targetFilter=getFileRegExp(this.core.settings,"syncInternalFilesTargetPatterns");this.cacheFileRegExps.clear();this.cacheFileRegExps.set(regExpKey,[targetFilter,ignoreFilter])}return{ignoreFilter,targetFilter}}isTargetFileInPatterns(path2){const{ignoreFilter,targetFilter}=this.parseRegExpSettings();if(ignoreFilter&&ignoreFilter.length>0)for(const pattern of ignoreFilter)if(pattern.test(path2))return!1;if(targetFilter&&targetFilter.length>0){for(const pattern of targetFilter)if(pattern.test(path2))return!0;return!1}return!0}getCustomisationSynchronizationIgnoredFiles(){const configDir=this.services.API.getSystemConfigDir(),key3=JSON.stringify(this.settings.pluginSyncExtendedSetting)+`||${this.settings.usePluginSync}||${configDir}`;if(this.cacheCustomisationSyncIgnoredFiles.has(key3))return this.cacheCustomisationSyncIgnoredFiles.get(key3);this.cacheCustomisationSyncIgnoredFiles.clear();const synchronisedInConfigSync=this.settings.usePluginSync?Object.values(this.settings.pluginSyncExtendedSetting).filter(e3=>e3.mode==MODE_SELECTIVE||e3.mode==MODE_PAUSED).map(e3=>e3.files).flat().map(e3=>`${configDir}/${e3}`.toLowerCase()):[];this.cacheCustomisationSyncIgnoredFiles.set(key3,synchronisedInConfigSync);return synchronisedInConfigSync}isNotIgnoredByCustomisationSync(path2){const ignoredFiles=this.getCustomisationSynchronizationIgnoredFiles(),result=!ignoredFiles.some(e3=>path2.startsWith(e3));return result}isHiddenFileSyncHandlingPath(path2){const result=path2.startsWith(".")&&!path2.startsWith(".trash");return result}async isTargetFile(path2){const result=this.isTargetFileInPatterns(path2)&&this.isNotIgnoredByCustomisationSync(path2)&&this.isHiddenFileSyncHandlingPath(path2);if(!result)return!1;const resultByFile=await this.services.vault.isIgnoredByIgnoreFile(path2);return!resultByFile}async trackScannedDatabaseChange(processFiles,showNotice=!1,onlyNew=!1,forceWriteAll=!1,includeDeletion=!0){const logLevel=getLogLevel(showNotice),p2=this._progress("[⚙ DB -> Storage ]\n",logLevel),notifyProgress=onlyInNTimes(100,progress=>p2.log(`${progress}/${processFiles.length}`)),processes=processFiles.map(async file=>{try{const path2=stripAllPrefixes(this.getPath(file));await this.isTargetFile(path2)?await this.trackDatabaseFileModification(path2,"[Hidden file scan]",!forceWriteAll,onlyNew,file,includeDeletion):this._log(`Database file tracking: Hidden file skipped: ${path2} is filtered out by the defined patterns.`,LOG_LEVEL_VERBOSE);notifyProgress()}catch(ex){this._log(`Failed to process storage change file:${tryGetFilePath(file)}`,logLevel);this._log(ex,LOG_LEVEL_VERBOSE)}});await Promise.all(processes);p2.done()}async applyOfflineChanges(showNotice){const logLevel=getLogLevel(showNotice);return await serialized("applyOfflineChanges",async()=>{const p2=this._progress("[⚙ Apply untracked changes ]\n",logLevel);this._log("Track changes.",logLevel);p2.log("Enumerating local files...");const currentStorageFiles=await this.scanInternalFileNames();p2.log("Enumerating database files...");const currentDatabaseFiles=await this.getAllDatabaseFiles(),allDatabaseMap=Object.fromEntries(currentDatabaseFiles.map(e3=>[stripAllPrefixes(this.getPath(e3)),e3])),currentDatabaseFileNames=[...Object.keys(allDatabaseMap)],untrackedLocal=currentStorageFiles.filter(e3=>!this._fileInfoLastProcessed.has(e3)),untrackedDatabase=currentDatabaseFileNames.filter(e3=>!this._databaseInfoLastProcessed.has(e3)),bothUntracked=untrackedLocal.filter(e3=>-1!==untrackedDatabase.indexOf(e3));p2.log("Applying untracked changes...");const stat=`Tracking statics:\nLocal files: ${currentStorageFiles.length}\nDatabase files: ${currentDatabaseFileNames.length}\nUntracked local files: ${untrackedLocal.length}\nUntracked database files: ${untrackedDatabase.length}\nCommon untracked files: ${bothUntracked.length}`;p2.once(stat);const semaphores2=Semaphore(10),notifyProgress=onlyInNTimes(25,progress=>p2.log(`${progress}/${bothUntracked.length}`)),allProcesses=bothUntracked.map(async file=>{notifyProgress();const rel=await semaphores2.acquire();try{const fileStat=await this.core.storageAccess.statHidden(file);if(null==fileStat){this._log(`Unexpected error: Failed to stat file during applyOfflineChange :${file}`);return}const dbInfo=allDatabaseMap[file];if(dbInfo.deleted||dbInfo._deleted)return;const fileMTime=getComparingMTime(fileStat),dbMTime=getComparingMTime(dbInfo),diff=compareMTime(fileMTime,dbMTime);diff==BASE_IS_NEW?await this.trackStorageFileModification(file,!0):diff==TARGET_IS_NEW?await this.trackDatabaseFileModification(file,"[Apply]",!0,!0,dbInfo):diff==EVEN&&this.updateLastProcessed(file,dbInfo,fileStat)}finally{rel()}});await Promise.all(allProcesses);await this.scanAllStorageChanges(showNotice);await this.scanAllDatabaseChanges(showNotice);p2.done()})}async scanAllDatabaseChanges(showNotice=!1,onlyNew=!1,forceWriteAll=!1,includeDeletion=!0){return await skipIfDuplicated("scanAllDatabaseChanges",async()=>{const databaseFiles=await this.getAllDatabaseFiles(),files=databaseFiles.filter(e3=>{const doc=e3,key3=this.docToKey(doc),path2=stripAllPrefixes(this.getPath(doc)),lastKey=this.getLastProcessedDatabaseKey(path2);return lastKey!=key3}),logLevel=getLogLevel(showNotice),staticsMessage=`[Database hidden file statics]\nAll files: ${databaseFiles.length}\nOffline Changed files: ${files.length}`;this._log(staticsMessage,logLevel,"scan-changes");return await this.trackScannedDatabaseChange(files,showNotice,onlyNew,forceWriteAll,includeDeletion)})}async useDatabaseFiles(files,showNotice=!1,onlyNew=!1){const logLevel=getLogLevel(showNotice),p2=this._progress("[⚙ Scanning DB -> Storage ]\n",logLevel);p2.log("Scanning database files...");const notifyProgress=onlyInNTimes(25,progress=>p2.log(`${progress}/${files.length}`)),processFiles=files.map(async file=>{try{const path2=stripAllPrefixes(this.getPath(file));await this.trackDatabaseFileModification(path2,"[Scanning]",!0,onlyNew,file);notifyProgress()}catch(ex){this._log(`Failed to process database changes:${tryGetFilePath(file)}`);this._log(ex,LOG_LEVEL_VERBOSE)}});await Promise.all(processFiles);p2.done();return!0}async trackDatabaseFileModification(path2,headerLine,preventDoubleProcess=!1,onlyNew=!1,meta=!1,includeDeletion=!0){return await this.serializedForEvent(path2,async()=>{try{const prefixedPath=addPrefix(path2,ICHeader),docMeta=meta||await this.localDatabase.getDBEntryMeta(prefixedPath,{conflicts:!0},!0);if(!1===docMeta){this._log(`${headerLine}: Failed to read detail of ${path2}`);throw new Error(`Failed to read detail ${path2}`)}if(docMeta._conflicts&&docMeta._conflicts.length>0){this.queueConflictCheck(path2);this._log(`${headerLine} Hidden file conflicted, enqueued to resolve`);return!0}const extractResult=await this.extractInternalFileFromDatabase(path2,!1,docMeta,preventDoubleProcess,onlyNew,includeDeletion);extractResult&&this._log(`${headerLine} Hidden file processed`)}catch(ex){this._log(`${headerLine} Failed to process hidden file`);this._log(ex,LOG_LEVEL_VERBOSE)}return!0})}notifyConfigChange(){const updatedFolders=[...this.queuedNotificationFiles];this.queuedNotificationFiles.clear();const noticeGroups=this.services.context.noticeGroups;let hasNoticeItems=!1;try{const pluginManager=getObsidianCommunityPluginManager(this.app),enabledPluginManifests=pluginManager.manifests.filter(manifest=>pluginManager.enabledPlugins.has(manifest.id)),modifiedManifests=enabledPluginManifests.filter(e3=>{var _a13;return updatedFolders.indexOf(null!=(_a13=null==e3?void 0:e3.dir)?_a13:"")>=0});for(const manifest of modifiedManifests){const updatePluginId=manifest.id,updatePluginName=manifest.name,itemKey=`plugin:${updatePluginId}`;noticeGroups.setItem(HIDDEN_FILE_NOTICE_GROUP,itemKey,{message:`Files in ${updatePluginName} were updated.`,action:{label:`Reload ${updatePluginName}`,onSelect:()=>{fireAndForget(async()=>{this._log(`Unloading plugin: ${updatePluginName}`,LOG_LEVEL_NOTICE,"plugin-reload-"+updatePluginId);await pluginManager.unloadPlugin(updatePluginId);await pluginManager.loadPlugin(updatePluginId);this._log(`Plugin reloaded: ${updatePluginName}`,LOG_LEVEL_NOTICE,"plugin-reload-"+updatePluginId);noticeGroups.removeItem(HIDDEN_FILE_NOTICE_GROUP,itemKey)})}}});hasNoticeItems=!0}}catch(ex){this._log("Error on checking plugin status.");this._log(ex,LOG_LEVEL_VERBOSE)}if(updatedFolders.indexOf(this.services.API.getSystemConfigDir())>=0)if(this.services.appLifecycle.isReloadingScheduled())noticeGroups.removeItem(HIDDEN_FILE_NOTICE_GROUP,"restart");else{noticeGroups.setItem(HIDDEN_FILE_NOTICE_GROUP,"restart",{message:"Other Obsidian settings files were updated.",action:{label:"Schedule an Obsidian restart",onSelect:()=>{this.services.appLifecycle.scheduleRestart();noticeGroups.removeItem(HIDDEN_FILE_NOTICE_GROUP,"restart")}}});hasNoticeItems=!0}hasNoticeItems&&noticeGroups.finish(HIDDEN_FILE_NOTICE_GROUP,{durationMs:HIDDEN_FILE_NOTICE_DURATION_MS})}queueNotification(key3){if(this.settings.suppressNotifyHiddenFilesChange)return;const configDir=this.services.API.getSystemConfigDir();if(!key3.startsWith(configDir))return;const dirName=key3.split("/").slice(0,-1).join("/");this.queuedNotificationFiles.add(dirName);scheduleTask("notify-config-change",1e3,()=>{this.notifyConfigChange()})}async rebuildMerging(showNotice,targetFiles=!1){const logLevel=getLogLevel(showNotice),p2=this._progress("[⚙ Rebuild by Merge ]\n",logLevel);this._log("Rebuilding hidden files from the storage and the local database.",logLevel);p2.log("Enumerating local files...");const currentStorageFilesAll=await this.scanInternalFileNames(),currentStorageFiles=targetFiles?currentStorageFilesAll.filter(e3=>targetFiles.some(f4=>f4==e3)):currentStorageFilesAll;p2.log("Enumerating database files...");const allDatabaseFiles=await this.getAllDatabaseFiles(),allDatabaseMap=new Map(allDatabaseFiles.map(e3=>[stripAllPrefixes(this.getPath(e3)),e3])),currentDatabaseFiles=targetFiles?allDatabaseFiles.filter(e3=>targetFiles.some(f4=>f4==stripAllPrefixes(this.getPath(e3)))):allDatabaseFiles,allFileNames=new Set([...currentStorageFiles,...currentDatabaseFiles.map(e3=>stripAllPrefixes(this.getPath(e3)))]),storageToDatabase=[],databaseToStorage=[],eachProgress=onlyInNTimes(100,progress=>p2.log(`Checking ${progress}/${allFileNames.size}`));for(const file of allFileNames){eachProgress();const storageMTime=await this.core.storageAccess.statHidden(file),mtimeStorage=getComparingMTime(storageMTime),dbEntry=allDatabaseMap.get(file),mtimeDB=getComparingMTime(dbEntry),diff=compareMTime(mtimeStorage,mtimeDB);diff==BASE_IS_NEW?storageToDatabase.push(file):diff==TARGET_IS_NEW?databaseToStorage.push(dbEntry):diff==EVEN&&storageToDatabase.push(file)}p2.once(`Storage to Database: ${storageToDatabase.length} files\n Database to Storage: ${databaseToStorage.length} files`);this.resetLastProcessedDatabase(targetFiles);this.resetLastProcessedFile(targetFiles);const processes=[this.useStorageFiles(storageToDatabase,showNotice,!1),this.useDatabaseFiles(databaseToStorage,showNotice,!1)];p2.log("Start processing...");await Promise.all(processes);p2.done();return[...allFileNames]}async rebuildFromStorage(showNotice,targetFiles=!1,onlyNew=!1){const logLevel=getLogLevel(showNotice);this._verbose("Rebuilding hidden files from the storage.");this._log("Rebuilding hidden files from the storage.",logLevel);const p2=this._progress("[⚙ Rebuild by Storage ]\n",logLevel);p2.log("Enumerating local files...");const currentFilesAll=await this.scanInternalFileNames(),currentFiles=targetFiles?currentFilesAll.filter(e3=>targetFiles.some(f4=>f4==e3)):currentFilesAll;p2.once(`Storage to Database: ${currentFiles.length} files.`);p2.log("Start processing...");this.resetLastProcessedFile(targetFiles);await this.useStorageFiles(currentFiles,showNotice,onlyNew);p2.done();return currentFiles}async getAllDatabaseFiles(){const allFiles=(await this.localDatabase.allDocsRaw({startkey:ICHeader,endkey:ICHeaderEnd,include_docs:!0})).rows.filter(e3=>isInternalMetadata(e3.id)).map(e3=>e3.doc),files=[];for(const file of allFiles)await this.isTargetFile(stripAllPrefixes(this.getPath(file)))&&files.push(file);return files}async rebuildFromDatabase(showNotice,targetFiles=!1,onlyNew=!1){const logLevel=getLogLevel(showNotice);this._verbose("Rebuilding hidden files from the local database.");const p2=this._progress("[⚙ Rebuild by Database ]\n",logLevel);p2.log("Enumerating database files...");const allFiles=await this.getAllDatabaseFiles(),currentFiles=targetFiles?allFiles.filter(e3=>targetFiles.some(f4=>f4==stripAllPrefixes(this.getPath(e3)))):allFiles;p2.once(`Database to Storage: ${currentFiles.length} files.`);this.resetLastProcessedDatabase(targetFiles);p2.log("Start processing...");await this.useDatabaseFiles(currentFiles,showNotice,onlyNew);p2.done();return currentFiles}async initialiseInternalFileSync(direction,showMessage2,targetFilesSrc=!1,initialisationProgress){const logLevel=showMessage2?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,p2=null!=initialisationProgress?initialisationProgress:this._progress("[⚙ Initialise]\n",logLevel);p2.log("Initialising hidden files sync...");const targetFiles=!!targetFilesSrc&&targetFilesSrc.map(e3=>stripAllPrefixes(e3));if("pushForce"==direction||"push"==direction){const onlyNew="push"==direction;p2.log("Started: Storage --\x3e Database "+(onlyNew?"(Only New)":""));const updatedFiles=await this.rebuildFromStorage(false,targetFiles,onlyNew);await this.adoptCurrentStorageFilesAsProcessed(updatedFiles);await this.adoptCurrentDatabaseFilesAsProcessed(updatedFiles);p2.log("Checking for remaining storage and database changes...");await this.scanAllStorageChanges(false,!0,!1);await this.scanAllDatabaseChanges(false,!0,!1)}if("pullForce"==direction||"pull"==direction){const onlyNew="pull"==direction;p2.log("Started: Database --\x3e Storage "+(onlyNew?"(Only New)":""));const updatedEntries=await this.rebuildFromDatabase(false,targetFiles,onlyNew),updatedFiles=updatedEntries.map(e3=>stripAllPrefixes(this.getPath(e3)));await this.adoptCurrentStorageFilesAsProcessed(updatedFiles);await this.adoptCurrentDatabaseFilesAsProcessed(updatedFiles);p2.log("Checking for remaining database and storage changes...");await this.scanAllDatabaseChanges(false,!0,!1);await this.scanAllStorageChanges(false,!0,!1)}if("safe"==direction){p2.log("Started: Database <--\x3e Storage (by modified date)");const updatedFiles=await this.rebuildMerging(false,targetFiles);await this.adoptCurrentStorageFilesAsProcessed(updatedFiles);await this.adoptCurrentDatabaseFilesAsProcessed(updatedFiles);p2.log("Checking for remaining storage and database changes...");await this.scanAllStorageChanges(false,!0,!1);await this.scanAllDatabaseChanges(false,!0,!1)}p2.done()}async __loadBaseSaveData(file,includeContent=!0){const prefixedFileName=addPrefix(file,ICHeader),id=await this.path2id(prefixedFileName,ICHeader);try{const old=includeContent?await this.localDatabase.getDBEntry(prefixedFileName,void 0,!1,!0):await this.localDatabase.getDBEntryMeta(prefixedFileName,{conflicts:!0},!0);if(!1===old){const baseSaveData={_id:id,data:[],path:prefixedFileName,mtime:0,ctime:0,datatype:"newnote",children:[],size:0,deleted:!1,type:"newnote",eden:{}};return baseSaveData}return old}catch(ex){this._log("Getting base save data failed");this._log(ex,LOG_LEVEL_VERBOSE);return!1}}async getLiveInternalRevision(prefixedFileName,revision){const[selected,current,conflicts]=await Promise.all([this.core.databaseFileAccess.fetchEntryMeta(prefixedFileName,revision,!0),this.core.databaseFileAccess.fetchEntryMeta(prefixedFileName,void 0,!0),this.core.databaseFileAccess.getConflictedRevs(prefixedFileName)]),liveRevisions=new Set([...current&&current._rev?[current._rev]:[],...conflicts]);if(!selected||selected._rev!==revision||!liveRevisions.has(revision)){this._log(`Could not use hidden-file revision ${revision} of ${stripAllPrefixes(prefixedFileName)}; the selected revision is no longer live`,LOG_LEVEL_NOTICE);return!1}return selected}async storeInternalFileToDatabase(file,forceWrite=!1){const storeFilePath=stripAllPrefixes(file.path),storageFilePath=file.path;if(await this.services.vault.isIgnoredByIgnoreFile(storageFilePath))return;const prefixedFileName=addPrefix(storeFilePath,ICHeader);return await serialized("file-"+prefixedFileName,async()=>{try{const fileInfo="stat"in file&&"body"in file?file:await this.loadFileWithInfo(storeFilePath);if(fileInfo.deleted)throw new Error(`Hidden file:${storeFilePath} is deleted. This should not be occurred.`);const baseData=await this.__loadBaseSaveData(storeFilePath,!0);if(!1===baseData)throw new Error("Failed to load base data");if(baseData._rev&&!forceWrite){const isSame=await isDocContentSame(readAsBlob(baseData),fileInfo.body);if(isSame){this.updateLastProcessed(storeFilePath,baseData,fileInfo.stat);return}}const saveData={...baseData,data:fileInfo.body,mtime:fileInfo.stat.mtime,size:fileInfo.stat.size,children:[],deleted:!1,type:baseData.datatype},ret=await this.localDatabase.putDBEntry(saveData);if(ret&&ret.ok){saveData._rev=ret.rev;this.updateLastProcessed(storeFilePath,saveData,fileInfo.stat)}const success=ret&&ret.ok;this._log(`STORAGE --\x3e DB:${storageFilePath}: (hidden) ${success?"Done":"Failed"}`);return success}catch(ex){this._log(`STORAGE --\x3e DB:${storageFilePath}: (hidden) Failed`);this._log(ex,LOG_LEVEL_VERBOSE);return!1}})}async storeInternalFileToDatabaseWithBaseRevision(file,baseRevision,createIfDifferent=!0){const storeFilePath=stripAllPrefixes(file.path),storageFilePath=file.path;if(await this.services.vault.isIgnoredByIgnoreFile(storageFilePath))return!1;const prefixedFileName=addPrefix(storeFilePath,ICHeader);return await serialized("file-"+prefixedFileName,async()=>{try{const baseData=await this.getLiveInternalRevision(prefixedFileName,baseRevision);if(!1===baseData)return!1;const fileInfo="stat"in file&&"body"in file?file:await this.loadFileWithInfo(storeFilePath);if(fileInfo.deleted)throw new Error(`Hidden file:${storeFilePath} is deleted. This should not be occurred.`);if(!baseData.deleted&&!baseData._deleted){const loadedBase=await this.core.databaseFileAccess.fetchEntryFromMeta(baseData,!0,!0);if(loadedBase&&await isDocContentSame(readAsBlob(loadedBase),fileInfo.body)){this.updateLastProcessed(storeFilePath,baseData,fileInfo.stat);return!0}}if(!createIfDifferent){this._log(`Could not mark hidden file ${storeFilePath} as revision ${baseRevision}; the storage content differs`,LOG_LEVEL_NOTICE);return!1}const storedRevision=await this.core.databaseFileAccess.storeWithBaseRevision({...fileInfo,path:storeFilePath,name:fileInfo.name||storeFilePath.split("/").pop()||"",isInternal:!0},baseRevision,!0);if(!1===storedRevision)return!1;this.updateLastProcessed(storeFilePath,{...baseData,_rev:storedRevision,path:prefixedFileName,ctime:fileInfo.stat.ctime,mtime:fileInfo.stat.mtime,size:fileInfo.stat.size,deleted:!1},fileInfo.stat);this._log(`STORAGE --\x3e DB:${storageFilePath}: (hidden, selected branch) Done`);return!0}catch(ex){this._log(`STORAGE --\x3e DB:${storageFilePath}: (hidden, selected branch) Failed`);this._log(ex,LOG_LEVEL_VERBOSE);return!1}})}async deleteInternalFileOnDatabase(filenameSrc,forceWrite=!1){const storeFilePath=filenameSrc,storageFilePath=filenameSrc,displayFileName=filenameSrc,prefixedFileName=addPrefix(storeFilePath,ICHeader),mtime=(new Date).getTime();if(!await this.services.vault.isIgnoredByIgnoreFile(storageFilePath))return await serialized("file-"+prefixedFileName,async()=>{try{const baseData=await this.__loadBaseSaveData(storeFilePath,!1);if(!1===baseData)throw new Error("Failed to load base data during deleting");if(void 0!==baseData._conflicts)for(const conflictRev of baseData._conflicts){await this.localDatabase.removeRevision(baseData._id,conflictRev);this._log(`STORAGE -x> DB: ${displayFileName}: (hidden) conflict removed ${baseData._rev} => ${conflictRev}`,LOG_LEVEL_VERBOSE)}if(baseData.deleted){this._log(`STORAGE -x> DB: ${displayFileName}: (hidden) already deleted`,LOG_LEVEL_VERBOSE);this.updateLastProcessedDeletion(storeFilePath,baseData);return!0}const saveData={...baseData,mtime,size:0,children:[],deleted:!0,type:baseData.datatype},ret=await this.localDatabase.putRaw(saveData);if(ret&&ret.ok){this._log(`STORAGE -x> DB: ${displayFileName}: (hidden) Done`);saveData._rev=ret.rev;this.updateLastProcessedDeletion(storeFilePath,saveData);return!0}this._log(`STORAGE -x> DB: ${displayFileName}: (hidden) Failed`);return!1}catch(ex){this._log(`STORAGE -x> DB: ${displayFileName}: (hidden) Failed`);this._log(ex,LOG_LEVEL_VERBOSE);return!1}})}async extractInternalFileFromDatabase(storageFilePath,force=!1,metaEntry,preventDoubleProcess=!0,onlyNew=!1,includeDeletion=!0,requiredLiveRevision){const prefixedFileName=addPrefix(storageFilePath,ICHeader);if(!await this.services.vault.isIgnoredByIgnoreFile(storageFilePath))return await serialized("file-"+prefixedFileName,async()=>{var _a13,_b6;try{const metaOnDB=requiredLiveRevision?await this.getLiveInternalRevision(prefixedFileName,requiredLiveRevision):metaEntry||await this.localDatabase.getDBEntryMeta(prefixedFileName,{conflicts:!0},!0);if(!1===metaOnDB)throw new Error(`File not found on database.:${storageFilePath}`);if(null==(_a13=null==metaOnDB?void 0:metaOnDB._conflicts)?void 0:_a13.length){this._log(`Hidden file ${storageFilePath} has conflicted revisions, to keep in safe, writing to storage has been prevented`,LOG_LEVEL_INFO);return!1}if(preventDoubleProcess){const key3=this.docToKey(metaOnDB);if(this.getLastProcessedDatabaseKey(storageFilePath)==key3&&!force){this._log(`STORAGE <-- DB: ${storageFilePath}: skipped (hidden, overwrite${force?", force":""}) (Previously processed)`);return}}if(onlyNew){const dbMTime=getComparingMTime(metaOnDB,includeDeletion),storageStat=await this.core.storageAccess.statHidden(storageFilePath),storageMTimeActual=null!=(_b6=null==storageStat?void 0:storageStat.mtime)?_b6:0,storageMTime=0==storageMTimeActual?this.getLastProcessedFileMTime(storageFilePath):storageMTimeActual,diff=compareMTime(storageMTime,dbMTime);if(diff!=TARGET_IS_NEW){this._log(`STORAGE <-- DB: ${storageFilePath}: skipped (hidden, overwrite${force?", force":""}) (Not new)`);this.updateLastProcessedDatabase(storageFilePath,metaOnDB);storageStat&&this.updateLastProcessedFile(storageFilePath,storageStat);return}}const deleted=metaOnDB.deleted||metaOnDB._deleted||!1;if(deleted){const result=await this.__deleteFile(storageFilePath);if("OK"==result){this.updateLastProcessedDeletion(storageFilePath,metaOnDB);return!0}if("ALREADY"==result){this.updateLastProcessedDatabase(storageFilePath,metaOnDB);return!0}return!1}{const fileOnDB=await this.localDatabase.getDBEntryFromMeta(metaOnDB,!1,!0);if(!1===fileOnDB)throw new Error(`Failed to read file from database:${storageFilePath}`);const resultStat=await this.__writeFile(storageFilePath,fileOnDB,force);if(resultStat){this.updateLastProcessed(storageFilePath,metaOnDB,resultStat);this.queueNotification(storageFilePath);this._log(`STORAGE <-- DB: ${storageFilePath}: written (hidden, overwrite${force?", force":""}) Done`);return!0}}return!1}catch(ex){this._log(`STORAGE <-- DB: ${storageFilePath}: written (hidden, overwrite${force?", force":""}) Failed`);this._log(ex,LOG_LEVEL_VERBOSE);return!1}})}async extractInternalFileRevisionFromDatabase(storageFilePath,revision,force=!1){return Boolean(await this.extractInternalFileFromDatabase(storageFilePath,force,void 0,!0,!1,!0,revision))}async __checkIsNeedToWriteFile(storageFilePath,content){try{const storageContent=await this.core.storageAccess.readHiddenFileAuto(storageFilePath),needWrite=!await isDocContentSame(storageContent,content);return needWrite}catch(ex){this._log(`Cannot check the content of ${storageFilePath}`);this._log(ex,LOG_LEVEL_VERBOSE);return!0}}async __writeFile(storageFilePath,fileOnDB,force){try{const statBefore=await this.core.storageAccess.statHidden(storageFilePath),isExist=null!=statBefore,writeContent=readContent(fileOnDB);await this.ensureDir(storageFilePath);const needWrite=force||!isExist||isExist&&await this.__checkIsNeedToWriteFile(storageFilePath,writeContent);if(!needWrite){this._log(`STORAGE <-- DB: ${storageFilePath}: skipped (hidden) Not changed`,LOG_LEVEL_DEBUG);return statBefore}const writeResultStat=await this.writeFile(storageFilePath,writeContent,{mtime:fileOnDB.mtime,ctime:fileOnDB.ctime});if(null==writeResultStat){this._log(`STORAGE <-- DB: ${storageFilePath}: written (hidden,new${force?", force":""}) Failed (writeResult)`);return!1}this._log(`STORAGE <-- DB: ${storageFilePath}: written (hidden, overwrite${force?", force":""})`);return writeResultStat}catch(ex){this._log(`STORAGE <-- DB: ${storageFilePath}: written (hidden, overwrite${force?", force":""}) Failed`);this._log(ex,LOG_LEVEL_VERBOSE);return!1}}async __deleteFile(storageFilePath){const result=await this.__removeFile(storageFilePath);if(!1===result){this._log(`STORAGE <x- DB: ${storageFilePath}: deleting (hidden) Failed`);return!1}"OK"===result&&await this.triggerEvent(storageFilePath);this._log(`STORAGE <x- DB: ${storageFilePath}: deleting (hidden) ${"OK"==result?"Done":"Already not found"}`);return result}_allSuspendExtraSync(){if(this.core.settings.syncInternalFiles){this._log($msg("Hidden file synchronization have been temporarily disabled. Please enable them after the fetching, if you need them."),LOG_LEVEL_NOTICE);this.core.settings.syncInternalFiles=!1}return Promise.resolve(!0)}async _allConfigureOptionalSyncFeature(mode){await this.configureHiddenFileSync(mode);return!0}async configureHiddenFileSync(mode){let initialisationProgress,result;try{result=await configureHiddenFileSyncMode(mode,{disable:async()=>{await this.core.services.setting.applyPartial({syncInternalFiles:!1},!0)},enable:async()=>{initialisationProgress=this._progress("[⚙ Initialise]\n",LOG_LEVEL_NOTICE);initialisationProgress.log("Preparing Hidden File Sync...");await this.core.services.setting.applyPartial({useAdvancedMode:!0,syncInternalFiles:!0},!0)},initialise:async direction=>{await this.initialiseInternalFileSync(direction,!0,!1,initialisationProgress);initialisationProgress=void 0}})}catch(error){null==initialisationProgress||initialisationProgress.done("Failed");throw error}"ignored"!=result&&"disabled"!=result&&this._log("Hidden File Sync initialisation completed.",LOG_LEVEL_INFO)}async scanInternalFileNames(){const root44=this.app.vault.getRoot(),findRoot=root44.path,filenames=await this.getFiles(findRoot,path2=>this.isTargetFile(path2));return filenames}async scanInternalFiles(){var _a13,_b6,_c3,_d2,_e2,_f;const fileNames=await this.scanInternalFileNames(),files=fileNames.map(async e3=>({path:e3,stat:await this.core.storageAccess.statHidden(e3)})),result=[];for(const f4 of files){const w2=await f4;if(await this.services.vault.isIgnoredByIgnoreFile(w2.path))continue;const mtime=null!=(_b6=null==(_a13=w2.stat)?void 0:_a13.mtime)?_b6:0,ctime=null!=(_d2=null==(_c3=w2.stat)?void 0:_c3.ctime)?_d2:mtime,size=null!=(_f=null==(_e2=w2.stat)?void 0:_e2.size)?_f:0;result.push({...w2,mtime,ctime,size})}return result}async getFiles(path2,checkFunction){let w2;try{w2=await this.app.vault.adapter.list(path2)}catch(ex){this._log(`Could not traverse(HiddenSync):${path2}`,LOG_LEVEL_INFO);this._log(ex,LOG_LEVEL_VERBOSE);return[]}let files=[];for(const file of w2.files)await checkFunction(file)&&files.push(file);for(const v2 of w2.folders)await checkFunction(v2)&&(files=files.concat(await this.getFiles(v2,checkFunction)));return files}onBindFunction(core,services){services.appLifecycle.onSettingLoaded.addHandler(this._everyOnloadAfterLoadSettings.bind(this));services.fileProcessing.processOptionalFileEvent.addHandler(this._anyProcessOptionalFileEvent.bind(this));services.conflict.getOptionalConflictCheckMethod.addHandler(this._anyGetOptionalConflictCheckMethod.bind(this));services.replication.processOptionalSynchroniseResult.addHandler(this._anyProcessOptionalSyncFiles.bind(this));services.setting.onRealiseSetting.addHandler(this._everyRealizeSettingSyncMode.bind(this));services.appLifecycle.onResuming.addHandler(this._everyOnResumeProcess.bind(this));services.replication.onBeforeReplicate.addHandler(this._everyBeforeReplicate.bind(this));services.databaseEvents.onDatabaseInitialised.addHandler(this._everyOnDatabaseInitialized.bind(this));services.setting.suspendExtraSync.addHandler(this._allSuspendExtraSync.bind(this));services.setting.enableOptionalFeature.addHandler(this._allConfigureOptionalSyncFeature.bind(this));services.vault.isTargetFileInExtra.addHandler(file=>this.isTargetFile("string"==typeof file?file:stripAllPrefixes(file.path)))}};t=new Uint8Array([0,97,115,109,1,0,0,0,1,48,8,96,3,127,127,127,0,96,3,127,127,127,1,127,96,2,127,127,0,96,2,127,126,0,96,1,127,1,127,96,1,127,1,126,96,3,127,127,126,1,126,96,3,126,127,127,1,126,3,11,10,1,1,2,0,4,6,7,3,0,5,5,3,1,0,1,7,85,9,3,109,101,109,2,0,5,120,120,104,51,50,0,0,6,105,110,105,116,51,50,0,2,8,117,112,100,97,116,101,51,50,0,3,8,100,105,103,101,115,116,51,50,0,4,5,120,120,104,54,52,0,5,6,105,110,105,116,54,52,0,7,8,117,112,100,97,116,101,54,52,0,8,8,100,105,103,101,115,116,54,52,0,9,10,211,23,10,242,1,1,4,127,32,0,32,1,106,33,3,32,1,65,16,79,4,127,32,3,65,16,107,33,6,32,2,65,168,136,141,161,2,106,33,3,32,2,65,247,148,175,175,120,106,33,4,32,2,65,177,243,221,241,121,107,33,5,3,64,32,0,40,2,0,65,247,148,175,175,120,108,32,3,106,65,13,119,65,177,243,221,241,121,108,33,3,32,0,65,4,106,34,0,40,2,0,65,247,148,175,175,120,108,32,4,106,65,13,119,65,177,243,221,241,121,108,33,4,32,0,65,4,106,34,0,40,2,0,65,247,148,175,175,120,108,32,2,106,65,13,119,65,177,243,221,241,121,108,33,2,32,0,65,4,106,34,0,40,2,0,65,247,148,175,175,120,108,32,5,106,65,13,119,65,177,243,221,241,121,108,33,5,32,0,65,4,106,34,0,32,6,77,13,0,11,32,2,65,12,119,32,5,65,18,119,106,32,4,65,7,119,106,32,3,65,1,119,106,5,32,2,65,177,207,217,178,1,106,11,32,1,106,32,0,32,1,65,15,113,16,1,11,146,1,0,32,1,32,2,106,33,2,3,64,32,1,65,4,106,32,2,75,69,4,64,32,1,40,2,0,65,189,220,202,149,124,108,32,0,106,65,17,119,65,175,214,211,190,2,108,33,0,32,1,65,4,106,33,1,12,1,11,11,3,64,32,1,32,2,79,69,4,64,32,1,45,0,0,65,177,207,217,178,1,108,32,0,106,65,11,119,65,177,243,221,241,121,108,33,0,32,1,65,1,106,33,1,12,1,11,11,32,0,65,15,118,32,0,115,65,247,148,175,175,120,108,34,0,32,0,65,13,118,115,65,189,220,202,149,124,108,34,0,32,0,65,16,118,115,11,63,0,32,0,65,8,106,32,1,65,168,136,141,161,2,106,54,2,0,32,0,65,12,106,32,1,65,247,148,175,175,120,106,54,2,0,32,0,65,16,106,32,1,54,2,0,32,0,65,20,106,32,1,65,177,243,221,241,121,107,54,2,0,11,211,4,1,6,127,32,1,32,2,106,33,6,32,0,65,24,106,33,5,32,0,65,40,106,40,2,0,33,3,32,0,32,0,40,2,0,32,2,106,54,2,0,32,0,65,4,106,34,4,32,4,40,2,0,32,2,65,16,79,32,0,40,2,0,65,16,79,114,114,54,2,0,32,2,32,3,106,65,16,73,4,64,32,3,32,5,106,32,1,32,2,252,10,0,0,32,0,65,40,106,32,2,32,3,106,54,2,0,15,11,32,3,4,64,32,3,32,5,106,32,1,65,16,32,3,107,34,2,252,10,0,0,32,0,65,8,106,34,3,40,2,0,32,5,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,33,4,32,3,32,4,54,2,0,32,0,65,12,106,34,3,40,2,0,32,5,65,4,106,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,33,4,32,3,32,4,54,2,0,32,0,65,16,106,34,3,40,2,0,32,5,65,8,106,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,33,4,32,3,32,4,54,2,0,32,0,65,20,106,34,3,40,2,0,32,5,65,12,106,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,33,4,32,3,32,4,54,2,0,32,0,65,40,106,65,0,54,2,0,32,1,32,2,106,33,1,11,32,1,32,6,65,16,107,77,4,64,32,6,65,16,107,33,8,32,0,65,8,106,40,2,0,33,2,32,0,65,12,106,40,2,0,33,3,32,0,65,16,106,40,2,0,33,4,32,0,65,20,106,40,2,0,33,7,3,64,32,1,40,2,0,65,247,148,175,175,120,108,32,2,106,65,13,119,65,177,243,221,241,121,108,33,2,32,1,65,4,106,34,1,40,2,0,65,247,148,175,175,120,108,32,3,106,65,13,119,65,177,243,221,241,121,108,33,3,32,1,65,4,106,34,1,40,2,0,65,247,148,175,175,120,108,32,4,106,65,13,119,65,177,243,221,241,121,108,33,4,32,1,65,4,106,34,1,40,2,0,65,247,148,175,175,120,108,32,7,106,65,13,119,65,177,243,221,241,121,108,33,7,32,1,65,4,106,34,1,32,8,77,13,0,11,32,0,65,8,106,32,2,54,2,0,32,0,65,12,106,32,3,54,2,0,32,0,65,16,106,32,4,54,2,0,32,0,65,20,106,32,7,54,2,0,11,32,1,32,6,73,4,64,32,5,32,1,32,6,32,1,107,34,1,252,10,0,0,32,0,65,40,106,32,1,54,2,0,11,11,97,1,1,127,32,0,65,16,106,40,2,0,33,1,32,0,65,4,106,40,2,0,4,127,32,1,65,12,119,32,0,65,20,106,40,2,0,65,18,119,106,32,0,65,12,106,40,2,0,65,7,119,106,32,0,65,8,106,40,2,0,65,1,119,106,5,32,1,65,177,207,217,178,1,106,11,32,0,40,2,0,106,32,0,65,24,106,32,0,65,40,106,40,2,0,16,1,11,157,4,2,1,127,3,126,32,0,32,1,106,33,3,32,1,65,32,79,4,126,32,3,65,32,107,33,3,32,2,66,135,149,175,175,152,182,222,155,158,127,124,66,207,214,211,190,210,199,171,217,66,124,33,4,32,2,66,207,214,211,190,210,199,171,217,66,124,33,5,32,2,66,0,124,33,6,32,2,66,135,149,175,175,152,182,222,155,158,127,125,33,2,3,64,32,0,41,3,0,66,207,214,211,190,210,199,171,217,66,126,32,4,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,4,32,0,65,8,106,34,0,41,3,0,66,207,214,211,190,210,199,171,217,66,126,32,5,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,5,32,0,65,8,106,34,0,41,3,0,66,207,214,211,190,210,199,171,217,66,126,32,6,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,6,32,0,65,8,106,34,0,41,3,0,66,207,214,211,190,210,199,171,217,66,126,32,2,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,2,32,0,65,8,106,34,0,32,3,77,13,0,11,32,6,66,12,137,32,2,66,18,137,124,32,5,66,7,137,124,32,4,66,1,137,124,32,4,66,207,214,211,190,210,199,171,217,66,126,66,0,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,227,220,202,149,252,206,242,245,133,127,124,32,5,66,207,214,211,190,210,199,171,217,66,126,66,0,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,227,220,202,149,252,206,242,245,133,127,124,32,6,66,207,214,211,190,210,199,171,217,66,126,66,0,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,227,220,202,149,252,206,242,245,133,127,124,32,2,66,207,214,211,190,210,199,171,217,66,126,66,0,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,227,220,202,149,252,206,242,245,133,127,124,5,32,2,66,197,207,217,178,241,229,186,234,39,124,11,32,1,173,124,32,0,32,1,65,31,113,16,6,11,137,2,0,32,1,32,2,106,33,2,3,64,32,1,65,8,106,32,2,77,4,64,32,1,41,3,0,66,207,214,211,190,210,199,171,217,66,126,66,0,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,32,0,133,66,27,137,66,135,149,175,175,152,182,222,155,158,127,126,66,227,220,202,149,252,206,242,245,133,127,124,33,0,32,1,65,8,106,33,1,12,1,11,11,32,1,65,4,106,32,2,77,4,64,32,1,53,2,0,66,135,149,175,175,152,182,222,155,158,127,126,32,0,133,66,23,137,66,207,214,211,190,210,199,171,217,66,126,66,249,243,221,241,153,246,153,171,22,124,33,0,32,1,65,4,106,33,1,11,3,64,32,1,32,2,73,4,64,32,1,49,0,0,66,197,207,217,178,241,229,186,234,39,126,32,0,133,66,11,137,66,135,149,175,175,152,182,222,155,158,127,126,33,0,32,1,65,1,106,33,1,12,1,11,11,32,0,66,33,136,32,0,133,66,207,214,211,190,210,199,171,217,66,126,34,0,32,0,66,29,136,133,66,249,243,221,241,153,246,153,171,22,126,34,0,32,0,66,32,136,133,11,88,0,32,0,65,8,106,32,1,66,135,149,175,175,152,182,222,155,158,127,124,66,207,214,211,190,210,199,171,217,66,124,55,3,0,32,0,65,16,106,32,1,66,207,214,211,190,210,199,171,217,66,124,55,3,0,32,0,65,24,106,32,1,55,3,0,32,0,65,32,106,32,1,66,135,149,175,175,152,182,222,155,158,127,125,55,3,0,11,132,5,2,3,127,4,126,32,1,32,2,106,33,5,32,0,65,40,106,33,4,32,0,65,200,0,106,40,2,0,33,3,32,0,32,0,41,3,0,32,2,173,124,55,3,0,32,2,32,3,106,65,32,73,4,64,32,3,32,4,106,32,1,32,2,252,10,0,0,32,0,65,200,0,106,32,2,32,3,106,54,2,0,15,11,32,3,4,64,32,3,32,4,106,32,1,65,32,32,3,107,34,2,252,10,0,0,32,0,65,8,106,34,3,41,3,0,32,4,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,6,32,3,32,6,55,3,0,32,0,65,16,106,34,3,41,3,0,32,4,65,8,106,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,6,32,3,32,6,55,3,0,32,0,65,24,106,34,3,41,3,0,32,4,65,16,106,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,6,32,3,32,6,55,3,0,32,0,65,32,106,34,3,41,3,0,32,4,65,24,106,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,6,32,3,32,6,55,3,0,32,0,65,200,0,106,65,0,54,2,0,32,1,32,2,106,33,1,11,32,1,65,32,106,32,5,77,4,64,32,5,65,32,107,33,2,32,0,65,8,106,41,3,0,33,6,32,0,65,16,106,41,3,0,33,7,32,0,65,24,106,41,3,0,33,8,32,0,65,32,106,41,3,0,33,9,3,64,32,1,41,3,0,66,207,214,211,190,210,199,171,217,66,126,32,6,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,6,32,1,65,8,106,34,1,41,3,0,66,207,214,211,190,210,199,171,217,66,126,32,7,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,7,32,1,65,8,106,34,1,41,3,0,66,207,214,211,190,210,199,171,217,66,126,32,8,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,8,32,1,65,8,106,34,1,41,3,0,66,207,214,211,190,210,199,171,217,66,126,32,9,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,9,32,1,65,8,106,34,1,32,2,77,13,0,11,32,0,65,8,106,32,6,55,3,0,32,0,65,16,106,32,7,55,3,0,32,0,65,24,106,32,8,55,3,0,32,0,65,32,106,32,9,55,3,0,11,32,1,32,5,73,4,64,32,4,32,1,32,5,32,1,107,34,1,252,10,0,0,32,0,65,200,0,106,32,1,54,2,0,11,11,200,2,1,5,126,32,0,65,24,106,41,3,0,33,1,32,0,41,3,0,34,2,66,32,90,4,126,32,0,65,8,106,41,3,0,34,3,66,1,137,32,0,65,16,106,41,3,0,34,4,66,7,137,124,32,1,66,12,137,32,0,65,32,106,41,3,0,34,5,66,18,137,124,124,32,3,66,207,214,211,190,210,199,171,217,66,126,66,0,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,227,220,202,149,252,206,242,245,133,127,124,32,4,66,207,214,211,190,210,199,171,217,66,126,66,0,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,227,220,202,149,252,206,242,245,133,127,124,32,1,66,207,214,211,190,210,199,171,217,66,126,66,0,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,227,220,202,149,252,206,242,245,133,127,124,32,5,66,207,214,211,190,210,199,171,217,66,126,66,0,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,227,220,202,149,252,206,242,245,133,127,124,5,32,1,66,197,207,217,178,241,229,186,234,39,124,11,32,2,124,32,0,65,40,106,32,2,66,31,131,167,16,6,11]);hashFunc=str=>fallbackMixedHashEach(str);!async function initHashFunc(){try{const{h32ToString}=await e();hashFunc=h32ToString;Logger("xxhash for plugin initialised",LOG_LEVEL_VERBOSE)}catch(ex){Logger("Could not initialise xxhash. fallback...",LOG_LEVEL_VERBOSE);Logger(ex);hashFunc=str=>fallbackMixedHashEach(str)}return hashFunc}();import_diff_match_patch2=__toESM(require_diff_match_patch(),1);POSTPONED=Symbol("postponed");ConflictResolveModal=class extends import_obsidian.Modal{constructor(app,filename,diff,pluginPickMode,remoteName,options){var _a13,_b6,_c3,_d2;super(app);this.response=CANCELLED;this.isClosed=!1;this.consumed=!1;this.resultPromise=promiseWithResolvers();this.title="Conflicting changes";this.pluginPickMode=!1;this.readOnly=!1;this.localName="Base";this.remoteName="Conflicted";this.currentDiffIndex=-1;this.result=diff;this.filename=filename;this.pluginPickMode=pluginPickMode||!1;this.readOnly=null!=(_a13=null==options?void 0:options.readOnly)&&_a13;if(this.pluginPickMode){this.title="Pick a version";this.remoteName=`${remoteName||"Remote"}`;this.localName="Local"}else if(this.readOnly){this.title=null!=(_b6=null==options?void 0:options.title)?_b6:"Vault and database revision";this.localName=null!=(_c3=null==options?void 0:options.localName)?_c3:"Vault file";this.remoteName=null!=(_d2=null==options?void 0:options.remoteName)?_d2:"Database revision"}}appendDiffFragment(container,text2,cls){const lines=text2.split("\n");lines.forEach((line,index6)=>{const span=container.createSpan({cls});span.setText(line);if(index6<lines.length-1){container.createSpan({cls:"ls-mark-cr"});container.createEl("br")}})}appendVersionInfo(container,cls,name,date2){const line=container.createSpan({cls});line.createSpan({text:name,cls:"conflict-dev-name"});line.appendText(`: ${date2}`);container.createEl("br")}navigateDiff(direction){const diffElements=this.diffView.querySelectorAll(".added, .deleted");if(0===diffElements.length)return;const prevFocused=this.diffView.querySelector(".diff-focused");prevFocused&&prevFocused.classList.remove("diff-focused");this.currentDiffIndex="next"===direction?(this.currentDiffIndex+1)%diffElements.length:this.currentDiffIndex<=0?diffElements.length-1:this.currentDiffIndex-1;const target=diffElements[this.currentDiffIndex];target.classList.add("diff-focused");target.scrollIntoView({behavior:"smooth",block:"center"});this.diffNavIndicator.setText(`${this.currentDiffIndex+1}/${diffElements.length}`)}resetDiffNavigation(){this.currentDiffIndex=-1;const diffElements=this.diffView.querySelectorAll(".added, .deleted");this.diffNavIndicator.setText(diffElements.length>0?`0/${diffElements.length}`:"—")}onOpen(){const{contentEl}=this;this.offEvent&&this.offEvent();if(!this.readOnly){eventHub.emitEvent(EVENT_CONFLICT_CANCELLED,this.filename);this.offEvent=eventHub.onEvent(EVENT_CONFLICT_CANCELLED,path2=>{path2===this.filename&&this.sendResponse(CANCELLED)})}this.titleEl.setText(this.title);contentEl.empty();const diffOptionsRow=contentEl.createDiv("");diffOptionsRow.addClass("diff-options-row");diffOptionsRow.createSpan({text:this.filename});const diffNavContainer=diffOptionsRow.createDiv("");diffNavContainer.addClass("diff-nav");diffNavContainer.createEl("button",{text:"▲ Prev"},e3=>{e3.addClass("diff-nav-btn");e3.addEventListener("click",()=>this.navigateDiff("prev"))});diffNavContainer.createEl("button",{text:"▼ Next"},e3=>{e3.addClass("diff-nav-btn");e3.addEventListener("click",()=>this.navigateDiff("next"))});this.diffNavIndicator=diffNavContainer.createSpan({text:"—"});this.diffNavIndicator.addClass("diff-nav-indicator");this.diffView=contentEl.createDiv("");this.diffView.addClass("op-scrollable");this.diffView.addClass("ls-dialog");let diffLength=0;for(const v2 of this.result.diff){const x1=v2[0],x22=v2[1];diffLength+=x22.length;diffLength>102400||(x1==import_diff_match_patch2.DIFF_DELETE?this.appendDiffFragment(this.diffView,x22,"deleted"):x1==import_diff_match_patch2.DIFF_EQUAL?this.appendDiffFragment(this.diffView,x22,"normal"):x1==import_diff_match_patch2.DIFF_INSERT&&this.appendDiffFragment(this.diffView,x22,"added"))}const div2=contentEl.createDiv("");div2.addClass("ls-dialog");const date1=new Date(this.result.left.mtime).toLocaleString()+(this.result.left.deleted?" (Deleted)":""),date2=new Date(this.result.right.mtime).toLocaleString()+(this.result.right.deleted?" (Deleted)":"");this.appendVersionInfo(div2,"deleted",this.localName,date1);this.appendVersionInfo(div2,"added",this.remoteName,date2);const actionContainer=contentEl.createDiv("conflict-action-container");if(this.readOnly)actionContainer.createEl("button",{text:"Close"},e3=>{e3.addClass("conflict-action-button");e3.addEventListener("click",()=>this.sendResponse(CANCELLED))});else{actionContainer.createEl("button",{text:`Use ${this.localName}`},e3=>{e3.addClass("conflict-action-button");e3.addEventListener("click",()=>this.sendResponse(this.result.right.rev))});actionContainer.createEl("button",{text:`Use ${this.remoteName}`},e3=>{e3.addClass("conflict-action-button");e3.addEventListener("click",()=>this.sendResponse(this.result.left.rev))});this.pluginPickMode||actionContainer.createEl("button",{text:"Concat both"},e3=>{e3.addClass("conflict-action-button");e3.addEventListener("click",()=>this.sendResponse(LEAVE_TO_SUBSEQUENT))});actionContainer.createEl("button",{text:this.pluginPickMode?"Cancel":"Not now"},e3=>{e3.addClass("conflict-action-button");e3.addEventListener("click",()=>this.sendResponse(this.pluginPickMode?CANCELLED:POSTPONED))})}if(diffLength>102400){this.diffView.empty();this.diffView.setText("(Too large diff to display)")}this.resetDiffNavigation();this.navigateDiff("next")}sendResponse(result){this.response=result;this.close()}onClose(){const{contentEl}=this;contentEl.empty();this.offEvent&&this.offEvent();if(!this.consumed){this.consumed=!0;this.resultPromise.resolve(this.response)}}async waitForResult(){return await this.resultPromise.promise}};(function enable_legacy_mode_flag(){legacy_mode_flag=!0})();root4=from_html("<option> </option>");root_13=from_html('<button class="svelte-14nm4oc">🗃️</button>');root_22=from_html('<button class="svelte-14nm4oc">⮂</button>');root_32=from_html('<button disabled="" class="svelte-14nm4oc"></button>');root_42=from_html('<!> <button class="svelte-14nm4oc">✓</button>',1);root_52=from_html('<button disabled="" class="svelte-14nm4oc"></button> <button disabled="" class="svelte-14nm4oc"></button>',1);root_62=from_html('<button class="svelte-14nm4oc">🗑️</button>');root_7=from_html('<button class="svelte-14nm4oc">📑</button>');root_8=from_html('<span class="chip-wrap svelte-14nm4oc"><span class="chip modified svelte-14nm4oc"> </span> <span class="chip content svelte-14nm4oc"> </span> <span class="chip version svelte-14nm4oc"> </span></span> <select><option>-</option><!></select> <!> <!>',1);root_9=from_html('<span class="spacer svelte-14nm4oc"></span> <!>',1);root_10=from_html('<span class="spacer svelte-14nm4oc"></span> <span class="message even svelte-14nm4oc"> </span> <button disabled="" class="svelte-14nm4oc"></button> <button disabled="" class="svelte-14nm4oc"></button>',1);$$css3={hash:"svelte-14nm4oc",code:'.spacer.svelte-14nm4oc {min-width:1px;flex-grow:1;}button.svelte-14nm4oc {margin:2px 4px;min-width:3em;max-width:4em;}button.svelte-14nm4oc:disabled {border:none;box-shadow:none;background-color:transparent;visibility:collapse;}button.svelte-14nm4oc:disabled:hover {border:none;box-shadow:none;background-color:transparent;visibility:collapse;}span.message.svelte-14nm4oc {color:var(--text-muted);font-size:var(--font-ui-smaller);padding:0 1em;line-height:var(--line-height-tight);}\n /* span.messages {\n display: flex;\n flex-direction: column;\n align-items: center;\n } */.is-mobile .spacer.svelte-14nm4oc {margin-left:auto;}.chip-wrap.svelte-14nm4oc {display:flex;gap:2px;flex-direction:column;justify-content:center;align-items:flex-start;}.chip.svelte-14nm4oc {display:inline-block;border-radius:2px;font-size:0.8em;padding:0 4px;margin:0 2px;border-color:var(--tag-border-color);background-color:var(--tag-background);color:var(--tag-color);}.chip.svelte-14nm4oc:empty {display:none;}.chip.svelte-14nm4oc:not(:empty)::before {min-width:1.8em;display:inline-block;}.chip.content.svelte-14nm4oc:not(:empty)::before {content:"📄: ";}.chip.version.svelte-14nm4oc:not(:empty)::before {content:"🏷️: ";}.chip.modified.svelte-14nm4oc:not(:empty)::before {content:"📅: ";}'};root5=from_html('<button class="svelte-10jah2g"> </button>');root_14=from_html("<span> </span>");root_23=from_html('<div class="center svelte-10jah2g"> </div>');root_33=from_html('<div class="statusnote svelte-10jah2g"> </div>');root_43=from_html('<div><div class="title svelte-10jah2g"><button class="status svelte-10jah2g"> </button> <span class="name"> </span></div> <div class="body svelte-10jah2g"><!></div></div>');root_53=from_html('<div><h3 class="svelte-10jah2g"> </h3> <!></div>');root_63=from_html('<div><div class="filetitle svelte-10jah2g"><button class="status svelte-10jah2g"> </button> <span class="name"> </span></div> <div class="body svelte-10jah2g"><!></div></div>');root_72=from_html('<div><div class="filetitle svelte-10jah2g"><button class="status svelte-10jah2g"> </button> <span class="name">MAIN</span></div> <div class="body svelte-10jah2g"><!></div></div> <div><div class="filetitle svelte-10jah2g"><button class="status svelte-10jah2g"> </button> <span class="name">DATA</span></div> <div class="body svelte-10jah2g"><!></div></div> <!>',1);root_82=from_html('<div class="noterow svelte-10jah2g"><div class="statusnote svelte-10jah2g"> </div></div>');root_92=from_html('<div><div class="title svelte-10jah2g"><button class="status svelte-10jah2g"> </button> <span class="name"> </span></div> <div class="body svelte-10jah2g"><!></div></div> <!>',1);root_102=from_html('<!> <div><h3 class="svelte-10jah2g"> </h3> <!></div>',1);root_11=from_html("<option> </option>");root_122=from_html('<div class="buttons svelte-10jah2g"><div><h3 class="svelte-10jah2g"> </h3> <div class="maintenancerow svelte-10jah2g"><label for="" class="svelte-10jah2g"> </label> <select></select> <button class="status svelte-10jah2g">🗑️</button></div></div></div>');root_132=from_html('<div class="buttonsWrap svelte-10jah2g"><div class="buttons svelte-10jah2g"><button class="svelte-10jah2g"> </button> <button class="svelte-10jah2g"> </button> <button class="svelte-10jah2g"> </button> <!></div> <div class="buttons svelte-10jah2g"><button class="svelte-10jah2g"> </button> <button class="svelte-10jah2g"> </button> <button class="svelte-10jah2g"> </button> <button class="mod-cta svelte-10jah2g"> </button></div></div> <div class="loading svelte-10jah2g"><!></div> <div class="list svelte-10jah2g"><!></div> <!> <div class="buttons svelte-10jah2g"><label class="svelte-10jah2g"><span class="svelte-10jah2g"> </span><input type="checkbox"/></label></div> <div class="buttons svelte-10jah2g"><label class="svelte-10jah2g"><span class="svelte-10jah2g"> </span><input type="checkbox"/></label></div>',1);$$css4={hash:"svelte-10jah2g",code:".buttonsWrap.svelte-10jah2g {padding-bottom:4px;}h3.svelte-10jah2g {position:sticky;top:0;background-color:var(--modal-background);}.labelrow.svelte-10jah2g {margin-left:0.4em;display:flex;justify-content:flex-start;align-items:center;border-top:1px solid var(--background-modifier-border);padding:4px;flex-wrap:wrap;}.filerow.svelte-10jah2g {margin-left:1.25em;display:flex;justify-content:flex-start;align-items:center;padding-right:4px;flex-wrap:wrap;}.filerow.hideeven.svelte-10jah2g:has(.even),\n .labelrow.hideeven.svelte-10jah2g:has(.even) {display:none;}.noterow.svelte-10jah2g {min-height:2em;display:flex;}button.status.svelte-10jah2g {flex-grow:0;margin:2px 4px;min-width:3em;max-width:4em;}.statusnote.svelte-10jah2g {display:flex;justify-content:flex-end;padding-right:var(--size-4-12);align-items:center;min-width:10em;flex-grow:1;}.list.svelte-10jah2g {overflow-y:auto;}.title.svelte-10jah2g {color:var(--text-normal);font-size:var(--font-ui-medium);line-height:var(--line-height-tight);margin-right:auto;}.body.svelte-10jah2g {\n /* margin-left: 0.4em; */margin-left:auto;display:flex;justify-content:flex-start;align-items:center;\n /* flex-wrap: wrap; */}.filetitle.svelte-10jah2g {color:var(--text-normal);font-size:var(--font-ui-medium);line-height:var(--line-height-tight);margin-right:auto;}.buttons.svelte-10jah2g {display:flex;flex-direction:row;justify-content:flex-end;margin-top:8px;flex-wrap:wrap;}.buttons.svelte-10jah2g > button:where(.svelte-10jah2g) {margin-left:4px;width:auto;}label.svelte-10jah2g {display:flex;justify-content:center;align-items:center;}label.svelte-10jah2g > span:where(.svelte-10jah2g) {margin-right:0.25em;}.is-mobile .title.svelte-10jah2g,\n .is-mobile .filetitle.svelte-10jah2g {width:100%;}.center.svelte-10jah2g {display:flex;justify-content:center;align-items:center;min-height:3em;}.maintenancerow.svelte-10jah2g {display:flex;justify-content:flex-end;align-items:center;}.maintenancerow.svelte-10jah2g label:where(.svelte-10jah2g) {margin-right:0.5em;margin-left:0.5em;}.loading.svelte-10jah2g {transition:height 0.25s ease-in-out;transition-delay:4ms;overflow-y:hidden;flex-shrink:0;display:flex;justify-content:flex-start;align-items:center;}.loading.svelte-10jah2g:empty {height:0px;transition:height 0.25s ease-in-out;transition-delay:1s;}.loading.svelte-10jah2g:not(:empty) {height:2em;transition:height 0.25s ease-in-out;transition-delay:0;}"};PluginDialogModal=class extends import_obsidian.Modal{isOpened(){return null!=this.component}constructor(app,plugin2){super(app);this.plugin=plugin2}onOpen(){const{contentEl}=this;this.contentEl.setCssStyles({overflow:"auto",display:"flex",flexDirection:"column"});this.titleEl.setText("Customization Sync (Beta3)");this.component||(this.component=mount(PluginPane,{target:contentEl,props:{plugin:this.plugin,core:this.plugin.core}}))}onClose(){if(this.component){unmount(this.component);this.component=void 0}}};d="";d2="\n";UPDATED_CONFIGURATION_NOTICE_KEY="config-sync:updated-configuration";DUMMY_HEAD=serialize({category:"CONFIG",name:"migrated",files:[],mtime:0,term:"-",displayName:"MIRAGED"});DUMMY_END=d+d2+"";pluginList=writable([]);pluginIsEnumerating=writable(!1);pluginV2Progress=writable(0);pluginManifests=new Map;pluginManifestStore=writable(pluginManifests);PluginDataExDisplayV2=class{constructor(data){this.files=[];this.documentPath=`${data.documentPath}`;this.category=`${data.category}`;this.name=`${data.name}`;this.term=`${data.term}`;this.files=[...data.files];this.confKey=`${categoryToFolder(this.category,this.term)}${this.name}`;this.applyLoadedManifest()}async setFile(file){const old=this.files.find(e3=>e3.filename==file.filename);if(old){if(old.mtime==file.mtime&&await isDocContentSame(old.data,file.data))return;this.files=this.files.filter(e3=>e3.filename!=file.filename)}this.files.push(file);"manifest.json"==file.filename&&this.applyLoadedManifest()}deleteFile(filename){this.files=this.files.filter(e3=>e3.filename!=filename)}applyLoadedManifest(){const manifest=pluginManifests.get(this.confKey);if(manifest){this._displayName=manifest.name;"PLUGIN_MAIN"!=this.category&&"THEME"!=this.category||(this._version=null==manifest?void 0:manifest.version)}}get displayName(){return this._displayName||this.name}get version(){return this._version}get mtime(){return~~this.files.reduce((a2,b3)=>a2+b3.mtime,0)/this.files.length}};ConfigSync=class extends LiveSyncCommands{constructor(core){super(core);this.pluginDialog=void 0;this.periodicPluginSweepProcessor=new PeriodicProcessor(this.core,async()=>await this.scanAllConfigFiles(!1));this.pluginList=[];this.addRibbonIcon=this.services.API.addRibbonIcon.bind(this.services.API);this.pluginScanProcessor=new QueueProcessor(async v2=>{const plugin2=v2[0];if(this.useV2){await this.migrateV1ToV2(!1,plugin2);return[]}const path2=plugin2.path||this.getPath(plugin2),oldEntry=this.pluginList.find(e3=>e3.documentPath==path2);if(oldEntry&&oldEntry.mtime==plugin2.mtime)return[];try{const pluginData=await this.loadPluginData(path2);if(pluginData){let newList=[...this.pluginList];newList=newList.filter(x3=>x3.documentPath!=pluginData.documentPath);newList.push(pluginData);this.pluginList=newList;pluginList.set(newList)}return[]}catch(ex){this._log(`Something happened at enumerating customization :${path2}`,LOG_LEVEL_NOTICE);this._log(ex,LOG_LEVEL_VERBOSE)}return[]},{suspended:!1,batchSize:1,concurrentLimit:10,delay:100,yieldThreshold:10,maintainDelay:!1,totalRemainingReactiveSource:pluginScanningCount}).startPipeline();this.pluginScanProcessorV2=new QueueProcessor(async v2=>{const plugin2=v2[0],path2=plugin2.path||this.getPath(plugin2),oldEntry=this.pluginList.find(e3=>e3.documentPath==path2);if(oldEntry&&oldEntry.mtime==plugin2.mtime)return[];try{const pluginData=await this.loadPluginData(path2);if(pluginData){let newList=[...this.pluginList];newList=newList.filter(x3=>x3.documentPath!=pluginData.documentPath);newList.push(pluginData);this.pluginList=newList;pluginList.set(newList)}return[]}catch(ex){this._log(`Something happened at enumerating customization :${path2}`,LOG_LEVEL_NOTICE);this._log(ex,LOG_LEVEL_VERBOSE)}return[]},{suspended:!1,batchSize:1,concurrentLimit:10,delay:100,yieldThreshold:10,maintainDelay:!1,totalRemainingReactiveSource:pluginScanningCount}).startPipeline();this.loadedManifest_mTime=new Map;this.updatingV2Count=0;this.recentProcessedInternalFiles=[];pluginScanningCount.onChanged(e3=>{const total=e3.value;pluginIsEnumerating.set(0!=total)})}get configDir(){return this.core.services.API.getSystemConfigDir()}get kvDB(){return this.core.kvDB}get useV2(){return this.core.settings.usePluginSyncV2}get useSyncPluginEtc(){return this.core.settings.usePluginEtc}isThisModuleEnabled(){return this.core.settings.usePluginSync}showPluginSyncModal(){if(this.isThisModuleEnabled())if(this.pluginDialog)this.pluginDialog.open();else{this.pluginDialog=new PluginDialogModal(this.app,this.services.context.liveSyncPlugin);this.pluginDialog.open()}}hidePluginSyncModal(){if(null!=this.pluginDialog){this.pluginDialog.close();this.pluginDialog=void 0}}onunload(){var _a13;cancelTask(UPDATED_CONFIGURATION_NOTICE_KEY);this.hidePluginSyncModal();null==(_a13=this.periodicPluginSweepProcessor)||_a13.disable();this.services.context.notices.hide(UPDATED_CONFIGURATION_NOTICE_KEY)}onload(){(0,import_obsidian.addIcon)("custom-sync",'<g transform="rotate(-90 75 218)" fill="currentColor" fill-rule="evenodd">\n <path d="m272 166-9.38 9.38 9.38 9.38 9.38-9.38c1.96-1.93 5.11-1.9 7.03 0.058 1.91 1.94 1.91 5.04 0 6.98l-9.38 9.38 5.86 5.86-11.7 11.7c-8.34 8.35-21.4 9.68-31.3 3.19l-3.84 3.98c-8.45 8.7-20.1 13.6-32.2 13.6h-5.55v-9.95h5.55c9.43-0.0182 18.5-3.84 25-10.6l3.95-4.09c-6.54-9.86-5.23-23 3.14-31.3l11.7-11.7 5.86 5.86 9.38-9.38c1.96-1.93 5.11-1.9 7.03 0.0564 1.91 1.93 1.91 5.04 2e-3 6.98z"/>\n </g>');this.services.API.addCommand({id:"livesync-plugin-dialog-ex",name:"Show customization sync dialog",checkCallback:checking=>{if(!this.isThisModuleEnabled())return!1;checking||this.showPluginSyncModal();return!0}});this.addRibbonIcon("custom-sync",$msg("cmdConfigSync.showCustomizationSync"),()=>{this.showPluginSyncModal()}).addClass("livesync-ribbon-showcustom");eventHub.onEvent(EVENT_REQUEST_OPEN_PLUGIN_SYNC_DIALOG2,()=>this.showPluginSyncModal())}getFileCategory(filePath){return 2==filePath.split("/").length&&filePath.endsWith(".json")?"CONFIG":4==filePath.split("/").length&&filePath.startsWith(`${this.configDir}/themes/`)?"THEME":filePath.startsWith(`${this.configDir}/snippets/`)&&filePath.endsWith(".css")?"SNIPPET":filePath.startsWith(`${this.configDir}/plugins/`)?filePath.endsWith("/styles.css")||filePath.endsWith("/manifest.json")||filePath.endsWith("/main.js")?"PLUGIN_MAIN":filePath.endsWith("/data.json")?"PLUGIN_DATA":this.useV2&&this.useSyncPluginEtc?"PLUGIN_ETC":"":""}isTargetPath(filePath){return!!filePath.startsWith(this.configDir)&&""!=this.getFileCategory(filePath)}async _everyOnDatabaseInitialized(showNotice){if(!this.isThisModuleEnabled())return!0;try{this._log("Scanning customizations...");await this.scanAllConfigFiles(showNotice);this._log("Scanning customizations : done")}catch(ex){this._log("Scanning customizations : failed");this._log(ex,LOG_LEVEL_VERBOSE)}return!0}async _everyBeforeReplicate(showNotice){if(!this.isThisModuleEnabled())return!0;if(this.settings.autoSweepPlugins){await this.scanAllConfigFiles(showNotice);return!0}return!0}async _everyOnResumeProcess(){if(!this.isThisModuleEnabled())return!0;if(this._isMainSuspended())return!0;this.settings.autoSweepPlugins&&await this.scanAllConfigFiles(!1);this.periodicPluginSweepProcessor.enable(this.settings.autoSweepPluginsPeriodic&&!this.settings.watchInternalFileChanges?1e3*PERIODIC_PLUGIN_SWEEP:0);return!0}_everyAfterResumeProcess(){const q2=activeDocument.querySelector(".livesync-ribbon-showcustom");null==q2||q2.toggleClass("sls-hidden",!this.isThisModuleEnabled());return Promise.resolve(!0)}async reloadPluginList(showMessage2){this.pluginList=[];this.loadedManifest_mTime.clear();pluginList.set(this.pluginList);await this.updatePluginList(showMessage2)}async loadPluginData(path2){const wx=await this.localDatabase.getDBEntry(path2,void 0,!1,!1);if(wx){const data=deserialize(getDocDataAsArray(wx.data),{}),xFiles=[];let missingHash=!1;for(const file of data.files){const work={...file,data:[]};if(!file.hash){const tempStr=getDocDataAsArray(work.data),hash3=digestHash(tempStr);file.hash=hash3;missingHash=!0}work.data=[file.hash];xFiles.push(work)}if(missingHash){this._log(`Digest created for ${path2} to improve checking`,LOG_LEVEL_VERBOSE);wx.data=serialize(data);fireAndForget(()=>this.localDatabase.putDBEntry(createSavingEntryFromLoadedEntry(wx)))}return{...data,documentPath:this.getPath(wx),files:xFiles}}return!1}filenameToUnifiedKey(path2,termOverRide){const term=termOverRide||this.services.setting.getDeviceAndVaultName(),category=this.getFileCategory(path2),name="CONFIG"==category||"SNIPPET"==category?path2.split("/").slice(-1)[0]:"PLUGIN_ETC"==category?path2.split("/").slice(-2).join("/"):path2.split("/").slice(-2)[0];return`${ICXHeader}${term}/${category}/${name}.md`}filenameWithUnifiedKey(path2,termOverRide){const term=termOverRide||this.services.setting.getDeviceAndVaultName(),category=this.getFileCategory(path2),name="CONFIG"==category||"SNIPPET"==category?path2.split("/").slice(-1)[0]:path2.split("/").slice(-2)[0],baseName="CONFIG"==category||"SNIPPET"==category?name:path2.split("/").slice(3).join("/");return`${ICXHeader}${term}/${category}/${name}%${baseName}`}unifiedKeyPrefixOfTerminal(termOverRide){const term=termOverRide||this.services.setting.getDeviceAndVaultName();return`${ICXHeader}${term}/`}parseUnifiedPath(unifiedPath){const[device,category,...rest]=stripAllPrefixes(unifiedPath).split("/"),relativePath=rest.join("/"),[key3,filename]=relativePath.split("%"),pathV1=unifiedPath.split("%")[0]+".md";return{device,category,key:key3,filename,pathV1}}async createPluginDataExFileV2(unifiedPathV2,loaded){const{category,key:key3,filename,device}=this.parseUnifiedPath(unifiedPathV2);if(!loaded){const d4=await this.localDatabase.getDBEntry(unifiedPathV2);if(!d4){this._log(`The file ${unifiedPathV2} is not found`,LOG_LEVEL_VERBOSE);return!1}if(!isLoadedEntry(d4)){this._log(`The file ${unifiedPathV2} is not a note`,LOG_LEVEL_VERBOSE);return!1}loaded=d4}const confKey=`${categoryToFolder(category,device)}${key3}`,relativeFilename=`${categoryToFolder(category,"")}${"CONFIG"==category||"SNIPPET"==category?"":key3+"/"}${filename}`.substring(1),dataSrc=getDocData(loaded.data),dataStart=dataSrc.indexOf(DUMMY_END),data=dataSrc.substring(dataStart+DUMMY_END.length),file={...loaded,hash:"",data:[base64ToString(data)],filename:relativeFilename,displayName:filename};if("manifest.json"==filename)if(this.loadedManifest_mTime.get(confKey)!=file.mtime&&null==pluginManifests.get(confKey)){try{const parsedManifest=JSON.parse(base64ToString(data));setManifest(confKey,parsedManifest);this.pluginList.filter(e3=>e3 instanceof PluginDataExDisplayV2&&e3.confKey==confKey).forEach(e3=>e3.applyLoadedManifest());pluginList.set(this.pluginList)}catch(ex){this._log(`The file ${loaded.path} seems to manifest, but could not be decoded as JSON`,LOG_LEVEL_VERBOSE);this._log(ex,LOG_LEVEL_VERBOSE)}this.loadedManifest_mTime.set(confKey,file.mtime)}else{this.pluginList.filter(e3=>e3 instanceof PluginDataExDisplayV2&&e3.confKey==confKey).forEach(e3=>e3.applyLoadedManifest());pluginList.set(this.pluginList)}return file}createPluginDataFromV2(unifiedPathV2){const{category,device,key:key3,pathV1}=this.parseUnifiedPath(unifiedPathV2);if(""==category)return;const ret=new PluginDataExDisplayV2({documentPath:pathV1,category,name:key3,term:`${device}`,files:[],mtime:0});return ret}async updatePluginListV2(showMessage2,unifiedFilenameWithKey){try{this.updatingV2Count++;pluginV2Progress.set(this.updatingV2Count);const{pathV1}=this.parseUnifiedPath(unifiedFilenameWithKey),oldEntry=this.pluginList.find(e3=>e3.documentPath==pathV1);let entry;if(oldEntry&&oldEntry instanceof PluginDataExDisplayV2)oldEntry instanceof PluginDataExDisplayV2&&(entry=oldEntry);else{const newEntry=this.createPluginDataFromV2(unifiedFilenameWithKey);newEntry&&(entry=newEntry)}if(!entry)return;const file=await this.createPluginDataExFileV2(unifiedFilenameWithKey);if(file)await entry.setFile(file);else{entry.deleteFile(unifiedFilenameWithKey);0==entry.files.length&&(this.pluginList=this.pluginList.filter(e3=>e3.documentPath!=pathV1))}const newList=this.pluginList.filter(e3=>e3.documentPath!=entry.documentPath);newList.push(entry);this.pluginList=newList;scheduleTask("updatePluginListV2",100,()=>{pluginList.set(this.pluginList)})}finally{this.updatingV2Count--;pluginV2Progress.set(this.updatingV2Count)}}async migrateV1ToV2(showMessage2,entry){var _a13;const v1Path=entry.path;this._log(`Migrating ${entry.path} to V2`,showMessage2?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO);if(entry.deleted){this._log(`The entry ${v1Path} is already deleted`,LOG_LEVEL_VERBOSE);return}if(!v1Path.endsWith(".md")&&!v1Path.startsWith(ICXHeader)){this._log(`The entry ${v1Path} is not a customisation sync binder`,LOG_LEVEL_VERBOSE);return}if(-1!==v1Path.indexOf("%")){this._log(`The entry ${v1Path} is already migrated`,LOG_LEVEL_VERBOSE);return}const loadedEntry=await this.localDatabase.getDBEntry(v1Path);if(!loadedEntry){this._log(`The entry ${v1Path} is not found`,LOG_LEVEL_VERBOSE);return}const pluginData=deserialize(getDocDataAsArray(loadedEntry.data),{}),prefixPath=v1Path.slice(0,-3)+"%",category=pluginData.category;for(const f4 of pluginData.files){const stripTable={CONFIG:0,THEME:2,SNIPPET:1,PLUGIN_MAIN:2,PLUGIN_DATA:2,PLUGIN_ETC:2},deletePrefixCount=null!=(_a13=null==stripTable?void 0:stripTable[category])?_a13:1,relativeFilename=f4.filename.split("/").slice(deletePrefixCount).join("/"),v2Path=prefixPath+relativeFilename;this._log(`Migrating ${v1Path} / ${relativeFilename} to ${v2Path}`,LOG_LEVEL_VERBOSE);const newId2=await this.services.path.path2id(v2Path),data=createBlob([DUMMY_HEAD,DUMMY_END,...getDocDataAsArray(f4.data)]),saving={...loadedEntry,_rev:void 0,_id:newId2,path:v2Path,data,datatype:"plain",type:"plain",children:[],eden:{}},r4=await this.core.localDatabase.putDBEntry(saving);if(r4&&r4.ok){this._log(`Migrated ${v1Path} / ${f4.filename} to ${v2Path}`,LOG_LEVEL_INFO);const delR=await this.deleteConfigOnDatabase(v1Path);delR?this._log(`Deleted ${v1Path} successfully`,LOG_LEVEL_INFO):this._log(`Failed to delete ${v1Path}`,LOG_LEVEL_NOTICE)}}}async updatePluginList(showMessage2,updatedDocumentPath){if(this.isThisModuleEnabled()){try{this.updatingV2Count++;pluginV2Progress.set(this.updatingV2Count);const updatedDocumentId=updatedDocumentPath?await this.path2id(updatedDocumentPath):"",plugins=updatedDocumentPath?this.localDatabase.findEntries(updatedDocumentId,updatedDocumentId+"􏿿",{include_docs:!0,key:updatedDocumentId,limit:1}):this.localDatabase.findEntries(ICXHeader+"",`${ICXHeader}􏿿`,{include_docs:!0});for await(const v2 of plugins){if(v2.deleted||v2._deleted)continue;if(-1!==v2.path.indexOf("%")){fireAndForget(()=>this.updatePluginListV2(showMessage2,v2.path));continue}const path2=v2.path||this.getPath(v2);updatedDocumentPath&&updatedDocumentPath!=path2||this.pluginScanProcessor.enqueue(v2)}}finally{pluginIsEnumerating.set(!1);this.updatingV2Count--;pluginV2Progress.set(this.updatingV2Count)}pluginIsEnumerating.set(!1)}else{this.pluginScanProcessor.clearQueue();this.pluginList=[];pluginList.set(this.pluginList)}}async compareUsingDisplayData(dataA,dataB,compareEach=!1){const loadFile=async data=>{if(data instanceof PluginDataExDisplayV2||compareEach)return data.files[0];const loadDoc=await this.localDatabase.getDBEntry(data.documentPath);if(!loadDoc)return!1;const pluginData=deserialize(getDocDataAsArray(loadDoc.data),{});pluginData.documentPath=data.documentPath;const file=pluginData.files[0],doc={...loadDoc,...file,datatype:"newnote"};return doc},fileA=await loadFile(dataA),fileB=await loadFile(dataB);this._log(`Comparing: ${dataA.documentPath} <-> ${dataB.documentPath}`,LOG_LEVEL_VERBOSE);if(!fileA||!fileB){this._log(`Could not load ${dataA.name} for comparison: ${fileA?"":dataA.term}${fileB?"":dataB.term}`,LOG_LEVEL_NOTICE);return!1}let path2=stripAllPrefixes(fileA.path.split("/").slice(-1).join("/"));-1!==path2.indexOf("%")&&(path2=path2.split("%")[1]);if(fileA.path.endsWith(".json"))return serialized("config:merge-data",()=>new Promise(res2=>{this._log("Opening data-merging dialog",LOG_LEVEL_VERBOSE);const modal=new JsonResolveModal(this.app,path2,[fileA,fileB],async(keep,result)=>{if(null==result)return res2(!1);try{res2(await this.applyData(dataA,result))}catch(ex){this._log("Could not apply merged file");this._log(ex,LOG_LEVEL_VERBOSE);res2(!1)}},"Local",`${dataB.term}`,"B",!0,!0,"Difference between local and remote");modal.open()}));{const dmp=new import_diff_match_patch.diff_match_patch;let docAData=getDocData(fileA.data),docBData=getDocData(fileB.data);"plain"!=(null==fileA?void 0:fileA.datatype)&&(docAData=base64ToString(docAData));"plain"!=(null==fileB?void 0:fileB.datatype)&&(docBData=base64ToString(docBData));const diffMap=dmp.diff_linesToChars_(docAData,docBData),diff=dmp.diff_main(diffMap.chars1,diffMap.chars2,!1);dmp.diff_charsToLines_(diff,diffMap.lineArray);dmp.diff_cleanupSemantic(diff);const diffResult={left:{rev:"A",...fileA,data:docAData},right:{rev:"B",...fileB,data:docBData},diff},d4=new ConflictResolveModal(this.app,path2,diffResult,!0,dataB.term);d4.open();const ret=await d4.waitForResult();if(ret===CANCELLED)return!1;if(ret===LEAVE_TO_SUBSEQUENT)return!1;const resultContent="A"==ret?docAData:"B"==ret?docBData:void 0;return!!resultContent&&await this.applyData(dataA,resultContent)}}async applyDataV2(data,content){const baseDir=this.configDir;try{if(content){const filename=data.files[0].filename;this._log(`Applying ${filename} of ${data.displayName||data.name}..`);const path2=`${baseDir}/${filename}`;await this.core.storageAccess.ensureDir(path2);await this.core.storageAccess.writeHiddenFileAuto(path2,content);await this.storeCustomisationFileV2(path2,this.services.setting.getDeviceAndVaultName())}else{const files=data.files;for(const f4 of files){const stat={mtime:f4.mtime,ctime:f4.ctime},path2=`${baseDir}/${f4.filename}`;this._log(`Applying ${f4.filename} of ${data.displayName||data.name}..`);await this.core.storageAccess.ensureDir(path2);if("newnote"==f4.datatype){let oldData;try{oldData=await this.core.storageAccess.readHiddenFileBinary(path2)}catch(ex){this._log(`Could not read the file ${f4.filename}`,LOG_LEVEL_VERBOSE);this._log(ex,LOG_LEVEL_VERBOSE);oldData=new ArrayBuffer(0)}const content2=base64ToArrayBuffer(f4.data);if(await isDocContentSame(oldData,content2)){this._log(`The file ${f4.filename} is already up-to-date`,LOG_LEVEL_VERBOSE);continue}await this.core.storageAccess.writeHiddenFileAuto(path2,content2,stat)}else{let oldData;try{oldData=await this.core.storageAccess.readHiddenFileText(path2)}catch(ex){this._log(`Could not read the file ${f4.filename}`,LOG_LEVEL_VERBOSE);this._log(ex,LOG_LEVEL_VERBOSE);oldData=""}const content2=getDocData(f4.data);if(await isDocContentSame(oldData,content2)){this._log(`The file ${f4.filename} is already up-to-date`,LOG_LEVEL_VERBOSE);continue}await this.core.storageAccess.writeHiddenFileAuto(path2,content2,stat)}this._log(`Applied ${f4.filename} of ${data.displayName||data.name}..`);await this.storeCustomisationFileV2(path2,this.services.setting.getDeviceAndVaultName())}}}catch(ex){this._log(`Applying ${data.displayName||data.name}.. Failed`,LOG_LEVEL_NOTICE);this._log(ex,LOG_LEVEL_VERBOSE);return!1}return!0}async applyData(data,content){this._log(`Applying ${data.displayName||data.name}..`);if(data instanceof PluginDataExDisplayV2)return this.applyDataV2(data,content);const baseDir=this.configDir;try{if(!data.documentPath)throw new LiveSyncError("InternalError: Document path not exist");const dx=await this.localDatabase.getDBEntry(data.documentPath);if(0==dx)throw new LiveSyncError("Not found on database");const loadedData=deserialize(getDocDataAsArray(dx.data),{});for(const f4 of loadedData.files){this._log(`Applying ${f4.filename} of ${data.displayName||data.name}..`);try{const path2=`${baseDir}/${f4.filename}`;await this.core.storageAccess.ensureDir(path2);if(content)await this.core.storageAccess.writeHiddenFileAuto(path2,content);else{const dt=decodeBinary(f4.data);await this.core.storageAccess.writeHiddenFileAuto(path2,dt)}this._log(`Applying ${f4.filename} of ${data.displayName||data.name}.. Done`)}catch(ex){this._log(`Applying ${f4.filename} of ${data.displayName||data.name}.. Failed`);this._log(ex,LOG_LEVEL_VERBOSE)}}const uPath=`${baseDir}/${loadedData.files[0].filename}`;await this.storeCustomizationFiles(uPath);await this.updatePluginList(!0,uPath);await delay(100);this._log(`Config ${data.displayName||data.name} has been applied`,LOG_LEVEL_NOTICE);if("PLUGIN_DATA"==data.category||"PLUGIN_MAIN"==data.category){const pluginManager=getObsidianCommunityPluginManager(this.app),pluginManifest=pluginManager.manifests.find(manifest=>pluginManager.enabledPlugins.has(manifest.id)&&manifest.dir==`${baseDir}/plugins/${data.name}`);if(pluginManifest){this._log(`Unloading plugin: ${pluginManifest.name}`,LOG_LEVEL_NOTICE,"plugin-reload-"+pluginManifest.id);await pluginManager.unloadPlugin(pluginManifest.id);await pluginManager.loadPlugin(pluginManifest.id);this._log(`Plugin reloaded: ${pluginManifest.name}`,LOG_LEVEL_NOTICE,"plugin-reload-"+pluginManifest.id)}}else"CONFIG"==data.category&&this.services.appLifecycle.askRestart();return!0}catch(ex){this._log(`Applying ${data.displayName||data.name}.. Failed`);this._log(ex,LOG_LEVEL_VERBOSE);return!1}}async deleteData(data){try{if(data.documentPath){const delList=[];if(this.useV2){const deleteList=this.pluginList.filter(e3=>e3.documentPath==data.documentPath).filter(e3=>e3 instanceof PluginDataExDisplayV2).map(e3=>e3.files).flat();for(const e3 of deleteList)delList.push(e3.path)}delList.push(data.documentPath);const p2=delList.map(async e3=>{await this.deleteConfigOnDatabase(e3);await this.updatePluginList(!1,e3)});await Promise.allSettled(p2);this._log(`Deleted: ${data.category}/${data.name} of ${data.category} (${delList.length} items)`,LOG_LEVEL_NOTICE)}return!0}catch(ex){this._log(`Failed to delete: ${data.documentPath}`,LOG_LEVEL_NOTICE);this._log(ex,LOG_LEVEL_VERBOSE);return!1}}async _anyModuleParsedReplicationResultItem(docs){if(!docs._id.startsWith(ICXHeader))return!1;this.isThisModuleEnabled()&&await this.updatePluginList(!1,docs.path?docs.path:this.getPath(docs));if(this.isThisModuleEnabled()&&this.core.settings.notifyPluginOrSettingUpdated&&(!this.pluginDialog||this.pluginDialog&&!this.pluginDialog.isOpened())){const fragment=createFragment(doc=>{doc.createSpan(void 0,a2=>{a2.appendText("Some configuration has been arrived, Press ");a2.appendChild(a2.createEl("a",void 0,anchor=>{anchor.text="HERE";anchor.addEventListener("click",()=>{this.showPluginSyncModal()})}));a2.appendText(" to open the config sync dialog , or press elsewhere to dismiss this message.")})});scheduleTask(UPDATED_CONFIGURATION_NOTICE_KEY,1e3,()=>{this.services.context.notices.show(UPDATED_CONFIGURATION_NOTICE_KEY,fragment,{durationMs:2e4})})}return!0}async _everyRealizeSettingSyncMode(){var _a13;null==(_a13=this.periodicPluginSweepProcessor)||_a13.disable();if(!this._isMainReady)return!0;if(!this._isMainSuspended())return!0;if(!this.isThisModuleEnabled())return!0;this.settings.autoSweepPlugins&&await this.scanAllConfigFiles(!1);this.periodicPluginSweepProcessor.enable(this.settings.autoSweepPluginsPeriodic&&!this.settings.watchInternalFileChanges?1e3*PERIODIC_PLUGIN_SWEEP:0);return!0}async makeEntryFromFile(path2){const stat=await this.core.storageAccess.statHidden(path2);let version2,displayName;if(!stat)return!1;const contentBin=await this.core.storageAccess.readHiddenFileBinary(path2);let content;try{content=await arrayBufferToBase64(contentBin);if(path2.toLowerCase().endsWith("/manifest.json")){const v2=readString(new Uint8Array(contentBin));try{const json=JSON.parse(v2);if("object"==typeof json&&null!==json){"version"in json&&(version2=String(json.version));"name"in json&&(displayName=String(json.name))}}catch(ex){this._log(`Configuration sync data: ${path2} looks like manifest, but could not read the version`,LOG_LEVEL_INFO);this._log(ex,LOG_LEVEL_VERBOSE)}}}catch(ex){this._log(`The file ${path2} could not be encoded`);this._log(ex,LOG_LEVEL_VERBOSE);return!1}const mtime=stat.mtime;return{filename:path2.substring(this.configDir.length+1),data:content,mtime,size:stat.size,version:version2,displayName}}async storeCustomisationFileV2(path2,term,force=!1){const vf=this.filenameWithUnifiedKey(path2,term);return await serialized(`plugin-${vf}`,async()=>{const prefixedFileName=vf,id=await this.path2id(prefixedFileName),stat=await this.core.storageAccess.statHidden(path2);if(!stat)return!1;const mtime=stat.mtime,content=await this.core.storageAccess.readHiddenFileBinary(path2),contentBlob=createBlob([DUMMY_HEAD,DUMMY_END,...await arrayBufferToBase64(content)]);try{const old=await this.localDatabase.getDBEntryMeta(prefixedFileName,void 0,!1);let saveData;if(!1===old)saveData={_id:id,path:prefixedFileName,data:contentBlob,mtime,ctime:mtime,datatype:"plain",size:contentBlob.size,children:[],deleted:!1,type:"plain",eden:{}};else{if(this.services.path.isMarkedAsSameChanges(prefixedFileName,[old.mtime,mtime+1])==EVEN){this._log(`STORAGE --\x3e DB:${prefixedFileName}: (config) Skipped (Already checked the same)`,LOG_LEVEL_DEBUG);return}const docXDoc=await this.localDatabase.getDBEntryFromMeta(old,!1,!1);if(0==docXDoc)throw new LiveSyncError("Could not load the document");const dataSrc=getDocData(docXDoc.data),dataStart=dataSrc.indexOf(DUMMY_END),oldContent=dataSrc.substring(dataStart+DUMMY_END.length),oldContentArray=base64ToArrayBuffer(oldContent);if(await isDocContentSame(oldContentArray,content)){this._log(`STORAGE --\x3e DB:${prefixedFileName}: (config) Skipped (the same content)`,LOG_LEVEL_VERBOSE);this.services.path.markChangesAreSame(prefixedFileName,old.mtime,mtime+1);return!0}saveData={...old,data:contentBlob,mtime,size:contentBlob.size,datatype:"plain",children:[],deleted:!1,type:"plain"}}const ret=await this.localDatabase.putDBEntry(saveData);this._log(`STORAGE --\x3e DB:${prefixedFileName}: (config) Done`);fireAndForget(()=>this.updatePluginListV2(!1,this.filenameWithUnifiedKey(path2)));return ret}catch(ex){this._log(`STORAGE --\x3e DB:${prefixedFileName}: (config) Failed`);this._log(ex,LOG_LEVEL_VERBOSE);return!1}})}async storeCustomizationFiles(path2,termOverRide){const term=termOverRide||this.services.setting.getDeviceAndVaultName();if(""==term){this._log($msg("We have to configure the device name"),LOG_LEVEL_NOTICE);return}if(this.useV2)return await this.storeCustomisationFileV2(path2,term);const vf=this.filenameToUnifiedKey(path2,term);return await serialized(`plugin-${vf}`,async()=>{const category=this.getFileCategory(path2);let mtime=0,fileTargets=[];const name="CONFIG"==category||"SNIPPET"==category?path2.split("/").reverse()[0]:path2.split("/").reverse()[1],parentPath=path2.split("/").slice(0,-1).join("/"),prefixedFileName=this.filenameToUnifiedKey(path2,term),id=await this.path2id(prefixedFileName),dt={category,files:[],name,mtime:0,term};if("CONFIG"==category||"SNIPPET"==category||"PLUGIN_ETC"==category||"PLUGIN_DATA"==category){fileTargets=[path2];"PLUGIN_ETC"==category&&(dt.displayName=path2.split("/").slice(-1).join("/"))}else"PLUGIN_MAIN"==category?fileTargets=["manifest.json","main.js","styles.css"].map(e3=>`${parentPath}/${e3}`):"THEME"==category&&(fileTargets=["manifest.json","theme.css"].map(e3=>`${parentPath}/${e3}`));for(const target of fileTargets){const data=await this.makeEntryFromFile(target);if(0!=data){data.version&&(dt.version=data.version);data.displayName&&(dt.displayName=data.displayName);mtime=0==mtime?data.mtime:(data.mtime+mtime)/2;dt.files.push(data)}else this._log(`Config: skipped (Possibly is not exist): ${target} `,LOG_LEVEL_VERBOSE)}dt.mtime=mtime;if(0==dt.files.length){this._log(`Nothing left: deleting.. ${path2}`);await this.deleteConfigOnDatabase(prefixedFileName);await this.updatePluginList(!1,prefixedFileName);return}const content=createTextBlob(serialize(dt));try{const old=await this.localDatabase.getDBEntryMeta(prefixedFileName,void 0,!1);let saveData;if(!1===old)saveData={_id:id,path:prefixedFileName,data:content,mtime,ctime:mtime,datatype:"newnote",size:content.size,children:[],deleted:!1,type:"newnote",eden:{}};else{if(old.mtime==mtime)return!0;const oldC=await this.localDatabase.getDBEntryFromMeta(old,!1,!1);if(oldC){const d4=deserialize(getDocDataAsArray(oldC.data),{});if(d4.files.length==dt.files.length){const diffs=d4.files.map(previous=>({prev:previous,curr:dt.files.find(e3=>e3.filename==previous.filename)})).map(async e3=>{var _a13,_b6;try{return await isDocContentSame(null!=(_b6=null==(_a13=e3.curr)?void 0:_a13.data)?_b6:[],e3.prev.data)}catch(e4){return!1}}),isSame=(await Promise.all(diffs)).every(e3=>1==e3);if(isSame){this._log(`STORAGE --\x3e DB:${prefixedFileName}: (config) Skipped (Same content)`,LOG_LEVEL_VERBOSE);return!0}}}saveData={...old,data:content,mtime,size:content.size,datatype:"newnote",children:[],deleted:!1,type:"newnote"}}const ret=await this.localDatabase.putDBEntry(saveData);await this.updatePluginList(!1,saveData.path);this._log(`STORAGE --\x3e DB:${prefixedFileName}: (config) Done`);return ret}catch(ex){this._log(`STORAGE --\x3e DB:${prefixedFileName}: (config) Failed`);this._log(ex,LOG_LEVEL_VERBOSE);return!1}})}async _anyProcessOptionalFileEvent(path2){return await this.watchVaultRawEventsAsync(path2)}async watchVaultRawEventsAsync(path2){if(!this._isMainReady)return!1;if(this._isMainSuspended())return!1;if(!this.isThisModuleEnabled())return!1;const stat=await this.core.storageAccess.statHidden(path2);if(stat&&"file"!=stat.type)return!1;const configDir=normalizePath(this.configDir),synchronisedInConfigSync=Object.values(this.settings.pluginSyncExtendedSetting).filter(e3=>e3.mode!=MODE_SELECTIVE&&e3.mode!=MODE_SHINY).map(e3=>e3.files).flat().map(e3=>`${configDir}/${e3}`.toLowerCase());if(synchronisedInConfigSync.some(e3=>e3.startsWith(path2.toLowerCase()))){this._log(`Customization file skipped: ${path2}`,LOG_LEVEL_VERBOSE);return!1}const storageMTime=~~((stat&&stat.mtime||0)/1e3),key3=`${path2}-${storageMTime}`;if(this.recentProcessedInternalFiles.contains(key3))return!0;this.recentProcessedInternalFiles=[key3,...this.recentProcessedInternalFiles].slice(0,100);const keySchedule=this.filenameToUnifiedKey(path2);scheduleTask(keySchedule,100,async()=>{await this.storeCustomizationFiles(path2)});return!0}async scanAllConfigFiles(showMessage2){await shareRunningResult("scanAllConfigFiles",async()=>{var _a13;const logLevel=showMessage2?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO;this._log("Scanning customizing files.",logLevel,"scan-all-config");const term=this.services.setting.getDeviceAndVaultName();if(""==term){this._log($msg("We have to configure the device name"),LOG_LEVEL_NOTICE);return}const filesAll=await this.scanInternalFiles();if(this.useV2){const filesAllUnified=filesAll.filter(e3=>this.isTargetPath(e3)).map(e3=>[this.filenameWithUnifiedKey(e3,term),e3]),localFileMap=new Map(filesAllUnified.map(e3=>[e3[0],e3[1]])),prefix=this.unifiedKeyPrefixOfTerminal(term),entries2=this.localDatabase.findEntries(prefix+"",`${prefix}􏿿`,{include_docs:!0}),tasks3=[],concurrency=10,semaphore=Semaphore(concurrency);for await(const item of entries2)-1===item.path.indexOf("%")&&tasks3.push(async()=>{const releaser=await semaphore.acquire();try{const unifiedFilenameWithKey=`${item._id}`,localPath=localFileMap.get(unifiedFilenameWithKey);if(localPath){await this.storeCustomisationFileV2(localPath,term);localFileMap.delete(unifiedFilenameWithKey)}else await this.deleteConfigOnDatabase(unifiedFilenameWithKey)}catch(ex){this._log(`scanAllConfigFiles - Error: ${item._id}`,LOG_LEVEL_VERBOSE);this._log(ex,LOG_LEVEL_VERBOSE)}finally{releaser()}});await Promise.all(tasks3.map(e3=>e3()));const taskExtra=[];for(const[,filePath]of localFileMap)taskExtra.push(async()=>{const releaser=await semaphore.acquire();try{await this.storeCustomisationFileV2(filePath,term)}catch(ex){this._log(`scanAllConfigFiles - Error: ${filePath}`,LOG_LEVEL_VERBOSE);this._log(ex,LOG_LEVEL_VERBOSE)}finally{releaser()}});await Promise.all(taskExtra.map(e3=>e3()));fireAndForget(()=>this.updatePluginList(!1))}else{const files=filesAll.filter(e3=>this.isTargetPath(e3)).map(e3=>({key:this.filenameToUnifiedKey(e3),file:e3})),virtualPathsOfLocalFiles=[...new Set(files.map(e3=>e3.key))],filesOnDB=(await this.localDatabase.allDocsRaw({startkey:ICXHeader+"",endkey:`${ICXHeader}􏿿`,include_docs:!0})).rows.map(e3=>e3.doc).filter(e3=>!e3.deleted);let deleteCandidate=filesOnDB.map(e3=>this.getPath(e3)).filter(e3=>e3.startsWith(`${ICXHeader}${term}/`));for(const vp of virtualPathsOfLocalFiles){const p2=null==(_a13=files.find(e3=>e3.key==vp))?void 0:_a13.file;if(p2){await this.storeCustomizationFiles(p2);deleteCandidate=deleteCandidate.filter(e3=>e3!=vp)}else this._log(`scanAllConfigFiles - File not found: ${vp}`,LOG_LEVEL_VERBOSE)}for(const vp of deleteCandidate)await this.deleteConfigOnDatabase(vp);fireAndForget(()=>this.updatePluginList(!1))}})}async deleteConfigOnDatabase(prefixedFileName,forceWrite=!1){const mtime=(new Date).getTime();return await serialized("file-x-"+prefixedFileName,async()=>{try{const old=await this.localDatabase.getDBEntryMeta(prefixedFileName,void 0,!1);let saveData;if(!1===old){this._log(`STORAGE -x> DB:${prefixedFileName}: (config) already deleted (Not found on database)`);return!0}if(old.deleted){this._log(`STORAGE -x> DB:${prefixedFileName}: (config) already deleted`);return!0}saveData={...old,mtime,size:0,children:[],deleted:!0,type:"newnote"};await this.localDatabase.putRaw(saveData);await this.updatePluginList(!1,prefixedFileName);this._log(`STORAGE -x> DB:${prefixedFileName}: (config) Done`);return!0}catch(ex){this._log(`STORAGE -x> DB:${prefixedFileName}: (config) Failed`);this._log(ex,LOG_LEVEL_VERBOSE);return!1}})}async scanInternalFiles(){const filenames=(await this.getFiles(this.configDir,2)).filter(e3=>e3.startsWith(".")).filter(e3=>!e3.startsWith(".trash"));return filenames}_anyGetOptionalConflictCheckMethod(path2){return isPluginMetadata(path2)||isCustomisationSyncMetadata(path2)?Promise.resolve("newer"):Promise.resolve(!1)}_allSuspendExtraSync(){if(this.core.settings.usePluginSync||this.core.settings.autoSweepPlugins){this._log("Customisation sync have been temporarily disabled. Please enable them after the fetching, if you need them.",LOG_LEVEL_NOTICE);this.core.settings.usePluginSync=!1;this.core.settings.autoSweepPlugins=!1}return Promise.resolve(!0)}async _allConfigureOptionalSyncFeature(mode){await this.configureHiddenFileSync(mode);return!0}async configureHiddenFileSync(mode){if("DISABLE"!=mode){if("CUSTOMIZE"==mode){if(!this.services.setting.getDeviceAndVaultName()){let name=await this.core.confirm.askString($msg("Device name"),$msg("Please set this device name"),"desktop");if(!name){name=import_obsidian.Platform.isAndroidApp?"android-app":import_obsidian.Platform.isIosApp?"ios":import_obsidian.Platform.isMacOS?"macos":import_obsidian.Platform.isMobileApp?"mobile-app":import_obsidian.Platform.isMobile?"mobile":import_obsidian.Platform.isSafari?"safari":import_obsidian.Platform.isDesktop?"desktop":import_obsidian.Platform.isDesktopApp?"desktop-app":"unknown";name+=Math.random().toString(36).slice(-4)}this.services.setting.setDeviceAndVaultName(name)}await this.core.services.setting.applyPartial({usePluginSync:!0,useAdvancedMode:!0},!0);await this.scanAllConfigFiles(!0)}}else await this.core.services.setting.applyPartial({usePluginSync:!1},!0)}async getFiles(path2,lastDepth){if(-1==lastDepth)return[];let w2;try{w2=await this.app.vault.adapter.list(path2)}catch(ex){this._log(`Could not traverse(ConfigSync):${path2}`,LOG_LEVEL_INFO);this._log(ex,LOG_LEVEL_VERBOSE);return[]}let files=[...w2.files];for(const v2 of w2.folders)files=files.concat(await this.getFiles(v2,lastDepth-1));return files}onBindFunction(core,services){services.fileProcessing.processOptionalFileEvent.addHandler(this._anyProcessOptionalFileEvent.bind(this));services.conflict.getOptionalConflictCheckMethod.addHandler(this._anyGetOptionalConflictCheckMethod.bind(this));services.replication.processVirtualDocument.addHandler(this._anyModuleParsedReplicationResultItem.bind(this));services.setting.onRealiseSetting.addHandler(this._everyRealizeSettingSyncMode.bind(this));services.appLifecycle.onResuming.addHandler(this._everyOnResumeProcess.bind(this));services.appLifecycle.onResumed.addHandler(this._everyAfterResumeProcess.bind(this));services.replication.onBeforeReplicate.addHandler(this._everyBeforeReplicate.bind(this));services.databaseEvents.onDatabaseInitialised.addHandler(this._everyOnDatabaseInitialized.bind(this));services.setting.suspendExtraSync.addHandler(this._allSuspendExtraSync.bind(this));services.setting.enableOptionalFeature.addHandler(this._allConfigureOptionalSyncFeature.bind(this))}};ModuleInteractiveConflictResolver=class extends AbstractObsidianModule{constructor(){super(...arguments);this.postponedConflictEpisodes=new Set}async getConflictVersionCount(filename){try{const conflictCount=(await this.core.databaseFileAccess.getConflictedRevs(filename)).length;return 0===conflictCount?0:conflictCount+1}catch(error){this._log(`Could not inspect the conflict state of ${filename}`,LOG_LEVEL_VERBOSE);this._log(error,LOG_LEVEL_VERBOSE);return}}async getActiveConflictMessages(){const filename=this.services.vault.getActiveFilePath();if(!filename)return[];const versionCount=await this.getConflictVersionCount(filename);if(0===versionCount){this.postponedConflictEpisodes.delete(filename);return[]}return void 0!==versionCount&&versionCount>=3?[$msg("This file has ${COUNT} unresolved versions. They will be reviewed one pair at a time.",{COUNT:`${versionCount}`})]:2===versionCount||this.postponedConflictEpisodes.has(filename)?[$msg("This file has unresolved conflicts.")]:[]}async refreshConflictState(filename){0===await this.getConflictVersionCount(filename)&&this.postponedConflictEpisodes.delete(filename);eventHub.emitEvent(EVENT_ON_UNRESOLVED_ERROR)}async requestConflictResolution(filename){this.postponedConflictEpisodes.delete(filename);eventHub.emitEvent(EVENT_ON_UNRESOLVED_ERROR);await this.services.conflict.queueCheckFor(filename);await this.services.conflict.ensureAllProcessed()}_everyOnloadStart(){this.addCommand({id:"livesync-checkdoc-conflicted",name:"Resolve if conflicted.",editorCallback:(editor,view)=>{const file=view.file;file&&this.requestConflictResolution(file.path)}});this.addCommand({id:"livesync-conflictcheck",name:"Pick a file to resolve conflict",callback:async()=>{await this.pickFileForResolve()}});this.addCommand({id:"livesync-all-conflictcheck",name:"Resolve all conflicted files",callback:async()=>{await this.allConflictCheck()}});return Promise.resolve(!0)}async _anyResolveConflictByUI(filename,conflictCheckResult){return await serialized("conflict-resolve-ui",async()=>{if(this.postponedConflictEpisodes.has(filename)){this._log(`Merge: Postponed ${filename}`,LOG_LEVEL_VERBOSE);eventHub.emitEvent(EVENT_ON_UNRESOLVED_ERROR);return!1}this._log("Merge:open conflict dialog",LOG_LEVEL_VERBOSE);const dialog=new ConflictResolveModal(this.app,filename,conflictCheckResult);dialog.open();const selected=await dialog.waitForResult();if(selected===POSTPONED){this.postponedConflictEpisodes.add(filename);eventHub.emitEvent(EVENT_ON_UNRESOLVED_ERROR);this._log(`Merge: Postponed ${filename}`,LOG_LEVEL_INFO);return!1}if(selected===CANCELLED){this._log(`Merge: Cancelled ${filename}`,LOG_LEVEL_INFO);return!1}const testDoc=await this.localDatabase.getDBEntry(filename,{conflicts:!0},!1,!0,!0);if(!1===testDoc){this._log(`Merge: Could not read ${filename} from the local database`,LOG_LEVEL_VERBOSE);return!1}if(!testDoc._conflicts||0===testDoc._conflicts.length){this._log(`Merge: Nothing to do ${filename}`,LOG_LEVEL_VERBOSE);await this.refreshConflictState(filename);return!1}if(testDoc._rev!==conflictCheckResult.left.rev||!testDoc._conflicts.includes(conflictCheckResult.right.rev)){this._log(`Merge: The compared revisions changed while the dialogue was open: ${filename}`,LOG_LEVEL_INFO);await this.refreshConflictState(filename);await this.services.conflict.queueCheckFor(filename);return!1}const toDelete=selected;if(toDelete===LEAVE_TO_SUBSEQUENT){const p2=conflictCheckResult.diff.map(e3=>e3[1]).join(""),delRev=conflictCheckResult.right.rev;if(!await this.core.databaseFileAccess.storeContent(filename,p2)){this._log(`Concatenated content cannot be stored:${filename}`,LOG_LEVEL_NOTICE);return!1}if(await this.services.conflict.resolveByDeletingRevision(filename,delRev,"UI Concatenated")==MISSING_OR_ERROR){this._log(`Concatenated saved, but cannot delete conflicted revisions: ${filename}, (${displayRev(delRev)})`,LOG_LEVEL_NOTICE);return!1}}else{if("string"!=typeof toDelete||toDelete!==conflictCheckResult.left.rev&&toDelete!==conflictCheckResult.right.rev){this._log(`Merge: Something went wrong: ${filename}, (${String(toDelete)})`,LOG_LEVEL_NOTICE);return!1}if(await this.services.conflict.resolveByDeletingRevision(filename,toDelete,"UI Selected")==MISSING_OR_ERROR){this._log(`Merge: Something went wrong: ${filename}, (${toDelete})`,LOG_LEVEL_NOTICE);return!1}}this.settings.syncAfterMerge&&!this.services.appLifecycle.isSuspended()&&await this.services.replication.replicateByEvent();await this.services.conflict.queueCheckFor(filename);return!1})}async allConflictCheck(){let notifyIfEmpty=!0;for(;await this.pickFileForResolve(notifyIfEmpty);)notifyIfEmpty=!1}async pickFileForResolve(notifyIfEmpty=!0){const notes=[];for await(const doc of this.localDatabase.findAllDocs({conflicts:!0}))"_conflicts"in doc&&notes.push({id:doc._id,path:this.getPath(doc),dispPath:this.getPathWithoutPrefix(doc),mtime:doc.mtime});notes.sort((a2,b3)=>b3.mtime-a2.mtime);const notesList=notes.map(e3=>e3.dispPath);if(0==notesList.length){notifyIfEmpty&&this._log("There are no conflicted documents",LOG_LEVEL_NOTICE);return!1}const target=await this.core.confirm.askSelectString("File to resolve conflict",notesList);if(target){const targetItem=notes.find(e3=>e3.dispPath==target);await this.requestConflictResolution(targetItem.path);return!0}return!1}async _allScanStat(){const notes=[];this._log("Checking conflicted files",LOG_LEVEL_VERBOSE);try{for await(const doc of this.localDatabase.findAllDocs({conflicts:!0}))"_conflicts"in doc&&notes.push({path:this.getPath(doc),mtime:doc.mtime});if(notes.length>0){this.core.confirm.askInPopup("conflicting-detected-on-safety",'Some files have been left conflicted! Press {HERE} to resolve them, or you can do it later by "Pick a file to resolve conflict',anchor=>{anchor.text="HERE";anchor.addEventListener("click",()=>{fireAndForget(()=>this.allConflictCheck())})});this._log('Some files have been left conflicted! Please resolve them by "Pick a file to resolve conflict". The list is written in the log.',LOG_LEVEL_VERBOSE);for(const note of notes)this._log(`Conflicted: ${note.path}`)}else this._log("There are no conflicting files",LOG_LEVEL_VERBOSE)}catch(e3){this._log("Error while scanning conflicted files...",LOG_LEVEL_NOTICE);this._log(e3,LOG_LEVEL_VERBOSE);return!1}return!0}onBindFunction(core,services){services.appLifecycle.onScanningStartupIssues.addHandler(this._allScanStat.bind(this));services.appLifecycle.onInitialise.addHandler(this._everyOnloadStart.bind(this));services.appLifecycle.getUnresolvedMessages.addHandler(this.getActiveConflictMessages.bind(this));services.conflict.resolveByUserInteraction.addHandler(this._anyResolveConflictByUI.bind(this));eventHub.onEvent(EVENT_CONFLICT_CANCELLED,filename=>{fireAndForget(()=>this.refreshConflictState(filename))})}};ModuleObsidianEvents=class extends AbstractObsidianModule{constructor(){super(...arguments);this.initialCallback=void 0;this.hasFocus=!0;this.isLastHidden=!1;this._totalProcessingCount=void 0}_everyOnloadStart(){this.plugin.registerEvent(this.app.vault.on("rename",(file,oldPath)=>{eventHub.emitEvent(EVENT_FILE_RENAMED,{newPath:file.path,old:oldPath})}));this.plugin.registerEvent(this.app.workspace.on("active-leaf-change",()=>eventHub.emitEvent(EVENT_LEAF_ACTIVE_CHANGED2)));return Promise.resolve(!0)}__performAppReload(){this.services.appLifecycle.performRestart()}swapSaveCommand(){var _a13;this._log("Modifying callback of the save command",LOG_LEVEL_VERBOSE);const commandRegistry=this.app.commands,saveCommandDefinition=null==(_a13=null==commandRegistry?void 0:commandRegistry.commands)?void 0:_a13["editor:save-file"],save2=null==saveCommandDefinition?void 0:saveCommandDefinition.callback;if(saveCommandDefinition&&"function"==typeof save2){this.initialCallback=save2;saveCommandDefinition.callback=()=>{scheduleTask("syncOnEditorSave",250,()=>{if(this.services.control.hasUnloaded()){this._log("Unload and remove the handler.",LOG_LEVEL_VERBOSE);saveCommandDefinition.callback=this.initialCallback;this.initialCallback=void 0}else if(this.settings.syncOnEditorSave){this._log("Sync on Editor Save.",LOG_LEVEL_VERBOSE);fireAndForget(()=>this.services.replication.replicateByEvent())}});save2()}}const codeMirrorAdapter=compatGlobal.CodeMirrorAdapter;codeMirrorAdapter?codeMirrorAdapter.commands.save=()=>{null==commandRegistry||commandRegistry.executeCommandById("editor:save-file")}:this._log("CodeMirrorAdapter is not available")}registerWatchEvents(){this.setHasFocus=this.setHasFocus.bind(this);this.watchWindowVisibility=this.watchWindowVisibility.bind(this);this.watchWorkspaceOpen=this.watchWorkspaceOpen.bind(this);this.watchOnline=this.watchOnline.bind(this);this.plugin.registerEvent(this.app.workspace.on("file-open",this.watchWorkspaceOpen));this.plugin.registerDomEvent(activeDocument,"visibilitychange",this.watchWindowVisibility);this.plugin.registerDomEvent(compatGlobal,"focus",()=>this.setHasFocus(!0));this.plugin.registerDomEvent(compatGlobal,"blur",()=>this.setHasFocus(!1));this.plugin.registerDomEvent(compatGlobal,"online",this.watchOnline);this.plugin.registerDomEvent(compatGlobal,"offline",this.watchOnline)}get boundedActivityCounts(){const replicator=this.services.replicator;return[replicator.boundedRemoteActivityCount,replicator.boundedLocalApplicationActivityCount]}hasBoundedActivity(){return this.boundedActivityCounts.some(count=>count.value>0)}keepReplicationActiveInBackground(){return this.settings.keepReplicationActiveInBackground&&(this.settings.liveSync||this.settings.periodicReplication)&&!this.services.API.isMobile()}async applyDeferredBoundedActivityLifecycle(){if(this.hasBoundedActivity()){this.deferLifecycleUntilBoundedActivityEnds();return}const deferredLifecycle=this.deferredBoundedLifecycle;this.deferredBoundedLifecycle=void 0;const keepActiveInBackground=this.keepReplicationActiveInBackground();if("suspend-if-hidden"===deferredLifecycle&&activeWindow.document.hidden)keepActiveInBackground||await this.services.appLifecycle.onSuspending();else if("restart-continuous-if-visible"===deferredLifecycle&&!activeWindow.document.hidden&&keepActiveInBackground&&this.settings.liveSync){await this.services.appLifecycle.onSuspending();await this.services.appLifecycle.onResuming();await this.services.appLifecycle.onResumed()}}deferLifecycleUntilBoundedActivityEnds(){if(this.boundedActivityEndHandler)return;const counts=this.boundedActivityCounts,handler=()=>{if(!this.hasBoundedActivity()){for(const count of counts)count.offChanged(handler);this.boundedActivityEndHandler=void 0;fireAndForget(()=>this.applyDeferredBoundedActivityLifecycle())}};this.boundedActivityEndHandler=handler;for(const count of counts)count.onChanged(handler)}setHasFocus(hasFocus){this.hasFocus=hasFocus;this.watchWindowVisibility()}watchWindowVisibility(){scheduleTask("watch-window-visibility",100,()=>fireAndForget(()=>this.watchWindowVisibilityAsync()))}watchOnline(){scheduleTask("watch-online",500,()=>fireAndForget(()=>this.watchOnlineAsync()))}async watchOnlineAsync(){if(compatGlobal.navigator.onLine&&this.localDatabase.needScanning){this.localDatabase.needScanning=!1;await this.services.vault.scanVault()}}async watchWindowVisibilityAsync(){if(this.settings.suspendFileWatching){if(this.settings.isConfigured&&this.services.appLifecycle.isReady()&&this.hasBoundedActivity()){const isHidden2=activeWindow.document.hidden;this.isLastHidden=isHidden2;this.deferredBoundedLifecycle=isHidden2?"suspend-if-hidden":void 0;this.deferLifecycleUntilBoundedActivityEnds()}return}if(!this.settings.isConfigured)return;if(!this.services.appLifecycle.isReady())return;if(this.isLastHidden&&!this.hasFocus)return;const isHidden=activeWindow.document.hidden;if(this.isLastHidden===isHidden)return;const boundedActivityInProgress=this.hasBoundedActivity();if(!isHidden&&boundedActivityInProgress&&"suspend-if-hidden"===this.deferredBoundedLifecycle){this.isLastHidden=!1;this.deferredBoundedLifecycle=void 0;return}this.isLastHidden=isHidden;await this.services.fileProcessing.commitPendingFileEvents();const keepActiveInBackground=this.keepReplicationActiveInBackground();if(isHidden)if(boundedActivityInProgress&&!keepActiveInBackground){this.deferredBoundedLifecycle="suspend-if-hidden";this.deferLifecycleUntilBoundedActivityEnds()}else keepActiveInBackground||await this.services.appLifecycle.onSuspending();else{if(this.services.appLifecycle.isSuspended())return;if(boundedActivityInProgress&&keepActiveInBackground&&this.settings.liveSync){this.deferredBoundedLifecycle="restart-continuous-if-visible";this.deferLifecycleUntilBoundedActivityEnds();return}keepActiveInBackground&&this.settings.liveSync&&await this.services.appLifecycle.onSuspending();await this.services.appLifecycle.onResuming();await this.services.appLifecycle.onResumed()}}watchWorkspaceOpen(file){this.settings.suspendFileWatching||this.settings.isConfigured&&this.services.appLifecycle.isReady()&&file&&scheduleTask("watch-workspace-open",500,()=>fireAndForget(()=>this.watchWorkspaceOpenAsync(file)))}async watchWorkspaceOpenAsync(file){if(!this.settings.suspendFileWatching&&this.settings.isConfigured&&this.services.appLifecycle.isReady()){await this.services.fileProcessing.commitPendingFileEvents();if(null!=file){this.settings.syncOnFileOpen&&!this.services.appLifecycle.isSuspended()&&await this.services.replication.replicateByEvent();await this.services.conflict.queueCheckForIfOpen(file.path)}}}_everyOnLayoutReady(){this.swapSaveCommand();this.registerWatchEvents();return Promise.resolve(!0)}_askReload(message){this.services.appLifecycle.isReloadingScheduled()?this._log("Reloading is already scheduled",LOG_LEVEL_VERBOSE):scheduleTask("configReload",250,async()=>{const ret=await this.core.confirm.askSelectStringDialogue(message||"Do you want to restart and reload Obsidian now?",["Yes, schedule a restart after stabilisation","Yes, restart immediately","No, Leave it to me"],{defaultAction:"No, Leave it to me"});"Yes, restart immediately"==ret?this.__performAppReload():"Yes, schedule a restart after stabilisation"==ret&&this.services.appLifecycle.scheduleRestart()})}_scheduleAppReload(){if(!this._totalProcessingCount){const __tick=reactiveSource(0);this._totalProcessingCount=reactive(()=>{const dbCount=this.services.replication.databaseQueueCount.value,replicationCount=this.services.replication.replicationResultCount.value,storageApplyingCount=this.services.replication.storageApplyingCount.value,chunkCount=collectingChunks.value,pluginScanCount=pluginScanningCount.value,hiddenFilesCount=hiddenFilesEventCount.value+hiddenFilesProcessingCount.value,conflictProcessCount=this.services.conflict.conflictProcessQueueCount.value;__tick.value;return dbCount+replicationCount+storageApplyingCount+chunkCount+pluginScanCount+hiddenFilesCount+conflictProcessCount+0+0});this.plugin.registerInterval(compatGlobal.setInterval(()=>{__tick.value++},1e3));let stableCheck=3;this._totalProcessingCount.onChanged(e3=>{if(0==e3.value){stableCheck--<=0&&this.__performAppReload();this._log(`Obsidian will be restarted soon! (Within ${stableCheck} seconds)`,LOG_LEVEL_NOTICE,"restart-notice")}else stableCheck=3})}}_isReloadingScheduled(){return void 0!==this._totalProcessingCount}onBindFunction(core,services){services.appLifecycle.onLayoutReady.addHandler(this._everyOnLayoutReady.bind(this));services.appLifecycle.onInitialise.addHandler(this._everyOnloadStart.bind(this));services.appLifecycle.askRestart.setHandler(this._askReload.bind(this));services.appLifecycle.scheduleRestart.setHandler(this._scheduleAppReload.bind(this));services.appLifecycle.isReloadingScheduled.setHandler(this._isReloadingScheduled.bind(this))}};checkRemoteVersion=async(db,migrate,barrier=VER)=>{try{const versionInfo=await db.get(VERSIONING_DOCID);if("versioninfo"!=versionInfo.type)return!1;const version2=versionInfo.version;if(version2<barrier){const versionUpResult=await migrate(version2,barrier);if(versionUpResult){await bumpRemoteVersion(db);return!0}}return version2==barrier}catch(ex){if(isErrorOfMissingDoc(ex))return!!await bumpRemoteVersion(db);throw ex}};bumpRemoteVersion=async(db,barrier=VER)=>{const vi={_id:VERSIONING_DOCID,version:barrier,type:"versioninfo"},versionInfo=await resolveWithIgnoreKnownError(db.get(VERSIONING_DOCID),vi);if("versioninfo"!=versionInfo.type)return!1;vi._rev=versionInfo._rev;await db.put(vi);return!0};checkSyncInfo=async db=>{try{const syncinfo=await db.get(SYNCINFO_ID);console.log(syncinfo);return!0}catch(ex){if(isErrorOfMissingDoc(ex)){const randomStrSrc="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",temp=[...Array(30)].map(_e2=>Math.floor(Math.random()*randomStrSrc.length)).map(e3=>randomStrSrc[e3]).join(""),newSyncInfo={_id:SYNCINFO_ID,type:"syncinfo",data:temp};return!!await db.put(newSyncInfo)}console.dir(ex);return!1}};SELECTOR_COMPROMISED_CHUNK_1={selector:{_id:{$lt:"h:"},type:"leaf"}};SELECTOR_COMPROMISED_CHUNK_2={selector:{_id:{$gt:"h;"},type:"leaf"}};webcrypto2=globalThis.crypto;SALT_STR="fancySyncForYou!";SALT=(new TextEncoder).encode(SALT_STR);previousPassphrase="";_nonceV3=new Uint32Array(1);bufV3=new Uint8Array(12);previousDecryptionPassphrase="";UNDEFINED=Symbol("undefined");webcrypto3=globalThis.crypto;IV_LENGTH=12;PBKDF2_ITERATIONS=31e4;HKDF_SALT_LENGTH=32;PBKDF2_SALT_LENGTH=32;gcmTagLength=128;HKDF_ENCRYPTED_PREFIX="%=";HKDF_SALTED_ENCRYPTED_PREFIX="%$";deriveMasterKey=function memoWithMap(bufferLength,fn,keyFunction){if(bufferLength<=0)throw new Error("Buffer length must be greater than 0");const cache2=new Map,getKey3=args=>args.length>0&&"string"==typeof args[0]?args[0]:JSON.stringify(args,(key3,value)=>void 0===value?UNDEFINED:value);return function(...args){const key3=keyFunction?keyFunction(args):getKey3(args);if(cache2.has(key3)){const hitPromise=cache2.get(key3);cache2.delete(key3);cache2.set(key3,hitPromise);return hitPromise}const newPromise=fn(...args);cache2.set(key3,newPromise);newPromise.catch(()=>{cache2.get(key3)===newPromise&&cache2.delete(key3)});if(cache2.size>bufferLength){const oldest=cache2.keys().next();oldest.done||cache2.delete(oldest.value)}return newPromise}}(10,async(passphrase,pbkdf2Salt)=>{const binaryPassphrase=writeString(passphrase),keyMaterial=await webcrypto3.subtle.importKey("raw",binaryPassphrase,{name:"PBKDF2",length:256},!1,["deriveKey"]),masterKeyRaw=await webcrypto3.subtle.deriveKey({name:"PBKDF2",salt:pbkdf2Salt,iterations:PBKDF2_ITERATIONS,hash:"SHA-256"},keyMaterial,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),masterKeyBuffer=await webcrypto3.subtle.exportKey("raw",masterKeyRaw),hkdfKey=await webcrypto3.subtle.importKey("raw",masterKeyBuffer,{name:"HKDF"},!1,["deriveKey"]);return hkdfKey},([passphrase,salt])=>`${passphrase}-${uint8ArrayToHexString(salt)}`);webcrypto4=globalThis.crypto;ENCRYPT_V1_PREFIX_PROBABLY="[";ENCRYPT_V2_PREFIX="%";ENCRYPT_V3_PREFIX="%~";KeyBuffs=new Map;decKeyBuffs=new Map;KEY_RECYCLE_COUNT=100;nonceBuffer=new Uint32Array(1);webcrypto5=globalThis.crypto;keyGCCount=5*KEY_RECYCLE_COUNT;decKeyIdx=0;decKeyMin=0;__defProp2=Object.defineProperty;__getOwnPropDesc2=Object.getOwnPropertyDescriptor;__getOwnPropNames2=Object.getOwnPropertyNames;__hasOwnProp2=Object.prototype.hasOwnProperty;__copyProps2=(to,from,except,desc)=>{if(from&&"object"==typeof from||"function"==typeof from)for(let key22 of __getOwnPropNames2(from))__hasOwnProp2.call(to,key22)||key22===except||__defProp2(to,key22,{get:()=>from[key22],enumerable:!(desc=__getOwnPropDesc2(from,key22))||desc.enumerable});return to};__reExport=(target,mod,secondTarget)=>(__copyProps2(target,mod,"default"),secondTarget&&__copyProps2(secondTarget,mod,"default"));workerSource='"use strict";\n(() => {\n var __create = Object.create;\n var __defProp = Object.defineProperty;\n var __getOwnPropDesc = Object.getOwnPropertyDescriptor;\n var __getOwnPropNames = Object.getOwnPropertyNames;\n var __getProtoOf = Object.getPrototypeOf;\n var __hasOwnProp = Object.prototype.hasOwnProperty;\n var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {\n get: (a, b) => (typeof require !== "undefined" ? require : a)[b]\n }) : x)(function(x) {\n if (typeof require !== "undefined") return require.apply(this, arguments);\n throw Error(\'Dynamic require of "\' + x + \'" is not supported\');\n });\n var __copyProps = (to, from, except, desc) => {\n if (from && typeof from === "object" || typeof from === "function") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n };\n var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(\n // If the importer is in node compatibility mode or this is not an ESM\n // file that has been converted to a CommonJS file using a Babel-\n // compatible transform (i.e. "__esModule" has not been set), then set\n // "default" to the CommonJS "module.exports" for node compatibility.\n isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,\n mod\n ));\n\n // node_modules/octagonal-wheels/dist/common/logger.js\n var LOG_LEVEL_VERBOSE = 16;\n var LOG_LEVEL_INFO = 32;\n var LOG_KIND_DEBUG = 1;\n var LOG_KIND_VERBOSE = 2;\n var LOG_KIND_WARNING = 4;\n var LOG_KIND_ERROR = 8;\n var LEVEL_INFO = LOG_LEVEL_INFO;\n var defaultLoggerEnv = {\n minLogLevel: LOG_LEVEL_INFO\n };\n var defaultLogger = function defaultLogger2(message, level = LEVEL_INFO, key) {\n if (level < defaultLoggerEnv.minLogLevel) {\n return;\n }\n const now = /* @__PURE__ */ new Date();\n const timestamp = now.toLocaleString();\n const messageContent = typeof message == "string" ? message : message instanceof Error ? `${message.name}:${message.message}` : JSON.stringify(message, null, 2);\n const newMessage = `${timestamp}\t${level}\t${messageContent}`;\n if (level & LOG_KIND_DEBUG) {\n console.debug(newMessage);\n } else if (level & LOG_KIND_WARNING) {\n console.warn(newMessage);\n } else if (level & LOG_KIND_ERROR) {\n console.error(newMessage);\n } else if (level & LOG_KIND_VERBOSE) {\n console.info(newMessage);\n } else {\n console.log(newMessage);\n }\n if (message instanceof Error) {\n console.dir(message.stack);\n }\n };\n var _logger = defaultLogger;\n function Logger(message, level, key) {\n _logger(message, level, key);\n }\n\n // node_modules/octagonal-wheels/dist/binary/base64.js\n var isProposalArrayBufferBase64Available = typeof Uint8Array !== "undefined" && //@ts-ignore: Not typed in project target level\n typeof Uint8Array.prototype.toBase64 === "function" && //@ts-ignore: Not typed in project target level\n typeof Uint8Array.fromBase64 === "function";\n function base64ToArrayBufferNative(base64) {\n if (base64.length === 0)\n return new ArrayBuffer(0);\n try {\n if (typeof base64 == "string")\n return Uint8Array.fromBase64(base64).buffer;\n const bufItems = base64.map((e) => Uint8Array.fromBase64(e).buffer);\n const len = bufItems.reduce((p, c) => p + c.byteLength, 0);\n const joinedArray = new Uint8Array(len);\n let offset = 0;\n bufItems.forEach((e) => {\n joinedArray.set(new Uint8Array(e), offset);\n offset += e.byteLength;\n });\n return joinedArray.buffer;\n } catch (ex) {\n Logger("Base64 Decode error", LOG_LEVEL_VERBOSE);\n Logger(ex, LOG_LEVEL_VERBOSE);\n return new ArrayBuffer(0);\n }\n }\n function base64ToArrayBufferBrowser(base64) {\n if (typeof base64 == "string")\n return base64ToArrayBufferInternalBrowser(base64);\n const bufItems = base64.map((e) => base64ToArrayBufferInternalBrowser(e));\n const len = bufItems.reduce((p, c) => p + c.byteLength, 0);\n const joinedArray = new Uint8Array(len);\n let offset = 0;\n bufItems.forEach((e) => {\n joinedArray.set(new Uint8Array(e), offset);\n offset += e.byteLength;\n });\n return joinedArray.buffer;\n }\n var base64ToArrayBuffer = isProposalArrayBufferBase64Available ? base64ToArrayBufferNative : base64ToArrayBufferBrowser;\n function base64ToArrayBufferInternalBrowser(base64) {\n try {\n const binary_string = globalThis.atob(base64);\n const len = binary_string.length;\n const bytes = new Uint8Array(len);\n for (let i = 0; i < len; i++) {\n bytes[i] = binary_string.charCodeAt(i);\n }\n return bytes.buffer;\n } catch (ex) {\n Logger("Base64 Decode error", LOG_LEVEL_VERBOSE);\n Logger(ex, LOG_LEVEL_VERBOSE);\n return new ArrayBuffer(0);\n }\n }\n var encodeChunkSize = 3 * 5e7;\n function arrayBufferToBase64internalBrowser(buffer) {\n if (typeof FileReader === "undefined") {\n const nodeBuffer = globalThis.Buffer;\n if (nodeBuffer === void 0) {\n return Promise.reject(new TypeError("Base64 encoding requires FileReader or Buffer support"));\n }\n return Promise.resolve(nodeBuffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength).toString("base64"));\n }\n return new Promise((res, rej) => {\n const blob = new Blob([buffer], { type: "application/octet-binary" });\n const reader = new FileReader();\n reader.onload = function(evt) {\n const dataURI = evt.target?.result?.toString() || "";\n if (buffer.byteLength != 0 && (dataURI == "" || dataURI == "data:"))\n return rej(new TypeError("Could not parse the encoded string"));\n const result = dataURI.substring(dataURI.indexOf(",") + 1);\n res(result);\n };\n reader.readAsDataURL(blob);\n });\n }\n async function arrayBufferToBase64SingleBrowser(buffer) {\n const buf = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);\n if (buf.byteLength < QUANTUM)\n return btoa(String.fromCharCode.apply(null, [...buf]));\n return await arrayBufferToBase64internalBrowser(buf);\n }\n function arrayBufferToBase64SingleNative(buffer) {\n const buf = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);\n return Promise.resolve(buf.toBase64());\n }\n var arrayBufferToBase64Single = isProposalArrayBufferBase64Available ? arrayBufferToBase64SingleNative : arrayBufferToBase64SingleBrowser;\n var QUANTUM = 32768;\n var te = new TextEncoder();\n var td = new TextDecoder("utf-8", { ignoreBOM: true });\n function writeString(string) {\n if (string.length > 128) {\n const buf = te.encode(string);\n return buf;\n }\n const buffer = new Uint8Array(string.length * 4);\n const length = string.length;\n let index = 0;\n let chr = 0;\n let idx = 0;\n while (idx < length) {\n chr = string.charCodeAt(idx++);\n if (chr < 128) {\n buffer[index++] = chr;\n } else if (chr < 2048) {\n buffer[index++] = 192 | chr >>> 6;\n buffer[index++] = 128 | chr & 63;\n } else if (chr < 55296 || chr > 57343) {\n buffer[index++] = 224 | chr >>> 12;\n buffer[index++] = 128 | chr >>> 6 & 63;\n buffer[index++] = 128 | chr & 63;\n } else {\n chr = (chr - 55296 << 10 | string.charCodeAt(idx++) - 56320) + 65536;\n buffer[index++] = 240 | chr >>> 18;\n buffer[index++] = 128 | chr >>> 12 & 63;\n buffer[index++] = 128 | chr >>> 6 & 63;\n buffer[index++] = 128 | chr & 63;\n }\n }\n return buffer.slice(0, index);\n }\n function readString(buffer) {\n const length = buffer.length;\n if (length > 128)\n return td.decode(buffer);\n let index = 0;\n const end = length;\n let string = "";\n while (index < end) {\n const chunk = [];\n const cEnd = Math.min(index + QUANTUM, end);\n while (index < cEnd) {\n const chr = buffer[index++];\n if (chr < 128) {\n chunk.push(chr);\n } else if ((chr & 224) === 192) {\n chunk.push((chr & 31) << 6 | buffer[index++] & 63);\n } else if ((chr & 240) === 224) {\n chunk.push((chr & 15) << 12 | (buffer[index++] & 63) << 6 | buffer[index++] & 63);\n } else if ((chr & 248) === 240) {\n let code = (chr & 7) << 18 | (buffer[index++] & 63) << 12 | (buffer[index++] & 63) << 6 | buffer[index++] & 63;\n if (code < 65536) {\n chunk.push(code);\n } else {\n code -= 65536;\n chunk.push((code >>> 10) + 55296, (code & 1023) + 56320);\n }\n }\n }\n string += String.fromCharCode(...chunk);\n }\n return string;\n }\n\n // node_modules/octagonal-wheels/dist/collection.js\n function* range(from, to) {\n for (let i = from; i <= to; i++) {\n yield i;\n }\n return;\n }\n\n // node_modules/octagonal-wheels/dist/binary/encodedUTF16.js\n var BINARY_CHUNK_MAX = 1024 * 1024 * 30;\n var table = {};\n var revTable = {};\n [...range(192, 447)].forEach((e, i) => {\n table[i] = e;\n revTable[e] = i;\n });\n function decodeToArrayBuffer(src) {\n if (src.length == 1)\n return _decodeToArrayBuffer(src[0]);\n const bufItems = src.map((e) => _decodeToArrayBuffer(e));\n const len = bufItems.reduce((p, c) => p + c.byteLength, 0);\n const joinedArray = new Uint8Array(len);\n let offset = 0;\n bufItems.forEach((e) => {\n joinedArray.set(new Uint8Array(e), offset);\n offset += e.byteLength;\n });\n return joinedArray.buffer;\n }\n function _decodeToArrayBuffer(src) {\n const out = new Uint8Array(src.length);\n const len = src.length;\n for (let i = 0; i < len; i++) {\n const char = src.charCodeAt(i);\n if (char >= 38 && char <= 126 && char != 58) {\n out[i] = char;\n } else {\n out[i] = revTable[char];\n }\n }\n return out.buffer;\n }\n\n // node_modules/octagonal-wheels/dist/binary/hex.js\n var revMap = {};\n var numMap = {};\n for (let i = 0; i < 256; i++) {\n revMap[`00${i.toString(16)}`.slice(-2)] = i;\n numMap[i] = `00${i.toString(16)}`.slice(-2);\n }\n var isProposalArrayBufferBase64Available2 = typeof Uint8Array !== "undefined" && //@ts-ignore: Not typed in project target level\n typeof Uint8Array.prototype.toBase64 === "function" && //@ts-ignore: Not typed in project target level\n typeof Uint8Array.fromBase64 === "function";\n var hexStringToUint8Array = isProposalArrayBufferBase64Available2 ? hexStringToUint8ArrayNative : hexStringToUint8ArrayBrowser;\n function hexStringToUint8ArrayNative(src) {\n return Uint8Array.fromHex(src);\n }\n function hexStringToUint8ArrayBrowser(src) {\n const len = src.length / 2;\n const ret = new Uint8Array(len);\n for (let i = 0; i < len; i++) {\n ret[i] = revMap[src[i * 2] + src[i * 2 + 1]];\n }\n return ret;\n }\n var uint8ArrayToHexString = isProposalArrayBufferBase64Available2 ? uint8ArrayToHexStringNative : uint8ArrayToHexStringBrowser;\n function uint8ArrayToHexStringBrowser(src) {\n return [...src].map((e) => numMap[e]).join("");\n }\n function uint8ArrayToHexStringNative(src) {\n return src.toHex();\n }\n\n // node_modules/octagonal-wheels/dist/binary/index.js\n function decodeBinary(src) {\n if (src.length == 0)\n return new Uint8Array().buffer;\n if (typeof src === "string") {\n if (src[0] === "%") {\n return _decodeToArrayBuffer(src.substring(1));\n }\n } else {\n if (src[0][0] === "%") {\n const [head, ...last] = src;\n return decodeToArrayBuffer([head.substring(1), ...last]);\n }\n }\n return base64ToArrayBuffer(src);\n }\n\n // src/common/coreEnvFunctions.ts\n var compatGlobal = typeof window !== "undefined" ? window : (\n // compatibility for CLIs, tests, and other non-browser environments.\n // eslint-disable-next-line obsidianmd/no-global-this\n globalThis\n );\n var _fetch = compatGlobal.fetch.bind(compatGlobal);\n var activeDocumentWindow = compatGlobal;\n var _activeDocument = activeDocumentWindow.activeDocument ?? activeDocumentWindow.document;\n\n // src/string_and_binary/convert.ts\n async function arrayBufferToBase64Single2(buffer) {\n try {\n return await arrayBufferToBase64Single(buffer);\n } catch (ex) {\n const maybeBuffer = compatGlobal?.Buffer;\n if (typeof maybeBuffer?.from === "function") {\n const view = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);\n return maybeBuffer.from(view.buffer, view.byteOffset, view.byteLength).toString("base64");\n }\n throw ex;\n }\n }\n\n // node_modules/octagonal-wheels/dist/memory/LRUCache.js\n var LRUCache = class {\n /**\n * Creates a new instance of the LRUCache class.\n * @param maxCache The maximum number of items to cache.\n * @param maxCacheLength The maximum length of the cached values.\n * @param forwardOnly True if we only need to cache forward values.\n */\n constructor(maxCache, maxCacheLength, forwardOnly = false) {\n Object.defineProperty(this, "cache", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: /* @__PURE__ */ new Map([])\n });\n Object.defineProperty(this, "revCache", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: /* @__PURE__ */ new Map([])\n });\n Object.defineProperty(this, "maxCache", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 200\n });\n Object.defineProperty(this, "maxCachedLength", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 5e7\n });\n Object.defineProperty(this, "cachedLength", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 0\n });\n Object.defineProperty(this, "enableReversed", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: true\n });\n this.maxCache = maxCache || 200;\n this.maxCachedLength = (maxCacheLength || 1) * 1e6;\n this.enableReversed = !forwardOnly;\n Logger(`Cache initialized ${this.maxCache} / ${this.maxCachedLength}`, LOG_LEVEL_VERBOSE);\n }\n /**\n * Clears the cache.\n */\n clear() {\n this.cache.clear();\n this.revCache.clear();\n }\n /**\n * Checks if the cache contains the specified key.\n * @param key The key to check.\n * @returns A boolean indicating whether the cache contains the key.\n */\n has(key) {\n return this.cache.has(key);\n }\n /**\n * Gets the value associated with the specified key from the cache.\n * @param key The key to retrieve the value for.\n * @returns The value associated with the key, or undefined if the key is not found.\n * @remarks After calling this method, the key will be updated to recently used.\n */\n get(key) {\n const v = this.cache.get(key);\n if (v) {\n this.cache.delete(key);\n this.cache.set(key, v);\n if (this.enableReversed) {\n this.revCache.delete(v);\n this.revCache.set(v, key);\n }\n }\n return v;\n }\n /**\n * Gets the key associated with the specified value from the cache.\n * @param value The value to retrieve the key for.\n * @returns The key associated with the value, or undefined if the value is not found.\n * @remarks After calling this method, the key will be updated to recently used.\n */\n revGet(value) {\n const key = this.revCache.get(value);\n if (key) {\n this.cache.delete(key);\n this.revCache.delete(value);\n this.cache.set(key, value);\n this.revCache.set(value, key);\n }\n return key;\n }\n /**\n * Sets the value associated with the specified key in the cache.\n * @param key The key to set the value for.\n * @param value The value to set.\n */\n set(key, value) {\n this.cache.set(key, value);\n if (this.enableReversed)\n this.revCache.set(value, key);\n this.cachedLength += `${value}`.length;\n if (this.cache.size > this.maxCache || this.cachedLength > this.maxCachedLength) {\n for (const [key2, value2] of this.cache) {\n this.cache.delete(key2);\n if (this.enableReversed)\n this.revCache.delete(value2);\n this.cachedLength -= `${value2}`.length;\n if (this.cache.size <= this.maxCache && this.cachedLength <= this.maxCachedLength)\n break;\n }\n }\n }\n };\n\n // node_modules/balanced-match/dist/esm/index.js\n var balanced = (a, b, str) => {\n const ma = a instanceof RegExp ? maybeMatch(a, str) : a;\n const mb = b instanceof RegExp ? maybeMatch(b, str) : b;\n const r = ma !== null && mb != null && range2(ma, mb, str);\n return r && {\n start: r[0],\n end: r[1],\n pre: str.slice(0, r[0]),\n body: str.slice(r[0] + ma.length, r[1]),\n post: str.slice(r[1] + mb.length)\n };\n };\n var maybeMatch = (reg, str) => {\n const m = str.match(reg);\n return m ? m[0] : null;\n };\n var range2 = (a, b, str) => {\n let begs, beg, left, right = void 0, result;\n let ai = str.indexOf(a);\n let bi = str.indexOf(b, ai + 1);\n let i = ai;\n if (ai >= 0 && bi > 0) {\n if (a === b) {\n return [ai, bi];\n }\n begs = [];\n left = str.length;\n while (i >= 0 && !result) {\n if (i === ai) {\n begs.push(i);\n ai = str.indexOf(a, i + 1);\n } else if (begs.length === 1) {\n const r = begs.pop();\n if (r !== void 0)\n result = [r, bi];\n } else {\n beg = begs.pop();\n if (beg !== void 0 && beg < left) {\n left = beg;\n right = bi;\n }\n bi = str.indexOf(b, i + 1);\n }\n i = ai < bi && ai >= 0 ? ai : bi;\n }\n if (begs.length && right !== void 0) {\n result = [left, right];\n }\n }\n return result;\n };\n\n // node_modules/brace-expansion/dist/esm/index.js\n var escSlash = "\\0SLASH" + Math.random() + "\\0";\n var escOpen = "\\0OPEN" + Math.random() + "\\0";\n var escClose = "\\0CLOSE" + Math.random() + "\\0";\n var escComma = "\\0COMMA" + Math.random() + "\\0";\n var escPeriod = "\\0PERIOD" + Math.random() + "\\0";\n var escSlashPattern = new RegExp(escSlash, "g");\n var escOpenPattern = new RegExp(escOpen, "g");\n var escClosePattern = new RegExp(escClose, "g");\n var escCommaPattern = new RegExp(escComma, "g");\n var escPeriodPattern = new RegExp(escPeriod, "g");\n var slashPattern = /\\\\\\\\/g;\n var openPattern = /\\\\{/g;\n var closePattern = /\\\\}/g;\n var commaPattern = /\\\\,/g;\n var periodPattern = /\\\\\\./g;\n var EXPANSION_MAX = 1e5;\n var EXPANSION_MAX_LENGTH = 4e6;\n function numeric(str) {\n return !isNaN(str) ? parseInt(str, 10) : str.charCodeAt(0);\n }\n function escapeBraces(str) {\n return str.replace(slashPattern, escSlash).replace(openPattern, escOpen).replace(closePattern, escClose).replace(commaPattern, escComma).replace(periodPattern, escPeriod);\n }\n function unescapeBraces(str) {\n return str.replace(escSlashPattern, "\\\\").replace(escOpenPattern, "{").replace(escClosePattern, "}").replace(escCommaPattern, ",").replace(escPeriodPattern, ".");\n }\n function parseCommaParts(str) {\n if (!str) {\n return [""];\n }\n const parts = [];\n const m = balanced("{", "}", str);\n if (!m) {\n return str.split(",");\n }\n const { pre, body, post } = m;\n const p = pre.split(",");\n p[p.length - 1] += "{" + body + "}";\n const postParts = parseCommaParts(post);\n if (post.length) {\n ;\n p[p.length - 1] += postParts.shift();\n p.push.apply(p, postParts);\n }\n parts.push.apply(parts, p);\n return parts;\n }\n function expand(str, options = {}) {\n if (!str) {\n return [];\n }\n const { max = EXPANSION_MAX, maxLength = EXPANSION_MAX_LENGTH } = options;\n if (str.slice(0, 2) === "{}") {\n str = "\\\\{\\\\}" + str.slice(2);\n }\n return expand_(escapeBraces(str), max, maxLength, true).map(unescapeBraces);\n }\n function embrace(str) {\n return "{" + str + "}";\n }\n function isPadded(el) {\n return /^-?0\\d/.test(el);\n }\n function lte(i, y) {\n return i <= y;\n }\n function gte(i, y) {\n return i >= y;\n }\n function combine(acc, pre, values, max, maxLength, dropEmpties) {\n const out = [];\n let length = 0;\n for (let a = 0; a < acc.length; a++) {\n for (let v = 0; v < values.length; v++) {\n if (out.length >= max)\n return out;\n const expansion = acc[a] + pre + values[v];\n if (dropEmpties && !expansion)\n continue;\n if (length + expansion.length > maxLength)\n return out;\n out.push(expansion);\n length += expansion.length;\n }\n }\n return out;\n }\n function expandSequence(body, isAlphaSequence, max, maxLength) {\n const n = body.split(/\\.\\./);\n const N = [];\n if (n[0] === void 0 || n[1] === void 0) {\n return N;\n }\n const x = numeric(n[0]);\n const y = numeric(n[1]);\n const width = Math.max(n[0].length, n[1].length);\n let incr = n.length === 3 && n[2] !== void 0 ? Math.max(Math.abs(numeric(n[2])), 1) : 1;\n let test = lte;\n const reverse = y < x;\n if (reverse) {\n incr *= -1;\n test = gte;\n }\n const pad = n.some(isPadded);\n let length = 0;\n for (let i = x; test(i, y) && N.length < max; i += incr) {\n let c;\n if (isAlphaSequence) {\n c = String.fromCharCode(i);\n if (c === "\\\\") {\n c = "";\n }\n } else {\n c = String(i);\n if (pad) {\n const need = width - c.length;\n if (need > 0) {\n const z = new Array(need + 1).join("0");\n if (i < 0) {\n c = "-" + z + c.slice(1);\n } else {\n c = z + c;\n }\n }\n }\n }\n if (length + c.length > maxLength)\n break;\n N.push(c);\n length += c.length;\n }\n return N;\n }\n function expand_(str, max, maxLength, isTop) {\n let acc = [""];\n let dropEmpties = false;\n let firstGroup = true;\n for (; ; ) {\n const m = balanced("{", "}", str);\n if (!m) {\n return combine(acc, str, [""], max, maxLength, dropEmpties);\n }\n const pre = m.pre;\n if (/\\$$/.test(pre)) {\n acc = combine(acc, pre + "{" + m.body + "}", [""], max, maxLength, dropEmpties && !m.post.length);\n firstGroup = false;\n if (!m.post.length)\n break;\n str = m.post;\n continue;\n }\n const isNumericSequence = /^-?\\d+\\.\\.-?\\d+(?:\\.\\.-?\\d+)?$/.test(m.body);\n const isAlphaSequence = /^[a-zA-Z]\\.\\.[a-zA-Z](?:\\.\\.-?\\d+)?$/.test(m.body);\n const isSequence = isNumericSequence || isAlphaSequence;\n const isOptions = m.body.indexOf(",") >= 0;\n if (!isSequence && !isOptions) {\n if (m.post.match(/,(?!,).*\\}/)) {\n str = m.pre + "{" + m.body + escClose + m.post;\n isTop = true;\n continue;\n }\n return combine(acc, pre + "{" + m.body + "}" + m.post, [""], max, maxLength, dropEmpties);\n }\n if (firstGroup) {\n dropEmpties = isTop && !isSequence;\n firstGroup = false;\n }\n let values;\n if (isSequence) {\n values = expandSequence(m.body, isAlphaSequence, max, maxLength);\n } else {\n let n = parseCommaParts(m.body);\n if (n.length === 1 && n[0] !== void 0) {\n n = expand_(n[0], max, maxLength, false).map(embrace);\n if (n.length === 1) {\n acc = combine(acc, pre + n[0], [""], max, maxLength, dropEmpties && !m.post.length);\n if (!m.post.length)\n break;\n str = m.post;\n continue;\n }\n }\n let dropsEmpties = dropEmpties && !m.post.length && !pre;\n for (let d = 0; dropsEmpties && d < acc.length; d++) {\n if (acc[d]) {\n dropsEmpties = false;\n }\n }\n values = [];\n let valuesLength = 0;\n outer: for (let j = 0; j < n.length; j++) {\n const expanded = expand_(n[j], max, maxLength, false);\n for (let k = 0; k < expanded.length; k++) {\n const v = expanded[k];\n if (dropsEmpties && !v)\n continue;\n if (values.length >= max || valuesLength + v.length > maxLength) {\n break outer;\n }\n values.push(v);\n valuesLength += v.length;\n }\n }\n }\n acc = combine(acc, pre, values, max, maxLength, dropEmpties && !m.post.length);\n if (!m.post.length)\n break;\n str = m.post;\n }\n return acc;\n }\n\n // node_modules/minimatch/dist/esm/assert-valid-pattern.js\n var MAX_PATTERN_LENGTH = 1024 * 64;\n var assertValidPattern = (pattern) => {\n if (typeof pattern !== "string") {\n throw new TypeError("invalid pattern");\n }\n if (pattern.length > MAX_PATTERN_LENGTH) {\n throw new TypeError("pattern is too long");\n }\n };\n\n // node_modules/minimatch/dist/esm/brace-expressions.js\n var posixClasses = {\n "[:alnum:]": ["\\\\p{L}\\\\p{Nl}\\\\p{Nd}", true],\n "[:alpha:]": ["\\\\p{L}\\\\p{Nl}", true],\n "[:ascii:]": ["\\\\x00-\\\\x7f", false],\n "[:blank:]": ["\\\\p{Zs}\\\\t", true],\n "[:cntrl:]": ["\\\\p{Cc}", true],\n "[:digit:]": ["\\\\p{Nd}", true],\n "[:graph:]": ["\\\\p{Z}\\\\p{C}", true, true],\n "[:lower:]": ["\\\\p{Ll}", true],\n "[:print:]": ["\\\\p{C}", true],\n "[:punct:]": ["\\\\p{P}", true],\n "[:space:]": ["\\\\p{Z}\\\\t\\\\r\\\\n\\\\v\\\\f", true],\n "[:upper:]": ["\\\\p{Lu}", true],\n "[:word:]": ["\\\\p{L}\\\\p{Nl}\\\\p{Nd}\\\\p{Pc}", true],\n "[:xdigit:]": ["A-Fa-f0-9", false]\n };\n var braceEscape = (s) => s.replace(/[[\\]\\\\-]/g, "\\\\$&");\n var regexpEscape = (s) => s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, "\\\\$&");\n var rangesToString = (ranges) => ranges.join("");\n var parseClass = (glob, position) => {\n const pos = position;\n if (glob.charAt(pos) !== "[") {\n throw new Error("not in a brace expression");\n }\n const ranges = [];\n const negs = [];\n let i = pos + 1;\n let sawStart = false;\n let uflag = false;\n let escaping = false;\n let negate = false;\n let endPos = pos;\n let rangeStart = "";\n WHILE: while (i < glob.length) {\n const c = glob.charAt(i);\n if ((c === "!" || c === "^") && i === pos + 1) {\n negate = true;\n i++;\n continue;\n }\n if (c === "]" && sawStart && !escaping) {\n endPos = i + 1;\n break;\n }\n sawStart = true;\n if (c === "\\\\") {\n if (!escaping) {\n escaping = true;\n i++;\n continue;\n }\n }\n if (c === "[" && !escaping) {\n for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {\n if (glob.startsWith(cls, i)) {\n if (rangeStart) {\n return ["$.", false, glob.length - pos, true];\n }\n i += cls.length;\n if (neg)\n negs.push(unip);\n else\n ranges.push(unip);\n uflag = uflag || u;\n continue WHILE;\n }\n }\n }\n escaping = false;\n if (rangeStart) {\n if (c > rangeStart) {\n ranges.push(braceEscape(rangeStart) + "-" + braceEscape(c));\n } else if (c === rangeStart) {\n ranges.push(braceEscape(c));\n }\n rangeStart = "";\n i++;\n continue;\n }\n if (glob.startsWith("-]", i + 1)) {\n ranges.push(braceEscape(c + "-"));\n i += 2;\n continue;\n }\n if (glob.startsWith("-", i + 1)) {\n rangeStart = c;\n i += 2;\n continue;\n }\n ranges.push(braceEscape(c));\n i++;\n }\n if (endPos < i) {\n return ["", false, 0, false];\n }\n if (!ranges.length && !negs.length) {\n return ["$.", false, glob.length - pos, true];\n }\n if (negs.length === 0 && ranges.length === 1 && /^\\\\?.$/.test(ranges[0]) && !negate) {\n const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];\n return [regexpEscape(r), false, endPos - pos, false];\n }\n const sranges = "[" + (negate ? "^" : "") + rangesToString(ranges) + "]";\n const snegs = "[" + (negate ? "" : "^") + rangesToString(negs) + "]";\n const comb = ranges.length && negs.length ? "(" + sranges + "|" + snegs + ")" : ranges.length ? sranges : snegs;\n return [comb, uflag, endPos - pos, true];\n };\n\n // node_modules/minimatch/dist/esm/unescape.js\n var unescape = (s, { windowsPathsNoEscape = false, magicalBraces = true } = {}) => {\n if (magicalBraces) {\n return windowsPathsNoEscape ? s.replace(/\\[([^/\\\\])\\]/g, "$1") : s.replace(/((?!\\\\).|^)\\[([^/\\\\])\\]/g, "$1$2").replace(/\\\\([^/])/g, "$1");\n }\n return windowsPathsNoEscape ? s.replace(/\\[([^/\\\\{}])\\]/g, "$1") : s.replace(/((?!\\\\).|^)\\[([^/\\\\{}])\\]/g, "$1$2").replace(/\\\\([^/{}])/g, "$1");\n };\n\n // node_modules/minimatch/dist/esm/ast.js\n var _a;\n var types = /* @__PURE__ */ new Set(["!", "?", "+", "*", "@"]);\n var isExtglobType = (c) => types.has(c);\n var isExtglobAST = (c) => isExtglobType(c.type);\n var adoptionMap = /* @__PURE__ */ new Map([\n ["!", ["@"]],\n ["?", ["?", "@"]],\n ["@", ["@"]],\n ["*", ["*", "+", "?", "@"]],\n ["+", ["+", "@"]]\n ]);\n var adoptionWithSpaceMap = /* @__PURE__ */ new Map([\n ["!", ["?"]],\n ["@", ["?"]],\n ["+", ["?", "*"]]\n ]);\n var adoptionAnyMap = /* @__PURE__ */ new Map([\n ["!", ["?", "@"]],\n ["?", ["?", "@"]],\n ["@", ["?", "@"]],\n ["*", ["*", "+", "?", "@"]],\n ["+", ["+", "@", "?", "*"]]\n ]);\n var usurpMap = /* @__PURE__ */ new Map([\n ["!", /* @__PURE__ */ new Map([["!", "@"]])],\n [\n "?",\n /* @__PURE__ */ new Map([\n ["*", "*"],\n ["+", "*"]\n ])\n ],\n [\n "@",\n /* @__PURE__ */ new Map([\n ["!", "!"],\n ["?", "?"],\n ["@", "@"],\n ["*", "*"],\n ["+", "+"]\n ])\n ],\n [\n "+",\n /* @__PURE__ */ new Map([\n ["?", "*"],\n ["*", "*"]\n ])\n ]\n ]);\n var startNoTraversal = "(?!(?:^|/)\\\\.\\\\.?(?:$|/))";\n var startNoDot = "(?!\\\\.)";\n var addPatternStart = /* @__PURE__ */ new Set(["[", "."]);\n var justDots = /* @__PURE__ */ new Set(["..", "."]);\n var reSpecials = new Set("().*{}+?[]^$\\\\!");\n var regExpEscape = (s) => s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, "\\\\$&");\n var qmark = "[^/]";\n var star = qmark + "*?";\n var starNoEmpty = qmark + "+?";\n var ID = 0;\n var AST = class {\n type;\n #root;\n #hasMagic;\n #uflag = false;\n #parts = [];\n #parent;\n #parentIndex;\n #negs;\n #filledNegs = false;\n #options;\n #toString;\n // set to true if it\'s an extglob with no children\n // (which really means one child of \'\')\n #emptyExt = false;\n id = ++ID;\n get depth() {\n return (this.#parent?.depth ?? -1) + 1;\n }\n [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {\n return {\n "@@type": "AST",\n id: this.id,\n type: this.type,\n root: this.#root.id,\n parent: this.#parent?.id,\n depth: this.depth,\n partsLength: this.#parts.length,\n parts: this.#parts\n };\n }\n constructor(type, parent, options = {}) {\n this.type = type;\n if (type)\n this.#hasMagic = true;\n this.#parent = parent;\n this.#root = this.#parent ? this.#parent.#root : this;\n this.#options = this.#root === this ? options : this.#root.#options;\n this.#negs = this.#root === this ? [] : this.#root.#negs;\n if (type === "!" && !this.#root.#filledNegs)\n this.#negs.push(this);\n this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;\n }\n get hasMagic() {\n if (this.#hasMagic !== void 0)\n return this.#hasMagic;\n for (const p of this.#parts) {\n if (typeof p === "string")\n continue;\n if (p.type || p.hasMagic)\n return this.#hasMagic = true;\n }\n return this.#hasMagic;\n }\n // reconstructs the pattern\n toString() {\n return this.#toString !== void 0 ? this.#toString : !this.type ? this.#toString = this.#parts.map((p) => String(p)).join("") : this.#toString = this.type + "(" + this.#parts.map((p) => String(p)).join("|") + ")";\n }\n #fillNegs() {\n if (this !== this.#root)\n throw new Error("should only call on root");\n if (this.#filledNegs)\n return this;\n this.toString();\n this.#filledNegs = true;\n let n;\n while (n = this.#negs.pop()) {\n if (n.type !== "!")\n continue;\n let p = n;\n let pp = p.#parent;\n while (pp) {\n for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {\n for (const part of n.#parts) {\n if (typeof part === "string") {\n throw new Error("string part in extglob AST??");\n }\n part.copyIn(pp.#parts[i]);\n }\n }\n p = pp;\n pp = p.#parent;\n }\n }\n return this;\n }\n push(...parts) {\n for (const p of parts) {\n if (p === "")\n continue;\n if (typeof p !== "string" && !(p instanceof _a && p.#parent === this)) {\n throw new Error("invalid part: " + p);\n }\n this.#parts.push(p);\n }\n }\n toJSON() {\n const ret = this.type === null ? this.#parts.slice().map((p) => typeof p === "string" ? p : p.toJSON()) : [this.type, ...this.#parts.map((p) => p.toJSON())];\n if (this.isStart() && !this.type)\n ret.unshift([]);\n if (this.isEnd() && (this === this.#root || this.#root.#filledNegs && this.#parent?.type === "!")) {\n ret.push({});\n }\n return ret;\n }\n isStart() {\n if (this.#root === this)\n return true;\n if (!this.#parent?.isStart())\n return false;\n if (this.#parentIndex === 0)\n return true;\n const p = this.#parent;\n for (let i = 0; i < this.#parentIndex; i++) {\n const pp = p.#parts[i];\n if (!(pp instanceof _a && pp.type === "!")) {\n return false;\n }\n }\n return true;\n }\n isEnd() {\n if (this.#root === this)\n return true;\n if (this.#parent?.type === "!")\n return true;\n if (!this.#parent?.isEnd())\n return false;\n if (!this.type)\n return this.#parent?.isEnd();\n const pl = this.#parent ? this.#parent.#parts.length : 0;\n return this.#parentIndex === pl - 1;\n }\n copyIn(part) {\n if (typeof part === "string")\n this.push(part);\n else\n this.push(part.clone(this));\n }\n clone(parent) {\n const c = new _a(this.type, parent);\n for (const p of this.#parts) {\n c.copyIn(p);\n }\n return c;\n }\n static #parseAST(str, ast, pos, opt, extDepth) {\n const maxDepth = opt.maxExtglobRecursion ?? 2;\n let escaping = false;\n let inBrace = false;\n let braceStart = -1;\n let braceNeg = false;\n if (ast.type === null) {\n let i2 = pos;\n let acc2 = "";\n while (i2 < str.length) {\n const c = str.charAt(i2++);\n if (escaping || c === "\\\\") {\n escaping = !escaping;\n acc2 += c;\n continue;\n }\n if (inBrace) {\n if (i2 === braceStart + 1) {\n if (c === "^" || c === "!") {\n braceNeg = true;\n }\n } else if (c === "]" && !(i2 === braceStart + 2 && braceNeg)) {\n inBrace = false;\n }\n acc2 += c;\n continue;\n } else if (c === "[") {\n inBrace = true;\n braceStart = i2;\n braceNeg = false;\n acc2 += c;\n continue;\n }\n const doRecurse = !opt.noext && isExtglobType(c) && str.charAt(i2) === "(" && extDepth <= maxDepth;\n if (doRecurse) {\n ast.push(acc2);\n acc2 = "";\n const ext2 = new _a(c, ast);\n i2 = _a.#parseAST(str, ext2, i2, opt, extDepth + 1);\n ast.push(ext2);\n continue;\n }\n acc2 += c;\n }\n ast.push(acc2);\n return i2;\n }\n let i = pos + 1;\n let part = new _a(null, ast);\n const parts = [];\n let acc = "";\n while (i < str.length) {\n const c = str.charAt(i++);\n if (escaping || c === "\\\\") {\n escaping = !escaping;\n acc += c;\n continue;\n }\n if (inBrace) {\n if (i === braceStart + 1) {\n if (c === "^" || c === "!") {\n braceNeg = true;\n }\n } else if (c === "]" && !(i === braceStart + 2 && braceNeg)) {\n inBrace = false;\n }\n acc += c;\n continue;\n } else if (c === "[") {\n inBrace = true;\n braceStart = i;\n braceNeg = false;\n acc += c;\n continue;\n }\n const doRecurse = !opt.noext && isExtglobType(c) && str.charAt(i) === "(" && /* c8 ignore start - the maxDepth is sufficient here */\n (extDepth <= maxDepth || ast && ast.#canAdoptType(c));\n if (doRecurse) {\n const depthAdd = ast && ast.#canAdoptType(c) ? 0 : 1;\n part.push(acc);\n acc = "";\n const ext2 = new _a(c, part);\n part.push(ext2);\n i = _a.#parseAST(str, ext2, i, opt, extDepth + depthAdd);\n continue;\n }\n if (c === "|") {\n part.push(acc);\n acc = "";\n parts.push(part);\n part = new _a(null, ast);\n continue;\n }\n if (c === ")") {\n if (acc === "" && ast.#parts.length === 0) {\n ast.#emptyExt = true;\n }\n part.push(acc);\n acc = "";\n ast.push(...parts, part);\n return i;\n }\n acc += c;\n }\n ast.type = null;\n ast.#hasMagic = void 0;\n ast.#parts = [str.substring(pos - 1)];\n return i;\n }\n #canAdoptWithSpace(child) {\n return this.#canAdopt(child, adoptionWithSpaceMap);\n }\n #canAdopt(child, map = adoptionMap) {\n if (!child || typeof child !== "object" || child.type !== null || child.#parts.length !== 1 || this.type === null) {\n return false;\n }\n const gc = child.#parts[0];\n if (!gc || typeof gc !== "object" || gc.type === null) {\n return false;\n }\n return this.#canAdoptType(gc.type, map);\n }\n #canAdoptType(c, map = adoptionAnyMap) {\n return !!map.get(this.type)?.includes(c);\n }\n #adoptWithSpace(child, index) {\n const gc = child.#parts[0];\n const blank = new _a(null, gc, this.options);\n blank.#parts.push("");\n gc.push(blank);\n this.#adopt(child, index);\n }\n #adopt(child, index) {\n const gc = child.#parts[0];\n this.#parts.splice(index, 1, ...gc.#parts);\n for (const p of gc.#parts) {\n if (typeof p === "object")\n p.#parent = this;\n }\n this.#toString = void 0;\n }\n #canUsurpType(c) {\n const m = usurpMap.get(this.type);\n return !!m?.has(c);\n }\n #canUsurp(child) {\n if (!child || typeof child !== "object" || child.type !== null || child.#parts.length !== 1 || this.type === null || this.#parts.length !== 1) {\n return false;\n }\n const gc = child.#parts[0];\n if (!gc || typeof gc !== "object" || gc.type === null) {\n return false;\n }\n return this.#canUsurpType(gc.type);\n }\n #usurp(child) {\n const m = usurpMap.get(this.type);\n const gc = child.#parts[0];\n const nt = m?.get(gc.type);\n if (!nt)\n return false;\n this.#parts = gc.#parts;\n for (const p of this.#parts) {\n if (typeof p === "object") {\n p.#parent = this;\n }\n }\n this.type = nt;\n this.#toString = void 0;\n this.#emptyExt = false;\n }\n static fromGlob(pattern, options = {}) {\n const ast = new _a(null, void 0, options);\n _a.#parseAST(pattern, ast, 0, options, 0);\n return ast;\n }\n // returns the regular expression if there\'s magic, or the unescaped\n // string if not.\n toMMPattern() {\n if (this !== this.#root)\n return this.#root.toMMPattern();\n const glob = this.toString();\n const [re, body, hasMagic, uflag] = this.toRegExpSource();\n const anyMagic = hasMagic || this.#hasMagic || this.#options.nocase && !this.#options.nocaseMagicOnly && glob.toUpperCase() !== glob.toLowerCase();\n if (!anyMagic) {\n return body;\n }\n const flags = (this.#options.nocase ? "i" : "") + (uflag ? "u" : "");\n return Object.assign(new RegExp(`^${re}$`, flags), {\n _src: re,\n _glob: glob\n });\n }\n get options() {\n return this.#options;\n }\n // returns the string match, the regexp source, whether there\'s magic\n // in the regexp (so a regular expression is required) and whether or\n // not the uflag is needed for the regular expression (for posix classes)\n // TODO: instead of injecting the start/end at this point, just return\n // the BODY of the regexp, along with the start/end portions suitable\n // for binding the start/end in either a joined full-path makeRe context\n // (where we bind to (^|/), or a standalone matchPart context (where\n // we bind to ^, and not /). Otherwise slashes get duped!\n //\n // In part-matching mode, the start is:\n // - if not isStart: nothing\n // - if traversal possible, but not allowed: ^(?!\\.\\.?$)\n // - if dots allowed or not possible: ^\n // - if dots possible and not allowed: ^(?!\\.)\n // end is:\n // - if not isEnd(): nothing\n // - else: $\n //\n // In full-path matching mode, we put the slash at the START of the\n // pattern, so start is:\n // - if first pattern: same as part-matching mode\n // - if not isStart(): nothing\n // - if traversal possible, but not allowed: /(?!\\.\\.?(?:$|/))\n // - if dots allowed or not possible: /\n // - if dots possible and not allowed: /(?!\\.)\n // end is:\n // - if last pattern, same as part-matching mode\n // - else nothing\n //\n // Always put the (?:$|/) on negated tails, though, because that has to be\n // there to bind the end of the negated pattern portion, and it\'s easier to\n // just stick it in now rather than try to inject it later in the middle of\n // the pattern.\n //\n // We can just always return the same end, and leave it up to the caller\n // to know whether it\'s going to be used joined or in parts.\n // And, if the start is adjusted slightly, can do the same there:\n // - if not isStart: nothing\n // - if traversal possible, but not allowed: (?:/|^)(?!\\.\\.?$)\n // - if dots allowed or not possible: (?:/|^)\n // - if dots possible and not allowed: (?:/|^)(?!\\.)\n //\n // But it\'s better to have a simpler binding without a conditional, for\n // performance, so probably better to return both start options.\n //\n // Then the caller just ignores the end if it\'s not the first pattern,\n // and the start always gets applied.\n //\n // But that\'s always going to be $ if it\'s the ending pattern, or nothing,\n // so the caller can just attach $ at the end of the pattern when building.\n //\n // So the todo is:\n // - better detect what kind of start is needed\n // - return both flavors of starting pattern\n // - attach $ at the end of the pattern when creating the actual RegExp\n //\n // Ah, but wait, no, that all only applies to the root when the first pattern\n // is not an extglob. If the first pattern IS an extglob, then we need all\n // that dot prevention biz to live in the extglob portions, because eg\n // +(*|.x*) can match .xy but not .yx.\n //\n // So, return the two flavors if it\'s #root and the first child is not an\n // AST, otherwise leave it to the child AST to handle it, and there,\n // use the (?:^|/) style of start binding.\n //\n // Even simplified further:\n // - Since the start for a join is eg /(?!\\.) and the start for a part\n // is ^(?!\\.), we can just prepend (?!\\.) to the pattern (either root\n // or start or whatever) and prepend ^ or / at the Regexp construction.\n toRegExpSource(allowDot) {\n const dot = allowDot ?? !!this.#options.dot;\n if (this.#root === this) {\n this.#flatten();\n this.#fillNegs();\n }\n if (!isExtglobAST(this)) {\n const noEmpty = this.isStart() && this.isEnd() && !this.#parts.some((s) => typeof s !== "string");\n const src = this.#parts.map((p) => {\n const [re, _, hasMagic, uflag] = typeof p === "string" ? _a.#parseGlob(p, this.#hasMagic, noEmpty) : p.toRegExpSource(allowDot);\n this.#hasMagic = this.#hasMagic || hasMagic;\n this.#uflag = this.#uflag || uflag;\n return re;\n }).join("");\n let start2 = "";\n if (this.isStart()) {\n if (typeof this.#parts[0] === "string") {\n const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);\n if (!dotTravAllowed) {\n const aps = addPatternStart;\n const needNoTrav = (\n // dots are allowed, and the pattern starts with [ or .\n dot && aps.has(src.charAt(0)) || // the pattern starts with \\., and then [ or .\n src.startsWith("\\\\.") && aps.has(src.charAt(2)) || // the pattern starts with \\.\\., and then [ or .\n src.startsWith("\\\\.\\\\.") && aps.has(src.charAt(4))\n );\n const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));\n start2 = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : "";\n }\n }\n }\n let end = "";\n if (this.isEnd() && this.#root.#filledNegs && this.#parent?.type === "!") {\n end = "(?:$|\\\\/)";\n }\n const final2 = start2 + src + end;\n return [\n final2,\n unescape(src),\n this.#hasMagic = !!this.#hasMagic,\n this.#uflag\n ];\n }\n const repeated = this.type === "*" || this.type === "+";\n const start = this.type === "!" ? "(?:(?!(?:" : "(?:";\n let body = this.#partsToRegExp(dot);\n if (this.isStart() && this.isEnd() && !body && this.type !== "!") {\n const s = this.toString();\n const me = this;\n me.#parts = [s];\n me.type = null;\n me.#hasMagic = void 0;\n return [s, unescape(this.toString()), false, false];\n }\n let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot ? "" : this.#partsToRegExp(true);\n if (bodyDotAllowed === body) {\n bodyDotAllowed = "";\n }\n if (bodyDotAllowed) {\n body = `(?:${body})(?:${bodyDotAllowed})*?`;\n }\n let final = "";\n if (this.type === "!" && this.#emptyExt) {\n final = (this.isStart() && !dot ? startNoDot : "") + starNoEmpty;\n } else {\n const close = this.type === "!" ? (\n // !() must match something,but !(x) can match \'\'\n "))" + (this.isStart() && !dot && !allowDot ? startNoDot : "") + star + ")"\n ) : this.type === "@" ? ")" : this.type === "?" ? ")?" : this.type === "+" && bodyDotAllowed ? ")" : this.type === "*" && bodyDotAllowed ? `)?` : `)${this.type}`;\n final = start + body + close;\n }\n return [\n final,\n unescape(body),\n this.#hasMagic = !!this.#hasMagic,\n this.#uflag\n ];\n }\n #flatten() {\n if (!isExtglobAST(this)) {\n for (const p of this.#parts) {\n if (typeof p === "object") {\n p.#flatten();\n }\n }\n } else {\n let iterations = 0;\n let done = false;\n do {\n done = true;\n for (let i = 0; i < this.#parts.length; i++) {\n const c = this.#parts[i];\n if (typeof c === "object") {\n c.#flatten();\n if (this.#canAdopt(c)) {\n done = false;\n this.#adopt(c, i);\n } else if (this.#canAdoptWithSpace(c)) {\n done = false;\n this.#adoptWithSpace(c, i);\n } else if (this.#canUsurp(c)) {\n done = false;\n this.#usurp(c);\n }\n }\n }\n } while (!done && ++iterations < 10);\n }\n this.#toString = void 0;\n }\n #partsToRegExp(dot) {\n return this.#parts.map((p) => {\n if (typeof p === "string") {\n throw new Error("string type in extglob ast??");\n }\n const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot);\n this.#uflag = this.#uflag || uflag;\n return re;\n }).filter((p) => !(this.isStart() && this.isEnd()) || !!p).join("|");\n }\n static #parseGlob(glob, hasMagic, noEmpty = false) {\n let escaping = false;\n let re = "";\n let uflag = false;\n let inStar = false;\n for (let i = 0; i < glob.length; i++) {\n const c = glob.charAt(i);\n if (escaping) {\n escaping = false;\n re += (reSpecials.has(c) ? "\\\\" : "") + c;\n continue;\n }\n if (c === "*") {\n if (inStar)\n continue;\n inStar = true;\n re += noEmpty && /^[*]+$/.test(glob) ? starNoEmpty : star;\n hasMagic = true;\n continue;\n } else {\n inStar = false;\n }\n if (c === "\\\\") {\n if (i === glob.length - 1) {\n re += "\\\\\\\\";\n } else {\n escaping = true;\n }\n continue;\n }\n if (c === "[") {\n const [src, needUflag, consumed, magic] = parseClass(glob, i);\n if (consumed) {\n re += src;\n uflag = uflag || needUflag;\n i += consumed - 1;\n hasMagic = hasMagic || magic;\n continue;\n }\n }\n if (c === "?") {\n re += qmark;\n hasMagic = true;\n continue;\n }\n re += regExpEscape(c);\n }\n return [re, unescape(glob), !!hasMagic, uflag];\n }\n };\n _a = AST;\n\n // node_modules/minimatch/dist/esm/escape.js\n var escape = (s, { windowsPathsNoEscape = false, magicalBraces = false } = {}) => {\n if (magicalBraces) {\n return windowsPathsNoEscape ? s.replace(/[?*()[\\]{}]/g, "[$&]") : s.replace(/[?*()[\\]\\\\{}]/g, "\\\\$&");\n }\n return windowsPathsNoEscape ? s.replace(/[?*()[\\]]/g, "[$&]") : s.replace(/[?*()[\\]\\\\]/g, "\\\\$&");\n };\n\n // node_modules/minimatch/dist/esm/index.js\n var minimatch = (p, pattern, options = {}) => {\n assertValidPattern(pattern);\n if (!options.nocomment && pattern.charAt(0) === "#") {\n return false;\n }\n return new Minimatch(pattern, options).match(p);\n };\n var starDotExtRE = /^\\*+([^+@!?*[(]*)$/;\n var starDotExtTest = (ext2) => (f) => !f.startsWith(".") && f.endsWith(ext2);\n var starDotExtTestDot = (ext2) => (f) => f.endsWith(ext2);\n var starDotExtTestNocase = (ext2) => {\n ext2 = ext2.toLowerCase();\n return (f) => !f.startsWith(".") && f.toLowerCase().endsWith(ext2);\n };\n var starDotExtTestNocaseDot = (ext2) => {\n ext2 = ext2.toLowerCase();\n return (f) => f.toLowerCase().endsWith(ext2);\n };\n var starDotStarRE = /^\\*+\\.\\*+$/;\n var starDotStarTest = (f) => !f.startsWith(".") && f.includes(".");\n var starDotStarTestDot = (f) => f !== "." && f !== ".." && f.includes(".");\n var dotStarRE = /^\\.\\*+$/;\n var dotStarTest = (f) => f !== "." && f !== ".." && f.startsWith(".");\n var starRE = /^\\*+$/;\n var starTest = (f) => f.length !== 0 && !f.startsWith(".");\n var starTestDot = (f) => f.length !== 0 && f !== "." && f !== "..";\n var qmarksRE = /^\\?+([^+@!?*[(]*)?$/;\n var qmarksTestNocase = ([$0, ext2 = ""]) => {\n const noext = qmarksTestNoExt([$0]);\n if (!ext2)\n return noext;\n ext2 = ext2.toLowerCase();\n return (f) => noext(f) && f.toLowerCase().endsWith(ext2);\n };\n var qmarksTestNocaseDot = ([$0, ext2 = ""]) => {\n const noext = qmarksTestNoExtDot([$0]);\n if (!ext2)\n return noext;\n ext2 = ext2.toLowerCase();\n return (f) => noext(f) && f.toLowerCase().endsWith(ext2);\n };\n var qmarksTestDot = ([$0, ext2 = ""]) => {\n const noext = qmarksTestNoExtDot([$0]);\n return !ext2 ? noext : (f) => noext(f) && f.endsWith(ext2);\n };\n var qmarksTest = ([$0, ext2 = ""]) => {\n const noext = qmarksTestNoExt([$0]);\n return !ext2 ? noext : (f) => noext(f) && f.endsWith(ext2);\n };\n var qmarksTestNoExt = ([$0]) => {\n const len = $0.length;\n return (f) => f.length === len && !f.startsWith(".");\n };\n var qmarksTestNoExtDot = ([$0]) => {\n const len = $0.length;\n return (f) => f.length === len && f !== "." && f !== "..";\n };\n var defaultPlatform = typeof process === "object" && process ? typeof process.env === "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix";\n var path = {\n win32: { sep: "\\\\" },\n posix: { sep: "/" }\n };\n var sep = defaultPlatform === "win32" ? path.win32.sep : path.posix.sep;\n minimatch.sep = sep;\n var GLOBSTAR = /* @__PURE__ */ Symbol("globstar **");\n minimatch.GLOBSTAR = GLOBSTAR;\n var qmark2 = "[^/]";\n var star2 = qmark2 + "*?";\n var twoStarDot = "(?:(?!(?:\\\\/|^)(?:\\\\.{1,2})($|\\\\/)).)*?";\n var twoStarNoDot = "(?:(?!(?:\\\\/|^)\\\\.).)*?";\n var filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options);\n minimatch.filter = filter;\n var ext = (a, b = {}) => Object.assign({}, a, b);\n var defaults = (def) => {\n if (!def || typeof def !== "object" || !Object.keys(def).length) {\n return minimatch;\n }\n const orig = minimatch;\n const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));\n return Object.assign(m, {\n Minimatch: class Minimatch extends orig.Minimatch {\n constructor(pattern, options = {}) {\n super(pattern, ext(def, options));\n }\n static defaults(options) {\n return orig.defaults(ext(def, options)).Minimatch;\n }\n },\n AST: class AST extends orig.AST {\n /* c8 ignore start */\n constructor(type, parent, options = {}) {\n super(type, parent, ext(def, options));\n }\n /* c8 ignore stop */\n static fromGlob(pattern, options = {}) {\n return orig.AST.fromGlob(pattern, ext(def, options));\n }\n },\n unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),\n escape: (s, options = {}) => orig.escape(s, ext(def, options)),\n filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),\n defaults: (options) => orig.defaults(ext(def, options)),\n makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),\n braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),\n match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),\n sep: orig.sep,\n GLOBSTAR\n });\n };\n minimatch.defaults = defaults;\n var braceExpand = (pattern, options = {}) => {\n assertValidPattern(pattern);\n if (options.nobrace || !/\\{(?:(?!\\{).)*\\}/.test(pattern)) {\n return [pattern];\n }\n return expand(pattern, { max: options.braceExpandMax });\n };\n minimatch.braceExpand = braceExpand;\n var makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();\n minimatch.makeRe = makeRe;\n var match = (list, pattern, options = {}) => {\n const mm = new Minimatch(pattern, options);\n list = list.filter((f) => mm.match(f));\n if (mm.options.nonull && !list.length) {\n list.push(pattern);\n }\n return list;\n };\n minimatch.match = match;\n var globMagic = /[?*]|[+@!]\\(.*?\\)|\\[|\\]/;\n var regExpEscape2 = (s) => s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, "\\\\$&");\n var Minimatch = class {\n options;\n set;\n pattern;\n windowsPathsNoEscape;\n nonegate;\n negate;\n comment;\n empty;\n preserveMultipleSlashes;\n partial;\n globSet;\n globParts;\n nocase;\n isWindows;\n platform;\n windowsNoMagicRoot;\n maxGlobstarRecursion;\n regexp;\n constructor(pattern, options = {}) {\n assertValidPattern(pattern);\n options = options || {};\n this.options = options;\n this.maxGlobstarRecursion = options.maxGlobstarRecursion ?? 200;\n this.pattern = pattern;\n this.platform = options.platform || defaultPlatform;\n this.isWindows = this.platform === "win32";\n const awe = "allowWindowsEscape";\n this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || options[awe] === false;\n if (this.windowsPathsNoEscape) {\n this.pattern = this.pattern.replace(/\\\\/g, "/");\n }\n this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;\n this.regexp = null;\n this.negate = false;\n this.nonegate = !!options.nonegate;\n this.comment = false;\n this.empty = false;\n this.partial = !!options.partial;\n this.nocase = !!this.options.nocase;\n this.windowsNoMagicRoot = options.windowsNoMagicRoot !== void 0 ? options.windowsNoMagicRoot : !!(this.isWindows && this.nocase);\n this.globSet = [];\n this.globParts = [];\n this.set = [];\n this.make();\n }\n hasMagic() {\n if (this.options.magicalBraces && this.set.length > 1) {\n return true;\n }\n for (const pattern of this.set) {\n for (const part of pattern) {\n if (typeof part !== "string")\n return true;\n }\n }\n return false;\n }\n debug(..._) {\n }\n make() {\n const pattern = this.pattern;\n const options = this.options;\n if (!options.nocomment && pattern.charAt(0) === "#") {\n this.comment = true;\n return;\n }\n if (!pattern) {\n this.empty = true;\n return;\n }\n this.parseNegate();\n this.globSet = [...new Set(this.braceExpand())];\n if (options.debug) {\n this.debug = (...args) => console.error(...args);\n }\n this.debug(this.pattern, this.globSet);\n const rawGlobParts = this.globSet.map((s) => this.slashSplit(s));\n this.globParts = this.preprocess(rawGlobParts);\n this.debug(this.pattern, this.globParts);\n let set = this.globParts.map((s, _, __) => {\n if (this.isWindows && this.windowsNoMagicRoot) {\n const isUNC = s[0] === "" && s[1] === "" && (s[2] === "?" || !globMagic.test(s[2])) && !globMagic.test(s[3]);\n const isDrive = /^[a-z]:/i.test(s[0]);\n if (isUNC) {\n return [\n ...s.slice(0, 4),\n ...s.slice(4).map((ss) => this.parse(ss))\n ];\n } else if (isDrive) {\n return [s[0], ...s.slice(1).map((ss) => this.parse(ss))];\n }\n }\n return s.map((ss) => this.parse(ss));\n });\n this.debug(this.pattern, set);\n this.set = set.filter((s) => s.indexOf(false) === -1);\n if (this.isWindows) {\n for (let i = 0; i < this.set.length; i++) {\n const p = this.set[i];\n if (p[0] === "" && p[1] === "" && this.globParts[i][2] === "?" && typeof p[3] === "string" && /^[a-z]:$/i.test(p[3])) {\n p[2] = "?";\n }\n }\n }\n this.debug(this.pattern, this.set);\n }\n // various transforms to equivalent pattern sets that are\n // faster to process in a filesystem walk. The goal is to\n // eliminate what we can, and push all ** patterns as far\n // to the right as possible, even if it increases the number\n // of patterns that we have to process.\n preprocess(globParts) {\n if (this.options.noglobstar) {\n for (const partset of globParts) {\n for (let j = 0; j < partset.length; j++) {\n if (partset[j] === "**") {\n partset[j] = "*";\n }\n }\n }\n }\n const { optimizationLevel = 1 } = this.options;\n if (optimizationLevel >= 2) {\n globParts = this.firstPhasePreProcess(globParts);\n globParts = this.secondPhasePreProcess(globParts);\n } else if (optimizationLevel >= 1) {\n globParts = this.levelOneOptimize(globParts);\n } else {\n globParts = this.adjascentGlobstarOptimize(globParts);\n }\n return globParts;\n }\n // just get rid of adjascent ** portions\n adjascentGlobstarOptimize(globParts) {\n return globParts.map((parts) => {\n let gs = -1;\n while (-1 !== (gs = parts.indexOf("**", gs + 1))) {\n let i = gs;\n while (parts[i + 1] === "**") {\n i++;\n }\n if (i !== gs) {\n parts.splice(gs, i - gs);\n }\n }\n return parts;\n });\n }\n // get rid of adjascent ** and resolve .. portions\n levelOneOptimize(globParts) {\n return globParts.map((parts) => {\n parts = parts.reduce((set, part) => {\n const prev = set[set.length - 1];\n if (part === "**" && prev === "**") {\n return set;\n }\n if (part === "..") {\n if (prev && prev !== ".." && prev !== "." && prev !== "**") {\n set.pop();\n return set;\n }\n }\n set.push(part);\n return set;\n }, []);\n return parts.length === 0 ? [""] : parts;\n });\n }\n levelTwoFileOptimize(parts) {\n if (!Array.isArray(parts)) {\n parts = this.slashSplit(parts);\n }\n let didSomething = false;\n do {\n didSomething = false;\n if (!this.preserveMultipleSlashes) {\n for (let i = 1; i < parts.length - 1; i++) {\n const p = parts[i];\n if (i === 1 && p === "" && parts[0] === "")\n continue;\n if (p === "." || p === "") {\n didSomething = true;\n parts.splice(i, 1);\n i--;\n }\n }\n if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {\n didSomething = true;\n parts.pop();\n }\n }\n let dd = 0;\n while (-1 !== (dd = parts.indexOf("..", dd + 1))) {\n const p = parts[dd - 1];\n if (p && p !== "." && p !== ".." && p !== "**" && !(this.isWindows && /^[a-z]:$/i.test(p))) {\n didSomething = true;\n parts.splice(dd - 1, 2);\n dd -= 2;\n }\n }\n } while (didSomething);\n return parts.length === 0 ? [""] : parts;\n }\n // First phase: single-pattern processing\n // <pre> is 1 or more portions\n // <rest> is 1 or more portions\n // <p> is any portion other than ., .., \'\', or **\n // <e> is . or \'\'\n //\n // **/.. is *brutal* for filesystem walking performance, because\n // it effectively resets the recursive walk each time it occurs,\n // and ** cannot be reduced out by a .. pattern part like a regexp\n // or most strings (other than .., ., and \'\') can be.\n //\n // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}\n // <pre>/<e>/<rest> -> <pre>/<rest>\n // <pre>/<p>/../<rest> -> <pre>/<rest>\n // **/**/<rest> -> **/<rest>\n //\n // **/*/<rest> -> */**/<rest> <== not valid because ** doesn\'t follow\n // this WOULD be allowed if ** did follow symlinks, or * didn\'t\n firstPhasePreProcess(globParts) {\n let didSomething = false;\n do {\n didSomething = false;\n for (let parts of globParts) {\n let gs = -1;\n while (-1 !== (gs = parts.indexOf("**", gs + 1))) {\n let gss = gs;\n while (parts[gss + 1] === "**") {\n gss++;\n }\n if (gss > gs) {\n parts.splice(gs + 1, gss - gs);\n }\n let next = parts[gs + 1];\n const p = parts[gs + 2];\n const p2 = parts[gs + 3];\n if (next !== "..")\n continue;\n if (!p || p === "." || p === ".." || !p2 || p2 === "." || p2 === "..") {\n continue;\n }\n didSomething = true;\n parts.splice(gs, 1);\n const other = parts.slice(0);\n other[gs] = "**";\n globParts.push(other);\n gs--;\n }\n if (!this.preserveMultipleSlashes) {\n for (let i = 1; i < parts.length - 1; i++) {\n const p = parts[i];\n if (i === 1 && p === "" && parts[0] === "")\n continue;\n if (p === "." || p === "") {\n didSomething = true;\n parts.splice(i, 1);\n i--;\n }\n }\n if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {\n didSomething = true;\n parts.pop();\n }\n }\n let dd = 0;\n while (-1 !== (dd = parts.indexOf("..", dd + 1))) {\n const p = parts[dd - 1];\n if (p && p !== "." && p !== ".." && p !== "**") {\n didSomething = true;\n const needDot = dd === 1 && parts[dd + 1] === "**";\n const splin = needDot ? ["."] : [];\n parts.splice(dd - 1, 2, ...splin);\n if (parts.length === 0)\n parts.push("");\n dd -= 2;\n }\n }\n }\n } while (didSomething);\n return globParts;\n }\n // second phase: multi-pattern dedupes\n // {<pre>/*/<rest>,<pre>/<p>/<rest>} -> <pre>/*/<rest>\n // {<pre>/<rest>,<pre>/<rest>} -> <pre>/<rest>\n // {<pre>/**/<rest>,<pre>/<rest>} -> <pre>/**/<rest>\n //\n // {<pre>/**/<rest>,<pre>/**/<p>/<rest>} -> <pre>/**/<rest>\n // ^-- not valid because ** doens\'t follow symlinks\n secondPhasePreProcess(globParts) {\n for (let i = 0; i < globParts.length - 1; i++) {\n for (let j = i + 1; j < globParts.length; j++) {\n const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);\n if (matched) {\n globParts[i] = [];\n globParts[j] = matched;\n break;\n }\n }\n }\n return globParts.filter((gs) => gs.length);\n }\n partsMatch(a, b, emptyGSMatch = false) {\n let ai = 0;\n let bi = 0;\n let result = [];\n let which = "";\n while (ai < a.length && bi < b.length) {\n if (a[ai] === b[bi]) {\n result.push(which === "b" ? b[bi] : a[ai]);\n ai++;\n bi++;\n } else if (emptyGSMatch && a[ai] === "**" && b[bi] === a[ai + 1]) {\n result.push(a[ai]);\n ai++;\n } else if (emptyGSMatch && b[bi] === "**" && a[ai] === b[bi + 1]) {\n result.push(b[bi]);\n bi++;\n } else if (a[ai] === "*" && b[bi] && (this.options.dot || !b[bi].startsWith(".")) && b[bi] !== "**") {\n if (which === "b")\n return false;\n which = "a";\n result.push(a[ai]);\n ai++;\n bi++;\n } else if (b[bi] === "*" && a[ai] && (this.options.dot || !a[ai].startsWith(".")) && a[ai] !== "**") {\n if (which === "a")\n return false;\n which = "b";\n result.push(b[bi]);\n ai++;\n bi++;\n } else {\n return false;\n }\n }\n return a.length === b.length && result;\n }\n parseNegate() {\n if (this.nonegate)\n return;\n const pattern = this.pattern;\n let negate = false;\n let negateOffset = 0;\n for (let i = 0; i < pattern.length && pattern.charAt(i) === "!"; i++) {\n negate = !negate;\n negateOffset++;\n }\n if (negateOffset)\n this.pattern = pattern.slice(negateOffset);\n this.negate = negate;\n }\n // set partial to true to test if, for example,\n // "/a/b" matches the start of "/*/b/*/d"\n // Partial means, if you run out of file before you run\n // out of pattern, then that\'s fine, as long as all\n // the parts match.\n matchOne(file, pattern, partial = false) {\n let fileStartIndex = 0;\n let patternStartIndex = 0;\n if (this.isWindows) {\n const fileDrive = typeof file[0] === "string" && /^[a-z]:$/i.test(file[0]);\n const fileUNC = !fileDrive && file[0] === "" && file[1] === "" && file[2] === "?" && /^[a-z]:$/i.test(file[3]);\n const patternDrive = typeof pattern[0] === "string" && /^[a-z]:$/i.test(pattern[0]);\n const patternUNC = !patternDrive && pattern[0] === "" && pattern[1] === "" && pattern[2] === "?" && typeof pattern[3] === "string" && /^[a-z]:$/i.test(pattern[3]);\n const fdi = fileUNC ? 3 : fileDrive ? 0 : void 0;\n const pdi = patternUNC ? 3 : patternDrive ? 0 : void 0;\n if (typeof fdi === "number" && typeof pdi === "number") {\n const [fd, pd] = [\n file[fdi],\n pattern[pdi]\n ];\n if (fd.toLowerCase() === pd.toLowerCase()) {\n pattern[pdi] = fd;\n patternStartIndex = pdi;\n fileStartIndex = fdi;\n }\n }\n }\n const { optimizationLevel = 1 } = this.options;\n if (optimizationLevel >= 2) {\n file = this.levelTwoFileOptimize(file);\n }\n if (pattern.includes(GLOBSTAR)) {\n return this.#matchGlobstar(file, pattern, partial, fileStartIndex, patternStartIndex);\n }\n return this.#matchOne(file, pattern, partial, fileStartIndex, patternStartIndex);\n }\n #matchGlobstar(file, pattern, partial, fileIndex, patternIndex) {\n const firstgs = pattern.indexOf(GLOBSTAR, patternIndex);\n const lastgs = pattern.lastIndexOf(GLOBSTAR);\n const [head, body, tail] = partial ? [\n pattern.slice(patternIndex, firstgs),\n pattern.slice(firstgs + 1),\n []\n ] : [\n pattern.slice(patternIndex, firstgs),\n pattern.slice(firstgs + 1, lastgs),\n pattern.slice(lastgs + 1)\n ];\n if (head.length) {\n const fileHead = file.slice(fileIndex, fileIndex + head.length);\n if (!this.#matchOne(fileHead, head, partial, 0, 0)) {\n return false;\n }\n fileIndex += head.length;\n patternIndex += head.length;\n }\n let fileTailMatch = 0;\n if (tail.length) {\n if (tail.length + fileIndex > file.length)\n return false;\n let tailStart = file.length - tail.length;\n if (this.#matchOne(file, tail, partial, tailStart, 0)) {\n fileTailMatch = tail.length;\n } else {\n if (file[file.length - 1] !== "" || fileIndex + tail.length === file.length) {\n return false;\n }\n tailStart--;\n if (!this.#matchOne(file, tail, partial, tailStart, 0)) {\n return false;\n }\n fileTailMatch = tail.length + 1;\n }\n }\n if (!body.length) {\n let sawSome = !!fileTailMatch;\n for (let i2 = fileIndex; i2 < file.length - fileTailMatch; i2++) {\n const f = String(file[i2]);\n sawSome = true;\n if (f === "." || f === ".." || !this.options.dot && f.startsWith(".")) {\n return false;\n }\n }\n return partial || sawSome;\n }\n const bodySegments = [[[], 0]];\n let currentBody = bodySegments[0];\n let nonGsParts = 0;\n const nonGsPartsSums = [0];\n for (const b of body) {\n if (b === GLOBSTAR) {\n nonGsPartsSums.push(nonGsParts);\n currentBody = [[], 0];\n bodySegments.push(currentBody);\n } else {\n currentBody[0].push(b);\n nonGsParts++;\n }\n }\n let i = bodySegments.length - 1;\n const fileLength = file.length - fileTailMatch;\n for (const b of bodySegments) {\n b[1] = fileLength - (nonGsPartsSums[i--] + b[0].length);\n }\n return !!this.#matchGlobStarBodySections(file, bodySegments, fileIndex, 0, partial, 0, !!fileTailMatch);\n }\n // return false for "nope, not matching"\n // return null for "not matching, cannot keep trying"\n #matchGlobStarBodySections(file, bodySegments, fileIndex, bodyIndex, partial, globStarDepth, sawTail) {\n const bs = bodySegments[bodyIndex];\n if (!bs) {\n for (let i = fileIndex; i < file.length; i++) {\n sawTail = true;\n const f = file[i];\n if (f === "." || f === ".." || !this.options.dot && f.startsWith(".")) {\n return false;\n }\n }\n return sawTail;\n }\n const [body, after] = bs;\n while (fileIndex <= after) {\n const m = this.#matchOne(file.slice(0, fileIndex + body.length), body, partial, fileIndex, 0);\n if (m && globStarDepth < this.maxGlobstarRecursion) {\n const sub = this.#matchGlobStarBodySections(file, bodySegments, fileIndex + body.length, bodyIndex + 1, partial, globStarDepth + 1, sawTail);\n if (sub !== false) {\n return sub;\n }\n }\n const f = file[fileIndex];\n if (f === "." || f === ".." || !this.options.dot && f.startsWith(".")) {\n return false;\n }\n fileIndex++;\n }\n return partial || null;\n }\n #matchOne(file, pattern, partial, fileIndex, patternIndex) {\n let fi;\n let pi;\n let pl;\n let fl;\n for (fi = fileIndex, pi = patternIndex, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {\n this.debug("matchOne loop");\n let p = pattern[pi];\n let f = file[fi];\n this.debug(pattern, p, f);\n if (p === false || p === GLOBSTAR) {\n return false;\n }\n let hit;\n if (typeof p === "string") {\n hit = f === p;\n this.debug("string match", p, f, hit);\n } else {\n hit = p.test(f);\n this.debug("pattern match", p, f, hit);\n }\n if (!hit)\n return false;\n }\n if (fi === fl && pi === pl) {\n return true;\n } else if (fi === fl) {\n return partial;\n } else if (pi === pl) {\n return fi === fl - 1 && file[fi] === "";\n } else {\n throw new Error("wtf?");\n }\n }\n braceExpand() {\n return braceExpand(this.pattern, this.options);\n }\n parse(pattern) {\n assertValidPattern(pattern);\n const options = this.options;\n if (pattern === "**")\n return GLOBSTAR;\n if (pattern === "")\n return "";\n let m;\n let fastTest = null;\n if (m = pattern.match(starRE)) {\n fastTest = options.dot ? starTestDot : starTest;\n } else if (m = pattern.match(starDotExtRE)) {\n fastTest = (options.nocase ? options.dot ? starDotExtTestNocaseDot : starDotExtTestNocase : options.dot ? starDotExtTestDot : starDotExtTest)(m[1]);\n } else if (m = pattern.match(qmarksRE)) {\n fastTest = (options.nocase ? options.dot ? qmarksTestNocaseDot : qmarksTestNocase : options.dot ? qmarksTestDot : qmarksTest)(m);\n } else if (m = pattern.match(starDotStarRE)) {\n fastTest = options.dot ? starDotStarTestDot : starDotStarTest;\n } else if (m = pattern.match(dotStarRE)) {\n fastTest = dotStarTest;\n }\n const re = AST.fromGlob(pattern, this.options).toMMPattern();\n if (fastTest && typeof re === "object") {\n Reflect.defineProperty(re, "test", { value: fastTest });\n }\n return re;\n }\n makeRe() {\n if (this.regexp || this.regexp === false)\n return this.regexp;\n const set = this.set;\n if (!set.length) {\n this.regexp = false;\n return this.regexp;\n }\n const options = this.options;\n const twoStar = options.noglobstar ? star2 : options.dot ? twoStarDot : twoStarNoDot;\n const flags = new Set(options.nocase ? ["i"] : []);\n let re = set.map((pattern) => {\n const pp = pattern.map((p) => {\n if (p instanceof RegExp) {\n for (const f of p.flags.split(""))\n flags.add(f);\n }\n return typeof p === "string" ? regExpEscape2(p) : p === GLOBSTAR ? GLOBSTAR : p._src;\n });\n pp.forEach((p, i) => {\n const next = pp[i + 1];\n const prev = pp[i - 1];\n if (p !== GLOBSTAR || prev === GLOBSTAR) {\n return;\n }\n if (prev === void 0) {\n if (next !== void 0 && next !== GLOBSTAR) {\n pp[i + 1] = "(?:\\\\/|" + twoStar + "\\\\/)?" + next;\n } else {\n pp[i] = twoStar;\n }\n } else if (next === void 0) {\n pp[i - 1] = prev + "(?:\\\\/|\\\\/" + twoStar + ")?";\n } else if (next !== GLOBSTAR) {\n pp[i - 1] = prev + "(?:\\\\/|\\\\/" + twoStar + "\\\\/)" + next;\n pp[i + 1] = GLOBSTAR;\n }\n });\n const filtered = pp.filter((p) => p !== GLOBSTAR);\n if (this.partial && filtered.length >= 1) {\n const prefixes = [];\n for (let i = 1; i <= filtered.length; i++) {\n prefixes.push(filtered.slice(0, i).join("/"));\n }\n return "(?:" + prefixes.join("|") + ")";\n }\n return filtered.join("/");\n }).join("|");\n const [open, close] = set.length > 1 ? ["(?:", ")"] : ["", ""];\n re = "^" + open + re + close + "$";\n if (this.partial) {\n re = "^(?:\\\\/|" + open + re.slice(1, -1) + close + ")$";\n }\n if (this.negate)\n re = "^(?!" + re + ").+$";\n try {\n this.regexp = new RegExp(re, [...flags].join(""));\n } catch {\n this.regexp = false;\n }\n return this.regexp;\n }\n slashSplit(p) {\n if (this.preserveMultipleSlashes) {\n return p.split("/");\n } else if (this.isWindows && /^\\/\\/[^/]+/.test(p)) {\n return ["", ...p.split(/\\/+/)];\n } else {\n return p.split(/\\/+/);\n }\n }\n match(f, partial = this.partial) {\n this.debug("match", f, this.pattern);\n if (this.comment) {\n return false;\n }\n if (this.empty) {\n return f === "";\n }\n if (f === "/" && partial) {\n return true;\n }\n const options = this.options;\n if (this.isWindows) {\n f = f.split("\\\\").join("/");\n }\n const ff = this.slashSplit(f);\n this.debug(this.pattern, "split", ff);\n const set = this.set;\n this.debug(this.pattern, "set", set);\n let filename = ff[ff.length - 1];\n if (!filename) {\n for (let i = ff.length - 2; !filename && i >= 0; i--) {\n filename = ff[i];\n }\n }\n for (const pattern of set) {\n let file = ff;\n if (options.matchBase && pattern.length === 1) {\n file = [filename];\n }\n const hit = this.matchOne(file, pattern, partial);\n if (hit) {\n if (options.flipNegate) {\n return true;\n }\n return !this.negate;\n }\n }\n if (options.flipNegate) {\n return false;\n }\n return this.negate;\n }\n static defaults(def) {\n return minimatch.defaults(def).Minimatch;\n }\n };\n minimatch.AST = AST;\n minimatch.Minimatch = Minimatch;\n minimatch.escape = escape;\n minimatch.unescape = unescape;\n\n // src/mods.ts\n var webcrypto;\n async function getWebCrypto() {\n if (webcrypto) {\n return webcrypto;\n }\n if (compatGlobal.crypto) {\n webcrypto = compatGlobal.crypto;\n return webcrypto;\n } else {\n const module = await import("crypto");\n webcrypto = module.webcrypto;\n return webcrypto;\n }\n }\n\n // src/common/models/db.const.ts\n var EntryTypes = {\n NOTE_LEGACY: "notes",\n NOTE_BINARY: "newnote",\n NOTE_PLAIN: "plain",\n INTERNAL_FILE: "internalfile",\n CHUNK: "leaf",\n CHUNK_PACK: "chunkpack",\n VERSION_INFO: "versioninfo",\n SYNC_INFO: "syncinfo",\n SYNC_PARAMETERS: "sync-parameters",\n MILESTONE_INFO: "milestoneinfo",\n NODE_INFO: "nodeinfo"\n };\n var NoteTypes = [EntryTypes.NOTE_LEGACY, EntryTypes.NOTE_BINARY, EntryTypes.NOTE_PLAIN];\n var ChunkTypes = [EntryTypes.CHUNK, EntryTypes.CHUNK_PACK];\n\n // src/common/models/setting.const.ts\n var SETTING_VERSION_SUPPORT_CASE_INSENSITIVE = 10;\n var CURRENT_SETTING_VERSION = SETTING_VERSION_SUPPORT_CASE_INSENSITIVE;\n var RemoteTypes = {\n REMOTE_COUCHDB: "",\n REMOTE_MINIO: "MINIO",\n REMOTE_P2P: "ONLY_P2P"\n };\n var REMOTE_COUCHDB = RemoteTypes.REMOTE_COUCHDB;\n var REMOTE_MINIO = RemoteTypes.REMOTE_MINIO;\n var REMOTE_P2P = RemoteTypes.REMOTE_P2P;\n var P2PConnectionPaths = {\n Automatic: "automatic",\n Relay: "relay"\n };\n var P2PMessageSizePresets = {\n Standard: 15360,\n Reduced: 2048,\n Conservative: 1024,\n MaximumCompatibility: 800\n };\n var E2EEAlgorithms = {\n V1: "",\n V2: "v2",\n ForceV1: "forceV1"\n };\n var ChunkAlgorithms = {\n V1: "v1",\n V2: "v2",\n V2Segmenter: "v2-segmenter",\n RabinKarp: "v3-rabin-karp"\n };\n\n // src/common/models/setting.const.preferred.ts\n var PREFERRED_BASE = {\n syncMaxSizeInMB: 50,\n chunkSplitterVersion: "v3-rabin-karp",\n usePluginSyncV2: true,\n handleFilenameCaseSensitive: false,\n E2EEAlgorithm: E2EEAlgorithms.V2\n };\n var PREFERRED_SETTING_CLOUDANT = {\n ...PREFERRED_BASE,\n customChunkSize: 0,\n sendChunksBulkMaxSize: 1,\n concurrencyOfReadChunksOnline: 100,\n minimumIntervalOfReadChunksOnline: 333\n };\n var PREFERRED_SETTING_SELF_HOSTED = {\n ...PREFERRED_BASE,\n customChunkSize: 60,\n sendChunksBulkMaxSize: 1,\n concurrencyOfReadChunksOnline: 30,\n minimumIntervalOfReadChunksOnline: 25\n };\n var PREFERRED_JOURNAL_SYNC = {\n ...PREFERRED_BASE,\n customChunkSize: 10,\n concurrencyOfReadChunksOnline: 30,\n minimumIntervalOfReadChunksOnline: 25\n };\n\n // src/common/models/setting.const.defaults.ts\n var P2P_DEFAULT_SETTINGS = {\n P2P_Enabled: false,\n P2P_AutoAccepting: 0 /* NONE */,\n P2P_AppID: "self-hosted-livesync",\n P2P_roomID: "",\n P2P_passphrase: "",\n P2P_relays: "wss://exp-relay.vrtmrz.net/",\n P2P_AutoBroadcast: false,\n P2P_AutoStart: false,\n P2P_AutoSyncPeers: "",\n P2P_AutoWatchPeers: "",\n P2P_SyncOnReplication: "",\n P2P_RebuildFrom: "",\n P2P_AutoAcceptingPeers: "",\n P2P_AutoDenyingPeers: "",\n P2P_IsHeadless: false,\n P2P_DevicePeerName: "",\n P2P_turnServers: "",\n P2P_turnUsername: "",\n P2P_turnCredential: "",\n P2P_maxWirePayloadBytes: P2PMessageSizePresets.Standard,\n P2P_connectionPath: P2PConnectionPaths.Automatic,\n P2P_useDiagRTC: false\n };\n var SETTINGS_SCHEMA_DEFAULTS = {\n remoteType: REMOTE_COUCHDB,\n useCustomRequestHandler: false,\n couchDB_URI: "",\n couchDB_USER: "",\n couchDB_PASSWORD: "",\n couchDB_DBNAME: "",\n liveSync: false,\n syncOnSave: false,\n syncOnStart: false,\n savingDelay: 200,\n lessInformationInLog: false,\n gcDelay: 300,\n versionUpFlash: "",\n minimumChunkSize: 20,\n longLineThreshold: 250,\n showVerboseLog: false,\n suspendFileWatching: false,\n trashInsteadDelete: true,\n periodicReplication: false,\n periodicReplicationInterval: 60,\n syncOnFileOpen: false,\n encrypt: false,\n passphrase: "",\n usePathObfuscation: false,\n doNotDeleteFolder: false,\n resolveConflictsByNewerFile: false,\n batchSave: false,\n batchSaveMinimumDelay: 5,\n batchSaveMaximumDelay: 60,\n deviceAndVaultName: "",\n usePluginSettings: false,\n showOwnPlugins: false,\n showStatusOnEditor: true,\n showStatusOnStatusbar: true,\n showOnlyIconsOnEditor: false,\n hideFileWarningNotice: false,\n networkWarningStyle: "",\n usePluginSync: false,\n autoSweepPlugins: false,\n autoSweepPluginsPeriodic: false,\n notifyPluginOrSettingUpdated: false,\n checkIntegrityOnSave: false,\n batch_size: 25,\n batches_limit: 25,\n useHistory: false,\n disableRequestURI: false,\n skipOlderFilesOnSync: true,\n checkConflictOnlyOnOpen: false,\n showMergeDialogOnlyOnActive: false,\n syncInternalFiles: false,\n syncInternalFilesBeforeReplication: false,\n syncInternalFilesIgnorePatterns: "\\\\/node_modules\\\\/, \\\\/\\\\.git\\\\/, \\\\/obsidian-livesync\\\\/",\n syncInternalFilesTargetPatterns: "",\n syncInternalFilesInterval: 60,\n additionalSuffixOfDatabaseName: "",\n ignoreVersionCheck: false,\n lastReadUpdates: 0,\n deleteMetadataOfDeletedFiles: false,\n syncIgnoreRegEx: "",\n syncOnlyRegEx: "",\n customChunkSize: 0,\n readChunksOnline: true,\n watchInternalFileChanges: true,\n automaticallyDeleteMetadataOfDeletedFiles: 0,\n disableMarkdownAutoMerge: false,\n writeDocumentsIfConflicted: false,\n useDynamicIterationCount: false,\n syncAfterMerge: false,\n configPassphraseStore: "",\n encryptedPassphrase: "",\n encryptedCouchDBConnection: "",\n permitEmptyPassphrase: false,\n remoteConfigurations: {},\n activeConfigurationId: "",\n P2P_ActiveRemoteConfigurationId: "",\n useIndexedDBAdapter: false,\n useTimeouts: false,\n writeLogToTheFile: false,\n doNotPaceReplication: false,\n hashCacheMaxCount: 300,\n hashCacheMaxAmount: 50,\n concurrencyOfReadChunksOnline: 40,\n minimumIntervalOfReadChunksOnline: 50,\n hashAlg: "xxhash64",\n suspendParseReplicationResult: false,\n doNotSuspendOnFetching: false,\n useIgnoreFiles: false,\n ignoreFiles: ".gitignore",\n syncOnEditorSave: false,\n keepReplicationActiveInBackground: false,\n allowSleepDuringSynchronisation: false,\n allowSleepDuringSynchronisationOnDesktop: true,\n pluginSyncExtendedSetting: {},\n syncMaxSizeInMB: 50,\n settingSyncFile: "",\n writeCredentialsForSettingSync: false,\n notifyAllSettingSyncFile: false,\n isConfigured: void 0,\n settingVersion: CURRENT_SETTING_VERSION,\n enableCompression: false,\n accessKey: "",\n bucket: "",\n endpoint: "",\n region: "auto",\n secretKey: "",\n useEden: false,\n maxChunksInEden: 10,\n maxTotalLengthInEden: 1024,\n maxAgeInEden: 10,\n disableCheckingConfigMismatch: false,\n autoAcceptCompatibleTweak: void 0,\n displayLanguage: "",\n /**\n * @deprecated\n */\n enableChunkSplitterV2: false,\n disableWorkerForGeneratingChunks: false,\n processSmallFilesInUIThread: false,\n notifyThresholdOfRemoteStorageSize: -1,\n usePluginSyncV2: false,\n usePluginEtc: false,\n handleFilenameCaseSensitive: void 0,\n doNotUseFixedRevisionForChunks: true,\n showLongerLogInsideEditor: false,\n /** @deprecated Retained for settings and Setup URI compatibility. */\n sendChunksBulk: false,\n sendChunksBulkMaxSize: 1,\n /**\n * @deprecated\n * This setting is no longer used and will be removed in the future.\n */\n useSegmenter: false,\n useAdvancedMode: false,\n usePowerUserMode: false,\n useEdgeCaseMode: false,\n enableDebugTools: false,\n suppressNotifyHiddenFilesChange: false,\n syncMinimumInterval: 2e3,\n ...P2P_DEFAULT_SETTINGS,\n doctorProcessedVersion: "",\n bucketCustomHeaders: "",\n couchDB_CustomHeaders: "",\n useJWT: false,\n jwtAlgorithm: "",\n jwtKey: "",\n jwtKid: "",\n jwtSub: "",\n jwtExpDuration: 5,\n useRequestAPI: false,\n bucketPrefix: "",\n chunkSplitterVersion: ChunkAlgorithms.RabinKarp,\n E2EEAlgorithm: E2EEAlgorithms.V2,\n processSizeMismatchedFiles: false,\n forcePathStyle: true,\n syncInternalFileOverwritePatterns: "",\n useOnlyLocalChunk: false,\n maxMTimeForReflectEvents: 0,\n tweakModified: void 0\n };\n var NEW_VAULT_SETTINGS = {\n ...SETTINGS_SCHEMA_DEFAULTS,\n ...PREFERRED_BASE,\n remoteConfigurations: {},\n pluginSyncExtendedSetting: {}\n };\n var DEFAULT_SETTINGS = SETTINGS_SCHEMA_DEFAULTS;\n\n // src/common/models/sync.definition.ts\n var ProtocolVersions = {\n UNSET: void 0,\n LEGACY: 1,\n ADVANCED_E2EE: 2\n };\n var DOCID_SYNC_PARAMETERS = "_local/obsidian_livesync_sync_parameters";\n var DEFAULT_SYNC_PARAMETERS = {\n _id: DOCID_SYNC_PARAMETERS,\n type: EntryTypes["SYNC_PARAMETERS"],\n protocolVersion: ProtocolVersions.ADVANCED_E2EE,\n pbkdf2salt: ""\n };\n\n // src/common/models/tweak.definition.ts\n var TweakValuesShouldMatchedTemplate = {\n minimumChunkSize: 20,\n longLineThreshold: 250,\n encrypt: false,\n usePathObfuscation: false,\n enableCompression: false,\n useEden: false,\n customChunkSize: 0,\n useDynamicIterationCount: false,\n hashAlg: "xxhash64",\n enableChunkSplitterV2: false,\n maxChunksInEden: 10,\n maxTotalLengthInEden: 1024,\n maxAgeInEden: 10,\n usePluginSyncV2: false,\n handleFilenameCaseSensitive: false,\n useSegmenter: false,\n E2EEAlgorithm: E2EEAlgorithms.V2,\n chunkSplitterVersion: ChunkAlgorithms.RabinKarp\n };\n var TweakValuesRecommendedTemplate = {\n useIgnoreFiles: false,\n useCustomRequestHandler: false,\n batch_size: 25,\n batches_limit: 25,\n // useIndexedDBAdapter: false,\n useTimeouts: false,\n readChunksOnline: true,\n hashCacheMaxCount: 300,\n hashCacheMaxAmount: 50,\n concurrencyOfReadChunksOnline: 40,\n minimumIntervalOfReadChunksOnline: 50,\n ignoreFiles: ".gitignore",\n syncMaxSizeInMB: 50,\n enableChunkSplitterV2: false,\n usePluginSyncV2: true,\n handleFilenameCaseSensitive: false,\n E2EEAlgorithm: E2EEAlgorithms.V2,\n chunkSplitterVersion: ChunkAlgorithms.RabinKarp\n };\n var TweakValuesDefault = {\n usePluginSyncV2: false,\n E2EEAlgorithm: DEFAULT_SETTINGS.E2EEAlgorithm,\n chunkSplitterVersion: DEFAULT_SETTINGS.chunkSplitterVersion,\n tweakModified: DEFAULT_SETTINGS.tweakModified\n };\n var TweakValuesTemplate = {\n ...TweakValuesRecommendedTemplate,\n ...TweakValuesShouldMatchedTemplate,\n tweakModified: 0\n };\n\n // src/common/models/redflag.const.ts\n var FlagFilesOriginal = {\n SUSPEND_ALL: "redflag.md",\n REBUILD_ALL: "redflag2.md",\n FETCH_ALL: "redflag3.md"\n };\n var FlagFilesHumanReadable = {\n REBUILD_ALL: "flag_rebuild.md",\n FETCH_ALL: "flag_fetch.md"\n };\n var FLAGMD_REDFLAG = FlagFilesOriginal.SUSPEND_ALL;\n var FLAGMD_REDFLAG2 = FlagFilesOriginal.REBUILD_ALL;\n var FLAGMD_REDFLAG2_HR = FlagFilesHumanReadable.REBUILD_ALL;\n var FLAGMD_REDFLAG3 = FlagFilesOriginal.FETCH_ALL;\n var FLAGMD_REDFLAG3_HR = FlagFilesHumanReadable.FETCH_ALL;\n\n // src/common/models/shared.definition.ts\n var DatabaseConnectingStatuses = {\n STARTED: "STARTED",\n NOT_CONNECTED: "NOT_CONNECTED",\n PAUSED: "PAUSED",\n CONNECTED: "CONNECTED",\n COMPLETED: "COMPLETED",\n CLOSED: "CLOSED",\n ERRORED: "ERRORED",\n JOURNAL_SEND: "JOURNAL_SEND",\n JOURNAL_RECEIVE: "JOURNAL_RECEIVE"\n };\n var DEFAULT_REPLICATION_STATICS = {\n sent: 0,\n arrived: 0,\n maxPullSeq: 0,\n maxPushSeq: 0,\n lastSyncPullSeq: 0,\n lastSyncPushSeq: 0,\n syncStatus: DatabaseConnectingStatuses.CLOSED\n };\n\n // src/string_and_binary/path.ts\n var _hashString = memorizeFuncWithLRUCache(async (key) => {\n const buff = writeString(key);\n const webcrypto7 = await getWebCrypto();\n const digest = await webcrypto7.subtle.digest("SHA-256", buff);\n return uint8ArrayToHexString(new Uint8Array(digest));\n });\n\n // node_modules/octagonal-wheels/dist/promises.js\n function polyfillPromiseWithResolvers() {\n let resolve;\n let reject;\n const promise = new Promise((res, rej) => {\n resolve = res;\n reject = rej;\n });\n return { promise, resolve, reject };\n }\n function nativePromiseWithResolvers() {\n const p = Promise.withResolvers();\n const { promise, resolve, reject } = p;\n return { promise, resolve, reject };\n }\n var polyfilledFunc = "withResolvers" in Promise ? nativePromiseWithResolvers : polyfillPromiseWithResolvers;\n var promiseWithResolvers = polyfilledFunc;\n var noop = () => {\n };\n function fireAndForget(p) {\n if (typeof p == "function")\n return fireAndForget(p());\n p.then(noop).catch(noop);\n }\n function yieldMicrotask() {\n return new Promise((res) => queueMicrotask(res));\n }\n var TIMED_OUT_SIGNAL = /* @__PURE__ */ Symbol("timed out");\n function cancelableDelay(timeout, cancel = TIMED_OUT_SIGNAL) {\n let timer = void 0;\n const promise = promiseWithResolvers();\n timer = setTimeout(() => {\n timer = void 0;\n promise.resolve(cancel);\n }, timeout);\n return {\n promise: promise.promise,\n cancel() {\n if (timer) {\n clearTimeout(timer);\n timer = void 0;\n }\n }\n };\n }\n\n // node_modules/octagonal-wheels/dist/concurrency/semaphore_v2.js\n function Semaphore(limit) {\n let counter = 0;\n const _limit = limit;\n const queue = [];\n const semaphore = {\n get waiting() {\n return queue.length;\n },\n async tryAcquire(quantity = 1, timeout) {\n if (counter < _limit) {\n counter += quantity;\n return () => {\n this.release(quantity);\n };\n }\n const d = cancelableDelay(timeout, TIMED_OUT_SIGNAL);\n const aq = this.acquire(quantity);\n const p = await Promise.race([d.promise, aq]);\n if (p === TIMED_OUT_SIGNAL) {\n fireAndForget(() => aq.then((release) => release()));\n return false;\n }\n return p;\n },\n async acquire(quantity = 1) {\n if (counter < _limit) {\n counter += quantity;\n return () => this.release();\n }\n const n = promiseWithResolvers();\n queue.push(n);\n await n.promise;\n return () => {\n this.release(quantity);\n };\n },\n release(quantity = 1) {\n if (queue.length > 0) {\n const next = queue.shift();\n if (next) {\n fireAndForget(async () => await yieldMicrotask().then(() => next.resolve()));\n }\n } else {\n if (counter > 0) {\n counter -= quantity;\n }\n }\n }\n };\n return semaphore;\n }\n\n // node_modules/octagonal-wheels/dist/encoding/encodeobject.js\n var prefixMapObject = {\n s: {\n 1: "V",\n 2: "W",\n 3: "X",\n 4: "Y",\n 5: "Z"\n },\n o: {\n 1: "v",\n 2: "w",\n 3: "x",\n 4: "y",\n 5: "z"\n }\n };\n var decodePrefixMapObject = Object.fromEntries(Object.entries(prefixMapObject).flatMap(([prefix, map]) => Object.entries(map).map(([len, char]) => [char, { prefix, len: parseInt(len) }])));\n var prefixMapNumber = {\n n: {\n 1: "a",\n 2: "b",\n 3: "c",\n 4: "d",\n 5: "e"\n },\n N: {\n 1: "A",\n 2: "B",\n 3: "C",\n 4: "D",\n 5: "E"\n }\n };\n var decodePrefixMapNumber = Object.fromEntries(Object.entries(prefixMapNumber).flatMap(([prefix, map]) => Object.entries(map).map(([len, char]) => [char, { prefix, len: parseInt(len) }])));\n\n // node_modules/octagonal-wheels/dist/bureau/SlipBoard.js\n var SlipBoard = class {\n constructor() {\n Object.defineProperty(this, "_clip", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: /* @__PURE__ */ new Map()\n });\n }\n /**\n * Checks if a specific key is awaiting.\n *\n * @template ET - The type of the events.\n * @template K - The key of the event in the events type.\n * @param {SlipType<ET, K>} type - The key representing the event type.\n * @param {string} key - The key representing the specific sub-event.\n * @returns {boolean} - Returns `true` if the event and sub-event combination is awaiting, otherwise `false`.\n */\n isAwaiting(type, key) {\n return this._clip.has(`${String(type)}:${key}`);\n }\n /**\n * Issues a slip of process and proceeds with the provided options.\n *\n * @template T - The type of the result expected from the process.\n * @param {string} type - The type of the process to be issued.\n * @param {string} [key=""] - An optional key to identify the process.\n * @param {SlipProcessOptions<T>} opt - The options for the process, including the callback to be executed.\n * @returns {Promise<T>} - A promise that resolves with the result of the process.\n *\n * @remarks\n * - If the process is not already awaiting, it will be issued and the callback will be executed.\n * - If the callback succeeds, the result will be submitted.\n * - If the callback fails, the error handling depends on the options provided:\n * - If `submitAsSuccess` is true, the error (or transformed error) will be submitted as a success.\n * - If `dropSlipWithRisks` is true, the process will be deleted from the clip.\n * - Otherwise, the error will be rejected.\n * - The method returns a promise that resolves with the next result of the process.\n */\n issueAndProceed(type, key = "", opt) {\n if (!this.isAwaiting(type, key)) {\n fireAndForget(async () => {\n try {\n const ret = await opt.callback();\n this.submit(type, key, ret);\n } catch (ex) {\n if (opt.submitAsSuccess) {\n this.submit(type, key, opt.transformError ? opt.transformError(ex) : ex);\n } else {\n if (opt.dropSlipWithRisks) {\n this._clip.delete(type);\n } else {\n this.reject(type, key, ex);\n }\n }\n }\n });\n }\n return this.awaitNext(type, key);\n }\n /**\n * Waits for the next event of the specified type and key, with an optional timeout.\n *\n * @template ET - The type of the events.\n * @template K - The key of the event type.\n * @param {SlipType<ET, K>} type - The type of the event to wait for.\n * @param {string} [key=""] - The key associated with the event.\n * @param {number} [timeout] - The optional timeout in milliseconds.\n * @returns {Promise<void | ET[K] | TIMED_OUT_SIGNAL>} A promise that resolves with the event data,\n * resolves with `TIMED_OUT_SIGNAL` if the timeout is reached, or resolves to void if no event is found.\n */\n async awaitNext(type, key = "", { timeout, onNotAwaited } = { timeout: void 0, onNotAwaited: void 0 }) {\n let taskPromise = this._clip.get(`${String(type)}:${key}`);\n if (!taskPromise) {\n taskPromise = promiseWithResolvers();\n taskPromise.promise = taskPromise.promise.then((ret) => {\n return ret;\n }).finally(() => {\n this._clip.delete(`${String(type)}:${key}`);\n });\n this._clip.set(`${String(type)}:${key}`, taskPromise);\n if (onNotAwaited) {\n fireAndForget(async () => (await yieldMicrotask(), onNotAwaited()));\n }\n }\n if (timeout) {\n const cDelay = cancelableDelay(timeout);\n return Promise.race([\n cDelay.promise,\n taskPromise.promise.then((ret) => ret).finally(() => cDelay.cancel())\n ]);\n }\n return await taskPromise.promise;\n }\n /**\n * Submits an event of a specified type with optional data.\n *\n * @template ET - The type of events.\n * @template K - The key of the event type in ET.\n * @param {SlipType<ET, K>} type - The type of the event to submit.\n * @param {string} [key=""] - An optional key associated with the event.\n * @param {SlipDataType<ET, K>} [data] - Optional data to be passed with the event.\n * @returns {void}\n */\n submit(type, key, data) {\n const taskPromise = this._clip.get(`${String(type)}:${key}`);\n if (taskPromise) {\n taskPromise.resolve(data);\n }\n }\n /**\n * Submits an event of a specified type to all listeners.\n *\n * @template ET - The type of events.\n * @template K - The key of the event type in ET.\n * @param {SlipType<ET, K>} type - The type of the event to submit.\n * @param {string} prefix - The prefix to match the keys of the listeners.\n * @param {SlipDataType<ET, K>} [data] - Optional data to be passed with the event.\n * @returns {void}\n */\n submitToAll(type, prefix, data) {\n for (const [key, taskPromise] of this._clip.entries()) {\n if (`${String(key)}`.startsWith(`${String(type)}:${prefix}`)) {\n taskPromise.resolve(data);\n }\n }\n }\n /**\n * Rejects a task promise associated with a specific event type and key.\n *\n * @template ET - The type of events.\n * @template K - The keys of the events.\n * @param {SlipType<ET, K>} type - The type of the event.\n * @param {string} [key=""] - The key associated with the event. Defaults to an empty string.\n * @param {any} reason - The reason for rejecting the promise.\n */\n reject(type, key = "", reason) {\n const taskPromise = this._clip.get(`${String(type)}:${key}`);\n if (taskPromise) {\n taskPromise.reject(reason);\n }\n }\n };\n var globalSlipBoard = new SlipBoard();\n\n // src/common/utils.patch.ts\n var MARK_OPERATOR = ``;\n var MARK_DELETED = `${MARK_OPERATOR}__DELETED`;\n var MARK_ISARRAY = `${MARK_OPERATOR}__ARRAY`;\n var MARK_SWAPPED = `${MARK_OPERATOR}__SWAP`;\n\n // src/common/utils.ts\n var isIndexDBCmpExist = typeof compatGlobal?.indexedDB?.cmp !== "undefined";\n function memorizeFuncWithLRUCache(func) {\n const cache = new LRUCache(100, 1e5, true);\n return (key) => {\n const isExists = cache.has(key);\n if (isExists) return cache.get(key);\n const value = func(key);\n cache.set(key, value);\n return value;\n };\n }\n var globalConcurrencyController = Semaphore(50);\n function wrapByDefault(func, onError) {\n try {\n return func();\n } catch (ex) {\n const error = ex instanceof Error ? ex : new Error(String(ex));\n return onError(error);\n }\n }\n\n // src/string_and_binary/chunks.ts\n function isTextBlob(blob) {\n return blob.type === "text/plain";\n }\n function* pickPiece(leftData, minimumChunkSize) {\n let buffer = "";\n L1: do {\n const curLine = leftData.shift();\n if (typeof curLine === "undefined") {\n yield buffer;\n break L1;\n }\n if (curLine.startsWith("```") || curLine.startsWith(" ```") || curLine.startsWith(" ```") || curLine.startsWith(" ```")) {\n yield buffer;\n buffer = curLine + (leftData.length != 0 ? "\\n" : "");\n L2: do {\n const curPx = leftData.shift();\n if (typeof curPx === "undefined") {\n break L2;\n }\n buffer += curPx + (leftData.length != 0 ? "\\n" : "");\n } while (leftData.length > 0 && !(leftData[0].startsWith("```") || leftData[0].startsWith(" ```") || leftData[0].startsWith(" ```") || leftData[0].startsWith(" ```")));\n const isLooksLikeBASE64 = buffer.endsWith("=");\n const maybeUneditable = buffer.length > 2048;\n const endOfCodeBlock = leftData.shift();\n if (typeof endOfCodeBlock !== "undefined") {\n buffer += endOfCodeBlock;\n buffer += leftData.length != 0 ? "\\n" : "";\n }\n if (!isLooksLikeBASE64 && !maybeUneditable) {\n const splitExpr = /(.*?[;,:<])/g;\n const sx = buffer.split(splitExpr).filter((e) => e != "");\n for (const v of sx) {\n yield v;\n }\n } else {\n yield buffer;\n }\n buffer = "";\n } else {\n buffer += curLine + (leftData.length != 0 ? "\\n" : "");\n if (buffer.length >= minimumChunkSize || leftData.length == 0 || leftData[0] == "#" || buffer[0] == "#") {\n yield buffer;\n buffer = "";\n }\n }\n } while (leftData.length > 0);\n }\n var charNewLine = "\\n".charCodeAt(0);\n var segmenter = "Segmenter" in Intl ? wrapByDefault(\n // @ts-ignore We have checked Intl existence above.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-return\n () => new Intl.Segmenter(compatGlobal.navigator.language, { granularity: "sentence" }),\n (err) => {\n Logger(`Failed to create Intl.Segmenter: ${err.message}`, LOG_LEVEL_VERBOSE);\n return void 0;\n }\n ) : void 0;\n function* splitStringWithinLength(text, pieceSize) {\n let leftData = text;\n do {\n const splitSize = pieceSize;\n const piece = leftData.substring(0, splitSize);\n leftData = leftData.substring(splitSize);\n yield piece;\n } while (leftData != "");\n }\n function* splitTextInSegment(text, pieceSize, minimumChunkSize) {\n const segments = segmenter.segment(text);\n let prev = "";\n let buf = "";\n for (const seg of segments) {\n const buffer = seg.segment;\n if (prev == buffer || buf.length < minimumChunkSize) {\n buf += buffer;\n prev = buffer;\n } else {\n prev = buffer;\n if (buf.length > 0) {\n yield* splitStringWithinLength(buf, pieceSize);\n }\n buf = buffer;\n }\n }\n if (buf.length > 0) {\n yield* splitStringWithinLength(buf, pieceSize);\n }\n }\n function* splitInNewLine(texts) {\n for (const text of texts) {\n let start = -1;\n let end = -1;\n do {\n end = text.indexOf("\\n", start);\n if (end == -1) {\n yield text.substring(start);\n break;\n }\n while (text[end] == "\\n") {\n end++;\n }\n yield text.substring(start, end);\n start = end;\n } while (end != -1);\n }\n return;\n }\n function splitPiecesTextV2(dataSrc, pieceSize, minimumChunkSize) {\n const dataListAllArray = typeof dataSrc == "string" ? [dataSrc] : dataSrc;\n const dataListAll = splitInNewLine(dataListAllArray);\n let inCodeBlock = 0;\n let flush = false;\n let flushBefore = false;\n return function* () {\n const buf = [];\n for (const line of dataListAll) {\n if (line.startsWith("````")) {\n if (inCodeBlock == 0) {\n inCodeBlock = 4;\n flushBefore = true;\n } else if (inCodeBlock == 4) {\n inCodeBlock = 0;\n flush = true;\n }\n } else if (line.startsWith("```")) {\n if (inCodeBlock == 0) {\n inCodeBlock = 3;\n flushBefore = true;\n } else if (inCodeBlock == 3) {\n inCodeBlock = 0;\n flush = true;\n }\n }\n if (flushBefore) {\n if (buf.length > 0) {\n yield* splitTextInSegment(buf.join(""), pieceSize, minimumChunkSize);\n buf.length = 0;\n }\n flushBefore = false;\n }\n buf.push(line);\n if (flush) {\n if (buf.length > 0) {\n yield* splitStringWithinLength(buf.join(""), pieceSize);\n buf.length = 0;\n }\n flush = false;\n }\n }\n if (buf.length > 0) {\n if (inCodeBlock == 0) {\n yield* splitTextInSegment(buf.join(""), pieceSize, minimumChunkSize);\n } else {\n yield* splitStringWithinLength(buf.join(""), pieceSize);\n }\n }\n };\n }\n function binaryTextSplit(data, pieceSize, minimumChunkSize) {\n return function* pieces() {\n yield* splitStringWithinLength(data, pieceSize);\n };\n }\n function splitPiecesText(dataSrc, pieceSize, plainSplit, minimumChunkSize, useSegmenter) {\n if (!useSegmenter || !segmenter) {\n return splitPiecesTextV1(dataSrc, pieceSize, plainSplit, minimumChunkSize);\n }\n if (!plainSplit) {\n return binaryTextSplit(dataSrc, pieceSize, minimumChunkSize);\n }\n return splitPiecesTextV2(dataSrc, pieceSize, minimumChunkSize);\n }\n function splitPiecesTextV1(dataSrc, pieceSize, plainSplit, minimumChunkSize) {\n const dataList = typeof dataSrc == "string" ? [dataSrc] : dataSrc;\n return function* pieces() {\n for (const data of dataList) {\n if (plainSplit) {\n const leftData = data.split("\\n");\n const f = pickPiece(leftData, minimumChunkSize);\n for (const piece of f) {\n let buffer = piece;\n do {\n let ps = pieceSize;\n if (buffer.charCodeAt(ps - 1) != buffer.codePointAt(ps - 1)) {\n ps++;\n }\n yield buffer.substring(0, ps);\n buffer = buffer.substring(ps);\n } while (buffer != "");\n }\n } else {\n let leftData = data;\n do {\n const splitSize = pieceSize;\n const piece = leftData.substring(0, splitSize);\n leftData = leftData.substring(splitSize);\n yield piece;\n } while (leftData != "");\n }\n }\n };\n }\n function* splitByDelimiterWithMinLength(sources, delimiter, minimumChunkLength = 25, splitThreshold) {\n let buf = "";\n let last = false;\n const dl = delimiter.length;\n for (const source of sources) {\n const max = source.length;\n if (splitThreshold && max > splitThreshold) {\n yield buf + source;\n last = false;\n buf = "";\n continue;\n }\n let i = -1;\n let prev = 0;\n L1: do {\n i = source.indexOf(delimiter, prev);\n if (i == -1) break L1;\n buf += source.slice(prev, i) + delimiter;\n if (buf.length > minimumChunkLength) {\n yield buf;\n buf = "";\n last = false;\n } else {\n last = true;\n }\n prev = i + dl;\n } while (i < max);\n if (prev != i || prev == -1 && i == -1) {\n buf += source.slice(prev);\n last = true;\n }\n }\n if (last) {\n yield buf;\n }\n }\n function* chunkStringGenerator(source, maxLength) {\n const strLen = source.length;\n if (strLen > maxLength) {\n let from = 0;\n do {\n let end = from + maxLength;\n if (end > strLen) {\n yield source.substring(from);\n break;\n }\n while (source.charCodeAt(end - 1) != source.codePointAt(end - 1)) {\n end++;\n }\n yield source.substring(from, end);\n from = end;\n } while (from < strLen);\n } else {\n yield source;\n }\n }\n function* chunkStringGeneratorFromGenerator(sources, maxLength) {\n for (const source of sources) {\n yield* chunkStringGenerator(source, maxLength);\n }\n }\n function* stringGenerator(sources) {\n for (const str of sources) {\n yield str;\n }\n }\n var MAX_ITEMS = 100;\n async function splitPieces2V2(dataSrc, pieceSize, plainSplit, minimumChunkSize, filename, useSegmenter) {\n if (dataSrc.size == 0) {\n return function* noItems() {\n return;\n };\n }\n if (isTextBlob(dataSrc)) {\n const text = await dataSrc.text();\n if (!plainSplit) {\n const gen2 = chunkStringGenerator(text, pieceSize);\n return function* pieces() {\n yield* gen2;\n };\n }\n const textLen = text.length;\n let xMinimumChunkSize = minimumChunkSize;\n while (textLen / xMinimumChunkSize > MAX_ITEMS) {\n xMinimumChunkSize += minimumChunkSize;\n }\n const org = stringGenerator([text]);\n const gen1 = splitByDelimiterWithMinLength(org, "\\n", xMinimumChunkSize);\n const gen = chunkStringGeneratorFromGenerator(gen1, pieceSize);\n return function* pieces() {\n yield* gen;\n };\n }\n let canBeSmall = false;\n let delimiter = 0;\n if (filename && filename.endsWith(".pdf")) {\n delimiter = "/".charCodeAt(0);\n } else if (filename && filename.endsWith(".json")) {\n canBeSmall = true;\n delimiter = ",".charCodeAt(0);\n }\n const clampMin = canBeSmall ? 100 : 1e5;\n const clampMax = 1e8;\n const clampedSize = Math.max(clampMin, Math.min(clampMax, dataSrc.size));\n let step = 1;\n let w = clampedSize;\n while (w > 10) {\n w /= 12.5;\n step++;\n }\n minimumChunkSize = Math.floor(10 ** (step - 1));\n return async function* piecesBlob() {\n const size = dataSrc.size;\n let i = 0;\n const buf = new Uint8Array(await dataSrc.arrayBuffer());\n do {\n const findStart = i + minimumChunkSize;\n const defaultSplitEnd = i + pieceSize;\n let splitEnd;\n let i1 = buf.indexOf(delimiter, findStart);\n if (i1 == -1) {\n i1 = buf.indexOf(charNewLine, findStart);\n }\n if (i1 == -1) {\n splitEnd = defaultSplitEnd;\n } else {\n splitEnd = i1 < defaultSplitEnd ? i1 : defaultSplitEnd;\n }\n yield await arrayBufferToBase64Single2(buf.slice(i, splitEnd));\n i = splitEnd;\n } while (i < size);\n };\n }\n async function splitPieces2(dataSrc, pieceSize, plainSplit, minimumChunkSize, filename, useSegmenter) {\n if (isTextBlob(dataSrc)) {\n return splitPiecesText(await dataSrc.text(), pieceSize, plainSplit, minimumChunkSize, useSegmenter ?? false);\n }\n let delimiter = 0;\n let canBeSmall = false;\n if (filename && filename.endsWith(".pdf")) {\n delimiter = "/".charCodeAt(0);\n } else if (filename && filename.endsWith(".json")) {\n canBeSmall = true;\n delimiter = ",".charCodeAt(0);\n }\n const clampMin = canBeSmall ? 100 : 1e5;\n const clampMax = 1e8;\n const clampedSize = Math.max(clampMin, Math.min(clampMax, dataSrc.size));\n let step = 1;\n let w = clampedSize;\n while (w > 10) {\n w /= 12.5;\n step++;\n }\n minimumChunkSize = Math.floor(10 ** (step - 1));\n return async function* piecesBlob() {\n const size = dataSrc.size;\n let i = 0;\n do {\n let splitSize = pieceSize;\n const currentData = new Uint8Array(await dataSrc.slice(i, i + pieceSize).arrayBuffer());\n let nextIdx = currentData.indexOf(delimiter, minimumChunkSize);\n splitSize = nextIdx == -1 ? pieceSize : Math.min(pieceSize, nextIdx);\n if (nextIdx == -1) nextIdx = currentData.indexOf(charNewLine, minimumChunkSize);\n const piece = currentData.slice(0, splitSize);\n i += piece.length;\n const b64 = await arrayBufferToBase64Single2(piece);\n yield b64;\n } while (i < size);\n };\n }\n async function splitPiecesRabinKarp(dataSrc, absoluteMaxPieceSize, doPlainSplit, minimumChunkSize, _filename, _useSegmenter) {\n let plainSplit = doPlainSplit || isTextBlob(dataSrc);\n const dataSize = dataSrc.size;\n let chunkUnitPlain = 64;\n const MAX_CHUNK_COUNT = 500;\n if (plainSplit) {\n const isDataSizeTooLargeForPlainSplit = dataSize >= 4 * 1024 * 1024;\n if (isDataSizeTooLargeForPlainSplit) {\n plainSplit = false;\n } else {\n let estimatedChunkCount;\n do {\n estimatedChunkCount = dataSize / (chunkUnitPlain * 4);\n if (estimatedChunkCount > MAX_CHUNK_COUNT) {\n chunkUnitPlain += 32;\n }\n } while (estimatedChunkCount > MAX_CHUNK_COUNT);\n }\n }\n const chunkUnitBinary = 256 * 1024;\n const fixedAvgChunkSize = plainSplit ? chunkUnitPlain * 4 : chunkUnitBinary * 4;\n const fixedMaxChunkSize = plainSplit ? chunkUnitPlain * 16 : chunkUnitBinary * 16;\n const fixedMinChunkSize = plainSplit ? chunkUnitPlain * 2 : chunkUnitBinary;\n const rkAbsoluteMaxPieceSizeFloor = 30 * 1024;\n const effectiveAbsoluteMaxPieceSize = Math.max(absoluteMaxPieceSize, rkAbsoluteMaxPieceSizeFloor);\n const maxChunkSize = Math.min(fixedMaxChunkSize, effectiveAbsoluteMaxPieceSize);\n const minChunkSize = Math.min(Math.max(fixedMinChunkSize, minimumChunkSize), maxChunkSize);\n const avgChunkSize = Math.min(Math.max(fixedAvgChunkSize, minChunkSize), maxChunkSize);\n const windowSize = 48;\n const hashModulus = avgChunkSize;\n const boundaryPattern = 1;\n const PRIME = 31;\n let P_pow_w = 1;\n for (let i = 0; i < windowSize - 1; i++) {\n P_pow_w = Math.imul(P_pow_w, PRIME);\n }\n const buffer = new Uint8Array(await dataSrc.arrayBuffer());\n let pos = 0;\n let hash = 0;\n let start = 0;\n const isText = isTextBlob(dataSrc);\n const length = buffer.length;\n return async function* piecesBlob() {\n while (pos < length) {\n const byte = buffer[pos];\n if (pos >= start + windowSize) {\n const oldByte = buffer[pos - windowSize];\n const oldByteTerm = Math.imul(oldByte, P_pow_w);\n hash = hash - oldByteTerm | 0;\n hash = Math.imul(hash, PRIME);\n hash = hash + byte | 0;\n } else {\n hash = Math.imul(hash, PRIME);\n hash = hash + byte | 0;\n }\n const currentChunkSize = pos - start + 1;\n let isBoundaryCandidate = false;\n if (currentChunkSize >= minChunkSize) {\n if ((hash >>> 0) % hashModulus === boundaryPattern) {\n isBoundaryCandidate = true;\n }\n }\n if (currentChunkSize >= maxChunkSize) {\n isBoundaryCandidate = true;\n }\n if (isBoundaryCandidate) {\n let isSafeBoundary = true;\n if (isText) {\n if (pos + 1 < length && (buffer[pos + 1] & 192) === 128) {\n isSafeBoundary = false;\n }\n }\n if (isSafeBoundary) {\n if (isText) {\n yield Promise.resolve(readString(buffer.subarray(start, pos + 1)));\n } else {\n yield await arrayBufferToBase64Single2(buffer.subarray(start, pos + 1));\n }\n start = pos + 1;\n }\n }\n pos++;\n }\n if (start < length) {\n if (isText) {\n yield Promise.resolve(readString(buffer.subarray(start, length)));\n } else {\n yield await arrayBufferToBase64Single2(buffer.subarray(start, length));\n }\n }\n };\n }\n\n // src/worker/bg.common.ts\n function postBack(key, seq, data) {\n self.postMessage({ key, seq, result: data });\n }\n\n // src/worker/universalTypes.ts\n var END_OF_DATA = null;\n\n // src/worker/bg.worker.splitting.ts\n function getMainThreadPostBack(key) {\n const _key = key;\n let seq = 0;\n return function(data) {\n if (data === END_OF_DATA) {\n if (seq === 0) {\n postBack(_key, seq++, "");\n }\n postBack(_key, seq++, END_OF_DATA);\n } else {\n postBack(_key, seq++, data);\n }\n };\n }\n async function processSplit(data) {\n const key = data.key;\n const dataSrc = data.dataSrc;\n const pieceSize = data.pieceSize;\n const plainSplit = data.plainSplit;\n const minimumChunkSize = data.minimumChunkSize;\n const filename = data.filename;\n const useSegmenter = data.useSegmenter;\n const func = data.splitVersion == 3 ? splitPiecesRabinKarp : data.splitVersion == 2 ? splitPieces2V2 : splitPieces2;\n const gen = await func(dataSrc, pieceSize, plainSplit, minimumChunkSize, filename, useSegmenter);\n const emit = getMainThreadPostBack(key);\n for await (const v of gen()) {\n emit(v);\n }\n emit(END_OF_DATA);\n }\n\n // node_modules/octagonal-wheels/dist/encryption/encryptionv3.js\n var webcrypto2 = globalThis.crypto;\n var SALT_STR = "fancySyncForYou!";\n var SALT = new TextEncoder().encode(SALT_STR);\n var _nonceV3 = new Uint32Array(1);\n var bufV3 = new Uint8Array(12);\n async function generateKey(passphrase) {\n const passphraseBin = new TextEncoder().encode(passphrase);\n const digestOfPassphrase = await webcrypto2.subtle.digest("SHA-256", new Uint8Array([...passphraseBin, ...SALT]));\n const salt = digestOfPassphrase.slice(0, 16);\n const baseKey = await webcrypto2.subtle.importKey("raw", passphraseBin, "PBKDF2", false, [\n "deriveBits",\n "deriveKey"\n ]);\n const pbkdf2Params = {\n name: "PBKDF2",\n hash: "SHA-256",\n salt,\n iterations: 1e5\n // Increased iterations for better security\n };\n const derivedKey = await webcrypto2.subtle.deriveKey(pbkdf2Params, baseKey, { name: "AES-GCM", length: 256 }, false, ["decrypt", "encrypt"]);\n return derivedKey;\n }\n var previousDecryptionPassphrase = "";\n var decryptionKey;\n async function decryptV3(encryptedResult, passphrase) {\n if (previousDecryptionPassphrase !== passphrase) {\n const key = await generateKey(passphrase);\n decryptionKey = key;\n previousDecryptionPassphrase = passphrase;\n }\n const ivStr = encryptedResult.substring(2, 26);\n const encryptedData = encryptedResult.substring(26);\n const iv = hexStringToUint8Array(ivStr);\n const encryptedDataArrayBuffer = base64ToArrayBuffer(encryptedData);\n const dataBuffer = await webcrypto2.subtle.decrypt({ name: "AES-GCM", iv }, decryptionKey, encryptedDataArrayBuffer);\n const plain = readString(new Uint8Array(dataBuffer));\n return plain;\n }\n\n // node_modules/octagonal-wheels/dist/memory/memo.js\n var UNDEFINED = /* @__PURE__ */ Symbol("undefined");\n function memoWithMap(bufferLength, fn, keyFunction) {\n if (bufferLength <= 0) {\n throw new Error("Buffer length must be greater than 0");\n }\n const cache = /* @__PURE__ */ new Map();\n const getKey = (args) => {\n return args.length > 0 && typeof args[0] === "string" ? args[0] : JSON.stringify(args, (key, value) => value === void 0 ? UNDEFINED : value);\n };\n return function(...args) {\n const key = keyFunction ? keyFunction(args) : getKey(args);\n if (cache.has(key)) {\n const hitPromise = cache.get(key);\n cache.delete(key);\n cache.set(key, hitPromise);\n return hitPromise;\n }\n const newPromise = fn(...args);\n cache.set(key, newPromise);\n newPromise.catch(() => {\n if (cache.get(key) === newPromise) {\n cache.delete(key);\n }\n });\n if (cache.size > bufferLength) {\n const oldest = cache.keys().next();\n if (!oldest.done)\n cache.delete(oldest.value);\n }\n return newPromise;\n };\n }\n\n // node_modules/octagonal-wheels/dist/encryption/hkdf.js\n var webcrypto3 = globalThis.crypto;\n var IV_LENGTH = 12;\n var PBKDF2_ITERATIONS = 31e4;\n var HKDF_SALT_LENGTH = 32;\n var gcmTagLength = 128;\n var HKDF_ENCRYPTED_PREFIX = "%=";\n var deriveMasterKey = memoWithMap(10, async (passphrase, pbkdf2Salt) => {\n const binaryPassphrase = writeString(passphrase);\n const keyMaterial = await webcrypto3.subtle.importKey("raw", binaryPassphrase, {\n name: "PBKDF2",\n length: 256\n // Length of the key in bits\n }, false, ["deriveKey"]);\n const masterKeyRaw = await webcrypto3.subtle.deriveKey(\n {\n name: "PBKDF2",\n salt: pbkdf2Salt,\n iterations: PBKDF2_ITERATIONS,\n hash: "SHA-256"\n },\n keyMaterial,\n // Output the "raw" key\n { name: "AES-GCM", length: 256 },\n true,\n // extractable\n ["encrypt", "decrypt"]\n // The master key is used for encryption/decryption\n );\n const masterKeyBuffer = await webcrypto3.subtle.exportKey("raw", masterKeyRaw);\n const hkdfKey = await webcrypto3.subtle.importKey("raw", masterKeyBuffer, { name: "HKDF" }, false, [\n "deriveKey"\n ]);\n return hkdfKey;\n }, ([passphrase, salt]) => {\n return `${passphrase}-${uint8ArrayToHexString(salt)}`;\n });\n async function deriveKey(passphrase, pbkdf2Salt, hkdfSalt) {\n const masterKey = await deriveMasterKey(passphrase, pbkdf2Salt);\n const chunkKey = await webcrypto3.subtle.deriveKey(\n {\n name: "HKDF",\n salt: hkdfSalt,\n info: new Uint8Array(),\n // Context info (if needed)\n hash: "SHA-256"\n },\n masterKey,\n // Specify the algorithm and usage for the chunk key\n { name: "AES-GCM", length: 256 },\n false,\n ["encrypt", "decrypt"]\n // The chunk key is used only for encryption/decryption\n );\n return chunkKey;\n }\n async function encryptData(key, iv, data) {\n return await webcrypto3.subtle.encrypt({\n name: "AES-GCM",\n iv,\n tagLength: gcmTagLength\n }, key, data);\n }\n async function _encrypt(input, passphrase, pbkdf2Salt) {\n const hkdfSalt = webcrypto3.getRandomValues(new Uint8Array(HKDF_SALT_LENGTH));\n const key = await deriveKey(passphrase, pbkdf2Salt, hkdfSalt);\n const iv = webcrypto3.getRandomValues(new Uint8Array(IV_LENGTH));\n const encryptedDataArrayBuffer = await encryptData(key, iv, input);\n const encryptedData = new Uint8Array(encryptedDataArrayBuffer);\n return [iv, hkdfSalt, encryptedData];\n }\n async function encryptBinary(input, passphrase, pbkdf2Salt) {\n const [iv, hkdfSalt, encryptedData] = await _encrypt(input, passphrase, pbkdf2Salt);\n const totalLength = iv.length + hkdfSalt.length + encryptedData.length;\n const result = new Uint8Array(totalLength);\n result.set(iv, 0);\n result.set(hkdfSalt, iv.length);\n result.set(encryptedData, iv.length + hkdfSalt.length);\n return result;\n }\n async function encrypt(input, passphrase, pbkdf2Salt) {\n const inputBuffer = writeString(input);\n const encrypted = await encryptBinary(inputBuffer, passphrase, pbkdf2Salt);\n const inBase64 = await arrayBufferToBase64Single(encrypted);\n return `${HKDF_ENCRYPTED_PREFIX}${inBase64}`;\n }\n async function _decrypt(iv, pbkdf2Salt, hkdfSalt, encryptedData, passphrase) {\n const key = await deriveKey(passphrase, pbkdf2Salt, hkdfSalt);\n const decryptedDataArrayBuffer = await webcrypto3.subtle.decrypt({\n name: "AES-GCM",\n iv,\n tagLength: gcmTagLength\n }, key, encryptedData);\n return new Uint8Array(decryptedDataArrayBuffer);\n }\n async function decryptBinary(binary, passphrase, pbkdf2Salt) {\n if (binary.length < IV_LENGTH + HKDF_SALT_LENGTH) {\n throw new Error("Invalid binary data length. Expected at least ivLength + saltLength bytes.");\n }\n const iv = binary.slice(0, IV_LENGTH);\n const hkdfSalt = binary.slice(IV_LENGTH, IV_LENGTH + HKDF_SALT_LENGTH);\n const encryptedData = binary.slice(IV_LENGTH + HKDF_SALT_LENGTH);\n const decryptedData = await _decrypt(iv, pbkdf2Salt, hkdfSalt, encryptedData, passphrase);\n return decryptedData;\n }\n async function decrypt(input, passphrase, pbkdf2Salt) {\n if (!input.startsWith(HKDF_ENCRYPTED_PREFIX)) {\n throw new Error(`Invalid input format. Expected input to start with \'${HKDF_ENCRYPTED_PREFIX}\'.`);\n }\n const headerLength = HKDF_ENCRYPTED_PREFIX.length;\n const encryptedData = base64ToArrayBuffer(input.slice(headerLength));\n const decrypted = await decryptBinary(new Uint8Array(encryptedData), passphrase, pbkdf2Salt);\n return readString(decrypted);\n }\n\n // node_modules/octagonal-wheels/dist/encryption/obfuscatePath.js\n var webcrypto4 = globalThis.crypto;\n\n // node_modules/octagonal-wheels/dist/encryption/encryption.js\n var KeyBuffs = /* @__PURE__ */ new Map();\n var decKeyBuffs = /* @__PURE__ */ new Map();\n var KEY_RECYCLE_COUNT = 100;\n var semiStaticFieldBuffer;\n var nonceBuffer = new Uint32Array(1);\n var webcrypto5 = globalThis.crypto;\n async function getKeyForEncrypt(passphrase, autoCalculateIterations) {\n const buffKey = `${passphrase}-${autoCalculateIterations}`;\n const f = KeyBuffs.get(buffKey);\n if (f) {\n f.count--;\n if (f.count > 0) {\n return [f.key, f.salt];\n }\n f.count--;\n }\n const passphraseLen = 15 - passphrase.length;\n const iteration = autoCalculateIterations ? (passphraseLen > 0 ? passphraseLen : 0) * 1e3 + 121 - passphraseLen : 1e5;\n const passphraseBin = new TextEncoder().encode(passphrase);\n const digest = await webcrypto5.subtle.digest({ name: "SHA-256" }, passphraseBin);\n const keyMaterial = await webcrypto5.subtle.importKey("raw", digest, { name: "PBKDF2" }, false, ["deriveKey"]);\n const salt = webcrypto5.getRandomValues(new Uint8Array(16));\n const key = await webcrypto5.subtle.deriveKey({\n name: "PBKDF2",\n salt,\n iterations: iteration,\n hash: "SHA-256"\n }, keyMaterial, { name: "AES-GCM", length: 256 }, false, ["encrypt"]);\n KeyBuffs.set(buffKey, {\n key,\n salt,\n count: KEY_RECYCLE_COUNT\n });\n return [key, salt];\n }\n var keyGCCount = KEY_RECYCLE_COUNT * 5;\n var decKeyIdx = 0;\n var decKeyMin = 0;\n async function getKeyForDecryption(passphrase, salt, autoCalculateIterations) {\n keyGCCount--;\n if (keyGCCount < 0) {\n keyGCCount = KEY_RECYCLE_COUNT;\n const threshold = (decKeyIdx - decKeyMin) / 2;\n for (const [key2, buff] of decKeyBuffs) {\n if (buff.count < threshold) {\n decKeyBuffs.delete(key2);\n }\n decKeyMin = decKeyIdx;\n }\n }\n decKeyIdx++;\n const bufKey = passphrase + uint8ArrayToHexString(salt) + autoCalculateIterations;\n const f = decKeyBuffs.get(bufKey);\n if (f) {\n f.count = decKeyIdx;\n return [f.key, f.salt];\n }\n const passphraseLen = 15 - passphrase.length;\n const iteration = autoCalculateIterations ? (passphraseLen > 0 ? passphraseLen : 0) * 1e3 + 121 - passphraseLen : 1e5;\n const passphraseBin = new TextEncoder().encode(passphrase);\n const digest = await webcrypto5.subtle.digest({ name: "SHA-256" }, passphraseBin);\n const keyMaterial = await webcrypto5.subtle.importKey("raw", digest, { name: "PBKDF2" }, false, ["deriveKey"]);\n const key = await webcrypto5.subtle.deriveKey({\n name: "PBKDF2",\n salt,\n iterations: iteration,\n hash: "SHA-256"\n }, keyMaterial, { name: "AES-GCM", length: 256 }, false, ["decrypt"]);\n decKeyBuffs.set(bufKey, {\n key,\n salt,\n count: 0\n });\n return [key, salt];\n }\n function getSemiStaticField(reset) {\n if (semiStaticFieldBuffer != null && !reset) {\n return semiStaticFieldBuffer;\n }\n semiStaticFieldBuffer = webcrypto5.getRandomValues(new Uint8Array(12));\n return semiStaticFieldBuffer;\n }\n function getNonce() {\n nonceBuffer[0]++;\n if (nonceBuffer[0] > 1e4) {\n getSemiStaticField(true);\n }\n return nonceBuffer;\n }\n async function encrypt2(input, passphrase, autoCalculateIterations) {\n const [key, salt] = await getKeyForEncrypt(passphrase, autoCalculateIterations);\n const fixedPart = getSemiStaticField();\n const invocationPart = getNonce();\n const iv = new Uint8Array([...fixedPart, ...new Uint8Array(invocationPart.buffer)]);\n const dataBuf = writeString(input);\n const encryptedDataArrayBuffer = await webcrypto5.subtle.encrypt({ name: "AES-GCM", iv }, key, dataBuf);\n const encryptedData2 = "" + await arrayBufferToBase64Single(new Uint8Array(encryptedDataArrayBuffer));\n const ret = `%${uint8ArrayToHexString(iv)}${uint8ArrayToHexString(salt)}${encryptedData2}`;\n return ret;\n }\n async function decryptV2(encryptedResult, passphrase, autoCalculateIterations) {\n try {\n const ivStr = encryptedResult.substring(1, 33);\n const salt = encryptedResult.substring(33, 65);\n const encryptedData = encryptedResult.substring(65);\n const [key] = await getKeyForDecryption(passphrase, hexStringToUint8Array(salt), autoCalculateIterations);\n const iv = hexStringToUint8Array(ivStr);\n const encryptedDataArrayBuffer = decodeBinary(encryptedData);\n const dataBuffer = await webcrypto5.subtle.decrypt({ name: "AES-GCM", iv }, key, encryptedDataArrayBuffer);\n const plain = readString(new Uint8Array(dataBuffer));\n return plain;\n } catch (ex) {\n Logger("Couldn\'t decode! You should wrong the passphrases (V2)", LOG_LEVEL_VERBOSE);\n Logger(ex, LOG_LEVEL_VERBOSE);\n throw ex;\n }\n }\n async function decrypt2(encryptedResult, passphrase, autoCalculateIterations) {\n try {\n if (encryptedResult[0] == "%") {\n if (encryptedResult[1] === "~") {\n return decryptV3(encryptedResult, passphrase);\n }\n return decryptV2(encryptedResult, passphrase, autoCalculateIterations);\n }\n if (!encryptedResult.startsWith("[") || !encryptedResult.endsWith("]")) {\n throw new Error("Encrypted data corrupted!");\n }\n const w = encryptedResult.substring(1, encryptedResult.length - 1).split(",").map((e) => e[0] == \'"\' ? e.substring(1, e.length - 1) : e);\n const [encryptedData, ivString, salt] = w;\n const [key] = await getKeyForDecryption(passphrase, hexStringToUint8Array(salt), autoCalculateIterations);\n const iv = hexStringToUint8Array(ivString);\n const encryptedDataBin = atob(encryptedData);\n const len = encryptedDataBin.length;\n const encryptedDataArrayBuffer = new Uint8Array(len);\n for (let i = len; i >= 0; --i) {\n encryptedDataArrayBuffer[i] = encryptedDataBin.charCodeAt(i);\n }\n const plainStringBuffer = await webcrypto5.subtle.decrypt({ name: "AES-GCM", iv }, key, encryptedDataArrayBuffer);\n const plainStringified = readString(new Uint8Array(plainStringBuffer));\n const plain = JSON.parse(plainStringified);\n return plain;\n } catch (ex) {\n Logger("Couldn\'t decode! You should wrong the passphrases", LOG_LEVEL_VERBOSE);\n Logger(ex, LOG_LEVEL_VERBOSE);\n throw ex;\n }\n }\n\n // node_modules/octagonal-wheels/dist/encryption/openSSLCompat/CBC.js\n var SALT_PREFIX = new Uint8Array([83, 97, 108, 116, 101, 100, 95, 95]);\n\n // node_modules/octagonal-wheels/dist/encryption/asymmetric/common.js\n var webCrypto = globalThis.crypto || window.crypto;\n var DEFAULT_RSA_PUBLIC_EXPONENT = new Uint8Array([1, 0, 1]);\n var HEAD_RSA = new Uint8Array([10, 244, 193]);\n var HEAD_ECDH = new Uint8Array([10, 244, 194]);\n\n // node_modules/octagonal-wheels/dist/encryption/obfuscatePathV2.js\n var webcrypto6 = globalThis.crypto;\n async function _deriveKeyFromPassphrase(passphrase, hkdfSalt) {\n const passphraseBin = writeString(passphrase);\n const keyMaterial = await webcrypto6.subtle.importKey("raw", passphraseBin, { name: "HKDF" }, false, ["deriveKey"]);\n const derivedKey = await webcrypto6.subtle.deriveKey({\n name: "HKDF",\n hash: "SHA-256",\n salt: hkdfSalt,\n info: new Uint8Array([])\n }, keyMaterial, { name: "HMAC", hash: "SHA-256", length: 256 }, false, ["sign"]);\n return derivedKey;\n }\n var deriveKeyFromPassphrase = memoWithMap(10, _deriveKeyFromPassphrase, ([passphrase, hkdfSalt]) => {\n return `${writeString(passphrase)}-${uint8ArrayToHexString(hkdfSalt)}`;\n });\n\n // src/worker/bg.worker.encryption.ts\n async function processEncryption(data) {\n const key = data.key;\n const { type, input, passphrase } = data;\n try {\n if (type == "encrypt") {\n const autoCalculateIterations = data.autoCalculateIterations;\n const result = await encrypt2(input, passphrase, autoCalculateIterations);\n self.postMessage({ key, result });\n } else if (type == "decrypt") {\n const autoCalculateIterations = data.autoCalculateIterations;\n const result = await decrypt2(input, passphrase, autoCalculateIterations);\n self.postMessage({ key, result });\n } else if (type == "encryptHKDF") {\n const pbkdf2Salt = data.pbkdf2Salt;\n const result = await encrypt(input, passphrase, pbkdf2Salt);\n self.postMessage({ key, result });\n } else if (type == "decryptHKDF") {\n const pbkdf2Salt = data.pbkdf2Salt;\n const result = await decrypt(input, passphrase, pbkdf2Salt);\n self.postMessage({ key, result });\n }\n } catch (ex) {\n self.postMessage({ key, error: ex });\n }\n }\n\n // src/worker/bg.worker.ts\n self.onmessage = (e) => {\n const data = e.data.data;\n if (data.type === "split") {\n return processSplit(data);\n } else if (data.type === "encrypt" || data.type === "decrypt") {\n return processEncryption(data);\n } else if (data.type === "encryptHKDF" || data.type === "decryptHKDF") {\n return processEncryption(data);\n } else {\n self.postMessage({ key: data.key, error: new Error("Invalid type") });\n }\n };\n})();\n/*! Bundled license information:\n\noctagonal-wheels/dist/encryption/asymmetric/common.js:\n (* istanbul ignore next -- @preserve *)\n*/\n';EVENT_PLATFORM_UNLOADED2="platform-unloaded";logger_exports2={};__reExport(logger_exports2,logger_exports);SYMBOL_USED=Symbol("used");SYMBOL_END_OF_DATA=Symbol("endOfData");workerStreams=new Map;writers=new Map;responseBuf=new Map;writerPromise=Promise.resolve();compatGlobal2="undefined"!=typeof window?window:globalThis;compatGlobal2.fetch.bind(compatGlobal2);activeDocumentWindow2=compatGlobal2;null!=(_a9=activeDocumentWindow2.activeDocument)?_a9:activeDocumentWindow2.document;tasks2=new Map;taskWorkerMap=new Map;workers=[];key2=0;roundRobinIdx=0;encrypt4=function encryptWorker(input,passphrase,autoCalculateIterations){return encryptionOnWorker({type:"encrypt",input,passphrase,autoCalculateIterations})};decrypt4=function decryptWorker(input,passphrase,autoCalculateIterations){return encryptionOnWorker({type:"decrypt",input,passphrase,autoCalculateIterations})};encryptHKDF=encryptHKDFWorker;decryptHKDF=function decryptHKDFWorker(input,passphrase,pbkdf2Salt){return encryptionHKDFOnWorker({type:"decryptHKDF",input,passphrase,pbkdf2Salt})};Encrypt_HKDF_Header="%=";Encrypt_OLD_Header="%";EncryptionVersions_UNENCRYPTED=0,EncryptionVersions_ENCRYPTED=1,EncryptionVersions_HKDF=2,EncryptionVersions_UNKNOWN=99;ENCRYPTED_META_PREFIX="/\\:";MESSAGE_FALLBACK_DECRYPT_FAILED="Failed to decrypt the data with V1 method. Cannot encrypt with HKDF.";ENCRYPTION_HKDF_FAILED="Encryption with HKDF failed.";DECRYPTION_HKDF_FAILED="Decryption with HKDF failed.";DECRYPTION_FALLBACK_FAILED="Decryption with fallback failed.";preprocessOutgoing=async doc=>await Promise.resolve(doc);0;enableEncryption=(db,passphrase,useDynamicIterationCount,migrationDecrypt,getPBKDF2Salt,algorithm)=>{const{incoming,outgoing}=getConfiguredFunctionsForEncryption(passphrase,useDynamicIterationCount,migrationDecrypt,getPBKDF2Salt,algorithm);db.transform({incoming,outgoing})};EDEN_ENCRYPTED_KEY="h:++encrypted";EDEN_ENCRYPTED_KEY_HKDF="h:++encrypted-hkdf";LiveSyncAbstractReplicator=class{constructor(env){__publicField(this,"syncStatus","NOT_CONNECTED");__publicField(this,"docArrived",0);__publicField(this,"docSent",0);__publicField(this,"lastSyncPullSeq",0);__publicField(this,"maxPullSeq",0);__publicField(this,"lastSyncPushSeq",0);__publicField(this,"maxPushSeq",0);__publicField(this,"controller");__publicField(this,"originalSetting");__publicField(this,"nodeid","");__publicField(this,"remoteLocked",!1);__publicField(this,"remoteCleaned",!1);__publicField(this,"remoteLockedAndDeviceNotAccepted",!1);__publicField(this,"tweakSettingsMismatched",!1);__publicField(this,"preferredTweakValue");__publicField(this,"env");__publicField(this,"updateInfo",()=>{this.env.services.replicator.replicationStatics.value={sent:this.docSent,arrived:this.docArrived,maxPullSeq:this.maxPullSeq,maxPushSeq:this.maxPushSeq,lastSyncPullSeq:this.lastSyncPullSeq,lastSyncPushSeq:this.lastSyncPushSeq,syncStatus:this.syncStatus}});this.env=env}get database(){return this.env.services.database.localDatabase}get rawDatabase(){return this.env.services.database.localDatabase.localDatabase}get currentSettings(){return this.env.services.setting.currentSettings()}translate(key3,params){return this.env.services.context.translate(key3,params)}sendChunks(setting,remoteDB,showResult,fromSeq){return Promise.resolve(!0)}async ensurePBKDF2Salt(setting,showMessage2=!1,useCache=!0){try{const hash3=await this.getReplicationPBKDF2Salt(setting,!useCache);if(0==hash3.length)throw new Error("PBKDF2 salt (Security Seed) is empty");Logger(`PBKDF2 salt (Security Seed): ${await arrayBufferToBase64Single2(hash3)}`,LOG_LEVEL_VERBOSE);return!0}catch(ex){const level=showMessage2?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO;Logger("Failed to obtain PBKDF2 salt (Security Seed) for replication",level);Logger(ex,LOG_LEVEL_VERBOSE);return!1}}async initializeDatabaseForReplication(){const db=this.rawDatabase;try{const nodeinfo=await resolveWithIgnoreKnownError(db.get(NODEINFO_DOCID),{_id:NODEINFO_DOCID,type:"nodeinfo",nodeid:"",v20220607:!0});if(""==nodeinfo.nodeid){nodeinfo.nodeid=Math.random().toString(36).slice(-10);await db.put(nodeinfo)}this.nodeid=nodeinfo.nodeid;return!0}catch(ex){Logger(ex)}return!1}};PREFIX_TRENCH="trench";PREFIX_EPHEMERAL="ephemeral";PREFIX_PERMANENT="permanent";idx=0;series=`${Date.now()}`;indexes=new Map;inProgress=new Set;failed=new Map;Trench=class{constructor(db,flushExistItems=!0){Object.defineProperty(this,"_db",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_flushTask",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"concealing",{enumerable:!0,configurable:!0,writable:!0,value:new Map});this._db=db;flushExistItems&&(this._flushTask=(async()=>{const keys3=await db.keys(`${PREFIX_TRENCH}-${PREFIX_EPHEMERAL}`,`${PREFIX_TRENCH}-${PREFIX_EPHEMERAL}.`);for(const key3 of keys3)await db.delete(key3)})())}async eraseAllEphemerals(){const keys3=await this._db.keys(`${PREFIX_TRENCH}-${PREFIX_EPHEMERAL}`,`${PREFIX_TRENCH}-${PREFIX_EPHEMERAL}.`);for(const key3 of keys3)await this._db.delete(key3)}async eraseAllPermanences(){const keys3=await this._db.keys(`${PREFIX_TRENCH}-${PREFIX_PERMANENT}`,`${PREFIX_TRENCH}-${PREFIX_PERMANENT}.`);for(const key3 of keys3)await this._db.delete(key3)}conceal(obj){const key3=generateId(PREFIX_EPHEMERAL);this.concealing.set(key3,obj);this._db.set(key3,obj).then(async e3=>{this.concealing.has(key3)?this.concealing.delete(key3):await this._db.delete(key3)});return key3}async bury(key3){this.concealing.has(key3)&&this.concealing.delete(key3);await this._db.delete(key3)}async expose(key3){if(this.concealing.has(key3)){const value=this.concealing.get(key3);this.concealing.delete(key3);return value}const obj=await this._db.get(key3);await this._db.delete(key3);return obj}_evacuate(storeTask,key3){return async()=>{if(this._flushTask){await this._flushTask;this._flushTask=void 0}await storeTask;const item=await this._db.get(key3);await this._db.delete(key3);return item}}evacuatePromise(task){const key3=generateId(PREFIX_EPHEMERAL),storeTask=(async()=>{const data=await task;await this._db.set(key3,data)})();return this._evacuate(storeTask,key3)}evacuate(obj){if(obj instanceof Promise)return this.evacuatePromise(obj);const key3=generateId(PREFIX_EPHEMERAL),storeTask=this._db.set(key3,obj);return this._evacuate(storeTask,key3)}async _queue(type,key3,obj,index6){var _a13;if(void 0===index6){index6=null!=(_a13=indexes.get(key3))?_a13:0;indexes.set(key3,index6+1)}const storeKey=createId(type,key3,index6);await this._db.set(storeKey,obj)}async _dequeue(type,key3){const range4=createRange(type,key3),keys3=(await this._db.keys(range4[0],range4[1])).filter(e3=>!inProgress.has(e3));if(0!==keys3.length)return await this.expose(keys3[0])}async _dequeueWithCommit(type,key3){const range4=createRange(type,key3),keysAll=await this._db.keys(range4[0],range4[1]),keys3=keysAll.filter(e3=>!inProgress.has(e3));if(0===keys3.length)return;const storeKey=keys3[0];inProgress.add(storeKey);const previousFailed=failed.get(storeKey)||0,value=await this._db.get(storeKey);return{key:storeKey,value,cancelCount:previousFailed,pendingItems:keysAll.length-1,commit:async()=>{await this._db.delete(storeKey);failed.delete(storeKey);inProgress.delete(storeKey)},cancel:()=>{failed.set(storeKey,(failed.get(storeKey)||0)+1);inProgress.delete(storeKey)}}}queue(key3,obj,index6){return this._queue(PREFIX_EPHEMERAL,key3,obj,index6)}dequeue(key3){return this._dequeue(PREFIX_EPHEMERAL,key3)}dequeueWithCommit(key3){return this._dequeueWithCommit(PREFIX_EPHEMERAL,key3)}queuePermanent(key3,obj,index6){return this._queue(PREFIX_PERMANENT,key3,obj,index6)}dequeuePermanent(key3){return this._dequeue(PREFIX_PERMANENT,key3)}dequeuePermanentWithCommit(key3){return this._dequeueWithCommit(PREFIX_PERMANENT,key3)}};StreamInbox=class{constructor(options={}){var _a13,_b6;Object.defineProperty(this,"readable",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_capacity",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_overflowPolicy",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_queue",{enumerable:!0,configurable:!0,writable:!0,value:[]});Object.defineProperty(this,"_controller",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_isClosed",{enumerable:!0,configurable:!0,writable:!0,value:!1});Object.defineProperty(this,"_isControllerClosed",{enumerable:!0,configurable:!0,writable:!0,value:!1});const capacity=null!=(_a13=options.capacity)?_a13:1;if(capacity<=0)throw new TypeError("capacity must be greater than 0");this._capacity=capacity;this._overflowPolicy=null!=(_b6=options.overflowPolicy)?_b6:"reject";this.readable=new ReadableStream({start:controller=>{this._controller=controller;this._drain()},pull:()=>{this._drain()},cancel:()=>{this._isClosed=!0;this._queue.length=0}},{highWaterMark:capacity})}get size(){var _a13,_b6;const desiredSize=null!=(_b6=null==(_a13=this._controller)?void 0:_a13.desiredSize)?_b6:this._capacity,streamQueued=Math.max(0,this._capacity-desiredSize);return this._queue.length+streamQueued}get free(){return this._capacity-this.size}get isFull(){return this.free<=0}get isClosed(){return this._isClosed}post(item){if(this._isClosed)return!1;if(!this.isFull){this._queue.push(item);this._drain();return!0}return this._overflowPolicy,!1}close(){if(!this._isClosed){this._isClosed=!0;this._drain();0===this._queue.length&&this._closeController()}}error(reason){var _a13;if(!this._isClosed){this._isClosed=!0;this._queue.length=0;null==(_a13=this._controller)||_a13.error(reason)}}_drain(){var _a13;if(this._controller){for(;0!==this._queue.length&&(null!=(_a13=this._controller.desiredSize)?_a13:0)>0;){const item=this._queue[0];this._queue.shift();this._controller.enqueue(item)}this._isClosed&&0===this._queue.length&&this._closeController()}}_closeController(){var _a13;if(!this._isControllerClosed){this._isControllerClosed=!0;null==(_a13=this._controller)||_a13.close()}}};_handlers=new Map;SyncParamsHandlerError=class extends LiveSyncError{};SyncParamsFetchError=class extends SyncParamsHandlerError{};SyncParamsNotFoundError=class extends SyncParamsHandlerError{};SyncParamsUpdateError=class extends SyncParamsHandlerError{};currentVersionRange={min:0,max:2400,current:2};selectorOnDemandPull={selector:{type:{$ne:"leaf"}}};DEFAULT_ONE_SHOT_CONNECTIVITY_TIMEOUT_MS=6e4;OneShotConnectivityPreflightTimeoutError=class extends Error{constructor(timeoutMs){super(`Remote connectivity preflight exceeded ${timeoutMs} ms.`);this.name="OneShotConnectivityPreflightTimeoutError"}};LiveSyncCouchDBReplicator=class extends LiveSyncAbstractReplicator{isMobile(){return this.env.services.API.isMobile()}constructor(env){super(env);this.env=env}getInitialSyncParameters(setting){return Promise.resolve({...DEFAULT_SYNC_PARAMETERS,protocolVersion:ProtocolVersions_ADVANCED_E2EE})}async getSyncParameters(setting){try{const downloadedSyncParams=await this.fetchRemoteDocument(setting,DOCID_SYNC_PARAMETERS);if(!downloadedSyncParams)throw new SyncParamsNotFoundError("Sync parameters not found on remote server");return downloadedSyncParams}catch(ex){Logger("Could not retrieve remote sync parameters",LOG_LEVEL_INFO);throw SyncParamsFetchError.fromError(ex)}}async putSyncParameters(setting,params){try{const ret=await this.putRemoteDocument(setting,params);if(ret.ok)return!0;throw new SyncParamsUpdateError(`Could not store remote sync parameters: ${JSON.stringify(ret)}`)}catch(ex){Logger("Could not store remote sync parameters",LOG_LEVEL_INFO);throw SyncParamsUpdateError.fromError(ex)}}async getReplicationPBKDF2Salt(setting,refresh){const server=`${setting.couchDB_URI.replace(/\/+$/,"")}/${setting.couchDB_DBNAME}`,manager=createSyncParamsHanderForServer(server,{put:params=>this.putSyncParameters(setting,params),get:()=>this.getSyncParameters(setting),create:()=>this.getInitialSyncParameters(setting)});return await manager.getPBKDF2Salt(refresh)}async migrate(from,to){Logger(`Database updated from ${from} to ${to}`,LOG_LEVEL_NOTICE);return Promise.resolve(!0)}terminateSync(){if(this.controller){this.controller.abort();this.controller=void 0}}async openReplication(setting,keepAlive,showResult,ignoreCleanLock){if(!await this.initializeDatabaseForReplication())return!1;if(!keepAlive)return this.openOneShotReplication(setting,showResult,!1,"sync",ignoreCleanLock);this.openContinuousReplication(setting,showResult,!1)}replicationActivated(showResult){this.syncStatus="CONNECTED";this.updateInfo();Logger("Replication activated",showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,"sync")}async replicationChangeDetected(e3,showResult,docSentOnStart,docArrivedOnStart){try{if("pull"==e3.direction){await this.env.services.replication.parseSynchroniseResult(e3.change.docs);this.docArrived+=e3.change.docs.length}else this.docSent+=e3.change.docs.length;if(showResult){const maxPullSeq=this.maxPullSeq,maxPushSeq=this.maxPushSeq,lastSyncPullSeq=this.lastSyncPullSeq,lastSyncPushSeq=this.lastSyncPushSeq,pushLast=0==lastSyncPushSeq?"":lastSyncPushSeq>=maxPushSeq?" (LIVE)":` (${maxPushSeq-lastSyncPushSeq})`,pullLast=0==lastSyncPullSeq?"":lastSyncPullSeq>=maxPullSeq?" (LIVE)":` (${maxPullSeq-lastSyncPullSeq})`;Logger(`↑${this.docSent-docSentOnStart}${pushLast} ↓${this.docArrived-docArrivedOnStart}${pullLast}`,LOG_LEVEL_NOTICE,"sync")}this.updateInfo()}catch(ex){Logger("Replication callback error",LOG_LEVEL_NOTICE,"sync");Logger(ex,LOG_LEVEL_VERBOSE)}}replicationCompleted(showResult){this.syncStatus="COMPLETED";this.updateInfo();Logger("Replication completed",showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,showResult?"sync":"");this.terminateSync()}replicationDenied(e3){this.syncStatus="ERRORED";this.updateInfo();this.terminateSync();Logger("Replication denied",LOG_LEVEL_NOTICE,"sync");Logger(e3,LOG_LEVEL_VERBOSE)}replicationErrored(e3){this.syncStatus="ERRORED";this.terminateSync();this.updateInfo();Logger("Replication error",LOG_LEVEL_NOTICE,"sync");Logger(e3,LOG_LEVEL_VERBOSE)}replicationPaused(){this.syncStatus="PAUSED";this.updateInfo();Logger("Replication paused",LOG_LEVEL_VERBOSE,"sync")}async processSync(syncHandler,showResult,docSentOnStart,docArrivedOnStart,syncMode,retrying,reportCancelledAsDone=!0){const controller=new AbortController;this.controller&&this.controller.abort();this.controller=controller;const gen=genReplication(syncHandler,controller.signal);try{for await(const[type,e3]of gen){const releaser=await globalConcurrencyController.tryAcquire(1,REPLICATION_BUSY_TIMEOUT);if(!1===releaser){Logger("Replication stopped for busy.",showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,"sync");return"FAILED"}releaser();switch(type){case"change":if("direction"in e3){"pull"==e3.direction?this.lastSyncPullSeq=Number(`${e3.change.last_seq}`.split("-")[0]):this.lastSyncPushSeq=Number(`${e3.change.last_seq}`.split("-")[0]);await this.replicationChangeDetected(e3,showResult,docSentOnStart,docArrivedOnStart)}else if("pullOnly"==syncMode){this.lastSyncPullSeq=Number(`${e3.last_seq}`.split("-")[0]);await this.replicationChangeDetected({direction:"pull",change:e3},showResult,docSentOnStart,docArrivedOnStart)}else if("pushOnly"==syncMode){this.lastSyncPushSeq=Number(`${e3.last_seq}`.split("-")[0]);this.updateInfo();await this.replicationChangeDetected({direction:"push",change:e3},showResult,docSentOnStart,docArrivedOnStart)}if(retrying&&this.docSent-docSentOnStart+(this.docArrived-docArrivedOnStart)>2*this.originalSetting.batch_size)return"NEED_RESURRECT";break;case"complete":this.replicationCompleted(showResult);return"DONE";case"active":this.replicationActivated(showResult);break;case"denied":this.replicationDenied(e3);return"FAILED";case"error":this.replicationErrored(e3);Logger("Replication stopped.",showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,"sync");if(this.env.services.remote.hadLastPostFailedBySize){if(e3&&413==e3.status){Logger("Something went wrong during synchronisation. Please check the log!",LOG_LEVEL_NOTICE);return"FAILED"}return"NEED_RETRY"}Logger("Replication error",LOG_LEVEL_NOTICE,"sync");Logger(e3,LOG_LEVEL_VERBOSE);return"FAILED";case"paused":this.replicationPaused();break;case"finally":break;default:Logger(`Unexpected synchronization status:${JSON.stringify(e3)}`)}}return reportCancelledAsDone?"DONE":"CANCELLED"}catch(ex){Logger("Unexpected synchronization exception");Logger(ex,LOG_LEVEL_VERBOSE);return"FAILED"}finally{this.terminateSync();this.controller=void 0}}getEmptyMaxEntry(remoteID){return{_id:`_local/max_seq_on_chunk-${remoteID}`,maxSeq:0,remoteID,seqStatusMap:{},_rev:void 0}}async getLastTransferredSeqOfChunks(localDB,remoteID){const prevMax={_id:`_local/max_seq_on_chunk-${remoteID}`,maxSeq:0,remoteID,seqStatusMap:{},_rev:void 0},previous_max_seq_on_chunk=await wrapException(()=>localDB.get(prevMax._id));return previous_max_seq_on_chunk instanceof Error?prevMax:previous_max_seq_on_chunk}async updateMaxTransferredSeqOnChunks(localDB,remoteID,seqStatusMap){const newMax={_id:"_local/max_seq_on_chunk",maxSeq:0,remoteID,seqStatusMap,_rev:void 0},seqs=Object.keys(seqStatusMap).map(e3=>Number(e3));let maxSeq=0;for(const seq of seqs){if(!seqStatusMap[seq])break;maxSeq=seq}Logger(`Updating max seq on chunk to ${maxSeq}`,LOG_LEVEL_VERBOSE);newMax.maxSeq=maxSeq;const previous_max_seq_on_chunk=await wrapException(()=>localDB.get(newMax._id));if(previous_max_seq_on_chunk instanceof Error)delete newMax._rev;else{newMax._rev=previous_max_seq_on_chunk._rev;newMax.seqStatusMap={...previous_max_seq_on_chunk.seqStatusMap,...seqStatusMap}}await wrapException(()=>localDB.put(newMax));return newMax}async sendChunks(setting,remoteDB,showResult,fromSeq){var _a13;const trench=new Trench(this.env.services.keyValueDB.openSimpleStore("sc-"),!1);await trench.eraseAllEphemerals();if(!remoteDB){const d4=await this.connectRemoteCouchDBWithSetting(setting,this.isMobile(),!0);if("string"==typeof d4){Logger(this.translate("liveSyncReplicator.couldNotConnectToRemoteDb",{d:d4}),showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,"fetch");return!1}return await this.withRemoteConnection(d4,async db=>this.sendChunks(setting,db,showResult,fromSeq))}const connectivity=await this.checkReplicationConnectivity(setting,!1,!1,!1,!1);!1!==connectivity&&await this.closeRemoteConnection(connectivity);Logger("Bulk sending chunks to remote database...",showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,"fetch");const remoteMilestone=await remoteDB.get(MILESTONE_DOCID),remoteID=null!=(_a13=null==remoteMilestone?void 0:remoteMilestone.created)?_a13:0,localDB=this.rawDatabase,te5=new TextEncoder;Logger(this.translate("liveSyncReplicator.checkingLastSyncPoint"),showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,"fetch");this.syncStatus="CONNECTED";const prev=await this.getLastTransferredSeqOfChunks(localDB,remoteID),seq=null!=fromSeq?fromSeq:prev.maxSeq,localScannedDocs=[],sentMap={},diffChunks=localDB.changes({since:seq,live:!1,include_docs:!0,return_docs:!1,selector:{type:"leaf"}}).on("change",e3=>{const numSeq=Number(e3.seq);prev.seqStatusMap[numSeq]||localScannedDocs.push({id:e3.id,seq:Number(e3.seq)})});await diffChunks;localScannedDocs.sort((a2,b3)=>a2.seq-b3.seq);const idSeqMap=Object.fromEntries(localScannedDocs.map(e3=>[e3.id,e3.seq]));for(const checkDocs of arrayToChunkedArray(localScannedDocs,250)){const remoteDocs=await remoteDB.allDocs({keys:checkDocs.map(e3=>e3.id),include_docs:!1}),remoteDocMap=Object.fromEntries(remoteDocs.rows.map(e3=>[e3.key,"error"in e3?e3.error:e3.value])),sendDocs=checkDocs.filter(e3=>"not_found"==remoteDocMap[e3.id]),sentDocs=checkDocs.filter(e3=>"not_found"!=remoteDocMap[e3.id]);sendDocs.forEach(e3=>sentMap[e3.seq]=!1);sentDocs.forEach(e3=>sentMap[e3.seq]=!0);const sendDocsMap=Object.fromEntries(sendDocs.map(e3=>[e3.id,e3.seq]));if(sendDocs.length>0){const localDocs=await localDB.allDocs({keys:sendDocs.map(e3=>e3.id),include_docs:!0});await trench.queue("send-chunks",localDocs.rows.filter(e3=>"id"in e3).map(e3=>({seq:sendDocsMap[e3.id],doc:e3.doc,id:e3.id})))}}let bulkDocs2=[],bulkDocsSizeBytes=0,bulkDocsSizeCount=0,maxSeq=0;const maxBatchSizeBytes=1024*setting.sendChunksBulkMaxSize*1024,semaphore=Semaphore(4);let sendingDocs=0,sentDocsCount=0;const sendChunks=async(bulkDocs22,bulkDocsSize,seq2)=>{Logger(`Sending ${bulkDocs22.length} (${bulkDocsSize} => ${sizeToHumanReadable(bulkDocsSize)} in plain) chunks to remote database...`,LOG_LEVEL_VERBOSE);const releaser=await semaphore.acquire(1);sendingDocs+=bulkDocs22.length;Logger(`↑ Uploading chunks \n${sendingDocs}/(${sentDocsCount} done)`,showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,"send");try{const uploadBulkDocTasks=bulkDocs22.map(e3=>preprocessOutgoing(e3)),uploadBulkDocs=await Promise.all(uploadBulkDocTasks);await remoteDB.bulkDocs(uploadBulkDocs,{new_edits:!1});uploadBulkDocs.forEach(e3=>sentMap[idSeqMap[e3._id]]=!0);await this.updateMaxTransferredSeqOnChunks(localDB,remoteID,sentMap);sentDocsCount+=bulkDocs22.length;Logger(`↑ Uploading chunks \n${sendingDocs}/(${sentDocsCount} done)`,showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,"send")}catch(ex){Logger("Bulk sending failed.",showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,"send");Logger(ex,LOG_LEVEL_VERBOSE);return!1}finally{releaser()}return!0},tasks3=[];for(;;){const nowSendChunks=await trench.dequeue("send-chunks");if(!nowSendChunks||0==nowSendChunks.length)break;for(const chunk of nowSendChunks){const jsonLength=te5.encode(JSON.stringify(chunk.doc)).byteLength+32;if((bulkDocsSizeBytes+jsonLength>maxBatchSizeBytes||bulkDocsSizeCount+1>200)&&bulkDocs2.length>0){tasks3.push(sendChunks([...bulkDocs2],bulkDocsSizeBytes));bulkDocs2=[];bulkDocsSizeBytes=0;bulkDocsSizeCount=0}bulkDocs2.push(chunk.doc);maxSeq=chunk.seq;bulkDocsSizeBytes+=jsonLength;bulkDocsSizeCount+=1}bulkDocs2.length>0&&tasks3.push(sendChunks([...bulkDocs2],bulkDocsSizeBytes));const results=await Promise.all(tasks3.map(async e3=>{try{await e3}catch(ex){Logger("Bulk sending failed.",showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,"send");Logger(ex,LOG_LEVEL_VERBOSE);return!1}}));if(results.some(e3=>!1===e3))return!1}return!0}async openOneShotReplication(setting,showResult,retrying,syncMode,ignoreCleanLock=!1){if(!1===await this.ensurePBKDF2Salt(setting,showResult,!retrying))return!1;const next2=await shareRunningResult("oneShotReplication",async()=>{if(this.controller){Logger(this.translate("liveSyncReplicator.replicationInProgress"),showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,"sync");return!1}const localDB=this.rawDatabase;Logger(this.translate("liveSyncReplicator.oneShotSyncBegin",{syncMode}));const ret=await this.checkOneShotReplicationConnectivity(setting,retrying,showResult,ignoreCleanLock);if(!1===ret){Logger(this.translate("liveSyncReplicator.couldNotConnectToServer"),showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,"sync");return!1}const{db,syncOptionBase}=ret;try{this.maxPullSeq=Number(`${ret.info.update_seq}`.split("-")[0]);this.maxPushSeq=Number(`${(await localDB.info()).update_seq}`.split("-")[0]);showResult&&Logger(this.translate("liveSyncReplicator.checkingLastSyncPoint"),LOG_LEVEL_NOTICE,"sync");this.syncStatus="STARTED";this.updateInfo();const docArrivedOnStart=this.docArrived,docSentOnStart=this.docSent;retrying||(this.originalSetting=setting);this.terminateSync();const syncHandler="sync"==syncMode?localDB.sync(db,{...syncOptionBase}):"pullOnly"==syncMode?localDB.replicate.from(db,{...syncOptionBase,...setting.readChunksOnline?selectorOnDemandPull:{}}):"pushOnly"==syncMode?localDB.replicate.to(db,{...syncOptionBase}):void 0,syncResult=await this.processSync(syncHandler,showResult,docSentOnStart,docArrivedOnStart,syncMode,retrying,!1);if("DONE"==syncResult)return!0;if("CANCELLED"==syncResult)return!1;if("FAILED"==syncResult)return!1;if("NEED_RESURRECT"==syncResult){this.terminateSync();return async()=>await this.openOneShotReplication(this.originalSetting,showResult,!1,syncMode,ignoreCleanLock)}if("NEED_RETRY"==syncResult){const tempSetting=JSON.parse(JSON.stringify(setting));tempSetting.batch_size=Math.ceil(tempSetting.batch_size/2)+2;tempSetting.batches_limit=Math.ceil(tempSetting.batches_limit/2)+2;if(tempSetting.batch_size<=5&&tempSetting.batches_limit<=5){Logger(this.translate("liveSyncReplicator.cantReplicateLowerValue"),showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO);return!1}Logger(this.translate("liveSyncReplicator.retryLowerBatchSize",{batch_size:tempSetting.batch_size.toString(),batches_limit:tempSetting.batches_limit.toString()}),showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO);return async()=>await this.openOneShotReplication(tempSetting,showResult,!0,syncMode,ignoreCleanLock)}return!1}finally{await this.closeRemoteConnection(ret)}});return"boolean"==typeof next2?next2:await next2()}async checkOneShotReplicationConnectivity(setting,skipCheck,showResult,ignoreCleanLock){var _a13;if(setting.useRequestAPI)return await this.checkReplicationConnectivity(setting,!1,skipCheck,showResult,ignoreCleanLock);const timeoutMs=null!=(_a13=this.env.oneShotConnectivityTimeoutMs)?_a13:DEFAULT_ONE_SHOT_CONNECTIVITY_TIMEOUT_MS,controller=new AbortController,timeout=compatGlobal.setTimeout(()=>controller.abort(new OneShotConnectivityPreflightTimeoutError(timeoutMs)),timeoutMs);try{return await this.checkReplicationConnectivity(setting,!1,skipCheck,showResult,ignoreCleanLock,{signal:controller.signal,allowNativeFallback:!1})}finally{compatGlobal.clearTimeout(timeout)}}async closeRemoteConnection(connection){try{await connection.close()}catch(ex){Logger("Failed to close remote database.",LOG_LEVEL_INFO,"sync");Logger(ex,LOG_LEVEL_VERBOSE,"sync")}}async withRemoteConnection(connection,task){try{return await task(connection.db)}finally{await this.closeRemoteConnection(connection)}}replicateAllToServer(setting,showingNotice){return this.openOneShotReplication(setting,null!=showingNotice&&showingNotice,!1,"pushOnly")}replicateAllFromServer(setting,showingNotice){return this.openOneShotReplication(setting,null!=showingNotice&&showingNotice,!1,"pullOnly")}reportConnectivityPreflightTimeout(connectionOptions,showResult,error){var _a13;if(!((null==(_a13=null==connectionOptions?void 0:connectionOptions.signal)?void 0:_a13.aborted)&&connectionOptions.signal.reason instanceof OneShotConnectivityPreflightTimeoutError))return!1;Logger("The remote connectivity check timed out.",showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,"sync");void 0!==error&&Logger(error,LOG_LEVEL_VERBOSE,"sync");return!0}async checkReplicationConnectivity(setting,keepAlive,skipCheck,showResult,ignoreCleanLock=!1,connectionOptions){if(""!=setting.versionUpFlash){Logger(this.translate("Replicator.Message.VersionUpFlash"),LOG_LEVEL_NOTICE);return!1}const uri=setting.couchDB_URI.replace(/\/+$/,"")+(""==setting.couchDB_DBNAME?"":"/"+setting.couchDB_DBNAME);if(this.controller){Logger("Another replication running.");return!1}let dbRet;try{dbRet=await this.connectRemoteCouchDBWithSetting(setting,this.isMobile(),!0,!1,connectionOptions)}catch(ex){if(this.reportConnectivityPreflightTimeout(connectionOptions,showResult,ex))return!1;throw ex}if("string"==typeof dbRet){if(this.reportConnectivityPreflightTimeout(connectionOptions,showResult))return!1;Logger(this.translate("liveSyncReplicator.couldNotConnectToURI",{uri,dbRet}),showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO);return!1}let ownershipTransferred=!1;try{if(!skipCheck){if(!await checkRemoteVersion(dbRet.db,this.migrate.bind(this),VER)){Logger(this.translate("liveSyncReplicator.remoteDbCorrupted"),LOG_LEVEL_NOTICE);return!1}this.remoteCleaned=!1;this.remoteLocked=!1;this.remoteLockedAndDeviceNotAccepted=!1;this.tweakSettingsMismatched=!1;this.preferredTweakValue=void 0;const progress=`${dbRet.info.update_seq}`,info3={app_version:this.env.services.API.getAppVersion(),plugin_version:this.env.services.API.getPluginVersion(),vault_name:this.env.services.vault.vaultName(),device_name:this.env.services.vault.getVaultName(),progress},ensure=await ensureDatabaseIsCompatible(dbRet.db,setting,this.nodeid,currentVersionRange,info3);if("INCOMPATIBLE"==ensure){Logger("The remote database has no compatibility with the running version. Please upgrade the plugin.",LOG_LEVEL_NOTICE);return!1}if("NODE_LOCKED"==ensure){Logger("The remote database has been rebuilt or corrupted since we have synchronized last time. Fetch rebuilt DB, explicit unlocking or chunk clean-up is required.",LOG_LEVEL_NOTICE);this.remoteLockedAndDeviceNotAccepted=!0;this.remoteLocked=!0;return!1}if("LOCKED"==ensure)this.remoteLocked=!0;else if("NODE_CLEANED"==ensure){if(!ignoreCleanLock){Logger("The remote database has been cleaned up. Fetch rebuilt DB, explicit unlocking or chunk clean-up is required.",LOG_LEVEL_NOTICE);this.remoteLockedAndDeviceNotAccepted=!0;this.remoteLocked=!0;this.remoteCleaned=!0;return!1}this.remoteLocked=!0}else if("OK"==ensure);else if("MISMATCHED"==ensure[0]){Logger(this.translate("liveSyncReplicator.mismatchedTweakDetected"),LOG_LEVEL_NOTICE);this.tweakSettingsMismatched=!0;this.preferredTweakValue=ensure[1];return!1}}const syncOptionBase={batches_limit:setting.batches_limit,batch_size:setting.batch_size,push:{}};setting.readChunksOnline&&(syncOptionBase.pull={...selectorOnDemandPull});if(this.reportConnectivityPreflightTimeout(connectionOptions,showResult))return!1;const syncOption=keepAlive?{live:!0,retry:!0,heartbeat:!setting.useTimeouts&&3e4,...syncOptionBase}:{...syncOptionBase},connection={...dbRet,syncOptionBase,syncOption};ownershipTransferred=!0;return connection}catch(ex){if(this.reportConnectivityPreflightTimeout(connectionOptions,showResult,ex))return!1;throw ex}finally{ownershipTransferred||await this.closeRemoteConnection(dbRet)}}async openContinuousReplication(setting,showResult,retrying){const next2=await shareRunningResult("continuousReplication",async()=>{if(this.controller){Logger(this.translate("liveSyncReplicator.replicationInProgress"),showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO);return!1}const localDB=this.rawDatabase;Logger(this.translate("liveSyncReplicator.beforeLiveSync"));const caughtUp=await this.env.services.replicator.runFiniteReplicationActivity(()=>this.openOneShotReplication(setting,showResult,!1,"pullOnly"),{label:"replication"});if(caughtUp){Logger(this.translate("liveSyncReplicator.liveSyncBegin"));const ret=await this.checkReplicationConnectivity(setting,!0,!0,showResult);if(!1===ret){Logger(this.translate("liveSyncReplicator.couldNotConnectToServer"),showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO);return!1}showResult&&Logger(this.translate("liveSyncReplicator.checkingLastSyncPoint"),LOG_LEVEL_NOTICE,"sync");const{db,syncOption}=ret;try{this.syncStatus="STARTED";this.maxPullSeq=Number(`${ret.info.update_seq}`.split("-")[0]);this.maxPushSeq=Number(`${(await localDB.info()).update_seq}`.split("-")[0]);this.updateInfo();const docArrivedOnStart=this.docArrived,docSentOnStart=this.docSent;retrying||(this.originalSetting=setting);this.terminateSync();const syncHandler=localDB.sync(db,{...syncOption}),syncMode="sync",syncResult=await this.processSync(syncHandler,showResult,docSentOnStart,docArrivedOnStart,syncMode,retrying);if("DONE"==syncResult)return!0;if("FAILED"==syncResult)return!1;if("NEED_RESURRECT"==syncResult){this.terminateSync();return async()=>await this.openContinuousReplication(this.originalSetting,showResult,!1)}if("NEED_RETRY"==syncResult){const tempSetting=JSON.parse(JSON.stringify(setting));tempSetting.batch_size=Math.ceil(tempSetting.batch_size/2)+2;tempSetting.batches_limit=Math.ceil(tempSetting.batches_limit/2)+2;if(tempSetting.batch_size<=5&&tempSetting.batches_limit<=5){Logger(this.translate("liveSyncReplicator.cantReplicateLowerValue"),showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO);return!1}Logger(this.translate("liveSyncReplicator.retryLowerBatchSize",{batch_size:tempSetting.batch_size.toString(),batches_limit:tempSetting.batches_limit.toString()}),showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO);return async()=>await this.openContinuousReplication(tempSetting,showResult,!0)}}finally{await this.closeRemoteConnection(ret)}}return!1});return"boolean"==typeof next2?next2:await next2()}closeReplication(){if(this.controller){this.controller.abort();this.controller=void 0;this.syncStatus="CLOSED";Logger(this.translate("liveSyncReplicator.replicationClosed"));this.updateInfo()}}async tryResetRemoteDatabase(setting){this.closeReplication();const con=await this.connectRemoteCouchDBWithSetting(setting,this.isMobile(),!0);if("string"!=typeof con){try{try{await con.db.destroy();Logger(this.translate("liveSyncReplicator.remoteDbDestroyed"),LOG_LEVEL_NOTICE);await this.tryCreateRemoteDatabase(setting)}catch(ex){Logger(this.translate("liveSyncReplicator.remoteDbDestroyError"),LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_NOTICE)}}finally{await this.closeRemoteConnection(con)}clearHandlers();await this.ensurePBKDF2Salt(setting,!0,!1)}}async tryCreateRemoteDatabase(setting){this.closeReplication();const con2=await this.connectRemoteCouchDBWithSetting(setting,this.isMobile(),!0);if("string"!=typeof con2){await this.closeRemoteConnection(con2);clearHandlers();await this.ensurePBKDF2Salt(setting,!0,!1);Logger(this.translate("liveSyncReplicator.remoteDbCreatedOrConnected"),LOG_LEVEL_NOTICE)}}async markRemoteLocked(setting,locked,lockByClean){const uri=setting.couchDB_URI.replace(/\/+$/,"")+(""==setting.couchDB_DBNAME?"":"/"+setting.couchDB_DBNAME),dbRet=await this.connectRemoteCouchDBWithSetting(setting,this.isMobile(),!0);"string"!=typeof dbRet?await this.withRemoteConnection(dbRet,async db=>{if(!await checkRemoteVersion(db,this.migrate.bind(this),VER)){Logger(this.translate("liveSyncReplicator.remoteDbCorrupted"),LOG_LEVEL_NOTICE);return}const defInitPoint={_id:MILESTONE_DOCID,type:"milestoneinfo",created:Date.now(),locked,cleaned:lockByClean,accepted_nodes:[this.nodeid],node_chunk_info:{[this.nodeid]:currentVersionRange},node_info:{},tweak_values:{}},remoteMilestone={...defInitPoint,...await resolveWithIgnoreKnownError(db.get(MILESTONE_DOCID),defInitPoint)};remoteMilestone.node_chunk_info={...defInitPoint.node_chunk_info,...remoteMilestone.node_chunk_info};remoteMilestone.accepted_nodes=[this.nodeid];remoteMilestone.locked=locked;remoteMilestone.cleaned=remoteMilestone.cleaned||lockByClean;Logger(locked?this.translate("liveSyncReplicator.lockRemoteDb"):this.translate("liveSyncReplicator.unlockRemoteDb"),LOG_LEVEL_NOTICE);await db.put(remoteMilestone)}):Logger(this.translate("liveSyncReplicator.couldNotConnectToURI",{uri,dbRet}),LOG_LEVEL_NOTICE)}async markRemoteResolved(setting){const uri=setting.couchDB_URI.replace(/\/+$/,"")+(""==setting.couchDB_DBNAME?"":"/"+setting.couchDB_DBNAME),dbRet=await this.connectRemoteCouchDBWithSetting(setting,this.isMobile(),!0);"string"!=typeof dbRet?await this.withRemoteConnection(dbRet,async db=>{if(!await checkRemoteVersion(db,this.migrate.bind(this),VER)){Logger(this.translate("liveSyncReplicator.remoteDbCorrupted"),LOG_LEVEL_NOTICE);return}const defInitPoint={_id:MILESTONE_DOCID,type:"milestoneinfo",created:Date.now(),locked:!1,accepted_nodes:[this.nodeid],node_info:{},node_chunk_info:{[this.nodeid]:currentVersionRange},tweak_values:{}},remoteMilestone={...defInitPoint,...await resolveWithIgnoreKnownError(db.get(MILESTONE_DOCID),defInitPoint)};remoteMilestone.node_chunk_info={...defInitPoint.node_chunk_info,...remoteMilestone.node_chunk_info};remoteMilestone.accepted_nodes=Array.from(new Set([...remoteMilestone.accepted_nodes,this.nodeid]));Logger(this.translate("liveSyncReplicator.markDeviceResolved"),LOG_LEVEL_NOTICE);const result=await db.put(remoteMilestone);result.ok?Logger(this.translate("liveSyncReplicator.remoteDbMarkedResolved"),LOG_LEVEL_VERBOSE):Logger(this.translate("liveSyncReplicator.couldNotMarkResolveRemoteDb"),LOG_LEVEL_NOTICE)}):Logger(this.translate("liveSyncReplicator.couldNotConnectToURI",{uri,dbRet}),LOG_LEVEL_NOTICE)}connectRemoteCouchDBWithSetting(settings,isMobile,performSetup=!1,skipInfo=!1,connectionOptions){if(settings.encrypt&&""==settings.passphrase&&!settings.permitEmptyPassphrase)return"Empty passphrases cannot be used without explicit permission";const customHeaders=parseHeaderValues(settings.couchDB_CustomHeaders),auth=settings.useJWT?{jwtAlgorithm:settings.jwtAlgorithm,jwtKey:settings.jwtKey,jwtExpDuration:settings.jwtExpDuration,jwtKid:settings.jwtKid,jwtSub:settings.jwtSub,type:"jwt"}:{username:settings.couchDB_USER,password:settings.couchDB_PASSWORD,type:"basic"};return this.env.services.remote.connect(settings.couchDB_URI.replace(/\/+$/,"")+(""==settings.couchDB_DBNAME?"":"/"+settings.couchDB_DBNAME),auth,settings.disableRequestURI||isMobile,!!settings.encrypt&&settings.passphrase,settings.useDynamicIterationCount,performSetup,skipInfo,settings.enableCompression,customHeaders,settings.useRequestAPI,async()=>await this.getReplicationPBKDF2Salt(settings),connectionOptions)}async openOwnedConnection(settings,performSetup=!1){const ret=await this.connectRemoteCouchDBWithSetting(settings,this.isMobile(),performSetup,!0);if("string"==typeof ret)throw new Error(`${this.translate("liveSyncReplicator.couldNotConnectToServer")}:${ret}`);return ret}async _ensureConnection(settings,performSetup=!1){return(await this.openOwnedConnection(settings,performSetup)).db}async fetchRemoteDocument(settings,id,db){const connection=void 0===db?await this.openOwnedConnection(settings):void 0,connDB=null!=db?db:connection.db;try{return await connDB.get(id)}catch(ex){if(ex&&404==ex.status)return!1;throw ex}finally{connection&&await this.closeRemoteConnection(connection)}}async putRemoteDocument(settings,doc,db){const connection=void 0===db?await this.openOwnedConnection(settings,!0):void 0,connDB=null!=db?db:connection.db;try{return await connDB.put(doc)}finally{connection&&await this.closeRemoteConnection(connection)}}async fetchRemoteChunks(missingChunks,showResult){const ret=await this.connectRemoteCouchDBWithSetting(this.currentSettings,this.isMobile(),!1,!0);if("string"==typeof ret){Logger(`${this.translate("liveSyncReplicator.couldNotConnectToServer")} ${ret} `,showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,"fetch");return!1}return await this.withRemoteConnection(ret,async db=>{const remoteChunks=await db.allDocs({keys:missingChunks,include_docs:!0}),errorRows=remoteChunks.rows.filter(e3=>"error"in e3);if(errorRows.length>0){Logger("Some requested chunks were not found in the remote database.",showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,"fetch");Logger(`Requested chunks: ${missingChunks.join(",")}`,LOG_LEVEL_VERBOSE);Logger(`Error chunks: ${errorRows.map(e3=>e3.key).join(",")}`,LOG_LEVEL_VERBOSE)}return remoteChunks.rows.filter(e3=>!("error"in e3)).map(e3=>e3.doc).filter(e3=>void 0!==e3)})}async tryConnectRemote(setting,showResult=!0){const db=await this.connectRemoteCouchDBWithSetting(setting,this.isMobile(),!0);if("string"==typeof db){Logger(this.translate("liveSyncReplicator.couldNotConnectTo",{uri:setting.couchDB_URI,name:setting.couchDB_DBNAME,db}),LOG_LEVEL_NOTICE);return!1}return await this.withRemoteConnection(db,async()=>{Logger(`Connected to ${db.info.db_name} successfully`,LOG_LEVEL_NOTICE);return!0})}async resetRemoteTweakSettings(setting){const uri=setting.couchDB_URI.replace(/\/+$/,"")+(""==setting.couchDB_DBNAME?"":"/"+setting.couchDB_DBNAME),dbRet=await this.connectRemoteCouchDBWithSetting(setting,this.isMobile(),!0);"string"!=typeof dbRet?await this.withRemoteConnection(dbRet,async db=>{if(await checkRemoteVersion(db,this.migrate.bind(this),VER))try{const remoteMilestone=await db.get(MILESTONE_DOCID);remoteMilestone.tweak_values={};await db.put(remoteMilestone);Logger("tweak values on the remote database have been cleared",LOG_LEVEL_VERBOSE)}catch(ex){Logger("Could not retrieve remote milestone",LOG_LEVEL_NOTICE);throw ex}else Logger(this.translate("liveSyncReplicator.remoteDbCorrupted"),LOG_LEVEL_NOTICE)}):Logger(this.translate("liveSyncReplicator.couldNotConnectToURI",{uri,dbRet}),LOG_LEVEL_NOTICE)}async setPreferredRemoteTweakSettings(setting){const uri=setting.couchDB_URI.replace(/\/+$/,"")+(""==setting.couchDB_DBNAME?"":"/"+setting.couchDB_DBNAME),dbRet=await this.connectRemoteCouchDBWithSetting(setting,this.isMobile(),!0);"string"!=typeof dbRet?await this.withRemoteConnection(dbRet,async db=>{if(await checkRemoteVersion(db,this.migrate.bind(this),VER))try{const remoteMilestone=await db.get(MILESTONE_DOCID);remoteMilestone.tweak_values[DEVICE_ID_PREFERRED]=extractObject(TweakValuesTemplate,{...setting});await db.put(remoteMilestone);Logger("Preferred tweak values has been registered",LOG_LEVEL_VERBOSE)}catch(ex){Logger("Could not retrieve remote milestone",LOG_LEVEL_NOTICE);throw ex}else Logger(this.translate("liveSyncReplicator.remoteDbCorrupted"),LOG_LEVEL_NOTICE)}):Logger(this.translate("liveSyncReplicator.couldNotConnectToURI",{uri,dbRet}),LOG_LEVEL_NOTICE)}async getRemotePreferredTweakValues(setting){const uri=setting.couchDB_URI.replace(/\/+$/,"")+(""==setting.couchDB_DBNAME?"":"/"+setting.couchDB_DBNAME);let dbRet;try{dbRet=await this.connectRemoteCouchDBWithSetting(setting,this.isMobile(),!0)}catch(ex){Logger("Could not connect to the remote database",LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_VERBOSE);return{status:RemotePreferredTweakStatuses_UNAVAILABLE,error:ex}}if("string"==typeof dbRet){Logger(this.translate("liveSyncReplicator.couldNotConnectToURI",{uri,dbRet}),LOG_LEVEL_NOTICE);return{status:RemotePreferredTweakStatuses_UNAVAILABLE,error:new Error(dbRet)}}return await this.withRemoteConnection(dbRet,async db=>{var _a13;try{if(!await checkRemoteVersion(db,this.migrate.bind(this),VER)){const error=new Error("The remote database version is not compatible");Logger(this.translate("liveSyncReplicator.remoteDbCorrupted"),LOG_LEVEL_NOTICE);return{status:RemotePreferredTweakStatuses_UNAVAILABLE,error}}}catch(ex){Logger("Could not check the remote database version",LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_VERBOSE);return{status:RemotePreferredTweakStatuses_UNAVAILABLE,error:ex}}try{const remoteMilestone=await db.get(MILESTONE_DOCID);if(!remoteMilestone)return{status:RemotePreferredTweakStatuses_NOT_CONFIGURED,reason:RemotePreferredTweakNotConfiguredReasons_MILESTONE_MISSING};const preferred=null==(_a13=remoteMilestone.tweak_values)?void 0:_a13[DEVICE_ID_PREFERRED];return preferred?{status:RemotePreferredTweakStatuses_AVAILABLE,values:preferred}:{status:RemotePreferredTweakStatuses_NOT_CONFIGURED,reason:RemotePreferredTweakNotConfiguredReasons_PREFERRED_VALUES_MISSING}}catch(ex){if(isErrorOfMissingDoc(ex))return{status:RemotePreferredTweakStatuses_NOT_CONFIGURED,reason:RemotePreferredTweakNotConfiguredReasons_MILESTONE_MISSING};Logger("Could not retrieve remote milestone",LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_VERBOSE);return{status:RemotePreferredTweakStatuses_UNAVAILABLE,error:ex}}})}async compactRemote(setting){const uri=setting.couchDB_URI.replace(/\/+$/,"")+(""==setting.couchDB_DBNAME?"":"/"+setting.couchDB_DBNAME),dbRet=await this.connectRemoteCouchDBWithSetting(setting,this.isMobile(),!0);if("string"==typeof dbRet){Logger(this.translate("liveSyncReplicator.couldNotConnectToURI",{uri,dbRet}),LOG_LEVEL_NOTICE);return!1}return await this.withRemoteConnection(dbRet,async db=>(await db.compact({interval:1e3})).ok)}async getRemoteStatus(setting){const dbRet=await this.connectRemoteCouchDBWithSetting(setting,this.isMobile(),!0);if("string"==typeof dbRet){const uri=setting.couchDB_URI.replace(/\/+$/,"")+(""==setting.couchDB_DBNAME?"":"/"+setting.couchDB_DBNAME);Logger(this.translate("liveSyncReplicator.couldNotConnectToURI",{uri,dbRet}),LOG_LEVEL_NOTICE);return!1}return await this.withRemoteConnection(dbRet,async db=>{var _a13;const info3=await db.info();return{...info3,estimatedSize:(null==(_a13=null==info3?void 0:info3.sizes)?void 0:_a13.file)||0}})}async countCompromisedChunks(setting=this.currentSettings){const dbRet=await this.connectRemoteCouchDBWithSetting(setting,this.isMobile(),!0);if("string"==typeof dbRet){const uri=setting.couchDB_URI.replace(/\/+$/,"")+(""==setting.couchDB_DBNAME?"":"/"+setting.couchDB_DBNAME);Logger(this.translate("liveSyncReplicator.couldNotConnectToURI",{uri,dbRet}),LOG_LEVEL_NOTICE);return!1}return await this.withRemoteConnection(dbRet,countCompromisedChunks)}async getConnectedDeviceList(setting=this.currentSettings){const dbRet=await this.connectRemoteCouchDBWithSetting(setting,this.isMobile(),!0);if("string"==typeof dbRet){const uri=setting.couchDB_URI.replace(/\/+$/,"")+(""==setting.couchDB_DBNAME?"":"/"+setting.couchDB_DBNAME);Logger(this.translate("liveSyncReplicator.couldNotConnectToURI",{uri,dbRet}),LOG_LEVEL_NOTICE);return!1}return await this.withRemoteConnection(dbRet,async db=>{const milestoneDoc=await db.get(MILESTONE_DOCID);if(!milestoneDoc){Logger("Could not retrieve remote milestone",LOG_LEVEL_NOTICE);return!1}const nodeInfo=milestoneDoc.node_info,acceptedNodes=milestoneDoc.accepted_nodes||[];return{node_info:nodeInfo,accepted_nodes:acceptedNodes}})}};OnDialogSettingsDefault={configPassphrase:"",preset:"",syncMode:"ONEVENTS",dummy:0,deviceAndVaultName:""};({...DEFAULT_SETTINGS,...OnDialogSettingsDefault});SettingInformation={liveSync:{name:"Sync Mode"},couchDB_URI:{name:"Server URI",placeHolder:"https://........"},couchDB_USER:{name:"Username",desc:"username"},couchDB_PASSWORD:{name:"Password",desc:"password",isHidden:!0},couchDB_DBNAME:{name:"Database Name"},passphrase:{name:"Passphrase",desc:"Encryption passphrase. If changed, you should overwrite the server's database with the new (encrypted) files.",isHidden:!0},showStatusOnEditor:{name:"Show status inside the editor",desc:"Requires restart of Obsidian."},showOnlyIconsOnEditor:{name:"Show status as icons only"},showStatusOnStatusbar:{name:"Show status on the status bar",desc:"Requires restart of Obsidian."},lessInformationInLog:{name:"Show only notifications",desc:"Disables logging, only shows notifications. Please disable if you report an issue."},showVerboseLog:{name:"Verbose Log",desc:"Show verbose log. Please enable if you report an issue."},hashCacheMaxCount:{name:"Memory cache size (by total items)"},hashCacheMaxAmount:{name:"Memory cache size (by total characters)",desc:"(Mega chars)"},writeCredentialsForSettingSync:{name:"Write credentials in the file",desc:"(Not recommended) If set, credentials will be stored in the file."},notifyAllSettingSyncFile:{name:"Notify all setting files"},configPassphrase:{name:"Passphrase of sensitive configuration items",desc:"This passphrase will not be copied to another device. It will be set to `Default` until you configure it again."},configPassphraseStore:{name:"Encrypting sensitive configuration items"},syncOnSave:{name:"Sync on Save",desc:"Starts synchronisation when a file is saved."},syncOnEditorSave:{name:"Sync on Editor Save",desc:"When you save a file in the editor, start a sync automatically"},keepReplicationActiveInBackground:{name:"Keep replication active in the background",desc:"Desktop only; uses more battery and network."},allowSleepDuringSynchronisation:{name:"Allow sleep during synchronisation",desc:"Allow the operating system to sleep while finite synchronisation operations are in progress."},allowSleepDuringSynchronisationOnDesktop:{name:"Allow sleep during synchronisation on the desktop",desc:"Desktop only. Allow sleep on this device even when the general option is disabled."},syncOnFileOpen:{name:"Sync on File Open",desc:"Forces the file to be synced when opened."},syncOnStart:{name:"Sync on Startup",desc:"Automatically Sync all files when opening Obsidian."},syncAfterMerge:{name:"Sync after merging file",desc:"Sync automatically after merging files"},trashInsteadDelete:{name:"Use the trash bin",desc:"Move remotely deleted files to the trash, instead of deleting. (This setting is ineffective from Obsidian v1.7.2 onwards, as deletion always respects your Obsidian preferences.)"},doNotDeleteFolder:{name:"Keep empty folder",desc:"Should we keep folders that don't have any files inside?"},resolveConflictsByNewerFile:{name:"(BETA) Always overwrite with a newer file",desc:"Testing only - Resolve file conflicts by syncing newer copies of the file, this can overwrite modified files. Be Warned."},checkConflictOnlyOnOpen:{name:"Delay conflict resolution of inactive files",desc:"Should we only check for conflicts when a file is opened?"},showMergeDialogOnlyOnActive:{name:"Delay merge conflict prompt for inactive files.",desc:"Should we prompt you about conflicting files when a file is opened?"},disableMarkdownAutoMerge:{name:"Always prompt merge conflicts",desc:"Should we prompt you for every single merge, even if we can safely merge automatcially?"},writeDocumentsIfConflicted:{name:"Apply Latest Change if Conflicting",desc:"Enable this option to automatically apply the most recent change to documents even when it conflicts"},syncInternalFilesInterval:{name:"Scan hidden files periodically",desc:"Seconds, 0 to disable"},batchSave:{name:"Batch database update",desc:"Reducing the frequency with which on-disk changes are reflected into the DB"},readChunksOnline:{name:"Fetch chunks on demand",desc:"(ex. Read chunks online) If this option is enabled, LiveSync reads chunks online directly instead of replicating them locally. Increasing Custom chunk size is recommended."},syncMaxSizeInMB:{name:"Maximum file size",desc:"(MB) If this is set, changes to local and remote files that are larger than this will be skipped. If the file becomes smaller again, a newer one will be used."},useIgnoreFiles:{name:"(Beta) Use ignore files",desc:"If this is set, changes to local files which are matched by the ignore files will be skipped. Remote changes are determined using local ignore files."},ignoreFiles:{name:"Ignore files",desc:"Comma separated `.gitignore, .dockerignore`"},batch_size:{name:"Batch size",desc:"Number of changes to sync at a time. Defaults to 50. Minimum is 2."},batches_limit:{name:"Batch limit",desc:"Number of batches to process at a time. Defaults to 40. Minimum is 2. This along with batch size controls how many docs are kept in memory at a time."},useTimeouts:{name:"Use timeouts instead of heartbeats",desc:"If this option is enabled, PouchDB will hold the connection open for 60 seconds, and if no change arrives in that time, close and reopen the socket, instead of holding it open indefinitely. Useful when a proxy limits request duration but can increase resource usage."},concurrencyOfReadChunksOnline:{name:"Batch size of on-demand fetching"},minimumIntervalOfReadChunksOnline:{name:"The delay for consecutive on-demand fetches"},suspendFileWatching:{name:"Suspend file watching",desc:"Stop watching for file changes."},suspendParseReplicationResult:{name:"Suspend database reflecting",desc:"Stop reflecting database changes to storage files."},writeLogToTheFile:{name:"Write logs into the file",desc:"Warning! This will have a serious impact on performance. And the logs will not be synchronised under the default name. Please be careful with logs; they often contain your confidential information."},deleteMetadataOfDeletedFiles:{name:"Do not keep metadata of deleted files."},useIndexedDBAdapter:{name:"(Obsolete) Use an old adapter for compatibility",desc:"Before v0.17.16, we used an old adapter for the local database. Now the new adapter is preferred. However, it needs local database rebuilding. Please disable this toggle when you have enough time. If leave it enabled, also while fetching from the remote database, you will be asked to disable this.",obsolete:!0},watchInternalFileChanges:{name:"Scan changes on customization sync",desc:"Do not use internal API"},doNotSuspendOnFetching:{name:"Fetch database with previous behaviour"},disableCheckingConfigMismatch:{name:"Do not check configuration mismatch before replication"},usePluginSync:{name:"Enable customization sync"},autoSweepPlugins:{name:"Scan customization automatically",desc:"Scan customization before replicating."},autoSweepPluginsPeriodic:{name:"Scan customization periodically",desc:"Scan customization every 1 minute."},notifyPluginOrSettingUpdated:{name:"Notify customized",desc:"Notify when other device has newly customized."},remoteType:{name:"Active Remote Type",desc:"Remote server type"},endpoint:{name:"Endpoint URL",placeHolder:"https://........"},accessKey:{name:"Access Key"},secretKey:{name:"Secret Key",isHidden:!0},region:{name:"Region",placeHolder:"auto"},bucket:{name:"Bucket Name"},useCustomRequestHandler:{name:"Use Custom HTTP Handler",desc:"Enable this if your Object Storage doesn't support CORS"},maxChunksInEden:{name:"Maximum Incubating Chunks",desc:"The maximum number of chunks that can be incubated within the document. Chunks exceeding this number will immediately graduate to independent chunks."},maxTotalLengthInEden:{name:"Maximum Incubating Chunk Size",desc:"The maximum total size of chunks that can be incubated within the document. Chunks exceeding this size will immediately graduate to independent chunks."},maxAgeInEden:{name:"Maximum Incubation Period",desc:"The maximum duration for which chunks can be incubated within the document. Chunks exceeding this period will graduate to independent chunks."},settingSyncFile:{name:"Filename",desc:"Save settings to a markdown file. You will be notified when new settings arrive. You can set different files by the platform."},preset:{name:"Presets",desc:"Apply preset configuration"},syncMode:{name:"Sync Mode"},periodicReplicationInterval:{name:"Periodic Sync interval",desc:"Interval (sec)"},syncInternalFilesBeforeReplication:{name:"Scan for hidden files before replication"},automaticallyDeleteMetadataOfDeletedFiles:{name:"Delete old metadata of deleted files on start-up",desc:"(Days passed, 0 to disable automatic-deletion)"},additionalSuffixOfDatabaseName:{name:"Database suffix",desc:"LiveSync could not handle multiple vaults which have same name without different prefix, This should be automatically configured."},hashAlg:{name:(null==(_a10=configurationNames.hashAlg)?void 0:_a10.name)||"",desc:"xxhash64 is the current default."},deviceAndVaultName:{name:"Device name",desc:"Unique name between all synchronized devices. To edit this setting, please disable customization sync once."},displayLanguage:{name:"Display Language",desc:'Not all messages have been translated. And, please revert to "Default" when reporting errors.'},enableChunkSplitterV2:{name:"Use splitting-limit-capped chunk splitter",desc:"If enabled, chunks will be split into no more than 100 items. However, dedupe is slightly weaker."},disableWorkerForGeneratingChunks:{name:"Do not split chunks in the background",desc:"If disabled(toggled), chunks will be split on the UI thread (Previous behaviour)."},processSmallFilesInUIThread:{name:"Process small files in the foreground",desc:"If enabled, the file under 1kb will be processed in the UI thread."},batchSaveMinimumDelay:{name:"Minimum delay for batch database updating",desc:"Seconds. Saving to the local database will be delayed until this value after we stop typing or saving."},batchSaveMaximumDelay:{name:"Maximum delay for batch database updating",desc:"Saving will be performed forcefully after this number of seconds."},notifyThresholdOfRemoteStorageSize:{name:"Notify when the estimated remote storage size exceeds on start up",desc:"MB (0 to disable)."},usePluginSyncV2:{name:"Enable per-file customization sync",desc:"If enabled, efficient per-file customization sync will be used. A minor migration is required when enabling this feature, and all devices must be updated to v0.23.18. Enabling this feature will result in losing compatibility with older versions."},handleFilenameCaseSensitive:{name:"Handle files as Case-Sensitive",desc:"If this enabled, All files are handled as case-Sensitive (Previous behaviour)."},doNotUseFixedRevisionForChunks:{name:"Content-derived chunk revisions (obsolete setting)",desc:"Chunk revisions are always derived from their content. This stored key is retained only for compatibility."},sendChunksBulkMaxSize:{name:"Maximum request size for manually resending chunks",desc:"MB per request"},useAdvancedMode:{name:"Enable advanced features"},usePowerUserMode:{name:"Enable poweruser features"},useEdgeCaseMode:{name:"Enable edge case treatment features"},enableDebugTools:{name:"Enable Developers' Debug Tools (If available).",desc:"While enabled, it causes very performance impact but debugging replication testing and other features will be enabled. Please disable this if you have not read the source code. Requires restart of Obsidian. Sometimes there is no implementation."},suppressNotifyHiddenFilesChange:{name:"Suppress notification of hidden files change",desc:"If enabled, the notification of hidden files change will be suppressed."},syncMinimumInterval:{name:"Minimum interval for syncing",desc:"The minimum interval for automatic synchronisation on event."},useRequestAPI:{name:"Use Request API to avoid `inevitable` CORS problem",desc:"If enabled, the request API will be used to avoid `inevitable` CORS problems. This is a workaround and may not work in all cases. PLEASE READ THE DOCUMENTATION BEFORE USING THIS OPTION. This is a less-secure option."},hideFileWarningNotice:{name:"Show status icon instead of file warnings banner",desc:"If enabled, the ⛔ icon will be shown inside the status instead of the file warnings banner. No details will be shown."},networkWarningStyle:{name:"Network warning style",desc:"How to display network errors when the sync server is unreachable."},bucketPrefix:{name:"File prefix on the bucket",desc:"Effectively a directory. Should end with `/`. e.g., `vault-name/`."},chunkSplitterVersion:{name:"Chunk Splitter",desc:"Now we can choose how to split the chunks; V3 is the most efficient. If you have troubled, please make this Default or Legacy."},processSizeMismatchedFiles:{name:"Process files even if seems to be corrupted",desc:"You can enable this setting to process the files with size mismatches, these files can be created by some APIs or integrations."},forcePathStyle:{name:"Enable forcePathStyle",desc:"If enabled, the forcePathStyle option will be used for bucket operations."},P2P_AutoBroadcast:{name:"Automatically broadcast changes to connected peers",desc:"If enabled, changes will be automatically broadcasted to all connected peers. Notified peers will start fetching the changes."},P2P_AutoStart:{name:"Automatically start P2P connection on launch",desc:"If enabled, the P2P connection will be automatically started when the application launches."},P2P_Enabled:{name:"Enable P2P Synchronization"},maxMTimeForReflectEvents:{name:"Maximum file modification time for reflected file events",desc:"Files with modification times greater than this value (in seconds since the Unix epoch) will not have their events reflected. Set to 0 to disable this limit."}};0;setLevelClass=(el,level)=>{switch(level){case LEVEL_POWER_USER:el.addClass("sls-setting-poweruser");break;case LEVEL_ADVANCED:el.addClass("sls-setting-advanced");break;case LEVEL_EDGE_CASE:el.addClass("sls-setting-edgecase");break;default:}};SETTING_WITH_ADDITIONAL_ACTIONS_CLASS="sls-setting-with-additional-actions";ADDITIONAL_ACTION_CLASS="sls-setting-additional-action";LiveSyncSetting=class _LiveSyncSetting extends import_obsidian.Setting{constructor(containerEl){super(containerEl);this.watchDirtyKeys=[];this.holdValue=!1;this.descBuf="";this.nameBuf="";this.placeHolderBuf="";this.hasPassword=!1;this.updateHandlers=new Set;this.prevStatus={};_LiveSyncSetting.env.settingComponents.push(this)}setDesc(desc){this.descBuf=desc;super.setDesc(desc);return this}setName(name){this.nameBuf=name;super.setName(name);return this}setAuto(key3,opt){this.autoWireSetting(key3,opt);return this}autoWireSetting(key3,opt){const conf=getConfig2(key3);if(!conf)return;const name=`${conf.name}${statusDisplay(conf.status)}`;this.setName(name);conf.desc&&this.setDesc(conf.desc);this.holdValue=(null==opt?void 0:opt.holdValue)||this.holdValue;this.selfKey=key3;(conf.obsolete||(null==opt?void 0:opt.obsolete))&&this.settingEl.toggleClass("sls-setting-obsolete",!0);(null==opt?void 0:opt.onUpdate)&&this.addOnUpdate(opt.onUpdate);const stat=this._getComputedStatus();!1===stat.visibility&&this.settingEl.toggleClass("sls-setting-hidden",!stat.visibility);return conf}autoWireComponent(component2,conf,opt){this.placeHolderBuf=(null==conf?void 0:conf.placeHolder)||(null==opt?void 0:opt.placeHolder)||"";(null==conf?void 0:conf.level)==LEVEL_ADVANCED?this.settingEl.toggleClass("sls-setting-advanced",!0):(null==conf?void 0:conf.level)==LEVEL_POWER_USER&&this.settingEl.toggleClass("sls-setting-poweruser",!0);this.placeHolderBuf&&component2 instanceof import_obsidian.TextComponent&&component2.setPlaceholder(this.placeHolderBuf);(null==opt?void 0:opt.onUpdate)&&this.addOnUpdate(opt.onUpdate)}async commitValue(value){const key3=this.selfKey;if(void 0!==key3&&value!=_LiveSyncSetting.env.editingSettings[key3]){_LiveSyncSetting.env.editingSettings[key3]=value;this.holdValue||await _LiveSyncSetting.env.saveSettings([key3])}_LiveSyncSetting.env.requestUpdate()}autoWireText(key3,opt){const conf=this.autoWireSetting(key3,opt);this.addText(text2=>{this.autoWiredComponent=text2;const setValue=wrapMemo(value=>{text2.setValue(value)});this.invalidateValue=()=>setValue(`${_LiveSyncSetting.env.editingSettings[key3]}`);this.invalidateValue();text2.onChange(async value=>{await this.commitValue(value)});if(null==opt?void 0:opt.isPassword){text2.inputEl.setAttribute("type","password");this.hasPassword=!0}this.autoWireComponent(this.autoWiredComponent,conf,opt)});return this}autoWireTextArea(key3,opt){const conf=this.autoWireSetting(key3,opt);this.addTextArea(text2=>{this.autoWiredComponent=text2;const setValue=wrapMemo(value=>{text2.setValue(value)});this.invalidateValue=()=>setValue(`${_LiveSyncSetting.env.editingSettings[key3]}`);this.invalidateValue();text2.onChange(async value=>{await this.commitValue(value)});if(null==opt?void 0:opt.isPassword){text2.inputEl.setAttribute("type","password");this.hasPassword=!0}this.autoWireComponent(this.autoWiredComponent,conf,opt)});return this}autoWireNumeric(key3,opt){const conf=this.autoWireSetting(key3,opt);this.addText(text2=>{this.autoWiredComponent=text2;void 0!==opt.clampMin&&text2.inputEl.setAttribute("min",`${opt.clampMin}`);void 0!==opt.clampMax&&text2.inputEl.setAttribute("max",`${opt.clampMax}`);let lastError=!1;const setValue=wrapMemo(value=>{text2.setValue(value)});this.invalidateValue=()=>{lastError||setValue(`${_LiveSyncSetting.env.editingSettings[key3]}`)};this.invalidateValue();text2.onChange(async TextValue=>{var _a13,_b6;const parsedValue=Number(TextValue),value=parsedValue;let hasError=!1;isNaN(value)&&(hasError=!0);void 0!==opt.clampMax&&opt.clampMax<value&&(hasError=!0);void 0!==opt.clampMin&&opt.clampMin>value&&(opt.acceptZero&&0==value||(hasError=!0));if(hasError){this.setTooltip($msg("liveSyncSetting.valueShouldBeInRange",{min:(null==(_a13=opt.clampMin)?void 0:_a13.toString())||"~",max:(null==(_b6=opt.clampMax)?void 0:_b6.toString())||"~"}));text2.inputEl.toggleClass("sls-item-invalid-value",!0);lastError=!0;return!1}lastError=!1;this.setTooltip("");text2.inputEl.toggleClass("sls-item-invalid-value",!1);await this.commitValue(value)});text2.inputEl.setAttr("type","number");this.autoWireComponent(this.autoWiredComponent,conf,opt)});return this}autoWireToggle(key3,opt){const conf=this.autoWireSetting(key3,opt);this.addToggle(toggle=>{this.autoWiredComponent=toggle;const setValue=wrapMemo(value=>{toggle.setValue((null==opt?void 0:opt.invert)?!value:value)});this.invalidateValue=()=>{var _a13,_b6;return setValue(null!=(_b6=null!=(_a13=_LiveSyncSetting.env.editingSettings[key3])?_a13:null==opt?void 0:opt.defaultToggleValue)&&_b6)};this.invalidateValue();toggle.onChange(async value=>{await this.commitValue((null==opt?void 0:opt.invert)?!value:value)});this.autoWireComponent(this.autoWiredComponent,conf,opt)});return this}autoWireDropDown(key3,opt){const conf=this.autoWireSetting(key3,opt);this.addDropdown(dropdown=>{this.autoWiredComponent=dropdown;const setValue=wrapMemo(value=>{dropdown.setValue(value)});dropdown.addOptions(opt.options);this.invalidateValue=()=>setValue(_LiveSyncSetting.env.editingSettings[key3]||"");this.invalidateValue();dropdown.onChange(async value=>{await this.commitValue(value)});this.autoWireComponent(this.autoWiredComponent,conf,opt)});return this}addApplyButton(keys3,text2){this.addButton(button=>{this.applyButtonComponent=button;this.watchDirtyKeys=unique([...keys3,...this.watchDirtyKeys]);button.setButtonText(null!=text2?text2:$msg("liveSyncSettings.btnApply"));button.onClick(async()=>{await _LiveSyncSetting.env.saveSettings(keys3);_LiveSyncSetting.env.reloadAllSettings()});_LiveSyncSetting.env.requestUpdate()});return this}addOnUpdate(func){this.updateHandlers.add(func);return this}_getComputedStatus(){let newConf={};for(const handler of this.updateHandlers)newConf={...newConf,...handler()};return newConf}_applyOnUpdateHandlers(){var _a13;if(this.updateHandlers.size>0){const newConf=this._getComputedStatus(),keys3=Object.keys(newConf);for(const k2 of keys3)if(!(k2 in this.prevStatus)||this.prevStatus[k2]!=newConf[k2])switch(k2){case"visibility":this.settingEl.toggleClass("sls-setting-hidden",!newConf[k2]);this.prevStatus[k2]=newConf[k2];break;case"classes":break;case"disabled":this.setDisabled(newConf[k2]||!1);this.settingEl.toggleClass("sls-setting-disabled",newConf[k2]||!1);this.prevStatus[k2]=newConf[k2];break;case"isCta":{const component2=this.autoWiredComponent;component2 instanceof import_obsidian.ButtonComponent&&(newConf[k2]?component2.setCta():component2.removeCta());this.prevStatus[k2]=newConf[k2]}break;case"isWarning":{const component2=this.autoWiredComponent;component2 instanceof import_obsidian.ButtonComponent&&setButtonDestructiveState(component2,null!=(_a13=newConf[k2])&&_a13);this.prevStatus[k2]=newConf[k2]}break}}}_onUpdate(){var _a13,_b6;if(this.applyButtonComponent){const isDirty2=_LiveSyncSetting.env.isSomeDirty(this.watchDirtyKeys);this.applyButtonComponent.setDisabled(!isDirty2);isDirty2?this.applyButtonComponent.setCta():this.applyButtonComponent.removeCta()}this.selfKey&&!_LiveSyncSetting.env.isDirty(this.selfKey)&&this.invalidateValue&&this.invalidateValue();if(this.holdValue&&this.selfKey){const isDirty2=_LiveSyncSetting.env.isDirty(this.selfKey),alt=isDirty2?$msg("liveSyncSetting.originalValue",{value:String(null!=(_b6=null==(_a13=_LiveSyncSetting.env.initialSettings)?void 0:_a13[this.selfKey])?_b6:"")}):"";this.controlEl.toggleClass("sls-item-dirty",isDirty2);if(!this.hasPassword){this.nameEl.toggleClass("sls-item-dirty-help",isDirty2);this.setTooltip(alt,{delay:10,placement:"right"})}}this._applyOnUpdateHandlers()}};ch2={};wk=function(c3,id,msg,transfer,cb2){var w2=new Worker(ch2[id]||(ch2[id]=URL.createObjectURL(new Blob([c3+';addEventListener("error",function(e){e=e.error;postMessage({$e$:[e.message,e.code,e.stack]})})'],{type:"text/javascript"}))));w2.onmessage=function(e3){var err3,d4=e3.data,ed=d4.$e$;if(ed){err3=new Error(ed[0]);err3.code=ed[1];err3.stack=ed[2];cb2(err3,null)}else cb2(null,d4)};w2.postMessage(msg,transfer);return w2};u8=Uint8Array,u16=Uint16Array,i32=Int32Array;fleb=new u8([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]);fdeb=new u8([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]);clim=new u8([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);freb=function(eb,start){var i3,r4,j2,b3=new u16(31);for(i3=0;i3<31;++i3)b3[i3]=start+=1<<eb[i3-1];r4=new i32(b3[30]);for(i3=1;i3<30;++i3)for(j2=b3[i3];j2<b3[i3+1];++j2)r4[j2]=j2-b3[i3]<<5|i3;return{b:b3,r:r4}};_a11=freb(fleb,2),fl=_a11.b,revfl=_a11.r;fl[28]=258,revfl[258]=28;_b5=freb(fdeb,0),fd=_b5.b,revfd=_b5.r;rev=new u16(32768);for(i=0;i<32768;++i){x=(43690&i)>>1|(21845&i)<<1;x=(52428&x)>>2|(13107&x)<<2;x=(61680&x)>>4|(3855&x)<<4;rev[i]=((65280&x)>>8|(255&x)<<8)>>1}hMap=function(cd2,mb,r4){for(var le,co2,rvb,sv,r_1,v2,m3,s2=cd2.length,i3=0,l2=new u16(mb);i3<s2;++i3)cd2[i3]&&++l2[cd2[i3]-1];le=new u16(mb);for(i3=1;i3<mb;++i3)le[i3]=le[i3-1]+l2[i3-1]<<1;if(r4){co2=new u16(1<<mb);rvb=15-mb;for(i3=0;i3<s2;++i3)if(cd2[i3]){sv=i3<<4|cd2[i3];r_1=mb-cd2[i3];v2=le[cd2[i3]-1]++<<r_1;for(m3=v2|(1<<r_1)-1;v2<=m3;++v2)co2[rev[v2]>>rvb]=sv}}else{co2=new u16(s2);for(i3=0;i3<s2;++i3)cd2[i3]&&(co2[i3]=rev[le[cd2[i3]-1]++]>>15-cd2[i3])}return co2};flt=new u8(288);for(i=0;i<144;++i)flt[i]=8;for(i=144;i<256;++i)flt[i]=9;for(i=256;i<280;++i)flt[i]=7;for(i=280;i<288;++i)flt[i]=8;fdt=new u8(32);for(i=0;i<32;++i)fdt[i]=5;flm=hMap(flt,9,0),flrm=hMap(flt,9,1);fdm=hMap(fdt,5,0),fdrm=hMap(fdt,5,1);max=function(a2){var i3,m3=a2[0];for(i3=1;i3<a2.length;++i3)a2[i3]>m3&&(m3=a2[i3]);return m3};bits=function(d4,p2,m3){var o2=p2/8|0;return(d4[o2]|d4[o2+1]<<8)>>(7&p2)&m3};bits16=function(d4,p2){var o2=p2/8|0;return(d4[o2]|d4[o2+1]<<8|d4[o2+2]<<16)>>(7&p2)};shft=function(p2){return(p2+7)/8|0};slc=function(v2,s2,e3){(null==s2||s2<0)&&(s2=0);(null==e3||e3>v2.length)&&(e3=v2.length);return new u8(v2.subarray(s2,e3))};0;ec=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"];err2=function(ind,msg,nt){var e3=new Error(msg||ec[ind]);e3.code=ind;Error.captureStackTrace&&Error.captureStackTrace(e3,err2);if(!nt)throw e3;return e3};inflt=function(dat,st,buf,dict){var noBuf,resize,noSt,cbuf,final,pos,bt2,lm,dm,lbt,dbt,tbts,type,s2,l2,t9,hLit,hcLen,tl,ldt,clt,i3,clb,clbmsk,clm,r4,c3,n3,lt,dt,lms,dms,lpos,sym,add,b3,d4,dsym,end,shift,dend,sl=dat.length,dl=dict?dict.length:0;if(!sl||st.f&&!st.l)return buf||new u8(0);noBuf=!buf;resize=noBuf||2!=st.i;noSt=st.i;noBuf&&(buf=new u8(3*sl));cbuf=function(l3){var nbuf,bl2=buf.length;if(l3>bl2){nbuf=new u8(Math.max(2*bl2,l3));nbuf.set(buf);buf=nbuf}};final=st.f||0,pos=st.p||0,bt2=st.b||0,lm=st.l,dm=st.d,lbt=st.m,dbt=st.n;tbts=8*sl;do{if(!lm){final=bits(dat,pos,1);type=bits(dat,pos+1,3);pos+=3;if(!type){s2=shft(pos)+4,l2=dat[s2-4]|dat[s2-3]<<8,t9=s2+l2;if(t9>sl){noSt&&err2(0);break}resize&&cbuf(bt2+l2);buf.set(dat.subarray(s2,t9),bt2);st.b=bt2+=l2,st.p=pos=8*t9,st.f=final;continue}if(1==type)lm=flrm,dm=fdrm,lbt=9,dbt=5;else if(2==type){hLit=bits(dat,pos,31)+257,hcLen=bits(dat,pos+10,15)+4;tl=hLit+bits(dat,pos+5,31)+1;pos+=14;ldt=new u8(tl);clt=new u8(19);for(i3=0;i3<hcLen;++i3)clt[clim[i3]]=bits(dat,pos+3*i3,7);pos+=3*hcLen;clb=max(clt),clbmsk=(1<<clb)-1;clm=hMap(clt,clb,1);for(i3=0;i3<tl;){r4=clm[bits(dat,pos,clbmsk)];pos+=15&r4;s2=r4>>4;if(s2<16)ldt[i3++]=s2;else{c3=0,n3=0;16==s2?(n3=3+bits(dat,pos,3),pos+=2,c3=ldt[i3-1]):17==s2?(n3=3+bits(dat,pos,7),pos+=3):18==s2&&(n3=11+bits(dat,pos,127),pos+=7);for(;n3--;)ldt[i3++]=c3}}lt=ldt.subarray(0,hLit),dt=ldt.subarray(hLit);lbt=max(lt);dbt=max(dt);lm=hMap(lt,lbt,1);dm=hMap(dt,dbt,1)}else err2(1);if(pos>tbts){noSt&&err2(0);break}}resize&&cbuf(bt2+131072);lms=(1<<lbt)-1,dms=(1<<dbt)-1;lpos=pos;for(;;lpos=pos){c3=lm[bits16(dat,pos)&lms],sym=c3>>4;pos+=15&c3;if(pos>tbts){noSt&&err2(0);break}c3||err2(2);if(sym<256)buf[bt2++]=sym;else{if(256==sym){lpos=pos,lm=null;break}add=sym-254;if(sym>264){i3=sym-257,b3=fleb[i3];add=bits(dat,pos,(1<<b3)-1)+fl[i3];pos+=b3}d4=dm[bits16(dat,pos)&dms],dsym=d4>>4;d4||err2(3);pos+=15&d4;dt=fd[dsym];if(dsym>3){b3=fdeb[dsym];dt+=bits16(dat,pos)&(1<<b3)-1,pos+=b3}if(pos>tbts){noSt&&err2(0);break}resize&&cbuf(bt2+131072);end=bt2+add;if(bt2<dt){shift=dl-dt,dend=Math.min(dt,end);shift+bt2<0&&err2(3);for(;bt2<dend;++bt2)buf[bt2]=dict[shift+bt2]}for(;bt2<end;++bt2)buf[bt2]=buf[bt2-dt]}}st.l=lm,st.p=lpos,st.b=bt2,st.f=final;lm&&(final=1,st.m=lbt,st.d=dm,st.n=dbt)}while(!final);return bt2!=buf.length&&noBuf?slc(buf,0,bt2):buf.subarray(0,bt2)};wbits=function(d4,p2,v2){v2<<=7&p2;var o2=p2/8|0;d4[o2]|=v2;d4[o2+1]|=v2>>8};wbits16=function(d4,p2,v2){v2<<=7&p2;var o2=p2/8|0;d4[o2]|=v2;d4[o2+1]|=v2>>8;d4[o2+2]|=v2>>16};hTree=function(d4,mb){var i3,s2,t22,v2,l2,r4,i0,i1,i22,maxSym,tr,mbt,dt,lft,cst,i2_1,i2_2,i2_3,t9=[];for(i3=0;i3<d4.length;++i3)d4[i3]&&t9.push({s:i3,f:d4[i3]});s2=t9.length;t22=t9.slice();if(!s2)return{t:et,l:0};if(1==s2){v2=new u8(t9[0].s+1);v2[t9[0].s]=1;return{t:v2,l:1}}t9.sort(function(a2,b3){return a2.f-b3.f});t9.push({s:-1,f:25001});l2=t9[0],r4=t9[1],i0=0,i1=1,i22=2;t9[0]={s:-1,f:l2.f+r4.f,l:l2,r:r4};for(;i1!=s2-1;){l2=t9[t9[i0].f<t9[i22].f?i0++:i22++];r4=t9[i0!=i1&&t9[i0].f<t9[i22].f?i0++:i22++];t9[i1++]={s:-1,f:l2.f+r4.f,l:l2,r:r4}}maxSym=t22[0].s;for(i3=1;i3<s2;++i3)t22[i3].s>maxSym&&(maxSym=t22[i3].s);tr=new u16(maxSym+1);mbt=ln(t9[i1-1],tr,0);if(mbt>mb){i3=0,dt=0;lft=mbt-mb,cst=1<<lft;t22.sort(function(a2,b3){return tr[b3.s]-tr[a2.s]||a2.f-b3.f});for(;i3<s2;++i3){i2_1=t22[i3].s;if(!(tr[i2_1]>mb))break;dt+=cst-(1<<mbt-tr[i2_1]);tr[i2_1]=mb}dt>>=lft;for(;dt>0;){i2_2=t22[i3].s;tr[i2_2]<mb?dt-=1<<mb-tr[i2_2]++-1:++i3}for(;i3>=0&&dt;--i3){i2_3=t22[i3].s;if(tr[i2_3]==mb){--tr[i2_3];++dt}}mbt=mb}return{t:new u8(tr),l:mbt}};ln=function(n3,l2,d4){return-1==n3.s?Math.max(ln(n3.l,l2,d4+1),ln(n3.r,l2,d4+1)):l2[n3.s]=d4};lc=function(c3){for(var cl2,cli,cln,cls,w2,i3,s2=c3.length;s2&&!c3[--s2];);cl2=new u16(++s2);cli=0,cln=c3[0],cls=1;w2=function(v2){cl2[cli++]=v2};for(i3=1;i3<=s2;++i3)if(c3[i3]==cln&&i3!=s2)++cls;else{if(!cln&&cls>2){for(;cls>138;cls-=138)w2(32754);if(cls>2){w2(cls>10?cls-11<<5|28690:cls-3<<5|12305);cls=0}}else if(cls>3){w2(cln),--cls;for(;cls>6;cls-=6)w2(8304);cls>2&&(w2(cls-3<<5|8208),cls=0)}for(;cls--;)w2(cln);cls=1;cln=c3[i3]}return{c:cl2.subarray(0,cli),n:s2}};clen=function(cf2,cl2){var i3,l2=0;for(i3=0;i3<cl2.length;++i3)l2+=cf2[i3]*cl2[i3];return l2};wfblk=function(out,pos,dat){var i3,s2=dat.length,o2=shft(pos+2);out[o2]=255&s2;out[o2+1]=s2>>8;out[o2+2]=255^out[o2];out[o2+3]=255^out[o2+1];for(i3=0;i3<s2;++i3)out[o2+i3+4]=dat[i3];return 8*(o2+4+s2)};wblk=function(dat,out,final,syms,lf,df,eb,li,bs2,bl2,p2){var _a13,dlt,mlb,_b6,ddt,mdb,_c3,lclt,nlc,_d2,lcdt,ndc,lcfreq,i3,_e2,lct,mlcb,nlcc,flen,ftlen,dtlen,lm,ll,dm,dl,llm,lcts,it,clct,len,sym,dst;wbits(out,p2++,final);++lf[256];_a13=hTree(lf,15),dlt=_a13.t,mlb=_a13.l;_b6=hTree(df,15),ddt=_b6.t,mdb=_b6.l;_c3=lc(dlt),lclt=_c3.c,nlc=_c3.n;_d2=lc(ddt),lcdt=_d2.c,ndc=_d2.n;lcfreq=new u16(19);for(i3=0;i3<lclt.length;++i3)++lcfreq[31&lclt[i3]];for(i3=0;i3<lcdt.length;++i3)++lcfreq[31&lcdt[i3]];_e2=hTree(lcfreq,7),lct=_e2.t,mlcb=_e2.l;nlcc=19;for(;nlcc>4&&!lct[clim[nlcc-1]];--nlcc);flen=bl2+5<<3;ftlen=clen(lf,flt)+clen(df,fdt)+eb;dtlen=clen(lf,dlt)+clen(df,ddt)+eb+14+3*nlcc+clen(lcfreq,lct)+2*lcfreq[16]+3*lcfreq[17]+7*lcfreq[18];if(bs2>=0&&flen<=ftlen&&flen<=dtlen)return wfblk(out,p2,dat.subarray(bs2,bs2+bl2));wbits(out,p2,1+(dtlen<ftlen)),p2+=2;if(dtlen<ftlen){lm=hMap(dlt,mlb,0),ll=dlt,dm=hMap(ddt,mdb,0),dl=ddt;llm=hMap(lct,mlcb,0);wbits(out,p2,nlc-257);wbits(out,p2+5,ndc-1);wbits(out,p2+10,nlcc-4);p2+=14;for(i3=0;i3<nlcc;++i3)wbits(out,p2+3*i3,lct[clim[i3]]);p2+=3*nlcc;lcts=[lclt,lcdt];for(it=0;it<2;++it){clct=lcts[it];for(i3=0;i3<clct.length;++i3){len=31&clct[i3];wbits(out,p2,llm[len]),p2+=lct[len];len>15&&(wbits(out,p2,clct[i3]>>5&127),p2+=clct[i3]>>12)}}}else lm=flm,ll=flt,dm=fdm,dl=fdt;for(i3=0;i3<li;++i3){sym=syms[i3];if(sym>255){len=sym>>18&31;wbits16(out,p2,lm[len+257]),p2+=ll[len+257];len>7&&(wbits(out,p2,sym>>23&31),p2+=fleb[len]);dst=31&sym;wbits16(out,p2,dm[dst]),p2+=dl[dst];dst>3&&(wbits16(out,p2,sym>>5&8191),p2+=fdeb[dst])}else wbits16(out,p2,lm[sym]),p2+=ll[sym]}wbits16(out,p2,lm[256]);return p2+ll[256]};deo=new i32([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]);et=new u8(0);dflt=function(dat,lvl,plvl,pre,post,st){var opt,n3,c3,msk_1,prev,head2,bs1_1,bs2_1,hsh,syms,lf,df,lc_1,eb,i3,li,wi,bs2,hv,imod,pimod,rem,j2,l2,d4,ch_1,dif,maxn,maxd,ml,nl,mmd,md,ti,pti,cd2,lin,din,e3,s2=st.z||dat.length,o2=new u8(pre+s2+5*(1+Math.ceil(s2/7e3))+post),w2=o2.subarray(pre,o2.length-post),lst=st.l,pos=7&(st.r||0);if(lvl){pos&&(w2[0]=st.r>>3);opt=deo[lvl-1];n3=opt>>13,c3=8191&opt;msk_1=(1<<plvl)-1;prev=st.p||new u16(32768),head2=st.h||new u16(msk_1+1);bs1_1=Math.ceil(plvl/3),bs2_1=2*bs1_1;hsh=function(i4){return(dat[i4]^dat[i4+1]<<bs1_1^dat[i4+2]<<bs2_1)&msk_1};syms=new i32(25e3);lf=new u16(288),df=new u16(32);lc_1=0,eb=0,i3=st.i||0,li=0,wi=st.w||0,bs2=0;for(;i3+2<s2;++i3){hv=hsh(i3);imod=32767&i3,pimod=head2[hv];prev[imod]=pimod;head2[hv]=imod;if(wi<=i3){rem=s2-i3;if((lc_1>7e3||li>24576)&&(rem>423||!lst)){pos=wblk(dat,w2,0,syms,lf,df,eb,li,bs2,i3-bs2,pos);li=lc_1=eb=0,bs2=i3;for(j2=0;j2<286;++j2)lf[j2]=0;for(j2=0;j2<30;++j2)df[j2]=0}l2=2,d4=0,ch_1=c3,dif=imod-pimod&32767;if(rem>2&&hv==hsh(i3-dif)){maxn=Math.min(n3,rem)-1;maxd=Math.min(32767,i3);ml=Math.min(258,rem);for(;dif<=maxd&&--ch_1&&imod!=pimod;){if(dat[i3+l2]==dat[i3+l2-dif]){nl=0;for(;nl<ml&&dat[i3+nl]==dat[i3+nl-dif];++nl);if(nl>l2){l2=nl,d4=dif;if(nl>maxn)break;mmd=Math.min(dif,nl-2);md=0;for(j2=0;j2<mmd;++j2){ti=i3-dif+j2&32767;pti=prev[ti];cd2=ti-pti&32767;cd2>md&&(md=cd2,pimod=ti)}}}imod=pimod,pimod=prev[imod];dif+=imod-pimod&32767}}if(d4){syms[li++]=268435456|revfl[l2]<<18|revfd[d4];lin=31&revfl[l2],din=31&revfd[d4];eb+=fleb[lin]+fdeb[din];++lf[257+lin];++df[din];wi=i3+l2;++lc_1}else{syms[li++]=dat[i3];++lf[dat[i3]]}}}for(i3=Math.max(i3,wi);i3<s2;++i3){syms[li++]=dat[i3];++lf[dat[i3]]}pos=wblk(dat,w2,lst,syms,lf,df,eb,li,bs2,i3-bs2,pos);if(!lst){st.r=7&pos|w2[pos/8|0]<<3;pos-=7;st.h=head2,st.p=prev,st.i=i3,st.w=wi}}else{for(i3=st.w||0;i3<s2+lst;i3+=65535){e3=i3+65535;if(e3>=s2){w2[pos/8|0]=lst;e3=s2}pos=wfblk(w2,pos+1,dat.subarray(i3,e3))}st.i=s2}return slc(o2,0,pre+shft(pos)+post)};crct=function(){var i3,c3,k2,t9=new Int32Array(256);for(i3=0;i3<256;++i3){c3=i3,k2=9;for(;--k2;)c3=(1&c3&&-306674912)^c3>>>1;t9[i3]=c3}return t9}();crc=function(){var c3=-1;return{p:function(d4){var i3,cr2=c3;for(i3=0;i3<d4.length;++i3)cr2=crct[255&cr2^d4[i3]]^cr2>>>8;c3=cr2},d:function(){return~c3}}};adler=function(){var a2=1,b3=0;return{p:function(d4){var i3,e3,n3=a2,m3=b3,l2=0|d4.length;for(i3=0;i3!=l2;){e3=Math.min(i3+2655,l2);for(;i3<e3;++i3)m3+=n3+=d4[i3];n3=(65535&n3)+15*(n3>>16),m3=(65535&m3)+15*(m3>>16)}a2=n3,b3=m3},d:function(){a2%=65521,b3%=65521;return(255&a2)<<24|(65280&a2)<<8|(255&b3)<<8|b3>>8}}};dopt=function(dat,opt,pre,post,st){var dict,newDat;if(!st){st={l:1};if(opt.dictionary){dict=opt.dictionary.subarray(-32768);newDat=new u8(dict.length+dat.length);newDat.set(dict);newDat.set(dat,dict.length);dat=newDat;st.w=dict.length}}return dflt(dat,null==opt.level?6:opt.level,null==opt.mem?st.l?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(dat.length)))):20:12+opt.mem,pre,post,st)};mrg=function(a2,b3){var k2,o2={};for(k2 in a2)o2[k2]=a2[k2];for(k2 in b3)o2[k2]=b3[k2];return o2};wcln=function(fn,fnStr,td3){var i3,v2,k2,st_1,spInd,t9,dt=fn(),st=fn.toString(),ks=st.slice(st.indexOf("[")+1,st.lastIndexOf("]")).replace(/\s+/g,"").split(",");for(i3=0;i3<dt.length;++i3){v2=dt[i3],k2=ks[i3];if("function"==typeof v2){fnStr+=";"+k2+"=";st_1=v2.toString();if(v2.prototype)if(-1!=st_1.indexOf("[native code]")){spInd=st_1.indexOf(" ",8)+1;fnStr+=st_1.slice(spInd,st_1.indexOf("(",spInd))}else{fnStr+=st_1;for(t9 in v2.prototype)fnStr+=";"+k2+".prototype."+t9+"="+v2.prototype[t9].toString()}else fnStr+=st_1}else td3[k2]=v2}return fnStr};ch=[];cbfs=function(v2){var k2,tl=[];for(k2 in v2)v2[k2].buffer&&tl.push((v2[k2]=new v2[k2].constructor(v2[k2])).buffer);return tl};wrkr=function(fns,init3,id,cb2){var fnStr,td_1,m3,i3,td3;if(!ch[id]){fnStr="",td_1={},m3=fns.length-1;for(i3=0;i3<m3;++i3)fnStr=wcln(fns[i3],fnStr,td_1);ch[id]={c:wcln(fns[m3],fnStr,td_1),e:td_1}}td3=mrg({},ch[id].e);return wk(ch[id].c+";onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage="+init3.toString()+"}",id,td3,cbfs(td3),cb2)};bInflt=function(){return[u8,u16,i32,fleb,fdeb,clim,fl,fd,flrm,fdrm,rev,ec,hMap,max,bits,bits16,shft,slc,err2,inflt,inflateSync,pbf,gopt]};bDflt=function(){return[u8,u16,i32,fleb,fdeb,clim,revfl,revfd,flm,flt,fdm,fdt,rev,deo,et,hMap,wbits,wbits16,hTree,ln,lc,clen,wfblk,wblk,shft,slc,dflt,dopt,deflateSync,pbf]};gze=function(){return[gzh,gzhl,wbytes,crc,crct]};guze=function(){return[gzs,gzl]};zle=function(){return[zlh,wbytes,adler]};zule=function(){return[zls]};pbf=function(msg){return postMessage(msg,[msg.buffer])};gopt=function(o2){return o2&&{out:o2.size&&new u8(o2.size),dictionary:o2.dictionary}};cbify=function(dat,opts,fns,init3,id,cb2){var w2=wrkr(fns,init3,id,function(err3,dat2){w2.terminate();cb2(err3,dat2)});w2.postMessage([dat,opts],opts.consume?[dat.buffer]:[]);return function(){w2.terminate()}};astrm=function(strm){strm.ondata=function(dat,final){return postMessage([dat,final],[dat.buffer])};return function(ev){if(ev.data.length){strm.push(ev.data[0],ev.data[1]);postMessage([ev.data[0].length])}else strm.flush()}};astrmify=function(fns,strm,opts,init3,id,flush2,ext2){var t9,w2=wrkr(fns,init3,id,function(err3,dat){if(err3)w2.terminate(),strm.ondata.call(strm,err3);else if(Array.isArray(dat))if(1==dat.length){strm.queuedSize-=dat[0];strm.ondrain&&strm.ondrain(dat[0])}else{dat[1]&&w2.terminate();strm.ondata.call(strm,err3,dat[0],dat[1])}else ext2(dat)});w2.postMessage(opts);strm.queuedSize=0;strm.push=function(d4,f4){strm.ondata||err2(5);t9&&strm.ondata(err2(4,0,1),null,!!f4);strm.queuedSize+=d4.length;w2.postMessage([d4,t9=f4],[d4.buffer])};strm.terminate=function(){w2.terminate()};flush2&&(strm.flush=function(){w2.postMessage([])})};b2=function(d4,b3){return d4[b3]|d4[b3+1]<<8};b4=function(d4,b3){return(d4[b3]|d4[b3+1]<<8|d4[b3+2]<<16|d4[b3+3]<<24)>>>0};b8=function(d4,b3){return b4(d4,b3)+4294967296*b4(d4,b3+4)};wbytes=function(d4,b3,v2){for(;v2;++b3)d4[b3]=v2,v2>>>=8};gzh=function(c3,o2){var i3,fn=o2.filename;c3[0]=31,c3[1]=139,c3[2]=8,c3[8]=o2.level<2?4:9==o2.level?2:0,c3[9]=3;0!=o2.mtime&&wbytes(c3,4,Math.floor(new Date(o2.mtime||Date.now())/1e3));if(fn){c3[3]=8;for(i3=0;i3<=fn.length;++i3)c3[i3+10]=fn.charCodeAt(i3)}};gzs=function(d4){var flg,st,zs;31==d4[0]&&139==d4[1]&&8==d4[2]||err2(6,"invalid gzip data");flg=d4[3];st=10;4&flg&&(st+=2+(d4[10]|d4[11]<<8));for(zs=(flg>>3&1)+(flg>>4&1);zs>0;zs-=!d4[st++]);return st+(2&flg)};gzl=function(d4){var l2=d4.length;return(d4[l2-4]|d4[l2-3]<<8|d4[l2-2]<<16|d4[l2-1]<<24)>>>0};gzhl=function(o2){return 10+(o2.filename?o2.filename.length+1:0)};zlh=function(c3,o2){var h3,lv=o2.level,fl2=0==lv?0:lv<6?1:9==lv?3:2;c3[0]=120,c3[1]=fl2<<6|(o2.dictionary&&32);c3[1]|=31-(c3[0]<<8|c3[1])%31;if(o2.dictionary){h3=adler();h3.p(o2.dictionary);wbytes(c3,2,h3.d())}};zls=function(d4,dict){(8!=(15&d4[0])||d4[0]>>4>7||(d4[0]<<8|d4[1])%31)&&err2(6,"invalid zlib data");(d4[1]>>5&1)==+!dict&&err2(6,"invalid zlib data: "+(32&d4[1]?"need":"unexpected")+" dictionary");return 2+(d4[1]>>3&4)};Deflate=function(){function Deflate2(opts,cb2){"function"==typeof opts&&(cb2=opts,opts={});this.ondata=cb2;this.o=opts||{};this.s={l:0,i:32768,w:32768,z:32768};this.b=new u8(98304);if(this.o.dictionary){var dict=this.o.dictionary.subarray(-32768);this.b.set(dict,32768-dict.length);this.s.i=32768-dict.length}}Deflate2.prototype.p=function(c3,f4){this.ondata(dopt(c3,this.o,0,0,this.s),f4)};Deflate2.prototype.push=function(chunk,final){var endLen,newBuf,split;this.ondata||err2(5);this.s.l&&err2(4);endLen=chunk.length+this.s.z;if(endLen>this.b.length){if(endLen>2*this.b.length-32768){newBuf=new u8(-32768&endLen);newBuf.set(this.b.subarray(0,this.s.z));this.b=newBuf}split=this.b.length-this.s.z;this.b.set(chunk.subarray(0,split),this.s.z);this.s.z=this.b.length;this.p(this.b,!1);this.b.set(this.b.subarray(-32768));this.b.set(chunk.subarray(split),32768);this.s.z=chunk.length-split+32768;this.s.i=32766,this.s.w=32768}else{this.b.set(chunk,this.s.z);this.s.z+=chunk.length}this.s.l=1&final;if(this.s.z>this.s.w+8191||final){this.p(this.b,final||!1);this.s.w=this.s.i,this.s.i-=2}};Deflate2.prototype.flush=function(){this.ondata||err2(5);this.s.l&&err2(4);this.p(this.b,!1);this.s.w=this.s.i,this.s.i-=2};return Deflate2}();AsyncDeflate=function(){return function AsyncDeflate2(opts,cb2){astrmify([bDflt,function(){return[astrm,Deflate]}],this,StrmOpt.call(this,opts,cb2),function(ev){var strm=new Deflate(ev.data);onmessage=astrm(strm)},6,1)}}();Inflate=function(){function Inflate2(opts,cb2){"function"==typeof opts&&(cb2=opts,opts={});this.ondata=cb2;var dict=opts&&opts.dictionary&&opts.dictionary.subarray(-32768);this.s={i:0,b:dict?dict.length:0};this.o=new u8(32768);this.p=new u8(0);dict&&this.o.set(dict)}Inflate2.prototype.e=function(c3){this.ondata||err2(5);this.d&&err2(4);if(this.p.length){if(c3.length){var n3=new u8(this.p.length+c3.length);n3.set(this.p),n3.set(c3,this.p.length),this.p=n3}}else this.p=c3};Inflate2.prototype.c=function(final){var bts,dt;this.s.i=+(this.d=final||!1);bts=this.s.b;dt=inflt(this.p,this.s,this.o);this.ondata(slc(dt,bts,this.s.b),this.d);this.o=slc(dt,this.s.b-32768),this.s.b=this.o.length;this.p=slc(this.p,this.s.p/8|0),this.s.p&=7};Inflate2.prototype.push=function(chunk,final){this.e(chunk),this.c(final)};return Inflate2}();AsyncInflate=function(){return function AsyncInflate2(opts,cb2){astrmify([bInflt,function(){return[astrm,Inflate]}],this,StrmOpt.call(this,opts,cb2),function(ev){var strm=new Inflate(ev.data);onmessage=astrm(strm)},7,0)}}();Gzip=function(){function Gzip2(opts,cb2){this.c=crc();this.l=0;this.v=1;Deflate.call(this,opts,cb2)}Gzip2.prototype.push=function(chunk,final){this.c.p(chunk);this.l+=chunk.length;Deflate.prototype.push.call(this,chunk,final)};Gzip2.prototype.p=function(c3,f4){var raw=dopt(c3,this.o,this.v&&gzhl(this.o),f4&&8,this.s);this.v&&(gzh(raw,this.o),this.v=0);f4&&(wbytes(raw,raw.length-8,this.c.d()),wbytes(raw,raw.length-4,this.l));this.ondata(raw,f4)};Gzip2.prototype.flush=function(){Deflate.prototype.flush.call(this)};return Gzip2}();0;Gunzip=function(){function Gunzip2(opts,cb2){this.v=1;this.r=0;Inflate.call(this,opts,cb2)}Gunzip2.prototype.push=function(chunk,final){var p2,s2;Inflate.prototype.e.call(this,chunk);this.r+=chunk.length;if(this.v){p2=this.p.subarray(this.v-1);s2=p2.length>3?gzs(p2):4;if(s2>p2.length){if(!final)return}else this.v>1&&this.onmember&&this.onmember(this.r-p2.length);this.p=p2.subarray(s2),this.v=0}Inflate.prototype.c.call(this,final);if(this.s.f&&!this.s.l&&!final){this.v=shft(this.s.p)+9;this.s={i:0};this.o=new u8(0);this.push(new u8(0),final)}};return Gunzip2}();AsyncGunzip=function(){return function AsyncGunzip2(opts,cb2){var _this=this;astrmify([bInflt,guze,function(){return[astrm,Inflate,Gunzip]}],this,StrmOpt.call(this,opts,cb2),function(ev){var strm=new Gunzip(ev.data);strm.onmember=function(offset){return postMessage(offset)};onmessage=astrm(strm)},9,0,function(offset){return _this.onmember&&_this.onmember(offset)})}}();Zlib=function(){function Zlib2(opts,cb2){this.c=adler();this.v=1;Deflate.call(this,opts,cb2)}Zlib2.prototype.push=function(chunk,final){this.c.p(chunk);Deflate.prototype.push.call(this,chunk,final)};Zlib2.prototype.p=function(c3,f4){var raw=dopt(c3,this.o,this.v&&(this.o.dictionary?6:2),f4&&4,this.s);this.v&&(zlh(raw,this.o),this.v=0);f4&&wbytes(raw,raw.length-4,this.c.d());this.ondata(raw,f4)};Zlib2.prototype.flush=function(){Deflate.prototype.flush.call(this)};return Zlib2}();0;Unzlib=function(){function Unzlib2(opts,cb2){Inflate.call(this,opts,cb2);this.v=opts&&opts.dictionary?2:1}Unzlib2.prototype.push=function(chunk,final){Inflate.prototype.e.call(this,chunk);if(this.v){if(this.p.length<6&&!final)return;this.p=this.p.subarray(zls(this.p,this.v-1)),this.v=0}if(final){this.p.length<4&&err2(6,"invalid zlib data");this.p=this.p.subarray(0,-4)}Inflate.prototype.c.call(this,final)};return Unzlib2}();AsyncUnzlib=function(){return function AsyncUnzlib2(opts,cb2){astrmify([bInflt,zule,function(){return[astrm,Inflate,Unzlib]}],this,StrmOpt.call(this,opts,cb2),function(ev){var strm=new Unzlib(ev.data);onmessage=astrm(strm)},11,0)}}();Decompress=function(){function Decompress2(opts,cb2){this.o=StrmOpt.call(this,opts,cb2)||{};this.G=Gunzip;this.I=Inflate;this.Z=Unzlib}Decompress2.prototype.i=function(){var _this=this;this.s.ondata=function(dat,final){_this.ondata(dat,final)}};Decompress2.prototype.push=function(chunk,final){this.ondata||err2(5);if(this.s)this.s.push(chunk,final);else{if(this.p&&this.p.length){var n3=new u8(this.p.length+chunk.length);n3.set(this.p),n3.set(chunk,this.p.length)}else this.p=chunk;if(this.p.length>2){this.s=31==this.p[0]&&139==this.p[1]&&8==this.p[2]?new this.G(this.o):8!=(15&this.p[0])||this.p[0]>>4>7||(this.p[0]<<8|this.p[1])%31?new this.I(this.o):new this.Z(this.o);this.i();this.s.push(this.p,final);this.p=null}}};return Decompress2}();0;fltn=function(d4,p2,t9,o2){var k2,val,n3,op;for(k2 in d4){val=d4[k2],n3=p2+k2,op=o2;Array.isArray(val)&&(op=mrg(o2,val[1]),val=val[0]);if(val instanceof u8)t9[n3]=[val,op];else{t9[n3+="/"]=[new u8(0),op];fltn(val,n3,t9,o2)}}};te3="undefined"!=typeof TextEncoder&&new TextEncoder;td2="undefined"!=typeof TextDecoder&&new TextDecoder;tds=0;try{td2.decode(et,{stream:!0});tds=1}catch(e3){}dutf8=function(d4){var r4,i3,c3,eb;for(r4="",i3=0;;){c3=d4[i3++];eb=(c3>127)+(c3>223)+(c3>239);if(i3+eb>d4.length)return{s:r4,r:slc(d4,i3-1)};eb?3==eb?(c3=((15&c3)<<18|(63&d4[i3++])<<12|(63&d4[i3++])<<6|63&d4[i3++])-65536,r4+=String.fromCharCode(55296|c3>>10,56320|1023&c3)):r4+=1&eb?String.fromCharCode((31&c3)<<6|63&d4[i3++]):String.fromCharCode((15&c3)<<12|(63&d4[i3++])<<6|63&d4[i3++]):r4+=String.fromCharCode(c3)}};0;0;dbf=function(l2){return 1==l2?3:l2<6?2:9==l2?1:0};0;0;z64e=function(d4,b3){for(;1!=b2(d4,b3);b3+=4+b2(d4,b3+2));return[b8(d4,b3+12),b8(d4,b3+4),b8(d4,b3+20)]};exfl=function(ex){var k2,l2,le=0;if(ex)for(k2 in ex){l2=ex[k2].length;l2>65535&&err2(9);le+=l2+4}return le};wzh=function(d4,b3,f4,fn,u2,c3,ce2,co2){var dt,y2,k2,exf,l2,fl2=fn.length,ex=f4.extra,col=co2&&co2.length,exl=exfl(ex);wbytes(d4,b3,null!=ce2?33639248:67324752),b3+=4;null!=ce2&&(d4[b3++]=20,d4[b3++]=f4.os);d4[b3]=20,b3+=2;d4[b3++]=f4.flag<<1|(c3<0&&8),d4[b3++]=u2&&8;d4[b3++]=255&f4.compression,d4[b3++]=f4.compression>>8;dt=new Date(null==f4.mtime?Date.now():f4.mtime),y2=dt.getFullYear()-1980;(y2<0||y2>119)&&err2(10);wbytes(d4,b3,y2<<25|dt.getMonth()+1<<21|dt.getDate()<<16|dt.getHours()<<11|dt.getMinutes()<<5|dt.getSeconds()>>1),b3+=4;if(-1!=c3){wbytes(d4,b3,f4.crc);wbytes(d4,b3+4,c3<0?-c3-2:c3);wbytes(d4,b3+8,f4.size)}wbytes(d4,b3+12,fl2);wbytes(d4,b3+14,exl),b3+=16;if(null!=ce2){wbytes(d4,b3,col);wbytes(d4,b3+6,f4.attrs);wbytes(d4,b3+10,ce2),b3+=14}d4.set(fn,b3);b3+=fl2;if(exl)for(k2 in ex){exf=ex[k2],l2=exf.length;wbytes(d4,b3,+k2);wbytes(d4,b3+2,l2);d4.set(exf,b3+4),b3+=4+l2}col&&(d4.set(co2,b3),b3+=col);return b3};wzf=function(o2,b3,c3,d4,e3){wbytes(o2,b3,101010256);wbytes(o2,b3+8,c3);wbytes(o2,b3+10,c3);wbytes(o2,b3+12,d4);wbytes(o2,b3+16,e3)};ZipPassThrough=function(){function ZipPassThrough2(filename){this.filename=filename;this.c=crc();this.size=0;this.compression=0}ZipPassThrough2.prototype.process=function(chunk,final){this.ondata(null,chunk,final)};ZipPassThrough2.prototype.push=function(chunk,final){this.ondata||err2(5);this.c.p(chunk);this.size+=chunk.length;final&&(this.crc=this.c.d());this.process(chunk,final||!1)};return ZipPassThrough2}();0;0;0;UnzipPassThrough=function(){function UnzipPassThrough2(){}UnzipPassThrough2.prototype.push=function(data,final){this.ondata(null,data,final)};UnzipPassThrough2.compression=0;return UnzipPassThrough2}();0;0;0;"function"==typeof queueMicrotask?queueMicrotask:"function"==typeof setTimeout?setTimeout:function(fn){fn()};wrappedInflate=wrapFflateFunc(inflate);wrappedDeflate=wrapFflateFunc(deflate);replicationFilter=(db,compress)=>{db.transform({incoming:async doc=>compress?await compressDoc(doc):doc,outgoing:async doc=>await decompressDoc(doc)})};MARK_SHIFT="L";MARK_SHIFT_COMPRESSED=`${MARK_SHIFT}Z`;CheckPointInfoDefault={lastLocalSeq:0,journalEpoch:"",knownIDs:new Set,sentIDs:new Set,receivedFiles:new Set,sentFiles:new Set};JournalStorageReadStatuses_AVAILABLE="available",JournalStorageReadStatuses_NOT_FOUND="not-found",JournalStorageReadStatuses_UNAVAILABLE="unavailable";DatabaseReadLayer=class{constructor(database){__publicField(this,"database");this.database=database}isChunkDoc(doc){return doc&&"string"==typeof doc._id&&"leaf"===doc.type}getError(error){return error instanceof Error?error:"object"==typeof error&&null!==error&&"error"in error&&error.error instanceof Error?error.error:void 0}isMissingError(error){return"object"==typeof error&&null!==error&&("status"in error&&404===error.status||("error"in error&&"not_found"===error.error||"error"in error&&this.isMissingError(error.error)))}async read(ids,options,next2){if(0===ids.length)return[];const resultMap=new Map,remainingIds=[];try{const results=await this.database.allDocs({keys:ids,include_docs:!0});for(const row of results.rows)if("doc"in row&&row.doc&&this.isChunkDoc(row.doc)){const chunk=row.doc;resultMap.set(chunk._id,chunk)}else{if(!this.isMissingError(row))throw new LiveSyncError(`Failed to read chunk ${row.key}`,{status:404,cause:this.getError(row)});{const idFromRow="string"==typeof row.key?row.key:void 0;idFromRow&&remainingIds.push(idFromRow)}}}catch(error){if(error instanceof LiveSyncError)throw error;Logger("Database read error!",LOG_LEVEL_VERBOSE);Logger(error,LOG_LEVEL_VERBOSE);return ids.map(()=>!1)}if(0===remainingIds.length)return ids.map(id=>{var _a13;return null!=(_a13=resultMap.get(id))&&_a13});const nextResults=await next2(remainingIds),nextResultMap=new Map(remainingIds.map((id,index6)=>[id,nextResults[index6]])),mergedResults=[...ids.map(id=>{var _a13,_b6;return null!=(_b6=null!=(_a13=resultMap.get(id))?_a13:nextResultMap.get(id))&&_b6})];return mergedResults}};CacheLayer=class{constructor(maxCacheSize){__publicField(this,"caches",new Map);__publicField(this,"maxCacheSize");__publicField(this,"allocCount",0);__publicField(this,"derefCount",0);this.maxCacheSize=maxCacheSize}getCachedChunk(id){if(!this.caches.has(id))return!1;const weakRef=this.caches.get(id);if(weakRef){const cachedChunk=weakRef.deref();if(cachedChunk)return cachedChunk;this.derefCount++;this.deleteCachedChunk(id);return!1}return!1}getChunkIDFromCache(data){for(const[id,weakRef]of this.caches){const chunk=weakRef.deref();if(chunk){if(chunk.data===data)return id}else{this.derefCount++;this.deleteCachedChunk(id)}}return!1}cacheChunk(chunk){if(this.getCachedChunk(chunk._id))this.reorderChunk(chunk._id);else{this.caches.set(chunk._id,new FallbackWeakRef(chunk));this.allocCount++;if(this.caches.size>this.maxCacheSize)do{const firstKey=this.caches.keys().next().value;firstKey&&this.caches.delete(firstKey)}while(this.caches.size>this.maxCacheSize)}}reorderChunk(id){const chunk=this.getCachedChunk(id);if(chunk){this.caches.delete(id);this.caches.set(id,new FallbackWeakRef(chunk))}}deleteCachedChunk(id){this.caches.has(id)&&this.caches.delete(id)}clearCaches(){this.caches.clear();this.allocCount=0;this.derefCount=0}tearDown(){this.clearCaches()}getStatistics(){return{size:this.caches.size,allocCount:this.allocCount,derefCount:this.derefCount}}async read(ids,options,next2){if(options.skipCache)return next2(ids);const resultMap=new Map,remainingIds=[];for(const id of ids){const cached=this.getCachedChunk(id);if(cached){this.reorderChunk(id);resultMap.set(id,cached)}else remainingIds.push(id)}if(0===remainingIds.length)return ids.map(id=>resultMap.get(id)||!1);const nextResults=await next2(remainingIds),nextResultMap=new Map(remainingIds.map((id,index6)=>[id,nextResults[index6]]));return ids.map(id=>{var _a13,_b6;return null!=(_b6=null!=(_a13=resultMap.get(id))?_a13:nextResultMap.get(id))&&_b6})}async write(chunks,options,origin2,next2){const filtered=[],cachedCount=chunks.length;for(const chunk of chunks){const cached=this.getCachedChunk(chunk._id);cached?this.reorderChunk(chunk._id):filtered.push(chunk)}const result=await next2(filtered);if(result.result&&!options.skipCache)for(const chunk of chunks)this.cacheChunk(chunk);result.processed&&(result.processed.cached=cachedCount-filtered.length);return result}};DEFAULT_CHUNK_DELIVERY_STALL_TIMEOUT_MS=3e5;ChunkDeliveryCoordinator=class{constructor(finiteReplicationActivity){__publicField(this,"finiteReplicationActivity");__publicField(this,"activeClaimCounts",new Map);__publicField(this,"claimReleases",new Set);__publicField(this,"listeners",new Set);__publicField(this,"finiteActivityWasActive",!1);__publicField(this,"finiteActivityChanged",()=>{var _a13,_b6;const active=(null!=(_b6=null==(_a13=this.finiteReplicationActivity)?void 0:_a13.value)?_b6:0)>0;if(active!==this.finiteActivityWasActive){this.finiteActivityWasActive=active;this.notifyChanged()}});__publicField(this,"disposed",!1);var _a13,_b6;this.finiteReplicationActivity=finiteReplicationActivity;this.finiteActivityWasActive=(null!=(_a13=null==finiteReplicationActivity?void 0:finiteReplicationActivity.value)?_a13:0)>0;null==(_b6=this.finiteReplicationActivity)||_b6.onChanged(this.finiteActivityChanged)}claim(ids,options={}){var _a13,_b6;if(this.disposed)throw new Error("Cannot claim chunk delivery activity after the coordinator has been disposed.");const pending3=new Set(ids),resolver2=promiseWithResolvers();if(0===pending3.size){resolver2.resolve();return{done:resolver2.promise,pendingIds:[],release:()=>{},settle:()=>{},touch:()=>{}}}const stallTimeoutMs=null!=(_a13=options.stallTimeoutMs)?_a13:DEFAULT_CHUNK_DELIVERY_STALL_TIMEOUT_MS;let timer,released=!1;const clearTimer=()=>{if(void 0!==timer){compatGlobal.clearTimeout(timer);timer=void 0}},removeActiveIds=activeIds=>{var _a14;for(const id of activeIds){const count=null!=(_a14=this.activeClaimCounts.get(id))?_a14:0;count<=1?this.activeClaimCounts.delete(id):this.activeClaimCounts.set(id,count-1)}},release=()=>{if(released)return;released=!0;clearTimer();const activeIds=[...pending3];pending3.clear();removeActiveIds(activeIds);this.claimReleases.delete(release);resolver2.resolve();activeIds.length>0&&this.notifyChanged(activeIds)},armStallTimer=()=>{clearTimer();released||0===pending3.size||stallTimeoutMs<=0||(timer=compatGlobal.setTimeout(()=>{var _a14;timer=void 0;const stalledIds=[...pending3];release();null==(_a14=options.onStalled)||_a14.call(options,stalledIds)},stallTimeoutMs))};for(const id of pending3)this.activeClaimCounts.set(id,(null!=(_b6=this.activeClaimCounts.get(id))?_b6:0)+1);this.claimReleases.add(release);this.notifyChanged([...pending3]);armStallTimer();return{done:resolver2.promise,get pendingIds(){return[...pending3]},release,settle:id=>{if(!released&&pending3.delete(id)){removeActiveIds([id]);this.notifyChanged([id]);0===pending3.size?release():armStallTimer()}},touch:armStallTimer}}isActivityActiveFor(id){return this.isClaimActiveFor(id)||this.isFiniteReplicationActive()}isClaimActiveFor(id){return this.activeClaimCounts.has(id)}isFiniteReplicationActive(){var _a13,_b6;return(null!=(_b6=null==(_a13=this.finiteReplicationActivity)?void 0:_a13.value)?_b6:0)>0}onChanged(listener){this.listeners.add(listener);return()=>this.listeners.delete(listener)}dispose(){var _a13;if(!this.disposed){this.disposed=!0;null==(_a13=this.finiteReplicationActivity)||_a13.offChanged(this.finiteActivityChanged);for(const release of[...this.claimReleases])release();this.listeners.clear()}}notifyChanged(ids){for(const listener of this.listeners)listener(ids)}};ArrivalWaitLayer=class{constructor(eventEmitter2,deliveryCoordinator,recheckAvailability){__publicField(this,"recheckAvailability");__publicField(this,"waitingMap",new Map);__publicField(this,"eventEmitter");__publicField(this,"deliveryCoordinator");__publicField(this,"ownsDeliveryCoordinator");__publicField(this,"stopObservingActivity");this.recheckAvailability=recheckAvailability;this.eventEmitter=eventEmitter2;this.deliveryCoordinator=null!=deliveryCoordinator?deliveryCoordinator:new ChunkDeliveryCoordinator;this.ownsDeliveryCoordinator=void 0===deliveryCoordinator;this.stopObservingActivity=this.deliveryCoordinator.onChanged(ids=>this.refreshActivity(ids))}enqueueWaiting(id){const previous=this.waitingMap.get(id);if(previous)return previous.resolver.promise;const resolver2=promiseWithResolvers();this.waitingMap.set(id,{activityVersion:0,observedActivity:!1,resolver:resolver2});return resolver2.promise}settle(id,value){const queue2=this.waitingMap.get(id);if(queue2){this.waitingMap.delete(id);queue2.resolver.resolve(value)}}async settleAfterObservedActivity(ids){var _a13;const candidates=ids.flatMap(id=>{const queue2=this.waitingMap.get(id);if(!(null==queue2?void 0:queue2.observedActivity)||this.deliveryCoordinator.isActivityActiveFor(id))return[];const version2=++queue2.activityVersion;return[{id,version:version2}]});if(0===candidates.length)return;let results;try{results=this.recheckAvailability?await this.recheckAvailability(candidates.map(({id})=>id)):candidates.map(()=>!1)}catch(error){Logger("Could not recheck chunk availability after finite delivery activity completed.",LOG_LEVEL_VERBOSE);Logger(error,LOG_LEVEL_VERBOSE);results=candidates.map(()=>!1)}for(let index6=0;index6<candidates.length;index6++){const{id,version:version2}=candidates[index6],queue2=this.waitingMap.get(id);if(!queue2||queue2.activityVersion!==version2)continue;const result=null!=(_a13=results[index6])&&_a13;result?this.settle(id,result):this.deliveryCoordinator.isActivityActiveFor(id)?this.refreshActivity([id]):this.settle(id,!1)}}refreshActivity(ids=[...this.waitingMap.keys()]){const completedActivityIds=[];for(const id of ids){const queue2=this.waitingMap.get(id);if(queue2)if(this.deliveryCoordinator.isActivityActiveFor(id)){queue2.observedActivity=!0;queue2.activityVersion++}else queue2.observedActivity?completedActivityIds.push(id):this.settle(id,!1)}completedActivityIds.length>0&&this.settleAfterObservedActivity(completedActivityIds)}onChunkArrived(doc,deleted=!1){this.settle(doc._id,!doc._deleted&&!deleted&&doc)}onMissingChunk(id){this.settle(id,!1)}async read(ids,options,next2){var _a13;const waitForDelivery=null!=(_a13=options.waitForDelivery)?_a13:void 0===options.timeout||options.timeout>0;if(!waitForDelivery||0===ids.length)return ids.map(()=>!1);const tasks3=ids.map(id=>this.enqueueWaiting(id));options.preventRemoteRequest||this.eventEmitter("missingChunks",ids);this.refreshActivity(ids);return await Promise.all(tasks3)}clearWaiting(){for(const id of[...this.waitingMap.keys()])this.settle(id,!1)}tearDown(){this.stopObservingActivity();this.clearWaiting();this.ownsDeliveryCoordinator&&this.deliveryCoordinator.dispose()}getWaitingCount(){return this.waitingMap.size}};DatabaseWriteLayer=class{constructor(database){__publicField(this,"database");this.database=database}async write(chunks,options=void 0,origin2,next2){if(0===chunks.length)return next2([]);try{const result=await this.database.bulkDocs(chunks,{new_edits:!(null==options?void 0:options.force)}),failed2=result.filter(res2=>"error"in res2);if(failed2.some(res2=>409!==res2.status))throw new LiveSyncError(`Failed to write chunks: ${failed2.map(res2=>res2.error).join(", ")}`,{status:500});const conflictedChunkIDs=failed2.filter(res2=>"string"==typeof res2.id).map(res2=>res2.id),nextResult=await next2(chunks),writeResult={result:!0,processed:{cached:nextResult.processed.cached,hotPack:nextResult.processed.hotPack,written:result.length-failed2.length,duplicated:conflictedChunkIDs.length}};conflictedChunkIDs.length;return writeResult}catch(error){if(error instanceof LiveSyncError)throw error;throw new LiveSyncError("Database write layer error!",{status:500,cause:error})}}};LayeredChunkManager=class{constructor(options){__publicField(this,"options");__publicField(this,"eventTarget",new EventTarget);__publicField(this,"cacheLayer");__publicField(this,"databaseReadLayer");__publicField(this,"readLayers");__publicField(this,"writeLayers");__publicField(this,"arrivalWaitLayer");__publicField(this,"deliveryCoordinator");__publicField(this,"abort",new AbortController);__publicField(this,"offChangeHandler");__publicField(this,"initialised",Promise.resolve());__publicField(this,"onChunkArrivedHandler",this.onChunkArrived.bind(this));__publicField(this,"onChangeHandler",this.onChange.bind(this));__publicField(this,"onMissingChunkRemoteHandler",this.onMissingChunkRemote.bind(this));__publicField(this,"concurrentTransactions",0);__publicField(this,"stabilised",Promise.resolve());this.options=options;const settings=options.settingService.currentSettings(),maxCacheSize=10*settings.hashCacheMaxCount;this.cacheLayer=new CacheLayer(maxCacheSize);this.databaseReadLayer=new DatabaseReadLayer(this.database);this.deliveryCoordinator=new ChunkDeliveryCoordinator(options.finiteReplicationActivity);this.arrivalWaitLayer=new ArrivalWaitLayer((eventName,data)=>{"missingChunks"===eventName&&this.emitEvent(EVENT_MISSING_CHUNKS,data)},this.deliveryCoordinator,ids=>this.databaseReadLayer.read([...ids],{preventRemoteRequest:!0,skipCache:!0,waitForDelivery:!1},remaining=>Promise.resolve(remaining.map(()=>!1))));this.readLayers=[this.cacheLayer,this.databaseReadLayer,this.arrivalWaitLayer];this.writeLayers=[new DatabaseWriteLayer(this.database),this.cacheLayer];this.offChangeHandler=this.changeManager.addCallback(this.onChangeHandler);this.addListener(EVENT_CHUNK_FETCHED,this.onChunkArrivedHandler,{signal:this.abort.signal});this.addListener(EVENT_MISSING_CHUNK_REMOTE,this.onMissingChunkRemoteHandler,{signal:this.abort.signal});this.initialised=this._initialise()}get changeManager(){return this.options.changeManager}get database(){return this.options.database}get cacheStatistics(){return this.cacheLayer.getStatistics()}addListener(type,listener,options){const callback=ev=>{listener.call(this,ev.detail)};this.eventTarget.addEventListener(type,callback,options);return()=>{this.eventTarget.removeEventListener(type,callback,options)}}emitEvent(type,detail){const event2=new CustomEvent(type,{detail});this.eventTarget.dispatchEvent(event2)}async _initialise(){Logger("ChunkManager initialised",LOG_LEVEL_VERBOSE);return await Promise.resolve()}destroy(){const layers=unique([...this.readLayers,...this.writeLayers]);this.abort.abort();this.offChangeHandler();for(const layer of layers)layer.tearDown&&layer.tearDown();this.deliveryCoordinator.dispose()}getCachedChunk(id){return this.cacheLayer.getCachedChunk(id)}getChunkIDFromCache(data){return this.cacheLayer.getChunkIDFromCache(data)}cacheChunk(chunk){this.cacheLayer.cacheChunk(chunk)}clearCaches(){this.cacheLayer.clearCaches()}async read(ids,options,preloadedChunks){const order=[...ids],resultMap=new Map(ids.map(id=>[id,!1])),readIds=new Set([...resultMap.keys()]);if(preloadedChunks)for(const[id,chunk]of Object.entries(preloadedChunks))if(this.isChunkDoc(chunk)){this.cacheLayer.cacheChunk(chunk);resultMap.set(id,chunk);readIds.delete(id)}const results=await this.executeReadPipeline([...readIds],options);for(let i3=0;i3<results.length;i3++)if(results[i3]){const chunk=results[i3];resultMap.set(chunk._id,chunk)}return order.map(id=>resultMap.get(id)||!1)}executeReadPipeline(ids,options){let layerIndex=0;const layers=this.readLayers,executeNextLayer=remaining=>{if(layerIndex>=layers.length)return Promise.resolve(remaining.map(()=>!1));const layer=layers[layerIndex];layerIndex++;return layer.read(remaining,options,executeNextLayer)};return executeNextLayer(ids)}async write(chunks,options,origin2){const result=await this.executeWritePipeline(chunks,options,origin2);return result}executeWritePipeline(chunks,options,origin2){let layerIndex=0;const layers=this.writeLayers,executeNextLayer=remaining=>{if(layerIndex>=layers.length)return Promise.resolve({result:!0,processed:{cached:0,hotPack:0,written:0,duplicated:0}});const layer=layers[layerIndex];layerIndex++;return layer.write(remaining,options,origin2,executeNextLayer)};return executeNextLayer(chunks)}isChunkDoc(doc){return"object"==typeof doc&&null!==doc&&("_id"in doc&&"type"in doc&&(doc&&"string"==typeof doc._id&&"leaf"===doc.type))}onChunkArrived(doc,deleted=!1){this.arrivalWaitLayer.onChunkArrived(doc,deleted)}onChange(change){const doc=change.doc;doc&&doc._id&&"leaf"===doc.type&&this.onChunkArrived(doc,change.deleted)}onMissingChunkRemote(id){this.arrivalWaitLayer.onMissingChunk(id)}async transaction(callback){await this.initialised;await this.stabilised;this.concurrentTransactions++;try{const result=await callback();return result}finally{this.concurrentTransactions--;if(0===this.concurrentTransactions){Logger("All transactions completed. Performing stabilisation.",LOG_LEVEL_VERBOSE);await this._stabilise()}else Logger(`Transaction completed. Remaining: ${this.concurrentTransactions}`,LOG_LEVEL_VERBOSE)}}async _stabilise(){const pr=promiseWithResolvers();this.stabilised=pr.promise;try{await this.__stabilise()}finally{pr.resolve()}}__stabilise(){return Promise.resolve()}};EVENT_MISSING_CHUNKS="missingChunks";EVENT_MISSING_CHUNK_REMOTE="missingChunkRemote";EVENT_CHUNK_FETCHED="chunkFetched";BATCH_SIZE=100;ChunkFetcher=class{constructor(options){__publicField(this,"options");__publicField(this,"queue",[]);__publicField(this,"pendingClaims",new Map);__publicField(this,"destroyed",!1);__publicField(this,"abort",new AbortController);__publicField(this,"onEventHandler",this.onEvent.bind(this));__publicField(this,"currentProcessing",0);__publicField(this,"previousRequestTime",0);this.options=options;this.chunkManager.addListener(EVENT_MISSING_CHUNKS,this.onEventHandler,{signal:this.abort.signal})}get chunkManager(){return this.options.chunkManager}get interval(){const settings=this.options.settingService.currentSettings();return settings.minimumIntervalOfReadChunksOnline||DEFAULT_SETTINGS.minimumIntervalOfReadChunksOnline}get concurrency(){const settings=this.options.settingService.currentSettings();return settings.concurrencyOfReadChunksOnline||DEFAULT_SETTINGS.concurrencyOfReadChunksOnline}destroy(){if(this.destroyed)return;this.destroyed=!0;this.abort.abort();this.queue=[];const pendingDeliveries=new Set(this.pendingClaims.values());this.pendingClaims.clear();for(const pending3 of pendingDeliveries){pending3.resolveActivityBoundary(!1);pending3.claim.release()}}onEvent(ids){if(this.destroyed)return;const claimedIds=this.ensureClaims(ids);this.queue=unique([...this.queue,...claimedIds]);this.canRequestMore()&&compatGlobal.setTimeout(()=>{this.requestMissingChunks()},1)}ensureClaims(ids){var _a13;const unclaimedIds=unique(ids.filter(id=>!this.pendingClaims.has(id)));if(0===unclaimedIds.length)return[];let pending3;const activityBoundary=promiseWithResolvers(),claim=this.chunkManager.deliveryCoordinator.claim(unclaimedIds,{stallTimeoutMs:null!=(_a13=this.options.deliveryStallTimeoutMs)?_a13:DEFAULT_CHUNK_DELIVERY_STALL_TIMEOUT_MS,onStalled:stalledIds=>this.onClaimStalled(pending3,stalledIds)});pending3={activityBoundaryEntered:activityBoundary.promise,claim,resolveActivityBoundary:activityBoundary.resolve};for(const id of unclaimedIds)this.pendingClaims.set(id,pending3);this.options.replicatorService.runBoundedRemoteActivity(()=>{pending3.claim.touch();pending3.resolveActivityBoundary(!0);return claim.done},{label:"chunk-fetch"}).catch(error=>{const abandonedIds=claim.pendingIds;pending3.resolveActivityBoundary(!1);this.removePendingDelivery(pending3,abandonedIds);claim.release();Logger("The chunk-delivery activity runner rejected before the claim settled.",LOG_LEVEL_VERBOSE);Logger(error,LOG_LEVEL_VERBOSE)});return unclaimedIds}removePendingDelivery(pending3,ids){for(const id of ids)this.pendingClaims.get(id)===pending3&&this.pendingClaims.delete(id);const removed=new Set(ids);this.queue=this.queue.filter(id=>!(removed.has(id)&&!this.pendingClaims.has(id)))}onClaimStalled(pending3,stalledIds){pending3.resolveActivityBoundary(!1);this.removePendingDelivery(pending3,stalledIds);Logger(`Chunk delivery stalled for the following IDs: ${stalledIds.join(", ")}`,LOG_LEVEL_VERBOSE)}settleClaim(id){const pending3=this.pendingClaims.get(id);if(pending3){this.pendingClaims.delete(id);pending3.claim.settle(id)}}touchClaims(ids){const pendingDeliveries=new Set(ids.map(id=>this.pendingClaims.get(id)).filter(pending3=>void 0!==pending3));for(const pending3 of pendingDeliveries)pending3.claim.touch()}async waitForActivityBoundary(ids){const pendingDeliveries=new Set(ids.map(id=>this.pendingClaims.get(id)).filter(pending3=>void 0!==pending3)),entered=new Map(await Promise.all([...pendingDeliveries].map(async pending3=>[pending3,await pending3.activityBoundaryEntered])));return ids.filter(id=>{const pending3=this.pendingClaims.get(id);return void 0!==pending3&&!0===entered.get(pending3)})}canRequestMore(){return this.currentProcessing<this.concurrency&&this.queue.length>0}async requestMissingChunks(){if(this.destroyed||!this.canRequestMore())return;let requestIDs=[];try{let isValidChunk2=function(chunk){return chunk&&"string"==typeof(null==chunk?void 0:chunk._id)&&"string"==typeof(null==chunk?void 0:chunk.data)};this.currentProcessing++;requestIDs=this.queue.splice(0,BATCH_SIZE);this.ensureClaims(requestIDs);requestIDs=await this.waitForActivityBoundary(requestIDs);if(0===requestIDs.length)return;this.touchClaims(requestIDs);const now3=Date.now(),timeSinceLastRequest=now3-this.previousRequestTime;this.previousRequestTime=now3;const timeToWait=Math.max(this.interval-timeSinceLastRequest,0);timeToWait>0&&await delay(timeToWait);this.touchClaims(requestIDs);const replicator=this.options.replicatorService.getActiveReplicator();if(!replicator){Logger("No active replicator was found to request missing chunks.");return}const fetched=await replicator.fetchRemoteChunks(requestIDs,!1);this.touchClaims(requestIDs);if(!fetched){Logger(`No chunks were found for the following IDs: ${requestIDs.join(", ")}`);for(const chunkID of requestIDs)this.chunkManager.emitEvent(EVENT_MISSING_CHUNK_REMOTE,chunkID);return}const chunks=fetched.filter(chunk=>isValidChunk2(chunk));if(chunks.length!==fetched.length){Logger(`Some fetched chunks are invalid and will be ignored: (${fetched.length-chunks.length} / ${fetched.length}).`,LOG_LEVEL_VERBOSE);for(const chunk of fetched)isValidChunk2(chunk)||Logger(`Invalid chunk: ${JSON.stringify(chunk)}`,LOG_LEVEL_VERBOSE)}0===chunks.length&&Logger(`No valid chunks were found for the following IDs: ${requestIDs.join(", ")}`);const missingIDs=requestIDs.filter(id=>!chunks.some(chunk=>chunk._id===id));try{if(0===chunks.length)return;Logger(`Writing fetched chunks (${chunks.length}) to the database...`);const result=await this.chunkManager.write(chunks,{skipCache:!0,force:!0},"ChunkFetcher");this.touchClaims(requestIDs);!0===result.result?Logger(`Fetched chunks were stored successfully: ${chunks.length}`,LOG_LEVEL_VERBOSE):Logger(`Fetched chunks could not be stored: ${chunks.map(chunk=>chunk._id).join(", ")}`,LOG_LEVEL_VERBOSE)}catch(error){Logger("An error occurred while storing fetched chunks!",LOG_LEVEL_VERBOSE);Logger(error,LOG_LEVEL_VERBOSE)}finally{for(const chunk of chunks)this.chunkManager.emitEvent(EVENT_CHUNK_FETCHED,chunk);for(const chunkID of missingIDs)this.chunkManager.emitEvent(EVENT_MISSING_CHUNK_REMOTE,chunkID)}}catch(error){Logger("An error occurred while fetching remote chunks.",LOG_LEVEL_VERBOSE);Logger(error,LOG_LEVEL_VERBOSE)}finally{for(const id of requestIDs)this.settleClaim(id);this.currentProcessing--;this.previousRequestTime=Date.now();this.queue.length>0&&compatGlobal.setTimeout(()=>{this.requestMissingChunks()},0)}}};MAX_CHUNKS_SIZE_ON_UI=1024;ContentSplitterCore=class{constructor(params){__publicField(this,"options");__publicField(this,"initialised");this.options=params;this.initialised=this.initialise(params)}};ContentSplitterBase=class extends ContentSplitterCore{initialise(_options3){this.options=_options3;return Promise.resolve(!0)}static isAvailableFor(setting){return!1}getParamsFor(entry){const settings=this.options.settingService.currentSettings(),maxChunkSize=Math.floor(MAX_DOC_SIZE_BIN*(1*(settings.customChunkSize||0)+1)),pieceSize=maxChunkSize,minimumChunkSize=settings.minimumChunkSize,path2=entry.path,plainSplit=shouldSplitAsPlainText(path2),maxSize=MAX_CHUNKS_SIZE_ON_UI,blob=entry.data instanceof Blob?entry.data:createTextBlob(entry.data);let useWorker=!0;settings.disableWorkerForGeneratingChunks&&(useWorker=!1);useWorker&&settings.processSmallFilesInUIThread&&blob.size<=maxSize&&(useWorker=!1);const useSegmenter=settings.chunkSplitterVersion===ChunkAlgorithms_V2Segmenter;return{blob,path:path2,pieceSize,plainSplit,minimumChunkSize,useWorker,useSegmenter}}async splitContent(entry){await this.initialised;const options=this.getParamsFor(entry),generator=await this.processSplit(options);return generator}};charNewLine="\n".charCodeAt(0);segmenter="Segmenter"in Intl?function wrapByDefault(func,onError){try{return func()}catch(ex){const error=ex instanceof Error?ex:new Error(String(ex));return onError(error)}}(()=>new Intl.Segmenter(compatGlobal.navigator.language,{granularity:"sentence"}),err3=>{Logger(`Failed to create Intl.Segmenter: ${err3.message}`,LOG_LEVEL_VERBOSE)}):void 0;MAX_ITEMS=100;ContentSplitterRabinKarp=class extends ContentSplitterBase{static isAvailableFor(setting){const settings=setting.settingService.currentSettings();return settings.chunkSplitterVersion===ChunkAlgorithms_RabinKarp}async processSplit(options){return options.useWorker?(await splitPieces2WorkerRabinKarp(options.blob,options.pieceSize,options.plainSplit,options.minimumChunkSize,options.path))():(await splitPiecesRabinKarp(options.blob,options.pieceSize,options.plainSplit,options.minimumChunkSize,options.path))()}};ContentSplitterV1=class extends ContentSplitterBase{static isAvailableFor(setting){const settings=setting.settingService.currentSettings();return settings.chunkSplitterVersion===ChunkAlgorithms_V1||""===settings.chunkSplitterVersion||void 0===settings.chunkSplitterVersion}async processSplit(options){return options.useWorker?(await splitPieces2Worker(options.blob,options.pieceSize,options.plainSplit,options.minimumChunkSize,options.path,options.useSegmenter))():(await splitPieces2(options.blob,options.pieceSize,options.plainSplit,options.minimumChunkSize,options.path,options.useSegmenter))()}};ContentSplitterV2=class extends ContentSplitterBase{static isAvailableFor(setting){const settings=setting.settingService.currentSettings();return settings.chunkSplitterVersion===ChunkAlgorithms_V2||settings.chunkSplitterVersion===ChunkAlgorithms_V2Segmenter}async processSplit(options){return options.useWorker?(await splitPieces2WorkerV2(options.blob,options.pieceSize,options.plainSplit,options.minimumChunkSize,options.path,options.useSegmenter))():(await splitPieces2V2(options.blob,options.pieceSize,options.plainSplit,options.minimumChunkSize,options.path,options.useSegmenter))()}};ContentSplitters=[ContentSplitterV1,ContentSplitterV2,ContentSplitterRabinKarp];ContentSplitter=class extends ContentSplitterCore{constructor(options){super(options)}initialise(options){for(const Splitter of ContentSplitters)if(Splitter.isAvailableFor(options)){this._activeSplitter=new Splitter(options);break}if(!this._activeSplitter)throw new Error("ContentSplitter: No available splitter for settings!!");return this._activeSplitter.initialise(options)}async splitContent(entry){await this.initialised;return this._activeSplitter.splitContent(entry)}};ChangeManager=class{constructor(options){__publicField(this,"_database");__publicField(this,"_callbacks",[]);__publicField(this,"_changes");this._database=options.database;this.setupListener()}addCallback(callback){const callbackHandler=new FallbackWeakRef(callback);this._callbacks.push(callbackHandler);return()=>{this._callbacks=this._callbacks.filter(cb2=>cb2!==callbackHandler)}}removeCallback(callback){this._callbacks=this._callbacks.filter(cb2=>cb2.deref()!==callback)}async _onChange(changeResponse){var _a13;if(this._callbacks.length){this._callbacks=this._callbacks.filter(callback=>void 0!==callback.deref());for(const callback of this._callbacks)try{const cb2=callback.deref();if(!cb2)continue;await Promise.resolve(cb2(changeResponse))}catch(err3){null==(_a13=this._changes)||_a13.emit("error",err3)}}}setupListener(){if(this._changes){const changes22=this._changes;this._changes=void 0;changes22.removeAllListeners();changes22.cancel()}const changes3=this._database.changes({since:"now",live:!0,include_docs:!0});changes3.on("change",change=>{this._onChange(change)});changes3.on("error",err3=>{Logger("ChangeManager Error watching changes");Logger(err3,LOG_LEVEL_VERBOSE)});this._changes=changes3}teardown(){var _a13,_b6;null==(_a13=this._changes)||_a13.removeAllListeners();null==(_b6=this._changes)||_b6.cancel();this._changes=void 0}restartWatch(){this.teardown();this.setupListener()}};import_diff_match_patch3=__toESM(require_diff_match_patch(),1);ConflictManager=class{constructor(options){__publicField(this,"options");this.options=options}get database(){return this.options.database}async getConflictedDoc(path2,rev3){try{const doc=await this.options.entryManager.getDBEntry(path2,{rev:rev3},!1,!0,!0);if(!1===doc)return!1;let data=getDocData(doc.data);"newnote"==doc.datatype?data=readString(new Uint8Array(decodeBinary(doc.data))):doc.datatype;return{deleted:doc.deleted||doc._deleted,ctime:doc.ctime,mtime:doc.mtime,rev:rev3,data}}catch(ex){if(isErrorOfMissingDoc(ex))return!1}return!1}async mergeSensibly(path2,baseRev,currentRev,conflictedRev){function splitDiffPiece(src){const ret=[];do{const d4=src.shift();if(void 0===d4)return ret;const pieces=d4[1].split(/([^\n]*\n)/).filter(f4=>""!=f4);if(void 0===d4)break;d4[0]!=import_diff_match_patch3.DIFF_DELETE&&ret.push(...pieces.map(e3=>[d4[0],e3]));if(d4[0]==import_diff_match_patch3.DIFF_DELETE){const nd=src.shift();if(void 0!==nd){const piecesPair=nd[1].split(/([^\n]*\n)/).filter(f4=>""!=f4);if(nd[0]==import_diff_match_patch3.DIFF_INSERT){for(const pt of pieces){ret.push([d4[0],pt]);const pairP=piecesPair.shift();void 0!==pairP&&ret.push([import_diff_match_patch3.DIFF_INSERT,pairP])}ret.push(...piecesPair.map(e3=>[nd[0],e3]))}else{ret.push(...pieces.map(e3=>[d4[0],e3]));ret.push(...piecesPair.map(e3=>[nd[0],e3]))}}else ret.push(...pieces.map(e3=>[0,e3]))}}while(src.length>0);return ret}var _a13,_b6,_c3,_d2;const baseLeaf=await this.getConflictedDoc(path2,baseRev),leftLeaf=await this.getConflictedDoc(path2,currentRev),rightLeaf=await this.getConflictedDoc(path2,conflictedRev);let autoMerge=!1;if(0==baseLeaf||0==leftLeaf||0==rightLeaf)return!1;if(leftLeaf.deleted||rightLeaf.deleted)return!1;const dmp=new import_diff_match_patch3.diff_match_patch,mapLeft=dmp.diff_linesToChars_(baseLeaf.data,leftLeaf.data),diffLeftSrc=dmp.diff_main(mapLeft.chars1,mapLeft.chars2,!1);dmp.diff_charsToLines_(diffLeftSrc,mapLeft.lineArray);const mapRight=dmp.diff_linesToChars_(baseLeaf.data,rightLeaf.data),diffRightSrc=dmp.diff_main(mapRight.chars1,mapRight.chars2,!1);dmp.diff_charsToLines_(diffRightSrc,mapRight.lineArray);const diffLeft=splitDiffPiece(diffLeftSrc),diffRight=splitDiffPiece(diffRightSrc);let rightIdx=0,leftIdx=0;const merged=[];autoMerge=!0;LOOP_MERGE:do{if(leftIdx>=diffLeft.length&&rightIdx>=diffRight.length)break LOOP_MERGE;const leftItem=null!=(_a13=diffLeft[leftIdx])?_a13:[0,""],rightItem=null!=(_b6=diffRight[rightIdx])?_b6:[0,""];leftIdx++;rightIdx++;if(leftItem[0]!=import_diff_match_patch3.DIFF_EQUAL||rightItem[0]!=import_diff_match_patch3.DIFF_EQUAL||leftItem[1]!=rightItem[1]){if(leftItem[0]==import_diff_match_patch3.DIFF_DELETE&&rightItem[0]==import_diff_match_patch3.DIFF_DELETE&&leftItem[1]==rightItem[1]){const nextLeftIdx=leftIdx,nextRightIdx=rightIdx,[nextLeftItem,nextRightItem]=[null!=(_c3=diffLeft[nextLeftIdx])?_c3:[0,""],null!=(_d2=diffRight[nextRightIdx])?_d2:[0,""]],nextLeftIsInsert=nextLeftItem[0]==import_diff_match_patch3.DIFF_INSERT,nextRightIsInsert=nextRightItem[0]==import_diff_match_patch3.DIFF_INSERT;if(nextLeftIsInsert!=nextRightIsInsert){autoMerge=!1;break}if(nextLeftIsInsert&&nextRightIsInsert&&nextLeftItem[1]!=nextRightItem[1]){autoMerge=!1;break}merged.push(leftItem);continue}if(leftItem[0]!=import_diff_match_patch3.DIFF_INSERT||rightItem[0]!=import_diff_match_patch3.DIFF_INSERT)if(leftItem[0]!=import_diff_match_patch3.DIFF_INSERT){if(rightItem[0]!=import_diff_match_patch3.DIFF_INSERT){if(rightItem[1]!=leftItem[1]){Logger(`MERGING PANIC:${leftItem[0]},${leftItem[1]} == ${rightItem[0]},${rightItem[1]}`,LOG_LEVEL_VERBOSE);autoMerge=!1;break LOOP_MERGE}if(leftItem[0]==import_diff_match_patch3.DIFF_DELETE){if(rightItem[0]==import_diff_match_patch3.DIFF_EQUAL){merged.push(leftItem);continue}autoMerge=!1;break LOOP_MERGE}if(rightItem[0]==import_diff_match_patch3.DIFF_DELETE){if(leftItem[0]==import_diff_match_patch3.DIFF_EQUAL){merged.push(rightItem);continue}autoMerge=!1;break LOOP_MERGE}Logger(`Weird condition:${leftItem[0]},${leftItem[1]} == ${rightItem[0]},${rightItem[1]}`,LOG_LEVEL_VERBOSE);break LOOP_MERGE}leftIdx--;merged.push(rightItem)}else{rightIdx--;merged.push(leftItem)}else{if(leftItem[1]==rightItem[1]){merged.push(leftItem);continue}if(leftLeaf.mtime<=rightLeaf.mtime){merged.push(leftItem);merged.push(rightItem);continue}merged.push(rightItem);merged.push(leftItem)}}else merged.push(leftItem)}while(leftIdx<diffLeft.length||rightIdx<diffRight.length);if(autoMerge){Logger("Sensibly merge available",LOG_LEVEL_VERBOSE);return merged}return!1}async mergeObject(path2,baseRev,currentRev,conflictedRev){try{const baseLeaf=await this.getConflictedDoc(path2,baseRev),leftLeaf=await this.getConflictedDoc(path2,currentRev),rightLeaf=await this.getConflictedDoc(path2,conflictedRev);if(0==baseLeaf||0==leftLeaf||0==rightLeaf){Logger("Could not load leafs for merge",LOG_LEVEL_VERBOSE);Logger(`${baseLeaf?"base":"missing base"}, ${leftLeaf?"left":"missing left"}, ${rightLeaf?"right":"missing right"} }`,LOG_LEVEL_VERBOSE);return!1}if(leftLeaf.deleted||rightLeaf.deleted){Logger("Either is deleted",LOG_LEVEL_VERBOSE);return!1}const baseObj={data:tryParseJSON(baseLeaf.data,{})},leftObj={data:tryParseJSON(leftLeaf.data,{})},rightObj={data:tryParseJSON(rightLeaf.data,{})},diffLeft=generatePatchObj(baseObj,leftObj),diffRight=generatePatchObj(baseObj,rightObj),diffSetLeft=new Map(flattenObject(diffLeft)),diffSetRight=new Map(flattenObject(diffRight));for(const[key3,value]of diffSetLeft)diffSetRight.has(key3)&&diffSetRight.get(key3)==value&&diffSetRight.delete(key3);for(const[key3,value]of diffSetRight)if(diffSetLeft.has(key3)&&diffSetLeft.get(key3)!=value){Logger(`Conflicted key:${key3}`,LOG_LEVEL_VERBOSE);return!1}const patches=[{mtime:leftLeaf.mtime,patch:diffLeft},{mtime:rightLeaf.mtime,patch:diffRight}].sort((a2,b3)=>a2.mtime-b3.mtime);let newObj={...baseObj};for(const patch of patches)newObj=applyPatch(newObj,patch.patch);Logger("Object merge is applicable!",LOG_LEVEL_VERBOSE);return JSON.stringify(newObj.data)}catch(ex){Logger("Could not merge object");Logger(ex,LOG_LEVEL_VERBOSE);return!1}}async tryAutoMergeSensibly(path2,test,conflicts){var _a13,_b6;const conflictedRev=conflicts[0];let p2,commonBase="";try{const documentId=await this.options.pathService.path2id(path2),[currentBranch,conflictedBranch]=await Promise.all([this.database.get(documentId,{rev:test._rev,revs_info:!0}),this.database.get(documentId,{rev:conflictedRev,revs_info:!0})]),currentAvailable=new Set((currentBranch._revs_info||[]).filter(revision=>"available"===revision.status).map(revision=>revision.rev));commonBase=null!=(_b6=null==(_a13=(conflictedBranch._revs_info||[]).filter(revision=>"available"===revision.status&&currentAvailable.has(revision.rev)).sort((left,right)=>Number(right.rev.split("-")[0])-Number(left.rev.split("-")[0]))[0])?void 0:_a13.rev)?_b6:""}catch(ex){Logger(`Could not determine the common revision for ${path2}`,LOG_LEVEL_VERBOSE);Logger(ex,LOG_LEVEL_VERBOSE);return!1}if(commonBase){if(isSensibleMargeApplicable(path2)){const result=await this.mergeSensibly(path2,commonBase,test._rev,conflictedRev);if(result){p2=result.filter(e3=>e3[0]!=import_diff_match_patch3.DIFF_DELETE).map(e3=>e3[1]).join("");Logger(`Sensible merge:${path2}`,LOG_LEVEL_INFO)}else Logger("Sensible merge is not applicable.",LOG_LEVEL_VERBOSE)}else if(isObjectMargeApplicable(path2)){const result=await this.mergeObject(path2,commonBase,test._rev,conflictedRev);if(result){Logger(`Object merge:${path2}`,LOG_LEVEL_INFO);p2=result}else Logger("Object merge is not applicable..",LOG_LEVEL_VERBOSE)}if(void 0!==p2)return{result:p2,conflictedRev}}return!1}async tryAutoMerge(path2,enableMarkdownAutoMerge){const test=await this.options.entryManager.getDBEntry(path2,{conflicts:!0,revs_info:!0},!1,!1,!0);if(!1===test)return{ok:MISSING_OR_ERROR};if(null==test)return{ok:MISSING_OR_ERROR};if(!test._conflicts)return{ok:NOT_CONFLICTED};if(0==test._conflicts.length)return{ok:NOT_CONFLICTED};const conflictCandidates=await Promise.all(test._conflicts.map(async revision=>({revision,leaf:await this.getConflictedDoc(path2,revision)})));conflictCandidates.sort(compareConflictCandidates);const conflicts=conflictCandidates.map(({revision})=>revision),leftLeaf=await this.getConflictedDoc(path2,test._rev),rightLeaf=conflictCandidates[0].leaf;if(!1!==leftLeaf&&!1!==rightLeaf&&leftLeaf.data==rightLeaf.data&&leftLeaf.deleted==rightLeaf.deleted)return{leftRev:test._rev,rightRev:conflicts[0],leftLeaf,rightLeaf};if((isSensibleMargeApplicable(path2)||isObjectMargeApplicable(path2))&&enableMarkdownAutoMerge){const autoMergeResult=await this.tryAutoMergeSensibly(path2,test,conflicts);if(!1!==autoMergeResult)return autoMergeResult}return{leftRev:test._rev,rightRev:conflicts[0],leftLeaf,rightLeaf}}};EntryManager=class{constructor(options){__publicField(this,"options");this.options=options}get localDatabase(){return this.options.database}get hashManager(){return this.options.hashManager}get chunkManager(){return this.options.chunkManager}get splitter(){return this.options.splitter}get serviceHost(){return{services:{setting:this.options.settingService,path:this.options.pathService},serviceModules:{}}}get isOnDemandChunkEnabled(){const settings=this.options.settingService.currentSettings();return settings.remoteType===REMOTE_COUCHDB&&!settings.useOnlyLocalChunk}isTargetFile(filenameSrc){return isTargetFile(this.serviceHost,filenameSrc)}async prepareChunk(piece){return await prepareChunk(this,piece)}async getDBEntryMeta(path2,opt,includeDeleted=!1){return await getDBEntryMetaByPath(this.serviceHost,this,path2,opt,includeDeleted)}async getDBEntry(path2,opt,dump=!1,waitForReady=!0,includeDeleted=!1){return await getDBEntryByPath(this.serviceHost,this,path2,opt,dump,waitForReady,includeDeleted)}async getDBEntryFromMeta(meta,dump=!1,waitForReady=!0){return await getDBEntryFromMeta(this.serviceHost,this,meta,dump,waitForReady)}async deleteDBEntry(path2,opt){return await deleteDBEntryByPath(this.serviceHost,this,path2,opt)}async storeDeletionAtRevision(path2,baseRevision){return await storeDeletionByPathAtRevision(this.serviceHost,this,path2,baseRevision)}async putDBEntry(note,onlyChunks,conflictBaseRev){return await putDBEntry(this.serviceHost,this,note,onlyChunks,conflictBaseRev)}async putDBEntryWithLiveBaseRevision(note,baseRevision,onlyChunks){return await putDBEntryWithLiveBaseRevision(this.serviceHost,this,note,baseRevision,onlyChunks)}};HashEncryptedPrefix="+";HashManagerCore=class{constructor(options){__publicField(this,"settingService");__publicField(this,"useEncryption",!1);__publicField(this,"hashedPassphrase","");__publicField(this,"hashedPassphrase32",0);__publicField(this,"options");__publicField(this,"initialiseTask");this.options=options;this.settingService=options.settingService;this.applyOptions(options)}applyOptions(options){var _a13;options&&(this.options=options);const settings=this.options.settingService.currentSettings();this.useEncryption=null!=(_a13=settings.encrypt)&&_a13;const passphrase=settings.passphrase||"",usingLetters=~~(passphrase.length/4*3),passphraseForHash=SALT_OF_ID+passphrase.substring(0,usingLetters);this.hashedPassphrase=fallbackMixedHashEach(passphraseForHash);this.hashedPassphrase32=mixedHash(passphraseForHash,SEED_MURMURHASH)[0]}initialise(){if(this.initialiseTask)return this.initialiseTask;this.initialiseTask=this.processInitialise();return this.initialiseTask}async computeHash(piece){return this.useEncryption?HashEncryptedPrefix+await this.computeHashWithEncryption(piece):await this.computeHashWithoutEncryption(piece)}static isAvailableFor(hashAlg){return!1}};XXHashHashManager=class extends HashManagerCore{constructor(options){super(options);__publicField(this,"xxhash")}async processInitialise(){this.xxhash=await e();return!0}};XXHash32RawHashManager=class extends XXHashHashManager{static isAvailableFor(hashAlg){return hashAlg===HashAlgorithms_LEGACY}computeHashWithEncryption(piece){return Promise.resolve((this.xxhash.h32Raw((new TextEncoder).encode(piece))^this.hashedPassphrase32^piece.length).toString(36))}computeHashWithoutEncryption(piece){return Promise.resolve((this.xxhash.h32Raw((new TextEncoder).encode(piece))^piece.length).toString(36))}};XXHash64HashManager=class extends XXHashHashManager{static isAvailableFor(hashAlg){return hashAlg===HashAlgorithms_XXHASH64}computeHashWithEncryption(piece){return Promise.resolve(this.xxhash.h64(`${piece}-${this.hashedPassphrase}-${piece.length}`).toString(36))}computeHashWithoutEncryption(piece){return Promise.resolve(this.xxhash.h64(`${piece}-${piece.length}`).toString(36))}};FallbackWasmHashManager=class extends XXHashHashManager{static isAvailableFor(hashAlg){return!0}computeHashWithEncryption(piece){return Promise.resolve(this.xxhash.h32(`${piece}-${this.hashedPassphrase}-${piece.length}`).toString(36))}computeHashWithoutEncryption(piece){return Promise.resolve(this.xxhash.h32(`${piece}-${piece.length}`).toString(36))}};PureJSHashManager=class extends HashManagerCore{static isAvailableFor(hashAlg){return hashAlg===HashAlgorithms_MIXED_PUREJS}processInitialise(){return Promise.resolve(!0)}computeHashWithEncryption(input){return Promise.resolve(fallbackMixedHashEach(`${input}${this.hashedPassphrase}${input.length}`))}computeHashWithoutEncryption(input){return Promise.resolve(fallbackMixedHashEach(`${input}-${input.length}`))}};SHA1HashManager=class extends HashManagerCore{static isAvailableFor(hashAlg){return hashAlg===HashAlgorithms_SHA1}processInitialise(){return Promise.resolve(!0)}computeHashWithEncryption(input){return sha12(`${input}-${this.hashedPassphrase}-${input.length}`)}computeHashWithoutEncryption(input){return sha12(`${input}-${input.length}`)}};FallbackPureJSHashManager=class extends PureJSHashManager{static isAvailableFor(_hashAlg){return!0}};HashManagers=[XXHash64HashManager,XXHash32RawHashManager,SHA1HashManager,PureJSHashManager,FallbackWasmHashManager,FallbackPureJSHashManager];HashManager=class extends HashManagerCore{constructor(options){super(options);__publicField(this,"manager")}static isAvailableFor(hashAlg){return HashManagers.some(manager=>manager.isAvailableFor(hashAlg))}async setManager(){const settings=this.options.settingService.currentSettings();for(const Manager of HashManagers)if(Manager.isAvailableFor(settings.hashAlg)){this.manager=new Manager(this.options);return await this.manager.initialise()}throw new Error(`HashManager for ${settings.hashAlg} is not available`)}async processInitialise(){const settings=this.options.settingService.currentSettings();if(await this.setManager()){Logger(`HashManager for ${settings.hashAlg} has been initialised`,LOG_LEVEL_VERBOSE);return!0}Logger(`HashManager for ${settings.hashAlg} failed to initialise`);throw new Error(`HashManager for ${settings.hashAlg} failed to initialise`)}async computeHash(piece){return await this.manager.computeHash(piece)}computeHashWithoutEncryption(piece){return this.manager.computeHashWithoutEncryption(piece)}computeHashWithEncryption(piece){return this.manager.computeHashWithEncryption(piece)}};LiveSyncManagers=class{constructor(options){__publicField(this,"_pathService");__publicField(this,"_replicatorService");__publicField(this,"_settingService");__publicField(this,"_APIService");__publicField(this,"hashManager");__publicField(this,"chunkFetcher");__publicField(this,"changeManager");__publicField(this,"chunkManager");__publicField(this,"splitter");__publicField(this,"entryManager");__publicField(this,"conflictManager");__publicField(this,"options");__publicField(this,"log");this.options=options;this._APIService=options.APIService;this._pathService=options.pathService;this._replicatorService=options.replicatorService;this._settingService=options.settingService;this.log=createInstanceLogFunction("LiveSyncManagers",this._APIService);const{changeManager,hashManager,splitter,chunkManager,chunkFetcher,entryManager,conflictManager}=this.getManagerMembers();this.changeManager=changeManager;this.hashManager=hashManager;this.splitter=splitter;this.chunkManager=chunkManager;this.chunkFetcher=chunkFetcher;this.entryManager=entryManager;this.conflictManager=conflictManager}async teardownManagers(){this.log("Teardown LiveSync Managers...",LOG_LEVEL_VERBOSE);if(this.changeManager){this.changeManager.teardown();this.changeManager=void 0}if(this.chunkFetcher){this.chunkFetcher.destroy();this.chunkFetcher=void 0}if(this.chunkManager){this.chunkManager.destroy();this.chunkManager=void 0}this.log("Teardown LiveSync Managers... Done");return await Promise.resolve()}getManagerMembers(){this.log("Creating LiveSync Managers...");const database=this.options.database,changeManager=new ChangeManager({database}),hashManager=new HashManager({settingService:this.options.settingService}),splitter=new ContentSplitter({settingService:this.options.settingService}),chunkManager=new LayeredChunkManager({changeManager,database,settingService:this.options.settingService,finiteReplicationActivity:this.options.replicatorService.finiteReplicationActivityCount}),chunkFetcher=new ChunkFetcher({chunkManager,replicatorService:this.options.replicatorService,settingService:this.options.settingService}),entryManager=new EntryManager({database,hashManager,chunkManager,splitter,pathService:this._pathService,settingService:this.options.settingService}),conflictManager=new ConflictManager({entryManager,database,pathService:this._pathService});this.log("LiveSync Managers have been created");return{changeManager,hashManager,splitter,chunkManager,chunkFetcher,entryManager,conflictManager}}async initialise(){this.log("Initialising LiveSync Managers...",LOG_LEVEL_VERBOSE);await this.splitter.initialise({settingService:this.options.settingService});await this.hashManager.initialise();this.log("LiveSync Manager has been initialised")}async reinitialise(){await this.teardownManagers();const{changeManager,hashManager,splitter,chunkManager,chunkFetcher,entryManager,conflictManager}=this.getManagerMembers();this.changeManager=changeManager;this.hashManager=hashManager;this.splitter=splitter;this.chunkManager=chunkManager;this.chunkFetcher=chunkFetcher;this.entryManager=entryManager;this.conflictManager=conflictManager;await this.initialise()}clearCaches(){var _a13;null==(_a13=this.chunkManager)||_a13.clearCaches()}async prepareHashFunction(){this.hashManager=new HashManager({settingService:this.options.settingService});await this.hashManager.initialise()}};REMOTE_CHUNK_FETCHED="remote-chunk-fetched";LiveSyncLocalDB=class{constructor(dbname,env){__publicField(this,"auth");__publicField(this,"dbname");__publicField(this,"settings");__publicField(this,"localDatabase");__publicField(this,"_log");__publicField(this,"_managers");__publicField(this,"isReady",!1);__publicField(this,"needScanning",!1);__publicField(this,"env");__publicField(this,"offRemoteChunkFetchedHandler");__publicField(this,"databaseCloseCleanup");__publicField(this,"databaseUnloadNotification");this.auth={username:"",password:""};this.dbname=dbname;this.env=env;this._log=createInstanceLogFunction("LiveSyncLocalDB",this.env.services.API);this.refreshSettings()}get managers(){if(!this._managers)throw new Error("Managers are not ready yet.");return this._managers}clearCaches(){var _a13;null==(_a13=this._managers)||_a13.clearCaches()}async _prepareHashFunctions(){var _a13;await(null==(_a13=this._managers)?void 0:_a13.prepareHashFunction())}refreshSettings(){const settings=this.env.services.setting.currentSettings();this.settings=settings;this._prepareHashFunctions()}notifyDatabaseUnload(){this.databaseUnloadNotification||(this.databaseUnloadNotification=Promise.resolve().then(async()=>{await this.env.services.databaseEvents.onUnloadDatabase(this)}));return this.databaseUnloadNotification}onunload(){this.notifyDatabaseUnload()}async close(){var _a13,_b6;this._log("Database closed (by close)");this.isReady=!1;null==(_a13=this.offRemoteChunkFetchedHandler)||_a13.call(this);this.offRemoteChunkFetchedHandler=void 0;if(null!=this.localDatabase){const database=this.localDatabase;await database.close();(null==(_b6=this.databaseCloseCleanup)?void 0:_b6.database)===database&&await this.databaseCloseCleanup.promise;this.localDatabase===database&&(this.localDatabase=null)}this._managers=void 0;await this.notifyDatabaseUnload()}async teardownDatabaseDependencies(managers){var _a13;try{await Promise.resolve(null==(_a13=this.env.services.replicator.getActiveReplicator())?void 0:_a13.closeReplication())}catch(error){this._log("Failed to close replication while tearing down the local database.",LOG_LEVEL_VERBOSE);this._log(error,LOG_LEVEL_VERBOSE)}try{await managers.teardownManagers()}catch(error){this._log("Failed to tear down managers while closing the local database.",LOG_LEVEL_VERBOSE);this._log(error,LOG_LEVEL_VERBOSE)}}async rollbackFailedInitialisation(database,managers){var _a13,_b6;this.isReady=!1;null==(_a13=this.offRemoteChunkFetchedHandler)||_a13.call(this);this.offRemoteChunkFetchedHandler=void 0;const closeCleanup=(null==(_b6=this.databaseCloseCleanup)?void 0:_b6.database)===database?this.databaseCloseCleanup:void 0;if(closeCleanup)await closeCleanup.promise;else{database.removeAllListeners();await this.teardownDatabaseDependencies(managers);try{await database.close()}catch(error){this._log("Failed to close the database after its initialisation was rejected.",LOG_LEVEL_VERBOSE);this._log(error,LOG_LEVEL_VERBOSE)}}this.localDatabase===database&&(this.localDatabase=null);this._managers===managers&&(this._managers=void 0);try{await this.notifyDatabaseUnload()}catch(error){this._log("A database unload handler failed after initialisation was rejected.",LOG_LEVEL_VERBOSE);this._log(error,LOG_LEVEL_VERBOSE)}}onNewLeaf(chunk){var _a13;null==(_a13=this.managers.chunkManager)||_a13.emitEvent(EVENT_CHUNK_FETCHED,chunk)}async initializeDatabase(){await this._prepareHashFunctions();if(null!=this.localDatabase){this.localDatabase.removeAllListeners();await this.localDatabase.close()}this.localDatabase=null;this.localDatabase=this.env.services.database.createPouchDBInstance(this.dbname+SuffixDatabaseName,{auto_compaction:!1,revs_limit:100,deterministic_revs:!0});this.databaseUnloadNotification=void 0;const manager=new LiveSyncManagers({database:this.localDatabase,APIService:this.env.services.API,pathService:this.env.services.path,replicatorService:this.env.services.replicator,settingService:this.env.services.setting,databaseService:this.env.services.database});this._managers=manager;const openedDatabase=this.localDatabase;this.databaseCloseCleanup=void 0;try{if(!await this.env.services.databaseEvents.onDatabaseInitialisation(this)){await this.rollbackFailedInitialisation(openedDatabase,manager);this._log("Database initialisation was rejected by a required module.",LOG_LEVEL_NOTICE);return!1}this._log("Opening Database...");this._log("Database info",LOG_LEVEL_VERBOSE);this._log(JSON.stringify(await openedDatabase.info(),null,2),LOG_LEVEL_VERBOSE);await manager.initialise();openedDatabase.on("close",()=>{var _a13;this._log("Database closed.");this.isReady=!1;openedDatabase.removeAllListeners();(null==(_a13=this.databaseCloseCleanup)?void 0:_a13.database)!==openedDatabase&&(this.databaseCloseCleanup={database:openedDatabase,promise:this.teardownDatabaseDependencies(manager)})});const _instance2=new FallbackWeakRef(this),unload=this.env.services.context.events.onEvent(REMOTE_CHUNK_FETCHED,chunk=>{var _a13;null==_instance2.deref()&&unload();null==(_a13=_instance2.deref())||_a13.onNewLeaf(chunk)});this.offRemoteChunkFetchedHandler=unload;this.isReady=!0;const readyAccepted=await this.env.services.databaseEvents.onDatabaseHasReady();if(!readyAccepted||this.localDatabase!==openedDatabase||!this.isReady){await this.rollbackFailedInitialisation(openedDatabase,manager);this._log("Some module has prevented the database from being ready. The database is initialised but not ready for use.",LOG_LEVEL_NOTICE);return!1}this._log("Database is now ready.");return!0}catch(error){await this.rollbackFailedInitialisation(openedDatabase,manager);throw error}}async allChunks(includeDeleted=!1){const used=new Set,existing=new Map;let since=0;for(;;){const changes3=await this.localDatabase.changes({since,limit:100,include_docs:!0,conflicts:!0,style:includeDeleted?"all_docs":"main_only"});if(0==changes3.results.length)break;for(const change of changes3.results){const doc=change.doc;if("leaf"==doc.type){if(doc._deleted&&!includeDeleted)continue;existing.set(doc._id,doc)}if("children"in doc){if(change.deleted&&(!doc._conflicts||0==doc._conflicts.length))continue;doc.children.forEach(e3=>used.add(e3));if(doc._conflicts){const revs=await this.localDatabase.get(doc._id,{revs:!0,revs_info:!0}),mineRevInfo=revs._revs_info||[],keepRevs=new Set;for(const conflict of doc._conflicts){const conflictedRevs=await this.localDatabase.get(doc._id,{rev:conflict,revs:!0,revs_info:!0}),conflictedRevInfo=conflictedRevs._revs_info||[],diffRevs=mineRevInfo.filter(e3=>!conflictedRevInfo.some(f4=>f4.rev==e3.rev&&f4.status==e3.status)),diffRevs2=conflictedRevInfo.filter(e3=>!mineRevInfo.some(f4=>f4.rev==e3.rev&&f4.status==e3.status)),diffRevs3=diffRevs.concat(diffRevs2),sameRevs=mineRevInfo.filter(e3=>conflictedRevInfo.some(f4=>f4.rev==e3.rev&&f4.status==e3.status)).filter(e3=>"available"==e3.status).sort((a2,b3)=>getNoFromRev(b3.rev)-getNoFromRev(a2.rev)),sameRevsTop=sameRevs.length>0?[sameRevs[0].rev]:[],keepRevList=[...diffRevs3.filter(e3=>"available"==e3.status).map(e3=>e3.rev),...sameRevsTop];keepRevList.forEach(e3=>keepRevs.add(e3))}const detail=await this.localDatabase.bulkGet({docs:[...keepRevs.values()].map(e3=>({id:doc._id,rev:e3}))});for(const e3 of detail.results)if("docs"in e3){const docs=e3.docs;for(const doc2 of docs)"ok"in doc2&&"children"in doc2.ok&&doc2.ok.children.forEach(e22=>used.add(e22))}}}}since=changes3.results[changes3.results.length-1].seq}return{used,existing}}async resetDatabase(){var _a13;this.isReady=!1;await this.managers.teardownManagers();null==(_a13=this.env.services.replicator.getActiveReplicator())||_a13.closeReplication();if(!await this.env.services.databaseEvents.onResetDatabase(this)){Logger("Database reset has been prevented or failed on some modules.",LOG_LEVEL_NOTICE);return!1}Logger("Database closed for reset Database.");await this.localDatabase.destroy();this.localDatabase=null;if(!await this.initializeDatabase()){this._log("Local Database could not be reinitialised after reset.",LOG_LEVEL_NOTICE);return!1}this._log("Local Database Reset",LOG_LEVEL_NOTICE);return!0}async*findEntries(startKey,endKey,opt){let nextKey=startKey;""==endKey&&(endKey="􏿿");let req=this.allDocsRaw({limit:100,startkey:nextKey,endkey:endKey,include_docs:!0,...opt});do{const docs=await req;if(0===docs.rows.length)break;nextKey=`${docs.rows[docs.rows.length-1].id}`;req=this.allDocsRaw({limit:100,skip:1,startkey:nextKey,endkey:endKey,include_docs:!0,...opt});for(const row of docs.rows){const doc=row.doc;"type"in doc&&("newnote"!=doc.type&&"plain"!=doc.type||(yield doc))}}while(""!=nextKey)}async*findAllDocs(opt){const targets=[()=>this.findEntries("","_",null!=opt?opt:{}),()=>this.findEntries("_􏿿","h:",null!=opt?opt:{}),()=>this.findEntries("h:􏿿","",null!=opt?opt:{})];for(const targetFun of targets)yield*targetFun()}async*findEntryNames(startKey,endKey,opt){let nextKey=startKey;""==endKey&&(endKey="􏿿");let req=this.allDocsRaw({limit:100,startkey:nextKey,endkey:endKey,...opt});do{const docs=await req;if(0==docs.rows.length){nextKey="";break}nextKey=`${docs.rows[docs.rows.length-1].key}`;req=this.allDocsRaw({limit:100,skip:1,startkey:nextKey,endkey:endKey,...opt});for(const row of docs.rows)yield row.id}while(""!=nextKey)}async*findAllDocNames(opt){const targets=[()=>this.findEntryNames("","_",null!=opt?opt:{}),()=>this.findEntryNames("_􏿿","h:",null!=opt?opt:{}),()=>this.findEntryNames("h:􏿿","i:",null!=opt?opt:{}),()=>this.findEntryNames("i:􏿿","ix:",null!=opt?opt:{}),()=>this.findEntryNames("ix:􏿿","ps:",null!=opt?opt:{}),()=>this.findEntryNames("ps:􏿿","",null!=opt?opt:{})];for(const targetFun of targets){const target=targetFun();for await(const f4 of target)f4.startsWith("_")||f4!=VERSIONING_DOCID&&(yield f4)}}async*findAllNormalDocs(opt){const targets=[()=>this.findEntries("","_",null!=opt?opt:{}),()=>this.findEntries("_􏿿","h:",null!=opt?opt:{}),()=>this.findEntries("h:􏿿","i:",null!=opt?opt:{}),()=>this.findEntries("i:􏿿","ix:",null!=opt?opt:{}),()=>this.findEntries("ix:􏿿","ps:",null!=opt?opt:{}),()=>this.findEntries("ps:􏿿","",null!=opt?opt:{})];for(const targetFun of targets){const target=targetFun();for await(const f4 of target)f4._id.startsWith("_")||"newnote"!=f4.type&&"plain"!=f4.type||(yield f4)}}async removeRevision(docId,revision){try{const doc=await this.localDatabase.get(docId,{rev:revision});doc._deleted=!0;await this.localDatabase.put(doc);return!0}catch(ex){isErrorOfMissingDoc(ex)&&Logger(`Remove revision: Missing target revision, ${docId}-${revision}`,LOG_LEVEL_VERBOSE)}return!1}getRaw(docId,options){return this.localDatabase.get(docId,options||{})}removeRaw(docId,revision,options){return this.localDatabase.remove(docId,revision,options||{})}putRaw(doc,options){return this.localDatabase.put(doc,options||{})}allDocsRaw(options){return this.localDatabase.allDocs(options)}bulkDocsRaw(docs,options){return this.localDatabase.bulkDocs(docs,options||{})}isTargetFile(filenameSrc){return this.managers.entryManager.isTargetFile(filenameSrc)}async getDBEntryMeta(path2,opt,includeDeleted=!1){return await this.managers.entryManager.getDBEntryMeta(path2,opt,includeDeleted)}async getDBEntry(path2,opt,dump=!1,waitForReady=!0,includeDeleted=!1){return await this.managers.entryManager.getDBEntry(path2,opt,dump,waitForReady,includeDeleted)}async getDBEntryFromMeta(meta,dump=!1,waitForReady=!0){return await this.managers.entryManager.getDBEntryFromMeta(meta,dump,waitForReady)}async deleteDBEntry(path2,opt){return await this.managers.entryManager.deleteDBEntry(path2,opt)}async storeDeletionAtRevision(path2,baseRevision){return await this.managers.entryManager.storeDeletionAtRevision(path2,baseRevision)}async putDBEntry(note,onlyChunks,conflictBaseRev){return await this.managers.entryManager.putDBEntry(note,onlyChunks,conflictBaseRev)}async putDBEntryWithLiveBaseRevision(note,baseRevision,onlyChunks){return await this.managers.entryManager.putDBEntryWithLiveBaseRevision(note,baseRevision,onlyChunks)}async getConflictedDoc(path2,rev3){return await this.managers.conflictManager.getConflictedDoc(path2,rev3)}async tryAutoMerge(path2,enableMarkdownAutoMerge){return await this.managers.conflictManager.tryAutoMerge(path2,enableMarkdownAutoMerge)}};RECORD_SPLIT="\n";UNIT_SPLIT="";te4=new TextEncoder;JournalSyncCore=class{constructor(settings,store,env,storage){__publicField(this,"_settings");__publicField(this,"storage");__publicField(this,"hash","");__publicField(this,"processReplication");__publicField(this,"batchSize",100);__publicField(this,"env");__publicField(this,"store");__publicField(this,"requestedStop",!1);__publicField(this,"_currentCheckPointInfo",{...CheckPointInfoDefault});this._settings=settings;this.env=env;this.processReplication=async docs=>await env.services.replication.parseSynchroniseResult(docs);this.store=store;this.hash=this.getHash(settings);this.storage=storage;clearHandlers()}get db(){return this.env.services.database.localDatabase.localDatabase}get currentSettings(){return this.env.services.setting.currentSettings()}getInitialSyncParameters(){return Promise.resolve({...DEFAULT_SYNC_PARAMETERS,protocolVersion:ProtocolVersions_ADVANCED_E2EE,pbkdf2salt:""})}async getSyncParameters(){try{const downloadedData=await this.storage.download(DOCID_JOURNAL_SYNC_PARAMETERS,!0);if(!downloadedData)throw new SyncParamsNotFoundError("Missing sync parameters");const downloadedSyncParams=JSON.parse((new TextDecoder).decode(downloadedData));return downloadedSyncParams}catch(ex){Logger("Could not retrieve remote sync parameters",LOG_LEVEL_INFO);throw SyncParamsFetchError.fromError(ex)}}async putSyncParameters(params){try{const data=(new TextEncoder).encode(JSON.stringify(params));if(await this.storage.upload(DOCID_JOURNAL_SYNC_PARAMETERS,data,"application/json"))return!0;throw new SyncParamsUpdateError("Could not store remote sync parameters")}catch(ex){Logger("Could not upload sync parameters",LOG_LEVEL_INFO);Logger(ex,LOG_LEVEL_VERBOSE);throw SyncParamsUpdateError.fromError(ex)}}getHash(settings){return btoa(encodeURI([settings.endpoint,`${settings.bucket}${settings.bucketPrefix}`,settings.region].join()))}async downloadJson(key3){try{const data=await this.storage.download(key3,!0);return!!data&&JSON.parse((new TextDecoder).decode(data))}catch(ex){Logger(`Could not download json ${key3}`);Logger(ex,LOG_LEVEL_VERBOSE);return!1}}async downloadJsonWithResult(key3){const result=await this.storage.downloadWithResult(key3,!0);if(result.status!==JournalStorageReadStatuses_AVAILABLE)return result;try{return{status:JournalStorageReadStatuses_AVAILABLE,value:JSON.parse((new TextDecoder).decode(result.value))}}catch(ex){Logger(`Could not parse downloaded json ${key3}`);Logger(ex,LOG_LEVEL_VERBOSE);return{status:JournalStorageReadStatuses_UNAVAILABLE,error:ex}}}async uploadJson(key3,body){try{const data=(new TextEncoder).encode(JSON.stringify(body));return await this.storage.upload(key3,data,"application/json")}catch(ex){Logger(`Could not upload json ${key3}`);Logger(ex,LOG_LEVEL_VERBOSE);return!1}}applyNewConfig(settings,store,env){this._settings=settings;this.env=env;this.processReplication=async docs=>await env.services.replication.parseSynchroniseResult(docs);this.store=store;this.hash=this.getHash(settings);this.storage.applyNewConfig(settings);clearHandlers()}updateInfo(info3){var _a13,_b6,_c3,_d2,_e2,_f,_g;const old=this.env.services.replicator.replicationStatics.value;this.env.services.replicator.replicationStatics.value={sent:null!=(_a13=info3.sent)?_a13:old.sent,arrived:null!=(_b6=info3.arrived)?_b6:old.arrived,maxPullSeq:null!=(_c3=info3.maxPullSeq)?_c3:old.maxPullSeq,maxPushSeq:null!=(_d2=info3.maxPushSeq)?_d2:old.maxPushSeq,lastSyncPullSeq:null!=(_e2=info3.lastSyncPullSeq)?_e2:old.lastSyncPullSeq,lastSyncPushSeq:null!=(_f=info3.lastSyncPushSeq)?_f:old.lastSyncPushSeq,syncStatus:null!=(_g=info3.syncStatus)?_g:old.syncStatus}}async updateCheckPointInfo(func){const checkPointKey=`bucketsync-checkpoint-${this.hash}`,old=await this.getCheckpointInfo(),newInfo=func(old);this._currentCheckPointInfo=newInfo;await this.store.set(checkPointKey,newInfo);return newInfo}async getCheckpointInfo(){const checkPointKey=`bucketsync-checkpoint-${this.hash}`,old=await this.store.get(checkPointKey)||{},items=["knownIDs","sentIDs","receivedFiles","sentFiles"];for(const key3 of items){if(!(key3 in old))continue;const value=old[key3];value instanceof Set||(Array.isArray(value)?old[key3]=new Set(value):old[key3]=value&&"object"==typeof value?new Set(Object.keys(value)):new Set)}this._currentCheckPointInfo={...CheckPointInfoDefault,...old};return this._currentCheckPointInfo}resetAllCaches(){clearHandlers()}async resetCheckpointInfo(){await this.updateCheckPointInfo(info3=>({...CheckPointInfoDefault}));clearHandlers()}getJournalEpochFromSyncParams(params){return`${params.protocolVersion}:${params.pbkdf2salt}`}async ensureCheckpointCachesAreFresh(){let journalEpoch="";try{const params=await this.getSyncParameters();journalEpoch=this.getJournalEpochFromSyncParams(params)}catch(e3){return}const current=await this.getCheckpointInfo();if(current.journalEpoch===journalEpoch)return;const lastSentFile=[...current.sentFiles].sort().pop();if(!lastSentFile){await this.updateCheckPointInfo(info3=>({...info3,journalEpoch}));return}let remoteWipeConfirmed;try{const probe=await this.storage.listFiles(lastSentFile.slice(0,-1),1);remoteWipeConfirmed=probe[0]!==lastSentFile}catch(e3){remoteWipeConfirmed=!0}if(remoteWipeConfirmed){Logger("Journal epoch changed and remote wipe confirmed. Clearing dedupe caches.",LOG_LEVEL_NOTICE);await this.updateCheckPointInfo(info3=>({...info3,journalEpoch,knownIDs:new Set,sentIDs:new Set,receivedFiles:new Set,sentFiles:new Set}));clearHandlers()}else{await this.updateCheckPointInfo(info3=>({...info3,journalEpoch}));Logger("Journal epoch changed (remote files still present). Epoch updated; caches kept.",LOG_LEVEL_NOTICE)}}async isAvailable(){return await this.storage.isAvailable()}async resetBucket(){let files=[];try{do{files=await this.storage.listFiles("",100);if(0==files.length)break;await this.storage.deleteFiles(files)}while(0!=files.length);clearHandlers()}catch(ex){Logger("WARNING! Could not delete files.",LOG_LEVEL_NOTICE,"reset-bucket");Logger(ex,LOG_LEVEL_VERBOSE)}const journals=await this._getRemoteJournals();if(0==journals.length){Logger("Nothing to delete!",LOG_LEVEL_NOTICE);return!0}await this.storage.deleteFiles(journals);Logger(`${journals.length} items has been deleted!`,LOG_LEVEL_NOTICE);await this.resetCheckpointInfo();return!0}getRemoteKey(){return this.getHash(this._settings)}async getReplicationPBKDF2Salt(refresh){const server=this.getRemoteKey(),manager=createSyncParamsHanderForServer(server,{put:params=>this.putSyncParameters(params),get:()=>this.getSyncParameters(),create:()=>this.getInitialSyncParameters()});return await manager.getPBKDF2Salt(refresh)}isEncryptionPrevented(fileName){return!!fileName.endsWith(DOCID_JOURNAL_SYNC_PARAMETERS)}async decryptDataV2(encrypted,set2){const salt=await this.getReplicationPBKDF2Salt();return await decryptBinary(encrypted,set2.passphrase,salt)}async decryptDataV1(encrypted,set2){return await decryptBinary2(encrypted,set2.passphrase,set2.useDynamicIterationCount)}async decryptDownloaded(key3,encrypted,set2){const u2=new Uint8Array(encrypted);try{if(!set2.encrypt||""==set2.passphrase||this.isEncryptionPrevented(key3))return u2;if(set2.E2EEAlgorithm===E2EEAlgorithms.ForceV1)return await this.decryptDataV1(u2,set2);const decrypted=await this.decryptDataV2(u2,set2);return decrypted}catch(ex){Logger(`Failed to decrypt in v2. Falling back to v1: ${key3}`,LOG_LEVEL_INFO);try{const r4=await this.decryptDataV1(u2,set2);Logger(`Decrypted in v1: ${key3}`,LOG_LEVEL_VERBOSE);return r4}catch(ex2){Logger(`Could not decrypt in v1: ${key3}`,LOG_LEVEL_VERBOSE);Logger(ex,LOG_LEVEL_VERBOSE);Logger(ex2,LOG_LEVEL_VERBOSE);throw ex2}}}async encryptForUpload(key3,data,set2){if(!set2.encrypt||""==set2.passphrase||this.isEncryptionPrevented(key3))return data;if(set2.E2EEAlgorithm===E2EEAlgorithms.V2){const salt=await this.getReplicationPBKDF2Salt();return await encryptBinary(data,set2.passphrase,salt)}return await encryptBinary2(data,set2.passphrase,set2.useDynamicIterationCount)}getDocKey(doc){return doc&&doc._id.startsWith("h:")?doc._id:doc._id+"-"+doc._rev}async _createJournalPack(override){const checkPointInfo=await this.getCheckpointInfo(),from=override||checkPointInfo.lastLocalSeq;Logger(`Journal reading from seq:${from}`,LOG_LEVEL_VERBOSE);let knownKeyCount=0;const allChangesTask=this.db.changes({live:!1,since:override||from,conflicts:!0,limit:this.batchSize,return_docs:!0,attachments:!1,style:"all_docs"}),allChanges=await allChangesTask;if(0==allChanges.results.length)return{changes:[],hasNext:!1,packLastSeq:allChanges.last_seq};const bd2=await this.db.bulkGet({docs:allChanges.results.map(e3=>e3.changes.map(change=>({id:e3.id,rev:change.rev}))).flat(),revs:!0}),packLastSeq=allChanges.last_seq,dbInfo=await this.db.info(),hasNext=packLastSeq<dbInfo.update_seq,docs=bd2.results.map(e3=>e3.docs).flat(),docChanges=docs.filter(e3=>"ok"in e3).map(e3=>e3.ok).filter(doc=>{const key3=this.getDocKey(doc);if(this._currentCheckPointInfo.knownIDs.has(key3)){knownKeyCount++;return!1}if(this._currentCheckPointInfo.sentIDs.has(key3)){knownKeyCount++;return!1}return!0});Logger(`Checked ${allChanges.results.length} changed entries, selected ${docChanges.length} docs (${knownKeyCount} keys already known)`,LOG_LEVEL_DEBUG);return{changes:docChanges,hasNext,packLastSeq}}_createSendReadableStream(startSeq,logLevel,MSG_KEY){let currentLastSeq=startSeq;return new ReadableStream({pull:async controller=>{for(;;){if(this.requestedStop){Logger("Packing Journal : Stop requested",logLevel,MSG_KEY);controller.close();return}const{changes:changes3,hasNext,packLastSeq}=await this._createJournalPack(currentLastSeq);currentLastSeq=packLastSeq;if(changes3.length>0){controller.enqueue({changes:changes3,packLastSeq});return}if(!hasNext){controller.close();return}}}})}_createSendCompressTransformStream(startSeq,seqToProcess,logLevel,MSG_KEY,stats){let outBuf=[],binarySize=0,batchSentIDs=[],lastProcessedSeq=startSeq;return new TransformStream({transform:async(chunk,controller)=>{lastProcessedSeq=chunk.packLastSeq;const currentSeq=lastProcessedSeq-startSeq;Logger(`Packing Journal: ${currentSeq} / ${seqToProcess}`,logLevel,MSG_KEY);for(const row of chunk.changes){const serialized2=serializeDoc(row);batchSentIDs.push(this.getDocKey(row));binarySize+=serialized2.length;outBuf.push(serialized2);stats.packedDocs++;if(outBuf.length>250||binarySize>10485760){const sendBuf=concatUInt8Array2(outBuf),bin=await wrappedDeflate(sendBuf,{consume:!0,level:8});controller.enqueue({bin,packLastSeq:chunk.packLastSeq,sentIDs:[...batchSentIDs]});outBuf=[];binarySize=0;batchSentIDs=[]}}},flush:async controller=>{if(outBuf.length>0){const sendBuf=concatUInt8Array2(outBuf),bin=await wrappedDeflate(sendBuf,{consume:!0,level:8});controller.enqueue({bin,packLastSeq:lastProcessedSeq,sentIDs:[...batchSentIDs]})}}})}_createSendUploadWritableStream(max3,logLevel,MSG_KEY,stats){let sentFilesCount=0;return new WritableStream({write:async chunk=>{const sendTimeStamp=Date.now(),filename=`${sendTimeStamp}-docs.jsonl.gz`,encryptedBin=await this.encryptForUpload(filename,chunk.bin,this.currentSettings),ret=await this.storage.upload(filename,encryptedBin,"application/octet-stream");if(!ret)throw new Error(`Could not send journalPack to the bucket (${filename})`);sentFilesCount++;stats.uploadedFiles++;this.updateInfo({sent:sentFilesCount,maxPushSeq:max3,lastSyncPushSeq:chunk.packLastSeq});await this.updateCheckPointInfo(info3=>({...info3,lastLocalSeq:chunk.packLastSeq,sentIDs:setAllItems(info3.sentIDs,chunk.sentIDs),sentFiles:info3.sentFiles.add(filename)}));Logger(`Uploading journal: ${sentFilesCount} / ...`,logLevel,MSG_KEY)}})}async sendLocalJournal(showMessage2=!1){this.updateInfo({syncStatus:"JOURNAL_SEND"});return await shareRunningResult("send_journal_stream",async()=>{this.requestedStop=!1;const logLevel=showMessage2?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,MSG_KEY="pack_journal",max3=(await this.db.info()).update_seq,checkPointInfo=await this.getCheckpointInfo(),startSeq=checkPointInfo.lastLocalSeq,seqToProcess=max3-startSeq;Logger("Packing Journal: Start sending",logLevel,MSG_KEY);const stats={packedDocs:0,uploadedFiles:0},readable2=this._createSendReadableStream(startSeq,logLevel,MSG_KEY),transform2=this._createSendCompressTransformStream(startSeq,seqToProcess,logLevel,MSG_KEY,stats),writable2=this._createSendUploadWritableStream(max3,logLevel,`${MSG_KEY}_upload`,stats);try{await readable2.pipeThrough(transform2).pipeTo(writable2);if(0!=seqToProcess){Logger(`Packing Journal: Finished. Processed ${stats.packedDocs} doc(s) into ${stats.uploadedFiles} chunk(s)`,logLevel,MSG_KEY);stats.uploadedFiles>0&&Logger(`Uploading journal: All ${stats.uploadedFiles} chunk(s) uploaded`,logLevel,`${MSG_KEY}_upload`)}else Logger("Packing Journal: No journals to be packed!",logLevel,MSG_KEY);this.updateInfo({syncStatus:"COMPLETED"});return!0}catch(ex){Logger("Packing Journal Error",logLevel);Logger(ex,LOG_LEVEL_VERBOSE);this.updateInfo({syncStatus:"ERRORED"});return!1}})}async _getRemoteJournals(){const checkPointInfo=await this.getCheckpointInfo(),StartAfter=[...checkPointInfo.receivedFiles.keys()].sort((a2,b3)=>b3.localeCompare(a2,void 0,{numeric:!0}))[0],files=(await this.storage.listFiles(StartAfter)).filter(e3=>!e3.startsWith("_"));return files?files.sort((a2,b3)=>a2.localeCompare(b3,void 0,{numeric:!0})):[]}async processDocuments(allDocs2){let applyTotal=0,wholeItems=0;try{const chunks=[],docs=[];allDocs2.forEach(e3=>{e3._id.startsWith("h:")?chunks.push(e3):docs.push(e3)});try{const e1=(await this.db.allDocs({include_docs:!0,keys:[...chunks.map(e3=>e3._id)]})).rows,e22=e1.map(e3=>{var _a13;return null!=(_a13=e3.id)?_a13:void 0}),existChunks=new Set(e22.filter(e3=>void 0!==e3)),saveChunks=chunks.filter(e3=>!existChunks.has(e3._id)).map(e3=>({...e3,_rev:void 0})),ret=await this.db.bulkDocs(saveChunks,{new_edits:!0}),saveError=ret.filter(e3=>"error"in e3).map(e3=>e3.id);saveChunks.filter(e3=>-1===saveError.indexOf(e3._id)).forEach(doc=>this.env.services.context.events.emitEvent(REMOTE_CHUNK_FETCHED,doc));await this.updateCheckPointInfo(info3=>({...info3,knownIDs:setAllItems(info3.knownIDs,chunks.map(e3=>this.getDocKey(e3)))}))}catch(ex){Logger("Applying chunks failed",LOG_LEVEL_INFO);Logger(ex,LOG_LEVEL_VERBOSE)}const params=docs.map(e3=>[e3._id,[e3._rev]]),docsRevs=params.reduce((acc,[id,revs])=>{var _a13;return{...acc,[id]:[...null!=(_a13=acc[id])?_a13:[],...revs]}},{}),diffRevs=await this.db.revsDiff(docsRevs),saveDocs=docs.filter(e3=>{var _a13,_b6;return e3._id in diffRevs&&"missing"in diffRevs[e3._id]&&-1!==(null!=(_b6=null==(_a13=diffRevs[e3._id].missing)?void 0:_a13.indexOf(e3._rev))?_b6:0)});await this.db.bulkDocs(saveDocs,{new_edits:!1});const writeDoc=!this.env.services.setting.currentSettings().suspendParseReplicationResult;writeDoc&&await this.processReplication(saveDocs);await this.updateCheckPointInfo(info3=>({...info3,knownIDs:setAllItems(info3.knownIDs,docs.map(e3=>this.getDocKey(e3)))}));applyTotal+=saveDocs.length;wholeItems+=docs.length;Logger(`Applied ${applyTotal} of ${wholeItems} docs (${wholeItems-applyTotal} skipped)`,LOG_LEVEL_VERBOSE);return!0}catch(ex){Logger("Applying journal failed",LOG_LEVEL_INFO);Logger(ex,LOG_LEVEL_VERBOSE);return!1}}_createReceiveReadableStream(files){return new ReadableStream({pull:controller=>{if(this.requestedStop||0===files.length){controller.close();return}const file=files.shift();file&&controller.enqueue(file)}})}_createReceiveTransformStream(logLevel){let count=0;return new TransformStream({transform:async(key3,controller)=>{count++;Logger(`Receiving Journal: ${count}`,logLevel,"receivejournal");const checkPointInfo=await this.getCheckpointInfo();if(checkPointInfo.sentFiles.has(key3)||checkPointInfo.receivedFiles.has(key3)){Logger(`Receiving Journal: ${key3} is already processed`,LOG_LEVEL_VERBOSE);await this.updateCheckPointInfo(info3=>({...info3,receivedFiles:info3.receivedFiles.add(key3)}))}else try{const encryptedData=await this.storage.download(key3,!0);if(!1===encryptedData)throw new Error("Download Error");const data=await this.decryptDownloaded(key3,encryptedData,this.currentSettings),decompressed=await wrappedInflate(new Uint8Array(data),{consume:!0});if(0==decompressed.length){controller.enqueue({key:key3,docs:[]});return}let idxFrom=0,idxTo=0;const d4=new TextDecoder,result=[];do{idxTo=decompressed.indexOf(10,idxFrom);if(-1==idxTo)break;const piece=decompressed.slice(idxFrom,idxTo),strPiece=d4.decode(piece);if(strPiece.startsWith("~")){const[idPart,dataPart]=strPiece.substring(1).split(UNIT_SPLIT);result.push({_id:idPart,data:unescapeNewLineFromString(dataPart),type:"leaf",_rev:""})}else result.push(JSON.parse(strPiece));idxFrom=idxTo+1}while(idxTo>0);controller.enqueue({key:key3,docs:result})}catch(ex){controller.error(ex)}}})}_createReceiveWritableStream(){let downloaded=0;return new WritableStream({write:async chunk=>{const{key:key3,docs}=chunk;if(docs.length>0){const success=await this.processDocuments(docs);if(!success)throw new Error(`Could not process downloaded journals for ${key3}`)}await this.updateCheckPointInfo(info3=>({...info3,receivedFiles:info3.receivedFiles.add(key3)}));downloaded++;this.updateInfo({arrived:downloaded,maxPullSeq:downloaded,lastSyncPullSeq:downloaded});Logger(`Processing journal: ${key3} has been processed`,LOG_LEVEL_INFO)}})}async receiveRemoteJournal(showMessage2=!1){this.updateInfo({syncStatus:"JOURNAL_RECEIVE"});return await shareRunningResult("receive_journal_stream",async()=>{this.requestedStop=!1;const logLevel=showMessage2?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO;Logger("Receiving Journal: Getting list of remote journal",logLevel,"receivejournal");const files=await this._getRemoteJournals();if(0==files.length){Logger("Receiving Journal: No journals needs to be downloaded",logLevel,"receivejournal");this.updateInfo({syncStatus:"COMPLETED"});return!0}const readable2=this._createReceiveReadableStream(files),transform2=this._createReceiveTransformStream(logLevel),writable2=this._createReceiveWritableStream();try{await readable2.pipeThrough(transform2).pipeTo(writable2);this.updateInfo({syncStatus:"COMPLETED"});return!0}catch(ex){Logger("Receive Journal Error",logLevel);Logger(ex,LOG_LEVEL_VERBOSE);this.updateInfo({syncStatus:"ERRORED"});return!1}})}async sync(showResult=!1){var _a13;return null!=(_a13=await shareRunningResult("replicate",async()=>{this.requestedStop=!1;const receiveResult=await this.receiveRemoteJournal(showResult);if(!this.requestedStop){if(!receiveResult){const logLevel=showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO;Logger("Could not receive remote journal, so we prevent sending local journals to prevent unwanted mass transfers",logLevel);return}return await this.sendLocalJournal(showResult)}}))&&_a13}requestStop(){this.requestedStop=!0}};getHttpHandlerExtensionConfiguration=runtimeConfig=>({setHttpHandler(handler){runtimeConfig.httpHandler=handler},httpHandler:()=>runtimeConfig.httpHandler,updateHttpClientConfig(key3,value){var _a13;null==(_a13=runtimeConfig.httpHandler)||_a13.updateHttpClientConfig(key3,value)},httpHandlerConfigs:()=>runtimeConfig.httpHandler.httpHandlerConfigs()});resolveHttpHandlerRuntimeConfig=httpHandlerExtensionConfiguration=>({httpHandler:httpHandlerExtensionConfiguration.httpHandler()});HttpRequest=class _HttpRequest{constructor(options){__publicField(this,"method");__publicField(this,"protocol");__publicField(this,"hostname");__publicField(this,"port");__publicField(this,"path");__publicField(this,"query");__publicField(this,"headers");__publicField(this,"username");__publicField(this,"password");__publicField(this,"fragment");__publicField(this,"body");this.method=options.method||"GET";this.hostname=options.hostname||"localhost";this.port=options.port;this.query=options.query||{};this.headers=options.headers||{};this.body=options.body;this.protocol=options.protocol?":"!==options.protocol.slice(-1)?`${options.protocol}:`:options.protocol:"https:";this.path=options.path?"/"!==options.path.charAt(0)?`/${options.path}`:options.path:"/";this.username=options.username;this.password=options.password;this.fragment=options.fragment}static clone(request2){const cloned=new _HttpRequest({...request2,headers:{...request2.headers}});cloned.query&&(cloned.query=cloneQuery(cloned.query));return cloned}static isInstance(request2){if(!request2)return!1;const req=request2;return"method"in req&&"protocol"in req&&"hostname"in req&&"path"in req&&"object"==typeof req.query&&"object"==typeof req.headers}clone(){return _HttpRequest.clone(this)}};HttpResponse=class{constructor(options){__publicField(this,"statusCode");__publicField(this,"reason");__publicField(this,"headers");__publicField(this,"body");this.statusCode=options.statusCode;this.reason=options.reason;this.headers=options.headers||{};this.body=options.body}static isInstance(response){if(!response)return!1;const resp=response;return"number"==typeof resp.statusCode&&"object"==typeof resp.headers}};addExpectContinueMiddlewareOptions={step:"build",tags:["SET_EXPECT_HEADER","EXPECT_HEADER"],name:"addExpectContinueMiddleware",override:!0};getAddExpectContinuePlugin=options=>({applyToStack:clientStack=>{clientStack.add(addExpectContinueMiddleware(options),addExpectContinueMiddlewareOptions)}});RequestChecksumCalculation_WHEN_SUPPORTED="WHEN_SUPPORTED",RequestChecksumCalculation_WHEN_REQUIRED="WHEN_REQUIRED";DEFAULT_REQUEST_CHECKSUM_CALCULATION=RequestChecksumCalculation_WHEN_SUPPORTED;ResponseChecksumValidation_WHEN_SUPPORTED="WHEN_SUPPORTED",ResponseChecksumValidation_WHEN_REQUIRED="WHEN_REQUIRED";DEFAULT_RESPONSE_CHECKSUM_VALIDATION=RequestChecksumCalculation_WHEN_SUPPORTED;(function(ChecksumAlgorithm2){ChecksumAlgorithm2.MD5="MD5";ChecksumAlgorithm2.CRC32="CRC32";ChecksumAlgorithm2.CRC32C="CRC32C";ChecksumAlgorithm2.CRC64NVME="CRC64NVME";ChecksumAlgorithm2.SHA1="SHA1";ChecksumAlgorithm2.SHA256="SHA256"})(ChecksumAlgorithm||(ChecksumAlgorithm={}));(function(ChecksumLocation2){ChecksumLocation2.HEADER="header";ChecksumLocation2.TRAILER="trailer"})(ChecksumLocation||(ChecksumLocation={}));DEFAULT_CHECKSUM_ALGORITHM=ChecksumAlgorithm.CRC32;getDateHeader=response=>{var _a13,_b6,_c3;return HttpResponse.isInstance(response)?null!=(_c3=null==(_a13=response.headers)?void 0:_a13.date)?_c3:null==(_b6=response.headers)?void 0:_b6.Date:void 0};getSkewCorrectedDate=systemClockOffset=>new Date(Date.now()+systemClockOffset);isClockSkewed=(clockTime,systemClockOffset)=>Math.abs(getSkewCorrectedDate(systemClockOffset).getTime()-clockTime)>=3e5;getUpdatedSystemClockOffset=(clockTime,currentSystemClockOffset)=>{const clockTimeInMs=Date.parse(clockTime);return isClockSkewed(clockTimeInMs,currentSystemClockOffset)?clockTimeInMs-Date.now():currentSystemClockOffset};throwSigningPropertyError=(name,property)=>{if(!property)throw new Error(`Property \`${name}\` is not resolved for AWS SDK SigV4Auth`);return property};validateSigningProperties=async signingProperties=>{var _a13,_b6,_c3;const context2=throwSigningPropertyError("context",signingProperties.context),config=throwSigningPropertyError("config",signingProperties.config),authScheme=null==(_c3=null==(_b6=null==(_a13=context2.endpointV2)?void 0:_a13.properties)?void 0:_b6.authSchemes)?void 0:_c3[0],signerFunction=throwSigningPropertyError("signer",config.signer),signer=await signerFunction(authScheme),signingRegion=null==signingProperties?void 0:signingProperties.signingRegion,signingRegionSet=null==signingProperties?void 0:signingProperties.signingRegionSet,signingName=null==signingProperties?void 0:signingProperties.signingName;return{config,signer,signingRegion,signingRegionSet,signingName}};AwsSdkSigV4Signer=class{async sign(httpRequest,identity,signingProperties){var _a13,_b6,_c3,_d2;if(!HttpRequest.isInstance(httpRequest))throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");const validatedProps=await validateSigningProperties(signingProperties),{config,signer}=validatedProps;let{signingRegion,signingName}=validatedProps;const handlerExecutionContext=signingProperties.context;if(null!=(_b6=null==(_a13=null==handlerExecutionContext?void 0:handlerExecutionContext.authSchemes)?void 0:_a13.length)&&_b6){const[first,second]=handlerExecutionContext.authSchemes;if("sigv4a"===(null==first?void 0:first.name)&&"sigv4"===(null==second?void 0:second.name)){signingRegion=null!=(_c3=null==second?void 0:second.signingRegion)?_c3:signingRegion;signingName=null!=(_d2=null==second?void 0:second.signingName)?_d2:signingName}}const signedRequest=await signer.sign(httpRequest,{signingDate:getSkewCorrectedDate(config.systemClockOffset),signingRegion,signingService:signingName});return signedRequest}errorHandler(signingProperties){return error=>{var _a13;const serverTime=null!=(_a13=error.ServerTime)?_a13:getDateHeader(error.$response);if(serverTime){const config=throwSigningPropertyError("config",signingProperties.config),initialSystemClockOffset=config.systemClockOffset;config.systemClockOffset=getUpdatedSystemClockOffset(serverTime,config.systemClockOffset);const clockSkewCorrected=config.systemClockOffset!==initialSystemClockOffset;clockSkewCorrected&&error.$metadata&&(error.$metadata.clockSkewCorrected=!0)}throw error}}successHandler(httpResponse,signingProperties){const dateHeader=getDateHeader(httpResponse);if(dateHeader){const config=throwSigningPropertyError("config",signingProperties.config);config.systemClockOffset=getUpdatedSystemClockOffset(dateHeader,config.systemClockOffset)}}};0;AwsSdkSigV4ASigner=class extends AwsSdkSigV4Signer{async sign(httpRequest,identity,signingProperties){var _a13,_b6;if(!HttpRequest.isInstance(httpRequest))throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");const{config,signer,signingRegion,signingRegionSet,signingName}=await validateSigningProperties(signingProperties),configResolvedSigningRegionSet=await(null==(_a13=config.sigv4aSigningRegionSet)?void 0:_a13.call(config)),multiRegionOverride=(null!=(_b6=null!=configResolvedSigningRegionSet?configResolvedSigningRegionSet:signingRegionSet)?_b6:[signingRegion]).join(","),signedRequest=await signer.sign(httpRequest,{signingDate:getSkewCorrectedDate(config.systemClockOffset),signingRegion:multiRegionOverride,signingService:signingName});return signedRequest}};resolveAuthOptions=(candidateAuthOptions,authSchemePreference)=>{if(!authSchemePreference||0===authSchemePreference.length)return candidateAuthOptions;const preferredAuthOptions=[];for(const preferredSchemeName of authSchemePreference)for(const candidateAuthOption of candidateAuthOptions){const candidateAuthSchemeName=candidateAuthOption.schemeId.split("#")[1];candidateAuthSchemeName===preferredSchemeName&&preferredAuthOptions.push(candidateAuthOption)}for(const candidateAuthOption of candidateAuthOptions)preferredAuthOptions.find(({schemeId})=>schemeId===candidateAuthOption.schemeId)||preferredAuthOptions.push(candidateAuthOption);return preferredAuthOptions};init_transport();httpAuthSchemeMiddleware=(config,mwOptions)=>(next2,context2)=>async args=>{var _a13;const options=config.httpAuthSchemeProvider(await mwOptions.httpAuthSchemeParametersProvider(config,context2,args.input)),authSchemePreference=config.authSchemePreference?await config.authSchemePreference():[],resolvedOptions=resolveAuthOptions(options,authSchemePreference),authSchemes=convertHttpAuthSchemesToMap(config.httpAuthSchemes),smithyContext=getSmithyContext(context2),failureReasons=[];for(const option of resolvedOptions){const scheme=authSchemes.get(option.schemeId);if(!scheme){failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` was not enabled for this service.`);continue}const identityProvider=scheme.identityProvider(await mwOptions.identityProviderConfigProvider(config));if(!identityProvider){failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` did not have an IdentityProvider configured.`);continue}const{identityProperties={},signingProperties={}}=(null==(_a13=option.propertiesExtractor)?void 0:_a13.call(option,config,context2))||{};option.identityProperties=Object.assign(option.identityProperties||{},identityProperties);option.signingProperties=Object.assign(option.signingProperties||{},signingProperties);smithyContext.selectedHttpAuthScheme={httpAuthOption:option,identity:await identityProvider(option.identityProperties),signer:scheme.signer};break}if(!smithyContext.selectedHttpAuthScheme)throw new Error(failureReasons.join("\n"));return next2(args)};httpAuthSchemeEndpointRuleSetMiddlewareOptions={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"endpointV2Middleware"};getHttpAuthSchemeEndpointRuleSetPlugin=(config,{httpAuthSchemeParametersProvider,identityProviderConfigProvider})=>({applyToStack:clientStack=>{clientStack.addRelativeTo(httpAuthSchemeMiddleware(config,{httpAuthSchemeParametersProvider,identityProviderConfigProvider}),httpAuthSchemeEndpointRuleSetMiddlewareOptions)}});init_index_browser2();collectBody=async(streamBody=new Uint8Array,context2)=>{if(streamBody instanceof Uint8Array)return Uint8ArrayBlobAdapter.mutate(streamBody);if(!streamBody)return Uint8ArrayBlobAdapter.mutate(new Uint8Array);const fromContext=context2.streamCollector(streamBody);return Uint8ArrayBlobAdapter.mutate(await fromContext)};deref=schemaRef=>"function"==typeof schemaRef?schemaRef():schemaRef;operation=(namespace,name,traits,input,output)=>({name,namespace,traits,input,output});init_transport();schemaDeserializationMiddleware=config=>(next2,context2)=>async args=>{var _a13,_b6,_c3,_d2;const{response}=await next2(args),{operationSchema}=getSmithyContext(context2),[,ns,n3,t9,i3,o2]=null!=operationSchema?operationSchema:[];try{const parsed=await config.protocol.deserializeResponse(operation(ns,n3,t9,i3,o2),{...config,...context2},response);return{response,output:parsed}}catch(error){Object.defineProperty(error,"$response",{value:response,enumerable:!1,writable:!1,configurable:!1});if(!("$metadata"in error)){const hint="Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.";try{error.message+="\n "+hint}catch(e3){context2.logger&&"NoOpLogger"!==(null==(_b6=null==(_a13=context2.logger)?void 0:_a13.constructor)?void 0:_b6.name)?null==(_d2=null==(_c3=context2.logger)?void 0:_c3.warn)||_d2.call(_c3,hint):console.warn(hint)}void 0!==error.$responseBodyText&&error.$response&&(error.$response.body=error.$responseBodyText);try{if(HttpResponse2.isInstance(response)){const{headers={},statusCode}=response,headerEntries=Object.entries(headers);error.$metadata={httpStatusCode:statusCode,requestId:findHeader(/^x-[\w-]+-request-?id$/,headerEntries),extendedRequestId:findHeader(/^x-[\w-]+-id-2$/,headerEntries),cfId:findHeader(/^x-[\w-]+-cf-id$/,headerEntries)}}}catch(e3){}}throw error}};findHeader=(pattern,headers)=>(headers.find(([k2])=>k2.match(pattern))||[void 0,void 0])[1];init_transport();schemaSerializationMiddleware=config=>(next2,context2)=>async args=>{const{operationSchema}=getSmithyContext(context2),[,ns,n3,t9,i3,o2]=null!=operationSchema?operationSchema:[],endpoint=context2.endpointV2?async()=>toEndpointV1(context2.endpointV2):config.endpoint,request2=await config.protocol.serializeRequest(operation(ns,n3,t9,i3,o2),args.input,{...config,...context2,endpoint});return next2({...args,request:request2})};deserializerMiddlewareOption2={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0};serializerMiddlewareOption3={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};traitsCache=[];anno_it=Symbol.for("@smithy/nor-struct-it"),anno_ns=Symbol.for("@smithy/ns");simpleSchemaCacheN=[];simpleSchemaCacheS={};_NormalizedSchema=class _NormalizedSchema{constructor(ref,memberName){__publicField(this,"ref");__publicField(this,"memberName");__publicField(this,"symbol",_NormalizedSchema.symbol);__publicField(this,"name");__publicField(this,"schema");__publicField(this,"_isMemberSchema");__publicField(this,"traits");__publicField(this,"memberTraits");__publicField(this,"normalizedTraits");var _a13;this.ref=ref;this.memberName=memberName;const traitStack=[];let _ref=ref,schema=ref;this._isMemberSchema=!1;for(;isMemberSchema(_ref);){traitStack.push(_ref[1]);_ref=_ref[0];schema=deref(_ref);this._isMemberSchema=!0}if(traitStack.length>0){this.memberTraits={};for(let i3=traitStack.length-1;i3>=0;--i3){const traitSet=traitStack[i3];Object.assign(this.memberTraits,translateTraits(traitSet))}}else this.memberTraits=0;if(schema instanceof _NormalizedSchema){const computedMemberTraits=this.memberTraits;Object.assign(this,schema);this.memberTraits=Object.assign({},computedMemberTraits,schema.getMemberTraits(),this.getMemberTraits());this.normalizedTraits=void 0;this.memberName=null!=memberName?memberName:schema.memberName;return}this.schema=deref(schema);if(isStaticSchema(this.schema)){this.name=`${this.schema[1]}#${this.schema[2]}`;this.traits=this.schema[3]}else{this.name=null!=(_a13=this.memberName)?_a13:String(schema);this.traits=0}if(this._isMemberSchema&&!memberName)throw new Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(!0)} missing member name.`)}static[Symbol.hasInstance](lhs){const isPrototype=this.prototype.isPrototypeOf(lhs);if(!isPrototype&&"object"==typeof lhs&&null!==lhs){const ns=lhs;return ns.symbol===this.symbol}return isPrototype}static of(ref){const keyAble="function"==typeof ref||"object"==typeof ref&&null!==ref;if("number"==typeof ref){if(simpleSchemaCacheN[ref])return simpleSchemaCacheN[ref]}else if("string"==typeof ref){if(simpleSchemaCacheS[ref])return simpleSchemaCacheS[ref]}else if(keyAble&&ref[anno_ns])return ref[anno_ns];const sc=deref(ref);if(sc instanceof _NormalizedSchema)return sc;if(isMemberSchema(sc)){const[ns2,traits]=sc;if(ns2 instanceof _NormalizedSchema){Object.assign(ns2.getMergedTraits(),translateTraits(traits));return ns2}throw new Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(ref,null,2)}.`)}const ns=new _NormalizedSchema(sc);return keyAble?ref[anno_ns]=ns:"string"==typeof sc?simpleSchemaCacheS[sc]=ns:"number"==typeof sc?simpleSchemaCacheN[sc]=ns:ns}getSchema(){const sc=this.schema;return Array.isArray(sc)&&0===sc[0]?sc[4]:sc}getName(withNamespace=!1){const{name}=this,short=!withNamespace&&name&&name.includes("#");return short?name.split("#")[1]:name||void 0}getMemberName(){return this.memberName}isMemberSchema(){return this._isMemberSchema}isListSchema(){const sc=this.getSchema();return"number"==typeof sc?sc>=64&&sc<128:1===sc[0]}isMapSchema(){const sc=this.getSchema();return"number"==typeof sc?sc>=128&&sc<=255:2===sc[0]}isStructSchema(){const sc=this.getSchema();if("object"!=typeof sc)return!1;const id=sc[0];return 3===id||-3===id||4===id}isUnionSchema(){const sc=this.getSchema();return"object"==typeof sc&&4===sc[0]}isBlobSchema(){const sc=this.getSchema();return 21===sc||42===sc}isTimestampSchema(){const sc=this.getSchema();return"number"==typeof sc&&sc>=4&&sc<=7}isUnitSchema(){return"unit"===this.getSchema()}isDocumentSchema(){return 15===this.getSchema()}isStringSchema(){return 0===this.getSchema()}isBooleanSchema(){return 2===this.getSchema()}isNumericSchema(){return 1===this.getSchema()}isBigIntegerSchema(){return 17===this.getSchema()}isBigDecimalSchema(){return 19===this.getSchema()}isStreaming(){const{streaming}=this.getMergedTraits();return!!streaming||42===this.getSchema()}isIdempotencyToken(){return!!this.getMergedTraits().idempotencyToken}getMergedTraits(){var _a13;return null!=(_a13=this.normalizedTraits)?_a13:this.normalizedTraits={...this.getOwnTraits(),...this.getMemberTraits()}}getMemberTraits(){return translateTraits(this.memberTraits)}getOwnTraits(){return translateTraits(this.traits)}getKeySchema(){var _a13;const[isDoc,isMap]=[this.isDocumentSchema(),this.isMapSchema()];if(!isDoc&&!isMap)throw new Error(`@smithy/core/schema - cannot get key for non-map: ${this.getName(!0)}`);const schema=this.getSchema(),memberSchema=isDoc?15:null!=(_a13=schema[4])?_a13:0;return member([memberSchema,0],"key")}getValueSchema(){const sc=this.getSchema(),[isDoc,isMap,isList]=[this.isDocumentSchema(),this.isMapSchema(),this.isListSchema()],memberSchema="number"==typeof sc?63&sc:sc&&"object"==typeof sc&&(isMap||isList)?sc[3+sc[0]]:isDoc?15:void 0;if(null!=memberSchema)return member([memberSchema,0],isMap?"value":"member");throw new Error(`@smithy/core/schema - ${this.getName(!0)} has no value member.`)}getMemberSchema(memberName){const struct=this.getSchema();if(this.isStructSchema()&&struct[4].includes(memberName)){const i3=struct[4].indexOf(memberName),memberSchema=struct[5][i3];return member(isMemberSchema(memberSchema)?memberSchema:[memberSchema,0],memberName)}if(this.isDocumentSchema())return member([15,0],memberName);throw new Error(`@smithy/core/schema - ${this.getName(!0)} has no member=${memberName}.`)}getMemberSchemas(){const buffer={};try{for(const[k2,v2]of this.structIterator())buffer[k2]=v2}catch(ignored){}return buffer}getEventStreamMember(){if(this.isStructSchema())for(const[memberName,memberSchema]of this.structIterator())if(memberSchema.isStreaming()&&memberSchema.isStructSchema())return memberName;return""}*structIterator(){if(this.isUnitSchema())return;if(!this.isStructSchema())throw new Error("@smithy/core/schema - cannot iterate non-struct schema.");const struct=this.getSchema(),z2=struct[4].length;let it=struct[anno_it];if(it&&z2===it.length)yield*it;else{it=Array(z2);for(let i3=0;i3<z2;++i3){const k2=struct[4][i3],v2=member([struct[5][i3],0],k2);yield it[i3]=[k2,v2]}struct[anno_it]=it}}};__publicField(_NormalizedSchema,"symbol",Symbol.for("@smithy/nor"));NormalizedSchema=_NormalizedSchema;isMemberSchema=sc=>Array.isArray(sc)&&2===sc.length;isStaticSchema=sc=>Array.isArray(sc)&&sc.length>=5;_TypeRegistry=class _TypeRegistry{constructor(namespace,schemas=new Map,exceptions=new Map){__publicField(this,"namespace");__publicField(this,"schemas");__publicField(this,"exceptions");this.namespace=namespace;this.schemas=schemas;this.exceptions=exceptions}static for(namespace){_TypeRegistry.registries.has(namespace)||_TypeRegistry.registries.set(namespace,new _TypeRegistry(namespace));return _TypeRegistry.registries.get(namespace)}copyFrom(other){const{schemas,exceptions}=this;for(const[k2,v2]of other.schemas)schemas.has(k2)||schemas.set(k2,v2);for(const[k2,v2]of other.exceptions)exceptions.has(k2)||exceptions.set(k2,v2)}register(shapeId,schema){const qualifiedName=this.normalizeShapeId(shapeId);for(const r4 of[this,_TypeRegistry.for(qualifiedName.split("#")[0])])r4.schemas.set(qualifiedName,schema)}getSchema(shapeId){const id=this.normalizeShapeId(shapeId);if(!this.schemas.has(id)){if(!shapeId.includes("#")){const suffix="#"+shapeId,candidates=[];for(const[shapeId2,schema]of this.schemas.entries())shapeId2.endsWith(suffix)&&candidates.push(schema);if(1===candidates.length)return candidates[0]}throw new Error(`@smithy/core/schema - schema not found for ${id}`)}return this.schemas.get(id)}registerError(es,ctor){const $error=es,ns=$error[1];for(const r4 of[this,_TypeRegistry.for(ns)]){r4.schemas.set(ns+"#"+$error[2],$error);r4.exceptions.set($error,ctor)}}getErrorCtor(es){const $error=es;if(this.exceptions.has($error))return this.exceptions.get($error);const registry=_TypeRegistry.for($error[1]);return registry.exceptions.get($error)}getBaseException(){for(const exceptionKey of this.exceptions.keys())if(Array.isArray(exceptionKey)){const[,ns,name]=exceptionKey,id=ns+"#"+name;if(id.startsWith("smithy.ts.sdk.synthetic.")&&id.endsWith("ServiceException"))return exceptionKey}}find(predicate){for(const schema of this.schemas.values())if(predicate(schema))return schema}clear(){this.schemas.clear();this.exceptions.clear()}normalizeShapeId(shapeId){return shapeId.includes("#")?shapeId:this.namespace+"#"+shapeId}};__publicField(_TypeRegistry,"registries",new Map);TypeRegistry=_TypeRegistry;SerdeContext=class{constructor(){__publicField(this,"serdeContext")}setSerdeContext(serdeContext){this.serdeContext=serdeContext}};init_transport();HttpProtocol=class extends SerdeContext{constructor(options){var _a13;super();__publicField(this,"options");__publicField(this,"compositeErrorRegistry");this.options=options;this.compositeErrorRegistry=TypeRegistry.for(options.defaultNamespace);for(const etr of null!=(_a13=options.errorTypeRegistries)?_a13:[])this.compositeErrorRegistry.copyFrom(etr)}getRequestType(){return HttpRequest2}getResponseType(){return HttpResponse2}setSerdeContext(serdeContext){this.serdeContext=serdeContext;this.serializer.setSerdeContext(serdeContext);this.deserializer.setSerdeContext(serdeContext);this.getPayloadCodec()&&this.getPayloadCodec().setSerdeContext(serdeContext)}updateServiceEndpoint(request2,endpoint){if("url"in endpoint){request2.protocol=endpoint.url.protocol;request2.hostname=endpoint.url.hostname;request2.port=endpoint.url.port?Number(endpoint.url.port):void 0;request2.path=endpoint.url.pathname;request2.fragment=endpoint.url.hash||void 0;request2.username=endpoint.url.username||void 0;request2.password=endpoint.url.password||void 0;request2.query||(request2.query={});for(const[k2,v2]of endpoint.url.searchParams.entries())request2.query[k2]=v2;if(endpoint.headers)for(const name in endpoint.headers)request2.headers[name]=endpoint.headers[name].join(", ");return request2}request2.protocol=endpoint.protocol;request2.hostname=endpoint.hostname;request2.port=endpoint.port?Number(endpoint.port):void 0;request2.path=endpoint.path;request2.query={...endpoint.query};if(endpoint.headers)for(const name in endpoint.headers)request2.headers[name]=endpoint.headers[name];return request2}setHostPrefix(request2,operationSchema,input){var _a13,_b6,_c3;if(null==(_a13=this.serdeContext)?void 0:_a13.disableHostPrefix)return;const inputNs=NormalizedSchema.of(operationSchema.input),opTraits=translateTraits(null!=(_b6=operationSchema.traits)?_b6:{});if(opTraits.endpoint){let hostPrefix=null==(_c3=opTraits.endpoint)?void 0:_c3[0];if("string"==typeof hostPrefix){for(const[name,member2]of inputNs.structIterator()){if(!member2.getMergedTraits().hostLabel)continue;const replacement=input[name];if("string"!=typeof replacement)throw new Error(`@smithy/core/schema - ${name} in input must be a string as hostLabel.`);hostPrefix=hostPrefix.replace(`{${name}}`,replacement)}request2.hostname=hostPrefix+request2.hostname}}}deserializeMetadata(output){var _a13,_b6;return{httpStatusCode:output.statusCode,requestId:null!=(_b6=null!=(_a13=output.headers["x-amzn-requestid"])?_a13:output.headers["x-amzn-request-id"])?_b6:output.headers["x-amz-request-id"],extendedRequestId:output.headers["x-amz-id-2"],cfId:output.headers["x-amz-cf-id"]}}async serializeEventStream({eventStream,requestSchema,initialRequest}){const eventStreamSerde=await this.loadEventStreamCapability();return eventStreamSerde.serializeEventStream({eventStream,requestSchema,initialRequest})}async deserializeEventStream({response,responseSchema,initialResponseContainer}){const eventStreamSerde=await this.loadEventStreamCapability();return eventStreamSerde.deserializeEventStream({response,responseSchema,initialResponseContainer})}async loadEventStreamCapability(){const{EventStreamSerde:EventStreamSerde2}=await Promise.resolve().then(()=>(init_index_browser3(),index_browser_exports));return new EventStreamSerde2({marshaller:this.getEventStreamMarshaller(),serializer:this.serializer,deserializer:this.deserializer,serdeContext:this.serdeContext,defaultContentType:this.getDefaultContentType()})}getDefaultContentType(){throw new Error(`@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.`)}async deserializeHttpMessage(schema,context2,response,arg4,arg5){return[]}getEventStreamMarshaller(){const context2=this.serdeContext;if(!context2.eventStreamMarshaller)throw new Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext.");return context2.eventStreamMarshaller}};init_index_browser2();init_transport();HttpBindingProtocol=class extends HttpProtocol{async serializeRequest(operationSchema,_input,context2){var _a13,_b6;const input=_input&&"object"==typeof _input?_input:{},serializer=this.serializer,query3={},headers={},endpoint=await context2.endpoint(),ns=NormalizedSchema.of(null==operationSchema?void 0:operationSchema.input),payloadMemberNames=[],payloadMemberSchemas=[];let payload,hasNonHttpBindingMember=!1;const request2=new HttpRequest2({protocol:"",hostname:"",port:void 0,path:"",fragment:void 0,query:query3,headers,body:void 0});if(endpoint){this.updateServiceEndpoint(request2,endpoint);this.setHostPrefix(request2,operationSchema,input);const opTraits=translateTraits(operationSchema.traits);if(opTraits.http){request2.method=opTraits.http[0];const[path2,search]=opTraits.http[1].split("?");"/"==request2.path?request2.path=path2:request2.path+=path2;const traitSearchParams=new URLSearchParams(null!=search?search:"");for(const[key3,value]of traitSearchParams)query3[key3]=value}}for(const[memberName,memberNs]of ns.structIterator()){const memberTraits=null!=(_a13=memberNs.getMergedTraits())?_a13:{},inputMemberValue=input[memberName];if(null!=inputMemberValue||memberNs.isIdempotencyToken())if(memberTraits.httpPayload){const isStreaming2=memberNs.isStreaming();if(isStreaming2){const isEventStream=memberNs.isStructSchema();isEventStream?input[memberName]&&(payload=await this.serializeEventStream({eventStream:input[memberName],requestSchema:ns})):payload=inputMemberValue}else{serializer.write(memberNs,inputMemberValue);payload=serializer.flush()}}else if(memberTraits.httpLabel){serializer.write(memberNs,inputMemberValue);const replacement=serializer.flush();request2.path.includes(`{${memberName}+}`)?request2.path=request2.path.replace(`{${memberName}+}`,replacement.split("/").map(extendedEncodeURIComponent).join("/")):request2.path.includes(`{${memberName}}`)&&(request2.path=request2.path.replace(`{${memberName}}`,extendedEncodeURIComponent(replacement)))}else if(memberTraits.httpHeader){serializer.write(memberNs,inputMemberValue);headers[memberTraits.httpHeader.toLowerCase()]=String(serializer.flush())}else if("string"==typeof memberTraits.httpPrefixHeaders)for(const key3 in inputMemberValue){const val=inputMemberValue[key3],amalgam=memberTraits.httpPrefixHeaders+key3;serializer.write([memberNs.getValueSchema(),{httpHeader:amalgam}],val);headers[amalgam.toLowerCase()]=serializer.flush()}else if(memberTraits.httpQuery||memberTraits.httpQueryParams)this.serializeQuery(memberNs,inputMemberValue,query3);else{hasNonHttpBindingMember=!0;payloadMemberNames.push(memberName);payloadMemberSchemas.push(memberNs)}else if(memberTraits.httpLabel&&(request2.path.includes(`{${memberName}+}`)||request2.path.includes(`{${memberName}}`)))throw new Error(`No value provided for input HTTP label: ${memberName}.`)}if(hasNonHttpBindingMember&&input){const[namespace,name]=(null!=(_b6=ns.getName(!0))?_b6:"#Unknown").split("#"),requiredMembers=ns.getSchema()[6],payloadSchema=[3,namespace,name,ns.getMergedTraits(),payloadMemberNames,payloadMemberSchemas,void 0];requiredMembers?payloadSchema[6]=requiredMembers:payloadSchema.pop();serializer.write(payloadSchema,input);payload=serializer.flush()}request2.headers=headers;request2.query=query3;request2.body=payload;return request2}serializeQuery(ns,data,query3){const serializer=this.serializer,traits=ns.getMergedTraits();if(traits.httpQueryParams){for(const key3 in data)if(!(key3 in query3)){const val=data[key3],valueSchema=ns.getValueSchema();Object.assign(valueSchema.getMergedTraits(),{...traits,httpQuery:key3,httpQueryParams:void 0});this.serializeQuery(valueSchema,val,query3)}}else if(ns.isListSchema()){const sparse=!!ns.getMergedTraits().sparse,buffer=[];for(const item of data){serializer.write([ns.getValueSchema(),traits],item);const serializable=serializer.flush();(sparse||void 0!==serializable)&&buffer.push(serializable)}query3[traits.httpQuery]=buffer}else{serializer.write([ns,traits],data);query3[traits.httpQuery]=serializer.flush()}}async deserializeResponse(operationSchema,context2,response){const deserializer=this.deserializer,ns=NormalizedSchema.of(operationSchema.output),dataObject={};if(response.statusCode>=300){const bytes=await collectBody(response.body,context2);bytes.byteLength>0&&Object.assign(dataObject,await deserializer.read(15,bytes));await this.handleError(operationSchema,context2,response,dataObject,this.deserializeMetadata(response));throw new Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw.")}for(const header in response.headers){const value=response.headers[header];delete response.headers[header];response.headers[header.toLowerCase()]=value}const nonHttpBindingMembers=await this.deserializeHttpMessage(ns,context2,response,dataObject);if(nonHttpBindingMembers.length){const bytes=await collectBody(response.body,context2);if(bytes.byteLength>0){const dataFromBody=await deserializer.read(ns,bytes);for(const member2 of nonHttpBindingMembers)null!=dataFromBody[member2]&&(dataObject[member2]=dataFromBody[member2])}}else nonHttpBindingMembers.discardResponseBody&&await collectBody(response.body,context2);dataObject.$metadata=this.deserializeMetadata(response);return dataObject}async deserializeHttpMessage(schema,context2,response,arg4,arg5){let dataObject;dataObject=arg4 instanceof Set?arg5:arg4;let discardResponseBody=!0;const deserializer=this.deserializer,ns=NormalizedSchema.of(schema),nonHttpBindingMembers=[];for(const[memberName,memberSchema]of ns.structIterator()){const memberTraits=memberSchema.getMemberTraits();if(memberTraits.httpPayload){discardResponseBody=!1;const isStreaming2=memberSchema.isStreaming();if(isStreaming2){const isEventStream=memberSchema.isStructSchema();dataObject[memberName]=isEventStream?await this.deserializeEventStream({response,responseSchema:ns}):sdkStreamMixin(response.body)}else if(response.body){const bytes=await collectBody(response.body,context2);bytes.byteLength>0&&(dataObject[memberName]=await deserializer.read(memberSchema,bytes))}}else if(memberTraits.httpHeader){const key3=String(memberTraits.httpHeader).toLowerCase(),value=response.headers[key3];if(null!=value)if(memberSchema.isListSchema()){const headerListValueSchema=memberSchema.getValueSchema();headerListValueSchema.getMergedTraits().httpHeader=key3;let sections;sections=headerListValueSchema.isTimestampSchema()&&4===headerListValueSchema.getSchema()?splitEvery(value,",",2):splitHeader(value);const list=[];for(const section of sections)list.push(await deserializer.read(headerListValueSchema,section.trim()));dataObject[memberName]=list}else dataObject[memberName]=await deserializer.read(memberSchema,value)}else if(void 0!==memberTraits.httpPrefixHeaders){dataObject[memberName]={};for(const header in response.headers)if(header.startsWith(memberTraits.httpPrefixHeaders)){const value=response.headers[header],valueSchema=memberSchema.getValueSchema();valueSchema.getMergedTraits().httpHeader=header;dataObject[memberName][header.slice(memberTraits.httpPrefixHeaders.length)]=await deserializer.read(valueSchema,value)}}else memberTraits.httpResponseCode?dataObject[memberName]=response.statusCode:nonHttpBindingMembers.push(memberName)}nonHttpBindingMembers.discardResponseBody=discardResponseBody;return nonHttpBindingMembers}};init_index_browser2();FromStringShapeDeserializer=class extends SerdeContext{constructor(settings){super();__publicField(this,"settings");this.settings=settings}read(_schema,data){var _a13,_b6;const ns=NormalizedSchema.of(_schema);if(ns.isListSchema())return splitHeader(data).map(item=>this.read(ns.getValueSchema(),item));if(ns.isBlobSchema())return(null!=(_b6=null==(_a13=this.serdeContext)?void 0:_a13.base64Decoder)?_b6:fromBase64)(data);if(ns.isTimestampSchema()){const format2=determineTimestampFormat(ns,this.settings);switch(format2){case 5:return _parseRfc3339DateTimeWithOffset(data);case 6:return _parseRfc7231DateTime(data);case 7:return _parseEpochTimestamp(data);default:console.warn("Missing timestamp format, parsing value with Date constructor:",data);return new Date(data)}}if(ns.isStringSchema()){const mediaType=ns.getMergedTraits().mediaType;let intermediateValue=data;if(mediaType){ns.getMergedTraits().httpHeader&&(intermediateValue=this.base64ToUtf8(intermediateValue));const isJson="application/json"===mediaType||mediaType.endsWith("+json");isJson&&(intermediateValue=LazyJsonString.from(intermediateValue));return intermediateValue}}return ns.isNumericSchema()?Number(data):ns.isBigIntegerSchema()?BigInt(data):ns.isBigDecimalSchema()?new NumericValue(data,"bigDecimal"):ns.isBooleanSchema()?"true"===String(data).toLowerCase():data}base64ToUtf8(base64String){var _a13,_b6,_c3,_d2;return(null!=(_b6=null==(_a13=this.serdeContext)?void 0:_a13.utf8Encoder)?_b6:toUtf8)((null!=(_d2=null==(_c3=this.serdeContext)?void 0:_c3.base64Decoder)?_d2:fromBase64)(base64String))}};init_index_browser2();HttpInterceptingShapeDeserializer=class extends SerdeContext{constructor(codecDeserializer,codecSettings){super();__publicField(this,"codecDeserializer");__publicField(this,"stringDeserializer");this.codecDeserializer=codecDeserializer;this.stringDeserializer=new FromStringShapeDeserializer(codecSettings)}setSerdeContext(serdeContext){this.stringDeserializer.setSerdeContext(serdeContext);this.codecDeserializer.setSerdeContext(serdeContext);this.serdeContext=serdeContext}read(schema,data){var _a13,_b6,_c3,_d2;const ns=NormalizedSchema.of(schema),traits=ns.getMergedTraits(),toString=null!=(_b6=null==(_a13=this.serdeContext)?void 0:_a13.utf8Encoder)?_b6:toUtf8;if(traits.httpHeader||traits.httpResponseCode)return this.stringDeserializer.read(ns,toString(data));if(traits.httpPayload){if(ns.isBlobSchema()){const toBytes=null!=(_d2=null==(_c3=this.serdeContext)?void 0:_c3.utf8Decoder)?_d2:fromUtf8;return"string"==typeof data?toBytes(data):data}if(ns.isStringSchema())return"byteLength"in data?toString(data):data}return this.codecDeserializer.read(ns,data)}};init_index_browser2();ToStringShapeSerializer=class extends SerdeContext{constructor(settings){super();__publicField(this,"settings");__publicField(this,"stringBuffer","");this.settings=settings}write(schema,value){var _a13,_b6,_c3,_d2;const ns=NormalizedSchema.of(schema);switch(typeof value){case"object":if(null===value){this.stringBuffer="null";return}if(ns.isTimestampSchema()){if(!(value instanceof Date))throw new Error(`@smithy/core/protocols - received non-Date value ${value} when schema expected Date in ${ns.getName(!0)}`);const format2=determineTimestampFormat(ns,this.settings);switch(format2){case 5:this.stringBuffer=value.toISOString().replace(".000Z","Z");break;case 6:this.stringBuffer=dateToUtcString(value);break;case 7:this.stringBuffer=String(value.getTime()/1e3);break;default:console.warn("Missing timestamp format, using epoch seconds",value);this.stringBuffer=String(value.getTime()/1e3)}return}if(ns.isBlobSchema()&&"byteLength"in value){this.stringBuffer=(null!=(_b6=null==(_a13=this.serdeContext)?void 0:_a13.base64Encoder)?_b6:toBase64)(value);return}if(ns.isListSchema()&&Array.isArray(value)){let buffer="";for(const item of value){this.write([ns.getValueSchema(),ns.getMergedTraits()],item);const headerItem=this.flush(),serialized2=ns.getValueSchema().isTimestampSchema()?headerItem:quoteHeader(headerItem);""!==buffer&&(buffer+=", ");buffer+=serialized2}this.stringBuffer=buffer;return}this.stringBuffer=JSON.stringify(value,null,2);break;case"string":const mediaType=ns.getMergedTraits().mediaType;let intermediateValue=value;if(mediaType){const isJson="application/json"===mediaType||mediaType.endsWith("+json");isJson&&(intermediateValue=LazyJsonString.from(intermediateValue));if(ns.getMergedTraits().httpHeader){this.stringBuffer=(null!=(_d2=null==(_c3=this.serdeContext)?void 0:_c3.base64Encoder)?_d2:toBase64)(intermediateValue.toString());return}}this.stringBuffer=value;break;default:ns.isIdempotencyToken()?this.stringBuffer=generateIdempotencyToken():this.stringBuffer=String(value)}}flush(){const buffer=this.stringBuffer;this.stringBuffer="";return buffer}};HttpInterceptingShapeSerializer=class{constructor(codecSerializer,codecSettings,stringSerializer=new ToStringShapeSerializer(codecSettings)){__publicField(this,"codecSerializer");__publicField(this,"stringSerializer");__publicField(this,"buffer");this.codecSerializer=codecSerializer;this.stringSerializer=stringSerializer}setSerdeContext(serdeContext){this.codecSerializer.setSerdeContext(serdeContext);this.stringSerializer.setSerdeContext(serdeContext)}write(schema,value){const ns=NormalizedSchema.of(schema),traits=ns.getMergedTraits();if(!(traits.httpHeader||traits.httpLabel||traits.httpQuery))return this.codecSerializer.write(ns,value);this.stringSerializer.write(ns,value);this.buffer=this.stringSerializer.flush()}flush(){if(void 0!==this.buffer){const buffer=this.buffer;this.buffer=void 0;return buffer}return this.codecSerializer.flush()}};init_transport();init_transport();init_transport();init_transport();init_transport();init_transport();defaultErrorHandler=signingProperties=>error=>{throw error};defaultSuccessHandler=(httpResponse,signingProperties)=>{};httpSigningMiddleware=config=>(next2,context2)=>async args=>{if(!HttpRequest2.isInstance(args.request))return next2(args);const smithyContext=getSmithyContext(context2),scheme=smithyContext.selectedHttpAuthScheme;if(!scheme)throw new Error("No HttpAuthScheme was selected: unable to sign request");const{httpAuthOption:{signingProperties={}},identity,signer}=scheme,output=await next2({...args,request:await signer.sign(args.request,identity,signingProperties)}).catch((signer.errorHandler||defaultErrorHandler)(signingProperties));(signer.successHandler||defaultSuccessHandler)(output.response,signingProperties);return output};httpSigningMiddlewareOptions={step:"finalizeRequest",tags:["HTTP_SIGNING"],name:"httpSigningMiddleware",aliases:["apiKeyMiddleware","tokenMiddleware","awsAuthMiddleware"],override:!0,relation:"after",toMiddleware:"retryMiddleware"};getHttpSigningPlugin=config=>({applyToStack:clientStack=>{clientStack.addRelativeTo(httpSigningMiddleware(config),httpSigningMiddlewareOptions)}});normalizeProvider2=input=>{if("function"==typeof input)return input;const promisified=Promise.resolve(input);return()=>promisified};makePagedClientRequest=async(CommandCtor,client,input,withCommand=_=>_,...args)=>{var _a13;let command=new CommandCtor(input);command=null!=(_a13=withCommand(command))?_a13:command;return await client.send(command,...args)};get3=(fromObject,path2)=>{let cursor=fromObject;const pathComponents=path2.split(".");for(const step of pathComponents){if(!cursor||"object"!=typeof cursor)return;cursor=cursor[step]}return cursor};DefaultIdentityProviderConfig=class{constructor(config){__publicField(this,"authSchemes",new Map);for(const key3 in config){const value=config[key3];void 0!==value&&this.authSchemes.set(key3,value)}}getIdentityProvider(schemeId){return this.authSchemes.get(schemeId)}};createIsIdentityExpiredFunction=expirationMs=>function isIdentityExpired2(identity){return doesIdentityRequireRefresh(identity)&&identity.expiration.getTime()-Date.now()<expirationMs};EXPIRATION_MS=3e5;isIdentityExpired=createIsIdentityExpiredFunction(EXPIRATION_MS);doesIdentityRequireRefresh=identity=>void 0!==identity.expiration;memoizeIdentityProvider=(provider,isExpired,requiresRefresh)=>{if(void 0===provider)return;const normalizedProvider="function"!=typeof provider?async()=>Promise.resolve(provider):provider;let resolved,pending3,hasResult,isConstant=!1;const coalesceProvider=async options=>{pending3||(pending3=normalizedProvider(options));try{resolved=await pending3;hasResult=!0;isConstant=!1}finally{pending3=void 0}return resolved};return void 0===isExpired?async options=>{hasResult&&!(null==options?void 0:options.forceRefresh)||(resolved=await coalesceProvider(options));return resolved}:async options=>{hasResult&&!(null==options?void 0:options.forceRefresh)||(resolved=await coalesceProvider(options));if(isConstant)return resolved;if(!requiresRefresh(resolved)){isConstant=!0;return resolved}if(isExpired(resolved)){await coalesceProvider(options);return resolved}return resolved}};init_transport();ProviderError=class _ProviderError extends Error{constructor(message,options=!0){var _a13,_b6;let logger2,tryNextLink=!0;if("boolean"==typeof options){logger2=void 0;tryNextLink=options}else if(null!=options&&"object"==typeof options){logger2=options.logger;tryNextLink=null==(_a13=options.tryNextLink)||_a13}super(message);__publicField(this,"name","ProviderError");__publicField(this,"tryNextLink");this.tryNextLink=tryNextLink;Object.setPrototypeOf(this,_ProviderError.prototype);null==(_b6=null==logger2?void 0:logger2.debug)||_b6.call(logger2,`@smithy/property-provider ${tryNextLink?"->":"(!)"} ${message}`)}static from(error,options=!0){return Object.assign(new this(error.message,options),error)}};memoize=(provider,isExpired,requiresRefresh)=>{let resolved,pending3,hasResult,isConstant=!1;const coalesceProvider=async()=>{pending3||(pending3=provider());try{resolved=await pending3;hasResult=!0;isConstant=!1}finally{pending3=void 0}return resolved};return void 0===isExpired?async options=>{hasResult&&!(null==options?void 0:options.forceRefresh)||(resolved=await coalesceProvider());return resolved}:async options=>{hasResult&&!(null==options?void 0:options.forceRefresh)||(resolved=await coalesceProvider());if(isConstant)return resolved;if(requiresRefresh&&!requiresRefresh(resolved)){isConstant=!0;return resolved}if(isExpired(resolved)){await coalesceProvider();return resolved}return resolved}};resolveAwsSdkSigV4AConfig=config=>{config.sigv4aSigningRegionSet=normalizeProvider2(config.sigv4aSigningRegionSet);return config};0;SHORT_TO_HEX2={};HEX_TO_SHORT2={};for(let i3=0;i3<256;i3++){let encodedByte=i3.toString(16).toLowerCase();1===encodedByte.length&&(encodedByte=`0${encodedByte}`);SHORT_TO_HEX2[i3]=encodedByte;HEX_TO_SHORT2[encodedByte]=i3}init_index_browser2();ALGORITHM_QUERY_PARAM="X-Amz-Algorithm";CREDENTIAL_QUERY_PARAM="X-Amz-Credential";AMZ_DATE_QUERY_PARAM="X-Amz-Date";SIGNED_HEADERS_QUERY_PARAM="X-Amz-SignedHeaders";EXPIRES_QUERY_PARAM="X-Amz-Expires";SIGNATURE_QUERY_PARAM="X-Amz-Signature";TOKEN_QUERY_PARAM="X-Amz-Security-Token";0;AUTH_HEADER="authorization";AMZ_DATE_HEADER=AMZ_DATE_QUERY_PARAM.toLowerCase();DATE_HEADER="date";GENERATED_HEADERS=[AUTH_HEADER,AMZ_DATE_HEADER,DATE_HEADER];SIGNATURE_HEADER=SIGNATURE_QUERY_PARAM.toLowerCase();SHA256_HEADER="x-amz-content-sha256";TOKEN_HEADER=TOKEN_QUERY_PARAM.toLowerCase();0;ALWAYS_UNSIGNABLE_HEADERS={authorization:!0,"cache-control":!0,connection:!0,expect:!0,from:!0,"keep-alive":!0,"max-forwards":!0,pragma:!0,referer:!0,te:!0,trailer:!0,"transfer-encoding":!0,upgrade:!0,"user-agent":!0,"x-amzn-trace-id":!0};PROXY_HEADER_PATTERN=/^proxy-/;SEC_HEADER_PATTERN=/^sec-/;0;ALGORITHM_IDENTIFIER="AWS4-HMAC-SHA256";0;EVENT_ALGORITHM_IDENTIFIER="AWS4-HMAC-SHA256-PAYLOAD";UNSIGNED_PAYLOAD="UNSIGNED-PAYLOAD";MAX_CACHE_SIZE=50;KEY_TYPE_IDENTIFIER="aws4_request";MAX_PRESIGNED_TTL=604800;signingKeyCache={};cacheQueue=[];createScope=(shortDate,region,service)=>`${shortDate}/${region}/${service}/${KEY_TYPE_IDENTIFIER}`;getSigningKey=async(sha256Constructor,credentials,shortDate,region,service)=>{const credsHash=await hmac(sha256Constructor,credentials.secretAccessKey,credentials.accessKeyId),cacheKey=`${shortDate}:${region}:${service}:${toHex3(credsHash)}:${credentials.sessionToken}`;if(cacheKey in signingKeyCache)return signingKeyCache[cacheKey];cacheQueue.push(cacheKey);for(;cacheQueue.length>MAX_CACHE_SIZE;)delete signingKeyCache[cacheQueue.shift()];let key3=`AWS4${credentials.secretAccessKey}`;for(const signable of[shortDate,region,service,KEY_TYPE_IDENTIFIER])key3=await hmac(sha256Constructor,key3,signable);return signingKeyCache[cacheKey]=key3};0;hmac=(ctor,secret,data)=>{const hash3=new ctor(secret);hash3.update(toUint8Array(data));return hash3.digest()};getCanonicalHeaders=({headers},unsignableHeaders,signableHeaders)=>{const canonical={};for(const headerName of Object.keys(headers).sort()){if(null==headers[headerName])continue;const canonicalHeaderName=headerName.toLowerCase();(canonicalHeaderName in ALWAYS_UNSIGNABLE_HEADERS||(null==unsignableHeaders?void 0:unsignableHeaders.has(canonicalHeaderName))||PROXY_HEADER_PATTERN.test(canonicalHeaderName)||SEC_HEADER_PATTERN.test(canonicalHeaderName))&&(!signableHeaders||signableHeaders&&!signableHeaders.has(canonicalHeaderName))||(canonical[canonicalHeaderName]=headers[headerName].trim().replace(/\s+/g," "))}return canonical};init_index_browser2();getPayloadHash=async({headers,body},hashConstructor)=>{for(const headerName of Object.keys(headers))if(headerName.toLowerCase()===SHA256_HEADER)return headers[headerName];if(null==body)return"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";if("string"==typeof body||ArrayBuffer.isView(body)||isArrayBuffer(body)){const hashCtor=new hashConstructor;hashCtor.update(toUint8Array(body));return toHex3(await hashCtor.digest())}return UNSIGNED_PAYLOAD};HeaderFormatter=class{format(headers){const chunks=[];for(const headerName of Object.keys(headers)){const bytes=fromUtf8(headerName);chunks.push(Uint8Array.from([bytes.byteLength]),bytes,this.formatHeaderValue(headers[headerName]))}const out=new Uint8Array(chunks.reduce((carry,bytes)=>carry+bytes.byteLength,0));let position=0;for(const chunk of chunks){out.set(chunk,position);position+=chunk.byteLength}return out}formatHeaderValue(header){switch(header.type){case"boolean":return Uint8Array.from([header.value?0:1]);case"byte":return Uint8Array.from([2,header.value]);case"short":const shortView=new DataView(new ArrayBuffer(3));shortView.setUint8(0,3);shortView.setInt16(1,header.value,!1);return new Uint8Array(shortView.buffer);case"integer":const intView=new DataView(new ArrayBuffer(5));intView.setUint8(0,4);intView.setInt32(1,header.value,!1);return new Uint8Array(intView.buffer);case"long":const longBytes=new Uint8Array(9);longBytes[0]=5;longBytes.set(header.value.bytes,1);return longBytes;case"binary":const binView=new DataView(new ArrayBuffer(3+header.value.byteLength));binView.setUint8(0,6);binView.setUint16(1,header.value.byteLength,!1);const binBytes=new Uint8Array(binView.buffer);binBytes.set(header.value,3);return binBytes;case"string":const utf8Bytes=fromUtf8(header.value),strView=new DataView(new ArrayBuffer(3+utf8Bytes.byteLength));strView.setUint8(0,7);strView.setUint16(1,utf8Bytes.byteLength,!1);const strBytes=new Uint8Array(strView.buffer);strBytes.set(utf8Bytes,3);return strBytes;case"timestamp":const tsBytes=new Uint8Array(9);tsBytes[0]=8;tsBytes.set(Int642.fromNumber(header.value.valueOf()).bytes,1);return tsBytes;case"uuid":if(!UUID_PATTERN2.test(header.value))throw new Error(`Invalid UUID received: ${header.value}`);const uuidBytes=new Uint8Array(17);uuidBytes[0]=9;uuidBytes.set(fromHex2(header.value.replace(/\-/g,"")),1);return uuidBytes}}};(function(HEADER_VALUE_TYPE4){HEADER_VALUE_TYPE4[HEADER_VALUE_TYPE4.boolTrue=0]="boolTrue";HEADER_VALUE_TYPE4[HEADER_VALUE_TYPE4.boolFalse=1]="boolFalse";HEADER_VALUE_TYPE4[HEADER_VALUE_TYPE4.byte=2]="byte";HEADER_VALUE_TYPE4[HEADER_VALUE_TYPE4.short=3]="short";HEADER_VALUE_TYPE4[HEADER_VALUE_TYPE4.integer=4]="integer";HEADER_VALUE_TYPE4[HEADER_VALUE_TYPE4.long=5]="long";HEADER_VALUE_TYPE4[HEADER_VALUE_TYPE4.byteArray=6]="byteArray";HEADER_VALUE_TYPE4[HEADER_VALUE_TYPE4.string=7]="string";HEADER_VALUE_TYPE4[HEADER_VALUE_TYPE4.timestamp=8]="timestamp";HEADER_VALUE_TYPE4[HEADER_VALUE_TYPE4.uuid=9]="uuid"})(HEADER_VALUE_TYPE2||(HEADER_VALUE_TYPE2={}));UUID_PATTERN2=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;Int642=class _Int64{constructor(bytes){__publicField(this,"bytes");this.bytes=bytes;if(8!==bytes.byteLength)throw new Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(number){if(number>0x8000000000000000||number<-0x8000000000000000)throw new Error(`${number} is too large (or, if negative, too small) to represent as an Int64`);const bytes=new Uint8Array(8);for(let i3=7,remaining=Math.abs(Math.round(number));i3>-1&&remaining>0;i3--,remaining/=256)bytes[i3]=remaining;number<0&&negate2(bytes);return new _Int64(bytes)}valueOf(){const bytes=this.bytes.slice(0),negative=128&bytes[0];negative&&negate2(bytes);return parseInt(toHex3(bytes),16)*(negative?-1:1)}toString(){return String(this.valueOf())}};hasHeader=(soughtHeader,headers)=>{soughtHeader=soughtHeader.toLowerCase();for(const headerName of Object.keys(headers))if(soughtHeader===headerName.toLowerCase())return!0;return!1};0;0;moveHeadersToQuery=(request2,options={})=>{var _a13,_b6;const{headers,query:query3={}}=HttpRequest.clone(request2);for(const name of Object.keys(headers)){const lname=name.toLowerCase();if("x-amz-"===lname.slice(0,6)&&!(null==(_a13=options.unhoistableHeaders)?void 0:_a13.has(lname))||(null==(_b6=options.hoistableHeaders)?void 0:_b6.has(lname))){query3[name]=headers[name];delete headers[name]}}return{...request2,headers,query:query3}};prepareRequest=request2=>{request2=HttpRequest.clone(request2);for(const headerName of Object.keys(request2.headers))GENERATED_HEADERS.indexOf(headerName.toLowerCase())>-1&&delete request2.headers[headerName];return request2};init_dist_es();getSmithyContext2=context2=>context2[SMITHY_CONTEXT_KEY]||(context2[SMITHY_CONTEXT_KEY]={});normalizeProvider3=input=>{if("function"==typeof input)return input;const promisified=Promise.resolve(input);return()=>promisified};escapeUri2=uri=>encodeURIComponent(uri).replace(/[!'()*]/g,hexEncode);hexEncode=c3=>`%${c3.charCodeAt(0).toString(16).toUpperCase()}`;getCanonicalQuery=({query:query3={}})=>{const keys3=[],serialized2={};for(const key3 of Object.keys(query3)){if(key3.toLowerCase()===SIGNATURE_HEADER)continue;const encodedKey=escapeUri2(key3);keys3.push(encodedKey);const value=query3[key3];"string"==typeof value?serialized2[encodedKey]=`${encodedKey}=${escapeUri2(value)}`:Array.isArray(value)&&(serialized2[encodedKey]=value.slice(0).reduce((encoded,value2)=>encoded.concat([`${encodedKey}=${escapeUri2(value2)}`]),[]).sort().join("&"))}return keys3.sort().map(key3=>serialized2[key3]).filter(serialized3=>serialized3).join("&")};iso8601=time2=>toDate(time2).toISOString().replace(/\.\d{3}Z$/,"Z");toDate=time2=>"number"==typeof time2?new Date(1e3*time2):"string"==typeof time2?Number(time2)?new Date(1e3*Number(time2)):new Date(time2):time2;SignatureV4Base=class{constructor({applyChecksum,credentials,region,service,sha256,uriEscapePath=!0}){__publicField(this,"service");__publicField(this,"regionProvider");__publicField(this,"credentialProvider");__publicField(this,"sha256");__publicField(this,"uriEscapePath");__publicField(this,"applyChecksum");this.service=service;this.sha256=sha256;this.uriEscapePath=uriEscapePath;this.applyChecksum="boolean"!=typeof applyChecksum||applyChecksum;this.regionProvider=normalizeProvider3(region);this.credentialProvider=normalizeProvider3(credentials)}createCanonicalRequest(request2,canonicalHeaders,payloadHash){const sortedHeaders=Object.keys(canonicalHeaders).sort();return`${request2.method}\n${this.getCanonicalPath(request2)}\n${getCanonicalQuery(request2)}\n${sortedHeaders.map(name=>`${name}:${canonicalHeaders[name]}`).join("\n")}\n\n${sortedHeaders.join(";")}\n${payloadHash}`}async createStringToSign(longDate,credentialScope,canonicalRequest,algorithmIdentifier){const hash3=new this.sha256;hash3.update(toUint8Array(canonicalRequest));const hashedRequest=await hash3.digest();return`${algorithmIdentifier}\n${longDate}\n${credentialScope}\n${toHex3(hashedRequest)}`}getCanonicalPath({path:path2}){if(this.uriEscapePath){const normalizedPathSegments=[];for(const pathSegment of path2.split("/"))0!==(null==pathSegment?void 0:pathSegment.length)&&"."!==pathSegment&&(".."===pathSegment?normalizedPathSegments.pop():normalizedPathSegments.push(pathSegment));const normalizedPath=`${(null==path2?void 0:path2.startsWith("/"))?"/":""}${normalizedPathSegments.join("/")}${normalizedPathSegments.length>0&&(null==path2?void 0:path2.endsWith("/"))?"/":""}`,doubleEncoded=escapeUri2(normalizedPath);return doubleEncoded.replace(/%2F/g,"/")}return path2}validateResolvedCredentials(credentials){if("object"!=typeof credentials||"string"!=typeof credentials.accessKeyId||"string"!=typeof credentials.secretAccessKey)throw new Error("Resolved credential object is not valid")}formatDate(now3){const longDate=iso8601(now3).replace(/[\-:]/g,"");return{longDate,shortDate:longDate.slice(0,8)}}getCanonicalHeaderList(headers){return Object.keys(headers).sort().join(";")}};SignatureV4=class extends SignatureV4Base{constructor({applyChecksum,credentials,region,service,sha256,uriEscapePath=!0}){super({applyChecksum,credentials,region,service,sha256,uriEscapePath});__publicField(this,"headerFormatter",new HeaderFormatter)}async presign(originalRequest,options={}){const{signingDate=new Date,expiresIn=3600,unsignableHeaders,unhoistableHeaders,signableHeaders,hoistableHeaders,signingRegion,signingService}=options,credentials=await this.credentialProvider();this.validateResolvedCredentials(credentials);const region=null!=signingRegion?signingRegion:await this.regionProvider(),{longDate,shortDate}=this.formatDate(signingDate);if(expiresIn>MAX_PRESIGNED_TTL)return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");const scope=createScope(shortDate,region,null!=signingService?signingService:this.service),request2=moveHeadersToQuery(prepareRequest(originalRequest),{unhoistableHeaders,hoistableHeaders});credentials.sessionToken&&(request2.query[TOKEN_QUERY_PARAM]=credentials.sessionToken);request2.query[ALGORITHM_QUERY_PARAM]=ALGORITHM_IDENTIFIER;request2.query[CREDENTIAL_QUERY_PARAM]=`${credentials.accessKeyId}/${scope}`;request2.query[AMZ_DATE_QUERY_PARAM]=longDate;request2.query[EXPIRES_QUERY_PARAM]=expiresIn.toString(10);const canonicalHeaders=getCanonicalHeaders(request2,unsignableHeaders,signableHeaders);request2.query[SIGNED_HEADERS_QUERY_PARAM]=this.getCanonicalHeaderList(canonicalHeaders);request2.query[SIGNATURE_QUERY_PARAM]=await this.getSignature(longDate,scope,this.getSigningKey(credentials,region,shortDate,signingService),this.createCanonicalRequest(request2,canonicalHeaders,await getPayloadHash(originalRequest,this.sha256)));return request2}async sign(toSign,options){return"string"==typeof toSign?this.signString(toSign,options):toSign.headers&&toSign.payload?this.signEvent(toSign,options):toSign.message?this.signMessage(toSign,options):this.signRequest(toSign,options)}async signEvent({headers,payload},{signingDate=new Date,priorSignature,signingRegion,signingService}){const region=null!=signingRegion?signingRegion:await this.regionProvider(),{shortDate,longDate}=this.formatDate(signingDate),scope=createScope(shortDate,region,null!=signingService?signingService:this.service),hashedPayload=await getPayloadHash({headers:{},body:payload},this.sha256),hash3=new this.sha256;hash3.update(headers);const hashedHeaders=toHex3(await hash3.digest()),stringToSign=[EVENT_ALGORITHM_IDENTIFIER,longDate,scope,priorSignature,hashedHeaders,hashedPayload].join("\n");return this.signString(stringToSign,{signingDate,signingRegion:region,signingService})}async signMessage(signableMessage,{signingDate=new Date,signingRegion,signingService}){const promise=this.signEvent({headers:this.headerFormatter.format(signableMessage.message.headers),payload:signableMessage.message.body},{signingDate,signingRegion,signingService,priorSignature:signableMessage.priorSignature});return promise.then(signature=>({message:signableMessage.message,signature}))}async signString(stringToSign,{signingDate=new Date,signingRegion,signingService}={}){const credentials=await this.credentialProvider();this.validateResolvedCredentials(credentials);const region=null!=signingRegion?signingRegion:await this.regionProvider(),{shortDate}=this.formatDate(signingDate),hash3=new this.sha256(await this.getSigningKey(credentials,region,shortDate,signingService));hash3.update(toUint8Array(stringToSign));return toHex3(await hash3.digest())}async signRequest(requestToSign,{signingDate=new Date,signableHeaders,unsignableHeaders,signingRegion,signingService}={}){const credentials=await this.credentialProvider();this.validateResolvedCredentials(credentials);const region=null!=signingRegion?signingRegion:await this.regionProvider(),request2=prepareRequest(requestToSign),{longDate,shortDate}=this.formatDate(signingDate),scope=createScope(shortDate,region,null!=signingService?signingService:this.service);request2.headers[AMZ_DATE_HEADER]=longDate;credentials.sessionToken&&(request2.headers[TOKEN_HEADER]=credentials.sessionToken);const payloadHash=await getPayloadHash(request2,this.sha256);!hasHeader(SHA256_HEADER,request2.headers)&&this.applyChecksum&&(request2.headers[SHA256_HEADER]=payloadHash);const canonicalHeaders=getCanonicalHeaders(request2,unsignableHeaders,signableHeaders),signature=await this.getSignature(longDate,scope,this.getSigningKey(credentials,region,shortDate,signingService),this.createCanonicalRequest(request2,canonicalHeaders,payloadHash));request2.headers[AUTH_HEADER]=`${ALGORITHM_IDENTIFIER} Credential=${credentials.accessKeyId}/${scope}, SignedHeaders=${this.getCanonicalHeaderList(canonicalHeaders)}, Signature=${signature}`;return request2}async getSignature(longDate,credentialScope,keyPromise,canonicalRequest){const stringToSign=await this.createStringToSign(longDate,credentialScope,canonicalRequest,ALGORITHM_IDENTIFIER),hash3=new this.sha256(await keyPromise);hash3.update(toUint8Array(stringToSign));return toHex3(await hash3.digest())}getSigningKey(credentials,region,shortDate,service){return getSigningKey(this.sha256,credentials,shortDate,region,service||this.service)}};signatureV4aContainer_SignatureV4a=null;resolveAwsSdkSigV4Config=config=>{let resolvedCredentials,inputCredentials=config.credentials,isUserSupplied=!!config.credentials;Object.defineProperty(config,"credentials",{set(credentials){credentials&&credentials!==inputCredentials&&credentials!==resolvedCredentials&&(isUserSupplied=!0);inputCredentials=credentials;const memoizedProvider=normalizeCredentialProvider(config,{credentials:inputCredentials,credentialDefaultProvider:config.credentialDefaultProvider}),boundProvider=bindCallerConfig(config,memoizedProvider);if(isUserSupplied&&!boundProvider.attributed){const isCredentialObject="object"==typeof inputCredentials&&null!==inputCredentials;resolvedCredentials=async options=>{const creds=await boundProvider(options),attributedCreds=creds;return!isCredentialObject||attributedCreds.$source&&0!==Object.keys(attributedCreds.$source).length?attributedCreds:setCredentialFeature(attributedCreds,"CREDENTIALS_CODE","e")};resolvedCredentials.memoized=boundProvider.memoized;resolvedCredentials.configBound=boundProvider.configBound;resolvedCredentials.attributed=!0}else resolvedCredentials=boundProvider},get:()=>resolvedCredentials,enumerable:!0,configurable:!0});config.credentials=inputCredentials;const{signingEscapePath=!0,systemClockOffset=config.systemClockOffset||0,sha256}=config;let signer;signer=config.signer?normalizeProvider2(config.signer):config.regionInfoProvider?()=>normalizeProvider2(config.region)().then(async region=>[await config.regionInfoProvider(region,{useFipsEndpoint:await config.useFipsEndpoint(),useDualstackEndpoint:await config.useDualstackEndpoint()})||{},region]).then(([regionInfo,region])=>{const{signingRegion,signingService}=regionInfo;config.signingRegion=config.signingRegion||signingRegion||region;config.signingName=config.signingName||signingService||config.serviceId;const params={...config,credentials:config.credentials,region:config.signingRegion,service:config.signingName,sha256,uriEscapePath:signingEscapePath},SignerCtor=config.signerConstructor||SignatureV4;return new SignerCtor(params)}):async authScheme=>{authScheme=Object.assign({},{name:"sigv4",signingName:config.signingName||config.defaultSigningName,signingRegion:await normalizeProvider2(config.region)(),properties:{}},authScheme);const signingRegion=authScheme.signingRegion,signingService=authScheme.signingName;config.signingRegion=config.signingRegion||signingRegion;config.signingName=config.signingName||signingService||config.serviceId;const params={...config,credentials:config.credentials,region:config.signingRegion,service:config.signingName,sha256,uriEscapePath:signingEscapePath},SignerCtor=config.signerConstructor||SignatureV4;return new SignerCtor(params)};const resolvedConfig=Object.assign(config,{systemClockOffset,signingEscapePath,signer});return resolvedConfig};0;getAllAliases=(name,aliases)=>{const _aliases=[];name&&_aliases.push(name);if(aliases)for(const alias of aliases)_aliases.push(alias);return _aliases};getMiddlewareNameWithAliases=(name,aliases)=>`${name||"anonymous"}${aliases&&aliases.length>0?` (a.k.a. ${aliases.join(",")})`:""}`;constructStack=()=>{let absoluteEntries=[],relativeEntries=[],identifyOnResolve=!1;const entriesNameSet=new Set,sort=entries2=>entries2.sort((a2,b3)=>stepWeights[b3.step]-stepWeights[a2.step]||priorityWeights[b3.priority||"normal"]-priorityWeights[a2.priority||"normal"]),removeByName=toRemove=>{let isRemoved=!1;const filterCb=entry=>{const aliases=getAllAliases(entry.name,entry.aliases);if(aliases.includes(toRemove)){isRemoved=!0;for(const alias of aliases)entriesNameSet.delete(alias);return!1}return!0};absoluteEntries=absoluteEntries.filter(filterCb);relativeEntries=relativeEntries.filter(filterCb);return isRemoved},removeByReference=toRemove=>{let isRemoved=!1;const filterCb=entry=>{if(entry.middleware===toRemove){isRemoved=!0;for(const alias of getAllAliases(entry.name,entry.aliases))entriesNameSet.delete(alias);return!1}return!0};absoluteEntries=absoluteEntries.filter(filterCb);relativeEntries=relativeEntries.filter(filterCb);return isRemoved},cloneTo=toStack=>{var _a13;absoluteEntries.forEach(entry=>{toStack.add(entry.middleware,{...entry})});relativeEntries.forEach(entry=>{toStack.addRelativeTo(entry.middleware,{...entry})});null==(_a13=toStack.identifyOnResolve)||_a13.call(toStack,stack2.identifyOnResolve());return toStack},expandRelativeMiddlewareList=from=>{const expandedMiddlewareList=[];from.before.forEach(entry=>{0===entry.before.length&&0===entry.after.length?expandedMiddlewareList.push(entry):expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry))});expandedMiddlewareList.push(from);from.after.reverse().forEach(entry=>{0===entry.before.length&&0===entry.after.length?expandedMiddlewareList.push(entry):expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry))});return expandedMiddlewareList},getMiddlewareList=(debug2=!1)=>{const normalizedAbsoluteEntries=[],normalizedRelativeEntries=[],normalizedEntriesNameMap={};absoluteEntries.forEach(entry=>{const normalizedEntry={...entry,before:[],after:[]};for(const alias of getAllAliases(normalizedEntry.name,normalizedEntry.aliases))normalizedEntriesNameMap[alias]=normalizedEntry;normalizedAbsoluteEntries.push(normalizedEntry)});relativeEntries.forEach(entry=>{const normalizedEntry={...entry,before:[],after:[]};for(const alias of getAllAliases(normalizedEntry.name,normalizedEntry.aliases))normalizedEntriesNameMap[alias]=normalizedEntry;normalizedRelativeEntries.push(normalizedEntry)});normalizedRelativeEntries.forEach(entry=>{if(entry.toMiddleware){const toMiddleware=normalizedEntriesNameMap[entry.toMiddleware];if(void 0===toMiddleware){if(debug2)return;throw new Error(`${entry.toMiddleware} is not found when adding ${getMiddlewareNameWithAliases(entry.name,entry.aliases)} middleware ${entry.relation} ${entry.toMiddleware}`)}"after"===entry.relation&&toMiddleware.after.push(entry);"before"===entry.relation&&toMiddleware.before.push(entry)}});const mainChain=sort(normalizedAbsoluteEntries).map(expandRelativeMiddlewareList).reduce((wholeList,expandedMiddlewareList)=>{wholeList.push(...expandedMiddlewareList);return wholeList},[]);return mainChain},stack2={add:(middleware,options={})=>{const{name,override,aliases:_aliases}=options,entry={step:"initialize",priority:"normal",middleware,...options},aliases=getAllAliases(name,_aliases);if(aliases.length>0){if(aliases.some(alias=>entriesNameSet.has(alias))){if(!override)throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name,_aliases)}'`);for(const alias of aliases){const toOverrideIndex=absoluteEntries.findIndex(entry2=>{var _a13;return entry2.name===alias||(null==(_a13=entry2.aliases)?void 0:_a13.some(a2=>a2===alias))});if(-1===toOverrideIndex)continue;const toOverride=absoluteEntries[toOverrideIndex];if(toOverride.step!==entry.step||entry.priority!==toOverride.priority)throw new Error(`"${getMiddlewareNameWithAliases(toOverride.name,toOverride.aliases)}" middleware with ${toOverride.priority} priority in ${toOverride.step} step cannot be overridden by "${getMiddlewareNameWithAliases(name,_aliases)}" middleware with ${entry.priority} priority in ${entry.step} step.`);absoluteEntries.splice(toOverrideIndex,1)}}for(const alias of aliases)entriesNameSet.add(alias)}absoluteEntries.push(entry)},addRelativeTo:(middleware,options)=>{const{name,override,aliases:_aliases}=options,entry={middleware,...options},aliases=getAllAliases(name,_aliases);if(aliases.length>0){if(aliases.some(alias=>entriesNameSet.has(alias))){if(!override)throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name,_aliases)}'`);for(const alias of aliases){const toOverrideIndex=relativeEntries.findIndex(entry2=>{var _a13;return entry2.name===alias||(null==(_a13=entry2.aliases)?void 0:_a13.some(a2=>a2===alias))});if(-1===toOverrideIndex)continue;const toOverride=relativeEntries[toOverrideIndex];if(toOverride.toMiddleware!==entry.toMiddleware||toOverride.relation!==entry.relation)throw new Error(`"${getMiddlewareNameWithAliases(toOverride.name,toOverride.aliases)}" middleware ${toOverride.relation} "${toOverride.toMiddleware}" middleware cannot be overridden by "${getMiddlewareNameWithAliases(name,_aliases)}" middleware ${entry.relation} "${entry.toMiddleware}" middleware.`);relativeEntries.splice(toOverrideIndex,1)}}for(const alias of aliases)entriesNameSet.add(alias)}relativeEntries.push(entry)},clone:()=>cloneTo(constructStack()),use:plugin2=>{plugin2.applyToStack(stack2)},remove:toRemove=>"string"==typeof toRemove?removeByName(toRemove):removeByReference(toRemove),removeByTag:toRemove=>{let isRemoved=!1;const filterCb=entry=>{const{tags,name,aliases:_aliases}=entry;if(tags&&tags.includes(toRemove)){const aliases=getAllAliases(name,_aliases);for(const alias of aliases)entriesNameSet.delete(alias);isRemoved=!0;return!1}return!0};absoluteEntries=absoluteEntries.filter(filterCb);relativeEntries=relativeEntries.filter(filterCb);return isRemoved},concat:from=>{var _a13,_b6;const cloned=cloneTo(constructStack());cloned.use(from);cloned.identifyOnResolve(identifyOnResolve||cloned.identifyOnResolve()||null!=(_b6=null==(_a13=from.identifyOnResolve)?void 0:_a13.call(from))&&_b6);return cloned},applyToStack:cloneTo,identify:()=>getMiddlewareList(!0).map(mw=>{var _a13;const step=null!=(_a13=mw.step)?_a13:mw.relation+" "+mw.toMiddleware;return getMiddlewareNameWithAliases(mw.name,mw.aliases)+" - "+step}),identifyOnResolve(toggle){"boolean"==typeof toggle&&(identifyOnResolve=toggle);return identifyOnResolve},resolve:(handler,context2)=>{for(const middleware of getMiddlewareList().map(entry=>entry.middleware).reverse())handler=middleware(handler,context2);identifyOnResolve&&console.log(stack2.identify());return handler}};return stack2};stepWeights={initialize:5,serialize:4,build:3,finalizeRequest:2,deserialize:1};priorityWeights={high:3,normal:2,low:1};Client=class{constructor(config){__publicField(this,"config");__publicField(this,"middlewareStack",constructStack());__publicField(this,"initConfig");__publicField(this,"handlers");this.config=config;const{protocol,protocolSettings}=config;protocolSettings&&"function"==typeof protocol&&(config.protocol=new protocol(protocolSettings))}send(command,optionsOrCb,cb2){const options="function"!=typeof optionsOrCb?optionsOrCb:void 0,callback="function"==typeof optionsOrCb?optionsOrCb:cb2,useHandlerCache=void 0===options&&!0===this.config.cacheMiddleware;let handler;if(useHandlerCache){this.handlers||(this.handlers=new WeakMap);const handlers3=this.handlers;if(handlers3.has(command.constructor))handler=handlers3.get(command.constructor);else{handler=command.resolveMiddleware(this.middlewareStack,this.config,options);handlers3.set(command.constructor,handler)}}else{delete this.handlers;handler=command.resolveMiddleware(this.middlewareStack,this.config,options)}if(!callback)return handler(command).then(result=>result.output);handler(command).then(result=>callback(null,result.output),err3=>callback(err3)).catch(()=>{})}destroy(){var _a13,_b6,_c3;null==(_c3=null==(_b6=null==(_a13=this.config)?void 0:_a13.requestHandler)?void 0:_b6.destroy)||_c3.call(_b6);delete this.handlers}};SENSITIVE_STRING="***SensitiveInformation***";init_dist_es();Command=class{constructor(){__publicField(this,"middlewareStack",constructStack());__publicField(this,"schema")}static classBuilder(){return new ClassBuilder}resolveMiddlewareWithContext(clientStack,configuration,options,{middlewareFn,clientName,commandName,inputFilterSensitiveLog,outputFilterSensitiveLog,smithyContext,additionalContext,CommandCtor}){for(const mw of middlewareFn.bind(this)(CommandCtor,clientStack,configuration,options))this.middlewareStack.use(mw);const stack2=clientStack.concat(this.middlewareStack),{logger:logger2}=configuration,handlerExecutionContext={logger:logger2,clientName,commandName,inputFilterSensitiveLog,outputFilterSensitiveLog,[SMITHY_CONTEXT_KEY]:{commandInstance:this,...smithyContext},...additionalContext},{requestHandler}=configuration;return stack2.resolve(request2=>requestHandler.handle(request2.request,options||{}),handlerExecutionContext)}};ClassBuilder=class{constructor(){__publicField(this,"_init",()=>{});__publicField(this,"_ep",{});__publicField(this,"_middlewareFn",()=>[]);__publicField(this,"_commandName","");__publicField(this,"_clientName","");__publicField(this,"_additionalContext",{});__publicField(this,"_smithyContext",{});__publicField(this,"_inputFilterSensitiveLog");__publicField(this,"_outputFilterSensitiveLog");__publicField(this,"_serializer",null);__publicField(this,"_deserializer",null);__publicField(this,"_operationSchema")}init(cb2){this._init=cb2}ep(endpointParameterInstructions){this._ep=endpointParameterInstructions;return this}m(middlewareSupplier){this._middlewareFn=middlewareSupplier;return this}s(service,operation2,smithyContext={}){this._smithyContext={service,operation:operation2,...smithyContext};return this}c(additionalContext={}){this._additionalContext=additionalContext;return this}n(clientName,commandName){this._clientName=clientName;this._commandName=commandName;return this}f(inputFilter=_=>_,outputFilter=_=>_){this._inputFilterSensitiveLog=inputFilter;this._outputFilterSensitiveLog=outputFilter;return this}ser(serializer){this._serializer=serializer;return this}de(deserializer){this._deserializer=deserializer;return this}sc(operation2){this._operationSchema=operation2;this._smithyContext.operationSchema=operation2;return this}build(){const closure=this;let CommandRef;return CommandRef=class extends Command{constructor(...[input]){super();__publicField(this,"input");__publicField(this,"serialize",closure._serializer);__publicField(this,"deserialize",closure._deserializer);this.input=null!=input?input:{};closure._init(this);this.schema=closure._operationSchema}static getEndpointParameterInstructions(){return closure._ep}resolveMiddleware(stack2,configuration,options){var _a13,_b6,_c3,_d2;const op=closure._operationSchema,input=null!=(_a13=null==op?void 0:op[4])?_a13:null==op?void 0:op.input,output=null!=(_b6=null==op?void 0:op[5])?_b6:null==op?void 0:op.output;return this.resolveMiddlewareWithContext(stack2,configuration,options,{CommandCtor:CommandRef,middlewareFn:closure._middlewareFn,clientName:closure._clientName,commandName:closure._commandName,inputFilterSensitiveLog:null!=(_c3=closure._inputFilterSensitiveLog)?_c3:op?schemaLogFilter.bind(null,input):_=>_,outputFilterSensitiveLog:null!=(_d2=closure._outputFilterSensitiveLog)?_d2:op?schemaLogFilter.bind(null,output):_=>_,smithyContext:closure._smithyContext,additionalContext:closure._additionalContext})}}}};createAggregatedClient=(commands2,Client3,options)=>{for(const[command,CommandCtor]of Object.entries(commands2)){const methodImpl=async function(args,optionsOrCb,cb2){const command2=new CommandCtor(args);if("function"==typeof optionsOrCb)this.send(command2,optionsOrCb);else{if("function"!=typeof cb2)return this.send(command2,optionsOrCb);if("object"!=typeof optionsOrCb)throw new Error("Expected http options but got "+typeof optionsOrCb);this.send(command2,optionsOrCb||{},cb2)}},methodName=(command[0].toLowerCase()+command.slice(1)).replace(/Command$/,"");Client3.prototype[methodName]=methodImpl}const{paginators:paginators2={},waiters:waiters2={}}=null!=options?options:{};for(const[paginatorName,paginatorFn]of Object.entries(paginators2))void 0===Client3.prototype[paginatorName]&&(Client3.prototype[paginatorName]=function(commandInput={},paginationConfiguration,...rest){return paginatorFn({...paginationConfiguration,client:this},commandInput,...rest)});for(const[waiterName,waiterFn]of Object.entries(waiters2))void 0===Client3.prototype[waiterName]&&(Client3.prototype[waiterName]=async function(commandInput={},waiterConfiguration,...rest){let config=waiterConfiguration;"number"==typeof waiterConfiguration&&(config={maxWaitTime:waiterConfiguration});return waiterFn({...config,client:this},commandInput,...rest)})};ServiceException=class _ServiceException extends Error{constructor(options){super(options.message);__publicField(this,"$fault");__publicField(this,"$response");__publicField(this,"$retryable");__publicField(this,"$metadata");Object.setPrototypeOf(this,Object.getPrototypeOf(this).constructor.prototype);this.name=options.name;this.$fault=options.$fault;this.$metadata=options.$metadata}static isInstance(value){if(!value)return!1;const candidate=value;return _ServiceException.prototype.isPrototypeOf(candidate)||Boolean(candidate.$fault)&&Boolean(candidate.$metadata)&&("client"===candidate.$fault||"server"===candidate.$fault)}static[Symbol.hasInstance](instance){if(!instance)return!1;const candidate=instance;return this===_ServiceException?_ServiceException.isInstance(instance):!!_ServiceException.isInstance(instance)&&(candidate.name&&this.name?this.prototype.isPrototypeOf(instance)||candidate.name===this.name:this.prototype.isPrototypeOf(instance))}};decorateServiceException=(exception,additions={})=>{Object.entries(additions).filter(([,v2])=>void 0!==v2).forEach(([k2,v2])=>{null!=exception[k2]&&""!==exception[k2]||(exception[k2]=v2)});const message=exception.message||exception.Message||"UnknownError";exception.message=message;delete exception.Message;return exception};loadConfigsForDefaultMode=mode=>{switch(mode){case"standard":return{retryMode:"standard",connectionTimeout:3100};case"in-region":return{retryMode:"standard",connectionTimeout:1100};case"cross-region":return{retryMode:"standard",connectionTimeout:3100};case"mobile":return{retryMode:"standard",connectionTimeout:3e4};default:return{}}};init_dist_es();knownAlgorithms=Object.values(AlgorithmId);getChecksumConfiguration2=runtimeConfig=>{var _a13;const checksumAlgorithms=[];for(const id in AlgorithmId){const algorithmId=AlgorithmId[id];void 0!==runtimeConfig[algorithmId]&&checksumAlgorithms.push({algorithmId:()=>algorithmId,checksumConstructor:()=>runtimeConfig[algorithmId]})}for(const[id,ChecksumCtor]of Object.entries(null!=(_a13=runtimeConfig.checksumAlgorithms)?_a13:{}))checksumAlgorithms.push({algorithmId:()=>id,checksumConstructor:()=>ChecksumCtor});return{addChecksumAlgorithm(algo2){var _a14;runtimeConfig.checksumAlgorithms=null!=(_a14=runtimeConfig.checksumAlgorithms)?_a14:{};const id=algo2.algorithmId(),ctor=algo2.checksumConstructor();knownAlgorithms.includes(id)?runtimeConfig.checksumAlgorithms[id.toUpperCase()]=ctor:runtimeConfig.checksumAlgorithms[id]=ctor;checksumAlgorithms.push(algo2)},checksumAlgorithms:()=>checksumAlgorithms}};resolveChecksumRuntimeConfig2=clientConfig=>{const runtimeConfig={};clientConfig.checksumAlgorithms().forEach(checksumAlgorithm=>{const id=checksumAlgorithm.algorithmId();knownAlgorithms.includes(id)&&(runtimeConfig[id]=checksumAlgorithm.checksumConstructor())});return runtimeConfig};getRetryConfiguration=runtimeConfig=>({setRetryStrategy(retryStrategy){runtimeConfig.retryStrategy=retryStrategy},retryStrategy:()=>runtimeConfig.retryStrategy});resolveRetryRuntimeConfig=retryStrategyConfiguration=>{const runtimeConfig={};runtimeConfig.retryStrategy=retryStrategyConfiguration.retryStrategy();return runtimeConfig};getDefaultExtensionConfiguration=runtimeConfig=>Object.assign(getChecksumConfiguration2(runtimeConfig),getRetryConfiguration(runtimeConfig));0;resolveDefaultRuntimeConfig=config=>Object.assign(resolveChecksumRuntimeConfig2(config),resolveRetryRuntimeConfig(config));getValueFromTextNode=obj=>{for(const key3 in obj)obj.hasOwnProperty(key3)&&void 0!==obj[key3]["#text"]?obj[key3]=obj[key3]["#text"]:"object"==typeof obj[key3]&&null!==obj[key3]&&(obj[key3]=getValueFromTextNode(obj[key3]));return obj};NoOpLogger=class{trace(){}debug(){}info(){}warn(){}error(){}};ProtocolLib=class{constructor(queryCompat=!1){__publicField(this,"queryCompat");__publicField(this,"errorRegistry");this.queryCompat=queryCompat}resolveRestContentType(defaultContentType,inputSchema){const members=inputSchema.getMemberSchemas(),httpPayloadMember=Object.values(members).find(m3=>!!m3.getMergedTraits().httpPayload);if(httpPayloadMember){const mediaType=httpPayloadMember.getMergedTraits().mediaType;return mediaType||(httpPayloadMember.isStringSchema()?"text/plain":httpPayloadMember.isBlobSchema()?"application/octet-stream":defaultContentType)}if(!inputSchema.isUnitSchema()){const hasBody=Object.values(members).find(m3=>{const{httpQuery,httpQueryParams,httpHeader,httpLabel,httpPrefixHeaders}=m3.getMergedTraits(),noPrefixHeaders=void 0===httpPrefixHeaders;return!httpQuery&&!httpQueryParams&&!httpHeader&&!httpLabel&&noPrefixHeaders});if(hasBody)return defaultContentType}}async getErrorSchemaOrThrowBaseException(errorIdentifier,defaultNamespace,response,dataObject,metadata,getErrorSchema){var _a13,_b6,_c3,_d2,_e2,_f,_g,_h2,_i2;let errorName=errorIdentifier;errorIdentifier.includes("#")&&([,errorName]=errorIdentifier.split("#"));const errorMetadata={$metadata:metadata,$fault:response.statusCode<500?"client":"server"};if(!this.errorRegistry)throw new Error("@aws-sdk/core/protocols - error handler not initialized.");try{const errorSchema=null!=(_a13=null==getErrorSchema?void 0:getErrorSchema(this.errorRegistry,errorName))?_a13:this.errorRegistry.getSchema(errorIdentifier);return{errorSchema,errorMetadata}}catch(e3){dataObject.message=null!=(_c3=null!=(_b6=dataObject.message)?_b6:dataObject.Message)?_c3:"UnknownError";const synthetic=this.errorRegistry,baseExceptionSchema=synthetic.getBaseException();if(baseExceptionSchema){const ErrorCtor=null!=(_d2=synthetic.getErrorCtor(baseExceptionSchema))?_d2:Error;throw this.decorateServiceException(Object.assign(new ErrorCtor({name:errorName}),errorMetadata),dataObject)}const d4=dataObject,message=null!=(_i2=null!=(_g=null!=(_e2=null==d4?void 0:d4.message)?_e2:null==d4?void 0:d4.Message)?_g:null==(_f=null==d4?void 0:d4.Error)?void 0:_f.Message)?_i2:null==(_h2=null==d4?void 0:d4.Error)?void 0:_h2.message;throw this.decorateServiceException(Object.assign(new Error(message),{name:errorName},errorMetadata),dataObject)}}compose(composite,errorIdentifier,defaultNamespace){let namespace=defaultNamespace;errorIdentifier.includes("#")&&([namespace]=errorIdentifier.split("#"));const staticRegistry=TypeRegistry.for(namespace),defaultSyntheticRegistry=TypeRegistry.for("smithy.ts.sdk.synthetic."+defaultNamespace);composite.copyFrom(staticRegistry);composite.copyFrom(defaultSyntheticRegistry);this.errorRegistry=composite}decorateServiceException(exception,additions={}){var _a13,_b6,_c3,_d2,_e2,_f,_g;if(this.queryCompat){const msg=null!=(_a13=exception.Message)?_a13:additions.Message,error=decorateServiceException(exception,additions);msg&&(error.message=msg);error.Error={...error.Error,Type:null==(_b6=error.Error)?void 0:_b6.Type,Code:null==(_c3=error.Error)?void 0:_c3.Code,Message:null!=(_g=null!=(_f=null==(_d2=error.Error)?void 0:_d2.message)?_f:null==(_e2=error.Error)?void 0:_e2.Message)?_g:msg};const reqId=error.$metadata.requestId;reqId&&(error.RequestId=reqId);return error}return decorateServiceException(exception,additions)}setQueryCompatError(output,response){var _a13;const queryErrorHeader=null==(_a13=response.headers)?void 0:_a13["x-amzn-query-error"];if(void 0!==output&&null!=queryErrorHeader){const[Code,Type]=queryErrorHeader.split(";"),entries2=Object.entries(output),Error2={Code,Type};Object.assign(output,Error2);for(const[k2,v2]of entries2)Error2["message"===k2?"Message":k2]=v2;delete Error2.__type;output.Error=Error2}}queryCompatOutput(queryCompatErrorData,errorData){queryCompatErrorData.Error&&(errorData.Error=queryCompatErrorData.Error);queryCompatErrorData.Type&&(errorData.Type=queryCompatErrorData.Type);queryCompatErrorData.Code&&(errorData.Code=queryCompatErrorData.Code)}findQueryCompatibleError(registry,errorName){try{return registry.getSchema(errorName)}catch(e3){return registry.find(schema=>{var _a13;return(null==(_a13=NormalizedSchema.of(schema).getMergedTraits().awsQueryError)?void 0:_a13[0])===errorName})}}};SerdeContextConfig=class{constructor(){__publicField(this,"serdeContext")}setSerdeContext(serdeContext){this.serdeContext=serdeContext}};chars2="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";alphabetByEncoding2=Object.entries(chars2).reduce((acc,[i3,c3])=>{acc[c3]=Number(i3);return acc},{});alphabetByValue2=chars2.split("");bitsPerLetter2=6;bitsPerByte2=8;maxLetterValue2=63;fromBase642=input=>{let totalByteLength=input.length/4*3;"=="===input.slice(-2)?totalByteLength-=2:"="===input.slice(-1)&&totalByteLength--;const out=new ArrayBuffer(totalByteLength),dataView=new DataView(out);for(let i3=0;i3<input.length;i3+=4){let bits2=0,bitLength=0;for(let j2=i3,limit=i3+3;j2<=limit;j2++)if("="!==input[j2]){if(!(input[j2]in alphabetByEncoding2))throw new TypeError(`Invalid character ${input[j2]} in base64 string.`);bits2|=alphabetByEncoding2[input[j2]]<<(limit-j2)*bitsPerLetter2;bitLength+=bitsPerLetter2}else bits2>>=bitsPerLetter2;const chunkOffset=i3/4*3;bits2>>=bitLength%bitsPerByte2;const byteLength=Math.floor(bitLength/bitsPerByte2);for(let k2=0;k2<byteLength;k2++){const offset=(byteLength-k2-1)*bitsPerByte2;dataView.setUint8(chunkOffset+k2,(bits2&255<<offset)>>offset)}}return new Uint8Array(out)};UnionSerde=class{constructor(from,to){__publicField(this,"from");__publicField(this,"to");__publicField(this,"keys");this.from=from;this.to=to;this.keys=new Set(Object.keys(this.from).filter(k2=>"__type"!==k2))}mark(key3){this.keys.delete(key3)}hasUnknown(){return 1===this.keys.size&&0===Object.keys(this.to).length}writeUnknown(){if(this.hasUnknown()){const k2=this.keys.values().next().value,v2=this.from[k2];this.to.$unknown=[k2,v2]}}};collectBodyString=(streamBody,context2)=>collectBody(streamBody,context2).then(body=>{var _a13;return(null!=(_a13=null==context2?void 0:context2.utf8Encoder)?_a13:toUtf8)(body)});ATTR_ESCAPE_RE=/[&<>"]/g;ATTR_ESCAPE_MAP={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"};ELEMENT_ESCAPE_RE=/[&"'<>\r\n\u0085\u2028]/g;ELEMENT_ESCAPE_MAP={"&":"&amp;",'"':"&quot;","'":"&apos;","<":"&lt;",">":"&gt;","\r":"&#x0D;","\n":"&#x0A;","…":"&#x85;","\u2028":"&#x2028;"};XmlText=class{constructor(value){__publicField(this,"value");this.value=value}toString(){return escapeElement(""+this.value)}};XmlNode=class _XmlNode{constructor(name,children=[]){__publicField(this,"name");__publicField(this,"children");__publicField(this,"attributes",{});this.name=name;this.children=children}static of(name,childText,withName){const node=new _XmlNode(name);void 0!==childText&&node.addChildNode(new XmlText(childText));void 0!==withName&&node.withName(withName);return node}withName(name){this.name=name;return this}addAttribute(name,value){this.attributes[name]=value;return this}addChildNode(child2){this.children.push(child2);return this}removeAttribute(name){delete this.attributes[name];return this}n(name){this.name=name;return this}c(child2){this.children.push(child2);return this}a(name,value){null!=value&&(this.attributes[name]=value);return this}cc(input,field,withName=field){if(null!=input[field]){const node=_XmlNode.of(field,input[field]).withName(withName);this.c(node)}}l(input,listName,memberName,valueProvider){if(null!=input[listName]){const nodes=valueProvider();nodes.map(node=>{node.withName(memberName);this.c(node)})}}lc(input,listName,memberName,valueProvider){if(null!=input[listName]){const nodes=valueProvider(),containerNode=new _XmlNode(memberName);nodes.map(node=>{containerNode.c(node)});this.c(containerNode)}}toString(){const hasChildren=Boolean(this.children.length);let xmlText=`<${this.name}`;const attributes=this.attributes;for(const attributeName of Object.keys(attributes)){const attribute=attributes[attributeName];null!=attribute&&(xmlText+=` ${attributeName}="${escapeAttribute(""+attribute)}"`)}return xmlText+(hasChildren?`>${this.children.map(c3=>c3.toString()).join("")}</${this.name}>`:"/>")}};XmlShapeDeserializer=class extends SerdeContextConfig{constructor(settings){super();__publicField(this,"settings");__publicField(this,"stringDeserializer");this.settings=settings;this.stringDeserializer=new FromStringShapeDeserializer(settings)}setSerdeContext(serdeContext){this.serdeContext=serdeContext;this.stringDeserializer.setSerdeContext(serdeContext)}read(schema,bytes,key3){var _a13,_b6;const ns=NormalizedSchema.of(schema),memberSchemas=ns.getMemberSchemas(),isEventPayload=ns.isStructSchema()&&ns.isMemberSchema()&&!!Object.values(memberSchemas).find(memberNs=>!!memberNs.getMemberTraits().eventPayload);if(isEventPayload){const output={},memberName=Object.keys(memberSchemas)[0],eventMemberSchema=memberSchemas[memberName];eventMemberSchema.isBlobSchema()?output[memberName]=bytes:output[memberName]=this.read(memberSchemas[memberName],bytes);return output}const xmlString=(null!=(_b6=null==(_a13=this.serdeContext)?void 0:_a13.utf8Encoder)?_b6:toUtf8)(bytes),parsedObject=this.parseXml(xmlString);return this.readSchema(schema,key3?parsedObject[key3]:parsedObject)}readSchema(_schema,value){var _a13,_b6,_c3,_d2,_e2,_f;const ns=NormalizedSchema.of(_schema);if(ns.isUnitSchema())return;const traits=ns.getMergedTraits();if(ns.isListSchema()&&!Array.isArray(value))return this.readSchema(ns,[value]);if(null==value)return value;if("object"==typeof value){const flat=!!traits.xmlFlattened;if(ns.isListSchema()){const listValue=ns.getValueSchema(),buffer2=[],sourceKey=null!=(_a13=listValue.getMergedTraits().xmlName)?_a13:"member",source2=flat?value:(null!=(_b6=value[0])?_b6:value)[sourceKey];if(null==source2)return buffer2;const sourceArray=Array.isArray(source2)?source2:[source2];for(const v2 of sourceArray)buffer2.push(this.readSchema(listValue,v2));return buffer2}const buffer={};if(ns.isMapSchema()){const keyNs=ns.getKeySchema(),memberNs=ns.getValueSchema();let entries2;entries2=flat?Array.isArray(value)?value:[value]:Array.isArray(value.entry)?value.entry:[value.entry];const keyProperty=null!=(_c3=keyNs.getMergedTraits().xmlName)?_c3:"key",valueProperty=null!=(_d2=memberNs.getMergedTraits().xmlName)?_d2:"value";for(const entry of entries2){const key3=entry[keyProperty],value2=entry[valueProperty];buffer[key3]=this.readSchema(memberNs,value2)}return buffer}if(ns.isStructSchema()){const union=ns.isUnionSchema();let unionSerde;union&&(unionSerde=new UnionSerde(value,buffer));for(const[memberName,memberSchema]of ns.structIterator()){const memberTraits=memberSchema.getMergedTraits(),xmlObjectKey=memberTraits.httpPayload?null!=(_f=memberTraits.xmlName)?_f:memberSchema.getName():null!=(_e2=memberSchema.getMemberTraits().xmlName)?_e2:memberName;union&&unionSerde.mark(xmlObjectKey);null!=value[xmlObjectKey]&&(buffer[memberName]=this.readSchema(memberSchema,value[xmlObjectKey]))}union&&unionSerde.writeUnknown();return buffer}if(ns.isDocumentSchema())return value;throw new Error(`@aws-sdk/core/protocols - xml deserializer unhandled schema type for ${ns.getName(!0)}`)}return ns.isListSchema()?[]:ns.isMapSchema()||ns.isStructSchema()?{}:this.stringDeserializer.read(ns,value)}parseXml(xml){if(xml.length){let parsedObj;try{parsedObj=parseXML(xml)}catch(e3){e3&&"object"==typeof e3&&Object.defineProperty(e3,"$responseBodyText",{value:xml});throw e3}const textNodeName="#text",key3=Object.keys(parsedObj)[0],parsedObjToReturn=parsedObj[key3];if(parsedObjToReturn[textNodeName]){parsedObjToReturn[key3]=parsedObjToReturn[textNodeName];delete parsedObjToReturn[textNodeName]}return getValueFromTextNode(parsedObjToReturn)}return{}}};parseXmlBody=(streamBody,context2)=>collectBodyString(streamBody,context2).then(encoded=>{if(encoded.length){let parsedObj;try{parsedObj=parseXML(encoded)}catch(e3){e3&&"object"==typeof e3&&Object.defineProperty(e3,"$responseBodyText",{value:encoded});throw e3}const textNodeName="#text",key3=Object.keys(parsedObj)[0],parsedObjToReturn=parsedObj[key3];if(parsedObjToReturn[textNodeName]){parsedObjToReturn[key3]=parsedObjToReturn[textNodeName];delete parsedObjToReturn[textNodeName]}return getValueFromTextNode(parsedObjToReturn)}return{}});0;loadRestXmlErrorCode=(output,data)=>{var _a13;return void 0!==(null==(_a13=null==data?void 0:data.Error)?void 0:_a13.Code)?data.Error.Code:void 0!==(null==data?void 0:data.Code)?data.Code:404==output.statusCode?"NotFound":void 0};init_index_browser2();XmlShapeSerializer=class extends SerdeContextConfig{constructor(settings){super();__publicField(this,"settings");__publicField(this,"stringBuffer");__publicField(this,"byteBuffer");__publicField(this,"buffer");this.settings=settings}write(schema,value){var _a13,_b6;const ns=NormalizedSchema.of(schema);if(ns.isStringSchema()&&"string"==typeof value)this.stringBuffer=value;else if(ns.isBlobSchema())this.byteBuffer="byteLength"in value?value:(null!=(_b6=null==(_a13=this.serdeContext)?void 0:_a13.base64Decoder)?_b6:fromBase642)(value);else{this.buffer=this.writeStruct(ns,value,void 0);const traits=ns.getMergedTraits();traits.httpPayload&&!traits.xmlName&&this.buffer.withName(ns.getName())}}flush(){var _a13;if(void 0!==this.byteBuffer){const bytes=this.byteBuffer;delete this.byteBuffer;return bytes}if(void 0!==this.stringBuffer){const str=this.stringBuffer;delete this.stringBuffer;return str}const buffer=this.buffer;this.settings.xmlNamespace&&((null==(_a13=null==buffer?void 0:buffer.attributes)?void 0:_a13.xmlns)||buffer.addAttribute("xmlns",this.settings.xmlNamespace));delete this.buffer;return buffer.toString()}writeStruct(ns,value,parentXmlns){var _a13,_b6,_c3,_d2;const traits=ns.getMergedTraits(),name=ns.isMemberSchema()&&!traits.httpPayload?null!=(_a13=ns.getMemberTraits().xmlName)?_a13:ns.getMemberName():null!=(_b6=traits.xmlName)?_b6:ns.getName();if(!name||!ns.isStructSchema())throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write struct with empty name or non-struct, schema=${ns.getName(!0)}.`);const structXmlNode=XmlNode.of(name),[xmlnsAttr,xmlns]=this.getXmlnsAttribute(ns,parentXmlns);for(const[memberName,memberSchema]of ns.structIterator()){const val=value[memberName];if(null!=val||memberSchema.isIdempotencyToken()){if(memberSchema.getMergedTraits().xmlAttribute){structXmlNode.addAttribute(null!=(_c3=memberSchema.getMergedTraits().xmlName)?_c3:memberName,this.writeSimple(memberSchema,val));continue}if(memberSchema.isListSchema())this.writeList(memberSchema,val,structXmlNode,xmlns);else if(memberSchema.isMapSchema())this.writeMap(memberSchema,val,structXmlNode,xmlns);else if(memberSchema.isStructSchema())structXmlNode.addChildNode(this.writeStruct(memberSchema,val,xmlns));else{const memberNode=XmlNode.of(null!=(_d2=memberSchema.getMergedTraits().xmlName)?_d2:memberSchema.getMemberName());this.writeSimpleInto(memberSchema,val,memberNode,xmlns);structXmlNode.addChildNode(memberNode)}}}const{$unknown}=value;if($unknown&&ns.isUnionSchema()&&Array.isArray($unknown)&&1===Object.keys(value).length){const[k2,v2]=$unknown,node=XmlNode.of(k2);if("string"!=typeof v2){if(!(value instanceof XmlNode||value instanceof XmlText))throw new Error("@aws-sdk - $unknown union member in XML requires value of type string, @aws-sdk/xml-builder::XmlNode or XmlText.");structXmlNode.addChildNode(value)}this.writeSimpleInto(0,v2,node,xmlns);structXmlNode.addChildNode(node)}xmlns&&structXmlNode.addAttribute(xmlnsAttr,xmlns);return structXmlNode}writeList(listMember,array,container,parentXmlns){var _a13;if(!listMember.isMemberSchema())throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member list: ${listMember.getName(!0)}`);const listTraits=listMember.getMergedTraits(),listValueSchema=listMember.getValueSchema(),listValueTraits=listValueSchema.getMergedTraits(),sparse=!!listValueTraits.sparse,flat=!!listTraits.xmlFlattened,[xmlnsAttr,xmlns]=this.getXmlnsAttribute(listMember,parentXmlns),writeItem=(container2,value)=>{var _a14,_b6,_c3,_d2;if(listValueSchema.isListSchema())this.writeList(listValueSchema,Array.isArray(value)?value:[value],container2,xmlns);else if(listValueSchema.isMapSchema())this.writeMap(listValueSchema,value,container2,xmlns);else if(listValueSchema.isStructSchema()){const struct=this.writeStruct(listValueSchema,value,xmlns);container2.addChildNode(struct.withName(flat?null!=(_a14=listTraits.xmlName)?_a14:listMember.getMemberName():null!=(_b6=listValueTraits.xmlName)?_b6:"member"))}else{const listItemNode=XmlNode.of(flat?null!=(_c3=listTraits.xmlName)?_c3:listMember.getMemberName():null!=(_d2=listValueTraits.xmlName)?_d2:"member");this.writeSimpleInto(listValueSchema,value,listItemNode,xmlns);container2.addChildNode(listItemNode)}};if(flat)for(const value of array)(sparse||null!=value)&&writeItem(container,value);else{const listNode=XmlNode.of(null!=(_a13=listTraits.xmlName)?_a13:listMember.getMemberName());xmlns&&listNode.addAttribute(xmlnsAttr,xmlns);for(const value of array)(sparse||null!=value)&&writeItem(listNode,value);container.addChildNode(listNode)}}writeMap(mapMember,map4,container,parentXmlns,containerIsMap=!1){var _a13,_b6,_c3,_d2;if(!mapMember.isMemberSchema())throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member map: ${mapMember.getName(!0)}`);const mapTraits=mapMember.getMergedTraits(),mapKeySchema=mapMember.getKeySchema(),mapKeyTraits=mapKeySchema.getMergedTraits(),keyTag=null!=(_a13=mapKeyTraits.xmlName)?_a13:"key",mapValueSchema=mapMember.getValueSchema(),mapValueTraits=mapValueSchema.getMergedTraits(),valueTag=null!=(_b6=mapValueTraits.xmlName)?_b6:"value",sparse=!!mapValueTraits.sparse,flat=!!mapTraits.xmlFlattened,[xmlnsAttr,xmlns]=this.getXmlnsAttribute(mapMember,parentXmlns),addKeyValue=(entry,key3,val)=>{const keyNode=XmlNode.of(keyTag,key3),[keyXmlnsAttr,keyXmlns]=this.getXmlnsAttribute(mapKeySchema,xmlns);keyXmlns&&keyNode.addAttribute(keyXmlnsAttr,keyXmlns);entry.addChildNode(keyNode);let valueNode=XmlNode.of(valueTag);mapValueSchema.isListSchema()?this.writeList(mapValueSchema,val,valueNode,xmlns):mapValueSchema.isMapSchema()?this.writeMap(mapValueSchema,val,valueNode,xmlns,!0):mapValueSchema.isStructSchema()?valueNode=this.writeStruct(mapValueSchema,val,xmlns):this.writeSimpleInto(mapValueSchema,val,valueNode,xmlns);entry.addChildNode(valueNode)};if(flat){for(const[key3,val]of Object.entries(map4))if(sparse||null!=val){const entry=XmlNode.of(null!=(_c3=mapTraits.xmlName)?_c3:mapMember.getMemberName());addKeyValue(entry,key3,val);container.addChildNode(entry)}}else{let mapNode;if(!containerIsMap){mapNode=XmlNode.of(null!=(_d2=mapTraits.xmlName)?_d2:mapMember.getMemberName());xmlns&&mapNode.addAttribute(xmlnsAttr,xmlns);container.addChildNode(mapNode)}for(const[key3,val]of Object.entries(map4))if(sparse||null!=val){const entry=XmlNode.of("entry");addKeyValue(entry,key3,val);(containerIsMap?container:mapNode).addChildNode(entry)}}}writeSimple(_schema,value){var _a13,_b6;if(null===value)throw new Error("@aws-sdk/core/protocols - (XML serializer) cannot write null value.");const ns=NormalizedSchema.of(_schema);let nodeContents=null;if(value&&"object"==typeof value)if(ns.isBlobSchema())nodeContents=(null!=(_b6=null==(_a13=this.serdeContext)?void 0:_a13.base64Encoder)?_b6:toBase642)(value);else{if(!(ns.isTimestampSchema()&&value instanceof Date)){if(ns.isBigDecimalSchema()&&value)return value instanceof NumericValue?value.string:String(value);throw ns.isMapSchema()||ns.isListSchema()?new Error("@aws-sdk/core/protocols - xml serializer, cannot call _write() on List/Map schema, call writeList or writeMap() instead."):new Error(`@aws-sdk/core/protocols - xml serializer, unhandled schema type for object value and schema: ${ns.getName(!0)}`)}{const format2=determineTimestampFormat(ns,this.settings);switch(format2){case 5:nodeContents=value.toISOString().replace(".000Z","Z");break;case 6:nodeContents=dateToUtcString(value);break;case 7:nodeContents=String(value.getTime()/1e3);break;default:console.warn("Missing timestamp format, using http date",value);nodeContents=dateToUtcString(value);break}}}(ns.isBooleanSchema()||ns.isNumericSchema()||ns.isBigIntegerSchema()||ns.isBigDecimalSchema())&&(nodeContents=String(value));ns.isStringSchema()&&(nodeContents=void 0===value&&ns.isIdempotencyToken()?generateIdempotencyToken():String(value));if(null===nodeContents)throw new Error(`Unhandled schema-value pair ${ns.getName(!0)}=${value}`);return nodeContents}writeSimpleInto(_schema,value,into,parentXmlns){const nodeContents=this.writeSimple(_schema,value),ns=NormalizedSchema.of(_schema),content=new XmlText(nodeContents),[xmlnsAttr,xmlns]=this.getXmlnsAttribute(ns,parentXmlns);xmlns&&into.addAttribute(xmlnsAttr,xmlns);into.addChildNode(content)}getXmlnsAttribute(ns,parentXmlns){var _a13;const traits=ns.getMergedTraits(),[prefix,xmlns]=null!=(_a13=traits.xmlNamespace)?_a13:[];return xmlns&&xmlns!==parentXmlns?[prefix?`xmlns:${prefix}`:"xmlns",xmlns]:[void 0,void 0]}};XmlCodec=class extends SerdeContextConfig{constructor(settings){super();__publicField(this,"settings");this.settings=settings}createSerializer(){const serializer=new XmlShapeSerializer(this.settings);serializer.setSerdeContext(this.serdeContext);return serializer}createDeserializer(){const deserializer=new XmlShapeDeserializer(this.settings);deserializer.setSerdeContext(this.serdeContext);return deserializer}};AwsRestXmlProtocol=class extends HttpBindingProtocol{constructor(options){super(options);__publicField(this,"codec");__publicField(this,"serializer");__publicField(this,"deserializer");__publicField(this,"mixin",new ProtocolLib);const settings={timestampFormat:{useTrait:!0,default:5},httpBindings:!0,xmlNamespace:options.xmlNamespace,serviceNamespace:options.defaultNamespace};this.codec=new XmlCodec(settings);this.serializer=new HttpInterceptingShapeSerializer(this.codec.createSerializer(),settings);this.deserializer=new HttpInterceptingShapeDeserializer(this.codec.createDeserializer(),settings);this.compositeErrorRegistry}getPayloadCodec(){return this.codec}getShapeId(){return"aws.protocols#restXml"}async serializeRequest(operationSchema,input,context2){const request2=await super.serializeRequest(operationSchema,input,context2),inputSchema=NormalizedSchema.of(operationSchema.input);if(!request2.headers["content-type"]){const contentType=this.mixin.resolveRestContentType(this.getDefaultContentType(),inputSchema);contentType&&(request2.headers["content-type"]=contentType)}"string"!=typeof request2.body||request2.headers["content-type"]!==this.getDefaultContentType()||request2.body.startsWith("<?xml ")||this.hasUnstructuredPayloadBinding(inputSchema)||(request2.body='<?xml version="1.0" encoding="UTF-8"?>'+request2.body);return request2}async deserializeResponse(operationSchema,context2,response){return super.deserializeResponse(operationSchema,context2,response)}async handleError(operationSchema,context2,response,dataObject,metadata){var _a13,_b6,_c3,_d2,_e2,_f,_g,_h2,_i2,_j,_k;const errorIdentifier=null!=(_a13=loadRestXmlErrorCode(response,dataObject))?_a13:"Unknown";this.mixin.compose(this.compositeErrorRegistry,errorIdentifier,this.options.defaultNamespace);if(dataObject.Error&&"object"==typeof dataObject.Error)for(const key3 of Object.keys(dataObject.Error)){dataObject[key3]=dataObject.Error[key3];"message"===key3.toLowerCase()&&(dataObject.message=dataObject.Error[key3])}dataObject.RequestId&&!metadata.requestId&&(metadata.requestId=dataObject.RequestId);const{errorSchema,errorMetadata}=await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier,this.options.defaultNamespace,response,dataObject,metadata),ns=NormalizedSchema.of(errorSchema),message=null!=(_g=null!=(_f=null!=(_e2=null!=(_d2=null==(_b6=dataObject.Error)?void 0:_b6.message)?_d2:null==(_c3=dataObject.Error)?void 0:_c3.Message)?_e2:dataObject.message)?_f:dataObject.Message)?_g:"UnknownError",ErrorCtor=null!=(_h2=this.compositeErrorRegistry.getErrorCtor(errorSchema))?_h2:Error,exception=new ErrorCtor(message);await this.deserializeHttpMessage(errorSchema,context2,response,dataObject);const output={};for(const[name,member2]of ns.structIterator()){const target=null!=(_i2=member2.getMergedTraits().xmlName)?_i2:name,value=null!=(_k=null==(_j=dataObject.Error)?void 0:_j[target])?_k:dataObject[target];output[name]=this.codec.createDeserializer().readSchema(member2,value)}throw this.mixin.decorateServiceException(Object.assign(exception,errorMetadata,{$fault:ns.getMergedTraits().error,message},output),dataObject)}getDefaultContentType(){return"application/xml"}hasUnstructuredPayloadBinding(ns){for(const[,member2]of ns.structIterator())if(member2.getMergedTraits().httpPayload)return!(member2.isStructSchema()||member2.isMapSchema()||member2.isListSchema());return!1}};ReadableStreamRef="function"==typeof ReadableStream?ReadableStream:function(){};ChecksumStream2=class extends ReadableStreamRef{};isReadableStream3=stream=>{var _a13;return"function"==typeof ReadableStream&&((null==(_a13=null==stream?void 0:stream.constructor)?void 0:_a13.name)===ReadableStream.name||stream instanceof ReadableStream)};0;createChecksumStream2=({expectedChecksum,checksum,source:source2,checksumSourceLocation,base64Encoder})=>{var _a13,_b6;if(!isReadableStream3(source2))throw new Error(`@smithy/util-stream: unsupported source type ${null!=(_b6=null==(_a13=null==source2?void 0:source2.constructor)?void 0:_a13.name)?_b6:source2} in ChecksumStream.`);const encoder3=null!=base64Encoder?base64Encoder:toBase642;if("function"!=typeof TransformStream)throw new Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream.");const transform2=new TransformStream({start(){},async transform(chunk,controller){checksum.update(chunk);controller.enqueue(chunk)},async flush(controller){const digest=await checksum.digest(),received=encoder3(digest);if(expectedChecksum!==received){const error=new Error(`Checksum mismatch: expected "${expectedChecksum}" but received "${received}" in response header "${checksumSourceLocation}".`);controller.error(error)}else controller.terminate()}});source2.pipeThrough(transform2);const readable2=transform2.readable;Object.setPrototypeOf(readable2,ChecksumStream2.prototype);return readable2};ByteArrayCollector=class{constructor(allocByteArray){__publicField(this,"allocByteArray");__publicField(this,"byteLength",0);__publicField(this,"byteArrays",[]);this.allocByteArray=allocByteArray}push(byteArray){this.byteArrays.push(byteArray);this.byteLength+=byteArray.byteLength}flush(){if(1===this.byteArrays.length){const bytes=this.byteArrays[0];this.reset();return bytes}const aggregation=this.allocByteArray(this.byteLength);let cursor=0;for(let i3=0;i3<this.byteArrays.length;++i3){const bytes=this.byteArrays[i3];aggregation.set(bytes,cursor);cursor+=bytes.byteLength}this.reset();return aggregation}reset(){this.byteArrays=[];this.byteLength=0}};createBufferedReadable2=function createBufferedReadableStream(upstream,size,logger2){const reader=upstream.getReader();let streamBufferingLoggedWarning=!1,bytesSeen=0;const buffers=["",new ByteArrayCollector(size2=>new Uint8Array(size2))];let mode=-1;const pull=async controller=>{const{value,done}=await reader.read(),chunk=value;if(done){if(-1!==mode){const remainder=flush(buffers,mode);sizeOf(remainder)>0&&controller.enqueue(remainder)}controller.close()}else{const chunkMode=modeOf(chunk,!1);if(mode!==chunkMode){mode>=0&&controller.enqueue(flush(buffers,mode));mode=chunkMode}if(-1===mode){controller.enqueue(chunk);return}const chunkSize2=sizeOf(chunk);bytesSeen+=chunkSize2;const bufferSize=sizeOf(buffers[mode]);if(chunkSize2>=size&&0===bufferSize)controller.enqueue(chunk);else{const newSize=merge(buffers,mode,chunk);if(!streamBufferingLoggedWarning&&bytesSeen>2*size){streamBufferingLoggedWarning=!0;null==logger2||logger2.warn(`@smithy/util-stream - stream chunk size ${chunkSize2} is below threshold of ${size}, automatically buffering.`)}newSize>=size?controller.enqueue(flush(buffers,mode)):await pull(controller)}}};return new ReadableStream({pull})};getAwsChunkedEncodingStream2=(readableStream,options)=>{const{base64Encoder,bodyLengthChecker,checksumAlgorithmFn,checksumLocationName,streamHasher}=options,checksumRequired=void 0!==base64Encoder&&void 0!==bodyLengthChecker&&void 0!==checksumAlgorithmFn&&void 0!==checksumLocationName&&void 0!==streamHasher,digest=checksumRequired?streamHasher(checksumAlgorithmFn,readableStream):void 0,reader=readableStream.getReader();return new ReadableStream({async pull(controller){const{value,done}=await reader.read();if(done){controller.enqueue("0\r\n");if(checksumRequired){const checksum=base64Encoder(await digest);controller.enqueue(`${checksumLocationName}:${checksum}\r\n`);controller.enqueue("\r\n")}controller.close()}else controller.enqueue(`${(bodyLengthChecker(value)||0).toString(16)}\r\n${value}\r\n`)}})};keepAliveSupport={supported:void 0};FetchHttpHandler=class _FetchHttpHandler{constructor(options){__publicField(this,"config");__publicField(this,"configProvider");if("function"==typeof options)this.configProvider=options().then(opts=>opts||{});else{this.config=null!=options?options:{};this.configProvider=Promise.resolve(this.config)}void 0===keepAliveSupport.supported&&(keepAliveSupport.supported=Boolean("undefined"!=typeof Request&&"keepalive"in createRequest("https://[::1]")))}static create(instanceOrOptions){return"function"==typeof(null==instanceOrOptions?void 0:instanceOrOptions.handle)?instanceOrOptions:new _FetchHttpHandler(instanceOrOptions)}destroy(){}async handle(request2,{abortSignal,requestTimeout:requestTimeout3}={}){var _a13,_b6,_c3;this.config||(this.config=await this.configProvider);const requestTimeoutInMs=null!=requestTimeout3?requestTimeout3:this.config.requestTimeout,keepAlive=!0===this.config.keepAlive,credentials=this.config.credentials;if(null==abortSignal?void 0:abortSignal.aborted){const abortError=buildAbortError(abortSignal);return Promise.reject(abortError)}let path2=request2.path;const queryString=buildQueryString2(request2.query||{});queryString&&(path2+=`?${queryString}`);request2.fragment&&(path2+=`#${request2.fragment}`);let auth="";if(null!=request2.username||null!=request2.password){const username=null!=(_a13=request2.username)?_a13:"",password=null!=(_b6=request2.password)?_b6:"";auth=`${username}:${password}@`}const{port,method}=request2,url=`${request2.protocol}//${auth}${request2.hostname}${port?`:${port}`:""}${path2}`,body="GET"===method||"HEAD"===method?void 0:request2.body,requestOptions={body,headers:new Headers(request2.headers),method,credentials};(null==(_c3=this.config)?void 0:_c3.cache)&&(requestOptions.cache=this.config.cache);body&&(requestOptions.duplex="half");"undefined"!=typeof AbortController&&(requestOptions.signal=abortSignal);keepAliveSupport.supported&&(requestOptions.keepalive=keepAlive);"function"==typeof this.config.requestInit&&Object.assign(requestOptions,this.config.requestInit(request2));let removeSignalEventListener=()=>{};const fetchRequest=createRequest(url,requestOptions),raceOfPromises=[fetch(fetchRequest).then(response=>{const fetchHeaders=response.headers,transformedHeaders={};for(const pair of fetchHeaders.entries())transformedHeaders[pair[0]]=pair[1];const hasReadableStream=null!=response.body;return hasReadableStream?{response:new HttpResponse({headers:transformedHeaders,reason:response.statusText,statusCode:response.status,body:response.body})}:response.blob().then(body2=>({response:new HttpResponse({headers:transformedHeaders,reason:response.statusText,statusCode:response.status,body:body2})}))}),requestTimeout(requestTimeoutInMs)];abortSignal&&raceOfPromises.push(new Promise((resolve,reject)=>{const onAbort=()=>{const abortError=buildAbortError(abortSignal);reject(abortError)};if("function"==typeof abortSignal.addEventListener){const signal=abortSignal;signal.addEventListener("abort",onAbort,{once:!0});removeSignalEventListener=()=>signal.removeEventListener("abort",onAbort)}else abortSignal.onabort=onAbort}));return Promise.race(raceOfPromises).finally(removeSignalEventListener)}updateHttpClientConfig(key3,value){this.config=void 0;this.configProvider=this.configProvider.then(config=>{config[key3]=value;return config})}httpHandlerConfigs(){var _a13;return null!=(_a13=this.config)?_a13:{}}};streamCollector2=async stream=>{var _a13;return"function"==typeof Blob&&stream instanceof Blob||"Blob"===(null==(_a13=stream.constructor)?void 0:_a13.name)?void 0!==Blob.prototype.arrayBuffer?new Uint8Array(await stream.arrayBuffer()):collectBlob2(stream):collectStream2(stream)};ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED2="The stream has already been transformed.";sdkStreamMixin2=stream=>{var _a13,_b6;if(!isBlobInstance2(stream)&&!isReadableStream3(stream)){const name=(null==(_b6=null==(_a13=null==stream?void 0:stream.__proto__)?void 0:_a13.constructor)?void 0:_b6.name)||stream;throw new Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${name}`)}let transformed=!1;const transformToByteArray=async()=>{if(transformed)throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED2);transformed=!0;return await streamCollector2(stream)},blobToWebStream=blob=>{if("function"!=typeof blob.stream)throw new Error("Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.\nIf you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body");return blob.stream()};return Object.assign(stream,{transformToByteArray,transformToString:async encoding=>{const buf=await transformToByteArray();if("base64"===encoding)return toBase642(buf);if("hex"===encoding)return toHex3(buf);if(void 0===encoding||"utf8"===encoding||"utf-8"===encoding)return toUtf8(buf);if("function"==typeof TextDecoder)return new TextDecoder(encoding).decode(buf);throw new Error("TextDecoder is not available, please make sure polyfill is provided.")},transformToWebStream:()=>{if(transformed)throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED2);transformed=!0;if(isBlobInstance2(stream))return blobToWebStream(stream);if(isReadableStream3(stream))return stream;throw new Error(`Cannot transform payload to web stream, got ${stream}`)}})};isBlobInstance2=stream=>"function"==typeof Blob&&stream instanceof Blob;getChecksumAlgorithmForRequest=(input,{requestChecksumRequired,requestAlgorithmMember,requestChecksumCalculation})=>{if(!requestAlgorithmMember)return requestChecksumCalculation===RequestChecksumCalculation_WHEN_SUPPORTED||requestChecksumRequired?DEFAULT_CHECKSUM_ALGORITHM:void 0;if(!input[requestAlgorithmMember])return;const checksumAlgorithm=input[requestAlgorithmMember];return checksumAlgorithm};getChecksumLocationName=algorithm=>algorithm===ChecksumAlgorithm.MD5?"content-md5":`x-amz-checksum-${algorithm.toLowerCase()}`;hasHeader2=(header,headers)=>{const soughtHeader=header.toLowerCase();for(const headerName of Object.keys(headers))if(soughtHeader===headerName.toLowerCase())return!0;return!1};hasHeaderWithPrefix=(headerPrefix,headers)=>{const soughtHeaderPrefix=headerPrefix.toLowerCase();for(const headerName of Object.keys(headers))if(headerName.toLowerCase().startsWith(soughtHeaderPrefix))return!0;return!1};isStreaming=body=>void 0!==body&&"string"!=typeof body&&!ArrayBuffer.isView(body)&&!isArrayBuffer(body);init_tslib_es6();init_module();AwsCrc32c=function(){function AwsCrc32c2(){this.crc32c=new Crc32c}AwsCrc32c2.prototype.update=function(toHash){isEmptyData(toHash)||this.crc32c.update(convertToBuffer(toHash))};AwsCrc32c2.prototype.digest=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a13){return[2,numToUint8(this.crc32c.digest())]})})};AwsCrc32c2.prototype.reset=function(){this.crc32c=new Crc32c};return AwsCrc32c2}();init_tslib_es6();init_module();Crc32c=function(){function Crc32c2(){this.checksum=4294967295}Crc32c2.prototype.update=function(data){var e_1,_a13,data_1,data_1_1,byte;try{for(data_1=__values(data),data_1_1=data_1.next();!data_1_1.done;data_1_1=data_1.next()){byte=data_1_1.value;this.checksum=this.checksum>>>8^lookupTable2[255&(this.checksum^byte)]}}catch(e_1_1){e_1={error:e_1_1}}finally{try{data_1_1&&!data_1_1.done&&(_a13=data_1.return)&&_a13.call(data_1)}finally{if(e_1)throw e_1.error}}return this};Crc32c2.prototype.digest=function(){return(4294967295^this.checksum)>>>0};return Crc32c2}();a_lookupTable=[0,4067132163,3778769143,324072436,3348797215,904991772,648144872,3570033899,2329499855,2024987596,1809983544,2575936315,1296289744,3207089363,2893594407,1578318884,274646895,3795141740,4049975192,51262619,3619967088,632279923,922689671,3298075524,2592579488,1760304291,2075979607,2312596564,1562183871,2943781820,3156637768,1313733451,549293790,3537243613,3246849577,871202090,3878099393,357341890,102525238,4101499445,2858735121,1477399826,1264559846,3107202533,1845379342,2677391885,2361733625,2125378298,820201905,3263744690,3520608582,598981189,4151959214,85089709,373468761,3827903834,3124367742,1213305469,1526817161,2842354314,2107672161,2412447074,2627466902,1861252501,1098587580,3004210879,2688576843,1378610760,2262928035,1955203488,1742404180,2511436119,3416409459,969524848,714683780,3639785095,205050476,4266873199,3976438427,526918040,1361435347,2739821008,2954799652,1114974503,2529119692,1691668175,2005155131,2247081528,3690758684,697762079,986182379,3366744552,476452099,3993867776,4250756596,255256311,1640403810,2477592673,2164122517,1922457750,2791048317,1412925310,1197962378,3037525897,3944729517,427051182,170179418,4165941337,746937522,3740196785,3451792453,1070968646,1905808397,2213795598,2426610938,1657317369,3053634322,1147748369,1463399397,2773627110,4215344322,153784257,444234805,3893493558,1021025245,3467647198,3722505002,797665321,2197175160,1889384571,1674398607,2443626636,1164749927,3070701412,2757221520,1446797203,137323447,4198817972,3910406976,461344835,3484808360,1037989803,781091935,3705997148,2460548119,1623424788,1939049696,2180517859,1429367560,2807687179,3020495871,1180866812,410100952,3927582683,4182430767,186734380,3756733383,763408580,1053836080,3434856499,2722870694,1344288421,1131464017,2971354706,1708204729,2545590714,2229949006,1988219213,680717673,3673779818,3383336350,1002577565,4010310262,493091189,238226049,4233660802,2987750089,1082061258,1395524158,2705686845,1972364758,2279892693,2494862625,1725896226,952904198,3399985413,3656866545,731699698,4283874585,222117402,510512622,3959836397,3280807620,837199303,582374963,3504198960,68661723,4135334616,3844915500,390545967,1230274059,3141532936,2825850620,1510247935,2395924756,2091215383,1878366691,2644384480,3553878443,565732008,854102364,3229815391,340358836,3861050807,4117890627,119113024,1493875044,2875275879,3090270611,1247431312,2660249211,1828433272,2141937292,2378227087,3811616794,291187481,34330861,4032846830,615137029,3603020806,3314634738,939183345,1776939221,2609017814,2295496738,2058945313,2926798794,1545135305,1330124605,3173225534,4084100981,17165430,307568514,3762199681,888469610,3332340585,3587147933,665062302,2042050490,2346497209,2559330125,1793573966,3190661285,1279665062,1595330642,2910671697];lookupTable2=uint32ArrayFrom(a_lookupTable);generateCRC64NVMETable=()=>{const tables=new Array(8);for(let slice=0;slice<8;slice++){const table3=new Array(512);for(let i3=0;i3<256;i3++){let crc2=BigInt(i3);for(let j2=0;j2<8*(slice+1);j2++)crc2&BigInt("1")?crc2=crc2>>BigInt("1")^BigInt("0x9a6c9329ac4bc9b5"):crc2>>=BigInt("1");table3[2*i3]=Number(crc2>>BigInt("32")&BigInt("0xffffffff"));table3[2*i3+1]=Number(crc2&BigInt("0xffffffff"))}tables[slice]=new Uint32Array(table3)}return tables};ensureTablesInitialized=()=>{if(!CRC64_NVME_REVERSED_TABLE){CRC64_NVME_REVERSED_TABLE=generateCRC64NVMETable();[t0,t1,t2,t3,t4,t5,t6,t7]=CRC64_NVME_REVERSED_TABLE}};Crc64Nvme=class{constructor(){__publicField(this,"c1",0);__publicField(this,"c2",0);ensureTablesInitialized();this.reset()}update(data){const len=data.length;let i3=0,crc1=this.c1,crc2=this.c2;for(;i3+8<=len;){const idx0=(255&(crc2^data[i3++]))<<1,idx1=(255&(crc2>>>8^data[i3++]))<<1,idx2=(255&(crc2>>>16^data[i3++]))<<1,idx3=(255&(crc2>>>24^data[i3++]))<<1,idx4=(255&(crc1^data[i3++]))<<1,idx5=(255&(crc1>>>8^data[i3++]))<<1,idx6=(255&(crc1>>>16^data[i3++]))<<1,idx7=(255&(crc1>>>24^data[i3++]))<<1;crc1=t7[idx0]^t6[idx1]^t5[idx2]^t4[idx3]^t3[idx4]^t2[idx5]^t1[idx6]^t0[idx7];crc2=t7[idx0+1]^t6[idx1+1]^t5[idx2+1]^t4[idx3+1]^t3[idx4+1]^t2[idx5+1]^t1[idx6+1]^t0[idx7+1]}for(;i3<len;){const idx2=(255&(crc2^data[i3]))<<1;crc2=(crc2>>>8|(255&crc1)<<24)>>>0;crc1=crc1>>>8^t0[idx2];crc2^=t0[idx2+1];i3++}this.c1=crc1;this.c2=crc2}async digest(){const c12=4294967295^this.c1,c22=4294967295^this.c2;return new Uint8Array([c12>>>24,c12>>>16&255,c12>>>8&255,255&c12,c22>>>24,c22>>>16&255,c22>>>8&255,255&c22])}reset(){this.c1=4294967295;this.c2=4294967295}};crc64NvmeCrtContainer_CrtCrc64Nvme=null;init_module2();getCrc32ChecksumAlgorithmFunction=()=>AwsCrc32;CLIENT_SUPPORTED_ALGORITHMS=[ChecksumAlgorithm.CRC32,ChecksumAlgorithm.CRC32C,ChecksumAlgorithm.CRC64NVME,ChecksumAlgorithm.SHA1,ChecksumAlgorithm.SHA256];PRIORITY_ORDER_ALGORITHMS=[ChecksumAlgorithm.SHA256,ChecksumAlgorithm.SHA1,ChecksumAlgorithm.CRC32,ChecksumAlgorithm.CRC32C,ChecksumAlgorithm.CRC64NVME];selectChecksumAlgorithmFunction=(checksumAlgorithm,config)=>{var _a13,_b6,_c3,_d2,_e2,_f,_g;const{checksumAlgorithms={}}=config;switch(checksumAlgorithm){case ChecksumAlgorithm.MD5:return null!=(_a13=null==checksumAlgorithms?void 0:checksumAlgorithms.MD5)?_a13:config.md5;case ChecksumAlgorithm.CRC32:return null!=(_b6=null==checksumAlgorithms?void 0:checksumAlgorithms.CRC32)?_b6:getCrc32ChecksumAlgorithmFunction();case ChecksumAlgorithm.CRC32C:return null!=(_c3=null==checksumAlgorithms?void 0:checksumAlgorithms.CRC32C)?_c3:AwsCrc32c;case ChecksumAlgorithm.CRC64NVME:return"function"!=typeof crc64NvmeCrtContainer_CrtCrc64Nvme?null!=(_d2=null==checksumAlgorithms?void 0:checksumAlgorithms.CRC64NVME)?_d2:Crc64Nvme:null!=(_e2=null==checksumAlgorithms?void 0:checksumAlgorithms.CRC64NVME)?_e2:crc64NvmeCrtContainer_CrtCrc64Nvme;case ChecksumAlgorithm.SHA1:return null!=(_f=null==checksumAlgorithms?void 0:checksumAlgorithms.SHA1)?_f:config.sha1;case ChecksumAlgorithm.SHA256:return null!=(_g=null==checksumAlgorithms?void 0:checksumAlgorithms.SHA256)?_g:config.sha256;default:if(null==checksumAlgorithms?void 0:checksumAlgorithms[checksumAlgorithm])return checksumAlgorithms[checksumAlgorithm];throw new Error(`The checksum algorithm "${checksumAlgorithm}" is not supported by the client. Select one of ${CLIENT_SUPPORTED_ALGORITHMS}, or provide an implementation to the client constructor checksums field.`)}};stringHasher=(checksumAlgorithmFn,body)=>{const hash3=new checksumAlgorithmFn;hash3.update(toUint8Array(body||""));return hash3.digest()};flexibleChecksumsMiddlewareOptions={name:"flexibleChecksumsMiddleware",step:"build",tags:["BODY_CHECKSUM"],override:!0};flexibleChecksumsMiddleware=(config,middlewareConfig)=>(next2,context2)=>async args=>{if(!HttpRequest.isInstance(args.request))return next2(args);if(hasHeaderWithPrefix("x-amz-checksum-",args.request.headers))return next2(args);const{request:request2,input}=args,{body:requestBody,headers}=request2,{base64Encoder,streamHasher}=config,{requestChecksumRequired,requestAlgorithmMember}=middlewareConfig,requestChecksumCalculation=await config.requestChecksumCalculation(),requestAlgorithmMemberName=null==requestAlgorithmMember?void 0:requestAlgorithmMember.name,requestAlgorithmMemberHttpHeader=null==requestAlgorithmMember?void 0:requestAlgorithmMember.httpHeader;if(requestAlgorithmMemberName&&!input[requestAlgorithmMemberName]&&(requestChecksumCalculation===RequestChecksumCalculation_WHEN_SUPPORTED||requestChecksumRequired)){input[requestAlgorithmMemberName]=DEFAULT_CHECKSUM_ALGORITHM;requestAlgorithmMemberHttpHeader&&(headers[requestAlgorithmMemberHttpHeader]=DEFAULT_CHECKSUM_ALGORITHM)}const checksumAlgorithm=getChecksumAlgorithmForRequest(input,{requestChecksumRequired,requestAlgorithmMember:null==requestAlgorithmMember?void 0:requestAlgorithmMember.name,requestChecksumCalculation});let updatedBody=requestBody,updatedHeaders=headers;if(checksumAlgorithm){switch(checksumAlgorithm){case ChecksumAlgorithm.CRC32:setFeature(context2,"FLEXIBLE_CHECKSUMS_REQ_CRC32","U");break;case ChecksumAlgorithm.CRC32C:setFeature(context2,"FLEXIBLE_CHECKSUMS_REQ_CRC32C","V");break;case ChecksumAlgorithm.CRC64NVME:setFeature(context2,"FLEXIBLE_CHECKSUMS_REQ_CRC64","W");break;case ChecksumAlgorithm.SHA1:setFeature(context2,"FLEXIBLE_CHECKSUMS_REQ_SHA1","X");break;case ChecksumAlgorithm.SHA256:setFeature(context2,"FLEXIBLE_CHECKSUMS_REQ_SHA256","Y");break}const checksumLocationName=getChecksumLocationName(checksumAlgorithm),checksumAlgorithmFn=selectChecksumAlgorithmFunction(checksumAlgorithm,config);if(isStreaming(requestBody)){const{getAwsChunkedEncodingStream:getAwsChunkedEncodingStream3,bodyLengthChecker}=config;updatedBody=getAwsChunkedEncodingStream3("number"==typeof config.requestStreamBufferSize&&config.requestStreamBufferSize>=8192?createBufferedReadable2(requestBody,config.requestStreamBufferSize,context2.logger):requestBody,{base64Encoder,bodyLengthChecker,checksumLocationName,checksumAlgorithmFn,streamHasher});updatedHeaders={...headers,"content-encoding":headers["content-encoding"]?`${headers["content-encoding"]},aws-chunked`:"aws-chunked","transfer-encoding":"chunked","x-amz-decoded-content-length":headers["content-length"],"x-amz-content-sha256":"STREAMING-UNSIGNED-PAYLOAD-TRAILER","x-amz-trailer":checksumLocationName};delete updatedHeaders["content-length"]}else if(!hasHeader2(checksumLocationName,headers)){const rawChecksum=await stringHasher(checksumAlgorithmFn,requestBody);updatedHeaders={...headers,[checksumLocationName]:base64Encoder(rawChecksum)}}}try{const result=await next2({...args,request:{...request2,headers:updatedHeaders,body:updatedBody}});return result}catch(e3){if(e3 instanceof Error&&"InvalidChunkSizeError"===e3.name)try{e3.message.endsWith(".")||(e3.message+=".");e3.message+=" Set [requestStreamBufferSize=number e.g. 65_536] in client constructor to instruct AWS SDK to buffer your input stream."}catch(ignored){}throw e3}};flexibleChecksumsInputMiddlewareOptions={name:"flexibleChecksumsInputMiddleware",toMiddleware:"serializerMiddleware",relation:"before",tags:["BODY_CHECKSUM"],override:!0};flexibleChecksumsInputMiddleware=(config,middlewareConfig)=>(next2,context2)=>async args=>{const input=args.input,{requestValidationModeMember}=middlewareConfig,requestChecksumCalculation=await config.requestChecksumCalculation(),responseChecksumValidation=await config.responseChecksumValidation();switch(requestChecksumCalculation){case RequestChecksumCalculation_WHEN_REQUIRED:setFeature(context2,"FLEXIBLE_CHECKSUMS_REQ_WHEN_REQUIRED","a");break;case RequestChecksumCalculation_WHEN_SUPPORTED:setFeature(context2,"FLEXIBLE_CHECKSUMS_REQ_WHEN_SUPPORTED","Z");break}switch(responseChecksumValidation){case ResponseChecksumValidation_WHEN_REQUIRED:setFeature(context2,"FLEXIBLE_CHECKSUMS_RES_WHEN_REQUIRED","c");break;case ResponseChecksumValidation_WHEN_SUPPORTED:setFeature(context2,"FLEXIBLE_CHECKSUMS_RES_WHEN_SUPPORTED","b");break}requestValidationModeMember&&!input[requestValidationModeMember]&&responseChecksumValidation===ResponseChecksumValidation_WHEN_SUPPORTED&&(input[requestValidationModeMember]="ENABLED");return next2(args)};getChecksumAlgorithmListForResponse=(responseAlgorithms=[])=>{const validChecksumAlgorithms=[];let i3=PRIORITY_ORDER_ALGORITHMS.length;for(const algorithm of responseAlgorithms){const priority=PRIORITY_ORDER_ALGORITHMS.indexOf(algorithm);-1!==priority?validChecksumAlgorithms[priority]=algorithm:validChecksumAlgorithms[i3++]=algorithm}return validChecksumAlgorithms.filter(Boolean)};isChecksumWithPartNumber=checksum=>{const lastHyphenIndex=checksum.lastIndexOf("-");if(-1!==lastHyphenIndex){const numberPart=checksum.slice(lastHyphenIndex+1);if(!numberPart.startsWith("0")){const number=parseInt(numberPart,10);if(!isNaN(number)&&number>=1&&number<=1e4)return!0}}return!1};getChecksum=async(body,{checksumAlgorithmFn,base64Encoder})=>base64Encoder(await stringHasher(checksumAlgorithmFn,body));validateChecksumFromResponse=async(response,{config,responseAlgorithms,logger:logger2})=>{const checksumAlgorithms=getChecksumAlgorithmListForResponse(responseAlgorithms),{body:responseBody,headers:responseHeaders}=response;for(const algorithm of checksumAlgorithms){const responseHeader=getChecksumLocationName(algorithm),checksumFromResponse=responseHeaders[responseHeader];if(checksumFromResponse){let checksumAlgorithmFn;try{checksumAlgorithmFn=selectChecksumAlgorithmFunction(algorithm,config)}catch(error){if(algorithm===ChecksumAlgorithm.CRC64NVME){null==logger2||logger2.warn(`Skipping ${ChecksumAlgorithm.CRC64NVME} checksum validation: ${error.message}`);continue}throw error}const{base64Encoder}=config;if(isStreaming(responseBody)){response.body=createChecksumStream2({expectedChecksum:checksumFromResponse,checksumSourceLocation:responseHeader,checksum:new checksumAlgorithmFn,source:responseBody,base64Encoder});return}const checksum=await getChecksum(responseBody,{checksumAlgorithmFn,base64Encoder});if(checksum===checksumFromResponse)break;throw new Error(`Checksum mismatch: expected "${checksum}" but received "${checksumFromResponse}" in response header "${responseHeader}".`)}}};flexibleChecksumsResponseMiddlewareOptions={name:"flexibleChecksumsResponseMiddleware",toMiddleware:"deserializerMiddleware",relation:"after",tags:["BODY_CHECKSUM"],override:!0};flexibleChecksumsResponseMiddleware=(config,middlewareConfig)=>(next2,context2)=>async args=>{var _a13;if(!HttpRequest.isInstance(args.request))return next2(args);const input=args.input,result=await next2(args),response=result.response,{requestValidationModeMember,responseAlgorithms}=middlewareConfig;if(requestValidationModeMember&&"ENABLED"===input[requestValidationModeMember]){const{clientName,commandName}=context2,customChecksumAlgorithms=Object.keys(null!=(_a13=config.checksumAlgorithms)?_a13:{}).filter(algorithm=>{const responseHeader=getChecksumLocationName(algorithm);return void 0!==response.headers[responseHeader]}),algoList=getChecksumAlgorithmListForResponse([...null!=responseAlgorithms?responseAlgorithms:[],...customChecksumAlgorithms]),isS3WholeObjectMultipartGetResponseChecksum="S3Client"===clientName&&"GetObjectCommand"===commandName&&algoList.every(algorithm=>{const responseHeader=getChecksumLocationName(algorithm),checksumFromResponse=response.headers[responseHeader];return!checksumFromResponse||isChecksumWithPartNumber(checksumFromResponse)});if(isS3WholeObjectMultipartGetResponseChecksum)return result;await validateChecksumFromResponse(response,{config,responseAlgorithms:algoList,logger:context2.logger})}return result};getFlexibleChecksumsPlugin=(config,middlewareConfig)=>({applyToStack:clientStack=>{clientStack.add(flexibleChecksumsMiddleware(config,middlewareConfig),flexibleChecksumsMiddlewareOptions);clientStack.addRelativeTo(flexibleChecksumsInputMiddleware(config,middlewareConfig),flexibleChecksumsInputMiddlewareOptions);clientStack.addRelativeTo(flexibleChecksumsResponseMiddleware(config,middlewareConfig),flexibleChecksumsResponseMiddlewareOptions)}});resolveFlexibleChecksumsConfig=input=>{var _a13;const{requestChecksumCalculation,responseChecksumValidation,requestStreamBufferSize}=input;return Object.assign(input,{requestChecksumCalculation:normalizeProvider3(null!=requestChecksumCalculation?requestChecksumCalculation:DEFAULT_REQUEST_CHECKSUM_CALCULATION),responseChecksumValidation:normalizeProvider3(null!=responseChecksumValidation?responseChecksumValidation:DEFAULT_RESPONSE_CHECKSUM_VALIDATION),requestStreamBufferSize:Number(null!=requestStreamBufferSize?requestStreamBufferSize:0),checksumAlgorithms:null!=(_a13=input.checksumAlgorithms)?_a13:{}})};hostHeaderMiddleware=options=>next2=>async args=>{if(!HttpRequest.isInstance(args.request))return next2(args);const{request:request2}=args,{handlerProtocol=""}=options.requestHandler.metadata||{};if(handlerProtocol.indexOf("h2")>=0&&!request2.headers[":authority"]){delete request2.headers.host;request2.headers[":authority"]=request2.hostname+(request2.port?":"+request2.port:"")}else if(!request2.headers.host){let host=request2.hostname;null!=request2.port&&(host+=`:${request2.port}`);request2.headers.host=host}return next2(args)};hostHeaderMiddlewareOptions={name:"hostHeaderMiddleware",step:"build",priority:"low",tags:["HOST"],override:!0};getHostHeaderPlugin=options=>({applyToStack:clientStack=>{clientStack.add(hostHeaderMiddleware(options),hostHeaderMiddlewareOptions)}});loggerMiddleware=()=>(next2,context2)=>async args=>{var _a13,_b6;try{const response=await next2(args),{clientName,commandName,logger:logger2,dynamoDbDocumentClientOptions={}}=context2,{overrideInputFilterSensitiveLog,overrideOutputFilterSensitiveLog}=dynamoDbDocumentClientOptions,inputFilterSensitiveLog=null!=overrideInputFilterSensitiveLog?overrideInputFilterSensitiveLog:context2.inputFilterSensitiveLog,outputFilterSensitiveLog=null!=overrideOutputFilterSensitiveLog?overrideOutputFilterSensitiveLog:context2.outputFilterSensitiveLog,{$metadata,...outputWithoutMetadata}=response.output;null==(_a13=null==logger2?void 0:logger2.info)||_a13.call(logger2,{clientName,commandName,input:inputFilterSensitiveLog(args.input),output:outputFilterSensitiveLog(outputWithoutMetadata),metadata:$metadata});return response}catch(error){const{clientName,commandName,logger:logger2,dynamoDbDocumentClientOptions={}}=context2,{overrideInputFilterSensitiveLog}=dynamoDbDocumentClientOptions,inputFilterSensitiveLog=null!=overrideInputFilterSensitiveLog?overrideInputFilterSensitiveLog:context2.inputFilterSensitiveLog;null==(_b6=null==logger2?void 0:logger2.error)||_b6.call(logger2,{clientName,commandName,input:inputFilterSensitiveLog(args.input),error,metadata:error.$metadata});throw error}};loggerMiddlewareOptions={name:"loggerMiddleware",tags:["LOGGER"],step:"initialize",override:!0};getLoggerPlugin=options=>({applyToStack:clientStack=>{clientStack.add(loggerMiddleware(),loggerMiddlewareOptions)}});recursionDetectionMiddlewareOptions={step:"build",tags:["RECURSION_DETECTION"],name:"recursionDetectionMiddleware",override:!0,priority:"low"};recursionDetectionMiddleware=()=>next2=>async args=>next2(args);getRecursionDetectionPlugin=options=>({applyToStack:clientStack=>{clientStack.add(recursionDetectionMiddleware(),recursionDetectionMiddlewareOptions)}});CONTENT_LENGTH_HEADER="content-length";DECODED_CONTENT_LENGTH_HEADER="x-amz-decoded-content-length";checkContentLengthHeaderMiddlewareOptions={step:"finalizeRequest",tags:["CHECK_CONTENT_LENGTH_HEADER"],name:"getCheckContentLengthHeaderPlugin",override:!0};getCheckContentLengthHeaderPlugin=unused=>({applyToStack:clientStack=>{clientStack.add(checkContentLengthHeader(),checkContentLengthHeaderMiddlewareOptions)}});regionRedirectEndpointMiddleware=config=>(next2,context2)=>async args=>{const originalRegion=await config.region(),regionProviderRef=config.region;let unlock=()=>{};if(context2.__s3RegionRedirect){Object.defineProperty(config,"region",{writable:!1,value:async()=>context2.__s3RegionRedirect});unlock=()=>Object.defineProperty(config,"region",{writable:!0,value:regionProviderRef})}try{const result=await next2(args);if(context2.__s3RegionRedirect){unlock();const region=await config.region();if(originalRegion!==region)throw new Error("Region was not restored following S3 region redirect.")}return result}catch(e3){unlock();throw e3}};regionRedirectEndpointMiddlewareOptions={tags:["REGION_REDIRECT","S3"],name:"regionRedirectEndpointMiddleware",override:!0,relation:"before",toMiddleware:"endpointV2Middleware"};regionRedirectMiddlewareOptions={step:"initialize",tags:["REGION_REDIRECT","S3"],name:"regionRedirectMiddleware",override:!0};getRegionRedirectMiddlewarePlugin=clientConfig=>({applyToStack:clientStack=>{clientStack.add(regionRedirectMiddleware(clientConfig),regionRedirectMiddlewareOptions);clientStack.addRelativeTo(regionRedirectEndpointMiddleware(clientConfig),regionRedirectEndpointMiddlewareOptions)}});s3ExpiresMiddleware=config=>(next2,context2)=>async args=>{var _a13;const result=await next2(args),{response}=result;if(HttpResponse.isInstance(response)&&response.headers.expires){response.headers.expiresstring=response.headers.expires;try{parseRfc7231DateTime(response.headers.expires)}catch(e3){null==(_a13=context2.logger)||_a13.warn(`AWS SDK Warning for ${context2.clientName}::${context2.commandName} response parsing (${response.headers.expires}): ${e3}`);delete response.headers.expires}}return result};s3ExpiresMiddlewareOptions={tags:["S3"],name:"s3ExpiresMiddleware",override:!0,relation:"after",toMiddleware:"deserializerMiddleware"};getS3ExpiresMiddlewarePlugin=clientConfig=>({applyToStack:clientStack=>{clientStack.addRelativeTo(s3ExpiresMiddleware(clientConfig),s3ExpiresMiddlewareOptions)}});_S3ExpressIdentityCache=class _S3ExpressIdentityCache{constructor(data={}){__publicField(this,"data");__publicField(this,"lastPurgeTime",Date.now());this.data=data}get(key3){const entry=this.data[key3];if(entry)return entry}set(key3,entry){this.data[key3]=entry;return entry}delete(key3){delete this.data[key3]}async purgeExpired(){const now3=Date.now();if(!(this.lastPurgeTime+_S3ExpressIdentityCache.EXPIRED_CREDENTIAL_PURGE_INTERVAL_MS>now3))for(const key3 in this.data){const entry=this.data[key3];if(!entry.isRefreshing){const credential=await entry.identity;credential.expiration&&credential.expiration.getTime()<now3&&delete this.data[key3]}}}};__publicField(_S3ExpressIdentityCache,"EXPIRED_CREDENTIAL_PURGE_INTERVAL_MS",3e4);S3ExpressIdentityCache=_S3ExpressIdentityCache;S3ExpressIdentityCacheEntry=class{constructor(_identity,isRefreshing=!1,accessed=Date.now()){__publicField(this,"_identity");__publicField(this,"isRefreshing");__publicField(this,"accessed");this._identity=_identity;this.isRefreshing=isRefreshing;this.accessed=accessed}get identity(){this.accessed=Date.now();return this._identity}};_S3ExpressIdentityProviderImpl=class _S3ExpressIdentityProviderImpl{constructor(createSessionFn,cache2=new S3ExpressIdentityCache){__publicField(this,"createSessionFn");__publicField(this,"cache");this.createSessionFn=createSessionFn;this.cache=cache2}async getS3ExpressIdentity(awsIdentity,identityProperties){const key3=identityProperties.Bucket,{cache:cache2}=this,entry=cache2.get(key3);return entry?entry.identity.then(identity=>{var _a13,_b6,_c3,_d2;const isExpired=(null!=(_b6=null==(_a13=identity.expiration)?void 0:_a13.getTime())?_b6:0)<Date.now();if(isExpired)return cache2.set(key3,new S3ExpressIdentityCacheEntry(this.getIdentity(key3))).identity;const isExpiringSoon=(null!=(_d2=null==(_c3=identity.expiration)?void 0:_c3.getTime())?_d2:0)<Date.now()+_S3ExpressIdentityProviderImpl.REFRESH_WINDOW_MS;if(isExpiringSoon&&!entry.isRefreshing){entry.isRefreshing=!0;this.getIdentity(key3).then(id=>{cache2.set(key3,new S3ExpressIdentityCacheEntry(Promise.resolve(id)))})}return identity}):cache2.set(key3,new S3ExpressIdentityCacheEntry(this.getIdentity(key3))).identity}async getIdentity(key3){var _a13,_b6;await this.cache.purgeExpired().catch(error=>{console.warn("Error while clearing expired entries in S3ExpressIdentityCache: \n"+error)});const session=await this.createSessionFn(key3);if(!(null==(_a13=session.Credentials)?void 0:_a13.AccessKeyId)||!(null==(_b6=session.Credentials)?void 0:_b6.SecretAccessKey))throw new Error("s3#createSession response credential missing AccessKeyId or SecretAccessKey.");const identity={accessKeyId:session.Credentials.AccessKeyId,secretAccessKey:session.Credentials.SecretAccessKey,sessionToken:session.Credentials.SessionToken,expiration:session.Credentials.Expiration?new Date(session.Credentials.Expiration):void 0};return identity}};__publicField(_S3ExpressIdentityProviderImpl,"REFRESH_WINDOW_MS",6e4);S3ExpressIdentityProviderImpl=_S3ExpressIdentityProviderImpl;booleanSelector=(obj,key3,type)=>{if(key3 in obj){if("true"===obj[key3])return!0;if("false"===obj[key3])return!1;throw new Error(`Cannot load ${type} "${key3}". Expected "true" or "false", got ${obj[key3]}.`)}};(function(SelectorType2){SelectorType2.ENV="env";SelectorType2.CONFIG="shared config entry"})(SelectorType||(SelectorType={}));S3_EXPRESS_BUCKET_TYPE="Directory";S3_EXPRESS_BACKEND="S3Express";S3_EXPRESS_AUTH_SCHEME="sigv4-s3express";SESSION_TOKEN_QUERY_PARAM="X-Amz-S3session-Token";SESSION_TOKEN_HEADER=SESSION_TOKEN_QUERY_PARAM.toLowerCase();NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_ENV_NAME="AWS_S3_DISABLE_EXPRESS_SESSION_AUTH";NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_INI_NAME="s3_disable_express_session_auth";0;SignatureV4S3Express=class extends SignatureV4{async signWithCredentials(requestToSign,credentials,options){const credentialsWithoutSessionToken=getCredentialsWithoutSessionToken(credentials);requestToSign.headers[SESSION_TOKEN_HEADER]=credentials.sessionToken;setSingleOverride(this,credentialsWithoutSessionToken);return this.signRequest(requestToSign,null!=options?options:{})}async presignWithCredentials(requestToSign,credentials,options){var _a13;const credentialsWithoutSessionToken=getCredentialsWithoutSessionToken(credentials);delete requestToSign.headers[SESSION_TOKEN_HEADER];requestToSign.headers[SESSION_TOKEN_QUERY_PARAM]=credentials.sessionToken;requestToSign.query=null!=(_a13=requestToSign.query)?_a13:{};requestToSign.query[SESSION_TOKEN_QUERY_PARAM]=credentials.sessionToken;setSingleOverride(this,credentialsWithoutSessionToken);return this.presign(requestToSign,options)}};s3ExpressMiddleware=options=>(next2,context2)=>async args=>{var _a13,_b6,_c3,_d2,_e2;if(context2.endpointV2){const endpoint=context2.endpointV2,isS3ExpressAuth=(null==(_c3=null==(_b6=null==(_a13=endpoint.properties)?void 0:_a13.authSchemes)?void 0:_b6[0])?void 0:_c3.name)===S3_EXPRESS_AUTH_SCHEME,isS3ExpressBucket=(null==(_d2=endpoint.properties)?void 0:_d2.backend)===S3_EXPRESS_BACKEND||(null==(_e2=endpoint.properties)?void 0:_e2.bucketType)===S3_EXPRESS_BUCKET_TYPE;if(isS3ExpressBucket){setFeature(context2,"S3_EXPRESS_BUCKET","J");context2.isS3ExpressBucket=!0}if(isS3ExpressAuth){const requestBucket=args.input.Bucket;if(requestBucket){const s3ExpressIdentity=await options.s3ExpressIdentityProvider.getS3ExpressIdentity(await options.credentials(),{Bucket:requestBucket});context2.s3ExpressIdentity=s3ExpressIdentity;HttpRequest.isInstance(args.request)&&s3ExpressIdentity.sessionToken&&(args.request.headers[SESSION_TOKEN_HEADER]=s3ExpressIdentity.sessionToken)}}}return next2(args)};s3ExpressMiddlewareOptions={name:"s3ExpressMiddleware",step:"build",tags:["S3","S3_EXPRESS"],override:!0};getS3ExpressPlugin=options=>({applyToStack:clientStack=>{clientStack.add(s3ExpressMiddleware(options),s3ExpressMiddlewareOptions)}});signS3Express=async(s3ExpressIdentity,signingOptions,request2,sigV4MultiRegionSigner)=>{const signedRequest=await sigV4MultiRegionSigner.signWithCredentials(request2,s3ExpressIdentity,{});if(signedRequest.headers["X-Amz-Security-Token"]||signedRequest.headers["x-amz-security-token"])throw new Error("X-Amz-Security-Token must not be set for s3-express requests.");return signedRequest};defaultErrorHandler2=signingProperties=>error=>{throw error};defaultSuccessHandler2=(httpResponse,signingProperties)=>{};0;s3ExpressHttpSigningMiddleware=config=>(next2,context2)=>async args=>{if(!HttpRequest.isInstance(args.request))return next2(args);const smithyContext=getSmithyContext2(context2),scheme=smithyContext.selectedHttpAuthScheme;if(!scheme)throw new Error("No HttpAuthScheme was selected: unable to sign request");const{httpAuthOption:{signingProperties={}},identity,signer}=scheme;let request2;request2=context2.s3ExpressIdentity?await signS3Express(context2.s3ExpressIdentity,signingProperties,args.request,await config.signer()):await signer.sign(args.request,identity,signingProperties);const output=await next2({...args,request:request2}).catch((signer.errorHandler||defaultErrorHandler2)(signingProperties));(signer.successHandler||defaultSuccessHandler2)(output.response,signingProperties);return output};getS3ExpressHttpSigningPlugin=config=>({applyToStack:clientStack=>{clientStack.addRelativeTo(s3ExpressHttpSigningMiddleware(config),httpSigningMiddlewareOptions)}});resolveS3Config=(input,{session})=>{const[s3ClientProvider,CreateSessionCommandCtor]=session,{forcePathStyle,useAccelerateEndpoint,disableMultiregionAccessPoints,followRegionRedirects,s3ExpressIdentityProvider,bucketEndpoint,expectContinueHeader}=input;return Object.assign(input,{forcePathStyle:null!=forcePathStyle&&forcePathStyle,useAccelerateEndpoint:null!=useAccelerateEndpoint&&useAccelerateEndpoint,disableMultiregionAccessPoints:null!=disableMultiregionAccessPoints&&disableMultiregionAccessPoints,followRegionRedirects:null!=followRegionRedirects&&followRegionRedirects,s3ExpressIdentityProvider:null!=s3ExpressIdentityProvider?s3ExpressIdentityProvider:new S3ExpressIdentityProviderImpl(async key3=>s3ClientProvider().send(new CreateSessionCommandCtor({Bucket:key3}))),bucketEndpoint:null!=bucketEndpoint&&bucketEndpoint,expectContinueHeader:null!=expectContinueHeader?expectContinueHeader:2097152})};THROW_IF_EMPTY_BODY={CopyObjectCommand:!0,UploadPartCopyCommand:!0,CompleteMultipartUploadCommand:!0};MAX_BYTES_TO_INSPECT=3e3;throw200ExceptionsMiddleware=config=>(next2,context2)=>async args=>{const result=await next2(args),{response}=result;if(!HttpResponse.isInstance(response))return result;const{statusCode,body:sourceBody}=response;if(statusCode<200||statusCode>=300)return result;const isSplittableStream="function"==typeof(null==sourceBody?void 0:sourceBody.stream)||"function"==typeof(null==sourceBody?void 0:sourceBody.pipe)||"function"==typeof(null==sourceBody?void 0:sourceBody.tee);if(!isSplittableStream)return result;let bodyCopy=sourceBody,body=sourceBody;!sourceBody||"object"!=typeof sourceBody||sourceBody instanceof Uint8Array||([bodyCopy,body]=await splitStream2(sourceBody));response.body=body;const bodyBytes=await collectBody2(bodyCopy,{streamCollector:async stream=>headStream2(stream,MAX_BYTES_TO_INSPECT)});"function"==typeof(null==bodyCopy?void 0:bodyCopy.destroy)&&bodyCopy.destroy();const bodyStringTail=config.utf8Encoder(bodyBytes.subarray(bodyBytes.length-16));if(0===bodyBytes.length&&THROW_IF_EMPTY_BODY[context2.commandName]){const err3=new Error("S3 aborted request");err3.name="InternalError";throw err3}bodyStringTail&&bodyStringTail.endsWith("</Error>")&&(response.statusCode=400);return result};collectBody2=(streamBody=new Uint8Array,context2)=>streamBody instanceof Uint8Array?Promise.resolve(streamBody):context2.streamCollector(streamBody)||Promise.resolve(new Uint8Array);throw200ExceptionsMiddlewareOptions={relation:"after",toMiddleware:"deserializerMiddleware",tags:["THROW_200_EXCEPTIONS","S3"],name:"throw200ExceptionsMiddleware",override:!0};getThrow200ExceptionsPlugin=config=>({applyToStack:clientStack=>{clientStack.addRelativeTo(throw200ExceptionsMiddleware(config),throw200ExceptionsMiddlewareOptions)}});validate=str=>"string"==typeof str&&0===str.indexOf("arn:")&&str.split(":").length>=6;0;0;bucketEndpointMiddlewareOptions={name:"bucketEndpointMiddleware",override:!0,relation:"after",toMiddleware:"endpointV2Middleware"};validateBucketNameMiddlewareOptions={step:"initialize",tags:["VALIDATE_BUCKET_NAME"],name:"validateBucketNameMiddleware",override:!0};getValidateBucketNamePlugin=options=>({applyToStack:clientStack=>{clientStack.add(validateBucketNameMiddleware(options),validateBucketNameMiddlewareOptions);clientStack.addRelativeTo(bucketEndpointMiddleware(options),bucketEndpointMiddlewareOptions)}});S3RestXmlProtocol=class extends AwsRestXmlProtocol{async serializeRequest(operationSchema,input,context2){var _a13;const request2=await super.serializeRequest(operationSchema,input,context2),ns=NormalizedSchema.of(operationSchema.input),staticStructureSchema=ns.getSchema();let bucketMemberIndex=0;const requiredMemberCount=null!=(_a13=staticStructureSchema[6])?_a13:0;if(input&&"object"==typeof input)for(const[memberName,memberNs]of ns.structIterator()){if(++bucketMemberIndex>requiredMemberCount)break;if("Bucket"===memberName){if(!input.Bucket&&memberNs.getMergedTraits().httpLabel)throw new Error("No value provided for input HTTP label: Bucket.");break}}return request2}};DEFAULT_UA_APP_ID=void 0;EndpointCache2=class{constructor({size,params}){__publicField(this,"capacity");__publicField(this,"data",new Map);__publicField(this,"parameters",[]);this.capacity=null!=size?size:50;params&&(this.parameters=params)}get(endpointParams,resolver2){const key3=this.hash(endpointParams);if(!1===key3)return resolver2();if(!this.data.has(key3)){if(this.data.size>this.capacity+10){const keys3=this.data.keys();let i3=0;for(;;){const{value,done}=keys3.next();this.data.delete(value);if(done||++i3>10)break}}this.data.set(key3,resolver2())}return this.data.get(key3)}size(){return this.data.size}hash(endpointParams){var _a13;let buffer="";const{parameters}=this;if(0===parameters.length)return!1;for(const param of parameters){const val=String(null!=(_a13=endpointParams[param])?_a13:"");if(val.includes("|;"))return!1;buffer+=val+"|;"}return buffer}};IP_V4_REGEX2=new RegExp("^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$");isIpAddress2=value=>IP_V4_REGEX2.test(value)||value.startsWith("[")&&value.endsWith("]");VALID_HOST_LABEL_REGEX2=new RegExp("^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$");isValidHostLabel2=(value,allowSubDomains=!1)=>{if(!allowSubDomains)return VALID_HOST_LABEL_REGEX2.test(value);const labels=value.split(".");for(const label2 of labels)if(!isValidHostLabel2(label2))return!1;return!0};customEndpointFunctions2={};debugId="endpoints";EndpointError=class extends Error{constructor(message){super(message);this.name="EndpointError"}};booleanEquals=(value1,value2)=>value1===value2;getAttrPathList=path2=>{const parts=path2.split("."),pathList=[];for(const part of parts){const squareBracketIndex=part.indexOf("[");if(-1!==squareBracketIndex){if(part.indexOf("]")!==part.length-1)throw new EndpointError(`Path: '${path2}' does not end with ']'`);const arrayIndex=part.slice(squareBracketIndex+1,-1);if(Number.isNaN(parseInt(arrayIndex)))throw new EndpointError(`Invalid array index: '${arrayIndex}' in path: '${path2}'`);0!==squareBracketIndex&&pathList.push(part.slice(0,squareBracketIndex));pathList.push(arrayIndex)}else pathList.push(part)}return pathList};getAttr=(value,path2)=>getAttrPathList(path2).reduce((acc,index6)=>{if("object"!=typeof acc)throw new EndpointError(`Index '${index6}' in '${path2}' not found in '${JSON.stringify(value)}'`);return Array.isArray(acc)?acc[parseInt(index6)]:acc[index6]},value);isSet=value=>null!=value;not=value=>!value;init_dist_es();DEFAULT_PORTS={[EndpointURLScheme.HTTP]:80,[EndpointURLScheme.HTTPS]:443};parseURL=value=>{const whatwgURL=(()=>{try{if(value instanceof URL)return value;if("object"==typeof value&&"hostname"in value){const{hostname:hostname2,port,protocol:protocol2="",path:path2="",query:query3={}}=value,url=new URL(`${protocol2}//${hostname2}${port?`:${port}`:""}${path2}`);url.search=Object.entries(query3).map(([k2,v2])=>`${k2}=${v2}`).join("&");return url}return new URL(value)}catch(error){return null}})();if(!whatwgURL){console.error(`Unable to parse ${JSON.stringify(value)} as a whatwg URL.`);return null}const urlString=whatwgURL.href,{host,hostname,pathname,protocol,search}=whatwgURL;if(search)return null;const scheme=protocol.slice(0,-1);if(!Object.values(EndpointURLScheme).includes(scheme))return null;const isIp=isIpAddress2(hostname),inputContainsDefaultPort=urlString.includes(`${host}:${DEFAULT_PORTS[scheme]}`)||"string"==typeof value&&value.includes(`${host}:${DEFAULT_PORTS[scheme]}`),authority=`${host}${inputContainsDefaultPort?`:${DEFAULT_PORTS[scheme]}`:""}`;return{scheme,authority,path:pathname,normalizedPath:pathname.endsWith("/")?pathname:`${pathname}/`,isIp}};stringEquals=(value1,value2)=>value1===value2;substring=(input,start,stop,reverse)=>start>=stop||input.length<stop||/[^\u0000-\u007f]/.test(input)?null:reverse?input.substring(input.length-stop,input.length-start):input.substring(start,stop);uriEncode=value=>encodeURIComponent(value).replace(/[!*'()]/g,c3=>`%${c3.charCodeAt(0).toString(16).toUpperCase()}`);endpointFunctions={booleanEquals,getAttr,isSet,isValidHostLabel:isValidHostLabel2,not,parseURL,stringEquals,substring,uriEncode};evaluateTemplate=(template,options)=>{const evaluatedTemplateArr=[],templateContext={...options.endpointParams,...options.referenceRecord};let currentIndex=0;for(;currentIndex<template.length;){const openingBraceIndex=template.indexOf("{",currentIndex);if(-1===openingBraceIndex){evaluatedTemplateArr.push(template.slice(currentIndex));break}evaluatedTemplateArr.push(template.slice(currentIndex,openingBraceIndex));const closingBraceIndex=template.indexOf("}",openingBraceIndex);if(-1===closingBraceIndex){evaluatedTemplateArr.push(template.slice(openingBraceIndex));break}if("{"===template[openingBraceIndex+1]&&"}"===template[closingBraceIndex+1]){evaluatedTemplateArr.push(template.slice(openingBraceIndex+1,closingBraceIndex));currentIndex=closingBraceIndex+2}const parameterName=template.substring(openingBraceIndex+1,closingBraceIndex);if(parameterName.includes("#")){const[refName,attrName]=parameterName.split("#");evaluatedTemplateArr.push(getAttr(templateContext[refName],attrName))}else evaluatedTemplateArr.push(templateContext[parameterName]);currentIndex=closingBraceIndex+1}return evaluatedTemplateArr.join("")};getReferenceValue=({ref},options)=>{const referenceRecord={...options.endpointParams,...options.referenceRecord};return referenceRecord[ref]};evaluateExpression=(obj,keyName,options)=>{if("string"==typeof obj)return evaluateTemplate(obj,options);if(obj.fn)return group.callFunction(obj,options);if(obj.ref)return getReferenceValue(obj,options);throw new EndpointError(`'${keyName}': ${String(obj)} is not a string, function or reference.`)};callFunction=({fn,argv},options)=>{const evaluatedArgs=argv.map(arg=>["boolean","number"].includes(typeof arg)?arg:group.evaluateExpression(arg,"arg",options)),fnSegments=fn.split(".");return fnSegments[0]in customEndpointFunctions2&&null!=fnSegments[1]?customEndpointFunctions2[fnSegments[0]][fnSegments[1]](...evaluatedArgs):endpointFunctions[fn](...evaluatedArgs)};group={evaluateExpression,callFunction};evaluateCondition=({assign:assign2,...fnArgs},options)=>{var _a13,_b6;if(assign2&&assign2 in options.referenceRecord)throw new EndpointError(`'${assign2}' is already defined in Reference Record.`);const value=callFunction(fnArgs,options);null==(_b6=null==(_a13=options.logger)?void 0:_a13.debug)||_b6.call(_a13,`${debugId} evaluateCondition: ${toDebugString(fnArgs)} = ${toDebugString(value)}`);return{result:""===value||!!value,...null!=assign2&&{toAssign:{name:assign2,value}}}};evaluateConditions=(conditions=[],options)=>{var _a13,_b6;const conditionsReferenceRecord={};for(const condition of conditions){const{result,toAssign}=evaluateCondition(condition,{...options,referenceRecord:{...options.referenceRecord,...conditionsReferenceRecord}});if(!result)return{result};if(toAssign){conditionsReferenceRecord[toAssign.name]=toAssign.value;null==(_b6=null==(_a13=options.logger)?void 0:_a13.debug)||_b6.call(_a13,`${debugId} assign: ${toAssign.name} := ${toDebugString(toAssign.value)}`)}}return{result:!0,referenceRecord:conditionsReferenceRecord}};getEndpointHeaders=(headers,options)=>Object.entries(headers).reduce((acc,[headerKey,headerVal])=>({...acc,[headerKey]:headerVal.map(headerValEntry=>{const processedExpr=evaluateExpression(headerValEntry,"Header value entry",options);if("string"!=typeof processedExpr)throw new EndpointError(`Header '${headerKey}' value '${processedExpr}' is not a string`);return processedExpr})}),{});getEndpointProperties=(properties,options)=>Object.entries(properties).reduce((acc,[propertyKey,propertyVal])=>({...acc,[propertyKey]:group2.getEndpointProperty(propertyVal,options)}),{});getEndpointProperty=(property,options)=>{if(Array.isArray(property))return property.map(propertyEntry=>getEndpointProperty(propertyEntry,options));switch(typeof property){case"string":return evaluateTemplate(property,options);case"object":if(null===property)throw new EndpointError(`Unexpected endpoint property: ${property}`);return group2.getEndpointProperties(property,options);case"boolean":return property;default:throw new EndpointError("Unexpected endpoint property type: "+typeof property)}};group2={getEndpointProperty,getEndpointProperties};getEndpointUrl=(endpointUrl,options)=>{const expression=evaluateExpression(endpointUrl,"Endpoint URL",options);if("string"==typeof expression)try{return new URL(expression)}catch(error){console.error(`Failed to construct URL with ${expression}`,error);throw error}throw new EndpointError("Endpoint URL must be a string, got "+typeof expression)};evaluateEndpointRule=(endpointRule,options)=>{var _a13,_b6;const{conditions,endpoint}=endpointRule,{result,referenceRecord}=evaluateConditions(conditions,options);if(!result)return;const endpointRuleOptions={...options,referenceRecord:{...options.referenceRecord,...referenceRecord}},{url,properties,headers}=endpoint;null==(_b6=null==(_a13=options.logger)?void 0:_a13.debug)||_b6.call(_a13,`${debugId} Resolving endpoint from template: ${toDebugString(endpoint)}`);return{...null!=headers&&{headers:getEndpointHeaders(headers,endpointRuleOptions)},...null!=properties&&{properties:getEndpointProperties(properties,endpointRuleOptions)},url:getEndpointUrl(url,endpointRuleOptions)}};evaluateErrorRule=(errorRule,options)=>{const{conditions,error}=errorRule,{result,referenceRecord}=evaluateConditions(conditions,options);if(result)throw new EndpointError(evaluateExpression(error,"Error",{...options,referenceRecord:{...options.referenceRecord,...referenceRecord}}))};evaluateRules=(rules,options)=>{for(const rule of rules)if("endpoint"===rule.type){const endpointOrUndefined=evaluateEndpointRule(rule,options);if(endpointOrUndefined)return endpointOrUndefined}else if("error"===rule.type)evaluateErrorRule(rule,options);else{if("tree"!==rule.type)throw new EndpointError(`Unknown endpoint rule: ${rule}`);{const endpointOrUndefined=group3.evaluateTreeRule(rule,options);if(endpointOrUndefined)return endpointOrUndefined}}throw new EndpointError("Rules evaluation failed")};evaluateTreeRule=(treeRule,options)=>{const{conditions,rules}=treeRule,{result,referenceRecord}=evaluateConditions(conditions,options);if(result)return group3.evaluateRules(rules,{...options,referenceRecord:{...options.referenceRecord,...referenceRecord}})};group3={evaluateRules,evaluateTreeRule};resolveEndpoint2=(ruleSetObject,options)=>{var _a13,_b6,_c3,_d2,_e2;const{endpointParams,logger:logger2}=options,{parameters,rules}=ruleSetObject;null==(_b6=null==(_a13=options.logger)?void 0:_a13.debug)||_b6.call(_a13,`${debugId} Initial EndpointParams: ${toDebugString(endpointParams)}`);const paramsWithDefault=Object.entries(parameters).filter(([,v2])=>null!=v2.default).map(([k2,v2])=>[k2,v2.default]);if(paramsWithDefault.length>0)for(const[paramKey,paramDefaultValue]of paramsWithDefault)endpointParams[paramKey]=null!=(_c3=endpointParams[paramKey])?_c3:paramDefaultValue;const requiredParams=Object.entries(parameters).filter(([,v2])=>v2.required).map(([k2])=>k2);for(const requiredParam of requiredParams)if(null==endpointParams[requiredParam])throw new EndpointError(`Missing required parameter: '${requiredParam}'`);const endpoint=evaluateRules(rules,{endpointParams,logger:logger2,referenceRecord:{}});null==(_e2=null==(_d2=options.logger)?void 0:_d2.debug)||_e2.call(_d2,`${debugId} Resolved endpoint: ${toDebugString(endpoint)}`);return endpoint};isVirtualHostableS3Bucket=(value,allowSubDomains=!1)=>{if(allowSubDomains){for(const label2 of value.split("."))if(!isVirtualHostableS3Bucket(label2))return!1;return!0}return!!isValidHostLabel2(value)&&(!(value.length<3||value.length>63)&&(value===value.toLowerCase()&&!isIpAddress2(value)))};ARN_DELIMITER=":";RESOURCE_DELIMITER="/";parseArn=value=>{const segments=value.split(ARN_DELIMITER);if(segments.length<6)return null;const[arn,partition2,service,region,accountId,...resourcePath]=segments;if("arn"!==arn||""===partition2||""===service||""===resourcePath.join(ARN_DELIMITER))return null;const resourceId=resourcePath.map(resource=>resource.split(RESOURCE_DELIMITER)).flat();return{partition:partition2,service,region,accountId,resourceId}};partitions_default={partitions:[{id:"aws",outputs:{dnsSuffix:"amazonaws.com",dualStackDnsSuffix:"api.aws",implicitGlobalRegion:"us-east-1",name:"aws",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$",regions:{"af-south-1":{description:"Africa (Cape Town)"},"ap-east-1":{description:"Asia Pacific (Hong Kong)"},"ap-east-2":{description:"Asia Pacific (Taipei)"},"ap-northeast-1":{description:"Asia Pacific (Tokyo)"},"ap-northeast-2":{description:"Asia Pacific (Seoul)"},"ap-northeast-3":{description:"Asia Pacific (Osaka)"},"ap-south-1":{description:"Asia Pacific (Mumbai)"},"ap-south-2":{description:"Asia Pacific (Hyderabad)"},"ap-southeast-1":{description:"Asia Pacific (Singapore)"},"ap-southeast-2":{description:"Asia Pacific (Sydney)"},"ap-southeast-3":{description:"Asia Pacific (Jakarta)"},"ap-southeast-4":{description:"Asia Pacific (Melbourne)"},"ap-southeast-5":{description:"Asia Pacific (Malaysia)"},"ap-southeast-6":{description:"Asia Pacific (New Zealand)"},"ap-southeast-7":{description:"Asia Pacific (Thailand)"},"aws-global":{description:"aws global region"},"ca-central-1":{description:"Canada (Central)"},"ca-west-1":{description:"Canada West (Calgary)"},"eu-central-1":{description:"Europe (Frankfurt)"},"eu-central-2":{description:"Europe (Zurich)"},"eu-north-1":{description:"Europe (Stockholm)"},"eu-south-1":{description:"Europe (Milan)"},"eu-south-2":{description:"Europe (Spain)"},"eu-west-1":{description:"Europe (Ireland)"},"eu-west-2":{description:"Europe (London)"},"eu-west-3":{description:"Europe (Paris)"},"il-central-1":{description:"Israel (Tel Aviv)"},"me-central-1":{description:"Middle East (UAE)"},"me-south-1":{description:"Middle East (Bahrain)"},"mx-central-1":{description:"Mexico (Central)"},"sa-east-1":{description:"South America (Sao Paulo)"},"us-east-1":{description:"US East (N. Virginia)"},"us-east-2":{description:"US East (Ohio)"},"us-west-1":{description:"US West (N. California)"},"us-west-2":{description:"US West (Oregon)"}}},{id:"aws-cn",outputs:{dnsSuffix:"amazonaws.com.cn",dualStackDnsSuffix:"api.amazonwebservices.com.cn",implicitGlobalRegion:"cn-northwest-1",name:"aws-cn",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^cn\\-\\w+\\-\\d+$",regions:{"aws-cn-global":{description:"aws-cn global region"},"cn-north-1":{description:"China (Beijing)"},"cn-northwest-1":{description:"China (Ningxia)"}}},{id:"aws-eusc",outputs:{dnsSuffix:"amazonaws.eu",dualStackDnsSuffix:"api.amazonwebservices.eu",implicitGlobalRegion:"eusc-de-east-1",name:"aws-eusc",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^eusc\\-(de)\\-\\w+\\-\\d+$",regions:{"eusc-de-east-1":{description:"AWS European Sovereign Cloud (Germany)"}}},{id:"aws-iso",outputs:{dnsSuffix:"c2s.ic.gov",dualStackDnsSuffix:"api.aws.ic.gov",implicitGlobalRegion:"us-iso-east-1",name:"aws-iso",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-iso\\-\\w+\\-\\d+$",regions:{"aws-iso-global":{description:"aws-iso global region"},"us-iso-east-1":{description:"US ISO East"},"us-iso-west-1":{description:"US ISO WEST"}}},{id:"aws-iso-b",outputs:{dnsSuffix:"sc2s.sgov.gov",dualStackDnsSuffix:"api.aws.scloud",implicitGlobalRegion:"us-isob-east-1",name:"aws-iso-b",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-isob\\-\\w+\\-\\d+$",regions:{"aws-iso-b-global":{description:"aws-iso-b global region"},"us-isob-east-1":{description:"US ISOB East (Ohio)"},"us-isob-west-1":{description:"US ISOB West"}}},{id:"aws-iso-e",outputs:{dnsSuffix:"cloud.adc-e.uk",dualStackDnsSuffix:"api.cloud-aws.adc-e.uk",implicitGlobalRegion:"eu-isoe-west-1",name:"aws-iso-e",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^eu\\-isoe\\-\\w+\\-\\d+$",regions:{"aws-iso-e-global":{description:"aws-iso-e global region"},"eu-isoe-west-1":{description:"EU ISOE West"}}},{id:"aws-iso-f",outputs:{dnsSuffix:"csp.hci.ic.gov",dualStackDnsSuffix:"api.aws.hci.ic.gov",implicitGlobalRegion:"us-isof-south-1",name:"aws-iso-f",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-isof\\-\\w+\\-\\d+$",regions:{"aws-iso-f-global":{description:"aws-iso-f global region"},"us-isof-east-1":{description:"US ISOF EAST"},"us-isof-south-1":{description:"US ISOF SOUTH"}}},{id:"aws-us-gov",outputs:{dnsSuffix:"amazonaws.com",dualStackDnsSuffix:"api.aws",implicitGlobalRegion:"us-gov-west-1",name:"aws-us-gov",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-gov\\-\\w+\\-\\d+$",regions:{"aws-us-gov-global":{description:"aws-us-gov global region"},"us-gov-east-1":{description:"AWS GovCloud (US-East)"},"us-gov-west-1":{description:"AWS GovCloud (US-West)"}}}],version:"1.1"};selectedPartitionsInfo=partitions_default;selectedUserAgentPrefix="";partition=value=>{const{partitions}=selectedPartitionsInfo;for(const partition2 of partitions){const{regions,outputs}=partition2;for(const[region,regionData]of Object.entries(regions))if(region===value)return{...outputs,...regionData}}for(const partition2 of partitions){const{regionRegex,outputs}=partition2;if(new RegExp(regionRegex).test(value))return{...outputs}}const DEFAULT_PARTITION=partitions.find(partition2=>"aws"===partition2.id);if(!DEFAULT_PARTITION)throw new Error("Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist.");return{...DEFAULT_PARTITION.outputs}};setPartitionInfo=(partitionsInfo,userAgentPrefix="")=>{selectedPartitionsInfo=partitionsInfo;selectedUserAgentPrefix=userAgentPrefix};0;getUserAgentPrefix=()=>selectedUserAgentPrefix;awsEndpointFunctions={isVirtualHostableS3Bucket,parseArn,partition};customEndpointFunctions2.aws=awsEndpointFunctions;parseUrl2=url=>{if("string"==typeof url)return parseUrl2(new URL(url));const{hostname,pathname,port,protocol,search}=url;let query3;search&&(query3=parseQueryString2(search));return{hostname,port:port?parseInt(port):void 0,protocol,path:pathname,query:query3}};isStreamingPayload=request2=>(null==request2?void 0:request2.body)instanceof ReadableStream;NoOpLogger2=class{trace(){}debug(){}info(){}warn(){}error(){}};init_transport();init_transport();CLOCK_SKEW_ERROR_CODES=["AuthFailure","InvalidSignatureException","RequestExpired","RequestInTheFuture","RequestTimeTooSkewed","SignatureDoesNotMatch"];THROTTLING_ERROR_CODES=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"];TRANSIENT_ERROR_CODES=["TimeoutError","RequestTimeout","RequestTimeoutException"];TRANSIENT_ERROR_STATUS_CODES=[500,502,503,504];NODEJS_TIMEOUT_ERROR_CODES=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"];NODEJS_NETWORK_ERROR_CODES=["EHOSTUNREACH","ENETUNREACH","ENOTFOUND","EAI_AGAIN"];isRetryableByTrait=error=>void 0!==(null==error?void 0:error.$retryable);0;isClockSkewCorrectedError=error=>{var _a13;return null==(_a13=error.$metadata)?void 0:_a13.clockSkewCorrected};isBrowserNetworkError=error=>{const errorMessages=new Set(["Failed to fetch","NetworkError when attempting to fetch resource","The Internet connection appears to be offline","Load failed","Network request failed"]),isValid=error&&error instanceof TypeError;return!!isValid&&errorMessages.has(error.message)};isThrottlingError=error=>{var _a13,_b6;return 429===(null==(_a13=error.$metadata)?void 0:_a13.httpStatusCode)||THROTTLING_ERROR_CODES.includes(error.name)||1==(null==(_b6=error.$retryable)?void 0:_b6.throttling)};isTransientError=(error,depth=0)=>{var _a13,_b6;return isRetryableByTrait(error)||isClockSkewCorrectedError(error)||"InvalidSignatureException"===error.name&&(null==(_a13=error.message)?void 0:_a13.includes("Signature expired"))||TRANSIENT_ERROR_CODES.includes(error.name)||NODEJS_TIMEOUT_ERROR_CODES.includes((null==error?void 0:error.code)||"")||NODEJS_NETWORK_ERROR_CODES.includes((null==error?void 0:error.code)||"")||TRANSIENT_ERROR_STATUS_CODES.includes((null==(_b6=error.$metadata)?void 0:_b6.httpStatusCode)||0)||isBrowserNetworkError(error)||isNodeJsHttp2TransientError(error)||void 0!==error.cause&&depth<=10&&isTransientError(error.cause,depth+1)};isServerError=error=>{var _a13;if(void 0!==(null==(_a13=error.$metadata)?void 0:_a13.httpStatusCode)){const statusCode=error.$metadata.httpStatusCode;return 500<=statusCode&&statusCode<=599&&!isTransientError(error)}return!1};0;MAXIMUM_RETRY_DELAY=2e4;0;INITIAL_RETRY_TOKENS=500;0;0;NO_RETRY_INCREMENT=1;INVOCATION_ID_HEADER="amz-sdk-invocation-id";REQUEST_HEADER="amz-sdk-request";init_index_browser2();asSdkError=error=>error instanceof Error?error:error instanceof Object?Object.assign(new Error,error):"string"==typeof error?new Error(error):new Error(`AWS SDK error wrapper for ${error}`);init_index_browser2();cooldown=ms=>new Promise(resolve=>setTimeout(resolve,ms));isRetryStrategyV2=retryStrategy=>void 0!==retryStrategy.acquireInitialRetryToken&&void 0!==retryStrategy.refreshRetryTokenForRetry&&void 0!==retryStrategy.recordSuccess;getRetryErrorInfo=(error,logger2)=>{const errorInfo={error,errorType:getRetryErrorType(error)},retryAfterHint=parseRetryAfterHeader(error.$response,logger2);retryAfterHint&&(errorInfo.retryAfterHint=retryAfterHint);return errorInfo};getRetryErrorType=error=>isThrottlingError(error)?"THROTTLING":isTransientError(error)?"TRANSIENT":isServerError(error)?"SERVER_ERROR":"CLIENT_ERROR";retryMiddlewareOptions={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high",override:!0};_DefaultRateLimiter=class _DefaultRateLimiter{constructor(options){__publicField(this,"beta");__publicField(this,"minCapacity");__publicField(this,"minFillRate");__publicField(this,"scaleConstant");__publicField(this,"smooth");__publicField(this,"enabled",!1);__publicField(this,"availableTokens",0);__publicField(this,"lastMaxRate",0);__publicField(this,"measuredTxRate",0);__publicField(this,"requestCount",0);__publicField(this,"fillRate");__publicField(this,"lastThrottleTime");__publicField(this,"lastTimestamp",0);__publicField(this,"lastTxRateBucket");__publicField(this,"maxCapacity");__publicField(this,"timeWindow",0);var _a13,_b6,_c3,_d2,_e2;this.beta=null!=(_a13=null==options?void 0:options.beta)?_a13:.7;this.minCapacity=null!=(_b6=null==options?void 0:options.minCapacity)?_b6:1;this.minFillRate=null!=(_c3=null==options?void 0:options.minFillRate)?_c3:.5;this.scaleConstant=null!=(_d2=null==options?void 0:options.scaleConstant)?_d2:.4;this.smooth=null!=(_e2=null==options?void 0:options.smooth)?_e2:.8;this.lastThrottleTime=this.getCurrentTimeInSeconds();this.lastTxRateBucket=Math.floor(this.getCurrentTimeInSeconds());this.fillRate=this.minFillRate;this.maxCapacity=this.minCapacity}async getSendToken(){return this.acquireTokenBucket(1)}updateClientSendingRate(response){var _a13;let calculatedRate;this.updateMeasuredRate();const retryErrorInfo=response,isThrottling="THROTTLING"===(null==retryErrorInfo?void 0:retryErrorInfo.errorType)||isThrottlingError(null!=(_a13=null==retryErrorInfo?void 0:retryErrorInfo.error)?_a13:response);if(isThrottling){const rateToUse=this.enabled?Math.min(this.measuredTxRate,this.fillRate):this.measuredTxRate;this.lastMaxRate=rateToUse;this.calculateTimeWindow();this.lastThrottleTime=this.getCurrentTimeInSeconds();calculatedRate=this.cubicThrottle(rateToUse);this.enableTokenBucket()}else{this.calculateTimeWindow();calculatedRate=this.cubicSuccess(this.getCurrentTimeInSeconds())}const newRate=Math.min(calculatedRate,2*this.measuredTxRate);this.updateTokenBucketRate(newRate)}getCurrentTimeInSeconds(){return Date.now()/1e3}async acquireTokenBucket(amount){if(this.enabled){this.refillTokenBucket();for(;amount>this.availableTokens;){const delay2=(amount-this.availableTokens)/this.fillRate*1e3;await new Promise(resolve=>_DefaultRateLimiter.setTimeoutFn(resolve,delay2));this.refillTokenBucket()}this.availableTokens=this.availableTokens-amount}}refillTokenBucket(){const timestamp=this.getCurrentTimeInSeconds();if(!this.lastTimestamp){this.lastTimestamp=timestamp;return}const fillAmount=(timestamp-this.lastTimestamp)*this.fillRate;this.availableTokens=Math.min(this.maxCapacity,this.availableTokens+fillAmount);this.lastTimestamp=timestamp}calculateTimeWindow(){this.timeWindow=this.getPrecise(Math.pow(this.lastMaxRate*(1-this.beta)/this.scaleConstant,1/3))}cubicThrottle(rateToUse){return this.getPrecise(rateToUse*this.beta)}cubicSuccess(timestamp){return this.getPrecise(this.scaleConstant*Math.pow(timestamp-this.lastThrottleTime-this.timeWindow,3)+this.lastMaxRate)}enableTokenBucket(){this.enabled=!0}updateTokenBucketRate(newRate){this.refillTokenBucket();this.fillRate=Math.max(newRate,this.minFillRate);this.maxCapacity=Math.max(newRate,this.minCapacity);this.availableTokens=Math.min(this.availableTokens,this.maxCapacity)}updateMeasuredRate(){const t9=this.getCurrentTimeInSeconds(),timeBucket=Math.floor(2*t9)/2;this.requestCount++;if(timeBucket>this.lastTxRateBucket){const currentRate=this.requestCount/(timeBucket-this.lastTxRateBucket);this.measuredTxRate=this.getPrecise(currentRate*this.smooth+this.measuredTxRate*(1-this.smooth));this.requestCount=0;this.lastTxRateBucket=timeBucket}}getPrecise(num){return parseFloat(num.toFixed(8))}};__publicField(_DefaultRateLimiter,"setTimeoutFn",(fn,delay2)=>setTimeout(fn,delay2));DefaultRateLimiter=_DefaultRateLimiter;_Retry=class _Retry{static delay(){return _Retry.v2026?50:100}static throttlingDelay(){return _Retry.v2026?1e3:500}static cost(){return _Retry.v2026?14:5}static throttlingCost(){return _Retry.v2026?5:10}static modifiedCostType(){return _Retry.v2026?"THROTTLING":"TRANSIENT"}};__publicField(_Retry,"v2026","undefined"!=typeof process&&"true"===(null==(_a12=process.env)?void 0:_a12.SMITHY_NEW_RETRIES_2026));Retry=_Retry;DefaultRetryBackoffStrategy=class{constructor(){__publicField(this,"x",Retry.delay())}computeNextBackoffDelay(i3){const b3=Math.random(),t_i=b3*Math.min(this.x*2**i3,MAXIMUM_RETRY_DELAY);return Math.floor(t_i)}setDelayBase(delay2){this.x=delay2}};DefaultRetryToken=class{constructor(delay2,count,cost,longPoll){__publicField(this,"delay");__publicField(this,"count");__publicField(this,"cost");__publicField(this,"longPoll");__publicField(this,"$retryLog",{acquisitionDelay:0});this.delay=delay2;this.count=count;this.cost=cost;this.longPoll=longPoll}getRetryCount(){return this.count}getRetryDelay(){return Math.min(MAXIMUM_RETRY_DELAY,this.delay)}getRetryCost(){return this.cost}isLongPoll(){return this.longPoll}};(function(RETRY_MODES2){RETRY_MODES2.STANDARD="standard";RETRY_MODES2.ADAPTIVE="adaptive"})(RETRY_MODES||(RETRY_MODES={}));DEFAULT_MAX_ATTEMPTS=3;DEFAULT_RETRY_MODE=RETRY_MODES.STANDARD;refusal_incompatible=1,refusal_attempts=2,refusal_capacity=3;StandardRetryStrategy=class{constructor(arg1){__publicField(this,"mode",RETRY_MODES.STANDARD);__publicField(this,"retryBackoffStrategy");__publicField(this,"capacity",INITIAL_RETRY_TOKENS);__publicField(this,"maxAttemptsProvider");__publicField(this,"baseDelay");if("number"==typeof arg1)this.maxAttemptsProvider=async()=>arg1;else if("function"==typeof arg1)this.maxAttemptsProvider=arg1;else if(arg1&&"object"==typeof arg1){this.maxAttemptsProvider=async()=>arg1.maxAttempts;this.baseDelay=arg1.baseDelay;this.retryBackoffStrategy=arg1.backoff}null!=this.maxAttemptsProvider||(this.maxAttemptsProvider=async()=>DEFAULT_MAX_ATTEMPTS);null!=this.baseDelay||(this.baseDelay=Retry.delay());null!=this.retryBackoffStrategy||(this.retryBackoffStrategy=new DefaultRetryBackoffStrategy)}async acquireInitialRetryToken(retryTokenScope){return new DefaultRetryToken(Retry.delay(),0,void 0,Retry.v2026&&retryTokenScope.includes(":longpoll"))}async refreshRetryTokenForRetry(token,errorInfo){var _a13,_b6,_c3;const maxAttempts=await this.getMaxAttempts(),retryCode=this.retryCode(token,errorInfo,maxAttempts),shouldRetry=0===retryCode,isLongPoll=null==(_a13=token.isLongPoll)?void 0:_a13.call(token);if(shouldRetry||isLongPoll){const errorType=errorInfo.errorType;this.retryBackoffStrategy.setDelayBase("THROTTLING"===errorType?Retry.throttlingDelay():this.baseDelay);const delayFromErrorType=this.retryBackoffStrategy.computeNextBackoffDelay(token.getRetryCount());let retryDelay=delayFromErrorType;errorInfo.retryAfterHint instanceof Date&&(retryDelay=Math.max(delayFromErrorType,Math.min(errorInfo.retryAfterHint.getTime()-Date.now(),delayFromErrorType+5e3)));if(shouldRetry){const capacityCost=this.getCapacityCost(errorType);this.capacity-=capacityCost;const nextToken=new DefaultRetryToken(0,token.getRetryCount()+1,capacityCost,null!=(_c3=null==(_b6=token.isLongPoll)?void 0:_b6.call(token))&&_c3);await new Promise(r4=>setTimeout(r4,retryDelay));nextToken.$retryLog.acquisitionDelay=retryDelay;return nextToken}{const longPollBackoff=Retry.v2026&&retryCode===refusal_capacity&&isLongPoll?retryDelay:0;longPollBackoff>0&&await new Promise(r4=>setTimeout(r4,longPollBackoff))}}throw new Error("No retry token available")}recordSuccess(token){var _a13;this.capacity=Math.min(INITIAL_RETRY_TOKENS,this.capacity+(null!=(_a13=token.getRetryCost())?_a13:NO_RETRY_INCREMENT))}getCapacity(){return this.capacity}async maxAttempts(){return this.maxAttemptsProvider()}async getMaxAttempts(){try{return await this.maxAttemptsProvider()}catch(error){console.warn(`Max attempts provider could not resolve. Using default of ${DEFAULT_MAX_ATTEMPTS}`);return DEFAULT_MAX_ATTEMPTS}}retryCode(tokenToRenew,errorInfo,maxAttempts){const attempts=tokenToRenew.getRetryCount()+1,retryableStatus=this.isRetryableError(errorInfo.errorType)?0:refusal_incompatible,attemptStatus=attempts<maxAttempts?0:refusal_attempts,capacityStatus=this.capacity>=this.getCapacityCost(errorInfo.errorType)?0:refusal_capacity;return retryableStatus||attemptStatus||capacityStatus}getCapacityCost(errorType){return errorType===Retry.modifiedCostType()?Retry.throttlingCost():Retry.cost()}isRetryableError(errorType){return"THROTTLING"===errorType||"TRANSIENT"===errorType}};AdaptiveRetryStrategy=class{constructor(maxAttemptsProvider,options){__publicField(this,"mode",RETRY_MODES.ADAPTIVE);__publicField(this,"rateLimiter");__publicField(this,"standardRetryStrategy");const{rateLimiter}=null!=options?options:{};this.rateLimiter=null!=rateLimiter?rateLimiter:new DefaultRateLimiter;this.standardRetryStrategy=new StandardRetryStrategy(options?{maxAttempts:"number"==typeof maxAttemptsProvider?maxAttemptsProvider:3,...options}:maxAttemptsProvider)}async acquireInitialRetryToken(retryTokenScope){const token=await this.standardRetryStrategy.acquireInitialRetryToken(retryTokenScope);await this.rateLimiter.getSendToken();return token}async refreshRetryTokenForRetry(tokenToRenew,errorInfo){this.rateLimiter.updateClientSendingRate(errorInfo);const token=await this.standardRetryStrategy.refreshRetryTokenForRetry(tokenToRenew,errorInfo);await this.rateLimiter.getSendToken();return token}recordSuccess(token){this.rateLimiter.updateClientSendingRate({});this.standardRetryStrategy.recordSuccess(token)}async maxAttemptsProvider(){return this.standardRetryStrategy.maxAttempts()}};ConfiguredRetryStrategy=class extends StandardRetryStrategy{constructor(maxAttempts,computeNextBackoffDelay=Retry.delay()){super("function"==typeof maxAttempts?maxAttempts:async()=>maxAttempts);__publicField(this,"computeNextBackoffDelay");this.computeNextBackoffDelay="number"==typeof computeNextBackoffDelay?()=>computeNextBackoffDelay:computeNextBackoffDelay;this.retryBackoffStrategy.computeNextBackoffDelay=completedAttempt=>{const nextAttempt=completedAttempt+1;return this.computeNextBackoffDelay(nextAttempt)}}};no2=Symbol.for("node-only");0;0;0;0;0;0;bindRetryMiddleware(isStreamingPayload);(function bindGetRetryPlugin(isStreamingPayload3){const retryMiddleware3=bindRetryMiddleware(isStreamingPayload3);return options=>({applyToStack:clientStack=>{clientStack.add(retryMiddleware3(options),retryMiddlewareOptions)}})})(isStreamingPayload);ACCOUNT_ID_ENDPOINT_REGEX=/\d{12}\.ddb/;USER_AGENT="user-agent";X_AMZ_USER_AGENT="x-amz-user-agent";SPACE=" ";UA_NAME_SEPARATOR="/";UA_NAME_ESCAPE_REGEX=/[^!$%&'*+\-.^_`|~\w]/g;UA_VALUE_ESCAPE_REGEX=/[^!$%&'*+\-.^_`|~\w#]/g;UA_ESCAPE_CHAR="-";BYTE_LIMIT=1024;userAgentMiddleware=options=>(next2,context2)=>async args=>{var _a13,_b6,_c3,_d2;const{request:request2}=args;if(!HttpRequest.isInstance(request2))return next2(args);const{headers}=request2,userAgent=(null==(_a13=null==context2?void 0:context2.userAgent)?void 0:_a13.map(escapeUserAgent))||[],defaultUserAgent2=(await options.defaultUserAgentProvider()).map(escapeUserAgent);await checkFeatures(context2,options,args);const awsContext=context2;defaultUserAgent2.push(`m/${encodeFeatures(Object.assign({},null==(_b6=context2.__smithy_context)?void 0:_b6.features,null==(_c3=awsContext.__aws_sdk_context)?void 0:_c3.features))}`);const customUserAgent=(null==(_d2=null==options?void 0:options.customUserAgent)?void 0:_d2.map(escapeUserAgent))||[],appId=await options.userAgentAppId();appId&&defaultUserAgent2.push(escapeUserAgent(["app",`${appId}`]));const prefix=getUserAgentPrefix(),sdkUserAgentValue=(prefix?[prefix]:[]).concat([...defaultUserAgent2,...userAgent,...customUserAgent]).join(SPACE),normalUAValue=[...defaultUserAgent2.filter(section=>section.startsWith("aws-sdk-")),...customUserAgent].join(SPACE);if("browser"!==options.runtime){normalUAValue&&(headers[X_AMZ_USER_AGENT]=headers[X_AMZ_USER_AGENT]?`${headers[USER_AGENT]} ${normalUAValue}`:normalUAValue);headers[USER_AGENT]=sdkUserAgentValue}else headers[X_AMZ_USER_AGENT]=sdkUserAgentValue;return next2({...args,request:request2})};escapeUserAgent=userAgentPair=>{var _a13;const name=userAgentPair[0].split(UA_NAME_SEPARATOR).map(part=>part.replace(UA_NAME_ESCAPE_REGEX,UA_ESCAPE_CHAR)).join(UA_NAME_SEPARATOR),version2=null==(_a13=userAgentPair[1])?void 0:_a13.replace(UA_VALUE_ESCAPE_REGEX,UA_ESCAPE_CHAR),prefixSeparatorIndex=name.indexOf(UA_NAME_SEPARATOR),prefix=name.substring(0,prefixSeparatorIndex);let uaName=name.substring(prefixSeparatorIndex+1);"api"===prefix&&(uaName=uaName.toLowerCase());return[prefix,uaName,version2].filter(item=>item&&item.length>0).reduce((acc,item,index6)=>{switch(index6){case 0:return item;case 1:return`${acc}/${item}`;default:return`${acc}#${item}`}},"")};getUserAgentMiddlewareOptions={name:"getUserAgentMiddleware",step:"build",priority:"low",tags:["SET_USER_AGENT","USER_AGENT"],override:!0};getUserAgentPlugin=config=>({applyToStack:clientStack=>{clientStack.add(userAgentMiddleware(config),getUserAgentMiddlewareOptions)}});ENV_USE_DUALSTACK_ENDPOINT="AWS_USE_DUALSTACK_ENDPOINT";CONFIG_USE_DUALSTACK_ENDPOINT="use_dualstack_endpoint";DEFAULT_USE_DUALSTACK_ENDPOINT=!1;0;0;ENV_USE_FIPS_ENDPOINT="AWS_USE_FIPS_ENDPOINT";CONFIG_USE_FIPS_ENDPOINT="use_fips_endpoint";DEFAULT_USE_FIPS_ENDPOINT=!1;0;0;validRegions=new Set;checkRegion=(region,check=isValidHostLabel2)=>{if(validRegions.has(region)||check(region))validRegions.add(region);else{if("*"!==region)throw new Error(`Region not accepted: region="${region}" is not a valid hostname component.`);console.warn('@smithy/config-resolver WARN - Please use the caller region instead of "*". See "sigv4a" in https://github.com/aws/aws-sdk-js-v3/blob/main/supplemental-docs/CLIENTS.md.')}};isFipsRegion=region=>"string"==typeof region&&(region.startsWith("fips-")||region.endsWith("-fips"));getRealRegion=region=>isFipsRegion(region)?["fips-aws-global","aws-fips"].includes(region)?"us-east-1":region.replace(/fips-(dkr-|prod-)?|-fips/,""):region;resolveRegionConfig=input=>{const{region,useFipsEndpoint}=input;if(!region)throw new Error("Region is missing");return Object.assign(input,{region:async()=>{const providedRegion="function"==typeof region?await region():region,realRegion=getRealRegion(providedRegion);checkRegion(realRegion);return realRegion},useFipsEndpoint:async()=>{const providedRegion="string"==typeof region?region:await region();return!!isFipsRegion(providedRegion)||("function"!=typeof useFipsEndpoint?Promise.resolve(!!useFipsEndpoint):useFipsEndpoint())}})};resolveEventStreamSerdeConfig2=input=>Object.assign(input,{eventStreamMarshaller:input.eventStreamSerdeProvider(input)});CONTENT_LENGTH_HEADER2="content-length";contentLengthMiddlewareOptions2={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware",override:!0};getContentLengthPlugin2=options=>({applyToStack:clientStack=>{clientStack.add(contentLengthMiddleware2(options.bodyLengthChecker),contentLengthMiddlewareOptions2)}});resolveParamsForS32=async endpointParams=>{const bucket=(null==endpointParams?void 0:endpointParams.Bucket)||"";"string"==typeof endpointParams.Bucket&&(endpointParams.Bucket=bucket.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?")));if(isArnBucketName2(bucket)){if(!0===endpointParams.ForcePathStyle)throw new Error("Path-style addressing cannot be used with ARN buckets")}else(!isDnsCompatibleBucketName2(bucket)||-1!==bucket.indexOf(".")&&!String(endpointParams.Endpoint).startsWith("http:")||bucket.toLowerCase()!==bucket||bucket.length<3)&&(endpointParams.ForcePathStyle=!0);if(endpointParams.DisableMultiRegionAccessPoints){endpointParams.disableMultiRegionAccessPoints=!0;endpointParams.DisableMRAP=!0}return endpointParams};DOMAIN_PATTERN2=/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/;IP_ADDRESS_PATTERN2=/(\d+\.){3}\d+/;DOTS_PATTERN2=/\.\./;0;0;isDnsCompatibleBucketName2=bucketName=>DOMAIN_PATTERN2.test(bucketName)&&!IP_ADDRESS_PATTERN2.test(bucketName)&&!DOTS_PATTERN2.test(bucketName);isArnBucketName2=bucketName=>{const[arn,partition2,service,,,bucket]=bucketName.split(":"),isArn="arn"===arn&&bucketName.split(":").length>=6,isValidArn=Boolean(isArn&&partition2&&service&&bucket);if(isArn&&!isValidArn)throw new Error(`Invalid ARN: ${bucketName} was an invalid ARN.`);return isValidArn};createConfigValueProvider2=(configKey,canonicalEndpointParamKey,config,isClientContextParam=!1)=>{const configProvider=async()=>{var _a13,_b6;let configValue;if(isClientContextParam){const clientContextParams=config.clientContextParams,nestedValue=null==clientContextParams?void 0:clientContextParams[configKey];configValue=null!=(_a13=null!=nestedValue?nestedValue:config[configKey])?_a13:config[canonicalEndpointParamKey]}else configValue=null!=(_b6=config[configKey])?_b6:config[canonicalEndpointParamKey];return"function"==typeof configValue?configValue():configValue};return"credentialScope"===configKey||"CredentialScope"===canonicalEndpointParamKey?async()=>{var _a13;const credentials="function"==typeof config.credentials?await config.credentials():config.credentials,configValue=null!=(_a13=null==credentials?void 0:credentials.credentialScope)?_a13:null==credentials?void 0:credentials.CredentialScope;return configValue}:"accountId"===configKey||"AccountId"===canonicalEndpointParamKey?async()=>{var _a13;const credentials="function"==typeof config.credentials?await config.credentials():config.credentials,configValue=null!=(_a13=null==credentials?void 0:credentials.accountId)?_a13:null==credentials?void 0:credentials.AccountId;return configValue}:"endpoint"===configKey||"endpoint"===canonicalEndpointParamKey?async()=>{if(!1===config.isCustomEndpoint)return;const endpoint=await configProvider();if(endpoint&&"object"==typeof endpoint){if("url"in endpoint)return endpoint.url.href;if("hostname"in endpoint){const{protocol,hostname,port,path:path2}=endpoint;return`${protocol}//${hostname}${port?":"+port:""}${path2}`}}return endpoint}:configProvider};getEndpointFromConfig2=async serviceId=>{};toEndpointV12=endpoint=>{if("object"==typeof endpoint){if("url"in endpoint){const v1Endpoint=parseUrl2(endpoint.url);if(endpoint.headers){v1Endpoint.headers={};for(const[name,values2]of Object.entries(endpoint.headers))v1Endpoint.headers[name.toLowerCase()]=values2.join(", ")}return v1Endpoint}return endpoint}return parseUrl2(endpoint)};getEndpointFromInstructions2=async(commandInput,instructionsSupplier,clientConfig,context2)=>{if(!clientConfig.isCustomEndpoint){let endpointFromConfig;endpointFromConfig=clientConfig.serviceConfiguredEndpoint?await clientConfig.serviceConfiguredEndpoint():await getEndpointFromConfig2(clientConfig.serviceId);if(endpointFromConfig){clientConfig.endpoint=()=>Promise.resolve(toEndpointV12(endpointFromConfig));clientConfig.isCustomEndpoint=!0}}const endpointParams=await resolveParams2(commandInput,instructionsSupplier,clientConfig);if("function"!=typeof clientConfig.endpointProvider)throw new Error("config.endpointProvider is not set.");const endpoint=clientConfig.endpointProvider(endpointParams,context2);if(clientConfig.isCustomEndpoint&&clientConfig.endpoint){const customEndpoint=await clientConfig.endpoint();if(null==customEndpoint?void 0:customEndpoint.headers){null!=endpoint.headers||(endpoint.headers={});for(const[name,value]of Object.entries(customEndpoint.headers))endpoint.headers[name]=Array.isArray(value)?value:[value]}}return endpoint};resolveParams2=async(commandInput,instructionsSupplier,clientConfig)=>{var _a13;const endpointParams={},instructions=(null==(_a13=null==instructionsSupplier?void 0:instructionsSupplier.getEndpointParameterInstructions)?void 0:_a13.call(instructionsSupplier))||{};for(const[name,instruction]of Object.entries(instructions))switch(instruction.type){case"staticContextParams":endpointParams[name]=instruction.value;break;case"contextParams":endpointParams[name]=commandInput[instruction.name];break;case"clientContextParams":case"builtInParams":endpointParams[name]=await createConfigValueProvider2(instruction.name,name,clientConfig,"builtInParams"!==instruction.type)();break;case"operationContextParams":endpointParams[name]=instruction.get(commandInput);break;default:throw new Error("Unrecognized endpoint parameter instruction: "+JSON.stringify(instruction))}0===Object.keys(instructions).length&&Object.assign(endpointParams,clientConfig);"s3"===String(clientConfig.serviceId).toLowerCase()&&await resolveParamsForS32(endpointParams);return endpointParams};endpointMiddleware2=({config,instructions})=>(next2,context2)=>async args=>{var _a13,_b6,_c3;config.isCustomEndpoint&&setFeature3(context2,"ENDPOINT_OVERRIDE","N");const endpoint=await getEndpointFromInstructions2(args.input,{getEndpointParameterInstructions:()=>instructions},{...config},context2);context2.endpointV2=endpoint;context2.authSchemes=null==(_a13=endpoint.properties)?void 0:_a13.authSchemes;const authScheme=null==(_b6=context2.authSchemes)?void 0:_b6[0];if(authScheme){context2.signing_region=authScheme.signingRegion;context2.signing_service=authScheme.signingName;const smithyContext=getSmithyContext2(context2),httpAuthOption=null==(_c3=null==smithyContext?void 0:smithyContext.selectedHttpAuthScheme)?void 0:_c3.httpAuthOption;httpAuthOption&&(httpAuthOption.signingProperties=Object.assign(httpAuthOption.signingProperties||{},{signing_region:authScheme.signingRegion,signingRegion:authScheme.signingRegion,signing_service:authScheme.signingName,signingName:authScheme.signingName,signingRegionSet:authScheme.signingRegionSet},authScheme.properties))}return next2({...args})};0;findHeader2=(pattern,headers)=>(headers.find(([k2])=>k2.match(pattern))||[void 0,void 0])[1];init_index_browser();0;0;serializerMiddlewareOption4={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};endpointMiddlewareOptions2={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:serializerMiddlewareOption4.name};getEndpointPlugin2=(config,instructions)=>({applyToStack:clientStack=>{clientStack.addRelativeTo(endpointMiddleware2({config,instructions}),endpointMiddlewareOptions2)}});resolveEndpointConfig2=input=>{var _a13;const tls=null==(_a13=input.tls)||_a13,{endpoint,useDualstackEndpoint,useFipsEndpoint}=input,customEndpointProvider=null!=endpoint?async()=>toEndpointV12(await normalizeProvider3(endpoint)()):void 0,isCustomEndpoint=!!endpoint,resolvedConfig=Object.assign(input,{endpoint:customEndpointProvider,tls,isCustomEndpoint,useDualstackEndpoint:normalizeProvider3(null!=useDualstackEndpoint&&useDualstackEndpoint),useFipsEndpoint:normalizeProvider3(null!=useFipsEndpoint&&useFipsEndpoint)});let configuredEndpointPromise;resolvedConfig.serviceConfiguredEndpoint=async()=>{input.serviceId&&!configuredEndpointPromise&&(configuredEndpointPromise=getEndpointFromConfig2(input.serviceId));return configuredEndpointPromise};return resolvedConfig};CLOCK_SKEW_ERROR_CODES2=["AuthFailure","InvalidSignatureException","RequestExpired","RequestInTheFuture","RequestTimeTooSkewed","SignatureDoesNotMatch"];THROTTLING_ERROR_CODES2=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"];TRANSIENT_ERROR_CODES2=["TimeoutError","RequestTimeout","RequestTimeoutException"];TRANSIENT_ERROR_STATUS_CODES2=[500,502,503,504];NODEJS_TIMEOUT_ERROR_CODES2=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"];NODEJS_NETWORK_ERROR_CODES2=["EHOSTUNREACH","ENETUNREACH","ENOTFOUND"];isRetryableByTrait2=error=>void 0!==(null==error?void 0:error.$retryable);0;isClockSkewCorrectedError2=error=>{var _a13;return null==(_a13=error.$metadata)?void 0:_a13.clockSkewCorrected};isBrowserNetworkError2=error=>{const errorMessages=new Set(["Failed to fetch","NetworkError when attempting to fetch resource","The Internet connection appears to be offline","Load failed","Network request failed"]),isValid=error&&error instanceof TypeError;return!!isValid&&errorMessages.has(error.message)};isThrottlingError2=error=>{var _a13,_b6;return 429===(null==(_a13=error.$metadata)?void 0:_a13.httpStatusCode)||THROTTLING_ERROR_CODES2.includes(error.name)||1==(null==(_b6=error.$retryable)?void 0:_b6.throttling)};isTransientError2=(error,depth=0)=>{var _a13;return isRetryableByTrait2(error)||isClockSkewCorrectedError2(error)||TRANSIENT_ERROR_CODES2.includes(error.name)||NODEJS_TIMEOUT_ERROR_CODES2.includes((null==error?void 0:error.code)||"")||NODEJS_NETWORK_ERROR_CODES2.includes((null==error?void 0:error.code)||"")||TRANSIENT_ERROR_STATUS_CODES2.includes((null==(_a13=error.$metadata)?void 0:_a13.httpStatusCode)||0)||isBrowserNetworkError2(error)||void 0!==error.cause&&depth<=10&&isTransientError2(error.cause,depth+1)};isServerError2=error=>{var _a13;if(void 0!==(null==(_a13=error.$metadata)?void 0:_a13.httpStatusCode)){const statusCode=error.$metadata.httpStatusCode;return 500<=statusCode&&statusCode<=599&&!isTransientError2(error)}return!1};randomUUID="undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);decimalToHex2=Array.from({length:256},(_,i3)=>i3.toString(16).padStart(2,"0"));v42=()=>{if(randomUUID)return randomUUID();const rnds=new Uint8Array(16);crypto.getRandomValues(rnds);rnds[6]=15&rnds[6]|64;rnds[8]=63&rnds[8]|128;return decimalToHex2[rnds[0]]+decimalToHex2[rnds[1]]+decimalToHex2[rnds[2]]+decimalToHex2[rnds[3]]+"-"+decimalToHex2[rnds[4]]+decimalToHex2[rnds[5]]+"-"+decimalToHex2[rnds[6]]+decimalToHex2[rnds[7]]+"-"+decimalToHex2[rnds[8]]+decimalToHex2[rnds[9]]+"-"+decimalToHex2[rnds[10]]+decimalToHex2[rnds[11]]+decimalToHex2[rnds[12]]+decimalToHex2[rnds[13]]+decimalToHex2[rnds[14]]+decimalToHex2[rnds[15]]};asSdkError2=error=>error instanceof Error?error:error instanceof Object?Object.assign(new Error,error):"string"==typeof error?new Error(error):new Error(`AWS SDK error wrapper for ${error}`);ENV_MAX_ATTEMPTS2="AWS_MAX_ATTEMPTS";CONFIG_MAX_ATTEMPTS2="max_attempts";0;resolveRetryConfig2=input=>{var _a13;const{retryStrategy,retryMode}=input,maxAttempts=normalizeProvider3(null!=(_a13=input.maxAttempts)?_a13:DEFAULT_MAX_ATTEMPTS);let controller=retryStrategy?Promise.resolve(retryStrategy):void 0;const getDefault=async()=>await normalizeProvider3(retryMode)()===RETRY_MODES.ADAPTIVE?new AdaptiveRetryStrategy(maxAttempts):new StandardRetryStrategy(maxAttempts);return Object.assign(input,{maxAttempts,retryStrategy:()=>null!=controller?controller:controller=getDefault()})};ENV_RETRY_MODE2="AWS_RETRY_MODE";CONFIG_RETRY_MODE2="retry_mode";0;isStreamingPayload2=request2=>(null==request2?void 0:request2.body)instanceof ReadableStream;retryMiddleware2=options=>(next2,context2)=>async args=>{var _a13;let retryStrategy=await options.retryStrategy();const maxAttempts=await options.maxAttempts();if(!isRetryStrategyV22(retryStrategy)){(null==retryStrategy?void 0:retryStrategy.mode)&&(context2.userAgent=[...context2.userAgent||[],["cfg/retry-mode",retryStrategy.mode]]);return retryStrategy.retry(next2,args)}{let retryToken=await retryStrategy.acquireInitialRetryToken(context2.partition_id),lastError=new Error,attempts=0,totalRetryDelay=0;const{request:request2}=args,isRequest=HttpRequest.isInstance(request2);isRequest&&(request2.headers[INVOCATION_ID_HEADER]=v42());for(;;)try{isRequest&&(request2.headers[REQUEST_HEADER]=`attempt=${attempts+1}; max=${maxAttempts}`);const{response,output}=await next2(args);retryStrategy.recordSuccess(retryToken);output.$metadata.attempts=attempts+1;output.$metadata.totalRetryDelay=totalRetryDelay;return{response,output}}catch(e3){const retryErrorInfo=getRetryErrorInfo2(e3);lastError=asSdkError2(e3);if(isRequest&&isStreamingPayload2(request2)){null==(_a13=context2.logger instanceof NoOpLogger?console:context2.logger)||_a13.warn("An error was encountered in a non-retryable streaming request.");throw lastError}try{retryToken=await retryStrategy.refreshRetryTokenForRetry(retryToken,retryErrorInfo)}catch(refreshError){lastError.$metadata||(lastError.$metadata={});lastError.$metadata.attempts=attempts+1;lastError.$metadata.totalRetryDelay=totalRetryDelay;throw lastError}attempts=retryToken.getRetryCount();const delay2=retryToken.getRetryDelay();totalRetryDelay+=delay2;await new Promise(resolve=>setTimeout(resolve,delay2))}}};isRetryStrategyV22=retryStrategy=>void 0!==retryStrategy.acquireInitialRetryToken&&void 0!==retryStrategy.refreshRetryTokenForRetry&&void 0!==retryStrategy.recordSuccess;getRetryErrorInfo2=error=>{const errorInfo={error,errorType:getRetryErrorType2(error)},retryAfterHint=getRetryAfterHint2(error.$response);retryAfterHint&&(errorInfo.retryAfterHint=retryAfterHint);return errorInfo};getRetryErrorType2=error=>isThrottlingError2(error)?"THROTTLING":isTransientError2(error)?"TRANSIENT":isServerError2(error)?"SERVER_ERROR":"CLIENT_ERROR";retryMiddlewareOptions2={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high",override:!0};getRetryPlugin2=options=>({applyToStack:clientStack=>{clientStack.add(retryMiddleware2(options),retryMiddlewareOptions2)}});getRetryAfterHint2=response=>{if(!HttpResponse.isInstance(response))return;const retryAfterHeaderName=Object.keys(response.headers).find(key3=>"retry-after"===key3.toLowerCase());if(!retryAfterHeaderName)return;const retryAfter=response.headers[retryAfterHeaderName],retryAfterSeconds=Number(retryAfter);if(!Number.isNaN(retryAfterSeconds))return new Date(1e3*retryAfterSeconds);const retryAfterDate=new Date(retryAfter);return retryAfterDate};signatureV4CrtContainer_CrtSignerV4=null;SignatureV4MultiRegion=class{constructor(options){__publicField(this,"sigv4aSigner");__publicField(this,"sigv4Signer");__publicField(this,"signerOptions");this.sigv4Signer=new SignatureV4S3Express(options);this.signerOptions=options}static sigv4aDependency(){return"function"==typeof signatureV4CrtContainer_CrtSignerV4?"crt":"function"==typeof signatureV4aContainer_SignatureV4a?"js":"none"}async sign(requestToSign,options={}){return"*"===options.signingRegion?this.getSigv4aSigner().sign(requestToSign,options):this.sigv4Signer.sign(requestToSign,options)}async signWithCredentials(requestToSign,credentials,options={}){if("*"===options.signingRegion){const signer=this.getSigv4aSigner(),CrtSignerV4=signatureV4CrtContainer_CrtSignerV4;if(CrtSignerV4&&signer instanceof CrtSignerV4)return signer.signWithCredentials(requestToSign,credentials,options);throw new Error('signWithCredentials with signingRegion \'*\' is only supported when using the CRT dependency @aws-sdk/signature-v4-crt. Please check whether you have installed the "@aws-sdk/signature-v4-crt" package explicitly. You must also register the package by calling [require("@aws-sdk/signature-v4-crt");] or an ESM equivalent such as [import "@aws-sdk/signature-v4-crt";]. For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt')}return this.sigv4Signer.signWithCredentials(requestToSign,credentials,options)}async presign(originalRequest,options={}){if("*"===options.signingRegion){const signer=this.getSigv4aSigner(),CrtSignerV4=signatureV4CrtContainer_CrtSignerV4;if(CrtSignerV4&&signer instanceof CrtSignerV4)return signer.presign(originalRequest,options);throw new Error('presign with signingRegion \'*\' is only supported when using the CRT dependency @aws-sdk/signature-v4-crt. Please check whether you have installed the "@aws-sdk/signature-v4-crt" package explicitly. You must also register the package by calling [require("@aws-sdk/signature-v4-crt");] or an ESM equivalent such as [import "@aws-sdk/signature-v4-crt";]. For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt')}return this.sigv4Signer.presign(originalRequest,options)}async presignWithCredentials(originalRequest,credentials,options={}){if("*"===options.signingRegion)throw new Error("Method presignWithCredentials is not supported for [signingRegion=*].");return this.sigv4Signer.presignWithCredentials(originalRequest,credentials,options)}getSigv4aSigner(){if(!this.sigv4aSigner){const CrtSignerV4=signatureV4CrtContainer_CrtSignerV4,JsSigV4aSigner=signatureV4aContainer_SignatureV4a;if("node"===this.signerOptions.runtime){if(!CrtSignerV4&&!JsSigV4aSigner)throw new Error("Neither CRT nor JS SigV4a implementation is available. Please load either @aws-sdk/signature-v4-crt or @aws-sdk/signature-v4a. For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt");if(CrtSignerV4&&"function"==typeof CrtSignerV4)this.sigv4aSigner=new CrtSignerV4({...this.signerOptions,signingAlgorithm:1});else{if(!JsSigV4aSigner||"function"!=typeof JsSigV4aSigner)throw new Error("Available SigV4a implementation is not a valid constructor. Please ensure you've properly imported @aws-sdk/signature-v4-crt or @aws-sdk/signature-v4a.For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt");this.sigv4aSigner=new JsSigV4aSigner({...this.signerOptions})}}else{if(!JsSigV4aSigner||"function"!=typeof JsSigV4aSigner)throw new Error("JS SigV4a implementation is not available or not a valid constructor. Please check whether you have installed the @aws-sdk/signature-v4a package explicitly. The CRT implementation is not available for browsers. You must also register the package by calling [require('@aws-sdk/signature-v4a');] or an ESM equivalent such as [import '@aws-sdk/signature-v4a';]. For more information please go to https://github.com/aws/aws-sdk-js-v3#using-javascript-non-crt-implementation-of-sigv4a");this.sigv4aSigner=new JsSigV4aSigner({...this.signerOptions})}}return this.sigv4aSigner}};cs="required",ct="type",cu="rules",cv="conditions",cw="fn",cx="argv",cy="ref",cz="assign",cA="url",cB="properties",cC="backend",cD="authSchemes",cE="disableDoubleEncoding",cF="signingName",cG="signingRegion",cH="headers",cI="signingRegionSet";a=6,b=!1,c=!0,d3="isSet",e2="booleanEquals",f="error",g="aws.partition",h="stringEquals",i2="getAttr",j="name",k="substring",l="bucketSuffix",m2="parseURL",n2="endpoint",o="tree",p="aws.isVirtualHostableS3Bucket",q="{url#scheme}://{Bucket}.{url#authority}{url#path}",r3="not",s="accessPointSuffix",t8="{url#scheme}://{url#authority}{url#path}",u="hardwareType",v="regionPrefix",w="bucketAliasSuffix",x2="outpostId",y="isValidHostLabel",z="sigv4a",A="s3-outposts",B="s3",C2="{url#scheme}://{url#authority}{url#normalizedPath}{Bucket}",D="https://{Bucket}.s3-accelerate.{partitionResult#dnsSuffix}",E="https://{Bucket}.s3.{partitionResult#dnsSuffix}",F="aws.parseArn",G2="bucketArn",H="arnType",I2="",J="s3-object-lambda",K="accesspoint",L3="accessPointName",M2="{url#scheme}://{accessPointName}-{bucketArn#accountId}.{url#authority}{url#path}",N2="mrapPartition",O="outpostType",P2="arnPrefix",Q="{url#scheme}://{url#authority}{url#normalizedPath}{uri_encoded_bucket}",R="https://s3.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",S="https://s3.{partitionResult#dnsSuffix}",T={[cs]:!1,[ct]:"string"},U={[cs]:!0,default:!1,[ct]:"boolean"},V={[cs]:!1,[ct]:"boolean"},W2={[cw]:e2,[cx]:[{[cy]:"Accelerate"},!0]},X={[cw]:e2,[cx]:[{[cy]:"UseFIPS"},!0]},Y={[cw]:e2,[cx]:[{[cy]:"UseDualStack"},!0]},Z={[cw]:d3,[cx]:[{[cy]:"Endpoint"}]},aa={[cw]:g,[cx]:[{[cy]:"Region"}],[cz]:"partitionResult"},ab={[cw]:h,[cx]:[{[cw]:i2,[cx]:[{[cy]:"partitionResult"},j]},"aws-cn"]},ac={[cw]:d3,[cx]:[{[cy]:"Bucket"}]},ad={[cy]:"Bucket"},ae={[cv]:[W2],[f]:"S3Express does not support S3 Accelerate.",[ct]:f},af={[cv]:[Z,{[cw]:m2,[cx]:[{[cy]:"Endpoint"}],[cz]:"url"}],[cu]:[{[cv]:[{[cw]:d3,[cx]:[{[cy]:"DisableS3ExpressSessionAuth"}]},{[cw]:e2,[cx]:[{[cy]:"DisableS3ExpressSessionAuth"},!0]}],[cu]:[{[cv]:[{[cw]:e2,[cx]:[{[cw]:i2,[cx]:[{[cy]:"url"},"isIp"]},!0]}],[cu]:[{[cv]:[{[cw]:"uriEncode",[cx]:[ad],[cz]:"uri_encoded_bucket"}],[cu]:[{[n2]:{[cA]:"{url#scheme}://{url#authority}/{uri_encoded_bucket}{url#path}",[cB]:{[cC]:"S3Express",[cD]:[{[cE]:!0,[j]:"sigv4",[cF]:"s3express",[cG]:"{Region}"}]},[cH]:{}},[ct]:n2}],[ct]:o}],[ct]:o},{[cv]:[{[cw]:p,[cx]:[ad,!1]}],[cu]:[{[n2]:{[cA]:q,[cB]:{[cC]:"S3Express",[cD]:[{[cE]:!0,[j]:"sigv4",[cF]:"s3express",[cG]:"{Region}"}]},[cH]:{}},[ct]:n2}],[ct]:o},{[f]:"S3Express bucket name is not a valid virtual hostable name.",[ct]:f}],[ct]:o},{[cv]:[{[cw]:e2,[cx]:[{[cw]:i2,[cx]:[{[cy]:"url"},"isIp"]},!0]}],[cu]:[{[cv]:[{[cw]:"uriEncode",[cx]:[ad],[cz]:"uri_encoded_bucket"}],[cu]:[{[n2]:{[cA]:"{url#scheme}://{url#authority}/{uri_encoded_bucket}{url#path}",[cB]:{[cC]:"S3Express",[cD]:[{[cE]:!0,[j]:"sigv4-s3express",[cF]:"s3express",[cG]:"{Region}"}]},[cH]:{}},[ct]:n2}],[ct]:o}],[ct]:o},{[cv]:[{[cw]:p,[cx]:[ad,!1]}],[cu]:[{[n2]:{[cA]:q,[cB]:{[cC]:"S3Express",[cD]:[{[cE]:!0,[j]:"sigv4-s3express",[cF]:"s3express",[cG]:"{Region}"}]},[cH]:{}},[ct]:n2}],[ct]:o},{[f]:"S3Express bucket name is not a valid virtual hostable name.",[ct]:f}],[ct]:o},ag={[cw]:m2,[cx]:[{[cy]:"Endpoint"}],[cz]:"url"},ah={[cw]:e2,[cx]:[{[cw]:i2,[cx]:[{[cy]:"url"},"isIp"]},!0]},ai={[cy]:"url"},aj={[cw]:"uriEncode",[cx]:[ad],[cz]:"uri_encoded_bucket"},ak={[cC]:"S3Express",[cD]:[{[cE]:!0,[j]:"sigv4",[cF]:"s3express",[cG]:"{Region}"}]},al={},am={[cw]:p,[cx]:[ad,!1]},an={[f]:"S3Express bucket name is not a valid virtual hostable name.",[ct]:f},ao={[cw]:d3,[cx]:[{[cy]:"UseS3ExpressControlEndpoint"}]},ap={[cw]:e2,[cx]:[{[cy]:"UseS3ExpressControlEndpoint"},!0]},aq={[cw]:r3,[cx]:[Z]},ar={[cw]:e2,[cx]:[{[cy]:"UseDualStack"},!1]},as={[cw]:e2,[cx]:[{[cy]:"UseFIPS"},!1]},at={[f]:"Unrecognized S3Express bucket name format.",[ct]:f},au={[cw]:r3,[cx]:[ac]},av={[cy]:u},aw={[cv]:[aq],[f]:"Expected a endpoint to be specified but no endpoint was found",[ct]:f},ax={[cD]:[{[cE]:!0,[j]:z,[cF]:A,[cI]:["*"]},{[cE]:!0,[j]:"sigv4",[cF]:A,[cG]:"{Region}"}]},ay={[cw]:e2,[cx]:[{[cy]:"ForcePathStyle"},!1]},az={[cy]:"ForcePathStyle"},aA={[cw]:e2,[cx]:[{[cy]:"Accelerate"},!1]},aB={[cw]:h,[cx]:[{[cy]:"Region"},"aws-global"]},aC={[cD]:[{[cE]:!0,[j]:"sigv4",[cF]:B,[cG]:"us-east-1"}]},aD={[cw]:r3,[cx]:[aB]},aE={[cw]:e2,[cx]:[{[cy]:"UseGlobalEndpoint"},!0]},aF={[cA]:"https://{Bucket}.s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}",[cB]:{[cD]:[{[cE]:!0,[j]:"sigv4",[cF]:B,[cG]:"{Region}"}]},[cH]:{}},aG={[cD]:[{[cE]:!0,[j]:"sigv4",[cF]:B,[cG]:"{Region}"}]},aH={[cw]:e2,[cx]:[{[cy]:"UseGlobalEndpoint"},!1]},aI={[cA]:"https://{Bucket}.s3-fips.{Region}.{partitionResult#dnsSuffix}",[cB]:aG,[cH]:{}},aJ={[cA]:"https://{Bucket}.s3-accelerate.dualstack.{partitionResult#dnsSuffix}",[cB]:aG,[cH]:{}},aK={[cA]:"https://{Bucket}.s3.dualstack.{Region}.{partitionResult#dnsSuffix}",[cB]:aG,[cH]:{}},aL={[cw]:e2,[cx]:[{[cw]:i2,[cx]:[ai,"isIp"]},!1]},aM={[cA]:C2,[cB]:aG,[cH]:{}},aN={[cA]:q,[cB]:aG,[cH]:{}},aO={[n2]:aN,[ct]:n2},aP={[cA]:D,[cB]:aG,[cH]:{}},aQ={[cA]:"https://{Bucket}.s3.{Region}.{partitionResult#dnsSuffix}",[cB]:aG,[cH]:{}},aR={[f]:"Invalid region: region was not a valid DNS name.",[ct]:f},aS={[cy]:G2},aT={[cy]:H},aU={[cw]:i2,[cx]:[aS,"service"]},aV={[cy]:L3},aW={[cv]:[Y],[f]:"S3 Object Lambda does not support Dual-stack",[ct]:f},aX={[cv]:[W2],[f]:"S3 Object Lambda does not support S3 Accelerate",[ct]:f},aY={[cv]:[{[cw]:d3,[cx]:[{[cy]:"DisableAccessPoints"}]},{[cw]:e2,[cx]:[{[cy]:"DisableAccessPoints"},!0]}],[f]:"Access points are not supported for this operation",[ct]:f},aZ={[cv]:[{[cw]:d3,[cx]:[{[cy]:"UseArnRegion"}]},{[cw]:e2,[cx]:[{[cy]:"UseArnRegion"},!1]},{[cw]:r3,[cx]:[{[cw]:h,[cx]:[{[cw]:i2,[cx]:[aS,"region"]},"{Region}"]}]}],[f]:"Invalid configuration: region from ARN `{bucketArn#region}` does not match client region `{Region}` and UseArnRegion is `false`",[ct]:f},ba={[cw]:i2,[cx]:[{[cy]:"bucketPartition"},j]},bb={[cw]:i2,[cx]:[aS,"accountId"]},bc={[cD]:[{[cE]:!0,[j]:"sigv4",[cF]:J,[cG]:"{bucketArn#region}"}]},bd={[f]:"Invalid ARN: The access point name may only contain a-z, A-Z, 0-9 and `-`. Found: `{accessPointName}`",[ct]:f},be={[f]:"Invalid ARN: The account id may only contain a-z, A-Z, 0-9 and `-`. Found: `{bucketArn#accountId}`",[ct]:f},bf={[f]:"Invalid region in ARN: `{bucketArn#region}` (invalid DNS name)",[ct]:f},bg={[f]:"Client was configured for partition `{partitionResult#name}` but ARN (`{Bucket}`) has `{bucketPartition#name}`",[ct]:f},bh={[f]:"Invalid ARN: The ARN may only contain a single resource component after `accesspoint`.",[ct]:f},bi={[f]:"Invalid ARN: Expected a resource of the format `accesspoint:<accesspoint name>` but no name was provided",[ct]:f},bj={[cD]:[{[cE]:!0,[j]:"sigv4",[cF]:B,[cG]:"{bucketArn#region}"}]},bk={[cD]:[{[cE]:!0,[j]:z,[cF]:A,[cI]:["*"]},{[cE]:!0,[j]:"sigv4",[cF]:A,[cG]:"{bucketArn#region}"}]},bl={[cw]:F,[cx]:[ad]},bm={[cA]:"https://s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[cB]:aG,[cH]:{}},bn={[cA]:"https://s3-fips.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[cB]:aG,[cH]:{}},bo={[cA]:"https://s3.dualstack.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[cB]:aG,[cH]:{}},bp={[cA]:Q,[cB]:aG,[cH]:{}},bq={[cA]:"https://s3.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[cB]:aG,[cH]:{}},br={[cy]:"UseObjectLambdaEndpoint"},bs={[cD]:[{[cE]:!0,[j]:"sigv4",[cF]:J,[cG]:"{Region}"}]},bt={[cA]:"https://s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}",[cB]:aG,[cH]:{}},bu={[cA]:"https://s3-fips.{Region}.{partitionResult#dnsSuffix}",[cB]:aG,[cH]:{}},bv={[cA]:"https://s3.dualstack.{Region}.{partitionResult#dnsSuffix}",[cB]:aG,[cH]:{}},bw={[cA]:t8,[cB]:aG,[cH]:{}},bx={[cA]:"https://s3.{Region}.{partitionResult#dnsSuffix}",[cB]:aG,[cH]:{}},by=[{[cy]:"Region"}],bz=[{[cy]:"Endpoint"}],bA=[ad],bB=[W2],bC=[Z,ag],bD=[{[cw]:d3,[cx]:[{[cy]:"DisableS3ExpressSessionAuth"}]},{[cw]:e2,[cx]:[{[cy]:"DisableS3ExpressSessionAuth"},!0]}],bE=[aj],bF=[am],bG=[aa],bH=[X,Y],bI=[X,ar],bJ=[as,Y],bK=[as,ar],bL=[{[cw]:k,[cx]:[ad,6,14,!0],[cz]:"s3expressAvailabilityZoneId"},{[cw]:k,[cx]:[ad,14,16,!0],[cz]:"s3expressAvailabilityZoneDelim"},{[cw]:h,[cx]:[{[cy]:"s3expressAvailabilityZoneDelim"},"--"]}],bM=[{[cv]:[X,Y],[n2]:{[cA]:"https://{Bucket}.s3express-fips-{s3expressAvailabilityZoneId}.dualstack.{Region}.{partitionResult#dnsSuffix}",[cB]:ak,[cH]:{}},[ct]:n2},{[cv]:bI,[n2]:{[cA]:"https://{Bucket}.s3express-fips-{s3expressAvailabilityZoneId}.{Region}.{partitionResult#dnsSuffix}",[cB]:ak,[cH]:{}},[ct]:n2},{[cv]:bJ,[n2]:{[cA]:"https://{Bucket}.s3express-{s3expressAvailabilityZoneId}.dualstack.{Region}.{partitionResult#dnsSuffix}",[cB]:ak,[cH]:{}},[ct]:n2},{[cv]:bK,[n2]:{[cA]:"https://{Bucket}.s3express-{s3expressAvailabilityZoneId}.{Region}.{partitionResult#dnsSuffix}",[cB]:ak,[cH]:{}},[ct]:n2}],bN=[{[cw]:k,[cx]:[ad,6,15,!0],[cz]:"s3expressAvailabilityZoneId"},{[cw]:k,[cx]:[ad,15,17,!0],[cz]:"s3expressAvailabilityZoneDelim"},{[cw]:h,[cx]:[{[cy]:"s3expressAvailabilityZoneDelim"},"--"]}],bO=[{[cw]:k,[cx]:[ad,6,19,!0],[cz]:"s3expressAvailabilityZoneId"},{[cw]:k,[cx]:[ad,19,21,!0],[cz]:"s3expressAvailabilityZoneDelim"},{[cw]:h,[cx]:[{[cy]:"s3expressAvailabilityZoneDelim"},"--"]}],bP=[{[cw]:k,[cx]:[ad,6,20,!0],[cz]:"s3expressAvailabilityZoneId"},{[cw]:k,[cx]:[ad,20,22,!0],[cz]:"s3expressAvailabilityZoneDelim"},{[cw]:h,[cx]:[{[cy]:"s3expressAvailabilityZoneDelim"},"--"]}],bQ=[{[cw]:k,[cx]:[ad,6,26,!0],[cz]:"s3expressAvailabilityZoneId"},{[cw]:k,[cx]:[ad,26,28,!0],[cz]:"s3expressAvailabilityZoneDelim"},{[cw]:h,[cx]:[{[cy]:"s3expressAvailabilityZoneDelim"},"--"]}],bR=[{[cv]:[X,Y],[n2]:{[cA]:"https://{Bucket}.s3express-fips-{s3expressAvailabilityZoneId}.dualstack.{Region}.{partitionResult#dnsSuffix}",[cB]:{[cC]:"S3Express",[cD]:[{[cE]:!0,[j]:"sigv4-s3express",[cF]:"s3express",[cG]:"{Region}"}]},[cH]:{}},[ct]:n2},{[cv]:bI,[n2]:{[cA]:"https://{Bucket}.s3express-fips-{s3expressAvailabilityZoneId}.{Region}.{partitionResult#dnsSuffix}",[cB]:{[cC]:"S3Express",[cD]:[{[cE]:!0,[j]:"sigv4-s3express",[cF]:"s3express",[cG]:"{Region}"}]},[cH]:{}},[ct]:n2},{[cv]:bJ,[n2]:{[cA]:"https://{Bucket}.s3express-{s3expressAvailabilityZoneId}.dualstack.{Region}.{partitionResult#dnsSuffix}",[cB]:{[cC]:"S3Express",[cD]:[{[cE]:!0,[j]:"sigv4-s3express",[cF]:"s3express",[cG]:"{Region}"}]},[cH]:{}},[ct]:n2},{[cv]:bK,[n2]:{[cA]:"https://{Bucket}.s3express-{s3expressAvailabilityZoneId}.{Region}.{partitionResult#dnsSuffix}",[cB]:{[cC]:"S3Express",[cD]:[{[cE]:!0,[j]:"sigv4-s3express",[cF]:"s3express",[cG]:"{Region}"}]},[cH]:{}},[ct]:n2}],bS=[ad,0,7,!0],bT=[{[cw]:k,[cx]:[ad,7,15,!0],[cz]:"s3expressAvailabilityZoneId"},{[cw]:k,[cx]:[ad,15,17,!0],[cz]:"s3expressAvailabilityZoneDelim"},{[cw]:h,[cx]:[{[cy]:"s3expressAvailabilityZoneDelim"},"--"]}],bU=[{[cw]:k,[cx]:[ad,7,16,!0],[cz]:"s3expressAvailabilityZoneId"},{[cw]:k,[cx]:[ad,16,18,!0],[cz]:"s3expressAvailabilityZoneDelim"},{[cw]:h,[cx]:[{[cy]:"s3expressAvailabilityZoneDelim"},"--"]}],bV=[{[cw]:k,[cx]:[ad,7,20,!0],[cz]:"s3expressAvailabilityZoneId"},{[cw]:k,[cx]:[ad,20,22,!0],[cz]:"s3expressAvailabilityZoneDelim"},{[cw]:h,[cx]:[{[cy]:"s3expressAvailabilityZoneDelim"},"--"]}],bW=[{[cw]:k,[cx]:[ad,7,21,!0],[cz]:"s3expressAvailabilityZoneId"},{[cw]:k,[cx]:[ad,21,23,!0],[cz]:"s3expressAvailabilityZoneDelim"},{[cw]:h,[cx]:[{[cy]:"s3expressAvailabilityZoneDelim"},"--"]}],bX=[{[cw]:k,[cx]:[ad,7,27,!0],[cz]:"s3expressAvailabilityZoneId"},{[cw]:k,[cx]:[ad,27,29,!0],[cz]:"s3expressAvailabilityZoneDelim"},{[cw]:h,[cx]:[{[cy]:"s3expressAvailabilityZoneDelim"},"--"]}],bY=[ac],bZ=[{[cw]:y,[cx]:[{[cy]:x2},!1]}],ca=[{[cw]:h,[cx]:[{[cy]:v},"beta"]}],cb=["*"],cc=[{[cw]:y,[cx]:[{[cy]:"Region"},!1]}],cd=[{[cw]:h,[cx]:[{[cy]:"Region"},"us-east-1"]}],ce=[{[cw]:h,[cx]:[aT,K]}],cf=[{[cw]:i2,[cx]:[aS,"resourceId[1]"],[cz]:L3},{[cw]:r3,[cx]:[{[cw]:h,[cx]:[aV,I2]}]}],cg=[aS,"resourceId[1]"],ch3=[Y],ci=[{[cw]:r3,[cx]:[{[cw]:h,[cx]:[{[cw]:i2,[cx]:[aS,"region"]},I2]}]}],cj=[{[cw]:r3,[cx]:[{[cw]:d3,[cx]:[{[cw]:i2,[cx]:[aS,"resourceId[2]"]}]}]}],ck=[aS,"resourceId[2]"],cl=[{[cw]:g,[cx]:[{[cw]:i2,[cx]:[aS,"region"]}],[cz]:"bucketPartition"}],cm=[{[cw]:h,[cx]:[ba,{[cw]:i2,[cx]:[{[cy]:"partitionResult"},j]}]}],cn=[{[cw]:y,[cx]:[{[cw]:i2,[cx]:[aS,"region"]},!0]}],co=[{[cw]:y,[cx]:[bb,!1]}],cp=[{[cw]:y,[cx]:[aV,!1]}],cq=[X],cr=[{[cw]:y,[cx]:[{[cy]:"Region"},!0]}];_data={version:"1.0",parameters:{Bucket:T,Region:T,UseFIPS:U,UseDualStack:U,Endpoint:T,ForcePathStyle:U,Accelerate:U,UseGlobalEndpoint:U,UseObjectLambdaEndpoint:V,Key:T,Prefix:T,CopySource:T,DisableAccessPoints:V,DisableMultiRegionAccessPoints:U,UseArnRegion:V,UseS3ExpressControlEndpoint:V,DisableS3ExpressSessionAuth:V},[cu]:[{[cv]:[{[cw]:d3,[cx]:by}],[cu]:[{[cv]:[W2,X],error:"Accelerate cannot be used with FIPS",[ct]:f},{[cv]:[Y,Z],error:"Cannot set dual-stack in combination with a custom endpoint.",[ct]:f},{[cv]:[Z,X],error:"A custom endpoint cannot be combined with FIPS",[ct]:f},{[cv]:[Z,W2],error:"A custom endpoint cannot be combined with S3 Accelerate",[ct]:f},{[cv]:[X,aa,ab],error:"Partition does not support FIPS",[ct]:f},{[cv]:[ac,{[cw]:k,[cx]:[ad,0,a,c],[cz]:l},{[cw]:h,[cx]:[{[cy]:l},"--x-s3"]}],[cu]:[ae,af,{[cv]:[ao,ap],[cu]:[{[cv]:bG,[cu]:[{[cv]:[aj,aq],[cu]:[{[cv]:bH,endpoint:{[cA]:"https://s3express-control-fips.dualstack.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[cB]:ak,[cH]:al},[ct]:n2},{[cv]:bI,endpoint:{[cA]:"https://s3express-control-fips.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[cB]:ak,[cH]:al},[ct]:n2},{[cv]:bJ,endpoint:{[cA]:"https://s3express-control.dualstack.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[cB]:ak,[cH]:al},[ct]:n2},{[cv]:bK,endpoint:{[cA]:"https://s3express-control.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[cB]:ak,[cH]:al},[ct]:n2}],[ct]:o}],[ct]:o}],[ct]:o},{[cv]:bF,[cu]:[{[cv]:bG,[cu]:[{[cv]:bD,[cu]:[{[cv]:bL,[cu]:bM,[ct]:o},{[cv]:bN,[cu]:bM,[ct]:o},{[cv]:bO,[cu]:bM,[ct]:o},{[cv]:bP,[cu]:bM,[ct]:o},{[cv]:bQ,[cu]:bM,[ct]:o},at],[ct]:o},{[cv]:bL,[cu]:bR,[ct]:o},{[cv]:bN,[cu]:bR,[ct]:o},{[cv]:bO,[cu]:bR,[ct]:o},{[cv]:bP,[cu]:bR,[ct]:o},{[cv]:bQ,[cu]:bR,[ct]:o},at],[ct]:o}],[ct]:o},an],[ct]:o},{[cv]:[ac,{[cw]:k,[cx]:bS,[cz]:s},{[cw]:h,[cx]:[{[cy]:s},"--xa-s3"]}],[cu]:[ae,af,{[cv]:bF,[cu]:[{[cv]:bG,[cu]:[{[cv]:bD,[cu]:[{[cv]:bT,[cu]:bM,[ct]:o},{[cv]:bU,[cu]:bM,[ct]:o},{[cv]:bV,[cu]:bM,[ct]:o},{[cv]:bW,[cu]:bM,[ct]:o},{[cv]:bX,[cu]:bM,[ct]:o},at],[ct]:o},{[cv]:bT,[cu]:bR,[ct]:o},{[cv]:bU,[cu]:bR,[ct]:o},{[cv]:bV,[cu]:bR,[ct]:o},{[cv]:bW,[cu]:bR,[ct]:o},{[cv]:bX,[cu]:bR,[ct]:o},at],[ct]:o}],[ct]:o},an],[ct]:o},{[cv]:[au,ao,ap],[cu]:[{[cv]:bG,[cu]:[{[cv]:bC,endpoint:{[cA]:t8,[cB]:ak,[cH]:al},[ct]:n2},{[cv]:bH,endpoint:{[cA]:"https://s3express-control-fips.dualstack.{Region}.{partitionResult#dnsSuffix}",[cB]:ak,[cH]:al},[ct]:n2},{[cv]:bI,endpoint:{[cA]:"https://s3express-control-fips.{Region}.{partitionResult#dnsSuffix}",[cB]:ak,[cH]:al},[ct]:n2},{[cv]:bJ,endpoint:{[cA]:"https://s3express-control.dualstack.{Region}.{partitionResult#dnsSuffix}",[cB]:ak,[cH]:al},[ct]:n2},{[cv]:bK,endpoint:{[cA]:"https://s3express-control.{Region}.{partitionResult#dnsSuffix}",[cB]:ak,[cH]:al},[ct]:n2}],[ct]:o}],[ct]:o},{[cv]:[ac,{[cw]:k,[cx]:[ad,49,50,c],[cz]:u},{[cw]:k,[cx]:[ad,8,12,c],[cz]:v},{[cw]:k,[cx]:bS,[cz]:w},{[cw]:k,[cx]:[ad,32,49,c],[cz]:x2},{[cw]:g,[cx]:by,[cz]:"regionPartition"},{[cw]:h,[cx]:[{[cy]:w},"--op-s3"]}],[cu]:[{[cv]:bZ,[cu]:[{[cv]:bF,[cu]:[{[cv]:[{[cw]:h,[cx]:[av,"e"]}],[cu]:[{[cv]:ca,[cu]:[aw,{[cv]:bC,endpoint:{[cA]:"https://{Bucket}.ec2.{url#authority}",[cB]:ax,[cH]:al},[ct]:n2}],[ct]:o},{endpoint:{[cA]:"https://{Bucket}.ec2.s3-outposts.{Region}.{regionPartition#dnsSuffix}",[cB]:ax,[cH]:al},[ct]:n2}],[ct]:o},{[cv]:[{[cw]:h,[cx]:[av,"o"]}],[cu]:[{[cv]:ca,[cu]:[aw,{[cv]:bC,endpoint:{[cA]:"https://{Bucket}.op-{outpostId}.{url#authority}",[cB]:ax,[cH]:al},[ct]:n2}],[ct]:o},{endpoint:{[cA]:"https://{Bucket}.op-{outpostId}.s3-outposts.{Region}.{regionPartition#dnsSuffix}",[cB]:ax,[cH]:al},[ct]:n2}],[ct]:o},{error:'Unrecognized hardware type: "Expected hardware type o or e but got {hardwareType}"',[ct]:f}],[ct]:o},{error:"Invalid Outposts Bucket alias - it must be a valid bucket name.",[ct]:f}],[ct]:o},{error:"Invalid ARN: The outpost Id must only contain a-z, A-Z, 0-9 and `-`.",[ct]:f}],[ct]:o},{[cv]:bY,[cu]:[{[cv]:[Z,{[cw]:r3,[cx]:[{[cw]:d3,[cx]:[{[cw]:m2,[cx]:bz}]}]}],error:"Custom endpoint `{Endpoint}` was not a valid URI",[ct]:f},{[cv]:[ay,am],[cu]:[{[cv]:bG,[cu]:[{[cv]:cc,[cu]:[{[cv]:[W2,ab],error:"S3 Accelerate cannot be used in this region",[ct]:f},{[cv]:[Y,X,aA,aq,aB],endpoint:{[cA]:"https://{Bucket}.s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}",[cB]:aC,[cH]:al},[ct]:n2},{[cv]:[Y,X,aA,aq,aD,aE],[cu]:[{endpoint:aF,[ct]:n2}],[ct]:o},{[cv]:[Y,X,aA,aq,aD,aH],endpoint:aF,[ct]:n2},{[cv]:[ar,X,aA,aq,aB],endpoint:{[cA]:"https://{Bucket}.s3-fips.us-east-1.{partitionResult#dnsSuffix}",[cB]:aC,[cH]:al},[ct]:n2},{[cv]:[ar,X,aA,aq,aD,aE],[cu]:[{endpoint:aI,[ct]:n2}],[ct]:o},{[cv]:[ar,X,aA,aq,aD,aH],endpoint:aI,[ct]:n2},{[cv]:[Y,as,W2,aq,aB],endpoint:{[cA]:"https://{Bucket}.s3-accelerate.dualstack.us-east-1.{partitionResult#dnsSuffix}",[cB]:aC,[cH]:al},[ct]:n2},{[cv]:[Y,as,W2,aq,aD,aE],[cu]:[{endpoint:aJ,[ct]:n2}],[ct]:o},{[cv]:[Y,as,W2,aq,aD,aH],endpoint:aJ,[ct]:n2},{[cv]:[Y,as,aA,aq,aB],endpoint:{[cA]:"https://{Bucket}.s3.dualstack.us-east-1.{partitionResult#dnsSuffix}",[cB]:aC,[cH]:al},[ct]:n2},{[cv]:[Y,as,aA,aq,aD,aE],[cu]:[{endpoint:aK,[ct]:n2}],[ct]:o},{[cv]:[Y,as,aA,aq,aD,aH],endpoint:aK,[ct]:n2},{[cv]:[ar,as,aA,Z,ag,ah,aB],endpoint:{[cA]:C2,[cB]:aC,[cH]:al},[ct]:n2},{[cv]:[ar,as,aA,Z,ag,aL,aB],endpoint:{[cA]:q,[cB]:aC,[cH]:al},[ct]:n2},{[cv]:[ar,as,aA,Z,ag,ah,aD,aE],[cu]:[{[cv]:cd,endpoint:aM,[ct]:n2},{endpoint:aM,[ct]:n2}],[ct]:o},{[cv]:[ar,as,aA,Z,ag,aL,aD,aE],[cu]:[{[cv]:cd,endpoint:aN,[ct]:n2},aO],[ct]:o},{[cv]:[ar,as,aA,Z,ag,ah,aD,aH],endpoint:aM,[ct]:n2},{[cv]:[ar,as,aA,Z,ag,aL,aD,aH],endpoint:aN,[ct]:n2},{[cv]:[ar,as,W2,aq,aB],endpoint:{[cA]:D,[cB]:aC,[cH]:al},[ct]:n2},{[cv]:[ar,as,W2,aq,aD,aE],[cu]:[{[cv]:cd,endpoint:aP,[ct]:n2},{endpoint:aP,[ct]:n2}],[ct]:o},{[cv]:[ar,as,W2,aq,aD,aH],endpoint:aP,[ct]:n2},{[cv]:[ar,as,aA,aq,aB],endpoint:{[cA]:E,[cB]:aC,[cH]:al},[ct]:n2},{[cv]:[ar,as,aA,aq,aD,aE],[cu]:[{[cv]:cd,endpoint:{[cA]:E,[cB]:aG,[cH]:al},[ct]:n2},{endpoint:aQ,[ct]:n2}],[ct]:o},{[cv]:[ar,as,aA,aq,aD,aH],endpoint:aQ,[ct]:n2}],[ct]:o},aR],[ct]:o}],[ct]:o},{[cv]:[Z,ag,{[cw]:h,[cx]:[{[cw]:i2,[cx]:[ai,"scheme"]},"http"]},{[cw]:p,[cx]:[ad,c]},ay,as,ar,aA],[cu]:[{[cv]:bG,[cu]:[{[cv]:cc,[cu]:[aO],[ct]:o},aR],[ct]:o}],[ct]:o},{[cv]:[ay,{[cw]:F,[cx]:bA,[cz]:G2}],[cu]:[{[cv]:[{[cw]:i2,[cx]:[aS,"resourceId[0]"],[cz]:H},{[cw]:r3,[cx]:[{[cw]:h,[cx]:[aT,I2]}]}],[cu]:[{[cv]:[{[cw]:h,[cx]:[aU,J]}],[cu]:[{[cv]:ce,[cu]:[{[cv]:cf,[cu]:[aW,aX,{[cv]:ci,[cu]:[aY,{[cv]:cj,[cu]:[aZ,{[cv]:cl,[cu]:[{[cv]:bG,[cu]:[{[cv]:cm,[cu]:[{[cv]:cn,[cu]:[{[cv]:[{[cw]:h,[cx]:[bb,I2]}],error:"Invalid ARN: Missing account id",[ct]:f},{[cv]:co,[cu]:[{[cv]:cp,[cu]:[{[cv]:bC,endpoint:{[cA]:M2,[cB]:bc,[cH]:al},[ct]:n2},{[cv]:cq,endpoint:{[cA]:"https://{accessPointName}-{bucketArn#accountId}.s3-object-lambda-fips.{bucketArn#region}.{bucketPartition#dnsSuffix}",[cB]:bc,[cH]:al},[ct]:n2},{endpoint:{[cA]:"https://{accessPointName}-{bucketArn#accountId}.s3-object-lambda.{bucketArn#region}.{bucketPartition#dnsSuffix}",[cB]:bc,[cH]:al},[ct]:n2}],[ct]:o},bd],[ct]:o},be],[ct]:o},bf],[ct]:o},bg],[ct]:o}],[ct]:o}],[ct]:o},bh],[ct]:o},{error:"Invalid ARN: bucket ARN is missing a region",[ct]:f}],[ct]:o},bi],[ct]:o},{error:"Invalid ARN: Object Lambda ARNs only support `accesspoint` arn types, but found: `{arnType}`",[ct]:f}],[ct]:o},{[cv]:ce,[cu]:[{[cv]:cf,[cu]:[{[cv]:ci,[cu]:[{[cv]:ce,[cu]:[{[cv]:ci,[cu]:[aY,{[cv]:cj,[cu]:[aZ,{[cv]:cl,[cu]:[{[cv]:bG,[cu]:[{[cv]:[{[cw]:h,[cx]:[ba,"{partitionResult#name}"]}],[cu]:[{[cv]:cn,[cu]:[{[cv]:[{[cw]:h,[cx]:[aU,B]}],[cu]:[{[cv]:co,[cu]:[{[cv]:cp,[cu]:[{[cv]:bB,error:"Access Points do not support S3 Accelerate",[ct]:f},{[cv]:bH,endpoint:{[cA]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint-fips.dualstack.{bucketArn#region}.{bucketPartition#dnsSuffix}",[cB]:bj,[cH]:al},[ct]:n2},{[cv]:bI,endpoint:{[cA]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint-fips.{bucketArn#region}.{bucketPartition#dnsSuffix}",[cB]:bj,[cH]:al},[ct]:n2},{[cv]:bJ,endpoint:{[cA]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint.dualstack.{bucketArn#region}.{bucketPartition#dnsSuffix}",[cB]:bj,[cH]:al},[ct]:n2},{[cv]:[as,ar,Z,ag],endpoint:{[cA]:M2,[cB]:bj,[cH]:al},[ct]:n2},{[cv]:bK,endpoint:{[cA]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint.{bucketArn#region}.{bucketPartition#dnsSuffix}",[cB]:bj,[cH]:al},[ct]:n2}],[ct]:o},bd],[ct]:o},be],[ct]:o},{error:"Invalid ARN: The ARN was not for the S3 service, found: {bucketArn#service}",[ct]:f}],[ct]:o},bf],[ct]:o},bg],[ct]:o}],[ct]:o}],[ct]:o},bh],[ct]:o}],[ct]:o}],[ct]:o},{[cv]:[{[cw]:y,[cx]:[aV,c]}],[cu]:[{[cv]:ch3,error:"S3 MRAP does not support dual-stack",[ct]:f},{[cv]:cq,error:"S3 MRAP does not support FIPS",[ct]:f},{[cv]:bB,error:"S3 MRAP does not support S3 Accelerate",[ct]:f},{[cv]:[{[cw]:e2,[cx]:[{[cy]:"DisableMultiRegionAccessPoints"},c]}],error:"Invalid configuration: Multi-Region Access Point ARNs are disabled.",[ct]:f},{[cv]:[{[cw]:g,[cx]:by,[cz]:N2}],[cu]:[{[cv]:[{[cw]:h,[cx]:[{[cw]:i2,[cx]:[{[cy]:N2},j]},{[cw]:i2,[cx]:[aS,"partition"]}]}],[cu]:[{endpoint:{[cA]:"https://{accessPointName}.accesspoint.s3-global.{mrapPartition#dnsSuffix}",[cB]:{[cD]:[{[cE]:c,name:z,[cF]:B,[cI]:cb}]},[cH]:al},[ct]:n2}],[ct]:o},{error:"Client was configured for partition `{mrapPartition#name}` but bucket referred to partition `{bucketArn#partition}`",[ct]:f}],[ct]:o}],[ct]:o},{error:"Invalid Access Point Name",[ct]:f}],[ct]:o},bi],[ct]:o},{[cv]:[{[cw]:h,[cx]:[aU,A]}],[cu]:[{[cv]:ch3,error:"S3 Outposts does not support Dual-stack",[ct]:f},{[cv]:cq,error:"S3 Outposts does not support FIPS",[ct]:f},{[cv]:bB,error:"S3 Outposts does not support S3 Accelerate",[ct]:f},{[cv]:[{[cw]:d3,[cx]:[{[cw]:i2,[cx]:[aS,"resourceId[4]"]}]}],error:"Invalid Arn: Outpost Access Point ARN contains sub resources",[ct]:f},{[cv]:[{[cw]:i2,[cx]:cg,[cz]:x2}],[cu]:[{[cv]:bZ,[cu]:[aZ,{[cv]:cl,[cu]:[{[cv]:bG,[cu]:[{[cv]:cm,[cu]:[{[cv]:cn,[cu]:[{[cv]:co,[cu]:[{[cv]:[{[cw]:i2,[cx]:ck,[cz]:O}],[cu]:[{[cv]:[{[cw]:i2,[cx]:[aS,"resourceId[3]"],[cz]:L3}],[cu]:[{[cv]:[{[cw]:h,[cx]:[{[cy]:O},K]}],[cu]:[{[cv]:bC,endpoint:{[cA]:"https://{accessPointName}-{bucketArn#accountId}.{outpostId}.{url#authority}",[cB]:bk,[cH]:al},[ct]:n2},{endpoint:{[cA]:"https://{accessPointName}-{bucketArn#accountId}.{outpostId}.s3-outposts.{bucketArn#region}.{bucketPartition#dnsSuffix}",[cB]:bk,[cH]:al},[ct]:n2}],[ct]:o},{error:"Expected an outpost type `accesspoint`, found {outpostType}",[ct]:f}],[ct]:o},{error:"Invalid ARN: expected an access point name",[ct]:f}],[ct]:o},{error:"Invalid ARN: Expected a 4-component resource",[ct]:f}],[ct]:o},be],[ct]:o},bf],[ct]:o},bg],[ct]:o}],[ct]:o}],[ct]:o},{error:"Invalid ARN: The outpost Id may only contain a-z, A-Z, 0-9 and `-`. Found: `{outpostId}`",[ct]:f}],[ct]:o},{error:"Invalid ARN: The Outpost Id was not set",[ct]:f}],[ct]:o},{error:"Invalid ARN: Unrecognized format: {Bucket} (type: {arnType})",[ct]:f}],[ct]:o},{error:"Invalid ARN: No ARN type specified",[ct]:f}],[ct]:o},{[cv]:[{[cw]:k,[cx]:[ad,0,4,b],[cz]:P2},{[cw]:h,[cx]:[{[cy]:P2},"arn:"]},{[cw]:r3,[cx]:[{[cw]:d3,[cx]:[bl]}]}],error:"Invalid ARN: `{Bucket}` was not a valid ARN",[ct]:f},{[cv]:[{[cw]:e2,[cx]:[az,c]},bl],error:"Path-style addressing cannot be used with ARN buckets",[ct]:f},{[cv]:bE,[cu]:[{[cv]:bG,[cu]:[{[cv]:[aA],[cu]:[{[cv]:[Y,aq,X,aB],endpoint:{[cA]:"https://s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[cB]:aC,[cH]:al},[ct]:n2},{[cv]:[Y,aq,X,aD,aE],[cu]:[{endpoint:bm,[ct]:n2}],[ct]:o},{[cv]:[Y,aq,X,aD,aH],endpoint:bm,[ct]:n2},{[cv]:[ar,aq,X,aB],endpoint:{[cA]:"https://s3-fips.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[cB]:aC,[cH]:al},[ct]:n2},{[cv]:[ar,aq,X,aD,aE],[cu]:[{endpoint:bn,[ct]:n2}],[ct]:o},{[cv]:[ar,aq,X,aD,aH],endpoint:bn,[ct]:n2},{[cv]:[Y,aq,as,aB],endpoint:{[cA]:"https://s3.dualstack.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[cB]:aC,[cH]:al},[ct]:n2},{[cv]:[Y,aq,as,aD,aE],[cu]:[{endpoint:bo,[ct]:n2}],[ct]:o},{[cv]:[Y,aq,as,aD,aH],endpoint:bo,[ct]:n2},{[cv]:[ar,Z,ag,as,aB],endpoint:{[cA]:Q,[cB]:aC,[cH]:al},[ct]:n2},{[cv]:[ar,Z,ag,as,aD,aE],[cu]:[{[cv]:cd,endpoint:bp,[ct]:n2},{endpoint:bp,[ct]:n2}],[ct]:o},{[cv]:[ar,Z,ag,as,aD,aH],endpoint:bp,[ct]:n2},{[cv]:[ar,aq,as,aB],endpoint:{[cA]:R,[cB]:aC,[cH]:al},[ct]:n2},{[cv]:[ar,aq,as,aD,aE],[cu]:[{[cv]:cd,endpoint:{[cA]:R,[cB]:aG,[cH]:al},[ct]:n2},{endpoint:bq,[ct]:n2}],[ct]:o},{[cv]:[ar,aq,as,aD,aH],endpoint:bq,[ct]:n2}],[ct]:o},{error:"Path-style addressing cannot be used with S3 Accelerate",[ct]:f}],[ct]:o}],[ct]:o}],[ct]:o},{[cv]:[{[cw]:d3,[cx]:[br]},{[cw]:e2,[cx]:[br,c]}],[cu]:[{[cv]:bG,[cu]:[{[cv]:cr,[cu]:[aW,aX,{[cv]:bC,endpoint:{[cA]:t8,[cB]:bs,[cH]:al},[ct]:n2},{[cv]:cq,endpoint:{[cA]:"https://s3-object-lambda-fips.{Region}.{partitionResult#dnsSuffix}",[cB]:bs,[cH]:al},[ct]:n2},{endpoint:{[cA]:"https://s3-object-lambda.{Region}.{partitionResult#dnsSuffix}",[cB]:bs,[cH]:al},[ct]:n2}],[ct]:o},aR],[ct]:o}],[ct]:o},{[cv]:[au],[cu]:[{[cv]:bG,[cu]:[{[cv]:cr,[cu]:[{[cv]:[X,Y,aq,aB],endpoint:{[cA]:"https://s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}",[cB]:aC,[cH]:al},[ct]:n2},{[cv]:[X,Y,aq,aD,aE],[cu]:[{endpoint:bt,[ct]:n2}],[ct]:o},{[cv]:[X,Y,aq,aD,aH],endpoint:bt,[ct]:n2},{[cv]:[X,ar,aq,aB],endpoint:{[cA]:"https://s3-fips.us-east-1.{partitionResult#dnsSuffix}",[cB]:aC,[cH]:al},[ct]:n2},{[cv]:[X,ar,aq,aD,aE],[cu]:[{endpoint:bu,[ct]:n2}],[ct]:o},{[cv]:[X,ar,aq,aD,aH],endpoint:bu,[ct]:n2},{[cv]:[as,Y,aq,aB],endpoint:{[cA]:"https://s3.dualstack.us-east-1.{partitionResult#dnsSuffix}",[cB]:aC,[cH]:al},[ct]:n2},{[cv]:[as,Y,aq,aD,aE],[cu]:[{endpoint:bv,[ct]:n2}],[ct]:o},{[cv]:[as,Y,aq,aD,aH],endpoint:bv,[ct]:n2},{[cv]:[as,ar,Z,ag,aB],endpoint:{[cA]:t8,[cB]:aC,[cH]:al},[ct]:n2},{[cv]:[as,ar,Z,ag,aD,aE],[cu]:[{[cv]:cd,endpoint:bw,[ct]:n2},{endpoint:bw,[ct]:n2}],[ct]:o},{[cv]:[as,ar,Z,ag,aD,aH],endpoint:bw,[ct]:n2},{[cv]:[as,ar,aq,aB],endpoint:{[cA]:S,[cB]:aC,[cH]:al},[ct]:n2},{[cv]:[as,ar,aq,aD,aE],[cu]:[{[cv]:cd,endpoint:{[cA]:S,[cB]:aG,[cH]:al},[ct]:n2},{endpoint:bx,[ct]:n2}],[ct]:o},{[cv]:[as,ar,aq,aD,aH],endpoint:bx,[ct]:n2}],[ct]:o},aR],[ct]:o}],[ct]:o}],[ct]:o},{error:"A region must be set when sending requests to S3.",[ct]:f}]};ruleSet=_data;cache=new EndpointCache2({size:50,params:["Accelerate","Bucket","DisableAccessPoints","DisableMultiRegionAccessPoints","DisableS3ExpressSessionAuth","Endpoint","ForcePathStyle","Region","UseArnRegion","UseDualStack","UseFIPS","UseGlobalEndpoint","UseObjectLambdaEndpoint","UseS3ExpressControlEndpoint"]});defaultEndpointResolver=(endpointParams,context2={})=>cache.get(endpointParams,()=>resolveEndpoint2(ruleSet,{endpointParams,logger:context2.logger}));customEndpointFunctions2.aws=awsEndpointFunctions;createEndpointRuleSetHttpAuthSchemeParametersProvider=defaultHttpAuthSchemeParametersProvider=>async(config,context2,input)=>{var _a13,_b6,_c3;if(!input)throw new Error("Could not find `input` for `defaultEndpointRuleSetHttpAuthSchemeParametersProvider`");const defaultParameters=await defaultHttpAuthSchemeParametersProvider(config,context2,input),instructionsFn=null==(_c3=null==(_b6=null==(_a13=getSmithyContext2(context2))?void 0:_a13.commandInstance)?void 0:_b6.constructor)?void 0:_c3.getEndpointParameterInstructions;if(!instructionsFn)throw new Error(`getEndpointParameterInstructions() is not defined on '${context2.commandName}'`);const endpointParameters=await resolveParams2(input,{getEndpointParameterInstructions:instructionsFn},config);return Object.assign(defaultParameters,endpointParameters)};_defaultS3HttpAuthSchemeParametersProvider=async(config,context2,input)=>({operation:getSmithyContext2(context2).operation,region:await normalizeProvider3(config.region)()||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()});defaultS3HttpAuthSchemeParametersProvider=createEndpointRuleSetHttpAuthSchemeParametersProvider(_defaultS3HttpAuthSchemeParametersProvider);createEndpointRuleSetHttpAuthSchemeProvider=(defaultEndpointResolver2,defaultHttpAuthSchemeResolver,createHttpAuthOptionFunctions)=>authParameters=>{var _a13;const endpoint=defaultEndpointResolver2(authParameters),authSchemes=null==(_a13=endpoint.properties)?void 0:_a13.authSchemes;if(!authSchemes)return defaultHttpAuthSchemeResolver(authParameters);const options=[];for(const scheme of authSchemes){const{name:resolvedName,properties={},...rest}=scheme,name=resolvedName.toLowerCase();resolvedName!==name&&console.warn(`HttpAuthScheme has been normalized with lowercasing: '${resolvedName}' to '${name}'`);let schemeId;if("sigv4a"===name){schemeId="aws.auth#sigv4a";const sigv4Present=authSchemes.find(s2=>{const name2=s2.name.toLowerCase();return"sigv4a"!==name2&&name2.startsWith("sigv4")});if("none"===SignatureV4MultiRegion.sigv4aDependency()&&sigv4Present)continue}else{if(!name.startsWith("sigv4"))throw new Error(`Unknown HttpAuthScheme found in '@smithy.rules#endpointRuleSet': '${name}'`);schemeId="aws.auth#sigv4"}const createOption=createHttpAuthOptionFunctions[schemeId];if(!createOption)throw new Error(`Could not find HttpAuthOption create function for '${schemeId}'`);const option=createOption(authParameters);option.schemeId=schemeId;option.signingProperties={...option.signingProperties||{},...rest,...properties};options.push(option)}return options};_defaultS3HttpAuthSchemeProvider=authParameters=>{const options=[];switch(authParameters.operation){default:options.push(createAwsAuthSigv4HttpAuthOption(authParameters));options.push(createAwsAuthSigv4aHttpAuthOption(authParameters))}return options};defaultS3HttpAuthSchemeProvider=createEndpointRuleSetHttpAuthSchemeProvider(defaultEndpointResolver,_defaultS3HttpAuthSchemeProvider,{"aws.auth#sigv4":createAwsAuthSigv4HttpAuthOption,"aws.auth#sigv4a":createAwsAuthSigv4aHttpAuthOption});resolveHttpAuthSchemeConfig=config=>{var _a13;const config_0=resolveAwsSdkSigV4Config(config),config_1=resolveAwsSdkSigV4AConfig(config_0);return Object.assign(config_1,{authSchemePreference:normalizeProvider3(null!=(_a13=config.authSchemePreference)?_a13:[])})};resolveClientEndpointParameters=options=>{var _a13,_b6,_c3,_d2,_e2,_f,_g;return Object.assign(options,{useFipsEndpoint:null!=(_a13=options.useFipsEndpoint)&&_a13,useDualstackEndpoint:null!=(_b6=options.useDualstackEndpoint)&&_b6,forcePathStyle:null!=(_c3=options.forcePathStyle)&&_c3,useAccelerateEndpoint:null!=(_d2=options.useAccelerateEndpoint)&&_d2,useGlobalEndpoint:null!=(_e2=options.useGlobalEndpoint)&&_e2,disableMultiregionAccessPoints:null!=(_f=options.disableMultiregionAccessPoints)&&_f,defaultSigningName:"s3",clientContextParams:null!=(_g=options.clientContextParams)?_g:{}})};commonParams={ForcePathStyle:{type:"clientContextParams",name:"forcePathStyle"},UseArnRegion:{type:"clientContextParams",name:"useArnRegion"},DisableMultiRegionAccessPoints:{type:"clientContextParams",name:"disableMultiregionAccessPoints"},Accelerate:{type:"clientContextParams",name:"useAccelerateEndpoint"},DisableS3ExpressSessionAuth:{type:"clientContextParams",name:"disableS3ExpressSessionAuth"},UseGlobalEndpoint:{type:"builtInParams",name:"useGlobalEndpoint"},UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}};S3ServiceException=class _S3ServiceException extends ServiceException{constructor(options){super(options);Object.setPrototypeOf(this,_S3ServiceException.prototype)}};NoSuchUpload=class _NoSuchUpload extends S3ServiceException{constructor(opts){super({name:"NoSuchUpload",$fault:"client",...opts});__publicField(this,"name","NoSuchUpload");__publicField(this,"$fault","client");Object.setPrototypeOf(this,_NoSuchUpload.prototype)}};AccessDenied=class _AccessDenied extends S3ServiceException{constructor(opts){super({name:"AccessDenied",$fault:"client",...opts});__publicField(this,"name","AccessDenied");__publicField(this,"$fault","client");Object.setPrototypeOf(this,_AccessDenied.prototype)}};ObjectNotInActiveTierError=class _ObjectNotInActiveTierError extends S3ServiceException{constructor(opts){super({name:"ObjectNotInActiveTierError",$fault:"client",...opts});__publicField(this,"name","ObjectNotInActiveTierError");__publicField(this,"$fault","client");Object.setPrototypeOf(this,_ObjectNotInActiveTierError.prototype)}};BucketAlreadyExists=class _BucketAlreadyExists extends S3ServiceException{constructor(opts){super({name:"BucketAlreadyExists",$fault:"client",...opts});__publicField(this,"name","BucketAlreadyExists");__publicField(this,"$fault","client");Object.setPrototypeOf(this,_BucketAlreadyExists.prototype)}};BucketAlreadyOwnedByYou=class _BucketAlreadyOwnedByYou extends S3ServiceException{constructor(opts){super({name:"BucketAlreadyOwnedByYou",$fault:"client",...opts});__publicField(this,"name","BucketAlreadyOwnedByYou");__publicField(this,"$fault","client");Object.setPrototypeOf(this,_BucketAlreadyOwnedByYou.prototype)}};NoSuchBucket=class _NoSuchBucket extends S3ServiceException{constructor(opts){super({name:"NoSuchBucket",$fault:"client",...opts});__publicField(this,"name","NoSuchBucket");__publicField(this,"$fault","client");Object.setPrototypeOf(this,_NoSuchBucket.prototype)}};InvalidObjectState=class _InvalidObjectState extends S3ServiceException{constructor(opts){super({name:"InvalidObjectState",$fault:"client",...opts});__publicField(this,"name","InvalidObjectState");__publicField(this,"$fault","client");__publicField(this,"StorageClass");__publicField(this,"AccessTier");Object.setPrototypeOf(this,_InvalidObjectState.prototype);this.StorageClass=opts.StorageClass;this.AccessTier=opts.AccessTier}};NoSuchKey=class _NoSuchKey extends S3ServiceException{constructor(opts){super({name:"NoSuchKey",$fault:"client",...opts});__publicField(this,"name","NoSuchKey");__publicField(this,"$fault","client");Object.setPrototypeOf(this,_NoSuchKey.prototype)}};NotFound=class _NotFound extends S3ServiceException{constructor(opts){super({name:"NotFound",$fault:"client",...opts});__publicField(this,"name","NotFound");__publicField(this,"$fault","client");Object.setPrototypeOf(this,_NotFound.prototype)}};EncryptionTypeMismatch=class _EncryptionTypeMismatch extends S3ServiceException{constructor(opts){super({name:"EncryptionTypeMismatch",$fault:"client",...opts});__publicField(this,"name","EncryptionTypeMismatch");__publicField(this,"$fault","client");Object.setPrototypeOf(this,_EncryptionTypeMismatch.prototype)}};InvalidRequest=class _InvalidRequest extends S3ServiceException{constructor(opts){super({name:"InvalidRequest",$fault:"client",...opts});__publicField(this,"name","InvalidRequest");__publicField(this,"$fault","client");Object.setPrototypeOf(this,_InvalidRequest.prototype)}};InvalidWriteOffset=class _InvalidWriteOffset extends S3ServiceException{constructor(opts){super({name:"InvalidWriteOffset",$fault:"client",...opts});__publicField(this,"name","InvalidWriteOffset");__publicField(this,"$fault","client");Object.setPrototypeOf(this,_InvalidWriteOffset.prototype)}};TooManyParts=class _TooManyParts extends S3ServiceException{constructor(opts){super({name:"TooManyParts",$fault:"client",...opts});__publicField(this,"name","TooManyParts");__publicField(this,"$fault","client");Object.setPrototypeOf(this,_TooManyParts.prototype)}};IdempotencyParameterMismatch=class _IdempotencyParameterMismatch extends S3ServiceException{constructor(opts){super({name:"IdempotencyParameterMismatch",$fault:"client",...opts});__publicField(this,"name","IdempotencyParameterMismatch");__publicField(this,"$fault","client");Object.setPrototypeOf(this,_IdempotencyParameterMismatch.prototype)}};ObjectAlreadyInActiveTierError=class _ObjectAlreadyInActiveTierError extends S3ServiceException{constructor(opts){super({name:"ObjectAlreadyInActiveTierError",$fault:"client",...opts});__publicField(this,"name","ObjectAlreadyInActiveTierError");__publicField(this,"$fault","client");Object.setPrototypeOf(this,_ObjectAlreadyInActiveTierError.prototype)}};_A="Account";_AAO="AnalyticsAndOperator";_AC="AccelerateConfiguration";_ACL="AccessControlList";_ACL_="ACL";_ACLn="AnalyticsConfigurationList";_ACP="AccessControlPolicy";_ACT="AccessControlTranslation";_ACn="AnalyticsConfiguration";_AD="AccessDenied";_ADb="AbortDate";_AED="AnalyticsExportDestination";_AF="AnalyticsFilter";_AH="AllowedHeaders";_AHl="AllowedHeader";_AI="AccountId";_AIMU="AbortIncompleteMultipartUpload";_AKI="AccessKeyId";_AM="AllowedMethods";_AMU="AbortMultipartUpload";_AMUO="AbortMultipartUploadOutput";_AMUR="AbortMultipartUploadRequest";_AMl="AllowedMethod";_AO="AllowedOrigins";_AOl="AllowedOrigin";_APA="AccessPointAlias";_APAc="AccessPointArn";_AQRD="AllowQuotedRecordDelimiter";_AR="AcceptRanges";_ARI="AbortRuleId";_AS="AbacStatus";_ASBD="AnalyticsS3BucketDestination";_ASSEBD="ApplyServerSideEncryptionByDefault";_ASr="ArchiveStatus";_AT="AccessTier";_An="And";_B="Bucket";_BA="BucketArn";_BAE="BucketAlreadyExists";_BAI="BucketAccountId";_BAOBY="BucketAlreadyOwnedByYou";_BET="BlockedEncryptionTypes";_BGR="BypassGovernanceRetention";_BI="BucketInfo";_BKE="BucketKeyEnabled";_BLC="BucketLifecycleConfiguration";_BLN="BucketLocationName";_BLS="BucketLoggingStatus";_BLT="BucketLocationType";_BN="BucketNamespace";_BNu="BucketName";_BP="BytesProcessed";_BPA="BlockPublicAcls";_BPP="BlockPublicPolicy";_BR="BucketRegion";_BRy="BytesReturned";_BS="BytesScanned";_Bo="Body";_Bu="Buckets";_C="Checksum";_CA="ChecksumAlgorithm";_CACL="CannedACL";_CB="CreateBucket";_CBC="CreateBucketConfiguration";_CBMC="CreateBucketMetadataConfiguration";_CBMCR="CreateBucketMetadataConfigurationRequest";_CBMTC="CreateBucketMetadataTableConfiguration";_CBMTCR="CreateBucketMetadataTableConfigurationRequest";_CBO="CreateBucketOutput";_CBR="CreateBucketRequest";_CC="CacheControl";_CCRC="ChecksumCRC32";_CCRCC="ChecksumCRC32C";_CCRCNVME="ChecksumCRC64NVME";_CC_="Cache-Control";_CD="CreationDate";_CD_="Content-Disposition";_CDo="ContentDisposition";_CE="ContinuationEvent";_CE_="Content-Encoding";_CEo="ContentEncoding";_CF="CloudFunction";_CFC="CloudFunctionConfiguration";_CL="ContentLanguage";_CL_="Content-Language";_CL__="Content-Length";_CLo="ContentLength";_CM="Content-MD5";_CMD="ContentMD5";_CMU="CompletedMultipartUpload";_CMUO="CompleteMultipartUploadOutput";_CMUOr="CreateMultipartUploadOutput";_CMUR="CompleteMultipartUploadResult";_CMURo="CompleteMultipartUploadRequest";_CMURr="CreateMultipartUploadRequest";_CMUo="CompleteMultipartUpload";_CMUr="CreateMultipartUpload";_CMh="ChecksumMode";_CO="CopyObject";_COO="CopyObjectOutput";_COR="CopyObjectResult";_CORSC="CORSConfiguration";_CORSR="CORSRules";_CORSRu="CORSRule";_CORo="CopyObjectRequest";_CP="CommonPrefix";_CPL="CommonPrefixList";_CPLo="CompletedPartList";_CPR="CopyPartResult";_CPo="CompletedPart";_CPom="CommonPrefixes";_CR="ContentRange";_CRSBA="ConfirmRemoveSelfBucketAccess";_CR_="Content-Range";_CS="CopySource";_CSHA="ChecksumSHA1";_CSHAh="ChecksumSHA256";_CSIM="CopySourceIfMatch";_CSIMS="CopySourceIfModifiedSince";_CSINM="CopySourceIfNoneMatch";_CSIUS="CopySourceIfUnmodifiedSince";_CSO="CreateSessionOutput";_CSR="CreateSessionResult";_CSRo="CopySourceRange";_CSRr="CreateSessionRequest";_CSSSECA="CopySourceSSECustomerAlgorithm";_CSSSECK="CopySourceSSECustomerKey";_CSSSECKMD="CopySourceSSECustomerKeyMD5";_CSV="CSV";_CSVI="CopySourceVersionId";_CSVIn="CSVInput";_CSVO="CSVOutput";_CSo="ConfigurationState";_CSr="CreateSession";_CT="ChecksumType";_CT_="Content-Type";_CTl="ClientToken";_CTo="ContentType";_CTom="CompressionType";_CTon="ContinuationToken";_Co="Condition";_Cod="Code";_Com="Comments";_Con="Contents";_Cont="Cont";_Cr="Credentials";_D="Days";_DAI="DaysAfterInitiation";_DB="DeleteBucket";_DBAC="DeleteBucketAnalyticsConfiguration";_DBACR="DeleteBucketAnalyticsConfigurationRequest";_DBC="DeleteBucketCors";_DBCR="DeleteBucketCorsRequest";_DBE="DeleteBucketEncryption";_DBER="DeleteBucketEncryptionRequest";_DBIC="DeleteBucketInventoryConfiguration";_DBICR="DeleteBucketInventoryConfigurationRequest";_DBITC="DeleteBucketIntelligentTieringConfiguration";_DBITCR="DeleteBucketIntelligentTieringConfigurationRequest";_DBL="DeleteBucketLifecycle";_DBLR="DeleteBucketLifecycleRequest";_DBMC="DeleteBucketMetadataConfiguration";_DBMCR="DeleteBucketMetadataConfigurationRequest";_DBMCRe="DeleteBucketMetricsConfigurationRequest";_DBMCe="DeleteBucketMetricsConfiguration";_DBMTC="DeleteBucketMetadataTableConfiguration";_DBMTCR="DeleteBucketMetadataTableConfigurationRequest";_DBOC="DeleteBucketOwnershipControls";_DBOCR="DeleteBucketOwnershipControlsRequest";_DBP="DeleteBucketPolicy";_DBPR="DeleteBucketPolicyRequest";_DBR="DeleteBucketRequest";_DBRR="DeleteBucketReplicationRequest";_DBRe="DeleteBucketReplication";_DBT="DeleteBucketTagging";_DBTR="DeleteBucketTaggingRequest";_DBW="DeleteBucketWebsite";_DBWR="DeleteBucketWebsiteRequest";_DE="DataExport";_DIM="DestinationIfMatch";_DIMS="DestinationIfModifiedSince";_DINM="DestinationIfNoneMatch";_DIUS="DestinationIfUnmodifiedSince";_DM="DeleteMarker";_DME="DeleteMarkerEntry";_DMR="DeleteMarkerReplication";_DMVI="DeleteMarkerVersionId";_DMe="DeleteMarkers";_DN="DisplayName";_DO="DeletedObject";_DOO="DeleteObjectOutput";_DOOe="DeleteObjectsOutput";_DOR="DeleteObjectRequest";_DORe="DeleteObjectsRequest";_DOT="DeleteObjectTagging";_DOTO="DeleteObjectTaggingOutput";_DOTR="DeleteObjectTaggingRequest";_DOe="DeletedObjects";_DOel="DeleteObject";_DOele="DeleteObjects";_DPAB="DeletePublicAccessBlock";_DPABR="DeletePublicAccessBlockRequest";_DR="DataRedundancy";_DRe="DefaultRetention";_DRel="DeleteResult";_DRes="DestinationResult";_Da="Date";_De="Delete";_Del="Deleted";_Deli="Delimiter";_Des="Destination";_Desc="Description";_Det="Details";_E="Expiration";_EA="EmailAddress";_EBC="EventBridgeConfiguration";_EBO="ExpectedBucketOwner";_EC="EncryptionConfiguration";_ECr="ErrorCode";_ED="ErrorDetails";_EDr="ErrorDocument";_EE="EndEvent";_EH="ExposeHeaders";_EHx="ExposeHeader";_EM="ErrorMessage";_EODM="ExpiredObjectDeleteMarker";_EOR="ExistingObjectReplication";_ES="ExpiresString";_ESBO="ExpectedSourceBucketOwner";_ET="EncryptionType";_ETL="EncryptionTypeList";_ETM="EncryptionTypeMismatch";_ETa="ETag";_ETn="EncodingType";_ETv="EventThreshold";_ETx="ExpressionType";_En="Encryption";_Ena="Enabled";_End="End";_Er="Errors";_Err="Error";_Ev="Events";_Eve="Event";_Ex="Expires";_Exp="Expression";_F="Filter";_FD="FieldDelimiter";_FHI="FileHeaderInfo";_FO="FetchOwner";_FR="FilterRule";_FRL="FilterRuleList";_FRi="FilterRules";_Fi="Field";_Fo="Format";_Fr="Frequency";_G="Grants";_GBA="GetBucketAbac";_GBAC="GetBucketAccelerateConfiguration";_GBACO="GetBucketAccelerateConfigurationOutput";_GBACOe="GetBucketAnalyticsConfigurationOutput";_GBACR="GetBucketAccelerateConfigurationRequest";_GBACRe="GetBucketAnalyticsConfigurationRequest";_GBACe="GetBucketAnalyticsConfiguration";_GBAO="GetBucketAbacOutput";_GBAOe="GetBucketAclOutput";_GBAR="GetBucketAbacRequest";_GBARe="GetBucketAclRequest";_GBAe="GetBucketAcl";_GBC="GetBucketCors";_GBCO="GetBucketCorsOutput";_GBCR="GetBucketCorsRequest";_GBE="GetBucketEncryption";_GBEO="GetBucketEncryptionOutput";_GBER="GetBucketEncryptionRequest";_GBIC="GetBucketInventoryConfiguration";_GBICO="GetBucketInventoryConfigurationOutput";_GBICR="GetBucketInventoryConfigurationRequest";_GBITC="GetBucketIntelligentTieringConfiguration";_GBITCO="GetBucketIntelligentTieringConfigurationOutput";_GBITCR="GetBucketIntelligentTieringConfigurationRequest";_GBL="GetBucketLocation";_GBLC="GetBucketLifecycleConfiguration";_GBLCO="GetBucketLifecycleConfigurationOutput";_GBLCR="GetBucketLifecycleConfigurationRequest";_GBLO="GetBucketLocationOutput";_GBLOe="GetBucketLoggingOutput";_GBLR="GetBucketLocationRequest";_GBLRe="GetBucketLoggingRequest";_GBLe="GetBucketLogging";_GBMC="GetBucketMetadataConfiguration";_GBMCO="GetBucketMetadataConfigurationOutput";_GBMCOe="GetBucketMetricsConfigurationOutput";_GBMCR="GetBucketMetadataConfigurationResult";_GBMCRe="GetBucketMetadataConfigurationRequest";_GBMCRet="GetBucketMetricsConfigurationRequest";_GBMCe="GetBucketMetricsConfiguration";_GBMTC="GetBucketMetadataTableConfiguration";_GBMTCO="GetBucketMetadataTableConfigurationOutput";_GBMTCR="GetBucketMetadataTableConfigurationResult";_GBMTCRe="GetBucketMetadataTableConfigurationRequest";_GBNC="GetBucketNotificationConfiguration";_GBNCR="GetBucketNotificationConfigurationRequest";_GBOC="GetBucketOwnershipControls";_GBOCO="GetBucketOwnershipControlsOutput";_GBOCR="GetBucketOwnershipControlsRequest";_GBP="GetBucketPolicy";_GBPO="GetBucketPolicyOutput";_GBPR="GetBucketPolicyRequest";_GBPS="GetBucketPolicyStatus";_GBPSO="GetBucketPolicyStatusOutput";_GBPSR="GetBucketPolicyStatusRequest";_GBR="GetBucketReplication";_GBRO="GetBucketReplicationOutput";_GBRP="GetBucketRequestPayment";_GBRPO="GetBucketRequestPaymentOutput";_GBRPR="GetBucketRequestPaymentRequest";_GBRR="GetBucketReplicationRequest";_GBT="GetBucketTagging";_GBTO="GetBucketTaggingOutput";_GBTR="GetBucketTaggingRequest";_GBV="GetBucketVersioning";_GBVO="GetBucketVersioningOutput";_GBVR="GetBucketVersioningRequest";_GBW="GetBucketWebsite";_GBWO="GetBucketWebsiteOutput";_GBWR="GetBucketWebsiteRequest";_GFC="GrantFullControl";_GJP="GlacierJobParameters";_GO="GetObject";_GOA="GetObjectAcl";_GOAO="GetObjectAclOutput";_GOAOe="GetObjectAttributesOutput";_GOAP="GetObjectAttributesParts";_GOAR="GetObjectAclRequest";_GOARe="GetObjectAttributesResponse";_GOARet="GetObjectAttributesRequest";_GOAe="GetObjectAttributes";_GOLC="GetObjectLockConfiguration";_GOLCO="GetObjectLockConfigurationOutput";_GOLCR="GetObjectLockConfigurationRequest";_GOLH="GetObjectLegalHold";_GOLHO="GetObjectLegalHoldOutput";_GOLHR="GetObjectLegalHoldRequest";_GOO="GetObjectOutput";_GOR="GetObjectRequest";_GORO="GetObjectRetentionOutput";_GORR="GetObjectRetentionRequest";_GORe="GetObjectRetention";_GOT="GetObjectTagging";_GOTO="GetObjectTaggingOutput";_GOTOe="GetObjectTorrentOutput";_GOTR="GetObjectTaggingRequest";_GOTRe="GetObjectTorrentRequest";_GOTe="GetObjectTorrent";_GPAB="GetPublicAccessBlock";_GPABO="GetPublicAccessBlockOutput";_GPABR="GetPublicAccessBlockRequest";_GR="GrantRead";_GRACP="GrantReadACP";_GW="GrantWrite";_GWACP="GrantWriteACP";_Gr="Grant";_Gra="Grantee";_HB="HeadBucket";_HBO="HeadBucketOutput";_HBR="HeadBucketRequest";_HECRE="HttpErrorCodeReturnedEquals";_HN="HostName";_HO="HeadObject";_HOO="HeadObjectOutput";_HOR="HeadObjectRequest";_HRC="HttpRedirectCode";_I="Id";_IC="InventoryConfiguration";_ICL="InventoryConfigurationList";_ID="ID";_IDn="IndexDocument";_IDnv="InventoryDestination";_IE="IsEnabled";_IEn="InventoryEncryption";_IF="InventoryFilter";_IL="IsLatest";_IM="IfMatch";_IMIT="IfMatchInitiatedTime";_IMLMT="IfMatchLastModifiedTime";_IMS="IfMatchSize";_IMS_="If-Modified-Since";_IMSf="IfModifiedSince";_IMUR="InitiateMultipartUploadResult";_IM_="If-Match";_INM="IfNoneMatch";_INM_="If-None-Match";_IOF="InventoryOptionalFields";_IOS="InvalidObjectState";_IOV="IncludedObjectVersions";_IP="IsPublic";_IPA="IgnorePublicAcls";_IPM="IdempotencyParameterMismatch";_IR="InvalidRequest";_IRIP="IsRestoreInProgress";_IS="InputSerialization";_ISBD="InventoryS3BucketDestination";_ISn="InventorySchedule";_IT="IsTruncated";_ITAO="IntelligentTieringAndOperator";_ITC="IntelligentTieringConfiguration";_ITCL="IntelligentTieringConfigurationList";_ITCR="InventoryTableConfigurationResult";_ITCU="InventoryTableConfigurationUpdates";_ITCn="InventoryTableConfiguration";_ITF="IntelligentTieringFilter";_IUS="IfUnmodifiedSince";_IUS_="If-Unmodified-Since";_IWO="InvalidWriteOffset";_In="Initiator";_Ini="Initiated";_JSON="JSON";_JSONI="JSONInput";_JSONO="JSONOutput";_JTC="JournalTableConfiguration";_JTCR="JournalTableConfigurationResult";_JTCU="JournalTableConfigurationUpdates";_K="Key";_KC="KeyCount";_KI="KeyId";_KKA="KmsKeyArn";_KM="KeyMarker";_KMSC="KMSContext";_KMSKA="KMSKeyArn";_KMSKI="KMSKeyId";_KMSMKID="KMSMasterKeyID";_KPE="KeyPrefixEquals";_L="Location";_LAMBR="ListAllMyBucketsResult";_LAMDBR="ListAllMyDirectoryBucketsResult";_LB="ListBuckets";_LBAC="ListBucketAnalyticsConfigurations";_LBACO="ListBucketAnalyticsConfigurationsOutput";_LBACR="ListBucketAnalyticsConfigurationResult";_LBACRi="ListBucketAnalyticsConfigurationsRequest";_LBIC="ListBucketInventoryConfigurations";_LBICO="ListBucketInventoryConfigurationsOutput";_LBICR="ListBucketInventoryConfigurationsRequest";_LBITC="ListBucketIntelligentTieringConfigurations";_LBITCO="ListBucketIntelligentTieringConfigurationsOutput";_LBITCR="ListBucketIntelligentTieringConfigurationsRequest";_LBMC="ListBucketMetricsConfigurations";_LBMCO="ListBucketMetricsConfigurationsOutput";_LBMCR="ListBucketMetricsConfigurationsRequest";_LBO="ListBucketsOutput";_LBR="ListBucketsRequest";_LBRi="ListBucketResult";_LC="LocationConstraint";_LCi="LifecycleConfiguration";_LDB="ListDirectoryBuckets";_LDBO="ListDirectoryBucketsOutput";_LDBR="ListDirectoryBucketsRequest";_LE="LoggingEnabled";_LEi="LifecycleExpiration";_LFA="LambdaFunctionArn";_LFC="LambdaFunctionConfiguration";_LFCL="LambdaFunctionConfigurationList";_LFCa="LambdaFunctionConfigurations";_LH="LegalHold";_LI="LocationInfo";_LICR="ListInventoryConfigurationsResult";_LM="LastModified";_LMCR="ListMetricsConfigurationsResult";_LMT="LastModifiedTime";_LMU="ListMultipartUploads";_LMUO="ListMultipartUploadsOutput";_LMUR="ListMultipartUploadsResult";_LMURi="ListMultipartUploadsRequest";_LM_="Last-Modified";_LO="ListObjects";_LOO="ListObjectsOutput";_LOR="ListObjectsRequest";_LOV="ListObjectsV2";_LOVO="ListObjectsV2Output";_LOVOi="ListObjectVersionsOutput";_LOVR="ListObjectsV2Request";_LOVRi="ListObjectVersionsRequest";_LOVi="ListObjectVersions";_LP="ListParts";_LPO="ListPartsOutput";_LPR="ListPartsResult";_LPRi="ListPartsRequest";_LR="LifecycleRule";_LRAO="LifecycleRuleAndOperator";_LRF="LifecycleRuleFilter";_LRi="LifecycleRules";_LVR="ListVersionsResult";_M="Metadata";_MAO="MetricsAndOperator";_MAS="MaxAgeSeconds";_MB="MaxBuckets";_MC="MetadataConfiguration";_MCL="MetricsConfigurationList";_MCR="MetadataConfigurationResult";_MCe="MetricsConfiguration";_MD="MetadataDirective";_MDB="MaxDirectoryBuckets";_MDf="MfaDelete";_ME="MetadataEntry";_MF="MetricsFilter";_MFA="MFA";_MFAD="MFADelete";_MK="MaxKeys";_MM="MissingMeta";_MOS="MpuObjectSize";_MP="MaxParts";_MTC="MetadataTableConfiguration";_MTCR="MetadataTableConfigurationResult";_MTEC="MetadataTableEncryptionConfiguration";_MU="MultipartUpload";_MUL="MultipartUploadList";_MUa="MaxUploads";_Ma="Marker";_Me="Metrics";_Mes="Message";_Mi="Minutes";_Mo="Mode";_N="Name";_NC="NotificationConfiguration";_NCF="NotificationConfigurationFilter";_NCT="NextContinuationToken";_ND="NoncurrentDays";_NEKKAS="NonEmptyKmsKeyArnString";_NF="NotFound";_NKM="NextKeyMarker";_NM="NextMarker";_NNV="NewerNoncurrentVersions";_NPNM="NextPartNumberMarker";_NSB="NoSuchBucket";_NSK="NoSuchKey";_NSU="NoSuchUpload";_NUIM="NextUploadIdMarker";_NVE="NoncurrentVersionExpiration";_NVIM="NextVersionIdMarker";_NVT="NoncurrentVersionTransitions";_NVTL="NoncurrentVersionTransitionList";_NVTo="NoncurrentVersionTransition";_O="Owner";_OA="ObjectAttributes";_OAIATE="ObjectAlreadyInActiveTierError";_OC="OwnershipControls";_OCR="OwnershipControlsRule";_OCRw="OwnershipControlsRules";_OE="ObjectEncryption";_OF="OptionalFields";_OI="ObjectIdentifier";_OIL="ObjectIdentifierList";_OL="OutputLocation";_OLC="ObjectLockConfiguration";_OLE="ObjectLockEnabled";_OLEFB="ObjectLockEnabledForBucket";_OLLH="ObjectLockLegalHold";_OLLHS="ObjectLockLegalHoldStatus";_OLM="ObjectLockMode";_OLR="ObjectLockRetention";_OLRUD="ObjectLockRetainUntilDate";_OLRb="ObjectLockRule";_OLb="ObjectList";_ONIATE="ObjectNotInActiveTierError";_OO="ObjectOwnership";_OOA="OptionalObjectAttributes";_OP="ObjectParts";_OPb="ObjectPart";_OS="ObjectSize";_OSGT="ObjectSizeGreaterThan";_OSLT="ObjectSizeLessThan";_OSV="OutputSchemaVersion";_OSu="OutputSerialization";_OV="ObjectVersion";_OVL="ObjectVersionList";_Ob="Objects";_Obj="Object";_P="Prefix";_PABC="PublicAccessBlockConfiguration";_PBA="PutBucketAbac";_PBAC="PutBucketAccelerateConfiguration";_PBACR="PutBucketAccelerateConfigurationRequest";_PBACRu="PutBucketAnalyticsConfigurationRequest";_PBACu="PutBucketAnalyticsConfiguration";_PBAR="PutBucketAbacRequest";_PBARu="PutBucketAclRequest";_PBAu="PutBucketAcl";_PBC="PutBucketCors";_PBCR="PutBucketCorsRequest";_PBE="PutBucketEncryption";_PBER="PutBucketEncryptionRequest";_PBIC="PutBucketInventoryConfiguration";_PBICR="PutBucketInventoryConfigurationRequest";_PBITC="PutBucketIntelligentTieringConfiguration";_PBITCR="PutBucketIntelligentTieringConfigurationRequest";_PBL="PutBucketLogging";_PBLC="PutBucketLifecycleConfiguration";_PBLCO="PutBucketLifecycleConfigurationOutput";_PBLCR="PutBucketLifecycleConfigurationRequest";_PBLR="PutBucketLoggingRequest";_PBMC="PutBucketMetricsConfiguration";_PBMCR="PutBucketMetricsConfigurationRequest";_PBNC="PutBucketNotificationConfiguration";_PBNCR="PutBucketNotificationConfigurationRequest";_PBOC="PutBucketOwnershipControls";_PBOCR="PutBucketOwnershipControlsRequest";_PBP="PutBucketPolicy";_PBPR="PutBucketPolicyRequest";_PBR="PutBucketReplication";_PBRP="PutBucketRequestPayment";_PBRPR="PutBucketRequestPaymentRequest";_PBRR="PutBucketReplicationRequest";_PBT="PutBucketTagging";_PBTR="PutBucketTaggingRequest";_PBV="PutBucketVersioning";_PBVR="PutBucketVersioningRequest";_PBW="PutBucketWebsite";_PBWR="PutBucketWebsiteRequest";_PC="PartsCount";_PDS="PartitionDateSource";_PE="ProgressEvent";_PI="ParquetInput";_PL="PartsList";_PN="PartNumber";_PNM="PartNumberMarker";_PO="PutObject";_POA="PutObjectAcl";_POAO="PutObjectAclOutput";_POAR="PutObjectAclRequest";_POLC="PutObjectLockConfiguration";_POLCO="PutObjectLockConfigurationOutput";_POLCR="PutObjectLockConfigurationRequest";_POLH="PutObjectLegalHold";_POLHO="PutObjectLegalHoldOutput";_POLHR="PutObjectLegalHoldRequest";_POO="PutObjectOutput";_POR="PutObjectRequest";_PORO="PutObjectRetentionOutput";_PORR="PutObjectRetentionRequest";_PORu="PutObjectRetention";_POT="PutObjectTagging";_POTO="PutObjectTaggingOutput";_POTR="PutObjectTaggingRequest";_PP="PartitionedPrefix";_PPAB="PutPublicAccessBlock";_PPABR="PutPublicAccessBlockRequest";_PS="PolicyStatus";_Pa="Parts";_Par="Part";_Parq="Parquet";_Pay="Payer";_Payl="Payload";_Pe="Permission";_Po="Policy";_Pr="Progress";_Pri="Priority";_Pro="Protocol";_Q="Quiet";_QA="QueueArn";_QC="QuoteCharacter";_QCL="QueueConfigurationList";_QCu="QueueConfigurations";_QCue="QueueConfiguration";_QEC="QuoteEscapeCharacter";_QF="QuoteFields";_Qu="Queue";_R="Rules";_RART="RedirectAllRequestsTo";_RC="RequestCharged";_RCC="ResponseCacheControl";_RCD="ResponseContentDisposition";_RCE="ResponseContentEncoding";_RCL="ResponseContentLanguage";_RCT="ResponseContentType";_RCe="ReplicationConfiguration";_RD="RecordDelimiter";_RE="ResponseExpires";_RED="RestoreExpiryDate";_REe="RecordExpiration";_REec="RecordsEvent";_RKKID="ReplicaKmsKeyID";_RKPW="ReplaceKeyPrefixWith";_RKW="ReplaceKeyWith";_RM="ReplicaModifications";_RO="RenameObject";_ROO="RenameObjectOutput";_ROOe="RestoreObjectOutput";_ROP="RestoreOutputPath";_ROR="RenameObjectRequest";_RORe="RestoreObjectRequest";_ROe="RestoreObject";_RP="RequestPayer";_RPB="RestrictPublicBuckets";_RPC="RequestPaymentConfiguration";_RPe="RequestProgress";_RR="RoutingRules";_RRAO="ReplicationRuleAndOperator";_RRF="ReplicationRuleFilter";_RRe="ReplicationRule";_RRep="ReplicationRules";_RReq="RequestRoute";_RRes="RestoreRequest";_RRo="RoutingRule";_RS="ReplicationStatus";_RSe="RestoreStatus";_RSen="RenameSource";_RT="ReplicationTime";_RTV="ReplicationTimeValue";_RTe="RequestToken";_RUD="RetainUntilDate";_Ra="Range";_Re="Restore";_Rec="Records";_Red="Redirect";_Ret="Retention";_Ro="Role";_Ru="Rule";_S="Status";_SA="StartAfter";_SAK="SecretAccessKey";_SAs="SseAlgorithm";_SB="StreamingBlob";_SBD="S3BucketDestination";_SC="StorageClass";_SCA="StorageClassAnalysis";_SCADE="StorageClassAnalysisDataExport";_SCV="SessionCredentialValue";_SCe="SessionCredentials";_SCt="StatusCode";_SDV="SkipDestinationValidation";_SE="StatsEvent";_SIM="SourceIfMatch";_SIMS="SourceIfModifiedSince";_SINM="SourceIfNoneMatch";_SIUS="SourceIfUnmodifiedSince";_SK="SSE-KMS";_SKEO="SseKmsEncryptedObjects";_SKF="S3KeyFilter";_SKe="S3Key";_SL="S3Location";_SM="SessionMode";_SOC="SelectObjectContent";_SOCES="SelectObjectContentEventStream";_SOCO="SelectObjectContentOutput";_SOCR="SelectObjectContentRequest";_SP="SelectParameters";_SPi="SimplePrefix";_SR="ScanRange";_SS="SSE-S3";_SSC="SourceSelectionCriteria";_SSE="ServerSideEncryption";_SSEA="SSEAlgorithm";_SSEBD="ServerSideEncryptionByDefault";_SSEC="ServerSideEncryptionConfiguration";_SSECA="SSECustomerAlgorithm";_SSECK="SSECustomerKey";_SSECKMD="SSECustomerKeyMD5";_SSEKMS="SSEKMS";_SSEKMSE="SSEKMSEncryption";_SSEKMSEC="SSEKMSEncryptionContext";_SSEKMSKI="SSEKMSKeyId";_SSER="ServerSideEncryptionRule";_SSERe="ServerSideEncryptionRules";_SSES="SSES3";_ST="SessionToken";_STD="S3TablesDestination";_STDR="S3TablesDestinationResult";_S_="S3";_Sc="Schedule";_Si="Size";_St="Start";_Sta="Stats";_Su="Suffix";_T="Tags";_TA="TableArn";_TAo="TopicArn";_TB="TargetBucket";_TBA="TableBucketArn";_TBT="TableBucketType";_TC="TagCount";_TCL="TopicConfigurationList";_TCo="TopicConfigurations";_TCop="TopicConfiguration";_TD="TaggingDirective";_TDMOS="TransitionDefaultMinimumObjectSize";_TG="TargetGrants";_TGa="TargetGrant";_TL="TieringList";_TLr="TransitionList";_TMP="TooManyParts";_TN="TableNamespace";_TNa="TableName";_TOKF="TargetObjectKeyFormat";_TP="TargetPrefix";_TPC="TotalPartsCount";_TS="TagSet";_TSa="TableStatus";_Ta="Tag";_Tag="Tagging";_Ti="Tier";_Tie="Tierings";_Tier="Tiering";_Tim="Time";_To="Token";_Top="Topic";_Tr="Transitions";_Tra="Transition";_Ty="Type";_U="Uploads";_UBMITC="UpdateBucketMetadataInventoryTableConfiguration";_UBMITCR="UpdateBucketMetadataInventoryTableConfigurationRequest";_UBMJTC="UpdateBucketMetadataJournalTableConfiguration";_UBMJTCR="UpdateBucketMetadataJournalTableConfigurationRequest";_UI="UploadId";_UIM="UploadIdMarker";_UM="UserMetadata";_UOE="UpdateObjectEncryption";_UOER="UpdateObjectEncryptionRequest";_UOERp="UpdateObjectEncryptionResponse";_UP="UploadPart";_UPC="UploadPartCopy";_UPCO="UploadPartCopyOutput";_UPCR="UploadPartCopyRequest";_UPO="UploadPartOutput";_UPR="UploadPartRequest";_URI="URI";_Up="Upload";_V="Value";_VC="VersioningConfiguration";_VI="VersionId";_VIM="VersionIdMarker";_Ve="Versions";_Ver="Version";_WC="WebsiteConfiguration";_WGOR="WriteGetObjectResponse";_WGORR="WriteGetObjectResponseRequest";_WOB="WriteOffsetBytes";_WRL="WebsiteRedirectLocation";_Y="Years";_ar="accept-ranges";_br="bucket-region";_c2="client";_ct="continuation-token";_d="delimiter";_e="error";_eP="eventPayload";_en="endpoint";_et="encoding-type";_fo="fetch-owner";_h="http";_hC="httpChecksum";_hE="httpError";_hH="httpHeader";_hL="hostLabel";_hP="httpPayload";_hPH="httpPrefixHeaders";_hQ="httpQuery";_hi="http://www.w3.org/2001/XMLSchema-instance";_i="id";_iT="idempotencyToken";_km="key-marker";_m="marker";_mb="max-buckets";_mdb="max-directory-buckets";_mk="max-keys";_mp="max-parts";_mu="max-uploads";_p="prefix";_pN="partNumber";_pnm="part-number-marker";_rcc="response-cache-control";_rcd="response-content-disposition";_rce="response-content-encoding";_rcl="response-content-language";_rct="response-content-type";_re="response-expires";_s="smithy.ts.sdk.synthetic.com.amazonaws.s3";_sa="start-after";_st="streaming";_uI="uploadId";_uim="upload-id-marker";_vI="versionId";_vim="version-id-marker";_x="xsi";_xA="xmlAttribute";_xF="xmlFlattened";_xN="xmlName";_xNm="xmlNamespace";_xaa="x-amz-acl";_xaad="x-amz-abort-date";_xaapa="x-amz-access-point-alias";_xaari="x-amz-abort-rule-id";_xaas="x-amz-archive-status";_xaba="x-amz-bucket-arn";_xabgr="x-amz-bypass-governance-retention";_xabln="x-amz-bucket-location-name";_xablt="x-amz-bucket-location-type";_xabn="x-amz-bucket-namespace";_xabole="x-amz-bucket-object-lock-enabled";_xabolt="x-amz-bucket-object-lock-token";_xabr="x-amz-bucket-region";_xaca="x-amz-checksum-algorithm";_xacc="x-amz-checksum-crc32";_xacc_="x-amz-checksum-crc32c";_xacc__="x-amz-checksum-crc64nvme";_xacm="x-amz-checksum-mode";_xacrsba="x-amz-confirm-remove-self-bucket-access";_xacs="x-amz-checksum-sha1";_xacs_="x-amz-checksum-sha256";_xacs__="x-amz-copy-source";_xacsim="x-amz-copy-source-if-match";_xacsims="x-amz-copy-source-if-modified-since";_xacsinm="x-amz-copy-source-if-none-match";_xacsius="x-amz-copy-source-if-unmodified-since";_xacsm="x-amz-create-session-mode";_xacsr="x-amz-copy-source-range";_xacssseca="x-amz-copy-source-server-side-encryption-customer-algorithm";_xacssseck="x-amz-copy-source-server-side-encryption-customer-key";_xacssseckM="x-amz-copy-source-server-side-encryption-customer-key-MD5";_xacsvi="x-amz-copy-source-version-id";_xact="x-amz-checksum-type";_xact_="x-amz-client-token";_xadm="x-amz-delete-marker";_xae="x-amz-expiration";_xaebo="x-amz-expected-bucket-owner";_xafec="x-amz-fwd-error-code";_xafem="x-amz-fwd-error-message";_xafhCC="x-amz-fwd-header-Cache-Control";_xafhCD="x-amz-fwd-header-Content-Disposition";_xafhCE="x-amz-fwd-header-Content-Encoding";_xafhCL="x-amz-fwd-header-Content-Language";_xafhCR="x-amz-fwd-header-Content-Range";_xafhCT="x-amz-fwd-header-Content-Type";_xafhE="x-amz-fwd-header-ETag";_xafhE_="x-amz-fwd-header-Expires";_xafhLM="x-amz-fwd-header-Last-Modified";_xafhar="x-amz-fwd-header-accept-ranges";_xafhxacc="x-amz-fwd-header-x-amz-checksum-crc32";_xafhxacc_="x-amz-fwd-header-x-amz-checksum-crc32c";_xafhxacc__="x-amz-fwd-header-x-amz-checksum-crc64nvme";_xafhxacs="x-amz-fwd-header-x-amz-checksum-sha1";_xafhxacs_="x-amz-fwd-header-x-amz-checksum-sha256";_xafhxadm="x-amz-fwd-header-x-amz-delete-marker";_xafhxae="x-amz-fwd-header-x-amz-expiration";_xafhxamm="x-amz-fwd-header-x-amz-missing-meta";_xafhxampc="x-amz-fwd-header-x-amz-mp-parts-count";_xafhxaollh="x-amz-fwd-header-x-amz-object-lock-legal-hold";_xafhxaolm="x-amz-fwd-header-x-amz-object-lock-mode";_xafhxaolrud="x-amz-fwd-header-x-amz-object-lock-retain-until-date";_xafhxar="x-amz-fwd-header-x-amz-restore";_xafhxarc="x-amz-fwd-header-x-amz-request-charged";_xafhxars="x-amz-fwd-header-x-amz-replication-status";_xafhxasc="x-amz-fwd-header-x-amz-storage-class";_xafhxasse="x-amz-fwd-header-x-amz-server-side-encryption";_xafhxasseakki="x-amz-fwd-header-x-amz-server-side-encryption-aws-kms-key-id";_xafhxassebke="x-amz-fwd-header-x-amz-server-side-encryption-bucket-key-enabled";_xafhxasseca="x-amz-fwd-header-x-amz-server-side-encryption-customer-algorithm";_xafhxasseckM="x-amz-fwd-header-x-amz-server-side-encryption-customer-key-MD5";_xafhxatc="x-amz-fwd-header-x-amz-tagging-count";_xafhxavi="x-amz-fwd-header-x-amz-version-id";_xafs="x-amz-fwd-status";_xagfc="x-amz-grant-full-control";_xagr="x-amz-grant-read";_xagra="x-amz-grant-read-acp";_xagw="x-amz-grant-write";_xagwa="x-amz-grant-write-acp";_xaimit="x-amz-if-match-initiated-time";_xaimlmt="x-amz-if-match-last-modified-time";_xaims="x-amz-if-match-size";_xam="x-amz-meta-";_xam_="x-amz-mfa";_xamd="x-amz-metadata-directive";_xamm="x-amz-missing-meta";_xamos="x-amz-mp-object-size";_xamp="x-amz-max-parts";_xampc="x-amz-mp-parts-count";_xaoa="x-amz-object-attributes";_xaollh="x-amz-object-lock-legal-hold";_xaolm="x-amz-object-lock-mode";_xaolrud="x-amz-object-lock-retain-until-date";_xaoo="x-amz-object-ownership";_xaooa="x-amz-optional-object-attributes";_xaos="x-amz-object-size";_xapnm="x-amz-part-number-marker";_xar="x-amz-restore";_xarc="x-amz-request-charged";_xarop="x-amz-restore-output-path";_xarp="x-amz-request-payer";_xarr="x-amz-request-route";_xars="x-amz-replication-status";_xars_="x-amz-rename-source";_xarsim="x-amz-rename-source-if-match";_xarsims="x-amz-rename-source-if-modified-since";_xarsinm="x-amz-rename-source-if-none-match";_xarsius="x-amz-rename-source-if-unmodified-since";_xart="x-amz-request-token";_xasc="x-amz-storage-class";_xasca="x-amz-sdk-checksum-algorithm";_xasdv="x-amz-skip-destination-validation";_xasebo="x-amz-source-expected-bucket-owner";_xasse="x-amz-server-side-encryption";_xasseakki="x-amz-server-side-encryption-aws-kms-key-id";_xassebke="x-amz-server-side-encryption-bucket-key-enabled";_xassec="x-amz-server-side-encryption-context";_xasseca="x-amz-server-side-encryption-customer-algorithm";_xasseck="x-amz-server-side-encryption-customer-key";_xasseckM="x-amz-server-side-encryption-customer-key-MD5";_xat="x-amz-tagging";_xatc="x-amz-tagging-count";_xatd="x-amz-tagging-directive";_xatdmos="x-amz-transition-default-minimum-object-size";_xavi="x-amz-version-id";_xawob="x-amz-write-offset-bytes";_xawrl="x-amz-website-redirect-location";_xs="xsi:type";n0="com.amazonaws.s3";_s_registry=TypeRegistry.for(_s);S3ServiceException$=[-3,_s,"S3ServiceException",0,[],[]];_s_registry.registerError(S3ServiceException$,S3ServiceException);n0_registry=TypeRegistry.for(n0);AccessDenied$=[-3,n0,_AD,{[_e]:_c2,[_hE]:403},[],[]];n0_registry.registerError(AccessDenied$,AccessDenied);BucketAlreadyExists$=[-3,n0,_BAE,{[_e]:_c2,[_hE]:409},[],[]];n0_registry.registerError(BucketAlreadyExists$,BucketAlreadyExists);BucketAlreadyOwnedByYou$=[-3,n0,_BAOBY,{[_e]:_c2,[_hE]:409},[],[]];n0_registry.registerError(BucketAlreadyOwnedByYou$,BucketAlreadyOwnedByYou);EncryptionTypeMismatch$=[-3,n0,_ETM,{[_e]:_c2,[_hE]:400},[],[]];n0_registry.registerError(EncryptionTypeMismatch$,EncryptionTypeMismatch);IdempotencyParameterMismatch$=[-3,n0,_IPM,{[_e]:_c2,[_hE]:400},[],[]];n0_registry.registerError(IdempotencyParameterMismatch$,IdempotencyParameterMismatch);InvalidObjectState$=[-3,n0,_IOS,{[_e]:_c2,[_hE]:403},[_SC,_AT],[0,0]];n0_registry.registerError(InvalidObjectState$,InvalidObjectState);InvalidRequest$=[-3,n0,_IR,{[_e]:_c2,[_hE]:400},[],[]];n0_registry.registerError(InvalidRequest$,InvalidRequest);InvalidWriteOffset$=[-3,n0,_IWO,{[_e]:_c2,[_hE]:400},[],[]];n0_registry.registerError(InvalidWriteOffset$,InvalidWriteOffset);NoSuchBucket$=[-3,n0,_NSB,{[_e]:_c2,[_hE]:404},[],[]];n0_registry.registerError(NoSuchBucket$,NoSuchBucket);NoSuchKey$=[-3,n0,_NSK,{[_e]:_c2,[_hE]:404},[],[]];n0_registry.registerError(NoSuchKey$,NoSuchKey);NoSuchUpload$=[-3,n0,_NSU,{[_e]:_c2,[_hE]:404},[],[]];n0_registry.registerError(NoSuchUpload$,NoSuchUpload);NotFound$=[-3,n0,_NF,{[_e]:_c2},[],[]];n0_registry.registerError(NotFound$,NotFound);ObjectAlreadyInActiveTierError$=[-3,n0,_OAIATE,{[_e]:_c2,[_hE]:403},[],[]];n0_registry.registerError(ObjectAlreadyInActiveTierError$,ObjectAlreadyInActiveTierError);ObjectNotInActiveTierError$=[-3,n0,_ONIATE,{[_e]:_c2,[_hE]:403},[],[]];n0_registry.registerError(ObjectNotInActiveTierError$,ObjectNotInActiveTierError);TooManyParts$=[-3,n0,_TMP,{[_e]:_c2,[_hE]:400},[],[]];n0_registry.registerError(TooManyParts$,TooManyParts);errorTypeRegistries=[_s_registry,n0_registry];CopySourceSSECustomerKey=[0,n0,_CSSSECK,8,0];NonEmptyKmsKeyArnString=[0,n0,_NEKKAS,8,0];SessionCredentialValue=[0,n0,_SCV,8,0];SSECustomerKey=[0,n0,_SSECK,8,0];SSEKMSEncryptionContext=[0,n0,_SSEKMSEC,8,0];SSEKMSKeyId=[0,n0,_SSEKMSKI,8,0];StreamingBlob=[0,n0,_SB,{[_st]:1},42];AbacStatus$=[3,n0,_AS,0,[_S],[0]];AbortIncompleteMultipartUpload$=[3,n0,_AIMU,0,[_DAI],[1]];AbortMultipartUploadOutput$=[3,n0,_AMUO,0,[_RC],[[0,{[_hH]:_xarc}]]];AbortMultipartUploadRequest$=[3,n0,_AMUR,0,[_B,_K,_UI,_RP,_EBO,_IMIT],[[0,1],[0,1],[0,{[_hQ]:_uI}],[0,{[_hH]:_xarp}],[0,{[_hH]:_xaebo}],[6,{[_hH]:_xaimit}]],3];AccelerateConfiguration$=[3,n0,_AC,0,[_S],[0]];AccessControlPolicy$=[3,n0,_ACP,0,[_G,_O],[[()=>Grants,{[_xN]:_ACL}],()=>Owner$]];AccessControlTranslation$=[3,n0,_ACT,0,[_O],[0],1];AnalyticsAndOperator$=[3,n0,_AAO,0,[_P,_T],[0,[()=>TagSet,{[_xF]:1,[_xN]:_Ta}]]];AnalyticsConfiguration$=[3,n0,_ACn,0,[_I,_SCA,_F],[0,()=>StorageClassAnalysis$,[()=>AnalyticsFilter$,0]],2];AnalyticsExportDestination$=[3,n0,_AED,0,[_SBD],[()=>AnalyticsS3BucketDestination$],1];AnalyticsS3BucketDestination$=[3,n0,_ASBD,0,[_Fo,_B,_BAI,_P],[0,0,0,0],2];BlockedEncryptionTypes$=[3,n0,_BET,0,[_ET],[[()=>EncryptionTypeList,{[_xF]:1}]]];Bucket$=[3,n0,_B,0,[_N,_CD,_BR,_BA],[0,4,0,0]];BucketInfo$=[3,n0,_BI,0,[_DR,_Ty],[0,0]];BucketLifecycleConfiguration$=[3,n0,_BLC,0,[_R],[[()=>LifecycleRules,{[_xF]:1,[_xN]:_Ru}]],1];BucketLoggingStatus$=[3,n0,_BLS,0,[_LE],[[()=>LoggingEnabled$,0]]];Checksum$=[3,n0,_C,0,[_CCRC,_CCRCC,_CCRCNVME,_CSHA,_CSHAh,_CT],[0,0,0,0,0,0]];CommonPrefix$=[3,n0,_CP,0,[_P],[0]];CompletedMultipartUpload$=[3,n0,_CMU,0,[_Pa],[[()=>CompletedPartList,{[_xF]:1,[_xN]:_Par}]]];CompletedPart$=[3,n0,_CPo,0,[_ETa,_CCRC,_CCRCC,_CCRCNVME,_CSHA,_CSHAh,_PN],[0,0,0,0,0,0,1]];CompleteMultipartUploadOutput$=[3,n0,_CMUO,{[_xN]:_CMUR},[_L,_B,_K,_E,_ETa,_CCRC,_CCRCC,_CCRCNVME,_CSHA,_CSHAh,_CT,_SSE,_VI,_SSEKMSKI,_BKE,_RC],[0,0,0,[0,{[_hH]:_xae}],0,0,0,0,0,0,0,[0,{[_hH]:_xasse}],[0,{[_hH]:_xavi}],[()=>SSEKMSKeyId,{[_hH]:_xasseakki}],[2,{[_hH]:_xassebke}],[0,{[_hH]:_xarc}]]];CompleteMultipartUploadRequest$=[3,n0,_CMURo,0,[_B,_K,_UI,_MU,_CCRC,_CCRCC,_CCRCNVME,_CSHA,_CSHAh,_CT,_MOS,_RP,_EBO,_IM,_INM,_SSECA,_SSECK,_SSECKMD],[[0,1],[0,1],[0,{[_hQ]:_uI}],[()=>CompletedMultipartUpload$,{[_hP]:1,[_xN]:_CMUo}],[0,{[_hH]:_xacc}],[0,{[_hH]:_xacc_}],[0,{[_hH]:_xacc__}],[0,{[_hH]:_xacs}],[0,{[_hH]:_xacs_}],[0,{[_hH]:_xact}],[1,{[_hH]:_xamos}],[0,{[_hH]:_xarp}],[0,{[_hH]:_xaebo}],[0,{[_hH]:_IM_}],[0,{[_hH]:_INM_}],[0,{[_hH]:_xasseca}],[()=>SSECustomerKey,{[_hH]:_xasseck}],[0,{[_hH]:_xasseckM}]],3];Condition$=[3,n0,_Co,0,[_HECRE,_KPE],[0,0]];ContinuationEvent$=[3,n0,_CE,0,[],[]];CopyObjectOutput$=[3,n0,_COO,0,[_COR,_E,_CSVI,_VI,_SSE,_SSECA,_SSECKMD,_SSEKMSKI,_SSEKMSEC,_BKE,_RC],[[()=>CopyObjectResult$,16],[0,{[_hH]:_xae}],[0,{[_hH]:_xacsvi}],[0,{[_hH]:_xavi}],[0,{[_hH]:_xasse}],[0,{[_hH]:_xasseca}],[0,{[_hH]:_xasseckM}],[()=>SSEKMSKeyId,{[_hH]:_xasseakki}],[()=>SSEKMSEncryptionContext,{[_hH]:_xassec}],[2,{[_hH]:_xassebke}],[0,{[_hH]:_xarc}]]];CopyObjectRequest$=[3,n0,_CORo,0,[_B,_CS,_K,_ACL_,_CC,_CA,_CDo,_CEo,_CL,_CTo,_CSIM,_CSIMS,_CSINM,_CSIUS,_Ex,_GFC,_GR,_GRACP,_GWACP,_IM,_INM,_M,_MD,_TD,_SSE,_SC,_WRL,_SSECA,_SSECK,_SSECKMD,_SSEKMSKI,_SSEKMSEC,_BKE,_CSSSECA,_CSSSECK,_CSSSECKMD,_RP,_Tag,_OLM,_OLRUD,_OLLHS,_EBO,_ESBO],[[0,1],[0,{[_hH]:_xacs__}],[0,1],[0,{[_hH]:_xaa}],[0,{[_hH]:_CC_}],[0,{[_hH]:_xaca}],[0,{[_hH]:_CD_}],[0,{[_hH]:_CE_}],[0,{[_hH]:_CL_}],[0,{[_hH]:_CT_}],[0,{[_hH]:_xacsim}],[4,{[_hH]:_xacsims}],[0,{[_hH]:_xacsinm}],[4,{[_hH]:_xacsius}],[4,{[_hH]:_Ex}],[0,{[_hH]:_xagfc}],[0,{[_hH]:_xagr}],[0,{[_hH]:_xagra}],[0,{[_hH]:_xagwa}],[0,{[_hH]:_IM_}],[0,{[_hH]:_INM_}],[128,{[_hPH]:_xam}],[0,{[_hH]:_xamd}],[0,{[_hH]:_xatd}],[0,{[_hH]:_xasse}],[0,{[_hH]:_xasc}],[0,{[_hH]:_xawrl}],[0,{[_hH]:_xasseca}],[()=>SSECustomerKey,{[_hH]:_xasseck}],[0,{[_hH]:_xasseckM}],[()=>SSEKMSKeyId,{[_hH]:_xasseakki}],[()=>SSEKMSEncryptionContext,{[_hH]:_xassec}],[2,{[_hH]:_xassebke}],[0,{[_hH]:_xacssseca}],[()=>CopySourceSSECustomerKey,{[_hH]:_xacssseck}],[0,{[_hH]:_xacssseckM}],[0,{[_hH]:_xarp}],[0,{[_hH]:_xat}],[0,{[_hH]:_xaolm}],[5,{[_hH]:_xaolrud}],[0,{[_hH]:_xaollh}],[0,{[_hH]:_xaebo}],[0,{[_hH]:_xasebo}]],3];CopyObjectResult$=[3,n0,_COR,0,[_ETa,_LM,_CT,_CCRC,_CCRCC,_CCRCNVME,_CSHA,_CSHAh],[0,4,0,0,0,0,0,0]];CopyPartResult$=[3,n0,_CPR,0,[_ETa,_LM,_CCRC,_CCRCC,_CCRCNVME,_CSHA,_CSHAh],[0,4,0,0,0,0,0]];CORSConfiguration$=[3,n0,_CORSC,0,[_CORSR],[[()=>CORSRules,{[_xF]:1,[_xN]:_CORSRu}]],1];CORSRule$=[3,n0,_CORSRu,0,[_AM,_AO,_ID,_AH,_EH,_MAS],[[64,{[_xF]:1,[_xN]:_AMl}],[64,{[_xF]:1,[_xN]:_AOl}],0,[64,{[_xF]:1,[_xN]:_AHl}],[64,{[_xF]:1,[_xN]:_EHx}],1],2];CreateBucketConfiguration$=[3,n0,_CBC,0,[_LC,_L,_B,_T],[0,()=>LocationInfo$,()=>BucketInfo$,[()=>TagSet,0]]];CreateBucketMetadataConfigurationRequest$=[3,n0,_CBMCR,0,[_B,_MC,_CMD,_CA,_EBO],[[0,1],[()=>MetadataConfiguration$,{[_hP]:1,[_xN]:_MC}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xaebo}]],2];CreateBucketMetadataTableConfigurationRequest$=[3,n0,_CBMTCR,0,[_B,_MTC,_CMD,_CA,_EBO],[[0,1],[()=>MetadataTableConfiguration$,{[_hP]:1,[_xN]:_MTC}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xaebo}]],2];CreateBucketOutput$=[3,n0,_CBO,0,[_L,_BA],[[0,{[_hH]:_L}],[0,{[_hH]:_xaba}]]];CreateBucketRequest$=[3,n0,_CBR,0,[_B,_ACL_,_CBC,_GFC,_GR,_GRACP,_GW,_GWACP,_OLEFB,_OO,_BN],[[0,1],[0,{[_hH]:_xaa}],[()=>CreateBucketConfiguration$,{[_hP]:1,[_xN]:_CBC}],[0,{[_hH]:_xagfc}],[0,{[_hH]:_xagr}],[0,{[_hH]:_xagra}],[0,{[_hH]:_xagw}],[0,{[_hH]:_xagwa}],[2,{[_hH]:_xabole}],[0,{[_hH]:_xaoo}],[0,{[_hH]:_xabn}]],1];CreateMultipartUploadOutput$=[3,n0,_CMUOr,{[_xN]:_IMUR},[_ADb,_ARI,_B,_K,_UI,_SSE,_SSECA,_SSECKMD,_SSEKMSKI,_SSEKMSEC,_BKE,_RC,_CA,_CT],[[4,{[_hH]:_xaad}],[0,{[_hH]:_xaari}],[0,{[_xN]:_B}],0,0,[0,{[_hH]:_xasse}],[0,{[_hH]:_xasseca}],[0,{[_hH]:_xasseckM}],[()=>SSEKMSKeyId,{[_hH]:_xasseakki}],[()=>SSEKMSEncryptionContext,{[_hH]:_xassec}],[2,{[_hH]:_xassebke}],[0,{[_hH]:_xarc}],[0,{[_hH]:_xaca}],[0,{[_hH]:_xact}]]];CreateMultipartUploadRequest$=[3,n0,_CMURr,0,[_B,_K,_ACL_,_CC,_CDo,_CEo,_CL,_CTo,_Ex,_GFC,_GR,_GRACP,_GWACP,_M,_SSE,_SC,_WRL,_SSECA,_SSECK,_SSECKMD,_SSEKMSKI,_SSEKMSEC,_BKE,_RP,_Tag,_OLM,_OLRUD,_OLLHS,_EBO,_CA,_CT],[[0,1],[0,1],[0,{[_hH]:_xaa}],[0,{[_hH]:_CC_}],[0,{[_hH]:_CD_}],[0,{[_hH]:_CE_}],[0,{[_hH]:_CL_}],[0,{[_hH]:_CT_}],[4,{[_hH]:_Ex}],[0,{[_hH]:_xagfc}],[0,{[_hH]:_xagr}],[0,{[_hH]:_xagra}],[0,{[_hH]:_xagwa}],[128,{[_hPH]:_xam}],[0,{[_hH]:_xasse}],[0,{[_hH]:_xasc}],[0,{[_hH]:_xawrl}],[0,{[_hH]:_xasseca}],[()=>SSECustomerKey,{[_hH]:_xasseck}],[0,{[_hH]:_xasseckM}],[()=>SSEKMSKeyId,{[_hH]:_xasseakki}],[()=>SSEKMSEncryptionContext,{[_hH]:_xassec}],[2,{[_hH]:_xassebke}],[0,{[_hH]:_xarp}],[0,{[_hH]:_xat}],[0,{[_hH]:_xaolm}],[5,{[_hH]:_xaolrud}],[0,{[_hH]:_xaollh}],[0,{[_hH]:_xaebo}],[0,{[_hH]:_xaca}],[0,{[_hH]:_xact}]],2];CreateSessionOutput$=[3,n0,_CSO,{[_xN]:_CSR},[_Cr,_SSE,_SSEKMSKI,_SSEKMSEC,_BKE],[[()=>SessionCredentials$,{[_xN]:_Cr}],[0,{[_hH]:_xasse}],[()=>SSEKMSKeyId,{[_hH]:_xasseakki}],[()=>SSEKMSEncryptionContext,{[_hH]:_xassec}],[2,{[_hH]:_xassebke}]],1];CreateSessionRequest$=[3,n0,_CSRr,0,[_B,_SM,_SSE,_SSEKMSKI,_SSEKMSEC,_BKE],[[0,1],[0,{[_hH]:_xacsm}],[0,{[_hH]:_xasse}],[()=>SSEKMSKeyId,{[_hH]:_xasseakki}],[()=>SSEKMSEncryptionContext,{[_hH]:_xassec}],[2,{[_hH]:_xassebke}]],1];CSVInput$=[3,n0,_CSVIn,0,[_FHI,_Com,_QEC,_RD,_FD,_QC,_AQRD],[0,0,0,0,0,0,2]];CSVOutput$=[3,n0,_CSVO,0,[_QF,_QEC,_RD,_FD,_QC],[0,0,0,0,0]];DefaultRetention$=[3,n0,_DRe,0,[_Mo,_D,_Y],[0,1,1]];Delete$=[3,n0,_De,0,[_Ob,_Q],[[()=>ObjectIdentifierList,{[_xF]:1,[_xN]:_Obj}],2],1];DeleteBucketAnalyticsConfigurationRequest$=[3,n0,_DBACR,0,[_B,_I,_EBO],[[0,1],[0,{[_hQ]:_i}],[0,{[_hH]:_xaebo}]],2];DeleteBucketCorsRequest$=[3,n0,_DBCR,0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];DeleteBucketEncryptionRequest$=[3,n0,_DBER,0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];DeleteBucketIntelligentTieringConfigurationRequest$=[3,n0,_DBITCR,0,[_B,_I,_EBO],[[0,1],[0,{[_hQ]:_i}],[0,{[_hH]:_xaebo}]],2];DeleteBucketInventoryConfigurationRequest$=[3,n0,_DBICR,0,[_B,_I,_EBO],[[0,1],[0,{[_hQ]:_i}],[0,{[_hH]:_xaebo}]],2];DeleteBucketLifecycleRequest$=[3,n0,_DBLR,0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];DeleteBucketMetadataConfigurationRequest$=[3,n0,_DBMCR,0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];DeleteBucketMetadataTableConfigurationRequest$=[3,n0,_DBMTCR,0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];DeleteBucketMetricsConfigurationRequest$=[3,n0,_DBMCRe,0,[_B,_I,_EBO],[[0,1],[0,{[_hQ]:_i}],[0,{[_hH]:_xaebo}]],2];DeleteBucketOwnershipControlsRequest$=[3,n0,_DBOCR,0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];DeleteBucketPolicyRequest$=[3,n0,_DBPR,0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];DeleteBucketReplicationRequest$=[3,n0,_DBRR,0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];DeleteBucketRequest$=[3,n0,_DBR,0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];DeleteBucketTaggingRequest$=[3,n0,_DBTR,0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];DeleteBucketWebsiteRequest$=[3,n0,_DBWR,0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];DeletedObject$=[3,n0,_DO,0,[_K,_VI,_DM,_DMVI],[0,0,2,0]];DeleteMarkerEntry$=[3,n0,_DME,0,[_O,_K,_VI,_IL,_LM],[()=>Owner$,0,0,2,4]];DeleteMarkerReplication$=[3,n0,_DMR,0,[_S],[0]];DeleteObjectOutput$=[3,n0,_DOO,0,[_DM,_VI,_RC],[[2,{[_hH]:_xadm}],[0,{[_hH]:_xavi}],[0,{[_hH]:_xarc}]]];DeleteObjectRequest$=[3,n0,_DOR,0,[_B,_K,_MFA,_VI,_RP,_BGR,_EBO,_IM,_IMLMT,_IMS],[[0,1],[0,1],[0,{[_hH]:_xam_}],[0,{[_hQ]:_vI}],[0,{[_hH]:_xarp}],[2,{[_hH]:_xabgr}],[0,{[_hH]:_xaebo}],[0,{[_hH]:_IM_}],[6,{[_hH]:_xaimlmt}],[1,{[_hH]:_xaims}]],2];DeleteObjectsOutput$=[3,n0,_DOOe,{[_xN]:_DRel},[_Del,_RC,_Er],[[()=>DeletedObjects,{[_xF]:1}],[0,{[_hH]:_xarc}],[()=>Errors,{[_xF]:1,[_xN]:_Err}]]];DeleteObjectsRequest$=[3,n0,_DORe,0,[_B,_De,_MFA,_RP,_BGR,_EBO,_CA],[[0,1],[()=>Delete$,{[_hP]:1,[_xN]:_De}],[0,{[_hH]:_xam_}],[0,{[_hH]:_xarp}],[2,{[_hH]:_xabgr}],[0,{[_hH]:_xaebo}],[0,{[_hH]:_xasca}]],2];DeleteObjectTaggingOutput$=[3,n0,_DOTO,0,[_VI],[[0,{[_hH]:_xavi}]]];DeleteObjectTaggingRequest$=[3,n0,_DOTR,0,[_B,_K,_VI,_EBO],[[0,1],[0,1],[0,{[_hQ]:_vI}],[0,{[_hH]:_xaebo}]],2];DeletePublicAccessBlockRequest$=[3,n0,_DPABR,0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];Destination$=[3,n0,_Des,0,[_B,_A,_SC,_ACT,_EC,_RT,_Me],[0,0,0,()=>AccessControlTranslation$,()=>EncryptionConfiguration$,()=>ReplicationTime$,()=>Metrics$],1];DestinationResult$=[3,n0,_DRes,0,[_TBT,_TBA,_TN],[0,0,0]];Encryption$=[3,n0,_En,0,[_ET,_KMSKI,_KMSC],[0,[()=>SSEKMSKeyId,0],0],1];EncryptionConfiguration$=[3,n0,_EC,0,[_RKKID],[0]];EndEvent$=[3,n0,_EE,0,[],[]];_Error$=[3,n0,_Err,0,[_K,_VI,_Cod,_Mes],[0,0,0,0]];ErrorDetails$=[3,n0,_ED,0,[_ECr,_EM],[0,0]];ErrorDocument$=[3,n0,_EDr,0,[_K],[0],1];EventBridgeConfiguration$=[3,n0,_EBC,0,[],[]];ExistingObjectReplication$=[3,n0,_EOR,0,[_S],[0],1];FilterRule$=[3,n0,_FR,0,[_N,_V],[0,0]];GetBucketAbacOutput$=[3,n0,_GBAO,0,[_AS],[[()=>AbacStatus$,16]]];GetBucketAbacRequest$=[3,n0,_GBAR,0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];GetBucketAccelerateConfigurationOutput$=[3,n0,_GBACO,{[_xN]:_AC},[_S,_RC],[0,[0,{[_hH]:_xarc}]]];GetBucketAccelerateConfigurationRequest$=[3,n0,_GBACR,0,[_B,_EBO,_RP],[[0,1],[0,{[_hH]:_xaebo}],[0,{[_hH]:_xarp}]],1];GetBucketAclOutput$=[3,n0,_GBAOe,{[_xN]:_ACP},[_O,_G],[()=>Owner$,[()=>Grants,{[_xN]:_ACL}]]];GetBucketAclRequest$=[3,n0,_GBARe,0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];GetBucketAnalyticsConfigurationOutput$=[3,n0,_GBACOe,0,[_ACn],[[()=>AnalyticsConfiguration$,16]]];GetBucketAnalyticsConfigurationRequest$=[3,n0,_GBACRe,0,[_B,_I,_EBO],[[0,1],[0,{[_hQ]:_i}],[0,{[_hH]:_xaebo}]],2];GetBucketCorsOutput$=[3,n0,_GBCO,{[_xN]:_CORSC},[_CORSR],[[()=>CORSRules,{[_xF]:1,[_xN]:_CORSRu}]]];GetBucketCorsRequest$=[3,n0,_GBCR,0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];GetBucketEncryptionOutput$=[3,n0,_GBEO,0,[_SSEC],[[()=>ServerSideEncryptionConfiguration$,16]]];GetBucketEncryptionRequest$=[3,n0,_GBER,0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];GetBucketIntelligentTieringConfigurationOutput$=[3,n0,_GBITCO,0,[_ITC],[[()=>IntelligentTieringConfiguration$,16]]];GetBucketIntelligentTieringConfigurationRequest$=[3,n0,_GBITCR,0,[_B,_I,_EBO],[[0,1],[0,{[_hQ]:_i}],[0,{[_hH]:_xaebo}]],2];GetBucketInventoryConfigurationOutput$=[3,n0,_GBICO,0,[_IC],[[()=>InventoryConfiguration$,16]]];GetBucketInventoryConfigurationRequest$=[3,n0,_GBICR,0,[_B,_I,_EBO],[[0,1],[0,{[_hQ]:_i}],[0,{[_hH]:_xaebo}]],2];GetBucketLifecycleConfigurationOutput$=[3,n0,_GBLCO,{[_xN]:_LCi},[_R,_TDMOS],[[()=>LifecycleRules,{[_xF]:1,[_xN]:_Ru}],[0,{[_hH]:_xatdmos}]]];GetBucketLifecycleConfigurationRequest$=[3,n0,_GBLCR,0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];GetBucketLocationOutput$=[3,n0,_GBLO,{[_xN]:_LC},[_LC],[0]];GetBucketLocationRequest$=[3,n0,_GBLR,0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];GetBucketLoggingOutput$=[3,n0,_GBLOe,{[_xN]:_BLS},[_LE],[[()=>LoggingEnabled$,0]]];GetBucketLoggingRequest$=[3,n0,_GBLRe,0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];GetBucketMetadataConfigurationOutput$=[3,n0,_GBMCO,0,[_GBMCR],[[()=>GetBucketMetadataConfigurationResult$,16]]];GetBucketMetadataConfigurationRequest$=[3,n0,_GBMCRe,0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];GetBucketMetadataConfigurationResult$=[3,n0,_GBMCR,0,[_MCR],[()=>MetadataConfigurationResult$],1];GetBucketMetadataTableConfigurationOutput$=[3,n0,_GBMTCO,0,[_GBMTCR],[[()=>GetBucketMetadataTableConfigurationResult$,16]]];GetBucketMetadataTableConfigurationRequest$=[3,n0,_GBMTCRe,0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];GetBucketMetadataTableConfigurationResult$=[3,n0,_GBMTCR,0,[_MTCR,_S,_Err],[()=>MetadataTableConfigurationResult$,0,()=>ErrorDetails$],2];GetBucketMetricsConfigurationOutput$=[3,n0,_GBMCOe,0,[_MCe],[[()=>MetricsConfiguration$,16]]];GetBucketMetricsConfigurationRequest$=[3,n0,_GBMCRet,0,[_B,_I,_EBO],[[0,1],[0,{[_hQ]:_i}],[0,{[_hH]:_xaebo}]],2];GetBucketNotificationConfigurationRequest$=[3,n0,_GBNCR,0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];GetBucketOwnershipControlsOutput$=[3,n0,_GBOCO,0,[_OC],[[()=>OwnershipControls$,16]]];GetBucketOwnershipControlsRequest$=[3,n0,_GBOCR,0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];GetBucketPolicyOutput$=[3,n0,_GBPO,0,[_Po],[[0,16]]];GetBucketPolicyRequest$=[3,n0,_GBPR,0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];GetBucketPolicyStatusOutput$=[3,n0,_GBPSO,0,[_PS],[[()=>PolicyStatus$,16]]];GetBucketPolicyStatusRequest$=[3,n0,_GBPSR,0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];GetBucketReplicationOutput$=[3,n0,_GBRO,0,[_RCe],[[()=>ReplicationConfiguration$,16]]];GetBucketReplicationRequest$=[3,n0,_GBRR,0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];GetBucketRequestPaymentOutput$=[3,n0,_GBRPO,{[_xN]:_RPC},[_Pay],[0]];GetBucketRequestPaymentRequest$=[3,n0,_GBRPR,0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];GetBucketTaggingOutput$=[3,n0,_GBTO,{[_xN]:_Tag},[_TS],[[()=>TagSet,0]],1];GetBucketTaggingRequest$=[3,n0,_GBTR,0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];GetBucketVersioningOutput$=[3,n0,_GBVO,{[_xN]:_VC},[_S,_MFAD],[0,[0,{[_xN]:_MDf}]]];GetBucketVersioningRequest$=[3,n0,_GBVR,0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];GetBucketWebsiteOutput$=[3,n0,_GBWO,{[_xN]:_WC},[_RART,_IDn,_EDr,_RR],[()=>RedirectAllRequestsTo$,()=>IndexDocument$,()=>ErrorDocument$,[()=>RoutingRules,0]]];GetBucketWebsiteRequest$=[3,n0,_GBWR,0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];GetObjectAclOutput$=[3,n0,_GOAO,{[_xN]:_ACP},[_O,_G,_RC],[()=>Owner$,[()=>Grants,{[_xN]:_ACL}],[0,{[_hH]:_xarc}]]];GetObjectAclRequest$=[3,n0,_GOAR,0,[_B,_K,_VI,_RP,_EBO],[[0,1],[0,1],[0,{[_hQ]:_vI}],[0,{[_hH]:_xarp}],[0,{[_hH]:_xaebo}]],2];GetObjectAttributesOutput$=[3,n0,_GOAOe,{[_xN]:_GOARe},[_DM,_LM,_VI,_RC,_ETa,_C,_OP,_SC,_OS],[[2,{[_hH]:_xadm}],[4,{[_hH]:_LM_}],[0,{[_hH]:_xavi}],[0,{[_hH]:_xarc}],0,()=>Checksum$,[()=>GetObjectAttributesParts$,0],0,1]];GetObjectAttributesParts$=[3,n0,_GOAP,0,[_TPC,_PNM,_NPNM,_MP,_IT,_Pa],[[1,{[_xN]:_PC}],0,0,1,2,[()=>PartsList,{[_xF]:1,[_xN]:_Par}]]];GetObjectAttributesRequest$=[3,n0,_GOARet,0,[_B,_K,_OA,_VI,_MP,_PNM,_SSECA,_SSECK,_SSECKMD,_RP,_EBO],[[0,1],[0,1],[64,{[_hH]:_xaoa}],[0,{[_hQ]:_vI}],[1,{[_hH]:_xamp}],[0,{[_hH]:_xapnm}],[0,{[_hH]:_xasseca}],[()=>SSECustomerKey,{[_hH]:_xasseck}],[0,{[_hH]:_xasseckM}],[0,{[_hH]:_xarp}],[0,{[_hH]:_xaebo}]],3];GetObjectLegalHoldOutput$=[3,n0,_GOLHO,0,[_LH],[[()=>ObjectLockLegalHold$,{[_hP]:1,[_xN]:_LH}]]];GetObjectLegalHoldRequest$=[3,n0,_GOLHR,0,[_B,_K,_VI,_RP,_EBO],[[0,1],[0,1],[0,{[_hQ]:_vI}],[0,{[_hH]:_xarp}],[0,{[_hH]:_xaebo}]],2];GetObjectLockConfigurationOutput$=[3,n0,_GOLCO,0,[_OLC],[[()=>ObjectLockConfiguration$,16]]];GetObjectLockConfigurationRequest$=[3,n0,_GOLCR,0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];GetObjectOutput$=[3,n0,_GOO,0,[_Bo,_DM,_AR,_E,_Re,_LM,_CLo,_ETa,_CCRC,_CCRCC,_CCRCNVME,_CSHA,_CSHAh,_CT,_MM,_VI,_CC,_CDo,_CEo,_CL,_CR,_CTo,_Ex,_ES,_WRL,_SSE,_M,_SSECA,_SSECKMD,_SSEKMSKI,_BKE,_SC,_RC,_RS,_PC,_TC,_OLM,_OLRUD,_OLLHS],[[()=>StreamingBlob,16],[2,{[_hH]:_xadm}],[0,{[_hH]:_ar}],[0,{[_hH]:_xae}],[0,{[_hH]:_xar}],[4,{[_hH]:_LM_}],[1,{[_hH]:_CL__}],[0,{[_hH]:_ETa}],[0,{[_hH]:_xacc}],[0,{[_hH]:_xacc_}],[0,{[_hH]:_xacc__}],[0,{[_hH]:_xacs}],[0,{[_hH]:_xacs_}],[0,{[_hH]:_xact}],[1,{[_hH]:_xamm}],[0,{[_hH]:_xavi}],[0,{[_hH]:_CC_}],[0,{[_hH]:_CD_}],[0,{[_hH]:_CE_}],[0,{[_hH]:_CL_}],[0,{[_hH]:_CR_}],[0,{[_hH]:_CT_}],[4,{[_hH]:_Ex}],[0,{[_hH]:_ES}],[0,{[_hH]:_xawrl}],[0,{[_hH]:_xasse}],[128,{[_hPH]:_xam}],[0,{[_hH]:_xasseca}],[0,{[_hH]:_xasseckM}],[()=>SSEKMSKeyId,{[_hH]:_xasseakki}],[2,{[_hH]:_xassebke}],[0,{[_hH]:_xasc}],[0,{[_hH]:_xarc}],[0,{[_hH]:_xars}],[1,{[_hH]:_xampc}],[1,{[_hH]:_xatc}],[0,{[_hH]:_xaolm}],[5,{[_hH]:_xaolrud}],[0,{[_hH]:_xaollh}]]];GetObjectRequest$=[3,n0,_GOR,0,[_B,_K,_IM,_IMSf,_INM,_IUS,_Ra,_RCC,_RCD,_RCE,_RCL,_RCT,_RE,_VI,_SSECA,_SSECK,_SSECKMD,_RP,_PN,_EBO,_CMh],[[0,1],[0,1],[0,{[_hH]:_IM_}],[4,{[_hH]:_IMS_}],[0,{[_hH]:_INM_}],[4,{[_hH]:_IUS_}],[0,{[_hH]:_Ra}],[0,{[_hQ]:_rcc}],[0,{[_hQ]:_rcd}],[0,{[_hQ]:_rce}],[0,{[_hQ]:_rcl}],[0,{[_hQ]:_rct}],[6,{[_hQ]:_re}],[0,{[_hQ]:_vI}],[0,{[_hH]:_xasseca}],[()=>SSECustomerKey,{[_hH]:_xasseck}],[0,{[_hH]:_xasseckM}],[0,{[_hH]:_xarp}],[1,{[_hQ]:_pN}],[0,{[_hH]:_xaebo}],[0,{[_hH]:_xacm}]],2];GetObjectRetentionOutput$=[3,n0,_GORO,0,[_Ret],[[()=>ObjectLockRetention$,{[_hP]:1,[_xN]:_Ret}]]];GetObjectRetentionRequest$=[3,n0,_GORR,0,[_B,_K,_VI,_RP,_EBO],[[0,1],[0,1],[0,{[_hQ]:_vI}],[0,{[_hH]:_xarp}],[0,{[_hH]:_xaebo}]],2];GetObjectTaggingOutput$=[3,n0,_GOTO,{[_xN]:_Tag},[_TS,_VI],[[()=>TagSet,0],[0,{[_hH]:_xavi}]],1];GetObjectTaggingRequest$=[3,n0,_GOTR,0,[_B,_K,_VI,_EBO,_RP],[[0,1],[0,1],[0,{[_hQ]:_vI}],[0,{[_hH]:_xaebo}],[0,{[_hH]:_xarp}]],2];GetObjectTorrentOutput$=[3,n0,_GOTOe,0,[_Bo,_RC],[[()=>StreamingBlob,16],[0,{[_hH]:_xarc}]]];GetObjectTorrentRequest$=[3,n0,_GOTRe,0,[_B,_K,_RP,_EBO],[[0,1],[0,1],[0,{[_hH]:_xarp}],[0,{[_hH]:_xaebo}]],2];GetPublicAccessBlockOutput$=[3,n0,_GPABO,0,[_PABC],[[()=>PublicAccessBlockConfiguration$,16]]];GetPublicAccessBlockRequest$=[3,n0,_GPABR,0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];GlacierJobParameters$=[3,n0,_GJP,0,[_Ti],[0],1];Grant$=[3,n0,_Gr,0,[_Gra,_Pe],[[()=>Grantee$,{[_xNm]:[_x,_hi]}],0]];Grantee$=[3,n0,_Gra,0,[_Ty,_DN,_EA,_ID,_URI],[[0,{[_xA]:1,[_xN]:_xs}],0,0,0,0],1];HeadBucketOutput$=[3,n0,_HBO,0,[_BA,_BLT,_BLN,_BR,_APA],[[0,{[_hH]:_xaba}],[0,{[_hH]:_xablt}],[0,{[_hH]:_xabln}],[0,{[_hH]:_xabr}],[2,{[_hH]:_xaapa}]]];HeadBucketRequest$=[3,n0,_HBR,0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];HeadObjectOutput$=[3,n0,_HOO,0,[_DM,_AR,_E,_Re,_ASr,_LM,_CLo,_CCRC,_CCRCC,_CCRCNVME,_CSHA,_CSHAh,_CT,_ETa,_MM,_VI,_CC,_CDo,_CEo,_CL,_CTo,_CR,_Ex,_ES,_WRL,_SSE,_M,_SSECA,_SSECKMD,_SSEKMSKI,_BKE,_SC,_RC,_RS,_PC,_TC,_OLM,_OLRUD,_OLLHS],[[2,{[_hH]:_xadm}],[0,{[_hH]:_ar}],[0,{[_hH]:_xae}],[0,{[_hH]:_xar}],[0,{[_hH]:_xaas}],[4,{[_hH]:_LM_}],[1,{[_hH]:_CL__}],[0,{[_hH]:_xacc}],[0,{[_hH]:_xacc_}],[0,{[_hH]:_xacc__}],[0,{[_hH]:_xacs}],[0,{[_hH]:_xacs_}],[0,{[_hH]:_xact}],[0,{[_hH]:_ETa}],[1,{[_hH]:_xamm}],[0,{[_hH]:_xavi}],[0,{[_hH]:_CC_}],[0,{[_hH]:_CD_}],[0,{[_hH]:_CE_}],[0,{[_hH]:_CL_}],[0,{[_hH]:_CT_}],[0,{[_hH]:_CR_}],[4,{[_hH]:_Ex}],[0,{[_hH]:_ES}],[0,{[_hH]:_xawrl}],[0,{[_hH]:_xasse}],[128,{[_hPH]:_xam}],[0,{[_hH]:_xasseca}],[0,{[_hH]:_xasseckM}],[()=>SSEKMSKeyId,{[_hH]:_xasseakki}],[2,{[_hH]:_xassebke}],[0,{[_hH]:_xasc}],[0,{[_hH]:_xarc}],[0,{[_hH]:_xars}],[1,{[_hH]:_xampc}],[1,{[_hH]:_xatc}],[0,{[_hH]:_xaolm}],[5,{[_hH]:_xaolrud}],[0,{[_hH]:_xaollh}]]];HeadObjectRequest$=[3,n0,_HOR,0,[_B,_K,_IM,_IMSf,_INM,_IUS,_Ra,_RCC,_RCD,_RCE,_RCL,_RCT,_RE,_VI,_SSECA,_SSECK,_SSECKMD,_RP,_PN,_EBO,_CMh],[[0,1],[0,1],[0,{[_hH]:_IM_}],[4,{[_hH]:_IMS_}],[0,{[_hH]:_INM_}],[4,{[_hH]:_IUS_}],[0,{[_hH]:_Ra}],[0,{[_hQ]:_rcc}],[0,{[_hQ]:_rcd}],[0,{[_hQ]:_rce}],[0,{[_hQ]:_rcl}],[0,{[_hQ]:_rct}],[6,{[_hQ]:_re}],[0,{[_hQ]:_vI}],[0,{[_hH]:_xasseca}],[()=>SSECustomerKey,{[_hH]:_xasseck}],[0,{[_hH]:_xasseckM}],[0,{[_hH]:_xarp}],[1,{[_hQ]:_pN}],[0,{[_hH]:_xaebo}],[0,{[_hH]:_xacm}]],2];IndexDocument$=[3,n0,_IDn,0,[_Su],[0],1];Initiator$=[3,n0,_In,0,[_ID,_DN],[0,0]];InputSerialization$=[3,n0,_IS,0,[_CSV,_CTom,_JSON,_Parq],[()=>CSVInput$,0,()=>JSONInput$,()=>ParquetInput$]];IntelligentTieringAndOperator$=[3,n0,_ITAO,0,[_P,_T],[0,[()=>TagSet,{[_xF]:1,[_xN]:_Ta}]]];IntelligentTieringConfiguration$=[3,n0,_ITC,0,[_I,_S,_Tie,_F],[0,0,[()=>TieringList,{[_xF]:1,[_xN]:_Tier}],[()=>IntelligentTieringFilter$,0]],3];IntelligentTieringFilter$=[3,n0,_ITF,0,[_P,_Ta,_An],[0,()=>Tag$,[()=>IntelligentTieringAndOperator$,0]]];InventoryConfiguration$=[3,n0,_IC,0,[_Des,_IE,_I,_IOV,_Sc,_F,_OF],[[()=>InventoryDestination$,0],2,0,0,()=>InventorySchedule$,()=>InventoryFilter$,[()=>InventoryOptionalFields,0]],5];InventoryDestination$=[3,n0,_IDnv,0,[_SBD],[[()=>InventoryS3BucketDestination$,0]],1];InventoryEncryption$=[3,n0,_IEn,0,[_SSES,_SSEKMS],[[()=>SSES3$,{[_xN]:_SS}],[()=>SSEKMS$,{[_xN]:_SK}]]];InventoryFilter$=[3,n0,_IF,0,[_P],[0],1];InventoryS3BucketDestination$=[3,n0,_ISBD,0,[_B,_Fo,_AI,_P,_En],[0,0,0,0,[()=>InventoryEncryption$,0]],2];InventorySchedule$=[3,n0,_ISn,0,[_Fr],[0],1];InventoryTableConfiguration$=[3,n0,_ITCn,0,[_CSo,_EC],[0,()=>MetadataTableEncryptionConfiguration$],1];InventoryTableConfigurationResult$=[3,n0,_ITCR,0,[_CSo,_TSa,_Err,_TNa,_TA],[0,0,()=>ErrorDetails$,0,0],1];InventoryTableConfigurationUpdates$=[3,n0,_ITCU,0,[_CSo,_EC],[0,()=>MetadataTableEncryptionConfiguration$],1];JournalTableConfiguration$=[3,n0,_JTC,0,[_REe,_EC],[()=>RecordExpiration$,()=>MetadataTableEncryptionConfiguration$],1];JournalTableConfigurationResult$=[3,n0,_JTCR,0,[_TSa,_TNa,_REe,_Err,_TA],[0,0,()=>RecordExpiration$,()=>ErrorDetails$,0],3];JournalTableConfigurationUpdates$=[3,n0,_JTCU,0,[_REe],[()=>RecordExpiration$],1];JSONInput$=[3,n0,_JSONI,0,[_Ty],[0]];JSONOutput$=[3,n0,_JSONO,0,[_RD],[0]];LambdaFunctionConfiguration$=[3,n0,_LFC,0,[_LFA,_Ev,_I,_F],[[0,{[_xN]:_CF}],[64,{[_xF]:1,[_xN]:_Eve}],0,[()=>NotificationConfigurationFilter$,0]],2];LifecycleExpiration$=[3,n0,_LEi,0,[_Da,_D,_EODM],[5,1,2]];LifecycleRule$=[3,n0,_LR,0,[_S,_E,_ID,_P,_F,_Tr,_NVT,_NVE,_AIMU],[0,()=>LifecycleExpiration$,0,0,[()=>LifecycleRuleFilter$,0],[()=>TransitionList,{[_xF]:1,[_xN]:_Tra}],[()=>NoncurrentVersionTransitionList,{[_xF]:1,[_xN]:_NVTo}],()=>NoncurrentVersionExpiration$,()=>AbortIncompleteMultipartUpload$],1];LifecycleRuleAndOperator$=[3,n0,_LRAO,0,[_P,_T,_OSGT,_OSLT],[0,[()=>TagSet,{[_xF]:1,[_xN]:_Ta}],1,1]];LifecycleRuleFilter$=[3,n0,_LRF,0,[_P,_Ta,_OSGT,_OSLT,_An],[0,()=>Tag$,1,1,[()=>LifecycleRuleAndOperator$,0]]];ListBucketAnalyticsConfigurationsOutput$=[3,n0,_LBACO,{[_xN]:_LBACR},[_IT,_CTon,_NCT,_ACLn],[2,0,0,[()=>AnalyticsConfigurationList,{[_xF]:1,[_xN]:_ACn}]]];ListBucketAnalyticsConfigurationsRequest$=[3,n0,_LBACRi,0,[_B,_CTon,_EBO],[[0,1],[0,{[_hQ]:_ct}],[0,{[_hH]:_xaebo}]],1];ListBucketIntelligentTieringConfigurationsOutput$=[3,n0,_LBITCO,0,[_IT,_CTon,_NCT,_ITCL],[2,0,0,[()=>IntelligentTieringConfigurationList,{[_xF]:1,[_xN]:_ITC}]]];ListBucketIntelligentTieringConfigurationsRequest$=[3,n0,_LBITCR,0,[_B,_CTon,_EBO],[[0,1],[0,{[_hQ]:_ct}],[0,{[_hH]:_xaebo}]],1];ListBucketInventoryConfigurationsOutput$=[3,n0,_LBICO,{[_xN]:_LICR},[_CTon,_ICL,_IT,_NCT],[0,[()=>InventoryConfigurationList,{[_xF]:1,[_xN]:_IC}],2,0]];ListBucketInventoryConfigurationsRequest$=[3,n0,_LBICR,0,[_B,_CTon,_EBO],[[0,1],[0,{[_hQ]:_ct}],[0,{[_hH]:_xaebo}]],1];ListBucketMetricsConfigurationsOutput$=[3,n0,_LBMCO,{[_xN]:_LMCR},[_IT,_CTon,_NCT,_MCL],[2,0,0,[()=>MetricsConfigurationList,{[_xF]:1,[_xN]:_MCe}]]];ListBucketMetricsConfigurationsRequest$=[3,n0,_LBMCR,0,[_B,_CTon,_EBO],[[0,1],[0,{[_hQ]:_ct}],[0,{[_hH]:_xaebo}]],1];ListBucketsOutput$=[3,n0,_LBO,{[_xN]:_LAMBR},[_Bu,_O,_CTon,_P],[[()=>Buckets,0],()=>Owner$,0,0]];ListBucketsRequest$=[3,n0,_LBR,0,[_MB,_CTon,_P,_BR],[[1,{[_hQ]:_mb}],[0,{[_hQ]:_ct}],[0,{[_hQ]:_p}],[0,{[_hQ]:_br}]]];ListDirectoryBucketsOutput$=[3,n0,_LDBO,{[_xN]:_LAMDBR},[_Bu,_CTon],[[()=>Buckets,0],0]];ListDirectoryBucketsRequest$=[3,n0,_LDBR,0,[_CTon,_MDB],[[0,{[_hQ]:_ct}],[1,{[_hQ]:_mdb}]]];ListMultipartUploadsOutput$=[3,n0,_LMUO,{[_xN]:_LMUR},[_B,_KM,_UIM,_NKM,_P,_Deli,_NUIM,_MUa,_IT,_U,_CPom,_ETn,_RC],[0,0,0,0,0,0,0,1,2,[()=>MultipartUploadList,{[_xF]:1,[_xN]:_Up}],[()=>CommonPrefixList,{[_xF]:1}],0,[0,{[_hH]:_xarc}]]];ListMultipartUploadsRequest$=[3,n0,_LMURi,0,[_B,_Deli,_ETn,_KM,_MUa,_P,_UIM,_EBO,_RP],[[0,1],[0,{[_hQ]:_d}],[0,{[_hQ]:_et}],[0,{[_hQ]:_km}],[1,{[_hQ]:_mu}],[0,{[_hQ]:_p}],[0,{[_hQ]:_uim}],[0,{[_hH]:_xaebo}],[0,{[_hH]:_xarp}]],1];ListObjectsOutput$=[3,n0,_LOO,{[_xN]:_LBRi},[_IT,_Ma,_NM,_Con,_N,_P,_Deli,_MK,_CPom,_ETn,_RC],[2,0,0,[()=>ObjectList,{[_xF]:1}],0,0,0,1,[()=>CommonPrefixList,{[_xF]:1}],0,[0,{[_hH]:_xarc}]]];ListObjectsRequest$=[3,n0,_LOR,0,[_B,_Deli,_ETn,_Ma,_MK,_P,_RP,_EBO,_OOA],[[0,1],[0,{[_hQ]:_d}],[0,{[_hQ]:_et}],[0,{[_hQ]:_m}],[1,{[_hQ]:_mk}],[0,{[_hQ]:_p}],[0,{[_hH]:_xarp}],[0,{[_hH]:_xaebo}],[64,{[_hH]:_xaooa}]],1];ListObjectsV2Output$=[3,n0,_LOVO,{[_xN]:_LBRi},[_IT,_Con,_N,_P,_Deli,_MK,_CPom,_ETn,_KC,_CTon,_NCT,_SA,_RC],[2,[()=>ObjectList,{[_xF]:1}],0,0,0,1,[()=>CommonPrefixList,{[_xF]:1}],0,1,0,0,0,[0,{[_hH]:_xarc}]]];ListObjectsV2Request$=[3,n0,_LOVR,0,[_B,_Deli,_ETn,_MK,_P,_CTon,_FO,_SA,_RP,_EBO,_OOA],[[0,1],[0,{[_hQ]:_d}],[0,{[_hQ]:_et}],[1,{[_hQ]:_mk}],[0,{[_hQ]:_p}],[0,{[_hQ]:_ct}],[2,{[_hQ]:_fo}],[0,{[_hQ]:_sa}],[0,{[_hH]:_xarp}],[0,{[_hH]:_xaebo}],[64,{[_hH]:_xaooa}]],1];ListObjectVersionsOutput$=[3,n0,_LOVOi,{[_xN]:_LVR},[_IT,_KM,_VIM,_NKM,_NVIM,_Ve,_DMe,_N,_P,_Deli,_MK,_CPom,_ETn,_RC],[2,0,0,0,0,[()=>ObjectVersionList,{[_xF]:1,[_xN]:_Ver}],[()=>DeleteMarkers,{[_xF]:1,[_xN]:_DM}],0,0,0,1,[()=>CommonPrefixList,{[_xF]:1}],0,[0,{[_hH]:_xarc}]]];ListObjectVersionsRequest$=[3,n0,_LOVRi,0,[_B,_Deli,_ETn,_KM,_MK,_P,_VIM,_EBO,_RP,_OOA],[[0,1],[0,{[_hQ]:_d}],[0,{[_hQ]:_et}],[0,{[_hQ]:_km}],[1,{[_hQ]:_mk}],[0,{[_hQ]:_p}],[0,{[_hQ]:_vim}],[0,{[_hH]:_xaebo}],[0,{[_hH]:_xarp}],[64,{[_hH]:_xaooa}]],1];ListPartsOutput$=[3,n0,_LPO,{[_xN]:_LPR},[_ADb,_ARI,_B,_K,_UI,_PNM,_NPNM,_MP,_IT,_Pa,_In,_O,_SC,_RC,_CA,_CT],[[4,{[_hH]:_xaad}],[0,{[_hH]:_xaari}],0,0,0,0,0,1,2,[()=>Parts,{[_xF]:1,[_xN]:_Par}],()=>Initiator$,()=>Owner$,0,[0,{[_hH]:_xarc}],0,0]];ListPartsRequest$=[3,n0,_LPRi,0,[_B,_K,_UI,_MP,_PNM,_RP,_EBO,_SSECA,_SSECK,_SSECKMD],[[0,1],[0,1],[0,{[_hQ]:_uI}],[1,{[_hQ]:_mp}],[0,{[_hQ]:_pnm}],[0,{[_hH]:_xarp}],[0,{[_hH]:_xaebo}],[0,{[_hH]:_xasseca}],[()=>SSECustomerKey,{[_hH]:_xasseck}],[0,{[_hH]:_xasseckM}]],3];LocationInfo$=[3,n0,_LI,0,[_Ty,_N],[0,0]];LoggingEnabled$=[3,n0,_LE,0,[_TB,_TP,_TG,_TOKF],[0,0,[()=>TargetGrants,0],[()=>TargetObjectKeyFormat$,0]],2];MetadataConfiguration$=[3,n0,_MC,0,[_JTC,_ITCn],[()=>JournalTableConfiguration$,()=>InventoryTableConfiguration$],1];MetadataConfigurationResult$=[3,n0,_MCR,0,[_DRes,_JTCR,_ITCR],[()=>DestinationResult$,()=>JournalTableConfigurationResult$,()=>InventoryTableConfigurationResult$],1];MetadataEntry$=[3,n0,_ME,0,[_N,_V],[0,0]];MetadataTableConfiguration$=[3,n0,_MTC,0,[_STD],[()=>S3TablesDestination$],1];MetadataTableConfigurationResult$=[3,n0,_MTCR,0,[_STDR],[()=>S3TablesDestinationResult$],1];MetadataTableEncryptionConfiguration$=[3,n0,_MTEC,0,[_SAs,_KKA],[0,0],1];Metrics$=[3,n0,_Me,0,[_S,_ETv],[0,()=>ReplicationTimeValue$],1];MetricsAndOperator$=[3,n0,_MAO,0,[_P,_T,_APAc],[0,[()=>TagSet,{[_xF]:1,[_xN]:_Ta}],0]];MetricsConfiguration$=[3,n0,_MCe,0,[_I,_F],[0,[()=>MetricsFilter$,0]],1];MultipartUpload$=[3,n0,_MU,0,[_UI,_K,_Ini,_SC,_O,_In,_CA,_CT],[0,0,4,0,()=>Owner$,()=>Initiator$,0,0]];NoncurrentVersionExpiration$=[3,n0,_NVE,0,[_ND,_NNV],[1,1]];NoncurrentVersionTransition$=[3,n0,_NVTo,0,[_ND,_SC,_NNV],[1,0,1]];NotificationConfiguration$=[3,n0,_NC,0,[_TCo,_QCu,_LFCa,_EBC],[[()=>TopicConfigurationList,{[_xF]:1,[_xN]:_TCop}],[()=>QueueConfigurationList,{[_xF]:1,[_xN]:_QCue}],[()=>LambdaFunctionConfigurationList,{[_xF]:1,[_xN]:_CFC}],()=>EventBridgeConfiguration$]];NotificationConfigurationFilter$=[3,n0,_NCF,0,[_K],[[()=>S3KeyFilter$,{[_xN]:_SKe}]]];_Object$=[3,n0,_Obj,0,[_K,_LM,_ETa,_CA,_CT,_Si,_SC,_O,_RSe],[0,4,0,[64,{[_xF]:1}],0,1,0,()=>Owner$,()=>RestoreStatus$]];ObjectIdentifier$=[3,n0,_OI,0,[_K,_VI,_ETa,_LMT,_Si],[0,0,0,6,1],1];ObjectLockConfiguration$=[3,n0,_OLC,0,[_OLE,_Ru],[0,()=>ObjectLockRule$]];ObjectLockLegalHold$=[3,n0,_OLLH,0,[_S],[0]];ObjectLockRetention$=[3,n0,_OLR,0,[_Mo,_RUD],[0,5]];ObjectLockRule$=[3,n0,_OLRb,0,[_DRe],[()=>DefaultRetention$]];ObjectPart$=[3,n0,_OPb,0,[_PN,_Si,_CCRC,_CCRCC,_CCRCNVME,_CSHA,_CSHAh],[1,1,0,0,0,0,0]];ObjectVersion$=[3,n0,_OV,0,[_ETa,_CA,_CT,_Si,_SC,_K,_VI,_IL,_LM,_O,_RSe],[0,[64,{[_xF]:1}],0,1,0,0,0,2,4,()=>Owner$,()=>RestoreStatus$]];OutputLocation$=[3,n0,_OL,0,[_S_],[[()=>S3Location$,0]]];OutputSerialization$=[3,n0,_OSu,0,[_CSV,_JSON],[()=>CSVOutput$,()=>JSONOutput$]];Owner$=[3,n0,_O,0,[_DN,_ID],[0,0]];OwnershipControls$=[3,n0,_OC,0,[_R],[[()=>OwnershipControlsRules,{[_xF]:1,[_xN]:_Ru}]],1];OwnershipControlsRule$=[3,n0,_OCR,0,[_OO],[0],1];ParquetInput$=[3,n0,_PI,0,[],[]];Part$=[3,n0,_Par,0,[_PN,_LM,_ETa,_Si,_CCRC,_CCRCC,_CCRCNVME,_CSHA,_CSHAh],[1,4,0,1,0,0,0,0,0]];PartitionedPrefix$=[3,n0,_PP,{[_xN]:_PP},[_PDS],[0]];PolicyStatus$=[3,n0,_PS,0,[_IP],[[2,{[_xN]:_IP}]]];Progress$=[3,n0,_Pr,0,[_BS,_BP,_BRy],[1,1,1]];ProgressEvent$=[3,n0,_PE,0,[_Det],[[()=>Progress$,{[_eP]:1}]]];PublicAccessBlockConfiguration$=[3,n0,_PABC,0,[_BPA,_IPA,_BPP,_RPB],[[2,{[_xN]:_BPA}],[2,{[_xN]:_IPA}],[2,{[_xN]:_BPP}],[2,{[_xN]:_RPB}]]];PutBucketAbacRequest$=[3,n0,_PBAR,0,[_B,_AS,_CMD,_CA,_EBO],[[0,1],[()=>AbacStatus$,{[_hP]:1,[_xN]:_AS}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xaebo}]],2];PutBucketAccelerateConfigurationRequest$=[3,n0,_PBACR,0,[_B,_AC,_EBO,_CA],[[0,1],[()=>AccelerateConfiguration$,{[_hP]:1,[_xN]:_AC}],[0,{[_hH]:_xaebo}],[0,{[_hH]:_xasca}]],2];PutBucketAclRequest$=[3,n0,_PBARu,0,[_B,_ACL_,_ACP,_CMD,_CA,_GFC,_GR,_GRACP,_GW,_GWACP,_EBO],[[0,1],[0,{[_hH]:_xaa}],[()=>AccessControlPolicy$,{[_hP]:1,[_xN]:_ACP}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xagfc}],[0,{[_hH]:_xagr}],[0,{[_hH]:_xagra}],[0,{[_hH]:_xagw}],[0,{[_hH]:_xagwa}],[0,{[_hH]:_xaebo}]],1];PutBucketAnalyticsConfigurationRequest$=[3,n0,_PBACRu,0,[_B,_I,_ACn,_EBO],[[0,1],[0,{[_hQ]:_i}],[()=>AnalyticsConfiguration$,{[_hP]:1,[_xN]:_ACn}],[0,{[_hH]:_xaebo}]],3];PutBucketCorsRequest$=[3,n0,_PBCR,0,[_B,_CORSC,_CMD,_CA,_EBO],[[0,1],[()=>CORSConfiguration$,{[_hP]:1,[_xN]:_CORSC}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xaebo}]],2];PutBucketEncryptionRequest$=[3,n0,_PBER,0,[_B,_SSEC,_CMD,_CA,_EBO],[[0,1],[()=>ServerSideEncryptionConfiguration$,{[_hP]:1,[_xN]:_SSEC}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xaebo}]],2];PutBucketIntelligentTieringConfigurationRequest$=[3,n0,_PBITCR,0,[_B,_I,_ITC,_EBO],[[0,1],[0,{[_hQ]:_i}],[()=>IntelligentTieringConfiguration$,{[_hP]:1,[_xN]:_ITC}],[0,{[_hH]:_xaebo}]],3];PutBucketInventoryConfigurationRequest$=[3,n0,_PBICR,0,[_B,_I,_IC,_EBO],[[0,1],[0,{[_hQ]:_i}],[()=>InventoryConfiguration$,{[_hP]:1,[_xN]:_IC}],[0,{[_hH]:_xaebo}]],3];PutBucketLifecycleConfigurationOutput$=[3,n0,_PBLCO,0,[_TDMOS],[[0,{[_hH]:_xatdmos}]]];PutBucketLifecycleConfigurationRequest$=[3,n0,_PBLCR,0,[_B,_CA,_LCi,_EBO,_TDMOS],[[0,1],[0,{[_hH]:_xasca}],[()=>BucketLifecycleConfiguration$,{[_hP]:1,[_xN]:_LCi}],[0,{[_hH]:_xaebo}],[0,{[_hH]:_xatdmos}]],1];PutBucketLoggingRequest$=[3,n0,_PBLR,0,[_B,_BLS,_CMD,_CA,_EBO],[[0,1],[()=>BucketLoggingStatus$,{[_hP]:1,[_xN]:_BLS}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xaebo}]],2];PutBucketMetricsConfigurationRequest$=[3,n0,_PBMCR,0,[_B,_I,_MCe,_EBO],[[0,1],[0,{[_hQ]:_i}],[()=>MetricsConfiguration$,{[_hP]:1,[_xN]:_MCe}],[0,{[_hH]:_xaebo}]],3];PutBucketNotificationConfigurationRequest$=[3,n0,_PBNCR,0,[_B,_NC,_EBO,_SDV],[[0,1],[()=>NotificationConfiguration$,{[_hP]:1,[_xN]:_NC}],[0,{[_hH]:_xaebo}],[2,{[_hH]:_xasdv}]],2];PutBucketOwnershipControlsRequest$=[3,n0,_PBOCR,0,[_B,_OC,_CMD,_EBO,_CA],[[0,1],[()=>OwnershipControls$,{[_hP]:1,[_xN]:_OC}],[0,{[_hH]:_CM}],[0,{[_hH]:_xaebo}],[0,{[_hH]:_xasca}]],2];PutBucketPolicyRequest$=[3,n0,_PBPR,0,[_B,_Po,_CMD,_CA,_CRSBA,_EBO],[[0,1],[0,16],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[2,{[_hH]:_xacrsba}],[0,{[_hH]:_xaebo}]],2];PutBucketReplicationRequest$=[3,n0,_PBRR,0,[_B,_RCe,_CMD,_CA,_To,_EBO],[[0,1],[()=>ReplicationConfiguration$,{[_hP]:1,[_xN]:_RCe}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xabolt}],[0,{[_hH]:_xaebo}]],2];PutBucketRequestPaymentRequest$=[3,n0,_PBRPR,0,[_B,_RPC,_CMD,_CA,_EBO],[[0,1],[()=>RequestPaymentConfiguration$,{[_hP]:1,[_xN]:_RPC}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xaebo}]],2];PutBucketTaggingRequest$=[3,n0,_PBTR,0,[_B,_Tag,_CMD,_CA,_EBO],[[0,1],[()=>Tagging$,{[_hP]:1,[_xN]:_Tag}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xaebo}]],2];PutBucketVersioningRequest$=[3,n0,_PBVR,0,[_B,_VC,_CMD,_CA,_MFA,_EBO],[[0,1],[()=>VersioningConfiguration$,{[_hP]:1,[_xN]:_VC}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xam_}],[0,{[_hH]:_xaebo}]],2];PutBucketWebsiteRequest$=[3,n0,_PBWR,0,[_B,_WC,_CMD,_CA,_EBO],[[0,1],[()=>WebsiteConfiguration$,{[_hP]:1,[_xN]:_WC}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xaebo}]],2];PutObjectAclOutput$=[3,n0,_POAO,0,[_RC],[[0,{[_hH]:_xarc}]]];PutObjectAclRequest$=[3,n0,_POAR,0,[_B,_K,_ACL_,_ACP,_CMD,_CA,_GFC,_GR,_GRACP,_GW,_GWACP,_RP,_VI,_EBO],[[0,1],[0,1],[0,{[_hH]:_xaa}],[()=>AccessControlPolicy$,{[_hP]:1,[_xN]:_ACP}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xagfc}],[0,{[_hH]:_xagr}],[0,{[_hH]:_xagra}],[0,{[_hH]:_xagw}],[0,{[_hH]:_xagwa}],[0,{[_hH]:_xarp}],[0,{[_hQ]:_vI}],[0,{[_hH]:_xaebo}]],2];PutObjectLegalHoldOutput$=[3,n0,_POLHO,0,[_RC],[[0,{[_hH]:_xarc}]]];PutObjectLegalHoldRequest$=[3,n0,_POLHR,0,[_B,_K,_LH,_RP,_VI,_CMD,_CA,_EBO],[[0,1],[0,1],[()=>ObjectLockLegalHold$,{[_hP]:1,[_xN]:_LH}],[0,{[_hH]:_xarp}],[0,{[_hQ]:_vI}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xaebo}]],2];PutObjectLockConfigurationOutput$=[3,n0,_POLCO,0,[_RC],[[0,{[_hH]:_xarc}]]];PutObjectLockConfigurationRequest$=[3,n0,_POLCR,0,[_B,_OLC,_RP,_To,_CMD,_CA,_EBO],[[0,1],[()=>ObjectLockConfiguration$,{[_hP]:1,[_xN]:_OLC}],[0,{[_hH]:_xarp}],[0,{[_hH]:_xabolt}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xaebo}]],1];PutObjectOutput$=[3,n0,_POO,0,[_E,_ETa,_CCRC,_CCRCC,_CCRCNVME,_CSHA,_CSHAh,_CT,_SSE,_VI,_SSECA,_SSECKMD,_SSEKMSKI,_SSEKMSEC,_BKE,_Si,_RC],[[0,{[_hH]:_xae}],[0,{[_hH]:_ETa}],[0,{[_hH]:_xacc}],[0,{[_hH]:_xacc_}],[0,{[_hH]:_xacc__}],[0,{[_hH]:_xacs}],[0,{[_hH]:_xacs_}],[0,{[_hH]:_xact}],[0,{[_hH]:_xasse}],[0,{[_hH]:_xavi}],[0,{[_hH]:_xasseca}],[0,{[_hH]:_xasseckM}],[()=>SSEKMSKeyId,{[_hH]:_xasseakki}],[()=>SSEKMSEncryptionContext,{[_hH]:_xassec}],[2,{[_hH]:_xassebke}],[1,{[_hH]:_xaos}],[0,{[_hH]:_xarc}]]];PutObjectRequest$=[3,n0,_POR,0,[_B,_K,_ACL_,_Bo,_CC,_CDo,_CEo,_CL,_CLo,_CMD,_CTo,_CA,_CCRC,_CCRCC,_CCRCNVME,_CSHA,_CSHAh,_Ex,_IM,_INM,_GFC,_GR,_GRACP,_GWACP,_WOB,_M,_SSE,_SC,_WRL,_SSECA,_SSECK,_SSECKMD,_SSEKMSKI,_SSEKMSEC,_BKE,_RP,_Tag,_OLM,_OLRUD,_OLLHS,_EBO],[[0,1],[0,1],[0,{[_hH]:_xaa}],[()=>StreamingBlob,16],[0,{[_hH]:_CC_}],[0,{[_hH]:_CD_}],[0,{[_hH]:_CE_}],[0,{[_hH]:_CL_}],[1,{[_hH]:_CL__}],[0,{[_hH]:_CM}],[0,{[_hH]:_CT_}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xacc}],[0,{[_hH]:_xacc_}],[0,{[_hH]:_xacc__}],[0,{[_hH]:_xacs}],[0,{[_hH]:_xacs_}],[4,{[_hH]:_Ex}],[0,{[_hH]:_IM_}],[0,{[_hH]:_INM_}],[0,{[_hH]:_xagfc}],[0,{[_hH]:_xagr}],[0,{[_hH]:_xagra}],[0,{[_hH]:_xagwa}],[1,{[_hH]:_xawob}],[128,{[_hPH]:_xam}],[0,{[_hH]:_xasse}],[0,{[_hH]:_xasc}],[0,{[_hH]:_xawrl}],[0,{[_hH]:_xasseca}],[()=>SSECustomerKey,{[_hH]:_xasseck}],[0,{[_hH]:_xasseckM}],[()=>SSEKMSKeyId,{[_hH]:_xasseakki}],[()=>SSEKMSEncryptionContext,{[_hH]:_xassec}],[2,{[_hH]:_xassebke}],[0,{[_hH]:_xarp}],[0,{[_hH]:_xat}],[0,{[_hH]:_xaolm}],[5,{[_hH]:_xaolrud}],[0,{[_hH]:_xaollh}],[0,{[_hH]:_xaebo}]],2];PutObjectRetentionOutput$=[3,n0,_PORO,0,[_RC],[[0,{[_hH]:_xarc}]]];PutObjectRetentionRequest$=[3,n0,_PORR,0,[_B,_K,_Ret,_RP,_VI,_BGR,_CMD,_CA,_EBO],[[0,1],[0,1],[()=>ObjectLockRetention$,{[_hP]:1,[_xN]:_Ret}],[0,{[_hH]:_xarp}],[0,{[_hQ]:_vI}],[2,{[_hH]:_xabgr}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xaebo}]],2];PutObjectTaggingOutput$=[3,n0,_POTO,0,[_VI],[[0,{[_hH]:_xavi}]]];PutObjectTaggingRequest$=[3,n0,_POTR,0,[_B,_K,_Tag,_VI,_CMD,_CA,_EBO,_RP],[[0,1],[0,1],[()=>Tagging$,{[_hP]:1,[_xN]:_Tag}],[0,{[_hQ]:_vI}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xaebo}],[0,{[_hH]:_xarp}]],3];PutPublicAccessBlockRequest$=[3,n0,_PPABR,0,[_B,_PABC,_CMD,_CA,_EBO],[[0,1],[()=>PublicAccessBlockConfiguration$,{[_hP]:1,[_xN]:_PABC}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xaebo}]],2];QueueConfiguration$=[3,n0,_QCue,0,[_QA,_Ev,_I,_F],[[0,{[_xN]:_Qu}],[64,{[_xF]:1,[_xN]:_Eve}],0,[()=>NotificationConfigurationFilter$,0]],2];RecordExpiration$=[3,n0,_REe,0,[_E,_D],[0,1],1];RecordsEvent$=[3,n0,_REec,0,[_Payl],[[21,{[_eP]:1}]]];Redirect$=[3,n0,_Red,0,[_HN,_HRC,_Pro,_RKPW,_RKW],[0,0,0,0,0]];RedirectAllRequestsTo$=[3,n0,_RART,0,[_HN,_Pro],[0,0],1];RenameObjectOutput$=[3,n0,_ROO,0,[],[]];RenameObjectRequest$=[3,n0,_ROR,0,[_B,_K,_RSen,_DIM,_DINM,_DIMS,_DIUS,_SIM,_SINM,_SIMS,_SIUS,_CTl],[[0,1],[0,1],[0,{[_hH]:_xars_}],[0,{[_hH]:_IM_}],[0,{[_hH]:_INM_}],[4,{[_hH]:_IMS_}],[4,{[_hH]:_IUS_}],[0,{[_hH]:_xarsim}],[0,{[_hH]:_xarsinm}],[6,{[_hH]:_xarsims}],[6,{[_hH]:_xarsius}],[0,{[_hH]:_xact_,[_iT]:1}]],3];ReplicaModifications$=[3,n0,_RM,0,[_S],[0],1];ReplicationConfiguration$=[3,n0,_RCe,0,[_Ro,_R],[0,[()=>ReplicationRules,{[_xF]:1,[_xN]:_Ru}]],2];ReplicationRule$=[3,n0,_RRe,0,[_S,_Des,_ID,_Pri,_P,_F,_SSC,_EOR,_DMR],[0,()=>Destination$,0,1,0,[()=>ReplicationRuleFilter$,0],()=>SourceSelectionCriteria$,()=>ExistingObjectReplication$,()=>DeleteMarkerReplication$],2];ReplicationRuleAndOperator$=[3,n0,_RRAO,0,[_P,_T],[0,[()=>TagSet,{[_xF]:1,[_xN]:_Ta}]]];ReplicationRuleFilter$=[3,n0,_RRF,0,[_P,_Ta,_An],[0,()=>Tag$,[()=>ReplicationRuleAndOperator$,0]]];ReplicationTime$=[3,n0,_RT,0,[_S,_Tim],[0,()=>ReplicationTimeValue$],2];ReplicationTimeValue$=[3,n0,_RTV,0,[_Mi],[1]];RequestPaymentConfiguration$=[3,n0,_RPC,0,[_Pay],[0],1];RequestProgress$=[3,n0,_RPe,0,[_Ena],[2]];RestoreObjectOutput$=[3,n0,_ROOe,0,[_RC,_ROP],[[0,{[_hH]:_xarc}],[0,{[_hH]:_xarop}]]];RestoreObjectRequest$=[3,n0,_RORe,0,[_B,_K,_VI,_RRes,_RP,_CA,_EBO],[[0,1],[0,1],[0,{[_hQ]:_vI}],[()=>RestoreRequest$,{[_hP]:1,[_xN]:_RRes}],[0,{[_hH]:_xarp}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xaebo}]],2];RestoreRequest$=[3,n0,_RRes,0,[_D,_GJP,_Ty,_Ti,_Desc,_SP,_OL],[1,()=>GlacierJobParameters$,0,0,0,()=>SelectParameters$,[()=>OutputLocation$,0]]];RestoreStatus$=[3,n0,_RSe,0,[_IRIP,_RED],[2,4]];RoutingRule$=[3,n0,_RRo,0,[_Red,_Co],[()=>Redirect$,()=>Condition$],1];S3KeyFilter$=[3,n0,_SKF,0,[_FRi],[[()=>FilterRuleList,{[_xF]:1,[_xN]:_FR}]]];S3Location$=[3,n0,_SL,0,[_BNu,_P,_En,_CACL,_ACL,_Tag,_UM,_SC],[0,0,[()=>Encryption$,0],0,[()=>Grants,0],[()=>Tagging$,0],[()=>UserMetadata,0],0],2];S3TablesDestination$=[3,n0,_STD,0,[_TBA,_TNa],[0,0],2];S3TablesDestinationResult$=[3,n0,_STDR,0,[_TBA,_TNa,_TA,_TN],[0,0,0,0],4];ScanRange$=[3,n0,_SR,0,[_St,_End],[1,1]];SelectObjectContentOutput$=[3,n0,_SOCO,0,[_Payl],[[()=>SelectObjectContentEventStream$,16]]];SelectObjectContentRequest$=[3,n0,_SOCR,0,[_B,_K,_Exp,_ETx,_IS,_OSu,_SSECA,_SSECK,_SSECKMD,_RPe,_SR,_EBO],[[0,1],[0,1],0,0,()=>InputSerialization$,()=>OutputSerialization$,[0,{[_hH]:_xasseca}],[()=>SSECustomerKey,{[_hH]:_xasseck}],[0,{[_hH]:_xasseckM}],()=>RequestProgress$,()=>ScanRange$,[0,{[_hH]:_xaebo}]],6];SelectParameters$=[3,n0,_SP,0,[_IS,_ETx,_Exp,_OSu],[()=>InputSerialization$,0,0,()=>OutputSerialization$],4];ServerSideEncryptionByDefault$=[3,n0,_SSEBD,0,[_SSEA,_KMSMKID],[0,[()=>SSEKMSKeyId,0]],1];ServerSideEncryptionConfiguration$=[3,n0,_SSEC,0,[_R],[[()=>ServerSideEncryptionRules,{[_xF]:1,[_xN]:_Ru}]],1];ServerSideEncryptionRule$=[3,n0,_SSER,0,[_ASSEBD,_BKE,_BET],[[()=>ServerSideEncryptionByDefault$,0],2,[()=>BlockedEncryptionTypes$,0]]];SessionCredentials$=[3,n0,_SCe,0,[_AKI,_SAK,_ST,_E],[[0,{[_xN]:_AKI}],[()=>SessionCredentialValue,{[_xN]:_SAK}],[()=>SessionCredentialValue,{[_xN]:_ST}],[4,{[_xN]:_E}]],4];SimplePrefix$=[3,n0,_SPi,{[_xN]:_SPi},[],[]];SourceSelectionCriteria$=[3,n0,_SSC,0,[_SKEO,_RM],[()=>SseKmsEncryptedObjects$,()=>ReplicaModifications$]];SSEKMS$=[3,n0,_SSEKMS,{[_xN]:_SK},[_KI],[[()=>SSEKMSKeyId,0]],1];SseKmsEncryptedObjects$=[3,n0,_SKEO,0,[_S],[0],1];SSEKMSEncryption$=[3,n0,_SSEKMSE,{[_xN]:_SK},[_KMSKA,_BKE],[[()=>NonEmptyKmsKeyArnString,0],2],1];SSES3$=[3,n0,_SSES,{[_xN]:_SS},[],[]];Stats$=[3,n0,_Sta,0,[_BS,_BP,_BRy],[1,1,1]];StatsEvent$=[3,n0,_SE,0,[_Det],[[()=>Stats$,{[_eP]:1}]]];StorageClassAnalysis$=[3,n0,_SCA,0,[_DE],[()=>StorageClassAnalysisDataExport$]];StorageClassAnalysisDataExport$=[3,n0,_SCADE,0,[_OSV,_Des],[0,()=>AnalyticsExportDestination$],2];Tag$=[3,n0,_Ta,0,[_K,_V],[0,0],2];Tagging$=[3,n0,_Tag,0,[_TS],[[()=>TagSet,0]],1];TargetGrant$=[3,n0,_TGa,0,[_Gra,_Pe],[[()=>Grantee$,{[_xNm]:[_x,_hi]}],0]];TargetObjectKeyFormat$=[3,n0,_TOKF,0,[_SPi,_PP],[[()=>SimplePrefix$,{[_xN]:_SPi}],[()=>PartitionedPrefix$,{[_xN]:_PP}]]];Tiering$=[3,n0,_Tier,0,[_D,_AT],[1,0],2];TopicConfiguration$=[3,n0,_TCop,0,[_TAo,_Ev,_I,_F],[[0,{[_xN]:_Top}],[64,{[_xF]:1,[_xN]:_Eve}],0,[()=>NotificationConfigurationFilter$,0]],2];Transition$=[3,n0,_Tra,0,[_Da,_D,_SC],[5,1,0]];UpdateBucketMetadataInventoryTableConfigurationRequest$=[3,n0,_UBMITCR,0,[_B,_ITCn,_CMD,_CA,_EBO],[[0,1],[()=>InventoryTableConfigurationUpdates$,{[_hP]:1,[_xN]:_ITCn}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xaebo}]],2];UpdateBucketMetadataJournalTableConfigurationRequest$=[3,n0,_UBMJTCR,0,[_B,_JTC,_CMD,_CA,_EBO],[[0,1],[()=>JournalTableConfigurationUpdates$,{[_hP]:1,[_xN]:_JTC}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xaebo}]],2];UpdateObjectEncryptionRequest$=[3,n0,_UOER,0,[_B,_K,_OE,_VI,_RP,_EBO,_CMD,_CA],[[0,1],[0,1],[()=>ObjectEncryption$,16],[0,{[_hQ]:_vI}],[0,{[_hH]:_xarp}],[0,{[_hH]:_xaebo}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}]],3];UpdateObjectEncryptionResponse$=[3,n0,_UOERp,0,[_RC],[[0,{[_hH]:_xarc}]]];UploadPartCopyOutput$=[3,n0,_UPCO,0,[_CSVI,_CPR,_SSE,_SSECA,_SSECKMD,_SSEKMSKI,_BKE,_RC],[[0,{[_hH]:_xacsvi}],[()=>CopyPartResult$,16],[0,{[_hH]:_xasse}],[0,{[_hH]:_xasseca}],[0,{[_hH]:_xasseckM}],[()=>SSEKMSKeyId,{[_hH]:_xasseakki}],[2,{[_hH]:_xassebke}],[0,{[_hH]:_xarc}]]];UploadPartCopyRequest$=[3,n0,_UPCR,0,[_B,_CS,_K,_PN,_UI,_CSIM,_CSIMS,_CSINM,_CSIUS,_CSRo,_SSECA,_SSECK,_SSECKMD,_CSSSECA,_CSSSECK,_CSSSECKMD,_RP,_EBO,_ESBO],[[0,1],[0,{[_hH]:_xacs__}],[0,1],[1,{[_hQ]:_pN}],[0,{[_hQ]:_uI}],[0,{[_hH]:_xacsim}],[4,{[_hH]:_xacsims}],[0,{[_hH]:_xacsinm}],[4,{[_hH]:_xacsius}],[0,{[_hH]:_xacsr}],[0,{[_hH]:_xasseca}],[()=>SSECustomerKey,{[_hH]:_xasseck}],[0,{[_hH]:_xasseckM}],[0,{[_hH]:_xacssseca}],[()=>CopySourceSSECustomerKey,{[_hH]:_xacssseck}],[0,{[_hH]:_xacssseckM}],[0,{[_hH]:_xarp}],[0,{[_hH]:_xaebo}],[0,{[_hH]:_xasebo}]],5];UploadPartOutput$=[3,n0,_UPO,0,[_SSE,_ETa,_CCRC,_CCRCC,_CCRCNVME,_CSHA,_CSHAh,_SSECA,_SSECKMD,_SSEKMSKI,_BKE,_RC],[[0,{[_hH]:_xasse}],[0,{[_hH]:_ETa}],[0,{[_hH]:_xacc}],[0,{[_hH]:_xacc_}],[0,{[_hH]:_xacc__}],[0,{[_hH]:_xacs}],[0,{[_hH]:_xacs_}],[0,{[_hH]:_xasseca}],[0,{[_hH]:_xasseckM}],[()=>SSEKMSKeyId,{[_hH]:_xasseakki}],[2,{[_hH]:_xassebke}],[0,{[_hH]:_xarc}]]];UploadPartRequest$=[3,n0,_UPR,0,[_B,_K,_PN,_UI,_Bo,_CLo,_CMD,_CA,_CCRC,_CCRCC,_CCRCNVME,_CSHA,_CSHAh,_SSECA,_SSECK,_SSECKMD,_RP,_EBO],[[0,1],[0,1],[1,{[_hQ]:_pN}],[0,{[_hQ]:_uI}],[()=>StreamingBlob,16],[1,{[_hH]:_CL__}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xacc}],[0,{[_hH]:_xacc_}],[0,{[_hH]:_xacc__}],[0,{[_hH]:_xacs}],[0,{[_hH]:_xacs_}],[0,{[_hH]:_xasseca}],[()=>SSECustomerKey,{[_hH]:_xasseck}],[0,{[_hH]:_xasseckM}],[0,{[_hH]:_xarp}],[0,{[_hH]:_xaebo}]],4];VersioningConfiguration$=[3,n0,_VC,0,[_MFAD,_S],[[0,{[_xN]:_MDf}],0]];WebsiteConfiguration$=[3,n0,_WC,0,[_EDr,_IDn,_RART,_RR],[()=>ErrorDocument$,()=>IndexDocument$,()=>RedirectAllRequestsTo$,[()=>RoutingRules,0]]];WriteGetObjectResponseRequest$=[3,n0,_WGORR,0,[_RReq,_RTe,_Bo,_SCt,_ECr,_EM,_AR,_CC,_CDo,_CEo,_CL,_CLo,_CR,_CTo,_CCRC,_CCRCC,_CCRCNVME,_CSHA,_CSHAh,_DM,_ETa,_Ex,_E,_LM,_MM,_M,_OLM,_OLLHS,_OLRUD,_PC,_RS,_RC,_Re,_SSE,_SSECA,_SSEKMSKI,_SSECKMD,_SC,_TC,_VI,_BKE],[[0,{[_hL]:1,[_hH]:_xarr}],[0,{[_hH]:_xart}],[()=>StreamingBlob,16],[1,{[_hH]:_xafs}],[0,{[_hH]:_xafec}],[0,{[_hH]:_xafem}],[0,{[_hH]:_xafhar}],[0,{[_hH]:_xafhCC}],[0,{[_hH]:_xafhCD}],[0,{[_hH]:_xafhCE}],[0,{[_hH]:_xafhCL}],[1,{[_hH]:_CL__}],[0,{[_hH]:_xafhCR}],[0,{[_hH]:_xafhCT}],[0,{[_hH]:_xafhxacc}],[0,{[_hH]:_xafhxacc_}],[0,{[_hH]:_xafhxacc__}],[0,{[_hH]:_xafhxacs}],[0,{[_hH]:_xafhxacs_}],[2,{[_hH]:_xafhxadm}],[0,{[_hH]:_xafhE}],[4,{[_hH]:_xafhE_}],[0,{[_hH]:_xafhxae}],[4,{[_hH]:_xafhLM}],[1,{[_hH]:_xafhxamm}],[128,{[_hPH]:_xam}],[0,{[_hH]:_xafhxaolm}],[0,{[_hH]:_xafhxaollh}],[5,{[_hH]:_xafhxaolrud}],[1,{[_hH]:_xafhxampc}],[0,{[_hH]:_xafhxars}],[0,{[_hH]:_xafhxarc}],[0,{[_hH]:_xafhxar}],[0,{[_hH]:_xafhxasse}],[0,{[_hH]:_xafhxasseca}],[()=>SSEKMSKeyId,{[_hH]:_xafhxasseakki}],[0,{[_hH]:_xafhxasseckM}],[0,{[_hH]:_xafhxasc}],[1,{[_hH]:_xafhxatc}],[0,{[_hH]:_xafhxavi}],[2,{[_hH]:_xafhxassebke}]],2];__Unit="unit";0;0;0;AnalyticsConfigurationList=[1,n0,_ACLn,0,[()=>AnalyticsConfiguration$,0]];Buckets=[1,n0,_Bu,0,[()=>Bucket$,{[_xN]:_B}]];0;CommonPrefixList=[1,n0,_CPL,0,()=>CommonPrefix$];CompletedPartList=[1,n0,_CPLo,0,()=>CompletedPart$];CORSRules=[1,n0,_CORSR,0,[()=>CORSRule$,0]];DeletedObjects=[1,n0,_DOe,0,()=>DeletedObject$];DeleteMarkers=[1,n0,_DMe,0,()=>DeleteMarkerEntry$];EncryptionTypeList=[1,n0,_ETL,0,[0,{[_xN]:_ET}]];Errors=[1,n0,_Er,0,()=>_Error$];0;0;FilterRuleList=[1,n0,_FRL,0,()=>FilterRule$];Grants=[1,n0,_G,0,[()=>Grant$,{[_xN]:_Gr}]];IntelligentTieringConfigurationList=[1,n0,_ITCL,0,[()=>IntelligentTieringConfiguration$,0]];InventoryConfigurationList=[1,n0,_ICL,0,[()=>InventoryConfiguration$,0]];InventoryOptionalFields=[1,n0,_IOF,0,[0,{[_xN]:_Fi}]];LambdaFunctionConfigurationList=[1,n0,_LFCL,0,[()=>LambdaFunctionConfiguration$,0]];LifecycleRules=[1,n0,_LRi,0,[()=>LifecycleRule$,0]];MetricsConfigurationList=[1,n0,_MCL,0,[()=>MetricsConfiguration$,0]];MultipartUploadList=[1,n0,_MUL,0,()=>MultipartUpload$];NoncurrentVersionTransitionList=[1,n0,_NVTL,0,()=>NoncurrentVersionTransition$];0;ObjectIdentifierList=[1,n0,_OIL,0,()=>ObjectIdentifier$];ObjectList=[1,n0,_OLb,0,[()=>_Object$,0]];ObjectVersionList=[1,n0,_OVL,0,[()=>ObjectVersion$,0]];0;OwnershipControlsRules=[1,n0,_OCRw,0,()=>OwnershipControlsRule$];Parts=[1,n0,_Pa,0,()=>Part$];PartsList=[1,n0,_PL,0,()=>ObjectPart$];QueueConfigurationList=[1,n0,_QCL,0,[()=>QueueConfiguration$,0]];ReplicationRules=[1,n0,_RRep,0,[()=>ReplicationRule$,0]];RoutingRules=[1,n0,_RR,0,[()=>RoutingRule$,{[_xN]:_RRo}]];ServerSideEncryptionRules=[1,n0,_SSERe,0,[()=>ServerSideEncryptionRule$,0]];TagSet=[1,n0,_TS,0,[()=>Tag$,{[_xN]:_Ta}]];TargetGrants=[1,n0,_TG,0,[()=>TargetGrant$,{[_xN]:_Gr}]];TieringList=[1,n0,_TL,0,()=>Tiering$];TopicConfigurationList=[1,n0,_TCL,0,[()=>TopicConfiguration$,0]];TransitionList=[1,n0,_TLr,0,()=>Transition$];UserMetadata=[1,n0,_UM,0,[()=>MetadataEntry$,{[_xN]:_ME}]];0;AnalyticsFilter$=[4,n0,_AF,0,[_P,_Ta,_An],[0,()=>Tag$,[()=>AnalyticsAndOperator$,0]]];MetricsFilter$=[4,n0,_MF,0,[_P,_Ta,_APAc,_An],[0,()=>Tag$,0,[()=>MetricsAndOperator$,0]]];ObjectEncryption$=[4,n0,_OE,0,[_SSEKMS],[[()=>SSEKMSEncryption$,{[_xN]:_SK}]]];SelectObjectContentEventStream$=[4,n0,_SOCES,{[_st]:1},[_Rec,_Sta,_Pr,_Cont,_End],[[()=>RecordsEvent$,0],[()=>StatsEvent$,0],[()=>ProgressEvent$,0],()=>ContinuationEvent$,()=>EndEvent$]];AbortMultipartUpload$=[9,n0,_AMU,{[_h]:["DELETE","/{Key+}?x-id=AbortMultipartUpload",204]},()=>AbortMultipartUploadRequest$,()=>AbortMultipartUploadOutput$];CompleteMultipartUpload$=[9,n0,_CMUo,{[_h]:["POST","/{Key+}",200]},()=>CompleteMultipartUploadRequest$,()=>CompleteMultipartUploadOutput$];CopyObject$=[9,n0,_CO,{[_h]:["PUT","/{Key+}?x-id=CopyObject",200]},()=>CopyObjectRequest$,()=>CopyObjectOutput$];CreateBucket$=[9,n0,_CB,{[_h]:["PUT","/",200]},()=>CreateBucketRequest$,()=>CreateBucketOutput$];CreateBucketMetadataConfiguration$=[9,n0,_CBMC,{[_hC]:"-",[_h]:["POST","/?metadataConfiguration",200]},()=>CreateBucketMetadataConfigurationRequest$,()=>__Unit];CreateBucketMetadataTableConfiguration$=[9,n0,_CBMTC,{[_hC]:"-",[_h]:["POST","/?metadataTable",200]},()=>CreateBucketMetadataTableConfigurationRequest$,()=>__Unit];CreateMultipartUpload$=[9,n0,_CMUr,{[_h]:["POST","/{Key+}?uploads",200]},()=>CreateMultipartUploadRequest$,()=>CreateMultipartUploadOutput$];CreateSession$=[9,n0,_CSr,{[_h]:["GET","/?session",200]},()=>CreateSessionRequest$,()=>CreateSessionOutput$];DeleteBucket$=[9,n0,_DB,{[_h]:["DELETE","/",204]},()=>DeleteBucketRequest$,()=>__Unit];DeleteBucketAnalyticsConfiguration$=[9,n0,_DBAC,{[_h]:["DELETE","/?analytics",204]},()=>DeleteBucketAnalyticsConfigurationRequest$,()=>__Unit];DeleteBucketCors$=[9,n0,_DBC,{[_h]:["DELETE","/?cors",204]},()=>DeleteBucketCorsRequest$,()=>__Unit];DeleteBucketEncryption$=[9,n0,_DBE,{[_h]:["DELETE","/?encryption",204]},()=>DeleteBucketEncryptionRequest$,()=>__Unit];DeleteBucketIntelligentTieringConfiguration$=[9,n0,_DBITC,{[_h]:["DELETE","/?intelligent-tiering",204]},()=>DeleteBucketIntelligentTieringConfigurationRequest$,()=>__Unit];DeleteBucketInventoryConfiguration$=[9,n0,_DBIC,{[_h]:["DELETE","/?inventory",204]},()=>DeleteBucketInventoryConfigurationRequest$,()=>__Unit];DeleteBucketLifecycle$=[9,n0,_DBL,{[_h]:["DELETE","/?lifecycle",204]},()=>DeleteBucketLifecycleRequest$,()=>__Unit];DeleteBucketMetadataConfiguration$=[9,n0,_DBMC,{[_h]:["DELETE","/?metadataConfiguration",204]},()=>DeleteBucketMetadataConfigurationRequest$,()=>__Unit];DeleteBucketMetadataTableConfiguration$=[9,n0,_DBMTC,{[_h]:["DELETE","/?metadataTable",204]},()=>DeleteBucketMetadataTableConfigurationRequest$,()=>__Unit];DeleteBucketMetricsConfiguration$=[9,n0,_DBMCe,{[_h]:["DELETE","/?metrics",204]},()=>DeleteBucketMetricsConfigurationRequest$,()=>__Unit];DeleteBucketOwnershipControls$=[9,n0,_DBOC,{[_h]:["DELETE","/?ownershipControls",204]},()=>DeleteBucketOwnershipControlsRequest$,()=>__Unit];DeleteBucketPolicy$=[9,n0,_DBP,{[_h]:["DELETE","/?policy",204]},()=>DeleteBucketPolicyRequest$,()=>__Unit];DeleteBucketReplication$=[9,n0,_DBRe,{[_h]:["DELETE","/?replication",204]},()=>DeleteBucketReplicationRequest$,()=>__Unit];DeleteBucketTagging$=[9,n0,_DBT,{[_h]:["DELETE","/?tagging",204]},()=>DeleteBucketTaggingRequest$,()=>__Unit];DeleteBucketWebsite$=[9,n0,_DBW,{[_h]:["DELETE","/?website",204]},()=>DeleteBucketWebsiteRequest$,()=>__Unit];DeleteObject$=[9,n0,_DOel,{[_h]:["DELETE","/{Key+}?x-id=DeleteObject",204]},()=>DeleteObjectRequest$,()=>DeleteObjectOutput$];DeleteObjects$=[9,n0,_DOele,{[_hC]:"-",[_h]:["POST","/?delete",200]},()=>DeleteObjectsRequest$,()=>DeleteObjectsOutput$];DeleteObjectTagging$=[9,n0,_DOT,{[_h]:["DELETE","/{Key+}?tagging",204]},()=>DeleteObjectTaggingRequest$,()=>DeleteObjectTaggingOutput$];DeletePublicAccessBlock$=[9,n0,_DPAB,{[_h]:["DELETE","/?publicAccessBlock",204]},()=>DeletePublicAccessBlockRequest$,()=>__Unit];GetBucketAbac$=[9,n0,_GBA,{[_h]:["GET","/?abac",200]},()=>GetBucketAbacRequest$,()=>GetBucketAbacOutput$];GetBucketAccelerateConfiguration$=[9,n0,_GBAC,{[_h]:["GET","/?accelerate",200]},()=>GetBucketAccelerateConfigurationRequest$,()=>GetBucketAccelerateConfigurationOutput$];GetBucketAcl$=[9,n0,_GBAe,{[_h]:["GET","/?acl",200]},()=>GetBucketAclRequest$,()=>GetBucketAclOutput$];GetBucketAnalyticsConfiguration$=[9,n0,_GBACe,{[_h]:["GET","/?analytics&x-id=GetBucketAnalyticsConfiguration",200]},()=>GetBucketAnalyticsConfigurationRequest$,()=>GetBucketAnalyticsConfigurationOutput$];GetBucketCors$=[9,n0,_GBC,{[_h]:["GET","/?cors",200]},()=>GetBucketCorsRequest$,()=>GetBucketCorsOutput$];GetBucketEncryption$=[9,n0,_GBE,{[_h]:["GET","/?encryption",200]},()=>GetBucketEncryptionRequest$,()=>GetBucketEncryptionOutput$];GetBucketIntelligentTieringConfiguration$=[9,n0,_GBITC,{[_h]:["GET","/?intelligent-tiering&x-id=GetBucketIntelligentTieringConfiguration",200]},()=>GetBucketIntelligentTieringConfigurationRequest$,()=>GetBucketIntelligentTieringConfigurationOutput$];GetBucketInventoryConfiguration$=[9,n0,_GBIC,{[_h]:["GET","/?inventory&x-id=GetBucketInventoryConfiguration",200]},()=>GetBucketInventoryConfigurationRequest$,()=>GetBucketInventoryConfigurationOutput$];GetBucketLifecycleConfiguration$=[9,n0,_GBLC,{[_h]:["GET","/?lifecycle",200]},()=>GetBucketLifecycleConfigurationRequest$,()=>GetBucketLifecycleConfigurationOutput$];GetBucketLocation$=[9,n0,_GBL,{[_h]:["GET","/?location",200]},()=>GetBucketLocationRequest$,()=>GetBucketLocationOutput$];GetBucketLogging$=[9,n0,_GBLe,{[_h]:["GET","/?logging",200]},()=>GetBucketLoggingRequest$,()=>GetBucketLoggingOutput$];GetBucketMetadataConfiguration$=[9,n0,_GBMC,{[_h]:["GET","/?metadataConfiguration",200]},()=>GetBucketMetadataConfigurationRequest$,()=>GetBucketMetadataConfigurationOutput$];GetBucketMetadataTableConfiguration$=[9,n0,_GBMTC,{[_h]:["GET","/?metadataTable",200]},()=>GetBucketMetadataTableConfigurationRequest$,()=>GetBucketMetadataTableConfigurationOutput$];GetBucketMetricsConfiguration$=[9,n0,_GBMCe,{[_h]:["GET","/?metrics&x-id=GetBucketMetricsConfiguration",200]},()=>GetBucketMetricsConfigurationRequest$,()=>GetBucketMetricsConfigurationOutput$];GetBucketNotificationConfiguration$=[9,n0,_GBNC,{[_h]:["GET","/?notification",200]},()=>GetBucketNotificationConfigurationRequest$,()=>NotificationConfiguration$];GetBucketOwnershipControls$=[9,n0,_GBOC,{[_h]:["GET","/?ownershipControls",200]},()=>GetBucketOwnershipControlsRequest$,()=>GetBucketOwnershipControlsOutput$];GetBucketPolicy$=[9,n0,_GBP,{[_h]:["GET","/?policy",200]},()=>GetBucketPolicyRequest$,()=>GetBucketPolicyOutput$];GetBucketPolicyStatus$=[9,n0,_GBPS,{[_h]:["GET","/?policyStatus",200]},()=>GetBucketPolicyStatusRequest$,()=>GetBucketPolicyStatusOutput$];GetBucketReplication$=[9,n0,_GBR,{[_h]:["GET","/?replication",200]},()=>GetBucketReplicationRequest$,()=>GetBucketReplicationOutput$];GetBucketRequestPayment$=[9,n0,_GBRP,{[_h]:["GET","/?requestPayment",200]},()=>GetBucketRequestPaymentRequest$,()=>GetBucketRequestPaymentOutput$];GetBucketTagging$=[9,n0,_GBT,{[_h]:["GET","/?tagging",200]},()=>GetBucketTaggingRequest$,()=>GetBucketTaggingOutput$];GetBucketVersioning$=[9,n0,_GBV,{[_h]:["GET","/?versioning",200]},()=>GetBucketVersioningRequest$,()=>GetBucketVersioningOutput$];GetBucketWebsite$=[9,n0,_GBW,{[_h]:["GET","/?website",200]},()=>GetBucketWebsiteRequest$,()=>GetBucketWebsiteOutput$];GetObject$=[9,n0,_GO,{[_hC]:"-",[_h]:["GET","/{Key+}?x-id=GetObject",200]},()=>GetObjectRequest$,()=>GetObjectOutput$];GetObjectAcl$=[9,n0,_GOA,{[_h]:["GET","/{Key+}?acl",200]},()=>GetObjectAclRequest$,()=>GetObjectAclOutput$];GetObjectAttributes$=[9,n0,_GOAe,{[_h]:["GET","/{Key+}?attributes",200]},()=>GetObjectAttributesRequest$,()=>GetObjectAttributesOutput$];GetObjectLegalHold$=[9,n0,_GOLH,{[_h]:["GET","/{Key+}?legal-hold",200]},()=>GetObjectLegalHoldRequest$,()=>GetObjectLegalHoldOutput$];GetObjectLockConfiguration$=[9,n0,_GOLC,{[_h]:["GET","/?object-lock",200]},()=>GetObjectLockConfigurationRequest$,()=>GetObjectLockConfigurationOutput$];GetObjectRetention$=[9,n0,_GORe,{[_h]:["GET","/{Key+}?retention",200]},()=>GetObjectRetentionRequest$,()=>GetObjectRetentionOutput$];GetObjectTagging$=[9,n0,_GOT,{[_h]:["GET","/{Key+}?tagging",200]},()=>GetObjectTaggingRequest$,()=>GetObjectTaggingOutput$];GetObjectTorrent$=[9,n0,_GOTe,{[_h]:["GET","/{Key+}?torrent",200]},()=>GetObjectTorrentRequest$,()=>GetObjectTorrentOutput$];GetPublicAccessBlock$=[9,n0,_GPAB,{[_h]:["GET","/?publicAccessBlock",200]},()=>GetPublicAccessBlockRequest$,()=>GetPublicAccessBlockOutput$];HeadBucket$=[9,n0,_HB,{[_h]:["HEAD","/",200]},()=>HeadBucketRequest$,()=>HeadBucketOutput$];HeadObject$=[9,n0,_HO,{[_h]:["HEAD","/{Key+}",200]},()=>HeadObjectRequest$,()=>HeadObjectOutput$];ListBucketAnalyticsConfigurations$=[9,n0,_LBAC,{[_h]:["GET","/?analytics&x-id=ListBucketAnalyticsConfigurations",200]},()=>ListBucketAnalyticsConfigurationsRequest$,()=>ListBucketAnalyticsConfigurationsOutput$];ListBucketIntelligentTieringConfigurations$=[9,n0,_LBITC,{[_h]:["GET","/?intelligent-tiering&x-id=ListBucketIntelligentTieringConfigurations",200]},()=>ListBucketIntelligentTieringConfigurationsRequest$,()=>ListBucketIntelligentTieringConfigurationsOutput$];ListBucketInventoryConfigurations$=[9,n0,_LBIC,{[_h]:["GET","/?inventory&x-id=ListBucketInventoryConfigurations",200]},()=>ListBucketInventoryConfigurationsRequest$,()=>ListBucketInventoryConfigurationsOutput$];ListBucketMetricsConfigurations$=[9,n0,_LBMC,{[_h]:["GET","/?metrics&x-id=ListBucketMetricsConfigurations",200]},()=>ListBucketMetricsConfigurationsRequest$,()=>ListBucketMetricsConfigurationsOutput$];ListBuckets$=[9,n0,_LB,{[_h]:["GET","/?x-id=ListBuckets",200]},()=>ListBucketsRequest$,()=>ListBucketsOutput$];ListDirectoryBuckets$=[9,n0,_LDB,{[_h]:["GET","/?x-id=ListDirectoryBuckets",200]},()=>ListDirectoryBucketsRequest$,()=>ListDirectoryBucketsOutput$];ListMultipartUploads$=[9,n0,_LMU,{[_h]:["GET","/?uploads",200]},()=>ListMultipartUploadsRequest$,()=>ListMultipartUploadsOutput$];ListObjects$=[9,n0,_LO,{[_h]:["GET","/",200]},()=>ListObjectsRequest$,()=>ListObjectsOutput$];ListObjectsV2$=[9,n0,_LOV,{[_h]:["GET","/?list-type=2",200]},()=>ListObjectsV2Request$,()=>ListObjectsV2Output$];ListObjectVersions$=[9,n0,_LOVi,{[_h]:["GET","/?versions",200]},()=>ListObjectVersionsRequest$,()=>ListObjectVersionsOutput$];ListParts$=[9,n0,_LP,{[_h]:["GET","/{Key+}?x-id=ListParts",200]},()=>ListPartsRequest$,()=>ListPartsOutput$];PutBucketAbac$=[9,n0,_PBA,{[_hC]:"-",[_h]:["PUT","/?abac",200]},()=>PutBucketAbacRequest$,()=>__Unit];PutBucketAccelerateConfiguration$=[9,n0,_PBAC,{[_hC]:"-",[_h]:["PUT","/?accelerate",200]},()=>PutBucketAccelerateConfigurationRequest$,()=>__Unit];PutBucketAcl$=[9,n0,_PBAu,{[_hC]:"-",[_h]:["PUT","/?acl",200]},()=>PutBucketAclRequest$,()=>__Unit];PutBucketAnalyticsConfiguration$=[9,n0,_PBACu,{[_h]:["PUT","/?analytics",200]},()=>PutBucketAnalyticsConfigurationRequest$,()=>__Unit];PutBucketCors$=[9,n0,_PBC,{[_hC]:"-",[_h]:["PUT","/?cors",200]},()=>PutBucketCorsRequest$,()=>__Unit];PutBucketEncryption$=[9,n0,_PBE,{[_hC]:"-",[_h]:["PUT","/?encryption",200]},()=>PutBucketEncryptionRequest$,()=>__Unit];PutBucketIntelligentTieringConfiguration$=[9,n0,_PBITC,{[_h]:["PUT","/?intelligent-tiering",200]},()=>PutBucketIntelligentTieringConfigurationRequest$,()=>__Unit];PutBucketInventoryConfiguration$=[9,n0,_PBIC,{[_h]:["PUT","/?inventory",200]},()=>PutBucketInventoryConfigurationRequest$,()=>__Unit];PutBucketLifecycleConfiguration$=[9,n0,_PBLC,{[_hC]:"-",[_h]:["PUT","/?lifecycle",200]},()=>PutBucketLifecycleConfigurationRequest$,()=>PutBucketLifecycleConfigurationOutput$];PutBucketLogging$=[9,n0,_PBL,{[_hC]:"-",[_h]:["PUT","/?logging",200]},()=>PutBucketLoggingRequest$,()=>__Unit];PutBucketMetricsConfiguration$=[9,n0,_PBMC,{[_h]:["PUT","/?metrics",200]},()=>PutBucketMetricsConfigurationRequest$,()=>__Unit];PutBucketNotificationConfiguration$=[9,n0,_PBNC,{[_h]:["PUT","/?notification",200]},()=>PutBucketNotificationConfigurationRequest$,()=>__Unit];PutBucketOwnershipControls$=[9,n0,_PBOC,{[_hC]:"-",[_h]:["PUT","/?ownershipControls",200]},()=>PutBucketOwnershipControlsRequest$,()=>__Unit];PutBucketPolicy$=[9,n0,_PBP,{[_hC]:"-",[_h]:["PUT","/?policy",200]},()=>PutBucketPolicyRequest$,()=>__Unit];PutBucketReplication$=[9,n0,_PBR,{[_hC]:"-",[_h]:["PUT","/?replication",200]},()=>PutBucketReplicationRequest$,()=>__Unit];PutBucketRequestPayment$=[9,n0,_PBRP,{[_hC]:"-",[_h]:["PUT","/?requestPayment",200]},()=>PutBucketRequestPaymentRequest$,()=>__Unit];PutBucketTagging$=[9,n0,_PBT,{[_hC]:"-",[_h]:["PUT","/?tagging",200]},()=>PutBucketTaggingRequest$,()=>__Unit];PutBucketVersioning$=[9,n0,_PBV,{[_hC]:"-",[_h]:["PUT","/?versioning",200]},()=>PutBucketVersioningRequest$,()=>__Unit];PutBucketWebsite$=[9,n0,_PBW,{[_hC]:"-",[_h]:["PUT","/?website",200]},()=>PutBucketWebsiteRequest$,()=>__Unit];PutObject$=[9,n0,_PO,{[_hC]:"-",[_h]:["PUT","/{Key+}?x-id=PutObject",200]},()=>PutObjectRequest$,()=>PutObjectOutput$];PutObjectAcl$=[9,n0,_POA,{[_hC]:"-",[_h]:["PUT","/{Key+}?acl",200]},()=>PutObjectAclRequest$,()=>PutObjectAclOutput$];PutObjectLegalHold$=[9,n0,_POLH,{[_hC]:"-",[_h]:["PUT","/{Key+}?legal-hold",200]},()=>PutObjectLegalHoldRequest$,()=>PutObjectLegalHoldOutput$];PutObjectLockConfiguration$=[9,n0,_POLC,{[_hC]:"-",[_h]:["PUT","/?object-lock",200]},()=>PutObjectLockConfigurationRequest$,()=>PutObjectLockConfigurationOutput$];PutObjectRetention$=[9,n0,_PORu,{[_hC]:"-",[_h]:["PUT","/{Key+}?retention",200]},()=>PutObjectRetentionRequest$,()=>PutObjectRetentionOutput$];PutObjectTagging$=[9,n0,_POT,{[_hC]:"-",[_h]:["PUT","/{Key+}?tagging",200]},()=>PutObjectTaggingRequest$,()=>PutObjectTaggingOutput$];PutPublicAccessBlock$=[9,n0,_PPAB,{[_hC]:"-",[_h]:["PUT","/?publicAccessBlock",200]},()=>PutPublicAccessBlockRequest$,()=>__Unit];RenameObject$=[9,n0,_RO,{[_h]:["PUT","/{Key+}?renameObject",200]},()=>RenameObjectRequest$,()=>RenameObjectOutput$];RestoreObject$=[9,n0,_ROe,{[_hC]:"-",[_h]:["POST","/{Key+}?restore",200]},()=>RestoreObjectRequest$,()=>RestoreObjectOutput$];SelectObjectContent$=[9,n0,_SOC,{[_h]:["POST","/{Key+}?select&select-type=2",200]},()=>SelectObjectContentRequest$,()=>SelectObjectContentOutput$];UpdateBucketMetadataInventoryTableConfiguration$=[9,n0,_UBMITC,{[_hC]:"-",[_h]:["PUT","/?metadataInventoryTable",200]},()=>UpdateBucketMetadataInventoryTableConfigurationRequest$,()=>__Unit];UpdateBucketMetadataJournalTableConfiguration$=[9,n0,_UBMJTC,{[_hC]:"-",[_h]:["PUT","/?metadataJournalTable",200]},()=>UpdateBucketMetadataJournalTableConfigurationRequest$,()=>__Unit];UpdateObjectEncryption$=[9,n0,_UOE,{[_hC]:"-",[_h]:["PUT","/{Key+}?encryption",200]},()=>UpdateObjectEncryptionRequest$,()=>UpdateObjectEncryptionResponse$];UploadPart$=[9,n0,_UP,{[_hC]:"-",[_h]:["PUT","/{Key+}?x-id=UploadPart",200]},()=>UploadPartRequest$,()=>UploadPartOutput$];UploadPartCopy$=[9,n0,_UPC,{[_h]:["PUT","/{Key+}?x-id=UploadPartCopy",200]},()=>UploadPartCopyRequest$,()=>UploadPartCopyOutput$];WriteGetObjectResponse$=[9,n0,_WGOR,{[_en]:["{RequestRoute}."],[_h]:["POST","/WriteGetObjectResponse",200]},()=>WriteGetObjectResponseRequest$,()=>__Unit];CreateSessionCommand=class extends(Command.classBuilder().ep({...commonParams,DisableS3ExpressSessionAuth:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","CreateSession",{}).n("S3Client","CreateSessionCommand").sc(CreateSession$).build()){};package_default_version="3.1017.0";fromUtf84=input=>(new TextEncoder).encode(input);0;SHA_1_HASH={name:"SHA-1"};SHA_1_HMAC_ALGO={name:"HMAC",hash:SHA_1_HASH};EMPTY_DATA_SHA_1=new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]);fallbackWindow={};Sha1=function(){function Sha13(secret){this.toHash=new Uint8Array(0);if(void 0!==secret){this.key=new Promise(function(resolve,reject){locateWindow().crypto.subtle.importKey("raw",convertToBuffer2(secret),SHA_1_HMAC_ALGO,!1,["sign"]).then(resolve,reject)});this.key.catch(function(){})}}Sha13.prototype.update=function(data){var update2,typedArray;if(!isEmptyData2(data)){update2=convertToBuffer2(data);typedArray=new Uint8Array(this.toHash.byteLength+update2.byteLength);typedArray.set(this.toHash,0);typedArray.set(update2,this.toHash.byteLength);this.toHash=typedArray}};Sha13.prototype.digest=function(){var _this=this;return this.key?this.key.then(function(key3){return locateWindow().crypto.subtle.sign(SHA_1_HMAC_ALGO,key3,_this.toHash).then(function(data){return new Uint8Array(data)})}):isEmptyData2(this.toHash)?Promise.resolve(EMPTY_DATA_SHA_1):Promise.resolve().then(function(){return locateWindow().crypto.subtle.digest(SHA_1_HASH,_this.toHash)}).then(function(data){return Promise.resolve(new Uint8Array(data))})};Sha13.prototype.reset=function(){this.toHash=new Uint8Array(0)};return Sha13}();init_tslib_es6();subtleCryptoMethods=["decrypt","digest","encrypt","exportKey","generateKey","importKey","sign","verify"];init_module();Sha12=function(){function Sha13(secret){if(!supportsWebCrypto(locateWindow()))throw new Error("SHA1 not supported");this.hash=new Sha1(secret)}Sha13.prototype.update=function(data,encoding){this.hash.update(convertToBuffer(data))};Sha13.prototype.digest=function(){return this.hash.digest()};Sha13.prototype.reset=function(){this.hash.reset()};return Sha13}();SHA_256_HASH={name:"SHA-256"};SHA_256_HMAC_ALGO={name:"HMAC",hash:SHA_256_HASH};EMPTY_DATA_SHA_256=new Uint8Array([227,176,196,66,152,252,28,20,154,251,244,200,153,111,185,36,39,174,65,228,100,155,147,76,164,149,153,27,120,82,184,85]);init_module();Sha256=function(){function Sha2564(secret){this.toHash=new Uint8Array(0);this.secret=secret;this.reset()}Sha2564.prototype.update=function(data){var update2,typedArray;if(!isEmptyData(data)){update2=convertToBuffer(data);typedArray=new Uint8Array(this.toHash.byteLength+update2.byteLength);typedArray.set(this.toHash,0);typedArray.set(update2,this.toHash.byteLength);this.toHash=typedArray}};Sha2564.prototype.digest=function(){var _this=this;return this.key?this.key.then(function(key3){return locateWindow().crypto.subtle.sign(SHA_256_HMAC_ALGO,key3,_this.toHash).then(function(data){return new Uint8Array(data)})}):isEmptyData(this.toHash)?Promise.resolve(EMPTY_DATA_SHA_256):Promise.resolve().then(function(){return locateWindow().crypto.subtle.digest(SHA_256_HASH,_this.toHash)}).then(function(data){return Promise.resolve(new Uint8Array(data))})};Sha2564.prototype.reset=function(){var _this=this;this.toHash=new Uint8Array(0);if(this.secret&&void 0!==this.secret){this.key=new Promise(function(resolve,reject){locateWindow().crypto.subtle.importKey("raw",convertToBuffer(_this.secret),SHA_256_HMAC_ALGO,!1,["sign"]).then(resolve,reject)});this.key.catch(function(){})}};return Sha2564}();BLOCK_SIZE=64;DIGEST_LENGTH=32;KEY=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);INIT=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];MAX_HASHABLE_LENGTH=Math.pow(2,53)-1;RawSha256=function(){function RawSha2562(){this.state=Int32Array.from(INIT);this.temp=new Int32Array(64);this.buffer=new Uint8Array(64);this.bufferLength=0;this.bytesHashed=0;this.finished=!1}RawSha2562.prototype.update=function(data){var position,byteLength;if(this.finished)throw new Error("Attempted to update an already finished hash.");position=0;byteLength=data.byteLength;this.bytesHashed+=byteLength;if(8*this.bytesHashed>MAX_HASHABLE_LENGTH)throw new Error("Cannot hash more than 2^53 - 1 bits");for(;byteLength>0;){this.buffer[this.bufferLength++]=data[position++];byteLength--;if(this.bufferLength===BLOCK_SIZE){this.hashBuffer();this.bufferLength=0}}};RawSha2562.prototype.digest=function(){var bitsHashed,bufferView,undecoratedLength,i3,out;if(!this.finished){bitsHashed=8*this.bytesHashed;bufferView=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength);undecoratedLength=this.bufferLength;bufferView.setUint8(this.bufferLength++,128);if(undecoratedLength%BLOCK_SIZE>=BLOCK_SIZE-8){for(i3=this.bufferLength;i3<BLOCK_SIZE;i3++)bufferView.setUint8(i3,0);this.hashBuffer();this.bufferLength=0}for(i3=this.bufferLength;i3<BLOCK_SIZE-8;i3++)bufferView.setUint8(i3,0);bufferView.setUint32(BLOCK_SIZE-8,Math.floor(bitsHashed/4294967296),!0);bufferView.setUint32(BLOCK_SIZE-4,bitsHashed);this.hashBuffer();this.finished=!0}out=new Uint8Array(DIGEST_LENGTH);for(i3=0;i3<8;i3++){out[4*i3]=this.state[i3]>>>24&255;out[4*i3+1]=this.state[i3]>>>16&255;out[4*i3+2]=this.state[i3]>>>8&255;out[4*i3+3]=this.state[i3]>>>0&255}return out};RawSha2562.prototype.hashBuffer=function(){var i3,u2,t1_1,t2_1,t12,t22,_a13=this,buffer=_a13.buffer,state2=_a13.state,state0=state2[0],state1=state2[1],state22=state2[2],state3=state2[3],state4=state2[4],state5=state2[5],state6=state2[6],state7=state2[7];for(i3=0;i3<BLOCK_SIZE;i3++){if(i3<16)this.temp[i3]=(255&buffer[4*i3])<<24|(255&buffer[4*i3+1])<<16|(255&buffer[4*i3+2])<<8|255&buffer[4*i3+3];else{u2=this.temp[i3-2];t1_1=(u2>>>17|u2<<15)^(u2>>>19|u2<<13)^u2>>>10;u2=this.temp[i3-15];t2_1=(u2>>>7|u2<<25)^(u2>>>18|u2<<14)^u2>>>3;this.temp[i3]=(t1_1+this.temp[i3-7]|0)+(t2_1+this.temp[i3-16]|0)}t12=(((state4>>>6|state4<<26)^(state4>>>11|state4<<21)^(state4>>>25|state4<<7))+(state4&state5^~state4&state6)|0)+(state7+(KEY[i3]+this.temp[i3]|0)|0)|0;t22=((state0>>>2|state0<<30)^(state0>>>13|state0<<19)^(state0>>>22|state0<<10))+(state0&state1^state0&state22^state1&state22)|0;state7=state6;state6=state5;state5=state4;state4=state3+t12|0;state3=state22;state22=state1;state1=state0;state0=t12+t22|0}state2[0]+=state0;state2[1]+=state1;state2[2]+=state22;state2[3]+=state3;state2[4]+=state4;state2[5]+=state5;state2[6]+=state6;state2[7]+=state7};return RawSha2562}();init_tslib_es6();init_module();Sha2562=function(){function Sha2564(secret){this.secret=secret;this.hash=new RawSha256;this.reset()}Sha2564.prototype.update=function(toHash){if(!isEmptyData(toHash)&&!this.error)try{this.hash.update(convertToBuffer(toHash))}catch(e3){this.error=e3}};Sha2564.prototype.digestSync=function(){if(this.error)throw this.error;if(this.outer){this.outer.finished||this.outer.update(this.hash.digest());return this.outer.digest()}return this.hash.digest()};Sha2564.prototype.digest=function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a13){return[2,this.digestSync()]})})};Sha2564.prototype.reset=function(){var inner,outer,i3;this.hash=new RawSha256;if(this.secret){this.outer=new RawSha256;inner=bufferFromSecret(this.secret);outer=new Uint8Array(BLOCK_SIZE);outer.set(inner);for(i3=0;i3<BLOCK_SIZE;i3++){inner[i3]^=54;outer[i3]^=92}this.hash.update(inner);this.outer.update(outer);for(i3=0;i3<inner.byteLength;i3++)inner[i3]=0}};return Sha2564}();init_module();Sha2563=function(){function Sha2564(secret){supportsWebCrypto(locateWindow())?this.hash=new Sha256(secret):this.hash=new Sha2562(secret)}Sha2564.prototype.update=function(data,encoding){this.hash.update(convertToBuffer(data))};Sha2564.prototype.digest=function(){return this.hash.digest()};Sha2564.prototype.reset=function(){this.hash.reset()};return Sha2564}();createDefaultUserAgentProvider=({serviceId,clientVersion})=>async config=>{var _a13,_b6,_c3,_d2,_e2,_f,_g,_h2,_i2,_j;const navigator2="undefined"!=typeof window?window.navigator:void 0,uaString=null!=(_a13=null==navigator2?void 0:navigator2.userAgent)?_a13:"",osName=null!=(_d2=null!=(_c3=null==(_b6=null==navigator2?void 0:navigator2.userAgentData)?void 0:_b6.platform)?_c3:fallback2.os(uaString))?_d2:"other",brands=null!=(_f=null==(_e2=null==navigator2?void 0:navigator2.userAgentData)?void 0:_e2.brands)?_f:[],brand=brands[brands.length-1],browserName=null!=(_h2=null!=(_g=null==brand?void 0:brand.brand)?_g:fallback2.browser(uaString))?_h2:"unknown",browserVersion=null!=(_i2=null==brand?void 0:brand.version)?_i2:"unknown",sections=[["aws-sdk-js",clientVersion],["ua","2.1"],[`os/${osName}`,void 0],["lang/js"],["md/browser",`${browserName}_${browserVersion}`]];serviceId&&sections.push([`api/${serviceId}`,clientVersion]);const appId=await(null==(_j=null==config?void 0:config.userAgentAppId)?void 0:_j.call(config));appId&&sections.push([`app/${appId}`]);return sections};fallback2={os:ua=>/iPhone|iPad|iPod/.test(ua)?"iOS":/Macintosh|Mac OS X/.test(ua)?"macOS":/Windows NT/.test(ua)?"Windows":/Android/.test(ua)?"Android":/Linux/.test(ua)?"Linux":void 0,browser:ua=>/EdgiOS|EdgA|Edg\//.test(ua)?"Microsoft Edge":/Firefox\//.test(ua)?"Firefox":/Chrome\//.test(ua)?"Chrome":/Safari\//.test(ua)?"Safari":void 0};0;Int643=class _Int64{constructor(bytes){__publicField(this,"bytes");this.bytes=bytes;if(8!==bytes.byteLength)throw new Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(number){if(number>0x8000000000000000||number<-0x8000000000000000)throw new Error(`${number} is too large (or, if negative, too small) to represent as an Int64`);const bytes=new Uint8Array(8);for(let i3=7,remaining=Math.abs(Math.round(number));i3>-1&&remaining>0;i3--,remaining/=256)bytes[i3]=remaining;number<0&&negate3(bytes);return new _Int64(bytes)}valueOf(){const bytes=this.bytes.slice(0),negative=128&bytes[0];negative&&negate3(bytes);return parseInt(toHex3(bytes),16)*(negative?-1:1)}toString(){return String(this.valueOf())}};HeaderMarshaller2=class{constructor(toUtf82,fromUtf85){__publicField(this,"toUtf8");__publicField(this,"fromUtf8");this.toUtf8=toUtf82;this.fromUtf8=fromUtf85}format(headers){const chunks=[];for(const headerName of Object.keys(headers)){const bytes=this.fromUtf8(headerName);chunks.push(Uint8Array.from([bytes.byteLength]),bytes,this.formatHeaderValue(headers[headerName]))}const out=new Uint8Array(chunks.reduce((carry,bytes)=>carry+bytes.byteLength,0));let position=0;for(const chunk of chunks){out.set(chunk,position);position+=chunk.byteLength}return out}formatHeaderValue(header){switch(header.type){case"boolean":return Uint8Array.from([header.value?0:1]);case"byte":return Uint8Array.from([2,header.value]);case"short":const shortView=new DataView(new ArrayBuffer(3));shortView.setUint8(0,3);shortView.setInt16(1,header.value,!1);return new Uint8Array(shortView.buffer);case"integer":const intView=new DataView(new ArrayBuffer(5));intView.setUint8(0,4);intView.setInt32(1,header.value,!1);return new Uint8Array(intView.buffer);case"long":const longBytes=new Uint8Array(9);longBytes[0]=5;longBytes.set(header.value.bytes,1);return longBytes;case"binary":const binView=new DataView(new ArrayBuffer(3+header.value.byteLength));binView.setUint8(0,6);binView.setUint16(1,header.value.byteLength,!1);const binBytes=new Uint8Array(binView.buffer);binBytes.set(header.value,3);return binBytes;case"string":const utf8Bytes=this.fromUtf8(header.value),strView=new DataView(new ArrayBuffer(3+utf8Bytes.byteLength));strView.setUint8(0,7);strView.setUint16(1,utf8Bytes.byteLength,!1);const strBytes=new Uint8Array(strView.buffer);strBytes.set(utf8Bytes,3);return strBytes;case"timestamp":const tsBytes=new Uint8Array(9);tsBytes[0]=8;tsBytes.set(Int643.fromNumber(header.value.valueOf()).bytes,1);return tsBytes;case"uuid":if(!UUID_PATTERN3.test(header.value))throw new Error(`Invalid UUID received: ${header.value}`);const uuidBytes=new Uint8Array(17);uuidBytes[0]=9;uuidBytes.set(fromHex2(header.value.replace(/\-/g,"")),1);return uuidBytes}}parse(headers){const out={};let position=0;for(;position<headers.byteLength;){const nameLength=headers.getUint8(position++),name=this.toUtf8(new Uint8Array(headers.buffer,headers.byteOffset+position,nameLength));position+=nameLength;switch(headers.getUint8(position++)){case 0:out[name]={type:BOOLEAN_TAG2,value:!0};break;case 1:out[name]={type:BOOLEAN_TAG2,value:!1};break;case 2:out[name]={type:BYTE_TAG2,value:headers.getInt8(position++)};break;case 3:out[name]={type:SHORT_TAG2,value:headers.getInt16(position,!1)};position+=2;break;case 4:out[name]={type:INT_TAG2,value:headers.getInt32(position,!1)};position+=4;break;case 5:out[name]={type:LONG_TAG2,value:new Int643(new Uint8Array(headers.buffer,headers.byteOffset+position,8))};position+=8;break;case 6:const binaryLength=headers.getUint16(position,!1);position+=2;out[name]={type:BINARY_TAG2,value:new Uint8Array(headers.buffer,headers.byteOffset+position,binaryLength)};position+=binaryLength;break;case 7:const stringLength=headers.getUint16(position,!1);position+=2;out[name]={type:STRING_TAG2,value:this.toUtf8(new Uint8Array(headers.buffer,headers.byteOffset+position,stringLength))};position+=stringLength;break;case 8:out[name]={type:TIMESTAMP_TAG2,value:new Date(new Int643(new Uint8Array(headers.buffer,headers.byteOffset+position,8)).valueOf())};position+=8;break;case 9:const uuidBytes=new Uint8Array(headers.buffer,headers.byteOffset+position,16);position+=16;out[name]={type:UUID_TAG2,value:`${toHex3(uuidBytes.subarray(0,4))}-${toHex3(uuidBytes.subarray(4,6))}-${toHex3(uuidBytes.subarray(6,8))}-${toHex3(uuidBytes.subarray(8,10))}-${toHex3(uuidBytes.subarray(10))}`};break;default:throw new Error("Unrecognized header type tag")}}return out}};(function(HEADER_VALUE_TYPE4){HEADER_VALUE_TYPE4[HEADER_VALUE_TYPE4.boolTrue=0]="boolTrue";HEADER_VALUE_TYPE4[HEADER_VALUE_TYPE4.boolFalse=1]="boolFalse";HEADER_VALUE_TYPE4[HEADER_VALUE_TYPE4.byte=2]="byte";HEADER_VALUE_TYPE4[HEADER_VALUE_TYPE4.short=3]="short";HEADER_VALUE_TYPE4[HEADER_VALUE_TYPE4.integer=4]="integer";HEADER_VALUE_TYPE4[HEADER_VALUE_TYPE4.long=5]="long";HEADER_VALUE_TYPE4[HEADER_VALUE_TYPE4.byteArray=6]="byteArray";HEADER_VALUE_TYPE4[HEADER_VALUE_TYPE4.string=7]="string";HEADER_VALUE_TYPE4[HEADER_VALUE_TYPE4.timestamp=8]="timestamp";HEADER_VALUE_TYPE4[HEADER_VALUE_TYPE4.uuid=9]="uuid"})(HEADER_VALUE_TYPE3||(HEADER_VALUE_TYPE3={}));BOOLEAN_TAG2="boolean";BYTE_TAG2="byte";SHORT_TAG2="short";INT_TAG2="integer";LONG_TAG2="long";BINARY_TAG2="binary";STRING_TAG2="string";TIMESTAMP_TAG2="timestamp";UUID_TAG2="uuid";UUID_PATTERN3=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;init_module2();PRELUDE_MEMBER_LENGTH2=4;PRELUDE_LENGTH2=2*PRELUDE_MEMBER_LENGTH2;CHECKSUM_LENGTH2=4;MINIMUM_MESSAGE_LENGTH2=PRELUDE_LENGTH2+2*CHECKSUM_LENGTH2;init_module2();EventStreamCodec2=class{constructor(toUtf82,fromUtf85){__publicField(this,"headerMarshaller");__publicField(this,"messageBuffer");__publicField(this,"isEndOfStream");this.headerMarshaller=new HeaderMarshaller2(toUtf82,fromUtf85);this.messageBuffer=[];this.isEndOfStream=!1}feed(message){this.messageBuffer.push(this.decode(message))}endOfStream(){this.isEndOfStream=!0}getMessage(){const message=this.messageBuffer.pop(),isEndOfStream=this.isEndOfStream;return{getMessage:()=>message,isEndOfStream:()=>isEndOfStream}}getAvailableMessages(){const messages=this.messageBuffer;this.messageBuffer=[];const isEndOfStream=this.isEndOfStream;return{getMessages:()=>messages,isEndOfStream:()=>isEndOfStream}}encode({headers:rawHeaders,body}){const headers=this.headerMarshaller.format(rawHeaders),length=headers.byteLength+body.byteLength+16,out=new Uint8Array(length),view=new DataView(out.buffer,out.byteOffset,out.byteLength),checksum=new Crc32;view.setUint32(0,length,!1);view.setUint32(4,headers.byteLength,!1);view.setUint32(8,checksum.update(out.subarray(0,8)).digest(),!1);out.set(headers,12);out.set(body,headers.byteLength+12);view.setUint32(length-4,checksum.update(out.subarray(8,length-4)).digest(),!1);return out}decode(message){const{headers,body}=splitMessage2(message);return{headers:this.headerMarshaller.parse(headers),body}}formatHeaders(rawHeaders){return this.headerMarshaller.format(rawHeaders)}};MessageDecoderStream2=class{constructor(options){__publicField(this,"options");this.options=options}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(const bytes of this.options.inputStream){const decoded=this.options.decoder.decode(bytes);yield decoded}}};MessageEncoderStream2=class{constructor(options){__publicField(this,"options");this.options=options}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(const msg of this.options.messageStream){const encoded=this.options.encoder.encode(msg);yield encoded}this.options.includeEndFrame&&(yield new Uint8Array(0))}};SmithyMessageDecoderStream2=class{constructor(options){__publicField(this,"options");this.options=options}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(const message of this.options.messageStream){const deserialized=await this.options.deserializer(message);void 0!==deserialized&&(yield deserialized)}}};SmithyMessageEncoderStream2=class{constructor(options){__publicField(this,"options");this.options=options}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(const chunk of this.options.inputStream){const payloadBuf=this.options.serializer(chunk);yield payloadBuf}}};EventStreamMarshaller3=class{constructor({utf8Encoder,utf8Decoder}){__publicField(this,"eventStreamCodec");__publicField(this,"utfEncoder");this.eventStreamCodec=new EventStreamCodec2(utf8Encoder,utf8Decoder);this.utfEncoder=utf8Encoder}deserialize(body,deserializer){const inputStream=getChunkedStream2(body);return new SmithyMessageDecoderStream2({messageStream:new MessageDecoderStream2({inputStream,decoder:this.eventStreamCodec}),deserializer:getMessageUnmarshaller2(deserializer,this.utfEncoder)})}serialize(inputStream,serializer){return new MessageEncoderStream2({messageStream:new SmithyMessageEncoderStream2({inputStream,serializer}),encoder:this.eventStreamCodec,includeEndFrame:!0})}};readableStreamtoIterable=readableStream=>({[Symbol.asyncIterator]:async function*(){const reader=readableStream.getReader();try{for(;;){const{done,value}=await reader.read();if(done)return;yield value}}finally{reader.releaseLock()}}});iterableToReadableStream2=asyncIterable=>{const iterator=asyncIterable[Symbol.asyncIterator]();return new ReadableStream({async pull(controller){const{done,value}=await iterator.next();if(done)return controller.close();controller.enqueue(value)}})};EventStreamMarshaller4=class{constructor({utf8Encoder,utf8Decoder}){__publicField(this,"universalMarshaller");this.universalMarshaller=new EventStreamMarshaller3({utf8Decoder,utf8Encoder})}deserialize(body,deserializer){const bodyIterable=isReadableStream4(body)?readableStreamtoIterable(body):body;return this.universalMarshaller.deserialize(bodyIterable,deserializer)}serialize(input,serializer){const serialziedIterable=this.universalMarshaller.serialize(input,serializer);return"function"==typeof ReadableStream?iterableToReadableStream2(serialziedIterable):serialziedIterable}};isReadableStream4=body=>"function"==typeof ReadableStream&&body instanceof ReadableStream;eventStreamSerdeProvider3=options=>new EventStreamMarshaller4(options);blobHasher=async function blobHasher2(hashCtor,blob){const hash3=new hashCtor;await blobReader(blob,chunk=>{hash3.update(chunk)});return hash3.digest()};invalidProvider2=message=>()=>Promise.reject(message);BLOCK_SIZE2=64;DIGEST_LENGTH2=16;INIT2=[1732584193,4023233417,2562383102,271733878];Md5=class{constructor(){__publicField(this,"state");__publicField(this,"buffer");__publicField(this,"bufferLength");__publicField(this,"bytesHashed");__publicField(this,"finished");this.reset()}update(sourceData){if(isEmptyData3(sourceData))return;if(this.finished)throw new Error("Attempted to update an already finished hash.");const data=convertToBuffer3(sourceData);let position=0,{byteLength}=data;this.bytesHashed+=byteLength;for(;byteLength>0;){this.buffer.setUint8(this.bufferLength++,data[position++]);byteLength--;if(this.bufferLength===BLOCK_SIZE2){this.hashBuffer();this.bufferLength=0}}}async digest(){if(!this.finished){const{buffer,bufferLength:undecoratedLength,bytesHashed}=this,bitsHashed=8*bytesHashed;buffer.setUint8(this.bufferLength++,128);if(undecoratedLength%BLOCK_SIZE2>=BLOCK_SIZE2-8){for(let i3=this.bufferLength;i3<BLOCK_SIZE2;i3++)buffer.setUint8(i3,0);this.hashBuffer();this.bufferLength=0}for(let i3=this.bufferLength;i3<BLOCK_SIZE2-8;i3++)buffer.setUint8(i3,0);buffer.setUint32(BLOCK_SIZE2-8,bitsHashed>>>0,!0);buffer.setUint32(BLOCK_SIZE2-4,Math.floor(bitsHashed/4294967296),!0);this.hashBuffer();this.finished=!0}const out=new DataView(new ArrayBuffer(DIGEST_LENGTH2));for(let i3=0;i3<4;i3++)out.setUint32(4*i3,this.state[i3],!0);return new Uint8Array(out.buffer,out.byteOffset,out.byteLength)}hashBuffer(){const{buffer,state:state2}=this;let a2=state2[0],b3=state2[1],c3=state2[2],d4=state2[3];a2=ff(a2,b3,c3,d4,buffer.getUint32(0,!0),7,3614090360);d4=ff(d4,a2,b3,c3,buffer.getUint32(4,!0),12,3905402710);c3=ff(c3,d4,a2,b3,buffer.getUint32(8,!0),17,606105819);b3=ff(b3,c3,d4,a2,buffer.getUint32(12,!0),22,3250441966);a2=ff(a2,b3,c3,d4,buffer.getUint32(16,!0),7,4118548399);d4=ff(d4,a2,b3,c3,buffer.getUint32(20,!0),12,1200080426);c3=ff(c3,d4,a2,b3,buffer.getUint32(24,!0),17,2821735955);b3=ff(b3,c3,d4,a2,buffer.getUint32(28,!0),22,4249261313);a2=ff(a2,b3,c3,d4,buffer.getUint32(32,!0),7,1770035416);d4=ff(d4,a2,b3,c3,buffer.getUint32(36,!0),12,2336552879);c3=ff(c3,d4,a2,b3,buffer.getUint32(40,!0),17,4294925233);b3=ff(b3,c3,d4,a2,buffer.getUint32(44,!0),22,2304563134);a2=ff(a2,b3,c3,d4,buffer.getUint32(48,!0),7,1804603682);d4=ff(d4,a2,b3,c3,buffer.getUint32(52,!0),12,4254626195);c3=ff(c3,d4,a2,b3,buffer.getUint32(56,!0),17,2792965006);b3=ff(b3,c3,d4,a2,buffer.getUint32(60,!0),22,1236535329);a2=gg(a2,b3,c3,d4,buffer.getUint32(4,!0),5,4129170786);d4=gg(d4,a2,b3,c3,buffer.getUint32(24,!0),9,3225465664);c3=gg(c3,d4,a2,b3,buffer.getUint32(44,!0),14,643717713);b3=gg(b3,c3,d4,a2,buffer.getUint32(0,!0),20,3921069994);a2=gg(a2,b3,c3,d4,buffer.getUint32(20,!0),5,3593408605);d4=gg(d4,a2,b3,c3,buffer.getUint32(40,!0),9,38016083);c3=gg(c3,d4,a2,b3,buffer.getUint32(60,!0),14,3634488961);b3=gg(b3,c3,d4,a2,buffer.getUint32(16,!0),20,3889429448);a2=gg(a2,b3,c3,d4,buffer.getUint32(36,!0),5,568446438);d4=gg(d4,a2,b3,c3,buffer.getUint32(56,!0),9,3275163606);c3=gg(c3,d4,a2,b3,buffer.getUint32(12,!0),14,4107603335);b3=gg(b3,c3,d4,a2,buffer.getUint32(32,!0),20,1163531501);a2=gg(a2,b3,c3,d4,buffer.getUint32(52,!0),5,2850285829);d4=gg(d4,a2,b3,c3,buffer.getUint32(8,!0),9,4243563512);c3=gg(c3,d4,a2,b3,buffer.getUint32(28,!0),14,1735328473);b3=gg(b3,c3,d4,a2,buffer.getUint32(48,!0),20,2368359562);a2=hh(a2,b3,c3,d4,buffer.getUint32(20,!0),4,4294588738);d4=hh(d4,a2,b3,c3,buffer.getUint32(32,!0),11,2272392833);c3=hh(c3,d4,a2,b3,buffer.getUint32(44,!0),16,1839030562);b3=hh(b3,c3,d4,a2,buffer.getUint32(56,!0),23,4259657740);a2=hh(a2,b3,c3,d4,buffer.getUint32(4,!0),4,2763975236);d4=hh(d4,a2,b3,c3,buffer.getUint32(16,!0),11,1272893353);c3=hh(c3,d4,a2,b3,buffer.getUint32(28,!0),16,4139469664);b3=hh(b3,c3,d4,a2,buffer.getUint32(40,!0),23,3200236656);a2=hh(a2,b3,c3,d4,buffer.getUint32(52,!0),4,681279174);d4=hh(d4,a2,b3,c3,buffer.getUint32(0,!0),11,3936430074);c3=hh(c3,d4,a2,b3,buffer.getUint32(12,!0),16,3572445317);b3=hh(b3,c3,d4,a2,buffer.getUint32(24,!0),23,76029189);a2=hh(a2,b3,c3,d4,buffer.getUint32(36,!0),4,3654602809);d4=hh(d4,a2,b3,c3,buffer.getUint32(48,!0),11,3873151461);c3=hh(c3,d4,a2,b3,buffer.getUint32(60,!0),16,530742520);b3=hh(b3,c3,d4,a2,buffer.getUint32(8,!0),23,3299628645);a2=ii(a2,b3,c3,d4,buffer.getUint32(0,!0),6,4096336452);d4=ii(d4,a2,b3,c3,buffer.getUint32(28,!0),10,1126891415);c3=ii(c3,d4,a2,b3,buffer.getUint32(56,!0),15,2878612391);b3=ii(b3,c3,d4,a2,buffer.getUint32(20,!0),21,4237533241);a2=ii(a2,b3,c3,d4,buffer.getUint32(48,!0),6,1700485571);d4=ii(d4,a2,b3,c3,buffer.getUint32(12,!0),10,2399980690);c3=ii(c3,d4,a2,b3,buffer.getUint32(40,!0),15,4293915773);b3=ii(b3,c3,d4,a2,buffer.getUint32(4,!0),21,2240044497);a2=ii(a2,b3,c3,d4,buffer.getUint32(32,!0),6,1873313359);d4=ii(d4,a2,b3,c3,buffer.getUint32(60,!0),10,4264355552);c3=ii(c3,d4,a2,b3,buffer.getUint32(24,!0),15,2734768916);b3=ii(b3,c3,d4,a2,buffer.getUint32(52,!0),21,1309151649);a2=ii(a2,b3,c3,d4,buffer.getUint32(16,!0),6,4149444226);d4=ii(d4,a2,b3,c3,buffer.getUint32(44,!0),10,3174756917);c3=ii(c3,d4,a2,b3,buffer.getUint32(8,!0),15,718787259);b3=ii(b3,c3,d4,a2,buffer.getUint32(36,!0),21,3951481745);state2[0]=a2+state2[0]&4294967295;state2[1]=b3+state2[1]&4294967295;state2[2]=c3+state2[2]&4294967295;state2[3]=d4+state2[3]&4294967295}reset(){this.state=Uint32Array.from(INIT2);this.buffer=new DataView(new ArrayBuffer(BLOCK_SIZE2));this.bufferLength=0;this.bytesHashed=0;this.finished=!1}};TEXT_ENCODER2="function"==typeof TextEncoder?new TextEncoder:null;calculateBodyLength2=body=>{if("string"==typeof body){if(TEXT_ENCODER2)return TEXT_ENCODER2.encode(body).byteLength;let len=body.length;for(let i3=len-1;i3>=0;i3--){const code=body.charCodeAt(i3);code>127&&code<=2047?len++:code>2047&&code<=65535&&(len+=2);code>=56320&&code<=57343&&i3--}return len}if("number"==typeof body.byteLength)return body.byteLength;if("number"==typeof body.size)return body.size;throw new Error(`Body Length computation failed for ${body}`)};DEFAULTS_MODE_OPTIONS=["in-region","cross-region","mobile","standard","legacy"];resolveDefaultsModeConfig=({defaultsMode}={})=>memoize(async()=>{const mode="function"==typeof defaultsMode?await defaultsMode():defaultsMode;switch(null==mode?void 0:mode.toLowerCase()){case"auto":return Promise.resolve(useMobileConfiguration()?"mobile":"standard");case"mobile":case"in-region":case"cross-region":case"standard":case"legacy":return Promise.resolve(null==mode?void 0:mode.toLocaleLowerCase());case void 0:return Promise.resolve("legacy");default:throw new Error(`Invalid parameter for "defaultsMode", expect ${DEFAULTS_MODE_OPTIONS.join(", ")}, got ${mode}`)}});useMobileConfiguration=()=>{var _a13;const navigator2=null==window?void 0:window.navigator;if(null==navigator2?void 0:navigator2.connection){const{effectiveType,rtt,downlink}=null==navigator2?void 0:navigator2.connection,slow="string"==typeof effectiveType&&"4g"!==effectiveType||Number(rtt)>100||Number(downlink)<10;if(slow)return!0}return(null==(_a13=null==navigator2?void 0:navigator2.userAgentData)?void 0:_a13.mobile)||"number"==typeof(null==navigator2?void 0:navigator2.maxTouchPoints)&&(null==navigator2?void 0:navigator2.maxTouchPoints)>1};getRuntimeConfig=config=>{var _a13,_b6,_c3,_d2,_e2,_f,_g,_h2,_i2,_j,_k,_l,_m2,_n,_o,_p2,_q,_r,_s2;return{apiVersion:"2006-03-01",base64Decoder:null!=(_a13=null==config?void 0:config.base64Decoder)?_a13:fromBase642,base64Encoder:null!=(_b6=null==config?void 0:config.base64Encoder)?_b6:toBase642,disableHostPrefix:null!=(_c3=null==config?void 0:config.disableHostPrefix)&&_c3,endpointProvider:null!=(_d2=null==config?void 0:config.endpointProvider)?_d2:defaultEndpointResolver,extensions:null!=(_e2=null==config?void 0:config.extensions)?_e2:[],getAwsChunkedEncodingStream:null!=(_f=null==config?void 0:config.getAwsChunkedEncodingStream)?_f:getAwsChunkedEncodingStream2,httpAuthSchemeProvider:null!=(_g=null==config?void 0:config.httpAuthSchemeProvider)?_g:defaultS3HttpAuthSchemeProvider,httpAuthSchemes:null!=(_h2=null==config?void 0:config.httpAuthSchemes)?_h2:[{schemeId:"aws.auth#sigv4",identityProvider:ipc=>ipc.getIdentityProvider("aws.auth#sigv4"),signer:new AwsSdkSigV4Signer},{schemeId:"aws.auth#sigv4a",identityProvider:ipc=>ipc.getIdentityProvider("aws.auth#sigv4a"),signer:new AwsSdkSigV4ASigner}],logger:null!=(_i2=null==config?void 0:config.logger)?_i2:new NoOpLogger,protocol:null!=(_j=null==config?void 0:config.protocol)?_j:S3RestXmlProtocol,protocolSettings:null!=(_k=null==config?void 0:config.protocolSettings)?_k:{defaultNamespace:"com.amazonaws.s3",errorTypeRegistries,xmlNamespace:"http://s3.amazonaws.com/doc/2006-03-01/",version:"2006-03-01",serviceTarget:"AmazonS3"},sdkStreamMixin:null!=(_l=null==config?void 0:config.sdkStreamMixin)?_l:sdkStreamMixin2,serviceId:null!=(_m2=null==config?void 0:config.serviceId)?_m2:"S3",signerConstructor:null!=(_n=null==config?void 0:config.signerConstructor)?_n:SignatureV4MultiRegion,signingEscapePath:null!=(_o=null==config?void 0:config.signingEscapePath)&&_o,urlParser:null!=(_p2=null==config?void 0:config.urlParser)?_p2:parseUrl2,useArnRegion:null!=(_q=null==config?void 0:config.useArnRegion)?_q:void 0,utf8Decoder:null!=(_r=null==config?void 0:config.utf8Decoder)?_r:fromUtf8,utf8Encoder:null!=(_s2=null==config?void 0:config.utf8Encoder)?_s2:toUtf8}};getRuntimeConfig2=config=>{var _a13,_b6,_c3,_d2,_e2,_f,_g,_h2,_i2,_j,_k,_l,_m2,_n,_o;const defaultsMode=resolveDefaultsModeConfig(config),defaultConfigProvider=()=>defaultsMode().then(loadConfigsForDefaultMode),clientSharedValues=getRuntimeConfig(config);return{...clientSharedValues,...config,runtime:"browser",defaultsMode,bodyLengthChecker:null!=(_a13=null==config?void 0:config.bodyLengthChecker)?_a13:calculateBodyLength2,credentialDefaultProvider:null!=(_b6=null==config?void 0:config.credentialDefaultProvider)?_b6:_=>()=>Promise.reject(new Error("Credential is missing")),defaultUserAgentProvider:null!=(_c3=null==config?void 0:config.defaultUserAgentProvider)?_c3:createDefaultUserAgentProvider({serviceId:clientSharedValues.serviceId,clientVersion:package_default_version}),eventStreamSerdeProvider:null!=(_d2=null==config?void 0:config.eventStreamSerdeProvider)?_d2:eventStreamSerdeProvider3,maxAttempts:null!=(_e2=null==config?void 0:config.maxAttempts)?_e2:DEFAULT_MAX_ATTEMPTS,md5:null!=(_f=null==config?void 0:config.md5)?_f:Md5,region:null!=(_g=null==config?void 0:config.region)?_g:invalidProvider2("Region is missing"),requestHandler:FetchHttpHandler.create(null!=(_h2=null==config?void 0:config.requestHandler)?_h2:defaultConfigProvider),retryMode:null!=(_i2=null==config?void 0:config.retryMode)?_i2:async()=>(await defaultConfigProvider()).retryMode||DEFAULT_RETRY_MODE,sha1:null!=(_j=null==config?void 0:config.sha1)?_j:Sha12,sha256:null!=(_k=null==config?void 0:config.sha256)?_k:Sha2563,streamCollector:null!=(_l=null==config?void 0:config.streamCollector)?_l:streamCollector2,streamHasher:null!=(_m2=null==config?void 0:config.streamHasher)?_m2:blobHasher,useDualstackEndpoint:null!=(_n=null==config?void 0:config.useDualstackEndpoint)?_n:()=>Promise.resolve(DEFAULT_USE_DUALSTACK_ENDPOINT),useFipsEndpoint:null!=(_o=null==config?void 0:config.useFipsEndpoint)?_o:()=>Promise.resolve(DEFAULT_USE_FIPS_ENDPOINT)}};getAwsRegionExtensionConfiguration=runtimeConfig=>({setRegion(region){runtimeConfig.region=region},region:()=>runtimeConfig.region});resolveAwsRegionExtensionConfiguration=awsRegionExtensionConfiguration=>({region:awsRegionExtensionConfiguration.region()});getHttpAuthExtensionConfiguration=runtimeConfig=>{const _httpAuthSchemes=runtimeConfig.httpAuthSchemes;let _httpAuthSchemeProvider=runtimeConfig.httpAuthSchemeProvider,_credentials=runtimeConfig.credentials;return{setHttpAuthScheme(httpAuthScheme){const index6=_httpAuthSchemes.findIndex(scheme=>scheme.schemeId===httpAuthScheme.schemeId);-1===index6?_httpAuthSchemes.push(httpAuthScheme):_httpAuthSchemes.splice(index6,1,httpAuthScheme)},httpAuthSchemes:()=>_httpAuthSchemes,setHttpAuthSchemeProvider(httpAuthSchemeProvider){_httpAuthSchemeProvider=httpAuthSchemeProvider},httpAuthSchemeProvider:()=>_httpAuthSchemeProvider,setCredentials(credentials){_credentials=credentials},credentials:()=>_credentials}};resolveHttpAuthRuntimeConfig=config=>({httpAuthSchemes:config.httpAuthSchemes(),httpAuthSchemeProvider:config.httpAuthSchemeProvider(),credentials:config.credentials()});resolveRuntimeExtensions=(runtimeConfig,extensions)=>{const extensionConfiguration=Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig),getDefaultExtensionConfiguration(runtimeConfig),getHttpHandlerExtensionConfiguration(runtimeConfig),getHttpAuthExtensionConfiguration(runtimeConfig));extensions.forEach(extension=>extension.configure(extensionConfiguration));return Object.assign(runtimeConfig,resolveAwsRegionExtensionConfiguration(extensionConfiguration),resolveDefaultRuntimeConfig(extensionConfiguration),resolveHttpHandlerRuntimeConfig(extensionConfiguration),resolveHttpAuthRuntimeConfig(extensionConfiguration))};S3Client=class extends Client{constructor(...[configuration]){const _config_0=getRuntimeConfig2(configuration||{});super(_config_0);__publicField(this,"config");this.initConfig=_config_0;const _config_1=resolveClientEndpointParameters(_config_0),_config_2=resolveUserAgentConfig(_config_1),_config_3=resolveFlexibleChecksumsConfig(_config_2),_config_4=resolveRetryConfig2(_config_3),_config_5=resolveRegionConfig(_config_4),_config_6=resolveHostHeaderConfig(_config_5),_config_7=resolveEndpointConfig2(_config_6),_config_8=resolveEventStreamSerdeConfig2(_config_7),_config_9=resolveHttpAuthSchemeConfig(_config_8),_config_10=resolveS3Config(_config_9,{session:[()=>this,CreateSessionCommand]}),_config_11=resolveRuntimeExtensions(_config_10,(null==configuration?void 0:configuration.extensions)||[]);this.config=_config_11;this.middlewareStack.use(getSchemaSerdePlugin(this.config));this.middlewareStack.use(getUserAgentPlugin(this.config));this.middlewareStack.use(getRetryPlugin2(this.config));this.middlewareStack.use(getContentLengthPlugin2(this.config));this.middlewareStack.use(getHostHeaderPlugin(this.config));this.middlewareStack.use(getLoggerPlugin(this.config));this.middlewareStack.use(getRecursionDetectionPlugin(this.config));this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config,{httpAuthSchemeParametersProvider:defaultS3HttpAuthSchemeParametersProvider,identityProviderConfigProvider:async config=>new DefaultIdentityProviderConfig({"aws.auth#sigv4":config.credentials,"aws.auth#sigv4a":config.credentials})}));this.middlewareStack.use(getHttpSigningPlugin(this.config));this.middlewareStack.use(getValidateBucketNamePlugin(this.config));this.middlewareStack.use(getAddExpectContinuePlugin(this.config));this.middlewareStack.use(getRegionRedirectMiddlewarePlugin(this.config));this.middlewareStack.use(getS3ExpressPlugin(this.config));this.middlewareStack.use(getS3ExpressHttpSigningPlugin(this.config))}destroy(){super.destroy()}};AbortMultipartUploadCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","AbortMultipartUpload",{}).n("S3Client","AbortMultipartUploadCommand").sc(AbortMultipartUpload$).build()){};ssecMiddlewareOptions={name:"ssecMiddleware",step:"initialize",tags:["SSE"],override:!0};getSsecPlugin=config=>({applyToStack:clientStack=>{clientStack.add(ssecMiddleware(config),ssecMiddlewareOptions)}});CompleteMultipartUploadCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config),getSsecPlugin(config)]}).s("AmazonS3","CompleteMultipartUpload",{}).n("S3Client","CompleteMultipartUploadCommand").sc(CompleteMultipartUpload$).build()){};CopyObjectCommand=class extends(Command.classBuilder().ep({...commonParams,DisableS3ExpressSessionAuth:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"},CopySource:{type:"contextParams",name:"CopySource"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config),getSsecPlugin(config)]}).s("AmazonS3","CopyObject",{}).n("S3Client","CopyObjectCommand").sc(CopyObject$).build()){};locationConstraintMiddlewareOptions={step:"initialize",tags:["LOCATION_CONSTRAINT","CREATE_BUCKET_CONFIGURATION"],name:"locationConstraintMiddleware",override:!0};getLocationConstraintPlugin=config=>({applyToStack:clientStack=>{clientStack.add(locationConstraintMiddleware(config),locationConstraintMiddlewareOptions)}});CreateBucketCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},DisableAccessPoints:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config),getLocationConstraintPlugin(config)]}).s("AmazonS3","CreateBucket",{}).n("S3Client","CreateBucketCommand").sc(CreateBucket$).build()){};CreateBucketMetadataConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","CreateBucketMetadataConfiguration",{}).n("S3Client","CreateBucketMetadataConfigurationCommand").sc(CreateBucketMetadataConfiguration$).build()){};CreateBucketMetadataTableConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","CreateBucketMetadataTableConfiguration",{}).n("S3Client","CreateBucketMetadataTableConfigurationCommand").sc(CreateBucketMetadataTableConfiguration$).build()){};CreateMultipartUploadCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config),getSsecPlugin(config)]}).s("AmazonS3","CreateMultipartUpload",{}).n("S3Client","CreateMultipartUploadCommand").sc(CreateMultipartUpload$).build()){};DeleteBucketAnalyticsConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucketAnalyticsConfiguration",{}).n("S3Client","DeleteBucketAnalyticsConfigurationCommand").sc(DeleteBucketAnalyticsConfiguration$).build()){};DeleteBucketCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucket",{}).n("S3Client","DeleteBucketCommand").sc(DeleteBucket$).build()){};DeleteBucketCorsCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucketCors",{}).n("S3Client","DeleteBucketCorsCommand").sc(DeleteBucketCors$).build()){};DeleteBucketEncryptionCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucketEncryption",{}).n("S3Client","DeleteBucketEncryptionCommand").sc(DeleteBucketEncryption$).build()){};DeleteBucketIntelligentTieringConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucketIntelligentTieringConfiguration",{}).n("S3Client","DeleteBucketIntelligentTieringConfigurationCommand").sc(DeleteBucketIntelligentTieringConfiguration$).build()){};DeleteBucketInventoryConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucketInventoryConfiguration",{}).n("S3Client","DeleteBucketInventoryConfigurationCommand").sc(DeleteBucketInventoryConfiguration$).build()){};DeleteBucketLifecycleCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucketLifecycle",{}).n("S3Client","DeleteBucketLifecycleCommand").sc(DeleteBucketLifecycle$).build()){};DeleteBucketMetadataConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucketMetadataConfiguration",{}).n("S3Client","DeleteBucketMetadataConfigurationCommand").sc(DeleteBucketMetadataConfiguration$).build()){};DeleteBucketMetadataTableConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucketMetadataTableConfiguration",{}).n("S3Client","DeleteBucketMetadataTableConfigurationCommand").sc(DeleteBucketMetadataTableConfiguration$).build()){};DeleteBucketMetricsConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucketMetricsConfiguration",{}).n("S3Client","DeleteBucketMetricsConfigurationCommand").sc(DeleteBucketMetricsConfiguration$).build()){};DeleteBucketOwnershipControlsCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucketOwnershipControls",{}).n("S3Client","DeleteBucketOwnershipControlsCommand").sc(DeleteBucketOwnershipControls$).build()){};DeleteBucketPolicyCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucketPolicy",{}).n("S3Client","DeleteBucketPolicyCommand").sc(DeleteBucketPolicy$).build()){};DeleteBucketReplicationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucketReplication",{}).n("S3Client","DeleteBucketReplicationCommand").sc(DeleteBucketReplication$).build()){};DeleteBucketTaggingCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucketTagging",{}).n("S3Client","DeleteBucketTaggingCommand").sc(DeleteBucketTagging$).build()){};DeleteBucketWebsiteCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucketWebsite",{}).n("S3Client","DeleteBucketWebsiteCommand").sc(DeleteBucketWebsite$).build()){};DeleteObjectCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","DeleteObject",{}).n("S3Client","DeleteObjectCommand").sc(DeleteObject$).build()){};DeleteObjectsCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0}),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","DeleteObjects",{}).n("S3Client","DeleteObjectsCommand").sc(DeleteObjects$).build()){};DeleteObjectTaggingCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","DeleteObjectTagging",{}).n("S3Client","DeleteObjectTaggingCommand").sc(DeleteObjectTagging$).build()){};DeletePublicAccessBlockCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions())]}).s("AmazonS3","DeletePublicAccessBlock",{}).n("S3Client","DeletePublicAccessBlockCommand").sc(DeletePublicAccessBlock$).build()){};GetBucketAbacCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","GetBucketAbac",{}).n("S3Client","GetBucketAbacCommand").sc(GetBucketAbac$).build()){};GetBucketAccelerateConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","GetBucketAccelerateConfiguration",{}).n("S3Client","GetBucketAccelerateConfigurationCommand").sc(GetBucketAccelerateConfiguration$).build()){};GetBucketAclCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","GetBucketAcl",{}).n("S3Client","GetBucketAclCommand").sc(GetBucketAcl$).build()){};GetBucketAnalyticsConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","GetBucketAnalyticsConfiguration",{}).n("S3Client","GetBucketAnalyticsConfigurationCommand").sc(GetBucketAnalyticsConfiguration$).build()){};GetBucketCorsCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","GetBucketCors",{}).n("S3Client","GetBucketCorsCommand").sc(GetBucketCors$).build()){};GetBucketEncryptionCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","GetBucketEncryption",{}).n("S3Client","GetBucketEncryptionCommand").sc(GetBucketEncryption$).build()){};GetBucketIntelligentTieringConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","GetBucketIntelligentTieringConfiguration",{}).n("S3Client","GetBucketIntelligentTieringConfigurationCommand").sc(GetBucketIntelligentTieringConfiguration$).build()){};GetBucketInventoryConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","GetBucketInventoryConfiguration",{}).n("S3Client","GetBucketInventoryConfigurationCommand").sc(GetBucketInventoryConfiguration$).build()){};GetBucketLifecycleConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","GetBucketLifecycleConfiguration",{}).n("S3Client","GetBucketLifecycleConfigurationCommand").sc(GetBucketLifecycleConfiguration$).build()){};GetBucketLocationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","GetBucketLocation",{}).n("S3Client","GetBucketLocationCommand").sc(GetBucketLocation$).build()){};GetBucketLoggingCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","GetBucketLogging",{}).n("S3Client","GetBucketLoggingCommand").sc(GetBucketLogging$).build()){};GetBucketMetadataConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","GetBucketMetadataConfiguration",{}).n("S3Client","GetBucketMetadataConfigurationCommand").sc(GetBucketMetadataConfiguration$).build()){};GetBucketMetadataTableConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","GetBucketMetadataTableConfiguration",{}).n("S3Client","GetBucketMetadataTableConfigurationCommand").sc(GetBucketMetadataTableConfiguration$).build()){};GetBucketMetricsConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","GetBucketMetricsConfiguration",{}).n("S3Client","GetBucketMetricsConfigurationCommand").sc(GetBucketMetricsConfiguration$).build()){};GetBucketNotificationConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","GetBucketNotificationConfiguration",{}).n("S3Client","GetBucketNotificationConfigurationCommand").sc(GetBucketNotificationConfiguration$).build()){};GetBucketOwnershipControlsCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","GetBucketOwnershipControls",{}).n("S3Client","GetBucketOwnershipControlsCommand").sc(GetBucketOwnershipControls$).build()){};GetBucketPolicyCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","GetBucketPolicy",{}).n("S3Client","GetBucketPolicyCommand").sc(GetBucketPolicy$).build()){};GetBucketPolicyStatusCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","GetBucketPolicyStatus",{}).n("S3Client","GetBucketPolicyStatusCommand").sc(GetBucketPolicyStatus$).build()){};GetBucketReplicationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","GetBucketReplication",{}).n("S3Client","GetBucketReplicationCommand").sc(GetBucketReplication$).build()){};GetBucketRequestPaymentCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","GetBucketRequestPayment",{}).n("S3Client","GetBucketRequestPaymentCommand").sc(GetBucketRequestPayment$).build()){};GetBucketTaggingCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","GetBucketTagging",{}).n("S3Client","GetBucketTaggingCommand").sc(GetBucketTagging$).build()){};GetBucketVersioningCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","GetBucketVersioning",{}).n("S3Client","GetBucketVersioningCommand").sc(GetBucketVersioning$).build()){};GetBucketWebsiteCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","GetBucketWebsite",{}).n("S3Client","GetBucketWebsiteCommand").sc(GetBucketWebsite$).build()){};GetObjectAclCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","GetObjectAcl",{}).n("S3Client","GetObjectAclCommand").sc(GetObjectAcl$).build()){};GetObjectAttributesCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config),getSsecPlugin(config)]}).s("AmazonS3","GetObjectAttributes",{}).n("S3Client","GetObjectAttributesCommand").sc(GetObjectAttributes$).build()){};GetObjectCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestChecksumRequired:!1,requestValidationModeMember:"ChecksumMode",responseAlgorithms:["CRC64NVME","CRC32","CRC32C","SHA256","SHA1"]}),getSsecPlugin(config),getS3ExpiresMiddlewarePlugin(config)]}).s("AmazonS3","GetObject",{}).n("S3Client","GetObjectCommand").sc(GetObject$).build()){};GetObjectLegalHoldCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","GetObjectLegalHold",{}).n("S3Client","GetObjectLegalHoldCommand").sc(GetObjectLegalHold$).build()){};GetObjectLockConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","GetObjectLockConfiguration",{}).n("S3Client","GetObjectLockConfigurationCommand").sc(GetObjectLockConfiguration$).build()){};GetObjectRetentionCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","GetObjectRetention",{}).n("S3Client","GetObjectRetentionCommand").sc(GetObjectRetention$).build()){};GetObjectTaggingCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","GetObjectTagging",{}).n("S3Client","GetObjectTaggingCommand").sc(GetObjectTagging$).build()){};GetObjectTorrentCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions())]}).s("AmazonS3","GetObjectTorrent",{}).n("S3Client","GetObjectTorrentCommand").sc(GetObjectTorrent$).build()){};GetPublicAccessBlockCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","GetPublicAccessBlock",{}).n("S3Client","GetPublicAccessBlockCommand").sc(GetPublicAccessBlock$).build()){};HeadBucketCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","HeadBucket",{}).n("S3Client","HeadBucketCommand").sc(HeadBucket$).build()){};HeadObjectCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config),getSsecPlugin(config),getS3ExpiresMiddlewarePlugin(config)]}).s("AmazonS3","HeadObject",{}).n("S3Client","HeadObjectCommand").sc(HeadObject$).build()){};ListBucketAnalyticsConfigurationsCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","ListBucketAnalyticsConfigurations",{}).n("S3Client","ListBucketAnalyticsConfigurationsCommand").sc(ListBucketAnalyticsConfigurations$).build()){};ListBucketIntelligentTieringConfigurationsCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","ListBucketIntelligentTieringConfigurations",{}).n("S3Client","ListBucketIntelligentTieringConfigurationsCommand").sc(ListBucketIntelligentTieringConfigurations$).build()){};ListBucketInventoryConfigurationsCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","ListBucketInventoryConfigurations",{}).n("S3Client","ListBucketInventoryConfigurationsCommand").sc(ListBucketInventoryConfigurations$).build()){};ListBucketMetricsConfigurationsCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","ListBucketMetricsConfigurations",{}).n("S3Client","ListBucketMetricsConfigurationsCommand").sc(ListBucketMetricsConfigurations$).build()){};ListBucketsCommand=class extends(Command.classBuilder().ep(commonParams).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","ListBuckets",{}).n("S3Client","ListBucketsCommand").sc(ListBuckets$).build()){};ListDirectoryBucketsCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","ListDirectoryBuckets",{}).n("S3Client","ListDirectoryBucketsCommand").sc(ListDirectoryBuckets$).build()){};ListMultipartUploadsCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Prefix:{type:"contextParams",name:"Prefix"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","ListMultipartUploads",{}).n("S3Client","ListMultipartUploadsCommand").sc(ListMultipartUploads$).build()){};ListObjectsCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Prefix:{type:"contextParams",name:"Prefix"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","ListObjects",{}).n("S3Client","ListObjectsCommand").sc(ListObjects$).build()){};ListObjectsV2Command=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Prefix:{type:"contextParams",name:"Prefix"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","ListObjectsV2",{}).n("S3Client","ListObjectsV2Command").sc(ListObjectsV2$).build()){};ListObjectVersionsCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Prefix:{type:"contextParams",name:"Prefix"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","ListObjectVersions",{}).n("S3Client","ListObjectVersionsCommand").sc(ListObjectVersions$).build()){};ListPartsCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config),getSsecPlugin(config)]}).s("AmazonS3","ListParts",{}).n("S3Client","ListPartsCommand").sc(ListParts$).build()){};PutBucketAbacCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!1})]}).s("AmazonS3","PutBucketAbac",{}).n("S3Client","PutBucketAbacCommand").sc(PutBucketAbac$).build()){};PutBucketAccelerateConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!1})]}).s("AmazonS3","PutBucketAccelerateConfiguration",{}).n("S3Client","PutBucketAccelerateConfigurationCommand").sc(PutBucketAccelerateConfiguration$).build()){};PutBucketAclCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","PutBucketAcl",{}).n("S3Client","PutBucketAclCommand").sc(PutBucketAcl$).build()){};PutBucketAnalyticsConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions())]}).s("AmazonS3","PutBucketAnalyticsConfiguration",{}).n("S3Client","PutBucketAnalyticsConfigurationCommand").sc(PutBucketAnalyticsConfiguration$).build()){};PutBucketCorsCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","PutBucketCors",{}).n("S3Client","PutBucketCorsCommand").sc(PutBucketCors$).build()){};PutBucketEncryptionCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","PutBucketEncryption",{}).n("S3Client","PutBucketEncryptionCommand").sc(PutBucketEncryption$).build()){};PutBucketIntelligentTieringConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions())]}).s("AmazonS3","PutBucketIntelligentTieringConfiguration",{}).n("S3Client","PutBucketIntelligentTieringConfigurationCommand").sc(PutBucketIntelligentTieringConfiguration$).build()){};PutBucketInventoryConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions())]}).s("AmazonS3","PutBucketInventoryConfiguration",{}).n("S3Client","PutBucketInventoryConfigurationCommand").sc(PutBucketInventoryConfiguration$).build()){};PutBucketLifecycleConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0}),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","PutBucketLifecycleConfiguration",{}).n("S3Client","PutBucketLifecycleConfigurationCommand").sc(PutBucketLifecycleConfiguration$).build()){};PutBucketLoggingCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","PutBucketLogging",{}).n("S3Client","PutBucketLoggingCommand").sc(PutBucketLogging$).build()){};PutBucketMetricsConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions())]}).s("AmazonS3","PutBucketMetricsConfiguration",{}).n("S3Client","PutBucketMetricsConfigurationCommand").sc(PutBucketMetricsConfiguration$).build()){};PutBucketNotificationConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions())]}).s("AmazonS3","PutBucketNotificationConfiguration",{}).n("S3Client","PutBucketNotificationConfigurationCommand").sc(PutBucketNotificationConfiguration$).build()){};PutBucketOwnershipControlsCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","PutBucketOwnershipControls",{}).n("S3Client","PutBucketOwnershipControlsCommand").sc(PutBucketOwnershipControls$).build()){};PutBucketPolicyCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","PutBucketPolicy",{}).n("S3Client","PutBucketPolicyCommand").sc(PutBucketPolicy$).build()){};PutBucketReplicationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","PutBucketReplication",{}).n("S3Client","PutBucketReplicationCommand").sc(PutBucketReplication$).build()){};PutBucketRequestPaymentCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","PutBucketRequestPayment",{}).n("S3Client","PutBucketRequestPaymentCommand").sc(PutBucketRequestPayment$).build()){};PutBucketTaggingCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","PutBucketTagging",{}).n("S3Client","PutBucketTaggingCommand").sc(PutBucketTagging$).build()){};PutBucketVersioningCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","PutBucketVersioning",{}).n("S3Client","PutBucketVersioningCommand").sc(PutBucketVersioning$).build()){};PutBucketWebsiteCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","PutBucketWebsite",{}).n("S3Client","PutBucketWebsiteCommand").sc(PutBucketWebsite$).build()){};PutObjectAclCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0}),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","PutObjectAcl",{}).n("S3Client","PutObjectAclCommand").sc(PutObjectAcl$).build()){};PutObjectCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!1}),getCheckContentLengthHeaderPlugin(config),getThrow200ExceptionsPlugin(config),getSsecPlugin(config)]}).s("AmazonS3","PutObject",{}).n("S3Client","PutObjectCommand").sc(PutObject$).build()){};PutObjectLegalHoldCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0}),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","PutObjectLegalHold",{}).n("S3Client","PutObjectLegalHoldCommand").sc(PutObjectLegalHold$).build()){};PutObjectLockConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0}),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","PutObjectLockConfiguration",{}).n("S3Client","PutObjectLockConfigurationCommand").sc(PutObjectLockConfiguration$).build()){};PutObjectRetentionCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0}),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","PutObjectRetention",{}).n("S3Client","PutObjectRetentionCommand").sc(PutObjectRetention$).build()){};PutObjectTaggingCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0}),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","PutObjectTagging",{}).n("S3Client","PutObjectTaggingCommand").sc(PutObjectTagging$).build()){};PutPublicAccessBlockCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","PutPublicAccessBlock",{}).n("S3Client","PutPublicAccessBlockCommand").sc(PutPublicAccessBlock$).build()){};RenameObjectCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","RenameObject",{}).n("S3Client","RenameObjectCommand").sc(RenameObject$).build()){};RestoreObjectCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!1}),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","RestoreObject",{}).n("S3Client","RestoreObjectCommand").sc(RestoreObject$).build()){};SelectObjectContentCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config),getSsecPlugin(config)]}).s("AmazonS3","SelectObjectContent",{eventStream:{output:!0}}).n("S3Client","SelectObjectContentCommand").sc(SelectObjectContent$).build()){};UpdateBucketMetadataInventoryTableConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","UpdateBucketMetadataInventoryTableConfiguration",{}).n("S3Client","UpdateBucketMetadataInventoryTableConfigurationCommand").sc(UpdateBucketMetadataInventoryTableConfiguration$).build()){};UpdateBucketMetadataJournalTableConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","UpdateBucketMetadataJournalTableConfiguration",{}).n("S3Client","UpdateBucketMetadataJournalTableConfigurationCommand").sc(UpdateBucketMetadataJournalTableConfiguration$).build()){};UpdateObjectEncryptionCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0}),getThrow200ExceptionsPlugin(config)]}).s("AmazonS3","UpdateObjectEncryption",{}).n("S3Client","UpdateObjectEncryptionCommand").sc(UpdateObjectEncryption$).build()){};UploadPartCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!1}),getThrow200ExceptionsPlugin(config),getSsecPlugin(config)]}).s("AmazonS3","UploadPart",{}).n("S3Client","UploadPartCommand").sc(UploadPart$).build()){};UploadPartCopyCommand=class extends(Command.classBuilder().ep({...commonParams,DisableS3ExpressSessionAuth:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config),getSsecPlugin(config)]}).s("AmazonS3","UploadPartCopy",{}).n("S3Client","UploadPartCopyCommand").sc(UploadPartCopy$).build()){};WriteGetObjectResponseCommand=class extends(Command.classBuilder().ep({...commonParams,UseObjectLambdaEndpoint:{type:"staticContextParams",value:!0}}).m(function(Command3,cs2,config,o2){return[getEndpointPlugin2(config,Command3.getEndpointParameterInstructions())]}).s("AmazonS3","WriteGetObjectResponse",{}).n("S3Client","WriteGetObjectResponseCommand").sc(WriteGetObjectResponse$).build()){};paginateListBuckets=createPaginator(S3Client,ListBucketsCommand,"ContinuationToken","ContinuationToken","MaxBuckets");paginateListDirectoryBuckets=createPaginator(S3Client,ListDirectoryBucketsCommand,"ContinuationToken","ContinuationToken","MaxDirectoryBuckets");paginateListObjectsV2=createPaginator(S3Client,ListObjectsV2Command,"ContinuationToken","NextContinuationToken","MaxKeys");paginateListParts=createPaginator(S3Client,ListPartsCommand,"PartNumberMarker","NextPartNumberMarker","MaxParts");getCircularReplacer=()=>{const seen=new WeakSet;return(key3,value)=>{if("object"==typeof value&&null!==value){if(seen.has(value))return"[Circular]";seen.add(value)}return value}};sleep=seconds=>new Promise(resolve=>setTimeout(resolve,1e3*seconds));waiterServiceDefaults2={minDelay:2,maxDelay:120};(function(WaiterState3){WaiterState3.ABORTED="ABORTED";WaiterState3.FAILURE="FAILURE";WaiterState3.SUCCESS="SUCCESS";WaiterState3.RETRY="RETRY";WaiterState3.TIMEOUT="TIMEOUT"})(WaiterState2||(WaiterState2={}));checkExceptions2=result=>{if(result.state===WaiterState2.ABORTED){const abortError=new Error(`${JSON.stringify({...result,reason:"Request was aborted"},getCircularReplacer())}`);abortError.name="AbortError";throw abortError}if(result.state===WaiterState2.TIMEOUT){const timeoutError=new Error(`${JSON.stringify({...result,reason:"Waiter has timed out"},getCircularReplacer())}`);timeoutError.name="TimeoutError";throw timeoutError}if(result.state!==WaiterState2.SUCCESS)throw new Error(`${JSON.stringify(result,getCircularReplacer())}`);return result};exponentialBackoffWithJitter=(minDelay,maxDelay,attemptCeiling,attempt)=>{if(attempt>attemptCeiling)return maxDelay;const delay2=minDelay*2**(attempt-1);return randomInRange(minDelay,delay2)};randomInRange=(min2,max3)=>min2+Math.random()*(max3-min2);runPolling=async({minDelay,maxDelay,maxWaitTime,abortController,client,abortSignal},input,acceptorChecks)=>{var _a13;const observedResponses={},{state:state2,reason}=await acceptorChecks(client,input);if(reason){const message=createMessageFromResponse(reason);observedResponses[message]|=0;observedResponses[message]+=1}if(state2!==WaiterState2.RETRY)return{state:state2,reason,observedResponses};let currentAttempt=1;const waitUntil=Date.now()+1e3*maxWaitTime,attemptCeiling=Math.log(maxDelay/minDelay)/Math.log(2)+1;for(;;){if((null==(_a13=null==abortController?void 0:abortController.signal)?void 0:_a13.aborted)||(null==abortSignal?void 0:abortSignal.aborted)){const message="AbortController signal aborted.";observedResponses[message]|=0;observedResponses[message]+=1;return{state:WaiterState2.ABORTED,observedResponses}}const delay2=exponentialBackoffWithJitter(minDelay,maxDelay,attemptCeiling,currentAttempt);if(Date.now()+1e3*delay2>waitUntil)return{state:WaiterState2.TIMEOUT,observedResponses};await sleep(delay2);const{state:state3,reason:reason2}=await acceptorChecks(client,input);if(reason2){const message=createMessageFromResponse(reason2);observedResponses[message]|=0;observedResponses[message]+=1}if(state3!==WaiterState2.RETRY)return{state:state3,reason:reason2,observedResponses};currentAttempt+=1}};createMessageFromResponse=reason=>{var _a13,_b6,_c3,_d2,_e2,_f;return(null==reason?void 0:reason.$responseBodyText)?`Deserialization error for body: ${reason.$responseBodyText}`:(null==(_a13=null==reason?void 0:reason.$metadata)?void 0:_a13.httpStatusCode)?reason.$response||reason.message?`${null!=(_d2=null!=(_c3=null==(_b6=reason.$response)?void 0:_b6.statusCode)?_c3:reason.$metadata.httpStatusCode)?_d2:"Unknown"}: ${reason.message}`:`${reason.$metadata.httpStatusCode}: OK`:String(null!=(_f=null!=(_e2=null==reason?void 0:reason.message)?_e2:JSON.stringify(reason,getCircularReplacer()))?_f:"Unknown")};validateWaiterOptions=options=>{if(options.maxWaitTime<=0)throw new Error("WaiterConfiguration.maxWaitTime must be greater than 0");if(options.minDelay<=0)throw new Error("WaiterConfiguration.minDelay must be greater than 0");if(options.maxDelay<=0)throw new Error("WaiterConfiguration.maxDelay must be greater than 0");if(options.maxWaitTime<=options.minDelay)throw new Error(`WaiterConfiguration.maxWaitTime [${options.maxWaitTime}] must be greater than WaiterConfiguration.minDelay [${options.minDelay}] for this waiter`);if(options.maxDelay<options.minDelay)throw new Error(`WaiterConfiguration.maxDelay [${options.maxDelay}] must be greater than WaiterConfiguration.minDelay [${options.minDelay}] for this waiter`)};abortTimeout=abortSignal=>{let onAbort;const promise=new Promise(resolve=>{onAbort=()=>resolve({state:WaiterState2.ABORTED});"function"==typeof abortSignal.addEventListener?abortSignal.addEventListener("abort",onAbort):abortSignal.onabort=onAbort});return{clearListener(){"function"==typeof abortSignal.removeEventListener&&abortSignal.removeEventListener("abort",onAbort)},aborted:promise}};createWaiter2=async(options,input,acceptorChecks)=>{var _a13;const params={...waiterServiceDefaults2,...options};validateWaiterOptions(params);const exitConditions=[runPolling(params,input,acceptorChecks)],finalize=[];if(options.abortSignal){const{aborted:aborted2,clearListener}=abortTimeout(options.abortSignal);finalize.push(clearListener);exitConditions.push(aborted2)}if(null==(_a13=options.abortController)?void 0:_a13.signal){const{aborted:aborted2,clearListener}=abortTimeout(options.abortController.signal);finalize.push(clearListener);exitConditions.push(aborted2)}return Promise.race(exitConditions).then(result=>{for(const fn of finalize)fn();return result})};checkState=async(client,input)=>{let reason;try{let result=await client.send(new HeadBucketCommand(input));reason=result;return{state:WaiterState2.SUCCESS,reason}}catch(exception){reason=exception;if(exception.name&&"NotFound"==exception.name)return{state:WaiterState2.RETRY,reason}}return{state:WaiterState2.RETRY,reason}};0;waitUntilBucketExists=async(params,input)=>{const result=await createWaiter2({minDelay:5,maxDelay:120,...params},input,checkState);return checkExceptions2(result)};checkState2=async(client,input)=>{let reason;try{let result=await client.send(new HeadBucketCommand(input));reason=result}catch(exception){reason=exception;if(exception.name&&"NotFound"==exception.name)return{state:WaiterState2.SUCCESS,reason}}return{state:WaiterState2.RETRY,reason}};0;waitUntilBucketNotExists=async(params,input)=>{const result=await createWaiter2({minDelay:5,maxDelay:120,...params},input,checkState2);return checkExceptions2(result)};checkState3=async(client,input)=>{let reason;try{let result=await client.send(new HeadObjectCommand(input));reason=result;return{state:WaiterState2.SUCCESS,reason}}catch(exception){reason=exception;if(exception.name&&"NotFound"==exception.name)return{state:WaiterState2.RETRY,reason}}return{state:WaiterState2.RETRY,reason}};0;waitUntilObjectExists=async(params,input)=>{const result=await createWaiter2({minDelay:5,maxDelay:120,...params},input,checkState3);return checkExceptions2(result)};checkState4=async(client,input)=>{let reason;try{let result=await client.send(new HeadObjectCommand(input));reason=result}catch(exception){reason=exception;if(exception.name&&"NotFound"==exception.name)return{state:WaiterState2.SUCCESS,reason}}return{state:WaiterState2.RETRY,reason}};0;waitUntilObjectNotExists=async(params,input)=>{const result=await createWaiter2({minDelay:5,maxDelay:120,...params},input,checkState4);return checkExceptions2(result)};commands={AbortMultipartUploadCommand,CompleteMultipartUploadCommand,CopyObjectCommand,CreateBucketCommand,CreateBucketMetadataConfigurationCommand,CreateBucketMetadataTableConfigurationCommand,CreateMultipartUploadCommand,CreateSessionCommand,DeleteBucketCommand,DeleteBucketAnalyticsConfigurationCommand,DeleteBucketCorsCommand,DeleteBucketEncryptionCommand,DeleteBucketIntelligentTieringConfigurationCommand,DeleteBucketInventoryConfigurationCommand,DeleteBucketLifecycleCommand,DeleteBucketMetadataConfigurationCommand,DeleteBucketMetadataTableConfigurationCommand,DeleteBucketMetricsConfigurationCommand,DeleteBucketOwnershipControlsCommand,DeleteBucketPolicyCommand,DeleteBucketReplicationCommand,DeleteBucketTaggingCommand,DeleteBucketWebsiteCommand,DeleteObjectCommand,DeleteObjectsCommand,DeleteObjectTaggingCommand,DeletePublicAccessBlockCommand,GetBucketAbacCommand,GetBucketAccelerateConfigurationCommand,GetBucketAclCommand,GetBucketAnalyticsConfigurationCommand,GetBucketCorsCommand,GetBucketEncryptionCommand,GetBucketIntelligentTieringConfigurationCommand,GetBucketInventoryConfigurationCommand,GetBucketLifecycleConfigurationCommand,GetBucketLocationCommand,GetBucketLoggingCommand,GetBucketMetadataConfigurationCommand,GetBucketMetadataTableConfigurationCommand,GetBucketMetricsConfigurationCommand,GetBucketNotificationConfigurationCommand,GetBucketOwnershipControlsCommand,GetBucketPolicyCommand,GetBucketPolicyStatusCommand,GetBucketReplicationCommand,GetBucketRequestPaymentCommand,GetBucketTaggingCommand,GetBucketVersioningCommand,GetBucketWebsiteCommand,GetObjectCommand,GetObjectAclCommand,GetObjectAttributesCommand,GetObjectLegalHoldCommand,GetObjectLockConfigurationCommand,GetObjectRetentionCommand,GetObjectTaggingCommand,GetObjectTorrentCommand,GetPublicAccessBlockCommand,HeadBucketCommand,HeadObjectCommand,ListBucketAnalyticsConfigurationsCommand,ListBucketIntelligentTieringConfigurationsCommand,ListBucketInventoryConfigurationsCommand,ListBucketMetricsConfigurationsCommand,ListBucketsCommand,ListDirectoryBucketsCommand,ListMultipartUploadsCommand,ListObjectsCommand,ListObjectsV2Command,ListObjectVersionsCommand,ListPartsCommand,PutBucketAbacCommand,PutBucketAccelerateConfigurationCommand,PutBucketAclCommand,PutBucketAnalyticsConfigurationCommand,PutBucketCorsCommand,PutBucketEncryptionCommand,PutBucketIntelligentTieringConfigurationCommand,PutBucketInventoryConfigurationCommand,PutBucketLifecycleConfigurationCommand,PutBucketLoggingCommand,PutBucketMetricsConfigurationCommand,PutBucketNotificationConfigurationCommand,PutBucketOwnershipControlsCommand,PutBucketPolicyCommand,PutBucketReplicationCommand,PutBucketRequestPaymentCommand,PutBucketTaggingCommand,PutBucketVersioningCommand,PutBucketWebsiteCommand,PutObjectCommand,PutObjectAclCommand,PutObjectLegalHoldCommand,PutObjectLockConfigurationCommand,PutObjectRetentionCommand,PutObjectTaggingCommand,PutPublicAccessBlockCommand,RenameObjectCommand,RestoreObjectCommand,SelectObjectContentCommand,UpdateBucketMetadataInventoryTableConfigurationCommand,UpdateBucketMetadataJournalTableConfigurationCommand,UpdateObjectEncryptionCommand,UploadPartCommand,UploadPartCopyCommand,WriteGetObjectResponseCommand};paginators={paginateListBuckets,paginateListDirectoryBuckets,paginateListObjectsV2,paginateListParts};waiters={waitUntilBucketExists,waitUntilBucketNotExists,waitUntilObjectExists,waitUntilObjectNotExists};S3=class extends S3Client{};createAggregatedClient(commands,S3,{paginators,waiters});applyMd5BodyChecksumMiddleware=options=>next2=>async args=>{const{request:request2}=args;if(HttpRequest.isInstance(request2)){const{body,headers}=request2;if(!hasHeader3("content-md5",headers)){let digest;if(void 0===body||"string"==typeof body||ArrayBuffer.isView(body)||isArrayBuffer(body)){const hash3=new options.md5;hash3.update(body||"");digest=hash3.digest()}else digest=options.streamHasher(options.md5,body);const cloned=HttpRequest.clone(request2);cloned.headers={...headers,"content-md5":options.base64Encoder(await digest)};return next2({...args,request:cloned})}}return next2(args)};applyMd5BodyChecksumMiddlewareOptions={name:"applyMd5BodyChecksumMiddleware",step:"build",tags:["SET_CONTENT_MD5","BODY_CHECKSUM"],override:!0};0;hasHeader3=(soughtHeader,headers)=>{soughtHeader=soughtHeader.toLowerCase();for(const headerName of Object.keys(headers))if(soughtHeader===headerName.toLowerCase())return!0;return!1};MinioStorageAdapter=class{constructor(settings,env){__publicField(this,"_instance");__publicField(this,"_settings");__publicField(this,"_env");this._settings=settings;this._env=env}async runTrackedRequest(task){return await runWithTrackedPhysicalRequest(this._env.services.API,task)}applyNewConfig(settings){this._settings=settings;this._instance=void 0}get customHeaders(){return 0==this._settings.bucketCustomHeaders.length?[]:Object.entries(parseHeaderValues(this._settings.bucketCustomHeaders))}_getClient(){if(this._instance)return this._instance;const ep=this._settings.endpoint?{endpoint:this._settings.endpoint,forcePathStyle:this._settings.forcePathStyle}:{};this._instance=new S3({region:this._settings.region,...ep,credentials:{accessKeyId:this._settings.accessKey,secretAccessKey:this._settings.secretKey},maxAttempts:4,retryStrategy:new ConfiguredRetryStrategy(4,attempt=>100+1e3*attempt),requestHandler:this._settings.useCustomRequestHandler?this._env.services.API.getCustomFetchHandler():void 0,requestChecksumCalculation:"WHEN_REQUIRED",responseChecksumValidation:"WHEN_REQUIRED"});const bucketCustomHeaders=this.customHeaders;this._instance.middlewareStack.add((next2,context2)=>args=>{bucketCustomHeaders.forEach(([key3,value])=>{key3&&value&&(args.request.headers[key3]=value)});return next2(args)},{name:"addBucketCustomHeadersMiddleware",step:"finalizeRequest",priority:"low"});const arrayBufferToBase64Sync=buffer=>btoa(String.fromCharCode(...new Uint8Array(buffer)));this._instance.middlewareStack.add(applyMd5BodyChecksumMiddleware({md5:Md5,base64Encoder:data=>arrayBufferToBase64Sync(data.buffer),streamHasher:(hashConstructor,stream)=>{const result=promiseWithResolvers(),hash3=new hashConstructor;stream.on("data",chunk=>{hash3.update(chunk)});stream.on("end",()=>{result.resolve(hash3.digest())});return result.promise}}),{step:"build",name:"applyMd5BodyChecksumMiddlewareForDeleteObjects"});return this._instance}async upload(key3,data,mime){try{const client=this._getClient(),cmd=new PutObjectCommand({Bucket:this._settings.bucket,Key:`${this._settings.bucketPrefix}${key3}`,Body:data,ContentType:mime});if(await this.runTrackedRequest(()=>client.send(cmd)))return!0}catch(ex){Logger(`Could not upload ${key3}`);Logger(ex,LOG_LEVEL_VERBOSE)}return!1}async downloadWithResult(key3,ignoreCache=!1){const client=this._getClient(),cmd=new GetObjectCommand({Bucket:this._settings.bucket,Key:`${this._settings.bucketPrefix}${key3}`,...ignoreCache?{ResponseCacheControl:"no-cache"}:{}});try{return await this.runTrackedRequest(async()=>{const r4=await client.send(cmd);return r4.Body?{status:JournalStorageReadStatuses_AVAILABLE,value:new Uint8Array(await r4.Body.transformToByteArray())}:{status:JournalStorageReadStatuses_UNAVAILABLE,error:new Error(`The response body for ${key3} was empty`)}})}catch(ex){if(isMissingObjectError(ex))return{status:JournalStorageReadStatuses_NOT_FOUND};Logger(`Could not download ${key3}`);Logger(ex,LOG_LEVEL_VERBOSE);return{status:JournalStorageReadStatuses_UNAVAILABLE,error:ex}}}async download(key3,ignoreCache=!1){const result=await this.downloadWithResult(key3,ignoreCache);return result.status===JournalStorageReadStatuses_AVAILABLE&&result.value}async listFiles(from,limit){const client=this._getClient(),objects=await this.runTrackedRequest(()=>client.listObjectsV2({Bucket:this._settings.bucket,Prefix:this._settings.bucketPrefix,StartAfter:`${this._settings.bucketPrefix||""}${from||""}`,...limit?{MaxKeys:limit}:{}}));return objects.Contents?objects.Contents.filter(e3=>{var _a13;return null==(_a13=e3.Key)?void 0:_a13.startsWith(this._settings.bucketPrefix)}).map(e3=>{var _a13;return null==(_a13=e3.Key)?void 0:_a13.substring(this._settings.bucketPrefix.length)}):[]}async deleteFiles(keys3){if(0===keys3.length)return!0;const client=this._getClient();try{const cmd=new DeleteObjectsCommand({Bucket:this._settings.bucket,Delete:{Objects:keys3.map(e3=>({Key:`${this._settings.bucketPrefix}${e3}`}))}}),r4=await this.runTrackedRequest(()=>client.send(cmd)),{Deleted,Errors:Errors2}=r4,deleteCount=(null==Deleted?void 0:Deleted.length)||0,errorCount=(null==Errors2?void 0:Errors2.length)||0;Logger(`${deleteCount} items deleted.${0!==errorCount?` (${errorCount} items failed to delete)`:""}`,LOG_LEVEL_VERBOSE,"reset-bucket");return 0===errorCount}catch(ex){Logger("WARNING! Could not delete files.",LOG_LEVEL_NOTICE,"reset-bucket");Logger(ex,LOG_LEVEL_VERBOSE);return!1}}async isAvailable(){const client=this._getClient(),cmd=new HeadBucketCommand({Bucket:this._settings.bucket});try{await this.runTrackedRequest(()=>client.send(cmd));return!0}catch(ex){Logger("Could not connect to the remote bucket",LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_VERBOSE);return!1}}async getUsage(){const client=this._getClient();try{const objects=await this.runTrackedRequest(()=>client.listObjectsV2({Bucket:this._settings.bucket}));return objects.Contents?{estimatedSize:objects.Contents.reduce((acc,e3)=>acc+(e3.Size||0),0)}:{}}catch(ex){Logger("Could not get status of the remote bucket",LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_VERBOSE);return!1}}};LANG_DE="de";LANG_ES="es";LANG_FR="fr";LANG_HE="he";LANG_JA="ja";LANG_RU="ru";LANG_ZH="zh";LANG_KO="ko";LANG_ZH_TW="zh-tw";LANG_DEF="def";SUPPORTED_I18N_LANGS=[LANG_DEF,LANG_DE,LANG_ES,LANG_FR,LANG_HE,LANG_JA,LANG_KO,LANG_RU,LANG_ZH,LANG_ZH_TW];updateInformation="# 1.0\n\nWell then, everyone: it has been roughly a year since I declared the 0.25 beta. During that time, we have concentrated mainly on fixing defects and completing the features that the project needed.\n\nVersion 1.0 has been in mind for some time. We have now brought together the work intended to make it possible: stronger CI, more detailed tests, an E2E runner suited to synchronisation, and testing tools for physical devices. These now form a coherent Kit rather than a collection of isolated pieces. With those foundations in place, it seems that the time has finally come to reshape the structure of this repository.\n\nNone of this would have been possible without your issue reports, pull requests, sponsorship, and the support provided through OpenAI's Codex for Open Source. I would like to express my gratitude once again. As with every pull request contributed to the project, code produced with Codex and similar tools is reviewed and audited by me, vrtmrz. Anyone interested in how I manage that process can refer to my dotfiles.\n\nThis will call for your help once again. I would be very grateful for your co-operation as we build a sounder foundation for the project and its future development.\n\nEarlier releases remain available in the 1.0 release history, the 1.0 preview history, the 0.25 release history, and the legacy release history.\n\n## Unreleased\n\n## 1.0.21\n\n26th August, 2026\n\nIt is becoming more 'ordinary' with each release, but please let me know if anything has become less convenient.\n\n### Interface and translation\n\n#### Fixed\n\n- Remote Configuration section headings no longer overlap their contents when scrolling on mobile. Action buttons in Remote Configuration, Maintenance, and Patches now remain inside the settings pane on narrow screens.\n\n## 1.0.20\n\n~~1.0.19~~ was cancelled because prerelease validation exposed an incorrect warning at start-up.\n\n25th August, 2026\n\nI know this is the second time I have said it, but I had grown quite fond of the settings screen. It seems, however, that a simpler, healthier life is called for.\n\n### Interface and translation\n\n#### Fixed\n\n- Compatibility pause warnings now direct you to the dedicated compatibility review instead of the Change Log.\n- The Obsidian 1.13 settings page now waits for saved settings before choosing its initial layout. This prevents a spurious missing-replicator warning at start-up, keeps configured devices on the Synchronisation-first layout even when automatic synchronisation triggers are disabled, and keeps Quick Setup first on unconfigured devices.\n\n#### Improved\n\n- Settings page names, controls in General Settings, Quick Setup actions, and Advanced controls now use Obsidian 1.13's native settings interface and global search, while retaining their familiar icons. The landing page keeps Remote Configuration and Sync Settings together, places Appearance, Logging, and Extra menus under General Settings, and groups maintenance, optional features, advanced settings, and help by purpose. Earlier supported Obsidian versions continue to use the pane-based interface.\n- Settings changes which require database initialisation now use a focused Setup Manager dialogue to choose between existing synchronisation data and the files in the current Vault. The selected reset or rebuild is reserved before the settings are saved, while cancelling offers a separate, explicit settings-only fallback.\n\n## 1.0.18\n\n24th August, 2026\n\n### Synchronisation and storage\n\n#### Fixed\n\n- Reset and rebuild workflows now use the local database selected by their updated settings, preventing stale data from reopening after a **Database Suffix** change. If database initialisation does not complete, the workflow remains paused instead of continuing with incomplete state.\n\n#### Improved\n\n- Rebuilds now recheck restored file events against the current Vault, use current file contents, and finish processing them before the plug-in reports readiness.\n\n## 1.0.17\n\n23rd August, 2026\n\n### Interface and translation\n\n#### Fixed\n\n- Settings generated from the settings manifest, Setup Wizard configuration summaries, and warnings about externally changed settings now honour **Display language** when a translation is available, instead of remaining in English (PR #1123). Thank you to @nimula for the contribution!\n\n### Peer-to-peer synchronisation\n\n#### Improved\n\n- P2P connection profiles now provide four **P2P message size** presets and a **Connection path** choice between **Automatic** and **TURN relay only**. Smaller messages can improve compatibility on paths which fragment or drop larger WebRTC messages, while relay-only routing requires a configured TURN server. P2P connection strings and encrypted Setup URIs preserve both choices.\n - Thank you to @andrewschreiber for the detailed fragmentation diagnosis and working 800-byte threshold in vrtmrz/livesync-commonlib#97, which informed this compatibility design.\n- An optional self-hosted Coturn Compose starter is now available for P2P deployments that need a TURN relay. It uses a pinned upstream image and documents its network, credential, security, and verification boundaries.\n\n## 1.0.16\n\n19th August, 2026\n\n### Conflict handling and recovery\n\n#### Fixed\n\n- **Back to this revision** in Document History now restores the selected content as a new non-deleted successor revision before reflecting it to the Vault. A readable revision restored after a logical deletion therefore remains restored through later synchronisation instead of being overwritten by the deletion.\n - If the file changes while restoration is in progress, the operation stops instead of extending a stale revision. Existing conflicts remain available through **Inspect conflicts and file/database differences**.\n\n### Synchronisation and storage\n\n#### Improved\n\n- One-shot CouchDB synchronisation now releases stalled web-compatible connection checks before replication starts, so a later synchronisation can make a fresh attempt (Commonlib 0.1.16).\n - The 60-second safeguard applies only to pre-replication checks. It does not limit ordinary synchronisation, and the **Use Internal API** path is unchanged.\n";EVENT_REQUEST_SHOW_HISTORY="show-history";REPORT_WARNING="All revisions and chunk availability below are a snapshot of this device's local database; the remote is not queried. Review the Vault-relative path, document identifier, content-derived chunk identifiers, and metadata before sharing this report. File contents are omitted.";UnresolvedErrorManager=class{constructor(appLifecycleService,events){__publicField(this,"events");__publicField(this,"_log",createInstanceLogFunction("UnresolvedErrorManager"));__publicField(this,"appLifecycleService");__publicField(this,"_occurredErrors",new Set);this.events=events;this.appLifecycleService=appLifecycleService;this.appLifecycleService.getUnresolvedMessages.addHandler(this._reportUnresolvedMessages.bind(this))}showError(msg,max_log_level=LEVEL_NOTICE){const level=this._occurredErrors.has(msg)?LEVEL_INFO:max_log_level;this._log(msg,level);if(!this._occurredErrors.has(msg)){this._occurredErrors.add(msg);this.events.emitEvent(EVENT_ON_UNRESOLVED_ERROR)}}clearError(msg){if(this._occurredErrors.has(msg)){this._occurredErrors.delete(msg);this.events.emitEvent(EVENT_ON_UNRESOLVED_ERROR)}}clearErrors(){this._occurredErrors.clear();this.events.emitEvent(EVENT_ON_UNRESOLVED_ERROR)}countErrors(needle){return Array.from(this._occurredErrors).filter(error=>"string"==typeof error&&-1!==error.indexOf(needle)).length}_reportUnresolvedMessages(){return Promise.resolve(Array.from(this._occurredErrors))}};FilePairProcessResults_COMPLETED="completed",FilePairProcessResults_SKIPPED="skipped",FilePairProcessResults_FAILED="failed";MetadataDocumentNamespaces_NORMAL="normal",MetadataDocumentNamespaces_INTERNAL="internal",MetadataDocumentNamespaces_CUSTOMISATION="customisation",MetadataDocumentNamespaces_PLUGIN_STORAGE="plugin-storage";MetadataDocumentIdentityStatuses_CONSISTENT="consistent",MetadataDocumentIdentityStatuses_EXCLUDED="excluded",MetadataDocumentIdentityStatuses_UNRESOLVED="unresolved";OfflineScanUnresolvedReasons_DOCUMENT_ID_MISMATCH="document-id-mismatch",OfflineScanUnresolvedReasons_NAMESPACE_MISMATCH="namespace-mismatch";MetadataDocumentRepairResults_COMPLETED="completed",MetadataDocumentRepairResults_STALE="stale",MetadataDocumentRepairResults_BLOCKED="blocked",MetadataDocumentRepairResults_FAILED="failed";FullScanModes_DB_APPLY="db-apply",FullScanModes_NEWER_WINS="newer-wins";ExtraOnRemote_DELETE_LOCAL_MISSING="delete-local-missing";ExtraOnLocal_DELETE_DB_DELETED="delete-db-deleted",ExtraOnLocal_DELETE_DB_MISSING="delete-db-missing",ExtraOnLocal_APPEND_STORAGE_ONLY="append-storage-only";fileMaps=new Map;FILE_STATUS_MAP_KEY="fileStatusMap";FILE_STATUS_MAP_LOCK="offlineScanner-fileStatusMap";saveFileStatusTimeout=null;MetadataIdentityRepairExecutions_CANCELLED="cancelled",MetadataIdentityRepairExecutions_REPAIR_RESULT="repair-result";PouchError=class extends Error{constructor(status,error,reason){super();this.status=status;this.name=error;this.message=reason;this.error=!0}toString(){return JSON.stringify({status:this.status,name:this.name,message:this.message,reason:this.reason})}};new PouchError(401,"unauthorized","Name or password is incorrect.");MISSING_BULK_DOCS=new PouchError(400,"bad_request","Missing JSON list of 'docs'");MISSING_DOC=new PouchError(404,"not_found","missing");REV_CONFLICT=new PouchError(409,"conflict","Document update conflict");INVALID_ID=new PouchError(400,"bad_request","_id field must contain a string");MISSING_ID=new PouchError(412,"missing_id","_id is required for puts");RESERVED_ID=new PouchError(400,"bad_request","Only reserved document ids may start with underscore.");new PouchError(412,"precondition_failed","Database not open");UNKNOWN_ERROR=new PouchError(500,"unknown_error","Database encountered an unknown error");BAD_ARG=new PouchError(500,"badarg","Some query argument is invalid");new PouchError(400,"invalid_request","Request was invalid");QUERY_PARSE_ERROR=new PouchError(400,"query_parse_error","Some query parameter is invalid");DOC_VALIDATION=new PouchError(500,"doc_validation","Bad special document member");BAD_REQUEST=new PouchError(400,"bad_request","Something wrong with the request");NOT_AN_OBJECT=new PouchError(400,"bad_request","Document must be a JSON object");new PouchError(404,"not_found","Database not found");IDB_ERROR=new PouchError(500,"indexed_db_went_bad","unknown");new PouchError(500,"web_sql_went_bad","unknown");new PouchError(500,"levelDB_went_went_bad","unknown");new PouchError(403,"forbidden","Forbidden by design doc validate_doc_update function");INVALID_REV=new PouchError(400,"bad_request","Invalid rev format");new PouchError(412,"file_exists","The database could not be created, the file already exists.");MISSING_STUB=new PouchError(412,"missing_stub","A pre-existing attachment stub wasn't found");new PouchError(413,"invalid_url","Provided URL is invalid");regex_default=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;validate_default=function validate2(uuid2){return"string"==typeof uuid2&&regex_default.test(uuid2)};byteToHex=[];for(let i3=0;i3<256;++i3)byteToHex.push((i3+256).toString(16).slice(1));0;rnds8=new Uint8Array(16);randomUUID2="undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);native_default={randomUUID:randomUUID2};v4_default=function v43(options,buf,offset){var _a13,_b6,_c3;if(native_default.randomUUID&&!buf&&!options)return native_default.randomUUID();options=options||{};const rnds=null!=(_c3=null!=(_b6=options.random)?_b6:null==(_a13=options.rng)?void 0:_a13.call(options))?_c3:rng();if(rnds.length<16)throw new Error("Random bytes length must be >= 16");rnds[6]=15&rnds[6]|64;rnds[8]=63&rnds[8]|128;if(buf){offset=offset||0;if(offset<0||offset+16>buf.length)throw new RangeError(`UUID byte range ${offset}:${offset+15} is out of buffer bounds`);for(let i3=0;i3<16;++i3)buf[offset+i3]=rnds[i3];return buf}return unsafeStringify(rnds)};thisAtob=function(str){return atob(str)};thisBtoa=function(str){return btoa(str)};import_spark_md5=__toESM(require_spark_md5());setImmediateShim=self.setImmediate||self.setTimeout;MD5_CHUNK_SIZE=32768;import_events17=__toESM(require_events());funcToString=Function.prototype.toString;objectCtorString=funcToString.call(Object);MAX_NUM_CONCURRENT_REQUESTS=6;try{localStorage.setItem("_pouch_check_localstorage",1);hasLocal=!!localStorage.getItem("_pouch_check_localstorage")}catch(e3){hasLocal=!1}nextTick="function"==typeof queueMicrotask?queueMicrotask:function nextTick2(fn){Promise.resolve().then(fn)};Changes=class extends import_events17.default{constructor(){super();this._listeners={};hasLocalStorage()&&addEventListener("storage",e3=>{this.emit(e3.key)})}addListener(dbName,id,db,opts){function eventFunction(){if(self3._listeners[id])if(inprogress)inprogress="waiting";else{inprogress=!0;var changesOpts=pick(opts,["style","include_docs","attachments","conflicts","filter","doc_ids","view","since","query_params","binary","return_docs"]);db.changes(changesOpts).on("change",function(c3){if(c3.seq>opts.since&&!opts.cancelled){opts.since=c3.seq;opts.onChange(c3)}}).on("complete",function(){"waiting"===inprogress&&nextTick(eventFunction);inprogress=!1}).on("error",function onError(){inprogress=!1})}}var inprogress,self3;if(!this._listeners[id]){inprogress=!1;self3=this;this._listeners[id]=eventFunction;this.on(dbName,eventFunction)}}removeListener(dbName,id){if(id in this._listeners){super.removeListener(dbName,this._listeners[id]);delete this._listeners[id]}}notifyLocalWindows(dbName){hasLocalStorage()&&(localStorage[dbName]="a"===localStorage[dbName]?"b":"a")}notify(dbName){this.emit(dbName);this.notifyLocalWindows(dbName)}};hasName=(function f2(){}).name;res=hasName?function(fun){return fun.name}:function(fun){var match3=fun.toString().match(/^\s*function\s*(?:(\S+)\s*)?\(/);return match3&&match3[1]?match3[1]:""};0;keys2=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];qName="queryKey";qParser=/(?:^|&)([^&=]*)=?([^&]*)/g;parser2=/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;uuid=v4_default;f3=fetch;h2=Headers;MIN_MAGNITUDE=-324;MAGNITUDE_DIGITS=3;SEP="";combinationFields=["$or","$nor","$not"];matchers={$elemMatch:function(doc,userValue,parsedField,docFieldValue){return!!Array.isArray(docFieldValue)&&(0!==docFieldValue.length&&("object"==typeof docFieldValue[0]&&null!==docFieldValue[0]?docFieldValue.some(function(val){return rowFilter(val,userValue,Object.keys(userValue))}):docFieldValue.some(function(val){return matchSelector(userValue,doc,parsedField,val)})))},$allMatch:function(doc,userValue,parsedField,docFieldValue){return!!Array.isArray(docFieldValue)&&(0!==docFieldValue.length&&("object"==typeof docFieldValue[0]&&null!==docFieldValue[0]?docFieldValue.every(function(val){return rowFilter(val,userValue,Object.keys(userValue))}):docFieldValue.every(function(val){return matchSelector(userValue,doc,parsedField,val)})))},$eq:function(doc,userValue,parsedField,docFieldValue){return fieldIsNotUndefined(docFieldValue)&&0===collate(docFieldValue,userValue)},$gte:function(doc,userValue,parsedField,docFieldValue){return fieldIsNotUndefined(docFieldValue)&&collate(docFieldValue,userValue)>=0},$gt:function(doc,userValue,parsedField,docFieldValue){return fieldIsNotUndefined(docFieldValue)&&collate(docFieldValue,userValue)>0},$lte:function(doc,userValue,parsedField,docFieldValue){return fieldIsNotUndefined(docFieldValue)&&collate(docFieldValue,userValue)<=0},$lt:function(doc,userValue,parsedField,docFieldValue){return fieldIsNotUndefined(docFieldValue)&&collate(docFieldValue,userValue)<0},$exists:function(doc,userValue,parsedField,docFieldValue){return userValue?fieldIsNotUndefined(docFieldValue):!fieldIsNotUndefined(docFieldValue)},$mod:function(doc,userValue,parsedField,docFieldValue){return fieldExists(docFieldValue)&&modField(docFieldValue,userValue)},$ne:function(doc,userValue,parsedField,docFieldValue){return userValue.every(function(neValue){return 0!==collate(docFieldValue,neValue)})},$in:function(doc,userValue,parsedField,docFieldValue){return fieldExists(docFieldValue)&&arrayContainsValue(docFieldValue,userValue)},$nin:function(doc,userValue,parsedField,docFieldValue){return fieldExists(docFieldValue)&&!arrayContainsValue(docFieldValue,userValue)},$size:function(doc,userValue,parsedField,docFieldValue){return fieldExists(docFieldValue)&&Array.isArray(docFieldValue)&&arraySize(docFieldValue,userValue)},$all:function(doc,userValue,parsedField,docFieldValue){return Array.isArray(docFieldValue)&&arrayContainsAllValues(docFieldValue,userValue)},$regex:function(doc,userValue,parsedField,docFieldValue){return fieldExists(docFieldValue)&&"string"==typeof docFieldValue&&userValue.every(function(regexValue){return regexMatch(docFieldValue,regexValue)})},$type:function(doc,userValue,parsedField,docFieldValue){return typeMatch(docFieldValue,userValue)}};index_browser_es_default=function applyChangesFilterPlugin(PouchDB2){PouchDB2._changesFilterPlugin={validate:validate3,normalize,shouldFilter,filter:filter3}};import_events18=__toESM(require_events());Changes2=class extends import_events18.default{constructor(db,opts,callback){var complete,promise;super();this.db=db;opts=opts?clone2(opts):{};complete=opts.complete=once2((err3,resp)=>{err3?listenerCount(this,"error")>0&&this.emit("error",err3):this.emit("complete",resp);this.removeAllListeners();db.removeListener("destroyed",onDestroy2)});if(callback){this.on("complete",function(resp){callback(null,resp)});this.on("error",callback)}const onDestroy2=()=>{this.cancel()};db.once("destroyed",onDestroy2);opts.onChange=(change,pending3,lastSeq)=>{this.isCancelled||tryCatchInChangeListener(this,change,pending3,lastSeq)};promise=new Promise(function(fulfill,reject){opts.complete=function(err3,res2){err3?reject(err3):fulfill(res2)}});this.once("cancel",function(){db.removeListener("destroyed",onDestroy2);opts.complete(null,{status:"cancelled"})});this.then=promise.then.bind(promise);this.catch=promise.catch.bind(promise);this.then(function(result){complete(null,result)},complete);db.taskqueue.isReady?this.validateChanges(opts):db.taskqueue.addTask(failed2=>{failed2?opts.complete(failed2):this.isCancelled?this.emit("cancel"):this.validateChanges(opts)})}cancel(){this.isCancelled=!0;this.db.taskqueue.isReady&&this.emit("cancel")}validateChanges(opts){var callback=opts.complete;PouchDB._changesFilterPlugin?PouchDB._changesFilterPlugin.validate(opts,err3=>{if(err3)return callback(err3);this.doChanges(opts)}):this.doChanges(opts)}doChanges(opts){var newPromise,callback=opts.complete;opts=clone2(opts);"live"in opts&&!("continuous"in opts)&&(opts.continuous=opts.live);opts.processChange=processChange;"latest"===opts.since&&(opts.since="now");opts.since||(opts.since=0);if("now"!==opts.since){if(PouchDB._changesFilterPlugin){PouchDB._changesFilterPlugin.normalize(opts);if(PouchDB._changesFilterPlugin.shouldFilter(this,opts))return PouchDB._changesFilterPlugin.filter(this,opts)}else["doc_ids","filter","selector","view"].forEach(function(key3){key3 in opts&&guardedConsole("warn",'The "'+key3+'" option was passed in to changes/replicate, but pouchdb-changes-filter plugin is not installed, so it was ignored. Please install the plugin to enable filtering.')});"descending"in opts||(opts.descending=!1);opts.limit=0===opts.limit?1:opts.limit;opts.complete=callback;newPromise=this.db._changes(opts);if(newPromise&&"function"==typeof newPromise.cancel){const cancel=this.cancel;this.cancel=(...args)=>{newPromise.cancel();cancel.apply(this,args)}}}else this.db.info().then(info3=>{if(this.isCancelled)callback(null,{status:"cancelled"});else{opts.since=info3.update_seq;this.doChanges(opts)}},callback)}};validRevRegex=/^\d+-[^-]*$/;AbstractPouchDB=class extends import_events18.default{_setup(){this.post=adapterFun("post",function(doc,opts,callback){if("function"==typeof opts){callback=opts;opts={}}if(isNotSingleDoc(doc))return callback(createError(NOT_AN_OBJECT));this.bulkDocs({docs:[doc]},opts,yankError(callback,doc._id))}).bind(this);this.put=adapterFun("put",function(doc,opts,cb2){if("function"==typeof opts){cb2=opts;opts={}}if(isNotSingleDoc(doc))return cb2(createError(NOT_AN_OBJECT));invalidIdError(doc._id);if("_rev"in doc&&!isValidRev(doc._rev))return cb2(createError(INVALID_REV));if(isLocalId(doc._id)&&"function"==typeof this._putLocal)return doc._deleted?this._removeLocal(doc,cb2):this._putLocal(doc,cb2);const putDoc=next2=>{"function"==typeof this._put&&!1!==opts.new_edits?this._put(doc,opts,next2):this.bulkDocs({docs:[doc]},opts,yankError(next2,doc._id))};if(opts.force&&doc._rev){(function transformForceOptionToNewEditsOption(){var parts=doc._rev.split("-"),oldRevId=parts[1],oldRevNum=parseInt(parts[0],10),newRevNum=oldRevNum+1,newRevId=rev2();doc._revisions={start:newRevNum,ids:[newRevId,oldRevId]};doc._rev=newRevNum+"-"+newRevId;opts.new_edits=!1})();putDoc(function(err3){var result=err3?null:{ok:!0,id:doc._id,rev:doc._rev};cb2(err3,result)})}else putDoc(cb2)}).bind(this);this.putAttachment=adapterFun("putAttachment",function(docId,attachmentId,rev$$1,blob,type){function createAttachment(doc){var prevrevpos="_rev"in doc?parseInt(doc._rev,10):0;doc._attachments=doc._attachments||{};doc._attachments[attachmentId]={content_type:type,data:blob,revpos:++prevrevpos};return api.put(doc)}var api=this;if("function"==typeof type){type=blob;blob=rev$$1;rev$$1=null}if(void 0===type){type=blob;blob=rev$$1;rev$$1=null}type||guardedConsole("warn","Attachment",attachmentId,"on document",docId,"is missing content_type");return api.get(docId).then(function(doc){if(doc._rev!==rev$$1)throw createError(REV_CONFLICT);return createAttachment(doc)},function(err3){if(err3.reason===MISSING_DOC.message)return createAttachment({_id:docId});throw err3})}).bind(this);this.removeAttachment=adapterFun("removeAttachment",function(docId,attachmentId,rev$$1,callback){this.get(docId,(err3,obj)=>{if(err3)callback(err3);else if(obj._rev===rev$$1){if(!obj._attachments)return callback();delete obj._attachments[attachmentId];0===Object.keys(obj._attachments).length&&delete obj._attachments;this.put(obj,callback)}else callback(createError(REV_CONFLICT))})}).bind(this);this.remove=adapterFun("remove",function(docOrId,optsOrRev,opts,callback){var doc,newDoc;if("string"==typeof optsOrRev){doc={_id:docOrId,_rev:optsOrRev};if("function"==typeof opts){callback=opts;opts={}}}else{doc=docOrId;if("function"==typeof optsOrRev){callback=optsOrRev;opts={}}else{callback=opts;opts=optsOrRev}}opts=opts||{};opts.was_delete=!0;newDoc={_id:doc._id,_rev:doc._rev||opts.rev};newDoc._deleted=!0;if(isLocalId(newDoc._id)&&"function"==typeof this._removeLocal)return this._removeLocal(doc,callback);this.bulkDocs({docs:[newDoc]},opts,yankError(callback,newDoc._id))}).bind(this);this.revsDiff=adapterFun("revsDiff",function(req,opts,callback){function addToMissing(id,revId){missing.has(id)||missing.set(id,{missing:[]});missing.get(id).missing.push(revId)}function processDoc(id,rev_tree){var missingForId=req[id].slice(0);traverseRevTree(rev_tree,function(isLeaf,pos,revHash,ctx,opts2){var rev$$1=pos+"-"+revHash,idx2=missingForId.indexOf(rev$$1);if(-1!==idx2){missingForId.splice(idx2,1);"available"!==opts2.status&&addToMissing(id,rev$$1)}});missingForId.forEach(function(rev$$1){addToMissing(id,rev$$1)})}var ids,count,missing;if("function"==typeof opts){callback=opts;opts={}}ids=Object.keys(req);if(!ids.length)return callback(null,{});count=0;missing=new Map;ids.forEach(function(id){this._getRevisionTree(id,function(err3,rev_tree){if(err3&&404===err3.status&&"missing"===err3.message)missing.set(id,{missing:req[id]});else{if(err3)return callback(err3);processDoc(id,rev_tree)}if(++count===ids.length){var missingObj={};missing.forEach(function(value,key3){missingObj[key3]=value});return callback(null,missingObj)}})},this)}).bind(this);this.bulkGet=adapterFun("bulkGet",function(opts,callback){bulkGet(this,opts,callback)}).bind(this);this.compactDocument=adapterFun("compactDocument",function(docId,maxHeight,callback){this._getRevisionTree(docId,(err3,revTree)=>{var height,candidates,revs;if(err3)return callback(err3);height=computeHeight(revTree);candidates=[];revs=[];Object.keys(height).forEach(function(rev$$1){height[rev$$1]>maxHeight&&candidates.push(rev$$1)});traverseRevTree(revTree,function(isLeaf,pos,revHash,ctx,opts){var rev$$1=pos+"-"+revHash;"available"===opts.status&&-1!==candidates.indexOf(rev$$1)&&revs.push(rev$$1)});this._doCompaction(docId,revs,callback)})}).bind(this);this.compact=adapterFun("compact",function(opts,callback){if("function"==typeof opts){callback=opts;opts={}}opts=opts||{};this._compactionQueue=this._compactionQueue||[];this._compactionQueue.push({opts,callback});1===this._compactionQueue.length&&doNextCompaction(this)}).bind(this);this.get=adapterFun("get",function(id,opts,cb2){var leaves,i3,l2;if("function"==typeof opts){cb2=opts;opts={}}opts=opts||{};if("string"!=typeof id)return cb2(createError(INVALID_ID));if(isLocalId(id)&&"function"==typeof this._getLocal)return this._getLocal(id,cb2);leaves=[];const finishOpenRevs=()=>{var result=[],count=leaves.length;if(!count)return cb2(null,result);leaves.forEach(leaf=>{this.get(id,{rev:leaf,revs:opts.revs,latest:opts.latest,attachments:opts.attachments,binary:opts.binary},function(err3,doc){var existing,i4,l3;if(err3)result.push({missing:leaf});else{for(i4=0,l3=result.length;i4<l3;i4++)if(result[i4].ok&&result[i4].ok._rev===doc._rev){existing=!0;break}existing||result.push({ok:doc})}count--;count||cb2(null,result)})})};if(!opts.open_revs)return this._get(id,opts,(err3,result)=>{var doc,metadata,ctx,conflicts,splittedRev,revNo,revHash,paths,path2,i4,currentPath,hashFoundAtRevPos,howMany,pos,attachments,count,key3;if(err3){err3.docId=id;return cb2(err3)}doc=result.doc;metadata=result.metadata;ctx=result.ctx;if(opts.conflicts){conflicts=collectConflicts(metadata);conflicts.length&&(doc._conflicts=conflicts)}isDeleted(metadata,doc._rev)&&(doc._deleted=!0);if(opts.revs||opts.revs_info){splittedRev=doc._rev.split("-");revNo=parseInt(splittedRev[0],10);revHash=splittedRev[1];paths=rootToLeaf(metadata.rev_tree);path2=null;for(i4=0;i4<paths.length;i4++){currentPath=paths[i4];const hashIndex=currentPath.ids.findIndex(x3=>x3.id===revHash);hashFoundAtRevPos=hashIndex===revNo-1;(hashFoundAtRevPos||!path2&&-1!==hashIndex)&&(path2=currentPath)}if(!path2){err3=new Error("invalid rev tree");err3.docId=id;return cb2(err3)}const pathId=doc._rev.split("-")[1],indexOfRev=path2.ids.findIndex(x3=>x3.id===pathId)+1;howMany=path2.ids.length-indexOfRev;path2.ids.splice(indexOfRev,howMany);path2.ids.reverse();opts.revs&&(doc._revisions={start:path2.pos+path2.ids.length-1,ids:path2.ids.map(function(rev$$1){return rev$$1.id})});if(opts.revs_info){pos=path2.pos+path2.ids.length;doc._revs_info=path2.ids.map(function(rev$$1){pos--;return{rev:pos+"-"+rev$$1.id,status:rev$$1.opts.status}})}}if(opts.attachments&&doc._attachments){attachments=doc._attachments;count=Object.keys(attachments).length;if(0===count)return cb2(null,doc);Object.keys(attachments).forEach(key4=>{this._getAttachment(doc._id,key4,attachments[key4],{binary:opts.binary,metadata,ctx},function(err4,data){var att=doc._attachments[key4];att.data=data;delete att.stub;delete att.length;--count||cb2(null,doc)})})}else{if(doc._attachments)for(key3 in doc._attachments)Object.prototype.hasOwnProperty.call(doc._attachments,key3)&&(doc._attachments[key3].stub=!0);cb2(null,doc)}});if("all"===opts.open_revs)this._getRevisionTree(id,function(err3,rev_tree){if(err3)return cb2(err3);leaves=collectLeaves(rev_tree).map(function(leaf){return leaf.rev});finishOpenRevs()});else{if(!Array.isArray(opts.open_revs))return cb2(createError(UNKNOWN_ERROR,"function_clause"));leaves=opts.open_revs;for(i3=0;i3<leaves.length;i3++){l2=leaves[i3];if(!isValidRev(l2))return cb2(createError(INVALID_REV))}finishOpenRevs()}}).bind(this);this.getAttachment=adapterFun("getAttachment",function(docId,attachmentId,opts,callback){if(opts instanceof Function){callback=opts;opts={}}this._get(docId,opts,(err3,res2)=>{if(err3)return callback(err3);if(!res2.doc._attachments||!res2.doc._attachments[attachmentId])return callback(createError(MISSING_DOC));opts.ctx=res2.ctx;opts.binary=!0;opts.metadata=res2.metadata;this._getAttachment(docId,attachmentId,res2.doc._attachments[attachmentId],opts,callback)})}).bind(this);this.allDocs=adapterFun("allDocs",function(opts,callback){if("function"==typeof opts){callback=opts;opts={}}opts.skip=void 0!==opts.skip?opts.skip:0;opts.start_key&&(opts.startkey=opts.start_key);opts.end_key&&(opts.endkey=opts.end_key);if("keys"in opts){if(!Array.isArray(opts.keys))return callback(new TypeError("options.keys must be an array"));var incompatibleOpt=["startkey","endkey","key"].filter(function(incompatibleOpt2){return incompatibleOpt2 in opts})[0];if(incompatibleOpt){callback(createError(QUERY_PARSE_ERROR,"Query parameter `"+incompatibleOpt+"` is not compatible with multi-get"));return}if(!isRemote(this)){allDocsKeysParse(opts);if(0===opts.keys.length)return this._allDocs({limit:0},callback)}}return this._allDocs(opts,callback)}).bind(this);this.close=adapterFun("close",function(callback){this._closed=!0;this.emit("closed");return this._close(callback)}).bind(this);this.info=adapterFun("info",function(callback){this._info((err3,info3)=>{if(err3)return callback(err3);info3.db_name=info3.db_name||this.name;info3.auto_compaction=!(!this.auto_compaction||isRemote(this));info3.adapter=this.adapter;callback(null,info3)})}).bind(this);this.id=adapterFun("id",function(callback){return this._id(callback)}).bind(this);this.bulkDocs=adapterFun("bulkDocs",function(req,opts,callback){var i3,attachmentError,adapter,ids;if("function"==typeof opts){callback=opts;opts={}}opts=opts||{};Array.isArray(req)&&(req={docs:req});if(!req||!req.docs||!Array.isArray(req.docs))return callback(createError(MISSING_BULK_DOCS));for(i3=0;i3<req.docs.length;++i3){const doc=req.docs[i3];if(isNotSingleDoc(doc))return callback(createError(NOT_AN_OBJECT));if("_rev"in doc&&!isValidRev(doc._rev))return callback(createError(INVALID_REV))}req.docs.forEach(function(doc){doc._attachments&&Object.keys(doc._attachments).forEach(function(name){attachmentError=attachmentError||attachmentNameError(name);doc._attachments[name].content_type||guardedConsole("warn","Attachment",name,"on document",doc._id,"is missing content_type")})});if(attachmentError)return callback(createError(BAD_REQUEST,attachmentError));"new_edits"in opts||(opts.new_edits=!("new_edits"in req)||req.new_edits);adapter=this;opts.new_edits||isRemote(adapter)||req.docs.sort(compareByIdThenRev);cleanDocs(req.docs);ids=req.docs.map(function(doc){return doc._id});this._bulkDocs(req,opts,function(err3,res2){if(err3)return callback(err3);opts.new_edits||(res2=res2.filter(function(x3){return x3.error}));if(!isRemote(adapter))for(var i4=0,l2=res2.length;i4<l2;i4++)res2[i4].id=res2[i4].id||ids[i4];callback(null,res2)})}).bind(this);this.registerDependentDatabase=adapterFun("registerDependentDatabase",function(dependentDb,callback){var depDB,dbOptions=clone2(this.__opts);this.__opts.view_adapter&&(dbOptions.adapter=this.__opts.view_adapter);depDB=new this.constructor(dependentDb,dbOptions);upsert(this,"_local/_pouch_dependentDbs",function diffFun(doc){doc.dependentDbs=doc.dependentDbs||{};if(doc.dependentDbs[dependentDb])return!1;doc.dependentDbs[dependentDb]=!0;return doc}).then(function(){callback(null,{db:depDB})}).catch(callback)}).bind(this);this.destroy=adapterFun("destroy",function(opts,callback){if("function"==typeof opts){callback=opts;opts={}}var usePrefix=!("use_prefix"in this)||this.use_prefix;const destroyDb=()=>{this._destroy(opts,(err3,resp)=>{if(err3)return callback(err3);this._destroyed=!0;this.emit("destroyed");callback(null,resp||{ok:!0})})};if(isRemote(this))return destroyDb();this.get("_local/_pouch_dependentDbs",(err3,localDoc)=>{var dependentDbs,PouchDB2,deletedMap;if(err3)return 404!==err3.status?callback(err3):destroyDb();dependentDbs=localDoc.dependentDbs;PouchDB2=this.constructor;deletedMap=Object.keys(dependentDbs).map(name=>{var trueName=usePrefix?name.replace(new RegExp("^"+PouchDB2.prefix),""):name;return new PouchDB2(trueName,this.__opts).destroy()});Promise.all(deletedMap).then(destroyDb,callback)})}).bind(this)}_compact(opts,callback){var taskId,changesOpts={return_docs:!1,last_seq:opts.last_seq||0,since:opts.last_seq||0},promises=[],compactedDocs=0;const onChange=row=>{this.activeTasks.update(taskId,{completed_items:++compactedDocs});promises.push(this.compactDocument(row.id,0))},onError=err3=>{this.activeTasks.remove(taskId,err3);callback(err3)},onComplete=resp=>{var lastSeq=resp.last_seq;Promise.all(promises).then(()=>upsert(this,"_local/compaction",doc=>{if(!doc.last_seq||doc.last_seq<lastSeq){doc.last_seq=lastSeq;return doc}return!1})).then(()=>{this.activeTasks.remove(taskId);callback(null,{ok:!0})}).catch(onError)};this.info().then(info3=>{taskId=this.activeTasks.add({name:"database_compaction",total_items:info3.update_seq-changesOpts.last_seq});this.changes(changesOpts).on("change",onChange).on("complete",onComplete).on("error",onError)})}changes(opts,callback){if("function"==typeof opts){callback=opts;opts={}}opts=opts||{};opts.return_docs="return_docs"in opts?opts.return_docs:!opts.live;return new Changes2(this,opts,callback)}type(){return"function"==typeof this._type?this._type():this.adapter}};AbstractPouchDB.prototype.purge=adapterFun("_purge",function(docId,rev$$1,callback){if(void 0===this._purge)return callback(createError(UNKNOWN_ERROR,"Purge is not implemented in the "+this.adapter+" adapter."));var self3=this;self3._getRevisionTree(docId,(error,revs)=>{if(error)return callback(error);if(!revs)return callback(createError(MISSING_DOC));let path2;try{path2=findPathToLeaf(revs,rev$$1)}catch(error2){return callback(error2.message||error2)}self3._purge(docId,path2,(error2,result)=>{if(error2)return callback(error2);appendPurgeSeq(self3,docId,rev$$1).then(function(){return callback(null,result)})})})});TaskQueue=class{constructor(){this.isReady=!1;this.failed=!1;this.queue=[]}execute(){var fun;if(this.failed)for(;fun=this.queue.shift();)fun(this.failed);else for(;fun=this.queue.shift();)fun()}fail(err3){this.failed=err3;this.execute()}ready(db){this.isReady=!0;this.db=db;this.execute()}addTask(fun){this.queue.push(fun);this.failed&&this.execute()}};PouchInternal=class extends AbstractPouchDB{constructor(name,opts){super();this._setup(name,opts)}_setup(name,opts){var prefixedName,backend;super._setup();opts=opts||{};if(name&&"object"==typeof name){opts=name;name=opts.name;delete opts.name}void 0===opts.deterministic_revs&&(opts.deterministic_revs=!0);this.__opts=opts=clone2(opts);this.auto_compaction=opts.auto_compaction;this.purged_infos_limit=opts.purged_infos_limit||1e3;this.prefix=PouchDB.prefix;if("string"!=typeof name)throw new Error("Missing/invalid DB name");prefixedName=(opts.prefix||"")+name;backend=parseAdapter(prefixedName,opts);opts.name=backend.name;opts.adapter=opts.adapter||backend.adapter;this.name=name;this._adapter=opts.adapter;PouchDB.emit("debug",["adapter","Picked adapter: ",opts.adapter]);if(!PouchDB.adapters[opts.adapter]||!PouchDB.adapters[opts.adapter].valid())throw new Error("Invalid Adapter: "+opts.adapter);if(opts.view_adapter&&(!PouchDB.adapters[opts.view_adapter]||!PouchDB.adapters[opts.view_adapter].valid()))throw new Error("Invalid View Adapter: "+opts.view_adapter);this.taskqueue=new TaskQueue;this.adapter=opts.adapter;PouchDB.adapters[opts.adapter].call(this,opts,err3=>{if(err3)return this.taskqueue.fail(err3);prepareForDestruction(this);this.emit("created",this);PouchDB.emit("created",this.name);this.taskqueue.ready(this)})}};PouchDB=createClass(PouchInternal,function(name,opts){PouchInternal.prototype._setup.call(this,name,opts)});ActiveTasks=class{constructor(){this.tasks={}}list(){return Object.values(this.tasks)}add(task){const id=v4_default();this.tasks[id]={id,name:task.name,total_items:task.total_items,created_at:(new Date).toJSON()};return id}get(id){return this.tasks[id]}remove(id,reason){delete this.tasks[id];return this.tasks}update(id,updatedTask){const task=this.tasks[id];if(void 0!==task){const mergedTask={id:task.id,name:task.name,created_at:task.created_at,total_items:updatedTask.total_items||task.total_items,completed_items:updatedTask.completed_items||task.completed_items,updated_at:(new Date).toJSON()};this.tasks[id]=mergedTask}return this.tasks}};PouchDB.adapters={};PouchDB.preferredAdapters=[];PouchDB.prefix="_pouch_";eventEmitter=new import_events18.default;(function setUpEventEmitter(Pouch){Object.keys(import_events18.default.prototype).forEach(function(key3){"function"==typeof import_events18.default.prototype[key3]&&(Pouch[key3]=eventEmitter[key3].bind(eventEmitter))});var destructListeners=Pouch._destructionListeners=new Map;Pouch.on("ref",function onConstructorRef(db){destructListeners.has(db.name)||destructListeners.set(db.name,[]);destructListeners.get(db.name).push(db)});Pouch.on("unref",function onConstructorUnref(db){var dbList,pos;if(destructListeners.has(db.name)){dbList=destructListeners.get(db.name);pos=dbList.indexOf(db);if(!(pos<0)){dbList.splice(pos,1);dbList.length>1?destructListeners.set(db.name,dbList):destructListeners.delete(db.name)}}});Pouch.on("destroyed",function onConstructorDestroyed(name){if(destructListeners.has(name)){var dbList=destructListeners.get(name);destructListeners.delete(name);dbList.forEach(function(db){db.emit("destroyed",!0)})}})})(PouchDB);PouchDB.adapter=function(id,obj,addToPreferredAdapters){if(obj.valid()){PouchDB.adapters[id]=obj;addToPreferredAdapters&&PouchDB.preferredAdapters.push(id)}};PouchDB.plugin=function(obj){if("function"==typeof obj)obj(PouchDB);else{if("object"!=typeof obj||0===Object.keys(obj).length)throw new Error('Invalid plugin: got "'+obj+'", expected an object or a function');Object.keys(obj).forEach(function(id){PouchDB.prototype[id]=obj[id]})}this.__defaults&&(PouchDB.__defaults=Object.assign({},this.__defaults));return PouchDB};PouchDB.defaults=function(defaultOpts){let PouchWithDefaults=createClass(PouchDB,function(name,opts){opts=opts||{};if(name&&"object"==typeof name){opts=name;name=opts.name;delete opts.name}opts=Object.assign({},PouchWithDefaults.__defaults,opts);PouchDB.call(this,name,opts)});PouchWithDefaults.preferredAdapters=PouchDB.preferredAdapters.slice();Object.keys(PouchDB).forEach(function(key3){key3 in PouchWithDefaults||(PouchWithDefaults[key3]=PouchDB[key3])});PouchWithDefaults.__defaults=Object.assign({},this.__defaults,defaultOpts);return PouchWithDefaults};PouchDB.fetch=function(url,opts){return f3(url,opts)};PouchDB.prototype.activeTasks=PouchDB.activeTasks=new ActiveTasks;version="9.0.0";PouchDB.plugin(index_browser_es_default);PouchDB.version=version;index_es_default=PouchDB;import_vuvuzela=__toESM(require_vuvuzela());reservedWords=toObject(["_id","_rev","_access","_attachments","_deleted","_revisions","_revs_info","_conflicts","_deleted_conflicts","_local_seq","_rev_tree","_replication_id","_replication_state","_replication_state_time","_replication_state_reason","_replication_stats","_removed"]);dataWords=toObject(["_access","_attachments","_replication_id","_replication_state","_replication_state_time","_replication_state_reason","_replication_stats"]);ADAPTER_VERSION=5;DOC_STORE="document-store";BY_SEQ_STORE="by-sequence";ATTACH_STORE="attach-store";ATTACH_AND_SEQ_STORE="attach-seq-store";META_STORE="meta-store";LOCAL_STORE="local-store";DETECT_BLOB_SUPPORT_STORE="detect-blob-support";changesHandler$1=new Changes;running=!1;queue=[];cachedDBs=new Map;openReqList=new Map;IdbPouch.valid=function(){try{return"undefined"!=typeof indexedDB&&"undefined"!=typeof IDBKeyRange}catch(e3){return!1}};index_es_default2=function index2(PouchDB2){PouchDB2.adapter("idb",IdbPouch,!0)};IDB_NULL=Number.MIN_SAFE_INTEGER;IDB_FALSE=Number.MIN_SAFE_INTEGER+1;IDB_TRUE=Number.MIN_SAFE_INTEGER+2;TEST_KEY_INVALID=/^[^a-zA-Z$]|[^a-zA-Z0-9$]+/;TEST_PATH_INVALID=/\\.|(^|\.)[^a-zA-Z$]|[^a-zA-Z0-9$.]+/;KEY_INVALID=new RegExp(TEST_KEY_INVALID.source,"g");PATH_INVALID=new RegExp(TEST_PATH_INVALID.source,"g");SLASH="\\".charCodeAt(0);IS_DOT=".".charCodeAt(0);DOC_STORE2="docs";META_LOCAL_STORE="meta";POUCHDB_IDB_VERSION=2;versionMultiplier=Math.pow(10,13);BINARY_ATTACHMENTS=!1;COUCH_COLLATE_LO=null;COUCH_COLLATE_HI="￿";IDB_COLLATE_LO=Number.NEGATIVE_INFINITY;IDB_COLLATE_HI=[[[[[[[[[[[[]]]]]]]]]]]];ADAPTER_NAME="indexeddb";idbChanges=new Changes;openDatabases={};IndexeddbPouch.valid=function(){return!0};index_es_default3=function index3(PouchDB2){PouchDB2.adapter(ADAPTER_NAME,IndexeddbPouch,!0)};CHANGES_BATCH_SIZE=25;MAX_SIMULTANEOUS_REVS=50;CHANGES_TIMEOUT_BUFFER=5e3;DEFAULT_HEARTBEAT=1e4;supportsBulkGetMap={};HttpPouch.valid=function(){return!0};index_es_default4=function index4(PouchDB2){PouchDB2.adapter("http",HttpPouch,!1);PouchDB2.adapter("https",HttpPouch,!1)};QueryParseError=class _QueryParseError extends Error{constructor(message){super();this.status=400;this.name="query_parse_error";this.message=message;this.error=!0;try{Error.captureStackTrace(this,_QueryParseError)}catch(e3){}}};NotFoundError=class _NotFoundError extends Error{constructor(message){super();this.status=404;this.name="not_found";this.message=message;this.error=!0;try{Error.captureStackTrace(this,_NotFoundError)}catch(e3){}}};BuiltInError=class _BuiltInError extends Error{constructor(message){super();this.status=500;this.name="invalid_value";this.message=message;this.error=!0;try{Error.captureStackTrace(this,_BuiltInError)}catch(e3){}}};TaskQueue2=class{constructor(){this.promise=Promise.resolve()}add(promiseFactory){this.promise=this.promise.catch(()=>{}).then(()=>promiseFactory());return this.promise}finish(){return this.promise}};persistentQueues={};tempViewQueue=new TaskQueue2;CHANGES_BATCH_SIZE2=50;index_es_default5=function createAbstractMapReduce(localDocName2,mapper3,reducer3,ddocValidator3){function tryMap(db,fun,doc){try{fun(doc)}catch(e3){emitError(db,e3,{fun,doc})}}function tryReduce(db,fun,keys3,values2,rereduce){try{return{output:fun(keys3,values2,rereduce)}}catch(e3){emitError(db,e3,{fun,keys:keys3,values:values2,rereduce});return{error:e3}}}function sortByKeyThenValue(x3,y2){const keyCompare=collate(x3.key,y2.key);return 0!==keyCompare?keyCompare:collate(x3.value,y2.value)}function sliceResults(results,limit,skip){skip=skip||0;return"number"==typeof limit?results.slice(skip,limit+skip):skip>0?results.slice(skip):results}function rowToDocId(row){const val=row.value,docId=val&&"object"==typeof val&&val._id||row.id;return docId}function readAttachmentsAsBlobOrBuffer2(res2){for(const row of res2.rows){const atts=row.doc&&row.doc._attachments;if(atts)for(const filename of Object.keys(atts)){const att=atts[filename];atts[filename].data=b64ToBluffer(att.data,att.content_type)}}}function postprocessAttachments(opts){return function(res2){opts.include_docs&&opts.attachments&&opts.binary&&readAttachmentsAsBlobOrBuffer2(res2);return res2}}function addHttpParam(paramName,opts,params,asJson){let val=opts[paramName];if(void 0!==val){asJson&&(val=encodeURIComponent(JSON.stringify(val)));params.push(paramName+"="+val)}}function coerceInteger(integerCandidate){if(void 0!==integerCandidate){const asNumber=Number(integerCandidate);return isNaN(asNumber)||asNumber!==parseInt(integerCandidate,10)?integerCandidate:asNumber}}function coerceOptions(opts){opts.group_level=coerceInteger(opts.group_level);opts.limit=coerceInteger(opts.limit);opts.skip=coerceInteger(opts.skip);return opts}function checkPositiveInteger(number){if(number){if("number"!=typeof number)return new QueryParseError(`Invalid value for integer: "${number}"`);if(number<0)return new QueryParseError(`Invalid value for positive integer: "${number}"`)}}function checkQueryParseError(options,fun){const startkeyName=options.descending?"endkey":"startkey",endkeyName=options.descending?"startkey":"endkey";if(void 0!==options[startkeyName]&&void 0!==options[endkeyName]&&collate(options[startkeyName],options[endkeyName])>0)throw new QueryParseError("No rows can match your key range, reverse your start_key and end_key or set {descending : true}");if(fun.reduce&&!1!==options.reduce){if(options.include_docs)throw new QueryParseError("{include_docs:true} is invalid for reduce");if(options.keys&&options.keys.length>1&&!options.group&&!options.group_level)throw new QueryParseError("Multi-key fetches for reduce views must use {group: true}")}for(const optionName of["group_level","limit","skip"]){const error=checkPositiveInteger(options[optionName]);if(error)throw error}}async function httpQuery(db,fun,opts){let body,ok,params=[],method="GET";addHttpParam("reduce",opts,params);addHttpParam("include_docs",opts,params);addHttpParam("attachments",opts,params);addHttpParam("limit",opts,params);addHttpParam("descending",opts,params);addHttpParam("group",opts,params);addHttpParam("group_level",opts,params);addHttpParam("skip",opts,params);addHttpParam("stale",opts,params);addHttpParam("conflicts",opts,params);addHttpParam("startkey",opts,params,!0);addHttpParam("start_key",opts,params,!0);addHttpParam("endkey",opts,params,!0);addHttpParam("end_key",opts,params,!0);addHttpParam("inclusive_end",opts,params);addHttpParam("key",opts,params,!0);addHttpParam("update_seq",opts,params);params=params.join("&");params=""===params?"":"?"+params;if(void 0!==opts.keys){const MAX_URL_LENGTH=2e3,keysAsString=`keys=${encodeURIComponent(JSON.stringify(opts.keys))}`;if(keysAsString.length+params.length+1<=MAX_URL_LENGTH)params+=("?"===params[0]?"&":"?")+keysAsString;else{method="POST";"string"==typeof fun?body={keys:opts.keys}:fun.keys=opts.keys}}if("string"==typeof fun){const parts=parseViewName(fun),response2=await db.fetch("_design/"+parts[0]+"/_view/"+parts[1]+params,{headers:new h2({"Content-Type":"application/json"}),method,body:JSON.stringify(body)});ok=response2.ok;const result2=await response2.json();if(!ok){result2.status=response2.status;throw generateErrorFromResponse(result2)}for(const row of result2.rows)if(row.value&&row.value.error&&"builtin_reduce_error"===row.value.error)throw new Error(row.reason);return new Promise(function(resolve){resolve(result2)}).then(postprocessAttachments(opts))}body=body||{};for(const key3 of Object.keys(fun))Array.isArray(fun[key3])?body[key3]=fun[key3]:body[key3]=fun[key3].toString();const response=await db.fetch("_temp_view"+params,{headers:new h2({"Content-Type":"application/json"}),method:"POST",body:JSON.stringify(body)});ok=response.ok;const result=await response.json();if(!ok){result.status=response.status;throw generateErrorFromResponse(result)}return new Promise(function(resolve){resolve(result)}).then(postprocessAttachments(opts))}function customQuery(db,fun,opts){return new Promise(function(resolve,reject){db._query(fun,opts,function(err3,res2){if(err3)return reject(err3);resolve(res2)})})}function customViewCleanup(db){return new Promise(function(resolve,reject){db._viewCleanup(function(err3,res2){if(err3)return reject(err3);resolve(res2)})})}function defaultsTo(value){return function(reason){if(404===reason.status)return value;throw reason}}async function getDocsToPersist(docId,view,docIdsToChangesAndEmits){const metaDocId="_local/doc_"+docId,defaultMetaDoc={_id:metaDocId,keys:[]},docData=docIdsToChangesAndEmits.get(docId),indexableKeysToKeyValues=docData[0],changes3=docData[1],metaDoc=await function getMetaDoc(){return isGenOne(changes3)?Promise.resolve(defaultMetaDoc):view.db.get(metaDocId).catch(defaultsTo(defaultMetaDoc))}(),keyValueDocs=await function getKeyValueDocs(metaDoc2){return metaDoc2.keys.length?view.db.allDocs({keys:metaDoc2.keys,include_docs:!0}):Promise.resolve({rows:[]})}(metaDoc);return function processKeyValueDocs(metaDoc2,kvDocsRes){const kvDocs=[],oldKeys=new Set;for(const row of kvDocsRes.rows){const doc=row.doc;if(doc){kvDocs.push(doc);oldKeys.add(doc._id);doc._deleted=!indexableKeysToKeyValues.has(doc._id);if(!doc._deleted){const keyValue=indexableKeysToKeyValues.get(doc._id);"value"in keyValue&&(doc.value=keyValue.value)}}}const newKeys=mapToKeysArray(indexableKeysToKeyValues);for(const key3 of newKeys)if(!oldKeys.has(key3)){const kvDoc={_id:key3},keyValue=indexableKeysToKeyValues.get(key3);"value"in keyValue&&(kvDoc.value=keyValue.value);kvDocs.push(kvDoc)}metaDoc2.keys=uniq(newKeys.concat(metaDoc2.keys));kvDocs.push(metaDoc2);return kvDocs}(metaDoc,keyValueDocs)}function updatePurgeSeq(view){return view.sourceDB.get("_local/purges").then(function(res2){const purgeSeq=res2.purgeSeq;return view.db.get("_local/purgeSeq").then(function(res3){return res3._rev}).catch(defaultsTo(void 0)).then(function(rev3){return view.db.put({_id:"_local/purgeSeq",_rev:rev3,purgeSeq})})}).catch(function(err3){if(404!==err3.status)throw err3})}function saveKeyValues(view,docIdsToChangesAndEmits,seq){return view.db.get("_local/lastSeq").catch(defaultsTo({_id:"_local/lastSeq",seq:0})).then(function(lastSeqDoc){var docIds=mapToKeysArray(docIdsToChangesAndEmits);return Promise.all(docIds.map(function(docId){return getDocsToPersist(docId,view,docIdsToChangesAndEmits)})).then(function(listOfDocsToPersist){var docsToPersist=listOfDocsToPersist.flat();lastSeqDoc.seq=seq;docsToPersist.push(lastSeqDoc);return view.db.bulkDocs({docs:docsToPersist})}).then(()=>updatePurgeSeq(view))})}function getQueue(view){const viewName="string"==typeof view?view:view.name;let queue2=persistentQueues[viewName];queue2||(queue2=persistentQueues[viewName]=new TaskQueue2);return queue2}async function updateView(view,opts){return sequentialize(getQueue(view),function(){return updateViewInQueue(view,opts)})()}async function updateViewInQueue(view,opts){function processChange2(docIdsToChangesAndEmits,seq){return function(){return saveKeyValues(view,docIdsToChangesAndEmits,seq)}}async function processNextBatch(){const response=await view.sourceDB.changes({return_docs:!0,conflicts:!0,include_docs:!0,style:"all_docs",since:currentSeq,limit:opts.changes_batch_size}),purges=await getRecentPurges();return processBatch(response,purges)}function getRecentPurges(){return view.db.get("_local/purgeSeq").then(function(res2){return res2.purgeSeq}).catch(defaultsTo(-1)).then(function(purgeSeq){return view.sourceDB.get("_local/purges").then(function(res2){const recentPurges=res2.purges.filter(function(purge2,index6){return index6>purgeSeq}).map(purge2=>purge2.docId),uniquePurges=recentPurges.filter(function(docId,index6){return recentPurges.indexOf(docId)===index6});return Promise.all(uniquePurges.map(function(docId){return view.sourceDB.get(docId).then(function(doc2){return{docId,doc:doc2}}).catch(defaultsTo({docId}))}))}).catch(defaultsTo([]))})}function processBatch(response,purges){const results=response.results;if(!results.length&&!purges.length)return;for(const purge2 of purges){const index6=results.findIndex(function(change){return change.id===purge2.docId});if(index6<0){const entry={_id:purge2.docId,doc:{_id:purge2.docId,_deleted:1},changes:[]};if(purge2.doc){entry.doc=purge2.doc;entry.changes.push({rev:purge2.doc._rev})}results.push(entry)}}const docIdsToChangesAndEmits=createDocIdsToChangesAndEmits(results);queue2.add(processChange2(docIdsToChangesAndEmits,currentSeq));indexed_docs+=results.length;const progress2={view:view.name,last_seq:response.last_seq,results_count:results.length,indexed_docs};view.sourceDB.emit("indexing",progress2);view.sourceDB.activeTasks.update(taskId,{completed_items:indexed_docs});return results.length<opts.changes_batch_size?void 0:processNextBatch()}function createDocIdsToChangesAndEmits(results){const docIdsToChangesAndEmits=new Map;for(const change of results){if("_"!==change.doc._id[0]){mapResults=[];doc=change.doc;doc._deleted||tryMap(view.sourceDB,mapFun,doc);mapResults.sort(sortByKeyThenValue);const indexableKeysToKeyValues=createIndexableKeysToKeyValues(mapResults);docIdsToChangesAndEmits.set(change.doc._id,[indexableKeysToKeyValues,change.changes])}currentSeq=change.seq}return docIdsToChangesAndEmits}function createIndexableKeysToKeyValues(mapResults2){const indexableKeysToKeyValues=new Map;let lastKey;for(let i3=0,len=mapResults2.length;i3<len;i3++){const emittedKeyValue=mapResults2[i3],complexKey=[emittedKeyValue.key,emittedKeyValue.id];i3>0&&0===collate(emittedKeyValue.key,lastKey)&&complexKey.push(i3);indexableKeysToKeyValues.set(toIndexableString(complexKey),emittedKeyValue);lastKey=emittedKeyValue.key}return indexableKeysToKeyValues}let mapResults,doc,taskId;const mapFun=mapper3(view.mapFun,function emit2(key3,value){const output={id:doc._id,key:normalizeKey(key3)};null!=value&&(output.value=normalizeKey(value));mapResults.push(output)});let currentSeq=view.seq||0,indexed_docs=0;const progress={view:view.name,indexed_docs};view.sourceDB.emit("indexing",progress);const queue2=new TaskQueue2;try{await function createTask(){return view.sourceDB.info().then(function(info3){taskId=view.sourceDB.activeTasks.add({name:"view_indexing",total_items:info3.update_seq-currentSeq})})}();await processNextBatch();await queue2.finish();view.seq=currentSeq;view.sourceDB.activeTasks.remove(taskId)}catch(error){view.sourceDB.activeTasks.remove(taskId,error)}}function reduceView(view,results,options){0===options.group_level&&delete options.group_level;const shouldGroup=options.group||options.group_level,reduceFun=reducer3(view.reduceFun),groups=[],lvl=isNaN(options.group_level)?Number.POSITIVE_INFINITY:options.group_level;for(const result of results){const last=groups[groups.length-1];let groupKey=shouldGroup?result.key:null;shouldGroup&&Array.isArray(groupKey)&&(groupKey=groupKey.slice(0,lvl));if(last&&0===collate(last.groupKey,groupKey)){last.keys.push([result.key,result.id]);last.values.push(result.value)}else groups.push({keys:[[result.key,result.id]],values:[result.value],groupKey})}results=[];for(const group4 of groups){const reduceTry=tryReduce(view.sourceDB,reduceFun,group4.keys,group4.values,!1);if(reduceTry.error&&reduceTry.error instanceof BuiltInError)throw reduceTry.error;results.push({value:reduceTry.error?null:reduceTry.output,key:group4.groupKey})}return{rows:sliceResults(results,options.limit,options.skip)}}function queryView(view,opts){return sequentialize(getQueue(view),function(){return queryViewInQueue(view,opts)})()}async function queryViewInQueue(view,opts){async function fetchFromView(viewOpts){viewOpts.include_docs=!0;const res2=await view.db.allDocs(viewOpts);totalRows=res2.total_rows;return res2.rows.map(function(result){if("value"in result.doc&&"object"==typeof result.doc.value&&null!==result.doc.value){const keys3=Object.keys(result.doc.value).sort(),expectedKeys=["id","key","value"];if(!(keys3<expectedKeys||keys3>expectedKeys))return result.doc.value}const parsedKeyAndDocId=parseIndexableString(result.doc._id);return{key:parsedKeyAndDocId[0],id:parsedKeyAndDocId[1],value:"value"in result.doc?result.doc.value:null}})}async function onMapResultsReady(rows){let finalResults;finalResults=shouldReduce?reduceView(view,rows,opts):void 0===opts.keys?{total_rows:totalRows,offset:skip,rows}:{total_rows:totalRows,offset:skip,rows:sliceResults(rows,opts.limit,opts.skip)};opts.update_seq&&(finalResults.update_seq=view.seq);if(opts.include_docs){const docIds=uniq(rows.map(rowToDocId)),allDocsRes=await view.sourceDB.allDocs({keys:docIds,include_docs:!0,conflicts:opts.conflicts,attachments:opts.attachments,binary:opts.binary}),docIdsToDocs=new Map;for(const row of allDocsRes.rows)docIdsToDocs.set(row.id,row.doc);for(const row of rows){const docId=rowToDocId(row),doc=docIdsToDocs.get(docId);doc&&(row.doc=doc)}}return finalResults}let totalRows;const shouldReduce=view.reduceFun&&!1!==opts.reduce,skip=opts.skip||0;if(void 0!==opts.keys&&!opts.keys.length){opts.limit=0;delete opts.keys}if(void 0!==opts.keys){const keys3=opts.keys,fetchPromises=keys3.map(function(key3){const viewOpts={startkey:toIndexableString([key3]),endkey:toIndexableString([key3,{}])};opts.update_seq&&(viewOpts.update_seq=!0);return fetchFromView(viewOpts)}),result=await Promise.all(fetchPromises),flattenedResult=result.flat();return onMapResultsReady(flattenedResult)}{const viewOpts={descending:opts.descending};opts.update_seq&&(viewOpts.update_seq=!0);let startkey,endkey;"start_key"in opts&&(startkey=opts.start_key);"startkey"in opts&&(startkey=opts.startkey);"end_key"in opts&&(endkey=opts.end_key);"endkey"in opts&&(endkey=opts.endkey);void 0!==startkey&&(viewOpts.startkey=opts.descending?toIndexableString([startkey,{}]):toIndexableString([startkey]));if(void 0!==endkey){let inclusiveEnd=!1!==opts.inclusive_end;opts.descending&&(inclusiveEnd=!inclusiveEnd);viewOpts.endkey=toIndexableString(inclusiveEnd?[endkey,{}]:[endkey])}if(void 0!==opts.key){const keyStart=toIndexableString([opts.key]),keyEnd=toIndexableString([opts.key,{}]);if(viewOpts.descending){viewOpts.endkey=keyStart;viewOpts.startkey=keyEnd}else{viewOpts.startkey=keyStart;viewOpts.endkey=keyEnd}}if(!shouldReduce){"number"==typeof opts.limit&&(viewOpts.limit=opts.limit);viewOpts.skip=skip}const result=await fetchFromView(viewOpts);return onMapResultsReady(result)}}async function httpViewCleanup(db){const response=await db.fetch("_view_cleanup",{headers:new h2({"Content-Type":"application/json"}),method:"POST"});return response.json()}async function localViewCleanup(db){try{const metaDoc=await db.get("_local/"+localDocName2),docsToViews=new Map;for(const fullViewName of Object.keys(metaDoc.views)){const parts=parseViewName(fullViewName),designDocName="_design/"+parts[0],viewName=parts[1];let views=docsToViews.get(designDocName);if(!views){views=new Set;docsToViews.set(designDocName,views)}views.add(viewName)}const opts={keys:mapToKeysArray(docsToViews),include_docs:!0},res2=await db.allDocs(opts),viewsToStatus={};for(const row of res2.rows){const ddocName=row.key.substring(8);for(const viewName of docsToViews.get(row.key)){let fullViewName=ddocName+"/"+viewName;metaDoc.views[fullViewName]||(fullViewName=viewName);const viewDBNames=Object.keys(metaDoc.views[fullViewName]),statusIsGood=row.doc&&row.doc.views&&row.doc.views[viewName];for(const viewDBName of viewDBNames)viewsToStatus[viewDBName]=viewsToStatus[viewDBName]||statusIsGood}}const dbsToDelete=Object.keys(viewsToStatus).filter(function(viewDBName){return!viewsToStatus[viewDBName]}),destroyPromises=dbsToDelete.map(function(viewDBName){return sequentialize(getQueue(viewDBName),function(){return new db.constructor(viewDBName,db.__opts).destroy()})()});return Promise.all(destroyPromises).then(function(){return{ok:!0}})}catch(err3){if(404===err3.status)return{ok:!0};throw err3}}async function queryPromised(db,fun,opts){if("function"==typeof db._query)return customQuery(db,fun,opts);if(isRemote(db))return httpQuery(db,fun,opts);const updateViewOpts={changes_batch_size:db.__opts.view_update_changes_batch_size||CHANGES_BATCH_SIZE2};if("string"!=typeof fun){checkQueryParseError(opts,fun);tempViewQueue.add(async function(){const view=await createView(db,"temp_view/temp_view",fun.map,fun.reduce,!0,localDocName2);return fin(updateView(view,updateViewOpts).then(function(){return queryView(view,opts)}),function(){return view.db.destroy()})});return tempViewQueue.finish()}{const fullViewName=fun,parts=parseViewName(fullViewName),designDocName=parts[0],viewName=parts[1],doc=await db.get("_design/"+designDocName);fun=doc.views&&doc.views[viewName];if(!fun)throw new NotFoundError(`ddoc ${doc._id} has no view named ${viewName}`);ddocValidator3(doc,viewName);checkQueryParseError(opts,fun);const view=await createView(db,fullViewName,fun.map,fun.reduce,!1,localDocName2);if("ok"===opts.stale||"update_after"===opts.stale){"update_after"===opts.stale&&nextTick(function(){updateView(view,updateViewOpts)});return queryView(view,opts)}await updateView(view,updateViewOpts);return queryView(view,opts)}}const abstractViewCleanup=callbackify(function(){const db=this;return"function"==typeof db._viewCleanup?customViewCleanup(db):isRemote(db)?httpViewCleanup(db):localViewCleanup(db)});return{query:function abstractQuery(fun,opts,callback){const db=this;if("function"==typeof opts){callback=opts;opts={}}opts=opts?coerceOptions(opts):{};"function"==typeof fun&&(fun={map:fun});const promise=Promise.resolve().then(function(){return queryPromised(db,fun,opts)});promisedCallback(promise,callback);return promise},viewCleanup:abstractViewCleanup}};log=guardedConsole.bind(null,"log");isArray=Array.isArray;toJSON=JSON.parse;builtInReduce__sum=function(keys3,values2){return sum(values2)},builtInReduce__count=function(keys3,values2){return values2.length},builtInReduce__stats=function(keys3,values2){return{sum:sum(values2),min:Math.min.apply(null,values2),max:Math.max.apply(null,values2),count:values2.length,sumsqr:function sumsqr(values3){var i3,len,num,_sumsqr=0;for(i3=0,len=values3.length;i3<len;i3++){num=values3[i3];_sumsqr+=num*num}return _sumsqr}(values2)}};localDocName="mrviews";abstract=index_es_default5(localDocName,function mapper(mapFun,emit2){if("function"==typeof mapFun&&2===mapFun.length){var origMap=mapFun;return function(doc){return origMap(doc,emit2)}}return evalFunctionWithEval(mapFun.toString(),emit2)},function reducer(reduceFun){var reduceFunString=reduceFun.toString(),builtIn=getBuiltIn(reduceFunString);return builtIn||evalFunctionWithEval(reduceFunString)},function ddocValidator(ddoc,viewName){var fun=ddoc.views&&ddoc.views[viewName];if("string"!=typeof fun.map)throw new NotFoundError("ddoc "+ddoc._id+" has no string view named "+viewName+", instead found object of type: "+typeof fun.map)});index5={query:function query2(fun,opts,callback){return abstract.query.call(this,fun,opts,callback)},viewCleanup:function viewCleanup2(callback){return abstract.viewCleanup.call(this,callback)}};index_browser_es_default2=index5;CHECKPOINT_VERSION=1;REPLICATOR="pouchdb";CHECKPOINT_HISTORY_SIZE=5;LOWEST_SEQ=0;CheckpointerInternal=class{constructor(src,target,id,returnValue,opts={writeSourceCheckpoint:!0,writeTargetCheckpoint:!0}){this.src=src;this.target=target;this.id=id;this.returnValue=returnValue;this.opts=opts;void 0===opts.writeSourceCheckpoint&&(opts.writeSourceCheckpoint=!0);void 0===opts.writeTargetCheckpoint&&(opts.writeTargetCheckpoint=!0)}writeCheckpoint(checkpoint,session){var self3=this;return this.updateTarget(checkpoint,session).then(function(){return self3.updateSource(checkpoint,session)})}updateTarget(checkpoint,session){return this.opts.writeTargetCheckpoint?updateCheckpoint(this.target,this.id,checkpoint,session,this.returnValue):Promise.resolve(!0)}updateSource(checkpoint,session){if(this.opts.writeSourceCheckpoint){var self3=this;return updateCheckpoint(this.src,this.id,checkpoint,session,this.returnValue).catch(function(err3){if(isForbiddenError(err3)){self3.opts.writeSourceCheckpoint=!1;return!0}throw err3})}return Promise.resolve(!0)}getCheckpoint(){var self3=this;return self3.opts.writeSourceCheckpoint||self3.opts.writeTargetCheckpoint?self3.opts&&self3.opts.writeSourceCheckpoint&&!self3.opts.writeTargetCheckpoint?self3.src.get(self3.id).then(function(sourceDoc){return sourceDoc.last_seq||LOWEST_SEQ}).catch(function(err3){if(404!==err3.status)throw err3;return LOWEST_SEQ}):self3.target.get(self3.id).then(function(targetDoc){return self3.opts&&self3.opts.writeTargetCheckpoint&&!self3.opts.writeSourceCheckpoint?targetDoc.last_seq||LOWEST_SEQ:self3.src.get(self3.id).then(function(sourceDoc){if(targetDoc.version!==sourceDoc.version)return LOWEST_SEQ;var version2;version2=targetDoc.version?targetDoc.version.toString():"undefined";return version2 in comparisons?comparisons[version2](targetDoc,sourceDoc):LOWEST_SEQ},function(err3){if(404===err3.status&&targetDoc.last_seq)return self3.src.put({_id:self3.id,last_seq:LOWEST_SEQ}).then(function(){return LOWEST_SEQ},function(err4){if(isForbiddenError(err4)){self3.opts.writeSourceCheckpoint=!1;return targetDoc.last_seq}return LOWEST_SEQ});throw err3})}).catch(function(err3){if(404!==err3.status)throw err3;return LOWEST_SEQ}):Promise.resolve(LOWEST_SEQ)}};comparisons={undefined:function(targetDoc,sourceDoc){return 0===collate(targetDoc.last_seq,sourceDoc.last_seq)?sourceDoc.last_seq:0},1:function(targetDoc,sourceDoc){return compareReplicationLogs(sourceDoc,targetDoc).last_seq}};index_es_default6=function Checkpointer(src,target,id,returnValue,opts){return this instanceof CheckpointerInternal?Checkpointer:new CheckpointerInternal(src,target,id,returnValue,opts)};index_es_default7=function generateReplicationId(src,target,opts){var docIds=opts.doc_ids?opts.doc_ids.sort(collate):"",filterFun=opts.filter?opts.filter.toString():"",queryParams="",filterViewName="",selector="";opts.selector&&(selector=JSON.stringify(opts.selector));opts.filter&&opts.query_params&&(queryParams=JSON.stringify(sortObjectPropertiesByKey(opts.query_params)));opts.filter&&"_view"===opts.filter&&(filterViewName=opts.view.toString());return Promise.all([src.id(),target.id()]).then(function(res2){var queryData=res2[0]+res2[1]+filterFun+filterViewName+queryParams+docIds+selector;return new Promise(function(resolve){binaryMd5(queryData,resolve)})}).then(function(md5sum){md5sum=md5sum.replace(/\//g,".").replace(/\+/g,"_");return"_local/"+md5sum})};import_events19=__toESM(require_events());STARTING_BACK_OFF=0;Replication=class extends import_events19.default{constructor(){super();this.cancelled=!1;this.state="pending";const promise=new Promise((fulfill,reject)=>{this.once("complete",fulfill);this.once("error",reject)});this.then=function(resolve,reject){return promise.then(resolve,reject)};this.catch=function(reject){return promise.catch(reject)};this.catch(function(){})}cancel(){this.cancelled=!0;this.state="cancelled";this.emit("cancel")}ready(src,target){function cleanup(){src.removeListener("destroyed",onDestroy2);target.removeListener("destroyed",onDestroy2)}if(this._readyCalled)return;this._readyCalled=!0;const onDestroy2=()=>{this.cancel()};src.once("destroyed",onDestroy2);target.once("destroyed",onDestroy2);this.once("complete",cleanup);this.once("error",cleanup)}};Sync=class extends import_events19.default{constructor(src,target,opts,callback){function addOneListener(ee,event2,listener){-1==ee.listeners(event2).indexOf(listener)&&ee.on(event2,listener)}super();this.canceled=!1;const optsPush=opts.push?Object.assign({},opts,opts.push):opts,optsPull=opts.pull?Object.assign({},opts,opts.pull):opts;this.push=replicateWrapper(src,target,optsPush);this.pull=replicateWrapper(target,src,optsPull);this.pushPaused=!0;this.pullPaused=!0;const pullChange=change=>{this.emit("change",{direction:"pull",change})},pushChange=change=>{this.emit("change",{direction:"push",change})},pushDenied=doc=>{this.emit("denied",{direction:"push",doc})},pullDenied=doc=>{this.emit("denied",{direction:"pull",doc})},pushPaused=()=>{this.pushPaused=!0;this.pullPaused&&this.emit("paused")},pullPaused=()=>{this.pullPaused=!0;this.pushPaused&&this.emit("paused")},pushActive=()=>{this.pushPaused=!1;this.pullPaused&&this.emit("active",{direction:"push"})},pullActive=()=>{this.pullPaused=!1;this.pushPaused&&this.emit("active",{direction:"pull"})};let removed={};const removeAll=type=>(event2,func)=>{const isChange="change"===event2&&(func===pullChange||func===pushChange),isDenied="denied"===event2&&(func===pullDenied||func===pushDenied),isPaused="paused"===event2&&(func===pullPaused||func===pushPaused),isActive="active"===event2&&(func===pullActive||func===pushActive);if(isChange||isDenied||isPaused||isActive){event2 in removed||(removed[event2]={});removed[event2][type]=!0;2===Object.keys(removed[event2]).length&&this.removeAllListeners(event2)}};if(opts.live){this.push.on("complete",this.pull.cancel.bind(this.pull));this.pull.on("complete",this.push.cancel.bind(this.push))}this.on("newListener",function(event2){if("change"===event2){addOneListener(this.pull,"change",pullChange);addOneListener(this.push,"change",pushChange)}else if("denied"===event2){addOneListener(this.pull,"denied",pullDenied);addOneListener(this.push,"denied",pushDenied)}else if("active"===event2){addOneListener(this.pull,"active",pullActive);addOneListener(this.push,"active",pushActive)}else if("paused"===event2){addOneListener(this.pull,"paused",pullPaused);addOneListener(this.push,"paused",pushPaused)}});this.on("removeListener",function(event2){if("change"===event2){this.pull.removeListener("change",pullChange);this.push.removeListener("change",pushChange)}else if("denied"===event2){this.pull.removeListener("denied",pullDenied);this.push.removeListener("denied",pushDenied)}else if("active"===event2){this.pull.removeListener("active",pullActive);this.push.removeListener("active",pushActive)}else if("paused"===event2){this.pull.removeListener("paused",pullPaused);this.push.removeListener("paused",pushPaused)}});this.pull.on("removeListener",removeAll("pull"));this.push.on("removeListener",removeAll("push"));const promise=Promise.all([this.push,this.pull]).then(resp=>{const out={push:resp[0],pull:resp[1]};this.emit("complete",out);callback&&callback(null,out);this.removeAllListeners();return out},err3=>{this.cancel();callback?callback(err3):this.emit("error",err3);this.removeAllListeners();if(callback)throw err3});this.then=function(success,err3){return promise.then(success,err3)};this.catch=function(err3){return promise.catch(err3)}}cancel(){if(!this.canceled){this.canceled=!0;this.push.cancel();this.pull.cancel()}}};index_es_default8=function replication(PouchDB2){PouchDB2.replicate=replicateWrapper;PouchDB2.sync=sync;Object.defineProperty(PouchDB2.prototype,"replicate",{get:function(){var self3=this;void 0===this.replicateMethods&&(this.replicateMethods={from:function(other,opts,callback){return self3.constructor.replicate(other,self3,opts,callback)},to:function(other,opts,callback){return self3.constructor.replicate(self3,other,opts,callback)}});return this.replicateMethods}});PouchDB2.prototype.sync=function(dbName,opts,callback){return this.constructor.sync(this,dbName,opts,callback)}};nativeFlat=(...args)=>args.flat(1/0);polyFlat=(...args)=>{let res2=[];for(const subArr of args)Array.isArray(subArr)?res2=res2.concat(polyFlat(...subArr)):res2.push(subArr);return res2};flatten2="function"==typeof Array.prototype.flat?nativeFlat:polyFlat;requireValidation=["$all","$allMatch","$and","$elemMatch","$exists","$in","$mod","$nin","$nor","$not","$or","$regex","$size","$type"];arrayTypeComparisonOperators=["$in","$nin","$mod","$all"];equalityOperators=["$eq","$gt","$gte","$lt","$lte"];abstractMapper=index_es_default5("indexes",function mapper2(mapFunDef,emit2){const fields=Object.keys(mapFunDef.fields),partialSelector=mapFunDef.partial_filter_selector;return createMapper(fields,emit2,partialSelector)},function reducer2(){throw new Error("reduce not supported")},function ddocValidator2(ddoc,viewName){const view=ddoc.views[viewName];if(!view.map||!view.map.fields)throw new Error("ddoc "+ddoc._id+" with view "+viewName+" doesn't have map.fields defined. maybe it wasn't created by this plugin?")});ddocIdPrefix=/^_design\//;COLLATE_LO=null;COLLATE_HI={"￿":{}};SHORT_CIRCUIT_QUERY={queryOpts:{limit:0,startkey:COLLATE_HI,endkey:COLLATE_LO},inMemoryFields:[]};logicalMatchers=["$eq","$gt","$gte","$lt","$lte"];plugin={};plugin.createIndex=resolveToCallback(async function(requestDef){if("object"!=typeof requestDef)throw new Error("you must provide an index to create");const createIndex$$1=isRemote(this)?createIndex:createIndex$1;return createIndex$$1(this,requestDef)});plugin.find=resolveToCallback(async function(requestDef){if("object"!=typeof requestDef)throw new Error("you must provide search parameters to find()");const find$$1=isRemote(this)?find:find$1;return find$$1(this,requestDef)});plugin.explain=resolveToCallback(async function(requestDef){if("object"!=typeof requestDef)throw new Error("you must provide search parameters to explain()");const find$$1=isRemote(this)?explain:explain$1;return find$$1(this,requestDef)});plugin.getIndexes=resolveToCallback(async function(){const getIndexes$$1=isRemote(this)?getIndexes:getIndexes$1;return getIndexes$$1(this)});plugin.deleteIndex=resolveToCallback(async function(indexDef){if("object"!=typeof indexDef)throw new Error("you must provide an index to delete");const deleteIndex$$1=isRemote(this)?deleteIndex:deleteIndex$1;return deleteIndex$$1(this,indexDef)});index_browser_es_default3=plugin;import_transform_pouch=__toESM(require_transform_pouch(),1);index_es_default.plugin(index_es_default2).plugin(index_es_default3).plugin(index_es_default4).plugin(index_browser_es_default2).plugin(index_es_default8).plugin(index_browser_es_default3).plugin(import_transform_pouch.default);index_es_default.prototype.purgeMulti=adapterFun("_purgeMulti",function(docs,callback){if(void 0===this._purge)return callback(createError(UNKNOWN_ERROR,"Purge is not implemented in the "+this.adapter+" adapter."));const self3=this,tasks3=docs.map(param=>()=>new Promise((res2,rej)=>{const[docId,rev$$1]=param;self3._getRevisionTree(docId,(error,revs)=>{if(error)return res2([param,error]);if(!revs)return res2([param,createError(MISSING_DOC)]);let path2;try{path2=findPathToLeaf(revs,rev$$1)}catch(error2){return res2([param,error2.message||error2])}self3._purge(docId,path2,(error2,result)=>res2(error2?[param,error2]:[param,result]))})}));(async()=>{const ret=await mapAllTasksWithConcurrencyLimit(1,tasks3),retAll=ret.map(e3=>unwrapTaskResult(e3));await appendPurgeSeqs(self3,retAll.filter(e3=>"ok"in e3[1]).map(e3=>e3[0]));const result=Object.fromEntries(retAll.map(e3=>[e3[0][0],e3[1]]));return result})().then(result=>callback(void 0,result)).catch(error=>callback(error))});SveltePanel=class{constructor(component2,mountTo,valueStore){this._componentValue=writable(void 0);this._componentValue=null!=valueStore?valueStore:writable(void 0);this._mountedComponent=mount(component2,{target:mountTo,props:{port:this._componentValue}});return this}destroy(){this._mountedComponent&&unmount(this._mountedComponent)}get componentValue(){return get(this._componentValue)}set componentValue(value){this._componentValue.set(value)}};root6=from_html('<div class="info-entry info-key svelte-k6fu0l" role="listitem"><div class="key"> </div></div> <div class="info-entry info-item svelte-k6fu0l" role="listitem"><div class="value svelte-k6fu0l"> </div></div>',1);root_15=from_html('<div class="info-panel svelte-k6fu0l"><div class="info-grid svelte-k6fu0l" role="list"></div></div>');$$css5={hash:"svelte-k6fu0l",code:'.info-panel.svelte-k6fu0l {padding:0.6rem;flex-grow:1;}\n\n /* Main Grid (Info Items) 120px to 1fr, repeat */.info-grid.svelte-k6fu0l {display:grid;grid-template-columns:minmax(120px, 1fr) 1fr;column-count:2;gap:0.6rem;margin-top:0.5rem;grid-area:"info-key" "info-value";}.info-entry.svelte-k6fu0l {display:grid;gap:0.5rem;border-radius:6px;box-sizing:border-box;min-height:1.2em;}.info-key.svelte-k6fu0l {font-weight:600;align-items:center;border-top:1px solid var(--background-modifier-hover);border-bottom:1px solid var(--background-modifier-hover);grid-area:"info-key";}.info-item.svelte-k6fu0l {align-items:start;padding:0.5rem;background:var(--background-modifier-hover, rgba(0, 0, 0, 0.03));grid-area:"info-value";}.value.svelte-k6fu0l {white-space:pre-wrap;word-break:break-word;color:var(--text-normal, #e6e6e6);min-height:1em;}\n\n @container (max-width: 340px) {.info-grid.svelte-k6fu0l {grid-template-columns:1fr;}.info-item.svelte-k6fu0l {grid-template-columns:1fr;}\n }'};CONTEXT_DIALOG_CONTROLS="svelte-dialog-controls";SvelteDialogManagerBase=class{constructor(c3,dependents){__publicField(this,"_context");__publicField(this,"_dependents");this._context=c3;this._dependents=dependents}get context(){return this._context}get dependents(){return this._dependents}async open(component2,initialData){return await this.openSvelteDialog(component2,initialData)}async openWithExplicitCancel(component2,initialData){for(let i3=0;i3<10;i3++){const ret=await this.openSvelteDialog(component2,initialData);if(void 0!==ret)return ret;if(this.dependents.control.hasUnloaded())throw new Error("Operation cancelled due to app shutdown.");Logger(this.context.translate("Please select 'Cancel' explicitly to cancel this operation."),LOG_LEVEL_NOTICE)}throw new Error("Operation Forcibly cancelled by user.")}};root7=from_html("<h4> </h4>");root_16=from_html('<div class="dialog-header svelte-lddvve"><h2> </h2> <!></div>');$$css6={hash:"svelte-lddvve",code:".dialog-header.svelte-lddvve {display:none;}"};root8=from_html("<h3> </h3>");root_17=from_html("<div><!> <!></div>");root9=from_html("<div> </div>");root_18=from_html("<h3> </h3>");root_24=from_html("<p> </p>");root_34=from_html("<div><!> <!> <!> <!></div>");root10=from_html("<button> </button>");delegate(["click"]);root11=from_html("<h3><!></h3>");root_19=from_html('<div class="question-container svelte-1pmc71p"><!> <div class="question-content"><!></div></div>');$$css7={hash:"svelte-1pmc71p",code:".question-container.svelte-1pmc71p {border-bottom:2px solid var(--interactive-accent);margin-bottom:0.5lh;padding-bottom:0.5lh;}"};root12=from_html('<div><label><div class="choice-row svelte-1t4v6fm"><input type="radio" class="svelte-1t4v6fm"/> <span class="choice-title svelte-1t4v6fm"> </span></div> <div class="choice-notes svelte-1t4v6fm"><!> <!></div></label></div>');$$css8={hash:"svelte-1t4v6fm",code:'.option-container.svelte-1t4v6fm {border:1px solid transparent;border-radius:0.25lh;padding:0.5rem;}.option-container.selected.svelte-1t4v6fm {border-color:var(--interactive-accent);}.choice-row.svelte-1t4v6fm {display:flex;align-items:center;gap:0.5rem;\n /* margin-top: 1rem; */cursor:pointer;}.choice-row.svelte-1t4v6fm span.choice-title:where(.svelte-1t4v6fm) {width:auto;}.choice-row.svelte-1t4v6fm input[type="radio"]:where(.svelte-1t4v6fm) {\n /* width: 1.2rem;\n height: 1.2rem; */cursor:pointer;}.choice-notes.svelte-1t4v6fm {margin-left:2rem;margin-top:0.25rem;color:var(--text-muted);font-size:0.9rem;}.option-container.selected.svelte-1t4v6fm .choice-notes:where(.svelte-1t4v6fm) {color:var(--text-normal);}'};root13=from_html('<div class="options-container"><!></div>');root14=from_html('<div class="question-container"><!></div>');root15=from_html('<div class="button-group"><!></div>');TYPE_IDENTICAL="identical";TYPE_INDEPENDENT="independent";TYPE_UNBALANCED="unbalanced";TYPE_CANCEL="cancelled";TYPE_BACKUP_DONE="backup_done";TYPE_BACKUP_SKIPPED="backup_skipped";TYPE_UNABLE_TO_BACKUP="unable_to_backup";TYPE_NEW_USER="new-user";TYPE_EXISTING_USER="existing-user";TYPE_CANCELLED="cancelled";TYPE_EXISTING="existing-user";TYPE_NEW="new-user";TYPE_COMPATIBLE_EXISTING="compatible-existing-user";TYPE_APPLY="apply";TYPE_FETCH="fetch";TYPE_REBUILD="rebuild";TYPE_USE_SETUP_URI="use-setup-uri";TYPE_SCAN_QR_CODE="scan-qr-code";TYPE_CONFIGURE_MANUALLY="configure-manually";TYPE_CLOSE="close";TYPE_COUCHDB="couchdb";TYPE_BUCKET="bucket";TYPE_P2P="p2p";root16=from_html("<!> <!>",1);root_110=from_html("<!> <!> <!> <!> <!>",1);root17=from_html("<!> <!>",1);root_111=from_html("<!> <!> <!> <!>",1);root18=from_html("<!> <!> <!>",1);root_112=from_html("<!> <!>",1);root_25=from_html("<!> <!> <!> <!>",1);root19=from_html("<ol><li> </li> <li> </li> <li> </li> <li> </li></ol>");root_113=from_html("<!> <!> <!> <!>",1);root20=from_html('<label class="row"><span> </span> <!></label>');root21=from_html('<input spellcheck="false" autocorrect="off" autocapitalize="off"/> <input type="checkbox"/>',1);root22=from_html(" <br/> ",1);root_114=from_html('<input type="text" placeholder="obsidian://setuplivesync?settings=...." autocorrect="off" autocapitalize="off" spellcheck="false" required=""/>');root_26=from_html("<!> <!>",1);root_35=from_html("<!> <!> <!> <!> <!> <!> <!> <!>",1);root23=from_html("<p> </p> <p><strong> </strong> <br/> </p>",1);root_115=from_html("<!> <!>",1);root_27=from_html("<!> <!> <!> <!>",1);root_36=from_html("<p> <strong> </strong></p> <p><strong> </strong> <br/> </p>",1);root24=from_html("<p> </p> <p><strong> </strong> <br/> </p>",1);root_116=from_html("<!> <!>",1);root_28=from_html("<!> <!> <!> <!>",1);root_37=from_html("<p> <strong> </strong></p> <p><strong> </strong> <br/> </p>",1);root25=from_html(" <strong> </strong>",1);root_117=from_html("<!> <!> <!> <!>",1);root_29=from_html("<!> <!>",1);root26=from_html("<p> </p>");root_118=from_html("<!> <!> <!>",1);root_210=from_html("<!> <!>",1);root_38=from_html("<!> <!> <!> <!>",1);root27=from_html("<!> <!> <!>",1);root_119=from_html("<!> <!>",1);root28=from_html('<details><summary> </summary> <div class="sub-section"><!></div></details>');checkConfig=async editingSettings=>{var _a13,_b6,_c3,_d2,_e2,_f,_g,_h2,_i2,_j,_k,_l,_m2,_n;const result=[],addMessage=(msg,classes=[])=>{result.push({message:msg,classes})},addSuccess=(msg,value)=>{result.push({message:msg,result:"ok",value})},_addError=(message,fixMessage,settingKey,expectedValue,fix,value)=>{result.push({message,result:"error",fixMessage,settingKey,expectedValue,fix,value})},addErrorMessage=(msg,classes=[])=>{result.push({message:msg,result:"error",classes})},addError=(message,fixMessage,key3,expected)=>{_addError(message,fixMessage,key3,expected,async()=>{await updateRemoteSetting(editingSettings,key3,expected)},expected)};addMessage($msg("obsidianLiveSyncSettingTab.logCheckingDbConfig"));try{if(isCloudantURI(editingSettings.couchDB_URI)){addMessage($msg("obsidianLiveSyncSettingTab.logCannotUseCloudant"));return result}const customHeaders=parseHeaderValues(editingSettings.couchDB_CustomHeaders),credential=generateCredentialObject(editingSettings),r4=await requestToCouchDBWithCredentials(editingSettings.couchDB_URI,credential,compatGlobal.origin,void 0,void 0,void 0,customHeaders),responseConfig=normaliseCouchDBConfiguration(r4.json);addMessage($msg("obsidianLiveSyncSettingTab.msgNotice"),["ob-btn-config-head"]);addMessage($msg("obsidianLiveSyncSettingTab.msgIfConfigNotPersistent"),["ob-btn-config-info"]);addMessage($msg("obsidianLiveSyncSettingTab.msgConfigCheck"),["ob-btn-config-head"]);const serverBanner=null!=(_b6=null!=(_a13=r4.headers.server)?_a13:r4.headers.Server)?_b6:"unknown";addMessage($msg("obsidianLiveSyncSettingTab.serverVersion",{info:serverBanner}));const versionMatch=serverBanner.match(/CouchDB(\/([0-9.]+))?/),versionStr=versionMatch?versionMatch[2]:"0.0.0";editingSettings.couchDB_USER in responseConfig.admins?addSuccess($msg("obsidianLiveSyncSettingTab.okAdminPrivileges")):addSuccess($msg("obsidianLiveSyncSettingTab.warnNoAdmin"));isGreaterThanOrEqual(versionStr,"3.2.0")?"true"!=(null==(_c3=null==responseConfig?void 0:responseConfig.chttpd)?void 0:_c3.require_valid_user)?addError($msg("obsidianLiveSyncSettingTab.errRequireValidUser"),$msg("obsidianLiveSyncSettingTab.msgSetRequireValidUser"),"chttpd/require_valid_user","true"):addSuccess($msg("obsidianLiveSyncSettingTab.okRequireValidUser")):"true"!=(null==(_d2=null==responseConfig?void 0:responseConfig.chttpd_auth)?void 0:_d2.require_valid_user)?addError($msg("obsidianLiveSyncSettingTab.errRequireValidUserAuth"),$msg("obsidianLiveSyncSettingTab.msgSetRequireValidUserAuth"),"chttpd_auth/require_valid_user","true"):addSuccess($msg("obsidianLiveSyncSettingTab.okRequireValidUserAuth"));(null==responseConfig?void 0:responseConfig.httpd["WWW-Authenticate"])?addSuccess($msg("obsidianLiveSyncSettingTab.okWwwAuth")):addError($msg("obsidianLiveSyncSettingTab.errMissingWwwAuth"),$msg("obsidianLiveSyncSettingTab.msgSetWwwAuth"),"httpd/WWW-Authenticate",'Basic realm="couchdb"');isGreaterThanOrEqual(versionStr,"3.2.0")?"true"!=(null==(_e2=null==responseConfig?void 0:responseConfig.chttpd)?void 0:_e2.enable_cors)?addError($msg("obsidianLiveSyncSettingTab.errEnableCorsChttpd"),$msg("obsidianLiveSyncSettingTab.msgEnableCorsChttpd"),"chttpd/enable_cors","true"):addSuccess($msg("obsidianLiveSyncSettingTab.okEnableCorsChttpd")):"true"!=(null==(_f=null==responseConfig?void 0:responseConfig.httpd)?void 0:_f.enable_cors)?addError($msg("obsidianLiveSyncSettingTab.errEnableCors"),$msg("obsidianLiveSyncSettingTab.msgEnableCors"),"httpd/enable_cors","true"):addSuccess($msg("obsidianLiveSyncSettingTab.okEnableCors"));if(!isCloudantURI(editingSettings.couchDB_URI)){Number(null!=(_h2=null==(_g=null==responseConfig?void 0:responseConfig.chttpd)?void 0:_g.max_http_request_size)?_h2:0)<4294967296?addError($msg("obsidianLiveSyncSettingTab.errMaxRequestSize"),$msg("obsidianLiveSyncSettingTab.msgSetMaxRequestSize"),"chttpd/max_http_request_size","4294967296"):addSuccess($msg("obsidianLiveSyncSettingTab.okMaxRequestSize"));Number(null!=(_j=null==(_i2=null==responseConfig?void 0:responseConfig.couchdb)?void 0:_i2.max_document_size)?_j:0)<5e7?addError($msg("obsidianLiveSyncSettingTab.errMaxDocumentSize"),$msg("obsidianLiveSyncSettingTab.msgSetMaxDocSize"),"couchdb/max_document_size","50000000"):addSuccess($msg("obsidianLiveSyncSettingTab.okMaxDocumentSize"))}"true"!=(null==(_k=null==responseConfig?void 0:responseConfig.cors)?void 0:_k.credentials)?addError($msg("obsidianLiveSyncSettingTab.errCorsCredentials"),$msg("obsidianLiveSyncSettingTab.msgSetCorsCredentials"),"cors/credentials","true"):addSuccess($msg("obsidianLiveSyncSettingTab.okCorsCredentials"));const ConfiguredOrigins=((null!=(_m2=null==(_l=null==responseConfig?void 0:responseConfig.cors)?void 0:_l.origins)?_m2:"")+"").split(",");if("*"==(null==(_n=null==responseConfig?void 0:responseConfig.cors)?void 0:_n.origins)||-1!==ConfiguredOrigins.indexOf("app://obsidian.md")&&-1!==ConfiguredOrigins.indexOf("capacitor://localhost")&&-1!==ConfiguredOrigins.indexOf("http://localhost"))addSuccess($msg("obsidianLiveSyncSettingTab.okCorsOrigins"));else{const fixedValue=[...new Set([...ConfiguredOrigins.map(e3=>e3.trim()),"app://obsidian.md","capacitor://localhost","http://localhost"])].join(",");addError($msg("obsidianLiveSyncSettingTab.errCorsOrigins"),$msg("obsidianLiveSyncSettingTab.msgSetCorsOrigins"),"cors/origins",fixedValue)}addMessage($msg("obsidianLiveSyncSettingTab.msgConnectionCheck"),["ob-btn-config-head"]);addMessage($msg("obsidianLiveSyncSettingTab.msgCurrentOrigin",{origin:compatGlobal.location.origin}));const origins=["app://obsidian.md","capacitor://localhost","http://localhost"];for(const org of origins){const rr=await requestToCouchDBWithCredentials(editingSettings.couchDB_URI,credential,org,void 0,void 0,void 0,customHeaders),responseHeaders=Object.fromEntries(Object.entries(rr.headers).map(e3=>{e3[0]=`${e3[0]}`.toLowerCase();return e3}));addMessage($msg("obsidianLiveSyncSettingTab.msgOriginCheck",{org}));"true"!=responseHeaders["access-control-allow-credentials"]?addErrorMessage($msg("obsidianLiveSyncSettingTab.errCorsNotAllowingCredentials")):addSuccess($msg("obsidianLiveSyncSettingTab.okCorsCredentialsForOrigin"));responseHeaders["access-control-allow-origin"]!=org?addErrorMessage($msg("obsidianLiveSyncSettingTab.warnCorsOriginUnmatched",{from:origin,to:responseHeaders["access-control-allow-origin"]})):addSuccess($msg("obsidianLiveSyncSettingTab.okCorsOriginMatched"))}addMessage($msg("obsidianLiveSyncSettingTab.msgDone"),["ob-btn-config-head"]);addMessage($msg("obsidianLiveSyncSettingTab.msgConnectionProxyNote"),["ob-btn-config-info"]);addMessage($msg("obsidianLiveSyncSettingTab.logCheckingConfigDone"))}catch(ex){if(isUnauthorizedError(ex)){addErrorMessage($msg("obsidianLiveSyncSettingTab.errAccessForbidden"));addErrorMessage($msg("obsidianLiveSyncSettingTab.errCannotContinueTest"));addMessage($msg("obsidianLiveSyncSettingTab.logCheckingConfigDone"))}else{addErrorMessage($msg("obsidianLiveSyncSettingTab.logCheckingConfigFailed"));Logger(ex)}}return result};root29=from_html('<div class="operations svelte-a38xug"><button class="mod-cta"> </button></div>');root_120=from_html('<div><div class="message svelte-a38xug"> </div> <!></div>');root_211=from_html("<h3> </h3> <!>",1);root_39=from_html('<!> <div class="check-results svelte-a38xug"><details><summary><!></summary> <!></details></div>',1);$$css9={hash:"svelte-a38xug",code:"\n /* Make .check-result a CSS Grid: let .message expand and keep .operations at minimum width, aligned to the right */.check-results.svelte-a38xug {\n /* Adjust spacing as required */margin-top:0.75rem;}.check-result.svelte-a38xug {display:grid;grid-template-columns:1fr auto; /* message takes remaining space, operations use minimum width */align-items:center; /* vertically centre align */gap:0.5rem 1rem;padding:0rem 0.5rem;border-radius:0;box-shadow:none;border-left:0.5em solid var(--interactive-accent);margin-bottom:0.25lh;}.check-result.error.svelte-a38xug {border-left:0.5em solid var(--text-error);}.check-result.success.svelte-a38xug {border-left:0.5em solid var(--text-success);}.check-result.svelte-a38xug .message:where(.svelte-a38xug) {\n /* Wrap long messages */white-space:normal;word-break:break-word;font-size:0.95rem;color:var(--text-normal);}.check-result.svelte-a38xug .operations:where(.svelte-a38xug) {\n /* Centre the button(s) vertically and align to the right */display:flex;align-items:center;justify-content:flex-end;gap:0.5rem;}\n\n /* For small screens: move .operations below and stack vertically */\n @media (max-width: 520px) {.check-result.svelte-a38xug {grid-template-columns:1fr;grid-auto-rows:auto;}.check-result.svelte-a38xug .operations:where(.svelte-a38xug) {justify-content:flex-start;margin-top:0.5rem;}\n }"};delegate(["click"]);root30=from_html('<input type="text" name="couchdb-url" placeholder="https://example.com" autocorrect="off" autocapitalize="off" spellcheck="false" required="" pattern="^https?://.+"/>');root_121=from_html('<input type="text" name="couchdb-username" autocorrect="off" autocapitalize="off" spellcheck="false" required=""/>');root_212=from_html('<input type="text" name="couchdb-database" autocorrect="off" autocapitalize="off" spellcheck="false" required=""/>');root_310=from_html('<input type="checkbox" name="couchdb-use-internal-api"/>');root_44=from_html('<textarea name="couchdb-custom-headers" placeholder="e.g., x-example-header: value\\n another-header: value2" autocapitalize="off" spellcheck="false" rows="4"></textarea>');root_54=from_html('<input type="checkbox" name="couchdb-use-jwt"/>');root_64=from_html("<select><option>HS256</option><option>HS512</option><option>ES256</option><option>ES512</option></select>");root_73=from_html('<input type="text" name="couchdb-jwt-exp-duration" placeholder="0"/>');root_83=from_html('<textarea name="couchdb-jwt-key" rows="5" autocapitalize="off" spellcheck="false"></textarea>');root_93=from_html('<input type="text" name="couchdb-jwt-kid"/>');root_103=from_html('<input type="text" name="couchdb-jwt-sub"/>');root_1110=from_html("<!> <!> <!> <!> <!> <!> <!> <!>",1);root_123=from_html("<!> <!>",1);root_133=from_html("<!> <!> <!>",1);root_142=from_html("<!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <hr/> <!> <!>",1);root31=from_html('<input type="text" name="s3-endpoint" placeholder="https://s3.amazonaws.com" autocorrect="off" autocapitalize="off" spellcheck="false" required="" pattern="^https?://.+"/>');root_124=from_html('<input type="text" name="s3-access-key-id" autocorrect="off" autocapitalize="off" spellcheck="false" required=""/>');root_213=from_html('<input type="text" name="s3-bucket-name" autocorrect="off" autocapitalize="off" spellcheck="false" required=""/>');root_311=from_html('<input type="text" name="s3-region" autocorrect="off" autocapitalize="off" spellcheck="false"/>');root_45=from_html('<input type="checkbox" name="s3-use-path-style"/>');root_55=from_html('<input type="text" name="s3-folder-prefix" autocorrect="off" autocapitalize="off" spellcheck="false"/>');root_65=from_html('<input type="checkbox" name="s3-use-internal-api"/>');root_74=from_html('<textarea name="bucket-custom-headers" placeholder="e.g., x-example-header: value\\n another-header: value2" autocapitalize="off" spellcheck="false" rows="4"></textarea>');root_84=from_html("<!> <!> <!>",1);root_94=from_html("<!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!>",1);TrysteroReplicator=class{constructor(env,server){__publicField(this,"_env");__publicField(this,"server");__publicField(this,"_onSetup",!1);__publicField(this,"lastSeq","");__publicField(this,"changes");__publicField(this,"_isBroadcasting",!1);__publicField(this,"availableReplicationPairs",new Set);__publicField(this,"_replicateToPeers",new Set);__publicField(this,"_replicateFromPeers",new Set);__publicField(this,"_watchingPeers",new Set);this._env=env;if(server)this.server=server;else try{if(!this.settings.P2P_Enabled){Logger("P2P is not enabled",LOG_LEVEL_VERBOSE);return}if(!this.settings.P2P_AppID)throw new Error("P2P App ID is not provided. We need it to establish the P2P connection");if(!this.settings.P2P_roomID||!this.settings.P2P_passphrase)throw new Error("Room ID and/or P2P Passphrase have not provided. We need them to establish the P2P connection");if(!this.settings.P2P_relays||0===this.settings.P2P_relays.length)throw new Error("No relay URIs provided. We need them to establish the P2P connection");this.server=new TrysteroReplicatorP2PServer(env)}catch(e3){Logger(e3 instanceof Error?e3.message:"Error while creating TrysteroReplicator",LOG_LEVEL_NOTICE);Logger(e3,LOG_LEVEL_VERBOSE);throw e3}}replicationStatus(){return{}}get settings(){return this._env.settings}get db(){return this._env.db}get deviceName(){return this._env.deviceName}get platform(){return this._env.platform}get confirm(){return this._env.confirm}get translate(){return this._env.translate}async runFiniteReplicationActivity(task){return this._env.runFiniteReplicationActivity?await this._env.runFiniteReplicationActivity(task,{label:"replication"}):await task()}async canStartOrdinaryReplication(showMessage2=!1){return!this._env.canStartOrdinaryReplication||await this._env.canStartOrdinaryReplication(showMessage2)}async close(){var _a13;this.requestStatus();await(null==(_a13=this.server)?void 0:_a13.shutdown());this._replicateFromPeers.clear();this._replicateToPeers.clear();this._watchingPeers.clear();this.requestStatus();this.disconnectFromServer()}async open(){var _a13;this.allowReconnection();await(null==(_a13=this.server)?void 0:_a13.start([this.getCommands()]));this.dispatchStatus();this.settings.P2P_AutoBroadcast&&this.enableBroadcastChanges()}async makeSureOpened(){var _a13;(null==(_a13=this.server)?void 0:_a13.isServing)||await this.open()}get autoSyncPeers(){const peers=this.settings.P2P_AutoSyncPeers.split(",").map(e3=>e3.trim()).filter(e3=>e3.length>0).map(e3=>e3.startsWith("~")?new RegExp(e3.substring(1),"i"):new RegExp(`^${e3}$`,"i"));return peers}get autoWatchPeers(){const peers=this.settings.P2P_AutoWatchPeers.split(",").map(e3=>e3.trim()).filter(e3=>e3.length>0).map(e3=>e3.startsWith("~")?new RegExp(e3.substring(1),"i"):new RegExp(`^${e3}$`,"i"));return peers}async onNewPeer(peer){const peerName=peer.name;this.autoSyncPeers.some(e3=>e3.test(peerName))&&await this.runFiniteReplicationActivity(()=>this.sync(peer.peerId));this.autoWatchPeers.some(e3=>e3.test(peerName))&&this.watchPeer(peer.peerId)}onPeerLeaved(peerId){this.unwatchPeer(peerId)}setOnSetup(){this._onSetup=!0}clearOnSetup(){this._onSetup=!1}async getTweakSettings(fromPeerId){var _a13;const allSettings=JSON.parse(JSON.stringify(this.settings));for(const key3 in allSettings)"encrypt"!=key3&&("passphrase"!=key3?key3 in TweakValuesShouldMatchedTemplate||delete allSettings[key3]:allSettings[key3]=await getHashedStringWithCurrentTime(null!=(_a13=allSettings[key3])?_a13:""));return allSettings}getCommands(){return{reqSync:async fromPeerId=>{if(this._onSetup)return{error:new Error("The setup is in progress")};const result=await this.runFiniteReplicationActivity(()=>this.replicateFrom(fromPeerId));return result},"!reqAuth":async fromPeerId=>{var _a13;return await(null==(_a13=this.server)?void 0:_a13.isAcceptablePeer(fromPeerId))},getTweakSettings:async fromPeerId=>await this.getTweakSettings(fromPeerId),onProgress:async fromPeerId=>{if(this._onSetup)return{error:new Error("The setup is in progress")};await this.onUpdateDatabase(fromPeerId)},getAllConfig:async fromPeerId=>{if(this._onSetup)return{error:new Error("The setup is in progress")};const passphrase=await skipIfDuplicated(`getAllConfig-${fromPeerId}`,async()=>await this.confirm.askString("Passphrase required",this.translate("P2P.AskPassphraseForShare"),"something you only know",!0)),setting={...this.settings,configPassphraseStore:"",encryptedCouchDBConnection:"",encryptedPassphrase:"",pluginSyncExtendedSetting:{}};if(!passphrase||""==passphrase.trim()){Logger("Passphrase is required to transfer the configuration. The peer cannot be decrypt the config\nIf you repeatedly receive unintended configuration-sharing requests, change the RPC channel immediately. It allows you to leave the connection and disappear, while they are trying brute force attack for the decoy on their local.",LOG_LEVEL_NOTICE);const r4=JSON.stringify(Object.fromEntries(Object.entries(setting).map(([key3,value])=>[key3,"******".repeat(Math.ceil(10*Math.random())+2)]))),randomString=Math.random().toString(36).substring(7);return encrypt5(r4,randomString)}return encrypt5(JSON.stringify(setting),passphrase.trim())},onProgressAcknowledged:async(fromPeerId,info3)=>{try{await Promise.resolve(this.onProgressAcknowledged(fromPeerId,info3))}catch(e3){Logger("Error while acknowledging the progress",LOG_LEVEL_VERBOSE);Logger(e3,LOG_LEVEL_VERBOSE)}},getIsBroadcasting:()=>Promise.resolve(this._isBroadcasting),requestBroadcasting:async peerId=>{if(this._onSetup)return{error:new Error("The setup is in progress")};if(this._isBroadcasting)return!0;"yes"===await skipIfDuplicated(`requested-${peerId}`,async()=>await this.confirm.askYesNoDialog("The remote peer requested to broadcast the changes. Do you want to allow it?",{defaultOption:"No"}))&&this.enableBroadcastChanges()}}}async requestAuthenticate(peerId){if(!this.server)return!1;try{const connection=this.server.getConnection(peerId),selfPeerId=this.server.serverPeerId,r4=await connection.invokeRemoteObjectFunction("!reqAuth",[selfPeerId],2e4);return r4}catch(e3){Logger("Error while requesting authentication",LOG_LEVEL_VERBOSE);Logger(e3,LOG_LEVEL_VERBOSE);return!1}}async requestSynchroniseToPeer(peerId){if(!await this.canStartOrdinaryReplication(!1))return{error:new Error("Replication is not ready")};await delay(25);if(!this.server)throw new Error("Server is not available");const conn=this.server.getConnection(peerId),result=await conn.invokeRemoteFunction("reqSync",[this.server.serverPeerId],0);return result}async requestSynchroniseToAllAvailablePeers(){await scheduleOnceIfDuplicated("requestSynchroniseToAllAvailablePeers",async()=>{await delay(25);const replications=[...this.availableReplicationPairs].map(peerId=>this.requestSynchroniseToPeer(peerId));await Promise.all(replications)})}dispatchStatus(){this._env.events.emitEvent(EVENT_P2P_REPLICATOR_STATUS,{isBroadcasting:this._isBroadcasting,replicatingTo:[...this._replicateToPeers],replicatingFrom:[...this._replicateFromPeers],watchingPeers:[...this._watchingPeers]})}requestStatus(){var _a13;this.dispatchStatus();null==(_a13=this.server)||_a13.dispatchConnectionStatus()}disableBroadcastChanges(){var _a13;null==(_a13=this.changes)||_a13.cancel();this._isBroadcasting=!1;this.dispatchStatus()}enableBroadcastChanges(){if(this._isBroadcasting)return;this._isBroadcasting=!0;this.dispatchStatus();if(this.changes){this.changes.cancel();this.changes.removeAllListeners()}this.changes=this.db.changes({since:"now",live:!0,include_docs:!1,selector:{_id:{$gt:"_local/"}}});this.changes.on("change",async change=>{this.lastSeq=change.seq;await this.notifyProgress()});const closeChanges=reason=>{var _a13,_b6;if(reason)if(reason instanceof Error){Logger("Error while broadcasting the changes",LOG_LEVEL_INFO);Logger(reason,LOG_LEVEL_VERBOSE)}else{Logger("Broadcasting the changes has been finished",LOG_LEVEL_INFO);Logger(reason,LOG_LEVEL_VERBOSE)}null==(_a13=this.changes)||_a13.cancel();null==(_b6=this.changes)||_b6.removeAllListeners();this.changes=void 0;this._isBroadcasting=!1;this.dispatchStatus()};this.changes.on("error",closeChanges);this.changes.on("complete",closeChanges);fireAndForget(async()=>await this.notifyProgress())}get knownAdvertisements(){var _a13,_b6;return null!=(_b6=null==(_a13=this.server)?void 0:_a13.knownAdvertisements)?_b6:[]}async sync(remotePeer,showNotice=!1){const from=await this.replicateFrom(remotePeer,showNotice);if(!from||from.error){Logger("Error while replicating from the remote",LOG_LEVEL_VERBOSE);Logger(from.error,LOG_LEVEL_VERBOSE);return from}const logLevel=showNotice?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO;Logger(`P2P Replication has been requested to ${remotePeer}`,logLevel,"p2p-replicator");const res2=await this.requestSynchroniseToPeer(remotePeer);res2.ok&&Logger("P2P Replication has been done",logLevel,"p2p-replicator");if(res2.error){Logger("Error while syncing from the remote",logLevel,"p2p-replicator");Logger(res2.error,LOG_LEVEL_VERBOSE)}}dispatchReplicationProgress(peerId,info3){this.onReplicationProgress(peerId,info3)}onReplicationProgress(peerId,info3){var _a13,_b6;const name=(null==(_b6=null==(_a13=this.server)?void 0:_a13._knownAdvertisements.get(peerId))?void 0:_b6.name)||peerId,stat={peerId,peerName:name,fetching:{max:0,current:0,isActive:!1}};info3&&(stat.fetching={max:info3.maxSeqInBatch,current:info3.lastSeq,isActive:!0});this._env.events.emitEvent(EVENT_P2P_REPLICATOR_PROGRESS,stat);return!0}onProgressAcknowledged(peerId,info3){var _a13,_b6;const name=(null==(_b6=null==(_a13=this.server)?void 0:_a13._knownAdvertisements.get(peerId))?void 0:_b6.name)||peerId,ack={peerId,peerName:name,sending:{max:0,current:0,isActive:!1}};info3&&(ack.sending={max:info3.maxSeqInBatch,current:info3.lastSeq,isActive:!0});this._env.events.emitEvent(EVENT_P2P_REPLICATOR_PROGRESS,ack);return!0}acknowledgeProgress(remotePeerId,info3){if(!this.server)return;const connection=this.server.getConnection(remotePeerId);connection.invokeRemoteFunction("onProgressAcknowledged",[this.server.serverPeerId,info3],500).catch(ex=>{Logger("Error while acknowledging the progress",LOG_LEVEL_VERBOSE);Logger(ex,LOG_LEVEL_VERBOSE)})}async replicateFrom(remotePeer,showNotice=!1,fromStart=!1,skipOrdinaryReplicationPolicy=!1){if(!skipOrdinaryReplicationPolicy&&!await this.canStartOrdinaryReplication(showNotice))return{error:new Error("Replication is not ready")};const logLevel=showNotice?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO;Logger(`P2P Requesting Authentication to ${remotePeer}`,logLevel,"p2p-replicator");if(!0!==await this.requestAuthenticate(remotePeer)){Logger("Peer rejected the connection",LOG_LEVEL_NOTICE,"p2p-replicator");return{error:new Error("Peer rejected the connection")}}if(!0!==await this.checkTweakValues(remotePeer)){Logger("Tweak values are not matched",LOG_LEVEL_NOTICE,"p2p-replicator");return{error:new Error("Tweak values are not matched")}}Logger(`P2P Replicating from ${remotePeer}`,logLevel,"p2p-replicator");if(this._replicateFromPeers.has(remotePeer)){Logger(`Replication from ${remotePeer} is already in progress`,LOG_LEVEL_NOTICE,"p2p-replicator");return{error:new Error("Replication from this peer is already in progress")}}this._replicateFromPeers.add(remotePeer);this.dispatchStatus();try{if(!this.server)throw new Error("Server is not available");const connection=this.server.getConnection(remotePeer),remoteDB=connection.remoteDB;Logger(`P2P replicateFrom preparing remote DB info for ${remotePeer}`,LOG_LEVEL_VERBOSE,"p2p-replicator");const remoteDBInfo=await remoteDB.info();Logger(`P2P replicateFrom remote DB info for ${remotePeer}: ${remoteDBInfo.db_name} seq=${remoteDBInfo.update_seq}`,LOG_LEVEL_VERBOSE,"p2p-replicator");const localDBInfo=await this.db.info();Logger(`P2P replicateFrom local DB info for ${remotePeer}: ${localDBInfo.db_name} seq=${localDBInfo.update_seq}`,LOG_LEVEL_VERBOSE,"p2p-replicator");Logger(`P2P replicateFrom entering replicateShim for ${remotePeer}`,LOG_LEVEL_VERBOSE,"p2p-replicator");await replicateShim(this.db,remoteDB,async(docs,info3)=>{await this._env.processReplicatedDocs(docs);this.dispatchReplicationProgress(remotePeer,info3);this.acknowledgeProgress(remotePeer,info3);this.notifyProgress(remotePeer);Logger(`P2P Replication from ${remotePeer}\n${info3.lastSeq} / ${info3.maxSeqInBatch})`,logLevel,"p2p-replicator")},{live:!1,rewind:fromStart});Logger(`P2P replicateFrom replicateShim returned for ${remotePeer}`,LOG_LEVEL_VERBOSE,"p2p-replicator");this.acknowledgeProgress(remotePeer,void 0);Logger(`P2P Replication from ${remotePeer} has been completed`,logLevel,"p2p-replicator")}catch(e3){Logger("Error while P2P replicating",logLevel,"p2p-replicator");Logger(e3,LOG_LEVEL_VERBOSE);return{error:e3}}finally{this._replicateFromPeers.delete(remotePeer);this.dispatchStatus()}return{ok:!0}}notifyProgress(excludePeerId){if(this._isBroadcasting&&this.server){for(const peer of this.server.knownAdvertisements){const peerId=peer.peerId;peerId!==excludePeerId&&serialized(`notifyProgress-${peerId}`,async()=>{var _a13,_b6,_c3;const isAcceptable=await(null==(_a13=this.server)?void 0:_a13.isAcceptablePeer(peerId));if(isAcceptable)try{const ret=await(null==(_c3=this.server)?void 0:_c3.getConnection(peerId).invokeRemoteFunction("onProgress",[null==(_b6=this.server)?void 0:_b6.serverPeerId],0));return ret}catch(e3){Logger(`Error while notifying progress to ${peerId}`,LOG_LEVEL_VERBOSE);Logger(e3,LOG_LEVEL_VERBOSE)}else Logger(`Peer ${peerId} is not acceptable to notify progress`,LOG_LEVEL_VERBOSE)})}return Promise.resolve()}}async requestBroadcastChanges(peerId){var _a13;return await(null==(_a13=this.server)?void 0:_a13.getConnection(peerId).invokeRemoteFunction("requestBroadcasting",[this.server.serverPeerId],0))}async getRemoteIsBroadcasting(peerId){var _a13;try{return await(null==(_a13=this.server)?void 0:_a13.getConnection(peerId).invokeRemoteFunction("getIsBroadcasting",[],0))}catch(e3){Logger("Error while getting remote is broadcasting",LOG_LEVEL_VERBOSE);Logger(e3,LOG_LEVEL_VERBOSE)}}watchPeer(peerId){this._watchingPeers.add(peerId);this.dispatchStatus()}unwatchPeer(peerId){this._watchingPeers.delete(peerId);this.dispatchStatus()}async onUpdateDatabase(fromPeerId){if(this._watchingPeers.has(fromPeerId)){Logger(`Progress notification from ${fromPeerId}`,LOG_LEVEL_VERBOSE);return await serialized(`onProgress-${fromPeerId}`,async()=>await this.runFiniteReplicationActivity(()=>this.replicateFrom(fromPeerId)))}return!1}async getRemoteConfig(peerId){if(!this.server){Logger("Server is not available",LOG_LEVEL_NOTICE);return!1}const connection=this.server.getConnection(peerId),encryptedConfig=await connection.invokeRemoteFunction("getAllConfig",[this.server.serverPeerId],0),passphrase=await this.confirm.askString("Passphrase required",this.translate("P2P.AskPassphraseForDecrypt"),"something you only know",!0);if(!passphrase||""==passphrase.trim()){Logger("Passphrase is required to decrypt the configuration. The config cannot be decrypted",LOG_LEVEL_NOTICE);return!1}try{const decryptedConfig=JSON.parse(await decrypt5(encryptedConfig,passphrase));return decryptedConfig}catch(e3){Logger("Error while decrypting the configuration",LOG_LEVEL_NOTICE);Logger(e3,LOG_LEVEL_VERBOSE);return!1}}async checkTweakValues(peerId){var _a13;if(!this.server){Logger("Server is not available",LOG_LEVEL_NOTICE);return!1}const peerPlatform=null==(_a13=this.server.knownAdvertisements.find(e3=>e3.peerId==peerId))?void 0:_a13.platform;if(null==peerPlatform){Logger("Peer is not found",LOG_LEVEL_NOTICE);return!1}if("pseudo-replicator"===this.platform)return!0;if("pseudo-replicator"===peerPlatform)return!0;const connection=this.server.getConnection(peerId),tweakValues=await connection.invokeRemoteObjectFunction("getTweakSettings",[this.server.serverPeerId],5e3),thisTweakValues=await this.getTweakSettings("");if(!isObjectDifferent(thisTweakValues,tweakValues))return!0;if(thisTweakValues.passphrase!==tweakValues.passphrase){Logger("Replication cancelled: Passphrase is not matched\nCannot replicate to a remote database until the problem is resolved.",LOG_LEVEL_NOTICE);return!1}Logger("Some mismatched configuration have been detected... Please check settings for efficient replication.",LOG_LEVEL_NOTICE);return!0}async replicateFromCommand(showResult=!1){const r4=await skipIfDuplicated("replicateFromCommand",async()=>{var _a13;const logLevel=showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO;if(!this._env.settings.P2P_Enabled){Logger(this.translate("P2P.NotEnabled"),logLevel);return Promise.resolve(!1)}const peers=this._env.settings.P2P_SyncOnReplication.split(",").map(e3=>e3.trim()).filter(e3=>e3);if(0==peers.length){Logger(this.translate("P2P.NoAutoSyncPeers"),LOG_LEVEL_NOTICE);return Promise.resolve(!1)}for(const peer of peers){const peerId=null==(_a13=this.knownAdvertisements.find(e3=>e3.name==peer))?void 0:_a13.peerId;if(peerId){Logger(this.translate("P2P.SyncStartedWith",{name:peer}),logLevel);await this.sync(peerId,showResult)}else Logger(this.translate("P2P.SeemsOffline",{name:peer}),logLevel)}Logger(this.translate("P2P.SyncCompleted"),logLevel);return Promise.resolve(!0)});null===r4&&Logger(this.translate("P2P.SyncAlreadyRunning"),LOG_LEVEL_NOTICE)}disconnectFromServer(){const connections=getRelaySockets(),sockets=Object.entries(connections);pauseRelayReconnection();sockets.forEach(([,s2])=>{s2.close()});this.pauseServe()}async pauseServe(){var _a13,_b6;await(null==(_a13=this.server)?void 0:_a13.close());await(null==(_b6=this.server)?void 0:_b6.dispatchConnectionStatus())}allowReconnection(){resumeRelayReconnection()}};root32=from_html('<input type="checkbox" name="p2p-enabled"/>');root_125=from_html('<input type="text" name="p2p-relay-url" placeholder="wss://relay.example.com" autocorrect="off" autocapitalize="off" spellcheck="false"/> <button class="button"> </button>',1);root_214=from_html(' <a href="https://github.com/vrtmrz/obsidian-livesync/blob/main/docs/p2p.md" target="_blank" rel="noopener noreferrer"> </a>.',1);root_312=from_html('<input type="text" name="p2p-room-id" placeholder="123-456-789-abc" autocorrect="off" autocapitalize="off" spellcheck="false"/> <button class="button"> </button>',1);root_46=from_html(" <br/> ",1);root_56=from_html('<input type="text" name="p2p-device-peer-id" placeholder="main-iphone16" autocorrect="off" autocapitalize="off" spellcheck="false"/>');root_66=from_html('<input type="checkbox" name="p2p-auto-start"/>');root_75=from_html('<input type="checkbox" name="p2p-auto-broadcast"/>');root_85=from_html('<select name="p2p-message-size"><option> </option><option> </option><option> </option><option> </option></select>');root_95=from_html('<select name="p2p-connection-path"><option> </option><option> </option></select>');root_104=from_html("<!> <!> <!> <!> <!>",1);root_1111=from_html(' <a href="https://github.com/vrtmrz/obsidian-livesync/blob/main/docs/p2p.md#signalling-relay-and-turn-server" target="_blank" rel="noopener noreferrer"> </a>.',1);root_126=from_html('<textarea name="p2p-turn-servers" placeholder="turn:turn.example.com:3478,turn:turn.example.com:443" autocapitalize="off" spellcheck="false" rows="5"></textarea>');root_134=from_html('<input type="text" name="p2p-turn-username" autocorrect="off" autocapitalize="off" spellcheck="false"/>');root_143=from_html("<!> <!> <!>",1);root_152=from_html("<!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!>",1);delegate(["click","change"]);root33=from_html('<input type="checkbox"/> <!>',1);root_127=from_html(" <br/> ",1);root_215=from_html('<input type="checkbox"/>');root_313=from_html("<option> </option>");root_47=from_html("<select></select>");root_57=from_html("<!> <!> <!>",1);root_67=from_html("<p> </p> <p> <br/><br/> </p>",1);root_76=from_html("<!> <!>",1);root_86=from_html("<!> <!> <!> <!> <!> <!> <!> <!> <!> <!>",1);import_qrcode_generator=__toESM(require_qrcode(),1);OutputFormat=(OutputFormat2=>{OutputFormat2[OutputFormat2.SVG=0]="SVG";OutputFormat2[OutputFormat2.ASCII=1]="ASCII";return OutputFormat2})(OutputFormat||{});AGGREGATOR_URL="https://vrtmrz.github.io/obsidian-livesync/aggregator.html";necessaryErasureProperties=["configPassphraseStore","encryptedCouchDBConnection","encryptedPassphrase"];UserMode=(UserMode2=>{UserMode2.NewUser="new-user";UserMode2.ExistingUser="existing-user";UserMode2.Unknown="unknown";UserMode2.Update="unknown";return UserMode2})(UserMode||{});SetupManager=class extends AbstractModule{get dialogManager(){return this.services.UI.dialogManager}async applySettingsWithInitialisationChoice({applySettings,isP2P,validateChoice=()=>Promise.resolve(!0)}){const mode=await this.dialogManager.openWithExplicitCancel(ApplySettingsInitialisation,{isP2P});if("cancelled"===mode)return{result:"cancelled"};if(!await validateChoice(mode))return{result:"failed",mode};const scheduled=await applySettingsWithScheduledInitialisation(this.core.rebuilder,mode,applySettings);return scheduled?{result:"scheduled",mode}:{result:"failed",mode}}async startOnBoarding(){const isUserNewOrExisting=await this.dialogManager.openWithExplicitCancel(Intro);if("new-user"===isUserNewOrExisting)await this.onOnboard("new-user");else if("existing-user"===isUserNewOrExisting)await this.onOnboard("existing-user");else if("cancelled"===isUserNewOrExisting){this._log("Onboarding cancelled by user.",LOG_LEVEL_NOTICE);return!1}return!1}async onOnboard(userMode){const originalSetting="new-user"===userMode?createNewVaultSettings():this.core.settings;if("new-user"===userMode){const method=await this.dialogManager.openWithExplicitCancel(SelectMethodNewUser);if("use-setup-uri"===method)await this.onUseSetupURI(userMode);else if("configure-manually"===method)await this.onConfigureManually(originalSetting,userMode);else if("cancelled"===method){this._log("Onboarding cancelled by user.",LOG_LEVEL_NOTICE);return!1}}else if("existing-user"===userMode){const method=await this.dialogManager.openWithExplicitCancel(SelectMethodExisting);if("use-setup-uri"===method)await this.onUseSetupURI(userMode);else if("configure-manually"===method)await this.onConfigureManually(originalSetting,userMode);else if("scan-qr-code"===method)await this.onPromptQRCodeInstruction();else if("cancelled"===method){this._log("Onboarding cancelled by user.",LOG_LEVEL_NOTICE);return!1}}return!1}async onUseSetupURI(userMode,setupURI=""){const newSetting=await this.dialogManager.openWithExplicitCancel(UseSetupURI,setupURI);if("cancelled"===newSetting){this._log("Setup URI dialog cancelled.",LOG_LEVEL_NOTICE);return!1}this._log("Setup URI dialog closed.",LOG_LEVEL_VERBOSE);return await this.onConfirmApplySettingsFromWizard(newSetting,userMode)}async onCouchDBManualSetup(userMode,currentSetting,activate=!0){const couchConf=await this.dialogManager.openWithExplicitCancel(SetupRemoteCouchDB,{settings:currentSetting,mode:"new-user"===userMode?"create-or-connect":"existing-user"===userMode?"connect-existing":"settings"});if("cancelled"===couchConf){this._log("Manual configuration cancelled.",LOG_LEVEL_NOTICE);return await this.onOnboard(userMode)}const newSetting={...copySettingsForRemoteProfileUpdate(currentSetting),...couchConf};activate&&(newSetting.remoteType=REMOTE_COUCHDB);upsertRemoteConfigurationInPlace(newSetting,"couchdb",{activate});return await this.onConfirmApplySettingsFromWizard(newSetting,userMode,activate)}async onBucketManualSetup(userMode,currentSetting,activate=!0){const bucketConf=await this.dialogManager.openWithExplicitCancel(SetupRemoteBucket,currentSetting);if("cancelled"===bucketConf){this._log("Manual configuration cancelled.",LOG_LEVEL_NOTICE);return await this.onOnboard(userMode)}const newSetting={...copySettingsForRemoteProfileUpdate(currentSetting),...bucketConf};activate&&(newSetting.remoteType=REMOTE_MINIO);upsertRemoteConfigurationInPlace(newSetting,"s3",{activate});return await this.onConfirmApplySettingsFromWizard(newSetting,userMode,activate)}async onP2PManualSetup(userMode,currentSetting,activate=!0){const p2pConf=await this.dialogManager.openWithExplicitCancel(SetupRemoteP2P,currentSetting);if("cancelled"===p2pConf){this._log("Manual configuration cancelled.",LOG_LEVEL_NOTICE);return await this.onOnboard(userMode)}const newSetting={...copySettingsForRemoteProfileUpdate(currentSetting),...p2pConf};upsertRemoteConfigurationInPlace(newSetting,"p2p",{id:newSetting.P2P_ActiveRemoteConfigurationId||void 0,activate,activateForP2P:!0});return await this.onConfirmApplySettingsFromWizard(newSetting,userMode,activate)}async onlyE2EEConfiguration(userMode,currentSetting){const e2eeConf=await this.dialogManager.openWithExplicitCancel(SetupRemoteE2EE,currentSetting);if("cancelled"===e2eeConf){this._log("E2EE configuration cancelled.",LOG_LEVEL_NOTICE);return!1}const newSetting={...currentSetting,...e2eeConf};return await this.onConfirmApplySettingsFromWizard(newSetting,userMode)}async onConfigureManually(originalSetting,userMode){const e2eeConf=await this.dialogManager.openWithExplicitCancel(SetupRemoteE2EE,originalSetting);if("cancelled"===e2eeConf){this._log("Manual configuration cancelled.",LOG_LEVEL_NOTICE);return await this.onOnboard(userMode)}const currentSetting={...originalSetting,...e2eeConf};return await this.onSelectServer(currentSetting,userMode)}async onSelectServer(currentSetting,userMode){const method=await this.dialogManager.openWithExplicitCancel(SetupRemote);if("couchdb"===method)return await this.onCouchDBManualSetup(userMode,currentSetting,!0);if("bucket"===method)return await this.onBucketManualSetup(userMode,currentSetting,!0);if("p2p"===method)return await this.onP2PManualSetup(userMode,currentSetting,!0);if("cancelled"===method){this._log("Manual configuration cancelled.",LOG_LEVEL_NOTICE);if("unknown"!==userMode)return await this.onOnboard(userMode)}return!1}async onConfirmApplySettingsFromWizard(newConf,_userMode,activate=!0,extra=()=>{}){newConf=await this.services.setting.adjustSettings({...this.settings,...newConf});let userMode=_userMode;if("unknown"===userMode){if(!1===isObjectDifferent(this.settings,newConf,!0)){this._log("No changes in settings detected. Skipping applying settings from wizard.",LOG_LEVEL_NOTICE);return!0}if(!activate){extra();const applied=await this.applySettingAndScheduleFetchOnActivation(newConf,"existing-user");applied&&this._log("Setting Applied",LOG_LEVEL_NOTICE);return applied}const original={...this.settings,P2P_DevicePeerName:""},modified={...newConf,P2P_DevicePeerName:""},isOnlyVirtualChange=!1===isObjectDifferent(original,modified,!0);if(isOnlyVirtualChange){extra();const applied=await this.applySettingAndScheduleFetchOnActivation(newConf,"existing-user");applied&&this._log("Settings from wizard applied.",LOG_LEVEL_NOTICE);return applied}{const userModeResult=await this.dialogManager.openWithExplicitCancel(OutroAskUserMode);if("new-user"===userModeResult)userMode="new-user";else if("existing-user"===userModeResult)userMode="existing-user";else{if("compatible-existing-user"===userModeResult){extra();const applied=await this.applySettingAndScheduleFetchOnActivation(newConf,"existing-user");applied&&this._log("Settings from wizard applied.",LOG_LEVEL_NOTICE);return applied}if("cancelled"===userModeResult){this._log("User cancelled applying settings from wizard.",LOG_LEVEL_NOTICE);return!1}}}}const component2="new-user"===userMode?OutroNewUser:OutroExistingUser,confirm=await this.dialogManager.openWithExplicitCancel(component2,{isP2P:isP2PMainRemote(newConf)});if("cancelled"===confirm){this._log("User cancelled applying settings from wizard..",LOG_LEVEL_NOTICE);return!1}if(confirm){extra();"new-user"===userMode?await applySettingsWithScheduledInitialisation(this.core.rebuilder,"rebuild",async()=>{await this.applySetting(newConf,userMode)}):await applySettingsWithScheduledInitialisation(this.core.rebuilder,"fetch",async()=>{await this.applySetting(newConf,userMode)})}return!1}async onPromptQRCodeInstruction(){const qrResult=await this.dialogManager.open(ScanQRCode);this._log("QR Code dialog closed.",LOG_LEVEL_VERBOSE);this._log(qrResult,LOG_LEVEL_VERBOSE);return!1}async decodeQR(qr){const newSettings=decodeSettingsFromQRCodeData(qr);return await this.onConfirmApplySettingsFromWizard(newSettings,"unknown")}async applySetting(newConf,userMode){this.services.setting.clearUsedPassphrase();await this.services.setting.applyExternalSettings(newConf,!0);return!0}async applySettingAndScheduleFetchOnActivation(newConf,userMode){const wasConfigured=this.settings.isConfigured;return await applySettingsAndFetchOnActivation(this.core.rebuilder,wasConfigured,newConf.isConfigured,async()=>{await this.applySetting(newConf,userMode)})}};root34=from_html('<li class="svelte-9kxeje"><label class="svelte-9kxeje"> </label> <span class="chip svelte-9kxeje"> </span> <input type="text"/> <button class="iconbutton svelte-9kxeje">🗑</button></li>');root_128=from_html('<ul class="svelte-9kxeje"><!> <li class="svelte-9kxeje"><label class="svelte-9kxeje"><button>Add</button></label></li> <li class="buttons svelte-9kxeje"><button>Apply</button> <button>Revert</button></li></ul>');$$css10={hash:"svelte-9kxeje",code:"label.svelte-9kxeje {min-width:4em;width:4em;display:inline-flex;flex-direction:row;justify-content:flex-end;}ul.svelte-9kxeje {flex-grow:1;display:inline-flex;flex-direction:column;list-style-type:none;margin-block-start:0;margin-block-end:0;margin-inline-start:0;margin-inline-end:0;padding-inline-start:0;}li.svelte-9kxeje {padding:var(--size-2-1) var(--size-4-1);display:inline-flex;flex-grow:1;align-items:center;justify-content:flex-end;gap:var(--size-4-2);}li.svelte-9kxeje input:where(.svelte-9kxeje) {min-width:10em;}button.iconbutton.svelte-9kxeje {max-width:4em;}.chip.svelte-9kxeje {background-color:var(--tag-background);color:var(--tag-color);padding:var(--size-2-1) var(--size-4-1);border-radius:0.5em;font-size:0.8em;}.chip.svelte-9kxeje:empty {display:none;}"};SETTINGS_ROOT_GROUP_CATALOGUE={"quick-setup":{icon:"🧙‍♂️",name:()=>$msg("obsidianLiveSyncSettingTab.titleQuickSetup")},synchronisation:{icon:"🔄",name:()=>$msg("obsidianLiveSyncSettingTab.titleSynchronisation")},"general-settings":{icon:"⚙️",name:()=>$msg("obsidianLiveSyncSettingTab.panelGeneralSettings")},"setup-other-devices":{icon:"📲",name:()=>$msg("obsidianLiveSyncSettingTab.titleSetupOtherDevices")},"maintenance-and-recovery":{icon:"🛠️",name:()=>$msg("obsidianLiveSyncSettingTab.titleMaintenanceAndRecovery")},"extra-features":{icon:"🧩",name:()=>$msg("obsidianLiveSyncSettingTab.titleExtraFeaturesGroup")},"advanced-settings":{icon:"🔧",name:()=>$msg("obsidianLiveSyncSettingTab.titleAdvancedSettings")},"help-and-information":{icon:"️",name:()=>$msg("obsidianLiveSyncSettingTab.titleHelpAndInformation")}};numberRangeMessage=({min:min2,max:max3})=>$msg("liveSyncSetting.valueShouldBeInRange",{min:void 0===min2?"~":`${min2}`,max:void 0===max3?"~":`${max3}`});ObsidianLiveSyncSettingTab=class extends import_obsidian.PluginSettingTab{constructor(app,plugin2){super(app,plugin2);this.selectedScreen="";this.settingComponents=[];this.controlledElementFunc=[];this.onSavedHandlers=[];this.isShown=!1;this.screenElements={};this.onlyOnP2POrCouchDB=()=>({visibility:this.isConfiguredAs("remoteType",REMOTE_P2P)||this.isConfiguredAs("remoteType",REMOTE_COUCHDB)});this.onlyOnCouchDB=()=>({visibility:this.isConfiguredAs("remoteType",REMOTE_COUCHDB)});this.onlyOnMinIO=()=>({visibility:this.isConfiguredAs("remoteType",REMOTE_MINIO)});this.onlyOnOnlyP2P=()=>({visibility:this.isConfiguredAs("remoteType",REMOTE_P2P)});this.onlyOnCouchDBOrMinIO=()=>({visibility:this.isConfiguredAs("remoteType",REMOTE_COUCHDB)||this.isConfiguredAs("remoteType",REMOTE_MINIO)});this.checkWorkingPassphrase=async()=>{if(this.editingSettings.remoteType==REMOTE_MINIO)return!0;const settingForCheck={...this.editingSettings},replicator=this.services.replicator.getNewReplicator(settingForCheck);if(!(replicator instanceof LiveSyncCouchDBReplicator))return!0;const db=await replicator.connectRemoteCouchDBWithSetting(settingForCheck,this.services.API.isMobile(),!0);if("string"==typeof db){Logger($msg("obsidianLiveSyncSettingTab.logCheckPassphraseFailed",{db}),LOG_LEVEL_NOTICE);return!1}try{if(await checkSyncInfo(db.db))return!0;Logger($msg("obsidianLiveSyncSettingTab.logPassphraseNotCompatible"),LOG_LEVEL_NOTICE);return!1}finally{await db.db.close()}};this.isPassphraseValid=async()=>{if(this.editingSettings.encrypt&&""==this.editingSettings.passphrase){Logger($msg("obsidianLiveSyncSettingTab.logEncryptionNoPassphrase"),LOG_LEVEL_NOTICE);return!1}if(this.editingSettings.encrypt&&!await testCrypt()){Logger($msg("obsidianLiveSyncSettingTab.logEncryptionNoSupport"),LOG_LEVEL_NOTICE);return!1}return!0};this.rebuildDB=async method=>{if(this.editingSettings.encrypt&&""==this.editingSettings.passphrase)Logger($msg("obsidianLiveSyncSettingTab.logEncryptionNoPassphrase"),LOG_LEVEL_NOTICE);else if(!this.editingSettings.encrypt||await testCrypt()){this.editingSettings.encrypt||(this.editingSettings.passphrase="");this.applyAllSettings();await this.services.setting.suspendAllSync();await this.services.setting.suspendExtraSync();this.reloadAllSettings();this.editingSettings.isConfigured=!0;Logger($msg("obsidianLiveSyncSettingTab.logRebuildNote"),LOG_LEVEL_NOTICE);await this.saveAllDirtySettings();this.closeSetting();await delay(2e3);await this.core.rebuilder.$performRebuildDB(method)}else Logger($msg("obsidianLiveSyncSettingTab.logEncryptionNoSupport"),LOG_LEVEL_NOTICE)};this.plugin=plugin2;LiveSyncSetting.env=this;eventHub.onEvent(EVENT_REQUEST_RELOAD_SETTING_TAB2,()=>{this.requestReload()});this.addOnSaved("displayLanguage",()=>this.requestCatalogueRefresh());this.addOnSaved("showStatusOnEditor",()=>eventHub.emitEvent(EVENT_ON_UNRESOLVED_ERROR));this.addOnSaved("networkWarningStyle",()=>eventHub.emitEvent(EVENT_ON_UNRESOLVED_ERROR));this.addOnSaved("useAdvancedMode",()=>this.requestCatalogueRefresh());this.addOnSaved("usePowerUserMode",()=>this.requestCatalogueRefresh());this.addOnSaved("useEdgeCaseMode",()=>this.requestCatalogueRefresh())}get lifetimeComponent(){if(!this._lifetimeComponent)throw new Error("The settings page render scope has not been initialised");return this._lifetimeComponent}get core(){return this.plugin.core}get services(){return this.core.services}get editingSettings(){this._editingSettings||this.reloadAllSettings();return this._editingSettings}set editingSettings(v2){this._editingSettings||this.reloadAllSettings();this._editingSettings=v2}copySettingValue(target,source2,key3){if(!target)throw new Error("Initial settings have not been loaded");const value=Reflect.get(source2,key3);Reflect.set(target,key3,value)}applySetting(keys3){for(const k2 of keys3)if(this.isDirty(k2)&&!(k2 in OnDialogSettingsDefault)){this.copySettingValue(this.core.settings,this.editingSettings,k2);this.copySettingValue(this.initialSettings,this.core.settings,k2)}keys3.forEach(e3=>this.refreshSetting(e3))}applyAllSettings(){var _a13;const changedKeys=Object.keys(null!=(_a13=this.editingSettings)?_a13:{}).filter(e3=>this.isDirty(e3));this.applySetting(changedKeys);this.reloadAllSettings()}async saveLocalSetting(key3){var _a13,_b6,_c3,_d2;if("configPassphrase"==key3){compatGlobal.localStorage.setItem("ls-setting-passphrase",null!=(_b6=null==(_a13=this.editingSettings)?void 0:_a13[key3])?_b6:"");return await Promise.resolve()}if("deviceAndVaultName"==key3){this.services.setting.setDeviceAndVaultName(null!=(_d2=null==(_c3=this.editingSettings)?void 0:_c3[key3])?_d2:"");this.services.setting.saveDeviceAndVaultName();return await Promise.resolve()}}async saveSettings(keys3){let hasChanged=!1;const appliedKeys=[];for(const k2 of keys3)if(this.isDirty(k2)){appliedKeys.push(k2);if(k2 in OnDialogSettingsDefault){await this.saveLocalSetting(k2);this.copySettingValue(this.initialSettings,this.editingSettings,k2)}else{this.copySettingValue(this.core.settings,this.editingSettings,k2);this.copySettingValue(this.initialSettings,this.core.settings,k2);hasChanged=!0}}hasChanged&&await this.services.setting.saveSettingData();const handlers3=this.onSavedHandlers.filter(e3=>-1!==appliedKeys.indexOf(e3.key)).map(e3=>Promise.resolve(e3.handler(this.editingSettings[e3.key])));await Promise.all(handlers3);keys3.forEach(e3=>this.refreshSetting(e3))}async saveAllDirtySettings(){var _a13;const changedKeys=Object.keys(null!=(_a13=this.editingSettings)?_a13:{}).filter(e3=>this.isDirty(e3));await this.saveSettings(changedKeys);this.reloadAllSettings()}requestUpdate(){scheduleTask("update-setting",10,()=>{for(const setting of this.settingComponents)setting._onUpdate();for(const func of this.controlledElementFunc)func();(0,import_obsidian.requireApiVersion)("1.13.0")&&"function"==typeof this.refreshDomState&&this.refreshDomState()})}requestPageRefresh(){this.activePageRefresh?this.activePageRefresh():(0,import_obsidian.requireApiVersion)("1.13.0")&&"function"==typeof import_obsidian.SettingPage&&"function"==typeof this.update?this.update():this.displayImperative()}requestCatalogueRefresh(){if((0,import_obsidian.requireApiVersion)("1.13.0")&&"function"==typeof import_obsidian.SettingPage&&"function"==typeof this.update){const refreshPage=this.activePageRefresh,owner=this._lifetimeComponent;this.update();owner&&this._lifetimeComponent===owner&&(null==refreshPage||refreshPage())}else this.displayImperative()}reloadAllLocalSettings(){const ret={...OnDialogSettingsDefault};ret.configPassphrase=compatGlobal.localStorage.getItem("ls-setting-passphrase")||"";ret.preset="";ret.deviceAndVaultName=this.services.setting.getDeviceAndVaultName();return ret}computeAllLocalSettings(){var _a13,_b6;const syncMode=(null==(_a13=this.editingSettings)?void 0:_a13.liveSync)?"LIVESYNC":(null==(_b6=this.editingSettings)?void 0:_b6.periodicReplication)?"PERIODIC":"ONEVENTS";return{syncMode}}reloadAllSettings(skipUpdate=!1){const localSetting=this.reloadAllLocalSettings();this._editingSettings={...this.core.settings,...localSetting};this._editingSettings={...this.editingSettings,...this.computeAllLocalSettings()};this.initialSettings={...this.editingSettings};skipUpdate||this.requestUpdate()}refreshSetting(key3){var _a13;const localSetting=this.reloadAllLocalSettings();if(key3 in this.core.settings)if(key3 in localSetting){this.copySettingValue(this.initialSettings,localSetting,key3);this.copySettingValue(this.editingSettings,localSetting,key3)}else{this.copySettingValue(this.initialSettings,this.core.settings,key3);this.copySettingValue(this.editingSettings,null!=(_a13=this.initialSettings)?_a13:{},key3)}this.editingSettings={...this.editingSettings,...this.computeAllLocalSettings()};this.requestUpdate()}isDirty(key3){var _a13;return isObjectDifferent(this.editingSettings[key3],null==(_a13=this.initialSettings)?void 0:_a13[key3])}isSomeDirty(keys3){return keys3.some(e3=>this.isDirty(e3))}isConfiguredAs(key3,value){return!!this.editingSettings&&this.editingSettings[key3]==value}async testConnection(settingOverride={}){const trialSetting={...this.editingSettings,...settingOverride},replicator=await this.services.replicator.getNewReplicator(trialSetting);if(!replicator){Logger("No replicator available for the current settings.",LOG_LEVEL_NOTICE);return}await replicator.tryConnectRemote(trialSetting);const status=await replicator.getRemoteStatus(trialSetting);status&&status.estimatedSize&&Logger($msg("obsidianLiveSyncSettingTab.logEstimatedSize",{size:sizeToHumanReadable(status.estimatedSize)}),LOG_LEVEL_NOTICE)}closeSetting(){closeObsidianSettings(this.plugin.app)}requestOpenSetupURI(){this.closeSetting();eventHub.emitEvent(EVENT_REQUEST_OPEN_SETUP_URI2)}async rerunOnboardingWizard(){await this.core.getModule(SetupManager).startOnBoarding()}async enableLiveSyncFromSettings(){this.editingSettings.isConfigured=!0;await this.saveAllDirtySettings();this.services.appLifecycle.askRestart()}requestCopySetupURI(){eventHub.emitEvent(EVENT_REQUEST_COPY_SETUP_URI2)}requestShowSetupQRCode(){eventHub.emitEvent(EVENT_REQUEST_SHOW_SETUP_QR2)}handleElement(element2,func){const updateFunc=((element3,func2)=>{const prev={};return()=>{const newValue=func2(),keys3=Object.keys(newValue);for(const k2 of keys3)if(prev[k2]!==newValue[k2]){"visibility"==k2&&element3.toggleClass("sls-setting-hidden",!newValue[k2]);prev[k2]=newValue[k2]}}})(element2,func);this.controlledElementFunc.push(updateFunc);updateFunc()}createEl(el,tag3,o2,callback,func){const element2=el.createEl(tag3,o2,callback);func&&this.handleElement(element2,func);return element2}addEl(el,tag3,o2,callback,func){const elm=this.createEl(el,tag3,o2,callback,func);return Promise.resolve(elm)}addOnSaved(key3,func){const newHandler={key:key3,handler:func},existing=this.onSavedHandlers.findIndex(handler=>handler.key===key3);-1===existing?this.onSavedHandlers.push(newHandler):this.onSavedHandlers.splice(existing,1,newHandler)}resetEditingSettings(){this._editingSettings=void 0;this.initialSettings=void 0}hide(){this.disposeRenderScope();super.hide();this.isShown=!1}changesPageCatalogue(key3){return"displayLanguage"===key3||"useAdvancedMode"===key3||"usePowerUserMode"===key3||"useEdgeCaseMode"===key3||"isConfigured"===key3||"liveSync"===key3||"periodicReplication"===key3||"syncOnSave"===key3||"syncOnEditorSave"===key3||"syncOnStart"===key3||"syncOnFileOpen"===key3||"syncAfterMerge"===key3}requestReload(){var _a13;const nativeTabIsShown=this.supportsDeclarativeSettings()&&void 0!==this.containerEl&&this.containerEl.isShown();if(this.isShown||nativeTabIsShown){const newConf=this.core.settings,keys3=Object.keys(newConf);let hasLoaded=!1,catalogueVisibilityChanged=!1;for(const k2 of keys3)if(isObjectDifferent(newConf[k2],null==(_a13=this.initialSettings)?void 0:_a13[k2]))if(this.isDirty(k2))this.core.confirm.askInPopup(`config-reloaded-${k2}`,$msg("obsidianLiveSyncSettingTab.msgSettingModified",{setting:getConfName2(k2)}),anchor=>{anchor.text=$msg("obsidianLiveSyncSettingTab.optionHere");anchor.addEventListener("click",()=>{this.refreshSetting(k2);this.changesPageCatalogue(k2)?this.requestCatalogueRefresh():this.requestPageRefresh()})});else{this.refreshSetting(k2);if(k2 in OnDialogSettingsDefault)continue;hasLoaded=!0;this.changesPageCatalogue(k2)&&(catalogueVisibilityChanged=!0)}hasLoaded?catalogueVisibilityChanged?this.requestCatalogueRefresh():this.requestPageRefresh():this.requestUpdate()}else this.reloadAllSettings(!0)}changeDisplay(screen){for(const k2 in this.screenElements)k2==screen?this.screenElements[k2].forEach(element2=>element2.removeClass("setting-collapsed")):this.screenElements[k2].forEach(element2=>element2.addClass("setting-collapsed"));this.menuEl&&this.menuEl.querySelectorAll(".sls-setting-label").forEach(element2=>{if(element2.hasClass(`c-${screen}`)){element2.addClass("selected");element2.querySelector("input[type=radio]").checked=!0}else{element2.removeClass("selected");element2.querySelector("input[type=radio]").checked=!1}});this.selectedScreen=screen}addScreenElement(key3,element2){key3 in this.screenElements||(this.screenElements[key3]=[]);this.screenElements[key3].push(element2)}selectPane(event2){const target=event2.target;if("INPUT"==target.tagName){const value=target.getAttribute("value");value&&this.selectedScreen!=value&&this.changeDisplay(value)}}isNeedRebuildLocal(){return this.isSomeDirty(["useIndexedDBAdapter","handleFilenameCaseSensitive","passphrase","useDynamicIterationCount","usePathObfuscation","encrypt"])}isNeedRebuildRemote(){return this.isSomeDirty(["handleFilenameCaseSensitive","passphrase","useDynamicIterationCount","usePathObfuscation","encrypt"])}isLiveSyncConfigured(){return this.isConfiguredAs("isConfigured",!0)}supportsDeclarativeSettings(){return(0,import_obsidian.requireApiVersion)("1.13.0")&&"function"==typeof import_obsidian.SettingPage}isPageVisible(level){return level===LEVEL_ADVANCED?this.isConfiguredAs("useAdvancedMode",!0):level===LEVEL_POWER_USER?this.isConfiguredAs("usePowerUserMode",!0):level!==LEVEL_EDGE_CASE||this.isConfiguredAs("useEdgeCaseMode",!0)}getDeclarativeSettingSpec(key3){const spec=[...createGeneralSettingSpecGroups({showEditorStatusDetails:()=>this.isConfiguredAs("showStatusOnEditor",!0),showVerboseLog:()=>this.isConfiguredAs("lessInformationInLog",!1)}),createExtraMenuSettingSpecGroup(),...createAdvancedSettingSpecGroups({isCouchDB:()=>this.isConfiguredAs("remoteType",REMOTE_COUCHDB)})].flatMap(group4=>group4.items).find(candidate=>candidate.key===key3);if(!spec)throw new Error(`Unknown declarative setting key: ${key3}`);return spec}getControlValue(key3){const spec=this.getDeclarativeSettingSpec(key3);return this.editingSettings[spec.key]}async setControlValue(key3,value){const spec=this.getDeclarativeSettingSpec(key3);if(!isValidSettingSpecValue(spec,value))throw new TypeError(`Invalid value for declarative setting ${key3}`);Reflect.set(this.editingSettings,spec.key,value);await this.saveSettings([spec.key])}createRebuildRequiredAction(){return{name:$msg("obsidianLiveSyncSettingTab.optionApply"),desc:$msg("obsidianLiveSyncSettingTab.msgChangesNeedToBeApplied"),visible:()=>this.isNeedRebuildLocal()||this.isNeedRebuildRemote(),action:()=>fireAndForget(async()=>await this.confirmRebuild())}}renderRebuildRequiredAction(parentEl){this.createEl(parentEl,"div",{cls:"sls-setting-menu-buttons"},el=>{el.createEl("label",{text:$msg("obsidianLiveSyncSettingTab.msgChangesNeedToBeApplied")});this.addEl(el,"button",{text:$msg("obsidianLiveSyncSettingTab.optionApply"),cls:"mod-warning"},buttonEl=>{buttonEl.addEventListener("click",()=>fireAndForget(async()=>await this.confirmRebuild()))})},visibleOnly(()=>this.isNeedRebuildLocal()||this.isNeedRebuildRemote()))}addPanel(parentEl,title,callback,func,level){const owner=this.lifetimeComponent,el=this.createEl(parentEl,"div",{text:""},callback,func);setLevelClass(el,level);this.createEl(el,"h4",{text:title,cls:"sls-setting-panel-title"});return this.resolveWithinRenderScope(el,owner)}resolveWithinRenderScope(value,owner){return{then:callback=>{queueMicrotask(()=>{this._lifetimeComponent===owner&&callback(value)})}}}renderCustomPage(page,entry){if((0,import_obsidian.requireApiVersion)("1.13.0")){const component2=this.beginRenderScope(()=>page.display());this.isShown=!0;page.title=entry.name();page.containerEl.empty();page.containerEl.addClass("sls-setting");setStyle(page.containerEl,"menu-setting-poweruser",()=>this.isConfiguredAs("usePowerUserMode",!0));setStyle(page.containerEl,"menu-setting-advanced",()=>this.isConfiguredAs("useAdvancedMode",!0));setStyle(page.containerEl,"menu-setting-edgecase",()=>this.isConfiguredAs("useEdgeCaseMode",!0));this.renderRebuildRequiredAction(page.containerEl);const addPane=(parentEl,title,_icon,_order,level)=>{const paneEl=this.createEl(parentEl,"div",{text:""});setLevelClass(paneEl,level);new LiveSyncSetting(paneEl).setName(title).setHeading().setClass("sls-setting-pane-title");return this.resolveWithinRenderScope(paneEl,component2)};entry.legacy.call(this,page.containerEl,{addPane,addPanel:this.addPanel.bind(this)});this.requestUpdate();return component2}throw new Error("Custom settings pages require Obsidian 1.13.0 or later")}createCustomSettingPage(entry){if((0,import_obsidian.requireApiVersion)("1.13.0")&&"function"==typeof import_obsidian.SettingPage){const renderCustomPage=this.renderCustomPage.bind(this),disposeRenderScope=this.disposeRenderScope.bind(this);return new class extends import_obsidian.SettingPage{constructor(){super(...arguments);this.title=entry.name()}display(){this.scope=renderCustomPage(this,entry)}hide(){disposeRenderScope(this.scope);this.scope=void 0;super.hide()}}}throw new Error("Custom settings pages require Obsidian 1.13.0 or later")}createDeclarativePage(entry){const page={type:"page",name:`${entry.icon} ${entry.name()}`,visible:()=>this.isPageVisible(entry.level)};"native"===entry.content?page.items=[this.createRebuildRequiredAction(),...createAdvancedSettingDefinitionGroups({isCouchDB:()=>this.isConfiguredAs("remoteType",REMOTE_COUCHDB)})]:page.page=()=>this.createCustomSettingPage(entry);return page}createGeneralSettingsGroup(){const groups=createGeneralSettingDefinitionGroups({showEditorStatusDetails:()=>this.isConfiguredAs("showStatusOnEditor",!0),showVerboseLog:()=>this.isConfiguredAs("lessInformationInLog",!1)}),[appearance,logging]=groups;if(!appearance||!logging)throw new Error("General settings must define Appearance and Logging groups");return this.createRootGroup("general-settings",[{type:"page",name:`🎨 ${appearance.heading}`,items:appearance.items},{type:"page",name:`📝 ${logging.heading}`,items:logging.items},this.createExtraMenusPage()])}createExtraMenusPage(){return{type:"page",name:`🎚️ ${$msg("obsidianLiveSyncSettingTab.titleExtraMenus")}`,items:createExtraMenuSettingDefinitions()}}createQuickSetupGroup(){return this.createRootGroup("quick-setup",[{name:$msg("obsidianLiveSyncSettingTab.nameConnectSetupURI"),desc:$msg("obsidianLiveSyncSettingTab.descConnectSetupURI"),action:()=>this.requestOpenSetupURI()},{name:$msg("Rerun Onboarding Wizard"),desc:$msg("Rerun the onboarding wizard to set up Self-hosted LiveSync again."),action:()=>fireAndForget(async()=>await this.rerunOnboardingWizard())},{name:$msg("obsidianLiveSyncSettingTab.nameEnableLiveSync"),desc:$msg("obsidianLiveSyncSettingTab.descEnableLiveSync"),visible:()=>!this.isConfiguredAs("isConfigured",!0),action:()=>fireAndForget(async()=>await this.enableLiveSyncFromSettings())}])}createRootGroup(id,items,visible){const{icon,name}=getSettingsRootGroupEntry(id);return{type:"group",heading:`${icon} ${name()}`,items,...visible?{visible}:{}}}createSetupOtherDevicesGroup(){return this.createRootGroup("setup-other-devices",[{name:$msg("obsidianLiveSyncSettingTab.nameCopySetupURI"),desc:$msg("obsidianLiveSyncSettingTab.descCopySetupURI"),action:()=>this.requestCopySetupURI()},{name:$msg("Setup.ShowQRCode"),desc:$msg("Setup.ShowQRCode.Desc"),action:()=>this.requestShowSetupQRCode()}],()=>this.isConfiguredAs("isConfigured",!0))}getSettingDefinitions(){if(!this.supportsDeclarativeSettings())return[];const catalogue=createSettingsPageCatalogue(),getPage=id=>{const entry=catalogue.find(candidate=>candidate.id===id);if(!entry)throw new Error(`Unknown settings page: ${id}`);return this.createDeclarativePage(entry)},synchronisation=this.createRootGroup("synchronisation",[getPage("remote-configuration"),getPage("synchronisation")]),generalSettings=this.createGeneralSettingsGroup(),quickSetup=this.createQuickSetupGroup(),setupOtherDevices=this.createSetupOtherDevicesGroup(),maintenance=this.createRootGroup("maintenance-and-recovery",[getPage("maintenance"),getPage("hatch")]),extraFeatures=this.createRootGroup("extra-features",[getPage("selector"),getPage("customisation-sync")],()=>this.isPageVisible(LEVEL_ADVANCED)),advancedSettings=this.createRootGroup("advanced-settings",[getPage("advanced"),getPage("power-users"),getPage("patches")],()=>this.isPageVisible(LEVEL_ADVANCED)||this.isPageVisible(LEVEL_POWER_USER)||this.isPageVisible(LEVEL_EDGE_CASE)),helpAndInformation=this.createRootGroup("help-and-information",[getPage("help"),getPage("change-log")]),laterGroups=[maintenance,extraFeatures,advancedSettings,helpAndInformation],pendingInitialisation=this.createRebuildRequiredAction();return this.isLiveSyncConfigured()?[pendingInitialisation,synchronisation,generalSettings,setupOtherDevices,quickSetup,...laterGroups]:[pendingInitialisation,quickSetup,synchronisation,generalSettings,setupOtherDevices,...laterGroups]}beginRenderScope(refresh){this.disposeRenderScope();const component2=new import_obsidian.Component;this._lifetimeComponent=component2;this.activePageRefresh=refresh;this.settingComponents.length=0;this.controlledElementFunc.length=0;component2.load();return component2}disposeRenderScope(owner){var _a13;if(!owner||this._lifetimeComponent===owner){null==(_a13=this._lifetimeComponent)||_a13.unload();this._lifetimeComponent=void 0;this.activePageRefresh=void 0;this.settingComponents.length=0;this.controlledElementFunc.length=0}}async confirmRebuild(){if(!await this.isPassphraseValid()){Logger("Passphrase is not valid, please fix it.",LOG_LEVEL_NOTICE);return}const keepEditing=$msg("Ui.SetupWizard.ApplySettingsInitialisation.KeepEditing"),setupManager=this.core.getModule(SetupManager),result=await setupManager.applySettingsWithInitialisationChoice({isP2P:isP2PMainRemote(this.editingSettings),validateChoice:async mode=>{if("fetch"!==mode||await this.checkWorkingPassphrase())return!0;const continueFetch=$msg("Ui.SetupWizard.ApplySettingsInitialisation.ContinueFetch");return await this.core.confirm.confirmWithMessage($msg("Ui.SetupWizard.ApplySettingsInitialisation.RemoteVerificationTitle"),$msg("Ui.SetupWizard.ApplySettingsInitialisation.RemoteVerificationGuidance"),[continueFetch,keepEditing],keepEditing)===continueFetch},applySettings:async()=>{this.editingSettings.encrypt||(this.editingSettings.passphrase="");await this.saveAllDirtySettings()}});if("scheduled"===result.result){this.closeSetting();return}if("failed"===result.result)return;const applyWithoutInitialisation=$msg("Ui.SetupWizard.ApplySettingsInitialisation.ApplyWithoutInitialisation"),fallback3=await this.core.confirm.confirmWithMessage($msg("Ui.SetupWizard.ApplySettingsInitialisation.BypassTitle"),$msg("Ui.SetupWizard.ApplySettingsInitialisation.BypassGuidance"),[applyWithoutInitialisation,keepEditing],keepEditing);if(fallback3===applyWithoutInitialisation){this.editingSettings.encrypt||(this.editingSettings.passphrase="");await this.saveAllDirtySettings()}}display(){this.displayImperative()}displayImperative(){const changeDisplay=this.changeDisplay.bind(this);this.beginRenderScope(()=>this.displayImperative());const{containerEl}=this;this.screenElements={};null!=this._editingSettings&&null!=this.initialSettings||this.reloadAllSettings();if(void 0===this.editingSettings||null==this.initialSettings)return;this.isShown=!0;containerEl.empty();containerEl.addClass("sls-setting");setStyle(containerEl,"menu-setting-poweruser",()=>this.isConfiguredAs("usePowerUserMode",!0));setStyle(containerEl,"menu-setting-advanced",()=>this.isConfiguredAs("useAdvancedMode",!0));setStyle(containerEl,"menu-setting-edgecase",()=>this.isConfiguredAs("useEdgeCaseMode",!0));const menuWrapper=this.createEl(containerEl,"div",{cls:"sls-setting-menu-wrapper"});this.menuEl&&this.menuEl.remove();this.menuEl=menuWrapper.createDiv("");this.menuEl.addClass("sls-setting-menu");const menuTabs=this.menuEl.querySelectorAll(".sls-setting-label");this.renderRebuildRequiredAction(menuWrapper);const addPane=(parentEl,title,icon,order,level)=>{const owner=this.lifetimeComponent,el=this.createEl(parentEl,"div",{text:""});setLevelClass(el,level);new LiveSyncSetting(el).setName(title).setHeading().setClass("sls-setting-pane-title");this.menuEl&&this.menuEl.createEl("label",{cls:`sls-setting-label c-${order}`},el2=>{setLevelClass(el2,level);const inputEl=el2.createEl("input",{type:"radio",name:"disp",value:`${order}`,cls:"sls-setting-tab"});el2.createDiv({cls:"sls-setting-menu-btn",text:icon,title});inputEl.addEventListener("change",evt=>this.selectPane(evt));inputEl.addEventListener("click",evt=>this.selectPane(evt))});this.addScreenElement(`${order}`,el);return this.resolveWithinRenderScope(el,owner)},addPanel=this.addPanel.bind(this);menuTabs.forEach(element2=>{const e3=element2.querySelector(".sls-setting-tab");e3&&e3.addEventListener("change",event2=>{menuTabs.forEach(element3=>element3.removeClass("selected"));this.changeDisplay(event2.currentTarget.value);element2.addClass("selected")})});const bindPane=paneFunc=>paneEl=>{paneFunc.call(this,paneEl,{addPane,addPanel})};for(const entry of createSettingsPageCatalogue())addPane(containerEl,entry.name(),entry.icon,entry.order,entry.level).then(bindPane(entry.legacy));yieldNextAnimationFrame().then(()=>{""==this.selectedScreen?this.isLiveSyncConfigured()?changeDisplay("20"):changeDisplay("110"):changeDisplay(this.selectedScreen);this.requestUpdate()})}getMinioJournalSyncClient(){return new JournalSyncCore(this.core.settings,this.core.simpleStore,this.core,new MinioStorageAdapter(this.core.settings,this.core))}async resetRemoteBucket(){const minioJournal=this.getMinioJournalSyncClient();await minioJournal.resetBucket()}};ModuleObsidianSettingDialogue=class extends AbstractObsidianModule{_everyOnloadAfterLoadSettings(){this.settingTab=new ObsidianLiveSyncSettingTab(this.app,this.plugin);this.settingTab.reloadAllSettings(!0);this.plugin.addSettingTab(this.settingTab);eventHub.onEvent(EVENT_REQUEST_OPEN_SETTINGS,()=>this.openSetting());return Promise.resolve(!0)}openSetting(){openObsidianSettings(this.app,"obsidian-livesync")}get appId(){return`${"appId"in this.app?this.app.appId:""}`}onBindFunction(core,services){services.appLifecycle.onSettingLoaded.addHandler(this._everyOnloadAfterLoadSettings.bind(this))}};DOCUMENT_HISTORY_PREFERENCE_KEYS_diffOnly="ols-history-diffonly",DOCUMENT_HISTORY_PREFERENCE_KEYS_highlightDiff="ols-history-highlightdiff";DocumentHistoryModal=class extends import_obsidian.Modal{constructor(app,core,plugin2,file,id,revision){super(app);this.showDiff=!1;this.diffOnly=!1;this.revs_info=[];this.currentText="";this.currentDeleted=!1;this.currentDiffIndex=-1;this.searchKeyword="";this.searchResults=[];this.currentSearchIndex=-1;this.searchTimeout=null;this.BlobURLs=new Map;this.plugin=plugin2;this.core=core;this.file=file instanceof import_obsidian.TFile?getPathFromTFile(file):file;this.id=id;this.initialRev=revision;!file&&id&&(this.file=this.services.path.id2path(id));loadDocumentHistoryPreference(this.app,DOCUMENT_HISTORY_PREFERENCE_KEYS_highlightDiff)&&(this.showDiff=!0);loadDocumentHistoryPreference(this.app,DOCUMENT_HISTORY_PREFERENCE_KEYS_diffOnly)&&(this.diffOnly=!0)}get services(){return this.core.services}async loadFile(initialRev){var _a13,_b6;this.id||(this.id=await this.services.path.path2id(this.file));const db=this.core.localDatabase;try{const w2=await db.getRaw(this.id,{revs_info:!0});this.revs_info=null!=(_b6=null==(_a13=w2._revs_info)?void 0:_a13.filter(e3=>"available"==(null==e3?void 0:e3.status)))?_b6:[];this.range.max=`${Math.max(this.revs_info.length-1,0)}`;this.range.value=this.range.max;this.fileInfo.setText(`${this.file} / ${this.revs_info.length} revisions`);await this.loadRevs(initialRev);this.updateRevisionNavUI()}catch(ex){if(isErrorOfMissingDoc(ex)){this.range.max="0";this.range.value="";this.range.disabled=!0;this.contentView.setText("We don't have any history for this note.");this.updateRevisionNavUI()}else{this.contentView.setText("Error while loading file.");Logger(ex,LOG_LEVEL_VERBOSE)}}}async loadRevs(initialRev){if(0==this.revs_info.length)return;if(initialRev){const rIndex=this.revs_info.findIndex(e3=>e3.rev==initialRev);rIndex>=0&&(this.range.value=""+(this.revs_info.length-1-rIndex))}const index6=this.revs_info.length-1-(Number(this.range.value)||0),rev3=this.revs_info[index6];await this.showExactRev(rev3.rev);this.updateRevisionNavUI()}navigateVersion(direction){const current=Number(this.range.value)||0,max3=Number(this.range.max)||0;if("older"===direction&&current>0)this.range.value=""+(current-1);else{if(!("newer"===direction&&current<max3))return;this.range.value=`${current+1}`}this.updateRevisionNavUI();scheduleOnceIfDuplicated("loadRevs",()=>this.loadRevs())}updateRevisionNavUI(){if(!this.revNavIndicator)return;const total=this.revs_info.length,max3=Number(this.range.max)||0,current=Number(this.range.value)||0;this.revNavIndicator.setText(total>0?`Rev ${current+1}/${total}`:"—");const disabled=!!this.range.disabled||total<=1;this.revPrevBtn.disabled=disabled||current<=0;this.revNextBtn.disabled=disabled||current>=max3}revokeURL(key3){const v2=this.BlobURLs.get(key3);v2&&URL.revokeObjectURL(v2);this.BlobURLs.delete(key3)}generateBlobURL(key3,data){this.revokeURL(key3);const v2=URL.createObjectURL(new Blob([data],{endings:"transparent",type:"application/octet-stream"}));this.BlobURLs.set(key3,v2);return v2}prepareContentView(usePreformatted=!0){this.contentView.empty();this.contentView.toggleClass("op-pre",usePreformatted)}appendTextDiff(diff){let hasOmitted=!1;for(const[operation2,text2]of diff)if(operation2==import_diff_match_patch.DIFF_DELETE){this.appendSearchHighlightedText(this.contentView.createSpan({cls:"history-deleted"}),text2);hasOmitted=!1}else if(operation2==import_diff_match_patch.DIFF_EQUAL)if(this.diffOnly){if(!hasOmitted){this.contentView.appendText("\n...\n");hasOmitted=!0}}else this.appendSearchHighlightedText(this.contentView.createSpan({cls:"history-normal"}),text2);else if(operation2==import_diff_match_patch.DIFF_INSERT){this.appendSearchHighlightedText(this.contentView.createSpan({cls:"history-added"}),text2);hasOmitted=!1}}appendSearchHighlightedText(container,text2){var _a13;if(!this.searchKeyword){container.appendText(text2);return}const escapedKeyword=this.searchKeyword.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),regex=new RegExp(escapedKeyword,"gi");let lastIndex=0;for(const match3 of text2.matchAll(regex)){const index6=null!=(_a13=match3.index)?_a13:0;index6>lastIndex&&container.appendText(text2.slice(lastIndex,index6));container.createEl("mark",{text:match3[0]});lastIndex=index6+match3[0].length}lastIndex<text2.length&&container.appendText(text2.slice(lastIndex))}appendImageDiff(baseSrc,overlaySrc){const wrap2=this.contentView.createDiv({cls:"ls-imgdiff-wrap"}),overlay=wrap2.createDiv({cls:"overlay"});overlay.createEl("img",{cls:"img-base"},img=>{img.src=baseSrc});overlaySrc&&overlay.createEl("img",{cls:"img-overlay"},img=>{img.src=overlaySrc})}appendDeletedNotice(usePreformatted=!0){const notice2="(At this revision, the file has been deleted)";usePreformatted?this.contentView.appendText(`${notice2}\n`):this.contentView.createDiv({text:notice2})}async showExactRev(rev3){const db=this.core.localDatabase;this.currentDoc=void 0;const w2=await db.getDBEntry(this.file,{rev:rev3},!1,!1,!0);this.currentText="";this.currentDeleted=!1;this.prepareContentView();if(!1===w2){this.currentDeleted=!0;this.info.empty();this.contentView.appendText("Could not read this revision");this.contentView.createEl("br");this.contentView.appendText(`(${rev3})`)}else{this.currentDoc=w2;this.info.setText(`Modified:${new Date(w2.mtime).toLocaleString()}`);const w1data=readDocument(w2);this.currentDeleted=!!w2.deleted;"string"==typeof w1data&&(this.currentText=w1data);let rendered=!1;if(this.showDiff){const prevRevIdx=this.revs_info.length-1-((Number(this.range.value)||0)-1);if(prevRevIdx>=0&&prevRevIdx<this.revs_info.length){const oldRev=this.revs_info[prevRevIdx].rev,w22=await db.getDBEntry(this.file,{rev:oldRev},!1,!1,!0);if(0!=w22)if("string"==typeof w1data){const w2data=readDocument(w22);if("string"==typeof w2data){const dmp=new import_diff_match_patch.diff_match_patch,diff=dmp.diff_main(w2data,w1data);dmp.diff_cleanupSemantic(diff);this.currentDeleted&&this.appendDeletedNotice();this.appendTextDiff(diff);rendered=!0}}else if(isImage(this.file)){const src=this.generateBlobURL("base",w1data),overlay=this.generateBlobURL("overlay",readDocument(w22));this.prepareContentView(!1);this.currentDeleted&&this.appendDeletedNotice(!1);this.appendImageDiff(src,overlay);rendered=!0}}}if(!rendered)if("string"!=typeof w1data)if(isImage(this.file)){const src=this.generateBlobURL("base",w1data);this.prepareContentView(!1);this.currentDeleted&&this.appendDeletedNotice(!1);this.appendImageDiff(src)}else{this.currentDeleted&&this.appendDeletedNotice();this.contentView.appendText("Binary file")}else{this.currentDeleted&&this.appendDeletedNotice();this.appendSearchHighlightedText(this.contentView,w1data)}}this.resetDiffNavigation();if(this.showDiff)this.navigateDiff("next");else if(this.searchKeyword){const firstMark=this.contentView.querySelector("mark");firstMark&&firstMark.scrollIntoView({behavior:"smooth",block:"center"})}}navigateDiff(direction){const diffElements=this.contentView.querySelectorAll(".history-added, .history-deleted");if(0===diffElements.length)return;const prevFocused=this.contentView.querySelector(".diff-focused");prevFocused&&prevFocused.classList.remove("diff-focused");this.currentDiffIndex="next"===direction?(this.currentDiffIndex+1)%diffElements.length:this.currentDiffIndex<=0?diffElements.length-1:this.currentDiffIndex-1;const target=diffElements[this.currentDiffIndex];target.classList.add("diff-focused");target.scrollIntoView({behavior:"smooth",block:"center"});this.diffNavIndicator.setText(`${this.currentDiffIndex+1}/${diffElements.length}`)}resetDiffNavigation(){this.currentDiffIndex=-1;if(this.diffNavIndicator)if(this.showDiff){const diffElements=this.contentView.querySelectorAll(".history-added, .history-deleted");this.diffNavIndicator.setText(diffElements.length>0?`0/${diffElements.length}`:"—")}else this.diffNavIndicator.setText("—");this.updateDiffNavVisibility()}updateDiffNavVisibility(){this.diffNavContainer&&this.diffNavContainer.setCssStyles({display:this.showDiff?"flex":"none"});this.diffOnlyLabel&&this.diffOnlyLabel.setCssStyles({display:this.showDiff?"inline-block":"none"})}async performSearch(keyword){this.searchKeyword=keyword;this.searchResults=[];this.currentSearchIndex=-1;if(!keyword){this.searchResultIndicator.setText("");this.searchProgressIndicator.setText("");this.updateSearchUI();return}const db=this.core.localDatabase,totalRevs=this.revs_info.length,end=Math.min(totalRevs,100);this.searchProgressIndicator.setText("Searching...");const dmp=new import_diff_match_patch.diff_match_patch;for(let i3=0;i3<end;i3++){const revInfo=this.revs_info[i3],rev3=revInfo.rev;this.searchProgressIndicator.setText(`Searching ${i3+1}/${end}...`);const doc=await db.getDBEntry(this.file,{rev:rev3},!1,!1,!0);if(!1===doc)continue;const content=readDocument(doc);if("string"!=typeof content)continue;const keywordLower=keyword.toLocaleLowerCase();if(content.toLocaleLowerCase().includes(keywordLower)){this.searchResults.push({rev:rev3,index:i3,matchType:"Content"});this.updateSearchUI()}else if(i3<totalRevs-1){const olderRev=this.revs_info[i3+1].rev,olderDoc=await db.getDBEntry(this.file,{rev:olderRev},!1,!1,!0);if(!1!==olderDoc){const olderContent=readDocument(olderDoc);if("string"==typeof olderContent){const diffs=dmp.diff_main(olderContent,content);let foundInDiff=!1;for(const d4 of diffs)if((d4[0]===import_diff_match_patch.DIFF_INSERT||d4[0]===import_diff_match_patch.DIFF_DELETE)&&d4[1].toLocaleLowerCase().includes(keywordLower)){foundInDiff=!0;break}if(foundInDiff){this.searchResults.push({rev:rev3,index:i3,matchType:"Diff"});this.updateSearchUI()}}}}}this.searchProgressIndicator.setText("Done");this.updateSearchUI()}updateSearchUI(){if(0===this.searchResults.length)this.searchResultIndicator.setText(this.searchKeyword?"No matches found":"");else{const current=this.currentSearchIndex>=0?this.currentSearchIndex+1:0;this.searchResultIndicator.setText(`${current}/${this.searchResults.length} matches`)}const hasResults=this.searchResults.length>0;this.searchPrevBtn.disabled=!hasResults;this.searchNextBtn.disabled=!hasResults}navigateSearch(direction){if(0===this.searchResults.length)return;this.currentSearchIndex="next"===direction?(this.currentSearchIndex+1)%this.searchResults.length:this.currentSearchIndex<=0?this.searchResults.length-1:this.currentSearchIndex-1;const match3=this.searchResults[this.currentSearchIndex];this.range.value=""+(this.revs_info.length-1-match3.index);scheduleOnceIfDuplicated("loadRevs",()=>this.loadRevs());this.updateSearchUI();"Diff"===match3.matchType&&this.showDiff}onOpen(){const{contentEl}=this;this.titleEl.setText("Document History");contentEl.empty();this.fileInfo=contentEl.createDiv("");this.fileInfo.addClass("op-info");const searchRow=contentEl.createDiv("");searchRow.addClass("op-info");searchRow.addClass("search-row");searchRow.addClass("history-search-row");const searchInput=searchRow.createEl("input",{type:"text",placeholder:"Search in history (last 100)..."});searchInput.addClass("history-search-input");searchInput.addEventListener("input",()=>{this.searchTimeout&&compatGlobal.clearTimeout(this.searchTimeout);this.searchTimeout=compatGlobal.setTimeout(()=>{this.performSearch(searchInput.value)},500)});this.searchPrevBtn=searchRow.createEl("button",{text:"▲"},e3=>{e3.title="Previous match";e3.disabled=!0;e3.addEventListener("click",()=>this.navigateSearch("prev"))});this.searchNextBtn=searchRow.createEl("button",{text:"▼"},e3=>{e3.title="Next match";e3.disabled=!0;e3.addEventListener("click",()=>this.navigateSearch("next"))});this.searchResultIndicator=searchRow.createSpan({text:""});this.searchResultIndicator.addClass("history-search-result-indicator");this.searchProgressIndicator=searchRow.createSpan({text:""});this.searchProgressIndicator.addClass("history-search-progress-indicator");const revNavRow=contentEl.createDiv({cls:"history-rev-nav-row"});this.revPrevBtn=revNavRow.createEl("button",{text:"◀"},e3=>{e3.addClass("history-rev-nav-btn");e3.title="Older revision";e3.disabled=!0;e3.addEventListener("click",()=>this.navigateVersion("older"))});revNavRow.createEl("input",{type:"range"},e3=>{this.range=e3;e3.addEventListener("change",()=>{this.updateRevisionNavUI();scheduleOnceIfDuplicated("loadRevs",()=>this.loadRevs())});e3.addEventListener("input",()=>{this.updateRevisionNavUI();scheduleOnceIfDuplicated("loadRevs",()=>this.loadRevs())})});this.revNextBtn=revNavRow.createEl("button",{text:"▶"},e3=>{e3.addClass("history-rev-nav-btn");e3.title="Newer revision";e3.disabled=!0;e3.addEventListener("click",()=>this.navigateVersion("newer"))});this.revNavIndicator=revNavRow.createSpan({text:"—"},e3=>{e3.addClass("history-rev-indicator")});const diffOptionsRow=contentEl.createDiv("");diffOptionsRow.addClass("op-info");diffOptionsRow.addClass("diff-options-row");diffOptionsRow.addClass("history-diff-options-row");const highlightDiffContainer=diffOptionsRow.createDiv("");highlightDiffContainer.addClass("history-highlight-diff-container");highlightDiffContainer.createEl("label",{},label2=>{label2.addClass("history-highlight-diff-label");label2.createEl("input",{type:"checkbox"},checkbox=>{this.showDiff&&(checkbox.checked=!0);checkbox.addEventListener("input",evt=>{this.showDiff=checkbox.checked;saveDocumentHistoryPreference(this.app,DOCUMENT_HISTORY_PREFERENCE_KEYS_highlightDiff,this.showDiff);this.updateDiffNavVisibility();scheduleOnceIfDuplicated("loadRevs",()=>this.loadRevs())})});label2.appendText("Highlight diff")});const diffOnlyLabel=diffOptionsRow.createEl("label",{});diffOnlyLabel.createEl("input",{type:"checkbox"},checkbox=>{this.diffOnly&&(checkbox.checked=!0);checkbox.addEventListener("input",evt=>{this.diffOnly=checkbox.checked;saveDocumentHistoryPreference(this.app,DOCUMENT_HISTORY_PREFERENCE_KEYS_diffOnly,this.diffOnly);scheduleOnceIfDuplicated("loadRevs",()=>this.loadRevs())})});diffOnlyLabel.appendText("Diff only");diffOnlyLabel.addClass("diff-only-label");diffOnlyLabel.setCssStyles({display:this.showDiff?"inline-block":"none"});this.diffOnlyLabel=diffOnlyLabel;this.diffNavContainer=diffOptionsRow.createDiv("");this.diffNavContainer.addClass("diff-nav");this.diffNavContainer.setCssStyles({display:this.showDiff?"flex":"none"});this.diffNavContainer.createEl("button",{text:"▲ Prev"},e3=>{e3.addClass("diff-nav-btn");e3.addEventListener("click",()=>{this.navigateDiff("prev")})});this.diffNavContainer.createEl("button",{text:"▼ Next"},e3=>{e3.addClass("diff-nav-btn");e3.addEventListener("click",()=>{this.navigateDiff("next")})});this.diffNavIndicator=this.diffNavContainer.createSpan({text:"—"});this.diffNavIndicator.addClass("diff-nav-indicator");this.info=contentEl.createDiv("");this.info.addClass("op-info");fireAndForget(async()=>await this.loadFile(this.initialRev));const div=contentEl.createDiv({text:"Loading old revisions..."});this.contentView=div;div.addClass("op-scrollable");div.addClass("op-pre");const buttons=contentEl.createDiv("");buttons.createEl("button",{text:"Copy to clipboard"},e3=>{e3.addClass("mod-cta");e3.addEventListener("click",()=>{fireAndForget(async()=>{await compatGlobal.navigator.clipboard.writeText(this.currentText);Logger("Old content copied to clipboard",LOG_LEVEL_NOTICE)})})});const focusFile=async path2=>{const targetFile=this.plugin.app.vault.getFileByPath(path2);if(targetFile){const leaf=this.plugin.app.workspace.getLeaf(!1);await leaf.openFile(targetFile)}else Logger("Unable to display the file in the editor",LOG_LEVEL_NOTICE)};buttons.createEl("button",{text:"Back to this revision"},e3=>{e3.addClass("mod-cta");e3.addEventListener("click",()=>{fireAndForget(async()=>{const pathToWrite=stripPrefix(this.file);if(!isValidPath(pathToWrite)){Logger("Path is not valid to write content.",LOG_LEVEL_INFO);return}if(!this.currentDoc){Logger("No active file loaded.",LOG_LEVEL_INFO);return}const sourceRevision=this.currentDoc._rev;if(!sourceRevision){Logger("The selected revision does not have a revision identifier.",LOG_LEVEL_NOTICE);return}e3.disabled=!0;let result;try{result=await restoreDocumentHistoryRevision(this.core,this.file,sourceRevision,{isPathValid:isValidPath})}catch(ex){Logger("Restoring the selected revision failed before Vault reflection completed. Review the file with 'Inspect conflicts and file/database differences' before retrying.",LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_VERBOSE);e3.disabled=!1;return}if("source-unavailable"!==result.status)if("current-unavailable"!==result.status)if("unsupported-path"!==result.status)if("database-write-refused"!==result.status)if("stored-not-reflected"!==result.status){result.conflictCheckError&&Logger(result.conflictCheckError,LOG_LEVEL_VERBOSE);!0===result.conflictsRemain?Logger("The selected content was restored as a new revision. Other versions remain unresolved; use 'Inspect conflicts and file/database differences' to review them.",LOG_LEVEL_NOTICE):!1===result.conflictsRemain?Logger("The selected content was restored as a new revision.",LOG_LEVEL_NOTICE):Logger("The selected content was restored as a new revision. LiveSync could not confirm whether other versions remain; use 'Inspect conflicts and file/database differences' to review the file.",LOG_LEVEL_NOTICE);try{await focusFile(result.path)}catch(ex){Logger("The restored file could not be opened in the editor.",LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_VERBOSE)}this.close()}else{Logger("The restored revision was saved in the local database, but it could not be reflected to the Vault. Use 'Inspect conflicts and file/database differences' to review and apply it.",LOG_LEVEL_NOTICE);result.cause&&Logger(result.cause,LOG_LEVEL_VERBOSE);this.close()}else{Logger("The restored revision could not be created. The file may have changed during the operation, and the Vault was not changed.",LOG_LEVEL_NOTICE);e3.disabled=!1}else{Logger("Only an ordinary valid Vault path can be restored from Document History.",LOG_LEVEL_NOTICE);e3.disabled=!1}else{Logger("The current database revision could not be read. The Vault was not changed.",LOG_LEVEL_NOTICE);e3.disabled=!1}else{Logger("The selected revision could not be restored because its content is no longer available.",LOG_LEVEL_NOTICE);e3.disabled=!1}})})})}onClose(){const{contentEl}=this;contentEl.empty();this.BlobURLs.forEach(value=>{value&&URL.revokeObjectURL(value)})}};ModuleObsidianDocumentHistory=class extends AbstractObsidianModule{_everyOnloadStart(){this.addCommand({id:"livesync-history",name:"Show history",callback:()=>{const file=this.services.vault.getActiveFilePath();file&&this.showHistory(file,void 0)}});this.addCommand({id:"livesync-filehistory",name:"Pick a file to show history",callback:()=>{fireAndForget(async()=>await this.fileHistory())}});eventHub.onEvent(EVENT_REQUEST_SHOW_HISTORY,({file,fileOnDB})=>{this.showHistory(file,fileOnDB._id)});return Promise.resolve(!0)}showHistory(file,id){new DocumentHistoryModal(this.app,this.core,this.plugin,file,id).open()}async fileHistory(){const notes=[];for await(const doc of this.localDatabase.findAllDocs())notes.push({id:doc._id,path:this.getPath(doc),dispPath:this.getPath(doc),mtime:doc.mtime});notes.sort((a2,b3)=>b3.mtime-a2.mtime);const notesList=notes.map(e3=>e3.dispPath),target=await this.core.confirm.askSelectString("File to view History",notesList);if(target){const targetId=notes.find(e3=>e3.dispPath==target);this.showHistory(targetId.path,targetId.id)}}onBindFunction(core,services){services.appLifecycle.onInitialise.addHandler(this._everyOnloadStart.bind(this))}};root35=from_html('<div class="svelte-1ddarry"> </div>');root_129=from_html('<th class="svelte-1ddarry"> </th>');root_216=from_html('<div class="svelte-1ddarry"></div>');root_314=from_html('<div class="svelte-1ddarry"><button class="svelte-1ddarry"> </button></div>');root_48=from_html('<span class="filename svelte-1ddarry" style="text-decoration: line-through"> </span>');root_58=from_html('<span class="filename svelte-1ddarry"><a class="svelte-1ddarry"> </a></span>');root_68=from_html('<a class="svelte-1ddarry"> </a>');root_77=from_html('<td class="svelte-1ddarry"> </td>');root_87=from_html('<tr class="svelte-1ddarry"><td class="mtime svelte-1ddarry"> </td><td class="path svelte-1ddarry"><div class="filenames svelte-1ddarry"><span class="path svelte-1ddarry"> </span> <!></div></td><td class="svelte-1ddarry"><span class="rev svelte-1ddarry"><!></span></td><td class="svelte-1ddarry"> </td><!></tr>');root_96=from_html('<div class="globalhistory svelte-1ddarry"><h1 class="svelte-1ddarry">Vault history</h1> <div class="control svelte-1ddarry"><div class="row svelte-1ddarry"><label for="" class="svelte-1ddarry">From:</label><input type="date" class="svelte-1ddarry"/></div> <div class="row svelte-1ddarry"><label for="" class="svelte-1ddarry">To:</label><input type="date" class="svelte-1ddarry"/></div> <div class="row svelte-1ddarry"><label for="" class="svelte-1ddarry">Info:</label> <label class="svelte-1ddarry"><input type="checkbox" class="svelte-1ddarry"/><span class="svelte-1ddarry"> </span></label> <label class="svelte-1ddarry"><input type="checkbox" class="svelte-1ddarry"/><span class="svelte-1ddarry"> </span></label> <label class="svelte-1ddarry"><input type="checkbox" class="svelte-1ddarry"/><span class="svelte-1ddarry"> </span></label></div></div> <!> <table class="svelte-1ddarry"><tbody class="svelte-1ddarry"><tr class="svelte-1ddarry"><th class="svelte-1ddarry"> </th><th class="svelte-1ddarry"> </th><th class="svelte-1ddarry"> </th><th class="svelte-1ddarry"> </th><!></tr><tr class="svelte-1ddarry"><td colspan="5" class="more svelte-1ddarry"><!></td></tr><!><tr class="svelte-1ddarry"><td colspan="5" class="more svelte-1ddarry"><!></td></tr></tbody></table></div>');$$css11={hash:"svelte-1ddarry",code:".svelte-1ddarry {box-sizing:border-box;}.globalhistory.svelte-1ddarry {margin-bottom:2em;}table.svelte-1ddarry {width:100%;}.more.svelte-1ddarry > div:where(.svelte-1ddarry) {display:flex;}.more.svelte-1ddarry > div:where(.svelte-1ddarry) > button:where(.svelte-1ddarry) {flex-grow:1;}th.svelte-1ddarry {position:sticky;top:0;backdrop-filter:blur(10px);}td.mtime.svelte-1ddarry {white-space:break-spaces;}td.path.svelte-1ddarry {word-break:break-word;}.row.svelte-1ddarry {display:flex;flex-direction:row;flex-wrap:wrap;}.row.svelte-1ddarry > label:where(.svelte-1ddarry) {display:flex;align-items:center;min-width:5em;}.row.svelte-1ddarry > input:where(.svelte-1ddarry) {flex-grow:1;}.filenames.svelte-1ddarry {display:flex;flex-direction:column;}.filenames.svelte-1ddarry > .path:where(.svelte-1ddarry) {font-size:70%;}.rev.svelte-1ddarry {text-overflow:ellipsis;max-width:3em;display:inline-block;overflow:hidden;white-space:nowrap;}"};VIEW_TYPE_GLOBAL_HISTORY="global-history";GlobalHistoryView=class extends SvelteItemView{constructor(leaf,plugin2){super(leaf);this.icon="clock";this.title="";this.navigation=!0;this.plugin=plugin2}instantiateComponent(target){return mount(GlobalHistory,{target,props:{plugin:this.plugin,core:this.plugin.core}})}getIcon(){return"clock"}getViewType(){return VIEW_TYPE_GLOBAL_HISTORY}getDisplayText(){return"Vault history"}};ModuleObsidianGlobalHistory=class extends AbstractObsidianModule{_everyOnloadStart(){this.addCommand({id:"livesync-global-history",name:"Show vault history",callback:()=>{this.showGlobalHistory()}});this.registerView(VIEW_TYPE_GLOBAL_HISTORY,leaf=>new GlobalHistoryView(leaf,this.plugin));return Promise.resolve(!0)}showGlobalHistory(){this.services.API.showWindow(VIEW_TYPE_GLOBAL_HISTORY)}onBindFunction(core,services){services.appLifecycle.onInitialise.addHandler(this._everyOnloadStart.bind(this))}};DB_KEY_SEQ="gc-seq";DB_KEY_CHUNK_SET="chunk-set";DB_KEY_DOC_USAGE_MAP="doc-usage-map";LocalDatabaseMaintenance=class extends LiveSyncCommands{onunload(){}onload(){this.services.API.addCommand({id:"analyse-database",name:"Analyse Database Usage (advanced)",icon:"database-search",checkCallback:checking=>{if(!this.settings.useAdvancedMode||!this._isDatabaseReady())return!1;checking||this.analyseDatabase();return!0}});this.services.API.addCommand({id:"gc-v3",name:"Garbage Collection V3 (advanced, beta)",icon:"trash-2",checkCallback:checking=>{const isApplicableRemote=this.settings.remoteType===REMOTE_COUCHDB;if(!this.settings.useEdgeCaseMode||!this._isDatabaseReady()||!isApplicableRemote)return!1;checking||this.gcv3();return!0}});eventHub.onEvent(EVENT_ANALYSE_DB_USAGE,()=>this.analyseDatabase());eventHub.onEvent(EVENT_REQUEST_PERFORM_GC_V3,()=>this.gcv3())}async allChunks(includeDeleted=!1){const p2=this._progress("",LOG_LEVEL_NOTICE);p2.log("Retrieving chunks informations..");try{const ret=await this.localDatabase.allChunks(includeDeleted);return ret}finally{p2.done()}}get database(){return this.localDatabase.localDatabase}clearHash(){this.localDatabase.clearCaches()}async confirm(title,message,affirmative="Yes",negative="No"){return await this.core.confirm.askSelectStringDialogue(message,[affirmative,negative],{title,defaultAction:affirmative})===affirmative}async ensureAvailable(operationName){return await ensureLocalDatabaseMaintenancePrerequisites({operationName,settings:this.settings,askSelectStringDialogue:this.core.confirm.askSelectStringDialogue.bind(this.core.confirm),applyPartial:async(settings,saveImmediately)=>{await this.core.services.setting.applyPartial(settings,saveImmediately);Object.assign(this.core.settings,settings)}})}async resurrectChunks(){if(!await this.ensureAvailable("Resurrect Chunks"))return;const{used,existing}=await this.allChunks(!0),excessiveDeletions=[...existing].filter(([key3,e3])=>e3._deleted).filter(([key3,e3])=>used.has(e3._id)).map(([key3,e3])=>e3),completelyLostChunks=[],dataLostChunks=[...existing].filter(([key3,e3])=>e3._deleted&&""===e3.data).map(([key3,e3])=>e3).filter(e3=>used.has(e3._id));for(const e3 of dataLostChunks){const doc=await this.database.get(e3._id,{rev:e3._rev,revs:!0,revs_info:!0,conflicts:!0}),history=doc._revs_info||[];let resurrected=null;const availableRevs=history.filter(e4=>"available"==e4.status).map(e4=>e4.rev).sort((a2,b3)=>getNoFromRev(a2)-getNoFromRev(b3));for(const rev3 of availableRevs){const revDoc=await this.database.get(e3._id,{rev:rev3});if("leaf"==revDoc.type&&""!==revDoc.data){resurrected=revDoc.data;break}}null!==resurrected?excessiveDeletions.push({...e3,data:resurrected,_deleted:!1}):completelyLostChunks.push(e3._id)}const resurrectChunks=excessiveDeletions.filter(e3=>""!==e3.data).map(e3=>({...e3,_deleted:!1}));if(0==resurrectChunks.length){this._notice("No chunks are found to be resurrected.");return}const message=`We have following chunks that are deleted but still used in the database.\n\n- Completely lost chunks: ${completelyLostChunks.length}\n- Resurrectable chunks: ${resurrectChunks.length}\n\nDo you want to resurrect these chunks?`;if(await this.confirm("Resurrect Chunks",message,"Resurrect","Cancel")){const result=await this.database.bulkDocs(resurrectChunks);this.clearHash();const resurrectedChunks=result.filter(e3=>"ok"in e3).map(e3=>e3.id);this._notice(`Resurrected chunks: ${resurrectedChunks.length} / ${resurrectChunks.length}`)}else this._notice("Resurrect operation is cancelled.")}async commitFileDeletion(){if(!await this.ensureAvailable("Delete Files"))return;const p2=this._progress("",LOG_LEVEL_NOTICE);p2.log("Searching for deleted files..");const docs=await this.database.allDocs({include_docs:!0}),deletedDocs=docs.rows.filter(e3=>{var _a13,_b6,_c3;return("newnote"==(null==(_a13=e3.doc)?void 0:_a13.type)||"plain"==(null==(_b6=e3.doc)?void 0:_b6.type))&&(null==(_c3=e3.doc)?void 0:_c3.deleted)});if(0==deletedDocs.length){p2.done("No deleted files found.");return}p2.log(`Found ${deletedDocs.length} deleted files.`);const message=`We have following files that are marked as deleted.\n\n- Deleted files: ${deletedDocs.length}\n\nAre you sure to delete these files permanently?\n\nNote: **Make sure to synchronise all devices before deletion.**\n\n> [!Note]\n> This operation affects the database permanently. Deleted files will not be recovered after this operation.\n> And, the chunks that are used in the deleted files will be ready for compaction.`,deletingDocs=deletedDocs.map(e3=>({...e3.doc,_deleted:!0}));if(await this.confirm("Delete Files",message,"Delete","Cancel")){const result=await this.database.bulkDocs(deletingDocs);this.clearHash();p2.done(`Deleted ${result.filter(e3=>"ok"in e3).length} / ${deletedDocs.length} files.`)}else p2.done("Deletion operation is cancelled.")}async commitChunkDeletion(){if(!await this.ensureAvailable("Delete Chunks"))return;const{existing}=await this.allChunks(!0),deletedChunks=[...existing].filter(([key3,e3])=>e3._deleted&&""!==e3.data).map(([key3,e3])=>e3),deletedNotVacantChunks=deletedChunks.map(e3=>({...e3,data:"",_deleted:!0})),size=deletedChunks.reduce((acc,e3)=>acc+e3.data.length,0),humanSize=sizeToHumanReadable(size),message=`We have following chunks that are marked as deleted.\n\n- Deleted chunks: ${deletedNotVacantChunks.length} (${humanSize})\n\nAre you sure to delete these chunks permanently?\n\nNote: **Make sure to synchronise all devices before deletion.**\n\n> [!Note]\n> This operation finally reduces the capacity of the remote.`;if(0!=deletedNotVacantChunks.length)if(await this.confirm("Delete Chunks",message,"Delete","Cancel")){const result=await this.database.bulkDocs(deletedNotVacantChunks);this.clearHash();this._notice(`Deleted chunks: ${result.filter(e3=>"ok"in e3).length} / ${deletedNotVacantChunks.length}`)}else this._notice("Deletion operation is cancelled.");else this._notice("No deleted chunks found.")}async markUnusedChunks(){if(!await this.ensureAvailable("Mark unused chunks"))return;const{used,existing}=await this.allChunks(),existChunks=[...existing],unusedChunks=existChunks.filter(([key3,e3])=>!used.has(e3._id)).map(([key3,e3])=>e3),deleteChunks=unusedChunks.map(e3=>({...e3,_deleted:!0})),size=deleteChunks.reduce((acc,e3)=>acc+e3.data.length,0),humanSize=sizeToHumanReadable(size);if(0==deleteChunks.length){this._notice("No unused chunks found.");return}const message=`We have following chunks that are not used from any files.\n\n- Chunks: ${deleteChunks.length} (${humanSize})\n\nAre you sure to mark these chunks to be deleted?\n\nNote: **Make sure to synchronise all devices before deletion.**\n\n> [!Note]\n> This operation will not reduces the capacity of the remote until permanent deletion.`;if(await this.confirm("Mark unused chunks",message,"Mark","Cancel")){const result=await this.database.bulkDocs(deleteChunks);this.clearHash();this._notice(`Marked chunks: ${result.filter(e3=>"ok"in e3).length} / ${deleteChunks.length}`)}}async removeUnusedChunks(){if(!await this.ensureAvailable("Delete unused chunks"))return;const{used,existing}=await this.allChunks(),existChunks=[...existing],unusedChunks=existChunks.filter(([key3,e3])=>!used.has(e3._id)).map(([key3,e3])=>e3),deleteChunks=unusedChunks.map(e3=>({...e3,data:"",_deleted:!0})),size=unusedChunks.reduce((acc,e3)=>acc+e3.data.length,0),humanSize=sizeToHumanReadable(size);if(0==deleteChunks.length){this._notice("No unused chunks found.");return}const message=`We have following chunks that are not used from any files.\n\n- Chunks: ${deleteChunks.length} (${humanSize})\n\nAre you sure to delete these chunks?\n\nNote: **Make sure to synchronise all devices before deletion.**\n\n> [!Note]\n> Chunks referenced from deleted files are not deleted. Please run "Commit File Deletion" before this operation.`;if(await this.confirm("Mark unused chunks",message,"Mark","Cancel")){const result=await this.database.bulkDocs(deleteChunks);this._notice(`Deleted chunks: ${result.filter(e3=>"ok"in e3).length} / ${deleteChunks.length}`);this.clearHash()}}async scanUnusedChunks(){const kvDB=this.core.kvDB,chunkSet=await kvDB.get(DB_KEY_CHUNK_SET)||new Set,chunkUsageMap=await kvDB.get(DB_KEY_DOC_USAGE_MAP)||new Map,unusedSet=new Set([...chunkSet]);for(const[,revIdMap]of chunkUsageMap){const sortedRevId=[...revIdMap.entries()].sort((a2,b3)=>getNoFromRev(b3[0])-getNoFromRev(a2[0]));sortedRevId.length;const keepRevID=sortedRevId.slice(0,10);keepRevID.forEach(e3=>e3[1].forEach(ee=>unusedSet.delete(ee)))}return{chunkSet,chunkUsageMap,unusedSet}}async trackChanges(fromStart=!1,showNotice=!1){if(!await this.ensureAvailable("Track chunk usage"))return;const logLevel=showNotice?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,kvDB=this.core.kvDB,previousSeq=fromStart?"":await kvDB.get(DB_KEY_SEQ),chunkSet=await kvDB.get(DB_KEY_CHUNK_SET)||new Set,chunkUsageMap=await kvDB.get(DB_KEY_DOC_USAGE_MAP)||new Map,db=this.localDatabase.localDatabase,verbose2=msg=>this._verbose(msg),processDoc=async(doc,isDeleted2)=>{if(!("children"in doc))return;const id=doc._id,rev3=doc._rev,deleted=doc._deleted||isDeleted2,softDeleted=doc.deleted,children=doc.children||[];chunkUsageMap.has(id)||chunkUsageMap.set(id,new Map);for(const chunkId of children)deleted?chunkUsageMap.get(id).delete(rev3):chunkUsageMap.get(id).set(rev3,(chunkUsageMap.get(id).get(rev3)||new Set).add(chunkId));verbose2(`Tracking chunk: ${id}/${rev3} (${null==doc?void 0:doc.path}), deleted: ${deleted?"yes":"no"} Soft-Deleted:${softDeleted?"yes":"no"}`);return await Promise.resolve()},saveState=async seq=>{await kvDB.set(DB_KEY_SEQ,seq);await kvDB.set(DB_KEY_CHUNK_SET,chunkSet);await kvDB.set(DB_KEY_DOC_USAGE_MAP,chunkUsageMap)},processDocRevisions=async doc=>{var _a13;try{const oldRevisions=await db.get(doc._id,{revs:!0,revs_info:!0,conflicts:!0}),allRevs=(null==(_a13=oldRevisions._revs_info)?void 0:_a13.length)||0,info3=(oldRevisions._revs_info||[]).filter(e3=>"available"==e3.status&&e3.rev!=doc._rev).filter(info4=>{var _a14;return!(null==(_a14=chunkUsageMap.get(doc._id))?void 0:_a14.has(info4.rev))}),infoLength=info3.length;this._log(`Found ${allRevs} old revisions for ${doc._id} . ${infoLength} items to check `);if(info3.length>0){const oldDocs=await Promise.all(info3.filter(revInfo=>"available"==revInfo.status).map(revInfo=>db.get(doc._id,{rev:revInfo.rev}))).then(docs=>docs.filter(doc2=>doc2));for(const oldDoc of oldDocs)await processDoc(oldDoc,!1)}}catch(ex){if(isNotFoundError(ex))this._log(`No revisions found for ${doc._id}`,LOG_LEVEL_VERBOSE);else{this._log(`Error finding revisions for ${doc._id}`);this._verbose(ex)}}},processChange2=async(doc,isDeleted2,seq)=>{if(doc.type===EntryTypes_CHUNK){if(isDeleted2)return;chunkSet.add(doc._id)}else if("children"in doc){await processDoc(doc,isDeleted2);await serialized("x-process-doc",async()=>await processDocRevisions(doc))}};let i3=0;await db.changes({since:previousSeq||"",live:!1,conflicts:!0,include_docs:!0,style:"all_docs",return_docs:!1}).on("change",async change=>{var _a13;await processChange2(change.doc,null!=(_a13=change.deleted)&&_a13,change.seq);i3++%100==0&&await saveState(change.seq)}).on("complete",async info3=>{await saveState(info3.last_seq)});const result=await this.scanUnusedChunks(),message=`Total chunks: ${result.chunkSet.size}\nUnused chunks: ${result.unusedSet.size}`;this._log(message,logLevel)}async performGC(showingNotice=!1){var _a13;if(!await this.ensureAvailable("Garbage Collection"))return;await this.trackChanges(!1,showingNotice);const logLevel=showingNotice?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,result=await this.core.confirm.askSelectStringDialogue("This function deletes unused chunks from the device. If there are differences between devices, some chunks may be missing when resolving conflicts.\nBe sure to synchronise before executing.\n\nIf chunks used by current Vault files are deleted, Hatch -> Recreate chunks for current Vault files can recreate them only from files currently present in the Vault. It cannot recover unreadable historical or conflict content.\n\nAre you ready to delete unused chunks?",["Yes, delete chunks","Cancel"],{title:"Are all devices synchronised?",defaultAction:"Cancel"});if("Yes, delete chunks"!==result){this._log("User cancelled chunk deletion",logLevel);return}const{unusedSet,chunkSet}=await this.scanUnusedChunks(),deleteChunks=await this.database.allDocs({keys:[...unusedSet],include_docs:!0});for(const chunk of deleteChunks.rows)(null==(_a13=null==chunk?void 0:chunk.value)?void 0:_a13.deleted)&&chunkSet.delete(chunk.key);const deleteDocs=deleteChunks.rows.filter(e3=>"doc"in e3).map(e3=>({...e3.doc,_deleted:!0}));this._log(`Deleting chunks: ${deleteDocs.length}`,logLevel);const deleteChunkBatch=arrayToChunkedArray(deleteDocs,100);let successCount=0,errored=0;for(const batch of deleteChunkBatch){const results=await this.database.bulkDocs(batch);for(const result2 of results)if("ok"in result2){chunkSet.delete(result2.id);successCount++}else{this._log(`Failed to delete doc: ${result2.id}`,LOG_LEVEL_VERBOSE);errored++}this._log(`Deleting chunks: ${successCount} `,logLevel,"gc-preforming")}const message=`Garbage Collection completed.\nSuccess: ${successCount}, Errored: ${errored}`;this._log(message,logLevel);const kvDB=this.core.kvDB;await kvDB.set(DB_KEY_CHUNK_SET,chunkSet)}async analyseDatabase(){var _a13;if(!await this.ensureAvailable("Analyse Database Usage"))return;const db=this.localDatabase.localDatabase,chunkMap=new Map,docMap=new Map,info3=await db.info(),maxSeq=Number.parseInt(`${null!=(_a13=info3.update_seq)?_a13:0}`,10);let processed=0,read=0,errored=0;const ft=[],fetchRevision=async(id,rev3,seq)=>{try{processed++;const doc=await db.get(id,{rev:rev3});if(doc){if("children"in doc){const id2=doc._id,rev4=doc._rev,children=doc.children||[],set2=docMap.get(id2)||new Set;set2.add({id:id2,rev:rev4,chunks:new Set(children),uniqueChunks:new Set,sharedChunks:new Set,path:doc.path});docMap.set(id2,set2)}else if(doc.type===EntryTypes_CHUNK){const id2=doc._id;if(chunkMap.has(id2))return;if(doc._deleted)return;const length=doc.data.length,set2=chunkMap.get(id2)||new Set;set2.add({id:id2,length,refCount:0});chunkMap.set(id2,set2)}read++}else{this._log(`Analysing Database: not found: ${id} / ${rev3}`);errored++}}catch(error){this._log(`Error fetching document ${id} / ${rev3}: $`,LOG_LEVEL_NOTICE);this._log(error,LOG_LEVEL_VERBOSE);errored++}processed%100==0&&this._log(`Analysing database: ${read} (${errored}) / ${maxSeq} `,LOG_LEVEL_NOTICE,"db-analyse")},IDs=this.localDatabase.findEntryNames("","",{});for await(const id of IDs){const revList=await this.localDatabase.getRaw(id,{revs:!0,revs_info:!0,conflicts:!0}),revInfos=revList._revs_info||[];for(const revInfo of revInfos)"available"==revInfo.status&&ft.push(fetchRevision(id,revInfo.rev))}await Promise.all(ft);for(const[,docRevs]of docMap)for(const docRev of docRevs)for(const chunkId of docRev.chunks){const chunkInfos=chunkMap.get(chunkId);if(chunkInfos)for(const chunkInfo of chunkInfos){0===chunkInfo.refCount?docRev.uniqueChunks.add(chunkId):docRev.sharedChunks.add(chunkId);chunkInfo.refCount++}}const result=[],getTotalSize=ids=>[...ids].reduce((acc,chunkId)=>{const chunkInfos=chunkMap.get(chunkId);if(chunkInfos)for(const chunkInfo of chunkInfos)acc+=chunkInfo.length;return acc},0);for(const doc of docMap.values())for(const rev3 of doc){const title=`${rev3.path} (${rev3.rev})`,id=rev3.id,revStr=`${getNoFromRev(rev3.rev)}`,revHash=rev3.rev.split("-")[1].substring(0,6),path2=rev3.path,uniqueChunkCount=rev3.uniqueChunks.size,sharedChunkCount=rev3.sharedChunks.size,uniqueChunkSize=getTotalSize(rev3.uniqueChunks),sharedChunkSize=getTotalSize(rev3.sharedChunks);result.push({title,path:path2,rev:revStr,revHash,id,uniqueChunkCount,sharedChunkCount,uniqueChunkSize,sharedChunkSize})}const orphanChunks=[...chunkMap.entries()].filter(([chunkId,infos])=>{const totalRefCount=[...infos].reduce((acc,info4)=>acc+info4.refCount,0);return 0===totalRefCount}),orphanChunkSize=orphanChunks.reduce((acc,[chunkId,infos])=>{for(const info4 of infos)acc+=info4.length;return acc},0);result.push({title:"__orphan",id:"__orphan",path:"__orphan",rev:"1",revHash:"xxxxx",uniqueChunkCount:orphanChunks.length,sharedChunkCount:0,uniqueChunkSize:orphanChunkSize,sharedChunkSize:0});const csvSrc=result.map(e3=>[`${e3.title.replace(/"/g,'""')}"`,`${e3.id}`,`${e3.path}`,`${e3.rev}`,`${e3.revHash}`,`${e3.uniqueChunkCount}`,`${e3.sharedChunkCount}`,`${e3.uniqueChunkSize}`,`${e3.sharedChunkSize}`].join("\t"));csvSrc.unshift(Object.values({title:"Title",id:"Document ID",path:"Path",rev:"Revision No",revHash:"Revision Hash",uniqueChunkCount:"Unique Chunk Count",sharedChunkCount:"Shared Chunk Count",uniqueChunkSize:"Unique Chunk Size",sharedChunkSize:"Shared Chunk Size"}).join("\t"));const csv=csvSrc.join("\n");await this.services.UI.promptCopyToClipboard("Database Analysis data (TSV):",csv)}async compactDatabase(){const replicator=this.core.replicator,remote=await replicator.connectRemoteCouchDBWithSetting(this.settings,!1,!1,!0);if(remote)if("string"!=typeof remote)try{const compactResult=await remote.db.compact({interval:1e3});let timeout=12e4;for(;;){const status=await remote.db.info();if(!("compact_running"in status)||!(null==status?void 0:status.compact_running))break;this._notice("Compaction in progress on remote database...","gc-compact");await delay(2e3);timeout-=2e3;if(timeout<=0){this._notice("Compaction on remote database timed out.","gc-compact");return}}compactResult&&"ok"in compactResult?this._notice("Compaction on remote database completed successfully.","gc-compact"):this._notice("Compaction on remote database failed.","gc-compact")}finally{await remote.db.close()}else this._notice(`Failed to connect to remote for compaction. ${remote}`,"gc-compact");else this._notice("Failed to connect to remote for compaction.","gc-compact")}async gcv3(){if(!await this.ensureAvailable("Garbage Collection"))return;const replicator=this.core.replicator,r0=await replicator.openOneShotReplication(this.settings,!1,!1,"sync");if(!r0){this._notice("Failed to start one-shot replication before Garbage Collection. Garbage Collection Cancelled.");return}const OPTION_CANCEL="Cancel Garbage Collection",info3=await this.core.replicator.getConnectedDeviceList();if(!info3){this._notice("No connected device information found. Cancelling Garbage Collection.");return}const{accepted_nodes,node_info}=info3,infoMissingNodes=[];for(const node of accepted_nodes)node in node_info||infoMissingNodes.push(node);if(infoMissingNodes.length>0){const message2=`The following accepted nodes are missing its node information:\n- ${infoMissingNodes.join("\n- ")}\n\nThis indicates that they have not been connected for some time or have been left on an older version.\nIt is preferable to update all devices if possible. If you have any devices that are no longer in use, you can clear all accepted nodes by locking the remote once.`,OPTION_IGNORE="Ignore and Proceed",buttons2=[OPTION_CANCEL,OPTION_IGNORE],result2=await this.core.confirm.askSelectStringDialogue(message2,buttons2,{title:"Node Information Missing",defaultAction:OPTION_CANCEL});if(result2===OPTION_CANCEL){this._notice("Garbage Collection cancelled by user.");return}result2===OPTION_IGNORE&&this._notice("Proceeding with Garbage Collection, ignoring missing nodes.")}const progressValues=Object.values(node_info).map(entry=>{const progress="string"==typeof entry.progress?entry.progress.split("-")[0]:"";return/^\d+$/u.test(progress)?Number(progress):Number.NaN});if(0===progressValues.length||progressValues.some(progress=>!Number.isSafeInteger(progress))){this._notice("No connected device information found. Cancelling Garbage Collection.");return}const maxProgress=Math.max(...progressValues),minProgress=Math.min(...progressValues),progressDifference=maxProgress-minProgress,detail=`> [!INFO]- The connected devices have been detected as follows:\n${Object.entries(node_info).map(([nodeId,nodeData])=>`> - Device: ${nodeData.device_name} (Node ID: ${nodeId})\n> - Obsidian version: ${nodeData.app_version}\n> - Plug-in version: ${nodeData.plugin_version}\n> - Progress: ${nodeData.progress.split("-")[0]}`).join("\n")}\n`,message=0!=progressDifference?`Some devices have differing progress values (max: ${maxProgress}, min: ${minProgress}).\nThis may indicate that some devices have not completed synchronisation, which could lead to conflicts. Strongly recommend confirming that all devices are synchronised before proceeding.`:`All devices have the same progress value (${maxProgress}). Your devices seem to be synchronised. And be able to proceed with Garbage Collection.`,buttons=["Proceed Garbage Collection",OPTION_CANCEL],defaultAction=0!=progressDifference?OPTION_CANCEL:"Proceed Garbage Collection",result=await this.core.confirm.askSelectStringDialogue(message+"\n\n"+detail,buttons,{title:"Garbage Collection Confirmation",defaultAction});if("Proceed Garbage Collection"!==result){this._notice("Garbage Collection cancelled by user.");return}this._notice("Proceeding with Garbage Collection.");const gcStartTime=Date.now(),localDatabase=this.localDatabase.localDatabase,{used:usedChunks,existing:allChunks}=await this.localDatabase.allChunks();this._notice(`Garbage Collection: Scanning completed. Total chunks: ${allChunks.size}, Used chunks: ${usedChunks.size}`,"gc-scanning");const unusedChunks=[...allChunks.entries()].filter(([chunkId])=>!usedChunks.has(chunkId));this._notice(`Garbage Collection: Found ${unusedChunks.length} unused chunks to delete.`,"gc-scanning");const deleteChunkDocs=unusedChunks.map(([chunkId,chunk])=>({_id:chunkId,_deleted:!0,_rev:chunk._rev})),response=await localDatabase.bulkDocs(deleteChunkDocs),deletedCount=response.filter(e3=>"ok"in e3).length,gcEndTime=Date.now();this._notice(`Garbage Collection completed. Deleted chunks: ${deletedCount} / ${unusedChunks.length}. Time taken: ${(gcEndTime-gcStartTime)/1e3} seconds.`);const r4=await replicator.openOneShotReplication(this.settings,!1,!1,"pushOnly");if(r4){await this.compactDatabase();this.clearHash()}else this._notice("Failed to start replication after Garbage Collection.")}};ControlService=class extends ServiceBase{constructor(context2,dependencies){super(context2);__publicField(this,"services");__publicField(this,"_log");__publicField(this,"_unloaded",!1);__publicField(this,"_activated");this.services=dependencies;this._log=createInstanceLogFunction("ControlService",this.services.APIService);this._activated=promiseWithResolvers();this.services.appLifecycleService.onLoaded.addHandler(()=>{this.onActivated();return Promise.resolve(!0)})}hasUnloaded(){return this._unloaded}get activated(){return this._activated.promise}onActivated(){this._activated.resolve(!0)}async applySettings(){await this.services.appLifecycleService.onSuspending();await this.services.settingService.onBeforeRealiseSetting();this.services.databaseService.localDatabase.refreshSettings();await this.services.fileProcessingService.commitPendingFileEvents();await this.services.settingService.onRealiseSetting();if(!this.services.appLifecycleService.isSuspended()){await this.services.appLifecycleService.onResuming();await this.services.appLifecycleService.onResumed();await this.services.settingService.onSettingRealised()}}async _onLiveSyncUnload(){this.context.events.emitEvent(EVENT_PLUGIN_UNLOADED);await this.services.appLifecycleService.onBeforeUnload();await Promise.resolve(this.services.appLifecycleService.onAppUnload());cancelAllPeriodicTask();cancelAllTasks();stopAllRunningProcessors();await this.services.appLifecycleService.onUnload();this._unloaded=!0;const localDatabase=this.services.databaseService.localDatabaseDirect;if(null!=localDatabase){const activeReplicator=this.services.replicatorService.getActiveReplicator();activeReplicator&&activeReplicator.closeReplication();localDatabase.onunload();await localDatabase.close()}this.context.events.emitEvent(EVENT_PLATFORM_UNLOADED);this.context.events.offAll();this._log(this.context.translate("moduleLiveSyncMain.logUnloadingPlugin"))}async onLoad(){if(!await this.services.appLifecycleService.onLoad()){this._log("Self-hosted LiveSync cannot be initialised, exiting loading.",LOG_LEVEL_URGENT);return!1}return!0}async onReady(){return await this.services.appLifecycleService.onReady()}async onUnload(){return await this._onLiveSyncUnload()}};PathService=class extends ServiceBase{constructor(context2,dependencies){super(context2);__publicField(this,"settingService");__publicField(this,"getPathObfuscationPassphrase");this.settingService=dependencies.settingService;this.getPathObfuscationPassphrase=dependencies.getPathObfuscationPassphrase}get settings(){return this.settingService.currentSettings()}_id2path(id,entry){const filename=id2path_base(id,entry),temp=filename.split(":"),path2=temp.pop(),normalizedPath=this.normalizePath(path2);temp.push(normalizedPath);const fixedPath=temp.join(":");return fixedPath}async _path2id(filename,obfuscatePassphrase,caseInsensitive){const temp=filename.split(":"),path2=temp.pop(),normalizedPath=this.normalizePath(path2);temp.push(normalizedPath);const fixedPath=temp.join(":"),out=await path2id_base(fixedPath,obfuscatePassphrase,caseInsensitive);return out}id2path(id,entry,stripPrefix2){const tempId=this._id2path(id,entry);if(stripPrefix2&&isInternalMetadata(tempId)){const out=stripInternalMetadataPrefix(tempId);return out}return tempId}async path2id(filename,prefix){var _a13,_b6;const destPath=addPrefix(filename,null!=prefix?prefix:""),setting=this.settings,pathObfuscationPassphrase=null!=(_b6=null==(_a13=this.getPathObfuscationPassphrase)?void 0:_a13.call(this))?_b6:!!setting.usePathObfuscation&&setting.passphrase;return await this._path2id(destPath,pathObfuscationPassphrase,!setting.handleFilenameCaseSensitive)}getPath(entry){return this.id2path(entry._id,entry)}};ServiceHub=class{constructor(context2,services={}){__publicField(this,"context");__publicField(this,"_injected",{});this.context=context2;this._injected=services}get API(){return this._injected.API||this._api}get path(){return this._injected.path||this._path}get database(){return this._injected.database||this._database}get databaseEvents(){return this._injected.databaseEvents||this._databaseEvents}get replicator(){return this._injected.replicator||this._replicator}get fileProcessing(){return this._injected.fileProcessing||this._fileProcessing}get replication(){return this._injected.replication||this._replication}get remote(){return this._injected.remote||this._remote}get conflict(){return this._injected.conflict||this._conflict}get appLifecycle(){return this._injected.appLifecycle||this._appLifecycle}get setting(){return this._injected.setting||this._setting}get tweakValue(){return this._injected.tweakValue||this._tweakValue}get vault(){return this._injected.vault||this._vault}get test(){return this._injected.test||this._test}get UI(){return this._injected.ui||this._ui}get config(){return this._injected.config||this._config}get keyValueDB(){return this._injected.keyValueDB||this._keyValueDB}get control(){return this._injected.control||this._control}};APIService=class extends ServiceBase{constructor(){super(...arguments);__publicField(this,"requestCount",reactiveSource(0));__publicField(this,"responseCount",reactiveSource(0))}showWindowOnRight(type){return this.showWindow(type)}get isOnline(){return!("navigator"in compatGlobal)||compatGlobal.navigator.onLine}webCompatFetch(req,opts){return _fetch(req,opts)}nativeFetch(req,opts){throw new Error("nativeFetch is not implemented for this platform")}setInterval(handler,timeout){return compatGlobal.setInterval(handler,timeout)}clearInterval(timerId){compatGlobal.clearInterval(timerId)}getSystemConfigDir(){return".livesync"}};Binder=class{constructor(name,initialCallback){__publicField(this,"_name");__publicField(this,"_callback",null);this._name=name;initialCallback&&(this._callback=initialCallback)}assign(callback,override=!1){if(this._callback&&!override)throw new Error(`Handler ${this._name} is already assigned.`);this._callback=callback;return()=>{this._callback=null}}invoke(...args){if(this._callback)return this._callback(...args);throw new Error(`Handler ${this._name} is not assigned.`)}};LazyBinder=class{constructor(name,initialCallback){__publicField(this,"_name");__publicField(this,"_callbackPromise",promiseWithResolvers());__publicField(this,"_callback",null);this._name=name;if(initialCallback){this._callback=initialCallback;this._callbackPromise.resolve()}}assign(callback,override=!1){if(this._callback&&!override)throw new Error(`Handler ${this._name} is already assigned.`);this._callback=callback;this._callbackPromise.resolve();return()=>{this._callback=null;this._callbackPromise=promiseWithResolvers()}}async invoke(...args){await this._callbackPromise.promise;if(this._callback)return await this._callback(...args);throw new Error(`Handler ${this._name} is not assigned.`)}};MultiBinder=class{constructor(name){__publicField(this,"_name");__publicField(this,"_callbackMap",new Map);__publicField(this,"_isCallbackDirty",!1);__publicField(this,"_maxUsedPriority",0);__publicField(this,"_sortedCallbacks",[]);this._name=name}addHandler(callback,priority=0,allowSwap=!1){this._callbackMap.set(callback,[priority,this._maxUsedPriority++]);this._isCallbackDirty=!0;return()=>{this.removeHandler(callback);this._isCallbackDirty=!0}}removeHandler(callback){this._callbackMap.delete(callback);this._isCallbackDirty=!0}use(callback,priority=0){return this.addHandler(callback,priority)}get _callbacks(){if(this._isCallbackDirty){this._sortedCallbacks=Array.from(this._callbackMap.entries()).sort((a2,b3)=>{const[priorityA,registerOrderA]=a2[1],[priorityB,registerOrderB]=b3[1];return priorityA!==priorityB?priorityA-priorityB:registerOrderA-registerOrderB}).map(entry=>entry[0]);this._isCallbackDirty=!1}return this._sortedCallbacks}};0;DispatchParallel=class extends MultiBinder{dispatch(...args){const callbacks=[...this._callbacks],promises=callbacks.map(async callback=>{try{const result=await Promise.resolve(callback(...args));return result}catch(error){const err3=error instanceof Error?error:new Error(String(error));return err3}}),results=Promise.all(promises);return results}};BooleanHandlerBase=class extends MultiBinder{};AllHandler=class extends BooleanHandlerBase{async invoke(...args){const _callbacks=[...this._callbacks];for(const callback of _callbacks)try{const result=await Promise.resolve(callback(...args));if(!1===result)return!1}catch(error){Logger(`AllHandler ${this._name} treated error as failure!`,LOG_LEVEL_VERBOSE);Logger(error,LOG_LEVEL_VERBOSE);return!1}return!0}};ParallelAllHandler=class extends BooleanHandlerBase{async invoke(...args){const callbacks=[...this._callbacks],promises=callbacks.map(async callback=>{try{const result=await Promise.resolve(callback(...args));return result}catch(error){Logger(`ParallelAllHandler ${this._name} treated error as failure!`,LOG_LEVEL_VERBOSE);Logger(error,LOG_LEVEL_VERBOSE);return!1}}),results=await Promise.all(promises);return results.every(res2=>!0===res2)}};AnySuccessHandler=class extends BooleanHandlerBase{async invoke(...args){const _callbacks=[...this._callbacks];for(const callback of _callbacks)try{const result=await Promise.resolve(callback(...args));if(!0===result)return!0}catch(error){Logger(`FirstSuccessHandler ${this._name} ignored error!`,LOG_LEVEL_VERBOSE);Logger(error,LOG_LEVEL_VERBOSE)}return!1}};FirstResultHandler=class extends MultiBinder{async invoke(...args){const _callbacks=[...this._callbacks];for(const callback of _callbacks)try{const result=await Promise.resolve(callback(...args));if(void 0!==result&&!1!==result)return result}catch(error){Logger(`FirstResultHandler ${this._name} ignored error!`,LOG_LEVEL_VERBOSE);Logger(error,LOG_LEVEL_VERBOSE)}return!1}};InjectableAPIService=class extends APIService{constructor(){super(...arguments);__publicField(this,"addLog",handlers2().binder("addLog"))}getPlatform(){return"unknown"}getCrypto(){if("undefined"!=typeof crypto)return crypto;throw new Error("Crypto API is not available in this environment.")}};AppLifecycleService=class extends ServiceBase{constructor(context2,dependencies){super(context2);__publicField(this,"settingService");__publicField(this,"onLayoutReady",handlers2().bailFirstFailure("onLayoutReady"));__publicField(this,"onFirstInitialise",handlers2().bailFirstFailure("onFirstInitialise"));__publicField(this,"onReady",handlers2().bailFirstFailure("onReady"));__publicField(this,"onWireUpEvents",handlers2().bailFirstFailure("onWireUpEvents"));__publicField(this,"onInitialise",handlers2().bailFirstFailure("onInitialise"));__publicField(this,"onLoad",handlers2().bailFirstFailure("onLoad"));__publicField(this,"onSettingLoaded",handlers2().bailFirstFailure("onSettingLoaded"));__publicField(this,"onLoaded",handlers2().bailFirstFailure("onLoaded"));__publicField(this,"onScanningStartupIssues",handlers2().all("onScanningStartupIssues"));__publicField(this,"onAppUnload",handlers2().dispatchParallel("onAppUnload"));__publicField(this,"onBeforeUnload",handlers2().all("onBeforeUnload"));__publicField(this,"onUnload",handlers2().all("onUnload"));__publicField(this,"onSuspending",handlers2().bailFirstFailure("onSuspending"));__publicField(this,"onResuming",handlers2().bailFirstFailure("onResuming"));__publicField(this,"onResumed",handlers2().bailFirstFailure("onResumed"));__publicField(this,"_isSuspended",!1);__publicField(this,"_isReady",!1);__publicField(this,"getUnresolvedMessages",handlers2().dispatchParallel("getUnresolvedMessages"));this.settingService=dependencies.settingService}isSuspended(){const settings=this.settingService.currentSettings();return this._isSuspended||!(null==settings?void 0:settings.isConfigured)}setSuspended(suspend){this._isSuspended=suspend}isReady(){return this._isReady}markIsReady(){this._isReady=!0}resetIsReady(){this._isReady=!1}};AppLifecycleServiceBase=class extends AppLifecycleService{constructor(){super(...arguments);__publicField(this,"askRestart",handlers2().binder("askRestart"));__publicField(this,"scheduleRestart",handlers2().binder("scheduleRestart"));__publicField(this,"isReloadingScheduled",handlers2().binder("isReloadingScheduled"))}};0;ConflictService=class extends ServiceBase{constructor(){super(...arguments);__publicField(this,"getOptionalConflictCheckMethod",handlers2().firstResult("getOptionalConflictCheckMethod"));__publicField(this,"resolveByUserInteraction",handlers2().firstResult("resolveByUserInteraction"));__publicField(this,"conflictProcessQueueCount",reactiveSource(0))}};InjectableConflictService=class extends ConflictService{constructor(){super(...arguments);__publicField(this,"queueCheckForIfOpen",handlers2().binder("queueCheckForIfOpen"));__publicField(this,"queueCheckFor",handlers2().binder("queueCheckFor"));__publicField(this,"ensureAllProcessed",handlers2().binder("ensureAllProcessed"));__publicField(this,"resolveByDeletingRevision",handlers2().binder("resolveByDeletingRevision"));__publicField(this,"resolve",handlers2().binder("resolve"));__publicField(this,"resolveByNewest",handlers2().binder("resolveByNewest"));__publicField(this,"resolveAllConflictedFilesByNewerOnes",handlers2().binder("resolveAllConflictedFilesByNewerOnes"))}};DatabaseEventService=class extends ServiceBase{constructor(){super(...arguments);__publicField(this,"onUnloadDatabase",handlers2().all("onUnloadDatabase"));__publicField(this,"onCloseDatabase",handlers2().all("onCloseDatabase"));__publicField(this,"onDatabaseInitialisation",handlers2().bailFirstFailure("onDatabaseInitialisation"));__publicField(this,"onDatabaseInitialised",handlers2().bailFirstFailure("onDatabaseInitialised"));__publicField(this,"onResetDatabase",handlers2().bailFirstFailure("onResetDatabase"));__publicField(this,"onDatabaseHasReady",handlers2().bailFirstFailure("onDatabaseHasReady"));__publicField(this,"initialiseDatabase",handlers2().bailFirstFailure("initialiseDatabase"))}};InjectableDatabaseEventService=class extends DatabaseEventService{};FileProcessingService=class extends ServiceBase{constructor(){super(...arguments);__publicField(this,"processFileEvent",handlers2().anySuccess("processFileEvent"));__publicField(this,"processOptionalFileEvent",handlers2().anySuccess("processOptionalFileEvent"));__publicField(this,"commitPendingFileEvents",handlers2().bailFirstFailure("commitPendingFileEvents"));__publicField(this,"batched",reactiveSource(0));__publicField(this,"totalQueued",reactiveSource(0));__publicField(this,"processing",reactiveSource(0));__publicField(this,"totalStorageFileEventCount",0)}onStorageFileEvent(){this.totalStorageFileEventCount++}};InjectableFileProcessingService=class extends FileProcessingService{};REPLICATION_ON_EVENT_FORECASTED_TIME=5e3;ReplicationService=class extends ServiceBase{constructor(context2,dependencies){super(context2);__publicField(this,"_unresolvedErrorManager");__publicField(this,"_log");__publicField(this,"settingService");__publicField(this,"appLifecycleService");__publicField(this,"replicatorService");__publicField(this,"APIService");__publicField(this,"fileProcessing");__publicField(this,"databaseService");__publicField(this,"processSynchroniseResult",handlers2().anySuccess("processSynchroniseResult"));__publicField(this,"processOptionalSynchroniseResult",handlers2().anySuccess("processOptionalSynchroniseResult"));__publicField(this,"parseSynchroniseResult",handlers2().all("parseSynchroniseResult"));__publicField(this,"processVirtualDocument",handlers2().anySuccess("processVirtualDocument"));__publicField(this,"onBeforeReplicate",handlers2().bailFirstFailure("onBeforeReplicate"));__publicField(this,"onCheckReplicationReady",handlers2().bailFirstFailure("onCheckReplicationReady"));__publicField(this,"onReplicationFailed",handlers2().bailFirstFailure("onReplicationFailed"));__publicField(this,"previousReplicated",0);__publicField(this,"checkConnectionFailure",handlers2().firstResult("checkConnectionFailure"));__publicField(this,"databaseQueueCount",reactiveSource(0));__publicField(this,"storageApplyingCount",reactiveSource(0));__publicField(this,"replicationResultCount",reactiveSource(0));this.appLifecycleService=dependencies.appLifecycleService;this.settingService=dependencies.settingService;this.replicatorService=dependencies.replicatorService;this.APIService=dependencies.APIService;this.fileProcessing=dependencies.fileProcessingService;this.databaseService=dependencies.databaseService;this._log=createInstanceLogFunction("ReplicationService",dependencies.APIService);this._unresolvedErrorManager=new UnresolvedErrorManager(dependencies.appLifecycleService,this.context.events)}showError(msg,max_log_level=LOG_LEVEL_NOTICE){this._unresolvedErrorManager.showError(msg,max_log_level)}clearErrors(){this._unresolvedErrorManager.clearErrors()}async isReplicationReady(showMessage2=!1){if(!this.appLifecycleService.isReady()){this._log("Not ready");return!1}if(!await this.onCheckReplicationReady(showMessage2))return!1;const currentSettings=this.settingService.currentSettings();if(isLockAcquired("cleanup")){this._log(this.context.translate("Replicator.Message.Cleaned"),LOG_LEVEL_NOTICE);return!1}if(""!=currentSettings.versionUpFlash){this._log(this.context.translate("Replicator.Message.VersionUpFlash"),LOG_LEVEL_NOTICE);return!1}if(!await this.fileProcessing.commitPendingFileEvents()){this.showError(this.context.translate("Replicator.Message.Pending"),LOG_LEVEL_NOTICE);return!1}if(!this.APIService.isOnline){this.showError("Network is offline",showMessage2?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO);return!1}if(!await this.onBeforeReplicate(showMessage2)){const hasNetworkError=(await this.appLifecycleService.getUnresolvedMessages()).flat().some(e3=>"string"==typeof e3&&-1!==e3.indexOf(MARK_LOG_NETWORK_ERROR));hasNetworkError?this._log(this.context.translate("Replicator.Message.SomeModuleFailed"),LOG_LEVEL_INFO):this.showError(this.context.translate("Replicator.Message.SomeModuleFailed"),LOG_LEVEL_NOTICE);return!1}this.clearErrors();return!0}async performReplicationRequest(showMessage2){const activeReplicator=this.replicatorService.getActiveReplicator();if(!activeReplicator){this._log("No active replicator found",showMessage2?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO);return!1}const settings=this.settingService.currentSettings();return await activeReplicator.openReplication(settings,!1,!!showMessage2,!1)}async performReplication(showMessage2){const result=await this.performReplicationRequest(showMessage2);return result||await this.onReplicationFailed(showMessage2)}async replicate(showMessage2){try{const checkBeforeReplicate=await this.isReplicationReady(showMessage2);if(!checkBeforeReplicate)return!1;const result=await this.replicatorService.runFiniteReplicationActivity(()=>this.performReplicationRequest(showMessage2),{label:"replication"});return result||await this.onReplicationFailed(showMessage2)}finally{this.previousReplicated=Date.now()}}replicateByEvent(showMessage2){return shareRunningResult("replication",async()=>{const currentSettings=this.settingService.currentSettings(),least=currentSettings.syncMinimumInterval;if(least>0){const now3=Date.now(),elapsed=now3-this.previousReplicated;if(elapsed<least){this._log(`Replication triggered by event is rate limited. Elapsed: ${elapsed}ms, Least interval: ${least}ms`,LOG_LEVEL_VERBOSE);return Promise.resolve(!0)}this.previousReplicated=now3+REPLICATION_ON_EVENT_FORECASTED_TIME;return await this.replicate()}return this.replicate()})}getActiveReplicatorFor(usage){const activeReplicator=this.replicatorService.getActiveReplicator();if(!activeReplicator){this._log(`Active replicator not found during ${usage}`,LOG_LEVEL_NOTICE);return!1}return activeReplicator}async performReplicateAllToRemote(showingNotice){if(!await this.onBeforeReplicate(showingNotice)){this._log(this.context.translate("Replicator.Message.SomeModuleFailed"),LOG_LEVEL_NOTICE);return!1}const currentSettings=this.settingService.currentSettings(),activeReplicator=this.getActiveReplicatorFor("sending data to remote");if(!activeReplicator)return!1;const ret=await activeReplicator.replicateAllToServer(currentSettings,showingNotice);if(ret)return!0;const checkResult=await this.checkConnectionFailure();return"CHECKAGAIN"==checkResult?await activeReplicator.replicateAllToServer(currentSettings,showingNotice):!checkResult}async performReplicateAllFromRemote(showingNotice){const activeReplicator=this.getActiveReplicatorFor("fetching data from remote");if(!activeReplicator)return!1;const currentSettings=this.settingService.currentSettings(),ret=await activeReplicator.replicateAllFromServer(currentSettings,showingNotice);if(ret)return!0;const checkResult=await this.checkConnectionFailure();return"CHECKAGAIN"==checkResult?await activeReplicator.replicateAllFromServer(currentSettings,showingNotice):!checkResult}async replicateAllToRemote(showingNotice=!1){return!!this.appLifecycleService.isReady()&&await this.performReplicateAllToRemote(showingNotice)}async replicateAllFromRemote(showingNotice=!1){return!!this.appLifecycleService.isReady()&&await this.performReplicateAllFromRemote(showingNotice)}async replicateAllToRemoteForRebuild(showingNotice=!1){if(!this.databaseService.isDatabaseReady()){this._log("The selected local database is not ready for the rebuild upload.",LOG_LEVEL_NOTICE);return!1}return await this.performReplicateAllToRemote(showingNotice)}async replicateAllFromRemoteForRebuild(showingNotice=!1){if(!this.databaseService.isDatabaseReady()){this._log("The selected local database is not ready for the rebuild download.",LOG_LEVEL_NOTICE);return!1}return await this.performReplicateAllFromRemote(showingNotice)}_getReplicatorAndPerform(action2,perform){const activeReplicator=this.getActiveReplicatorFor(action2);if(!activeReplicator)return Promise.resolve();const currentSettings=this.settingService.currentSettings();return perform(currentSettings,activeReplicator)}async markLocked(lockByClean=!1){return await this._getReplicatorAndPerform("marking remote locked",async(currentSettings,activeReplicator)=>await activeReplicator.markRemoteLocked(currentSettings,!0,lockByClean))}async markUnlocked(){return await this._getReplicatorAndPerform("marking remote unlocked",async(currentSettings,activeReplicator)=>await activeReplicator.markRemoteLocked(currentSettings,!1,!1))}async markResolved(){return await this._getReplicatorAndPerform("marking remote resolved",async(currentSettings,activeReplicator)=>await activeReplicator.markRemoteResolved(currentSettings))}};InjectableReplicationService=class extends ReplicationService{};ReplicatorService=class extends ServiceBase{constructor(context2,dependencies){var _a13;super(context2);__publicField(this,"dependencies");__publicField(this,"boundedRemoteActivityCount",reactiveSource(0));__publicField(this,"finiteReplicationActivityCount",reactiveSource(0));__publicField(this,"_log",createInstanceLogFunction("ReplicatorService"));__publicField(this,"settingService");__publicField(this,"databaseEventService");__publicField(this,"_activeReplicator");__publicField(this,"_replicatorType");__publicField(this,"appLifecycleService");__publicField(this,"_unresolvedErrorManager");__publicField(this,"onCloseActiveReplication",handlers2().anySuccess("onCloseActiveReplication"));__publicField(this,"getNewReplicator",handlers2().firstResult("getNewReplicator"));__publicField(this,"onReplicatorInitialised",handlers2().bailFirstFailure("onReplicatorInitialised"));__publicField(this,"replicationStatics",reactiveSource({...DEFAULT_REPLICATION_STATICS}));this.dependencies=dependencies;this.appLifecycleService=dependencies.appLifecycleService;this._unresolvedErrorManager=new UnresolvedErrorManager(dependencies.appLifecycleService,this.context.events);this.settingService=dependencies.settingService;this.databaseEventService=dependencies.databaseEventService;if(null==(_a13=dependencies.registerLifecycleHandlers)||_a13){this.settingService.onRealiseSetting.addHandler(this._initialiseReplicator.bind(this));this.databaseEventService.onResetDatabase.addHandler(this.disposeReplicator.bind(this));this.databaseEventService.onDatabaseInitialisation.addHandler(this.disposeReplicator.bind(this));this.databaseEventService.onDatabaseInitialised.addHandler(this.reinitialiseReplicator.bind(this));this.databaseEventService.onDatabaseHasReady.addHandler(this.reinitialiseReplicator.bind(this));this.appLifecycleService.onSuspending.addHandler(this.suspendReplication.bind(this))}}async runBoundedRemoteActivity(task,options){return await this.runRemoteActivity(task,options,!1)}async runFiniteReplicationActivity(task,options){return await this.runRemoteActivity(task,options,!0)}async runRemoteActivity(task,options,isFiniteReplication){this.boundedRemoteActivityCount.value++;isFiniteReplication&&this.finiteReplicationActivityCount.value++;try{return await runWithOptionalActivity(this.dependencies.activityRunner,task,options)}finally{isFiniteReplication&&this.finiteReplicationActivityCount.value--;this.boundedRemoteActivityCount.value--}}suspendReplication(){const activeReplicator=this._activeReplicator;activeReplicator&&activeReplicator.closeReplication();return Promise.resolve(!0)}async reinitialiseReplicator(){await this.disposeReplicator();await yieldMicrotask();return this._initialiseReplicator()}async disposeReplicator(){this._log("Detect database reset, closing active replicator if exists.");this._activeReplicator&&await Promise.resolve(this._activeReplicator.closeReplication());this._activeReplicator=void 0;this._replicatorType=void 0;return!0}async discardFailedReplicator(replicator){if(this._activeReplicator===replicator){this._activeReplicator=void 0;this._replicatorType=void 0}try{await Promise.resolve(replicator.closeReplication())}catch(error){this._log("Failed to close a replicator after its initialisation failed.",LOG_LEVEL_VERBOSE);this._log(error,LOG_LEVEL_VERBOSE)}}async _initialiseReplicator(){var _a13,_b6,_c3,_d2;const message=this.context.translate("Replicator.Message.InitialiseFatalError"),setting=this.settingService.currentSettings();if(!setting){this._activeReplicator=void 0;this._replicatorType=void 0;this._unresolvedErrorManager.clearError(message);return!0}const replicatorType=setting.remoteType,isCouchDBConfigured=replicatorType===RemoteTypes_REMOTE_COUCHDB&&!!(null==(_a13=setting.couchDB_URI)?void 0:_a13.trim())&&!!(null==(_b6=setting.couchDB_DBNAME)?void 0:_b6.trim()),isMinioConfigured=replicatorType===RemoteTypes_REMOTE_MINIO&&!!(null==(_c3=setting.endpoint)?void 0:_c3.trim())&&!!(null==(_d2=setting.bucket)?void 0:_d2.trim()),isP2PEnabled=replicatorType===RemoteTypes_REMOTE_P2P&&setting.P2P_Enabled,hasReplicatorConfig=isCouchDBConfigured||isMinioConfigured||isP2PEnabled;if(!hasReplicatorConfig){this._activeReplicator=void 0;this._replicatorType=void 0;this._unresolvedErrorManager.clearError(message);this._log("No remote replicator configuration found. Skipping replicator initialisation.");return!0}if(replicatorType===this._replicatorType&&this._activeReplicator){this._unresolvedErrorManager.clearError(message);this._log("Active replicator has been kept",LOG_LEVEL_VERBOSE);return!0}{this._log("Acquiring new replicator");const newReplicator=await this.getNewReplicator();if(!newReplicator){this._unresolvedErrorManager.showError(message,LOG_LEVEL_NOTICE);return!1}if(this._activeReplicator){await Promise.resolve(this._activeReplicator.closeReplication());this._log("Active replicator closed",LOG_LEVEL_VERBOSE)}this._activeReplicator=newReplicator;this._replicatorType=replicatorType;this.replicationStatics.value={...DEFAULT_REPLICATION_STATICS};await yieldMicrotask();try{if(!await newReplicator.initializeDatabaseForReplication()){this._log("Failed to initialise the replicator's local node information.");await this.discardFailedReplicator(newReplicator);this._unresolvedErrorManager.showError(message,LOG_LEVEL_NOTICE);return!1}if(!await this.onReplicatorInitialised()){this._log("Failed to initialise the replicator, onReplicatorInitialised reported some problems.");await this.discardFailedReplicator(newReplicator);this._unresolvedErrorManager.showError(message,LOG_LEVEL_NOTICE);return!1}}catch(error){await this.discardFailedReplicator(newReplicator);this._unresolvedErrorManager.showError(message,LOG_LEVEL_NOTICE);throw error}const remoteTypeDisplay=replicatorType===RemoteTypes_REMOTE_COUCHDB?"CouchDB":replicatorType;this._log(`Replicator (${remoteTypeDisplay}) initialised and activated`,LOG_LEVEL_VERBOSE);this._unresolvedErrorManager.clearError(message);return!0}}getActiveReplicator(){const message="No replicator has been activated or has not been initialised yet.";if(this._activeReplicator){this._unresolvedErrorManager.clearError(message);return this._activeReplicator}this._unresolvedErrorManager.showError(message,LOG_LEVEL_NOTICE)}};InjectableReplicatorService=class extends ReplicatorService{};TestService=class extends ServiceBase{constructor(){super(...arguments);__publicField(this,"test",handlers2().bailFirstFailure("test"));__publicField(this,"testMultiDevice",handlers2().bailFirstFailure("testMultiDevice"))}};InjectableTestService=class extends TestService{constructor(){super(...arguments);__publicField(this,"addTestResult",handlers2().binder("addTestResult"))}};TweakValueService=class extends ServiceBase{};InjectableTweakValueService=class extends TweakValueService{constructor(){super(...arguments);__publicField(this,"fetchRemotePreferred",handlers2().binder("fetchRemotePreferred"));__publicField(this,"checkAndAskResolvingMismatched",handlers2().binder("checkAndAskResolvingMismatched"));__publicField(this,"askResolvingMismatched",handlers2().binder("askResolvingMismatched"));__publicField(this,"checkAndAskUseRemoteConfiguration",handlers2().binder("checkAndAskUseRemoteConfiguration"));__publicField(this,"askUseRemoteConfiguration",handlers2().binder("askUseRemoteConfiguration"))}};VaultService=class extends ServiceBase{constructor(context2,dependencies){super(context2);__publicField(this,"settingService");__publicField(this,"APIService");__publicField(this,"scanVault",handlers2().bailFirstFailure("scanVault"));__publicField(this,"isIgnoredByIgnoreFile",handlers2().anySuccess("isIgnoredByIgnoreFile"));__publicField(this,"isTargetFile",handlers2().bailFirstFailure("isTargetFile"));__publicField(this,"isTargetFileInExtra",handlers2().anySuccess("isTargetFileInExtra"));this.settingService=dependencies.settingService;this.APIService=dependencies.APIService}get settings(){return this.settingService.currentSettings()}vaultName(){return this.APIService.getSystemVaultName()}getVaultName(){return this.vaultName()+(this.settings.additionalSuffixOfDatabaseName?"-"+this.settings.additionalSuffixOfDatabaseName:"")}isFileSizeTooLarge(size){const maxSize=this.settings.syncMaxSizeInMB;return maxSize>0&&size>0&&1024*maxSize*1024<size}shouldCheckCaseInsensitively(){return!this.settings.handleFilenameCaseSensitive}};InjectableVaultService=class extends VaultService{};0;InjectableServiceHub=class extends ServiceHub{constructor(context2,services){var _a13,_b6,_c3,_d2,_e2,_f,_g;super(context2,services);__publicField(this,"_api");__publicField(this,"_path");__publicField(this,"_database");__publicField(this,"_databaseEvents");__publicField(this,"_replicator");__publicField(this,"_fileProcessing");__publicField(this,"_replication");__publicField(this,"_remote");__publicField(this,"_conflict");__publicField(this,"_appLifecycle");__publicField(this,"_setting");__publicField(this,"_tweakValue");__publicField(this,"_vault");__publicField(this,"_test");__publicField(this,"_ui");__publicField(this,"_config");__publicField(this,"_keyValueDB");__publicField(this,"_control");this._api=services.API;this._path=services.path;this._database=services.database;this._databaseEvents=null!=(_a13=services.databaseEvents)?_a13:new InjectableDatabaseEventService(context2);this._replicator=services.replicator;this._fileProcessing=null!=(_b6=services.fileProcessing)?_b6:new InjectableFileProcessingService(context2);this._conflict=null!=(_c3=services.conflict)?_c3:new InjectableConflictService(context2);this._appLifecycle=services.appLifecycle;this._setting=services.setting;this._remote=services.remote;this._tweakValue=null!=(_d2=services.tweakValue)?_d2:new InjectableTweakValueService(context2);this._replication=null!=(_e2=services.replication)?_e2:new InjectableReplicationService(context2,{APIService:this._api,appLifecycleService:this._appLifecycle,replicatorService:this._replicator,settingService:this._setting,databaseService:this._database,fileProcessingService:this._fileProcessing});this._vault=services.vault;this._test=null!=(_f=services.test)?_f:new InjectableTestService(context2);this._ui=services.ui;this._config=services.config;this._keyValueDB=services.keyValueDB;this._control=null!=(_g=services.control)?_g:new ControlService(context2,{appLifecycleService:this._appLifecycle,databaseService:this._database,fileProcessingService:this._fileProcessing,settingService:this._setting,APIService:this._api,replicatorService:this._replicator})}get API(){return this._api}get path(){return this._path}get database(){return this._database}get databaseEvents(){return this._databaseEvents}get replicator(){return this._replicator}get fileProcessing(){return this._fileProcessing}get replication(){return this._replication}get remote(){return this._remote}get conflict(){return this._conflict}get appLifecycle(){return this._appLifecycle}get setting(){return this._setting}get tweakValue(){return this._tweakValue}get vault(){return this._vault}get test(){return this._test}get control(){return this._control}get keyValueDB(){return this._keyValueDB}get UI(){return this._ui}get config(){return this._config}};ObsidianServiceContext=class extends ServiceContext{constructor(app,plugin2,liveSyncPlugin,notices,noticeGroups){super({events:eventHub,translate:translateLiveSyncMessage});this.app=app;this.plugin=plugin2;this.liveSyncPlugin=liveSyncPlugin;this.notices=notices;this.noticeGroups=noticeGroups}};FetchMethod_webCompat=0,FetchMethod_native=1;RemoteService=class extends ServiceBase{constructor(context2,dependencies){super(context2);__publicField(this,"_log");__publicField(this,"_authHeader",new AuthorizationHeaderGenerator);__publicField(this,"_APIService");__publicField(this,"_appLifecycleService");__publicField(this,"_settingService");__publicField(this,"_unresolvedErrors");__publicField(this,"_pouchDB");__publicField(this,"last_successful_post",!1);this._pouchDB=dependencies.pouchDB;this._APIService=dependencies.APIService;this._appLifecycleService=dependencies.appLifecycle;this._settingService=dependencies.setting;this._log=createInstanceLogFunction("RemoteService",dependencies.APIService);this._unresolvedErrors=new UnresolvedErrorManager(this._appLifecycleService,this.context.events)}get hadLastPostFailedBySize(){return!this.last_successful_post}showError(msg,max_log_level=LOG_LEVEL_NOTICE){this._unresolvedErrors.showError(msg,max_log_level)}clearErrors(){this._unresolvedErrors.clearErrors()}async performFetch(req,opts,fetchMethod=FetchMethod_webCompat){const useNativeFetch=fetchMethod===FetchMethod_native,fetchFunction=useNativeFetch?this._APIService.nativeFetch.bind(this._APIService):this._APIService.webCompatFetch.bind(this._APIService);return await runWithTrackedPhysicalRequest(this._APIService,async()=>{var _a13;const response=await fetchFunction(req,opts),method=null!=(_a13=null==opts?void 0:opts.method)?_a13:"GET";this.last_successful_post="POST"!=method&&"PUT"!=method||response.ok;const url=new URL("string"==typeof req?req:req.url),localURL=`${url.protocol}//${url.host}${url.pathname}`;this._log(`[REQ] (${method}) ${localURL} -> ${response.status}`,LOG_LEVEL_DEBUG);if(2!==Math.floor(response.status/100))if(404==response.status)"GET"===method&&-1===url.pathname.indexOf("/_local/")&&this._log("Just checkpoint or some server information has been missing. The 404 error shown above is not an error.",LOG_LEVEL_VERBOSE);else{const r4=response.clone();this._log(`The request may have failed. The reason sent by the server: ${r4.status}: ${r4.statusText}`,LOG_LEVEL_NOTICE);try{const result=await r4.text();this._log(result,LOG_LEVEL_VERBOSE)}catch(_){this._log("Could not fetch response body",LOG_LEVEL_VERBOSE);this._log(_,LOG_LEVEL_VERBOSE)}}else this.clearErrors();return response})}async connect(uri,auth,disableRequestURI,passphrase,useDynamicIterationCount,performSetup,skipInfo,compression,customHeaders,useRequestAPI,getPBKDF2Salt,connectionOptions={}){if(!isValidRemoteCouchDBURI(uri))return"Remote URI is not valid";if(uri.toLowerCase()!=uri)return"Remote URI and database name could not contain capital letters.";if(-1!==uri.indexOf(" "))return"Remote URI and database name could not contain spaces.";if(!this._APIService.isOnline)return"Network is offline";const connectionScope=createRemoteConnectionScope(connectionOptions.signal),conf={adapter:"http",auth:"username"in auth?auth:void 0,skip_setup:!performSetup,fetch:async(requestSrc,opts)=>{var _a13;const url=new URL("string"==typeof requestSrc?requestSrc:requestSrc.url),authHeader=await this._authHeader.getAuthorizationHeader(auth);let size="";const localURL=url.toString().substring(uri.length),method=null!=(_a13=null==opts?void 0:opts.method)?_a13:"GET";if(null==opts?void 0:opts.body){const bodyLength="string"==typeof opts.body?opts.body.length:JSON.stringify(opts.body).length,opts_length=isNaN(bodyLength)?0:bodyLength;if(opts_length>1e7&&isCloudantURI(uri)){this.last_successful_post=!1;this._log("This request should fail on IBM Cloudant.",LOG_LEVEL_VERBOSE);throw new Error("This request should fail on IBM Cloudant.")}size=` (${opts_length})`}try{const headers=new Headers(null==opts?void 0:opts.headers);if(customHeaders)for(const[key3,value]of Object.entries(customHeaders))key3&&value&&headers.append(key3,value);"username"in auth||headers.append("authorization",authHeader);try{const signal=connectionScope.combine(null==opts?void 0:opts.signal),response=await this.performFetch(requestSrc,{...opts,headers,signal},useRequestAPI?FetchMethod_native:FetchMethod_webCompat);return response}catch(ex){if(ex instanceof TypeError){if(connectionScope.signal.aborted||!1===connectionOptions.allowNativeFallback)throw ex;if(useRequestAPI){this._log("Failed to request by API.");throw ex}this._log("Failed to fetch by native fetch API. Trying to fetch by API to get more information.");const resp2=await this.performFetch(requestSrc,{...opts,headers},FetchMethod_native);if(resp2.status/100==2){this.showError("The request was successful by API. But the native fetch API failed! Please check CORS settings on the remote database!. While this condition, you cannot enable LiveSync",LOG_LEVEL_NOTICE);return resp2}const r22=resp2.clone(),msg=await r22.text();this.showError(`Failed to fetch by API. ${resp2.status}: ${msg}`,LOG_LEVEL_NOTICE);return resp2}throw ex}}catch(ex){this._log(`HTTP:${method}${size} to:${localURL} -> failed`,LOG_LEVEL_VERBOSE);const msg=ex instanceof Error?`${null==ex?void 0:ex.name}:${null==ex?void 0:ex.message}`:null==ex?void 0:ex.toString();connectionScope.signal.aborted||this.showError(`${MARK_LOG_NETWORK_ERROR}Network Error: Failed to fetch: ${msg}`,LOG_LEVEL_INFO);this._log(ex,LOG_LEVEL_VERBOSE);-1!==url.toString().indexOf("_bulk_docs")&&(this.last_successful_post=!1);this._log(ex);throw ex}}},setting=this._settingService.currentSettings();let db;try{db=new this._pouchDB(uri,conf)}catch(ex){connectionScope.abort(ex);throw ex}const connection=createCouchDBConnection(db,{db_name:"",doc_count:0,update_seq:""},connectionScope),closeAfterConnectionFailure=async()=>{try{await connection.close()}catch(closeError){this._log("Failed to close remote database after connection failure.",LOG_LEVEL_INFO);this._log(closeError,LOG_LEVEL_VERBOSE)}};try{replicationFilter(db,compression);disableEncryption();"false"!==passphrase&&"string"==typeof passphrase&&enableEncryption(db,passphrase,useDynamicIterationCount,!1,getPBKDF2Salt,setting.E2EEAlgorithm)}catch(ex){await closeAfterConnectionFailure();throw ex}if(skipInfo)return connection;try{const info3=await db.info();return{...connection,info:info3}}catch(ex){const exMsg=ex instanceof Error?ex:LiveSyncError.fromError(ex),msg=`${exMsg.name}:${exMsg.message}`;this._log(ex,LOG_LEVEL_VERBOSE);await closeAfterConnectionFailure();return msg}}};InjectableRemoteService=class extends RemoteService{};ConfigService=class extends ServiceBase{};ConfigServiceBrowserCompat=class extends ConfigService{constructor(context2,dependencies){super(context2);__publicField(this,"_settingService");__publicField(this,"_log");this._settingService=dependencies.settingService;this._log=createInstanceLogFunction("ConfigService",dependencies.APIService)}getSmallConfig(key3){return this._settingService.getSmallConfig(key3)}setSmallConfig(key3,value){return this._settingService.setSmallConfig(key3,value)}deleteSmallConfig(key3){return this._settingService.deleteSmallConfig(key3)}};KeyValueDBService=class extends ServiceBase{constructor(context2,dependencies){var _a13;super(context2);__publicField(this,"_kvDB");__publicField(this,"_simpleStore");__publicField(this,"databaseEvents");__publicField(this,"vault");__publicField(this,"appLifecycle");__publicField(this,"openKeyValueDatabase");__publicField(this,"_log",createInstanceLogFunction("KeyValueDBService"));this.databaseEvents=dependencies.databaseEvents;this.vault=dependencies.vault;this.appLifecycle=dependencies.appLifecycle;this.openKeyValueDatabase=dependencies.openKeyValueDatabase;if(null==(_a13=dependencies.registerLifecycleHandlers)||_a13){this.databaseEvents.onResetDatabase.addHandler(this._everyOnResetDatabase.bind(this));this.appLifecycle.onSettingLoaded.addHandler(this._everyOnloadAfterLoadSettings.bind(this));this.databaseEvents.onDatabaseInitialisation.addHandler(this._everyOnInitializeDatabase.bind(this));this.databaseEvents.onUnloadDatabase.addHandler(this._onOtherDatabaseUnload.bind(this));this.databaseEvents.onCloseDatabase.addHandler(this._onOtherDatabaseClose.bind(this))}}get simpleStore(){if(!this._simpleStore)throw new Error("SimpleStore is not initialized yet");return this._simpleStore}get kvDB(){if(!this._kvDB)throw new Error("KeyValueDB is not initialized yet");return this._kvDB}async _everyOnResetDatabase(any){var _a13,_b6;try{const kvDBKey="queued-files";await(null==(_a13=this._kvDB)?void 0:_a13.del(kvDBKey));await(null==(_b6=this._kvDB)?void 0:_b6.destroy());await yieldMicrotask();this._kvDB=await this.openKeyValueDatabase(this.vault.getVaultName()+"-livesync-kv");await delay(100)}catch(e3){this._kvDB=void 0;this._log("Failed to reset KeyValueDB",LOG_LEVEL_NOTICE);this._log(e3,LOG_LEVEL_VERBOSE);return!1}return!0}async tryCloseKvDB(){var _a13;try{await(null==(_a13=this._kvDB)?void 0:_a13.close());return!0}catch(e3){this._log("Failed to close KeyValueDB",LOG_LEVEL_VERBOSE);this._log(e3);return!1}}async openKeyValueDB(){await delay(10);try{await this.tryCloseKvDB();await delay(10);await yieldMicrotask();this._kvDB=await this.openKeyValueDatabase(this.vault.getVaultName()+"-livesync-kv");await yieldMicrotask();await delay(100)}catch(e3){this._kvDB=void 0;this._log("Failed to open KeyValueDB",LOG_LEVEL_NOTICE);this._log(e3,LOG_LEVEL_VERBOSE);return!1}return!0}async _onOtherDatabaseUnload(){this._kvDB&&await this.tryCloseKvDB();return Promise.resolve(!0)}async _onOtherDatabaseClose(){this._kvDB&&await this.tryCloseKvDB();return Promise.resolve(!0)}_everyOnInitializeDatabase(any){return this.openKeyValueDB()}async _everyOnloadAfterLoadSettings(){if(!await this.openKeyValueDB())return!1;this._simpleStore=this.openSimpleStore("os");return Promise.resolve(!0)}openSimpleStore(kind){const getDB=()=>{if(!this._kvDB)throw new Error("KeyValueDB is not initialized yet");return this._kvDB},prefix=`${kind}-`;return{get:async key3=>await getDB().get(`${prefix}${key3}`),set:async(key3,value)=>{await getDB().set(`${prefix}${key3}`,value)},delete:async key3=>{await getDB().del(`${prefix}${key3}`)},keys:async(from,to,count)=>{const ret=await getDB().keys(IDBKeyRange.bound(`${prefix}${from||""}`,`${prefix}${to||""}`),count);return ret.map(e3=>("string"==typeof e3?e3:JSON.stringify(e3)).toString()).filter(e3=>e3.startsWith(prefix)).map(e3=>e3.substring(prefix.length))},get db(){return Promise.resolve(getDB())}}}};ObsidianDatabaseEventService=class extends InjectableDatabaseEventService{};ObsidianReplicatorService=class extends InjectableReplicatorService{constructor(context2,dependencies){super(context2,withSleepPreference(dependencies));this.boundedLocalApplicationActivityCount=reactiveSource(0)}async runBoundedLocalApplicationActivity(task,options){this.boundedLocalApplicationActivityCount.value++;try{return this.dependencies.activityRunner?await this.dependencies.activityRunner.run(task,options):await task()}finally{this.boundedLocalApplicationActivityCount.value--}}};ObsidianFileProcessingService=class extends InjectableFileProcessingService{};ObsidianReplicationService=class extends InjectableReplicationService{};ObsidianRemoteService=class extends InjectableRemoteService{};ObsidianConflictService=class extends InjectableConflictService{};ObsidianTweakValueService=class extends InjectableTweakValueService{};ObsidianTestService=class extends InjectableTestService{};ObsidianConfigService=class extends ConfigServiceBrowserCompat{};ObsidianKeyValueDBService=class extends KeyValueDBService{};ObsidianControlService=class extends ControlService{};SettingService=class extends ServiceBase{constructor(context2,dependencies){super(context2);__publicField(this,"deviceAndVaultName","");__publicField(this,"APIService");__publicField(this,"onDisplayLanguageChanged");__publicField(this,"_settings");__publicField(this,"_lastPersistedSettings");__publicField(this,"_settingsMigrationState");__publicField(this,"_log");__publicField(this,"onBeforeRealiseSetting",handlers2().bailFirstFailure("onBeforeRealiseSetting"));__publicField(this,"onSettingRealised",handlers2().bailFirstFailure("onSettingRealised"));__publicField(this,"onRealiseSetting",handlers2().bailFirstFailure("onRealiseSetting"));__publicField(this,"suspendAllSync",handlers2().all("suspendAllSync"));__publicField(this,"suspendExtraSync",handlers2().all("suspendExtraSync"));__publicField(this,"enableOptionalFeature",handlers2().all("enableOptionalFeature"));__publicField(this,"onSettingLoaded",handlers2().allParallel("onSettingLoaded"));__publicField(this,"onSettingChanged",handlers2().allParallel("onSettingChanged"));__publicField(this,"onSettingSaved",handlers2().allParallel("onSettingSaved"));__publicField(this,"onBeforeSaveSettingData",handlers2().dispatchParallel("onBeforeSaveSettingData"));__publicField(this,"usedPassphrase","");this.APIService=dependencies.APIService;this.onDisplayLanguageChanged=dependencies.onDisplayLanguageChanged;this._log=createInstanceLogFunction("SettingService",this.APIService)}get settings(){return this._settings}set settings(value){this._settings=value}getSettingsMigrationState(){return this._settingsMigrationState}adjustSettings(settings){migrateLegacyRemoteConfigurationsInPlace(settings,message=>{this._log(message,LOG_LEVEL_NOTICE)})&&this._log("Legacy remote configuration has been migrated to the remote configuration list.",LOG_LEVEL_NOTICE);settings.disableRequestURI=!0;settings.gcDelay=0;settings.useHistory=!0;"workingEncrypt"in settings&&delete settings.workingEncrypt;"workingPassphrase"in settings&&delete settings.workingPassphrase;""==settings.chunkSplitterVersion?settings.enableChunkSplitterV2?settings.useSegmenter?settings.chunkSplitterVersion="v2-segmenter":settings.chunkSplitterVersion="v2":settings.chunkSplitterVersion="":settings.chunkSplitterVersion in ChunkAlgorithmNames||(settings.chunkSplitterVersion="");return Promise.resolve(settings)}getDeviceAndVaultName(){return this.deviceAndVaultName}setDeviceAndVaultName(name){this.deviceAndVaultName=name}saveDeviceAndVaultName(){const lsKey="obsidian-live-sync-vaultanddevicename-"+this.APIService.getSystemVaultName()+this.additionalSuffixOfDatabaseName();this.setDeviceLocalConfig(lsKey,this.deviceAndVaultName)}getDeviceLocalConfig(key3){return this.getItem(key3)}setDeviceLocalConfig(key3,value){this.setItem(key3,value)}deleteDeviceLocalConfig(key3){this.deleteItem(key3)}additionalSuffixOfDatabaseName(){var _a13;const suffix=null==(_a13=this.settings)?void 0:_a13.additionalSuffixOfDatabaseName;if(void 0===suffix){this._log("too early to get additionalSuffixOfDatabaseName, returning empty string");return""}return`-${suffix}`}getKey(key3){const keyMain=this.APIService.getSystemVaultName(),addSuffix=this.additionalSuffixOfDatabaseName();return`${keyMain}${addSuffix}-${key3}`}setSmallConfig(key3,value){const dbKey=this.getKey(key3);this.setDeviceLocalConfig(dbKey,value)}getSmallConfig(key3){var _a13;const dbKey=this.getKey(key3);return null!=(_a13=this.getDeviceLocalConfig(dbKey))?_a13:""}deleteSmallConfig(key3){const dbKey=this.getKey(key3);this.deleteDeviceLocalConfig(dbKey)}async saveSettingData(){var _a13;this.saveDeviceAndVaultName();const previousSettings=null!=(_a13=this._lastPersistedSettings)?_a13:this.cloneSettings(this.settings),settings={...this.settings,remoteConfigurations:Object.fromEntries(Object.entries(this.settings.remoteConfigurations||{}).map(([id,config])=>[id,{...config}]))},hookResults=await this.onBeforeSaveSettingData(settings,previousSettings);for(const patch of hookResults)if(!(patch instanceof Error)&&patch){Object.assign(settings,patch);Object.assign(this.settings,patch)}settings.deviceAndVaultName="";if(settings.P2P_DevicePeerName&&""!==settings.P2P_DevicePeerName.trim()){this._log("Saving device peer name to small config");this.setSmallConfig(SETTING_KEY_P2P_DEVICE_NAME,settings.P2P_DevicePeerName.trim());settings.P2P_DevicePeerName=""}if(""!=this.usedPassphrase||await this.getPassphrase(settings)){if(""!=settings.couchDB_PASSWORD||""!=settings.couchDB_URI||""!=settings.couchDB_USER||settings.couchDB_DBNAME){const connectionSetting={couchDB_DBNAME:settings.couchDB_DBNAME,couchDB_PASSWORD:settings.couchDB_PASSWORD,couchDB_URI:settings.couchDB_URI,couchDB_USER:settings.couchDB_USER,accessKey:settings.accessKey,bucket:settings.bucket,endpoint:settings.endpoint,region:settings.region,secretKey:settings.secretKey,useCustomRequestHandler:settings.useCustomRequestHandler,bucketCustomHeaders:settings.bucketCustomHeaders,couchDB_CustomHeaders:settings.couchDB_CustomHeaders,useJWT:settings.useJWT,jwtKey:settings.jwtKey,jwtAlgorithm:settings.jwtAlgorithm,jwtKid:settings.jwtKid,jwtExpDuration:settings.jwtExpDuration,jwtSub:settings.jwtSub,useRequestAPI:settings.useRequestAPI,bucketPrefix:settings.bucketPrefix,forcePathStyle:settings.forcePathStyle};settings.encryptedCouchDBConnection=await this.encryptConfigurationItem(JSON.stringify(connectionSetting),settings);settings.couchDB_PASSWORD="";settings.couchDB_DBNAME="";settings.couchDB_URI="";settings.couchDB_USER="";settings.accessKey="";settings.bucket="";settings.region="";settings.secretKey="";settings.endpoint=""}if(settings.encrypt&&""!=settings.passphrase){settings.encryptedPassphrase=await this.encryptConfigurationItem(settings.passphrase,settings);settings.passphrase=""}await this.encryptRemoteConfigurationUris(settings)}else this._log("Failed to retrieve passphrase. data.json contains unencrypted items!",LOG_LEVEL_NOTICE);await this.saveData(settings);this._lastPersistedSettings=this.cloneSettings(this.settings);this.onSettingSaved(settings)}async encryptRemoteConfigurationUris(settings){const configs=settings.remoteConfigurations||{};for(const[id,config]of Object.entries(configs)){if(config.isEncrypted||""===config.uri.trim())continue;const encryptedURI=await this.encryptConfigurationItem(config.uri,settings);""!==encryptedURI?configs[id]={...config,uri:encryptedURI,isEncrypted:!0}:this._log(`Failed to encrypt remote configuration '${id}'. This entry will be saved in plain text.`,LOG_LEVEL_URGENT)}}async decryptRemoteConfigurationUris(settings,passphrase){const configs=settings.remoteConfigurations||{};for(const[id,config]of Object.entries(configs)){if(!config.isEncrypted)continue;const decryptedURI=await this.decryptConfigurationItem(config.uri,passphrase);if(!1!==decryptedURI)configs[id]={...config,uri:decryptedURI,isEncrypted:!1};else{try{ConnectionStringParser.parse(config.uri);configs[id]={...config,isEncrypted:!1};this._log(`Remote configuration '${id}' had a plain-text URI marked as encrypted. The flag has been repaired.`,LOG_LEVEL_NOTICE);continue}catch(e3){}this._log(`Failed to decrypt remote configuration '${id}'. Verify passphrase and configuration.`,LOG_LEVEL_URGENT)}}}currentSettings(){return this.settings}updateSettings(updateFn,saveImmediately){try{const updated=updateFn(this.settings);this.settings=updated}catch(ex){this._log("Error in update function: ",LOG_LEVEL_URGENT);this._log(ex,LOG_LEVEL_VERBOSE);return Promise.reject(ex instanceof Error?ex:new Error(String(ex)))}return saveImmediately?this.saveSettingData():Promise.resolve()}async applyExternalSettings(partial,saveImmediately){try{this.settings=await this.adjustSettings({...this.settings,...partial})}catch(ex){this._log("Error in applying external settings: ",LOG_LEVEL_URGENT);this._log(ex,LOG_LEVEL_VERBOSE);return Promise.reject(ex instanceof Error?ex:new Error(String(ex)))}return saveImmediately?this.saveSettingData():Promise.resolve()}applyPartial(partial,saveImmediately){try{this.settings={...this.settings,...partial}}catch(ex){this._log("Error in applying partial settings: ",LOG_LEVEL_URGENT);this._log(ex,LOG_LEVEL_VERBOSE);return Promise.reject(ex instanceof Error?ex:new Error(String(ex)))}return saveImmediately?this.saveSettingData():Promise.resolve()}getPassphrase(settings){const methods={"":()=>Promise.resolve("*"),LOCALSTORAGE:()=>{var _a13;return Promise.resolve(null!=(_a13=this.getDeviceLocalConfig("ls-setting-passphrase"))&&_a13)},ASK_AT_LAUNCH:()=>this.APIService.confirm.askString("Passphrase","passphrase","")},method=settings.configPassphraseStore,methodFunc=method in methods?methods[method]:methods[""];return methodFunc()}clearUsedPassphrase(){this.usedPassphrase=""}async decryptConfigurationItem(encrypted,passphrase){try{const dec=await decryptString(encrypted,passphrase+SALT_OF_PASSPHRASE);if(dec){this.usedPassphrase=passphrase;return dec}}catch(ex){this._log("Failed to decrypt configuration item",LOG_LEVEL_NOTICE);this._log(ex,LOG_LEVEL_VERBOSE)}return!1}async encryptConfigurationItem(src,settings){if(""!=this.usedPassphrase)return await encryptString(src,this.usedPassphrase+SALT_OF_PASSPHRASE);const passphrase=await this.getPassphrase(settings);if(!1===passphrase){this._log("Failed to obtain passphrase when saving data.json! Please verify the configuration.",LOG_LEVEL_URGENT);return""}const dec=await encryptString(src,passphrase+SALT_OF_PASSPHRASE);if(dec){this.usedPassphrase=passphrase;return dec}return""}async decryptSettings(settings){const passphrase=await this.getPassphrase(settings);if(!1===passphrase){this._log("No passphrase found for data.json! Verify configuration before syncing.",LOG_LEVEL_URGENT);const hasEncryptedRemoteConfigurations=Object.values(settings.remoteConfigurations||{}).some(config=>config.isEncrypted);hasEncryptedRemoteConfigurations&&this._log("Encrypted remote configurations found, but passphrase is unavailable. Verify configuration before syncing.",LOG_LEVEL_URGENT)}else{if(settings.encryptedCouchDBConnection){const keys3=["couchDB_URI","couchDB_USER","couchDB_PASSWORD","couchDB_DBNAME","accessKey","bucket","endpoint","region","secretKey"],decrypted=this.tryDecodeJson(await this.decryptConfigurationItem(settings.encryptedCouchDBConnection,passphrase));if(decrypted)for(const key3 of keys3)key3 in decrypted&&(settings[key3]=decrypted[key3]);else{this._log("Failed to decrypt passphrase from data.json! Ensure configuration is correct before syncing with remote.",LOG_LEVEL_URGENT);for(const key3 of keys3)settings[key3]=""}}if(settings.encrypt&&settings.encryptedPassphrase){const encrypted=settings.encryptedPassphrase,decrypted=await this.decryptConfigurationItem(encrypted,passphrase);if(decrypted)settings.passphrase=decrypted;else{this._log("Failed to decrypt passphrase from data.json! Ensure configuration is correct before syncing with remote.",LOG_LEVEL_URGENT);settings.passphrase=""}}await this.decryptRemoteConfigurationUris(settings,passphrase)}return settings}async loadSettings(){var _a13,_b6,_c3,_d2,_e2;const prepared=prepareSettingsForLoad(await this.loadData()),{settings,...migrationState}=prepared;this._settingsMigrationState=migrationState;const hadRemoteConfigurations=Object.keys(null!=(_a13=settings.remoteConfigurations)?_a13:{}).length>0;if(void 0===settings.isConfigured)if(prepared.isNewVault){const appId=this.APIService.getAppID();settings.additionalSuffixOfDatabaseName=appId;settings.isConfigured=!1}else settings.isConfigured=!0;this.settings=await this.decryptSettings(settings);null==(_b6=this.onDisplayLanguageChanged)||_b6.call(this,this.settings.displayLanguage);await this.adjustSettings(this.settings);const migratedLegacyRemoteConfigurations=!hadRemoteConfigurations&&Object.keys(null!=(_c3=this.settings.remoteConfigurations)?_c3:{}).length>0,migratedP2PActiveRemoteConfiguration=migratedLegacyRemoteConfigurations&&migrateP2PActiveRemoteConfigurationIdInPlace(this.settings),activeConfigurationId=this.settings.activeConfigurationId;if(activeConfigurationId&&(null==(_d2=this.settings.remoteConfigurations)?void 0:_d2[activeConfigurationId])){const activated=activateRemoteConfiguration(this.settings,activeConfigurationId);activated?this._log(`Active remote configuration '${activeConfigurationId}' has been activated.`,LOG_LEVEL_VERBOSE):this._log(`Failed to activate the selected remote configuration: ${activeConfigurationId}`,LOG_LEVEL_NOTICE)}const p2pActiveConfigurationId=this.settings.P2P_ActiveRemoteConfigurationId;if(p2pActiveConfigurationId&&(null==(_e2=this.settings.remoteConfigurations)?void 0:_e2[p2pActiveConfigurationId])){const activatedP2P=activateP2PRemoteConfiguration(this.settings,p2pActiveConfigurationId);activatedP2P?this._log(`P2P active remote configuration '${p2pActiveConfigurationId}' has been activated.`,LOG_LEVEL_VERBOSE):this._log(`Failed to activate the selected P2P remote configuration: ${p2pActiveConfigurationId}`,LOG_LEVEL_NOTICE)}const lsKey="obsidian-live-sync-vaultanddevicename-"+this.APIService.getSystemVaultName()+this.additionalSuffixOfDatabaseName();if(""!=this.settings.deviceAndVaultName&&!this.getDeviceLocalConfig(lsKey)){this.setDeviceAndVaultName(this.settings.deviceAndVaultName);this.saveDeviceAndVaultName();this.settings.deviceAndVaultName=""}if(isCloudantURI(this.settings.couchDB_URI)&&0!=this.settings.customChunkSize){this._log("Configuration issues detected and automatically resolved. However, unsynchronized data may exist. Consider rebuilding if necessary.",LOG_LEVEL_NOTICE);this.settings.customChunkSize=0}this.setDeviceAndVaultName(this.getDeviceLocalConfig(lsKey)||"");if(""==this.getDeviceAndVaultName()&&this.settings.usePluginSync){this._log("Device name missing. Disabling plug-in sync.",LOG_LEVEL_NOTICE);this.settings.usePluginSync=!1}!prepared.isFromFutureSchema&&(prepared.changed||migratedLegacyRemoteConfigurations||migratedP2PActiveRemoteConfiguration)&&await this.saveSettingData();this._lastPersistedSettings=this.cloneSettings(this.settings);const dispatch=this.settings;this.onSettingLoaded(dispatch);this.onSettingChanged(dispatch)}tryDecodeJson(encoded){try{return!!encoded&&JSON.parse(encoded)}catch(e3){return!1}}cloneSettings(settings){return{...settings,remoteConfigurations:Object.fromEntries(Object.entries(settings.remoteConfigurations||{}).map(([id,config])=>[id,{...config}]))}}};ObsidianSettingService=class extends SettingService{constructor(context2,dependencies){super(context2,dependencies);this.onSettingSaved.addHandler(settings=>{this.context.events.emitEvent(EVENT_SETTING_SAVED,settings);return Promise.resolve(!0)});this.onSettingLoaded.addHandler(settings=>{this.context.events.emitEvent(EVENT_REQUEST_RELOAD_SETTING_TAB);return Promise.resolve(!0)})}setItem(key3,value){return compatGlobal.localStorage.setItem(key3,value)}getItem(key3){var _a13;return null!=(_a13=compatGlobal.localStorage.getItem(key3))?_a13:""}deleteItem(key3){compatGlobal.localStorage.removeItem(key3)}async saveData(data){return await this.context.liveSyncPlugin.saveData(data)}async loadData(){return normaliseObsidianSettingsData(await this.context.liveSyncPlugin.loadData())}};DatabaseService=class extends ServiceBase{constructor(context2,dependencies){super(context2);__publicField(this,"_log",createInstanceLogFunction("InjectableDatabaseService"));__publicField(this,"_localDatabase",null);__publicField(this,"services");__publicField(this,"onOpenDatabase",handlers2().bailFirstFailure("onOpenDatabase"));__publicField(this,"onDatabaseReset",handlers2().bailFirstFailure("onDatabaseReset"));this.services=dependencies}get localDatabase(){if(!this._localDatabase)throw new Error("Local database is not ready yet.");return this._localDatabase}get localDatabaseDirect(){return this._localDatabase}modifyDatabaseOptions(settings,name,options){const optionPass={...options};if(settings.useIndexedDBAdapter){optionPass.adapter="indexeddb";optionPass.purged_infos_limit=1;return{name:name+ExtraSuffixIndexedDB,options:optionPass}}return{name,options:optionPass}}createPouchDBInstance(name,options){const settings=this.services.setting.currentSettings(),optionPass=this.modifyDatabaseOptions(settings,null!=name?name:"",null!=options?options:{});return new this.services.pouchDB(optionPass.name,optionPass.options)}async openDatabase(params){null!=this._localDatabase&&await this._localDatabase.close();const vaultName=this.services.vault.getVaultName();this._log(this.context.translate("moduleLocalDatabase.logWaitingForReady"));const env={services:{context:this.context,...this.services,...params,database:this}},selectedDatabase=new LiveSyncLocalDB(vaultName,env);this._localDatabase=selectedDatabase;try{await this.onOpenDatabase(vaultName);const initialised=await selectedDatabase.initializeDatabase();initialised||this._localDatabase!==selectedDatabase||(this._localDatabase=null);return initialised}catch(error){this._localDatabase===selectedDatabase&&(this._localDatabase=null);throw error}}isDatabaseReady(){return null!=this._localDatabase&&this._localDatabase.isReady}async discardFailedActiveDatabase(database){this._localDatabase===database&&(this._localDatabase=null);try{await database.close()}catch(error){this._log("Failed to close the active database after a rejected lifecycle transition.",LOG_LEVEL_VERBOSE);this._log(error,LOG_LEVEL_VERBOSE)}}async resetDatabase(){if(!this._localDatabase)return Promise.resolve(!0);const activeDatabase=this._localDatabase;try{if(!await activeDatabase.resetDatabase()){await this.discardFailedActiveDatabase(activeDatabase);return!1}if(!await this.onDatabaseReset()){await this.discardFailedActiveDatabase(activeDatabase);return!1}return!0}catch(error){await this.discardFailedActiveDatabase(activeDatabase);throw error}}async resetDatabaseForCurrentSettings(params){var _a13,_b6;const selectedDatabaseName=this.services.vault.getVaultName();if((null==(_a13=this._localDatabase)?void 0:_a13.dbname)!==selectedDatabaseName){if(!await this.openDatabase(params))return!1;if((null==(_b6=this._localDatabase)?void 0:_b6.dbname)!==selectedDatabaseName)return!1}return await this.resetDatabase()}};ObsidianDatabaseService=class extends DatabaseService{__onOpenDatabase(vaultName){initializeStores(vaultName);return Promise.resolve(!0)}constructor(context2,dependencies){super(context2,dependencies);this.onOpenDatabase.addHandler(this.__onOpenDatabase.bind(this))}};ObsHttpHandler=class extends FetchHttpHandler{constructor(options,reverseProxyNoSignUrl){super(options);this.requestTimeoutInMs=void 0===options?void 0:options.requestTimeout;this.reverseProxyNoSignUrl=reverseProxyNoSignUrl}async handle(request2,{abortSignal}={}){if(null==abortSignal?void 0:abortSignal.aborted){const abortError=new Error("Request aborted");abortError.name="AbortError";return Promise.reject(abortError)}let path2=request2.path;if(request2.query){const queryString=buildQueryString2(request2.query);queryString&&(path2+=`?${queryString}`)}const{port,method}=request2;let url=`${request2.protocol}//${request2.hostname}${port?`:${port}`:""}${path2}`;if(void 0!==this.reverseProxyNoSignUrl&&""!==this.reverseProxyNoSignUrl){const urlObj=new URL(url);urlObj.host=this.reverseProxyNoSignUrl;url=urlObj.href}const body="GET"===method||"HEAD"===method?void 0:request2.body,transformedHeaders={};for(const key3 of Object.keys(request2.headers)){const keyLower=key3.toLowerCase();"host"!==keyLower&&"content-length"!==keyLower&&(transformedHeaders[keyLower]=request2.headers[key3])}let contentType;void 0!==transformedHeaders["content-type"]&&(contentType=transformedHeaders["content-type"]);const transformedBody=normaliseRequestBody(body),param={body:transformedBody,headers:transformedHeaders,method,url,contentType},raceOfPromises=[(0,import_obsidian.requestUrl)(param).then(rsp=>{const headers=rsp.headers,headersLower={};for(const key3 of Object.keys(headers))headersLower[key3.toLowerCase()]=headers[key3];const stream=new ReadableStream({start(controller){controller.enqueue(new Uint8Array(rsp.arrayBuffer));controller.close()}});return{response:new HttpResponse({headers:headersLower,statusCode:rsp.status,body:stream})}}),requestTimeout2(this.requestTimeoutInMs)];abortSignal&&raceOfPromises.push(new Promise((resolve,reject)=>{abortSignal.onabort=()=>{const abortError=new Error("Request aborted");abortError.name="AbortError";reject(abortError)}}));return Promise.race(raceOfPromises)}};import_obsidian3=require("obsidian");TextPromptModal=class extends import_obsidian3.Modal{constructor(app,options,resolveResult){var _a13;super(app);__publicField(this,"options");__publicField(this,"resolveResult");__publicField(this,"value");__publicField(this,"input");this.options=options;this.resolveResult=resolveResult;this.value=null!=(_a13=options.initialValue)?_a13:""}onOpen(){var _a13,_b6;this.setTitle(this.options.title);const inputSetting=new import_obsidian3.Setting(this.contentEl);void 0!==this.options.label&&inputSetting.setName(this.options.label);void 0!==this.options.description&&inputSetting.setDesc(this.options.description);inputSetting.addText(input=>{var _a14;this.input=input;input.setValue(this.value);input.setPlaceholder(null!=(_a14=this.options.placeholder)?_a14:"");input.inputEl.type=this.options.password?"password":"text";input.onChange(value=>{this.value=value});input.inputEl.addEventListener("keydown",event2=>{if("Enter"===event2.key&&!event2.isComposing){event2.preventDefault();this.submit()}})});new import_obsidian3.Setting(this.contentEl).addButton(button=>{var _a14;return button.setButtonText(null!=(_a14=this.options.submitLabel)?_a14:"OK").setCta().onClick(()=>this.submit())}).addButton(button=>{var _a14;return button.setButtonText(null!=(_a14=this.options.cancelLabel)?_a14:"Cancel").onClick(()=>this.close())});null==(_a13=this.input)||_a13.inputEl.focus();this.options.selectInitialValue&&this.value.length>0&&(null==(_b6=this.input)||_b6.inputEl.select())}onClose(){this.settle(null);this.input=void 0;this.contentEl.empty()}submit(){this.settle(this.value);this.close()}settle(result){const resolve=this.resolveResult;if(void 0!==resolve){this.resolveResult=void 0;resolve(result)}}};PickOneModal=class extends import_obsidian3.FuzzySuggestModal{constructor(app,options,resolveResult){var _a13;super(app);__publicField(this,"items");__publicField(this,"itemText");__publicField(this,"itemDescription");__publicField(this,"resolveResult");this.items=options.items;this.itemText=options.getText;this.itemDescription=options.getDescription;this.resolveResult=resolveResult;this.setPlaceholder(null!=(_a13=options.placeholder)?_a13:"Select an item")}getItems(){return[...this.items]}getItemText(item){return this.itemText(item)}renderSuggestion(match3,element2){var _a13;super.renderSuggestion(match3,element2);const description=null==(_a13=this.itemDescription)?void 0:_a13.call(this,match3.item);void 0!==description&&""!==description&&element2.createDiv({text:description,cls:"suggestion-note"})}onChooseItem(item,_event){this.settle(item)}onClose(){globalThis.setTimeout(()=>this.settle(null),0)}settle(result){const resolve=this.resolveResult;if(void 0!==resolve){this.resolveResult=void 0;resolve(result)}}};ActionDialog=class extends import_obsidian3.Modal{constructor(app,options,resolveResult){super(app);__publicField(this,"options");__publicField(this,"renderer",new import_obsidian3.Component);__publicField(this,"resolveResult");__publicField(this,"timeout");this.options=options;this.resolveResult=resolveResult}onOpen(){var _a13;this.setTitle(this.options.title);this.renderer.load();this.modalEl.addClass("vpk-action-dialog");this.modalEl.setCssStyles({maxHeight:"calc(100vh - var(--safe-area-inset-top, 0px) - var(--safe-area-inset-bottom, 0px) - 1rem)",minHeight:"0"});this.contentEl.setCssStyles({display:"flex",flexDirection:"column",minHeight:"0",overflowY:"hidden"});const messageEl=this.contentEl.createDiv({cls:"vpk-action-dialog__message"});messageEl.setCssStyles({flex:"1 1 auto",minHeight:"0",overflowY:"auto"});import_obsidian3.MarkdownRenderer.render(this.app,this.options.message,messageEl,null!=(_a13=this.options.sourcePath)?_a13:"",this.renderer);const actionsEl=this.contentEl.createDiv({cls:"vpk-action-dialog__actions-container"});actionsEl.setCssStyles({flexShrink:"0"});const actions=new import_obsidian3.Setting(actionsEl),verticalActions="vertical"===this.options.actionLayout;actions.controlEl.addClass("vpk-action-dialog__actions");verticalActions&&actions.controlEl.addClass("vpk-action-dialog__actions--vertical");actions.controlEl.setCssStyles({...verticalActions?{alignItems:"stretch",flexDirection:"column"}:{},flexWrap:"wrap",maxWidth:"100%",width:"100%"});for(const action2 of this.options.actions)actions.addButton(button=>{var _a14,_b6;button.buttonEl.addClass("vpk-action-dialog__action");button.buttonEl.setCssStyles({height:"auto",maxWidth:"100%",minHeight:"var(--input-height)",whiteSpace:"normal",...verticalActions?{width:"100%"}:{}});button.setButtonText(null!=(_b6=null==(_a14=this.options.labels)?void 0:_a14[action2])?_b6:action2).onClick(()=>this.choose(action2));action2===this.options.defaultAction&&button.setCta()});void 0!==this.options.timeoutMs&&void 0!==this.options.defaultAction&&(this.timeout=globalThis.setTimeout(()=>this.choose(this.options.defaultAction),this.options.timeoutMs))}onClose(){this.clearTimeout();this.renderer.unload();this.settle(null);this.contentEl.empty()}choose(action2){this.settle(action2);this.close()}settle(result){const resolve=this.resolveResult;if(void 0!==resolve){this.resolveResult=void 0;resolve(result)}}clearTimeout(){if(void 0!==this.timeout){globalThis.clearTimeout(this.timeout);this.timeout=void 0}}};import_obsidian4=require("obsidian");KeyedNoticeManager=class{constructor(options={}){__publicField(this,"entries",new Map);__publicField(this,"defaultDurationMs");__publicField(this,"disposed",!1);var _a13;this.defaultDurationMs=duration(null!=(_a13=options.defaultDurationMs)?_a13:5e3,"defaultDurationMs")}get isDisposed(){return this.disposed}show(key3,message,options={}){var _a13;this.assertActive();if(0===key3.length)throw new TypeError("key must not be empty");const durationMs=duration(null!=(_a13=options.durationMs)?_a13:this.defaultDurationMs,"durationMs");let entry=this.entries.get(key3);if(void 0!==entry&&!noticeEntryIsActive(entry)){this.clearTimer(entry);this.entries.delete(key3);entry.notice.hide();entry=void 0}if(void 0===entry){entry=createNoticeEntry(message);this.entries.set(key3,entry)}else renderNoticeMessage(entry,message);this.clearTimer(entry);if(!1!==durationMs){const scheduledEntry=entry;entry.hideTimer=globalThis.setTimeout(()=>this.expire(key3,scheduledEntry),durationMs)}return entry.notice}has(key3){const entry=this.entries.get(key3);if(void 0===entry)return!1;if(noticeEntryIsActive(entry))return!0;this.clearTimer(entry);this.entries.delete(key3);entry.notice.hide();return!1}hide(key3){const entry=this.entries.get(key3);if(void 0===entry)return!1;this.entries.delete(key3);this.clearTimer(entry);entry.notice.hide();return!0}hideAll(){const entries2=[...this.entries.values()];this.entries.clear();for(const entry of entries2){this.clearTimer(entry);entry.notice.hide()}}dispose(){if(!this.disposed){this.hideAll();this.disposed=!0}}expire(key3,entry){if(this.entries.get(key3)===entry){entry.hideTimer=void 0;this.entries.delete(key3);entry.notice.hide()}}clearTimer(entry){if(void 0!==entry.hideTimer){globalThis.clearTimeout(entry.hideTimer);entry.hideTimer=void 0}}assertActive(){if(this.disposed)throw new Error("KeyedNoticeManager has been disposed")}};KeyedNoticeGroupManager=class{constructor(options={}){__publicField(this,"groups",new Map);__publicField(this,"defaultCompletedDurationMs");__publicField(this,"disposed",!1);var _a13;this.defaultCompletedDurationMs=duration(null!=(_a13=options.defaultCompletedDurationMs)?_a13:5e3,"defaultCompletedDurationMs")}get isDisposed(){return this.disposed}setItem(groupKey,itemKey,item){this.assertActive();this.assertKey(groupKey,"groupKey");this.assertKey(itemKey,"itemKey");if(void 0!==item.action&&0===item.action.label.length)throw new TypeError("action label must not be empty");let entry=this.groups.get(groupKey);if(void 0===entry){entry=createGroupEntry();this.groups.set(groupKey,entry)}else{this.clearTimer(entry);if(!groupEntryIsActive(entry)){entry.notice.hide();entry=createGroupEntry();this.groups.set(groupKey,entry)}}entry.items.set(itemKey,{message:item.message,...void 0===item.action?{}:{action:item.action}});renderGroup(entry);return entry.notice}finish(groupKey,options={}){var _a13;this.assertActive();this.assertKey(groupKey,"groupKey");const entry=this.groups.get(groupKey);if(void 0===entry)return!1;if(!groupEntryIsActive(entry)){this.groups.delete(groupKey);this.clearTimer(entry);entry.notice.hide();return!1}const durationMs=duration(null!=(_a13=options.durationMs)?_a13:this.defaultCompletedDurationMs,"durationMs");this.clearTimer(entry);!1!==durationMs&&(entry.hideTimer=globalThis.setTimeout(()=>this.expire(groupKey,entry),durationMs));return!0}removeItem(groupKey,itemKey){const entry=this.groups.get(groupKey);if(void 0!==entry&&!groupEntryIsActive(entry)){this.groups.delete(groupKey);this.clearTimer(entry);entry.notice.hide();return!1}if(void 0===entry||!entry.items.delete(itemKey))return!1;if(0===entry.items.size){this.hide(groupKey);return!0}renderGroup(entry);return!0}has(groupKey){const entry=this.groups.get(groupKey);if(void 0===entry)return!1;if(groupEntryIsActive(entry))return!0;this.groups.delete(groupKey);this.clearTimer(entry);entry.notice.hide();return!1}hide(groupKey){const entry=this.groups.get(groupKey);if(void 0===entry)return!1;this.groups.delete(groupKey);this.clearTimer(entry);entry.notice.hide();return!0}hideAll(){const entries2=[...this.groups.values()];this.groups.clear();for(const entry of entries2){this.clearTimer(entry);entry.notice.hide()}}dispose(){if(!this.disposed){this.hideAll();this.disposed=!0}}expire(groupKey,entry){if(this.groups.get(groupKey)===entry){entry.hideTimer=void 0;this.groups.delete(groupKey);entry.notice.hide()}}clearTimer(entry){if(void 0!==entry.hideTimer){globalThis.clearTimeout(entry.hideTimer);entry.hideTimer=void 0}}assertKey(value,name){if(0===value.length)throw new TypeError(`${name} must not be empty`)}assertActive(){if(this.disposed)throw new Error("KeyedNoticeGroupManager has been disposed")}};0;AutoClosableModal=class extends import_obsidian.Modal{constructor(app){super(app);this._closeByUnload=()=>{eventHub.off(EVENT_PLUGIN_UNLOADED2,this._closeByUnload);this.close()};eventHub.once(EVENT_PLUGIN_UNLOADED2,this._closeByUnload)}onClose(){eventHub.off(EVENT_PLUGIN_UNLOADED2,this._closeByUnload)}};InputStringDialog=class extends AutoClosableModal{constructor(app,title,key3,placeholder,isPassword,onSubmit){super(app);this.result=!1;this.isManuallyClosed=!1;this.isPassword=!1;this.onSubmit=onSubmit;this.title=title;this.placeholder=placeholder;this.key=key3;this.isPassword=isPassword}onOpen(){const{contentEl}=this;this.titleEl.setText(this.title);const formEl=contentEl.createDiv();new import_obsidian.Setting(formEl).setName(this.key).setClass(this.isPassword?"password-input":"normal-input").addText(text2=>text2.onChange(value=>{this.result=value}));new import_obsidian.Setting(formEl).addButton(btn=>btn.setButtonText("Ok").setCta().onClick(()=>{this.isManuallyClosed=!0;this.close()})).addButton(btn=>btn.setButtonText("Cancel").setCta().onClick(()=>{this.close()}))}onClose(){super.onClose();const{contentEl}=this;contentEl.empty();this.isManuallyClosed?this.onSubmit(this.result):this.onSubmit(!1)}};PopoverSelectString=class extends import_obsidian.FuzzySuggestModal{constructor(app,note,placeholder,getItemsFun,callback){super(app);this.callback=()=>{};this.getItemsFun=()=>["yes","no"];this._app=app;this.setPlaceholder((null!=placeholder?placeholder:"y/n) ")+note);getItemsFun&&(this.getItemsFun=getItemsFun);this.callback=callback}getItems(){return this.getItemsFun()}getItemText(item){return item}onChooseItem(item,evt){var _a13;null==(_a13=this.callback)||_a13.call(this,item);this.callback=void 0}onClose(){compatGlobal.setTimeout(()=>{if(this.callback){this.callback("");this.callback=void 0}},100)}};MessageBox=class extends AutoClosableModal{constructor(plugin2,title,contentMd,buttons,defaultAction,timeout,wideButton,onSubmit){super(plugin2.app);this.result=!1;this.isManuallyClosed=!1;this.timer=void 0;this.component=new import_obsidian.Component;this.plugin=plugin2;this.title=title;this.contentMd=contentMd;this.buttons=buttons;this.onSubmit=onSubmit;this.defaultAction=defaultAction;this.timeout=timeout;this.wideButton=wideButton;this.timeout&&(this.timer=compatGlobal.setInterval(()=>{var _a13,_b6;if(void 0!==this.timeout){this.timeout--;if(this.timeout<0){if(this.timer){compatGlobal.clearInterval(this.timer);null==(_a13=this.defaultButtonComponent)||_a13.setButtonText(`${defaultAction}`);this.timer=void 0}this.result=defaultAction;this.isManuallyClosed=!0;this.close()}else null==(_b6=this.defaultButtonComponent)||_b6.setButtonText(`( ${this.timeout} ) ${defaultAction}`)}},1e3))}onOpen(){var _a13;this.component.load();const{contentEl}=this;null==(_a13=contentEl.closest(".modal-container"))||_a13.classList.add("livesync-message-box-container");this.titleEl.setText(this.title);const div=contentEl.createDiv();div.setCssStyles({userSelect:"text",webkitUserSelect:"text"});import_obsidian.MarkdownRenderer.render(this.plugin.app,this.contentMd,div,"/",this.component);const buttonSetting=new import_obsidian.Setting(contentEl),labelWrapper=contentEl.createDiv();labelWrapper.addClass("sls-dialogue-note-wrapper");const labelEl=labelWrapper.createEl("label",{text:"To stop the countdown, tap anywhere on the dialogue"});labelEl.addClass("sls-dialogue-note-countdown");if(!this.timeout||!this.timer){labelWrapper.empty();labelWrapper.setCssStyles({display:"none"})}buttonSetting.infoEl.setCssStyles({display:"none"});buttonSetting.controlEl.setCssStyles({flexWrap:"wrap"});this.wideButton&&buttonSetting.controlEl.setCssStyles({flexDirection:"column",alignItems:"center",justifyContent:"center",flexGrow:"1"});contentEl.addEventListener("click",()=>{var _a14;if(this.timer){labelWrapper.empty();labelWrapper.setCssStyles({display:"none"});compatGlobal.clearInterval(this.timer);this.timer=void 0;null==(_a14=this.defaultButtonComponent)||_a14.setButtonText(`${this.defaultAction}`)}});for(const button of this.buttons)buttonSetting.addButton(btn=>{btn.setButtonText(button).onClick(()=>{this.isManuallyClosed=!0;this.result=button;if(this.timer){compatGlobal.clearInterval(this.timer);this.timer=void 0}this.close()});if(button==this.defaultAction){this.defaultButtonComponent=btn;btn.setCta()}this.wideButton&&btn.buttonEl.setCssStyles({flexGrow:"1",width:"100%"});return btn})}onClose(){super.onClose();this.component.unload();const{contentEl}=this;contentEl.empty();if(this.timer){compatGlobal.clearInterval(this.timer);this.timer=void 0}this.isManuallyClosed?this.onSubmit(this.result):this.onSubmit(!1)}};0;0;0;ObsidianConfirm=class{constructor(context2){this.dialogueController=new AbortController;this.popupKeys=new Set;this._context=context2;context2.events.onceEvent(EVENT_PLUGIN_UNLOADED2,()=>{this.dialogueController.abort();for(const popupKey of this.popupKeys)this.closePopup(popupKey)})}get _app(){return this._context.app}get _plugin(){return this._context.plugin}get dialogueLifecycle(){return{signal:this.dialogueController.signal}}hasCountdown(timeout){return void 0!==timeout&&timeout>0}async askYesNo(message){const result=await confirmAction(this._app,{title:$msg("moduleInputUIObsidian.defaultTitleConfirmation"),message,actions:["yes","no"],labels:{yes:$msg("moduleInputUIObsidian.optionYes"),no:$msg("moduleInputUIObsidian.optionNo")},actionLayout:"vertical",defaultAction:"no",sourcePath:"/"},this.dialogueLifecycle);return"yes"===result?"yes":"no"}async askString(title,key3,placeholder,isPassword=!1){const prompt=isPassword?promptPassword:promptText,result=await prompt(this._app,{title,label:key3,placeholder},this.dialogueLifecycle);return null!=result&&result}async askYesNoDialog(message,opt={title:"Confirmation"}){const defaultTitle=$msg("moduleInputUIObsidian.defaultTitleConfirmation"),yesLabel=$msg("moduleInputUIObsidian.optionYes"),noLabel=$msg("moduleInputUIObsidian.optionNo"),defaultOption="Yes"===opt.defaultOption?yesLabel:noLabel;if(!this.hasCountdown(opt.timeout)){const result=await confirmAction(this._app,{title:opt.title||defaultTitle,message,actions:["Yes","No"],labels:{Yes:yesLabel,No:noLabel},actionLayout:"vertical",defaultAction:"Yes"===opt.defaultOption?"Yes":"No",sourcePath:"/"},this.dialogueLifecycle);return"Yes"===result?"yes":"no"}const ret=await confirmWithMessageWithWideButton(this._plugin,opt.title||defaultTitle,message,[yesLabel,noLabel],defaultOption,opt.timeout);return ret===yesLabel?"yes":"no"}async askSelectString(message,items){const result=await pickOne(this._app,{items,getText:item=>item,placeholder:message},this.dialogueLifecycle);return null!=result?result:""}async askSelectStringDialogue(message,buttons,opt){const defaultTitle=$msg("moduleInputUIObsidian.defaultTitleSelect"),presentedMessage="P2P Connection Request"===opt.title?message.replace("Peer-to-Peer Replicator Pane",$msg("P2P Status pane")):message;if(!this.hasCountdown(opt.timeout)){const result=await confirmAction(this._app,{title:opt.title||defaultTitle,message:presentedMessage,actions:buttons,actionLayout:"vertical",defaultAction:opt.defaultAction,sourcePath:"/"},this.dialogueLifecycle);return null!=result&&result}return confirmWithMessageWithWideButton(this._plugin,opt.title||defaultTitle,presentedMessage,buttons,opt.defaultAction,opt.timeout)}askInPopup(key3,dialogText,anchorCallback,durationMs=2e4){const popupKey="popup-"+key3;this.popupKeys.add(popupKey);const fragment=createFragment(doc=>{const[beforeText,afterText]=dialogText.split("{HERE}",2);doc.createSpan(void 0,a2=>{a2.appendText(beforeText);a2.appendChild(a2.createEl("a",void 0,anchor=>{anchorCallback(anchor);anchor.addEventListener("click",()=>this.closePopup(popupKey))}));a2.appendText(afterText)})});scheduleTask(popupKey,1e3,()=>{if(this.dialogueController.signal.aborted)this.popupKeys.delete(popupKey);else{this._context.notices.show(popupKey,fragment,{durationMs});scheduleTask(`${popupKey}-forget`,durationMs,()=>{this.popupKeys.delete(popupKey)})}})}closePopup(popupKey){this._context.notices.hide(popupKey);this.popupKeys.delete(popupKey)}async confirmWithMessage(title,contentMd,buttons,defaultAction,timeout,actionLayout){if(this.hasCountdown(timeout))return confirmWithMessageWithWideButton(this._plugin,title,contentMd,buttons,defaultAction,timeout);const result=await confirmAction(this._app,{title,message:contentMd,actions:buttons,defaultAction,sourcePath:"/",actionLayout:null!=actionLayout?actionLayout:"vertical"},this.dialogueLifecycle);return null!=result&&result}};ObsidianAPIService=class extends InjectableAPIService{constructor(context2){super(context2);this._confirmInstance=new ObsidianConfirm(context2)}getCustomFetchHandler(){this._customHandler||(this._customHandler=new ObsHttpHandler(void 0,void 0));return this._customHandler}async showWindow(viewType){const leaves=this.app.workspace.getLeavesOfType(viewType);0==leaves.length?await this.app.workspace.getLeaf(!0).setViewState({type:viewType,active:!0}):await leaves[0].setViewState({type:viewType,active:!0});leaves.length>0&&await this.app.workspace.revealLeaf(leaves[0])}async showWindowOnRight(viewType){const existing=this.app.workspace.getLeavesOfType(viewType);if(existing.length>0){await this.app.workspace.revealLeaf(existing[0]);return}const rightLeaf=this.app.workspace.getRightLeaf(!1);if(rightLeaf){await rightLeaf.setViewState({type:viewType,active:!1});await this.app.workspace.revealLeaf(rightLeaf)}else await this.showWindow(viewType)}get app(){return this.context.app}getPlatform(){return import_obsidian.Platform.isAndroidApp?"android-app":import_obsidian.Platform.isIosApp?"ios":import_obsidian.Platform.isMacOS?"macos":import_obsidian.Platform.isMobileApp?"mobile-app":import_obsidian.Platform.isMobile?"mobile":import_obsidian.Platform.isSafari?"safari":import_obsidian.Platform.isDesktop?"desktop":import_obsidian.Platform.isDesktopApp?"desktop-app":"unknown-obsidian"}isMobile(){return"isMobile"in this.app&&!!this.app.isMobile}getAppID(){return`${"appId"in this.app?this.app.appId:""}`}getSystemVaultName(){return this.app.vault.getName()}getAppVersion(){var _a13,_b6;const navigatorString=null!=(_b6=null==(_a13=compatGlobal.navigator)?void 0:_a13.userAgent)?_b6:"",match3=navigatorString.match(/obsidian\/([0-9]+\.[0-9]+\.[0-9]+)/);return match3&&match3.length>=2?match3[1]:"0.0.0"}getPluginVersion(){return this.context.plugin.manifest.version}get confirm(){return this._confirmInstance}addCommand(command){return this.context.plugin.addCommand(command)}registerWindow(type,factory){return this.context.plugin.registerView(type,factory)}addRibbonIcon(icon,title,callback){return this.context.plugin.addRibbonIcon(icon,title,callback)}registerProtocolHandler(action2,handler){return this.context.plugin.registerObsidianProtocolHandler(action2,handler)}async nativeFetch(req,opts){var _a13,_b6;const url="string"==typeof req?req:req.url;let body;const method="string"==typeof(null==opts?void 0:opts.method)?opts.method:req instanceof Request&&"string"==typeof req.method?req.method:"GET";"string"!=typeof req?(null==opts?void 0:opts.body)?body="string"==typeof opts.body?opts.body:await new Response(opts.body).arrayBuffer():req.body&&(body=await new Response(req.body).arrayBuffer()):body=null==opts?void 0:opts.body;const reqHeaders=new Headers(req instanceof Request?req.headers:{}),optHeaders={};reqHeaders.forEach((value,key3)=>{optHeaders[key3]=value});if(opts&&"headers"in opts)if(opts.headers instanceof Headers)opts.headers.forEach((value,key3)=>{optHeaders[key3]=value});else for(const[key3,value]of Object.entries(opts.headers))optHeaders[key3]=value;const transformedHeaders={...optHeaders};delete transformedHeaders.host;delete transformedHeaders.Host;delete transformedHeaders["content-length"];delete transformedHeaders["Content-Length"];const contentType=null!=(_b6=null!=(_a13=transformedHeaders["content-type"])?_a13:transformedHeaders["Content-Type"])?_b6:"application/json",requestParam={url,method,body,headers:transformedHeaders,contentType},r4=await(0,import_obsidian.requestUrl)({...requestParam,throw:!1});return new Response(r4.arrayBuffer,{headers:r4.headers,status:r4.status,statusText:`${r4.status}`})}addStatusBarItem(){return this.context.plugin.addStatusBarItem()}setInterval(handler,timeout){const timerId=compatGlobal.setInterval(handler,timeout);this.context.plugin.registerInterval(timerId);return timerId}getSystemConfigDir(){return this.app.vault.configDir}};ObsidianAppLifecycleService=class extends AppLifecycleServiceBase{performRestart(){this.context.plugin.app.commands.executeCommandById("app:reload")}};ObsidianPathService=class extends PathService{markChangesAreSame(old,newMtime,oldMtime){return markChangesAreSame(old,newMtime,oldMtime)}unmarkChanges(file){return unmarkChanges(file)}compareFileFreshness(baseFile,checkTarget){return compareFileFreshness(baseFile,checkTarget)}isMarkedAsSameChanges(file,mtimes){return isMarkedAsSameChanges(file,mtimes)}normalizePath(path2){return normalizePath(path2)}};ObsidianVaultService=class extends InjectableVaultService{vaultName(){return this.context.app.vault.getName()}getActiveFilePath(){const file=this.context.app.workspace.getActiveFile();if(file)return getPathFromTFile(file)}isStorageInsensitive(){var _a13;return null==(_a13=this.context.app.vault.adapter.insensitive)||_a13}shouldCheckCaseInsensitively(){return!this.isStorageInsensitive()&&super.shouldCheckCaseInsensitively()}isValidPath(path2){return isValidPath(path2)}};UIService=class extends ServiceBase{constructor(context2,dependents){super(context2);__publicField(this,"_dialogManager");__publicField(this,"_APIService");this._dialogManager=dependents.dialogManager;this._APIService=dependents.APIService}get dialogManager(){return this._dialogManager}async promptCopyToClipboard(title,value){const param={title,dataToCopy:value},result=await this._dialogManager.open(this.dialogToCopy,param);return"ok"===result}showMarkdownDialog(title,contentMD,buttons,defaultAction){return this._APIService.confirm.askSelectStringDialogue(contentMD,buttons,{title,defaultAction:null!=defaultAction?defaultAction:buttons[0],timeout:0})}get confirm(){return this._APIService.confirm}};rest_excludes=new Set(["$$slots","$$events","$$legacy"]);root36=from_html('<div class="dialog-host svelte-1slw0qc"><!></div>');$$css12={hash:"svelte-1slw0qc",code:'body.is-mobile .livesync-svelte-dialog-container {box-sizing:border-box;padding-top:var(--safe-area-inset-top, env(safe-area-inset-top, 0px));padding-right:var(--safe-area-inset-right, env(safe-area-inset-right, 0px));padding-bottom:var(--safe-area-inset-bottom, env(safe-area-inset-bottom, 0px));padding-left:var(--safe-area-inset-left, env(safe-area-inset-left, 0px));}body.is-mobile .livesync-svelte-dialog-container .modal {max-height:100%;}body.is-mobile .livesync-svelte-dialog-container .dialog-host > .button-group {background:var(--modal-background, var(--background-primary));bottom:0;padding-bottom:1px;position:sticky;z-index:1;}.dialog-host.svelte-1slw0qc {padding:20px;gap:0.5em;display:flex;flex-direction:column;padding-bottom:var(--keyboard-height, 0px);user-select:text;-webkit-user-select:text;}.dialog-host.svelte-1slw0qc button {margin-left:10px;}.dialog-host.svelte-1slw0qc .button-group {display:flex;flex-direction:column;gap:10px;margin-top:20px;}.dialog-host.svelte-1slw0qc .row {display:flex;flex-direction:row;justify-items:center;align-items:center;flex-wrap:wrap;}.dialog-host.svelte-1slw0qc .row > input[type="text"],\n .dialog-host.svelte-1slw0qc .row > input[type="password"],\n .dialog-host.svelte-1slw0qc .row > textarea,\n .dialog-host.svelte-1slw0qc .row > select {flex:1;margin-left:10px;min-width:10em;}.dialog-host.svelte-1slw0qc .row > input[type="password"] {-webkit-text-security:disc;}.dialog-host.svelte-1slw0qc .row > input[type="checkbox"] {margin-left:10px;margin-right:10px;}.dialog-host.svelte-1slw0qc label > span {display:block;width:8em;}.dialog-host.svelte-1slw0qc .note,\n .dialog-host.svelte-1slw0qc .note-important,\n .dialog-host.svelte-1slw0qc .note-error {padding:10px;margin-top:4px;margin-bottom:0.5lh;border-left:4px solid;}.dialog-host.svelte-1slw0qc .note {background-color:var(--interactive-hover);border-left-color:var(--interactive-accent);}.dialog-host.svelte-1slw0qc .note-important {background-color:var(--interactive-hover);border-left-color:var(--text-warning);}.dialog-host.svelte-1slw0qc .note-error {background-color:var(--interactive-hover);border-left-color:var(--text-error);}.dialog-host.svelte-1slw0qc hr {margin:0.7lh 0;}.dialog-host.svelte-1slw0qc details {gap:0.5em;padding-left:0.5em;border-left:2px solid var(--interactive-accent);}.dialog-host.svelte-1slw0qc summary::marker {display:none;content:"";}.dialog-host.svelte-1slw0qc summary {border-left:4px solid var(--interactive-accent);padding-left:0.5em;cursor:pointer;outline:none;}.dialog-host.svelte-1slw0qc details > summary::after {content:"⏷";float:right;margin-right:0.5em;}.dialog-host.svelte-1slw0qc details[open] > summary::after {content:"⏶";float:right;margin-right:0.5em;}.dialog-host.svelte-1slw0qc input:invalid,\n .dialog-host.svelte-1slw0qc textarea:invalid {border-color:var(--background-modifier-error);}.dialog-host.svelte-1slw0qc .sub-section {margin-left:1em;display:flex;flex-direction:column;gap:0.5em;}.dialog-host.svelte-1slw0qc .row > input[type="text"]:disabled,\n .dialog-host.svelte-1slw0qc .row > input[type="password"]:disabled,\n .dialog-host.svelte-1slw0qc .row > textarea:disabled,\n .dialog-host.svelte-1slw0qc .row > select:disabled {background-color:var(--background-secondary);}'};svelteDialogRenderer={mount:(dialogHost,target,props)=>mount(dialogHost,{target,props}),async unmount(component2){await unmount(component2)}};SvelteDialogSession=class{constructor(options){var _a13;this.surface=options.surface;this.context=options.context;this.dependencies=options.dependencies;this.dialogHost=options.dialogHost;this.component=options.component;this.initialData=options.initialData;this.renderer=null!=(_a13=options.renderer)?_a13:svelteDialogRenderer}onOpen(){var _a13;this.surface.contentEl.replaceChildren();null==(_a13=this.unregisterUnload)||_a13.call(this);this.unregisterUnload=void 0;this.pendingResult&&this.pendingResult.reject(new Error("Dialogue opened again"));this.result=void 0;const pendingResult=promiseWithResolvers();this.pendingResult=pendingResult;this.unregisterUnload=this.context.events.onceEvent(EVENT_PLUGIN_UNLOADED,()=>{if(this.pendingResult===pendingResult){this.pendingResult=void 0;pendingResult.reject(new Error("Plug-in unloaded"));this.surface.close()}});this.mountedDialog=this.renderer.mount(this.dialogHost,this.surface.contentEl,{onSetupContext:props=>{setupDialogContext({...props,context:this.context,services:this.dependencies})},setTitle:title=>{this.surface.setTitle(title)},closeDialog:()=>{this.surface.close()},setResult:result=>{this.result=result},getInitialData:()=>this.initialData,mountComponent:this.component})}waitForClose(){if(!this.pendingResult)throw new Error("Dialogue has not been opened");return this.pendingResult.promise}onClose(){var _a13,_b6;null==(_a13=this.unregisterUnload)||_a13.call(this);this.unregisterUnload=void 0;null==(_b6=this.pendingResult)||_b6.resolve(this.result);this.pendingResult=void 0;const mountedDialog=this.mountedDialog;this.mountedDialog=void 0;mountedDialog&&fireAndForget(()=>this.renderer.unmount(mountedDialog))}};SvelteDialogObsidian=class extends import_obsidian.Modal{constructor(context2,dependents,component2,initialData){super(context2.app);this.session=new SvelteDialogSession({surface:this,context:context2,dependencies:dependents,dialogHost:DialogHost,component:component2,initialData})}onOpen(){var _a13;this.session.onOpen();null==(_a13=this.contentEl.closest(".modal-container"))||_a13.classList.add("livesync-svelte-dialog-container")}onClose(){this.session.onClose()}waitForClose(){return this.session.waitForClose()}};ObsidianSvelteDialogManager=class extends SvelteDialogManagerBase{async openSvelteDialog(component2,initialData){const dialog=new SvelteDialogObsidian(this.context,this.dependents,component2,initialData);dialog.open();return await dialog.waitForClose()}};root37=from_html('<textarea readonly="" rows="4" class="svelte-14sk8z0"></textarea> <button><!></button>',1);root_130=from_html("<!> <!> <!> <!>",1);$$css13={hash:"svelte-14sk8z0",code:"textarea.svelte-14sk8z0 {resize:none;}"};delegate(["click"]);ObsidianUIService=class extends UIService{get dialogToCopy(){return DialogueToCopy}constructor(context2,dependents){const obsidianConfirm=dependents.APIService.confirm,obsidianSvelteDialogManager=new ObsidianSvelteDialogManager(context2,{appLifecycle:dependents.appLifecycle,config:dependents.config,replicator:dependents.replicator,confirm:obsidianConfirm,control:dependents.control});super(context2,{dialogManager:obsidianSvelteDialogManager,APIService:dependents.APIService})}};ScreenWakeLockManagerDisposedError=class extends Error{constructor(){super("The screen wake-lock manager has been disposed");this.name="ScreenWakeLockManagerDisposedError"}};instanceOfAny=(object,constructors)=>constructors.some(c3=>object instanceof c3);transactionDoneMap=new WeakMap;transformCache=new WeakMap;reverseTransformCache=new WeakMap;idbProxyTraps={get(target,prop2,receiver){if(target instanceof IDBTransaction){if("done"===prop2)return transactionDoneMap.get(target);if("store"===prop2)return receiver.objectStoreNames[1]?void 0:receiver.objectStore(receiver.objectStoreNames[0])}return wrap(target[prop2])},set(target,prop2,value){target[prop2]=value;return!0},has:(target,prop2)=>target instanceof IDBTransaction&&("done"===prop2||"store"===prop2)||prop2 in target};unwrap=value=>reverseTransformCache.get(value);readMethods=["get","getKey","getAll","getAllKeys","count"];writeMethods=["put","add","delete","clear"];cachedMethods=new Map;replaceTraps(oldTraps=>({...oldTraps,get:(target,prop2,receiver)=>getMethod(target,prop2)||oldTraps.get(target,prop2,receiver),has:(target,prop2)=>!!getMethod(target,prop2)||oldTraps.has(target,prop2)}));advanceMethodProps=["continue","continuePrimaryKey","advance"];methodMap={};advanceResults=new WeakMap;ittrProxiedCursorToOriginalProxy=new WeakMap;cursorIteratorTraps={get(target,prop2){if(!advanceMethodProps.includes(prop2))return target[prop2];let cachedFunc=methodMap[prop2];cachedFunc||(cachedFunc=methodMap[prop2]=function(...args){advanceResults.set(this,ittrProxiedCursorToOriginalProxy.get(this)[prop2](...args))});return cachedFunc}};replaceTraps(oldTraps=>({...oldTraps,get:(target,prop2,receiver)=>isIteratorProp(target,prop2)?iterate:oldTraps.get(target,prop2,receiver),has:(target,prop2)=>isIteratorProp(target,prop2)||oldTraps.has(target,prop2)}));databaseCache=new Map;IDBKeyValueDatabase=class{constructor(dbKey){this._dbPromise=null;this._isDestroyed=!1;this.destroyedPromise=null;this.dbKey=dbKey;this.storeKey=dbKey}get isDestroyed(){return this._isDestroyed}get ensuredDestroyed(){return this.destroyedPromise?this.destroyedPromise:Promise.resolve()}async getIsReady(){await this.ensureDB();return!1===this.isDestroyed}ensureDB(){if(this._isDestroyed)throw new Error("Database is destroyed");if(this._dbPromise)return this._dbPromise;this._dbPromise=openDB(this.dbKey,void 0,{upgrade:(db,_oldVersion,_newVersion,_transaction,_event)=>{if(!db.objectStoreNames.contains(this.storeKey))return db.createObjectStore(this.storeKey)},blocking:(currentVersion,blockedVersion,event2)=>{Logger(`Blocking database open for ${this.dbKey}: currentVersion=${currentVersion}, blockedVersion=${blockedVersion}`,LOG_LEVEL_VERBOSE);this.closeDB(!0)},blocked:(currentVersion,blockedVersion,event2)=>{Logger(`Database open blocked for ${this.dbKey}: currentVersion=${currentVersion}, blockedVersion=${blockedVersion}`,LOG_LEVEL_VERBOSE)},terminated:()=>{Logger(`Database connection terminated for ${this.dbKey}`,LOG_LEVEL_VERBOSE);this._dbPromise=null}}).catch(e3=>{this._dbPromise=null;throw e3});return this._dbPromise}async closeDB(setDestroyed=!1){if(this._dbPromise){const tempPromise=this._dbPromise;this._dbPromise=null;try{const dbR=await tempPromise;dbR.close()}catch(e3){Logger("Error closing database");Logger(e3,LOG_LEVEL_VERBOSE)}}this._dbPromise=null;if(setDestroyed){this._isDestroyed=!0;this.destroyedPromise=Promise.resolve()}}get DB(){return this._isDestroyed?Promise.reject(new Error("Database is destroyed")):this.ensureDB()}async get(key3){const db=await this.DB;return await db.get(this.storeKey,key3)}async set(key3,value){const db=await this.DB;await db.put(this.storeKey,value,key3);return key3}async del(key3){const db=await this.DB;return await db.delete(this.storeKey,key3)}async clear(){const db=await this.DB;return await db.clear(this.storeKey)}async keys(query3,count){const db=await this.DB;return await db.getAllKeys(this.storeKey,query3,count)}async close(){await this.closeDB()}async destroy(){this._isDestroyed=!0;this.destroyedPromise=(async()=>{await this.closeDB();await deleteDB(this.dbKey,{blocked:()=>{Logger(`Database delete blocked for ${this.dbKey}`)}})})();await this.destroyedPromise}};databaseCache2={};0;ObsidianNoticeGroupManager=class{constructor(manager=new KeyedNoticeGroupManager){this.manager=manager}setItem(groupKey,itemKey,item){this.manager.setItem(groupKey,itemKey,item)}finish(groupKey,options){return this.manager.finish(groupKey,options)}removeItem(groupKey,itemKey){return this.manager.removeItem(groupKey,itemKey)}hide(groupKey){return this.manager.hide(groupKey)}dispose(){this.manager.dispose()}};ObsidianServiceHub=class extends InjectableServiceHub{constructor(plugin2){const notices=new KeyedNoticeManager,noticeGroups=new ObsidianNoticeGroupManager,context2=new ObsidianServiceContext(plugin2.app,plugin2,plugin2,notices,noticeGroups),API=new ObsidianAPIService(context2),conflict=new ObsidianConflictService(context2),fileProcessing=new ObsidianFileProcessingService(context2),tweakValue=new ObsidianTweakValueService(context2),setting=new ObsidianSettingService(context2,{APIService:API,onDisplayLanguageChanged:setLang}),appLifecycle=new ObsidianAppLifecycleService(context2,{settingService:setting}),remote=new ObsidianRemoteService(context2,{pouchDB:index_es_default,APIService:API,appLifecycle,setting}),vault=new ObsidianVaultService(context2,{settingService:setting,APIService:API}),test=new ObsidianTestService(context2),databaseEvents=new ObsidianDatabaseEventService(context2),path2=new ObsidianPathService(context2,{settingService:setting}),screenWakeLock=createScreenWakeLockManager();appLifecycle.onUnload.addHandler(async()=>{await screenWakeLock.dispose();notices.dispose();noticeGroups.dispose();return!0});const database=new ObsidianDatabaseService(context2,{pouchDB:index_es_default,path:path2,vault,setting,API}),keyValueDB=new ObsidianKeyValueDBService(context2,{openKeyValueDatabase:OpenKeyValueDatabase,appLifecycle,databaseEvents,vault}),config=new ObsidianConfigService(context2,{settingService:setting,APIService:API}),replicator=new ObsidianReplicatorService(context2,{settingService:setting,appLifecycleService:appLifecycle,databaseEventService:databaseEvents,activityRunner:screenWakeLock,isMobile:()=>API.isMobile()}),replication2=new ObsidianReplicationService(context2,{APIService:API,appLifecycleService:appLifecycle,replicatorService:replicator,settingService:setting,fileProcessingService:fileProcessing,databaseService:database}),control=new ObsidianControlService(context2,{appLifecycleService:appLifecycle,databaseService:database,fileProcessingService:fileProcessing,settingService:setting,APIService:API,replicatorService:replicator}),ui=new ObsidianUIService(context2,{appLifecycle,config,replicator,APIService:API,control}),serviceInstancesToInit={appLifecycle,conflict,database,databaseEvents,fileProcessing,replication:replication2,replicator,remote,setting,tweakValue,vault,test,ui,path:path2,API,config,keyValueDB,control};super(context2,serviceInstancesToInit)}};ServiceModuleBase=class{constructor(services){__publicField(this,"_log");this._log=createInstanceLogFunction(this.name,services.API)}get name(){return this.constructor.name}};FAST_FETCH_CHANGES_PAGE_LIMIT=1e4;FAST_FETCH_CHANGES_PAGE_TIMEOUT_MS=1e3;StreamingFetchFailure=class extends Error{constructor(stage,message,retryable,options){super(message,void 0===(null==options?void 0:options.cause)?void 0:{cause:options.cause});__publicField(this,"stage");__publicField(this,"retryable");__publicField(this,"name","StreamingFetchFailure");__publicField(this,"status");this.stage=stage;this.retryable=retryable;this.status=null==options?void 0:options.status}};FAST_FETCH_CHECKPOINT_KEY="fast-fetch-checkpoint";FAST_FETCH_RETRY_DELAYS=[2e3,5e3,1e4,2e4];ServiceRebuilder=class extends ServiceModuleBase{constructor(services){super(services);__publicField(this,"events");__publicField(this,"appLifecycle");__publicField(this,"API");__publicField(this,"UI");__publicField(this,"setting");__publicField(this,"remote");__publicField(this,"databaseEvents");__publicField(this,"storageAccess");__publicField(this,"replicator");__publicField(this,"vault");__publicField(this,"replication");__publicField(this,"database");__publicField(this,"fileHandler");__publicField(this,"fileProcessing");__publicField(this,"control");this.events=services.events;this.appLifecycle=services.appLifecycle;this.API=services.API;this.UI=services.UI;this.setting=services.setting;this.remote=services.remote;this.databaseEvents=services.databaseEvents;this.storageAccess=services.storageAccess;this.replicator=services.replicator;this.vault=services.vault;this.replication=services.replication;this.database=services.database;this.fileHandler=services.fileHandler;this.fileProcessing=services.fileProcessing;this.control=services.control;services.database.onDatabaseReset.addHandler(this._onResetLocalDatabase.bind(this));services.setting.suspendAllSync.addHandler(this._allSuspendAllSync.bind(this))}async $performRebuildDB(method){"localOnly"==method&&await this.$fetchLocal();"localOnlyWithChunks"==method&&await this.$fetchLocal(!0);"remoteOnly"==method&&await this.$rebuildRemote();"rebuildBothByThisDevice"==method&&await this.$rebuildEverything()}async informOptionalFeatures(){await this.UI.showMarkdownDialog("All optional features are disabled","Customisation Sync and Hidden File Sync will all be disabled.\nPlease enable them from the settings screen after setup is complete.",["OK"])}async rebuildRemote(){await this.replicator.runBoundedRemoteActivity(()=>this.performRemoteRebuild(),{label:"rebuild-remote"});await this.informOptionalFeatures()}async performRemoteRebuild(){await this.setting.suspendExtraSync();await this.setting.applyPartial({isConfigured:!0,notifyThresholdOfRemoteStorageSize:DEFAULT_SETTINGS.notifyThresholdOfRemoteStorageSize});await this.control.applySettings();await this.replication.markLocked();await this._tryResetRemoteDatabase();await this.replication.markLocked();await delay(500);await delay(1e3);await this.replication.replicateAllToRemote(!0);await delay(1e3);await this.replication.replicateAllToRemote(!0)}$rebuildRemote(){return this.rebuildRemote()}async rebuildEverything(){await this.replicator.runBoundedRemoteActivity(()=>this.performRebuildEverything(),{label:"rebuild-everything"});await this.informOptionalFeatures()}async performRebuildEverything(){this.appLifecycle.resetIsReady();await this.setting.suspendExtraSync();await this.setting.applyPartial({isConfigured:!0,notifyThresholdOfRemoteStorageSize:DEFAULT_SETTINGS.notifyThresholdOfRemoteStorageSize});await this.control.applySettings();await this.resetLocalDatabase();await delay(1e3);await this.prepareLocalDatabaseForRebuild();if(this.setting.currentSettings().remoteType!==REMOTE_P2P){await this.replication.markLocked();await this._tryResetRemoteDatabase();await this.replication.markLocked();await delay(500);await delay(1e3);if(!await this.replication.replicateAllToRemoteForRebuild(!0))throw new Error("The first rebuild upload did not complete.");await delay(1e3);if(!await this.replication.replicateAllToRemoteForRebuild(!0))throw new Error("The final rebuild upload did not complete.");if(!await this.completePreparedRebuild())throw new Error("The rebuild could not be finalised.")}else if(!await this.completePreparedRebuild())throw new Error("The local P2P rebuild could not be finalised.")}$rebuildEverything(){return this.rebuildEverything()}$fetchLocal(makeLocalChunkBeforeSync,preventMakeLocalFilesBeforeSync){return this.fetchLocal(makeLocalChunkBeforeSync,preventMakeLocalFilesBeforeSync)}$fetchLocalDBFast(autoResume){return this.fetchLocalDBFast(autoResume)}async scheduleInitialisation(flag,prepareBeforeRestart){try{await this.storageAccess.writeFileAuto(flag,"")}catch(ex){this._log(`Could not create ${flag}`,LOG_LEVEL_NOTICE);this._log(ex,LOG_LEVEL_VERBOSE);return!1}this.appLifecycle.setSuspended(!0);try{await(null==prepareBeforeRestart?void 0:prepareBeforeRestart())}catch(ex){try{await this.storageAccess.delete(flag,!0)}catch(cleanupError){this._log(`Could not remove ${flag} after restart preparation failed`,LOG_LEVEL_NOTICE);this._log(cleanupError,LOG_LEVEL_VERBOSE)}this.appLifecycle.setSuspended(!1);throw ex}this.appLifecycle.performRestart();return!0}scheduleRebuild(prepareBeforeRestart){return this.scheduleInitialisation(FlagFilesHumanReadable_REBUILD_ALL,prepareBeforeRestart)}scheduleFetch(prepareBeforeRestart){return this.scheduleInitialisation(FlagFilesHumanReadable_FETCH_ALL,prepareBeforeRestart)}async _tryResetRemoteDatabase(){const currentReplicator=this.replicator.getActiveReplicator(),settings=this.setting.currentSettings();currentReplicator?await currentReplicator.tryResetRemoteDatabase(settings):this._log("No active replicator found when trying to reset remote database.",LOG_LEVEL_NOTICE)}_onResetLocalDatabase(){this.storageAccess.clearTouched();return Promise.resolve(!0)}async suspendAllSync(){await this.setting.applyPartial({liveSync:!1,periodicReplication:!1,syncOnSave:!1,syncOnEditorSave:!1,syncOnStart:!1,syncOnFileOpen:!1,syncAfterMerge:!1});await this.setting.suspendExtraSync()}async suspendReflectingDatabase(ignoreMinIO=!1){const settings=this.setting.currentSettings();if(!settings.doNotSuspendOnFetching&&(ignoreMinIO||settings.remoteType!=REMOTE_MINIO)){this._log("Suspending reflection: Database and storage changes will not be reflected in each other until completely finished the fetching.",LOG_LEVEL_NOTICE);await this.setting.applyPartial({suspendParseReplicationResult:!0,suspendFileWatching:!0});await this.setting.saveSettingData()}}async resumeReflectingDatabase(ignoreMinIO=!1){const settings=this.setting.currentSettings();if(settings.doNotSuspendOnFetching)return!0;if(!ignoreMinIO&&settings.remoteType==REMOTE_MINIO)return!0;this._log("Database and storage reflection has been resumed!",LOG_LEVEL_NOTICE);await this.setting.applyPartial({suspendParseReplicationResult:!1,suspendFileWatching:!1});return!!await this.vault.scanVault(!0)&&!!await this.replication.onBeforeReplicate(!1)}async prepareLocalDatabaseForRebuild(){if(!this.database.isDatabaseReady())throw new Error("The selected local database is not ready for rebuild preparation.");if(!await this.vault.scanVault(!0,!0))throw new Error("The Vault could not be scanned for rebuild preparation.");if(!await this.databaseEvents.onDatabaseInitialised(!0))throw new Error("The local database completion hooks failed during rebuild preparation.");if(!await this.fileProcessing.commitPendingFileEvents())throw new Error("The current file-event batch could not be released for rebuild preparation.")}async completePreparedRebuild(){this.appLifecycle.resetIsReady();if(!this.database.isDatabaseReady())return!1;if(!await this.fileProcessing.commitPendingFileEvents())return!1;this.appLifecycle.markIsReady();return!0}async fetchLocal(makeLocalChunkBeforeSync,preventMakeLocalFilesBeforeSync,autoResume=!0){await this.setting.suspendExtraSync();await this.setting.applyPartial({isConfigured:!0,notifyThresholdOfRemoteStorageSize:DEFAULT_SETTINGS.notifyThresholdOfRemoteStorageSize});const settings=this.setting.currentSettings();if(settings.maxMTimeForReflectEvents>0){const date2=new Date(settings.maxMTimeForReflectEvents),ask=`Your settings restrict file reflection times to no later than ${date2.toLocaleString()}.\n\n**This is a recovery configuration.**\n\nThis operation should only be performed on an empty vault.\nAre you sure you wish to proceed?`,PROCEED="I understand, proceed",CANCEL="Cancel operation",CLEARANDPROCEED="Clear restriction and proceed",choices=[PROCEED,CLEARANDPROCEED,CANCEL],ret=await this.UI.confirm.askSelectStringDialogue(ask,choices,{title:"Confirm restricted fetch",defaultAction:CANCEL,timeout:0});if(ret==CLEARANDPROCEED){await this.setting.applyPartial({maxMTimeForReflectEvents:0});await this.setting.saveSettingData()}if(ret==CANCEL)return}await this.replicator.runBoundedRemoteActivity(()=>this.performFetchLocal(makeLocalChunkBeforeSync,preventMakeLocalFilesBeforeSync,autoResume),{label:"rebuild-fetch"})}async performFetchLocal(makeLocalChunkBeforeSync,preventMakeLocalFilesBeforeSync,autoResume=!0){this.appLifecycle.resetIsReady();await this.suspendReflectingDatabase(!autoResume);await this.control.applySettings();await this.resetLocalDatabase();this.clearFastFetchCheckpoint();await delay(1e3);makeLocalChunkBeforeSync?await this.fileHandler.createAllChunks(!0):preventMakeLocalFilesBeforeSync||await this.prepareLocalDatabaseForRebuild();await this.replication.markResolved();await delay(500);if(!await this.replication.replicateAllFromRemoteForRebuild(!0))throw new Error("The first Standard Fetch pass did not complete.");if(this.setting.currentSettings().remoteType!==REMOTE_P2P){await delay(1e3);if(!await this.replication.replicateAllFromRemoteForRebuild(!0))throw new Error("The final Standard Fetch pass did not complete.")}if(autoResume&&!await this.finishRebuild())throw new Error("Standard Fetch could not be finalised.")}async fetchLocalDBFast(autoResume){await this.setting.suspendExtraSync();await this.setting.applyPartial({isConfigured:!0,notifyThresholdOfRemoteStorageSize:DEFAULT_SETTINGS.notifyThresholdOfRemoteStorageSize});const settings=this.setting.currentSettings();if(settings.remoteType===REMOTE_COUCHDB)if(settings.useRequestAPI){this._log("Fast database fetch is unavailable while 'Use Internal API' is enabled. Falling back to Standard Fetch.",LOG_LEVEL_NOTICE);await this.fetchLocal(!1,!0,autoResume)}else await this.replicator.runBoundedRemoteActivity(()=>this.performFetchLocalDBFast(settings,autoResume),{label:"fast-fetch"});else{this._log("Fast database fetch is available only for CouchDB remote. Falling back to standard fetch.",LOG_LEVEL_NOTICE);await this.fetchLocal(!1,!0,autoResume)}}async performFetchLocalDBFast(settings,autoResume){var _a13,_b6,_c3;this.appLifecycle.resetIsReady();const remote=settings.couchDB_URI.replace(/\/+$/,"")+(""==settings.couchDB_DBNAME?"":"/"+settings.couchDB_DBNAME);let checkpoint=this.getFastFetchCheckpoint(remote);await this.suspendReflectingDatabase();await this.control.applySettings();let since=null!=(_a13=null==checkpoint?void 0:checkpoint.sequence)?_a13:"0";if(checkpoint){this._log(`Resuming fast database fetch from sequence: ${checkpoint.sequence}`,LOG_LEVEL_NOTICE,"fetch-init-resume");if(!await this.database.openDatabase({databaseEvents:this.databaseEvents,replicator:this.replicator}))throw new Error("The selected local database could not be opened for Fast Fetch.")}else{await this.resetLocalDatabase();await delay(1e3)}let localDB=this.database.localDatabase.localDatabase;if(checkpoint&&0==(await localDB.info()).doc_count){this._log("Fast fetch checkpoint found, but the local database is empty. Starting from the beginning.",LOG_LEVEL_NOTICE,"fetch-init-resume");this.clearFastFetchCheckpoint();await this.resetLocalDatabase();await delay(1e3);localDB=this.database.localDatabase.localDatabase;since="0"}const replicator=null!=(_b6=this.replicator.getActiveReplicator())?_b6:await this.replicator.getNewReplicator();if(!replicator)throw new Error("No active replicator found for fast fetch.");const enc=getConfiguredFunctionsForEncryption(settings.passphrase,!1,!1,()=>replicator.getReplicationPBKDF2Salt(settings),settings.E2EEAlgorithm),authHeader=await(new AuthorizationHeaderGenerator).getAuthorizationHeader(generateCredentialObject(settings)),customHeaders=parseHeaderValues(settings.couchDB_CustomHeaders);for(let attempt=0;;attempt++)try{await fetchChangesForInitialSync(localDB,remote,authHeader,enc.outgoing,since,progress=>{this._log(`Fast fetch progress: ${progress.totalValidFetched} / ${progress.docsToFetch}\nTotal bytes fetched: ${sizeToHumanReadable(progress.totalBytes)}`,LOG_LEVEL_NOTICE,"fetch-init-progress")},sequence=>this.saveFastFetchCheckpoint(remote,sequence),customHeaders);break}catch(ex){if(!isRetryableStreamingFetchFailure(ex)||attempt>=FAST_FETCH_RETRY_DELAYS.length)throw ex;checkpoint=this.getFastFetchCheckpoint(remote);since=null!=(_c3=null==checkpoint?void 0:checkpoint.sequence)?_c3:since;this._log(`Fast fetch interrupted. Retrying from sequence: ${since}`,LOG_LEVEL_NOTICE,"fetch-init-resume");await delay(FAST_FETCH_RETRY_DELAYS[attempt])}const allDocs2=await localDB.allDocs({include_docs:!1});this._log(`Fast database fetch completed. Total documents in local database: ${allDocs2.total_rows}`,LOG_LEVEL_NOTICE,"fetch-init-complete");await this.replication.markResolved();if(autoResume&&!await this.finishRebuild())throw new Error("Fast Fetch could not be finalised.");this.clearFastFetchCheckpoint()}async finishRebuild(ignoreMinIO=!0){this.appLifecycle.resetIsReady();const settings=this.setting.currentSettings(),controlsReflection=!settings.doNotSuspendOnFetching&&(ignoreMinIO||settings.remoteType!==REMOTE_MINIO),previousReflectionState={suspendParseReplicationResult:settings.suspendParseReplicationResult,suspendFileWatching:settings.suspendFileWatching};let completed=!1;try{if(!this.database.isDatabaseReady())return!1;if(!await this.resumeReflectingDatabase(ignoreMinIO))return!1;if(!await this.fileProcessing.commitPendingFileEvents())return!1;controlsReflection&&await this.setting.saveSettingData();this.appLifecycle.markIsReady();completed=!0;return!0}finally{!completed&&controlsReflection&&await this.setting.applyPartial(previousReflectionState)}}async fetchLocalWithRebuild(){return await this.fetchLocal(!0)}async _allSuspendAllSync(){await this.suspendAllSync();return!0}async resetLocalDatabase(){const suffix=this.API.getAppID()||"";await this.setting.applyPartial({additionalSuffixOfDatabaseName:suffix});const reset2=await this.database.resetDatabaseForCurrentSettings({databaseEvents:this.databaseEvents,replicator:this.replicator});if(!reset2)throw new Error("The local database selected by the current settings could not be reset.");this.events.emitEvent(EVENT_DATABASE_REBUILT)}getFastFetchCheckpoint(remote){const rawCheckpoint=this.setting.getSmallConfig(FAST_FETCH_CHECKPOINT_KEY);if(rawCheckpoint){try{const checkpoint=JSON.parse(rawCheckpoint);if(checkpoint.remote===remote&&void 0!==checkpoint.sequence)return{remote,sequence:checkpoint.sequence}}catch(e3){}this.clearFastFetchCheckpoint()}}saveFastFetchCheckpoint(remote,sequence){this.setting.setSmallConfig(FAST_FETCH_CHECKPOINT_KEY,JSON.stringify({remote,sequence}))}clearFastFetchCheckpoint(){this.setting.deleteSmallConfig(FAST_FETCH_CHECKPOINT_KEY)}};ServiceDatabaseFileAccessBase=class extends ServiceModuleBase{constructor(services){super(services);__publicField(this,"events");__publicField(this,"vault");__publicField(this,"storageAccess");__publicField(this,"path");__publicField(this,"database");this.events=services.events;this.vault=services.vault;this.storageAccess=services.storageAccess;this.database=services.database;this.path=services.path}async checkIsTargetFile(file){const path2=getStoragePathFromUXFileInfo(file);if(!await this.vault.isTargetFile(path2)){this._log(`File is not target: ${path2}`,LOG_LEVEL_VERBOSE);return!1}if(shouldBeIgnored(path2)){this._log(`File should be ignored: ${path2}`,LOG_LEVEL_VERBOSE);return!1}return!0}async delete(file,rev3){if(!await this.checkIsTargetFile(file))return!0;const fullPath=getDatabasePathFromUXFileInfo(file);try{this._log(`deleteDB By path:${fullPath}`);return await this.deleteFromDBbyPath(fullPath,rev3)}catch(ex){this._log(`Failed to delete ${fullPath}`);this._log(ex,LOG_LEVEL_VERBOSE);return!1}}async createChunks(file,force=!1,skipCheck){return!1!==await this.__store(file,force,skipCheck,!0)}async store(file,force=!1,skipCheck){return!1!==await this.__store(file,force,skipCheck,!1)}async storeWithBaseRevision(file,baseRevision,skipCheck){const result=await this.__store(file,!0,skipCheck,!1,{mode:"force-base",baseRevision});return null!==result&&"object"==typeof result&&"rev"in result&&result.rev}async storeWithLiveBaseRevision(file,baseRevision,skipCheck){const result=await this.__store(file,!0,skipCheck,!1,{mode:"live-base",baseRevision});return null!==result&&"object"==typeof result&&"rev"in result&&result.rev}async storeAsConflictedRevision(file,currentRev,skipCheck){return!1!==await this.storeAsConflictedRevisionWithResult(file,currentRev,skipCheck)}async storeAsConflictedRevisionWithResult(file,currentRev,skipCheck){const conflictBaseRev=await this.getParentRev(file,currentRev);if(!conflictBaseRev){this._log(`Could not find parent revision for ${file.path} (${currentRev})`,LOG_LEVEL_VERBOSE);return!1}return await this.storeWithBaseRevision(file,conflictBaseRev,skipCheck)}async storeDeletionWithBaseRevision(file,baseRevision){if(!await this.checkIsTargetFile(file))return!1;const fullPath=getDatabasePathFromUXFileInfo(file),result=await this.database.localDatabase.storeDeletionAtRevision(fullPath,baseRevision);if(!1===result)return!1;this.events.emitEvent(EVENT_FILE_SAVED);return result.rev}async storeContent(path2,content){const blob=createTextBlob(content),bytes=(await blob.arrayBuffer()).byteLength,isInternal=!!path2.startsWith(".")||void 0,dummyUXFileInfo={name:path2.split("/").pop(),path:path2,stat:{size:bytes,ctime:Date.now(),mtime:Date.now(),type:"file"},body:blob,isInternal};return!1!==await this.__store(dummyUXFileInfo,!0,!1,!1)}async __store(file,force=!1,skipCheck,onlyChunks,revisionTarget={mode:"default"}){if(!skipCheck&&!await this.checkIsTargetFile(file))return!0;if(!file){this._log("File seems bad",LOG_LEVEL_VERBOSE);return!1}const isPlain=isPlainText(file.name),possiblyLarge=!isPlain,content=file.body,datatype=determineTypeFromBlob(content),idPrefix=file.isInternal?ICHeader:"",fullPath=getStoragePathFromUXFileInfo(file),fullPathOnDB=getDatabasePathFromUXFileInfo(file);possiblyLarge&&this._log(`Processing: ${fullPath}`,LOG_LEVEL_VERBOSE);if(file.isInternal)if(file.deleted)file.stat={size:0,ctime:Date.now(),mtime:Date.now(),type:"file"};else if(null==file.stat){const stat=await this.storageAccess.statHidden(file.path);if(!stat){this._log(`Internal file not found: ${fullPath}`,LOG_LEVEL_VERBOSE);return!1}file.stat=stat}const idMain=await this.path.path2id(fullPath),id=idPrefix+idMain,d4={_id:id,path:fullPathOnDB,data:content,ctime:file.stat.ctime,mtime:file.stat.mtime,size:file.stat.size,children:[],datatype,type:datatype,eden:{}},msg=`STORAGE -> DB (${datatype}) `,isNotChanged=await serialized("file-"+fullPath,async()=>{if("default"!==revisionTarget.mode)return!1;if(force){this._log(msg+"Force writing "+fullPath,LOG_LEVEL_VERBOSE);return!1}try{const old=await this.database.localDatabase.getDBEntry(d4.path,void 0,!1,!0,!1);if(!1!==old){const oldData={data:old.data,deleted:old._deleted||old.deleted},newData={data:d4.data,deleted:d4._deleted||d4.deleted};if(oldData.deleted!=newData.deleted)return!1;if(!await isDocContentSame(old.data,newData.data))return!1;this._log(msg+"Skipped (not changed) "+fullPath+(d4._deleted||d4.deleted?" (deleted)":""),LOG_LEVEL_VERBOSE);this.path.markChangesAreSame(old,d4.mtime,old.mtime);return!0}}catch(ex){this._log(msg+"Error, Could not check the diff for the old one."+(force?"force writing.":"")+fullPath+(d4._deleted||d4.deleted?" (deleted)":""),LOG_LEVEL_VERBOSE);this._log(ex,LOG_LEVEL_VERBOSE);return!force}return!1});if(isNotChanged){this._log(msg+" Skip "+fullPath,LOG_LEVEL_VERBOSE);return!0}const ret="live-base"===revisionTarget.mode?await this.database.localDatabase.putDBEntryWithLiveBaseRevision(d4,revisionTarget.baseRevision,onlyChunks):await this.database.localDatabase.putDBEntry(d4,onlyChunks,"force-base"===revisionTarget.mode?revisionTarget.baseRevision:void 0);if(!1!==ret){this._log(msg+fullPath);this.events.emitEvent(EVENT_FILE_SAVED)}return ret}async getParentRev(file,rev3){const filename=getDatabasePathFromUXFileInfo(file);try{const doc=await this.database.localDatabase.getDBEntryMeta(filename,{rev:rev3,revs:!0},!0);if(!1===doc)return!1;const revisions=doc._revisions;return!(!revisions||revisions.ids.length<2)&&`${revisions.start-1}-${revisions.ids[1]}`}catch(ex){this._log(`Could not read revision history for ${filename} (${rev3})`,LOG_LEVEL_VERBOSE);this._log(ex,LOG_LEVEL_VERBOSE);return!1}}async findContentRevisionsInternal(file,content,currentRev,stopAfterFirstMatch=!1){var _a13;const filename=getDatabasePathFromUXFileInfo(file);try{const doc=await this.database.localDatabase.getDBEntryMeta(filename,{rev:currentRev,revs_info:!0},!0);if(!1===doc)return[];const revisions=doc._revs_info,availableRevs=new Set((revisions||[]).filter(e3=>"available"===e3.status).map(e3=>e3.rev));currentRev&&availableRevs.add(currentRev);const leaves=await this.database.localDatabase.getRaw(doc._id,{open_revs:"all"});if(!Array.isArray(leaves))return[];for(const leaf of leaves){const leafRev=null==(_a13=leaf.ok)?void 0:_a13._rev;if(!leafRev)continue;const branch2=await this.database.localDatabase.getDBEntryMeta(filename,{rev:leafRev,revs_info:!0},!0);if(!1===branch2)continue;const branchRevisions=branch2._revs_info;for(const revision of branchRevisions||[])"available"===revision.status&&availableRevs.add(revision.rev)}const matchingRevisions=[];for(const rev3 of availableRevs){const entry=await this.database.localDatabase.getDBEntry(filename,{rev:rev3},!1,!0,!0);if(!1!==entry&&!entry._deleted&&await isDocContentSame(readContent(entry),content)){matchingRevisions.push(rev3);if(stopAfterFirstMatch)return matchingRevisions}}return matchingRevisions}catch(ex){this._log(`Could not check revision history for ${filename}`,LOG_LEVEL_VERBOSE);this._log(ex,LOG_LEVEL_VERBOSE)}return[]}async findContentRevisions(file,content,currentRev){return await this.checkIsTargetFile(file)?await this.findContentRevisionsInternal(file,content,currentRev):[]}async hasContentInRevisionHistory(file,content,currentRev){return!await this.checkIsTargetFile(file)||(await this.findContentRevisionsInternal(file,content,currentRev,!0)).length>0}async getConflictedRevs(file){if(!await this.checkIsTargetFile(file))return[];const filename=getDatabasePathFromUXFileInfo(file),doc=await this.database.localDatabase.getDBEntryMeta(filename,{conflicts:!0},!0);return!1===doc?[]:doc._conflicts||[]}async fetch(file,rev3,waitForReady,skipCheck=!1){if(skipCheck&&!await this.checkIsTargetFile(file))return!1;const entry=await this.fetchEntry(file,rev3,waitForReady,!0);if(!1===entry)return!1;const data=createBlob(readContent(entry)),path2=stripAllPrefixes(entry.path),fileInfo={name:path2.split("/").pop(),path:path2,stat:{size:entry.size,ctime:entry.ctime,mtime:entry.mtime,type:"file"},body:data,deleted:entry.deleted||entry._deleted};isInternalMetadata(entry.path)&&(fileInfo.isInternal=!0);return fileInfo}async fetchEntryMeta(file,rev3,skipCheck=!1){const dbFileName=getDatabasePathFromUXFileInfo(file);if(skipCheck&&!await this.checkIsTargetFile(file))return!1;const doc=await this.database.localDatabase.getDBEntryMeta(dbFileName,rev3?{rev:rev3}:void 0,!0);return!1!==doc&&doc}async fetchEntryFromMeta(meta,waitForReady=!0,skipCheck=!1){if(skipCheck&&!await this.checkIsTargetFile(meta.path))return!1;const doc=await this.database.localDatabase.getDBEntryFromMeta(meta,!1,waitForReady);return!1!==doc&&doc}async fetchEntry(file,rev3,waitForReady=!0,skipCheck=!1){if(skipCheck&&!await this.checkIsTargetFile(file))return!1;const entry=await this.fetchEntryMeta(file,rev3,!0);if(!1===entry)return!1;const doc=await this.fetchEntryFromMeta(entry,waitForReady,!0);return doc}async deleteFromDBbyPath(fullPath,rev3){if(!await this.checkIsTargetFile(fullPath)){this._log(`deleteFromDBbyPath: File is not target: ${fullPath}`);return!0}const opt=rev3?{rev:rev3}:void 0,ret=await this.database.localDatabase.deleteDBEntry(fullPath,opt);this.events.emitEvent(EVENT_FILE_SAVED);return ret}};ServiceDatabaseFileAccess=class extends ServiceDatabaseFileAccessBase{};StorageEventManager=class{};ServiceFileAccessBase=class extends ServiceModuleBase{constructor(services){super(services);__publicField(this,"vaultAccess");__publicField(this,"vaultManager");__publicField(this,"vault");__publicField(this,"setting");this.vault=services.vault;this.setting=services.setting;this.vaultManager=services.storageEventManager;this.vaultAccess=services.vaultAccess;services.appLifecycle.onFirstInitialise.addHandler(this._everyOnFirstInitialize.bind(this));services.fileProcessing.commitPendingFileEvents.addHandler(this._everyCommitPendingFileEvent.bind(this))}restoreState(){return this.vaultManager.restoreState()}async _everyOnFirstInitialize(){await this.vaultManager.beginWatch();return Promise.resolve(!0)}async _everyCommitPendingFileEvent(){await this.vaultManager.waitForIdle();return Promise.resolve(!0)}normalisePath(path2){return this.vaultAccess.normalisePath(path2)}async writeFileAuto(path2,data,opt){const file=await this.vaultAccess.getAbstractFileByPath(path2);if(this.vaultAccess.isFile(file))return this.vaultAccess.vaultModify(file,data,opt);if(null!==file){this._log(`Could not write file (Possibly already exists as a folder): ${path2}`,LOG_LEVEL_VERBOSE);return!1}if(!path2.endsWith(".md")){await this.vaultAccess.adapterWrite(path2,data,opt);return await this.vaultAccess.adapterExists(path2)}try{return null!==await this.vaultAccess.vaultCreate(path2,data,opt)}catch(ex){if(ex instanceof Error&&"File already exists."===ex.message){await this.vaultAccess.adapterWrite(path2,data,opt);return await this.vaultAccess.adapterExists(path2)}throw ex}}async readFileAuto(path2){const file=await this.vaultAccess.getAbstractFileByPath(path2);if(this.vaultAccess.isFile(file))return this.vaultAccess.vaultReadAuto(file);throw new Error(`Could not read file (Possibly does not exist): ${path2}`)}async readFileText(path2){const file=await this.vaultAccess.getAbstractFileByPath(path2);if(this.vaultAccess.isFile(file))return this.vaultAccess.vaultRead(file);throw new Error(`Could not read file (Possibly does not exist): ${path2}`)}async isExists(path2){return this.vaultAccess.isFile(await this.vaultAccess.getAbstractFileByPath(path2))}async renameFile(file,newPath){const oldPath="string"==typeof file?file:file.path,nativeFile=await this.vaultAccess.getAbstractFileByPath(oldPath);if(!this.vaultAccess.isFile(nativeFile)){this._log(`Could not rename file (Possibly does not exist): ${oldPath}`,LOG_LEVEL_VERBOSE);return null}const renamedNativeFile=await this.vaultAccess.vaultRename(nativeFile,newPath),renamedFile=this.vaultAccess.nativeFileToUXFileInfoStub(renamedNativeFile);await this.touched(renamedFile);return renamedFile}async writeHiddenFileAuto(path2,data,opt){try{await this.vaultAccess.adapterWrite(path2,data,opt);return!0}catch(e3){this._log(`Could not write hidden file: ${path2}`,LOG_LEVEL_VERBOSE);this._log(e3,LOG_LEVEL_VERBOSE);return!1}}async appendHiddenFile(path2,data,opt){try{await this.vaultAccess.adapterAppend(path2,data,opt);return!0}catch(e3){this._log(`Could not append hidden file: ${path2}`,LOG_LEVEL_VERBOSE);this._log(e3,LOG_LEVEL_VERBOSE);return!1}}async stat(path2){const file=await this.vaultAccess.getAbstractFileByPath(path2);if(null===file)return Promise.resolve(null);if(this.vaultAccess.isFile(file)){const fileWithStat=file;return Promise.resolve({ctime:fileWithStat.stat.ctime,mtime:fileWithStat.stat.mtime,size:fileWithStat.stat.size,type:"file"})}throw new Error(`Could not stat file (Possibly does not exist): ${path2}`)}statHidden(path2){return this.vaultAccess.tryAdapterStat(path2)}async removeHidden(path2){try{await this.vaultAccess.adapterRemove(path2);return null===this.vaultAccess.tryAdapterStat(path2)}catch(e3){this._log(`Could not remove hidden file: ${path2}`,LOG_LEVEL_VERBOSE);this._log(e3,LOG_LEVEL_VERBOSE);return!1}}async readHiddenFileAuto(path2){return await this.vaultAccess.adapterReadAuto(path2)}async readHiddenFileText(path2){return await this.vaultAccess.adapterRead(path2)}async readHiddenFileBinary(path2){return await this.vaultAccess.adapterReadBinary(path2)}async isExistsIncludeHidden(path2){return null!==await this.vaultAccess.tryAdapterStat(path2)}async ensureDir(path2){try{await this.vaultAccess.ensureDirectory(path2);return!0}catch(e3){this._log(`Could not ensure directory: ${path2}`,LOG_LEVEL_VERBOSE);this._log(e3,LOG_LEVEL_VERBOSE);return!1}}async _triggerFileEvent(event2,path2){const file=await this.vaultAccess.getAbstractFileByPath(path2);null!==file&&this.vaultAccess.trigger(event2,file)}triggerFileEvent(event2,path2){fireAndForget(async()=>await this._triggerFileEvent(event2,path2))}async triggerHiddenFile(path2){await this.vaultAccess.reconcileInternalFile(path2)}async getFileStub(path2){const file=await this.vaultAccess.getAbstractFileByPath(path2);return this.vaultAccess.isFile(file)?this.vaultAccess.nativeFileToUXFileInfoStub(file):null}async readStubContent(stub){const file=await this.vaultAccess.getAbstractFileByPath(stub.path);if(!this.vaultAccess.isFile(file)){this._log(`Could not read file (Possibly does not exist or a folder): ${stub.path}`,LOG_LEVEL_VERBOSE);return!1}const data=await this.vaultAccess.vaultReadAuto(file);return{...stub,...this.vaultAccess.nativeFileToUXFileInfoStub(file),body:createBlob(data)}}async getStub(path2){const file=await this.vaultAccess.getAbstractFileByPath(path2);return this.vaultAccess.isFile(file)?this.vaultAccess.nativeFileToUXFileInfoStub(file):this.vaultAccess.isFolder(file)?this.vaultAccess.nativeFolderToUXFolder(file):null}async getFiles(){const files=await this.vaultAccess.getFiles();return files.map(f4=>this.vaultAccess.nativeFileToUXFileInfoStub(f4))}async getFileNames(){const files=await this.vaultAccess.getFiles();return files.map(f4=>f4.path)}async getFilesIncludeHidden(basePath,includeFilter,excludeFilter,skipFolder=[".git",".trash","node_modules"]){var _a13;let w2;try{w2=await this.vaultAccess.adapterList(basePath)}catch(ex){this._log(`Could not traverse(getFilesIncludeHidden):${basePath}`,LOG_LEVEL_INFO);this._log(ex,LOG_LEVEL_VERBOSE);return[]}skipFolder=skipFolder.map(e3=>e3.toLowerCase());let files=[];for(const file of w2.files)includeFilter&&includeFilter.length>0&&!includeFilter.some(e3=>e3.test(file))||excludeFilter&&excludeFilter.some(ee=>ee.test(file))||await this.vault.isIgnoredByIgnoreFile(file)||files.push(file);for(const v2 of w2.folders){const folderName=(null!=(_a13=v2.split("/").pop())?_a13:"").toLowerCase();skipFolder.some(e3=>folderName===e3)||(excludeFilter&&excludeFilter.some(e3=>e3.test(v2))||await this.vault.isIgnoredByIgnoreFile(v2)||(files=files.concat(await this.getFilesIncludeHidden(v2,includeFilter,excludeFilter,skipFolder))))}return files}async touched(file){const path2="string"==typeof file?file:file.path;await this.vaultAccess.touch(path2)}async recentlyTouched(file){const xFile="string"==typeof file?await this.vaultAccess.getAbstractFileByPath(file):file;return null!==xFile&&(!this.vaultAccess.isFolder(xFile)&&this.vaultAccess.recentlyTouched(xFile))}clearTouched(){this.vaultAccess.clearTouched()}async delete(file,force){const xPath="string"==typeof file?file:file.path,xFile=await this.vaultAccess.getAbstractFileByPath(xPath);return null===xFile?Promise.resolve():this.vaultAccess.isFile(xFile)||this.vaultAccess.isFolder(xFile)?this.vaultAccess.delete(xFile,force):Promise.resolve()}async trash(file,system){const xPath="string"==typeof file?file:file.path,xFile=await this.vaultAccess.getAbstractFileByPath(xPath);return null===xFile?Promise.resolve():this.vaultAccess.isFile(xFile)||this.vaultAccess.isFolder(xFile)?this.vaultAccess.trash(xFile,system):Promise.resolve()}async __deleteVaultItem(file){var _a13,_b6,_c3,_d2;const filePath=this.vaultAccess.getPath(file);if(this.vaultAccess.isFile(file)&&!await this.vault.isTargetFile(filePath))return;const dir=file.parent,settings=this.setting.currentSettings();settings.trashInsteadDelete?await this.vaultAccess.trash(file,!1):await this.vaultAccess.delete(file,!0);this._log(`xxx <- STORAGE (deleted) ${filePath}`);if(dir){this._log(`files: ${null!=(_b6=null==(_a13=null==dir?void 0:dir.children)?void 0:_a13.length)?_b6:"unknown"}`);if(0===(null!=(_d2=null==(_c3=null==dir?void 0:dir.children)?void 0:_c3.length)?_d2:0)&&!settings.doNotDeleteFolder){this._log(`All files under the parent directory (${dir.path}) have been deleted, so delete this one.`);await this.__deleteVaultItem(dir)}}}async deleteVaultItem(fileSrc){const path2="string"==typeof fileSrc?fileSrc:fileSrc.path,file=await this.vaultAccess.getAbstractFileByPath(path2);if(null!==file)return this.vaultAccess.isFile(file)||this.vaultAccess.isFolder(file)?await this.__deleteVaultItem(file):void 0}};ServiceFileAccessObsidian=class extends ServiceFileAccessBase{};fileLockPrefix="file-lock:";StorageAccessManager=class{constructor(){__publicField(this,"processingFiles",new Set);__publicField(this,"touchedFiles",[])}processWriteFile(file,proc){const path2="string"==typeof file?file:file.path;return serialized(`${fileLockPrefix}${path2}`,async()=>{try{this.processingFiles.add(path2);return await proc()}finally{this.processingFiles.delete(path2)}})}processReadFile(file,proc){const path2="string"==typeof file?file:file.path;return serialized(`${fileLockPrefix}${path2}`,async()=>{try{this.processingFiles.add(path2);return await proc()}finally{this.processingFiles.delete(path2)}})}isFileProcessing(file){const path2="string"==typeof file?file:file.path;return this.processingFiles.has(path2)}touch(file){const key3="stat"in file?`${file.path}-${file.stat.mtime}-${file.stat.size}`:`${file.path}-${file.mtime}-${file.size}`;this.touchedFiles.unshift(key3);this.touchedFiles=this.touchedFiles.slice(0,100)}recentlyTouched(file){const key3="stat"in file?`${file.path}-${file.stat.mtime}-${file.stat.size}`:`${file.path}-${file.mtime}-${file.size}`;return-1!=this.touchedFiles.indexOf(key3)}clearTouched(){this.touchedFiles=[]}};ServiceFileHandlerBase=class extends ServiceModuleBase{constructor(services){super(services);__publicField(this,"events");__publicField(this,"databaseFileAccess");__publicField(this,"storageAccess");__publicField(this,"conflict");__publicField(this,"path");__publicField(this,"setting");__publicField(this,"vault");__publicField(this,"fileReflectionProvenance");this.events=services.events;this.databaseFileAccess=services.databaseFileAccess;this.storageAccess=services.storageAccess;this.conflict=services.conflict;this.path=services.path;this.setting=services.setting;this.vault=services.vault;this.fileReflectionProvenance=services.fileReflectionProvenance;services.fileProcessing.processFileEvent.addHandler(this._anyHandlerProcessesFileEvent.bind(this),100);services.replication.processSynchroniseResult.addHandler(this._anyProcessReplicatedDoc.bind(this),100)}get db(){return this.databaseFileAccess}get storage(){return this.storageAccess}async getProvenance(path2){if(this.fileReflectionProvenance)try{const record=await this.fileReflectionProvenance.get(path2);if(!record)return;const entry=await this.db.fetchEntryMeta(path2,record.revision,!0);if(entry&&!entry._deleted&&!entry.deleted)return record;await this.fileReflectionProvenance.delete(path2)}catch(ex){this._log(`Could not read file reflection provenance for ${path2}`,LOG_LEVEL_VERBOSE);this._log(ex,LOG_LEVEL_VERBOSE)}}async setProvenance(path2,revision,observedStorageMtime){if(this.fileReflectionProvenance&&revision)try{await this.fileReflectionProvenance.set(path2,{revision,observedStorageMtime})}catch(ex){this._log(`Could not record file reflection provenance for ${path2}`,LOG_LEVEL_VERBOSE);this._log(ex,LOG_LEVEL_VERBOSE)}}async deleteProvenance(path2){if(this.fileReflectionProvenance)try{await this.fileReflectionProvenance.delete(path2)}catch(ex){this._log(`Could not delete file reflection provenance for ${path2}`,LOG_LEVEL_VERBOSE);this._log(ex,LOG_LEVEL_VERBOSE)}}async findUniqueContentRevision(file){try{const revisions=await this.db.findContentRevisions(file,file.body);return 1===revisions.length?revisions[0]:void 0}catch(ex){this._log(`Could not reconstruct file reflection provenance for ${file.path}`,LOG_LEVEL_VERBOSE);this._log(ex,LOG_LEVEL_VERBOSE);return}}async getProvenBaseRevision(file,preferredPath){var _a13;const path2=null!=preferredPath?preferredPath:file.path,recorded=null!=(_a13=await this.getProvenance(path2))?_a13:preferredPath&&preferredPath!==file.path?await this.getProvenance(file.path):void 0;if(recorded)return recorded.revision;const matched=await this.findUniqueContentRevision(file);if(matched){await this.setProvenance(path2,matched,file.stat.mtime);return matched}}getPath(entry){return this.path.getPath(entry)}getPathWithoutPrefix(entry){return stripAllPrefixes(this.path.getPath(entry))}async readFileFromStub(file){if("body"in file&&file.body)return file;const readFile=await this.storage.readStubContent(file);if(!readFile)throw new Error(`File ${file.path} is not exist on the storage`);return readFile}async infoToStub(info3){if(null==info3)return null;const file="string"==typeof info3?await this.storage.getFileStub(info3):info3;return file}async storeFileToDB(info3,force=!1,onlyChunks=!1){return await this.storeFileToDBFromRevision(info3,force,onlyChunks)}async storeFileToDBWithBaseRevision(info3,baseRevision,createIfDifferent=!0){const file=await this.infoToStub(info3);if(null==file){this._log(`File ${tryGetFilePath(info3)} is not exist on the storage`,LOG_LEVEL_VERBOSE);return!1}if(file.isInternal){this._log(`Internal file ${file.path} is not allowed to be stored through the ordinary file handler`,LOG_LEVEL_VERBOSE);return!1}const[baseEntry,currentEntry,conflictedRevisions]=await Promise.all([this.db.fetchEntryMeta(file,baseRevision,!0),this.db.fetchEntryMeta(file,void 0,!0),this.db.getConflictedRevs(file)]),liveRevisions=new Set([...currentEntry&&currentEntry._rev?[currentEntry._rev]:[],...conflictedRevisions]);if(!baseEntry||baseEntry._rev!==baseRevision||!liveRevisions.has(baseRevision)){this._log(`Could not store ${file.path} on revision ${baseRevision}; the selected revision is no longer live`,LOG_LEVEL_NOTICE);return!1}const readFile=await this.readFileFromStub(file);if(!baseEntry.deleted&&!baseEntry._deleted){const loadedBase=await this.db.fetchEntry(file,baseRevision,!0,!0);if(loadedBase&&await isDocContentSame(getDocDataAsArray(loadedBase.data),readFile.body)){await this.setProvenance(file.path,baseRevision,readFile.stat.mtime);await this.conflict.queueCheckFor(file.path);return!0}}if(!createIfDifferent){this._log(`Could not mark ${file.path} as revision ${baseRevision}; the storage content differs`,LOG_LEVEL_NOTICE);return!1}const storedRevision=await this.db.storeWithBaseRevision(readFile,baseRevision,!0);if(!1===storedRevision)return!1;await this.setProvenance(file.path,storedRevision,readFile.stat.mtime);await this.conflict.queueCheckFor(file.path);return!0}async storeFileToDBFromRevision(info3,force=!1,onlyChunks=!1,preferredBasePath){const file=await this.infoToStub(info3);if(null==file){this._log(`File ${tryGetFilePath(info3)} is not exist on the storage`,LOG_LEVEL_VERBOSE);return!1}if(file.isInternal){this._log(`Internal file ${file.path} is not allowed to be processed on processFileEvent`,LOG_LEVEL_VERBOSE);return!1}if(onlyChunks){const readFile2=await this.readFileFromStub(file);return await this.db.createChunks(readFile2,force,!0)}const readFile=await this.readFileFromStub(file),entry=await this.db.fetchEntry(file,void 0,!0,!0),conflictedRevs=await this.db.getConflictedRevs(file),isConflicted=conflictedRevs.length>0;if(isConflicted){const baseRevision=await this.getProvenBaseRevision(readFile,preferredBasePath);if(baseRevision){const baseEntry=await this.db.fetchEntry(file,baseRevision,!0,!0);if(baseEntry&&await isDocContentSame(getDocDataAsArray(baseEntry.data),readFile.body)&&!force){await this.setProvenance(file.path,baseRevision,readFile.stat.mtime);this._log(`File ${file.path} is not changed on its displayed conflict branch`,LOG_LEVEL_VERBOSE);return!0}const storedRevision3=await this.db.storeWithBaseRevision(readFile,baseRevision,!0);if(!1===storedRevision3)return!1;preferredBasePath&&preferredBasePath!==file.path&&await this.deleteProvenance(preferredBasePath);await this.setProvenance(file.path,storedRevision3,readFile.stat.mtime);await this.conflict.queueCheckFor(file.path);return!0}const currentEntry=entry||await this.db.fetchEntryMeta(file,void 0,!0),currentRevision=currentEntry&&currentEntry._rev;if(!currentRevision){this._log(`Could not preserve the unknown conflict branch for ${file.path}; no current revision is available`,LOG_LEVEL_NOTICE);await this.conflict.queueCheckFor(file.path);return!1}const storedRevision2=await this.db.storeAsConflictedRevisionWithResult(readFile,currentRevision,!0);if(!1===storedRevision2){this._log(`Could not preserve the unknown conflict branch for ${file.path}`,LOG_LEVEL_NOTICE);await this.conflict.queueCheckFor(file.path);return!1}preferredBasePath&&preferredBasePath!==file.path&&await this.deleteProvenance(preferredBasePath);await this.setProvenance(file.path,storedRevision2,readFile.stat.mtime);await this.conflict.queueCheckFor(file.path);return!0}if(!entry||entry.deleted||entry._deleted){const storedRevision2=await this.db.storeWithBaseRevision(readFile,entry&&entry._rev,!0);if(!1===storedRevision2)return!1;preferredBasePath&&preferredBasePath!==file.path&&await this.deleteProvenance(preferredBasePath);await this.setProvenance(file.path,storedRevision2,readFile.stat.mtime);return!0}let shouldApplied=!1;if(!force&&!onlyChunks){this.path.compareFileFreshness(file,entry)!==EVEN&&(shouldApplied=!0);shouldApplied||(await isDocContentSame(getDocDataAsArray(entry.data),readFile.body)?this.path.markChangesAreSame(readFile,readFile.stat.mtime,entry.mtime):shouldApplied=!0);if(!shouldApplied){await this.setProvenance(file.path,entry._rev,readFile.stat.mtime);this._log(`File ${file.path} is not changed`,LOG_LEVEL_VERBOSE);return!0}}const storedRevision=await this.db.storeWithBaseRevision(readFile,entry._rev,!0);if(!1===storedRevision)return!1;preferredBasePath&&preferredBasePath!==file.path&&await this.deleteProvenance(preferredBasePath);await this.setProvenance(file.path,storedRevision,readFile.stat.mtime);return!0}async deleteFileFromDB(info3){var _a13;const file=await this.infoToStub(info3),path2="string"==typeof info3?info3:tryGetFilePath(info3);if(null==file){if(void 0===path2){this._log(`File ${tryGetFilePath(info3)} is not exist on the storage`,LOG_LEVEL_VERBOSE);return!1}const entryByPath=await this.db.fetchEntry(path2,void 0,!0,!0);if(!entryByPath||entryByPath.deleted||entryByPath._deleted){this._log(`File ${path2} is not exist on the storage nor the database (or already deleted)`,LOG_LEVEL_VERBOSE);return!1}const conflictedRevs2=await this.db.getConflictedRevs(path2);if(conflictedRevs2.length>0){const provenance=await this.getProvenance(path2);if(!provenance){this._log(`The deleted storage file ${path2} has conflicts, but its displayed revision is unknown; preserving every database branch`,LOG_LEVEL_NOTICE);await this.conflict.queueCheckFor(path2);return!0}const storedRevision=await this.db.storeDeletionWithBaseRevision(path2,provenance.revision);if(!1===storedRevision)return!1;await this.deleteProvenance(path2);await this.conflict.queueCheckFor(path2);return!0}this._log(`File ${path2} is missing on storage; deleting from the database by path`,LOG_LEVEL_INFO);const deleted2=await this.db.delete(path2);deleted2&&await this.deleteProvenance(path2);return deleted2}if(file.isInternal){this._log(`Internal file ${file.path} is not allowed to be processed on processFileEvent`,LOG_LEVEL_VERBOSE);return!1}const entry=await this.db.fetchEntry(file,void 0,!0,!0);if(!entry||entry.deleted||entry._deleted){this._log(`File ${file.path} is not exist or already deleted on the database`,LOG_LEVEL_VERBOSE);return!1}const conflictedRevs=await this.db.getConflictedRevs(file);if(conflictedRevs.length>0){let baseRevision=null==(_a13=await this.getProvenance(file.path))?void 0:_a13.revision;if(!baseRevision)try{const readFile=await this.readFileFromStub(file);baseRevision=await this.findUniqueContentRevision(readFile)}catch(e3){}if(!baseRevision){this._log(`The deleted storage file ${file.path} has conflicts, but its displayed revision is unknown; preserving every database branch`,LOG_LEVEL_NOTICE);await this.conflict.queueCheckFor(file.path);return!0}const storedRevision=await this.db.storeDeletionWithBaseRevision(file.path,baseRevision);if(!1===storedRevision)return!1;await this.deleteProvenance(file.path);await this.conflict.queueCheckFor(file.path);return!0}const deleted=await this.db.delete(file);deleted&&await this.deleteProvenance(file.path);return deleted}async renameFileInDB(info3,oldPath){var _a13;const newPath=getStoragePathFromUXFileInfo(info3),[oldDocumentId,newDocumentId]=await Promise.all([this.path.path2id(oldPath),this.path.path2id(newPath)]);if(oldDocumentId===newDocumentId){this._log(`Updating the stored path for case-only rename: ${oldPath} -> ${newPath}`,LOG_LEVEL_VERBOSE);return await this.storeFileToDBFromRevision(info3,!0,!1,oldPath)}const oldEntry=await this.db.fetchEntryMeta(oldPath,void 0,!0),newEntry=await this.db.fetchEntryMeta(newPath,void 0,!0);if(newEntry&&!newEntry.deleted&&!newEntry._deleted){this._log(`Refusing to overwrite the existing database entry while renaming ${oldPath} to ${newPath}`,LOG_LEVEL_NOTICE);return!1}if(!await this.storeFileToDB(info3,!0)){this._log(`Failed to store rename target; preserving source in the database: ${oldPath}`,LOG_LEVEL_NOTICE);return!1}if(!oldEntry||oldEntry.deleted||oldEntry._deleted){this._log(`Rename source is not present in the database: ${oldPath}`,LOG_LEVEL_VERBOSE);return!0}const oldConflicts=await this.db.getConflictedRevs(oldPath);if(oldConflicts.length>0){let baseRevision=null==(_a13=await this.getProvenance(oldPath))?void 0:_a13.revision;if(!baseRevision){const readFile=await this.readFileFromStub(info3),revisions=await this.db.findContentRevisions(oldPath,readFile.body);baseRevision=1===revisions.length?revisions[0]:void 0}if(!baseRevision){this._log(`Renamed ${oldPath} to ${newPath}, but preserved every conflicted source branch because the displayed source revision is unknown`,LOG_LEVEL_NOTICE);await this.conflict.queueCheckFor(oldPath);return!0}const storedRevision=await this.db.storeDeletionWithBaseRevision(oldPath,baseRevision);if(!1===storedRevision)return!1;await this.deleteProvenance(oldPath);await this.conflict.queueCheckFor(oldPath);return!0}const deleted=await this.db.delete(oldPath);deleted&&await this.deleteProvenance(oldPath);return deleted}async deleteRevisionFromDB(info3,rev3){const path2=getStoragePathFromUXFileInfo(info3),provenance=await this.getProvenance(path2),deleted=await this.db.delete(info3,rev3);deleted&&(null==provenance?void 0:provenance.revision)===rev3&&await this.deleteProvenance(path2);return deleted}async resolveConflictedByDeletingRevision(info3,rev3){const path2=getStoragePathFromUXFileInfo(info3),file=await this.infoToStub(info3),docEntry=await this.db.fetchEntryMeta(null!=file?file:info3,rev3,!0);if(!docEntry){this._log(`Failed to read the conflicted revision ${rev3} of ${path2}`,LOG_LEVEL_VERBOSE);return!1}if(!await this.deleteRevisionFromDB(info3,rev3)){this._log(`Failed to delete the conflicted revision ${rev3} of ${path2}`,LOG_LEVEL_VERBOSE);return!1}if(!await this.applyDatabaseEntryToStorage(docEntry,file,!0)){this._log(`Failed to apply the resolved revision ${rev3} of ${path2} to the storage`,LOG_LEVEL_VERBOSE);return!1}await this.deleteProvenance(path2)}async dbToStorageWithSpecificRev(info3,rev3,force){if(null==info3){this._log(`Cannot select database revision ${rev3} without a file path`,LOG_LEVEL_VERBOSE);return!1}const file=await this.infoToStub(info3),databaseTarget=null!=file?file:info3,[docEntry,currentEntry,conflictedRevisions]=await Promise.all([this.db.fetchEntryMeta(databaseTarget,rev3,!0),this.db.fetchEntryMeta(databaseTarget,void 0,!0),this.db.getConflictedRevs(databaseTarget)]);if(!docEntry){this._log(`File ${tryGetFilePath(info3)} is not exist on the database`,LOG_LEVEL_VERBOSE);return!1}const liveRevisions=new Set([...currentEntry&&currentEntry._rev?[currentEntry._rev]:[],...conflictedRevisions]);if(!liveRevisions.has(rev3)){this._log(`Could not apply ${tryGetFilePath(info3)} revision ${rev3}; the selected revision is no longer live`,LOG_LEVEL_NOTICE);return!1}return await this.applyDatabaseEntryToStorage(docEntry,file,force,!0)}async dbToStorage(entryInfo,info3,force){const file=await this.infoToStub(info3),pathFromEntryInfo="string"==typeof entryInfo?entryInfo:this.getPath(entryInfo),docEntry=await this.db.fetchEntryMeta(pathFromEntryInfo,void 0,!0);if(!docEntry){this._log(`File ${pathFromEntryInfo} is not exist on the database`,LOG_LEVEL_VERBOSE);return!1}return await this.applyDatabaseEntryToStorage(docEntry,file,force)}async applyDatabaseEntryToStorage(docEntry,file,force,allowExistingConflicts=!1){const mode=null==file?"create":"modify",path2=this.getPath(docEntry),settings=this.setting.currentSettings(),revs=await this.db.getConflictedRevs(path2);if(revs.length>0&&!allowExistingConflicts&&!settings.writeDocumentsIfConflicted){await this.conflict.queueCheckForIfOpen(path2);return!0}let existDoc=await this.storage.getStub(path2);if(isFolderInfo(existDoc)){this._log(`Folder ${path2} is already exist on the storage as a folder`,LOG_LEVEL_VERBOSE);return!0}const existOnDB=!(docEntry._deleted||docEntry.deleted);if(!existOnDB&&!existDoc){this._log(`File ${path2} seems to be deleted, but already not on storage`,LOG_LEVEL_VERBOSE);await this.deleteProvenance(path2);return!0}if(!existOnDB&&existDoc){if(!force&&!settings.writeDocumentsIfConflicted&&await this.preserveUnsyncedStorageAsConflict(path2,existDoc,docEntry))return!0;await this.storage.deleteVaultItem(path2);await this.deleteProvenance(path2);return!0}if(existDoc&&existDoc.path!==path2){const[existingDocumentId,targetDocumentId]=await Promise.all([this.path.path2id(existDoc.path),this.path.path2id(path2)]);if(existingDocumentId!==targetDocumentId){this._log(`Refusing to overwrite ${existDoc.path} while applying the distinct path ${path2}`,LOG_LEVEL_NOTICE);return!1}if(getParentPath(existDoc.path)!==getParentPath(path2)){this._log(`Refusing to apply a filename case change across differently cased parent directories: ${existDoc.path} -> ${path2}`,LOG_LEVEL_NOTICE);return!1}const renamedFile=await this.storage.renameFile(existDoc,path2);if(!renamedFile){this._log(`Could not apply the stored filename case: ${existDoc.path} -> ${path2}`,LOG_LEVEL_NOTICE);return!1}await this.deleteProvenance(existDoc.path);existDoc=renamedFile}const docRead=await this.db.fetchEntryFromMeta(docEntry);if(!docRead){this._log(`File ${path2} is not exist on the database`,LOG_LEVEL_VERBOSE);return!1}if(!settings.processSizeMismatchedFiles&&0!=docRead.size&&docRead.size!==readAsBlob(docRead).size){this._log(`File ${path2} seems to be corrupted! Writing prevented. (${docRead.size} != ${readAsBlob(docRead).size})`,LOG_LEVEL_NOTICE);return!1}const docData=readContent(docRead);if(allowExistingConflicts&&existDoc&&!force){const readFile=await this.readFileFromStub(existDoc);if(await isDocContentSame(docData,readFile.body)){await this.setProvenance(path2,docEntry._rev,existDoc.stat.mtime);this.path.markChangesAreSame(docRead,docRead.mtime,existDoc.stat.mtime);return!0}}if(existDoc&&!force){let shouldApplied=!1;const freshness=this.path.compareFileFreshness(existDoc,docEntry);freshness!==EVEN&&(shouldApplied=!0);if(!shouldApplied){const readFile=await this.readFileFromStub(existDoc);if(await isDocContentSame(docData,readFile.body)){shouldApplied=!1;this.path.markChangesAreSame(docRead,docRead.mtime,existDoc.stat.mtime)}else shouldApplied=!0}if(!shouldApplied){await this.setProvenance(path2,docEntry._rev,existDoc.stat.mtime);this._log(`File ${docRead.path} is not changed`,LOG_LEVEL_VERBOSE);return!0}if(!force&&!settings.writeDocumentsIfConflicted&&await this.preserveUnsyncedStorageAsConflict(path2,existDoc,docEntry,docData))return!0}else this._log(`File ${docRead.path} ${existDoc?"(new) ":""} ${force?" (forced)":""}`,LOG_LEVEL_VERBOSE);await this.storage.ensureDir(path2);const ret=await this.storage.writeFileAuto(path2,docData,{ctime:docRead.ctime,mtime:docRead.mtime});await this.storage.touched(path2);this.storage.triggerFileEvent(mode,path2);if(ret&&this.fileReflectionProvenance){const storedStat=await this.storage.stat(path2);await this.setProvenance(path2,docEntry._rev,null==storedStat?void 0:storedStat.mtime)}return ret}async preserveUnsyncedStorageAsConflict(path2,existDoc,incomingEntry,incomingContent){const readFile=await this.readFileFromStub(existDoc);if(incomingContent&&await isDocContentSame(incomingContent,readFile.body))return!1;if(incomingContent&&await isIncomingTextClearExtension(incomingContent,readFile.body))return!1;if(!incomingEntry._rev)return!1;if(await this.db.hasContentInRevisionHistory(path2,readFile.body,incomingEntry._rev))return!1;const storedRevision=await this.db.storeAsConflictedRevisionWithResult(readFile,incomingEntry._rev,!0);if(!1===storedRevision){this._log(`Prevented overwriting unsynchronised local changes for ${path2}`,LOG_LEVEL_NOTICE);return!0}await this.setProvenance(path2,storedRevision,readFile.stat.mtime);this._log(`Preserved unsynchronised local changes as a conflict for ${path2}`,LOG_LEVEL_NOTICE);await this.conflict.queueCheckFor(path2);return!0}async _anyHandlerProcessesFileEvent(item){if(item.restoredFromPreviousRuntime)return await this._processRestoredFileEvent(item);const eventItem=item.args,type=item.type,path2=eventItem.file.path;if(!await this.isCurrentPathSelected(path2))return!1;if("RENAME"===type&&!eventItem.oldPath){this._log(`Rename event for ${path2} has no source path`,LOG_LEVEL_VERBOSE);return!1}const eventPaths="RENAME"===type?[path2,eventItem.oldPath]:[path2];return await this.serializedByFileEventPaths(eventPaths,async()=>{switch(type){case"CREATE":case"CHANGED":return await this.storeFileToDB(item.args.file);case"DELETE":return await this.deleteFileFromDB(item.args.file);case"RENAME":return await this.renameFileInDB(item.args.file,item.args.oldPath);case"INTERNAL":return!1;default:this._log(`Unsupported event type: ${type}`,LOG_LEVEL_VERBOSE);return!1}})}async serializedByFileEventPaths(eventPaths,callback){const documentIds=await Promise.all(eventPaths.map(eventPath=>this.path.path2id(eventPath))),lockKeys=[...new Set(documentIds)].sort().map(documentId=>`processFileEvent-${documentId}`);return await serializedByKeys(lockKeys,()=>callback(2===documentIds.length&&documentIds[0]===documentIds[1]))}async _processRestoredFileEvent(item){const eventItem=item.args,type=item.type,path2=eventItem.file.path;if("RENAME"===type&&!eventItem.oldPath){this._log(`Rename event for ${path2} has no source path`,LOG_LEVEL_VERBOSE);return!0}const eventPaths="RENAME"===type?[path2,eventItem.oldPath]:[path2];return await this.serializedByFileEventPaths(eventPaths,async isSameDocument=>{let action2;try{action2=await this._planRestoredFileEvent(item,isSameDocument)}catch(ex){this.logRestoredEventValidationFailure(path2,ex);return!0}switch(action2.kind){case"none":return!0;case"store":return await this.storeFileToDB(action2.file);case"delete":return await this.deleteFileFromDB(action2.path);case"rename":return await this.renameFileInDB(action2.file,action2.oldPath)}})}async _planRestoredFileEvent(item,isSameDocument){const path2=item.args.file.path;switch(item.type){case"CREATE":case"CHANGED":{const current=this.getExactCurrentFile(await this.storage.getStub(path2),path2);return current&&await this.isCurrentFileSelected(current)?{kind:"store",file:current}:{kind:"none"}}case"DELETE":{const current=await this.storage.getStub(path2);return null===current&&await this.canApplyRestoredDeletion(path2)?{kind:"delete",path:path2}:{kind:"none"}}case"RENAME":return await this._planRestoredRename(path2,item.args.oldPath,isSameDocument);case"INTERNAL":return{kind:"none"};default:this._log(`Unsupported event type: ${item.type}`,LOG_LEVEL_VERBOSE);return{kind:"none"}}}async _planRestoredRename(newPath,oldPath,isSameDocument){if(isSameDocument){const currentTarget2=this.getExactCurrentFile(await this.storage.getStub(newPath),newPath);return currentTarget2&&await this.isCurrentFileSelected(currentTarget2)?{kind:"rename",file:currentTarget2,oldPath}:{kind:"none"}}const currentTargetItem=await this.storage.getStub(newPath);let currentSourceItem=null,sourceWasInspected=!0;try{currentSourceItem=await this.storage.getStub(oldPath)}catch(ex){sourceWasInspected=!1;this.logRestoredEventValidationFailure(oldPath,ex)}const currentTarget=this.getExactCurrentFile(currentTargetItem,newPath);return null!==currentTargetItem?currentTarget&&await this.isCurrentFileSelected(currentTarget)?sourceWasInspected&&null===currentSourceItem&&await this.canApplyRestoredDeletion(oldPath)?{kind:"rename",file:currentTarget,oldPath}:{kind:"store",file:currentTarget}:{kind:"none"}:sourceWasInspected&&null===currentSourceItem&&await this.canApplyRestoredDeletion(oldPath)?{kind:"delete",path:oldPath}:{kind:"none"}}getExactCurrentFile(current,expectedPath){return null===current||isFolderInfo(current)?null:this.storage.normalisePath(current.path)===this.storage.normalisePath(expectedPath)?current:null}async isCurrentFileSelected(file){if(!await this.isCurrentPathSelected(file.path))return!1;if(this.vault.isFileSizeTooLarge(file.stat.size)){this._log(`File ${file.path} exceeds the current maximum size`,LOG_LEVEL_VERBOSE);return!1}return!0}async isCurrentPathSelected(path2){if(!await this.vault.isTargetFile(path2)){this._log(`File ${path2} is not the target file`,LOG_LEVEL_VERBOSE);return!1}if(shouldBeIgnored(path2)){this._log(`File ${path2} should be ignored`,LOG_LEVEL_VERBOSE);return!1}return!0}async canApplyRestoredDeletion(path2){try{return await this.isCurrentPathSelected(path2)}catch(ex){this.logRestoredEventValidationFailure(path2,ex);return!1}}logRestoredEventValidationFailure(path2,ex){this._log(`Could not validate the saved storage operation for ${path2} against current storage; the Offline Scanner will reconcile the current state`,LOG_LEVEL_NOTICE);this._log(ex,LOG_LEVEL_VERBOSE)}async _anyProcessReplicatedDoc(entry){return await serialized(`processReplicatedDoc-${entry._id}`,async()=>{var _a13,_b6;if(!await this.vault.isTargetFile(entry.path)){this._log(`File ${entry.path} is not the target file`,LOG_LEVEL_VERBOSE);return!1}if(this.vault.isFileSizeTooLarge(entry.size)){this._log(`File ${entry.path} is too large (on database) to be processed`,LOG_LEVEL_VERBOSE);return!1}if(shouldBeIgnored(entry.path)){this._log(`File ${entry.path} should be ignored`,LOG_LEVEL_VERBOSE);return!1}const path2=this.getPath(entry),targetFile=await this.storage.getStub(this.getPathWithoutPrefix(entry));if(isFolderInfo(targetFile)){this._log(`${path2} is already exist as the folder`);return!0}{if(targetFile&&this.vault.isFileSizeTooLarge(targetFile.stat.size)){this._log(`File ${targetFile.path} is too large (on storage) to be processed`,LOG_LEVEL_VERBOSE);return!1}this._log(`Processing ${path2} (${entry._id.substring(0,8)} :${null==(_a13=entry._rev)?void 0:_a13.substring(0,5)}) : Started...`,LOG_LEVEL_VERBOSE);this.events.emitEvent(EVENT_CONFLICT_CANCELLED,path2);const ret=await this.dbToStorage(entry,targetFile);this._log(`Processing ${path2} (${entry._id.substring(0,8)} :${null==(_b6=entry._rev)?void 0:_b6.substring(0,5)}) : Done`);return ret}})}async createAllChunks(showingNotice){this._log("Collecting local files on the storage",LOG_LEVEL_VERBOSE);const semaphore=Semaphore(10);let processed=0;const filesStorageSrc=await this.storage.getFiles(),incProcessed=()=>{processed++;processed%25==0&&this._log(`Creating missing chunks: ${processed} of ${total} files`,showingNotice?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,"chunkCreation")},total=filesStorageSrc.length,procAllChunks=filesStorageSrc.map(async file=>{if(!await this.vault.isTargetFile(file)){incProcessed();return!0}if(this.vault.isFileSizeTooLarge(file.stat.size)){incProcessed();return!0}if(shouldBeIgnored(file.path)){incProcessed();return!0}const release=await semaphore.acquire();incProcessed();try{await this.storeFileToDB(file,!1,!0)}catch(ex){this._log(ex,LOG_LEVEL_VERBOSE)}finally{release()}});await Promise.all(procAllChunks);this._log(`Creating chunks Done: ${processed} of ${total} files`,showingNotice?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,"chunkCreation")}};ServiceFileHandler=class extends ServiceFileHandlerBase{};FileAccessBase=class{constructor(adapter,dependencies){__publicField(this,"storageAccessManager");__publicField(this,"vaultService");__publicField(this,"settingService");__publicField(this,"APIService");__publicField(this,"path");__publicField(this,"adapter");__publicField(this,"_log");this.adapter=adapter;this.storageAccessManager=dependencies.storageAccessManager;this.vaultService=dependencies.vaultService;this.settingService=dependencies.settingService;this.APIService=dependencies.APIService;this.path=dependencies.pathService;this._log=createInstanceLogFunction("FileAccess",this.APIService)}isFile(file){return this.adapter.typeGuard.isFile(file)}isFolder(item){return this.adapter.typeGuard.isFolder(item)}getPath(file){return this.adapter.path.getPath(file)}nativeFileToUXFileInfoStub(file){return this.adapter.conversion.nativeFileToUXFileInfoStub(file)}nativeFolderToUXFolder(file){return this.adapter.conversion.nativeFolderToUXFolder(file)}normalisePath(path2){return this.adapter.path.normalisePath(path2)}_writeOp(file,callback){const path2=this.getPath(file);return this.storageAccessManager.processWriteFile(path2,async()=>await callback(path2,file))}_readOp(file,callback){const path2=this.getPath(file);return this.storageAccessManager.processReadFile(path2,async()=>await callback(path2,file))}async tryAdapterStat(file){return await this._readOp(file,async path2=>await this.adapter.storage.trystat(path2))}async adapterStat(file){return await this._readOp(file,async path2=>await this.adapter.storage.stat(path2))}async adapterExists(file){return await this._readOp(file,async path2=>await this.adapter.storage.exists(path2))}async adapterRemove(file){return await this._writeOp(file,async path2=>await this.adapter.storage.remove(path2))}async adapterRead(file){return await this._readOp(file,async path2=>await this.adapter.storage.read(path2))}async adapterReadBinary(file){return await this._readOp(file,async path2=>await this.adapter.storage.readBinary(path2))}async adapterReadAuto(file){const path2=this.getPath(file);return isPlainText(path2)?await this._readOp(file,async path22=>await this.adapter.storage.read(path22)):await this._readOp(file,async path22=>await this.adapter.storage.readBinary(path22))}async adapterWrite(file,data,options){return"string"==typeof data?await this._writeOp(file,async path2=>await this.adapter.storage.write(path2,data,options)):await this._writeOp(file,async path2=>await this.adapter.storage.writeBinary(path2,toArrayBuffer2(data),options))}adapterList(basePath){return this.adapter.storage.list(basePath)}async vaultCacheRead(file){return await this._readOp(file,async path2=>await this.adapter.vault.cachedRead(file))}vaultRead(file){return this._readOp(file,async path2=>await this.adapter.vault.read(file))}vaultReadBinary(file){return this._readOp(file,async path2=>await this.adapter.vault.readBinary(file))}async vaultReadAuto(file){const path2=this.getPath(file);return isPlainText(path2)?await this._readOp(path2,async path22=>await this.adapter.vault.read(file)):await this._readOp(path2,async path22=>await this.adapter.vault.readBinary(file))}async vaultModify(file,data,options){return"string"==typeof data?await this._writeOp(file,async path2=>{const oldData=await this.adapter.vault.read(file);if(data===oldData){const stat=await this.adapter.statFromNative(file);options&&options.mtime&&this.path.markChangesAreSame(path2,stat.mtime,options.mtime);return!0}await this.adapter.vault.modify(file,data,options);return!0}):await this._writeOp(file,async path2=>{const oldData=await this.adapter.vault.readBinary(file);if(await isDocContentSame(createBinaryBlob(oldData),createBinaryBlob(data))){const stat=await this.adapter.statFromNative(file);options&&options.mtime&&this.path.markChangesAreSame(path2,stat.mtime,options.mtime);return!0}await this.adapter.vault.modifyBinary(file,toArrayBuffer2(data),options);return!0})}async vaultCreate(path2,data,options){return"string"==typeof data?await this._writeOp(path2,()=>this.adapter.vault.create(path2,data,options)):await this._writeOp(path2,()=>this.adapter.vault.createBinary(path2,toArrayBuffer2(data),options))}async vaultRename(file,newPath){return await this._writeOp(file,async()=>await this.adapter.renameFile(file,newPath))}trigger(name,...data){return this.adapter.vault.trigger(name,...data)}async reconcileInternalFile(path2){return await this.adapter.reconcileInternalFile(path2)}async adapterAppend(normalizedPath,data,options){return await this.adapter.storage.append(normalizedPath,data,options)}async delete(file,force){return await this._writeOp(file,async(path2,file2)=>await this.adapter.vault.delete(file2,force))}async trash(file,force){return await this._writeOp(file,async(path2,file2)=>await this.adapter.vault.trash(file2,force))}isStorageInsensitive(){return this.vaultService.isStorageInsensitive()}async getAbstractFileByPath(path2){const setting=this.settingService.currentSettings();return!setting.handleFilenameCaseSensitive||this.isStorageInsensitive()?await this.adapter.getAbstractFileByPathInsensitive(path2):await this.adapter.getAbstractFileByPath(path2)}async getFiles(){return await this.adapter.getFiles()}async ensureDirectory(fullPath){const pathElements=fullPath.split("/");pathElements.pop();let c3="";for(const v2 of pathElements){c3+=v2;try{await this.adapter.storage.mkdir(c3)}catch(ex){if("Folder already exists."==(null==ex?void 0:ex.message));else{this._log("Folder Create Error");this._log(ex)}}c3+="/"}}async touch(file){const path2=this.getPath(file),statOrg=this.isFile(file)?file.stat:await this.adapter.storage.stat(path2);return this.storageAccessManager.touch({path:path2,stat:statOrg||{ctime:0,mtime:0,size:0}})}recentlyTouched(file){const path2=file.path;return this.storageAccessManager.recentlyTouched({...file,path:path2})}clearTouched(){return this.storageAccessManager.clearTouched()}};ObsidianConversionAdapter=class{nativeFileToUXFileInfoStub(file){return TFileToUXFileInfoStub(file)}nativeFolderToUXFolder(folder){return TFolderToUXFileInfoStub(folder)}};ObsidianPathAdapter=class{getPath(file){return"string"==typeof file?file:file.path}normalisePath(path2){return normalizePath(path2)}};ObsidianStorageAdapter=class{constructor(app){this.app=app}async exists(path2){return await this.app.vault.adapter.exists(path2)}async trystat(path2){return await this.app.vault.adapter.exists(path2)?await this.app.vault.adapter.stat(path2):null}async stat(path2){return await this.app.vault.adapter.stat(path2)}async mkdir(path2){await this.app.vault.adapter.mkdir(path2)}async remove(path2){await this.app.vault.adapter.remove(path2)}async read(path2){return await this.app.vault.adapter.read(path2)}async readBinary(path2){return await this.app.vault.adapter.readBinary(path2)}async write(path2,data,options){return await this.app.vault.adapter.write(path2,data,toIntegerTimestamps(options))}async writeBinary(path2,data,options){return await this.app.vault.adapter.writeBinary(path2,toArrayBuffer2(data),toIntegerTimestamps(options))}async append(path2,data,options){return await this.app.vault.adapter.append(path2,data,toIntegerTimestamps(options))}list(basePath){return Promise.resolve(this.app.vault.adapter.list(basePath))}};import_obsidian5=require("obsidian");ObsidianTypeGuardAdapter=class{isFile(file){return file instanceof import_obsidian5.TFile}isFolder(item){return item instanceof import_obsidian5.TFolder}};ObsidianVaultAdapter=class{constructor(app){this.app=app}async read(file){return await this.app.vault.adapter.read(file.path)}async cachedRead(file){return await this.app.vault.cachedRead(file)}async readBinary(file){return await this.app.vault.readBinary(file)}async modify(file,data,options){return await this.app.vault.modify(file,data,toIntegerTimestamps(options))}async modifyBinary(file,data,options){return await this.app.vault.modifyBinary(file,toArrayBuffer2(data),toIntegerTimestamps(options))}async create(path2,data,options){return await this.app.vault.create(path2,data,toIntegerTimestamps(options))}async createBinary(path2,data,options){return await this.app.vault.createBinary(path2,toArrayBuffer2(data),toIntegerTimestamps(options))}async rename(file,newPath){return await this.app.vault.rename(file,newPath)}async delete(file){return await this.app.fileManager.trashFile(file)}async trash(file){return await this.app.fileManager.trashFile(file)}trigger(name,...data){return this.app.vault.trigger(name,...data)}};ObsidianFileSystemAdapter=class{constructor(app){this.app=app;this.path=new ObsidianPathAdapter;this.typeGuard=new ObsidianTypeGuardAdapter;this.conversion=new ObsidianConversionAdapter;this.storage=new ObsidianStorageAdapter(app);this.vault=new ObsidianVaultAdapter(app)}getAbstractFileByPath(path2){return Promise.resolve(this.app.vault.getAbstractFileByPath(path2))}getAbstractFileByPathInsensitive(path2){return Promise.resolve(this.app.vault.getAbstractFileByPathInsensitive(path2))}getFiles(){return Promise.resolve(this.app.vault.getFiles())}async renameFile(file,newPath){await this.vault.rename(file,newPath);return file}statFromNative(file){return Promise.resolve({...file.stat,type:"file"})}async reconcileInternalFile(path2){var _a13,_b6;return await Promise.resolve(null==(_b6=(_a13=this.app.vault.adapter).reconcileInternalFile)?void 0:_b6.call(_a13,path2))}};FileAccessObsidian=class extends FileAccessBase{constructor(app,dependencies){const adapter=new ObsidianFileSystemAdapter(app);super(adapter,dependencies)}};TYPE_SENTINEL_FLUSH="SENTINEL_FLUSH";StorageEventManagerBase=class extends StorageEventManager{constructor(adapter,dependencies){super();__publicField(this,"_log");__publicField(this,"setting");__publicField(this,"vaultService");__publicField(this,"fileProcessing");__publicField(this,"storageAccess");__publicField(this,"adapter");__publicField(this,"snapShotRestored",null);__publicField(this,"bufferedQueuedItems",[]);__publicField(this,"triggerTakeSnapshot",throttle(()=>this._triggerTakeSnapshot(),100));__publicField(this,"concurrentProcessing",Semaphore(5));__publicField(this,"_waitingMap",new Map);__publicField(this,"_waitForIdle",null);__publicField(this,"processingCount",0);this.adapter=adapter;this.setting=dependencies.setting;this.vaultService=dependencies.vaultService;this.fileProcessing=dependencies.fileProcessing;this.storageAccess=dependencies.storageAccessManager;this._log=createInstanceLogFunction("StorageEventManager",dependencies.APIService)}get shouldBatchSave(){var _a13,_b6;return(null==(_a13=this.settings)?void 0:_a13.batchSave)&&1!=(null==(_b6=this.settings)?void 0:_b6.liveSync)}get batchSaveMinimumDelay(){var _a13,_b6;return null!=(_b6=null==(_a13=this.settings)?void 0:_a13.batchSaveMinimumDelay)?_b6:DEFAULT_SETTINGS.batchSaveMinimumDelay}get batchSaveMaximumDelay(){var _a13,_b6;return null!=(_b6=null==(_a13=this.settings)?void 0:_a13.batchSaveMaximumDelay)?_b6:DEFAULT_SETTINGS.batchSaveMaximumDelay}get settings(){return this.setting.currentSettings()}_saveSnapshot(snapshot2){return this.adapter.persistence.saveSnapshot(snapshot2)}_loadSnapshot(){return this.adapter.persistence.loadSnapshot()}isFolder(file){return this.adapter.typeGuard.isFolder(file)}isFile(file){return this.adapter.typeGuard.isFile(file)}updateStatus(){const allFileEventItems=this.bufferedQueuedItems.filter(e3=>"args"in e3),allItems=allFileEventItems.filter(e3=>!e3.cancelled),totalItems=allItems.length+this.concurrentProcessing.waiting,processing=this.processingCount,batchedCount=this._waitingMap.size;this.adapter.status.updateStatus({batched:batchedCount,processing,totalQueued:totalItems+batchedCount+processing})}restoreState(){this.snapShotRestored=this._restoreFromSnapshot();return this.snapShotRestored}async appendQueue(params,ctx){var _a13,_b6;const settings=this.settings;if(settings.isConfigured&&!(settings.suspendFileWatching||settings.maxMTimeForReflectEvents>0)){this.fileProcessing.onStorageFileEvent();for(const param of params){const atomicKey=[0,0,0,0,0,0].map(e3=>`${Math.floor(1e5*Math.random())}`).join("-");let type=param.type,file=param.file;const oldPath=param.oldPath;if(this.isFolder(file)){this._log(`Folder event skipped: ${file.path}`,LOG_LEVEL_VERBOSE);continue}const isTargetPath=async path2=>!shouldBeIgnored(path2)&&(!(!settings.syncInternalFiles&&path2.startsWith("."))&&await this.vaultService.isTargetFile(path2));if("RENAME"===type){const renamedFile=file;if(!oldPath||!this.isFile(file)||!renamedFile.stat){this._log(`Invalid rename event skipped: ${file.path}`,LOG_LEVEL_VERBOSE);continue}const oldPathIsTarget=await isTargetPath(oldPath);let newPathIsTarget=await isTargetPath(file.path);if(newPathIsTarget&&this.vaultService.isFileSizeTooLarge(renamedFile.stat.size)){this._log(`The storage file has been changed but exceeds the maximum size. Skipping: ${param.file.path}`,LOG_LEVEL_NOTICE);newPathIsTarget=!1}if(!oldPathIsTarget&&!newPathIsTarget)continue;if(oldPathIsTarget&&!newPathIsTarget){type="DELETE";file={path:oldPath,name:null!=(_a13=oldPath.split("/").pop())?_a13:file.name,stat:renamedFile.stat,deleted:!0}}else!oldPathIsTarget&&newPathIsTarget&&(type="CREATE")}else{if(!await isTargetPath(file.path))continue;if("INTERNAL"!==type){const size=file.stat.size;if(this.vaultService.isFileSizeTooLarge(size)&&("CREATE"==type||"CHANGED"==type)){this._log(`The storage file has been changed but exceeds the maximum size. Skipping: ${param.file.path}`,LOG_LEVEL_NOTICE);continue}}}if(this.isFile(file)&&("CREATE"==type||"CHANGED"==type||"RENAME"==type)){await delay(10);if(this.storageAccess.recentlyTouched({path:file.path,stat:null!=(_b6=file.stat)?_b6:{ctime:0,mtime:0,size:0}}))continue}let cache2;param.cachedData&&(cache2=param.cachedData);this.enqueue({type,args:{file,oldPath:"RENAME"===type?oldPath:void 0,cache:cache2,ctx},skipBatchWait:param.skipBatchWait,key:atomicKey})}}}enqueue(newItem){"DELETE"!=newItem.type&&"RENAME"!=newItem.type||this.bufferedQueuedItems.push({type:TYPE_SENTINEL_FLUSH});this.updateStatus();this.bufferedQueuedItems.push(newItem);fireAndForget(()=>this._takeSnapshot().then(()=>this.runQueuedEvents()))}_triggerTakeSnapshot(){this._takeSnapshot()}waitForIdle(){if(0===this._waitingMap.size)return Promise.resolve();if(this._waitForIdle)return this._waitForIdle;const promises=[...this._waitingMap.entries()].map(([key3,waitInfo])=>new Promise(resolve=>{waitInfo.canProceed.promise.then(()=>{this._log(`Processing ${key3}: Wait for idle completed`,LOG_LEVEL_DEBUG)}).catch(e3=>{this._log(`Processing ${key3}: Wait for idle error`,LOG_LEVEL_INFO);this._log(e3,LOG_LEVEL_VERBOSE)}).finally(()=>{resolve()});this._proceedWaiting(key3)})),waitPromise=Promise.all(promises).then(()=>{this._waitForIdle=null;this._log("All wait for idle completed",LOG_LEVEL_VERBOSE)});this._waitForIdle=waitPromise;return waitPromise}_proceedWaiting(key3){const waitInfo=this._waitingMap.get(key3);if(waitInfo){waitInfo.canProceed.resolve(!0);compatGlobal.clearTimeout(waitInfo.timerHandler);this._waitingMap.delete(key3)}this.triggerTakeSnapshot()}_cancelWaiting(key3){const waitInfo=this._waitingMap.get(key3);if(waitInfo){waitInfo.canProceed.resolve(!1);compatGlobal.clearTimeout(waitInfo.timerHandler);this._waitingMap.delete(key3)}this.triggerTakeSnapshot()}_addWaiting(key3,event2,waitedSince){if(this._waitingMap.has(key3))throw new Error(`Already waiting for key: ${key3}`);const resolver2=promiseWithResolvers(),now3=Date.now(),since=null!=waitedSince?waitedSince:now3,elapsed=now3-since,maxDelay=1e3*this.batchSaveMaximumDelay,remainingDelay=Math.max(0,maxDelay-elapsed),nextDelay=Math.min(remainingDelay,1e3*this.batchSaveMinimumDelay);elapsed>=maxDelay?this._log(`Processing ${key3}: Batch save maximum delay already exceeded: ${event2.type}`,LOG_LEVEL_DEBUG):this._log(`Processing ${key3}: Adding waiting for batch save: ${event2.type} (${nextDelay}ms)`,LOG_LEVEL_DEBUG);const waitInfo={since,type:event2.type,event:event2,canProceed:resolver2,timerHandler:compatGlobal.setTimeout(()=>{this._log(`Processing ${key3}: Batch save timeout reached: ${event2.type}`,LOG_LEVEL_DEBUG);this._proceedWaiting(key3)},nextDelay)};this._waitingMap.set(key3,waitInfo);this.triggerTakeSnapshot();return waitInfo}async processFileEvent(fei){const releaser=await this.concurrentProcessing.acquire();try{this.updateStatus();const filename=fei.args.file.path,waitingKey=`${filename}`,previous=this._waitingMap.get(waitingKey);let isShouldBeCancelled=fei.skipBatchWait||!1,previousPromise=Promise.resolve(!0),waitPromise=Promise.resolve(!0);if(previous){previousPromise=previous.canProceed.promise;isShouldBeCancelled&&this._log(`Processing ${filename}: Requested to perform immediately, cancelling previous waiting: ${fei.type}`,LOG_LEVEL_DEBUG);if(!isShouldBeCancelled&&"DELETE"===fei.type){this._log(`Processing ${filename}: DELETE requested, cancelling previous waiting: ${fei.type}`,LOG_LEVEL_DEBUG);isShouldBeCancelled=!0}if(!isShouldBeCancelled&&previous.type===fei.type){this._log(`Processing ${filename}: Cancelling previous waiting: ${fei.type}`,LOG_LEVEL_DEBUG);isShouldBeCancelled=!0}if(isShouldBeCancelled){this._cancelWaiting(waitingKey);this._log(`Processing ${filename}: Previous cancelled: ${fei.type}`,LOG_LEVEL_DEBUG);isShouldBeCancelled=!0}if(!isShouldBeCancelled){this._log(`Processing ${filename}: Waiting for previous to complete: ${fei.type}`,LOG_LEVEL_DEBUG);this._proceedWaiting(waitingKey);this._log(`Processing ${filename}: Previous completed: ${fei.type}`,LOG_LEVEL_DEBUG)}}await previousPromise;if(this.shouldBatchSave&&!fei.skipBatchWait){if("CREATE"==fei.type||"CHANGED"==fei.type){const info3=this._addWaiting(waitingKey,fei,null==previous?void 0:previous.since);waitPromise=info3.canProceed.promise}else fei.type;this._log(`Processing ${filename}: Waiting for batch save: ${fei.type}`,LOG_LEVEL_DEBUG);const canProceed=await waitPromise;if(!canProceed){this._log(`Processing ${filename}: Cancelled by new queue: ${fei.type}`,LOG_LEVEL_DEBUG);return}}await this.requestProcessQueue(fei)}finally{await this._takeSnapshot();releaser()}}async _takeSnapshot(){const processingEvents=[...this._waitingMap.values()].map(e3=>e3.event),waitingEvents=this.bufferedQueuedItems,snapShot=[...processingEvents,...waitingEvents];await this._saveSnapshot(snapShot);this.updateStatus()}async _restoreFromSnapshot(){const snapShot=await this._loadSnapshot();if(snapShot&&Array.isArray(snapShot)&&snapShot.length>0){this._log(`Restoring storage operation snapshot: ${snapShot.length} items`,LOG_LEVEL_VERBOSE);this.bufferedQueuedItems=snapShot.map(event2=>event2.type===TYPE_SENTINEL_FLUSH?event2:{...event2,restoredFromPreviousRuntime:!0,skipBatchWait:!0});this.updateStatus();await this.runQueuedEvents({waitForProcessing:!0})}else this._log("No snapshot to restore",LOG_LEVEL_VERBOSE)}runQueuedEvents(options={}){var _a13;const waitForProcessing=null!=(_a13=options.waitForProcessing)&&_a13;return skipIfDuplicated("storage-event-manager-run-queued-events",async()=>{let dispatched=[];const waitForDispatched=async()=>{if(0===dispatched.length)return;const pending3=dispatched;dispatched=[];const results=await Promise.allSettled(pending3.map(({processing})=>processing));for(const[index6,result]of results.entries())if("rejected"===result.status){this._log(`Restored storage operation failed for ${pending3[index6].path}; the Offline Scanner will reconcile the current state`,LOG_LEVEL_NOTICE);this._log(result.reason,LOG_LEVEL_VERBOSE)}};do{if(0===this.bufferedQueuedItems.length)break;const fei=this.bufferedQueuedItems.shift();await this._takeSnapshot();this.updateStatus();const releaser=await this.concurrentProcessing.acquire();releaser();this.updateStatus();if(fei.type===TYPE_SENTINEL_FLUSH){this._log("Waiting for idle",LOG_LEVEL_VERBOSE);waitForProcessing&&await waitForDispatched();await this.waitForIdle();this.updateStatus();continue}const processing=this.processFileEvent(fei);waitForProcessing?dispatched.push({path:fei.args.file.path,processing}):fireAndForget(processing)}while(this.bufferedQueuedItems.length>0);waitForProcessing&&await waitForDispatched()})}async requestProcessQueue(fei){try{this.processingCount++;this.updateStatus();await this.handleFileEvent(fei);await this._takeSnapshot()}finally{this.processingCount--;this.updateStatus()}}isWaiting(filename){return isWaitingForTimeout(`storage-event-manager-batchsave-${filename}`)}async handleFileEvent(queue2){const file=queue2.args.file,lockKey=`handleFile:${file.path}`;await serialized(lockKey,async()=>{if(queue2.cancelled)this._log(`File event cancelled before processing: ${file.path}`,LOG_LEVEL_INFO);else if("INTERNAL"==queue2.type||file.isInternal)await this.fileProcessing.processOptionalFileEvent(file.path);else{const last=0;if("DELETE"==queue2.type)await this.fileProcessing.processFileEvent(queue2);else{if(file.stat.mtime==last){this._log(`File has been already scanned on ${queue2.type}, skip: ${file.path}`,LOG_LEVEL_VERBOSE);return}if(!await this.fileProcessing.processFileEvent(queue2)){this._log(`STORAGE -> DB: Handler failed, cancel the relative operations: ${file.path}`,LOG_LEVEL_INFO);this.cancelRelativeEvent(queue2);return}}}});this.updateStatus()}cancelRelativeEvent(item){this._cancelWaiting(item.args.file.path)}async beginWatch(){await this.snapShotRestored;await this.adapter.watch.beginWatch({onCreate:(file,ctx)=>this.watchVaultCreate(file,ctx),onChange:(file,ctx)=>this.watchVaultChange(file,ctx),onDelete:(file,ctx)=>this.watchVaultDelete(file,ctx),onRename:(file,oldPath,ctx)=>this.watchVaultRename(file,oldPath,ctx),onRaw:path2=>this.watchVaultRawEvents(path2),onEditorChange:(editor,info3)=>this.watchEditorChange(editor,info3)})}watchEditorChange(editor,info3){if("object"!=typeof info3||null===info3)return;if(!("path"in info3))return;if(!this.shouldBatchSave)return;if(!("file"in info3))return;const file=null==info3?void 0:info3.file;if(!file)return;const path2=this.adapter.typeGuard.isFile(file)?file.path:info3.path;if(!path2)return;if(this.storageAccess.isFileProcessing(path2))return;if(!this.isWaiting(path2))return;const data=null==info3?void 0:info3.data,fi={type:"CHANGED",file:this.adapter.converter.toFileInfo(file),cachedData:data};this.appendQueue([fi])}watchVaultCreate(file,ctx){if(this.adapter.typeGuard.isFolder(file))return;const path2=file.path;if(this.storageAccess.isFileProcessing(path2))return;const fileInfo=this.adapter.converter.toFileInfo(file);this.appendQueue([{type:"CREATE",file:fileInfo}],ctx)}watchVaultChange(file,ctx){if(this.adapter.typeGuard.isFolder(file))return;const path2=file.path;if(this.storageAccess.isFileProcessing(path2))return;const fileInfo=this.adapter.converter.toFileInfo(file);this.appendQueue([{type:"CHANGED",file:fileInfo}],ctx)}watchVaultDelete(file,ctx){if(this.adapter.typeGuard.isFolder(file))return;const path2=file.path;if(this.storageAccess.isFileProcessing(path2))return;const fileInfo=this.adapter.converter.toFileInfo(file,!0);this.appendQueue([{type:"DELETE",file:fileInfo}],ctx)}watchVaultRename(file,oldPath,ctx){if(this.adapter.typeGuard.isFile(file)){const fileInfo=this.adapter.converter.toFileInfo(file);this.appendQueue([{type:"RENAME",file:fileInfo,oldPath,skipBatchWait:!0}],ctx)}}watchVaultRawEvents(path2){this.storageAccess.isFileProcessing(path2)||this.settings&&(this.settings.useIgnoreFiles?this.vaultService.isTargetFile(path2).then(()=>this._watchVaultRawEvents(path2)):this._watchVaultRawEvents(path2))}async _watchVaultRawEvents(path2){}};ObsidianTypeGuardAdapter2=class{isFile(file){return file instanceof import_obsidian.TFile||!(!file||"object"!=typeof file||!("isFolder"in file))&&!file.isFolder}isFolder(item){return item instanceof import_obsidian.TFolder||!(!item||"object"!=typeof item||!("isFolder"in item))&&!!item.isFolder}};ObsidianPersistenceAdapter=class{constructor(core){this.core=core}async saveSnapshot(snapshot2){await this.core.kvDB.set("storage-event-manager-snapshot",snapshot2)}async loadSnapshot(){const snapShot=await this.core.kvDB.get("storage-event-manager-snapshot");return snapShot}};ObsidianStatusAdapter=class{constructor(fileProcessing){this.fileProcessing=fileProcessing}updateStatus(status){this.fileProcessing.batched.value=status.batched;this.fileProcessing.processing.value=status.processing;this.fileProcessing.totalQueued.value=status.totalQueued}};ObsidianConverterAdapter=class{toFileInfo(file,deleted){return TFileToUXFileInfoStub(file,deleted)}toInternalFileInfo(path2){return InternalFileToUXFileInfoStub(path2)}};ObsidianWatchAdapter=class{constructor(plugin2){this.plugin=plugin2}beginWatch(handlers3){var _a13;const plugin2=this.plugin,boundHandlers={onCreate:handlers3.onCreate.bind(handlers3),onChange:handlers3.onChange.bind(handlers3),onDelete:handlers3.onDelete.bind(handlers3),onRename:handlers3.onRename.bind(handlers3),onRaw:handlers3.onRaw.bind(handlers3),onEditorChange:null==(_a13=handlers3.onEditorChange)?void 0:_a13.bind(handlers3)};plugin2.registerEvent(plugin2.app.vault.on("create",boundHandlers.onCreate));plugin2.registerEvent(plugin2.app.vault.on("modify",boundHandlers.onChange));plugin2.registerEvent(plugin2.app.vault.on("delete",boundHandlers.onDelete));plugin2.registerEvent(plugin2.app.vault.on("rename",boundHandlers.onRename));plugin2.registerEvent(plugin2.app.vault.on("raw",boundHandlers.onRaw));boundHandlers.onEditorChange&&plugin2.registerEvent(plugin2.app.workspace.on("editor-change",boundHandlers.onEditorChange));return Promise.resolve()}};ObsidianStorageEventManagerAdapter=class{constructor(plugin2,core,fileProcessing){this.typeGuard=new ObsidianTypeGuardAdapter2;this.persistence=new ObsidianPersistenceAdapter(core);this.watch=new ObsidianWatchAdapter(plugin2);this.status=new ObsidianStatusAdapter(fileProcessing);this.converter=new ObsidianConverterAdapter}};StorageEventManagerObsidian=class extends StorageEventManagerBase{constructor(plugin2,core,dependencies){const adapter=new ObsidianStorageEventManagerAdapter(plugin2,core,dependencies.fileProcessing);super(adapter,dependencies);this.core=core}async _watchVaultRawEvents(path2){if(!this.settings.syncInternalFiles&&!this.settings.usePluginSync)return;if(!this.settings.watchInternalFileChanges)return;if(!path2.startsWith(this.core.services.API.getSystemConfigDir()))return;if(path2.endsWith("/"))return;const isTargetFile2=await this.vaultService.isTargetFileInExtra(path2);isTargetFile2&&this.appendQueue([{type:"INTERNAL",file:this.adapter.converter.toInternalFileInfo(path2),skipBatchWait:!0}],null)}};WrappedNotice=class{constructor(message,timeout){var _a13;let strMessage="";strMessage=message instanceof DocumentFragment?null!=(_a13=message.textContent)?_a13:"":message;Logger(strMessage,LOG_LEVEL_NOTICE)}setMessage(message){var _a13;let strMessage="";strMessage=message instanceof DocumentFragment?null!=(_a13=message.textContent)?_a13:"":message;Logger(strMessage,LOG_LEVEL_NOTICE);return this}hide(){}};0;ModulePeriodicProcess=class extends AbstractModule{constructor(){super(...arguments);this.periodicSyncProcessor=new PeriodicProcessor(this.core,async()=>await this.services.replication.replicate())}disablePeriodic(){var _a13;null==(_a13=this.periodicSyncProcessor)||_a13.disable();return Promise.resolve(!0)}resumePeriodic(){this.periodicSyncProcessor.enable(this.settings.periodicReplication?1e3*this.settings.periodicReplicationInterval:0);return Promise.resolve(!0)}_allOnUnload(){return this.disablePeriodic()}_everyBeforeRealizeSetting(){return this.disablePeriodic()}_everyBeforeSuspendProcess(){return this.disablePeriodic()}_everyAfterResumeProcess(){return this.resumePeriodic()}_everyAfterRealizeSetting(){return this.resumePeriodic()}onBindFunction(core,services){services.appLifecycle.onUnload.addHandler(this._allOnUnload.bind(this));services.setting.onBeforeRealiseSetting.addHandler(this._everyBeforeRealizeSetting.bind(this));services.setting.onSettingRealised.addHandler(this._everyAfterRealizeSetting.bind(this));services.appLifecycle.onSuspending.addHandler(this._everyBeforeSuspendProcess.bind(this));services.appLifecycle.onResumed.addHandler(this._everyAfterResumeProcess.bind(this))}};KV_KEY_REPLICATION_RESULT_PROCESSOR_SNAPSHOT="replicationResultProcessorSnapshot";REPROCESS_BATCH_SIZE=100;ReplicateResultProcessor=class{constructor(replicator){this._suspended=!1;this.triggerTakeSnapshot=throttle(()=>this._triggerTakeSnapshot(),50);this._restoreFromSnapshot=void 0;this._queuedChanges=[];this._processingChanges=[];this._semaphore=Semaphore(10);this._isRunningProcessQueue=!1;this.replicator=replicator}log(message,level=LOG_LEVEL_INFO){Logger(`[ReplicateResultProcessor] ${message}`,level)}logError(e3){Logger(e3,LOG_LEVEL_VERBOSE)}get localDatabase(){return this.replicator.core.localDatabase}get services(){return this.replicator.core.services}get core(){return this.replicator.core}getPath(entry){return this.services.path.getPath(entry)}suspend(){this._suspended=!0;this.updateProcessingActivity()}resume(){this._suspended=!1;this.updateProcessingActivity();fireAndForget(()=>this.runProcessQueue())}get isSuspended(){return this._suspended||!this.core.services.appLifecycle.isReady||this.replicator.settings.suspendParseReplicationResult||this.core.services.appLifecycle.isSuspended()}async _takeSnapshot(){const snapshot2={queued:this._queuedChanges.slice(),processing:this._processingChanges.slice()};await this.core.kvDB.set(KV_KEY_REPLICATION_RESULT_PROCESSOR_SNAPSHOT,snapshot2);this.log(`Snapshot taken. Queued: ${snapshot2.queued.length}, Processing: ${snapshot2.processing.length}`,LOG_LEVEL_DEBUG);this.reportStatus()}_triggerTakeSnapshot(){fireAndForget(()=>this._takeSnapshot())}async restoreFromSnapshot(){const snapshot2=await this.core.kvDB.get(KV_KEY_REPLICATION_RESULT_PROCESSOR_SNAPSHOT);if(snapshot2){const newQueue=[...snapshot2.processing,...snapshot2.queued,...this._queuedChanges];this._queuedChanges=[];this.enqueueAll(newQueue);this.log(`Restored from snapshot (${snapshot2.processing.length+snapshot2.queued.length} items)`,LOG_LEVEL_INFO)}}restoreFromSnapshotOnce(){this._restoreFromSnapshot||(this._restoreFromSnapshot=this.restoreFromSnapshot());return this._restoreFromSnapshot}async withCounting(proc,countValue){countValue.value++;try{return await proc()}finally{countValue.value--}}reportStatus(){this.services.replication.replicationResultCount.value=this._queuedChanges.length+this._processingChanges.length}enqueueAll(changes3){for(const change of changes3){const isProcessed=this.processIfNonDocumentChange(change);isProcessed||this.enqueueChange(change)}}async reprocessStoredDocuments(){let count=0,batch=[];for await(const document2 of this.localDatabase.findAllNormalDocs()){batch.push(document2);count++;if(!(batch.length<REPROCESS_BATCH_SIZE)){this.enqueueAll(batch);batch=[]}}batch.length>0&&this.enqueueAll(batch);this.log(`Requeued ${count} stored document(s) after the reflection filters changed`,LOG_LEVEL_INFO);return count}processIfNonDocumentChange(change){if(!change){this.log("Received empty change",LOG_LEVEL_VERBOSE);return!0}if(isChunk(change._id)){this.localDatabase.onNewLeaf(change);this.log(`Processed chunk: ${shortenId(change._id)}`,LOG_LEVEL_DEBUG);return!0}if("versioninfo"==change.type){this.log(`Version info document received: ${change._id}`,LOG_LEVEL_VERBOSE);if(change.version>VER){this.core.replicator.closeReplication();this.log("Remote database updated to incompatible version. update your Self-hosted LiveSync plugin.",LOG_LEVEL_NOTICE)}return!0}if(change._id==SYNCINFO_ID||change._id.startsWith("_design")){this.log(`Skipped system document: ${change._id}`,LOG_LEVEL_VERBOSE);return!0}return!1}updateProcessingActivity(){var _a13,_b6;if(this.isSuspended){null==(_a13=this._processingActivityDone)||_a13.resolve();return}const hasPendingDocuments=this._queuedChanges.length>0||this._processingChanges.length>0;if(!hasPendingDocuments){null==(_b6=this._processingActivityDone)||_b6.resolve();return}if(this._processingActivity)return;const activityDone=promiseWithResolvers();this._processingActivityDone=activityDone;const activityOwner=this.services.replicator;this._processingActivity=(activityOwner.runBoundedLocalApplicationActivity?activityOwner.runBoundedLocalApplicationActivity(()=>activityDone.promise,{label:"replicated-document-application"}):activityDone.promise).catch(error=>this.logError(error)).finally(()=>{this._processingActivityDone===activityDone&&(this._processingActivityDone=void 0);this._processingActivity=void 0;this.updateProcessingActivity()})}enqueueChange(doc){var _a13;const old=this._queuedChanges.find(e3=>e3._id==doc._id),path2="path"in doc?this.getPath(doc):"<unknown>",docNote=`${path2} (${shortenId(doc._id)}, ${shortenRev(doc._rev)})`;if(old){if(old._rev==doc._rev){this.log(`[Enqueue] skipped (Already queued): ${docNote}`,LOG_LEVEL_VERBOSE);return}const oldRev=null!=(_a13=old._rev)?_a13:"",isDeletedBefore=!0===old._deleted||"deleted"in old&&!0===old.deleted,isDeletedNow=!0===doc._deleted||"deleted"in doc&&!0===doc.deleted;if(isDeletedBefore===isDeletedNow){this._queuedChanges=this._queuedChanges.filter(e3=>e3._id!=doc._id);this.log(`[Enqueue] requeued: ${docNote} (from rev: ${shortenRev(oldRev)})`,LOG_LEVEL_VERBOSE)}}this._queuedChanges.push(doc);this.updateProcessingActivity();this.triggerTakeSnapshot();this.triggerProcessQueue()}triggerProcessQueue(){fireAndForget(()=>this.runProcessQueue())}async runProcessQueue(){if(!this._isRunningProcessQueue&&!this.isSuspended&&0!=this._queuedChanges.length)try{this._isRunningProcessQueue=!0;for(;this._queuedChanges.length>0;){if(this.isSuspended){this.log(`Processing has got suspended. Remaining items in queue: ${this._queuedChanges.length}`,LOG_LEVEL_INFO);break}const releaser=await this._semaphore.acquire();releaser();const doc=this._queuedChanges.shift();if(doc){this._processingChanges.push(doc);this.parseDocumentChange(doc)}this.triggerTakeSnapshot()}}finally{this._isRunningProcessQueue=!1}}async parseDocumentChange(change){var _a13;try{if(isAnyNote(change)){const docMtime=null!=(_a13=change.mtime)?_a13:0,maxMTime=this.replicator.settings.maxMTimeForReflectEvents;if(maxMTime>0&&docMtime>maxMTime){const docPath=this.getPath(change);this.log(`Processing ${docPath} has been skipped due to modification time (${new Date(1e3*docMtime).toISOString()}) exceeding the limit`,LOG_LEVEL_INFO);return}}if(await this.services.replication.processVirtualDocument(change))return;if(isAnyNote(change)){const docPath=this.getPath(change);if(!await this.services.vault.isTargetFile(docPath)){this.log(`Skipped: ${docPath}`,LOG_LEVEL_VERBOSE);return}const size=change.size;if(this.services.vault.isFileSizeTooLarge(size)){this.log(`Processing ${docPath} has been skipped due to file size exceeding the limit`,LOG_LEVEL_NOTICE);return}return await this.applyToDatabase(change)}this.log(`Skipped unexpected non-note document: ${change._id}`,LOG_LEVEL_INFO);return}finally{this._processingChanges=this._processingChanges.filter(e3=>e3!==change);try{if(0===this._queuedChanges.length&&0===this._processingChanges.length)try{await this._takeSnapshot()}catch(error){this.logError(error)}else this.triggerTakeSnapshot()}finally{this.updateProcessingActivity()}}}applyToDatabase(doc){return this.withCounting(async()=>{let releaser;try{releaser=await this._semaphore.acquire();await this._applyToDatabase(doc)}catch(e3){this.log("Error while processing replication result",LOG_LEVEL_NOTICE);this.logError(e3)}finally{releaser&&releaser()}},this.services.replication.databaseQueueCount)}_applyToDatabase(doc_){const dbDoc=doc_,path2=this.getPath(dbDoc);return serialized(`replication-process:${dbDoc._id}`,async()=>{const docNote=`${path2} (${shortenId(dbDoc._id)}, ${shortenRev(dbDoc._rev)})`,isRequired=await this.checkIsChangeRequiredForDatabaseProcessing(dbDoc);if(!isRequired){this.log(`Skipped (Not latest): ${docNote}`,LOG_LEVEL_VERBOSE);return}const isDeleted2=!0===dbDoc._deleted||"deleted"in dbDoc&&!0===dbDoc.deleted,doc=isDeleted2?{...dbDoc,data:""}:await this.localDatabase.getDBEntryFromMeta({...dbDoc},!1,!0);if(doc)if(await this.services.replication.processOptionalSynchroniseResult(dbDoc))this.log(`Processed by other processor: ${docNote}`,LOG_LEVEL_DEBUG);else if(this.services.vault.isValidPath(this.getPath(doc))){await this.applyToStorage(doc);this.log(`Processed: ${docNote}`,LOG_LEVEL_DEBUG)}else this.log(`Unprocessed (Invalid path): ${docNote}`,LOG_LEVEL_VERBOSE);else this.log(`Failed to gather content of ${docNote}`,LOG_LEVEL_NOTICE)})}applyToStorage(entry){return this.withCounting(async()=>{await this.services.replication.processSynchroniseResult(entry)},this.services.replication.storageApplyingCount)}async checkIsChangeRequiredForDatabaseProcessing(dbDoc){var _a13,_b6,_c3,_d2;const path2=this.getPath(dbDoc);try{const savedDoc=await this.localDatabase.getRaw(dbDoc._id,{conflicts:!0,revs_info:!0}),newRev=null!=(_a13=dbDoc._rev)?_a13:"",latestRev=null!=(_b6=savedDoc._rev)?_b6:"",revisions=null!=(_d2=null==(_c3=savedDoc._revs_info)?void 0:_c3.map(e3=>e3.rev))?_d2:[];if(savedDoc._conflicts&&savedDoc._conflicts.length>0)return!0;if(newRev==latestRev)return!0;const index6=revisions.indexOf(newRev);return!(index6>=0)}catch(e3){if(isNotFoundError(e3))return!0;this.log(`Failed to get existing document for ${path2} (${shortenId(dbDoc._id)}, ${shortenRev(dbDoc._rev)}) `,LOG_LEVEL_NOTICE);this.logError(e3);return!1}}};ModuleReplicator=class extends AbstractModule{constructor(){super(...arguments);this.processor=new ReplicateResultProcessor(this);this._unresolvedErrorManager=new UnresolvedErrorManager(this.core.services.appLifecycle,this.core.services.context.events)}clearErrors(){this._unresolvedErrorManager.clearErrors()}getNormalFileReflectionFilterSignature(settings){var _a13,_b6,_c3,_d2,_e2,_f,_g,_h2;return JSON.stringify({handleFilenameCaseSensitive:null!=(_a13=settings.handleFilenameCaseSensitive)&&_a13,ignoreFiles:null!=(_b6=settings.ignoreFiles)?_b6:"",maxMTimeForReflectEvents:null!=(_c3=settings.maxMTimeForReflectEvents)?_c3:0,syncIgnoreRegEx:null!=(_d2=settings.syncIgnoreRegEx)?_d2:"",syncInternalFiles:null!=(_e2=settings.syncInternalFiles)&&_e2,syncMaxSizeInMB:null!=(_f=settings.syncMaxSizeInMB)?_f:0,syncOnlyRegEx:null!=(_g=settings.syncOnlyRegEx)?_g:"",useIgnoreFiles:null!=(_h2=settings.useIgnoreFiles)&&_h2})}_everyOnloadAfterLoadSettings(){this._normalFileReflectionFilterSignature=this.getNormalFileReflectionFilterSignature(this.settings);eventHub.onEvent(EVENT_FILE_SAVED2,()=>{this.settings.syncOnSave&&!this.core.services.appLifecycle.isSuspended()&&scheduleTask("perform-replicate-after-save",250,()=>this.services.replication.replicateByEvent())});eventHub.onEvent(EVENT_SETTING_SAVED,setting=>{const previousReflectionFilter=this._normalFileReflectionFilterSignature,nextReflectionFilter=this.getNormalFileReflectionFilterSignature(setting);this._normalFileReflectionFilterSignature=nextReflectionFilter;this.core.settings.suspendParseReplicationResult?this.processor.suspend():this.processor.resume();void 0!==previousReflectionFilter&&previousReflectionFilter!==nextReflectionFilter&&fireAndForget(()=>this.processor.reprocessStoredDocuments())});return Promise.resolve(!0)}_onReplicatorInitialised(){clearHandlers();return Promise.resolve(!0)}_everyOnDatabaseInitialized(showNotice){fireAndForget(()=>this.processor.restoreFromSnapshotOnce());return Promise.resolve(!0)}async _everyBeforeReplicate(showMessage2){await this.processor.restoreFromSnapshotOnce();this.clearErrors();return!0}async cleaned(showMessage2){Logger("The remote database has been cleaned.",showMessage2?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO);await skipIfDuplicated("cleanup",async()=>{const count=await purgeUnreferencedChunks(this.localDatabase.localDatabase,!0),message=`The remote database has been cleaned up.\nTo synchronize, this device must be also cleaned up. ${count} chunk(s) will be erased from this device.\nHowever, If there are many chunks to be deleted, maybe fetching again is faster.\nWe will lose the history of this device if we fetch the remote database again.\nEven if you choose to clean up, you will see this option again if you exit Obsidian and then synchronise again.`,ret=await this.core.confirm.confirmWithMessage("Cleaned",message,["Fetch again","Cleanup","Dismiss"],"Dismiss",30);"Fetch again"==ret&&await this.core.rebuilder.$performRebuildDB("localOnly");"Cleanup"==ret&&await this.services.replicator.runBoundedRemoteActivity(async()=>{var _a13;const replicator=this.services.replicator.getActiveReplicator();if(!(replicator instanceof LiveSyncCouchDBReplicator))return;const remoteDB=await replicator.connectRemoteCouchDBWithSetting(this.settings,this.services.API.isMobile(),!0);if("string"==typeof remoteDB){Logger(remoteDB,LOG_LEVEL_NOTICE);return!1}try{await purgeUnreferencedChunks(this.localDatabase.localDatabase,!1);this.localDatabase.clearCaches();const replicated=await this.services.replicator.runFiniteReplicationActivity(()=>this.core.replicator.openReplication(this.settings,!1,showMessage2,!0),{label:"replication"});if(replicated){await balanceChunkPurgedDBs(this.localDatabase.localDatabase,remoteDB.db);await purgeUnreferencedChunks(this.localDatabase.localDatabase,!1);this.localDatabase.clearCaches();await(null==(_a13=this.services.replicator.getActiveReplicator())?void 0:_a13.markRemoteResolved(this.settings));Logger("The local database has been cleaned up.",showMessage2?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO)}else Logger("Replication has been cancelled. Please try it again.",showMessage2?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO)}finally{await remoteDB.db.close()}},{label:"database-cleanup"})})}async onReplicationFailed(showMessage2=!1){const activeReplicator=this.services.replicator.getActiveReplicator();if(!activeReplicator){Logger("No active replicator found",LOG_LEVEL_INFO);return!1}if(activeReplicator.tweakSettingsMismatched&&activeReplicator.preferredTweakValue)await this.services.tweakValue.askResolvingMismatched(activeReplicator.preferredTweakValue);else if(activeReplicator.remoteLockedAndDeviceNotAccepted)if(activeReplicator.remoteCleaned&&usesLegacyIndexedDBAdapter(this.settings))await this.cleaned(showMessage2);else{const message=$msg("Replicator.Dialogue.Locked.Message"),CHOICE_FETCH=$msg("Replicator.Dialogue.Locked.Action.Fetch"),CHOICE_DISMISS=$msg("Replicator.Dialogue.Locked.Action.Dismiss"),CHOICE_UNLOCK=$msg("Replicator.Dialogue.Locked.Action.Unlock"),ret=await this.core.confirm.askSelectStringDialogue(message,[CHOICE_FETCH,CHOICE_UNLOCK,CHOICE_DISMISS],{title:$msg("Replicator.Dialogue.Locked.Title"),defaultAction:CHOICE_DISMISS,timeout:60});if(ret==CHOICE_FETCH){this._log($msg("Replicator.Dialogue.Locked.Message.Fetch"),LOG_LEVEL_NOTICE);await this.core.rebuilder.scheduleFetch();this.services.appLifecycle.scheduleRestart();return!1}if(ret==CHOICE_UNLOCK){await activeReplicator.markRemoteResolved(this.settings);this._log($msg("Replicator.Dialogue.Locked.Message.Unlocked"),LOG_LEVEL_NOTICE);return!1}}return!1}_parseReplicationResult(docs){this.processor.enqueueAll(docs);return Promise.resolve(!0)}onBindFunction(core,services){services.replicator.onReplicatorInitialised.addHandler(this._onReplicatorInitialised.bind(this));services.databaseEvents.onDatabaseInitialised.addHandler(this._everyOnDatabaseInitialized.bind(this));services.appLifecycle.onSettingLoaded.addHandler(this._everyOnloadAfterLoadSettings.bind(this));services.replication.parseSynchroniseResult.addHandler(this._parseReplicationResult.bind(this));const isOnlineAndCanReplicateWithHost=isOnlineAndCanReplicate.bind(null,this._unresolvedErrorManager,{services:{context:services.context,API:services.API},serviceModules:{}}),canReplicateWithPBKDF2WithHost=canReplicateWithPBKDF2.bind(null,this._unresolvedErrorManager,{services:{context:services.context,replicator:services.replicator,setting:services.setting},serviceModules:{}});services.replication.onBeforeReplicate.addHandler(isOnlineAndCanReplicateWithHost,10);services.replication.onBeforeReplicate.addHandler(canReplicateWithPBKDF2WithHost,20);services.replication.onBeforeReplicate.addHandler(this._everyBeforeReplicate.bind(this),100);services.replication.onReplicationFailed.addHandler(this.onReplicationFailed.bind(this))}};ModuleReplicatorCouchDB=class extends AbstractModule{_anyNewReplicator(settingOverride={}){const settings={...this.settings,...settingOverride};return settings.remoteType==REMOTE_MINIO||settings.remoteType==REMOTE_P2P?Promise.resolve(!1):Promise.resolve(new LiveSyncCouchDBReplicator(this.core))}_everyAfterResumeProcess(){if(this.services.appLifecycle.isSuspended())return Promise.resolve(!0);if(!this.services.appLifecycle.isReady())return Promise.resolve(!0);if(this.settings.remoteType!=REMOTE_MINIO&&this.settings.remoteType!=REMOTE_P2P){const LiveSyncEnabled=this.settings.liveSync,continuous=LiveSyncEnabled,eventualOnStart=!LiveSyncEnabled&&this.settings.syncOnStart;(LiveSyncEnabled||eventualOnStart)&&fireAndForget(async()=>{const canReplicate=await this.services.replication.isReplicationReady(!1);if(!canReplicate)return;const openReplication=()=>this.core.replicator.openReplication(this.settings,continuous,!1,!1);continuous?openReplication():await this.services.replicator.runFiniteReplicationActivity(openReplication,{label:"replication"})})}return Promise.resolve(!0)}onBindFunction(core,services){services.replicator.getNewReplicator.addHandler(this._anyNewReplicator.bind(this));services.appLifecycle.onResumed.addHandler(this._everyAfterResumeProcess.bind(this))}};MILSTONE_DOCID="_00000000-milestone.json";currentVersionRange2={min:0,max:2,current:2};LiveSyncJournalReplicator=class extends LiveSyncAbstractReplicator{constructor(env){super(env);__publicField(this,"_client");this.env=env}get client(){return this.setupJournalSyncClient()}get simpleStore(){return this.env.services.keyValueDB.simpleStore}async getReplicationPBKDF2Salt(setting,refresh){return await this.client.getReplicationPBKDF2Salt(refresh)}setupJournalSyncClient(){const settings=this.currentSettings;this._client?this._client.applyNewConfig(settings,this.simpleStore,this.env):this._client=new JournalSyncCore(settings,this.simpleStore,this.env,new MinioStorageAdapter(settings,this.env));return this._client}async ensureBucketIsCompatible(deviceNodeID,currentVersionRange22){const downloadedMilestone=await this.client.downloadJson(MILSTONE_DOCID),cPointInfo=await this.client.getCheckpointInfo(),progress=[...(null==cPointInfo?void 0:cPointInfo.receivedFiles)||[]].sort().pop()||"";return await ensureRemoteIsCompatible(downloadedMilestone,this.currentSettings,deviceNodeID,currentVersionRange22,{app_version:this.env.services.API.getAppVersion(),plugin_version:this.env.services.API.getPluginVersion(),vault_name:this.env.services.vault.vaultName(),device_name:this.env.services.vault.getVaultName(),progress},async info3=>{await this.client.uploadJson(MILSTONE_DOCID,info3)})}async migrate(from,to){Logger(`Database updated from ${from} to ${to}`,LOG_LEVEL_NOTICE);return Promise.resolve(!0)}terminateSync(){this.client.requestStop()}async openReplication(setting,_,showResult,ignoreCleanLock=!1){if(!await this.checkReplicationConnectivity(!1,ignoreCleanLock,showResult))return!1;await this.client.sync(showResult);return!0}async replicateAllToServer(setting,showingNotice){return!!await this.checkReplicationConnectivity(!1,!1,!!showingNotice)&&await this.client.sendLocalJournal(showingNotice)}async replicateAllFromServer(setting,showingNotice){return!!await this.checkReplicationConnectivity(!1,!1,!!showingNotice)&&await this.client.receiveRemoteJournal(showingNotice)}async checkReplicationConnectivity(skipCheck,ignoreCleanLock=!1,showMessage2=!1){if(!await this.client.isAvailable())return!1;if(!skipCheck){await this.client.ensureCheckpointCachesAreFresh();this.remoteCleaned=!1;this.remoteLocked=!1;this.remoteLockedAndDeviceNotAccepted=!1;this.tweakSettingsMismatched=!1;const ensure=await this.ensureBucketIsCompatible(this.nodeid,currentVersionRange2);if("INCOMPATIBLE"==ensure){Logger("The remote database has no compatibility with the running version. Please upgrade the plugin.",LOG_LEVEL_NOTICE);return!1}if("NODE_LOCKED"==ensure){Logger("The remote database has been rebuilt or corrupted since we have synchronized last time. Fetch rebuilt DB, explicit unlocking or chunk clean-up is required.",LOG_LEVEL_NOTICE);this.remoteLockedAndDeviceNotAccepted=!0;this.remoteLocked=!0;return!1}if("LOCKED"==ensure)this.remoteLocked=!0;else if("NODE_CLEANED"==ensure){if(!ignoreCleanLock){Logger("The remote database has been cleaned up. Fetch rebuilt DB, explicit unlocking or chunk clean-up is required.",LOG_LEVEL_NOTICE);this.remoteLockedAndDeviceNotAccepted=!0;this.remoteLocked=!0;this.remoteCleaned=!0;return!1}this.remoteLocked=!0}else if("OK"==ensure);else if("MISMATCHED"==ensure[0]){Logger(this.translate("liveSyncReplicator.mismatchedTweakDetected"),LOG_LEVEL_NOTICE);this.tweakSettingsMismatched=!0;this.preferredTweakValue=ensure[1];return!1}}return!0}async fetchRemoteChunks(missingChunks,showResult){return Promise.resolve([])}closeReplication(){this.client.requestStop();this.syncStatus="CLOSED";Logger("Replication closed");this.updateInfo()}async tryResetRemoteDatabase(setting){this.closeReplication();try{await this.client.resetBucket();clearHandlers();Logger("Remote Bucket Cleared",LOG_LEVEL_NOTICE);await this.tryCreateRemoteDatabase(setting)}catch(ex){Logger("Something happened on Remote Bucket Clear",LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_NOTICE)}}async tryCreateRemoteDatabase(setting){this.closeReplication();Logger("Remote Database Created or Connected",LOG_LEVEL_NOTICE);clearHandlers();await this.ensurePBKDF2Salt(setting,!0,!1);return await Promise.resolve()}async markRemoteLocked(setting,locked,lockByClean){const defInitPoint={_id:MILSTONE_DOCID,type:"milestoneinfo",created:Date.now(),locked,cleaned:lockByClean,accepted_nodes:[this.nodeid],node_chunk_info:{[this.nodeid]:currentVersionRange2},node_info:{},tweak_values:{}},remoteMilestone={...defInitPoint,...await this.client.downloadJson(MILSTONE_DOCID)||{}};remoteMilestone.node_chunk_info={...defInitPoint.node_chunk_info,...remoteMilestone.node_chunk_info};remoteMilestone.accepted_nodes=[this.nodeid];remoteMilestone.locked=locked;remoteMilestone.cleaned=remoteMilestone.cleaned||lockByClean;Logger(locked?"Lock remote bucket to prevent data corruption":"Unlock remote bucket to prevent data corruption",LOG_LEVEL_NOTICE);await this.client.uploadJson(MILSTONE_DOCID,remoteMilestone)}async markRemoteResolved(setting){const defInitPoint={_id:MILSTONE_DOCID,type:"milestoneinfo",created:Date.now(),locked:!1,accepted_nodes:[this.nodeid],node_chunk_info:{[this.nodeid]:currentVersionRange2},node_info:{},tweak_values:{}},remoteMilestone={...defInitPoint,...await this.client.downloadJson(MILSTONE_DOCID)||{}};remoteMilestone.node_chunk_info={...defInitPoint.node_chunk_info,...remoteMilestone.node_chunk_info};remoteMilestone.accepted_nodes=Array.from(new Set([...remoteMilestone.accepted_nodes,this.nodeid]));Logger("Mark this device as 'resolved'.",LOG_LEVEL_NOTICE);await this.client.uploadJson(MILSTONE_DOCID,remoteMilestone)}async tryConnectRemote(setting,showResult=!0){const endpoint=setting.endpoint,testClient=new MinioStorageAdapter(setting,this.env);try{await testClient.listFiles("",1);Logger(`Connected to ${endpoint} successfully!`,LOG_LEVEL_NOTICE);return!0}catch(ex){Logger(`Error! Could not connected to ${endpoint}\n${ex.message}`,LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_NOTICE);return!1}}async resetRemoteTweakSettings(setting){try{const remoteMilestone=await this.client.downloadJson(MILSTONE_DOCID);if(!remoteMilestone)throw new Error("Missing remote milestone");remoteMilestone.tweak_values={};Logger("tweak values on the remote database have been cleared",LOG_LEVEL_VERBOSE);await this.client.uploadJson(MILSTONE_DOCID,remoteMilestone)}catch(ex){Logger("Could not retrieve remote milestone",LOG_LEVEL_NOTICE);throw ex}}async setPreferredRemoteTweakSettings(setting){try{const remoteMilestone=await this.client.downloadJson(MILSTONE_DOCID);if(!remoteMilestone)throw new Error("Missing remote milestone");remoteMilestone.tweak_values[DEVICE_ID_PREFERRED]=extractObject(TweakValuesTemplate,{...setting});Logger("tweak values on the remote database have been cleared",LOG_LEVEL_VERBOSE);await this.client.uploadJson(MILSTONE_DOCID,remoteMilestone)}catch(ex){Logger("Could not retrieve remote milestone",LOG_LEVEL_NOTICE);throw ex}}async getRemotePreferredTweakValues(_setting){var _a13;const result=await this.client.downloadJsonWithResult(MILSTONE_DOCID);if(result.status===JournalStorageReadStatuses_NOT_FOUND)return{status:RemotePreferredTweakStatuses_NOT_CONFIGURED,reason:RemotePreferredTweakNotConfiguredReasons_MILESTONE_MISSING};if(result.status===JournalStorageReadStatuses_UNAVAILABLE)return{status:RemotePreferredTweakStatuses_UNAVAILABLE,error:result.error};const preferred=null==(_a13=result.value.tweak_values)?void 0:_a13[DEVICE_ID_PREFERRED];return preferred?{status:RemotePreferredTweakStatuses_AVAILABLE,values:preferred}:{status:RemotePreferredTweakStatuses_NOT_CONFIGURED,reason:RemotePreferredTweakNotConfiguredReasons_PREFERRED_VALUES_MISSING}}async getRemoteStatus(setting){const testClient=new MinioStorageAdapter(setting,this.env);return await testClient.getUsage()}countCompromisedChunks(){Logger("Bucket Sync Replicator cannot count compromised chunks",LOG_LEVEL_VERBOSE);return Promise.resolve(0)}getConnectedDeviceList(setting){return Promise.resolve(!1)}};ModuleReplicatorMinIO=class extends AbstractModule{_anyNewReplicator(settingOverride={}){const settings={...this.settings,...settingOverride};return settings.remoteType==REMOTE_MINIO?Promise.resolve(new LiveSyncJournalReplicator(this.core)):Promise.resolve(!1)}onBindFunction(core,services){services.replicator.getNewReplicator.addHandler(this._anyNewReplicator.bind(this))}};ModuleConflictChecker=class extends AbstractModule{constructor(){super(...arguments);this.conflictResolveQueue=new QueueProcessor(async filenames=>{const filename=filenames[0];return await this.services.conflict.resolve(filename)},{suspended:!1,batchSize:1,concurrentLimit:10,delay:0,keepResultUntilDownstreamConnected:!1}).replaceEnqueueProcessor((queue2,newEntity)=>{const filename=newEntity;sendValue("cancel-resolve-conflict:"+filename,!0);const newQueue=[...queue2].filter(e3=>e3!=newEntity);return[...newQueue,newEntity]});this.conflictCheckQueue=new QueueProcessor(files=>{const filename=files[0];return Promise.resolve([filename])},{suspended:!1,batchSize:1,concurrentLimit:10,delay:0,keepResultUntilDownstreamConnected:!0,pipeTo:this.conflictResolveQueue,totalRemainingReactiveSource:this.services.conflict.conflictProcessQueueCount})}async _queueConflictCheckIfOpen(file){const path2=file;if(this.settings.checkConflictOnlyOnOpen){const af2=this.services.vault.getActiveFilePath();if(af2&&af2!=path2){this._log(`${file} is conflicted, merging process has been postponed.`,LOG_LEVEL_NOTICE);return}}await this.services.conflict.queueCheckFor(path2)}async _queueConflictCheck(file){const optionalConflictResult=await this.services.conflict.getOptionalConflictCheckMethod(file);1!=optionalConflictResult&&("newer"===optionalConflictResult?await this.services.conflict.resolveByNewest(file):this.conflictCheckQueue.enqueue(file))}_waitForAllConflictProcessed(){return this.conflictResolveQueue.waitForAllProcessed()}onBindFunction(core,services){services.conflict.queueCheckForIfOpen.setHandler(this._queueConflictCheckIfOpen.bind(this));services.conflict.queueCheckFor.setHandler(this._queueConflictCheck.bind(this));services.conflict.ensureAllProcessed.setHandler(this._waitForAllConflictProcessed.bind(this))}};import_diff_match_patch4=__toESM(require_diff_match_patch(),1);ModuleConflictResolver=class extends AbstractModule{async _resolveConflictByDeletingRev(path2,deleteRevision,subTitle="",showNotice=!0){const title=`Resolving ${subTitle?`[${subTitle}]`:""}:`;if(!await this.core.fileHandler.deleteRevisionFromDB(path2,deleteRevision)){this._log(`${title} Could not delete conflicted revision ${displayRev(deleteRevision)} of ${path2}`,LOG_LEVEL_NOTICE);return MISSING_OR_ERROR}eventHub.emitEvent(EVENT_CONFLICT_CANCELLED,path2);this._log(`${title} Conflicted revision has been deleted ${displayRev(deleteRevision)} ${path2}`,LOG_LEVEL_INFO);if(0!=(await this.core.databaseFileAccess.getConflictedRevs(path2)).length){this._log(`${title} some conflicts are left in ${path2}`,LOG_LEVEL_INFO);return AUTO_MERGED}if(isPluginMetadata(path2)||isCustomisationSyncMetadata(path2)){this._log(`${title} ${path2} is a plugin metadata file, no need to write to storage`,LOG_LEVEL_INFO);return AUTO_MERGED}if(!await this.core.fileHandler.dbToStorage(path2,stripAllPrefixes(path2),!0)){this._log(`Could not write the resolved content to the storage: ${path2}`,LOG_LEVEL_NOTICE);return MISSING_OR_ERROR}const level=-1===subTitle.indexOf("same")&&showNotice?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO;this._log(`${path2} has been merged automatically`,level);return AUTO_MERGED}async checkConflictAndPerformAutoMerge(path2){const ret=await this.localDatabase.tryAutoMerge(path2,!this.settings.disableMarkdownAutoMerge);if("ok"in ret)return ret.ok;if("result"in ret){const p2=ret.result;if(!await this.core.databaseFileAccess.storeContent(path2,p2)){this._log(`Merged content cannot be stored:${path2}`,LOG_LEVEL_NOTICE);return MISSING_OR_ERROR}return await this.services.conflict.resolveByDeletingRevision(path2,ret.conflictedRev,"Sensible")}const{rightRev,leftLeaf,rightLeaf}=ret;if(0==leftLeaf){this._log(`could not get current revisions:${path2}`,LOG_LEVEL_NOTICE);return MISSING_OR_ERROR}if(0==rightLeaf){this._log(`could not read conflicted revision ${rightRev}:${path2}`,LOG_LEVEL_NOTICE);return MISSING_OR_ERROR}const isSame=leftLeaf.data==rightLeaf.data&&leftLeaf.deleted==rightLeaf.deleted,isBinary=!isPlainText(path2),alwaysNewer=this.settings.resolveConflictsByNewerFile;if(isSame||isBinary||alwaysNewer){const result=compareMTime(leftLeaf.mtime,rightLeaf.mtime);let loser=leftLeaf;result!=TARGET_IS_NEW&&(loser=rightLeaf);const subTitle=[""+(isSame?"same":""),""+(isBinary?"binary":""),""+(alwaysNewer?"alwaysNewer":"")].filter(e3=>e3.trim()).join(",");return await this.services.conflict.resolveByDeletingRevision(path2,loser.rev,subTitle)}const dmp=new import_diff_match_patch4.default,diff=dmp.diff_main(leftLeaf.data,rightLeaf.data);dmp.diff_cleanupSemantic(diff);this._log(`conflict(s) found:${path2}`);return{left:leftLeaf,right:rightLeaf,diff}}async _resolveConflict(filename){return await serialized(`conflict-resolve:${filename}`,async()=>{const conflictCheckResult=await this.checkConflictAndPerformAutoMerge(filename);if(conflictCheckResult!==NOT_CONFLICTED)if(conflictCheckResult!==MISSING_OR_ERROR&&conflictCheckResult!==CANCELLED)if(conflictCheckResult!==AUTO_MERGED){if(this.settings.showMergeDialogOnlyOnActive){const af2=this.services.vault.getActiveFilePath();if(af2&&af2!=filename){this._log(`[conflict] ${filename} is conflicted. Merging process has been postponed to the file have got opened.`,LOG_LEVEL_NOTICE);return}}this._log("[conflict] Manual merge required!");eventHub.emitEvent(EVENT_CONFLICT_CANCELLED,filename);await this.services.conflict.resolveByUserInteraction(filename,conflictCheckResult)}else{this.settings.syncAfterMerge&&!this.services.appLifecycle.isSuspended()&&await this.services.replication.replicateByEvent();this._log("[conflict] Automatically merged, but we have to check it again");await this.services.conflict.queueCheckFor(filename)}else this._log(`[conflict] Not conflicted or cancelled: ${filename}`,LOG_LEVEL_VERBOSE);else{eventHub.emitEvent(EVENT_CONFLICT_CANCELLED,filename);this._log(`[conflict] Not conflicted or cancelled: ${filename}`,LOG_LEVEL_VERBOSE)}})}async _anyResolveConflictByNewest(filename,showNotice=!0){const currentRev=await this.core.databaseFileAccess.fetchEntryMeta(filename,void 0,!0);if(0==currentRev){this._log(`Could not get current revision of ${filename}`);return Promise.resolve(!1)}const revs=await this.core.databaseFileAccess.getConflictedRevs(filename);if(0==revs.length)return Promise.resolve(!0);const mTimeAndRev=[[currentRev.mtime,currentRev._rev],...await Promise.all(revs.map(async rev3=>{const leaf=await this.core.databaseFileAccess.fetchEntryMeta(filename,rev3);return 0==leaf?[0,rev3]:[leaf.mtime,rev3]}))].sort((a2,b3)=>{const diff=b3[0]-a2[0];return 0==diff?a2[1].localeCompare(b3[1],"en",{numeric:!0}):diff});this._log(`Resolving conflict by newest: ${filename} (Newest: ${new Date(mTimeAndRev[0][0]).toLocaleString()}) (${mTimeAndRev.length} revisions exists)`);for(let i3=1;i3<mTimeAndRev.length;i3++){this._log(`conflict: Deleting the older revision ${mTimeAndRev[i3][1]} (${new Date(mTimeAndRev[i3][0]).toLocaleString()}) of ${filename}`);await this._resolveConflictByDeletingRev(filename,mTimeAndRev[i3][1],"NEWEST",showNotice)}return!0}async _resolveAllConflictedFilesByNewerOnes(){this._log("Resolving conflicts by newer ones",LOG_LEVEL_NOTICE);const files=await this.core.storageAccess.getFileNames();let i3=0;for(const file of files){i3++;i3%10==0&&this._log(`Check and Processing ${i3} / ${files.length}`,LOG_LEVEL_NOTICE,"resolveAllConflictedFilesByNewerOnes");await this._anyResolveConflictByNewest(file,!1)}this._log("Done!",LOG_LEVEL_NOTICE,"resolveAllConflictedFilesByNewerOnes")}onBindFunction(core,services){services.conflict.resolveByDeletingRevision.setHandler(this._resolveConflictByDeletingRev.bind(this));services.conflict.resolve.setHandler(this._resolveConflict.bind(this));services.conflict.resolveByNewest.setHandler(this._anyResolveConflictByNewest.bind(this));services.conflict.resolveAllConflictedFilesByNewerOnes.setHandler(this._resolveAllConflictedFilesByNewerOnes.bind(this))}};ModuleResolvingMismatchedTweaks=class extends AbstractModule{_collectMismatchedTweakKeys(current,preferred){const items=Object.keys(TweakValuesShouldMatchedTemplate);return items.filter(key3=>current[key3]!==preferred[key3])}_selectNewerTweakSide(current,preferred){Logger(`Modified: ${current.tweakModified} (current) vs ${preferred.tweakModified} (preferred)`);const currentModified=current.tweakModified,preferredModified=preferred.tweakModified,hasCurrentModified="number"==typeof currentModified&&currentModified>0,hasPreferredModified="number"==typeof preferredModified&&preferredModified>0;return(hasCurrentModified||hasPreferredModified)&&hasCurrentModified?hasPreferredModified&&preferredModified>=currentModified?"REMOTE":"CURRENT":"REMOTE"}async _shouldAutoAcceptCompatibleLossy(current,preferred,mismatchedKeys){if(0===mismatchedKeys.length)return;const hasOnlyCompatibleLossyMismatches=mismatchedKeys.every(key3=>-1!==CompatibleButLossyChanges.indexOf(key3));if(!hasOnlyCompatibleLossyMismatches)return;let autoAcceptCompatibleTweak=this.settings.autoAcceptCompatibleTweak;if(void 0===this.settings.autoAcceptCompatibleTweak){this.settings.autoAcceptCompatibleTweak=!0;await this.services.setting.saveSettingData();autoAcceptCompatibleTweak=!0;Logger("Automatic alignment of compatible chunk settings has been enabled.")}return!0===autoAcceptCompatibleTweak?this._selectNewerTweakSide(current,preferred):void 0}async _onBeforeSaveSettingData(next2,previous){const tweakKeys=Object.keys(TweakValuesTemplate),tweakKeysForUpdate=tweakKeys.filter(key3=>"tweakModified"!==key3),hasChangedTweak=tweakKeysForUpdate.some(key3=>next2[key3]!==previous[key3]);if(!hasChangedTweak)return;Logger(`Some tweak values have been changed. ${tweakKeysForUpdate.filter(key3=>next2[key3]!==previous[key3]).join(", ")}`);const modified=Date.now();Logger(`Modified: ${modified}`);return await Promise.resolve({tweakModified:modified})}async _anyAfterConnectCheckFailed(){if(!this.core.replicator.tweakSettingsMismatched&&!this.core.replicator.preferredTweakValue)return!1;const preferred=this.core.replicator.preferredTweakValue;if(!preferred)return!1;const ret=await this.services.tweakValue.askResolvingMismatched(preferred);return"OK"!=ret&&("CHECKAGAIN"==ret?"CHECKAGAIN":"IGNORE"==ret||void 0)}async _checkAndAskResolvingMismatchedTweaks(preferred){const mine=extractObject(TweakValuesTemplate,this.settings),mismatchedKeys=this._collectMismatchedTweakKeys(mine,preferred),autoAcceptSide=await this._shouldAutoAcceptCompatibleLossy(mine,preferred,mismatchedKeys);if("REMOTE"===autoAcceptSide)return[{...mine,...preferred},!1];if("CURRENT"===autoAcceptSide)return[!0,!1];const items=Object.entries(TweakValuesShouldMatchedTemplate);let rebuildRequired=!1,rebuildRecommended=!1;const tableRows=[];for(const v2 of items){const key3=v2[0],valueMine=escapeMarkdownValue(mine[key3]),valuePreferred=escapeMarkdownValue(preferred[key3]);if(valueMine!=valuePreferred){-1!==IncompatibleChanges.indexOf(key3)&&(rebuildRequired=!0);for(const pattern of IncompatibleChangesInSpecificPattern){if(pattern.key!==key3)continue;const isFromConditionMet="from"in pattern&&pattern.from===mine[key3],isToConditionMet="to"in pattern&&pattern.to===preferred[key3];(isFromConditionMet||isToConditionMet)&&(pattern.isRecommendation?rebuildRecommended=!0:rebuildRequired=!0)}-1!==CompatibleButLossyChanges.indexOf(key3)&&(rebuildRecommended=!0);tableRows.push($msg("TweakMismatchResolve.Table.Row",{name:localisedConfName(key3),self:valueToString(valueMine),remote:valueToString(valuePreferred)}))}}const additionalMessage=rebuildRequired&&this.core.settings.isConfigured?$msg("TweakMismatchResolve.Message.WarningIncompatibleRebuildRequired"):"",additionalMessage2=rebuildRecommended&&this.core.settings.isConfigured?$msg("TweakMismatchResolve.Message.WarningIncompatibleRebuildRecommended"):"",table3=$msg("TweakMismatchResolve.Table",{rows:tableRows.join("\n")}),message=$msg("TweakMismatchResolve.Message.MainTweakResolving",{table:table3,additionalMessage:[additionalMessage,additionalMessage2].filter(v2=>v2).join("\n")}),CHOICE_USE_REMOTE=$msg("TweakMismatchResolve.Action.UseRemote"),CHOICE_USE_REMOTE_WITH_REBUILD=$msg("TweakMismatchResolve.Action.UseRemoteWithRebuild"),CHOICE_USE_REMOTE_PREVENT_REBUILD=$msg("TweakMismatchResolve.Action.UseRemoteAcceptIncompatible"),CHOICE_USE_MINE=$msg("TweakMismatchResolve.Action.UseMine"),CHOICE_USE_MINE_WITH_REBUILD=$msg("TweakMismatchResolve.Action.UseMineWithRebuild"),CHOICE_USE_MINE_PREVENT_REBUILD=$msg("TweakMismatchResolve.Action.UseMineAcceptIncompatible"),CHOICE_DISMISS=$msg("TweakMismatchResolve.Action.Dismiss"),CHOICE_AND_VALUES=[];if(rebuildRequired){CHOICE_AND_VALUES.push([CHOICE_USE_REMOTE_WITH_REBUILD,[preferred,!0]]);CHOICE_AND_VALUES.push([CHOICE_USE_MINE_WITH_REBUILD,[!0,!0]]);CHOICE_AND_VALUES.push([CHOICE_USE_REMOTE_PREVENT_REBUILD,[preferred,!1]]);CHOICE_AND_VALUES.push([CHOICE_USE_MINE_PREVENT_REBUILD,[!0,!1]])}else if(rebuildRecommended){CHOICE_AND_VALUES.push([CHOICE_USE_REMOTE,[preferred,!1]]);CHOICE_AND_VALUES.push([CHOICE_USE_MINE,[!0,!1]]);CHOICE_AND_VALUES.push([CHOICE_USE_REMOTE_WITH_REBUILD,[preferred,!0]]);CHOICE_AND_VALUES.push([CHOICE_USE_MINE_WITH_REBUILD,[!0,!0]])}else{CHOICE_AND_VALUES.push([CHOICE_USE_REMOTE,[preferred,!1]]);CHOICE_AND_VALUES.push([CHOICE_USE_MINE,[!0,!1]])}CHOICE_AND_VALUES.push([CHOICE_DISMISS,[!1,!1]]);const CHOICES=Object.fromEntries(CHOICE_AND_VALUES),retKey=await this.core.confirm.askSelectStringDialogue(message,Object.keys(CHOICES),{title:$msg("TweakMismatchResolve.Title.TweakResolving"),timeout:60,defaultAction:CHOICE_DISMISS});return retKey?CHOICES[retKey]:[!1,!1]}async _askResolvingMismatchedTweaks(){if(!this.core.replicator.tweakSettingsMismatched)return"OK";const tweaks=this.core.replicator.preferredTweakValue;if(!tweaks)return"IGNORE";const[conf,rebuildRequired]=await this.services.tweakValue.checkAndAskResolvingMismatched(tweaks);if(!conf)return"IGNORE";if(!0===conf){await this.core.replicator.setPreferredRemoteTweakSettings(this.settings);rebuildRequired&&await this.core.rebuilder.$rebuildRemote();Logger($msg("TweakMismatchResolve.Message.remoteUpdated"),LOG_LEVEL_NOTICE);return"CHECKAGAIN"}if(conf){Object.assign(this.settings,extractObject(TweakValuesTemplate,conf));await this.services.setting.saveSettingData();rebuildRequired||await this.localDatabase.managers.reinitialise();await this.core.replicator.setPreferredRemoteTweakSettings(this.settings);rebuildRequired&&await this.core.rebuilder.$fetchLocal();Logger($msg("TweakMismatchResolve.Message.mineUpdated"),LOG_LEVEL_NOTICE);return"CHECKAGAIN"}return"IGNORE"}async _fetchRemotePreferredTweakValues(trialSetting){try{const replicator=await this.services.replicator.getNewReplicator(trialSetting);if(!replicator){this._log("The remote type does not support preferred tweak values.",LOG_LEVEL_NOTICE);return{status:RemotePreferredTweakStatuses_UNSUPPORTED}}return await replicator.getRemotePreferredTweakValues(trialSetting)}catch(ex){this._log("Failed to get the preferred tweak values from the remote.",LOG_LEVEL_NOTICE);return{status:RemotePreferredTweakStatuses_UNAVAILABLE,error:ex}}}async _checkAndAskUseRemoteConfiguration(trialSetting){if(trialSetting.remoteType===REMOTE_P2P)return{result:!1,requireFetch:!1};const preferred=await this.services.tweakValue.fetchRemotePreferred(trialSetting);return preferred.status===RemotePreferredTweakStatuses_AVAILABLE?await this.services.tweakValue.askUseRemoteConfiguration(trialSetting,preferred.values):{result:!1,requireFetch:!1}}async _askUseRemoteConfiguration(trialSetting,preferred){const localTweaks=extractObject(TweakValuesTemplate,this.settings),mismatchedKeys=this._collectMismatchedTweakKeys(localTweaks,preferred),autoAcceptSide=await this._shouldAutoAcceptCompatibleLossy(localTweaks,preferred,mismatchedKeys);if("REMOTE"===autoAcceptSide)return{result:{...trialSetting,...preferred},requireFetch:!1};if("CURRENT"===autoAcceptSide)return{result:!1,requireFetch:!1};const items=Object.entries(TweakValuesShouldMatchedTemplate);let rebuildRequired=!1,rebuildRecommended=!1,differenceCount=0;const tableRows=[];for(const v2 of items){const key3=v2[0],remoteValueForDisplay=escapeMarkdownValue(valueToString(preferred[key3])),currentValueForDisplay=escapeMarkdownValue(valueToString(null==trialSetting?void 0:trialSetting[key3]));if((null==trialSetting?void 0:trialSetting[key3])!==preferred[key3]){-1!==IncompatibleChanges.indexOf(key3)&&(rebuildRequired=!0);for(const pattern of IncompatibleChangesInSpecificPattern){if(pattern.key!==key3)continue;const isFromConditionMet="from"in pattern&&pattern.from===(null==trialSetting?void 0:trialSetting[key3]),isToConditionMet="to"in pattern&&pattern.to===preferred[key3];(isFromConditionMet||isToConditionMet)&&(pattern.isRecommendation?rebuildRecommended=!0:rebuildRequired=!0)}-1!==CompatibleButLossyChanges.indexOf(key3)&&(rebuildRecommended=!0);tableRows.push($msg("TweakMismatchResolve.Table.Row",{name:localisedConfName(key3),self:currentValueForDisplay,remote:remoteValueForDisplay}));differenceCount++}}if(0===differenceCount){this._log("The settings in the remote database are the same as the local database.",LOG_LEVEL_NOTICE);return{result:!1,requireFetch:!1}}const additionalMessage=rebuildRequired&&this.core.settings.isConfigured?$msg("TweakMismatchResolve.Message.UseRemote.WarningRebuildRequired"):"",additionalMessage2=rebuildRecommended&&this.core.settings.isConfigured?$msg("TweakMismatchResolve.Message.UseRemote.WarningRebuildRecommended"):"",table3=$msg("TweakMismatchResolve.Table",{rows:tableRows.join("\n")}),message=$msg("TweakMismatchResolve.Message.Main",{table:table3,additionalMessage:[additionalMessage,additionalMessage2].filter(v2=>v2).join("\n")}),CHOICE_USE_REMOTE=$msg("TweakMismatchResolve.Action.UseConfigured"),CHOICE_DISMISS=$msg("TweakMismatchResolve.Action.Dismiss"),CHOICES=[CHOICE_USE_REMOTE,CHOICE_DISMISS],retKey=await this.core.confirm.askSelectStringDialogue(message,CHOICES,{title:$msg("TweakMismatchResolve.Title.UseRemoteConfig"),timeout:0,defaultAction:CHOICE_DISMISS});return retKey?retKey===CHOICE_DISMISS?{result:!1,requireFetch:!1}:retKey===CHOICE_USE_REMOTE?{result:{...trialSetting,...preferred},requireFetch:rebuildRequired}:{result:!1,requireFetch:!1}:{result:!1,requireFetch:!1}}onBindFunction(core,services){services.setting.onBeforeSaveSettingData.addHandler(this._onBeforeSaveSettingData.bind(this));services.tweakValue.fetchRemotePreferred.setHandler(this._fetchRemotePreferredTweakValues.bind(this));services.tweakValue.checkAndAskResolvingMismatched.setHandler(this._checkAndAskResolvingMismatchedTweaks.bind(this));services.tweakValue.askResolvingMismatched.setHandler(this._askResolvingMismatchedTweaks.bind(this));services.tweakValue.checkAndAskUseRemoteConfiguration.setHandler(this._checkAndAskUseRemoteConfiguration.bind(this));services.tweakValue.askUseRemoteConfiguration.setHandler(this._askUseRemoteConfiguration.bind(this));services.replication.checkConnectionFailure.addHandler(this._anyAfterConnectCheckFailed.bind(this))}};ModuleLiveSyncMain=class extends AbstractModule{async _onLiveSyncReady(){if(!await this.core.services.appLifecycle.onLayoutReady())return!1;eventHub.emitEvent(EVENT_LAYOUT_READY);if(this.settings.suspendFileWatching||this.settings.suspendParseReplicationResult){const ANSWER_KEEP=$msg("moduleLiveSyncMain.optionKeepLiveSyncDisabled"),ANSWER_RESUME=$msg("moduleLiveSyncMain.optionResumeAndRestart"),message=$msg("moduleLiveSyncMain.msgScramEnabled",{fileWatchingStatus:this.settings.suspendFileWatching?"suspended":"active",parseReplicationStatus:this.settings.suspendParseReplicationResult?"suspended":"active"});if(await this.core.confirm.askSelectStringDialogue(message,[ANSWER_KEEP,ANSWER_RESUME],{defaultAction:ANSWER_KEEP,title:$msg("moduleLiveSyncMain.titleScramEnabled")})==ANSWER_RESUME){this.settings.suspendFileWatching=!1;this.settings.suspendParseReplicationResult=!1;await this.saveSettings();this.services.appLifecycle.scheduleRestart();return!1}}const isInitialized=await this.services.databaseEvents.initialiseDatabase(!1,!1);if(!isInitialized)return!1;if(!await this.core.services.appLifecycle.onFirstInitialise())return!1;await this.services.control.applySettings();fireAndForget(async()=>{this._log($msg("moduleLiveSyncMain.logAdditionalSafetyScan"),LOG_LEVEL_VERBOSE);await this.services.appLifecycle.onScanningStartupIssues()?this._log($msg("moduleLiveSyncMain.logSafetyScanCompleted"),LOG_LEVEL_VERBOSE):this._log($msg("moduleLiveSyncMain.logSafetyScanFailed"),LOG_LEVEL_NOTICE)});return!0}_wireUpEvents(){eventHub.onEvent(EVENT_SETTING_SAVED,settings=>{fireAndForget(async()=>{var _a13;try{const lang=null==(_a13=this.core.services.setting.currentSettings())?void 0:_a13.displayLanguage;void 0!==lang&&setLang(lang);this.core.services.database.isDatabaseReady()&&await this.core.services.control.applySettings();eventHub.emitEvent(EVENT_REQUEST_RELOAD_SETTING_TAB2)}catch(e3){this._log("Error in Setting Save Event",LOG_LEVEL_NOTICE);this._log(e3,LOG_LEVEL_VERBOSE)}})});return Promise.resolve(!0)}async _onLiveSyncLoad(){initialiseWorkerModule(this.services.context.events);await this.services.appLifecycle.onWireUpEvents();eventHub.emitEvent(EVENT_PLUGIN_LOADED2);this._log($msg("moduleLiveSyncMain.logLoadingPlugin"));if(!await this.services.appLifecycle.onInitialise()){this._log($msg("moduleLiveSyncMain.logPluginInitCancelled"),LOG_LEVEL_NOTICE);return!1}this._log($msg("moduleLiveSyncMain.logPluginVersion",{manifestVersion,packageVersion}));await this.services.setting.loadSettings();if(!await this.services.appLifecycle.onSettingLoaded()){this._log($msg("moduleLiveSyncMain.logPluginInitCancelled"),LOG_LEVEL_NOTICE);return!1}await this.services.database.openDatabase({databaseEvents:this.services.databaseEvents,replicator:this.services.replicator});await this.core.services.appLifecycle.onLoaded();await Promise.all(this.core.addOns.map(e3=>Promise.resolve(e3.onload())));return!0}onBindFunction(core,services){super.onBindFunction(core,services);services.appLifecycle.onReady.addHandler(this._onLiveSyncReady.bind(this));services.appLifecycle.onWireUpEvents.addHandler(this._wireUpEvents.bind(this));services.appLifecycle.onLoad.addHandler(this._onLiveSyncLoad.bind(this))}};ModuleBasicMenu=class extends AbstractModule{_everyOnloadStart(){this.addCommand({id:"livesync-replicate",name:$msg("Sync now"),callback:async()=>{await this.services.replication.replicate()}});this.addCommand({id:"livesync-dump",name:$msg("Copy database information for the active file"),checkCallback:checking=>{const file=this.services.vault.getActiveFilePath();if(!file)return!1;checking||fireAndForget(()=>copyFileDatabaseInfo(this.core,file));return!0}});this.addCommand({id:"livesync-toggle",name:"Toggle LiveSync",callback:async()=>{if(this.settings.liveSync){this.settings.liveSync=!1;this._log("LiveSync Disabled.",LOG_LEVEL_NOTICE)}else{this.settings.liveSync=!0;this._log("LiveSync Enabled.",LOG_LEVEL_NOTICE)}await this.services.control.applySettings();await this.services.setting.saveSettingData()}});this.addCommand({id:"livesync-suspendall",name:"Toggle All Sync.",callback:async()=>{if(this.services.appLifecycle.isSuspended()){this.services.appLifecycle.setSuspended(!1);this._log("Self-hosted LiveSync resumed",LOG_LEVEL_NOTICE)}else{this.services.appLifecycle.setSuspended(!0);this._log("Self-hosted LiveSync suspended",LOG_LEVEL_NOTICE)}await this.services.control.applySettings();await this.services.setting.saveSettingData()}});this.addCommand({id:"livesync-scan-files",name:"Scan storage and database again",checkCallback:checking=>{if(!this.settings.useAdvancedMode)return!1;checking||fireAndForget(()=>this.services.vault.scanVault(!0));return!0}});this.addCommand({id:"livesync-runbatch",name:$msg("Apply pending changes now"),callback:async()=>{await this.services.fileProcessing.commitPendingFileEvents()}});this.addCommand({id:"livesync-abortsync",name:"Abort synchronization immediately",checkCallback:checking=>{if(!this.settings.useAdvancedMode)return!1;checking||this.core.replicator.terminateSync();return!0}});return Promise.resolve(!0)}onBindFunction(core,services){services.appLifecycle.onInitialise.addHandler(this._everyOnloadStart.bind(this))}};LiveSyncBaseCore=class{constructor(serviceHub,serviceModuleInitialiser,extraModuleInitialiser,addOnsInitialiser,featuresInitialiser){this.addOns=[];this._services=void 0;this.modules=[];this._services=serviceHub;this._serviceModules=serviceModuleInitialiser(this,serviceHub);const extraModules=extraModuleInitialiser(this);this.registerModules(extraModules);this.initialiseServiceFeatures();featuresInitialiser(this);const addOns=addOnsInitialiser(this);for(const addOn of addOns)this._registerAddOn(addOn);this.bindModuleFunctions()}_registerAddOn(addOn){this.addOns.push(addOn);this.services.appLifecycle.onUnload.addHandler(()=>Promise.resolve(addOn.onunload()).then(()=>!0))}getAddOn(cls){for(const addon of this.addOns)if(addon.constructor.name==cls)return addon}get services(){if(!this._services)throw new Error("Services not initialised yet");return this._services}get serviceModules(){return this._serviceModules}getModule(constructor){for(const module2 of this.modules)if(module2.constructor===constructor)return module2;throw new Error(`Module ${constructor.name} not found or not loaded.`)}_registerModule(module2){this.modules.push(module2)}registerModules(extraModules=[]){this._registerModule(new ModuleLiveSyncMain(this));this._registerModule(new ModuleConflictChecker(this));this._registerModule(new ModuleReplicatorMinIO(this));this._registerModule(new ModuleReplicatorCouchDB(this));this._registerModule(new ModuleReplicator(this));this._registerModule(new ModuleConflictResolver(this));this._registerModule(new ModulePeriodicProcess(this));this._registerModule(new ModuleResolvingMismatchedTweaks(this));this._registerModule(new ModuleBasicMenu(this));for(const module2 of extraModules)this._registerModule(module2)}bindModuleFunctions(){var _a13,_b6;for(const module2 of this.modules)if(module2 instanceof AbstractModule){module2.onBindFunction(this,this.services);__$checkInstanceBinding(module2)}else{const moduleName=null!=(_b6=null==(_a13=null==module2?void 0:module2.constructor)?void 0:_a13.name)?_b6:"unknown";this.services.API.addLog(`Module ${moduleName} does not have onBindFunction, skipping binding.`,LOG_LEVEL_INFO)}}get confirm(){return this.services.UI.confirm}get settings(){return this.services.setting.settings}set settings(value){this.services.setting.settings=value}getSettings(){return this.settings}get localDatabase(){return this.services.database.localDatabase}getDatabase(){return this.localDatabase.localDatabase}get simpleStore(){return this.services.keyValueDB.simpleStore}get replicator(){return this.services.replicator.getActiveReplicator()}get kvDB(){return this.services.keyValueDB.kvDB}get storageAccess(){return this.serviceModules.storageAccess}get databaseFileAccess(){return this.serviceModules.databaseFileAccess}get fileHandler(){return this.serviceModules.fileHandler}get rebuilder(){return this.serviceModules.rebuilder}initialiseServiceFeatures(){useTargetFilters(this);usePrepareDatabaseForUse(this);useRemoteConfigurationMigration(this)}};ModuleObsidianMenu=class extends AbstractModule{_everyOnloadStart(){(0,import_obsidian.addIcon)("replicate",'<g transform="matrix(1.15 0 0 1.15 -8.31 -9.52)" fill="currentColor" fill-rule="evenodd">\n <path d="m85 22.2c-0.799-4.74-4.99-8.37-9.88-8.37-0.499 0-1.1 0.101-1.6 0.101-2.4-3.03-6.09-4.94-10.3-4.94-6.09 0-11.2 4.14-12.8 9.79-5.59 1.11-9.78 6.05-9.78 12 0 6.76 5.39 12.2 12 12.2h29.9c5.79 0 10.1-4.74 10.1-10.6 0-4.84-3.29-8.88-7.68-10.2zm-2.99 14.7h-29.5c-2.3-0.202-4.29-1.51-5.29-3.53-0.899-2.12-0.699-4.54 0.698-6.46 1.2-1.61 2.99-2.52 4.89-2.52 0.299 0 0.698 0 0.998 0.101l1.8 0.303v-2.02c0-3.63 2.4-6.76 5.89-7.57 0.599-0.101 1.2-0.202 1.8-0.202 2.89 0 5.49 1.62 6.79 4.24l0.598 1.21 1.3-0.504c0.599-0.202 1.3-0.303 2-0.303 1.3 0 2.5 0.404 3.59 1.11 1.6 1.21 2.6 3.13 2.6 5.15v1.61h2c2.6 0 4.69 2.12 4.69 4.74-0.099 2.52-2.2 4.64-4.79 4.64z"/>\n <path d="m53.2 49.2h-41.6c-1.8 0-3.2 1.4-3.2 3.2v28.6c0 1.8 1.4 3.2 3.2 3.2h15.8v4h-7v6h24v-6h-7v-4h15.8c1.8 0 3.2-1.4 3.2-3.2v-28.6c0-1.8-1.4-3.2-3.2-3.2zm-2.8 29h-36v-23h36z"/>\n <path d="m73 49.2c1.02 1.29 1.53 2.97 1.53 4.56 0 2.97-1.74 5.65-4.39 7.04v-4.06l-7.46 7.33 7.46 7.14v-4.06c7.66-1.98 12.2-9.61 10-17-0.102-0.297-0.205-0.595-0.307-0.892z"/>\n <path d="m24.1 43c-0.817-0.991-1.53-2.97-1.53-4.56 0-2.97 1.74-5.65 4.39-7.04v4.06l7.46-7.33-7.46-7.14v4.06c-7.66 1.98-12.2 9.61-10 17 0.102 0.297 0.205 0.595 0.307 0.892z"/>\n </g>');this.addRibbonIcon("replicate",$msg("moduleObsidianMenu.replicate"),async()=>{await this.services.replication.replicate(!0)}).addClass("livesync-ribbon-replicate");return Promise.resolve(!0)}onBindFunction(core,services){services.appLifecycle.onInitialise.addHandler(this._everyOnloadStart.bind(this))}};SETTING_HEADER="````yaml:livesync-setting\n";SETTING_FOOTER="\n````";ModuleObsidianSettingsAsMarkdown=class extends AbstractModule{_everyOnloadStart(){this.addCommand({id:"livesync-export-config",name:"Write setting markdown manually",checkCallback:checking=>{if(checking)return""!=this.settings.settingSyncFile;fireAndForget(async()=>{await this.services.setting.saveSettingData()})}});this.addCommand({id:"livesync-import-config",name:"Parse setting file",editorCheckCallback:(checking,editor,ctx)=>{if(checking){const doc=editor.getValue(),ret=this.extractSettingFromWholeText(doc);return""!=ret.body}if(ctx.file){const file=ctx.file;fireAndForget(async()=>await this.checkAndApplySettingFromMarkdown(file.path,!1))}}});eventHub.onEvent("event-file-changed",info3=>{fireAndForget(()=>this.checkAndApplySettingFromMarkdown(info3.file,info3.automated))});eventHub.onEvent(EVENT_SETTING_SAVED,settings=>{""!=settings.settingSyncFile&&fireAndForget(()=>this.saveSettingToMarkdown(settings.settingSyncFile))});return Promise.resolve(!0)}extractSettingFromWholeText(data){if(-1===data.indexOf(SETTING_HEADER))return{preamble:data,body:"",postscript:""};const startMarkerPos=data.indexOf(SETTING_HEADER),dataStartPos=-1==startMarkerPos?data.length:startMarkerPos,endMarkerPos=-1==startMarkerPos?data.length:data.indexOf(SETTING_FOOTER,dataStartPos),dataEndPos=-1==endMarkerPos?data.length:endMarkerPos,body=data.substring(dataStartPos+SETTING_HEADER.length,dataEndPos),ret={preamble:data.substring(0,dataStartPos),body,postscript:data.substring(dataEndPos+SETTING_FOOTER.length+1)};return ret}async parseSettingFromMarkdown(filename,data){const file=await this.core.storageAccess.isExists(filename);if(!file)return{preamble:"",body:"",postscript:""};if(data)return this.extractSettingFromWholeText(data);const parseData=null!=data?data:await this.core.storageAccess.readFileText(filename);return this.extractSettingFromWholeText(parseData)}async checkAndApplySettingFromMarkdown(filename,automated){if(automated&&!this.settings.notifyAllSettingSyncFile&&(!this.settings.settingSyncFile||this.settings.settingSyncFile!=filename)){this._log(`Setting file (${filename}) does not match the current configuration. skipped.`,LOG_LEVEL_DEBUG);return}const{body}=await this.parseSettingFromMarkdown(filename);let newSetting={};try{const parsed=(0,import_obsidian.parseYaml)(body);if("object"!=typeof parsed||null===parsed)throw new TypeError("The YAML settings must contain an object");newSetting=parsed}catch(ex){this._log("Could not parse YAML",LOG_LEVEL_NOTICE);this._log(ex,LOG_LEVEL_VERBOSE);return}if("settingSyncFile"in newSetting&&newSetting.settingSyncFile!=filename){this._log("This setting file seems to backed up one. Please fix the filename or settingSyncFile value.",automated?LOG_LEVEL_INFO:LOG_LEVEL_NOTICE);return}let settingToApply={...DEFAULT_SETTINGS};settingToApply={...settingToApply,...newSetting};if(!(null==settingToApply?void 0:settingToApply.writeCredentialsForSettingSync)){settingToApply.couchDB_USER=this.settings.couchDB_USER;settingToApply.couchDB_PASSWORD=this.settings.couchDB_PASSWORD;settingToApply.passphrase=this.settings.passphrase}const oldSetting=this.generateSettingForMarkdown(this.settings,settingToApply.writeCredentialsForSettingSync);if(!isObjectDifferent(oldSetting,this.generateSettingForMarkdown(settingToApply))){this._log("Setting markdown has been detected, but not changed.",automated?LOG_LEVEL_INFO:LOG_LEVEL_NOTICE);return}const addMsg=this.settings.settingSyncFile!=filename?" (This is not-active file)":"";this.core.confirm.askInPopup("apply-setting-from-md",`Setting markdown ${filename}${addMsg} has been detected. Apply this from {HERE}.`,anchor=>{anchor.text="HERE";anchor.addEventListener("click",()=>{fireAndForget(async()=>{const APPLY_AND_RESTART="Apply settings and restart obsidian",APPLY_AND_REBUILD="Apply settings and restart obsidian with red_flag_rebuild.md",APPLY_AND_FETCH="Apply settings and restart obsidian with red_flag_fetch.md",result=await this.core.confirm.askSelectStringDialogue("Ready for apply the setting.",[APPLY_AND_RESTART,"Apply settings",APPLY_AND_FETCH,APPLY_AND_REBUILD,"Cancel"],{defaultAction:APPLY_AND_RESTART});if("Apply settings"==result||result==APPLY_AND_RESTART||result==APPLY_AND_REBUILD||result==APPLY_AND_FETCH){await this.services.setting.applyExternalSettings(settingToApply,!0);this.services.setting.clearUsedPassphrase();if("Apply settings"==result){this._log("Loaded settings have been applied!",LOG_LEVEL_NOTICE);return}result==APPLY_AND_REBUILD&&await this.core.rebuilder.scheduleRebuild();result==APPLY_AND_FETCH&&await this.core.rebuilder.scheduleFetch();this.services.appLifecycle.performRestart()}})})})}generateSettingForMarkdown(settings,keepCredential){const saveData={...settings||this.settings};delete saveData.encryptedCouchDBConnection;delete saveData.encryptedPassphrase;delete saveData.additionalSuffixOfDatabaseName;if(!saveData.writeCredentialsForSettingSync&&!keepCredential){delete saveData.couchDB_USER;delete saveData.couchDB_PASSWORD;delete saveData.passphrase;delete saveData.jwtKey;delete saveData.jwtKid;delete saveData.jwtSub;delete saveData.couchDB_CustomHeaders;delete saveData.bucketCustomHeaders}return saveData}async saveSettingToMarkdown(filename){const saveData=this.generateSettingForMarkdown(),file=await this.core.storageAccess.isExists(filename);if(!file){await this.core.storageAccess.ensureDir(filename);const initialContent='This file contains Self-hosted LiveSync settings as YAML.\nExcept for the `livesync-setting` code block, we can add a note for free.\n\nIf the name of this file matches the value of the "settingSyncFile" setting inside the `livesync-setting` block, LiveSync will tell us whenever the settings change. We can decide to accept or decline the remote setting. (In other words, we can back up this file by renaming it to another name).\n\nWe can perform a command in this file.\n- `Parse setting file` : load the setting from the file.\n\n**Note** Please handle it with all of your care if you have configured to write credentials in.\n\n\n';await this.core.storageAccess.writeFileAuto(filename,initialContent+SETTING_HEADER+"\n"+SETTING_FOOTER)}const data=await this.core.storageAccess.readFileText(filename),{preamble,body,postscript}=this.extractSettingFromWholeText(data),newBody=(0,import_obsidian.stringifyYaml)(saveData);if(newBody==body)this._log("Markdown setting: Nothing had been changed",LOG_LEVEL_VERBOSE);else{await this.core.storageAccess.writeFileAuto(filename,preamble+SETTING_HEADER+newBody+SETTING_FOOTER+postscript);this._log(`Markdown setting: ${filename} has been updated!`,LOG_LEVEL_VERBOSE)}}onBindFunction(core,services){services.appLifecycle.onInitialise.addHandler(this._everyOnloadStart.bind(this))}};ConditionType=(ConditionType2=>{ConditionType2.PLATFORM_CASE_INSENSITIVE="platform-case-insensitive";ConditionType2.PLATFORM_CASE_SENSITIVE="platform-case-sensitive";ConditionType2.REMOTE_CASE_SENSITIVE="remote-case-sensitive";return ConditionType2})(ConditionType||{});RuleLevel=(RuleLevel2=>{RuleLevel2[RuleLevel2.Must=0]="Must";RuleLevel2[RuleLevel2.Necessary=1]="Necessary";RuleLevel2[RuleLevel2.Recommended=2]="Recommended";RuleLevel2[RuleLevel2.Optional=3]="Optional";return RuleLevel2})(RuleLevel||{});DoctorRegulationV0_24_16={version:"0.24.16",rules:{sendChunksBulk:{value:!1,reason:"Automatic bulk chunk pre-send is obsolete and must remain disabled",level:0},sendChunksBulkMaxSize:{value:1,reason:"Use a conservative request size for the explicit manual chunk resend tool",level:0},doNotUseFixedRevisionForChunks:{value:!0,reason:"This value has been reverted at v0.24.16 for garbage collection of chunks.",level:2},handleFilenameCaseSensitive:{value:!1,reason:"If Self-hosted LiveSync is Case-Sensitive, unexpected file operations may occur when synchronising with Windows, Android or other devices. This value should only be enabled if all devices have a Case-Sensitive file system.",requireRebuild:!0,level:2},useIndexedDBAdapter:{value:!0,requireRebuildLocal:!0,level:3,reason:"The old option is active. This is not a performance-appropriate setting."},useEden:{reason:"This option is no longer recommended.",level:3,value:!1},hashAlg:{obsoleteValues:["sha1","xxhash32",""],value:"xxhash64",level:1,reason:"The hash function is set to the old fallback. This should be retried. This may result in a change to the new fallback."},disableCheckingConfigMismatch:{value:!1,level:2,reason:"If you disabled an older version of the dialogue because it was hard to understand, try it once in the latest version."},enableCompression:{value:!1,level:2,requireRebuild:!0,reason:"This option will be sunset soon."}}};DoctorRegulationV0_24_30_rules={...DoctorRegulationV0_24_16.rules,usePluginSyncV2:{value:!0,level:2,reason:"This option is now enabled by default. If you have problems with the new plugin, please report them."},chunkSplitterVersion:{value:"v3-rabin-karp",valueDisplay:ChunkAlgorithmNames["v3-rabin-karp"],level:2,reason:"Chunk splitting has been optimised for more effective de-duplication. This is the new default value."},customChunkSize:{min:55,value:60,valueDisplay:"60 (detected on if less than 55)",level:2,detectionFunc:settings=>(null==settings?void 0:settings.remoteType)===REMOTE_COUCHDB&&"v3-rabin-karp"===(null==settings?void 0:settings.chunkSplitterVersion)&&!isCloudantURI((null==settings?void 0:settings.couchDB_URI)||""),reason:"With the V3 Rabin-Karp chunk splitter and Self-hosted CouchDB, the chunk size is set to 60 (means around 6MB) by default. This is in effect the maximum chunk size, which in practice is divided more finely."}};DoctorRegulationV0_25_0_rules={...DoctorRegulationV0_24_30_rules,E2EEAlgorithm:{value:E2EEAlgorithms.V2,valueDisplay:E2EEAlgorithmNames[E2EEAlgorithms.V2],level:2,reasonFunc:(_settings,translate)=>translate("Doctor.RULES.E2EE_V02500.REASON")}};DoctorRegulationV0_25_27_rules={...DoctorRegulationV0_25_0_rules,useIndexedDBAdapter:void 0,doNotUseFixedRevisionForChunks:void 0};DoctorRegulationV1_0_0={version:"1.0.0",rules:{...DoctorRegulationV0_25_27_rules,enableCompression:void 0}};DoctorRegulation=DoctorRegulationV1_0_0;RebuildOptions_AutomaticAcceptable=0,RebuildOptions_ConfirmIfRequired=1,RebuildOptions_SkipEvenIfRequired=2;ONBOARDING_NOTICE_DURATION_MS=6e4;INCOMPLETE_DOCUMENT_NOTICE_GROUP="startup-integrity-check";ModuleMigration=class extends AbstractModule{constructor(core,waitForCompatibilityReview=()=>Promise.resolve()){super(core);this.waitForCompatibilityReview=waitForCompatibilityReview}async migrateUsingDoctor(skipRebuild=!1,activateReason="updated",forceRescan=!1){const{shouldRebuild,shouldRebuildLocal,isModified,settings}=await performDoctorConsultation({confirm:this.core.confirm,translate:this.services.context.translate},this.settings,{localRebuild:skipRebuild?RebuildOptions_SkipEvenIfRequired:RebuildOptions_AutomaticAcceptable,remoteRebuild:skipRebuild?RebuildOptions_SkipEvenIfRequired:RebuildOptions_AutomaticAcceptable,activateReason,forceRescan});if(isModified){this.settings=settings;await this.saveSettings()}if(!skipRebuild){if(shouldRebuild){await this.core.rebuilder.scheduleRebuild();this.services.appLifecycle.performRestart();return!1}if(shouldRebuildLocal){await this.core.rebuilder.scheduleFetch();this.services.appLifecycle.performRestart();return!1}}return!0}async migrateDisableBulkSend(){if(disableLegacyBulkChunkPreSend(this.settings)){this._log($msg("moduleMigration.logBulkSendCorrupted"),LOG_LEVEL_NOTICE);await this.saveSettings()}}initialMessage(){const manager=this.core.getModule(SetupManager);showOnboardingInvitation(this.core,manager)}async hasIncompleteDocs(force=!1){const incompleteDocsChecked=await this.core.kvDB.get("checkIncompleteDocs")||!1;if(incompleteDocsChecked&&!force){this._log("Incomplete docs check already done, skipping.",LOG_LEVEL_VERBOSE);return Promise.resolve(!0)}const noticeGroups=this.core.services.context.noticeGroups;noticeGroups.setItem(INCOMPLETE_DOCUMENT_NOTICE_GROUP,"checking",{message:"Checking for incomplete documents..."});this._log("Checking for incomplete documents...",LOG_LEVEL_VERBOSE);try{const errorFiles=[];for await(const metaDoc of this.localDatabase.findAllNormalDocs({conflicts:!0})){const path2=this.getPath(metaDoc);if(!isValidPath(path2))continue;if(!await this.services.vault.isTargetFile(path2))continue;if(!isMetaEntry(metaDoc))continue;const doc=await this.localDatabase.getDBEntryFromMeta(metaDoc);if(!doc||!isLoadedEntry(doc))continue;if(isDeletedEntry(doc))continue;const isConflicted=(null==metaDoc?void 0:metaDoc._conflicts)&&metaDoc._conflicts.length>0;let storageFileContent;try{storageFileContent=await this.core.storageAccess.readHiddenFileBinary(path2)}catch(e3){Logger(`Failed to read file ${path2}: Possibly unprocessed or missing`);Logger(e3,LOG_LEVEL_VERBOSE);continue}const sizeOnStorage=storageFileContent.byteLength,recordedSize=doc.size,docBlob=readAsBlob(doc),actualSize=docBlob.size;if(recordedSize!==actualSize||sizeOnStorage!==actualSize||sizeOnStorage!==recordedSize||isConflicted){const contentMatched=await isDocContentSame(doc.data,storageFileContent);errorFiles.push({path:path2,recordedSize,actualSize,storageSize:sizeOnStorage,contentMatched,isConflicted});Logger(`Size mismatch for ${path2}: ${recordedSize} (DB Recorded) , ${actualSize} (DB Stored) , ${sizeOnStorage} (Storage Stored), ${contentMatched?"Content Matched":"Content Mismatched"} ${isConflicted?"Conflicted":"Not Conflicted"}`)}}if(0==errorFiles.length){Logger("No size mismatches found",LOG_LEVEL_INFO);noticeGroups.setItem(INCOMPLETE_DOCUMENT_NOTICE_GROUP,"result",{message:"No size mismatches found"});await this.core.kvDB.set("checkIncompleteDocs",!0);return Promise.resolve(!0)}Logger(`Found ${errorFiles.length} size mismatches`,LOG_LEVEL_INFO);noticeGroups.setItem(INCOMPLETE_DOCUMENT_NOTICE_GROUP,"result",{message:`Found ${errorFiles.length} size mismatches`});const recoverable=errorFiles.filter(e3=>e3.recordedSize===e3.storageSize&&!e3.isConflicted),unrecoverable=errorFiles.filter(e3=>e3.recordedSize!==e3.storageSize||e3.isConflicted),fileInfo=e3=>`${e3.path} (M: ${e3.recordedSize}, A: ${e3.actualSize}, S: ${e3.storageSize}) ${e3.isConflicted?"(Conflicted)":""}`,messageUnrecoverable=unrecoverable.length>0?$msg("moduleMigration.fix0256.messageUnrecoverable",{filesNotRecoverable:unrecoverable.map(e3=>`- ${fileInfo(e3)}`).join("\n")}):"",message=$msg("moduleMigration.fix0256.message",{files:recoverable.map(e3=>`- ${fileInfo(e3)}`).join("\n"),messageUnrecoverable}),CHECK_IT_LATER=$msg("moduleMigration.fix0256.buttons.checkItLater"),FIX=$msg("moduleMigration.fix0256.buttons.fix"),DISMISS=$msg("moduleMigration.fix0256.buttons.DismissForever"),ret=await this.core.confirm.askSelectStringDialogue(message,[CHECK_IT_LATER,FIX,DISMISS],{title:$msg("moduleMigration.fix0256.title"),defaultAction:CHECK_IT_LATER});if(ret==FIX)for(const file of recoverable){const stubFile=await this.core.storageAccess.getFileStub(file.path);if(null==stubFile){Logger(`Could not find stub file for ${file.path}`,LOG_LEVEL_NOTICE);continue}stubFile.stat.mtime=Date.now();const result=await this.core.fileHandler.storeFileToDB(stubFile,!0,!1);result?Logger(`Successfully restored ${file.path} from storage`):Logger(`Failed to restore ${file.path} from storage`,LOG_LEVEL_NOTICE)}else ret===DISMISS&&await this.core.kvDB.set("checkIncompleteDocs",!0);return Promise.resolve(!0)}catch(error){noticeGroups.setItem(INCOMPLETE_DOCUMENT_NOTICE_GROUP,"result",{message:"The incomplete document check could not be completed."});throw error}finally{noticeGroups.finish(INCOMPLETE_DOCUMENT_NOTICE_GROUP)}}async hasCompromisedChunks(){Logger("Checking for compromised chunks...",LOG_LEVEL_VERBOSE);if(!this.settings.encrypt)return!0;const localCompromised=await countCompromisedChunks(this.localDatabase.localDatabase),remote=this.services.replicator.getActiveReplicator(),remoteCompromised=this.services.API.isOnline?await(null==remote?void 0:remote.countCompromisedChunks()):0;if(!1===localCompromised){Logger("Failed to count compromised chunks in local database",LOG_LEVEL_NOTICE);return!1}if(!1===remoteCompromised){Logger("Failed to count compromised chunks in remote database",LOG_LEVEL_NOTICE);return!1}if(0===remoteCompromised&&0===localCompromised)return!0;Logger(`Found compromised chunks : ${localCompromised} in local, ${remoteCompromised} in remote`,LOG_LEVEL_NOTICE);const title=$msg("moduleMigration.insecureChunkExist.title"),msg=$msg("moduleMigration.insecureChunkExist.message"),REBUILD=$msg("moduleMigration.insecureChunkExist.buttons.rebuild"),FETCH=$msg("moduleMigration.insecureChunkExist.buttons.fetch"),DISMISS=$msg("moduleMigration.insecureChunkExist.buttons.later"),buttons=[REBUILD,FETCH,DISMISS];0!=remoteCompromised&&buttons.splice(buttons.indexOf(FETCH),1);const result=await this.core.confirm.askSelectStringDialogue(msg,buttons,{title,defaultAction:DISMISS,timeout:0});if(result===REBUILD){await this.core.rebuilder.scheduleRebuild();this.services.appLifecycle.performRestart();return!1}if(result===FETCH){await this.core.rebuilder.scheduleFetch();this.services.appLifecycle.performRestart();return!1}this._log($msg("moduleMigration.insecureChunkExist.laterMessage"),LOG_LEVEL_NOTICE);return!0}async _everyOnFirstInitialize(){return await runConfiguredStartupLifecycle({databaseReady:this.localDatabase.isReady,reportDatabaseNotReady:()=>this._log($msg("moduleMigration.logLocalDatabaseNotReady"),LOG_LEVEL_NOTICE),hasCompromisedChunks:()=>this.hasCompromisedChunks(),hasIncompleteDocuments:()=>this.hasIncompleteDocs(),waitForCompatibilityReview:()=>this.waitForCompatibilityReview(),runDoctor:()=>this.migrateUsingDoctor(!1),migrateBulkSend:()=>this.migrateDisableBulkSend()})}_everyOnLayoutReady(){const shouldInitialiseDatabase=runStartupEntryLifecycle({configured:!0===this.settings.isConfigured,inviteToOnboarding:()=>this.initialMessage()});if(!shouldInitialiseDatabase)return Promise.resolve(!1);eventHub.onEvent(EVENT_REQUEST_RUN_DOCTOR,async reason=>{await this.migrateUsingDoctor(!1,reason,!0)});eventHub.onEvent(EVENT_REQUEST_RUN_FIX_INCOMPLETE,async()=>{await this.hasIncompleteDocs(!0)});return Promise.resolve(!0)}onBindFunction(core,services){super.onBindFunction(core,services);services.appLifecycle.onLayoutReady.addHandler(this._everyOnLayoutReady.bind(this));services.appLifecycle.onFirstInitialise.addHandler(this._everyOnFirstInitialize.bind(this))}};ObsidianLanguageAppliedNotice=class{show(openDetails){var _a13,_b6,_c3;this.clear();let reminderAnchor;const appliedMessage=null!=(_b6=null==(_a13=$msg("dialog.yourLanguageAvailable").split(/\r?\n\s*\r?\n/u,1)[0])?void 0:_a13.trim())?_b6:$msg("Display Language"),fragment=createFragment(documentFragment=>{documentFragment.createSpan({text:`${appliedMessage} `});documentFragment.createEl("a",{text:$msg("Open the dialog")},anchor=>{reminderAnchor=anchor;anchor.addEventListener("click",event2=>{event2.preventDefault();this.clear();openDetails()})})});this.reminder=new import_obsidian.Notice(fragment,0);null==(_c3=null==reminderAnchor?void 0:reminderAnchor.closest(".notice"))||_c3.classList.add("livesync-language-applied-notice")}clear(){var _a13;null==(_a13=this.reminder)||_a13.hide();this.reminder=void 0}};enableI18nFeature=function createServiceFeature(featureFunction){return featureFunction}(async({services:{setting,API,appLifecycle}})=>{__onMissingTranslation(()=>{});let isChanged=!1;const settings=setting.currentSettings();if(""==settings.displayLanguage){const obsidianLanguage=tryGetLanguage(error=>{API.addLog(`Failed to get Obsidian language; defaulting to 'en': ${String(error)}`,LOG_LEVEL_VERBOSE,"i18n-language")});if(-1!==SUPPORTED_I18N_LANGS.indexOf(obsidianLanguage)&&obsidianLanguage!=settings.displayLanguage){await setting.applyPartial({displayLanguage:obsidianLanguage});isChanged=!0;setLang(obsidianLanguage)}else if(""==settings.displayLanguage){await setting.applyPartial({displayLanguage:"def"});setLang("def");await setting.saveSettingData()}}if(isChanged){await setting.saveSettingData();const reminder=new ObsidianLanguageAppliedNotice;appLifecycle.onUnload.addHandler(()=>{reminder.clear();return Promise.resolve(!0)});reminder.show(()=>{(async()=>{try{const revert=$msg("dialog.yourLanguageAvailable.btnRevertToDefault");if(await API.confirm.askSelectStringDialogue($msg("dialog.yourLanguageAvailable"),["OK",revert],{defaultAction:"OK",title:$msg("Display Language")})==revert){await setting.applyPartial({displayLanguage:"def"});setLang("def");await setting.saveSettingData()}}catch(error){API.addLog(`Failed to open translation details: ${String(error)}`,LOG_LEVEL_VERBOSE,"i18n-language")}})()})}return!0});REMOTE_SIZE_NOTICE_DURATION_MS=3e5;root38=from_html('<label class="choice-row svelte-kqatc9"><input type="checkbox" class="svelte-kqatc9"/> <span class="choice-title svelte-kqatc9"> </span></label> <div class="choice-notes svelte-kqatc9"><!> <!></div>',1);$$css14={hash:"svelte-kqatc9",code:'.choice-row.svelte-kqatc9 {display:flex;align-items:center;gap:0.5rem;margin-top:1rem;cursor:pointer;}.choice-row.svelte-kqatc9 span.choice-title:where(.svelte-kqatc9) {width:auto;}.choice-row.svelte-kqatc9 input[type="checkbox"]:where(.svelte-kqatc9) {\n /* width: 1.2rem;\n height: 1.2rem; */cursor:pointer;}.choice-notes.svelte-kqatc9 {margin-left:2rem;margin-top:0.25rem;color:var(--text-muted);font-size:0.9rem;}'};root39=from_html("<strong> </strong><br/> ",1);root_131=from_html("<strong> </strong> ",1);root_217=from_html(" <!>",1);root_315=from_html("<!> <!> <!>",1);root_49=from_html("<!> <!>",1);root_59=from_html("<strong> </strong> <br/> ",1);root_69=from_html("<!> <!> <!> <hr/> <!> <hr/> <!> <!> <!>",1);root40=from_html("<!> <!> <!> <!>",1);root_135=from_html(" <strong> </strong>.",1);root_218=from_html("<!> <!>",1);root_316=from_html("<!> <!> <!>",1);root_410=from_html("<strong> <br/> </strong>");root_510=from_html("<!> <hr/> <!> <!> <!>",1);SIMPLE_FETCH_STAGE1_REMOTE_WINS="Overwrite all with remote files";SIMPLE_FETCH_STAGE1_NEWER_WINS="Compare time and take newer";SIMPLE_FETCH_STAGE1_DETAILED="Use the detailed flow";SIMPLE_FETCH_STAGE1_CANCEL="Cancel";SIMPLE_FETCH_STAGE2_REMOTE_DELETE_NONE="Keep local files even if not on remote";SIMPLE_FETCH_STAGE2_REMOTE_DELETE_ALL="Delete local files if not on remote";SIMPLE_FETCH_STAGE2_NEWER_CLEANUP="Delete local files if deleted on remote";SIMPLE_FETCH_STAGE2_NEWER_SYNC_ALL="Keep local files even if deleted on remote";STAGE2_ABORT="Cancel all and reboot";SIMPLE_FETCH_MODE_KEY="simple-fetch-mode";RERUN_PROCESS="Reboot to re-run the process";RELEASE_FLAG_PROCESS="Finalise the process and resume normal operation";REMOTE_KEEP_CURRENT="Use active remote";REMOTE_CANCEL="Cancel";LiveSyncTrysteroReplicator=class extends LiveSyncAbstractReplicator{constructor(env){super(env);__publicField(this,"_p2pHost");__publicField(this,"_replicator");__publicField(this,"_lifecycleOperation",Promise.resolve());__publicField(this,"_shouldBeOpen",!1);__publicField(this,"_activeTransportCompatibilitySignature");this.env=env}get openReplicationUI(){return this.env.openReplicationUI}get rawReplicator(){return this._replicator}get rawHost(){return this._p2pHost}getReplicationPBKDF2Salt(_setting,_refresh){return Promise.resolve(new Uint8Array(32))}terminateSync(){}_buildEnv(){const services=this.env.services;return{events:services.context.events,translate:services.context.translate,get settings(){return services.setting.currentSettings()},get db(){return services.database.localDatabase.localDatabase},get simpleStore(){return services.keyValueDB.openSimpleStore("p2p-sync")},get deviceName(){return services.config.getSmallConfig(SETTING_KEY_P2P_DEVICE_NAME)||services.vault.getVaultName()},get platform(){return services.API.getPlatform()},get confirm(){return services.API.confirm},runFiniteReplicationActivity:(task,options)=>services.replicator.runFiniteReplicationActivity(task,options),canStartOrdinaryReplication:(showMessage2=!1)=>services.replication.onCheckReplicationReady(showMessage2),processReplicatedDocs:async docs=>{const settings=services.setting.currentSettings();if(settings.suspendParseReplicationResult){const docLength=docs.length;docLength>0&&Logger(`P2P sync, but parseReplicationResult is suspended. Ignoring ${docLength} documents.`,LOG_LEVEL_VERBOSE);return}await services.replication.parseSynchroniseResult(docs)}}}_enqueueLifecycleOperation(operation2){const queued=this._lifecycleOperation.catch(()=>{}).then(operation2);this._lifecycleOperation=queued.catch(()=>{});return queued}_getTransportCompatibilitySignature(){var _a13;const settings=this.env.services.setting.currentSettings(),configuredPath=normaliseP2PConnectionPath(settings.P2P_connectionPath),effectivePath=configuredPath===P2PConnectionPaths_Relay&&hasValidP2PTurnServerUrl(null!=(_a13=settings.P2P_turnServers)?_a13:"")?P2PConnectionPaths_Relay:P2PConnectionPaths_Automatic;return`${normaliseP2PMaxWirePayloadBytes(settings.P2P_maxWirePayloadBytes)}:${effectivePath}`}async _closeTransport(){if(this._replicator){this._replicator.disableBroadcastChanges();await this._replicator.close();this._replicator=void 0}this._p2pHost=void 0;this._activeTransportCompatibilitySignature=void 0}async open(){if(this.env.services.setting.currentSettings().P2P_Enabled){this._shouldBeOpen=!0;await this._enqueueLifecycleOperation(async()=>{var _a13;if(!this._shouldBeOpen)return;const compatibilitySignature=this._getTransportCompatibilitySignature();if(this._replicator&&(null==(_a13=this._p2pHost)?void 0:_a13.isServing)){if(this._activeTransportCompatibilitySignature===compatibilitySignature){Logger("P2P replicator is already open.");return}await this._closeTransport()}try{const env=this._buildEnv(),host=new TrysteroReplicatorP2PServer(env),replicator=new TrysteroReplicator(env,host);this._p2pHost=host;this._replicator=replicator;await replicator.open();this._activeTransportCompatibilitySignature=compatibilitySignature}catch(e3){Logger(e3 instanceof Error?e3.message:"Error while opening P2P connection",LOG_LEVEL_NOTICE);Logger(e3,LOG_LEVEL_VERBOSE);this._p2pHost=void 0;this._replicator=void 0;this._activeTransportCompatibilitySignature=void 0}})}else Logger(this.translate("P2P.NotEnabled"),LOG_LEVEL_NOTICE)}async close(){this._shouldBeOpen=!1;await this._enqueueLifecycleOperation(async()=>{await this._closeTransport()})}closeReplication(){var _a13;null==(_a13=this._replicator)||_a13.disconnectFromServer()}get server(){var _a13;return null==(_a13=this._replicator)?void 0:_a13.server}get knownAdvertisements(){var _a13,_b6;return null!=(_b6=null==(_a13=this._replicator)?void 0:_a13.knownAdvertisements)?_b6:[]}enableBroadcastChanges(){var _a13;null==(_a13=this._replicator)||_a13.enableBroadcastChanges()}disableBroadcastChanges(){var _a13;null==(_a13=this._replicator)||_a13.disableBroadcastChanges()}requestStatus(){var _a13;null==(_a13=this._replicator)||_a13.requestStatus()}onNewPeer(peer){var _a13;return null==(_a13=this._replicator)?void 0:_a13.onNewPeer(peer)}onPeerLeaved(peerId){var _a13;null==(_a13=this._replicator)||_a13.onPeerLeaved(peerId)}async replicateFromCommand(showResult=!1){const replicator=this._replicator;replicator&&await this.env.services.replicator.runFiniteReplicationActivity(()=>replicator.replicateFromCommand(showResult),{label:"replication"})}async replicateFrom(peerId,showNotice=!1,skipOrdinaryReplicationPolicy=!1){const replicator=this._replicator;if(!replicator)throw new Error("P2P replicator is not open");return await this.env.services.replicator.runFiniteReplicationActivity(()=>skipOrdinaryReplicationPolicy?replicator.replicateFrom(peerId,showNotice,!1,!0):replicator.replicateFrom(peerId,showNotice),{label:"replication"})}async requestSynchroniseToPeer(peerId){const replicator=this._replicator;if(!replicator)throw new Error("P2P replicator is not open");return await this.env.services.replicator.runBoundedRemoteActivity(()=>replicator.requestSynchroniseToPeer(peerId),{label:"replication"})}async getRemoteConfig(peerId){if(!this._replicator)throw new Error("P2P replicator is not open");return await this._replicator.getRemoteConfig(peerId)}watchPeer(peerId){var _a13;null==(_a13=this._replicator)||_a13.watchPeer(peerId)}unwatchPeer(peerId){var _a13;null==(_a13=this._replicator)||_a13.unwatchPeer(peerId)}async sync(peerId,showNotice=!1){if(!this._replicator)throw new Error("P2P replicator is not open");return await this._replicator.sync(peerId,showNotice)}setOnSetup(){var _a13;null==(_a13=this._replicator)||_a13.setOnSetup()}clearOnSetup(){var _a13;null==(_a13=this._replicator)||_a13.clearOnSetup()}async makeDecision(decision){var _a13,_b6;await(null==(_b6=null==(_a13=this._replicator)?void 0:_a13.server)?void 0:_b6.makeDecision(decision))}async revokeDecision(decision){var _a13,_b6;await(null==(_b6=null==(_a13=this._replicator)?void 0:_a13.server)?void 0:_b6.revokeDecision(decision))}async makeSureOpened(){var _a13;this._replicator&&(null==(_a13=this._p2pHost)?void 0:_a13.isServing)||await this.open()}async openReplication(_setting,_keepAlive,showResult,_ignoreCleanLock){if(this.openReplicationUI)return this.openReplicationUI(showResult);const logLevel=showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO;await this.makeSureOpened();if(!this._replicator){Logger(this.translate("P2P.ReplicatorInstanceMissing"),logLevel);return!1}await this._replicator.replicateFromCommand(showResult)}tryConnectRemote(_setting,_showResult){return Promise.resolve(!1)}replicateAllToServer(_setting,_showingNotice){return Promise.resolve(!1)}async selectPeer(settingPeerName,r4,logLevel){var _a13,_b6,_c3,_d2,_e2;const knownPeersOrg=null!=(_b6=null==(_a13=r4.server)?void 0:_a13.knownAdvertisements)?_b6:[];let knownPeers;if(0!=knownPeersOrg.length)knownPeers=knownPeersOrg;else{Logger(this.translate("P2P.NoKnownPeers"),logLevel);await Promise.race([delay(5e3),this.env.services.context.events.waitFor(EVENT_ADVERTISEMENT_RECEIVED)]);knownPeers=null!=(_d2=null==(_c3=r4.server)?void 0:_c3.knownAdvertisements)?_d2:[]}const message="Rebuild from which peer?"+(settingPeerName?"\n [*] indicates the peer you have selected before.":""),confirm=this.env.services.UI.confirm,markedPeerNames=knownPeers.map(e3=>e3.name+""+(e3.name==settingPeerName?"[*]":"")+" ("+e3.peerId+")"),options=[...markedPeerNames,"Refresh List","Cancel"],selected=await confirm.askSelectStringDialogue(message,options,{title:"Select a peer to fetch from",defaultAction:"Refresh List"});if(!selected||"Cancel"==selected)return!1;if("Refresh List"==selected){await Promise.race([delay(1e3),this.env.services.context.events.waitFor(EVENT_ADVERTISEMENT_RECEIVED)]);return this.selectPeer(settingPeerName,r4,logLevel)}const selectedPeerName=selected.split("")[0],peerId=null==(_e2=knownPeers.find(e3=>e3.name==selectedPeerName))?void 0:_e2.peerId;if(!peerId){Logger("Failed to find peerId for "+selectedPeerName,logLevel);return!1}return peerId}async tryUntilSuccess(func,repeat,logLevel){const confirm=this.env.services.UI.confirm;if(!confirm){Logger("Cannot find confirm instance.",logLevel);return Promise.reject(new Error("Cannot find confirm instance."))}let result;for(;!result;)for(let i3=0;i3<repeat;i3++){try{result=await func();if(result)break}catch(e3){Logger(`Error: ${e3 instanceof Error?e3.message:String(e3)}`,logLevel);result=!1}await delay(1e3)}return result}async replicateAllFromServer(setting,showingNotice){var _a13;const logLevel=showingNotice?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO;if(0==setting.P2P_Enabled){const confirm=this.env.services.UI.confirm;"yes"!=await confirm.askYesNoDialog(this.translate("P2P.DisabledButNeed"),{})&&Logger(this.translate("P2P.NotEnabled"),logLevel);setting.P2P_Enabled=!0;this.env.services.setting.currentSettings().P2P_Enabled=!0;await this.env.services.setting.saveSettingData();await delay(100);return this.replicateAllFromServer(setting,showingNotice)}await this.open();if(!this._replicator){Logger("Failed to get replicator instance.",logLevel);return!1}if(this.env.openRebuildUI)return!1!==await this.env.openRebuildUI(null!=showingNotice&&showingNotice);await this.env.services.context.events.waitFor(EVENT_P2P_CONNECTED);const peerFrom=setting.P2P_RebuildFrom;this._replicator.setOnSetup();try{const r4=await this.tryUntilSuccess(async()=>{var _a14;await this.makeSureOpened();return null!=(_a14=this._replicator)&&_a14},10,logLevel);if(!1===r4){Logger("Failed to open P2P connection.",logLevel);return!1}const peerId=await this.selectPeer(peerFrom,r4,logLevel);if(!1===peerId){Logger("Failed to connect peer.",logLevel);return!1}this.env.services.setting.currentSettings().P2P_RebuildFrom="";Logger("Fetching from peer "+peerId+".",logLevel);const rep=await r4.replicateFrom(peerId,showingNotice,!1,!0);if(rep.ok){Logger("P2P Fetching has been succeed from "+peerId+".",logLevel);return!0}Logger("Failed to fetch from peer "+peerId+".",logLevel);Logger(rep.error,LOG_LEVEL_VERBOSE);return!1}finally{null==(_a13=this._replicator)||_a13.clearOnSetup()}}tryResetRemoteDatabase(_setting){throw new Error("P2P replication does not support database reset.")}tryCreateRemoteDatabase(_setting){throw new Error("P2P replication does not support database reset.")}markRemoteLocked(_setting,_locked,_lockByClean){throw new Error("P2P replication does not support database lock.")}markRemoteResolved(_setting){Logger("Trying resolving remote-database-lock but P2P replication does not support database lock. This operation has been ignored",LOG_LEVEL_INFO);return Promise.resolve()}resetRemoteTweakSettings(_setting){throw new Error("P2P replication does not support resetting tweaks.")}setPreferredRemoteTweakSettings(_setting){Logger("Trying setting tweak values but P2P replication does not support to do this. This operation has been ignored",LOG_LEVEL_INFO);return Promise.resolve()}fetchRemoteChunks(_missingChunks,_showResult){return Promise.resolve(!1)}getRemoteStatus(_setting){Logger("Trying to get remote status but P2P replication does not support to do this. This operation has been ignored",LOG_LEVEL_INFO);return Promise.resolve(!1)}getRemotePreferredTweakValues(_setting){Logger("Trying to get tweak values but P2P replication does not support to do this. This operation has been ignored",LOG_LEVEL_INFO);return Promise.resolve({status:RemotePreferredTweakStatuses_UNSUPPORTED})}countCompromisedChunks(){Logger("P2P Replicator cannot count compromised chunks",LOG_LEVEL_VERBOSE);return Promise.resolve(0)}getConnectedDeviceList(_setting){Logger("Trying to get connected device list but P2P replication does not support to do this. This operation has been ignored",LOG_LEVEL_INFO);return Promise.resolve(!1)}};root41=from_html("<button> </button>");root_136=from_html('<div class="status-item svelte-lxgvn4"><span> </span> <span class="room-suffix-display svelte-lxgvn4"> </span></div> <div class="status-item svelte-lxgvn4"><span> </span> <span class="peer-id-display svelte-lxgvn4"> </span></div> <div class="status-item svelte-lxgvn4"><span> </span> <span> </span></div>',1);root_219=from_html('<div class="status-item status-action broadcast-row svelte-lxgvn4"><label class="broadcast-label svelte-lxgvn4" for="broadcast-toggle"> </label> <button id="broadcast-toggle"> </button></div>');root_317=from_html('<div class="status-item status-action diag-toggle-row svelte-lxgvn4"><label class="broadcast-label svelte-lxgvn4" for="diag-toggle"> </label> <button id="diag-toggle"> </button></div>');root_411=from_html('<div class="diag-section svelte-lxgvn4"><h4 class="svelte-lxgvn4"> </h4> <div class="diag-grid svelte-lxgvn4"><div class="diag-item svelte-lxgvn4"><span> </span> <span> </span></div> <div class="diag-item svelte-lxgvn4"><span> </span> <span> </span></div> <div class="diag-item svelte-lxgvn4"><span> </span> <span> </span></div> <div class="diag-item svelte-lxgvn4"><span> </span> <span> </span></div></div></div>');root_511=from_html('<div class="server-status svelte-lxgvn4"><h3 class="svelte-lxgvn4"> </h3> <div class="status-item svelte-lxgvn4"><span> </span> <span> </span></div> <div class="status-item status-action svelte-lxgvn4"><!></div> <!> <!> <!> <!></div>');$$css15={hash:"svelte-lxgvn4",code:".server-status.svelte-lxgvn4 {border:1px solid var(--divider-color);border-radius:0.5rem;padding:1rem;}h3.svelte-lxgvn4 {margin:0 0 0.75rem 0;font-weight:600;font-size:1rem;}.status-item.svelte-lxgvn4 {display:flex;justify-content:space-between;flex-wrap:wrap;font-size:0.9rem;margin-bottom:0.5rem;}.status-action.svelte-lxgvn4 {align-items:center;gap:0.5rem;}.status-value.svelte-lxgvn4 {font-weight:500;}.status-value.connected.svelte-lxgvn4 {color:var(--text-success);}.status-value.disconnected.svelte-lxgvn4 {color:var(--text-error);}.peer-id-display.svelte-lxgvn4 {font-family:monospace;font-size:0.85rem;max-width:150px;overflow:hidden;text-overflow:ellipsis;}.room-suffix-display.svelte-lxgvn4 {font-family:monospace;font-size:0.85rem;font-weight:600;}.broadcast-row.svelte-lxgvn4 {align-items:center;margin-top:0.25rem;}.diag-toggle-row.svelte-lxgvn4 {align-items:center;margin-top:0.25rem;}.broadcast-label.svelte-lxgvn4 {font-size:0.9rem;color:var(--text-normal);cursor:pointer;}.broadcast-button.svelte-lxgvn4 {font-size:0.8rem;padding:0.2rem 0.6rem;border:1px solid var(--divider-color);border-radius:0.4rem;cursor:pointer;font-weight:600;transition:background-color 0.15s;}.broadcast-button.is-on.svelte-lxgvn4 {background-color:var(--interactive-accent);color:var(--text-on-accent);border-color:var(--interactive-accent);}.broadcast-button.is-off.svelte-lxgvn4 {background-color:var(--interactive-normal);color:var(--text-muted);}.broadcast-button.is-off.svelte-lxgvn4:hover {background-color:var(--interactive-hover);color:var(--text-normal);}.diag-section.svelte-lxgvn4 {border-top:1px solid var(--divider-color);margin-top:0.75rem;padding-top:0.75rem;}.diag-section.svelte-lxgvn4 h4:where(.svelte-lxgvn4) {margin:0 0 0.5rem 0;font-size:0.9rem;font-weight:600;}.diag-grid.svelte-lxgvn4 {display:grid;grid-template-columns:repeat(auto-fit, minmax(130px, 1fr));gap:0.35rem 0.75rem;}.diag-item.svelte-lxgvn4 {display:flex;justify-content:space-between;font-size:0.85rem;gap:0.5rem;}"};delegate(["click"]);root42=from_html('<option class="svelte-17w5ieg"> </option>');root_137=from_html('<p class="warning-line svelte-17w5ieg"> </p>');root_220=from_html('<span class="comm-icon svelte-17w5ieg">📡</span>');root_318=from_html('<div class="decision-row accepted-row svelte-17w5ieg"><span> </span> <button class="emoji-button svelte-17w5ieg"> </button> <button class="action-button svelte-17w5ieg"> </button> <button class="emoji-button svelte-17w5ieg">…</button></div> <div class="decision-row watch-row svelte-17w5ieg"><span class="decision-label svelte-17w5ieg"> </span> <button> </button></div>',1);root_412=from_html('<div class="decision-status svelte-17w5ieg"><span> </span></div> <div class="decision-row svelte-17w5ieg"><span class="decision-label svelte-17w5ieg"> </span> <button class="emoji-button svelte-17w5ieg">✅</button> <button class="emoji-button mod-warning svelte-17w5ieg">🚫</button></div> <div class="decision-row svelte-17w5ieg"><span class="decision-label svelte-17w5ieg"> </span> <button class="emoji-button svelte-17w5ieg">✅</button> <button class="emoji-button mod-warning svelte-17w5ieg">🚫</button></div>',1);root_512=from_html('<button class="action-button revoke-inline svelte-17w5ieg"> </button>');root_610=from_html('<div class="peer-item svelte-17w5ieg"><div class="peer-info svelte-17w5ieg"><div class="peer-name svelte-17w5ieg"> <span class="peer-id-mini svelte-17w5ieg"> </span> <!></div> <div class="peer-meta svelte-17w5ieg"><span class="badge svelte-17w5ieg"> </span></div></div> <div class="peer-actions svelte-17w5ieg"><!> <!></div></div>');root_78=from_html('<div class="peers-list svelte-17w5ieg"></div>');root_88=from_html('<p class="no-peers svelte-17w5ieg"> </p>');root_97=from_html('<div class="p2p-container svelte-17w5ieg"><div class="pane-header svelte-17w5ieg"><h2 class="svelte-17w5ieg"> </h2> <div class="pane-header-actions svelte-17w5ieg"><div class="remote-picker-wrap svelte-17w5ieg"><select class="remote-picker svelte-17w5ieg"><!><!></select> <button class="icon-button svelte-17w5ieg">+</button></div> <button class="icon-button svelte-17w5ieg">⚙</button></div></div> <!> <!> <div class="peers-section svelte-17w5ieg"><div class="peers-header svelte-17w5ieg"><h3 class="svelte-17w5ieg"> </h3> <button class="refresh svelte-17w5ieg"> </button></div> <!></div></div>');$$css16={hash:"svelte-17w5ieg",code:".p2p-container.svelte-17w5ieg {display:flex;flex-direction:column;gap:1rem;}.peers-section.svelte-17w5ieg {border:1px solid var(--divider-color);border-radius:0.5rem;padding:1rem;}.pane-header.svelte-17w5ieg {display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:0.5rem;}.pane-header-actions.svelte-17w5ieg {display:flex;align-items:center;gap:0.4rem;min-width:0;}.remote-picker-wrap.svelte-17w5ieg {display:inline-flex;gap:0.3rem;align-items:center;min-width:0;}.remote-picker.svelte-17w5ieg {max-width:10rem;min-width:1em;flex-shrink:1;height:1.9rem;border:1px solid var(--divider-color);border-radius:0.4rem;background-color:var(--interactive-normal);color:var(--text-normal);padding:0 0.45rem;}.warning-line.svelte-17w5ieg {margin:-0.2rem 0 0;font-size:0.82rem;color:var(--text-warning);}.pane-header.svelte-17w5ieg h2:where(.svelte-17w5ieg) {margin:0;font-size:1.1rem;font-weight:700;white-space:nowrap;}.icon-button.svelte-17w5ieg {width:1.9rem;height:1.9rem;display:inline-flex;align-items:center;justify-content:center;font-size:1rem;line-height:1;border:1px solid var(--divider-color);border-radius:0.4rem;background-color:var(--interactive-normal);color:var(--text-normal);cursor:pointer;flex-shrink:0;}.icon-button.svelte-17w5ieg:hover {background-color:var(--interactive-hover);}.peers-header.svelte-17w5ieg {display:flex;flex-wrap:wrap;justify-content:space-between;align-items:center;gap:0.5rem;margin-bottom:0.75rem;}h3.svelte-17w5ieg {margin:0;font-weight:600;font-size:1rem;}.refresh.svelte-17w5ieg {font-size:0.8rem;padding:0.2rem 0.5rem;border:1px solid var(--divider-color);border-radius:0.3rem;background-color:var(--interactive-normal);color:var(--text-normal);cursor:pointer;}.refresh.svelte-17w5ieg:hover {background-color:var(--interactive-hover);}.peers-list.svelte-17w5ieg {display:flex;flex-direction:column;gap:0.5rem;}.peer-item.svelte-17w5ieg {display:flex;flex-direction:column;align-items:stretch;gap:0.75rem;padding:0.75rem;background-color:var(--background-secondary);border:1px solid var(--divider-color);border-radius:0.4rem;}.peer-info.svelte-17w5ieg {flex:1;min-width:0;}.peer-name.svelte-17w5ieg {font-weight:600;margin-bottom:0.25rem;font-size:0.9rem;display:flex;align-items:center;gap:0.35rem;}.peer-meta.svelte-17w5ieg {display:flex;gap:0.5rem;font-size:0.8rem;flex-wrap:wrap;}.badge.svelte-17w5ieg {background-color:var(--background-tertiary);padding:0.1rem 0.4rem;border-radius:0.25rem;}.status-chip.svelte-17w5ieg {font-weight:600;}.status-chip.accepted.svelte-17w5ieg {background-color:var(--background-modifier-success);color:var(--text-normal);}.status-chip.denied.svelte-17w5ieg {background-color:var(--background-modifier-error);color:var(--text-normal);}.status-chip.unknown.svelte-17w5ieg {background-color:var(--background-modifier-border);color:var(--text-muted);}.peer-id-mini.svelte-17w5ieg {font-family:monospace;color:var(--text-muted);font-size:0.75rem;}.comm-icon.svelte-17w5ieg {font-size:0.8rem;line-height:1;\n animation: svelte-17w5ieg-pulse-comm 1.2s ease-in-out infinite;}\n\n @keyframes svelte-17w5ieg-pulse-comm {\n 0% {\n opacity: 0.55;\n transform: scale(0.95);\n }\n 50% {\n opacity: 1;\n transform: scale(1);\n }\n 100% {\n opacity: 0.55;\n transform: scale(0.95);\n }\n }.peer-actions.svelte-17w5ieg {display:flex;flex-direction:column;gap:0.35rem;width:100%;min-width:0;}.decision-status.svelte-17w5ieg {display:flex;justify-content:flex-start;}.decision-row.svelte-17w5ieg {display:grid;grid-template-columns:1fr auto auto;align-items:center;gap:0.35rem;}.accepted-row.svelte-17w5ieg {grid-template-columns:1fr auto auto auto;}.decision-label.svelte-17w5ieg {font-size:0.7rem;font-weight:700;color:var(--text-muted);letter-spacing:0.03em;}.action-button.svelte-17w5ieg {font-size:0.75rem;padding:0.2rem 0.45rem;border:1px solid var(--divider-color);border-radius:0.3rem;background-color:var(--interactive-normal);color:var(--text-normal);cursor:pointer;width:auto;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}.emoji-button.svelte-17w5ieg {width:2rem;height:1.7rem;display:inline-flex;align-items:center;justify-content:center;border:1px solid var(--divider-color);border-radius:0.3rem;background-color:var(--interactive-normal);cursor:pointer;padding:0;line-height:1;}.emoji-button.mod-warning.svelte-17w5ieg {background-color:var(--background-modifier-error);}.emoji-button.is-watching.svelte-17w5ieg {background-color:var(--interactive-accent);color:var(--text-on-accent);border-color:var(--interactive-accent);}.emoji-button.svelte-17w5ieg:hover:not(:disabled) {background-color:var(--interactive-hover);}.emoji-button.mod-warning.svelte-17w5ieg:hover:not(:disabled) {filter:brightness(0.95);}.watch-row.svelte-17w5ieg {margin-top:0.25rem;}.action-button.svelte-17w5ieg:hover:not(:disabled) {background-color:var(--interactive-hover);}.action-button.mod-warning.svelte-17w5ieg {background-color:var(--background-modifier-error);}.action-button.svelte-17w5ieg:disabled {opacity:0.6;cursor:not-allowed;}.emoji-button.svelte-17w5ieg:disabled {opacity:0.6;cursor:not-allowed;}.revoke-inline.svelte-17w5ieg {justify-self:start;}.no-peers.svelte-17w5ieg {text-align:center;color:var(--text-muted);font-size:0.9rem;padding:1rem;}"};delegate(["change","click"]);VIEW_TYPE_P2P_SERVER_STATUS="p2p-server-status";P2PServerStatusPaneView=class extends SvelteItemView{constructor(leaf,core,p2pResult){super(leaf);this.icon="waypoints";this.navigation=!1;this.core=core;this._p2pResult=p2pResult}getIcon(){return"waypoints"}getViewType(){return VIEW_TYPE_P2P_SERVER_STATUS}getDisplayText(){return"P2P Status"}instantiateComponent(target){return mount(P2PServerStatusPane,{target,props:{getLiveSyncReplicator:()=>this._p2pResult.replicator,core:this.core}})}};LEGACY_VIEW_TYPE_P2P="p2p-replicator";LegacyP2PStatusPaneView=class extends P2PServerStatusPaneView{getViewType(){return LEGACY_VIEW_TYPE_P2P}};REVIEW_HARNESS_SCENARIOS=[{id:"settings-lifecycle",title:"Settings lifecycle",description:"Checks whether loaded settings expose the seven synchronisation choices and apply new-Vault recommendations only to a genuinely new Vault.",mode:"automatic",access:"read-only"},{id:"compatibility-review",title:"Compatibility review boundary",description:"Checks the current device-local compatibility pause, then guides the reviewer through its explicit review and restart boundary.",mode:"guided",access:"device-local-state"},{id:"p2p-composition",title:"P2P composition",description:"Checks that the Obsidian host and P2P interface still resolve the current Commonlib replicator.",mode:"automatic",access:"read-only"},{id:"vault-round-trip",title:"Vault fixture round trip",description:"Creates, reads, modifies, renames, and removes a fixed owned fixture tree after explicit confirmation.",mode:"automatic",access:"dedicated-vault-fixtures"}];REVIEW_HARNESS_SCENARIOS.map(({id})=>id);REVIEW_HARNESS_STATE_KEY="review-harness-v1";PRESERVED_SYNC_SETTING_KEYS=["liveSync","syncOnSave","syncOnEditorSave","syncOnStart","syncOnFileOpen","syncAfterMerge","periodicReplication"];NEW_VAULT_RECOMMENDATION_KEYS=["syncMaxSizeInMB","chunkSplitterVersion","usePluginSyncV2","handleFilenameCaseSensitive","E2EEAlgorithm"];idleResult=()=>({status:"idle",detail:"Not run",observations:[]});ReviewHarnessController=class{constructor(runtime){this.runtime=runtime;this.results=initialResults();this.transcript=[];this.listeners=new Set;this.running=!1;this.current=null;this.resumedRequestId=null;this.continuationError=null}subscribe(listener){this.listeners.add(listener);return()=>this.listeners.delete(listener)}notify(){for(const listener of this.listeners)listener()}record(event2,detail){this.transcript.push({at:this.runtime.now().toISOString(),event:event2,...detail?{detail}:{}});for(;this.transcript.length>100;)this.transcript.shift()}snapshot(){return{results:Object.fromEntries(REVIEW_HARNESS_SCENARIOS.map(({id})=>[id,{...this.results[id]}])),running:this.running,current:this.current,resumedRequestId:this.resumedRequestId,continuationError:this.continuationError,transcript:[...this.transcript]}}consumeContinuation(){var _a13;const serialised=this.runtime.readContinuation();if(!serialised)return;this.runtime.deleteContinuation();const parsed=parsePendingReviewRun(serialised);if(parsed.pendingRun){this.resumedRequestId=parsed.pendingRun.requestId;this.results["compatibility-review"]={status:"waiting-for-user",detail:"Obsidian returned after the requested restart. Open the compatibility review to continue.",observations:[`requestedAt=${parsed.pendingRun.requestedAt}`]};this.record("continuation-consumed",parsed.pendingRun.requestId);this.notify()}else{this.continuationError=null!=(_a13=parsed.error)?_a13:"The Review Harness continuation was invalid.";this.results["compatibility-review"]={status:"failed",detail:"The stored continuation was invalid and was removed.",observations:[]};this.record("continuation-rejected");this.notify()}}async runAutomaticScenarios(){for(const id of["settings-lifecycle","p2p-composition"])await this.runScenario(id)}async runAllScenarios(){for(const{id}of REVIEW_HARNESS_SCENARIOS)await this.runScenario(id)}inspectCompatibilityReview(){return inspectCompatibilityReview({migration:this.runtime.getSettingsMigrationState(),reviewInitialised:this.runtime.isCompatibilityReviewInitialised(),pendingPause:this.runtime.getCompatibilityPause()})}async runScenario(id){if(!this.running){this.running=!0;this.current=id;this.results[id]={status:"running",detail:"Running",observations:[]};this.record("scenario-started",id);this.notify();try{let result;if("settings-lifecycle"===id)result=inspectSettingsLifecycle({migration:this.runtime.getSettingsMigrationState(),settings:this.runtime.getSettings(),newVaultSettings:this.runtime.getNewVaultSettings()});else if("p2p-composition"===id)result=inspectP2PComposition(this.runtime.getP2PComposition());else if("vault-round-trip"===id)result=await this.runtime.runVaultRoundTrip();else{const inspection=this.inspectCompatibilityReview();result="failed"!==inspection.status&&this.runtime.getCompatibilityPause()?{status:"waiting-for-user",detail:"Open the device-local compatibility review and complete its explicit action.",observations:inspection.observations}:inspection}this.results[id]=result;this.record("scenario-updated",`${id}:${result.status}`)}catch(error){this.setUnexpectedFailure(id,error)}finally{this.running=!1;this.current=null;this.notify()}}}async openCompatibilityReview(){if(!this.running){this.running=!0;this.current="compatibility-review";this.notify();try{const pauseWasPending=void 0!==this.runtime.getCompatibilityPause();await this.runtime.openCompatibilityReview();const inspection=this.inspectCompatibilityReview();this.results["compatibility-review"]="passed"!==inspection.status||this.runtime.getCompatibilityPause()?"failed"===inspection.status?inspection:{status:"waiting-for-user",detail:"The device-local compatibility review remains pending.",observations:inspection.observations}:{status:"passed",detail:pauseWasPending?"The device-local compatibility pause was reviewed and cleared.":inspection.detail,observations:inspection.observations};this.record("compatibility-review-updated",this.results["compatibility-review"].status)}catch(error){this.setUnexpectedFailure("compatibility-review",error)}finally{this.running=!1;this.current=null;this.notify()}}}setUnexpectedFailure(id,error){this.runtime.reportError(error);this.results[id]={status:"failed",detail:"The scenario failed unexpectedly. Review the in-app logs for diagnostic details.",observations:[]};this.record("scenario-failed",id)}prepareCompatibilityReviewRestart(){const requestedAt=this.runtime.now().toISOString(),pending3={formatVersion:1,requestId:`compatibility-review-${requestedAt}`,scenarioId:"compatibility-review",stage:"awaiting-restart",requestedAt};this.runtime.writeContinuation(JSON.stringify(pending3));this.results["compatibility-review"]={status:"waiting-for-user",detail:"Restart requested. The one-shot continuation will be removed before the review resumes.",observations:[]};this.record("restart-requested",pending3.requestId);this.notify();this.runtime.restart()}createReport(){return formatReviewHarnessReport({generatedAt:this.runtime.now().toISOString(),environment:this.runtime.getEnvironment(),scenarios:REVIEW_HARNESS_SCENARIOS.map(({id,title,mode})=>({id,title,mode,status:this.results[id].status,detail:this.results[id].detail})),transcript:this.transcript})}async copyReport(){await this.runtime.copyText(this.createReport());this.record("report-copied");this.notify()}};VIEW_TYPE_REVIEW_HARNESS="self-hosted-livesync-review-harness";STATUS_LABELS={idle:"Not run",queued:"Queued",running:"Running","waiting-for-user":"Waiting for review",passed:"Passed",failed:"Failed",cancelled:"Cancelled"};ReviewHarnessView=class extends import_obsidian.ItemView{constructor(leaf,controller){super(leaf);this.controller=controller;this.icon="test-tube-2";this.navigation=!0}getViewType(){return VIEW_TYPE_REVIEW_HARNESS}getDisplayText(){return"Self-hosted LiveSync review harness"}async onOpen(){this.unsubscribe=this.controller.subscribe(()=>this.render());this.render();await Promise.resolve()}async onClose(){var _a13;null==(_a13=this.unsubscribe)||_a13.call(this);this.unsubscribe=void 0;await Promise.resolve()}addActionButton(setting,label2,testId,action2,cta=!1){setting.addButton(button=>{button.setButtonText(label2);cta&&button.setCta();button.buttonEl.dataset.testid=testId;button.onClick(()=>{action2()})})}renderScenario(id){const scenario=REVIEW_HARNESS_SCENARIOS.find(candidate=>candidate.id===id),snapshot2=this.controller.snapshot(),result=snapshot2.results[id],setting=new import_obsidian.Setting(this.contentEl).setName(scenario.title).setDesc(`${scenario.description} Mode: ${scenario.mode}. Access: ${scenario.access}.`).setClass("sls-review-harness__scenario");setting.settingEl.dataset.testid=`review-harness-scenario-${id}`;this.addActionButton(setting,"compatibility-review"===id?"Start review":"Run",`review-harness-run-${id}`,()=>this.controller.runScenario(id));const resultEl=this.contentEl.createDiv({cls:"sls-review-harness__result"});resultEl.dataset.testid=`review-harness-result-${id}`;resultEl.createEl("strong",{text:`${STATUS_LABELS[result.status]}: `});resultEl.appendText(result.detail);if(result.observations.length>0){const observations=resultEl.createEl("ul");for(const observation of result.observations)observations.createEl("li",{text:observation})}if("compatibility-review"===id&&"waiting-for-user"===result.status){const actions=new import_obsidian.Setting(this.contentEl).setClass("sls-review-harness__actions");this.addActionButton(actions,"Open compatibility review","review-harness-open-compatibility-review",()=>this.controller.openCompatibilityReview(),!0);this.addActionButton(actions,"Restart and return","review-harness-restart",()=>this.controller.prepareCompatibilityReviewRestart())}}render(){var _a13;this.contentEl.empty();this.contentEl.addClass("sls-review-harness");this.contentEl.dataset.testid="review-harness";this.contentEl.createEl("h2",{text:"Self-hosted LiveSync review harness"});this.contentEl.createEl("p",{text:"Use a dedicated test Vault. Read-only scenarios are labelled. The Vault round-trip scenario writes only after confirmation, owns one fixed fixture tree, and removes it in a finally block. The Harness never accepts arbitrary commands, paths, code, or remote credentials.",cls:"sls-review-harness__warning"});this.contentEl.createEl("p",{text:"Automatic scenarios inspect local contracts. The guided compatibility review uses the same device-local pause and explicit action as normal start-up. Real P2P transport remains covered by the Compose E2E suite."});const snapshot2=this.controller.snapshot();if(snapshot2.continuationError)this.contentEl.createEl("p",{text:`Continuation error: ${snapshot2.continuationError}`,cls:"sls-review-harness__error"});else if(snapshot2.resumedRequestId){const resumed=this.contentEl.createEl("p",{text:"The one-shot restart continuation was consumed. Complete the guided review below.",cls:"sls-review-harness__resumed"});resumed.dataset.testid="review-harness-resumed"}const suiteActions=new import_obsidian.Setting(this.contentEl).setName("Review suite").setDesc(snapshot2.running?`Running ${null!=(_a13=snapshot2.current)?_a13:"scenario"}.`:"Choose the scope to run.").setClass("sls-review-harness__actions");this.addActionButton(suiteActions,"Automatic","review-harness-run-automatic",()=>this.controller.runAutomaticScenarios());this.addActionButton(suiteActions,"Full review","review-harness-run-full",()=>this.controller.runAllScenarios());this.addActionButton(suiteActions,"Copy Markdown report","review-harness-copy-report",async()=>{await this.controller.copyReport();new import_obsidian.Notice("Review Harness Markdown report copied.")});this.contentEl.createEl("h3",{text:"Scenarios"});for(const{id}of REVIEW_HARNESS_SCENARIOS)this.renderScenario(id);this.contentEl.createEl("p",{text:"Reports are copied locally and are not transmitted. They omit Vault identifiers, paths, contents, remote configuration, and secrets.",cls:"sls-review-harness__privacy"})}};REVIEW_HARNESS_FIXTURE_ROOT="__self-hosted-livesync-review-harness__";REVIEW_HARNESS_SOURCE_FILE=`${REVIEW_HARNESS_FIXTURE_ROOT}/round-trip.md`;REVIEW_HARNESS_RENAMED_FILE=`${REVIEW_HARNESS_FIXTURE_ROOT}/round-trip-renamed.md`;CREATED_CONTENT="review-harness:created\n";MODIFIED_CONTENT="review-harness:modified\n";root43=from_html('<button class="btn btn-primary svelte-15bwvlz"> </button> <button> </button>',1);root_138=from_html("<button> </button>");root_221=from_html('<div class="peer-item svelte-15bwvlz"><div class="peer-info svelte-15bwvlz"><div class="peer-name svelte-15bwvlz"> </div> <div class="peer-meta svelte-15bwvlz"><span class="badge svelte-15bwvlz"> </span> <span class="peer-id-mini svelte-15bwvlz"> </span> <span> </span></div></div> <div class="peer-actions svelte-15bwvlz"><!></div></div>');root_319=from_html('<div class="peers-list svelte-15bwvlz"></div>');root_413=from_html('<p class="no-peers svelte-15bwvlz"> </p>');root_513=from_html('<button class="btn btn-cancel svelte-15bwvlz"> </button>');root_611=from_html('<button class="btn btn-cancel svelte-15bwvlz"> </button> <button class="btn btn-cancel svelte-15bwvlz"> </button>',1);root_79=from_html('<div class="p2p-container svelte-15bwvlz"><!> <div class="peers-section svelte-15bwvlz"><h3 class="svelte-15bwvlz"> </h3> <!></div> <div class="footer svelte-15bwvlz"><!></div></div>');$$css17={hash:"svelte-15bwvlz",code:".p2p-container.svelte-15bwvlz {display:flex;flex-direction:column;gap:1rem;padding:1rem;max-height:70vh;overflow-y:auto;}.peers-section.svelte-15bwvlz {border:1px solid var(--divider-color);border-radius:0.5rem;padding:1rem;}h3.svelte-15bwvlz {margin:0 0 0.75rem 0;font-weight:600;font-size:1rem;}.peers-list.svelte-15bwvlz {display:flex;flex-direction:column;gap:0.5rem;}.peer-item.svelte-15bwvlz {display:flex;justify-content:space-between;flex-wrap:wrap;align-items:center;padding:0.75rem;background-color:var(--background-secondary);border:1px solid var(--divider-color);border-radius:0.4rem;}.peer-info.svelte-15bwvlz {flex:1;}.peer-name.svelte-15bwvlz {font-weight:600;margin-bottom:0.25rem;}.peer-meta.svelte-15bwvlz {display:flex;gap:0.5rem;font-size:0.8rem;}.badge.svelte-15bwvlz {background-color:var(--background-tertiary);padding:0.1rem 0.4rem;border-radius:0.25rem;}.status-chip.svelte-15bwvlz {font-weight:600;}.status-chip.accepted.svelte-15bwvlz {background-color:var(--background-modifier-success);color:var(--text-normal);}.status-chip.denied.svelte-15bwvlz {background-color:var(--background-modifier-error);color:var(--text-normal);}.status-chip.unknown.svelte-15bwvlz {background-color:var(--background-modifier-border);color:var(--text-muted);}.peer-id-mini.svelte-15bwvlz {font-family:monospace;color:var(--text-muted);}.peer-actions.svelte-15bwvlz {flex-wrap:wrap;display:flex;gap:0.5rem;}.btn.svelte-15bwvlz {padding:0.4rem 0.8rem;border:1px solid var(--divider-color);border-radius:0.3rem;background-color:var(--interactive-normal);color:var(--text-normal);cursor:pointer;font-size:0.8rem;font-weight:500;transition:background-color 0.2s;}.btn.svelte-15bwvlz:hover:not(:disabled) {background-color:var(--interactive-hover);}.btn.svelte-15bwvlz:disabled {opacity:0.6;cursor:not-allowed;}.btn-primary.svelte-15bwvlz {background-color:var(--interactive-accent);color:var(--text-on-accent);}.btn-secondary.svelte-15bwvlz {background-color:var(--background-tertiary);}.btn-cancel.svelte-15bwvlz {width:100%;margin-top:0.5rem;}.no-peers.svelte-15bwvlz {text-align:center;color:var(--text-muted);font-size:0.9rem;padding:1rem;}.footer.svelte-15bwvlz {border-top:1px solid var(--divider-color);padding-top:0.75rem;}"};delegate(["click"]);P2POpenReplicationModal=class extends import_obsidian.Modal{constructor(app,liveSyncReplicator,callback,showResult=!1,title="P2P Replication",onClosed,rebuildMode=!1){super(app);this.liveSyncReplicator=liveSyncReplicator;this.callback=callback;this.showResult=showResult;this.title=title;this.onClosed=onClosed;this.rebuildMode=rebuildMode}async onSync(peerId){var _a13;(null==(_a13=this.callback)?void 0:_a13.onSync)&&await this.callback.onSync(peerId)}async onSyncAndClose(peerId){var _a13;(null==(_a13=this.callback)?void 0:_a13.onSyncAndClose)&&await this.callback.onSyncAndClose(peerId);this.close()}onOpen(){const{contentEl}=this;this.titleEl.setText(this.title);contentEl.empty();void 0===this.component&&(this.component=mount(P2POpenReplicationPane,{target:contentEl,props:{liveSyncReplicator:this.liveSyncReplicator,onSync:peerId=>this.onSync(peerId),onSyncAndClose:peerId=>this.onSyncAndClose(peerId),onClose:()=>this.close(),showResult:this.showResult,rebuildMode:this.rebuildMode}}))}onClose(){var _a13;const{contentEl}=this;contentEl.empty();if(void 0!==this.component){unmount(this.component);this.component=void 0}null==(_a13=this.onClosed)||_a13.call(this)}};DATABASE_COMPATIBILITY_VERSION_KEY="database-compatibility-version";DATABASE_COMPATIBILITY_LEGACY_VERSION_KEY_PREFIX="obsidian-live-sync-ver";COMPATIBILITY_PAUSE_SETTING_MESSAGE="Remote synchronisation is paused until this device's compatibility review has been completed.";COMPATIBILITY_REVIEW_LAYOUT_PRIORITY=30;CompatibilityReviewController=class{constructor(core,ui,currentVersion=VER){this.core=core;this.ui=ui;this.currentVersion=currentVersion;this._initialised=!1;this.disposed=!1}get pendingPause(){return this.pause}get initialised(){return this._initialised}readAcknowledgedVersion(){const setting=this.core.services.setting,currentMarker=setting.getSmallConfig(DATABASE_COMPATIBILITY_VERSION_KEY);if(currentMarker)return currentMarker;const legacyKey=legacyDatabaseCompatibilityVersionKey(this.core.services.vault.getVaultName()),legacyMarker=setting.getDeviceLocalConfig(legacyKey);if(!legacyMarker)return null;setting.setSmallConfig(DATABASE_COMPATIBILITY_VERSION_KEY,legacyMarker);setting.deleteDeviceLocalConfig(legacyKey);return legacyMarker}async initialise(){if(this.disposed)return!0;const setting=this.core.services.setting,settings=setting.currentSettings(),migrationState=setting.getSettingsMigrationState();if(!0!==settings.isConfigured&&!0!==(null==migrationState?void 0:migrationState.isNewVault)){this.pause=void 0;this.ui.clearReminder();this._initialised=!0;return!0}const acknowledgedVersion=this.readAcknowledgedVersion(),evaluation=evaluateCompatibilityPause({acknowledgedVersion,currentVersion:this.currentVersion,migrationState,legacyReviewMessage:settings.versionUpFlash});this.pause=evaluation.pause;if(evaluation.initialiseAcknowledgedVersion){setting.setSmallConfig(DATABASE_COMPATIBILITY_VERSION_KEY,`${this.currentVersion}`);this._initialised=!0;return!0}if(!this.pause){this._initialised=!0;return!0}if(""===settings.versionUpFlash){settings.versionUpFlash=COMPATIBILITY_PAUSE_SETTING_MESSAGE;await setting.saveSettingData()}this._initialised=!0;return!0}async acknowledge(){var _a13;if(!(null==(_a13=this.pause)?void 0:_a13.resumable))return;const setting=this.core.services.setting,settings=setting.currentSettings(),previousMessage=settings.versionUpFlash;settings.versionUpFlash="";try{await setting.saveSettingData()}catch(error){settings.versionUpFlash=previousMessage||COMPATIBILITY_PAUSE_SETTING_MESSAGE;throw error}setting.setSmallConfig(DATABASE_COMPATIBILITY_VERSION_KEY,`${this.currentVersion}`);const legacyKey=legacyDatabaseCompatibilityVersionKey(this.core.services.vault.getVaultName());setting.deleteDeviceLocalConfig(legacyKey);this.pause=void 0;this.ui.clearReminder();await this.core.services.control.applySettings()}async runReview(){for(;this.pause;){const action2=await this.ui.showSummary(this.pause);if("details"===action2){const detailsAction=await this.ui.showDetails(this.pause);if("back"===detailsAction)continue;break}if("resume"===action2&&this.pause.resumable){await this.acknowledge();return}break}this.pause&&!this.disposed&&this.ui.showReminder(()=>{fireAndForget(()=>this.openReview())})}openReview(){if(this.disposed||!this.pause)return Promise.resolve();if(this.activeReview)return this.activeReview;this.ui.clearReminder();this.activeReview=this.runReview().finally(()=>{this.activeReview=void 0});return this.activeReview}dispose(){this.disposed=!0;this.pause=void 0;this.ui.clearReminder()}};REVIEW_DETAILS="Review compatibility details";KEEP_PAUSED="Keep synchronisation paused";RESUME="Resume synchronisation";BACK="Back to compatibility review";ObsidianCompatibilityReviewUi=class{constructor(confirm){this.confirm=confirm}async showSummary(pause){const buttons=pause.resumable?[REVIEW_DETAILS,RESUME,KEEP_PAUSED]:[REVIEW_DETAILS,KEEP_PAUSED],result=await this.confirm.confirmWithMessage("Synchronisation paused for compatibility review",compatibilityReviewSummaryMarkdown(pause),[...buttons],KEEP_PAUSED,void 0,"vertical");return result===REVIEW_DETAILS?"details":result===RESUME?"resume":result===KEEP_PAUSED&&"keep-paused"}async showDetails(pause){const result=await this.confirm.confirmWithMessage("Compatibility review details",compatibilityReviewDetailsMarkdown(pause),[BACK],BACK,void 0,"vertical");return result===BACK&&"back"}showReminder(openReview){var _a13;this.clearReminder();let reminderAnchor;const fragment=createFragment(documentFragment=>{documentFragment.createSpan({text:"Self-hosted LiveSync has paused remote synchronisation for compatibility review. "});documentFragment.createEl("a",{text:"Review why"},anchor=>{reminderAnchor=anchor;anchor.addEventListener("click",event2=>{event2.preventDefault();openReview()})})});this.reminder=new import_obsidian.Notice(fragment,0);null==(_a13=null==reminderAnchor?void 0:reminderAnchor.closest(".notice"))||_a13.classList.add("livesync-compatibility-review-notice")}clearReminder(){var _a13;null==(_a13=this.reminder)||_a13.hide();this.reminder=void 0}};StoredFileReflectionProvenance=class{constructor(store){__publicField(this,"store");this.store=store}async get(path2){var _a13;return null!=(_a13=await this.store.get(path2))?_a13:void 0}async set(path2,record){await this.store.set(path2,record)}async delete(path2){await this.store.delete(path2)}async move(from,to){const record=await this.get(from);record&&await this.set(to,record);await this.delete(from)}};FILE_REFLECTION_PROVENANCE_STORE="file-reflection-provenance-v1";(function setGetLanguage(func){_getLanguage=func})(import_obsidian.getLanguage);ObsidianLiveSyncPlugin=class extends import_obsidian.Plugin{initialiseServiceModules(core,services){const storageAccessManager=new StorageAccessManager,vaultAccess=new FileAccessObsidian(this.app,{storageAccessManager,vaultService:services.vault,settingService:services.setting,APIService:services.API,pathService:services.path}),storageEventManager=new StorageEventManagerObsidian(this,core,{fileProcessing:services.fileProcessing,setting:services.setting,vaultService:services.vault,storageAccessManager,APIService:services.API}),storageAccess=new ServiceFileAccessObsidian({API:services.API,setting:services.setting,fileProcessing:services.fileProcessing,vault:services.vault,appLifecycle:services.appLifecycle,storageEventManager,storageAccessManager,vaultAccess}),databaseFileAccess=new ServiceDatabaseFileAccess({events:services.context.events,API:services.API,database:services.database,path:services.path,storageAccess,vault:services.vault}),fileHandler=new ServiceFileHandler({events:services.context.events,API:services.API,databaseFileAccess,conflict:services.conflict,setting:services.setting,fileProcessing:services.fileProcessing,vault:services.vault,path:services.path,replication:services.replication,storageAccess,fileReflectionProvenance:createFileReflectionProvenance(services.keyValueDB)}),rebuilder=new ServiceRebuilder({events:services.context.events,API:services.API,database:services.database,appLifecycle:services.appLifecycle,setting:services.setting,remote:services.remote,databaseEvents:services.databaseEvents,replication:services.replication,replicator:services.replicator,UI:services.UI,vault:services.vault,fileHandler,fileProcessing:services.fileProcessing,storageAccess,control:services.control});return{rebuilder,fileHandler,databaseFileAccess,storageAccess}}async saveSettings(){await this.core.services.setting.saveSettingData()}constructor(app,manifest){super(app,manifest);setNoticeClass(import_obsidian.Notice);const serviceHub=new ObsidianServiceHub(this);let waitForCompatibilityReview=()=>Promise.resolve();this.core=new LiveSyncBaseCore(serviceHub,(core,serviceHub2)=>this.initialiseServiceModules(core,serviceHub2),core=>{const extraModules=[new ModuleObsidianEvents(this,core),new ModuleObsidianSettingDialogue(this,core),new ModuleObsidianMenu(core),new ModuleObsidianSettingsAsMarkdown(core),new ModuleLog(this,core),new ModuleObsidianDocumentHistory(this,core),new ModuleInteractiveConflictResolver(this,core),new ModuleObsidianGlobalHistory(this,core),new SetupManager(core),new ModuleMigration(core,()=>waitForCompatibilityReview())];return extraModules},core=>{const addOns=[new ConfigSync(core),new HiddenFileSync(core),new LocalDatabaseMaintenance(core)];return addOns},core=>{const featuresInitialiser=enableI18nFeature;core.services.appLifecycle.onLayoutReady.addHandler(()=>featuresInitialiser(core));const setupManager=core.getModule(SetupManager),replicator=useP2PReplicatorFeature(core,createOpenReplicationUI(this.app),createOpenRebuildUI(this.app));useP2PReplicatorCommands(core,replicator);useP2PReplicatorUI(core,core,replicator);useRemoteConfiguration(core);useSetupProtocolFeature(core,setupManager);useSetupQRCodeFeature(core);useSetupURIFeature(core);useSetupManagerHandlersFeature(core,setupManager);useOfflineScanner(core);useRedFlagFeatures(core);useCheckRemoteSize(core);const compatibilityReview=useCompatibilityReview(core,createObsidianCompatibilityReviewUi(core.confirm));waitForCompatibilityReview=()=>compatibilityReview.openReview();useReviewHarness(core,this,replicator,compatibilityReview)})}async _startUp(){if(!await this.core.services.control.onLoad())return;const onReady=this.core.services.control.onReady.bind(this.core.services.control);this.app.workspace.onLayoutReady(onReady)}onload(){this._startUp()}onunload(){this.core.services.control.onUnload()}};
/* nosourcemap */