@vrtmrz/livesync-commonlib 0.1.27 → 0.1.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -68,6 +68,18 @@ export declare function runWithInterval<T>(key: string, interval: number, task:
68
68
  export declare function runWithStartInterval<T>(key: string, interval: number, task: () => Promise<T>): Promise<T>;
69
69
  export declare const globalConcurrencyController: import("octagonal-wheels/concurrency/semaphore_v2").SemaphoreObject;
70
70
  export declare function determineTypeFromBlob(data: Blob): "newnote" | "plain";
71
+ /**
72
+ * Whether remediation mode is active.
73
+ *
74
+ * While a modification-time limit is configured, Commonlib refuses every reconciliation scan
75
+ * between the storage and the local database and keeps storage events unqueued, so that a state
76
+ * being recovered is not overwritten by the current one. A host therefore stays unready while the
77
+ * limit is configured, because readiness depends upon that refused scan. Applying the limit to the
78
+ * documents which arrive is the responsibility of the host.
79
+ * @param settings Settings to inspect
80
+ * @returns `true` when a modification-time limit is configured.
81
+ */
82
+ export declare function isRemediationModeActive(settings: Pick<ObsidianLiveSyncSettings, "maxMTimeForReflectEvents">): boolean;
71
83
  export declare function determineType(path: string, data: string | string[] | Uint8Array | ArrayBuffer | Blob): "newnote" | "plain";
72
84
  export declare function isAnyNote(doc: DatabaseEntry): doc is NewEntry | PlainEntry;
73
85
  export declare function isLoadedEntry(doc: DatabaseEntry): doc is LoadedEntry;
@@ -199,6 +199,9 @@ const globalConcurrencyController = Semaphore(50);
199
199
  function determineTypeFromBlob(data) {
200
200
  return isTextBlob(data) ? "plain" : "newnote";
201
201
  }
202
+ function isRemediationModeActive(settings) {
203
+ return (settings.maxMTimeForReflectEvents ?? 0) > 0;
204
+ }
202
205
  function determineType(path, data) {
203
206
  if (data instanceof Blob) {
204
207
  return determineTypeFromBlob(data);
@@ -548,6 +551,7 @@ export {
548
551
  isObfuscatedEntry,
549
552
  isObjectDifferent,
550
553
  isObjectMargeApplicable,
554
+ isRemediationModeActive,
551
555
  isSensibleMargeApplicable,
552
556
  isSyncInfoEntry,
553
557
  isTextBlob,
@@ -2,6 +2,12 @@ import type { FilePath, FilePathWithPrefix, MetaEntry } from "../common/models/d
2
2
  import type { UXFileInfo, UXFileInfoStub, UXInternalFileInfoStub } from "../common/models/fileaccess.type.js";
3
3
  export interface IFileHandler {
4
4
  readFileFromStub(file: UXFileInfoStub | UXFileInfo): Promise<UXFileInfo>;
5
+ /**
6
+ * Record an untracked, unchanged file during an equal-time scan.
7
+ * Return true only when the exact current revision was recorded. This
8
+ * operation never stores a document revision or writes to storage.
9
+ */
10
+ tryRecordUntrackedFileRevision(info: UXFileInfoStub | UXFileInfo, expectedRevision: string): Promise<boolean>;
5
11
  storeFileToDB(info: UXFileInfoStub | UXFileInfo | UXInternalFileInfoStub | FilePathWithPrefix, force?: boolean, onlyChunks?: boolean): Promise<boolean>;
6
12
  /**
7
13
  * Store the current storage content as a child of an exact live database revision.
@@ -209,7 +209,7 @@ function isTargetFile(host, filenameSrc) {
209
209
  const file = filenameSrc.startsWith(ICHeader) ? filenameSrc.substring(ICHeader.length) : filenameSrc;
210
210
  if (file.startsWith(ICXHeader)) return true;
211
211
  if (file.startsWith(PSCHeader)) return true;
212
- if (file.includes(":")) {
212
+ if (file.startsWith(IDPrefixes.Chunk) || file.startsWith(IDPrefixes.Obfuscated)) {
213
213
  return false;
214
214
  }
215
215
  if (!settings.syncInternalFiles) {
@@ -6,7 +6,7 @@ import {
6
6
  LOG_LEVEL_NOTICE,
7
7
  LOG_LEVEL_VERBOSE
8
8
  } from "../common/types.js";
9
- import { delay, fireAndForget, throttle } from "../common/utils.js";
9
+ import { delay, fireAndForget, isRemediationModeActive, throttle } from "../common/utils.js";
10
10
  import {} from "../common/types.js";
11
11
  import { serialized, skipIfDuplicated } from "octagonal-wheels/concurrency/lock";
12
12
  import { isWaitingForTimeout } from "octagonal-wheels/concurrency/task";
@@ -86,7 +86,7 @@ class StorageEventManagerBase extends StorageEventManager {
86
86
  const settings = this.settings;
87
87
  if (!settings.isConfigured) return;
88
88
  if (settings.suspendFileWatching) return;
89
- if (settings.maxMTimeForReflectEvents > 0) {
89
+ if (isRemediationModeActive(settings)) {
90
90
  return;
91
91
  }
92
92
  this.fileProcessing.onStorageFileEvent();
@@ -177,11 +177,10 @@ async function outgoingDecryptHKDF(doc, migrationDecrypt, decrypted, passphrase,
177
177
  }
178
178
  }
179
179
  if (isObfuscatedEntry(loadDoc)) {
180
- const path = getPath(loadDoc);
181
180
  if (isEncryptedMeta(loadDoc)) {
182
181
  const pbkdf2salt = await getPBKDF2Salt();
183
182
  try {
184
- const metadata = await decryptMetaWithHKDF(path, passphrase, pbkdf2salt);
183
+ const metadata = await decryptMetaWithHKDF(loadDoc.path, passphrase, pbkdf2salt);
185
184
  for (const key of Object.keys(metadata)) {
186
185
  loadDoc[key] = metadata[key];
187
186
  }
@@ -190,13 +189,16 @@ async function outgoingDecryptHKDF(doc, migrationDecrypt, decrypted, passphrase,
190
189
  Logger(ex);
191
190
  throw ex;
192
191
  }
193
- } else if (isPathProbablyObfuscated(path)) {
194
- const decryptedPath = await tryDecryptV1AsFallback(path, passphrase, useDynamicIterationCount);
195
- if (decryptedPath === false) {
196
- Logger(`${MESSAGE_FALLBACK_DECRYPT_FAILED} on Path`, LOG_LEVEL_NOTICE);
197
- throw new Error(MESSAGE_FALLBACK_DECRYPT_FAILED);
192
+ } else {
193
+ const path = getPath(loadDoc);
194
+ if (isPathProbablyObfuscated(path)) {
195
+ const decryptedPath = await tryDecryptV1AsFallback(path, passphrase, useDynamicIterationCount);
196
+ if (decryptedPath === false) {
197
+ Logger(`${MESSAGE_FALLBACK_DECRYPT_FAILED} on Path`, LOG_LEVEL_NOTICE);
198
+ throw new Error(MESSAGE_FALLBACK_DECRYPT_FAILED);
199
+ }
200
+ loadDoc.path = decryptedPath;
198
201
  }
199
- loadDoc.path = decryptedPath;
200
202
  }
201
203
  }
202
204
  let readEden = {};
@@ -7,7 +7,7 @@ import {
7
7
  LOG_LEVEL_VERBOSE,
8
8
  isMetaEntry
9
9
  } from "../common/types.js";
10
- import { compareMTime, isAnyNote } from "../common/utils.js";
10
+ import { compareMTime, isAnyNote, isRemediationModeActive } from "../common/utils.js";
11
11
  import { shouldBeIgnored, stripAllPrefixes } from "../string_and_binary/path.js";
12
12
  import { createInstanceLogFunction } from "../services/lib/logUtils.js";
13
13
  import { BASE_IS_NEW, EVEN, TARGET_IS_NEW } from "../common/models/shared.const.symbols.js";
@@ -389,6 +389,9 @@ async function syncFileBetweenDBandStorage(host, log, file, doc) {
389
389
  return FilePairProcessResults.SKIPPED;
390
390
  }
391
391
  case EVEN:
392
+ if (doc._rev) {
393
+ await host.serviceModules.fileHandler.tryRecordUntrackedFileRevision(file, doc._rev);
394
+ }
392
395
  log("STORAGE == DB :" + file.path, LOG_LEVEL_DEBUG);
393
396
  return FilePairProcessResults.COMPLETED;
394
397
  default:
@@ -411,7 +414,7 @@ function canProceedScan(host, errorManager, log, showingNotice = false, ignoreSu
411
414
  }
412
415
  errorManager.clearError(ERR_SUSPENDING);
413
416
  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.`;
414
- if (settings.maxMTimeForReflectEvents > 0) {
417
+ if (isRemediationModeActive(settings)) {
415
418
  errorManager.showError(MSG_IN_REMEDIATION, LOG_LEVEL_NOTICE);
416
419
  return false;
417
420
  }
@@ -8,7 +8,7 @@ import { ServiceModuleBase } from "./ServiceModuleBase.js";
8
8
  import { fetchChangesForInitialSync, isRetryableStreamingFetchFailure } from "../pouchdb/StreamingFetch.js";
9
9
  import { getConfiguredFunctionsForEncryption } from "../pouchdb/encryption.js";
10
10
  import { AuthorizationHeaderGenerator, generateCredentialObject } from "../replication/httplib.js";
11
- import { parseHeaderValues } from "../common/utils.js";
11
+ import { isRemediationModeActive, parseHeaderValues } from "../common/utils.js";
12
12
  import { sizeToHumanReadable } from "octagonal-wheels/number";
13
13
  import { REMOTE_RESOURCE_KINDS } from "../replication/index.js";
14
14
  const FAST_FETCH_CHECKPOINT_KEY = "fast-fetch-checkpoint";
@@ -106,6 +106,15 @@ Please enable them from the settings screen after setup is complete.`,
106
106
  await this.informOptionalFeatures();
107
107
  }
108
108
  async performRebuildEverything() {
109
+ if (isRemediationModeActive(this.setting.currentSettings())) {
110
+ this._log(
111
+ `Rebuilding has been refused: remediation mode is active. Clear the modification-time limit to rebuild.`,
112
+ LOG_LEVEL_NOTICE
113
+ );
114
+ throw new Error(
115
+ "Rebuilding is not available while remediation mode is active. Clear the modification-time limit first."
116
+ );
117
+ }
109
118
  this.appLifecycle.resetIsReady();
110
119
  await this.setting.suspendExtraSync();
111
120
  await this.setting.applyPartial({
@@ -249,7 +258,8 @@ Please enable them from the settings screen after setup is complete.`,
249
258
  suspendParseReplicationResult: false,
250
259
  suspendFileWatching: false
251
260
  });
252
- if (!await this.vault.scanVault(true)) return false;
261
+ const inRemediationMode = isRemediationModeActive(this.setting.currentSettings());
262
+ if (!inRemediationMode && !await this.vault.scanVault(true)) return false;
253
263
  if (!await this.replication.onBeforeReplicate(false)) return false;
254
264
  return true;
255
265
  }
@@ -281,7 +291,7 @@ Please enable them from the settings screen after setup is complete.`,
281
291
  notifyThresholdOfRemoteStorageSize: DEFAULT_SETTINGS.notifyThresholdOfRemoteStorageSize
282
292
  });
283
293
  const settings = this.setting.currentSettings();
284
- if (settings.maxMTimeForReflectEvents > 0) {
294
+ if (isRemediationModeActive(settings)) {
285
295
  const date = new Date(settings.maxMTimeForReflectEvents);
286
296
  const ask = `Your settings restrict file reflection times to no later than ${date.toLocaleString()}.
287
297
 
@@ -318,7 +328,12 @@ Are you sure you wish to proceed?`;
318
328
  await this.resetLocalDatabase();
319
329
  this.clearFastFetchCheckpoint();
320
330
  await delay(1e3);
321
- if (makeLocalChunkBeforeSync) {
331
+ if (isRemediationModeActive(this.setting.currentSettings())) {
332
+ this._log(
333
+ `Remediation mode: the files in storage are not stored in the database before fetching.`,
334
+ LOG_LEVEL_NOTICE
335
+ );
336
+ } else if (makeLocalChunkBeforeSync) {
322
337
  await this.fileHandler.createAllChunks(true);
323
338
  } else if (!preventMakeLocalFilesBeforeSync) {
324
339
  await this.prepareLocalDatabaseForRebuild();
@@ -496,7 +511,9 @@ Total bytes fetched: ${sizeToHumanReadable(progress.totalBytes)}`,
496
511
  if (controlsReflection) {
497
512
  await this.setting.saveSettingData();
498
513
  }
499
- this.appLifecycle.markIsReady();
514
+ if (!isRemediationModeActive(this.setting.currentSettings())) {
515
+ this.appLifecycle.markIsReady();
516
+ }
500
517
  completed = true;
501
518
  return true;
502
519
  } finally {
@@ -94,6 +94,7 @@ export declare abstract class ServiceFileHandlerBase extends ServiceModuleBase<S
94
94
  getPath(entry: AnyEntry): FilePathWithPrefix;
95
95
  getPathWithoutPrefix(entry: AnyEntry): FilePathWithPrefix;
96
96
  readFileFromStub(file: UXFileInfoStub | UXFileInfo): Promise<UXFileInfo>;
97
+ tryRecordUntrackedFileRevision(info: UXFileInfoStub | UXFileInfo, expectedRevision: string): Promise<boolean>;
97
98
  private infoToStub;
98
99
  storeFileToDB(info: UXFileInfoStub | UXFileInfo | UXInternalFileInfoStub | FilePathWithPrefix, force?: boolean, onlyChunks?: boolean): Promise<boolean>;
99
100
  storeFileToDBWithBaseRevision(info: UXFileInfoStub | UXFileInfo | FilePathWithPrefix, baseRevision: string, createIfDifferent?: boolean): Promise<boolean>;
@@ -215,6 +215,36 @@ class ServiceFileHandlerBase extends ServiceModuleBase {
215
215
  }
216
216
  return readFile;
217
217
  }
218
+ async tryRecordUntrackedFileRevision(info, expectedRevision) {
219
+ if (!this.fileReflectionProvenance || !expectedRevision) return false;
220
+ const path = getStoragePathFromUXFileInfo(info);
221
+ try {
222
+ return await this.serializedByFileEventPaths([path], async () => {
223
+ const provenance = this.fileReflectionProvenance;
224
+ if (await provenance.get(path)) return false;
225
+ const stub = await this.storage.getStub(path);
226
+ if (!stub || isFolderInfo(stub) || stub.path !== path) return false;
227
+ const file = await this.readFileFromStub(stub);
228
+ const current = await this.db.fetchEntryMeta(path, void 0, true);
229
+ if (!current || current._rev !== expectedRevision || current.deleted || current._deleted) return false;
230
+ if ((await this.db.getConflictedRevs(path)).length > 0) return false;
231
+ const entry = await this.db.fetchEntry(path, expectedRevision, true, true, true);
232
+ if (!entry || entry._rev !== expectedRevision || entry.deleted || entry._deleted) return false;
233
+ if (!await isDocContentSame(readContent(entry), file.body)) return false;
234
+ const latest = await this.db.fetchEntryMeta(path, void 0, true);
235
+ if (!latest || latest._rev !== expectedRevision || latest.deleted || latest._deleted) return false;
236
+ if ((await this.db.getConflictedRevs(path)).length > 0) return false;
237
+ if (!await this.currentStorageSnapshotMatches(file, void 0)) return false;
238
+ if (await provenance.get(path)) return false;
239
+ await provenance.set(path, { revision: expectedRevision, observedStorageMtime: file.stat.mtime });
240
+ return true;
241
+ });
242
+ } catch (ex) {
243
+ this._log(`Could not record unchanged file provenance for ${path}`, LOG_LEVEL_VERBOSE);
244
+ this._log(ex, LOG_LEVEL_VERBOSE);
245
+ return false;
246
+ }
247
+ }
218
248
  async infoToStub(info) {
219
249
  if (info == null) return null;
220
250
  const file = typeof info === "string" ? await this.storage.getFileStub(info) : info;
@@ -1,5 +1,5 @@
1
1
  import { ServiceBase } from "./ServiceBase.js";
2
- import { addPrefix, id2path_base, path2id_base } from "../../string_and_binary/path.js";
2
+ import { addPrefix, expandFilePathPrefix, id2path_base, path2id_base } from "../../string_and_binary/path.js";
3
3
  import { isInternalMetadata, stripInternalMetadataPrefix } from "../../common/typeUtils.js";
4
4
  class PathService extends ServiceBase {
5
5
  settingService;
@@ -14,19 +14,12 @@ class PathService extends ServiceBase {
14
14
  }
15
15
  _id2path(id, entry) {
16
16
  const filename = id2path_base(id, entry);
17
- const temp = filename.split(":");
18
- const path = temp.pop();
19
- const normalizedPath = this.normalizePath(path);
20
- temp.push(normalizedPath);
21
- const fixedPath = temp.join(":");
22
- return fixedPath;
17
+ const [prefix, path] = expandFilePathPrefix(filename);
18
+ return prefix + this.normalizePath(path);
23
19
  }
24
20
  async _path2id(filename, obfuscatePassphrase, caseInsensitive) {
25
- const temp = filename.split(":");
26
- const path = temp.pop();
27
- const normalizedPath = this.normalizePath(path);
28
- temp.push(normalizedPath);
29
- const fixedPath = temp.join(":");
21
+ const [prefix, path] = expandFilePathPrefix(filename);
22
+ const fixedPath = prefix + this.normalizePath(path);
30
23
  const out = await path2id_base(fixedPath, obfuscatePassphrase, caseInsensitive);
31
24
  return out;
32
25
  }
@@ -13,6 +13,7 @@ import {
13
13
  import { memorizeFuncWithLRUCache } from "../common/utils.js";
14
14
  import { uint8ArrayToHexString, writeString } from "./convert.js";
15
15
  import { unique } from "octagonal-wheels/collection.js";
16
+ import { CHeader, ICHeader, ICXHeader, PSCHeader } from "../common/models/fileaccess.const.js";
16
17
  function isValidFilenameInWidows(filename) {
17
18
  const regex = /[\u0000-\u001f]|[\\":?<>|*#]/g;
18
19
  if (regex.test(filename)) return false;
@@ -21,11 +22,11 @@ function isValidFilenameInWidows(filename) {
21
22
  return true;
22
23
  }
23
24
  function isValidFilenameInDarwin(filename) {
24
- const regex = /[\u0000-\u001f]|[:]/g;
25
+ const regex = /[\u0000-\u001f]/g;
25
26
  return !regex.test(filename);
26
27
  }
27
28
  function isValidFilenameInLinux(filename) {
28
- const regex = /[\u0000-\u001f]|[:]/g;
29
+ const regex = /[\u0000-\u001f]/g;
29
30
  return !regex.test(filename);
30
31
  }
31
32
  function isValidFilenameInAndroid(filename) {
@@ -33,37 +34,30 @@ function isValidFilenameInAndroid(filename) {
33
34
  return !regex.test(filename);
34
35
  }
35
36
  function isFilePath(path) {
36
- if (path.indexOf(":") === -1) return true;
37
- return false;
37
+ return expandFilePathPrefix(path)[0] === "";
38
38
  }
39
39
  function stripAllPrefixes(prefixedPath) {
40
- if (isFilePath(prefixedPath)) return prefixedPath;
41
- const [, body] = expandFilePathPrefix(prefixedPath);
42
- return stripAllPrefixes(body);
40
+ return stripPrefix(prefixedPath);
43
41
  }
44
42
  function addPrefix(path, prefix) {
45
43
  if (prefix && path.startsWith(prefix)) return path;
46
44
  return `${prefix ?? ""}${path}`;
47
45
  }
48
46
  function expandFilePathPrefix(path) {
49
- let [prefix, body] = path.split(":", 2);
50
- if (!body) {
51
- body = prefix;
52
- prefix = "";
53
- } else {
54
- prefix = prefix + ":";
47
+ for (const prefix of [ICHeader, ICXHeader, PSCHeader]) {
48
+ if (path.startsWith(prefix)) {
49
+ return [prefix, path.substring(prefix.length)];
50
+ }
55
51
  }
56
- return [prefix, body];
52
+ return ["", path];
57
53
  }
58
54
  function expandDocumentIDPrefix(id) {
59
- let [prefix, body] = id.split(":", 2);
60
- if (!body) {
61
- body = prefix;
62
- prefix = "";
63
- } else {
64
- prefix = prefix + ":";
55
+ for (const prefix of [CHeader, PREFIX_OBFUSCATED]) {
56
+ if (id.startsWith(prefix)) {
57
+ return [prefix, id.substring(prefix.length)];
58
+ }
65
59
  }
66
- return [prefix, body];
60
+ return expandFilePathPrefix(id);
67
61
  }
68
62
  const _hashString = memorizeFuncWithLRUCache(async (key) => {
69
63
  const buff = writeString(key);
@@ -112,11 +106,7 @@ function getPathWithoutPrefix(entry) {
112
106
  return stripAllPrefixes(f);
113
107
  }
114
108
  function stripPrefix(prefixedPath) {
115
- const [prefix, body] = prefixedPath.split(":", 2);
116
- if (!body) {
117
- return prefix;
118
- }
119
- return body;
109
+ return expandFilePathPrefix(prefixedPath)[1];
120
110
  }
121
111
  function shouldBeIgnored(filename) {
122
112
  if (filename == FLAGMD_REDFLAG) {
@@ -16,7 +16,7 @@ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "defau
16
16
  import { promiseWithResolvers } from "octagonal-wheels/promises.js";
17
17
 
18
18
  // commonlib-inline-worker:bg.worker.ts
19
- var 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} ${level} ${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 TweakCompatibilityRules = Object.freeze([\n { key: "minimumChunkSize", templateValue: 20, reconstruction: "none" },\n { key: "longLineThreshold", templateValue: 250, reconstruction: "none" },\n { key: "encrypt", templateValue: false, reconstruction: "required" },\n { key: "usePathObfuscation", templateValue: false, reconstruction: "required" },\n { key: "enableCompression", templateValue: false, reconstruction: "none" },\n { key: "useEden", templateValue: false, reconstruction: "none" },\n { key: "customChunkSize", templateValue: 0, reconstruction: "recommended", compatibleLossyOrder: 1 },\n { key: "useDynamicIterationCount", templateValue: false, reconstruction: "required" },\n { key: "hashAlg", templateValue: "xxhash64", reconstruction: "recommended", compatibleLossyOrder: 0 },\n { key: "enableChunkSplitterV2", templateValue: false, reconstruction: "none" },\n { key: "maxChunksInEden", templateValue: 10, reconstruction: "none" },\n { key: "maxTotalLengthInEden", templateValue: 1024, reconstruction: "none" },\n { key: "maxAgeInEden", templateValue: 10, reconstruction: "none" },\n {\n key: "usePluginSyncV2",\n templateValue: false,\n reconstruction: "none",\n knownDefault: false\n },\n {\n key: "handleFilenameCaseSensitive",\n templateValue: false,\n reconstruction: "required",\n knownDefault: false\n },\n { key: "useSegmenter", templateValue: false, reconstruction: "none" },\n {\n key: "E2EEAlgorithm",\n templateValue: E2EEAlgorithms.V2,\n reconstruction: "none",\n knownDefault: DEFAULT_SETTINGS.E2EEAlgorithm\n },\n {\n key: "chunkSplitterVersion",\n templateValue: ChunkAlgorithms.RabinKarp,\n reconstruction: "recommended",\n knownDefault: DEFAULT_SETTINGS.chunkSplitterVersion,\n compatibleLossyOrder: 2\n }\n ]);\n var TweakValuesShouldMatchedTemplate = Object.fromEntries(\n TweakCompatibilityRules.map(({ key, templateValue }) => [key, templateValue])\n );\n var IncompatibleChanges = [\n ...TweakCompatibilityRules.filter(({ reconstruction }) => reconstruction === "required").map(({ key }) => key)\n ];\n var CompatibleButLossyChanges = TweakCompatibilityRules.filter(\n (rule) => "compatibleLossyOrder" in rule\n ).slice().sort((left, right) => left.compatibleLossyOrder - right.compatibleLossyOrder).map(({ key }) => key);\n var IncompatibleChangesInSpecificPattern = TweakCompatibilityRules.flatMap(\n (rule) => (rule.specificPatterns ?? []).map((pattern) => ({\n key: rule.key,\n ...Object.prototype.hasOwnProperty.call(pattern, "from") ? { from: pattern.from } : {},\n ...Object.prototype.hasOwnProperty.call(pattern, "to") ? { to: pattern.to } : {},\n ...pattern.reconstruction === "recommended" ? { isRecommendation: true } : {}\n }))\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 ...Object.fromEntries(\n TweakCompatibilityRules.filter((rule) => "knownDefault" in rule && rule.key !== "handleFilenameCaseSensitive").map(\n ({ key, knownDefault }) => [key, knownDefault]\n )\n ),\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';
19
+ var 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} ${level} ${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 TweakCompatibilityRules = Object.freeze([\n { key: "minimumChunkSize", templateValue: 20, reconstruction: "none" },\n { key: "longLineThreshold", templateValue: 250, reconstruction: "none" },\n { key: "encrypt", templateValue: false, reconstruction: "required" },\n { key: "usePathObfuscation", templateValue: false, reconstruction: "required" },\n { key: "enableCompression", templateValue: false, reconstruction: "none" },\n { key: "useEden", templateValue: false, reconstruction: "none" },\n { key: "customChunkSize", templateValue: 0, reconstruction: "recommended", compatibleLossyOrder: 1 },\n { key: "useDynamicIterationCount", templateValue: false, reconstruction: "required" },\n { key: "hashAlg", templateValue: "xxhash64", reconstruction: "recommended", compatibleLossyOrder: 0 },\n { key: "enableChunkSplitterV2", templateValue: false, reconstruction: "none" },\n { key: "maxChunksInEden", templateValue: 10, reconstruction: "none" },\n { key: "maxTotalLengthInEden", templateValue: 1024, reconstruction: "none" },\n { key: "maxAgeInEden", templateValue: 10, reconstruction: "none" },\n {\n key: "usePluginSyncV2",\n templateValue: false,\n reconstruction: "none",\n knownDefault: false\n },\n {\n key: "handleFilenameCaseSensitive",\n templateValue: false,\n reconstruction: "required",\n knownDefault: false\n },\n { key: "useSegmenter", templateValue: false, reconstruction: "none" },\n {\n key: "E2EEAlgorithm",\n templateValue: E2EEAlgorithms.V2,\n reconstruction: "none",\n knownDefault: DEFAULT_SETTINGS.E2EEAlgorithm\n },\n {\n key: "chunkSplitterVersion",\n templateValue: ChunkAlgorithms.RabinKarp,\n reconstruction: "recommended",\n knownDefault: DEFAULT_SETTINGS.chunkSplitterVersion,\n compatibleLossyOrder: 2\n }\n ]);\n var TweakValuesShouldMatchedTemplate = Object.fromEntries(\n TweakCompatibilityRules.map(({ key, templateValue }) => [key, templateValue])\n );\n var IncompatibleChanges = [\n ...TweakCompatibilityRules.filter(({ reconstruction }) => reconstruction === "required").map(({ key }) => key)\n ];\n var CompatibleButLossyChanges = TweakCompatibilityRules.filter(\n (rule) => "compatibleLossyOrder" in rule\n ).slice().sort((left, right) => left.compatibleLossyOrder - right.compatibleLossyOrder).map(({ key }) => key);\n var IncompatibleChangesInSpecificPattern = TweakCompatibilityRules.flatMap(\n (rule) => (rule.specificPatterns ?? []).map((pattern) => ({\n key: rule.key,\n ...Object.prototype.hasOwnProperty.call(pattern, "from") ? { from: pattern.from } : {},\n ...Object.prototype.hasOwnProperty.call(pattern, "to") ? { to: pattern.to } : {},\n ...pattern.reconstruction === "recommended" ? { isRecommendation: true } : {}\n }))\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 ...Object.fromEntries(\n TweakCompatibilityRules.filter((rule) => "knownDefault" in rule && rule.key !== "handleFilenameCaseSensitive").map(\n ({ key, knownDefault }) => [key, knownDefault]\n )\n ),\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/common/models/fileaccess.const.ts\n var ICHeader = "i:";\n var ICHeaderLength = ICHeader.length;\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';
20
20
  function createWorker() {
21
21
  const blob = new Blob([workerSource], { type: "text/javascript" });
22
22
  const url = URL.createObjectURL(blob);
@@ -85,6 +85,10 @@ The full offline scanner applies both the host's target-file policy and Commonli
85
85
 
86
86
  The unreleased watcher deletion checks and the separate database-to-storage reflection path are recorded in [Storage events and database-to-storage reflection](storage-events-and-reflection.md).
87
87
 
88
+ File-path parsing recognises only the leading `i:`, `ix:`, and `ps:` namespaces. Colons elsewhere belong to the path, including the complete remainder after one namespace. Document-ID parsing additionally recognises `h:` and `f:`; those document IDs are not ordinary storage paths. Keep normalisation, selection patterns, and database lookup on the complete path. `pathPrefixes.unit.spec.ts`, `typeUtils.unit.spec.ts`, and `PathService.unit.spec.ts` cover these conversions, and `ServiceFileHandlerBase.colonPaths.unit.spec.ts` exercises storage and reflection with real PouchDB Metadata and Chunks. Host filename restrictions remain a separate contract: a host must not interpret an unsupported name as permission to write a shortened one.
89
+
90
+ Before HKDF decryption, an obfuscated Metadata document's `path` field contains an encrypted payload beginning `/\:` rather than a logical file path or a document ID. Read that field directly for decryption; apply path and ID conversion only after obtaining the decoded path. `encryption.unit.spec.ts` covers this round trip, the legacy V1 path fallback, and decoded PouchDB replication events. `StreamingFetch.unit.spec.ts` covers decryption before the initial fetch writes and checkpoints a document.
91
+
88
92
  The revision-tree safety rules are documented in [Conflict resolution and file provenance](conflict-resolution.md). `ConflictManager.unit.spec.ts` owns common-ancestor and conservative merge behaviour, deterministic pair selection for multiple live leaves, and reconstruction from the committed tree between stages. `EntryManagerImpls.unit.spec.ts` owns the distinction between force-writing below an exact revision and conditionally advancing a current live leaf through PouchDB's ordinary revision check. `ServiceDatabaseFileAccessBase.unit.spec.ts` owns all-branch content discovery, short-circuiting history existence checks after an exact match, exact-revision logical deletion, and the public live-base result and event boundary. `ServiceFileHandlerBase.unit.spec.ts` owns the injected provenance policy for edit, deletion, and rename operations, together with user-selected reflection, child creation, strict matching, matching-provenance cleanup after exact branch deletion, and stale-revision refusal. `LiveSyncLocalDB.unit.spec.ts` owns chunk reachability across current winners, shared chunks, live conflicts, available merge ancestry, conflict resolution, and PouchDB replication of collection and recreation. Extend the relevant sides when changing conflict resolution, compaction handling, provenance, chunk collection, or database-to-storage overwrite protection.
89
93
 
90
94
  `LiveSyncReplicator.unit.spec.ts` owns the CouchDB remote-chunk batch contract: a mixed `_all_docs` result must return each available document even when another keyed row reports an error. `ChunkFetcher.unit.spec.ts` owns the consumer behaviour: it writes valid returned chunks and emits `missingChunkRemote` only for requested IDs which are absent from the returned set. Extend both sides when changing remote chunk acquisition or missing-chunk delivery.
@@ -138,6 +138,12 @@ By default, the complete scan returns `false` when any pair is `failed`, and ret
138
138
 
139
139
  Self-hosted LiveSync enables this policy only for ordinary Obsidian start-up, where one unavailable path must not prevent unaffected files from synchronising. Fast Setup, Fetch, Rebuild, direct scans, and CLI mirror or daemon paths retain the strict default.
140
140
 
141
+ ## Equal-time files without a recorded revision
142
+
143
+ An equal modification time does not establish that the storage file is unchanged. Before completing such a pair, the scanner asks the file handler to record its current database revision if device-local provenance is absent. The handler reads the actual storage and database content under its document lock and records the revision only when both contain the same bytes, the database has no conflicting leaf, and its current revision agrees with the one observed by the scan. It rechecks the storage snapshot, database revision, and absent provenance before writing the record. This operation writes neither storage content nor a database revision.
144
+
145
+ An existing provenance record keeps its branch identity even when the file bytes match another revision. An unreadable record, unavailable content, differing bytes, a competing branch, or a changing snapshot leaves provenance untouched. The scan still completes that equal-time pair; a later file event or incoming reflection retains the ordinary conservative conflict policy. If the local database has already advanced past the file's content, the equal-time repair cannot establish its earlier origin.
146
+
141
147
  ## Result-state verification
142
148
 
143
149
  Focused two-pass coverage starts with a `DB_APPLY` reflection whose file handler returns `false`, persists the resulting scanner state, and then runs `NEWER_WINS`. It verifies that:
@@ -150,6 +156,8 @@ Focused two-pass coverage starts with a `DB_APPLY` reflection whose file handler
150
156
 
151
157
  Full-scan coverage also verifies that the strict default returns `false`, an ordinary-start-up scan which explicitly continues returns `completed-with-file-failures` while logging the affected path at verbose level, and a later clean scan returns `true`.
152
158
 
159
+ The equal-time regression uses real in-memory PouchDB and the file handler. It checks missing and recorded provenance with unchanged files and genuine local edits, then advances the database and reflects the incoming revision. Focused handler tests cover provenance read and write failures, unreadable current content, an existing conflict, and storage or database changes during verification.
160
+
153
161
  A second two-pass case starts with a `db-only` entry skipped by the size limit. It then removes that limit and verifies that the entry is reflected to storage rather than misclassified as an offline local deletion. Coverage for an existing storage file verifies that a failed `sync-newer` reflection retains the observed storage mtime, and full-scan coverage verifies that the aggregate failure reaches its caller after scanner initialisation completes.
154
162
 
155
163
  Identity coverage verifies early quarantine when no consistent target exists, continued processing when consistent Metadata represents the same logical path, expired-deletion retention, special-namespace routing, actual-ID-first inspection, stale and ambiguous repair rejection, target-first ordering, exact-target retry, source preservation after failure, and last-seen clearing.
@@ -8,6 +8,10 @@ The code paths below identify the maintained Self-hosted LiveSync composition po
8
8
 
9
9
  ## Obsidian plug-in
10
10
 
11
+ Unreleased colon-path regression tests establish that Commonlib preserves ordinary file paths through Metadata storage, Chunk retrieval, and storage reflection, with path obfuscation enabled or disabled. They use real PouchDB with injected storage. This result does not establish which filenames a host's file-creation API accepts; that boundary requires host runtime verification.
12
+
13
+ Commonlib's encryption tests verify that an obfuscated Metadata document retains its document ID while its HKDF-encrypted path and file properties round-trip, that V1-obfuscated paths remain readable through the fallback, and that PouchDB replication presents a decoded path to both local storage and change events. The Fast Fetch test verifies decryption before storage and checkpointing. On 26th September 2026, a local packed candidate of this fix passed LiveSync 1.0.31's `npm run check` and unit tests, as well as real Obsidian two-Vault synchronisation, encrypted CLI-to-Obsidian transfer, and encrypted Metadata retrieval through Fast Fetch during manual CouchDB onboarding.
14
+
11
15
  The plug-in extends the neutral `ServiceContext` with Obsidian-owned capabilities in `src/modules/services/ObsidianServiceContext.ts`. One context instance carries the LiveSync-owned translator and event hub through the Service Hub rather than placing those dependencies in Commonlib globals. Commonlib supplies its typed English fallback when another host omits the translator.
12
16
 
13
17
  The consumer contract in `test/contracts/serviceContext.ts` checks shared result semantics and exact context identity across the composed services. The real-Obsidian suite documented in `test/e2e-obsidian/README.md` then covers plug-in loading, representative Svelte dialogue mounts, Vault reflection, CouchDB and Object Storage synchronisation, a two-device P2P Setup URI round-trip, two-Vault behaviour, and other Obsidian-owned boundaries.
@@ -16,6 +20,8 @@ Commonlib supplies the two sleep preferences and preserves them through Setup UR
16
20
 
17
21
  Commonlib's real-PouchDB and injected-boundary unit tests prove that conservative merge uses the nearest revision actually shared by both conflict leaves, multiple remaining leaves are selected in a deterministic order, each completed pair is reconstructed from the committed tree, storage content with exact provenance remains recognisable below a deleted losing branch after resolution, and ordinary file saves preserve edits below their recorded base or on an independent root when the base cannot be read. Incoming reflection uses the same classification. Current non-deleted leaf matches prevent duplicate preservation without using historical byte equality as proof of an unchanged file. Conflict-time deletion and rename retain their separate displayed-branch contracts. They also verify that a boolean history check stops after its first exact content match without reading an older unavailable revision, while revision enumeration still returns every match. Unknown-origin local content remains readable on a fresh independent root when the winning body is unavailable, including when the existing winner is generation one. A separately confirmed exact deletion of an unreadable current leaf remains an explicit repair operation. Exact reconciliation tests cover reflecting a selected live leaf, storing Vault content as its child, recording a matching leaf without creating a revision, clearing matching provenance after exact branch deletion, and refusing to record a stale revision or a revision whose content differs. Separate live-base tests advance a selected conflict leaf or logical-deletion leaf through PouchDB's ordinary revision check, retain the other live leaf, and reject reuse of a stale base. Self-hosted LiveSync supplies the host composition, persistent device-local provenance, and the per-revision repair interface. Its optional two-Vault scopes cover post-resolution propagation and edit, logical deletion, case-only rename, and cross-path rename while conflicts remain active. The conflict-operation scope passes in real Obsidian against the exact locally packed Commonlib artefact, including replicated parent revisions and preservation of the other live branches. Its Document History scenario restores readable historical bytes as a new live successor and reflects that exact revision to the Vault.
18
22
 
23
+ The equal-time scan test uses real in-memory PouchDB to verify that a missing record is established from unchanged current content before a newer revision arrives. It also verifies that existing provenance is retained and equal-time local edits remain protected as conflicts. Focused handler tests cover failures and changes during verification. Self-hosted LiveSync owns the persistent store and real-Obsidian restart check; these Commonlib tests do not exercise Windows file events or remote CouchDB timing.
24
+
19
25
  Commonlib's chunk-reachability tests use real PouchDB revision trees. They verify that an ordinary superseded revision releases its unique chunks, a chunk shared by current files remains reachable, live conflict branches and their nearest available shared ancestor remain protected, and losing-branch ancestry becomes eligible after resolution. They also replicate a collected chunk deletion to another PouchDB database and verify that writing the same content can recreate and replicate the content-addressed chunk. Self-hosted LiveSync owns the CouchDB-specific Garbage Collection V3 workflow, including device checks, confirmation, deletion, push-only replication, and remote compaction.
20
26
 
21
27
  Commonlib's injected CouchDB tests verify that a mixed remote chunk batch preserves available documents when another requested ID is absent. Its chunk-delivery tests separately verify that available chunks reach local storage and only absent IDs are marked unavailable. Self-hosted LiveSync supplies the real CouchDB connection and start-up composition, so device-specific replication timing remains downstream integration evidence rather than Commonlib unit coverage.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vrtmrz/livesync-commonlib",
3
- "version": "0.1.27",
3
+ "version": "0.1.29",
4
4
  "description": "Shared data, storage, and replication primitives for Self-hosted LiveSync clients.",
5
5
  "type": "module",
6
6
  "types": "./dist/index.d.ts",