@gusto/baerly-storage 0.3.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +157 -92
- package/dist/API.md +64 -32
- package/dist/CHANGELOG.md +301 -5
- package/dist/RECIPES.md +125 -0
- package/dist/THIRD-PARTY-LICENSES.txt +22 -96
- package/dist/{app-config-BIzyAKzy.d.ts → app-config-DyiFK3_k.d.ts} +43 -11
- package/dist/app-config.d.ts +1 -1
- package/dist/auth.d.ts +1 -1
- package/dist/auth.js +13 -13
- package/dist/auth.js.map +1 -1
- package/dist/aws4fetch.esm-p7eEzLCs.js +1702 -0
- package/dist/aws4fetch.esm-p7eEzLCs.js.map +1 -0
- package/dist/baerly.js +35 -15
- package/dist/baerly.js.map +1 -1
- package/dist/baerly.spec.json +342 -0
- package/dist/{client-BJXF3XJA.d.ts → client-Fe8CwB73.d.ts} +3 -3
- package/dist/client-react.d.ts +3 -3
- package/dist/client-react.js +4 -4
- package/dist/client-react.js.map +1 -1
- package/dist/client.d.ts +4 -4
- package/dist/client.js +3 -3
- package/dist/{cloudflare-Cn2ibODt.js → cloudflare-DzKBrUlg.js} +2 -2
- package/dist/{cloudflare-Cn2ibODt.js.map → cloudflare-DzKBrUlg.js.map} +1 -1
- package/dist/cloudflare.d.ts +49 -6
- package/dist/cloudflare.js +55 -21
- package/dist/cloudflare.js.map +1 -1
- package/dist/config-1tv0-Yzm.js +2693 -0
- package/dist/config-1tv0-Yzm.js.map +1 -0
- package/dist/constants-CfeMWQWk.js +222 -0
- package/dist/constants-CfeMWQWk.js.map +1 -0
- package/dist/{cost-BZ_MDBmn.js → cost-DSMIVqzL.js} +42 -43
- package/dist/cost-DSMIVqzL.js.map +1 -0
- package/dist/{current-json-DsN7FNY1.js → current-json-C6nhPOm1.js} +6 -204
- package/dist/current-json-C6nhPOm1.js.map +1 -0
- package/dist/{db-CCT6tDfY.d.ts → db-DsPkOVEH.d.ts} +3 -3
- package/dist/{deploy-BKKyGlSJ.js → deploy-DonTr-CV.js} +4 -4
- package/dist/{deploy-BKKyGlSJ.js.map → deploy-DonTr-CV.js.map} +1 -1
- package/dist/dev-vite.d.ts +9 -5
- package/dist/dev-vite.js +5 -4
- package/dist/dev-vite.js.map +1 -1
- package/dist/dev.d.ts +1 -1
- package/dist/dev.js +1 -1
- package/dist/{doctor-BVU4GNXN.js → doctor-DSIyCDg_.js} +5 -8
- package/dist/{doctor-BVU4GNXN.js.map → doctor-DSIyCDg_.js.map} +1 -1
- package/dist/{dump-DPEAKub6.js → dump-Bh5k26VQ.js} +9 -32
- package/dist/dump-Bh5k26VQ.js.map +1 -0
- package/dist/{errors-DOdL95kK.js → errors-Dfa3p78c.js} +25 -5
- package/dist/errors-Dfa3p78c.js.map +1 -0
- package/dist/{export-BcuCLFFe.js → export-DtF5tDIM.js} +9 -32
- package/dist/{export-BcuCLFFe.js.map → export-DtF5tDIM.js.map} +1 -1
- package/dist/{fsck-RXgLOaJG.js → fsck-D_djMO5D.js} +10 -33
- package/dist/fsck-D_djMO5D.js.map +1 -0
- package/dist/{http-Bd4byR4n.js → http-DxM9MflO.js} +123 -35
- package/dist/http-DxM9MflO.js.map +1 -0
- package/dist/http.d.ts +42 -26
- package/dist/http.js +3 -2
- package/dist/{index-DnBGSeuU.d.ts → index-0rZcMBwy.d.ts} +2 -2
- package/dist/{index-Cmsxx-ZN.d.ts → index-B6oexfOB.d.ts} +7 -7
- package/dist/{index-BDceQQi-.d.ts → index-BNRh23K9.d.ts} +4 -4
- package/dist/{index-DW7GT6M2.d.ts → index-BYk9oCNf.d.ts} +193 -163
- package/dist/index.d.ts +6 -6
- package/dist/index.js +4 -4
- package/dist/{indexes-Cx7uMXm0.d.ts → indexes-Dn9hbGQG.d.ts} +2 -2
- package/dist/{inspect-DhI49PSi.js → inspect-6WZ-pC7-.js} +10 -33
- package/dist/inspect-6WZ-pC7-.js.map +1 -0
- package/dist/key-Di6yyxFu.js +35 -0
- package/dist/key-Di6yyxFu.js.map +1 -0
- package/dist/{log-tail-DXeDkWEp.js → log-tail-D98U1JBo.js} +31 -7
- package/dist/log-tail-D98U1JBo.js.map +1 -0
- package/dist/{maintenance-CWBQpZ2y.js → maintenance-B4Dki6Ig.js} +77 -22
- package/dist/maintenance-B4Dki6Ig.js.map +1 -0
- package/dist/{maintenance-BkhUr72A.d.ts → maintenance-B_e0T99L.d.ts} +28 -5
- package/dist/{maintenance-C_KSkVjd.js → maintenance-C7coQp4c.js} +17 -16
- package/dist/maintenance-C7coQp4c.js.map +1 -0
- package/dist/maintenance.d.ts +3 -3
- package/dist/maintenance.js +3 -3
- package/dist/node.d.ts +168 -65
- package/dist/node.js +3 -2
- package/dist/{normalize-XWY25_sG.js → normalize-rjnZLwS4.js} +2 -2
- package/dist/normalize-rjnZLwS4.js.map +1 -0
- package/dist/{observability-BYd-RzEx.js → observability-wzs3-BL_.js} +233 -71
- package/dist/observability-wzs3-BL_.js.map +1 -0
- package/dist/observability.d.ts +2 -2
- package/dist/observability.js +1 -1
- package/dist/{plan-DIu_B6fy.js → plan-a7PJHBCy.js} +2 -2
- package/dist/{plan-DIu_B6fy.js.map → plan-a7PJHBCy.js.map} +1 -1
- package/dist/{query-sQNO5vU_.js → query-rAtXNQQB.js} +96 -207
- package/dist/query-rAtXNQQB.js.map +1 -0
- package/dist/{rebuild-index-DP4CqSSs.js → rebuild-index-BVzQSZlm.js} +9 -32
- package/dist/rebuild-index-BVzQSZlm.js.map +1 -0
- package/dist/{request-BEF_OvMh.js → request-u0M51mhJ.js} +3 -3
- package/dist/{request-BEF_OvMh.js.map → request-u0M51mhJ.js.map} +1 -1
- package/dist/{restore-DpQYef6r.js → restore-R-4rbciV.js} +73 -100
- package/dist/restore-R-4rbciV.js.map +1 -0
- package/dist/runtime-spec-_GTdeSMo.js +391 -0
- package/dist/runtime-spec-_GTdeSMo.js.map +1 -0
- package/dist/s3-http-B-z8th6O.d.ts +60 -0
- package/dist/s3.d.ts +47 -0
- package/dist/s3.js +45 -0
- package/dist/s3.js.map +1 -0
- package/dist/{shared-secret-BJdSwpgw.js → shared-secret-DgEicd3x.js} +13 -5
- package/dist/shared-secret-DgEicd3x.js.map +1 -0
- package/dist/{src-Db4-qVtM.js → src-CYHFDrKz.js} +51 -8
- package/dist/src-CYHFDrKz.js.map +1 -0
- package/dist/{src-CWpkSbvJ.js → src-DYZ4H1aF.js} +6 -5
- package/dist/src-DYZ4H1aF.js.map +1 -0
- package/dist/src-D__mHQmQ.js +2271 -0
- package/dist/src-D__mHQmQ.js.map +1 -0
- package/dist/{subcommand-CP9NY2J4.js → subcommand-DoDA-K7d.js} +44 -6
- package/dist/subcommand-DoDA-K7d.js.map +1 -0
- package/dist/time-DUqvFMHq.js +119 -0
- package/dist/time-DUqvFMHq.js.map +1 -0
- package/dist/{usage-CTfDq9HR.js → usage-DBV1eQHC.js} +7 -22
- package/dist/usage-DBV1eQHC.js.map +1 -0
- package/dist/wire-izfGZDvr.js.map +1 -1
- package/package.json +51 -27
- package/dist/config-CGyBopy3.js +0 -5326
- package/dist/config-CGyBopy3.js.map +0 -1
- package/dist/cost-BZ_MDBmn.js.map +0 -1
- package/dist/current-json-DsN7FNY1.js.map +0 -1
- package/dist/dump-DPEAKub6.js.map +0 -1
- package/dist/errors-DOdL95kK.js.map +0 -1
- package/dist/fsck-RXgLOaJG.js.map +0 -1
- package/dist/http-Bd4byR4n.js.map +0 -1
- package/dist/inspect-DhI49PSi.js.map +0 -1
- package/dist/log-tail-DXeDkWEp.js.map +0 -1
- package/dist/maintenance-CWBQpZ2y.js.map +0 -1
- package/dist/maintenance-C_KSkVjd.js.map +0 -1
- package/dist/normalize-XWY25_sG.js.map +0 -1
- package/dist/observability-BYd-RzEx.js.map +0 -1
- package/dist/query-sQNO5vU_.js.map +0 -1
- package/dist/rebuild-index-DP4CqSSs.js.map +0 -1
- package/dist/restore-DpQYef6r.js.map +0 -1
- package/dist/shared-secret-BJdSwpgw.js.map +0 -1
- package/dist/src-CWpkSbvJ.js.map +0 -1
- package/dist/src-D24wDpzR.js +0 -6247
- package/dist/src-D24wDpzR.js.map +0 -1
- package/dist/src-Db4-qVtM.js.map +0 -1
- package/dist/subcommand-CP9NY2J4.js.map +0 -1
- package/dist/usage-CTfDq9HR.js.map +0 -1
- /package/dist/{chunk-EAsCxrDo.js → rolldown-runtime-EAsCxrDo.js} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"config-CGyBopy3.js","names":["utf8Encoder","compareKeysUtf8","#objects","#etagCounter","#nextEtag","#root","#pathFor","validateEntityName","DEFAULT_XML_ENTITIES","defaultOptions","METADATA_SYMBOL","isName","xmlNode","#endpoint","#bucket","#fetch","#sign","#retries","#backoffMs","#dispatch","#objectUrl","#retry"],"sources":["../packages/protocol/src/constants.ts","../packages/protocol/src/storage/memory.ts","../packages/protocol/src/types.ts","../packages/protocol/src/time.ts","../packages/dev/src/local-fs.ts","../node_modules/.pnpm/fast-xml-parser@5.8.0/node_modules/fast-xml-parser/src/util.js","../node_modules/.pnpm/@nodable+entities@2.1.0/node_modules/@nodable/entities/src/entities.js","../node_modules/.pnpm/@nodable+entities@2.1.0/node_modules/@nodable/entities/src/EntityDecoder.js","../node_modules/.pnpm/fast-xml-parser@5.8.0/node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js","../node_modules/.pnpm/fast-xml-parser@5.8.0/node_modules/fast-xml-parser/src/xmlparser/xmlNode.js","../node_modules/.pnpm/xml-naming@0.1.0/node_modules/xml-naming/src/index.js","../node_modules/.pnpm/fast-xml-parser@5.8.0/node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js","../node_modules/.pnpm/strnum@2.3.0/node_modules/strnum/strnum.js","../node_modules/.pnpm/fast-xml-parser@5.8.0/node_modules/fast-xml-parser/src/ignoreAttributes.js","../node_modules/.pnpm/path-expression-matcher@1.5.0/node_modules/path-expression-matcher/src/Expression.js","../node_modules/.pnpm/path-expression-matcher@1.5.0/node_modules/path-expression-matcher/src/ExpressionSet.js","../node_modules/.pnpm/path-expression-matcher@1.5.0/node_modules/path-expression-matcher/src/Matcher.js","../node_modules/.pnpm/fast-xml-parser@5.8.0/node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js","../node_modules/.pnpm/fast-xml-parser@5.8.0/node_modules/fast-xml-parser/src/xmlparser/node2json.js","../node_modules/.pnpm/fast-xml-parser@5.8.0/node_modules/fast-xml-parser/src/validator.js","../node_modules/.pnpm/fast-xml-parser@5.8.0/node_modules/fast-xml-parser/src/xmlparser/XMLParser.js","../packages/adapter-node/src/xml.ts","../packages/adapter-node/src/s3-http.ts","../node_modules/.pnpm/aws4fetch@1.0.20/node_modules/aws4fetch/dist/aws4fetch.esm.mjs","../packages/adapter-node/src/credentials/signer.ts","../packages/adapter-node/src/storage-factories.ts","../packages/cli/src/bucket-uri.ts","../packages/cli/src/config.ts"],"sourcesContent":["/**\n * Max total object-key length S3 and R2 accept (UTF-8 bytes). A key\n * over this fails the PUT with an opaque provider 400; baerly surfaces\n * it early as InvalidConfig. See docs/spec/storage-compatibility.md.\n */\nexport const MAX_KEY_BYTES = 1024;\n\n/**\n * Half-window (in milliseconds) within which a `LogEntry`'s embedded\n * `commit_ts` must agree with wall-clock time for downstream consumers\n * to accept the entry as causally ordered. Bound on tolerated\n * client/server clock skew across the protocol.\n *\n * 5 s is the protocol's tolerance for client/server clock skew.\n * Tightening this can cause spurious rejections on machines that\n * haven't synced NTP; loosening it widens the window during which\n * causal ordering can be disturbed by skew.\n *\n * @see docs/spec/sync-protocol.md\n * @see packages/protocol/src/storage/types.ts (`Storage` JSDoc)\n */\nexport const LAG_WINDOW_MILLIS: number = 5000;\n\n/**\n * Bit width of the descending base-32 seq segment in every LSN\n * (`<base32-time>_<session>_<seq>`, minted in `Writer.commit`).\n * The output character width is `Math.ceil(COUNT_BIT_WIDTH / 5) = 11`.\n *\n * **Domain:** 0 .. `Number.MAX_SAFE_INTEGER` (2^53 − 1). A collection\n * would need 2^53 writes before the seq counter could overflow — an\n * unreachable ceiling in practice.\n *\n * **Why 53 bits:** JavaScript numbers are IEEE-754 doubles; the safe\n * integer range is exactly [0, 2^53 − 1]. Encoding at this width keeps\n * the arithmetic in the encoder and decoder (`uint2strDesc` /\n * `str2uintDesc` in `packages/protocol/src/types.ts`) exact and\n * leaves no headroom for the negative-overflow path that manifested\n * at the old 10-bit width (domain 0..1023).\n *\n * **Ordering property:** fixed-width base-32 encoding preserves\n * descending lex order across the entire domain\n * (`countKey(a) > countKey(b)` iff `a < b`), which the reverse-walk\n * on `Storage.list` relies on.\n *\n * **Three production consumers** must all agree on this value:\n * 1. Encoder — `countKey` in `packages/protocol/src/types.ts`\n * 2. Decoder — `lsnParts` in `packages/protocol/src/log.ts`\n * 3. Validator regex — `LSN_RE` in `packages/server/src/http/since.ts`\n * (derives its `{N}` from `Math.ceil(COUNT_BIT_WIDTH / 5)`)\n *\n * The independent shape-assertion literal in\n * `tests/fixtures/collection-api-cascade.ts` is kept hand-written and\n * is NOT a consumer of this constant (importing the production\n * validator into the test that checks it would make the assertion\n * a tautology).\n *\n * Changing this constant is a protocol-breaking change — it reshapes\n * every emitted LSN cursor.\n *\n * @see packages/protocol/src/types.ts (`countKey`, `uint2strDesc`)\n * @see packages/protocol/src/log.ts (`lsnParts`, `str2uintDesc` call)\n * @see packages/server/src/http/since.ts (`LSN_RE`)\n * @see docs/spec/log-entry-shape.md\n */\nexport const COUNT_BIT_WIDTH: number = 53;\n\n/**\n * Bit width of the base-32 timestamp prefix encoded into every\n * {@link LogEntry.lsn} (`<base32-time>_<session>_<seq>`, minted in\n * `Writer.commit`). 42 bits gives ~139 years of millisecond\n * precision, which is enough for the protocol's lifetime.\n *\n * Changing this is a protocol-breaking change — it would re-shape\n * every emitted LSN.\n *\n * @see packages/protocol/src/time.ts (`timestamp`)\n * @see packages/server/src/writer.ts (`Writer.commit`)\n * @see docs/spec/sync-protocol.md\n */\nexport const TIMESTAMP_BIT_WIDTH: number = 42;\n\n/**\n * Length of the random-prefix `session` segment embedded in every\n * {@link LogEntry.lsn} (`<base32-time>_<session>_<seq>`). 6 hex chars\n * from `crypto.randomUUID()` give 16⁶ ≈ 1.7 × 10⁷ distinct sessions;\n * birthday-collision rate at N=100 is ~3 × 10⁻⁴, comfortably below\n * the 1 % bound asserted in `tests/regressions.test.ts`. Collisions\n * within a single commit's writer set are also disambiguated by the\n * trailing `<seq>` counter.\n *\n * @see packages/server/src/writer.ts (`Writer.commit` —\n * `session = uuid().slice(0, SESSION_ID_LENGTH)`)\n */\nexport const SESSION_ID_LENGTH: number = 6;\n\n/**\n * Maximum attempts `S3HttpStorage.list` will make per page when the\n * server replies 429 (rate-limited). After this many in a row, it\n * gives up with `NetworkError`. Separate from the inner transient-\n * failure budget so a single hot page can't burn the whole retry\n * allowance.\n */\nexport const LIST_OBJECT_MAX_RETRIES: number = 10;\n\n/**\n * Backoff (in milliseconds) inserted between LIST attempts when S3\n * returns 429 (rate-limited).\n */\nexport const RATE_LIMIT_BACKOFF_MILLIS: number = 1000;\n\n/**\n * Upper clamp on a server-provided `Retry-After` hint, in seconds.\n * RFC 7231 §7.1.3 allows arbitrary delta-seconds or HTTP-dates, but a\n * client that blindly honours a multi-hour hint hands a misbehaving\n * proxy a denial-of-service primitive. 60s covers any plausible S3-\n * compatible throttle while keeping the worst-case bounded.\n *\n * @see packages/protocol/src/storage/s3-http.ts (`parseRetryAfter`)\n */\nexport const RETRY_AFTER_MAX_SECONDS: number = 60;\n\n/**\n * Default retry budget for `S3HttpStorage.retry` (the wrapper around\n * each of the four `Storage` methods). Bounded so that permanent\n * failures (CORS misconfig, NXDOMAIN, persistent 5xx) surface to\n * callers as rejected promises instead of retrying forever and\n * leaving `Writer.commit()` permanently pending.\n *\n * 8 attempts at the existing 100ms→×1.5→10s schedule covers ~30s of\n * transient turbulence, which is enough to ride out a leader election\n * or a brief network blip without papering over a real outage.\n */\nexport const S3_REQUEST_MAX_RETRIES: number = 8;\n\n/**\n * Maximum concurrent log-entry GETs issued by a single `walkLogRange`\n * call. Bounds Class-B fan-out per read and per CAS attempt — without\n * a bound, a reader on a collection whose compactor has fallen behind\n * fans out one GET per live-tail entry (typically 50-100 on the free-\n * tier profile), and a contended writer multiplies that by the CAS\n * retry budget ({@link S3_REQUEST_MAX_RETRIES}).\n *\n * 16 keeps the worst-case under retry to `16 * 8 = 128` concurrent\n * GETs — comfortably under the Workers subrequest cap (50 concurrent\n * / 1000 total) and leaving headroom for the writer's content / index\n * / log / CAS PUTs sharing the same isolate.\n *\n * @see packages/server/src/log-walk.ts (`walkLogRange`)\n */\nexport const MAX_PARALLEL_LOG_READS: number = 16;\n\n/**\n * Runaway guard on the tolerant forward-probe walk (`probeTailFrom`):\n * max `log/<seq>` GETs past `tail_hint` before it THROWS `Internal`\n * (rather than silently truncating reads). A runaway alarm only — the\n * maintenance tick keeps `tail_hint` near the tail, so a >cap gap means\n * maintenance is off or the collection is far past graduation.\n *\n * @see packages/server/src/log-tail.ts (`probeTailFrom`)\n */\nexport const LOG_FORWARD_PROBE_CAP: number = 100_000;\n\n/**\n * Current major version of the `current.json` control-object schema.\n * Readers MUST reject unknown versions with\n * `BaerlyError{code:\"InvalidResponse\"}` rather than try to coerce.\n *\n * Bump only on a breaking change to `CurrentJson` field semantics.\n * Adding a new optional field is NOT breaking; renaming or removing\n * a field IS breaking.\n *\n * @see packages/protocol/src/coordination/current-json.ts\n */\nexport const CURRENT_JSON_SCHEMA_VERSION = 3 as const;\n\n/**\n * MIME type written for `current.json` PUTs. S3 round-trips this on\n * subsequent GETs; useful for diagnostics when staring at a bucket\n * via the AWS console.\n *\n * @see packages/protocol/src/coordination/current-json.ts\n */\nexport const CURRENT_JSON_CONTENT_TYPE: string = \"application/json\";\n\n/**\n * Current major version of the `gc/pending.json` control-object\n * schema. Readers MUST reject unknown versions with\n * `BaerlyError{code:\"InvalidResponse\"}` rather than try to coerce.\n *\n * Bump only on a breaking change to `GcPending` field semantics.\n * Adding a new optional field is NOT breaking; renaming or removing\n * a field IS breaking.\n *\n * @see packages/protocol/src/coordination/gc-pending.ts\n */\nexport const GC_PENDING_SCHEMA_VERSION = 1 as const;\n\n/**\n * MIME type written for `gc/pending.json` PUTs.\n *\n * @see packages/protocol/src/coordination/gc-pending.ts\n */\nexport const GC_PENDING_CONTENT_TYPE: string = \"application/json\";\n\n/**\n * Default grace period between \"marking\" a key for GC and \"sweeping\"\n * (deleting) it. 7 days, chosen to span the worst plausible writer-\n * retry window (a paused-process writer that resumes hours later\n * should still find its idempotency anchor on the bucket). The\n * `runGc()` function accepts an override for tests.\n *\n * Why 7 days specifically:\n * - **1 day is too aggressive for batch workloads.** Worker isolate\n * scheduling pauses, cross-region replication lag, and\n * {@link RATE_LIMIT_BACKOFF_MILLIS} retry cascades can plausibly\n * exceed an hour under pathological conditions.\n * - **30 days is conservative beyond the worst plausible pause.**\n * Doubles `gc/pending.json` size at steady state and slows\n * visibility into \"did GC actually run?\" by 4×.\n * - **7 days spans the realistic upper bound** — long-running batch\n * jobs, multi-region propagation delays, queue backlogs, and\n * downstream outages the writer is retrying through. The protocol\n * is unaffected by the choice of value within the [hours, weeks]\n * range; this constant is the operator-tunable knob.\n *\n * Production code MUST NOT call `runGc` with `graceMillis` below the\n * default outside maintenance windows — going below the longest\n * plausible writer-retry latency risks deleting an anchor a writer\n * is about to find on retry. Test code that sets `graceMillis: 0` is\n * exercising the sweep path deliberately, not modelling production.\n *\n * @see packages/server/src/gc.ts\n */\n// Stryker disable next-line ArithmeticOperator: internal tuning value, not an off-process contract — asserting the literal would be a tautological change-detector. See docs/contributing/mutation-testing.md constants policy.\nexport const GC_GRACE_PERIOD_MILLIS: number = 7 * 24 * 60 * 60 * 1000;\n\n/**\n * Cap on candidates kept in `gc/pending.json` to bound the size of\n * the file. The compactor marks at most this many candidates per\n * pass; subsequent passes pick up the rest. Larger collections will\n * lag GC by one pass per `GC_MAX_PENDING_CANDIDATES` orphans, which\n * is acceptable.\n *\n * @see packages/server/src/gc.ts\n */\nexport const GC_MAX_PENDING_CANDIDATES: number = 1000;\n\n/**\n * Bounded retry cap for the `gc/pending.json` CAS read-modify-write\n * loop in {@link casUpdateGcPending}. On `Conflict` (a concurrent GC\n * pass landed between this pass's read and its write) the loop\n * re-reads `latest` and re-applies the pure merge mutator, retrying up\n * to this many total attempts before surfacing `Conflict`. Safe to\n * retry because the mutator is pure and the sweep DELETEs are\n * idempotent and already performed; a re-merge against fresh state\n * never loses a concurrently-marked candidate. Small fixed cap — under\n * one writer per collection at steady state, contention is rare; this\n * just bounds the worst case so a pathological storm can't spin.\n *\n * @see packages/protocol/src/coordination/gc-pending.ts\n */\nexport const GC_PENDING_CAS_MAX_ATTEMPTS: number = 3;\n\n/**\n * Fold-trigger ratio: fold fires at tail ≥ R×snapshot. Pure READ-AMP / fold-frequency\n * knob — with the ceiling on the snapshot axis (Decision 3a, tail sliced) the\n * auto-maintained snapshot ceiling is S_max = C, NOT C/(1+R). R=1.0 caps steady-state\n * read-amp at ~2× and keeps compaction write-amp (≈1+1/R) moderate. See\n * docs/about/graduation.md for the derivation.\n *\n * @see docs/about/graduation.md\n * @see packages/server/src/maintenance.ts\n */\nexport const MAINTENANCE_TARGET_RATIO: number = 1;\n\n/**\n * Floor for the ratio denominator — avoid div-by-tiny on a fresh collection. Also\n * sets the first-fold threshold: until a snapshot exists, fold fires at tail ≈ this.\n *\n * @see packages/server/src/maintenance.ts\n */\n// Stryker disable next-line ArithmeticOperator: internal tuning value, not an off-process contract — asserting the literal would be a tautological change-detector. See docs/contributing/mutation-testing.md constants policy.\nexport const MAINTENANCE_MIN_LIVE_BYTES: number = 64 * 1024;\n\n/**\n * Cold-start per-entry byte estimate for the ratio TRIGGER's derived live-tail\n * size (`estimateTailBytes`), used until the compactor stamps a real\n * `current.json.mean_entry_bytes` on the first fold. Folding too-few entries is\n * barred by Gate-1's entry-count floor (`minEntriesToCompact`), NOT by this\n * value — so over-estimating is equally safe; this is a first-fold-TIMING\n * choice. A small typical log-entry size keeps the first fold's cadence close\n * to a precisely measured path for typical entries; must be non-zero so a\n * bare `Db.create()` still bootstraps its first auto-fold (a 0 fallback leaves\n * the ratio dead pre-stamp). Large-body collections see a bounded first-fold\n * delay; after it stamps a real mean the estimate tracks the exact tail.\n *\n * @see packages/server/src/maintenance.ts (`estimateTailBytes`)\n */\n// Stryker disable next-line ArithmeticOperator: internal cold-start tuning value, not an off-process contract — asserting the literal would be a tautological change-detector. See docs/contributing/mutation-testing.md constants policy.\nexport const MAINTENANCE_COLD_START_ENTRY_BYTES: number = 128;\n\n/**\n * Per-tick GC budget — these are DEFAULTS (= the most-constrained tier, CF free, reusing\n * the TESTED `CLOUDFLARE_FREE_TIER` values in maintenance.ts / maintenance.budget.test.ts).\n * The adapter THREADS per-tier overrides into the context (§8.4); Node/CF-paid raise them.\n * NOT universal constants — a Node-sized value here would silently kill every CF-free fold\n * (round-4 Tier-1). gc pass ≈ 6 + maxMarks + maxSweeps subrequests (both GET/DELETE the\n * bucket — §3.1). Cadence is BOUNDARY-CROSSING (§3.1), not modulo.\n *\n * @see packages/server/src/maintenance.ts\n * @see packages/server/src/maintenance.budget.test.ts\n */\nexport const WRITE_TICK_GC_INTERVAL: number = 4; // tuned so maxSweeps/interval ≥ p (§7.1)\n\n/**\n * Fold-starvation guard (critique A): on `phasesPerTick:\"single\"`, every Nth GC-interval is a\n * HARD GC boundary the fold may NOT preempt, so a long fold-heavy drain can't starve GC to zero.\n * Stateless (seq-derived) — no per-isolate preemption counter (CF recycles isolates). At 4 a\n * sustained drain still yields ~1 GC tick per 4 GC-intervals.\n *\n * @see packages/server/src/maintenance.ts\n */\nexport const GC_STARVATION_GUARD: number = 4;\n\n/**\n * Maximum GC marks per write-tick pass (M in 6+M+S; GETs the live tail to hash).\n *\n * @see packages/server/src/maintenance.ts\n */\nexport const WRITE_TICK_GC_MAX_MARKS: number = 20;\n\n/**\n * Maximum GC sweeps per write-tick pass (S in 6+M+S; DELETE subrequests).\n *\n * @see packages/server/src/maintenance.ts\n */\nexport const WRITE_TICK_GC_MAX_SWEEPS: number = 10;\n\n/**\n * Per-pass tail SLICE default — compact()'s maxEntriesPerRun. Fold ≤ this+3 subrequests, so\n * a large tail drains incrementally over write-ticks (Decision 3). Adapter-overridable.\n *\n * @see packages/server/src/maintenance.ts\n */\nexport const WRITE_TICK_FOLD_ENTRIES_PER_PASS: number = 20;\n\n/**\n * compact()'s minEntriesToCompact, set EXPLICITLY by the runner so it agrees with Gate 1\n * rather than inheriting compact()'s silent default 100 (which would contradict the 64 KB\n * first-fold story — round-4 Tier-3). Adapter-overridable; CF-free value.\n *\n * @see packages/server/src/maintenance.ts\n */\nexport const WRITE_TICK_MIN_ENTRIES_TO_COMPACT: number = 50;\n\n/**\n * Node-tier write-tick maintenance caps — a MODERATE multiple of the CF-free `WRITE_TICK_*`\n * defaults, threaded into the per-request observability context by `baerlyNode` /\n * `createFetchHandler` (§8.4). Node v1 runs maintenance INLINE on the commit path (no\n * `waitUntil`), so the cap is NOT the CF subrequest wall — it's the worst-case single-write\n * added latency. A maintenance tick only fires on a ratio/boundary trip (rare), and when it\n * does it costs ~`maxFoldEntriesPerPass` + (6 + `gcMaxMarks` + `gcMaxSweeps`) storage\n * round-trips against a co-located S3/R2 — sub-second on the occasional boundary write at a\n * 10× multiple. These are deliberately BOUNDED (10× CF-free), NOT unbounded: the deleted\n * scheduled full-tail sweep folded the entire live tail in one shot, which a 100× multiple here\n * would reintroduce as multi-second commit stalls. Raise the snapshot ceiling separately via\n * `BAERLY_MAINTENANCE_MAX_FOLD_BYTES`; these caps slice the per-pass work, not the ceiling.\n *\n * @see packages/adapter-node/src/server.ts\n * @see packages/server/src/maintenance.ts\n * @see docs/about/graduation.md\n */\nexport const NODE_MAINTENANCE_FOLD_ENTRIES_PER_PASS: number = 200;\n\n/** Node-tier GC marks per pass (M in 6+M+S). 10× CF-free. @see {@link NODE_MAINTENANCE_FOLD_ENTRIES_PER_PASS} */\nexport const NODE_MAINTENANCE_GC_MAX_MARKS: number = 200;\n\n/** Node-tier GC sweeps per pass (S in 6+M+S). 10× CF-free. @see {@link NODE_MAINTENANCE_FOLD_ENTRIES_PER_PASS} */\nexport const NODE_MAINTENANCE_GC_MAX_SWEEPS: number = 100;\n\n/**\n * Node-tier GC cadence (boundary-crossing). Shorter than the CF-free `WRITE_TICK_GC_INTERVAL`\n * (4) so the per-write sweep budget keeps up: `gcMaxSweeps / gcInterval = 100 / 2 = 50`\n * comfortably clears the garbage-per-write rate `p` (the `maxSweeps/interval ≥ p` invariant,\n * §7.1) with a wide margin.\n *\n * @see {@link NODE_MAINTENANCE_FOLD_ENTRIES_PER_PASS}\n */\nexport const NODE_MAINTENANCE_GC_INTERVAL: number = 2;\n\n/**\n * SNAPSHOT-rebuild ceiling `C` (the unsliceable axis — Decision 3a), memory. Default sized\n * ~5.5 ms under CF-free ~10 ms. Raise via BAERLY_MAINTENANCE_MAX_FOLD_BYTES on capable\n * hosts. Auto-maintained snapshot ceiling S_max = C. NOT snapshot+tail (tail is sliced).\n *\n * @see docs/about/graduation.md\n * @see packages/server/src/maintenance.ts\n */\n// Stryker disable next-line ArithmeticOperator: internal tuning value, not an off-process contract — asserting the literal would be a tautological change-detector. See docs/contributing/mutation-testing.md constants policy.\nexport const MAINTENANCE_MAX_FOLD_BYTES_DEFAULT: number = 512 * 1024;\n\n/**\n * The largest snapshot a Cloudflare **free-tier** isolate can safely\n * rebuild in ONE fold under the ~10 ms CPU budget. This is the WARN\n * THRESHOLD, not a runtime cap: an operator who raises\n * `BAERLY_MAINTENANCE_MAX_FOLD_BYTES` ABOVE this value on a free Worker\n * risks a snapshot rebuild that exceeds the ~10 ms CPU limit and gets\n * CPU-killed MID-REBUILD — the CAS never lands, so the fold silently\n * never advances `log_seq_start` and the tail grows unbounded.\n *\n * Sized at 2× {@link MAINTENANCE_MAX_FOLD_BYTES_DEFAULT}. The default\n * (512 KiB) rebuilds in ~5.5 ms under the CF-free ~10 ms budget\n * (constants.ts default JSDoc); linear-extrapolating, ~1 MiB is the\n * point where one-shot rebuild fills the budget with little margin, so\n * anything strictly larger is no longer free-tier-safe. On CF **paid**\n * (raised CPU limits), Node, or once §11 chunked snapshots land, a\n * larger ceiling is fine — hence this is a one-time `console.warn` at\n * handler init, NOT a hard rejection.\n *\n * @see packages/adapter-cloudflare/src/worker.ts\n * @see packages/server/src/maintenance.ts\n * @see docs/about/graduation.md\n */\n// Stryker disable next-line ArithmeticOperator: internal tuning value, not an off-process contract — asserting the literal would be a tautological change-detector. See docs/contributing/mutation-testing.md constants policy.\nexport const CF_FREE_MAX_SAFE_FOLD_BYTES: number = 1024 * 1024;\n\n/**\n * SNAPSHOT-rebuild ceiling `E`, per-entry CPU axis: gates `snapshot_rows` (per-entry\n * parse/merge/serialize is ~half of fold CPU and scales with ROW COUNT not bytes, VLDB 2021\n * Sarkar — a tiny-doc snapshot can blow CPU under C). PROVISIONAL — bench\n * landed; paid recalibration deferred.\n *\n * @see docs/about/graduation.md\n * @see packages/server/src/maintenance.ts\n */\nexport const MAINTENANCE_MAX_FOLD_ROWS: number = 2048;\n\n// Declared here (not the nominal server `MaintenanceProfile`) to avoid a server→protocol cycle; keep field-identical to it.\ntype MaintenanceProfileShape = Readonly<{\n gcInterval: number;\n gcMaxMarks: number;\n gcMaxSweeps: number;\n maxFoldEntriesPerPass: number;\n maxFoldBytes: number;\n maxFoldRows: number;\n}>;\n\n/** CF-free profile; the absent-context default. */\nexport const MAINTENANCE_PROFILE_CF_FREE: MaintenanceProfileShape = {\n gcInterval: WRITE_TICK_GC_INTERVAL,\n gcMaxMarks: WRITE_TICK_GC_MAX_MARKS,\n gcMaxSweeps: WRITE_TICK_GC_MAX_SWEEPS,\n maxFoldEntriesPerPass: WRITE_TICK_FOLD_ENTRIES_PER_PASS,\n maxFoldBytes: MAINTENANCE_MAX_FOLD_BYTES_DEFAULT,\n maxFoldRows: MAINTENANCE_MAX_FOLD_ROWS,\n};\n\n/** Node profile; 10× CF-free caps. */\nexport const MAINTENANCE_PROFILE_NODE: MaintenanceProfileShape = {\n gcInterval: NODE_MAINTENANCE_GC_INTERVAL,\n gcMaxMarks: NODE_MAINTENANCE_GC_MAX_MARKS,\n gcMaxSweeps: NODE_MAINTENANCE_GC_MAX_SWEEPS,\n maxFoldEntriesPerPass: NODE_MAINTENANCE_FOLD_ENTRIES_PER_PASS,\n maxFoldBytes: MAINTENANCE_MAX_FOLD_BYTES_DEFAULT,\n maxFoldRows: MAINTENANCE_MAX_FOLD_ROWS,\n};\n\n/**\n * Rate-limit the defer-warn off SHARED current.json.last_warned_seq (not per-isolate\n * memory — CF recycles isolates). ~once per this many writes.\n *\n * @see packages/protocol/src/coordination/current-json.ts\n * @see packages/server/src/maintenance.ts\n */\nexport const MAINTENANCE_WARN_INTERVAL_WRITES: number = 1000;\n\n/**\n * Rate-limit for the maintenance tick's `tail_hint` advance on the\n * DEFER path (HR-2). When the fold defers (snapshot over the CF-CPU-kill\n * ceiling) the compactor never stamps `tail_hint` via its Step-7 fold\n * CAS, so the gap `(true_tail − tail_hint)` would grow without bound and\n * every read would re-walk the whole live tail via `probeTailFrom`. The\n * runner therefore advances `tail_hint` toward the observed tail with a\n * best-effort `current.json` CAS — but only once per this many writes,\n * so it is NOT a per-commit `current.json` write (which is exactly what\n * single-write commit removed).\n *\n * Sized at 128: it bounds a deferring collection's worst-case\n * read-walk to ≤128 forward GETs (≈one extra read-page sweep — a\n * negligible per-read latency cost), keeps the gap two-to-three orders\n * of magnitude below {@link LOG_FORWARD_PROBE_CAP} (so the cap-throw is a\n * pure runaway guard, never reached in normal operation), and holds the\n * hint-advance CAS rate under ~1% of the commit rate (negligible\n * Class-A cost, amortized). Smaller would tighten the read-walk at a\n * higher CAS rate; larger would loosen it — 128 is the modest middle.\n *\n * @see packages/server/src/maintenance.ts\n */\nexport const MAINTENANCE_TAIL_HINT_REFRESH_WRITES: number = 128;\n\n/**\n * Placeholder for `CurrentJson.snapshot === null` in the\n * `_meta.manifest_pointer` cursor emitted on read responses. The\n * wire format is `\"<snapshot>@<tail_hint>\"`, and `null` snapshots\n * serialise as this literal so the cursor is never empty and stays\n * byte-stable when destructured by operators.\n *\n * @see packages/server/src/contract.ts (HttpOkMeta)\n */\nexport const MANIFEST_POINTER_EMPTY_SNAPSHOT: string = \"none\";\n\n/**\n * Keys that must never propagate through {@link merge}: assigning to\n * them on a plain object pollutes the prototype chain. The literal\n * `{ __proto__: ... }` syntax is a prototype-setter (not an own key)\n * and bypasses `Object.keys`, but `JSON.parse('{\"__proto__\":...}')`\n * produces a real own property — which is exactly how a malicious\n * HTTP PATCH body would arrive on the wire.\n *\n * Lifted to a constant so every iteration path that touches a\n * caller-supplied object can re-use the same defence without\n * duplicating the keyword list.\n *\n * @see packages/protocol/src/json.ts (merge)\n * @see docs/spec/json-merge-patch.md\n */\nexport const FORBIDDEN_MERGE_KEYS: ReadonlySet<string> = new Set([\n \"__proto__\",\n \"constructor\",\n \"prototype\",\n]);\n\n/**\n * Architecturally-enforced ceiling: storage ops per logical write.\n *\n * Two Class A ops: PUT content + the committing `log/<seq>` create\n * (`If-None-Match: \"*\"`). There is no `current.json` CAS on the commit\n * path — the winning log create IS the commit. The cost-model page\n * derives the free-tier write budget from this multiplier; the phase-5\n * end-to-end test asserts it at CI time. Changing this constant is a\n * cost-model-breaking change.\n *\n * @see docs/about/cost-model.md §\"Cost ceiling\"\n * @see tests/integration/phase5-end-to-end.test.ts\n */\nexport const STORAGE_OPS_PER_LOGICAL_WRITE: number = 2;\n\n/**\n * Canonical auth posture identifiers consumed by `BaerlyAppConfig.auth`,\n * the adapter resolution path (`packages/adapter-cloudflare/src/worker.ts`,\n * `packages/adapter-node/src/baerly-node.ts`), and `baerly doctor`.\n *\n * - `\"none\"` — no header check; pin every request to `config.tenant`.\n * For local dev, intranet, CLI tools — contexts where the network\n * seam itself is the trust boundary.\n * - `\"shared-secret\"` — bearer-token check; reads `SHARED_SECRET` from\n * the runtime env and pins every request to `config.tenant`.\n *\n * Custom verifiers (`cloudflareAccess`, `bearerJwt`, SigV4, …) bypass\n * this enum — pass a `Verifier` to the adapter factory's `verifier:`\n * option instead.\n */\nexport const AUTH_CONFIG_VALUES = [\"none\", \"shared-secret\"] as const;\n\n/**\n * Locked error wording for the \"no auth configured\" failure mode. The\n * adapter throws this when neither `config.auth` nor `verifier:`\n * resolves a real `Verifier`. Pinned via a regression test so future\n * refactors do not drift the operator-facing wording.\n *\n * Consumed by:\n * - `packages/adapter-cloudflare/src/worker.ts` (first-fetch throw)\n * - `packages/adapter-node/src/server.ts` (first-fetch throw)\n * - `packages/cli/src/doctor/cloudflare.ts` (FAIL finding mirrors it)\n */\nexport const NO_AUTH_CONFIGURED_MESSAGE: string =\n 'baerly: no auth configured. Set `auth` in baerly.config.ts (\"none\", \"shared-secret\") or pass `verifier` on the adapter factory.';\n\n/**\n * Locked error wording for `auth: \"shared-secret\"` + missing env var.\n * Same pinning rationale as {@link NO_AUTH_CONFIGURED_MESSAGE}.\n */\nexport const SHARED_SECRET_MISSING_MESSAGE: string =\n 'baerly: auth=\"shared-secret\" but SHARED_SECRET env is empty/unset. Cloudflare: `wrangler secret put SHARED_SECRET`, or add to .dev.vars for local dev. Node: set in process env.';\n","import { BaerlyError } from \"../errors.ts\";\nimport type {\n Storage,\n StorageGetOptions,\n StorageGetResult,\n StorageListEntry,\n StoragePutOptions,\n StoragePutResult,\n} from \"./types.ts\";\n\ninterface StoredObject {\n body: Uint8Array;\n etag: string;\n contentType?: string;\n}\n\nconst utf8Encoder = new TextEncoder();\n\n/**\n * Compare two keys by their UTF-8 byte sequences — the order S3 and\n * R2 use for `list`. JavaScript's default string sort compares UTF-16\n * code units, which diverges from UTF-8 byte order for supplementary-\n * plane characters (e.g. emoji sort before high-BMP characters under\n * UTF-16 but after them in UTF-8). Using this keeps the in-memory\n * reference backend faithful to the real adapters. (All kernel keys\n * are ASCII base-32, where the two orders coincide — this only\n * matters for adversarial / non-ASCII keys.)\n */\nconst compareKeysUtf8 = (a: string, b: string): number => {\n const ba = utf8Encoder.encode(a);\n const bb = utf8Encoder.encode(b);\n const n = Math.min(ba.length, bb.length);\n for (let i = 0; i < n; i++) {\n if (ba[i] !== bb[i]) {\n return ba[i]! - bb[i]!;\n }\n }\n return ba.length - bb.length;\n};\n\n/**\n * In-memory `Storage`. The randomized property test runs against\n * this; it must be deterministic — no clocks beyond the caller's,\n * no randomness, no I/O.\n *\n * ETags are a monotonically increasing hex counter formatted in the\n * `\"<hex>\"` shape S3 returns (the surrounding double-quotes are part\n * of the ETag header value). Keys are stored verbatim.\n *\n * **Test-confidence caveat:** every method resolves on the microtask\n * queue with no real concurrency, so `put` reads `existing` and writes\n * back with no interleaving. MemoryStorage therefore CANNOT exercise the\n * compare-and-swap race the writer-fence model depends on — two writers\n * contending on one `current.json` always serialize here, so a green run\n * is necessary but not sufficient. That race is covered only by the\n * randomized integration tests against real S3 / Minio\n * (`tests/integration/randomized.test.ts`, `node-minio` variant).\n * Relatedly, `serverDate` returns the local clock, not an independent\n * server clock (see the `put` return below).\n */\nexport class MemoryStorage implements Storage {\n readonly #objects = new Map<string, StoredObject>();\n #etagCounter = 0;\n\n #nextEtag(): string {\n this.#etagCounter += 1;\n return `\"${this.#etagCounter.toString(16)}\"`;\n }\n\n async get(key: string, opts?: StorageGetOptions): Promise<StorageGetResult | null> {\n opts?.signal?.throwIfAborted();\n const stored = this.#objects.get(key);\n if (stored === undefined) {\n return null;\n }\n if (opts?.ifNoneMatch !== undefined && opts.ifNoneMatch === stored.etag) {\n // 304 Not Modified — caller's cached copy is current.\n return null;\n }\n return { body: stored.body, etag: stored.etag };\n }\n\n async put(key: string, body: Uint8Array, opts?: StoragePutOptions): Promise<StoragePutResult> {\n opts?.signal?.throwIfAborted();\n const existing = this.#objects.get(key);\n\n if (opts?.ifNoneMatch === \"*\" && existing !== undefined) {\n throw new BaerlyError(\n \"Conflict\",\n `PUT ${key}: precondition failed (ifNoneMatch=\"*\" but key exists)`,\n );\n }\n if (opts?.ifMatch !== undefined) {\n if (existing === undefined) {\n throw new BaerlyError(\n \"Conflict\",\n `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but key does not exist)`,\n );\n }\n if (existing.etag !== opts.ifMatch) {\n throw new BaerlyError(\n \"Conflict\",\n `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but current ETag is ${existing.etag})`,\n );\n }\n }\n\n const etag = this.#nextEtag();\n this.#objects.set(key, {\n body,\n etag,\n // Stryker disable next-line ObjectLiteral,ConditionalExpression: contentType is stored in the internal StoredObject but never returned by get() — the Storage interface has no contentType on StorageGetResult, so any mutation of this spread is observable-equivalent\n ...(opts?.contentType !== undefined && { contentType: opts.contentType }),\n });\n // `serverDate` is intentionally returned — the kernel's adaptive\n // clock-skew loop consumes the write-time server clock. `list()`\n // deliberately omits `lastModified`: the in-memory impl has no\n // independent server clock, and its only consumer (GC's `due_at`\n // anchor) falls back to `now()` when it is absent, so omitting it\n // changes nothing.\n return { etag, serverDate: new Date() };\n }\n\n async delete(key: string, opts?: { signal?: AbortSignal }): Promise<void> {\n opts?.signal?.throwIfAborted();\n this.#objects.delete(key);\n }\n\n async *list(\n prefix: string,\n opts?: { startAfter?: string; maxKeys?: number; signal?: AbortSignal },\n ): AsyncIterable<StorageListEntry> {\n opts?.signal?.throwIfAborted();\n const startAfter = opts?.startAfter ?? \"\";\n const maxKeys = opts?.maxKeys ?? Infinity;\n const sorted = [...this.#objects.keys()]\n .filter((k) => k.startsWith(prefix) && compareKeysUtf8(k, startAfter) > 0)\n .toSorted(compareKeysUtf8);\n let yielded = 0;\n for (const key of sorted) {\n if (yielded >= maxKeys) {\n return;\n }\n opts?.signal?.throwIfAborted();\n const stored = this.#objects.get(key);\n // Stryker disable next-line ConditionalExpression,BlockStatement: unreachable guard — keys come from Map.keys() so the corresponding value is always present; this branch exists only to satisfy noUncheckedIndexedAccess\n if (stored === undefined) {\n continue;\n }\n yield { key, etag: stored.etag };\n yielded += 1;\n }\n }\n\n /**\n * Test-only: drop all objects.\n * @internal\n */\n _clear(): void {\n this.#objects.clear();\n this.#etagCounter = 0;\n }\n}\n\n// Process-singleton MemoryStorage map keyed by bucket. Tests that need\n// multiple `Db` / `Writer` instances to see each other's writes\n// against an in-memory backend reach for this via\n// {@link getOrCreateMemoryStorageForBucket}; {@link resetMemoryStorage}\n// drops every bucket between test cases.\nconst sharedPerBucket = new Map<string, MemoryStorage>();\n\n/**\n * Test isolation: drop every bucket's contents from the shared\n * memory storage used by {@link getOrCreateMemoryStorageForBucket}.\n * Direct `MemoryStorage` instances built via `new MemoryStorage()`\n * are unaffected — those are isolated by construction.\n */\nexport const resetMemoryStorage = (): void => {\n sharedPerBucket.clear();\n};\n\n/**\n * Get the process-singleton {@link MemoryStorage} for the named\n * bucket, creating one on first access. Use this when constructing\n * a `Storage` directly so multiple consumers in the same process\n * see each other's writes for the same bucket name.\n */\nexport const getOrCreateMemoryStorageForBucket = (bucket: string): MemoryStorage => {\n let s = sharedPerBucket.get(bucket);\n if (s === undefined) {\n s = new MemoryStorage();\n sharedPerBucket.set(bucket, s);\n }\n return s;\n};\n","import { COUNT_BIT_WIDTH } from \"./constants.ts\";\n\ndeclare const brand: unique symbol;\ntype Brand<B> = { [brand]: B };\n\n/**\n * Nominal-typing helper. `Branded<string, \"UUID\">` is a `string` at\n * runtime but the type system rejects mixing it with a plain `string` or\n * a string branded as something else. Used to prevent confusion bugs at\n * protocol boundaries (UUIDs vs. content versions are both strings, but\n * using the wrong one corrupts the per-collection log).\n *\n * Construct branded values via the helpers in this file (e.g. {@link uuid})\n * or with a tagged cast at a single, deliberate boundary — never `as string`\n * to widen one back. See `docs/contributing/conventions/src.md`.\n */\nexport type Branded<T, B> = T & Brand<B>;\n\n/**\n * A v4 UUID minted by this client. Used as session IDs and content\n * identifiers in non-versioned mode.\n */\nexport type UUID = Branded<string, \"UUID\">;\n\n/**\n * SHA-256 content digest, lowercase hex truncated to\n * `VERSION_HEX_LENGTH` (32 chars). Minted by\n * `versionFromContent` in `useVersioning=false` mode and used as\n * the `<key>@<version>` suffix in content keys.\n *\n * The synthetic `local-${op}` placeholder used for in-flight\n * optimistic updates also wears this brand — it never round-trips\n * to S3, only flows through local optimistic state.\n */\nexport type ContentVersionId = Branded<string, \"ContentVersionId\">;\n\n/**\n * Mint a fresh {@link UUID}. The cast lives here so callers don't sprinkle\n * `<UUID>crypto.randomUUID()` throughout the codebase.\n */\nexport const uuid = (): UUID => crypto.randomUUID() as UUID;\n\n/**\n * Mint a UUIDv7 — 48-bit Unix-millis prefix + 74 bits of randomness,\n * formatted as a standard 8-4-4-4-12 UUID string per RFC 9562 §5.7.\n * Lex-sortable by mint time, so it pairs well with object-storage\n * list semantics. Returns a branded {@link UUID}.\n *\n * Uses `crypto.getRandomValues` which is universally available\n * (Node 19+, Workerd, Bun, browsers).\n *\n * @example\n * ```ts\n * const id = uuidv7();\n * // e.g. \"01956cad-4cc8-7abc-9def-0123456789ab\"\n * ```\n */\nexport const uuidv7 = (): UUID => {\n const millis = Date.now();\n const rand = new Uint8Array(10);\n crypto.getRandomValues(rand);\n // Version nibble: top 4 bits of rand[0] = 0b0111 (v7). The byte\n // sits at the start of the \"version-and-rand-a\" group below.\n rand[0] = (rand[0]! & 0x0f) | 0x70;\n // Variant bits: top 2 bits of rand[2] = 0b10 (RFC 4122 variant).\n // This byte starts the \"variant-and-rand-b\" group below.\n rand[2] = (rand[2]! & 0x3f) | 0x80;\n const millisHex = millis.toString(16).padStart(12, \"0\");\n const b = Array.from(rand, (n) => n.toString(16).padStart(2, \"0\")).join(\"\");\n return `${millisHex.slice(0, 8)}-${millisHex.slice(8, 12)}-${b.slice(0, 4)}-${b.slice(4, 8)}-${b.slice(8, 20)}` as UUID;\n};\n\n/**\n * Mint the trailing seq segment of an LSN (`<base32-time>_<sess>_<seq>`).\n * Uses `COUNT_BIT_WIDTH` (see `packages/protocol/src/constants.ts`) to\n * produce an 11-char descending base-32 string with a domain of\n * 0 .. `Number.MAX_SAFE_INTEGER` (2^53 − 1).\n *\n * Used together with {@link timestamp} (the descending base-32\n * encoding of millis-since-epoch). See {@link uint2strDesc} for the\n * lex-reversal property both rely on.\n */\nexport const countKey = (number: number): string => uint2strDesc(number, COUNT_BIT_WIDTH);\n\nexport const uint2str = (num: number, bits: number) => {\n const maxBase32Length = Math.ceil(bits / 5); // Change from 4 to 5 because log2(32) is roughly 5.\n const base32Representation = num.toString(32);\n return base32Representation.padStart(maxBase32Length, \"0\");\n};\n\nexport const str2uint = (str: string) => {\n return parseInt(str, 32); // Parse the string as base 32.\n};\n\n/**\n * Lex-reversed base-32 encoder for an unsigned integer in `[0, 2^bits)`.\n * Pads to `Math.ceil(bits/5)` chars so all values in the domain compare\n * lex against each other.\n *\n * **Order-reversal property:** for any pair of integers `a < b` (with\n * `a, b ∈ [0, 2^bits)`), `uint2strDesc(a, bits) > uint2strDesc(b, bits)`\n * lexicographically. Composed into an LSN of shape\n * `<base32-time>_<session>_<seq>` (where both `<base32-time>` and\n * `<seq>` use this encoder), a forward `Storage.list(prefix)`\n * returns log entries in reverse-causal order — newer entries first.\n *\n * This is the structural property the read path leans on:\n * `ListObjectsV2` is forward-only on S3, but the descending encoding\n * makes \"fetch the K newest entries\" a single bounded LIST with\n * `maxKeys=K` instead of a full-population LIST + in-memory reverse.\n *\n * Behaviourally verified across randomized populations in\n * `packages/protocol/src/lsn-reverse-list.test.ts`. Quantified\n * bytes-listed reduction is in\n * `docs/spec/attachments/lsn-reverse-walk-baseline.json`\n * (run `pnpm bench:lsn-reverse-walk` to reproduce). Spec rationale:\n * `docs/spec/sync-protocol.md` §\"LSNs, wall clocks, and downstream\n * consumers\".\n */\nexport const uint2strDesc = (num: number, bits: number): string => {\n const maxValue = Math.pow(2, bits) - 1;\n return uint2str(maxValue - num, bits);\n};\n\nexport const str2uintDesc = (str: string, bits: number): number => {\n const maxValue = Math.pow(2, bits) - 1;\n const num = parseInt(str, 32); // Convert base32 string to number\n return maxValue - num;\n};\n","import { TIMESTAMP_BIT_WIDTH } from \"./constants.ts\";\nimport { BaerlyError } from \"./errors.ts\";\nimport { uint2strDesc } from \"./types.ts\";\n\n/**\n * Encode an epoch-millis instant as a lexicographically-DEScending\n * base-32 key (newer sorts first). The load-bearing LSN ordering\n * primitive — see {@link uint2strDesc}.\n *\n * `epoch` is REQUIRED and validated. There is no default: an argless\n * call used to encode `0`, which descending-sorts as the most-ancient\n * instant and would silently invert ordering. A non-finite, negative,\n * or out-of-range `epoch` (e.g. a broken `Date.now()` returning `NaN`)\n * would corrupt the key silently rather than fail loud, so it throws\n * `Internal` instead — this is an invariant violation, not caller config\n * (the only legitimate argument is `Date.now()`).\n */\nexport const timestamp = (epoch: number): string => {\n if (!Number.isInteger(epoch) || epoch < 0 || epoch >= 2 ** TIMESTAMP_BIT_WIDTH) {\n throw new BaerlyError(\n \"Internal\",\n `timestamp(): epoch must be a non-negative integer < 2^${TIMESTAMP_BIT_WIDTH} (got ${epoch})`,\n );\n }\n return uint2strDesc(epoch, TIMESTAMP_BIT_WIDTH);\n};\n\n/**\n * Delay for `ms` milliseconds, with optional cancellation. If\n * `signal` aborts before the delay elapses, the returned promise\n * rejects with `signal.reason`. Used by `S3HttpStorage`'s retry\n * loop so shutdown can interrupt an in-flight backoff instead of\n * waiting for it to complete.\n */\nexport const delay = (ms: number, signal?: AbortSignal): Promise<void> =>\n new Promise<void>((resolve, reject) => {\n if (signal?.aborted) {\n reject(signal.reason);\n return;\n }\n const timer = setTimeout(resolve, ms);\n signal?.addEventListener(\n \"abort\",\n () => {\n clearTimeout(timer);\n reject(signal.reason);\n },\n // Stryker disable next-line BooleanLiteral,ObjectLiteral: `{ once: true }` removes the\n // listener after the first fire. AbortController fires `abort` only once per signal, so\n // `once: false` / `{}` produce identical observable behaviour — the listener stays attached\n // to an already-fired signal, but calling reject on a settled Promise is a no-op. The\n // BooleanLiteral (once:false) and ObjectLiteral ({}) mutations are genuine equivalences.\n { once: true },\n );\n });\n","import { createHash } from \"node:crypto\";\nimport { link, mkdir, readdir, readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join, posix, relative, resolve, sep } from \"node:path\";\nimport {\n BaerlyError,\n type Storage,\n type StorageGetOptions,\n type StorageGetResult,\n type StorageListEntry,\n type StoragePutOptions,\n type StoragePutResult,\n} from \"@baerly/protocol\";\n\n/**\n * Reserved prefix for the in-directory create-if-absent temp (see `put`).\n * `walk`/`list` skip it; it is internal/transient and never a real key.\n */\nconst TEMP_PREFIX = \".baerly-tmp-\";\n\nexport interface LocalFsStorageOptions {\n /** Root directory; treated as \"the bucket\". */\n root: string;\n}\n\nconst utf8Encoder = new TextEncoder();\n\n/**\n * Compare two keys by their UTF-8 byte sequences — the order S3 and R2\n * use for `list`. JS's default string sort compares UTF-16 code units,\n * which diverges from UTF-8 byte order for supplementary-plane\n * characters; using this keeps `list` ordering faithful to the real\n * adapters. (All kernel keys are ASCII base-32, where both orders\n * coincide.)\n */\nconst compareKeysUtf8 = (a: string, b: string): number => {\n const ba = utf8Encoder.encode(a);\n const bb = utf8Encoder.encode(b);\n const n = Math.min(ba.length, bb.length);\n for (let i = 0; i < n; i++) {\n if (ba[i] !== bb[i]) {\n return ba[i]! - bb[i]!;\n }\n }\n return ba.length - bb.length;\n};\n\n/**\n * `Storage` backed by a directory tree. Keys may contain `/` and map\n * to nested directories on disk so `ls`/`cat` work as expected.\n *\n * ETags are content-addressed: `\"<sha-256-hex>\"` (the surrounding\n * double-quotes match S3's wire format for non-multipart objects).\n * Identical bodies share an ETag across runs — the property that\n * makes this adapter useful for fixture-based tests.\n *\n * Writes are atomic via `writeFile(temp) + rename(final)`; readers\n * never see a partially-written file.\n *\n * `ifNoneMatch:\"*\"` uses a same-dir temp + `link(2)` (atomic exclusive\n * create; `EEXIST` ⇒ key exists) so concurrent creates have exactly one\n * winner. Same-dir avoids `EXDEV`; temp+`link` over `open(…,\"wx\")` keeps\n * a partially-written new key invisible to a concurrent reader. `ifMatch`\n * keeps the `rename` path (in-process TOCTOU only; cross-process\n * contention uses the S3 / Minio `If-Match` path).\n *\n * Node-only — imports `node:fs`, `node:path`, `node:crypto`. Lives in\n * `@baerly/dev` because the protocol kernel is pure-modules / no I/O\n * and must remain Worker-bundleable.\n */\nexport class LocalFsStorage implements Storage {\n readonly #root: string;\n\n constructor(opts: LocalFsStorageOptions) {\n this.#root = resolve(opts.root);\n }\n\n async get(key: string, opts?: StorageGetOptions): Promise<StorageGetResult | null> {\n opts?.signal?.throwIfAborted();\n const path = this.#pathFor(key);\n let body: Buffer;\n try {\n body = await readFile(path);\n } catch (error) {\n if (isErrnoException(error) && error.code === \"ENOENT\") {\n return null;\n }\n throw new BaerlyError(\n \"InvalidResponse\",\n `LocalFsStorage.get(${key}): ${(error as Error).message}`,\n error,\n );\n }\n const etag = etagOf(body);\n if (opts?.ifNoneMatch !== undefined && opts.ifNoneMatch === etag) {\n // 304 Not Modified — caller's cached copy is current.\n return null;\n }\n return { body: toUint8Array(body), etag };\n }\n\n async put(key: string, body: Uint8Array, opts?: StoragePutOptions): Promise<StoragePutResult> {\n opts?.signal?.throwIfAborted();\n const path = this.#pathFor(key);\n const newEtag = etagOf(body);\n\n await mkdir(dirname(path), { recursive: true });\n\n if (opts?.ifNoneMatch === \"*\") {\n // Atomic exclusive create via link(2) — see class JSDoc.\n const tmp = join(\n dirname(path),\n `${TEMP_PREFIX}${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`,\n );\n try {\n await writeFile(tmp, body);\n await link(tmp, path);\n } catch (error) {\n if (isErrnoException(error) && error.code === \"EEXIST\") {\n throw new BaerlyError(\n \"Conflict\",\n `PUT ${key}: precondition failed (ifNoneMatch=\"*\" but key exists)`,\n );\n }\n throw new BaerlyError(\n \"InvalidResponse\",\n `LocalFsStorage.put(${key}): ${(error as Error).message}`,\n error,\n );\n } finally {\n // Best-effort cleanup — a failed write may leave a partial temp,\n // and a cleanup failure must not mask a Conflict thrown above.\n await rm(tmp, { force: true }).catch(() => {});\n }\n return { etag: newEtag, serverDate: new Date() };\n }\n\n if (opts?.ifMatch !== undefined) {\n // TOCTOU within a process — fine. Cross-process callers should\n // not rely on these guards (see class JSDoc).\n const existing = await readExisting(path);\n if (existing === null) {\n throw new BaerlyError(\n \"Conflict\",\n `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but key does not exist)`,\n );\n }\n const currentEtag = etagOf(existing);\n if (currentEtag !== opts.ifMatch) {\n throw new BaerlyError(\n \"Conflict\",\n `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but current ETag is ${currentEtag})`,\n );\n }\n }\n\n // Unconditional PUT (or ifMatch already verified above).\n // Write to a unique temp path then rename for atomicity. Temp lives\n // in `os.tmpdir()` so a half-written file never appears under the\n // bucket root where `list` might see it. PID + timestamp + random\n // tail makes the name unique across concurrent writers in the same\n // process.\n const tmp = join(\n tmpdir(),\n `baerly-localfs-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`,\n );\n await writeFile(tmp, body);\n try {\n await rename(tmp, path);\n } catch (error) {\n // Best-effort cleanup of the temp file; swallow any error there\n // so the original failure surfaces unchanged.\n await rm(tmp, { force: true }).catch(() => {});\n throw new BaerlyError(\n \"InvalidResponse\",\n `LocalFsStorage.put(${key}): ${(error as Error).message}`,\n error,\n );\n }\n return { etag: newEtag, serverDate: new Date() };\n }\n\n async delete(key: string, opts?: { signal?: AbortSignal }): Promise<void> {\n opts?.signal?.throwIfAborted();\n const path = this.#pathFor(key);\n try {\n await rm(path);\n } catch (error) {\n if (isErrnoException(error) && error.code === \"ENOENT\") {\n return;\n } // idempotent\n throw new BaerlyError(\n \"InvalidResponse\",\n `LocalFsStorage.delete(${key}): ${(error as Error).message}`,\n error,\n );\n }\n }\n\n async *list(\n prefix: string,\n opts?: {\n startAfter?: string;\n maxKeys?: number;\n signal?: AbortSignal;\n },\n ): AsyncIterable<StorageListEntry> {\n opts?.signal?.throwIfAborted();\n const startAfter = opts?.startAfter ?? \"\";\n const maxKeys = opts?.maxKeys ?? Infinity;\n const keys: string[] = [];\n await walk(this.#root, keys);\n keys.sort(compareKeysUtf8);\n let yielded = 0;\n for (const key of keys) {\n if (!key.startsWith(prefix)) {\n continue;\n }\n if (compareKeysUtf8(key, startAfter) <= 0) {\n continue;\n }\n if (yielded >= maxKeys) {\n return;\n }\n opts?.signal?.throwIfAborted();\n const buf = await readFile(this.#pathFor(key));\n yield { key, etag: etagOf(buf) };\n yielded += 1;\n }\n }\n\n /**\n * Map an S3-style key to a filesystem path under `#root`, rejecting\n * anything that could escape the root (path traversal, absolute\n * paths, empty segments, backslashes). All rejections throw\n * `BaerlyError(\"InvalidConfig\", …)`.\n */\n #pathFor(key: string): string {\n if (key.length === 0) {\n throw new BaerlyError(\"InvalidConfig\", \"LocalFsStorage: empty key\");\n }\n if (key.startsWith(\"/\")) {\n throw new BaerlyError(\"InvalidConfig\", `LocalFsStorage: leading \"/\" in key: ${key}`);\n }\n if (key.includes(\"\\\\\")) {\n throw new BaerlyError(\"InvalidConfig\", `LocalFsStorage: backslash in key: ${key}`);\n }\n const segments = key.split(\"/\");\n if (segments.some((s) => s === \"\" || s === \".\" || s === \"..\")) {\n throw new BaerlyError(\"InvalidConfig\", `LocalFsStorage: illegal segment in key: ${key}`);\n }\n const path = join(this.#root, ...segments);\n if (path !== this.#root && !path.startsWith(this.#root + sep)) {\n throw new BaerlyError(\"InvalidConfig\", `LocalFsStorage: resolved path escapes root: ${key}`);\n }\n return path;\n }\n}\n\nconst etagOf = (body: Uint8Array): string => {\n const h = createHash(\"sha256\").update(body).digest(\"hex\");\n return `\"${h}\"`;\n};\n\nconst toUint8Array = (buf: Buffer): Uint8Array =>\n new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);\n\nconst isErrnoException = (e: unknown): e is NodeJS.ErrnoException =>\n typeof e === \"object\" && e !== null && \"code\" in e;\n\nconst readExisting = async (path: string): Promise<Buffer | null> => {\n try {\n return await readFile(path);\n } catch (error) {\n if (isErrnoException(error) && error.code === \"ENOENT\") {\n return null;\n }\n throw error;\n }\n};\n\n/**\n * Recursive directory walk. Yields filesystem-relative paths in\n * forward-slash form so callers can use them as S3-style keys\n * regardless of the host's path separator.\n */\nconst walk = async (root: string, out: string[]): Promise<void> => {\n const stack: string[] = [root];\n while (stack.length > 0) {\n const dir = stack.pop()!;\n let entries;\n try {\n entries = await readdir(dir, { withFileTypes: true });\n } catch (error) {\n if (isErrnoException(error) && error.code === \"ENOENT\") {\n continue;\n }\n throw error;\n }\n for (const entry of entries) {\n const full = join(dir, entry.name);\n if (entry.isDirectory()) {\n stack.push(full);\n } else if (entry.isFile() && !entry.name.startsWith(TEMP_PREFIX)) {\n // Skip the transient create-if-absent temps (see TEMP_PREFIX) so a\n // concurrent list during a create never surfaces a half-linked key.\n out.push(relative(root, full).split(sep).join(posix.sep));\n }\n }\n }\n};\n","'use strict';\n\nconst nameStartChar = ':A-Za-z_\\\\u00C0-\\\\u00D6\\\\u00D8-\\\\u00F6\\\\u00F8-\\\\u02FF\\\\u0370-\\\\u037D\\\\u037F-\\\\u1FFF\\\\u200C-\\\\u200D\\\\u2070-\\\\u218F\\\\u2C00-\\\\u2FEF\\\\u3001-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFFD';\nconst nameChar = nameStartChar + '\\\\-.\\\\d\\\\u00B7\\\\u0300-\\\\u036F\\\\u203F-\\\\u2040';\nexport const nameRegexp = '[' + nameStartChar + '][' + nameChar + ']*';\nconst regexName = new RegExp('^' + nameRegexp + '$');\n\nexport function getAllMatches(string, regex) {\n const matches = [];\n let match = regex.exec(string);\n while (match) {\n const allmatches = [];\n allmatches.startIndex = regex.lastIndex - match[0].length;\n const len = match.length;\n for (let index = 0; index < len; index++) {\n allmatches.push(match[index]);\n }\n matches.push(allmatches);\n match = regex.exec(string);\n }\n return matches;\n}\n\nexport const isName = function (string) {\n const match = regexName.exec(string);\n return !(match === null || typeof match === 'undefined');\n}\n\nexport function isExist(v) {\n return typeof v !== 'undefined';\n}\n\nexport function isEmptyObject(obj) {\n return Object.keys(obj).length === 0;\n}\n\nexport function getValue(v) {\n if (exports.isExist(v)) {\n return v;\n } else {\n return '';\n }\n}\n\n/**\n * Dangerous property names that could lead to prototype pollution or security issues\n */\nexport const DANGEROUS_PROPERTY_NAMES = [\n // '__proto__',\n // 'constructor',\n // 'prototype',\n 'hasOwnProperty',\n 'toString',\n 'valueOf',\n '__defineGetter__',\n '__defineSetter__',\n '__lookupGetter__',\n '__lookupSetter__'\n];\n\nexport const criticalProperties = [\"__proto__\", \"constructor\", \"prototype\"];","// ---------------------------------------------------------------------------\n// Complete HTML5 named entity reference\n// Organized by logical categories for easy maintenance and selective importing\n// ---------------------------------------------------------------------------\n\n/**\n * Basic Latin & Special Characters\n * @type {Record<string, string>}\n */\nexport const BASIC_LATIN = {\n amp: '&',\n AMP: '&',\n lt: '<',\n LT: '<',\n gt: '>',\n GT: '>',\n quot: '\"',\n QUOT: '\"',\n apos: \"'\",\n lsquo: '‘',\n rsquo: '’',\n ldquo: '“',\n rdquo: '”',\n lsquor: '‚',\n rsquor: '’',\n ldquor: '„',\n bdquo: '„',\n comma: ',',\n period: '.',\n colon: ':',\n semi: ';',\n excl: '!',\n quest: '?',\n num: '#',\n dollar: '$',\n percent: '%',\n amp: '&',\n ast: '*',\n commat: '@',\n lowbar: '_',\n verbar: '|',\n vert: '|',\n sol: '/',\n bsol: '\\\\',\n lbrace: '{',\n rbrace: '}',\n lbrack: '[',\n rbrack: ']',\n lpar: '(',\n rpar: ')',\n nbsp: '\\u00a0',\n iexcl: '¡',\n cent: '¢',\n pound: '£',\n curren: '¤',\n yen: '¥',\n brvbar: '¦',\n sect: '§',\n uml: '¨',\n copy: '©',\n COPY: '©',\n ordf: 'ª',\n laquo: '«',\n not: '¬',\n shy: '\\u00ad',\n reg: '®',\n REG: '®',\n macr: '¯',\n deg: '°',\n plusmn: '±',\n sup2: '²',\n sup3: '³',\n acute: '´',\n micro: 'µ',\n para: '¶',\n middot: '·',\n cedil: '¸',\n sup1: '¹',\n ordm: 'º',\n raquo: '»',\n frac14: '¼',\n frac12: '½',\n half: '½',\n frac34: '¾',\n iquest: '¿',\n times: '×',\n div: '÷',\n divide: '÷',\n};\n\n/**\n * Latin Extended & Accented Letters (A-Z)\n * @type {Record<string, string>}\n */\nexport const LATIN_ACCENTS = {\n Agrave: 'À',\n agrave: 'à',\n Aacute: 'Á',\n aacute: 'á',\n Acirc: 'Â',\n acirc: 'â',\n Atilde: 'Ã',\n atilde: 'ã',\n Auml: 'Ä',\n auml: 'ä',\n Aring: 'Å',\n aring: 'å',\n AElig: 'Æ',\n aelig: 'æ',\n Ccedil: 'Ç',\n ccedil: 'ç',\n Egrave: 'È',\n egrave: 'è',\n Eacute: 'É',\n eacute: 'é',\n Ecirc: 'Ê',\n ecirc: 'ê',\n Euml: 'Ë',\n euml: 'ë',\n Igrave: 'Ì',\n igrave: 'ì',\n Iacute: 'Í',\n iacute: 'í',\n Icirc: 'Î',\n icirc: 'î',\n Iuml: 'Ï',\n iuml: 'ï',\n ETH: 'Ð',\n eth: 'ð',\n Ntilde: 'Ñ',\n ntilde: 'ñ',\n Ograve: 'Ò',\n ograve: 'ò',\n Oacute: 'Ó',\n oacute: 'ó',\n Ocirc: 'Ô',\n ocirc: 'ô',\n Otilde: 'Õ',\n otilde: 'õ',\n Ouml: 'Ö',\n ouml: 'ö',\n Oslash: 'Ø',\n oslash: 'ø',\n Ugrave: 'Ù',\n ugrave: 'ù',\n Uacute: 'Ú',\n uacute: 'ú',\n Ucirc: 'Û',\n ucirc: 'û',\n Uuml: 'Ü',\n uuml: 'ü',\n Yacute: 'Ý',\n yacute: 'ý',\n THORN: 'Þ',\n thorn: 'þ',\n szlig: 'ß',\n yuml: 'ÿ',\n Yuml: 'Ÿ',\n};\n\n/**\n * Latin Extended (Letters with diacritics)\n * @type {Record<string, string>}\n */\nexport const LATIN_EXTENDED = {\n Amacr: 'Ā',\n amacr: 'ā',\n Abreve: 'Ă',\n abreve: 'ă',\n Aogon: 'Ą',\n aogon: 'ą',\n Cacute: 'Ć',\n cacute: 'ć',\n Ccirc: 'Ĉ',\n ccirc: 'ĉ',\n Cdot: 'Ċ',\n cdot: 'ċ',\n Ccaron: 'Č',\n ccaron: 'č',\n Dcaron: 'Ď',\n dcaron: 'ď',\n Dstrok: 'Đ',\n dstrok: 'đ',\n Emacr: 'Ē',\n emacr: 'ē',\n Ecaron: 'Ě',\n ecaron: 'ě',\n Edot: 'Ė',\n edot: 'ė',\n Eogon: 'Ę',\n eogon: 'ę',\n Gcirc: 'Ĝ',\n gcirc: 'ĝ',\n Gbreve: 'Ğ',\n gbreve: 'ğ',\n Gdot: 'Ġ',\n gdot: 'ġ',\n Gcedil: 'Ģ',\n Hcirc: 'Ĥ',\n hcirc: 'ĥ',\n Hstrok: 'Ħ',\n hstrok: 'ħ',\n Itilde: 'Ĩ',\n itilde: 'ĩ',\n Imacr: 'Ī',\n imacr: 'ī',\n Iogon: 'Į',\n iogon: 'į',\n Idot: 'İ',\n IJlig: 'IJ',\n ijlig: 'ij',\n Jcirc: 'Ĵ',\n jcirc: 'ĵ',\n Kcedil: 'Ķ',\n kcedil: 'ķ',\n kgreen: 'ĸ',\n Lacute: 'Ĺ',\n lacute: 'ĺ',\n Lcedil: 'Ļ',\n lcedil: 'ļ',\n Lcaron: 'Ľ',\n lcaron: 'ľ',\n Lmidot: 'Ŀ',\n lmidot: 'ŀ',\n Lstrok: 'Ł',\n lstrok: 'ł',\n Nacute: 'Ń',\n nacute: 'ń',\n Ncaron: 'Ň',\n ncaron: 'ň',\n Ncedil: 'Ņ',\n ncedil: 'ņ',\n ENG: 'Ŋ',\n eng: 'ŋ',\n Omacr: 'Ō',\n omacr: 'ō',\n Odblac: 'Ő',\n odblac: 'ő',\n OElig: 'Œ',\n oelig: 'œ',\n Racute: 'Ŕ',\n racute: 'ŕ',\n Rcaron: 'Ř',\n rcaron: 'ř',\n Rcedil: 'Ŗ',\n rcedil: 'ŗ',\n Sacute: 'Ś',\n sacute: 'ś',\n Scirc: 'Ŝ',\n scirc: 'ŝ',\n Scedil: 'Ş',\n scedil: 'ş',\n Scaron: 'Š',\n scaron: 'š',\n Tcedil: 'Ţ',\n tcedil: 'ţ',\n Tcaron: 'Ť',\n tcaron: 'ť',\n Tstrok: 'Ŧ',\n tstrok: 'ŧ',\n Utilde: 'Ũ',\n utilde: 'ũ',\n Umacr: 'Ū',\n umacr: 'ū',\n Ubreve: 'Ŭ',\n ubreve: 'ŭ',\n Uring: 'Ů',\n uring: 'ů',\n Udblac: 'Ű',\n udblac: 'ű',\n Uogon: 'Ų',\n uogon: 'ų',\n Wcirc: 'Ŵ',\n wcirc: 'ŵ',\n Ycirc: 'Ŷ',\n ycirc: 'ŷ',\n Zacute: 'Ź',\n zacute: 'ź',\n Zdot: 'Ż',\n zdot: 'ż',\n Zcaron: 'Ž',\n zcaron: 'ž',\n};\n\n/**\n * Greek Letters\n * @type {Record<string, string>}\n */\nexport const GREEK = {\n Alpha: 'Α',\n alpha: 'α',\n Beta: 'Β',\n beta: 'β',\n Gamma: 'Γ',\n gamma: 'γ',\n Delta: 'Δ',\n delta: 'δ',\n Epsilon: 'Ε',\n epsilon: 'ε',\n epsiv: 'ϵ',\n varepsilon: 'ϵ',\n Zeta: 'Ζ',\n zeta: 'ζ',\n Eta: 'Η',\n eta: 'η',\n Theta: 'Θ',\n theta: 'θ',\n thetasym: 'ϑ',\n vartheta: 'ϑ',\n Iota: 'Ι',\n iota: 'ι',\n Kappa: 'Κ',\n kappa: 'κ',\n kappav: 'ϰ',\n varkappa: 'ϰ',\n Lambda: 'Λ',\n lambda: 'λ',\n Mu: 'Μ',\n mu: 'μ',\n Nu: 'Ν',\n nu: 'ν',\n Xi: 'Ξ',\n xi: 'ξ',\n Omicron: 'Ο',\n omicron: 'ο',\n Pi: 'Π',\n pi: 'π',\n piv: 'ϖ',\n varpi: 'ϖ',\n Rho: 'Ρ',\n rho: 'ρ',\n rhov: 'ϱ',\n varrho: 'ϱ',\n Sigma: 'Σ',\n sigma: 'σ',\n sigmaf: 'ς',\n sigmav: 'ς',\n varsigma: 'ς',\n Tau: 'Τ',\n tau: 'τ',\n Upsilon: 'Υ',\n upsilon: 'υ',\n upsi: 'υ',\n Upsi: 'ϒ',\n upsih: 'ϒ',\n Phi: 'Φ',\n phi: 'φ',\n phiv: 'ϕ',\n varphi: 'ϕ',\n Chi: 'Χ',\n chi: 'χ',\n Psi: 'Ψ',\n psi: 'ψ',\n Omega: 'Ω',\n omega: 'ω',\n ohm: 'Ω',\n Gammad: 'Ϝ',\n gammad: 'ϝ',\n digamma: 'ϝ',\n};\n\n/**\n * Cyrillic Letters\n * @type {Record<string, string>}\n */\nexport const CYRILLIC = {\n Afr: '𝔄',\n afr: '𝔞',\n Acy: 'А',\n acy: 'а',\n Bcy: 'Б',\n bcy: 'б',\n Vcy: 'В',\n vcy: 'в',\n Gcy: 'Г',\n gcy: 'г',\n Dcy: 'Д',\n dcy: 'д',\n IEcy: 'Е',\n iecy: 'е',\n IOcy: 'Ё',\n iocy: 'ё',\n ZHcy: 'Ж',\n zhcy: 'ж',\n Zcy: 'З',\n zcy: 'з',\n Icy: 'И',\n icy: 'и',\n Jcy: 'Й',\n jcy: 'й',\n Kcy: 'К',\n kcy: 'к',\n Lcy: 'Л',\n lcy: 'л',\n Mcy: 'М',\n mcy: 'м',\n Ncy: 'Н',\n ncy: 'н',\n Ocy: 'О',\n ocy: 'о',\n Pcy: 'П',\n pcy: 'п',\n Rcy: 'Р',\n rcy: 'р',\n Scy: 'С',\n scy: 'с',\n Tcy: 'Т',\n tcy: 'т',\n Ucy: 'У',\n ucy: 'у',\n Fcy: 'Ф',\n fcy: 'ф',\n KHcy: 'Х',\n khcy: 'х',\n TScy: 'Ц',\n tscy: 'ц',\n CHcy: 'Ч',\n chcy: 'ч',\n SHcy: 'Ш',\n shcy: 'ш',\n SHCHcy: 'Щ',\n shchcy: 'щ',\n HARDcy: 'Ъ',\n hardcy: 'ъ',\n Ycy: 'Ы',\n ycy: 'ы',\n SOFTcy: 'Ь',\n softcy: 'ь',\n Ecy: 'Э',\n ecy: 'э',\n YUcy: 'Ю',\n yucy: 'ю',\n YAcy: 'Я',\n yacy: 'я',\n DJcy: 'Ђ',\n djcy: 'ђ',\n GJcy: 'Ѓ',\n gjcy: 'ѓ',\n Jukcy: 'Є',\n jukcy: 'є',\n DScy: 'Ѕ',\n dscy: 'ѕ',\n Iukcy: 'І',\n iukcy: 'і',\n YIcy: 'Ї',\n yicy: 'ї',\n Jsercy: 'Ј',\n jsercy: 'ј',\n LJcy: 'Љ',\n ljcy: 'љ',\n NJcy: 'Њ',\n njcy: 'њ',\n TSHcy: 'Ћ',\n tshcy: 'ћ',\n KJcy: 'Ќ',\n kjcy: 'ќ',\n Ubrcy: 'Ў',\n ubrcy: 'ў',\n DZcy: 'Џ',\n dzcy: 'џ',\n};\n\n/**\n * Mathematical Operators & Relations\n * @type {Record<string, string>}\n */\nexport const MATH = {\n plus: '+',\n minus: '−',\n mnplus: '∓',\n mp: '∓',\n pm: '±',\n times: '×',\n div: '÷',\n divide: '÷',\n sdot: '⋅',\n star: '☆',\n starf: '★',\n bigstar: '★',\n lowast: '∗',\n ast: '*',\n midast: '*',\n compfn: '∘',\n smallcircle: '∘',\n bullet: '•',\n bull: '•',\n nbsp: '\\u00a0',\n hellip: '…',\n mldr: '…',\n prime: '′',\n Prime: '″',\n tprime: '‴',\n bprime: '‵',\n backprime: '‵',\n minus: '−',\n minusd: '∸',\n dotminus: '∸',\n plusdo: '∔',\n dotplus: '∔',\n plusmn: '±',\n minusplus: '∓',\n mnplus: '∓',\n mp: '∓',\n setminus: '∖',\n smallsetminus: '∖',\n Backslash: '∖',\n setmn: '∖',\n ssetmn: '∖',\n lowbar: '_',\n verbar: '|',\n vert: '|',\n VerticalLine: '|',\n colon: ':',\n Colon: '∷',\n Proportion: '∷',\n ratio: '∶',\n equals: '=',\n ne: '≠',\n nequiv: '≢',\n equiv: '≡',\n Congruent: '≡',\n sim: '∼',\n thicksim: '∼',\n thksim: '∼',\n sime: '≃',\n simeq: '≃',\n TildeEqual: '≃',\n asymp: '≈',\n approx: '≈',\n thickapprox: '≈',\n thkap: '≈',\n TildeTilde: '≈',\n ncong: '≇',\n cong: '≅',\n TildeFullEqual: '≅',\n asympeq: '≍',\n CupCap: '≍',\n bump: '≎',\n Bumpeq: '≎',\n HumpDownHump: '≎',\n bumpe: '≏',\n bumpeq: '≏',\n HumpEqual: '≏',\n dotminus: '∸',\n minusd: '∸',\n plusdo: '∔',\n dotplus: '∔',\n le: '≤',\n LessEqual: '≤',\n ge: '≥',\n GreaterEqual: '≥',\n lesseqgtr: '⋚',\n lesseqqgtr: '⪋',\n greater: '>',\n less: '<',\n};\n\n/**\n * Mathematical Operators (Advanced)\n * @type {Record<string, string>}\n */\nexport const MATH_ADVANCED = {\n alefsym: 'ℵ',\n aleph: 'ℵ',\n beth: 'ℶ',\n gimel: 'ℷ',\n daleth: 'ℸ',\n forall: '∀',\n ForAll: '∀',\n part: '∂',\n PartialD: '∂',\n exist: '∃',\n Exists: '∃',\n nexist: '∄',\n nexists: '∄',\n empty: '∅',\n emptyset: '∅',\n emptyv: '∅',\n varnothing: '∅',\n nabla: '∇',\n Del: '∇',\n isin: '∈',\n isinv: '∈',\n in: '∈',\n Element: '∈',\n notin: '∉',\n notinva: '∉',\n ni: '∋',\n niv: '∋',\n SuchThat: '∋',\n ReverseElement: '∋',\n notni: '∌',\n notniva: '∌',\n prod: '∏',\n Product: '∏',\n coprod: '∐',\n Coproduct: '∐',\n sum: '∑',\n Sum: '∑',\n minus: '−',\n mp: '∓',\n plusdo: '∔',\n dotplus: '∔',\n setminus: '∖',\n lowast: '∗',\n radic: '√',\n Sqrt: '√',\n prop: '∝',\n propto: '∝',\n Proportional: '∝',\n varpropto: '∝',\n infin: '∞',\n infintie: '⧝',\n ang: '∠',\n angle: '∠',\n angmsd: '∡',\n measuredangle: '∡',\n angsph: '∢',\n mid: '∣',\n VerticalBar: '∣',\n nmid: '∤',\n nsmid: '∤',\n npar: '∦',\n parallel: '∥',\n spar: '∥',\n nparallel: '∦',\n nspar: '∦',\n and: '∧',\n wedge: '∧',\n or: '∨',\n vee: '∨',\n cap: '∩',\n cup: '∪',\n int: '∫',\n Integral: '∫',\n conint: '∮',\n ContourIntegral: '∮',\n Conint: '∯',\n DoubleContourIntegral: '∯',\n Cconint: '∰',\n there4: '∴',\n therefore: '∴',\n Therefore: '∴',\n becaus: '∵',\n because: '∵',\n Because: '∵',\n ratio: '∶',\n Proportion: '∷',\n minusd: '∸',\n dotminus: '∸',\n mDDot: '∺',\n homtht: '∻',\n sim: '∼',\n bsimg: '∽',\n backsim: '∽',\n ac: '∾',\n mstpos: '∾',\n acd: '∿',\n VerticalTilde: '≀',\n wr: '≀',\n wreath: '≀',\n nsime: '≄',\n nsimeq: '≄',\n nsimeq: '≄',\n ncong: '≇',\n simne: '≆',\n ncongdot: '⩭̸',\n ngsim: '≵',\n nsim: '≁',\n napprox: '≉',\n nap: '≉',\n ngeq: '≱',\n nge: '≱',\n nleq: '≰',\n nle: '≰',\n ngtr: '≯',\n ngt: '≯',\n nless: '≮',\n nlt: '≮',\n nprec: '⊀',\n npr: '⊀',\n nsucc: '⊁',\n nsc: '⊁',\n};\n\n/**\n * Arrows\n * @type {Record<string, string>}\n */\nexport const ARROWS = {\n larr: '←',\n leftarrow: '←',\n LeftArrow: '←',\n uarr: '↑',\n uparrow: '↑',\n UpArrow: '↑',\n rarr: '→',\n rightarrow: '→',\n RightArrow: '→',\n darr: '↓',\n downarrow: '↓',\n DownArrow: '↓',\n harr: '↔',\n leftrightarrow: '↔',\n LeftRightArrow: '↔',\n varr: '↕',\n updownarrow: '↕',\n UpDownArrow: '↕',\n nwarr: '↖',\n nwarrow: '↖',\n UpperLeftArrow: '↖',\n nearr: '↗',\n nearrow: '↗',\n UpperRightArrow: '↗',\n searr: '↘',\n searrow: '↘',\n LowerRightArrow: '↘',\n swarr: '↙',\n swarrow: '↙',\n LowerLeftArrow: '↙',\n lArr: '⇐',\n Leftarrow: '⇐',\n uArr: '⇑',\n Uparrow: '⇑',\n rArr: '⇒',\n Rightarrow: '⇒',\n dArr: '⇓',\n Downarrow: '⇓',\n hArr: '⇔',\n Leftrightarrow: '⇔',\n iff: '⇔',\n vArr: '⇕',\n Updownarrow: '⇕',\n lAarr: '⇚',\n Lleftarrow: '⇚',\n rAarr: '⇛',\n Rrightarrow: '⇛',\n lrarr: '⇆',\n leftrightarrows: '⇆',\n rlarr: '⇄',\n rightleftarrows: '⇄',\n lrhar: '⇋',\n leftrightharpoons: '⇋',\n ReverseEquilibrium: '⇋',\n rlhar: '⇌',\n rightleftharpoons: '⇌',\n Equilibrium: '⇌',\n udarr: '⇅',\n UpArrowDownArrow: '⇅',\n duarr: '⇵',\n DownArrowUpArrow: '⇵',\n llarr: '⇇',\n leftleftarrows: '⇇',\n rrarr: '⇉',\n rightrightarrows: '⇉',\n ddarr: '⇊',\n downdownarrows: '⇊',\n har: '↽',\n lhard: '↽',\n leftharpoondown: '↽',\n lharu: '↼',\n leftharpoonup: '↼',\n rhard: '⇁',\n rightharpoondown: '⇁',\n rharu: '⇀',\n rightharpoonup: '⇀',\n lsh: '↰',\n Lsh: '↰',\n rsh: '↱',\n Rsh: '↱',\n ldsh: '↲',\n rdsh: '↳',\n hookleftarrow: '↩',\n hookrightarrow: '↪',\n mapstoleft: '↤',\n mapstoup: '↥',\n map: '↦',\n mapsto: '↦',\n mapstodown: '↧',\n crarr: '↵',\n nwarrow: '↖',\n nearrow: '↗',\n searrow: '↘',\n swarrow: '↙',\n nleftarrow: '↚',\n nleftrightarrow: '↮',\n nrightarrow: '↛',\n nrarr: '↛',\n larrtl: '↢',\n rarrtl: '↣',\n leftarrowtail: '↢',\n rightarrowtail: '↣',\n twoheadleftarrow: '↞',\n twoheadrightarrow: '↠',\n Larr: '↞',\n Rarr: '↠',\n larrhk: '↩',\n rarrhk: '↪',\n larrlp: '↫',\n looparrowleft: '↫',\n rarrlp: '↬',\n looparrowright: '↬',\n harrw: '↭',\n leftrightsquigarrow: '↭',\n nrarrw: '↝̸',\n rarrw: '↝',\n rightsquigarrow: '↝',\n larrbfs: '⤟',\n rarrbfs: '⤠',\n nvHarr: '⤄',\n nvlArr: '⤂',\n nvrArr: '⤃',\n larrfs: '⤝',\n rarrfs: '⤞',\n Map: '⤅',\n larrsim: '⥳',\n rarrsim: '⥴',\n harrcir: '⥈',\n Uarrocir: '⥉',\n lurdshar: '⥊',\n ldrdhar: '⥧',\n ldrushar: '⥋',\n rdldhar: '⥩',\n lrhard: '⥭',\n rlhar: '⇌',\n uharr: '↾',\n uharl: '↿',\n dharr: '⇂',\n dharl: '⇃',\n Uarr: '↟',\n Darr: '↡',\n zigrarr: '⇝',\n nwArr: '⇖',\n neArr: '⇗',\n seArr: '⇘',\n swArr: '⇙',\n nharr: '↮',\n nhArr: '⇎',\n nlarr: '↚',\n nlArr: '⇍',\n nrarr: '↛',\n nrArr: '⇏',\n larrb: '⇤',\n LeftArrowBar: '⇤',\n rarrb: '⇥',\n RightArrowBar: '⇥',\n};\n\n/**\n * Geometric Shapes\n * @type {Record<string, string>}\n */\nexport const SHAPES = {\n square: '□',\n Square: '□',\n squ: '□',\n squf: '▪',\n squarf: '▪',\n blacksquar: '▪',\n blacksquare: '▪',\n FilledVerySmallSquare: '▪',\n blk34: '▓',\n blk12: '▒',\n blk14: '░',\n block: '█',\n srect: '▭',\n rect: '▭',\n sdot: '⋅',\n sdotb: '⊡',\n dotsquare: '⊡',\n triangle: '▵',\n tri: '▵',\n trine: '▵',\n utri: '▵',\n triangledown: '▿',\n dtri: '▿',\n tridown: '▿',\n triangleleft: '◃',\n ltri: '◃',\n triangleright: '▹',\n rtri: '▹',\n blacktriangle: '▴',\n utrif: '▴',\n blacktriangledown: '▾',\n dtrif: '▾',\n blacktriangleleft: '◂',\n ltrif: '◂',\n blacktriangleright: '▸',\n rtrif: '▸',\n loz: '◊',\n lozenge: '◊',\n blacklozenge: '⧫',\n lozf: '⧫',\n bigcirc: '◯',\n xcirc: '◯',\n circ: 'ˆ',\n Circle: '○',\n cir: '○',\n o: '○',\n bullet: '•',\n bull: '•',\n hellip: '…',\n mldr: '…',\n nldr: '‥',\n boxh: '─',\n HorizontalLine: '─',\n boxv: '│',\n boxdr: '┌',\n boxdl: '┐',\n boxur: '└',\n boxul: '┘',\n boxvr: '├',\n boxvl: '┤',\n boxhd: '┬',\n boxhu: '┴',\n boxvh: '┼',\n boxH: '═',\n boxV: '║',\n boxdR: '╒',\n boxDr: '╓',\n boxDR: '╔',\n boxDl: '╕',\n boxdL: '╖',\n boxDL: '╗',\n boxuR: '╘',\n boxUr: '╙',\n boxUR: '╚',\n boxUl: '╜',\n boxuL: '╛',\n boxUL: '╝',\n boxvR: '╞',\n boxVr: '╟',\n boxVR: '╠',\n boxVl: '╢',\n boxvL: '╡',\n boxVL: '╣',\n boxHd: '╤',\n boxhD: '╥',\n boxHD: '╦',\n boxHu: '╧',\n boxhU: '╨',\n boxHU: '╩',\n boxvH: '╪',\n boxVh: '╫',\n boxVH: '╬',\n};\n\n/**\n * Punctuation & Diacritics\n * @type {Record<string, string>}\n */\nexport const PUNCTUATION = {\n excl: '!',\n iexcl: '¡',\n brvbar: '¦',\n sect: '§',\n uml: '¨',\n copy: '©',\n ordf: 'ª',\n laquo: '«',\n not: '¬',\n shy: '\\u00ad',\n reg: '®',\n macr: '¯',\n deg: '°',\n plusmn: '±',\n sup2: '²',\n sup3: '³',\n acute: '´',\n micro: 'µ',\n para: '¶',\n middot: '·',\n cedil: '¸',\n sup1: '¹',\n ordm: 'º',\n raquo: '»',\n frac14: '¼',\n frac12: '½',\n frac34: '¾',\n iquest: '¿',\n nbsp: '\\u00a0',\n comma: ',',\n period: '.',\n colon: ':',\n semi: ';',\n vert: '|',\n Verbar: '‖',\n verbar: '|',\n dblac: '˝',\n circ: 'ˆ',\n caron: 'ˇ',\n breve: '˘',\n dot: '˙',\n ring: '˚',\n ogon: '˛',\n tilde: '˜',\n DiacriticalGrave: '`',\n DiacriticalAcute: '´',\n DiacriticalTilde: '˜',\n DiacriticalDot: '˙',\n DiacriticalDoubleAcute: '˝',\n grave: '`',\n acute: '´',\n};\n\n/**\n * Currency Symbols\n * @type {Record<string, string>}\n */\nexport const CURRENCY = {\n cent: '¢',\n pound: '£',\n curren: '¤',\n yen: '¥',\n euro: '€',\n dollar: '$',\n euro: '€',\n fnof: 'ƒ',\n inr: '₹',\n af: '؋',\n birr: 'ብር',\n peso: '₱',\n rub: '₽',\n won: '₩',\n yuan: '¥',\n cedil: '¸',\n};\n\n/**\n * Fractions\n * @type {Record<string, string>}\n */\nexport const FRACTIONS = {\n frac12: '½',\n half: '½',\n frac13: '⅓',\n frac14: '¼',\n frac15: '⅕',\n frac16: '⅙',\n frac18: '⅛',\n frac23: '⅔',\n frac25: '⅖',\n frac34: '¾',\n frac35: '⅗',\n frac38: '⅜',\n frac45: '⅘',\n frac56: '⅚',\n frac58: '⅝',\n frac78: '⅞',\n frasl: '⁄',\n};\n\n/**\n * Miscellaneous Symbols\n * @type {Record<string, string>}\n */\nexport const MISC_SYMBOLS = {\n trade: '™',\n TRADE: '™',\n telrec: '⌕',\n target: '⌖',\n ulcorn: '⌜',\n ulcorner: '⌜',\n urcorn: '⌝',\n urcorner: '⌝',\n dlcorn: '⌞',\n llcorner: '⌞',\n drcorn: '⌟',\n lrcorner: '⌟',\n intercal: '⊺',\n intcal: '⊺',\n oplus: '⊕',\n CirclePlus: '⊕',\n ominus: '⊖',\n CircleMinus: '⊖',\n otimes: '⊗',\n CircleTimes: '⊗',\n osol: '⊘',\n odot: '⊙',\n CircleDot: '⊙',\n oast: '⊛',\n circledast: '⊛',\n odash: '⊝',\n circleddash: '⊝',\n ocirc: '⊚',\n circledcirc: '⊚',\n boxplus: '⊞',\n plusb: '⊞',\n boxminus: '⊟',\n minusb: '⊟',\n boxtimes: '⊠',\n timesb: '⊠',\n boxdot: '⊡',\n sdotb: '⊡',\n veebar: '⊻',\n vee: '∨',\n barvee: '⊽',\n and: '∧',\n wedge: '∧',\n Cap: '⋒',\n Cup: '⋓',\n Fork: '⋔',\n pitchfork: '⋔',\n epar: '⋕',\n ltlarr: '⥶',\n nvap: '≍⃒',\n nvsim: '∼⃒',\n nvge: '≥⃒',\n nvle: '≤⃒',\n nvlt: '<⃒',\n nvgt: '>⃒',\n nvltrie: '⊴⃒',\n nvrtrie: '⊵⃒',\n Vdash: '⊩',\n dashv: '⊣',\n vDash: '⊨',\n Vdash: '⊩',\n Vvdash: '⊪',\n nvdash: '⊬',\n nvDash: '⊭',\n nVdash: '⊮',\n nVDash: '⊯',\n};\n\n/**\n * All entities combined (if you need everything)\n * @type {Record<string, string>}\n */\nexport const ALL_ENTITIES = {\n ...BASIC_LATIN,\n ...LATIN_ACCENTS,\n ...LATIN_EXTENDED,\n ...GREEK,\n ...CYRILLIC,\n ...MATH,\n ...MATH_ADVANCED,\n ...ARROWS,\n ...SHAPES,\n ...PUNCTUATION,\n ...CURRENCY,\n ...FRACTIONS,\n ...MISC_SYMBOLS,\n};\n\nexport const XML = {\n amp: \"&\",\n apos: \"'\",\n gt: \">\",\n lt: \"<\",\n quot: \"\\\"\"\n}\nexport const COMMON_HTML = {\n nbsp: '\\u00a0',\n copy: '\\u00a9',\n reg: '\\u00ae',\n trade: '\\u2122',\n mdash: '\\u2014',\n ndash: '\\u2013',\n hellip: '\\u2026',\n laquo: '\\u00ab',\n raquo: '\\u00bb',\n lsquo: '\\u2018',\n rsquo: '\\u2019',\n ldquo: '\\u201c',\n rdquo: '\\u201d',\n bull: '\\u2022',\n para: '\\u00b6',\n sect: '\\u00a7',\n deg: '\\u00b0',\n frac12: '\\u00bd',\n frac14: '\\u00bc',\n frac34: '\\u00be',\n}\n// ---------------------------------------------------------------------------\n// Note: NUMERIC_ENTITIES (&#NNN; / &#xHH;) are handled by the scanner directly\n// via String.fromCodePoint() without any map lookup.\n// ---------------------------------------------------------------------------","// ---------------------------------------------------------------------------\n// Built-in named entity map (name → replacement string)\n// No regex, no {regex,val} objects — just flat key/value pairs.\n// ---------------------------------------------------------------------------\n\nimport { XML as DEFAULT_XML_ENTITIES } from \"./entities.js\"\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nconst SPECIAL_CHARS = new Set('!?\\\\\\\\/[]$%{}^&*()<>|+');\n\n/**\n * Validate that an entity name contains no dangerous characters.\n * @param {string} name\n * @returns {string} the name, unchanged\n * @throws {Error} on invalid characters\n */\nfunction validateEntityName(name) {\n if (name[0] === '#') {\n throw new Error(`[EntityReplacer] Invalid character '#' in entity name: \"${name}\"`);\n }\n for (const ch of name) {\n if (SPECIAL_CHARS.has(ch)) {\n throw new Error(`[EntityReplacer] Invalid character '${ch}' in entity name: \"${name}\"`);\n }\n }\n return name;\n}\n\n/**\n * Merge one or more entity maps into a flat name→string map.\n * Accepts either:\n * - plain string values: { amp: '&' }\n * - legacy {regex,val} / {regx,val}: { lt: { regex: /.../, val: '<' } }\n *\n * Values containing '&' are skipped (recursive expansion risk).\n *\n * @param {...object} maps\n * @returns {Record<string, string>}\n */\nfunction mergeEntityMaps(...maps) {\n const out = Object.create(null);\n for (const map of maps) {\n if (!map) continue;\n for (const key of Object.keys(map)) {\n const raw = map[key];\n if (typeof raw === 'string') {\n out[key] = raw;\n } else if (raw && typeof raw === 'object' && raw.val !== undefined) {\n // Legacy {regex,val} or {regx,val} — extract the string val only\n const val = raw.val;\n if (typeof val === 'string') {\n out[key] = val;\n }\n // function vals are not supported in the scanner — skip\n }\n }\n }\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// applyLimitsTo helpers\n// ---------------------------------------------------------------------------\n\nconst LIMIT_TIER_EXTERNAL = 'external'; // input/runtime + persistent external maps\nconst LIMIT_TIER_BASE = 'base'; // DEFAULT_XML_ENTITIES + namedEntities (system) maps\nconst LIMIT_TIER_ALL = 'all'; // every entity regardless of tier\n\n/**\n * Resolve `applyLimitsTo` option into a normalised Set of tier strings.\n * Accepted values: 'external' | 'base' | 'all' | string[]\n * Default: 'external' (only untrusted injected entities are counted).\n * @param {string|string[]|undefined} raw\n * @returns {Set<string>}\n */\nfunction parseLimitTiers(raw) {\n if (!raw || raw === LIMIT_TIER_EXTERNAL) return new Set([LIMIT_TIER_EXTERNAL]);\n if (raw === LIMIT_TIER_ALL) return new Set([LIMIT_TIER_ALL]);\n if (raw === LIMIT_TIER_BASE) return new Set([LIMIT_TIER_BASE]);\n if (Array.isArray(raw)) return new Set(raw);\n return new Set([LIMIT_TIER_EXTERNAL]); // safe default for unrecognised values\n}\n\n// ---------------------------------------------------------------------------\n// NCR (Numeric Character Reference) classification\n// ---------------------------------------------------------------------------\n\n// Severity order — higher number = stricter action.\n// Used to enforce minimum action levels for specific codepoint ranges.\nconst NCR_LEVEL = Object.freeze({ allow: 0, leave: 1, remove: 2, throw: 3 });\n\n// XML 1.0 §2.2: allowed chars are #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]\n// Restricted C0: U+0001–U+001F excluding U+0009, U+000A, U+000D\nconst XML10_ALLOWED_C0 = new Set([0x09, 0x0A, 0x0D]);\n\n/**\n * Parse the `ncr` constructor option into flat, hot-path-friendly fields.\n * @param {object|undefined} ncr\n * @returns {{ xmlVersion: number, onLevel: number, nullLevel: number }}\n */\nfunction parseNCRConfig(ncr) {\n if (!ncr) {\n return { xmlVersion: 1.0, onLevel: NCR_LEVEL.allow, nullLevel: NCR_LEVEL.remove };\n }\n const xmlVersion = ncr.xmlVersion === 1.1 ? 1.1 : 1.0;\n const onLevel = NCR_LEVEL[ncr.onNCR] ?? NCR_LEVEL.allow;\n const nullLevel = NCR_LEVEL[ncr.nullNCR] ?? NCR_LEVEL.remove;\n // 'allow' is not meaningful for null — clamp to at least 'remove'\n const clampedNull = Math.max(nullLevel, NCR_LEVEL.remove);\n return { xmlVersion, onLevel, nullLevel: clampedNull };\n}\n\n// ---------------------------------------------------------------------------\n// EntityReplacer\n// ---------------------------------------------------------------------------\n\n/**\n * Single-pass, zero-regex entity replacer for XML/HTML content.\n *\n * Algorithm: scan the string once for '&', read to ';', resolve via map\n * or direct codepoint conversion, build output chunks, join once at the end.\n *\n * Entity lookup priority (highest → lowest):\n * 1. input / runtime (DOCTYPE entities for current document)\n * 2. persistent external (survive across documents)\n * 3. base named map (DEFAULT_XML_ENTITIES + user-supplied namedEntities)\n *\n * Both input and external resolve as the 'external' tier for limit purposes.\n * Base map entities resolve as the 'base' tier.\n *\n * Numeric / hex references (&#NNN; / &#xHH;) are resolved directly via\n * String.fromCodePoint() — no map needed. They count as 'base' tier.\n *\n * @example\n * const replacer = new EntityReplacer({ namedEntities: COMMON_HTML });\n * replacer.setExternalEntities({ brand: 'Acme' });\n *\n * const instance = replacer.reset();\n * instance.addInputEntities({ version: '1.0' });\n * instance.encode('&brand; v&version; <'); // 'Acme v1.0 <'\n */\nexport default class EntityDecoder {\n /**\n * @param {object} [options]\n * @param {object|null} [options.namedEntities] — extra named entities merged into base map\n * @param {object} [options.limit] — security limits\n * @param {number} [options.limit.maxTotalExpansions=0] — 0 = unlimited\n * @param {number} [options.limit.maxExpandedLength=0] — 0 = unlimited\n * @param {'external'|'base'|'all'|string[]} [options.limit.applyLimitsTo='external']\n * Which entity tiers count against the security limits:\n * - 'external' (default) — only input/runtime + persistent external entities\n * - 'base' — only DEFAULT_XML_ENTITIES + namedEntities\n * - 'all' — every entity regardless of tier\n * - string[] — explicit combination, e.g. ['external', 'base']\n * @param {((resolved: string, original: string) => string)|null} [options.postCheck=null]\n * @param {string[]} [options.remove=[]] — entity names (e.g. ['nbsp', '#13']) to delete (replace with empty string)\n * @param {string[]} [options.leave=[]] — entity names to keep as literal (unchanged in output)\n * @param {object} [options.ncr] — Numeric Character Reference controls\n * @param {1.0|1.1} [options.ncr.xmlVersion=1.0]\n * XML version governing which codepoint ranges are restricted:\n * - 1.0 — C0 controls U+0001–U+001F (except U+0009/000A/000D) are prohibited\n * - 1.1 — C0 controls are allowed when written as NCRs; C1 (U+007F–U+009F) decoded as-is\n * @param {'allow'|'leave'|'remove'|'throw'} [options.ncr.onNCR='allow']\n * Base action for numeric references. Severity order: allow < leave < remove < throw.\n * For codepoint ranges that carry a minimum level (surrogates → remove, XML 1.0 C0 → remove),\n * the effective action is max(onNCR, rangeMinimum).\n * @param {'remove'|'throw'} [options.ncr.nullNCR='remove']\n * Action for U+0000 (null). 'allow' and 'leave' are clamped to 'remove' since null is never safe.\n */\n constructor(options = {}) {\n this._limit = options.limit || {};\n this._maxTotalExpansions = this._limit.maxTotalExpansions || 0;\n this._maxExpandedLength = this._limit.maxExpandedLength || 0;\n this._postCheck = typeof options.postCheck === 'function' ? options.postCheck : r => r;\n this._limitTiers = parseLimitTiers(this._limit.applyLimitsTo ?? LIMIT_TIER_EXTERNAL);\n this._numericAllowed = options.numericAllowed ?? true;\n // Base map: DEFAULT_XML_ENTITIES + user-supplied extras. Immutable after construction.\n this._baseMap = mergeEntityMaps(DEFAULT_XML_ENTITIES, options.namedEntities || null);\n\n // Persistent external entities — survive across documents.\n // Stored as a separate map so reset() never touches them.\n /** @type {Record<string, string>} */\n this._externalMap = Object.create(null);\n\n // Input / runtime entities — current document only, wiped on reset().\n /** @type {Record<string, string>} */\n this._inputMap = Object.create(null);\n\n // Per-document counters\n this._totalExpansions = 0;\n this._expandedLength = 0;\n\n // --- New: remove / leave sets ---\n /** @type {Set<string>} */\n this._removeSet = new Set(options.remove && Array.isArray(options.remove) ? options.remove : []);\n /** @type {Set<string>} */\n this._leaveSet = new Set(options.leave && Array.isArray(options.leave) ? options.leave : []);\n\n // --- NCR config (parsed into flat fields for hot-path speed) ---\n const ncrCfg = parseNCRConfig(options.ncr);\n this._ncrXmlVersion = ncrCfg.xmlVersion;\n this._ncrOnLevel = ncrCfg.onLevel;\n this._ncrNullLevel = ncrCfg.nullLevel;\n }\n\n // -------------------------------------------------------------------------\n // Persistent external entity registration\n // -------------------------------------------------------------------------\n\n /**\n * Replace the full set of persistent external entities.\n * All keys are validated — throws on invalid characters.\n * @param {Record<string, string | { regex?: RegExp, val: string }>} map\n */\n setExternalEntities(map) {\n if (map) {\n for (const key of Object.keys(map)) {\n validateEntityName(key);\n }\n }\n this._externalMap = mergeEntityMaps(map);\n }\n\n /**\n * Add a single persistent external entity.\n * @param {string} key\n * @param {string} value\n */\n addExternalEntity(key, value) {\n validateEntityName(key);\n if (typeof value === 'string' && value.indexOf('&') === -1) {\n this._externalMap[key] = value;\n }\n }\n\n // -------------------------------------------------------------------------\n // Input / runtime entity registration (per document)\n // -------------------------------------------------------------------------\n\n /**\n * Inject DOCTYPE entities for the current document.\n * Also resets per-document expansion counters.\n * @param {Record<string, string | { regx?: RegExp, regex?: RegExp, val: string }>} map\n */\n addInputEntities(map) {\n this._totalExpansions = 0;\n this._expandedLength = 0;\n this._inputMap = mergeEntityMaps(map);\n }\n\n // -------------------------------------------------------------------------\n // Per-document reset\n // -------------------------------------------------------------------------\n\n /**\n * Wipe input/runtime entities and reset counters.\n * Call this before processing each new document.\n * @returns {this}\n */\n reset() {\n this._inputMap = Object.create(null);\n this._totalExpansions = 0;\n this._expandedLength = 0;\n return this;\n }\n\n // -------------------------------------------------------------------------\n // XML version (can be set after construction, e.g. once parser reads <?xml?>)\n // -------------------------------------------------------------------------\n\n /**\n * Update the XML version used for NCR classification.\n * Call this as soon as the document's `<?xml version=\"...\">` declaration is parsed.\n * @param {1.0|1.1|number} version\n */\n setXmlVersion(version) {\n this._ncrXmlVersion = version === 1.1 ? 1.1 : 1.0;\n }\n\n // -------------------------------------------------------------------------\n // Primary API\n // -------------------------------------------------------------------------\n\n /**\n * Replace all entity references in `str` in a single pass.\n *\n * @param {string} str\n * @returns {string}\n */\n decode(str) {\n if (typeof str !== 'string' || str.length === 0) return str;\n //TODO: check if needed\n //if (str.indexOf('&') === -1) return str; // fast path — no entities at all\n\n const original = str;\n const chunks = [];\n const len = str.length;\n let last = 0; // start of next unprocessed literal chunk\n let i = 0;\n\n const limitExpansions = this._maxTotalExpansions > 0;\n const limitLength = this._maxExpandedLength > 0;\n const checkLimits = limitExpansions || limitLength;\n\n while (i < len) {\n // Scan forward to next '&'\n if (str.charCodeAt(i) !== 38 /* '&' */) { i++; continue; }\n\n // --- Found '&' at position i ---\n\n // Scan forward to ';'\n let j = i + 1;\n while (j < len && str.charCodeAt(j) !== 59 /* ';' */ && (j - i) <= 32) j++;\n\n if (j >= len || str.charCodeAt(j) !== 59) {\n // No closing ';' within window — treat '&' as literal\n i++;\n continue;\n }\n\n // Raw token between '&' and ';' (exclusive)\n const token = str.slice(i + 1, j);\n if (token.length === 0) { i++; continue; }\n\n let replacement;\n let tier; // which limit tier this entity belongs to\n\n if (this._removeSet.has(token)) {\n // Remove entity: replace with empty string\n replacement = '';\n // If entity was unknown (replacement undefined), we still need a tier for limits.\n // Treat as external tier because it's user-directed removal of an unknown reference.\n if (tier === undefined) {\n tier = LIMIT_TIER_EXTERNAL;\n }\n } else if (this._leaveSet.has(token)) {\n // Do not replace — keep original &token; as literal\n i++;\n continue;\n } else if (token.charCodeAt(0) === 35 /* '#' */) {\n // ---- Numeric / NCR reference ----\n // NCR classification always runs first — prohibited codepoints must be\n // caught regardless of numericAllowed.\n const ncrResult = this._resolveNCR(token);\n if (ncrResult === undefined) {\n // 'leave' action — keep original &token; as-is\n i++;\n continue;\n }\n replacement = ncrResult; // '' for remove, char string for allow\n tier = LIMIT_TIER_BASE;\n } else {\n // ---- Named reference ----\n const resolved = this._resolveName(token);\n replacement = resolved?.value;\n tier = resolved?.tier;\n }\n\n if (replacement === undefined) {\n // Unknown entity — leave as-is, advance past '&' only\n i++;\n continue;\n }\n\n // Flush literal chunk before this entity\n if (i > last) chunks.push(str.slice(last, i));\n chunks.push(replacement);\n last = j + 1; // skip past ';'\n i = last;\n\n // Apply expansion limits only if this tier is being tracked\n if (checkLimits && this._tierCounts(tier)) {\n if (limitExpansions) {\n this._totalExpansions++;\n if (this._totalExpansions > this._maxTotalExpansions) {\n throw new Error(\n `[EntityReplacer] Entity expansion count limit exceeded: ` +\n `${this._totalExpansions} > ${this._maxTotalExpansions}`\n );\n }\n }\n if (limitLength) {\n // delta: replacement.length minus the raw &token; length (token.length + 2 for '&' and ';')\n const delta = replacement.length - (token.length + 2);\n if (delta > 0) {\n this._expandedLength += delta;\n if (this._expandedLength > this._maxExpandedLength) {\n throw new Error(\n `[EntityReplacer] Expanded content length limit exceeded: ` +\n `${this._expandedLength} > ${this._maxExpandedLength}`\n );\n }\n }\n }\n }\n }\n\n // Flush trailing literal\n if (last < len) chunks.push(str.slice(last));\n\n // If nothing was replaced, chunks is empty — return original\n const result = chunks.length === 0 ? str : chunks.join('');\n\n return this._postCheck(result, original);\n }\n\n // -------------------------------------------------------------------------\n // Private: limit tier check\n // -------------------------------------------------------------------------\n\n /**\n * Returns true if a resolved entity of the given tier should count\n * against the expansion/length limits.\n * @param {string} tier — LIMIT_TIER_EXTERNAL | LIMIT_TIER_BASE\n * @returns {boolean}\n */\n _tierCounts(tier) {\n if (this._limitTiers.has(LIMIT_TIER_ALL)) return true;\n return this._limitTiers.has(tier);\n }\n\n // -------------------------------------------------------------------------\n // Private: entity resolution\n // -------------------------------------------------------------------------\n\n /**\n * Resolve a named entity token (without & and ;).\n * Priority: inputMap > externalMap > baseMap\n * Returns the resolved value tagged with its limit tier.\n *\n * @param {string} name\n * @returns {{ value: string, tier: string }|undefined}\n */\n _resolveName(name) {\n // input and external both count as 'external' tier for limit purposes —\n // they are injected at runtime and are the untrusted surface.\n if (name in this._inputMap) return { value: this._inputMap[name], tier: LIMIT_TIER_EXTERNAL };\n if (name in this._externalMap) return { value: this._externalMap[name], tier: LIMIT_TIER_EXTERNAL };\n if (name in this._baseMap) return { value: this._baseMap[name], tier: LIMIT_TIER_BASE };\n return undefined;\n }\n\n /**\n * Classify a codepoint and return the minimum action level that must be applied.\n * Returns -1 when no minimum is imposed (normal allow path).\n *\n * Ranges checked (in priority order):\n * 1. U+0000 — null, governed by nullNCR (always ≥ remove)\n * 2. U+D800–U+DFFF — surrogates, always prohibited (min: remove)\n * 3. U+0001–U+001F \\ {0x09,0x0A,0x0D} — XML 1.0 restricted C0 (min: remove)\n * (skipped in XML 1.1 — C0 controls are allowed when written as NCRs)\n *\n * @param {number} cp — codepoint\n * @returns {number} — minimum NCR_LEVEL value, or -1 for no restriction\n */\n _classifyNCR(cp) {\n // 1. Null\n if (cp === 0) return this._ncrNullLevel;\n\n // 2. Surrogates — always prohibited, minimum 'remove'\n if (cp >= 0xD800 && cp <= 0xDFFF) return NCR_LEVEL.remove;\n\n // 3. XML 1.0 restricted C0 controls\n if (this._ncrXmlVersion === 1.0) {\n if (cp >= 0x01 && cp <= 0x1F && !XML10_ALLOWED_C0.has(cp)) return NCR_LEVEL.remove;\n }\n\n return -1; // no restriction\n }\n\n /**\n * Execute a resolved NCR action.\n *\n * @param {number} action — NCR_LEVEL value\n * @param {string} token — raw token (e.g. '#38') for error messages\n * @param {number} cp — codepoint, used only for error messages\n * @returns {string|undefined}\n * - decoded character string → 'allow'\n * - '' → 'remove'\n * - undefined → 'leave' (caller must skip past '&' only)\n * - throws Error → 'throw'\n */\n _applyNCRAction(action, token, cp) {\n switch (action) {\n case NCR_LEVEL.allow: return String.fromCodePoint(cp);\n case NCR_LEVEL.remove: return '';\n case NCR_LEVEL.leave: return undefined; // signal: keep literal\n case NCR_LEVEL.throw:\n throw new Error(\n `[EntityDecoder] Prohibited numeric character reference ` +\n `&${token}; (U+${cp.toString(16).toUpperCase().padStart(4, '0')})`\n );\n default: return String.fromCodePoint(cp);\n }\n }\n\n /**\n * Full NCR resolution pipeline for a numeric token.\n *\n * Steps:\n * 1. Parse the codepoint (decimal or hex).\n * 2. Validate the raw codepoint range (NaN, <0, >0x10FFFF).\n * 3. If numericAllowed is false and no minimum restriction applies → leave as-is.\n * 4. Classify the codepoint to find the minimum required action level.\n * 5. Resolve effective action = max(onNCR, minimum).\n * 6. Apply and return.\n *\n * @param {string} token — e.g. '#38', '#x26', '#X26'\n * @returns {string|undefined}\n * - string (incl. '') — replacement ('' = remove)\n * - undefined — leave original &token; as-is\n */\n _resolveNCR(token) {\n // Step 1: parse codepoint\n const second = token.charCodeAt(1);\n let cp;\n if (second === 120 /* x */ || second === 88 /* X */) {\n cp = parseInt(token.slice(2), 16);\n } else {\n cp = parseInt(token.slice(1), 10);\n }\n\n // Step 2: out-of-range → leave as-is unconditionally\n if (Number.isNaN(cp) || cp < 0 || cp > 0x10FFFF) return undefined;\n\n // Step 3: classify to get minimum action level\n const minimum = this._classifyNCR(cp);\n\n // Step 4: if numericAllowed is false and no hard minimum → leave\n if (!this._numericAllowed && minimum < NCR_LEVEL.remove) return undefined;\n\n // Step 5: effective action = max(configured onNCR, range minimum)\n const effective = minimum === -1\n ? this._ncrOnLevel\n : Math.max(this._ncrOnLevel, minimum);\n\n // Step 6: apply\n return this._applyNCRAction(effective, token, cp);\n }\n}","import { DANGEROUS_PROPERTY_NAMES, criticalProperties } from \"../util.js\";\nimport { COMMON_HTML, CURRENCY } from '@nodable/entities';\n\nconst defaultOnDangerousProperty = (name) => {\n if (DANGEROUS_PROPERTY_NAMES.includes(name)) {\n return \"__\" + name;\n }\n return name;\n};\n\n\nexport const defaultOptions = {\n preserveOrder: false,\n attributeNamePrefix: '@_',\n attributesGroupName: false,\n textNodeName: '#text',\n ignoreAttributes: true,\n removeNSPrefix: false, // remove NS from tag name or attribute name if true\n allowBooleanAttributes: false, //a tag can have attributes without any value\n //ignoreRootElement : false,\n parseTagValue: true,\n parseAttributeValue: false,\n trimValues: true, //Trim string values of tag and attributes\n cdataPropName: false,\n numberParseOptions: {\n hex: true,\n leadingZeros: true,\n eNotation: true\n },\n tagValueProcessor: function (tagName, val) {\n return val;\n },\n attributeValueProcessor: function (attrName, val) {\n return val;\n },\n stopNodes: [], //nested tags will not be parsed even for errors\n alwaysCreateTextNode: false,\n isArray: () => false,\n commentPropName: false,\n unpairedTags: [],\n processEntities: true,\n htmlEntities: false,\n entityDecoder: null,\n ignoreDeclaration: false,\n ignorePiTags: false,\n transformTagName: false,\n transformAttributeName: false,\n updateTag: function (tagName, jPath, attrs) {\n return tagName\n },\n // skipEmptyListItem: false\n captureMetaData: false,\n maxNestedTags: 100,\n strictReservedNames: true,\n jPath: true, // if true, pass jPath string to callbacks; if false, pass matcher instance\n onDangerousProperty: defaultOnDangerousProperty\n};\n\n\n/**\n * Validates that a property name is safe to use\n * @param {string} propertyName - The property name to validate\n * @param {string} optionName - The option field name (for error message)\n * @throws {Error} If property name is dangerous\n */\nfunction validatePropertyName(propertyName, optionName) {\n if (typeof propertyName !== 'string') {\n return; // Only validate string property names\n }\n\n const normalized = propertyName.toLowerCase();\n if (DANGEROUS_PROPERTY_NAMES.some(dangerous => normalized === dangerous.toLowerCase())) {\n throw new Error(\n `[SECURITY] Invalid ${optionName}: \"${propertyName}\" is a reserved JavaScript keyword that could cause prototype pollution`\n );\n }\n\n if (criticalProperties.some(dangerous => normalized === dangerous.toLowerCase())) {\n throw new Error(\n `[SECURITY] Invalid ${optionName}: \"${propertyName}\" is a reserved JavaScript keyword that could cause prototype pollution`\n );\n }\n}\n\n/**\n * Normalizes processEntities option for backward compatibility\n * @param {boolean|object} value \n * @returns {object} Always returns normalized object\n */\nfunction normalizeProcessEntities(value, htmlEntities) {\n // Boolean backward compatibility\n if (typeof value === 'boolean') {\n return {\n enabled: value, // true or false\n maxEntitySize: 10000,\n maxExpansionDepth: 10000,\n maxTotalExpansions: Infinity,\n maxExpandedLength: 100000,\n maxEntityCount: 1000,\n allowedTags: null,\n tagFilter: null,\n appliesTo: \"all\",\n };\n }\n\n // Object config - merge with defaults\n if (typeof value === 'object' && value !== null) {\n return {\n enabled: value.enabled !== false,\n maxEntitySize: Math.max(1, value.maxEntitySize ?? 10000),\n maxExpansionDepth: Math.max(1, value.maxExpansionDepth ?? 10000),\n maxTotalExpansions: Math.max(1, value.maxTotalExpansions ?? Infinity),\n maxExpandedLength: Math.max(1, value.maxExpandedLength ?? 100000),\n maxEntityCount: Math.max(1, value.maxEntityCount ?? 1000),\n allowedTags: value.allowedTags ?? null,\n tagFilter: value.tagFilter ?? null,\n appliesTo: value.appliesTo ?? \"all\",\n };\n }\n\n // Default to enabled with limits\n return normalizeProcessEntities(true);\n}\n\nexport const buildOptions = function (options) {\n const built = Object.assign({}, defaultOptions, options);\n\n // Validate property names to prevent prototype pollution\n const propertyNameOptions = [\n { value: built.attributeNamePrefix, name: 'attributeNamePrefix' },\n { value: built.attributesGroupName, name: 'attributesGroupName' },\n { value: built.textNodeName, name: 'textNodeName' },\n { value: built.cdataPropName, name: 'cdataPropName' },\n { value: built.commentPropName, name: 'commentPropName' }\n ];\n\n for (const { value, name } of propertyNameOptions) {\n if (value) {\n validatePropertyName(value, name);\n }\n }\n\n if (built.onDangerousProperty === null) {\n built.onDangerousProperty = defaultOnDangerousProperty;\n }\n\n // Always normalize processEntities for backward compatibility and validation\n built.processEntities = normalizeProcessEntities(built.processEntities, built.htmlEntities);\n built.unpairedTagsSet = new Set(built.unpairedTags);\n // Convert old-style stopNodes for backward compatibility\n if (built.stopNodes && Array.isArray(built.stopNodes)) {\n built.stopNodes = built.stopNodes.map(node => {\n if (typeof node === 'string' && node.startsWith('*.')) {\n // Old syntax: *.tagname meant \"tagname anywhere\"\n // Convert to new syntax: ..tagname\n return '..' + node.substring(2);\n }\n return node;\n });\n }\n //console.debug(built.processEntities)\n return built;\n};","'use strict';\n\nlet METADATA_SYMBOL;\n\nif (typeof Symbol !== \"function\") {\n METADATA_SYMBOL = \"@@xmlMetadata\";\n} else {\n METADATA_SYMBOL = Symbol(\"XML Node Metadata\");\n}\n\nexport default class XmlNode {\n constructor(tagname) {\n this.tagname = tagname;\n this.child = []; //nested tags, text, cdata, comments in order\n this[\":@\"] = Object.create(null); //attributes map\n }\n add(key, val) {\n // this.child.push( {name : key, val: val, isCdata: isCdata });\n if (key === \"__proto__\") key = \"#__proto__\";\n this.child.push({ [key]: val });\n }\n addChild(node, startIndex) {\n if (node.tagname === \"__proto__\") node.tagname = \"#__proto__\";\n if (node[\":@\"] && Object.keys(node[\":@\"]).length > 0) {\n this.child.push({ [node.tagname]: node.child, [\":@\"]: node[\":@\"] });\n } else {\n this.child.push({ [node.tagname]: node.child });\n }\n // if requested, add the startIndex\n if (startIndex !== undefined) {\n // Note: for now we just overwrite the metadata. If we had more complex metadata,\n // we might need to do an object append here: metadata = { ...metadata, startIndex }\n this.child[this.child.length - 1][METADATA_SYMBOL] = { startIndex };\n }\n }\n /** symbol used for metadata */\n static getMetaDataSymbol() {\n return METADATA_SYMBOL;\n }\n}\n","/**\n * xml-naming\n * Validates XML Name productions as defined in the XML 1.0 and 1.1 specifications.\n * Covers: Name, NCName, QName, NMToken, NMTokens\n *\n * XML 1.0 spec: https://www.w3.org/TR/xml/#NT-Name\n * XML 1.1 spec: https://www.w3.org/TR/xml11/#NT-NameStartChar\n * XML NS spec: https://www.w3.org/TR/xml-names/#NT-NCName\n */\n\n// ---------------------------------------------------------------------------\n// Character class strings — XML 1.0\n//\n// NameStartChar ::= \":\" | [A-Z] | \"_\" | [a-z]\n// | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF]\n// | [#x370-#x37D] | [#x37F-#x1FFF] <- split to exclude #x0487\n// | [#x200C-#x200D]\n// | [#x2070-#x218F] | [#x2C00-#x2FEF]\n// | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD]\n//\n// NameChar ::= NameStartChar | \"-\" | \".\" | [0-9]\n// | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]\n//\n// Note: \\u0487 (Combining Cyrillic Millions Sign) was added in Unicode 4.0,\n// after XML 1.0 was defined against Unicode 2.0. It falls inside the range\n// \\u037F-\\u1FFF but must be excluded. We split that range into\n// \\u037F-\\u0486 and \\u0488-\\u1FFF to exclude it explicitly.\n// ---------------------------------------------------------------------------\n\nconst nameStartChar10 =\n ':A-Za-z_' +\n '\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF' +\n '\\u0370-\\u037D' +\n '\\u037F-\\u0486\\u0488-\\u1FFF' + // split to exclude \\u0487\n '\\u200C-\\u200D' +\n '\\u2070-\\u218F' +\n '\\u2C00-\\u2FEF' +\n '\\u3001-\\uD7FF' +\n '\\uF900-\\uFDCF' +\n '\\uFDF0-\\uFFFD';\n\nconst nameChar10 =\n nameStartChar10 +\n '\\\\-\\\\.\\\\d' +\n '\\u00B7' +\n '\\u0300-\\u036F' +\n '\\u203F-\\u2040';\n\n// ---------------------------------------------------------------------------\n// Character class strings — XML 1.1\n//\n// Differences from XML 1.0:\n//\n// NameStartChar:\n// 1.0 has split ranges: \\u00C0-\\u00D6, \\u00D8-\\u00F6, \\u00F8-\\u02FF\n// 1.1 merges them into: \\u00C0-\\u02FF\n// (\\u00D7 x and \\u00F7 / are division symbols, excluded in both versions)\n//\n// 1.0 tops out at \\uFFFD (BMP only)\n// 1.1 adds \\u{10000}-\\u{EFFFF} (supplementary planes)\n// These require the /u flag on the RegExp — see buildRegexes below.\n//\n// NameChar:\n// 1.1 adds \\u0487 (Combining Cyrillic Millions Sign, added in Unicode 4.0)\n// ---------------------------------------------------------------------------\n\nconst nameStartChar11 =\n ':A-Za-z_' +\n '\\u00C0-\\u02FF' + // merged — 1.0 had three split ranges here\n '\\u0370-\\u037D' +\n '\\u037F-\\u0486\\u0488-\\u1FFF' + // split to exclude \\u0487 (combining mark, never a NameStartChar)\n '\\u200C-\\u200D' +\n '\\u2070-\\u218F' +\n '\\u2C00-\\u2FEF' +\n '\\u3001-\\uD7FF' +\n '\\uF900-\\uFDCF' +\n '\\uFDF0-\\uFFFD' +\n '\\u{10000}-\\u{EFFFF}'; // supplementary planes — REQUIRES /u flag on RegExp\n\nconst nameChar11 =\n nameStartChar11 +\n '\\\\-\\\\.\\\\d' +\n '\\u00B7' +\n '\\u0300-\\u036F' +\n '\\u0487' + // Combining Cyrillic Millions Sign — valid in 1.1, not 1.0\n '\\u203F-\\u2040';\n\n// ---------------------------------------------------------------------------\n// Regex builders\n//\n// XML 1.0 regexes: no flags — BMP only, standard JS regex behaviour.\n// XML 1.1 regexes: /u flag — required for \\u{10000}-\\u{EFFFF} to match actual\n// supplementary code points rather than lone surrogates (which are illegal XML).\n// ---------------------------------------------------------------------------\n\nconst buildRegexes = (startChar, char, flags = '') => {\n const ncStart = startChar.replace(':', '');\n const ncChar = char.replace(':', '');\n const ncNamePat = `[${ncStart}][${ncChar}]*`;\n\n return {\n name: new RegExp(`^[${startChar}][${char}]*$`, flags),\n ncName: new RegExp(`^${ncNamePat}$`, flags),\n qName: new RegExp(`^${ncNamePat}(?::${ncNamePat})?$`, flags),\n nmToken: new RegExp(`^[${char}]+$`, flags),\n nmTokens: new RegExp(`^[${char}]+(?:\\\\s+[${char}]+)*$`, flags),\n };\n};\n\nconst regexes10 = buildRegexes(nameStartChar10, nameChar10); // no /u — BMP only\nconst regexes11 = buildRegexes(nameStartChar11, nameChar11, 'u'); // /u — enables \\u{10000}-\\u{EFFFF}\n\nconst getRegexes = (xmlVersion = '1.0') =>\n xmlVersion === '1.1' ? regexes11 : regexes10;\n\n// ---------------------------------------------------------------------------\n// Boolean validators\n// ---------------------------------------------------------------------------\n\n/**\n * Returns true if the string is a valid XML Name.\n * Colons are allowed anywhere (Name production).\n * Used for: DOCTYPE entity names, notation names, DTD element declarations.\n */\nexport const name = (str, { xmlVersion = '1.0' } = {}) =>\n getRegexes(xmlVersion).name.test(str);\n\n/**\n * Returns true if the string is a valid NCName (Non-Colonized Name).\n * Colons are not permitted.\n * Used for: namespace prefixes, local names, SVG id attributes.\n */\nexport const ncName = (str, { xmlVersion = '1.0' } = {}) =>\n getRegexes(xmlVersion).ncName.test(str);\n\n/**\n * Returns true if the string is a valid QName (Qualified Name).\n * Allows exactly one colon as a prefix separator: prefix:localName.\n * Used for: element and attribute names in namespace-aware XML/SVG.\n */\nexport const qName = (str, { xmlVersion = '1.0' } = {}) =>\n getRegexes(xmlVersion).qName.test(str);\n\n/**\n * Returns true if the string is a valid NMToken.\n * Like Name but no restriction on the first character.\n * Used for: DTD NMTOKEN attribute values.\n */\nexport const nmToken = (str, { xmlVersion = '1.0' } = {}) =>\n getRegexes(xmlVersion).nmToken.test(str);\n\n/**\n * Returns true if the string is a valid NMTokens value.\n * A whitespace-separated list of NMToken values.\n * Used for: DTD NMTOKENS attribute values.\n */\nexport const nmTokens = (str, { xmlVersion = '1.0' } = {}) =>\n getRegexes(xmlVersion).nmTokens.test(str);\n\n// ---------------------------------------------------------------------------\n// Diagnostic validator\n// ---------------------------------------------------------------------------\n\nconst PRODUCTIONS = ['name', 'ncName', 'qName', 'nmToken', 'nmTokens'];\n\n/**\n * Validates a string against a named production and returns a detailed result.\n *\n * @param {string} str\n * @param {'name'|'ncName'|'qName'|'nmToken'|'nmTokens'} production\n * @param {{ xmlVersion?: '1.0'|'1.1' }} [opts]\n * @returns {{ valid: boolean, production: string, input: string, reason?: string, position?: number }}\n */\nexport const validate = (str, production, { xmlVersion = '1.0' } = {}) => {\n if (!PRODUCTIONS.includes(production)) {\n throw new TypeError(\n `Unknown production \"${production}\". Must be one of: ${PRODUCTIONS.join(', ')}`\n );\n }\n\n const validators = { name, ncName, qName, nmToken, nmTokens };\n const isValid = validators[production](str, { xmlVersion });\n\n if (isValid) return { valid: true, production, input: str };\n\n let reason = 'Does not match the production rules';\n let position;\n\n if (str.length === 0) {\n reason = 'Input is empty';\n } else if (production === 'ncName' && str.includes(':')) {\n position = str.indexOf(':');\n reason = 'Colon is not allowed in NCName';\n } else if (production === 'qName' && str.startsWith(':')) {\n reason = 'QName cannot start with a colon';\n position = 0;\n } else if (production === 'qName' && str.endsWith(':')) {\n reason = 'QName cannot end with a colon';\n position = str.length - 1;\n } else if (production === 'qName' && (str.match(/:/g) || []).length > 1) {\n reason = 'QName can have at most one colon';\n position = str.lastIndexOf(':');\n } else if (\n ['name', 'ncName', 'qName'].includes(production) &&\n !/^[:A-Za-z_\\u00C0-\\uFFFD]/.test(str[0])\n ) {\n reason = `First character \"${str[0]}\" is not a valid NameStartChar`;\n position = 0;\n } else {\n for (let i = 0; i < str.length; i++) {\n if (!/[\\w\\-\\\\.:\\u00B7\\u00C0-\\uFFFD]/.test(str[i])) {\n reason = `Character \"${str[i]}\" at position ${i} is not a valid NameChar`;\n position = i;\n break;\n }\n }\n }\n\n return { valid: false, production, input: str, reason, position };\n};\n\n// ---------------------------------------------------------------------------\n// Batch validator\n// ---------------------------------------------------------------------------\n\n/**\n * Validates an array of strings against a named production.\n *\n * @param {string[]} strings\n * @param {'name'|'ncName'|'qName'|'nmToken'|'nmTokens'} production\n * @param {{ xmlVersion?: '1.0'|'1.1' }} [opts]\n * @returns {Array<{ valid: boolean, production: string, input: string, reason?: string, position?: number }>}\n */\nexport const validateAll = (strings, production, opts = {}) =>\n strings.map(str => validate(str, production, opts));\n\n// ---------------------------------------------------------------------------\n// Sanitizer\n// ---------------------------------------------------------------------------\n\n/**\n * Transforms an invalid string into the nearest valid XML name for the given production.\n *\n * @param {string} str\n * @param {'name'|'ncName'|'qName'|'nmToken'|'nmTokens'} production\n * @param {{ replacement?: string }} [opts]\n * @returns {string}\n */\nexport const sanitize = (str, production = 'name', { replacement = '_' } = {}) => {\n if (!str) return replacement;\n\n let result = str;\n\n // Strip colons for NCName\n if (production === 'ncName') {\n result = result.replace(/:/g, '');\n }\n\n // Replace illegal characters\n result = result.replace(/[^\\w\\-\\.:\\u00B7\\u00C0-\\uFFFD]/g, replacement);\n\n // Fix invalid start character for Name / NCName / QName\n if (production !== 'nmToken' && production !== 'nmTokens') {\n if (/^[\\-\\.\\d]/.test(result)) {\n result = replacement + result;\n }\n }\n\n return result || replacement;\n};","import { qName as isName } from 'xml-naming';\n\nexport default class DocTypeReader {\n constructor(options, xmlVersion) {\n this.suppressValidationErr = !options;\n this.options = options;\n this.xmlVersion = xmlVersion || 1.0;\n }\n\n setXmlVersion(xmlVersion = 1.0) {\n this.xmlVersion = xmlVersion;\n }\n readDocType(xmlData, i) {\n const entities = Object.create(null);\n let entityCount = 0;\n\n if (xmlData[i + 3] === 'O' &&\n xmlData[i + 4] === 'C' &&\n xmlData[i + 5] === 'T' &&\n xmlData[i + 6] === 'Y' &&\n xmlData[i + 7] === 'P' &&\n xmlData[i + 8] === 'E') {\n i = i + 9;\n let angleBracketsCount = 1;\n let hasBody = false, comment = false;\n let exp = \"\";\n for (; i < xmlData.length; i++) {\n if (xmlData[i] === '<' && !comment) { //Determine the tag type\n if (hasBody && hasSeq(xmlData, \"!ENTITY\", i)) {\n i += 7;\n let entityName, val;\n [entityName, val, i] = this.readEntityExp(xmlData, i + 1, this.suppressValidationErr);\n if (val.indexOf(\"&\") === -1) { //Parameter entities are not supported\n if (this.options.enabled !== false &&\n this.options.maxEntityCount != null &&\n entityCount >= this.options.maxEntityCount) {\n throw new Error(\n `Entity count (${entityCount + 1}) exceeds maximum allowed (${this.options.maxEntityCount})`\n );\n }\n //const escaped = entityName.replace(/[.\\-+*:]/g, '\\\\.');\n //const escaped = entityName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n entities[entityName] = val;\n entityCount++;\n }\n }\n else if (hasBody && hasSeq(xmlData, \"!ELEMENT\", i)) {\n i += 8;//Not supported\n const { index } = this.readElementExp(xmlData, i + 1);\n i = index;\n } else if (hasBody && hasSeq(xmlData, \"!ATTLIST\", i)) {\n i += 8;//Not supported\n // const {index} = this.readAttlistExp(xmlData,i+1);\n // i = index;\n } else if (hasBody && hasSeq(xmlData, \"!NOTATION\", i)) {\n i += 9;//Not supported\n const { index } = this.readNotationExp(xmlData, i + 1, this.suppressValidationErr);\n i = index;\n } else if (hasSeq(xmlData, \"!--\", i)) comment = true;\n else throw new Error(`Invalid DOCTYPE`);\n\n angleBracketsCount++;\n exp = \"\";\n } else if (xmlData[i] === '>') { //Read tag content\n if (comment) {\n if (xmlData[i - 1] === \"-\" && xmlData[i - 2] === \"-\") {\n comment = false;\n angleBracketsCount--;\n }\n } else {\n angleBracketsCount--;\n }\n if (angleBracketsCount === 0) {\n break;\n }\n } else if (xmlData[i] === '[') {\n hasBody = true;\n } else {\n exp += xmlData[i];\n }\n }\n if (angleBracketsCount !== 0) {\n throw new Error(`Unclosed DOCTYPE`);\n }\n } else {\n throw new Error(`Invalid Tag instead of DOCTYPE`);\n }\n return { entities, i };\n }\n readEntityExp(xmlData, i) {\n //External entities are not supported\n // <!ENTITY ext SYSTEM \"http://normal-website.com\" >\n\n //Parameter entities are not supported\n // <!ENTITY entityname \"&anotherElement;\">\n\n //Internal entities are supported\n // <!ENTITY entityname \"replacement text\">\n\n // Skip leading whitespace after <!ENTITY\n i = skipWhitespace(xmlData, i);\n\n // Read entity name\n const startIndex = i;\n while (i < xmlData.length && !/\\s/.test(xmlData[i]) && xmlData[i] !== '\"' && xmlData[i] !== \"'\") {\n i++;\n }\n let entityName = xmlData.substring(startIndex, i);\n\n validateEntityName(entityName, { xmlVersion: this.xmlVersion });\n\n // Skip whitespace after entity name\n i = skipWhitespace(xmlData, i);\n\n // Check for unsupported constructs (external entities or parameter entities)\n if (!this.suppressValidationErr) {\n if (xmlData.substring(i, i + 6).toUpperCase() === \"SYSTEM\") {\n throw new Error(\"External entities are not supported\");\n } else if (xmlData[i] === \"%\") {\n throw new Error(\"Parameter entities are not supported\");\n }\n }\n\n // Read entity value (internal entity)\n let entityValue = \"\";\n [i, entityValue] = this.readIdentifierVal(xmlData, i, \"entity\");\n\n // Validate entity size\n if (this.options.enabled !== false &&\n this.options.maxEntitySize != null &&\n entityValue.length > this.options.maxEntitySize) {\n throw new Error(\n `Entity \"${entityName}\" size (${entityValue.length}) exceeds maximum allowed size (${this.options.maxEntitySize})`\n );\n }\n\n i--;\n return [entityName, entityValue, i];\n }\n\n readNotationExp(xmlData, i) {\n // Skip leading whitespace after <!NOTATION\n i = skipWhitespace(xmlData, i);\n\n // Read notation name\n\n const startIndex = i;\n while (i < xmlData.length && !/\\s/.test(xmlData[i])) {\n i++;\n }\n let notationName = xmlData.substring(startIndex, i);\n\n !this.suppressValidationErr && validateEntityName(notationName, { xmlVersion: this.xmlVersion });\n\n // Skip whitespace after notation name\n i = skipWhitespace(xmlData, i);\n\n // Check identifier type (SYSTEM or PUBLIC)\n const identifierType = xmlData.substring(i, i + 6).toUpperCase();\n if (!this.suppressValidationErr && identifierType !== \"SYSTEM\" && identifierType !== \"PUBLIC\") {\n throw new Error(`Expected SYSTEM or PUBLIC, found \"${identifierType}\"`);\n }\n i += identifierType.length;\n\n // Skip whitespace after identifier type\n i = skipWhitespace(xmlData, i);\n\n // Read public identifier (if PUBLIC)\n let publicIdentifier = null;\n let systemIdentifier = null;\n\n if (identifierType === \"PUBLIC\") {\n [i, publicIdentifier] = this.readIdentifierVal(xmlData, i, \"publicIdentifier\");\n\n // Skip whitespace after public identifier\n i = skipWhitespace(xmlData, i);\n\n // Optionally read system identifier\n if (xmlData[i] === '\"' || xmlData[i] === \"'\") {\n [i, systemIdentifier] = this.readIdentifierVal(xmlData, i, \"systemIdentifier\");\n }\n } else if (identifierType === \"SYSTEM\") {\n // Read system identifier (mandatory for SYSTEM)\n [i, systemIdentifier] = this.readIdentifierVal(xmlData, i, \"systemIdentifier\");\n\n if (!this.suppressValidationErr && !systemIdentifier) {\n throw new Error(\"Missing mandatory system identifier for SYSTEM notation\");\n }\n }\n\n return { notationName, publicIdentifier, systemIdentifier, index: --i };\n }\n\n readIdentifierVal(xmlData, i, type) {\n let identifierVal = \"\";\n const startChar = xmlData[i];\n if (startChar !== '\"' && startChar !== \"'\") {\n throw new Error(`Expected quoted string, found \"${startChar}\"`);\n }\n i++;\n\n const startIndex = i;\n while (i < xmlData.length && xmlData[i] !== startChar) {\n i++;\n }\n identifierVal = xmlData.substring(startIndex, i);\n\n if (xmlData[i] !== startChar) {\n throw new Error(`Unterminated ${type} value`);\n }\n i++;\n return [i, identifierVal];\n }\n\n readElementExp(xmlData, i) {\n // <!ELEMENT br EMPTY>\n // <!ELEMENT div ANY>\n // <!ELEMENT title (#PCDATA)>\n // <!ELEMENT book (title, author+)>\n // <!ELEMENT name (content-model)>\n\n // Skip leading whitespace after <!ELEMENT\n i = skipWhitespace(xmlData, i);\n\n // Read element name\n const startIndex = i;\n while (i < xmlData.length && !/\\s/.test(xmlData[i])) {\n i++;\n }\n let elementName = xmlData.substring(startIndex, i);\n\n // Validate element name\n if (!this.suppressValidationErr && !isName(elementName, { xmlVersion: this.xmlVersion })) {\n throw new Error(`Invalid element name: \"${elementName}\"`);\n }\n\n // Skip whitespace after element name\n i = skipWhitespace(xmlData, i);\n let contentModel = \"\";\n // Expect '(' to start content model\n if (xmlData[i] === \"E\" && hasSeq(xmlData, \"MPTY\", i)) i += 4;\n else if (xmlData[i] === \"A\" && hasSeq(xmlData, \"NY\", i)) i += 2;\n else if (xmlData[i] === \"(\") {\n i++; // Move past '('\n\n // Read content model\n const startIndex = i;\n while (i < xmlData.length && xmlData[i] !== \")\") {\n i++;\n }\n contentModel = xmlData.substring(startIndex, i);\n\n if (xmlData[i] !== \")\") {\n throw new Error(\"Unterminated content model\");\n }\n\n } else if (!this.suppressValidationErr) {\n throw new Error(`Invalid Element Expression, found \"${xmlData[i]}\"`);\n }\n\n return {\n elementName,\n contentModel: contentModel.trim(),\n index: i\n };\n }\n\n readAttlistExp(xmlData, i) {\n // Skip leading whitespace after <!ATTLIST\n i = skipWhitespace(xmlData, i);\n\n // Read element name\n let startIndex = i;\n while (i < xmlData.length && !/\\s/.test(xmlData[i])) {\n i++;\n }\n let elementName = xmlData.substring(startIndex, i);\n\n // Validate element name\n validateEntityName(elementName, { xmlVersion: this.xmlVersion })\n\n // Skip whitespace after element name\n i = skipWhitespace(xmlData, i);\n\n // Read attribute name\n startIndex = i;\n while (i < xmlData.length && !/\\s/.test(xmlData[i])) {\n i++;\n }\n let attributeName = xmlData.substring(startIndex, i);\n\n // Validate attribute name\n if (!validateEntityName(attributeName, { xmlVersion: this.xmlVersion })) {\n throw new Error(`Invalid attribute name: \"${attributeName}\"`);\n }\n\n // Skip whitespace after attribute name\n i = skipWhitespace(xmlData, i);\n\n // Read attribute type\n let attributeType = \"\";\n if (xmlData.substring(i, i + 8).toUpperCase() === \"NOTATION\") {\n attributeType = \"NOTATION\";\n i += 8; // Move past \"NOTATION\"\n\n // Skip whitespace after \"NOTATION\"\n i = skipWhitespace(xmlData, i);\n\n // Expect '(' to start the list of notations\n if (xmlData[i] !== \"(\") {\n throw new Error(`Expected '(', found \"${xmlData[i]}\"`);\n }\n i++; // Move past '('\n\n // Read the list of allowed notations\n let allowedNotations = [];\n while (i < xmlData.length && xmlData[i] !== \")\") {\n\n\n const startIndex = i;\n while (i < xmlData.length && xmlData[i] !== \"|\" && xmlData[i] !== \")\") {\n i++;\n }\n let notation = xmlData.substring(startIndex, i);\n\n // Validate notation name\n notation = notation.trim();\n if (!validateEntityName(notation, { xmlVersion: this.xmlVersion })) {\n throw new Error(`Invalid notation name: \"${notation}\"`);\n }\n\n allowedNotations.push(notation);\n\n // Skip '|' separator or exit loop\n if (xmlData[i] === \"|\") {\n i++; // Move past '|'\n i = skipWhitespace(xmlData, i); // Skip optional whitespace after '|'\n }\n }\n\n if (xmlData[i] !== \")\") {\n throw new Error(\"Unterminated list of notations\");\n }\n i++; // Move past ')'\n\n // Store the allowed notations as part of the attribute type\n attributeType += \" (\" + allowedNotations.join(\"|\") + \")\";\n } else {\n // Handle simple types (e.g., CDATA, ID, IDREF, etc.)\n const startIndex = i;\n while (i < xmlData.length && !/\\s/.test(xmlData[i])) {\n i++;\n }\n attributeType += xmlData.substring(startIndex, i);\n\n // Validate simple attribute type\n const validTypes = [\"CDATA\", \"ID\", \"IDREF\", \"IDREFS\", \"ENTITY\", \"ENTITIES\", \"NMTOKEN\", \"NMTOKENS\"];\n if (!this.suppressValidationErr && !validTypes.includes(attributeType.toUpperCase())) {\n throw new Error(`Invalid attribute type: \"${attributeType}\"`);\n }\n }\n\n // Skip whitespace after attribute type\n i = skipWhitespace(xmlData, i);\n\n // Read default value\n let defaultValue = \"\";\n if (xmlData.substring(i, i + 8).toUpperCase() === \"#REQUIRED\") {\n defaultValue = \"#REQUIRED\";\n i += 8;\n } else if (xmlData.substring(i, i + 7).toUpperCase() === \"#IMPLIED\") {\n defaultValue = \"#IMPLIED\";\n i += 7;\n } else {\n [i, defaultValue] = this.readIdentifierVal(xmlData, i, \"ATTLIST\");\n }\n\n return {\n elementName,\n attributeName,\n attributeType,\n defaultValue,\n index: i\n }\n }\n}\n\n\n\nconst skipWhitespace = (data, index) => {\n while (index < data.length && /\\s/.test(data[index])) {\n index++;\n }\n return index;\n};\n\n\n\nfunction hasSeq(data, seq, i) {\n for (let j = 0; j < seq.length; j++) {\n if (seq[j] !== data[i + j + 1]) return false;\n }\n return true;\n}\n\nfunction validateEntityName(name, xmlVersion) {\n if (isName(name, { xmlVersion: xmlVersion }))\n return name;\n else\n throw new Error(`Invalid entity name ${name}`);\n}","const hexRegex = /^[-+]?0x[a-fA-F0-9]+$/;\nconst binRegex = /^0b[01]+$/;\nconst octRegex = /^0o[0-7]+$/;\nconst numRegex = /^([\\-\\+])?(0*)([0-9]*(\\.[0-9]*)?)$/;\n\nconst consider = {\n hex: true,\n binary: false,\n octal: false,\n leadingZeros: true,\n decimalPoint: \"\\.\",\n eNotation: true,\n //skipLike: /regex/,\n infinity: \"original\", // \"null\", \"infinity\" (Infinity type), \"string\" (\"Infinity\" (the string literal))\n};\n\nexport default function toNumber(str, options = {}) {\n options = Object.assign({}, consider, options);\n if (!str || typeof str !== \"string\") return str;\n\n let trimmedStr = str.trim();\n\n if (trimmedStr.length === 0) return str;\n else if (options.skipLike !== undefined && options.skipLike.test(trimmedStr)) return str;\n else if (trimmedStr === \"0\") return 0;\n else if (options.hex && hexRegex.test(trimmedStr)) {\n return parse_int(trimmedStr, 16);\n } else if (options.binary && binRegex.test(trimmedStr)) {\n return parse_int(trimmedStr, 2);\n } else if (options.octal && octRegex.test(trimmedStr)) {\n return parse_int(trimmedStr, 8);\n } else if (!isFinite(trimmedStr)) { //Infinity\n return handleInfinity(str, Number(trimmedStr), options);\n } else if (trimmedStr.includes('e') || trimmedStr.includes('E')) { //eNotation\n return resolveEnotation(str, trimmedStr, options);\n } else {\n //separate negative sign, leading zeros, and rest number\n const match = numRegex.exec(trimmedStr);\n // +00.123 => [ , '+', '00', '.123', ..\n if (match) {\n const sign = match[1] || \"\";\n const leadingZeros = match[2];\n let numTrimmedByZeros = trimZeros(match[3]); //complete num without leading zeros\n const decimalAdjacentToLeadingZeros = sign ? // 0., -00., 000.\n str[leadingZeros.length + 1] === \".\"\n : str[leadingZeros.length] === \".\";\n\n //trim ending zeros for floating number\n if (!options.leadingZeros //leading zeros are not allowed\n && (leadingZeros.length > 1\n || (leadingZeros.length === 1 && !decimalAdjacentToLeadingZeros))) {\n // 00, 00.3, +03.24, 03, 03.24\n return str;\n }\n else {//no leading zeros or leading zeros are allowed\n const num = Number(trimmedStr);\n const parsedStr = String(num);\n\n if (num === 0) return num;\n if (parsedStr.search(/[eE]/) !== -1) { //given number is long and parsed to eNotation\n if (options.eNotation) return num;\n else return str;\n } else if (trimmedStr.indexOf(\".\") !== -1) { //floating number\n if (parsedStr === \"0\") return num; //0.0\n else if (parsedStr === numTrimmedByZeros) return num; //0.456. 0.79000\n else if (parsedStr === `${sign}${numTrimmedByZeros}`) return num;\n else return str;\n }\n\n let n = leadingZeros ? numTrimmedByZeros : trimmedStr;\n if (leadingZeros) {\n // -009 => -9\n return (n === parsedStr) || (sign + n === parsedStr) ? num : str\n } else {\n // +9\n return (n === parsedStr) || (n === sign + parsedStr) ? num : str\n }\n }\n } else { //non-numeric string\n return str;\n }\n }\n}\n\nconst eNotationRegx = /^([-+])?(0*)(\\d*(\\.\\d*)?[eE][-\\+]?\\d+)$/;\nfunction resolveEnotation(str, trimmedStr, options) {\n if (!options.eNotation) return str;\n const notation = trimmedStr.match(eNotationRegx);\n if (notation) {\n let sign = notation[1] || \"\";\n const eChar = notation[3].indexOf(\"e\") === -1 ? \"E\" : \"e\";\n const leadingZeros = notation[2];\n const eAdjacentToLeadingZeros = sign ? // 0E.\n str[leadingZeros.length + 1] === eChar\n : str[leadingZeros.length] === eChar;\n\n if (leadingZeros.length > 1 && eAdjacentToLeadingZeros) return str;\n else if (leadingZeros.length === 1\n && (notation[3].startsWith(`.${eChar}`) || notation[3][0] === eChar)) {\n return Number(trimmedStr);\n } else if (leadingZeros.length > 0) {\n // Has leading zeros — only accept if leadingZeros option allows it\n if (options.leadingZeros && !eAdjacentToLeadingZeros) {\n trimmedStr = (notation[1] || \"\") + notation[3];\n return Number(trimmedStr);\n } else return str;\n } else {\n // No leading zeros — always valid e-notation, parse it\n return Number(trimmedStr);\n }\n } else {\n return str;\n }\n}\n\n/**\n * \n * @param {string} numStr without leading zeros\n * @returns \n */\nfunction trimZeros(numStr) {\n if (numStr && numStr.indexOf(\".\") !== -1) {//float\n numStr = numStr.replace(/0+$/, \"\"); //remove ending zeros\n if (numStr === \".\") numStr = \"0\";\n else if (numStr[0] === \".\") numStr = \"0\" + numStr;\n else if (numStr[numStr.length - 1] === \".\") numStr = numStr.substring(0, numStr.length - 1);\n return numStr;\n }\n return numStr;\n}\n\nfunction parse_int(numStr, base) {\n const str = numStr.trim();\n if (base === 2 || base === 8) numStr = str.substring(2);\n\n if (parseInt) return parseInt(numStr, base);\n else if (Number.parseInt) return Number.parseInt(numStr, base);\n else if (window && window.parseInt) return window.parseInt(numStr, base);\n else throw new Error(\"parseInt, Number.parseInt, window.parseInt are not supported\");\n}\n\n/**\n * Handle infinite values based on user option\n * @param {string} str - original input string\n * @param {number} num - parsed number (Infinity or -Infinity)\n * @param {object} options - user options\n * @returns {string|number|null} based on infinity option\n */\nfunction handleInfinity(str, num, options) {\n const isPositive = num === Infinity;\n\n switch (options.infinity.toLowerCase()) {\n case \"null\":\n return null;\n case \"infinity\":\n return num; // Return Infinity or -Infinity\n case \"string\":\n return isPositive ? \"Infinity\" : \"-Infinity\";\n case \"original\":\n default:\n return str; // Return original string like \"1e1000\"\n }\n}","export default function getIgnoreAttributesFn(ignoreAttributes) {\n if (typeof ignoreAttributes === 'function') {\n return ignoreAttributes\n }\n if (Array.isArray(ignoreAttributes)) {\n return (attrName) => {\n for (const pattern of ignoreAttributes) {\n if (typeof pattern === 'string' && attrName === pattern) {\n return true\n }\n if (pattern instanceof RegExp && pattern.test(attrName)) {\n return true\n }\n }\n }\n }\n return () => false\n}","/**\n * Expression - Parses and stores a tag pattern expression\n * \n * Patterns are parsed once and stored in an optimized structure for fast matching.\n * \n * @example\n * const expr = new Expression(\"root.users.user\");\n * const expr2 = new Expression(\"..user[id]:first\");\n * const expr3 = new Expression(\"root/users/user\", { separator: '/' });\n */\nexport default class Expression {\n /**\n * Create a new Expression\n * @param {string} pattern - Pattern string (e.g., \"root.users.user\", \"..user[id]\")\n * @param {Object} options - Configuration options\n * @param {string} options.separator - Path separator (default: '.')\n */\n constructor(pattern, options = {}, data) {\n this.pattern = pattern;\n this.separator = options.separator || '.';\n this.segments = this._parse(pattern);\n this.data = data;\n // Cache expensive checks for performance (O(1) instead of O(n))\n this._hasDeepWildcard = this.segments.some(seg => seg.type === 'deep-wildcard');\n this._hasAttributeCondition = this.segments.some(seg => seg.attrName !== undefined);\n this._hasPositionSelector = this.segments.some(seg => seg.position !== undefined);\n }\n\n /**\n * Parse pattern string into segments\n * @private\n * @param {string} pattern - Pattern to parse\n * @returns {Array} Array of segment objects\n */\n _parse(pattern) {\n const segments = [];\n\n // Split by separator but handle \"..\" specially\n let i = 0;\n let currentPart = '';\n\n while (i < pattern.length) {\n if (pattern[i] === this.separator) {\n // Check if next char is also separator (deep wildcard)\n if (i + 1 < pattern.length && pattern[i + 1] === this.separator) {\n // Flush current part if any\n if (currentPart.trim()) {\n segments.push(this._parseSegment(currentPart.trim()));\n currentPart = '';\n }\n // Add deep wildcard\n segments.push({ type: 'deep-wildcard' });\n i += 2; // Skip both separators\n } else {\n // Regular separator\n if (currentPart.trim()) {\n segments.push(this._parseSegment(currentPart.trim()));\n }\n currentPart = '';\n i++;\n }\n } else {\n currentPart += pattern[i];\n i++;\n }\n }\n\n // Flush remaining part\n if (currentPart.trim()) {\n segments.push(this._parseSegment(currentPart.trim()));\n }\n\n return segments;\n }\n\n /**\n * Parse a single segment\n * @private\n * @param {string} part - Segment string (e.g., \"user\", \"ns::user\", \"user[id]\", \"ns::user:first\")\n * @returns {Object} Segment object\n */\n _parseSegment(part) {\n const segment = { type: 'tag' };\n\n // NEW NAMESPACE SYNTAX (v2.0):\n // ============================\n // Namespace uses DOUBLE colon (::)\n // Position uses SINGLE colon (:)\n // \n // Examples:\n // \"user\" → tag\n // \"user:first\" → tag + position\n // \"user[id]\" → tag + attribute\n // \"user[id]:first\" → tag + attribute + position\n // \"ns::user\" → namespace + tag\n // \"ns::user:first\" → namespace + tag + position\n // \"ns::user[id]\" → namespace + tag + attribute\n // \"ns::user[id]:first\" → namespace + tag + attribute + position\n // \"ns::first\" → namespace + tag named \"first\" (NO ambiguity!)\n //\n // This eliminates all ambiguity:\n // :: = namespace separator\n // : = position selector\n // [] = attributes\n\n // Step 1: Extract brackets [attr] or [attr=value]\n let bracketContent = null;\n let withoutBrackets = part;\n\n const bracketMatch = part.match(/^([^\\[]+)(\\[[^\\]]*\\])(.*)$/);\n if (bracketMatch) {\n withoutBrackets = bracketMatch[1] + bracketMatch[3];\n if (bracketMatch[2]) {\n const content = bracketMatch[2].slice(1, -1);\n if (content) {\n bracketContent = content;\n }\n }\n }\n\n // Step 2: Check for namespace (double colon ::)\n let namespace = undefined;\n let tagAndPosition = withoutBrackets;\n\n if (withoutBrackets.includes('::')) {\n const nsIndex = withoutBrackets.indexOf('::');\n namespace = withoutBrackets.substring(0, nsIndex).trim();\n tagAndPosition = withoutBrackets.substring(nsIndex + 2).trim(); // Skip ::\n\n if (!namespace) {\n throw new Error(`Invalid namespace in pattern: ${part}`);\n }\n }\n\n // Step 3: Parse tag and position (single colon :)\n let tag = undefined;\n let positionMatch = null;\n\n if (tagAndPosition.includes(':')) {\n const colonIndex = tagAndPosition.lastIndexOf(':'); // Use last colon for position\n const tagPart = tagAndPosition.substring(0, colonIndex).trim();\n const posPart = tagAndPosition.substring(colonIndex + 1).trim();\n\n // Verify position is a valid keyword\n const isPositionKeyword = ['first', 'last', 'odd', 'even'].includes(posPart) ||\n /^nth\\(\\d+\\)$/.test(posPart);\n\n if (isPositionKeyword) {\n tag = tagPart;\n positionMatch = posPart;\n } else {\n // Not a valid position keyword, treat whole thing as tag\n tag = tagAndPosition;\n }\n } else {\n tag = tagAndPosition;\n }\n\n if (!tag) {\n throw new Error(`Invalid segment pattern: ${part}`);\n }\n\n segment.tag = tag;\n if (namespace) {\n segment.namespace = namespace;\n }\n\n // Step 4: Parse attributes\n if (bracketContent) {\n if (bracketContent.includes('=')) {\n const eqIndex = bracketContent.indexOf('=');\n segment.attrName = bracketContent.substring(0, eqIndex).trim();\n segment.attrValue = bracketContent.substring(eqIndex + 1).trim();\n } else {\n segment.attrName = bracketContent.trim();\n }\n }\n\n // Step 5: Parse position selector\n if (positionMatch) {\n const nthMatch = positionMatch.match(/^nth\\((\\d+)\\)$/);\n if (nthMatch) {\n segment.position = 'nth';\n segment.positionValue = parseInt(nthMatch[1], 10);\n } else {\n segment.position = positionMatch;\n }\n }\n\n return segment;\n }\n\n /**\n * Get the number of segments\n * @returns {number}\n */\n get length() {\n return this.segments.length;\n }\n\n /**\n * Check if expression contains deep wildcard\n * @returns {boolean}\n */\n hasDeepWildcard() {\n return this._hasDeepWildcard;\n }\n\n /**\n * Check if expression has attribute conditions\n * @returns {boolean}\n */\n hasAttributeCondition() {\n return this._hasAttributeCondition;\n }\n\n /**\n * Check if expression has position selectors\n * @returns {boolean}\n */\n hasPositionSelector() {\n return this._hasPositionSelector;\n }\n\n /**\n * Get string representation\n * @returns {string}\n */\n toString() {\n return this.pattern;\n }\n}","/**\n * ExpressionSet - An indexed collection of Expressions for efficient bulk matching\n *\n * Instead of iterating all expressions on every tag, ExpressionSet pre-indexes\n * them at insertion time by depth and terminal tag name. At match time, only\n * the relevant bucket is evaluated — typically reducing checks from O(E) to O(1)\n * lookup plus O(small bucket) matches.\n *\n * Three buckets are maintained:\n * - `_byDepthAndTag` — exact depth + exact tag name (tightest, used first)\n * - `_wildcardByDepth` — exact depth + wildcard tag `*` (depth-matched only)\n * - `_deepWildcards` — expressions containing `..` (cannot be depth-indexed)\n *\n * @example\n * import { Expression, ExpressionSet } from 'fast-xml-tagger';\n *\n * // Build once at config time\n * const stopNodes = new ExpressionSet();\n * stopNodes.add(new Expression('root.users.user'));\n * stopNodes.add(new Expression('root.config.setting'));\n * stopNodes.add(new Expression('..script'));\n *\n * // Query on every tag — hot path\n * if (stopNodes.matchesAny(matcher)) { ... }\n */\nexport default class ExpressionSet {\n constructor() {\n /** @type {Map<string, import('./Expression.js').default[]>} depth:tag → expressions */\n this._byDepthAndTag = new Map();\n\n /** @type {Map<number, import('./Expression.js').default[]>} depth → wildcard-tag expressions */\n this._wildcardByDepth = new Map();\n\n /** @type {import('./Expression.js').default[]} expressions containing deep wildcard (..) */\n this._deepWildcards = [];\n\n /** @type {Set<string>} pattern strings already added — used for deduplication */\n this._patterns = new Set();\n\n /** @type {boolean} whether the set is sealed against further additions */\n this._sealed = false;\n }\n\n /**\n * Add an Expression to the set.\n * Duplicate patterns (same pattern string) are silently ignored.\n *\n * @param {import('./Expression.js').default} expression - A pre-constructed Expression instance\n * @returns {this} for chaining\n * @throws {TypeError} if called after seal()\n *\n * @example\n * set.add(new Expression('root.users.user'));\n * set.add(new Expression('..script'));\n */\n add(expression) {\n if (this._sealed) {\n throw new TypeError(\n 'ExpressionSet is sealed. Create a new ExpressionSet to add more expressions.'\n );\n }\n\n // Deduplicate by pattern string\n if (this._patterns.has(expression.pattern)) return this;\n this._patterns.add(expression.pattern);\n\n if (expression.hasDeepWildcard()) {\n this._deepWildcards.push(expression);\n return this;\n }\n\n const depth = expression.length;\n const lastSeg = expression.segments[expression.segments.length - 1];\n const tag = lastSeg?.tag;\n\n if (!tag || tag === '*') {\n // Can index by depth but not by tag\n if (!this._wildcardByDepth.has(depth)) this._wildcardByDepth.set(depth, []);\n this._wildcardByDepth.get(depth).push(expression);\n } else {\n // Tightest bucket: depth + tag\n const key = `${depth}:${tag}`;\n if (!this._byDepthAndTag.has(key)) this._byDepthAndTag.set(key, []);\n this._byDepthAndTag.get(key).push(expression);\n }\n\n return this;\n }\n\n /**\n * Add multiple expressions at once.\n *\n * @param {import('./Expression.js').default[]} expressions - Array of Expression instances\n * @returns {this} for chaining\n *\n * @example\n * set.addAll([\n * new Expression('root.users.user'),\n * new Expression('root.config.setting'),\n * ]);\n */\n addAll(expressions) {\n for (const expr of expressions) this.add(expr);\n return this;\n }\n\n /**\n * Check whether a pattern string is already present in the set.\n *\n * @param {import('./Expression.js').default} expression\n * @returns {boolean}\n */\n has(expression) {\n return this._patterns.has(expression.pattern);\n }\n\n /**\n * Number of expressions in the set.\n * @type {number}\n */\n get size() {\n return this._patterns.size;\n }\n\n /**\n * Seal the set against further modifications.\n * Useful to prevent accidental mutations after config is built.\n * Calling add() or addAll() on a sealed set throws a TypeError.\n *\n * @returns {this}\n */\n seal() {\n this._sealed = true;\n return this;\n }\n\n /**\n * Whether the set has been sealed.\n * @type {boolean}\n */\n get isSealed() {\n return this._sealed;\n }\n\n /**\n * Test whether the matcher's current path matches any expression in the set.\n *\n * Evaluation order (cheapest → most expensive):\n * 1. Exact depth + tag bucket — O(1) lookup, typically 0–2 expressions\n * 2. Depth-only wildcard bucket — O(1) lookup, rare\n * 3. Deep-wildcard list — always checked, but usually small\n *\n * @param {import('./Matcher.js').default} matcher - Matcher instance (or readOnly view)\n * @returns {boolean} true if any expression matches the current path\n *\n * @example\n * if (stopNodes.matchesAny(matcher)) {\n * // handle stop node\n * }\n */\n matchesAny(matcher) {\n return this.findMatch(matcher) !== null;\n }\n /**\n * Find and return the first Expression that matches the matcher's current path.\n *\n * Uses the same evaluation order as matchesAny (cheapest → most expensive):\n * 1. Exact depth + tag bucket\n * 2. Depth-only wildcard bucket\n * 3. Deep-wildcard list\n *\n * @param {import('./Matcher.js').default} matcher - Matcher instance (or readOnly view)\n * @returns {import('./Expression.js').default | null} the first matching Expression, or null\n *\n * @example\n * const expr = stopNodes.findMatch(matcher);\n * if (expr) {\n * // access expr.config, expr.pattern, etc.\n * }\n */\n findMatch(matcher) {\n const depth = matcher.getDepth();\n const tag = matcher.getCurrentTag();\n\n // 1. Tightest bucket — most expressions live here\n const exactKey = `${depth}:${tag}`;\n const exactBucket = this._byDepthAndTag.get(exactKey);\n if (exactBucket) {\n for (let i = 0; i < exactBucket.length; i++) {\n if (matcher.matches(exactBucket[i])) return exactBucket[i];\n }\n }\n\n // 2. Depth-matched wildcard-tag expressions\n const wildcardBucket = this._wildcardByDepth.get(depth);\n if (wildcardBucket) {\n for (let i = 0; i < wildcardBucket.length; i++) {\n if (matcher.matches(wildcardBucket[i])) return wildcardBucket[i];\n }\n }\n\n // 3. Deep wildcards — cannot be pre-filtered by depth or tag\n for (let i = 0; i < this._deepWildcards.length; i++) {\n if (matcher.matches(this._deepWildcards[i])) return this._deepWildcards[i];\n }\n\n return null;\n }\n}\n","import ExpressionSet from \"./ExpressionSet.js\";\n\n/**\n * MatcherView - A lightweight read-only view over a Matcher's internal state.\n *\n * Created once by Matcher and reused across all callbacks. Holds a direct\n * reference to the parent Matcher so it always reflects current parser state\n * with zero copying or freezing overhead.\n *\n * Users receive this via {@link Matcher#readOnly} or directly from parser\n * callbacks. It exposes all query and matching methods but has no mutation\n * methods — misuse is caught at the TypeScript level rather than at runtime.\n *\n * @example\n * const matcher = new Matcher();\n * const view = matcher.readOnly();\n *\n * matcher.push(\"root\", {});\n * view.getCurrentTag(); // \"root\"\n * view.getDepth(); // 1\n */\nexport class MatcherView {\n /**\n * @param {Matcher} matcher - The parent Matcher instance to read from.\n */\n constructor(matcher) {\n this._matcher = matcher;\n }\n\n /**\n * Get the path separator used by the parent matcher.\n * @returns {string}\n */\n get separator() {\n return this._matcher.separator;\n }\n\n /**\n * Get current tag name.\n * @returns {string|undefined}\n */\n getCurrentTag() {\n const path = this._matcher.path;\n return path.length > 0 ? path[path.length - 1].tag : undefined;\n }\n\n /**\n * Get current namespace.\n * @returns {string|undefined}\n */\n getCurrentNamespace() {\n const path = this._matcher.path;\n return path.length > 0 ? path[path.length - 1].namespace : undefined;\n }\n\n /**\n * Get current node's attribute value.\n * @param {string} attrName\n * @returns {*}\n */\n getAttrValue(attrName) {\n const path = this._matcher.path;\n if (path.length === 0) return undefined;\n return path[path.length - 1].values?.[attrName];\n }\n\n /**\n * Check if current node has an attribute.\n * @param {string} attrName\n * @returns {boolean}\n */\n hasAttr(attrName) {\n const path = this._matcher.path;\n if (path.length === 0) return false;\n const current = path[path.length - 1];\n return current.values !== undefined && attrName in current.values;\n }\n\n /**\n * Get current node's sibling position (child index in parent).\n * @returns {number}\n */\n getPosition() {\n const path = this._matcher.path;\n if (path.length === 0) return -1;\n return path[path.length - 1].position ?? 0;\n }\n\n /**\n * Get current node's repeat counter (occurrence count of this tag name).\n * @returns {number}\n */\n getCounter() {\n const path = this._matcher.path;\n if (path.length === 0) return -1;\n return path[path.length - 1].counter ?? 0;\n }\n\n /**\n * Get current node's sibling index (alias for getPosition).\n * @returns {number}\n * @deprecated Use getPosition() or getCounter() instead\n */\n getIndex() {\n return this.getPosition();\n }\n\n /**\n * Get current path depth.\n * @returns {number}\n */\n getDepth() {\n return this._matcher.path.length;\n }\n\n /**\n * Get path as string.\n * @param {string} [separator] - Optional separator (uses default if not provided)\n * @param {boolean} [includeNamespace=true]\n * @returns {string}\n */\n toString(separator, includeNamespace = true) {\n return this._matcher.toString(separator, includeNamespace);\n }\n\n /**\n * Get path as array of tag names.\n * @returns {string[]}\n */\n toArray() {\n return this._matcher.path.map(n => n.tag);\n }\n\n /**\n * Match current path against an Expression.\n * @param {Expression} expression\n * @returns {boolean}\n */\n matches(expression) {\n return this._matcher.matches(expression);\n }\n\n /**\n * Match any expression in the given set against the current path.\n * @param {ExpressionSet} exprSet\n * @returns {boolean}\n */\n matchesAny(exprSet) {\n return exprSet.matchesAny(this._matcher);\n }\n}\n\n/**\n * Matcher - Tracks current path in XML/JSON tree and matches against Expressions.\n *\n * The matcher maintains a stack of nodes representing the current path from root to\n * current tag. It only stores attribute values for the current (top) node to minimize\n * memory usage. Sibling tracking is used to auto-calculate position and counter.\n *\n * Use {@link Matcher#readOnly} to obtain a {@link MatcherView} safe to pass to\n * user callbacks — it always reflects current state with no Proxy overhead.\n *\n * @example\n * const matcher = new Matcher();\n * matcher.push(\"root\", {});\n * matcher.push(\"users\", {});\n * matcher.push(\"user\", { id: \"123\", type: \"admin\" });\n *\n * const expr = new Expression(\"root.users.user\");\n * matcher.matches(expr); // true\n */\nexport default class Matcher {\n /**\n * Create a new Matcher.\n * @param {Object} [options={}]\n * @param {string} [options.separator='.'] - Default path separator\n */\n constructor(options = {}) {\n this.separator = options.separator || '.';\n this.path = [];\n this.siblingStacks = [];\n // Each path node: { tag, values, position, counter, namespace? }\n // values only present for current (last) node\n // Each siblingStacks entry: Map<tagName, count> tracking occurrences at each level\n this._pathStringCache = null;\n this._view = new MatcherView(this);\n }\n\n /**\n * Push a new tag onto the path.\n * @param {string} tagName\n * @param {Object|null} [attrValues=null]\n * @param {string|null} [namespace=null]\n */\n push(tagName, attrValues = null, namespace = null) {\n this._pathStringCache = null;\n\n // Remove values from previous current node (now becoming ancestor)\n if (this.path.length > 0) {\n this.path[this.path.length - 1].values = undefined;\n }\n\n // Get or create sibling tracking for current level\n const currentLevel = this.path.length;\n if (!this.siblingStacks[currentLevel]) {\n this.siblingStacks[currentLevel] = new Map();\n }\n\n const siblings = this.siblingStacks[currentLevel];\n\n // Create a unique key for sibling tracking that includes namespace\n const siblingKey = namespace ? `${namespace}:${tagName}` : tagName;\n\n // Calculate counter (how many times this tag appeared at this level)\n const counter = siblings.get(siblingKey) || 0;\n\n // Calculate position (total children at this level so far)\n let position = 0;\n for (const count of siblings.values()) {\n position += count;\n }\n\n // Update sibling count for this tag\n siblings.set(siblingKey, counter + 1);\n\n // Create new node\n const node = {\n tag: tagName,\n position: position,\n counter: counter\n };\n\n if (namespace !== null && namespace !== undefined) {\n node.namespace = namespace;\n }\n\n if (attrValues !== null && attrValues !== undefined) {\n node.values = attrValues;\n }\n\n this.path.push(node);\n }\n\n /**\n * Pop the last tag from the path.\n * @returns {Object|undefined} The popped node\n */\n pop() {\n if (this.path.length === 0) return undefined;\n this._pathStringCache = null;\n\n const node = this.path.pop();\n\n if (this.siblingStacks.length > this.path.length + 1) {\n this.siblingStacks.length = this.path.length + 1;\n }\n\n return node;\n }\n\n /**\n * Update current node's attribute values.\n * Useful when attributes are parsed after push.\n * @param {Object} attrValues\n */\n updateCurrent(attrValues) {\n if (this.path.length > 0) {\n const current = this.path[this.path.length - 1];\n if (attrValues !== null && attrValues !== undefined) {\n current.values = attrValues;\n }\n }\n }\n\n /**\n * Get current tag name.\n * @returns {string|undefined}\n */\n getCurrentTag() {\n return this.path.length > 0 ? this.path[this.path.length - 1].tag : undefined;\n }\n\n /**\n * Get current namespace.\n * @returns {string|undefined}\n */\n getCurrentNamespace() {\n return this.path.length > 0 ? this.path[this.path.length - 1].namespace : undefined;\n }\n\n /**\n * Get current node's attribute value.\n * @param {string} attrName\n * @returns {*}\n */\n getAttrValue(attrName) {\n if (this.path.length === 0) return undefined;\n return this.path[this.path.length - 1].values?.[attrName];\n }\n\n /**\n * Check if current node has an attribute.\n * @param {string} attrName\n * @returns {boolean}\n */\n hasAttr(attrName) {\n if (this.path.length === 0) return false;\n const current = this.path[this.path.length - 1];\n return current.values !== undefined && attrName in current.values;\n }\n\n /**\n * Get current node's sibling position (child index in parent).\n * @returns {number}\n */\n getPosition() {\n if (this.path.length === 0) return -1;\n return this.path[this.path.length - 1].position ?? 0;\n }\n\n /**\n * Get current node's repeat counter (occurrence count of this tag name).\n * @returns {number}\n */\n getCounter() {\n if (this.path.length === 0) return -1;\n return this.path[this.path.length - 1].counter ?? 0;\n }\n\n /**\n * Get current node's sibling index (alias for getPosition).\n * @returns {number}\n * @deprecated Use getPosition() or getCounter() instead\n */\n getIndex() {\n return this.getPosition();\n }\n\n /**\n * Get current path depth.\n * @returns {number}\n */\n getDepth() {\n return this.path.length;\n }\n\n /**\n * Get path as string.\n * @param {string} [separator] - Optional separator (uses default if not provided)\n * @param {boolean} [includeNamespace=true]\n * @returns {string}\n */\n toString(separator, includeNamespace = true) {\n const sep = separator || this.separator;\n const isDefault = (sep === this.separator && includeNamespace === true);\n\n if (isDefault) {\n if (this._pathStringCache !== null) {\n return this._pathStringCache;\n }\n const result = this.path.map(n =>\n (n.namespace) ? `${n.namespace}:${n.tag}` : n.tag\n ).join(sep);\n this._pathStringCache = result;\n return result;\n }\n\n return this.path.map(n =>\n (includeNamespace && n.namespace) ? `${n.namespace}:${n.tag}` : n.tag\n ).join(sep);\n }\n\n /**\n * Get path as array of tag names.\n * @returns {string[]}\n */\n toArray() {\n return this.path.map(n => n.tag);\n }\n\n /**\n * Reset the path to empty.\n */\n reset() {\n this._pathStringCache = null;\n this.path = [];\n this.siblingStacks = [];\n }\n\n /**\n * Match current path against an Expression.\n * @param {Expression} expression\n * @returns {boolean}\n */\n matches(expression) {\n const segments = expression.segments;\n\n if (segments.length === 0) {\n return false;\n }\n\n if (expression.hasDeepWildcard()) {\n return this._matchWithDeepWildcard(segments);\n }\n\n return this._matchSimple(segments);\n }\n\n /**\n * @private\n */\n _matchSimple(segments) {\n if (this.path.length !== segments.length) {\n return false;\n }\n\n for (let i = 0; i < segments.length; i++) {\n if (!this._matchSegment(segments[i], this.path[i], i === this.path.length - 1)) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * @private\n */\n _matchWithDeepWildcard(segments) {\n let pathIdx = this.path.length - 1;\n let segIdx = segments.length - 1;\n\n while (segIdx >= 0 && pathIdx >= 0) {\n const segment = segments[segIdx];\n\n if (segment.type === 'deep-wildcard') {\n segIdx--;\n\n if (segIdx < 0) {\n return true;\n }\n\n const nextSeg = segments[segIdx];\n let found = false;\n\n for (let i = pathIdx; i >= 0; i--) {\n if (this._matchSegment(nextSeg, this.path[i], i === this.path.length - 1)) {\n pathIdx = i - 1;\n segIdx--;\n found = true;\n break;\n }\n }\n\n if (!found) {\n return false;\n }\n } else {\n if (!this._matchSegment(segment, this.path[pathIdx], pathIdx === this.path.length - 1)) {\n return false;\n }\n pathIdx--;\n segIdx--;\n }\n }\n\n return segIdx < 0;\n }\n\n /**\n * @private\n */\n _matchSegment(segment, node, isCurrentNode) {\n if (segment.tag !== '*' && segment.tag !== node.tag) {\n return false;\n }\n\n if (segment.namespace !== undefined) {\n if (segment.namespace !== '*' && segment.namespace !== node.namespace) {\n return false;\n }\n }\n\n if (segment.attrName !== undefined) {\n if (!isCurrentNode) {\n return false;\n }\n\n if (!node.values || !(segment.attrName in node.values)) {\n return false;\n }\n\n if (segment.attrValue !== undefined) {\n if (String(node.values[segment.attrName]) !== String(segment.attrValue)) {\n return false;\n }\n }\n }\n\n if (segment.position !== undefined) {\n if (!isCurrentNode) {\n return false;\n }\n\n const counter = node.counter ?? 0;\n\n if (segment.position === 'first' && counter !== 0) {\n return false;\n } else if (segment.position === 'odd' && counter % 2 !== 1) {\n return false;\n } else if (segment.position === 'even' && counter % 2 !== 0) {\n return false;\n } else if (segment.position === 'nth' && counter !== segment.positionValue) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Match any expression in the given set against the current path.\n * @param {ExpressionSet} exprSet\n * @returns {boolean}\n */\n matchesAny(exprSet) {\n return exprSet.matchesAny(this);\n }\n\n /**\n * Create a snapshot of current state.\n * @returns {Object}\n */\n snapshot() {\n return {\n path: this.path.map(node => ({ ...node })),\n siblingStacks: this.siblingStacks.map(map => new Map(map))\n };\n }\n\n /**\n * Restore state from snapshot.\n * @param {Object} snapshot\n */\n restore(snapshot) {\n this._pathStringCache = null;\n this.path = snapshot.path.map(node => ({ ...node }));\n this.siblingStacks = snapshot.siblingStacks.map(map => new Map(map));\n }\n\n /**\n * Return the read-only {@link MatcherView} for this matcher.\n *\n * The same instance is returned on every call — no allocation occurs.\n * It always reflects the current parser state and is safe to pass to\n * user callbacks without risk of accidental mutation.\n *\n * @returns {MatcherView}\n *\n * @example\n * const view = matcher.readOnly();\n * // pass view to callbacks — it stays in sync automatically\n * view.matches(expr); // ✓\n * view.getCurrentTag(); // ✓\n * // view.push(...) // ✗ method does not exist — caught by TypeScript\n */\n readOnly() {\n return this._view;\n }\n}","'use strict';\n///@ts-check\n\nimport { getAllMatches, isExist, DANGEROUS_PROPERTY_NAMES, criticalProperties } from '../util.js';\nimport xmlNode from './xmlNode.js';\nimport DocTypeReader from './DocTypeReader.js';\nimport toNumber from \"strnum\";\nimport getIgnoreAttributesFn from \"../ignoreAttributes.js\";\nimport { Expression, Matcher } from 'path-expression-matcher';\nimport { ExpressionSet } from 'path-expression-matcher';\nimport { EntityDecoder, XML, CURRENCY, COMMON_HTML } from '@nodable/entities';\n\n// const regx =\n// '<((!\\\\[CDATA\\\\[([\\\\s\\\\S]*?)(]]>))|((NAME:)?(NAME))([^>]*)>|((\\\\/)(NAME)\\\\s*>))([^<]*)'\n// .replace(/NAME/g, util.nameRegexp);\n\n//const tagsRegx = new RegExp(\"<(\\\\/?[\\\\w:\\\\-\\._]+)([^>]*)>(\\\\s*\"+cdataRegx+\")*([^<]+)?\",\"g\");\n//const tagsRegx = new RegExp(\"<(\\\\/?)((\\\\w*:)?([\\\\w:\\\\-\\._]+))([^>]*)>([^<]*)(\"+cdataRegx+\"([^<]*))*([^<]+)?\",\"g\");\n\n// Helper functions for attribute and namespace handling\n\n/**\n * Extract raw attributes (without prefix) from prefixed attribute map\n * @param {object} prefixedAttrs - Attributes with prefix from buildAttributesMap\n * @param {object} options - Parser options containing attributeNamePrefix\n * @returns {object} Raw attributes for matcher\n */\nfunction extractRawAttributes(prefixedAttrs, options) {\n if (!prefixedAttrs) return {};\n\n // Handle attributesGroupName option\n const attrs = options.attributesGroupName\n ? prefixedAttrs[options.attributesGroupName]\n : prefixedAttrs;\n\n if (!attrs) return {};\n\n const rawAttrs = {};\n for (const key in attrs) {\n // Remove the attribute prefix to get raw name\n if (key.startsWith(options.attributeNamePrefix)) {\n const rawName = key.substring(options.attributeNamePrefix.length);\n rawAttrs[rawName] = attrs[key];\n } else {\n // Attribute without prefix (shouldn't normally happen, but be safe)\n rawAttrs[key] = attrs[key];\n }\n }\n return rawAttrs;\n}\n\n/**\n * Extract namespace from raw tag name\n * @param {string} rawTagName - Tag name possibly with namespace (e.g., \"soap:Envelope\")\n * @returns {string|undefined} Namespace or undefined\n */\nfunction extractNamespace(rawTagName) {\n if (!rawTagName || typeof rawTagName !== 'string') return undefined;\n\n const colonIndex = rawTagName.indexOf(':');\n if (colonIndex !== -1 && colonIndex > 0) {\n const ns = rawTagName.substring(0, colonIndex);\n // Don't treat xmlns as a namespace\n if (ns !== 'xmlns') {\n return ns;\n }\n }\n return undefined;\n}\n\nexport default class OrderedObjParser {\n constructor(options, externalEntities) {\n this.options = options;\n this.currentNode = null;\n this.tagsNodeStack = [];\n this.parseXml = parseXml;\n this.parseTextData = parseTextData;\n this.resolveNameSpace = resolveNameSpace;\n this.buildAttributesMap = buildAttributesMap;\n this.isItStopNode = isItStopNode;\n this.replaceEntitiesValue = replaceEntitiesValue;\n this.readStopNodeData = readStopNodeData;\n this.saveTextToParentTag = saveTextToParentTag;\n this.addChild = addChild;\n this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes)\n this.entityExpansionCount = 0;\n this.currentExpandedLength = 0;\n let namedEntities = { ...XML };\n if (this.options.entityDecoder) {\n this.entityDecoder = this.options.entityDecoder\n } else {\n if (typeof this.options.htmlEntities === \"object\") namedEntities = this.options.htmlEntities;\n else if (this.options.htmlEntities === true) namedEntities = { ...COMMON_HTML, ...CURRENCY };\n this.entityDecoder = new EntityDecoder({\n namedEntities: { ...namedEntities, ...externalEntities },\n numericAllowed: this.options.htmlEntities,\n limit: {\n maxTotalExpansions: this.options.processEntities.maxTotalExpansions,\n maxExpandedLength: this.options.processEntities.maxExpandedLength,\n applyLimitsTo: this.options.processEntities.appliesTo,\n }\n //postCheck: resolved => resolved\n });\n }\n\n // Initialize path matcher for path-expression-matcher\n this.matcher = new Matcher();\n this.readonlyMatcher = this.matcher.readOnly();\n\n // Flag to track if current node is a stop node (optimization)\n this.isCurrentNodeStopNode = false;\n\n // Pre-compile stopNodes expressions\n this.stopNodeExpressionsSet = new ExpressionSet();\n const stopNodesOpts = this.options.stopNodes;\n if (stopNodesOpts && stopNodesOpts.length > 0) {\n for (let i = 0; i < stopNodesOpts.length; i++) {\n const stopNodeExp = stopNodesOpts[i];\n if (typeof stopNodeExp === 'string') {\n // Convert string to Expression object\n this.stopNodeExpressionsSet.add(new Expression(stopNodeExp));\n } else if (stopNodeExp instanceof Expression) {\n // Already an Expression object\n this.stopNodeExpressionsSet.add(stopNodeExp);\n }\n }\n this.stopNodeExpressionsSet.seal();\n }\n }\n\n}\n\n\n/**\n * @param {string} val\n * @param {string} tagName\n * @param {string|Matcher} jPath - jPath string or Matcher instance based on options.jPath\n * @param {boolean} dontTrim\n * @param {boolean} hasAttributes\n * @param {boolean} isLeafNode\n * @param {boolean} escapeEntities\n */\nfunction parseTextData(val, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) {\n const options = this.options;\n if (val !== undefined) {\n if (options.trimValues && !dontTrim) {\n val = val.trim();\n }\n if (val.length > 0) {\n if (!escapeEntities) val = this.replaceEntitiesValue(val, tagName, jPath);\n\n // Pass jPath string or matcher based on options.jPath setting\n const jPathOrMatcher = options.jPath ? jPath.toString() : jPath;\n const newval = options.tagValueProcessor(tagName, val, jPathOrMatcher, hasAttributes, isLeafNode);\n if (newval === null || newval === undefined) {\n //don't parse\n return val;\n } else if (typeof newval !== typeof val || newval !== val) {\n //overwrite\n return newval;\n } else if (options.trimValues) {\n return parseValue(val, options.parseTagValue, options.numberParseOptions);\n } else {\n const trimmedVal = val.trim();\n if (trimmedVal === val) {\n return parseValue(val, options.parseTagValue, options.numberParseOptions);\n } else {\n return val;\n }\n }\n }\n }\n}\n\nfunction resolveNameSpace(tagname) {\n if (this.options.removeNSPrefix) {\n const tags = tagname.split(':');\n const prefix = tagname.charAt(0) === '/' ? '/' : '';\n if (tags[0] === 'xmlns') {\n return '';\n }\n if (tags.length === 2) {\n tagname = prefix + tags[1];\n }\n }\n return tagname;\n}\n\n//TODO: change regex to capture NS\n//const attrsRegx = new RegExp(\"([\\\\w\\\\-\\\\.\\\\:]+)\\\\s*=\\\\s*(['\\\"])((.|\\n)*?)\\\\2\",\"gm\");\nconst attrsRegx = new RegExp('([^\\\\s=]+)\\\\s*(=\\\\s*([\\'\"])([\\\\s\\\\S]*?)\\\\3)?', 'gm');\n\nfunction buildAttributesMap(attrStr, jPath, tagName, force = false) {\n const options = this.options;\n if (force === true || (options.ignoreAttributes !== true && typeof attrStr === 'string')) {\n // attrStr = attrStr.replace(/\\r?\\n/g, ' ');\n //attrStr = attrStr || attrStr.trim();\n\n const matches = getAllMatches(attrStr, attrsRegx);\n const len = matches.length; //don't make it inline\n const attrs = {};\n\n // Pre-process values once: trim + entity replacement\n // Reused in both matcher update and second pass\n const processedVals = new Array(len);\n let hasRawAttrs = false;\n const rawAttrsForMatcher = {};\n\n for (let i = 0; i < len; i++) {\n const attrName = this.resolveNameSpace(matches[i][1]);\n const oldVal = matches[i][4];\n\n if (attrName.length && oldVal !== undefined) {\n let val = oldVal;\n if (options.trimValues) val = val.trim();\n val = this.replaceEntitiesValue(val, tagName, this.readonlyMatcher);\n processedVals[i] = val;\n\n rawAttrsForMatcher[attrName] = val;\n hasRawAttrs = true;\n }\n }\n\n // Update matcher ONCE before second pass, if applicable\n if (hasRawAttrs && typeof jPath === 'object' && jPath.updateCurrent) {\n jPath.updateCurrent(rawAttrsForMatcher);\n }\n\n // Hoist toString() once — path doesn't change during attribute processing\n const jPathStr = options.jPath ? jPath.toString() : this.readonlyMatcher;\n\n // Second pass: apply processors, build final attrs\n let hasAttrs = false;\n for (let i = 0; i < len; i++) {\n const attrName = this.resolveNameSpace(matches[i][1]);\n\n if (this.ignoreAttributesFn(attrName, jPathStr)) continue;\n\n let aName = options.attributeNamePrefix + attrName;\n\n if (attrName.length) {\n if (options.transformAttributeName) {\n aName = options.transformAttributeName(aName);\n }\n aName = sanitizeName(aName, options);\n\n if (matches[i][4] !== undefined) {\n // Reuse already-processed value — no double entity replacement\n const oldVal = processedVals[i];\n\n const newVal = options.attributeValueProcessor(attrName, oldVal, jPathStr);\n if (newVal === null || newVal === undefined) {\n attrs[aName] = oldVal;\n } else if (typeof newVal !== typeof oldVal || newVal !== oldVal) {\n attrs[aName] = newVal;\n } else {\n attrs[aName] = parseValue(oldVal, options.parseAttributeValue, options.numberParseOptions);\n }\n hasAttrs = true;\n } else if (options.allowBooleanAttributes) {\n attrs[aName] = true;\n hasAttrs = true;\n }\n }\n }\n\n if (!hasAttrs) return;\n\n if (options.attributesGroupName && !options.preserveOrder) {\n const attrCollection = {};\n attrCollection[options.attributesGroupName] = attrs;\n return attrCollection;\n }\n return attrs;\n }\n}\nconst parseXml = function (xmlData) {\n xmlData = xmlData.replace(/\\r\\n?/g, \"\\n\"); //TODO: remove this line\n const xmlObj = new xmlNode('!xml');\n let currentNode = xmlObj;\n let textData = \"\";\n\n // Reset matcher for new document\n this.matcher.reset();\n this.entityDecoder.reset();\n\n // Reset entity expansion counters for this document\n this.entityExpansionCount = 0;\n this.currentExpandedLength = 0;\n const options = this.options;\n const docTypeReader = new DocTypeReader(options.processEntities);\n const xmlLen = xmlData.length;\n for (let i = 0; i < xmlLen; i++) {//for each char in XML data\n const ch = xmlData[i];\n if (ch === '<') {\n // const nextIndex = i+1;\n // const _2ndChar = xmlData[nextIndex];\n const c1 = xmlData.charCodeAt(i + 1);\n if (c1 === 47) {//Closing Tag '/'\n const closeIndex = findClosingIndex(xmlData, \">\", i, \"Closing Tag is not closed.\")\n let tagName = xmlData.substring(i + 2, closeIndex).trim();\n\n if (options.removeNSPrefix) {\n const colonIndex = tagName.indexOf(\":\");\n if (colonIndex !== -1) {\n tagName = tagName.substr(colonIndex + 1);\n }\n }\n\n tagName = transformTagName(options.transformTagName, tagName, \"\", options).tagName;\n\n if (currentNode) {\n textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);\n }\n\n //check if last tag of nested tag was unpaired tag\n const lastTagName = this.matcher.getCurrentTag();\n if (tagName && options.unpairedTagsSet.has(tagName)) {\n throw new Error(`Unpaired tag can not be used as closing tag: </${tagName}>`);\n }\n if (lastTagName && options.unpairedTagsSet.has(lastTagName)) {\n // Pop the unpaired tag\n this.matcher.pop();\n this.tagsNodeStack.pop();\n }\n // Pop the closing tag\n this.matcher.pop();\n this.isCurrentNodeStopNode = false; // Reset flag when closing tag\n\n currentNode = this.tagsNodeStack.pop();//avoid recursion, set the parent tag scope\n textData = \"\";\n i = closeIndex;\n } else if (c1 === 63) { //'?'\n\n let tagData = readTagExp(xmlData, i, false, \"?>\");\n if (!tagData) throw new Error(\"Pi Tag is not closed.\");\n\n textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);\n const attsMap = this.buildAttributesMap(tagData.tagExp, this.matcher, tagData.tagName, true);\n if (attsMap) {\n const ver = attsMap[this.options.attributeNamePrefix + \"version\"];\n this.entityDecoder.setXmlVersion(Number(ver) || 1.0);\n docTypeReader.setXmlVersion(Number(ver) || 1.0);\n }\n if ((options.ignoreDeclaration && tagData.tagName === \"?xml\") || options.ignorePiTags) {\n //do nothing\n } else {\n\n const childNode = new xmlNode(tagData.tagName);\n childNode.add(options.textNodeName, \"\");\n\n if (tagData.tagName !== tagData.tagExp && tagData.attrExpPresent && options.ignoreAttributes !== true) {\n childNode[\":@\"] = attsMap\n }\n this.addChild(currentNode, childNode, this.readonlyMatcher, i);\n }\n\n\n i = tagData.closeIndex + 1;\n } else if (c1 === 33\n && xmlData.charCodeAt(i + 2) === 45\n && xmlData.charCodeAt(i + 3) === 45) { //'!--'\n const endIndex = findClosingIndex(xmlData, \"-->\", i + 4, \"Comment is not closed.\")\n if (options.commentPropName) {\n const comment = xmlData.substring(i + 4, endIndex - 2);\n\n textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);\n\n currentNode.add(options.commentPropName, [{ [options.textNodeName]: comment }]);\n }\n i = endIndex;\n } else if (c1 === 33\n && xmlData.charCodeAt(i + 2) === 68) { //'!D'\n const result = docTypeReader.readDocType(xmlData, i);\n this.entityDecoder.addInputEntities(result.entities);\n i = result.i;\n } else if (c1 === 33\n && xmlData.charCodeAt(i + 2) === 91) { // '!['\n const closeIndex = findClosingIndex(xmlData, \"]]>\", i, \"CDATA is not closed.\") - 2;\n const tagExp = xmlData.substring(i + 9, closeIndex);\n\n textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);\n\n let val = this.parseTextData(tagExp, currentNode.tagname, this.readonlyMatcher, true, false, true, true);\n if (val == undefined) val = \"\";\n\n //cdata should be set even if it is 0 length string\n if (options.cdataPropName) {\n currentNode.add(options.cdataPropName, [{ [options.textNodeName]: tagExp }]);\n } else {\n currentNode.add(options.textNodeName, val);\n }\n\n i = closeIndex + 2;\n } else {//Opening tag\n let result = readTagExp(xmlData, i, options.removeNSPrefix);\n\n // Safety check: readTagExp can return undefined\n if (!result) {\n // Log context for debugging\n const context = xmlData.substring(Math.max(0, i - 50), Math.min(xmlLen, i + 50));\n throw new Error(`readTagExp returned undefined at position ${i}. Context: \"${context}\"`);\n }\n\n let tagName = result.tagName;\n const rawTagName = result.rawTagName;\n let tagExp = result.tagExp;\n let attrExpPresent = result.attrExpPresent;\n let closeIndex = result.closeIndex;\n\n ({ tagName, tagExp } = transformTagName(options.transformTagName, tagName, tagExp, options));\n\n if (options.strictReservedNames &&\n (tagName === options.commentPropName\n || tagName === options.cdataPropName\n || tagName === options.textNodeName\n || tagName === options.attributesGroupName\n )) {\n throw new Error(`Invalid tag name: ${tagName}`);\n }\n\n //save text as child node\n if (currentNode && textData) {\n if (currentNode.tagname !== '!xml') {\n //when nested tag is found\n textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher, false);\n }\n }\n\n //check if last tag was unpaired tag\n const lastTag = currentNode;\n if (lastTag && options.unpairedTagsSet.has(lastTag.tagname)) {\n currentNode = this.tagsNodeStack.pop();\n this.matcher.pop();\n }\n\n // Clean up self-closing syntax BEFORE processing attributes\n // This is where tagExp gets the trailing / removed\n let isSelfClosing = false;\n if (tagExp.length > 0 && tagExp.lastIndexOf(\"/\") === tagExp.length - 1) {\n isSelfClosing = true;\n if (tagName[tagName.length - 1] === \"/\") {\n tagName = tagName.substr(0, tagName.length - 1);\n tagExp = tagName;\n } else {\n tagExp = tagExp.substr(0, tagExp.length - 1);\n }\n\n // Re-check attrExpPresent after cleaning\n attrExpPresent = (tagName !== tagExp);\n }\n\n // Now process attributes with CLEAN tagExp (no trailing /)\n let prefixedAttrs = null;\n let rawAttrs = {};\n let namespace = undefined;\n\n // Extract namespace from rawTagName\n namespace = extractNamespace(rawTagName);\n\n // Push tag to matcher FIRST (with empty attrs for now) so callbacks see correct path\n if (tagName !== xmlObj.tagname) {\n this.matcher.push(tagName, {}, namespace);\n }\n\n // Now build attributes - callbacks will see correct matcher state\n if (tagName !== tagExp && attrExpPresent) {\n // Build attributes (returns prefixed attributes for the tree)\n // Note: buildAttributesMap now internally updates the matcher with raw attributes\n prefixedAttrs = this.buildAttributesMap(tagExp, this.matcher, tagName);\n\n if (prefixedAttrs) {\n // Extract raw attributes (without prefix) for our use\n //TODO: seems a performance overhead\n rawAttrs = extractRawAttributes(prefixedAttrs, options);\n }\n }\n\n // Now check if this is a stop node (after attributes are set)\n if (tagName !== xmlObj.tagname) {\n this.isCurrentNodeStopNode = this.isItStopNode();\n }\n\n const startIndex = i;\n if (this.isCurrentNodeStopNode) {\n let tagContent = \"\";\n\n // For self-closing tags, content is empty\n if (isSelfClosing) {\n i = result.closeIndex;\n }\n //unpaired tag\n else if (options.unpairedTagsSet.has(tagName)) {\n i = result.closeIndex;\n }\n //normal tag\n else {\n //read until closing tag is found\n const result = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1);\n if (!result) throw new Error(`Unexpected end of ${rawTagName}`);\n i = result.i;\n tagContent = result.tagContent;\n }\n\n const childNode = new xmlNode(tagName);\n\n if (prefixedAttrs) {\n childNode[\":@\"] = prefixedAttrs;\n }\n\n // For stop nodes, store raw content as-is without any processing\n childNode.add(options.textNodeName, tagContent);\n\n this.matcher.pop(); // Pop the stop node tag\n this.isCurrentNodeStopNode = false; // Reset flag\n\n this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);\n } else {\n //selfClosing tag\n if (isSelfClosing) {\n ({ tagName, tagExp } = transformTagName(options.transformTagName, tagName, tagExp, options));\n\n const childNode = new xmlNode(tagName);\n if (prefixedAttrs) {\n childNode[\":@\"] = prefixedAttrs;\n }\n this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);\n this.matcher.pop(); // Pop self-closing tag\n this.isCurrentNodeStopNode = false; // Reset flag\n }\n else if (options.unpairedTagsSet.has(tagName)) {//unpaired tag\n const childNode = new xmlNode(tagName);\n if (prefixedAttrs) {\n childNode[\":@\"] = prefixedAttrs;\n }\n this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);\n this.matcher.pop(); // Pop unpaired tag\n this.isCurrentNodeStopNode = false; // Reset flag\n i = result.closeIndex;\n // Continue to next iteration without changing currentNode\n continue;\n }\n //opening tag\n else {\n const childNode = new xmlNode(tagName);\n if (this.tagsNodeStack.length > options.maxNestedTags) {\n throw new Error(\"Maximum nested tags exceeded\");\n }\n this.tagsNodeStack.push(currentNode);\n\n if (prefixedAttrs) {\n childNode[\":@\"] = prefixedAttrs;\n }\n this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);\n currentNode = childNode;\n }\n textData = \"\";\n i = closeIndex;\n }\n }\n } else {\n textData += xmlData[i];\n }\n }\n return xmlObj.child;\n}\n\nfunction addChild(currentNode, childNode, matcher, startIndex) {\n // unset startIndex if not requested\n if (!this.options.captureMetaData) startIndex = undefined;\n\n // Pass jPath string or matcher based on options.jPath setting\n const jPathOrMatcher = this.options.jPath ? matcher.toString() : matcher;\n const result = this.options.updateTag(childNode.tagname, jPathOrMatcher, childNode[\":@\"])\n if (result === false) {\n //do nothing\n } else if (typeof result === \"string\") {\n childNode.tagname = result\n currentNode.addChild(childNode, startIndex);\n } else {\n currentNode.addChild(childNode, startIndex);\n }\n}\n\n/**\n * @param {object} val - Entity object with regex and val properties\n * @param {string} tagName - Tag name\n * @param {string|Matcher} jPath - jPath string or Matcher instance based on options.jPath\n */\nfunction replaceEntitiesValue(val, tagName, jPath) {\n const entityConfig = this.options.processEntities;\n\n if (!entityConfig || !entityConfig.enabled) {\n return val;\n }\n\n // Check if tag is allowed to contain entities\n if (entityConfig.allowedTags) {\n const jPathOrMatcher = this.options.jPath ? jPath.toString() : jPath;\n const allowed = Array.isArray(entityConfig.allowedTags)\n ? entityConfig.allowedTags.includes(tagName)\n : entityConfig.allowedTags(tagName, jPathOrMatcher);\n\n if (!allowed) {\n return val;\n }\n }\n\n // Apply custom tag filter if provided\n if (entityConfig.tagFilter) {\n const jPathOrMatcher = this.options.jPath ? jPath.toString() : jPath;\n if (!entityConfig.tagFilter(tagName, jPathOrMatcher)) {\n return val; // Skip based on custom filter\n }\n }\n\n return this.entityDecoder.decode(val);\n}\n\n\nfunction saveTextToParentTag(textData, parentNode, matcher, isLeafNode) {\n if (textData) { //store previously collected data as textNode\n if (isLeafNode === undefined) isLeafNode = parentNode.child.length === 0\n\n textData = this.parseTextData(textData,\n parentNode.tagname,\n matcher,\n false,\n parentNode[\":@\"] ? Object.keys(parentNode[\":@\"]).length !== 0 : false,\n isLeafNode);\n\n if (textData !== undefined && textData !== \"\")\n parentNode.add(this.options.textNodeName, textData);\n textData = \"\";\n }\n return textData;\n}\n\n/**\n * @param {Array<Expression>} stopNodeExpressions - Array of compiled Expression objects\n * @param {Matcher} matcher - Current path matcher\n */\nfunction isItStopNode() {\n if (this.stopNodeExpressionsSet.size === 0) return false;\n\n return this.matcher.matchesAny(this.stopNodeExpressionsSet);\n}\n\n/**\n * Returns the tag Expression and where it is ending handling single-double quotes situation\n * @param {string} xmlData \n * @param {number} i starting index\n * @returns \n */\nfunction tagExpWithClosingIndex(xmlData, i, closingChar = \">\") {\n //TODO: ignore boolean attributes in tag expression\n //TODO: if ignore attributes, dont read full attribute expression but the end. But read for xml declaration\n let attrBoundary = 0;\n const len = xmlData.length;\n const closeCode0 = closingChar.charCodeAt(0);\n const closeCode1 = closingChar.length > 1 ? closingChar.charCodeAt(1) : -1;\n\n let result = '';\n let segmentStart = i;\n\n for (let index = i; index < len; index++) {\n const code = xmlData.charCodeAt(index);\n\n if (attrBoundary) {\n if (code === attrBoundary) attrBoundary = 0;\n } else if (code === 34 || code === 39) { // \" or '\n attrBoundary = code;\n } else if (code === closeCode0) {\n if (closeCode1 !== -1) {\n if (xmlData.charCodeAt(index + 1) === closeCode1) {\n result += xmlData.substring(segmentStart, index);\n return { data: result, index };\n }\n } else {\n result += xmlData.substring(segmentStart, index);\n return { data: result, index };\n }\n } else if (code === 9 && !attrBoundary) { // \\t - only replace with space outside attribute values\n // Flush accumulated segment, add space, start new segment\n result += xmlData.substring(segmentStart, index) + ' ';\n segmentStart = index + 1;\n }\n }\n}\n\nfunction findClosingIndex(xmlData, str, i, errMsg) {\n const closingIndex = xmlData.indexOf(str, i);\n if (closingIndex === -1) {\n throw new Error(errMsg)\n } else {\n return closingIndex + str.length - 1;\n }\n}\n\nfunction findClosingChar(xmlData, char, i, errMsg) {\n const closingIndex = xmlData.indexOf(char, i);\n if (closingIndex === -1) throw new Error(errMsg);\n return closingIndex; // no offset needed\n}\n\nfunction readTagExp(xmlData, i, removeNSPrefix, closingChar = \">\") {\n const result = tagExpWithClosingIndex(xmlData, i + 1, closingChar);\n if (!result) return;\n let tagExp = result.data;\n const closeIndex = result.index;\n const separatorIndex = tagExp.search(/\\s/);\n let tagName = tagExp;\n let attrExpPresent = true;\n if (separatorIndex !== -1) {//separate tag name and attributes expression\n tagName = tagExp.substring(0, separatorIndex);\n tagExp = tagExp.substring(separatorIndex + 1).trimStart();\n }\n\n const rawTagName = tagName;\n if (removeNSPrefix) {\n const colonIndex = tagName.indexOf(\":\");\n if (colonIndex !== -1) {\n tagName = tagName.substr(colonIndex + 1);\n attrExpPresent = tagName !== result.data.substr(colonIndex + 1);\n }\n }\n\n return {\n tagName: tagName,\n tagExp: tagExp,\n closeIndex: closeIndex,\n attrExpPresent: attrExpPresent,\n rawTagName: rawTagName,\n }\n}\n/**\n * find paired tag for a stop node\n * @param {string} xmlData \n * @param {string} tagName \n * @param {number} i \n */\nfunction readStopNodeData(xmlData, tagName, i) {\n const startIndex = i;\n // Starting at 1 since we already have an open tag\n let openTagCount = 1;\n\n const xmllen = xmlData.length;\n for (; i < xmllen; i++) {\n if (xmlData[i] === \"<\") {\n const c1 = xmlData.charCodeAt(i + 1);\n if (c1 === 47) {//close tag '/'\n const closeIndex = findClosingChar(xmlData, \">\", i, `${tagName} is not closed`);\n let closeTagName = xmlData.substring(i + 2, closeIndex).trim();\n if (closeTagName === tagName) {\n openTagCount--;\n if (openTagCount === 0) {\n return {\n tagContent: xmlData.substring(startIndex, i),\n i: closeIndex\n }\n }\n }\n i = closeIndex;\n } else if (c1 === 63) { //?\n const closeIndex = findClosingIndex(xmlData, \"?>\", i + 1, \"StopNode is not closed.\")\n i = closeIndex;\n } else if (c1 === 33\n && xmlData.charCodeAt(i + 2) === 45\n && xmlData.charCodeAt(i + 3) === 45) { // '!--'\n const closeIndex = findClosingIndex(xmlData, \"-->\", i + 3, \"StopNode is not closed.\")\n i = closeIndex;\n } else if (c1 === 33\n && xmlData.charCodeAt(i + 2) === 91) { // '!['\n const closeIndex = findClosingIndex(xmlData, \"]]>\", i, \"StopNode is not closed.\") - 2;\n i = closeIndex;\n } else {\n const tagData = readTagExp(xmlData, i, false)\n\n if (tagData) {\n const openTagName = tagData && tagData.tagName;\n if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length - 1] !== \"/\") {\n openTagCount++;\n }\n i = tagData.closeIndex;\n }\n }\n }\n }//end for loop\n}\n\nfunction parseValue(val, shouldParse, options) {\n if (shouldParse && typeof val === 'string') {\n //console.log(options)\n const newval = val.trim();\n if (newval === 'true') return true;\n else if (newval === 'false') return false;\n else return toNumber(val, options);\n } else {\n if (isExist(val)) {\n return val;\n } else {\n return '';\n }\n }\n}\n\nfunction fromCodePoint(str, base, prefix) {\n const codePoint = Number.parseInt(str, base);\n\n if (codePoint >= 0 && codePoint <= 0x10FFFF) {\n return String.fromCodePoint(codePoint);\n } else {\n return prefix + str + \";\";\n }\n}\n\nfunction transformTagName(fn, tagName, tagExp, options) {\n if (fn) {\n const newTagName = fn(tagName);\n if (tagExp === tagName) {\n tagExp = newTagName\n }\n tagName = newTagName;\n }\n tagName = sanitizeName(tagName, options);\n return { tagName, tagExp };\n}\n\n\n\nfunction sanitizeName(name, options) {\n if (criticalProperties.includes(name)) {\n throw new Error(`[SECURITY] Invalid name: \"${name}\" is a reserved JavaScript keyword that could cause prototype pollution`);\n } else if (DANGEROUS_PROPERTY_NAMES.includes(name)) {\n return options.onDangerousProperty(name);\n }\n return name;\n}","'use strict';\n\nimport XmlNode from './xmlNode.js';\nimport { Matcher } from 'path-expression-matcher';\n\nconst METADATA_SYMBOL = XmlNode.getMetaDataSymbol();\n\n/**\n * Helper function to strip attribute prefix from attribute map\n * @param {object} attrs - Attributes with prefix (e.g., {\"@_class\": \"code\"})\n * @param {string} prefix - Attribute prefix to remove (e.g., \"@_\")\n * @returns {object} Attributes without prefix (e.g., {\"class\": \"code\"})\n */\nfunction stripAttributePrefix(attrs, prefix) {\n if (!attrs || typeof attrs !== 'object') return {};\n if (!prefix) return attrs;\n\n const rawAttrs = {};\n for (const key in attrs) {\n if (key.startsWith(prefix)) {\n const rawName = key.substring(prefix.length);\n rawAttrs[rawName] = attrs[key];\n } else {\n // Attribute without prefix (shouldn't normally happen, but be safe)\n rawAttrs[key] = attrs[key];\n }\n }\n return rawAttrs;\n}\n\n/**\n * \n * @param {array} node \n * @param {any} options \n * @param {Matcher} matcher - Path matcher instance\n * @returns \n */\nexport default function prettify(node, options, matcher, readonlyMatcher) {\n return compress(node, options, matcher, readonlyMatcher);\n}\n\n/**\n * @param {array} arr \n * @param {object} options \n * @param {Matcher} matcher - Path matcher instance\n * @returns object\n */\nfunction compress(arr, options, matcher, readonlyMatcher) {\n let text;\n const compressedObj = {}; //This is intended to be a plain object\n for (let i = 0; i < arr.length; i++) {\n const tagObj = arr[i];\n const property = propName(tagObj);\n\n // Push current property to matcher WITH RAW ATTRIBUTES (no prefix)\n if (property !== undefined && property !== options.textNodeName) {\n const rawAttrs = stripAttributePrefix(\n tagObj[\":@\"] || {},\n options.attributeNamePrefix\n );\n matcher.push(property, rawAttrs);\n }\n\n if (property === options.textNodeName) {\n if (text === undefined) text = tagObj[property];\n else text += \"\" + tagObj[property];\n } else if (property === undefined) {\n continue;\n } else if (tagObj[property]) {\n\n let val = compress(tagObj[property], options, matcher, readonlyMatcher);\n const isLeaf = isLeafTag(val, options);\n\n if (Object.keys(val).length === 0 && options.alwaysCreateTextNode) {\n val[options.textNodeName] = \"\";\n }\n\n if (tagObj[\":@\"]) {\n assignAttributes(val, tagObj[\":@\"], readonlyMatcher, options);\n } else if (Object.keys(val).length === 1 && val[options.textNodeName] !== undefined && !options.alwaysCreateTextNode) {\n val = val[options.textNodeName];\n } else if (Object.keys(val).length === 0) {\n if (options.alwaysCreateTextNode) val[options.textNodeName] = \"\";\n else val = \"\";\n }\n\n if (tagObj[METADATA_SYMBOL] !== undefined && typeof val === \"object\" && val !== null) {\n val[METADATA_SYMBOL] = tagObj[METADATA_SYMBOL]; // copy over metadata\n }\n\n\n if (compressedObj[property] !== undefined && Object.prototype.hasOwnProperty.call(compressedObj, property)) {\n if (!Array.isArray(compressedObj[property])) {\n compressedObj[property] = [compressedObj[property]];\n }\n compressedObj[property].push(val);\n } else {\n //TODO: if a node is not an array, then check if it should be an array\n //also determine if it is a leaf node\n\n // Pass jPath string or readonlyMatcher based on options.jPath setting\n const jPathOrMatcher = options.jPath ? readonlyMatcher.toString() : readonlyMatcher;\n if (options.isArray(property, jPathOrMatcher, isLeaf)) {\n compressedObj[property] = [val];\n } else {\n compressedObj[property] = val;\n }\n }\n\n // Pop property from matcher after processing\n if (property !== undefined && property !== options.textNodeName) {\n matcher.pop();\n }\n }\n\n }\n // if(text && text.length > 0) compressedObj[options.textNodeName] = text;\n if (typeof text === \"string\") {\n if (text.length > 0) compressedObj[options.textNodeName] = text;\n } else if (text !== undefined) compressedObj[options.textNodeName] = text;\n\n\n return compressedObj;\n}\n\nfunction propName(obj) {\n const keys = Object.keys(obj);\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i];\n if (key !== \":@\") return key;\n }\n}\n\nfunction assignAttributes(obj, attrMap, readonlyMatcher, options) {\n if (attrMap) {\n const keys = Object.keys(attrMap);\n const len = keys.length; //don't make it inline\n for (let i = 0; i < len; i++) {\n const atrrName = keys[i]; // This is the PREFIXED name (e.g., \"@_class\")\n\n // Strip prefix for matcher path (for isArray callback)\n const rawAttrName = atrrName.startsWith(options.attributeNamePrefix)\n ? atrrName.substring(options.attributeNamePrefix.length)\n : atrrName;\n\n // For attributes, we need to create a temporary path\n // Pass jPath string or matcher based on options.jPath setting\n const jPathOrMatcher = options.jPath\n ? readonlyMatcher.toString() + \".\" + rawAttrName\n : readonlyMatcher;\n\n if (options.isArray(atrrName, jPathOrMatcher, true, true)) {\n obj[atrrName] = [attrMap[atrrName]];\n } else {\n obj[atrrName] = attrMap[atrrName];\n }\n }\n }\n}\n\nfunction isLeafTag(obj, options) {\n const { textNodeName } = options;\n const propCount = Object.keys(obj).length;\n\n if (propCount === 0) {\n return true;\n }\n\n if (\n propCount === 1 &&\n (obj[textNodeName] || typeof obj[textNodeName] === \"boolean\" || obj[textNodeName] === 0)\n ) {\n return true;\n }\n\n return false;\n}","'use strict';\n\nimport { getAllMatches, isName } from './util.js';\n\nconst defaultOptions = {\n allowBooleanAttributes: false, //A tag can have attributes without any value\n unpairedTags: []\n};\n\n//const tagsPattern = new RegExp(\"<\\\\/?([\\\\w:\\\\-_\\.]+)\\\\s*\\/?>\",\"g\");\nexport function validate(xmlData, options) {\n options = Object.assign({}, defaultOptions, options);\n\n //xmlData = xmlData.replace(/(\\r\\n|\\n|\\r)/gm,\"\");//make it single line\n //xmlData = xmlData.replace(/(^\\s*<\\?xml.*?\\?>)/g,\"\");//Remove XML starting tag\n //xmlData = xmlData.replace(/(<!DOCTYPE[\\s\\w\\\"\\.\\/\\-\\:]+(\\[.*\\])*\\s*>)/g,\"\");//Remove DOCTYPE\n const tags = [];\n let tagFound = false;\n\n //indicates that the root tag has been closed (aka. depth 0 has been reached)\n let reachedRoot = false;\n\n if (xmlData[0] === '\\ufeff') {\n // check for byte order mark (BOM)\n xmlData = xmlData.substr(1);\n }\n\n for (let i = 0; i < xmlData.length; i++) {\n\n if (xmlData[i] === '<' && xmlData[i + 1] === '?') {\n i += 2;\n i = readPI(xmlData, i);\n if (i.err) return i;\n } else if (xmlData[i] === '<') {\n //starting of tag\n //read until you reach to '>' avoiding any '>' in attribute value\n let tagStartPos = i;\n i++;\n\n if (xmlData[i] === '!') {\n i = readCommentAndCDATA(xmlData, i);\n continue;\n } else {\n let closingTag = false;\n if (xmlData[i] === '/') {\n //closing tag\n closingTag = true;\n i++;\n }\n //read tagname\n let tagName = '';\n for (; i < xmlData.length &&\n xmlData[i] !== '>' &&\n xmlData[i] !== ' ' &&\n xmlData[i] !== '\\t' &&\n xmlData[i] !== '\\n' &&\n xmlData[i] !== '\\r'; i++\n ) {\n tagName += xmlData[i];\n }\n tagName = tagName.trim();\n //console.log(tagName);\n\n if (tagName[tagName.length - 1] === '/') {\n //self closing tag without attributes\n tagName = tagName.substring(0, tagName.length - 1);\n //continue;\n i--;\n }\n if (!validateTagName(tagName)) {\n let msg;\n if (tagName.trim().length === 0) {\n msg = \"Invalid space after '<'.\";\n } else {\n msg = \"Tag '\" + tagName + \"' is an invalid name.\";\n }\n return getErrorObject('InvalidTag', msg, getLineNumberForPosition(xmlData, i));\n }\n\n const result = readAttributeStr(xmlData, i);\n if (result === false) {\n return getErrorObject('InvalidAttr', \"Attributes for '\" + tagName + \"' have open quote.\", getLineNumberForPosition(xmlData, i));\n }\n let attrStr = result.value;\n i = result.index;\n\n if (attrStr[attrStr.length - 1] === '/') {\n //self closing tag\n const attrStrStart = i - attrStr.length;\n attrStr = attrStr.substring(0, attrStr.length - 1);\n const isValid = validateAttributeString(attrStr, options);\n if (isValid === true) {\n tagFound = true;\n //continue; //text may presents after self closing tag\n } else {\n //the result from the nested function returns the position of the error within the attribute\n //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute\n //this gives us the absolute index in the entire xml, which we can use to find the line at last\n return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid.err.line));\n }\n } else if (closingTag) {\n if (!result.tagClosed) {\n return getErrorObject('InvalidTag', \"Closing tag '\" + tagName + \"' doesn't have proper closing.\", getLineNumberForPosition(xmlData, i));\n } else if (attrStr.trim().length > 0) {\n return getErrorObject('InvalidTag', \"Closing tag '\" + tagName + \"' can't have attributes or invalid starting.\", getLineNumberForPosition(xmlData, tagStartPos));\n } else if (tags.length === 0) {\n return getErrorObject('InvalidTag', \"Closing tag '\" + tagName + \"' has not been opened.\", getLineNumberForPosition(xmlData, tagStartPos));\n } else {\n const otg = tags.pop();\n if (tagName !== otg.tagName) {\n let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos);\n return getErrorObject('InvalidTag',\n \"Expected closing tag '\" + otg.tagName + \"' (opened in line \" + openPos.line + \", col \" + openPos.col + \") instead of closing tag '\" + tagName + \"'.\",\n getLineNumberForPosition(xmlData, tagStartPos));\n }\n\n //when there are no more tags, we reached the root level.\n if (tags.length == 0) {\n reachedRoot = true;\n }\n }\n } else {\n const isValid = validateAttributeString(attrStr, options);\n if (isValid !== true) {\n //the result from the nested function returns the position of the error within the attribute\n //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute\n //this gives us the absolute index in the entire xml, which we can use to find the line at last\n return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, i - attrStr.length + isValid.err.line));\n }\n\n //if the root level has been reached before ...\n if (reachedRoot === true) {\n return getErrorObject('InvalidXml', 'Multiple possible root nodes found.', getLineNumberForPosition(xmlData, i));\n } else if (options.unpairedTags.indexOf(tagName) !== -1) {\n //don't push into stack\n } else {\n tags.push({ tagName, tagStartPos });\n }\n tagFound = true;\n }\n\n //skip tag text value\n //It may include comments and CDATA value\n for (i++; i < xmlData.length; i++) {\n if (xmlData[i] === '<') {\n if (xmlData[i + 1] === '!') {\n //comment or CADATA\n i++;\n i = readCommentAndCDATA(xmlData, i);\n continue;\n } else if (xmlData[i + 1] === '?') {\n i = readPI(xmlData, ++i);\n if (i.err) return i;\n } else {\n break;\n }\n } else if (xmlData[i] === '&') {\n const afterAmp = validateAmpersand(xmlData, i);\n if (afterAmp == -1)\n return getErrorObject('InvalidChar', \"char '&' is not expected.\", getLineNumberForPosition(xmlData, i));\n i = afterAmp;\n } else {\n if (reachedRoot === true && !isWhiteSpace(xmlData[i])) {\n return getErrorObject('InvalidXml', \"Extra text at the end\", getLineNumberForPosition(xmlData, i));\n }\n }\n } //end of reading tag text value\n if (xmlData[i] === '<') {\n i--;\n }\n }\n } else {\n if (isWhiteSpace(xmlData[i])) {\n continue;\n }\n return getErrorObject('InvalidChar', \"char '\" + xmlData[i] + \"' is not expected.\", getLineNumberForPosition(xmlData, i));\n }\n }\n\n if (!tagFound) {\n return getErrorObject('InvalidXml', 'Start tag expected.', 1);\n } else if (tags.length == 1) {\n return getErrorObject('InvalidTag', \"Unclosed tag '\" + tags[0].tagName + \"'.\", getLineNumberForPosition(xmlData, tags[0].tagStartPos));\n } else if (tags.length > 0) {\n return getErrorObject('InvalidXml', \"Invalid '\" +\n JSON.stringify(tags.map(t => t.tagName), null, 4).replace(/\\r?\\n/g, '') +\n \"' found.\", { line: 1, col: 1 });\n }\n\n return true;\n};\n\nfunction isWhiteSpace(char) {\n return char === ' ' || char === '\\t' || char === '\\n' || char === '\\r';\n}\n/**\n * Read Processing insstructions and skip\n * @param {*} xmlData\n * @param {*} i\n */\nfunction readPI(xmlData, i) {\n const start = i;\n for (; i < xmlData.length; i++) {\n if (xmlData[i] == '?' || xmlData[i] == ' ') {\n //tagname\n const tagname = xmlData.substr(start, i - start);\n if (i > 5 && tagname === 'xml') {\n return getErrorObject('InvalidXml', 'XML declaration allowed only at the start of the document.', getLineNumberForPosition(xmlData, i));\n } else if (xmlData[i] == '?' && xmlData[i + 1] == '>') {\n //check if valid attribut string\n i++;\n break;\n } else {\n continue;\n }\n }\n }\n return i;\n}\n\nfunction readCommentAndCDATA(xmlData, i) {\n if (xmlData.length > i + 5 && xmlData[i + 1] === '-' && xmlData[i + 2] === '-') {\n //comment\n for (i += 3; i < xmlData.length; i++) {\n if (xmlData[i] === '-' && xmlData[i + 1] === '-' && xmlData[i + 2] === '>') {\n i += 2;\n break;\n }\n }\n } else if (\n xmlData.length > i + 8 &&\n xmlData[i + 1] === 'D' &&\n xmlData[i + 2] === 'O' &&\n xmlData[i + 3] === 'C' &&\n xmlData[i + 4] === 'T' &&\n xmlData[i + 5] === 'Y' &&\n xmlData[i + 6] === 'P' &&\n xmlData[i + 7] === 'E'\n ) {\n let angleBracketsCount = 1;\n for (i += 8; i < xmlData.length; i++) {\n if (xmlData[i] === '<') {\n angleBracketsCount++;\n } else if (xmlData[i] === '>') {\n angleBracketsCount--;\n if (angleBracketsCount === 0) {\n break;\n }\n }\n }\n } else if (\n xmlData.length > i + 9 &&\n xmlData[i + 1] === '[' &&\n xmlData[i + 2] === 'C' &&\n xmlData[i + 3] === 'D' &&\n xmlData[i + 4] === 'A' &&\n xmlData[i + 5] === 'T' &&\n xmlData[i + 6] === 'A' &&\n xmlData[i + 7] === '['\n ) {\n for (i += 8; i < xmlData.length; i++) {\n if (xmlData[i] === ']' && xmlData[i + 1] === ']' && xmlData[i + 2] === '>') {\n i += 2;\n break;\n }\n }\n }\n\n return i;\n}\n\nconst doubleQuote = '\"';\nconst singleQuote = \"'\";\n\n/**\n * Keep reading xmlData until '<' is found outside the attribute value.\n * @param {string} xmlData\n * @param {number} i\n */\nfunction readAttributeStr(xmlData, i) {\n let attrStr = '';\n let startChar = '';\n let tagClosed = false;\n for (; i < xmlData.length; i++) {\n if (xmlData[i] === doubleQuote || xmlData[i] === singleQuote) {\n if (startChar === '') {\n startChar = xmlData[i];\n } else if (startChar !== xmlData[i]) {\n //if vaue is enclosed with double quote then single quotes are allowed inside the value and vice versa\n } else {\n startChar = '';\n }\n } else if (xmlData[i] === '>') {\n if (startChar === '') {\n tagClosed = true;\n break;\n }\n }\n attrStr += xmlData[i];\n }\n if (startChar !== '') {\n return false;\n }\n\n return {\n value: attrStr,\n index: i,\n tagClosed: tagClosed\n };\n}\n\n/**\n * Select all the attributes whether valid or invalid.\n */\nconst validAttrStrRegxp = new RegExp('(\\\\s*)([^\\\\s=]+)(\\\\s*=)?(\\\\s*([\\'\"])(([\\\\s\\\\S])*?)\\\\5)?', 'g');\n\n//attr, =\"sd\", a=\"amit's\", a=\"sd\"b=\"saf\", ab cd=\"\"\n\nfunction validateAttributeString(attrStr, options) {\n //console.log(\"start:\"+attrStr+\":end\");\n\n //if(attrStr.trim().length === 0) return true; //empty string\n\n const matches = getAllMatches(attrStr, validAttrStrRegxp);\n const attrNames = {};\n\n for (let i = 0; i < matches.length; i++) {\n if (matches[i][1].length === 0) {\n //nospace before attribute name: a=\"sd\"b=\"saf\"\n return getErrorObject('InvalidAttr', \"Attribute '\" + matches[i][2] + \"' has no space in starting.\", getPositionFromMatch(matches[i]))\n } else if (matches[i][3] !== undefined && matches[i][4] === undefined) {\n return getErrorObject('InvalidAttr', \"Attribute '\" + matches[i][2] + \"' is without value.\", getPositionFromMatch(matches[i]));\n } else if (matches[i][3] === undefined && !options.allowBooleanAttributes) {\n //independent attribute: ab\n return getErrorObject('InvalidAttr', \"boolean attribute '\" + matches[i][2] + \"' is not allowed.\", getPositionFromMatch(matches[i]));\n }\n /* else if(matches[i][6] === undefined){//attribute without value: ab=\n return { err: { code:\"InvalidAttr\",msg:\"attribute \" + matches[i][2] + \" has no value assigned.\"}};\n } */\n const attrName = matches[i][2];\n if (!validateAttrName(attrName)) {\n return getErrorObject('InvalidAttr', \"Attribute '\" + attrName + \"' is an invalid name.\", getPositionFromMatch(matches[i]));\n }\n if (!Object.prototype.hasOwnProperty.call(attrNames, attrName)) {\n //check for duplicate attribute.\n attrNames[attrName] = 1;\n } else {\n return getErrorObject('InvalidAttr', \"Attribute '\" + attrName + \"' is repeated.\", getPositionFromMatch(matches[i]));\n }\n }\n\n return true;\n}\n\nfunction validateNumberAmpersand(xmlData, i) {\n let re = /\\d/;\n if (xmlData[i] === 'x') {\n i++;\n re = /[\\da-fA-F]/;\n }\n for (; i < xmlData.length; i++) {\n if (xmlData[i] === ';')\n return i;\n if (!xmlData[i].match(re))\n break;\n }\n return -1;\n}\n\nfunction validateAmpersand(xmlData, i) {\n // https://www.w3.org/TR/xml/#dt-charref\n i++;\n if (xmlData[i] === ';')\n return -1;\n if (xmlData[i] === '#') {\n i++;\n return validateNumberAmpersand(xmlData, i);\n }\n let count = 0;\n for (; i < xmlData.length; i++, count++) {\n if (xmlData[i].match(/\\w/) && count < 20)\n continue;\n if (xmlData[i] === ';')\n break;\n return -1;\n }\n return i;\n}\n\nfunction getErrorObject(code, message, lineNumber) {\n return {\n err: {\n code: code,\n msg: message,\n line: lineNumber.line || lineNumber,\n col: lineNumber.col,\n },\n };\n}\n\nfunction validateAttrName(attrName) {\n return isName(attrName);\n}\n\n// const startsWithXML = /^xml/i;\n\nfunction validateTagName(tagname) {\n return isName(tagname) /* && !tagname.match(startsWithXML) */;\n}\n\n//this function returns the line number for the character at the given index\nfunction getLineNumberForPosition(xmlData, index) {\n const lines = xmlData.substring(0, index).split(/\\r?\\n/);\n return {\n line: lines.length,\n\n // column number is last line's length + 1, because column numbering starts at 1:\n col: lines[lines.length - 1].length + 1\n };\n}\n\n//this function returns the position of the first character of match within attrStr\nfunction getPositionFromMatch(match) {\n return match.startIndex + match[1].length;\n}\n","import { buildOptions } from './OptionsBuilder.js';\nimport OrderedObjParser from './OrderedObjParser.js';\nimport prettify from './node2json.js';\nimport { validate } from \"../validator.js\";\nimport XmlNode from './xmlNode.js';\n\nexport default class XMLParser {\n\n constructor(options) {\n this.externalEntities = {};\n this.options = buildOptions(options);\n\n }\n /**\n * Parse XML dats to JS object \n * @param {string|Uint8Array} xmlData \n * @param {boolean|Object} validationOption \n */\n parse(xmlData, validationOption) {\n if (typeof xmlData !== \"string\" && xmlData.toString) {\n xmlData = xmlData.toString();\n } else if (typeof xmlData !== \"string\") {\n throw new Error(\"XML data is accepted in String or Bytes[] form.\")\n }\n\n if (validationOption) {\n if (validationOption === true) validationOption = {}; //validate with default options\n\n const result = validate(xmlData, validationOption);\n if (result !== true) {\n throw Error(`${result.err.msg}:${result.err.line}:${result.err.col}`)\n }\n }\n const orderedObjParser = new OrderedObjParser(this.options, this.externalEntities);\n // orderedObjParser.entityDecoder.setExternalEntities(this.externalEntities);\n const orderedResult = orderedObjParser.parseXml(xmlData);\n if (this.options.preserveOrder || orderedResult === undefined) return orderedResult;\n else return prettify(orderedResult, this.options, orderedObjParser.matcher, orderedObjParser.readonlyMatcher);\n }\n\n /**\n * Add Entity which is not by default supported by this library\n * @param {string} key \n * @param {string} value \n */\n addEntity(key, value) {\n if (value.indexOf(\"&\") !== -1) {\n throw new Error(\"Entity value can't have '&'\")\n } else if (key.indexOf(\"&\") !== -1 || key.indexOf(\";\") !== -1) {\n throw new Error(\"An entity must be set without '&' and ';'. Eg. use '#xD' for '
'\")\n } else if (value === \"&\") {\n throw new Error(\"An entity with value '&' is not permitted\");\n } else {\n this.externalEntities[key] = value;\n }\n }\n\n /**\n * Returns a Symbol that can be used to access the metadata\n * property on a node.\n * \n * If Symbol is not available in the environment, an ordinary property is used\n * and the name of the property is here returned.\n * \n * The XMLMetaData property is only present when `captureMetaData`\n * is true in the options.\n */\n static getMetaDataSymbol() {\n return XmlNode.getMetaDataSymbol();\n }\n}","import { XMLParser } from \"fast-xml-parser\";\nimport { BaerlyError } from \"@baerly/protocol\";\n\n/**\n * Subset of S3's `ListObjectsV2CommandOutput` produced by\n * {@link parseListObjectsV2CommandOutput}. Field names mirror the\n * S3 REST API exactly (PascalCase) so the parser stays a thin shape\n * over the wire format.\n */\nexport interface ParsedListObjectsV2Output {\n Contents?: Array<{ ETag?: string; Key?: string; LastModified?: Date }>;\n NextContinuationToken?: string;\n}\n\n/**\n * `<Code>` / `<Message>` extracted from an S3\n * `<Error>…</Error>` response body by {@link parseS3Error}. Field\n * names mirror the S3 REST API (PascalCase), matching the convention\n * of {@link ParsedListObjectsV2Output}.\n */\nexport interface ParsedS3Error {\n Code?: string;\n Message?: string;\n}\n\nconst xmlParser = new XMLParser({\n ignoreAttributes: true,\n // Keep numeric-looking strings as strings — S3 keys can be all-digits.\n parseTagValue: false,\n // Force `<Contents>` to an array even when only one is present.\n isArray: (name) => name === \"Contents\",\n // Decode numeric character refs (`"` → `\"`). fast-xml-parser's\n // `processEntities` only handles the 5 predefined XML entities by\n // default; the HTML entity table covers numeric refs too. Minio\n // emits `"` around ETags, so this is load-bearing.\n htmlEntities: true,\n});\n\n// The list request sets `encoding-type=url`, so S3 URL-encodes the **key\n// family only** (Key/Prefix/Delimiter/StartAfter) in the response,\n// including spaces as `+`. Use this to reverse both steps. Do NOT apply it\n// to ETag or NextContinuationToken — S3 leaves those verbatim, and a\n// continuation token routinely contains literal `+` that the `.replace`\n// step would mangle into a space (corrupting pagination on large buckets).\nconst xmlVal = (obj: Record<string, unknown>, name: string): string | undefined => {\n const v = obj[name];\n if (typeof v !== \"string\" || v === \"\") {\n return undefined;\n }\n return decodeURIComponent(v.replace(/\\+/g, \" \"));\n};\n\n// Read a field verbatim. Used for everything S3 does NOT URL-encode:\n// error-body `Code`/`Message`, list `ETag`/`LastModified`, and\n// `NextContinuationToken` — running any of these through `xmlVal`'s\n// `decodeURIComponent` / `+`→space would corrupt literal `+` and `%`.\nconst rawXmlVal = (obj: Record<string, unknown>, name: string): string | undefined => {\n const v = obj[name];\n return typeof v === \"string\" && v !== \"\" ? v : undefined;\n};\n\n/**\n * Parse an S3 `<Error><Code>…</Code><Message>…</Message></Error>`\n * body. Returns `undefined` when the body is not a recognizable S3\n * error document (empty, HTML, a success payload, or a DTD), so\n * callers can fall back to the raw response text. This never throws:\n * it runs on a path that is already reporting an error.\n */\nexport const parseS3Error = (xml: string): ParsedS3Error | undefined => {\n // Skip non-error bodies; refuse DTDs before parsing — see the DTD-guard\n // note above parseListObjectsV2CommandOutput.\n if (!/<Error\\b/i.test(xml) || /<!DOCTYPE\\b/i.test(xml)) {\n return undefined;\n }\n let result: { Error?: Record<string, unknown> };\n try {\n result = xmlParser.parse(xml) as { Error?: Record<string, unknown> };\n } catch {\n return undefined;\n }\n const root = result.Error;\n if (root === undefined) {\n return undefined;\n }\n const code = rawXmlVal(root, \"Code\");\n const message = rawXmlVal(root, \"Message\");\n if (code === undefined && message === undefined) {\n return undefined;\n }\n return {\n ...(code !== undefined && { Code: code }),\n ...(message !== undefined && { Message: message }),\n };\n};\n\n// `new Date(badString)` yields an Invalid Date (a non-null Date whose\n// getTime() is NaN) rather than throwing — surface `undefined` for a\n// malformed `LastModified` so it never leaks into a `StorageListEntry`.\n// GC then falls back to `now()` for the tombstone `due_at` anchor.\nconst parseLastModified = (lm: string | undefined): Date | undefined => {\n if (lm === undefined) {\n return undefined;\n }\n const d = new Date(lm);\n return Number.isNaN(d.getTime()) ? undefined : d;\n};\n\n// DTD guard: reject any DOCTYPE before fast-xml-parser sees the bytes. S3/R2/\n// MinIO/GCS never emit a DOCTYPE here, so one is always a bug or an attack —\n// this defangs the DOCTYPE entity vectors (XXE, billion-laughs, the\n// CVE-2026-25896 entity-shadow). The no-DOCTYPE numeric-ref expansion path\n// (CVE-2026-33036) it cannot match is covered by the `^5.5.6` floor in\n// package.json. `htmlEntities: true` (above) stays default-safe given both.\nexport const parseListObjectsV2CommandOutput = (xml: string): ParsedListObjectsV2Output => {\n if (/<!DOCTYPE\\b/i.test(xml)) {\n throw new BaerlyError(\"InvalidResponse\", \"DTD not allowed in S3 XML responses\");\n }\n let result: { ListBucketResult?: Record<string, unknown> };\n try {\n result = xmlParser.parse(xml) as { ListBucketResult?: Record<string, unknown> };\n } catch {\n throw new BaerlyError(\"InvalidResponse\", `Invalid XML: ${xml}`);\n }\n const root = result.ListBucketResult ?? {};\n const contents = (root[\"Contents\"] as Array<Record<string, unknown>> | undefined) ?? [];\n\n return {\n Contents: contents.map((content) => {\n return {\n ETag: rawXmlVal(content, \"ETag\"),\n Key: xmlVal(content, \"Key\"),\n LastModified: parseLastModified(rawXmlVal(content, \"LastModified\")),\n };\n }),\n NextContinuationToken: rawXmlVal(root, \"NextContinuationToken\"),\n };\n};\n","import {\n BaerlyError,\n LIST_OBJECT_MAX_RETRIES,\n RATE_LIMIT_BACKOFF_MILLIS,\n RETRY_AFTER_MAX_SECONDS,\n S3_REQUEST_MAX_RETRIES,\n delay,\n type Storage,\n type StorageGetOptions,\n type StorageGetResult,\n type StorageListEntry,\n type StoragePutOptions,\n type StoragePutResult,\n} from \"@baerly/protocol\";\nimport { parseListObjectsV2CommandOutput, parseS3Error } from \"./xml.ts\";\n\n/**\n * Permanent {@link BaerlyError} codes that must short-circuit `retry`.\n * These represent caller- or environment-level faults where retrying\n * cannot succeed: `AccessDenied` (403 — credentials/policy),\n * `InvalidConfig` (bad bucket / unsupported credential type),\n * `InvalidResponse` (server returned unparseable data), and\n * `Conflict` (CAS guard lost — retrying would just re-lose against\n * the same state). `NetworkError` is intentionally absent — it covers\n * transient transport faults and stays retryable.\n */\nconst PERMANENT_ERROR_CODES: ReadonlySet<string> = new Set([\n \"AccessDenied\",\n \"InvalidConfig\",\n \"InvalidResponse\",\n \"Conflict\",\n]);\n\n/**\n * Parse an HTTP `Retry-After` header into a non-negative seconds value,\n * clamped to {@link RETRY_AFTER_MAX_SECONDS}. Returns `undefined` if\n * the header is absent, malformed, or whitespace.\n *\n * RFC 7231 §7.1.3 admits two forms: delta-seconds (non-negative\n * integer) and HTTP-date. Both are accepted; dates in the past return\n * `0`. Fractional seconds, negatives, and arbitrary strings reject.\n *\n * The `now` injection point exists for the unit test; production\n * callers should pass nothing.\n */\nfunction parseRetryAfter(header: string | null, now: () => number = Date.now): number | undefined {\n if (header === null) {\n return undefined;\n }\n const trimmed = header.trim();\n if (trimmed === \"\") {\n return undefined;\n }\n if (/^\\d+$/.test(trimmed)) {\n const n = Number.parseInt(trimmed, 10);\n return Number.isFinite(n) ? Math.min(n, RETRY_AFTER_MAX_SECONDS) : undefined;\n }\n // RFC 7231 §7.1.1.1 HTTP-date formats (IMF-fixdate, RFC 850, asctime)\n // all contain alphabetic month/day-of-week tokens. Gating on a letter\n // avoids V8's lenient `Date.parse` accepting things like \"5.5\".\n if (!/[a-z]/i.test(trimmed)) {\n return undefined;\n }\n const t = Date.parse(trimmed);\n if (Number.isNaN(t)) {\n return undefined;\n }\n const seconds = Math.max(0, Math.ceil((t - now()) / 1000));\n return Math.min(seconds, RETRY_AFTER_MAX_SECONDS);\n}\n\nconst retryAfterCause = (res: Response): { retryAfterSeconds?: number } => {\n const hint = parseRetryAfter(res.headers.get(\"Retry-After\"));\n return hint !== undefined ? { retryAfterSeconds: hint } : {};\n};\n\n// Detail suffix for a non-status-mapped S3 error response. When the\n// body is a parseable `<Error><Code>…</Error>` document, surface S3's\n// own error code (and message) instead of concatenating the raw XML\n// blob into the thrown message; otherwise fall back to the raw text.\nconst s3ErrorDetail = (status: number, body: string): string => {\n const parsed = parseS3Error(body);\n if (parsed !== undefined) {\n const code = parsed.Code ?? \"UnknownError\";\n return parsed.Message !== undefined\n ? `${status} ${code}: ${parsed.Message}`\n : `${status} ${code}`;\n }\n return `${status} ${body}`;\n};\n\nconst retry = async <T>(\n fn: () => Promise<T>,\n { retries = S3_REQUEST_MAX_RETRIES, backoffMs = 100, maxDelayMs = 10_000 } = {},\n): Promise<T> => {\n let wait = backoffMs;\n for (let attempt = 0; attempt <= retries; attempt++) {\n try {\n return await fn();\n } catch (error) {\n if (error instanceof BaerlyError && PERMANENT_ERROR_CODES.has(error.code)) {\n throw error;\n }\n if (attempt === retries) {\n throw error;\n }\n const hintMs = retryAfterHintMs(error, maxDelayMs);\n await delay(hintMs ?? wait);\n if (hintMs === undefined) {\n wait = Math.min(wait * 1.5, maxDelayMs);\n } else {\n // A server-driven pause is new information about server state;\n // reset the exponential ladder so a subsequent non-hinted\n // transient starts fresh from `backoffMs`.\n wait = backoffMs;\n }\n }\n }\n throw new BaerlyError(\"Internal\", \"s3-http retry loop exited without returning or throwing\");\n};\n\nconst retryAfterHintMs = (e: unknown, maxDelayMs: number): number | undefined => {\n if (!(e instanceof BaerlyError)) {\n return undefined;\n }\n const cause = e.cause as { retryAfterSeconds?: number } | undefined;\n if (cause?.retryAfterSeconds === undefined) {\n return undefined;\n }\n return Math.min(cause.retryAfterSeconds * 1000, maxDelayMs);\n};\n\n/**\n * Construction-time options for {@link S3HttpStorage}. Everything is\n * optional except `endpoint` and `bucket`; the consumer chooses how\n * to satisfy `fetch` (browser/Node global vs. injected) and `sign`\n * (anonymous Minio vs. SigV4-signed via aws4fetch).\n */\nexport interface S3HttpStorageOptions {\n /**\n * S3 endpoint URL, e.g. `https://s3.us-east-1.amazonaws.com` or\n * `http://127.0.0.1:9102` (Minio). Trailing slashes are trimmed.\n */\n endpoint: string;\n /** S3 bucket name. */\n bucket: string;\n /**\n * `fetch` implementation. Defaults to `globalThis.fetch.bind(globalThis)`.\n * Tests pass a `vi.fn()` stub.\n */\n fetch?: typeof fetch;\n /**\n * Signs requests before send. Pass `undefined` for anonymous\n * (Minio without creds). The seam is `(req) => Promise<req>` so\n * SigV4 implementations like `aws4fetch.AwsClient.sign` plug in\n * directly.\n */\n sign?: (req: Request) => Promise<Request>;\n /** Max retries for transient (non-permanent) failures. */\n retries?: number;\n /** Initial backoff in ms. */\n backoffMs?: number;\n}\n\n/**\n * `Storage` impl that speaks the S3 REST API directly. Works against\n * any S3-compatible endpoint — AWS S3, R2 (S3-compat), GCS (S3-compat),\n * Minio. Does not depend on any AWS SDK.\n *\n * Authentication is plugged in via the `sign` callback; this class\n * itself does no SigV4. For Cloudflare Workers, the R2 binding fast\n * path lives in `@baerly/adapter-cloudflare`.\n */\nexport class S3HttpStorage implements Storage {\n readonly #endpoint: string;\n readonly #bucket: string;\n readonly #fetch: typeof fetch;\n readonly #sign?: (req: Request) => Promise<Request>;\n readonly #retries: number;\n readonly #backoffMs: number;\n\n constructor(options: S3HttpStorageOptions) {\n this.#endpoint = options.endpoint.replace(/\\/+$/, \"\");\n this.#bucket = options.bucket;\n this.#fetch = options.fetch ?? globalThis.fetch.bind(globalThis);\n this.#sign = options.sign;\n this.#retries = options.retries ?? S3_REQUEST_MAX_RETRIES;\n this.#backoffMs = options.backoffMs ?? 100;\n }\n\n #objectUrl(key: string, versionId?: string): string {\n const base = `${this.#endpoint}/${this.#bucket}/${encodeURIComponent(key)}`;\n return versionId !== undefined ? `${base}?versionId=${encodeURIComponent(versionId)}` : base;\n }\n\n async #dispatch(req: Request): Promise<Response> {\n const signed = this.#sign ? await this.#sign(req) : req;\n try {\n return await this.#fetch(signed);\n } catch (error) {\n if (error instanceof BaerlyError) {\n throw error;\n }\n const msg = error instanceof Error ? error.message : String(error);\n throw new BaerlyError(\"NetworkError\", msg, error);\n }\n }\n\n #retry<T>(fn: () => Promise<T>): Promise<T> {\n return retry(fn, { retries: this.#retries, backoffMs: this.#backoffMs });\n }\n\n async get(key: string, opts?: StorageGetOptions): Promise<StorageGetResult | null> {\n opts?.signal?.throwIfAborted();\n const url = this.#objectUrl(key, opts?.versionId);\n const headers = new Headers();\n if (opts?.ifNoneMatch !== undefined) {\n headers.set(\"If-None-Match\", opts.ifNoneMatch);\n }\n return this.#retry(async () => {\n const res = await this.#dispatch(\n new Request(url, { method: \"GET\", headers, signal: opts?.signal ?? null }),\n );\n switch (res.status) {\n case 200: {\n const etag = res.headers.get(\"ETag\");\n if (etag === null) {\n throw new BaerlyError(\"InvalidResponse\", `GET ${key}: missing ETag`);\n }\n const body = new Uint8Array(await res.arrayBuffer());\n const versionId = res.headers.get(\"x-amz-version-id\") ?? undefined;\n return versionId !== undefined ? { body, etag, versionId } : { body, etag };\n }\n case 304:\n case 404: {\n return null;\n }\n case 403: {\n throw new BaerlyError(\"AccessDenied\", `GET ${key}: 403`);\n }\n default: {\n if (res.status === 429 || res.status >= 500) {\n throw new BaerlyError(\"NetworkError\", `GET ${key}: ${res.status} ${await res.text()}`, {\n status: res.status,\n ...retryAfterCause(res),\n });\n }\n throw new BaerlyError(\n \"InvalidResponse\",\n `GET ${key}: ${s3ErrorDetail(res.status, await res.text())}`,\n );\n }\n }\n });\n }\n\n async put(key: string, body: Uint8Array, opts?: StoragePutOptions): Promise<StoragePutResult> {\n opts?.signal?.throwIfAborted();\n const url = this.#objectUrl(key);\n const headers = new Headers();\n headers.set(\"Content-Type\", opts?.contentType ?? \"application/octet-stream\");\n if (opts?.ifMatch !== undefined) {\n headers.set(\"If-Match\", opts.ifMatch);\n }\n if (opts?.ifNoneMatch === \"*\") {\n headers.set(\"If-None-Match\", \"*\");\n }\n return this.#retry(async () => {\n const res = await this.#dispatch(\n new Request(url, {\n method: \"PUT\",\n headers,\n // TS lib.dom narrows BodyInit and a generic `Uint8Array<ArrayBufferLike>`\n // is not assignable; the runtime accepts it.\n body: body as BodyInit,\n signal: opts?.signal ?? null,\n }),\n );\n if (res.status === 412) {\n throw new BaerlyError(\"Conflict\", `PUT ${key}: precondition failed`);\n }\n // AWS S3 returns 409 ConditionalRequestConflict when a concurrent\n // conditional create (If-None-Match:\"*\") races; Minio returns 412.\n // 409 means the write was contended and may NOT have landed, so it\n // maps to a retryable NetworkError — the single-write-commit writer\n // re-issues the same-seq PUT, which resolves deterministically to 200\n // (we win) or 412 (key now present → Conflict → adopt/re-probe). A\n // direct Conflict here would adopt-read a possibly-absent entry.\n if (res.status === 409 && opts?.ifNoneMatch === \"*\") {\n throw new BaerlyError(\n \"NetworkError\",\n `PUT ${key}: 409 ConditionalRequestConflict (contended conditional create; retryable)`,\n { status: res.status, ...retryAfterCause(res) },\n );\n }\n // S3-compatible servers diverge on `If-Match` against a missing\n // key: AWS S3 returns 412, Minio returns 404 (NoSuchKey). Map\n // 404-with-ifMatch to the same `Conflict` semantic so consumers\n // don't have to special-case the wire reply.\n if (res.status === 404 && opts?.ifMatch !== undefined) {\n throw new BaerlyError(\n \"Conflict\",\n `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but key does not exist)`,\n );\n }\n if (res.status === 403) {\n throw new BaerlyError(\"AccessDenied\", `PUT ${key}: 403`);\n }\n if (res.status === 429 || res.status >= 500) {\n throw new BaerlyError(\"NetworkError\", `PUT ${key}: ${res.status} ${await res.text()}`, {\n status: res.status,\n ...retryAfterCause(res),\n });\n }\n if (res.status !== 200 && res.status !== 204) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `PUT ${key}: ${s3ErrorDetail(res.status, await res.text())}`,\n );\n }\n const etag = res.headers.get(\"ETag\");\n if (etag === null) {\n throw new BaerlyError(\"InvalidResponse\", `PUT ${key}: missing ETag`);\n }\n const dateStr = res.headers.get(\"Date\");\n const versionId = res.headers.get(\"x-amz-version-id\") ?? undefined;\n const result: { etag: string; serverDate?: Date; versionId?: string } = { etag };\n if (dateStr !== null) {\n result.serverDate = new Date(dateStr);\n }\n if (versionId !== undefined) {\n result.versionId = versionId;\n }\n return result;\n });\n }\n\n async delete(key: string, opts?: { signal?: AbortSignal }): Promise<void> {\n opts?.signal?.throwIfAborted();\n const url = this.#objectUrl(key);\n await this.#retry(async () => {\n const res = await this.#dispatch(\n new Request(url, { method: \"DELETE\", signal: opts?.signal ?? null }),\n );\n if (res.status === 403) {\n throw new BaerlyError(\"AccessDenied\", `DELETE ${key}: 403`);\n }\n if (res.status === 429 || res.status >= 500) {\n throw new BaerlyError(\"NetworkError\", `DELETE ${key}: ${res.status} ${await res.text()}`, {\n status: res.status,\n ...retryAfterCause(res),\n });\n }\n // 200 / 204 / 404 → success (idempotent).\n });\n }\n\n async *list(\n prefix: string,\n opts?: { startAfter?: string; maxKeys?: number; signal?: AbortSignal },\n ): AsyncIterable<StorageListEntry> {\n opts?.signal?.throwIfAborted();\n let yielded = 0;\n let continuationToken: string | undefined;\n const startAfter = opts?.startAfter ?? \"\";\n while (true) {\n opts?.signal?.throwIfAborted();\n const params = new URLSearchParams();\n params.set(\"list-type\", \"2\");\n params.set(\"prefix\", prefix);\n // Force S3 to URL-encode object keys in the response so keys\n // containing XML-hostile or whitespace bytes survive the round trip.\n // The XML parser (`xmlVal` in ./xml.ts) reverses this on `Key`; only\n // the key family (Key/Prefix/Delimiter/StartAfter) is encoded — ETag\n // and NextContinuationToken come back verbatim.\n params.set(\"encoding-type\", \"url\");\n if (continuationToken !== undefined) {\n params.set(\"continuation-token\", continuationToken);\n } else if (startAfter !== \"\") {\n params.set(\"start-after\", startAfter);\n }\n if (opts?.maxKeys !== undefined) {\n const remaining = opts.maxKeys - yielded;\n params.set(\"max-keys\", String(Math.min(remaining, 1000)));\n }\n const url = `${this.#endpoint}/${this.#bucket}/?${params.toString()}`;\n\n // Per-page 429 retry budget separate from the inner #retry budget:\n // 429 means \"rate-limited, back off and retry the same page\", and\n // a single hot page shouldn't burn the overall transient-failure\n // budget.\n let parsed: Awaited<ReturnType<typeof parseListObjectsV2CommandOutput>> | undefined;\n let lastHint: number | undefined;\n for (let attempt = 0; attempt < LIST_OBJECT_MAX_RETRIES; attempt++) {\n const outcome = await this.#retry(async () => {\n const res = await this.#dispatch(\n new Request(url, { method: \"GET\", signal: opts?.signal ?? null }),\n );\n if (res.status === 200) {\n return { kind: \"ok\" as const, body: await res.text() };\n }\n if (res.status === 429) {\n return {\n kind: \"ratelimited\" as const,\n retryAfterSeconds: parseRetryAfter(res.headers.get(\"Retry-After\")),\n };\n }\n if (res.status === 403) {\n throw new BaerlyError(\"AccessDenied\", `LIST ${prefix}: 403`);\n }\n if (res.status >= 500) {\n throw new BaerlyError(\n \"NetworkError\",\n `LIST ${prefix}: ${res.status} ${await res.text()}`,\n { status: res.status, ...retryAfterCause(res) },\n );\n }\n throw new BaerlyError(\n \"InvalidResponse\",\n `LIST ${prefix}: ${s3ErrorDetail(res.status, await res.text())}`,\n );\n });\n if (outcome.kind === \"ok\") {\n parsed = parseListObjectsV2CommandOutput(outcome.body);\n break;\n }\n lastHint = outcome.retryAfterSeconds;\n const hintMs =\n outcome.retryAfterSeconds !== undefined ? outcome.retryAfterSeconds * 1000 : 0;\n await delay(Math.max(hintMs, RATE_LIMIT_BACKOFF_MILLIS));\n }\n if (parsed === undefined) {\n throw new BaerlyError(\"NetworkError\", `LIST ${prefix}: rate-limited`, {\n status: 429,\n ...(lastHint !== undefined ? { retryAfterSeconds: lastHint } : {}),\n });\n }\n\n for (const entry of parsed.Contents ?? []) {\n if (entry.Key === undefined) {\n continue;\n }\n yield {\n key: entry.Key,\n etag: entry.ETag ?? \"\",\n ...(entry.LastModified !== undefined && { lastModified: entry.LastModified }),\n };\n yielded += 1;\n if (opts?.maxKeys !== undefined && yielded >= opts.maxKeys) {\n return;\n }\n }\n continuationToken = parsed.NextContinuationToken;\n if (continuationToken === undefined || continuationToken === \"\") {\n return;\n }\n }\n }\n}\n","/**\n * @license MIT <https://opensource.org/licenses/MIT>\n * @copyright Michael Hart 2024\n */\nconst encoder = new TextEncoder();\nconst HOST_SERVICES = {\n appstream2: 'appstream',\n cloudhsmv2: 'cloudhsm',\n email: 'ses',\n marketplace: 'aws-marketplace',\n mobile: 'AWSMobileHubService',\n pinpoint: 'mobiletargeting',\n queue: 'sqs',\n 'git-codecommit': 'codecommit',\n 'mturk-requester-sandbox': 'mturk-requester',\n 'personalize-runtime': 'personalize',\n};\nconst UNSIGNABLE_HEADERS = new Set([\n 'authorization',\n 'content-type',\n 'content-length',\n 'user-agent',\n 'presigned-expires',\n 'expect',\n 'x-amzn-trace-id',\n 'range',\n 'connection',\n]);\nclass AwsClient {\n constructor({ accessKeyId, secretAccessKey, sessionToken, service, region, cache, retries, initRetryMs }) {\n if (accessKeyId == null) throw new TypeError('accessKeyId is a required option')\n if (secretAccessKey == null) throw new TypeError('secretAccessKey is a required option')\n this.accessKeyId = accessKeyId;\n this.secretAccessKey = secretAccessKey;\n this.sessionToken = sessionToken;\n this.service = service;\n this.region = region;\n this.cache = cache || new Map();\n this.retries = retries != null ? retries : 10;\n this.initRetryMs = initRetryMs || 50;\n }\n async sign(input, init) {\n if (input instanceof Request) {\n const { method, url, headers, body } = input;\n init = Object.assign({ method, url, headers }, init);\n if (init.body == null && headers.has('Content-Type')) {\n init.body = body != null && headers.has('X-Amz-Content-Sha256') ? body : await input.clone().arrayBuffer();\n }\n input = url;\n }\n const signer = new AwsV4Signer(Object.assign({ url: input.toString() }, init, this, init && init.aws));\n const signed = Object.assign({}, init, await signer.sign());\n delete signed.aws;\n try {\n return new Request(signed.url.toString(), signed)\n } catch (e) {\n if (e instanceof TypeError) {\n return new Request(signed.url.toString(), Object.assign({ duplex: 'half' }, signed))\n }\n throw e\n }\n }\n async fetch(input, init) {\n for (let i = 0; i <= this.retries; i++) {\n const fetched = fetch(await this.sign(input, init));\n if (i === this.retries) {\n return fetched\n }\n const res = await fetched;\n if (res.status < 500 && res.status !== 429) {\n return res\n }\n await new Promise(resolve => setTimeout(resolve, Math.random() * this.initRetryMs * Math.pow(2, i)));\n }\n throw new Error('An unknown error occurred, ensure retries is not negative')\n }\n}\nclass AwsV4Signer {\n constructor({ method, url, headers, body, accessKeyId, secretAccessKey, sessionToken, service, region, cache, datetime, signQuery, appendSessionToken, allHeaders, singleEncode }) {\n if (url == null) throw new TypeError('url is a required option')\n if (accessKeyId == null) throw new TypeError('accessKeyId is a required option')\n if (secretAccessKey == null) throw new TypeError('secretAccessKey is a required option')\n this.method = method || (body ? 'POST' : 'GET');\n this.url = new URL(url);\n this.headers = new Headers(headers || {});\n this.body = body;\n this.accessKeyId = accessKeyId;\n this.secretAccessKey = secretAccessKey;\n this.sessionToken = sessionToken;\n let guessedService, guessedRegion;\n if (!service || !region) {\n[guessedService, guessedRegion] = guessServiceRegion(this.url, this.headers);\n }\n this.service = service || guessedService || '';\n this.region = region || guessedRegion || 'us-east-1';\n this.cache = cache || new Map();\n this.datetime = datetime || new Date().toISOString().replace(/[:-]|\\.\\d{3}/g, '');\n this.signQuery = signQuery;\n this.appendSessionToken = appendSessionToken || this.service === 'iotdevicegateway';\n this.headers.delete('Host');\n if (this.service === 's3' && !this.signQuery && !this.headers.has('X-Amz-Content-Sha256')) {\n this.headers.set('X-Amz-Content-Sha256', 'UNSIGNED-PAYLOAD');\n }\n const params = this.signQuery ? this.url.searchParams : this.headers;\n params.set('X-Amz-Date', this.datetime);\n if (this.sessionToken && !this.appendSessionToken) {\n params.set('X-Amz-Security-Token', this.sessionToken);\n }\n this.signableHeaders = ['host', ...this.headers.keys()]\n .filter(header => allHeaders || !UNSIGNABLE_HEADERS.has(header))\n .sort();\n this.signedHeaders = this.signableHeaders.join(';');\n this.canonicalHeaders = this.signableHeaders\n .map(header => header + ':' + (header === 'host' ? this.url.host : (this.headers.get(header) || '').replace(/\\s+/g, ' ')))\n .join('\\n');\n this.credentialString = [this.datetime.slice(0, 8), this.region, this.service, 'aws4_request'].join('/');\n if (this.signQuery) {\n if (this.service === 's3' && !params.has('X-Amz-Expires')) {\n params.set('X-Amz-Expires', '86400');\n }\n params.set('X-Amz-Algorithm', 'AWS4-HMAC-SHA256');\n params.set('X-Amz-Credential', this.accessKeyId + '/' + this.credentialString);\n params.set('X-Amz-SignedHeaders', this.signedHeaders);\n }\n if (this.service === 's3') {\n try {\n this.encodedPath = decodeURIComponent(this.url.pathname.replace(/\\+/g, ' '));\n } catch (e) {\n this.encodedPath = this.url.pathname;\n }\n } else {\n this.encodedPath = this.url.pathname.replace(/\\/+/g, '/');\n }\n if (!singleEncode) {\n this.encodedPath = encodeURIComponent(this.encodedPath).replace(/%2F/g, '/');\n }\n this.encodedPath = encodeRfc3986(this.encodedPath);\n const seenKeys = new Set();\n this.encodedSearch = [...this.url.searchParams]\n .filter(([k]) => {\n if (!k) return false\n if (this.service === 's3') {\n if (seenKeys.has(k)) return false\n seenKeys.add(k);\n }\n return true\n })\n .map(pair => pair.map(p => encodeRfc3986(encodeURIComponent(p))))\n .sort(([k1, v1], [k2, v2]) => k1 < k2 ? -1 : k1 > k2 ? 1 : v1 < v2 ? -1 : v1 > v2 ? 1 : 0)\n .map(pair => pair.join('='))\n .join('&');\n }\n async sign() {\n if (this.signQuery) {\n this.url.searchParams.set('X-Amz-Signature', await this.signature());\n if (this.sessionToken && this.appendSessionToken) {\n this.url.searchParams.set('X-Amz-Security-Token', this.sessionToken);\n }\n } else {\n this.headers.set('Authorization', await this.authHeader());\n }\n return {\n method: this.method,\n url: this.url,\n headers: this.headers,\n body: this.body,\n }\n }\n async authHeader() {\n return [\n 'AWS4-HMAC-SHA256 Credential=' + this.accessKeyId + '/' + this.credentialString,\n 'SignedHeaders=' + this.signedHeaders,\n 'Signature=' + (await this.signature()),\n ].join(', ')\n }\n async signature() {\n const date = this.datetime.slice(0, 8);\n const cacheKey = [this.secretAccessKey, date, this.region, this.service].join();\n let kCredentials = this.cache.get(cacheKey);\n if (!kCredentials) {\n const kDate = await hmac('AWS4' + this.secretAccessKey, date);\n const kRegion = await hmac(kDate, this.region);\n const kService = await hmac(kRegion, this.service);\n kCredentials = await hmac(kService, 'aws4_request');\n this.cache.set(cacheKey, kCredentials);\n }\n return buf2hex(await hmac(kCredentials, await this.stringToSign()))\n }\n async stringToSign() {\n return [\n 'AWS4-HMAC-SHA256',\n this.datetime,\n this.credentialString,\n buf2hex(await hash(await this.canonicalString())),\n ].join('\\n')\n }\n async canonicalString() {\n return [\n this.method.toUpperCase(),\n this.encodedPath,\n this.encodedSearch,\n this.canonicalHeaders + '\\n',\n this.signedHeaders,\n await this.hexBodyHash(),\n ].join('\\n')\n }\n async hexBodyHash() {\n let hashHeader = this.headers.get('X-Amz-Content-Sha256') || (this.service === 's3' && this.signQuery ? 'UNSIGNED-PAYLOAD' : null);\n if (hashHeader == null) {\n if (this.body && typeof this.body !== 'string' && !('byteLength' in this.body)) {\n throw new Error('body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header')\n }\n hashHeader = buf2hex(await hash(this.body || ''));\n }\n return hashHeader\n }\n}\nasync function hmac(key, string) {\n const cryptoKey = await crypto.subtle.importKey(\n 'raw',\n typeof key === 'string' ? encoder.encode(key) : key,\n { name: 'HMAC', hash: { name: 'SHA-256' } },\n false,\n ['sign'],\n );\n return crypto.subtle.sign('HMAC', cryptoKey, encoder.encode(string))\n}\nasync function hash(content) {\n return crypto.subtle.digest('SHA-256', typeof content === 'string' ? encoder.encode(content) : content)\n}\nconst HEX_CHARS = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];\nfunction buf2hex(arrayBuffer) {\n const buffer = new Uint8Array(arrayBuffer);\n let out = '';\n for (let idx = 0; idx < buffer.length; idx++) {\n const n = buffer[idx];\n out += HEX_CHARS[(n >>> 4) & 0xF];\n out += HEX_CHARS[n & 0xF];\n }\n return out\n}\nfunction encodeRfc3986(urlEncodedStr) {\n return urlEncodedStr.replace(/[!'()*]/g, c => '%' + c.charCodeAt(0).toString(16).toUpperCase())\n}\nfunction guessServiceRegion(url, headers) {\n const { hostname, pathname } = url;\n if (hostname.endsWith('.on.aws')) {\n const match = hostname.match(/^[^.]{1,63}\\.lambda-url\\.([^.]{1,63})\\.on\\.aws$/);\n return match != null ? ['lambda', match[1] || ''] : ['', '']\n }\n if (hostname.endsWith('.r2.cloudflarestorage.com')) {\n return ['s3', 'auto']\n }\n if (hostname.endsWith('.backblazeb2.com')) {\n const match = hostname.match(/^(?:[^.]{1,63}\\.)?s3\\.([^.]{1,63})\\.backblazeb2\\.com$/);\n return match != null ? ['s3', match[1] || ''] : ['', '']\n }\n const match = hostname.replace('dualstack.', '').match(/([^.]{1,63})\\.(?:([^.]{0,63})\\.)?amazonaws\\.com(?:\\.cn)?$/);\n let service = (match && match[1]) || '';\n let region = match && match[2];\n if (region === 'us-gov') {\n region = 'us-gov-west-1';\n } else if (region === 's3' || region === 's3-accelerate') {\n region = 'us-east-1';\n service = 's3';\n } else if (service === 'iot') {\n if (hostname.startsWith('iot.')) {\n service = 'execute-api';\n } else if (hostname.startsWith('data.jobs.iot.')) {\n service = 'iot-jobs-data';\n } else {\n service = pathname === '/mqtt' ? 'iotdevicegateway' : 'iotdata';\n }\n } else if (service === 'autoscaling') {\n const targetPrefix = (headers.get('X-Amz-Target') || '').split('.')[0];\n if (targetPrefix === 'AnyScaleFrontendService') {\n service = 'application-autoscaling';\n } else if (targetPrefix === 'AnyScaleScalingPlannerFrontendService') {\n service = 'autoscaling-plans';\n }\n } else if (region == null && service.startsWith('s3-')) {\n region = service.slice(3).replace(/^fips-|^external-1/, '');\n service = 's3';\n } else if (service.endsWith('-fips')) {\n service = service.slice(0, -5);\n } else if (region && /-\\d$/.test(service) && !/-\\d$/.test(region)) {\n[service, region] = [region, service];\n }\n return [HOST_SERVICES[service] || service, region || '']\n}\n\nexport { AwsClient, AwsV4Signer };\n","import { AwsClient } from \"aws4fetch\";\nimport type { Credentials, CredentialsProvider } from \"./types.ts\";\n\nconst REFRESH_BUFFER_MS = 5 * 60 * 1000;\n\nfunction buildAwsClient(creds: Credentials, region: string): AwsClient {\n return new AwsClient({\n accessKeyId: creds.accessKeyId,\n secretAccessKey: creds.secretAccessKey,\n sessionToken: creds.sessionToken,\n region,\n service: \"s3\",\n });\n}\n\nexport function refreshingSigner(opts: {\n region: string;\n credentials: Credentials | CredentialsProvider;\n now?: () => number;\n}): (req: Request) => Promise<Request> {\n const region = opts.region;\n const now = opts.now ?? (() => Date.now());\n\n if (typeof opts.credentials !== \"function\") {\n const aws = buildAwsClient(opts.credentials, region);\n return (req) => aws.sign(req);\n }\n\n const provider = opts.credentials;\n let cached: { aws: AwsClient; expiresAt: number } | null = null;\n let inFlight: Promise<AwsClient> | null = null;\n\n const resolve = async (): Promise<AwsClient> => {\n if (cached !== null && cached.expiresAt - REFRESH_BUFFER_MS > now()) {\n return cached.aws;\n }\n if (inFlight !== null) {\n return inFlight;\n }\n inFlight = (async () => {\n try {\n const creds = await provider();\n const aws = buildAwsClient(creds, region);\n const expiresAt = creds.expiration?.getTime() ?? Number.POSITIVE_INFINITY;\n cached = { aws, expiresAt };\n return aws;\n } finally {\n inFlight = null;\n }\n })();\n return inFlight;\n };\n\n return async (req) => {\n const aws = await resolve();\n return aws.sign(req);\n };\n}\n","import type { Storage } from \"@baerly/protocol\";\nimport { S3HttpStorage } from \"./s3-http.ts\";\nimport { refreshingSigner } from \"./credentials/signer.ts\";\nimport type { Credentials, CredentialsProvider } from \"./credentials/types.ts\";\n\nfunction buildS3Storage(opts: {\n endpoint: string;\n region: string;\n bucket: string;\n credentials: Credentials | CredentialsProvider;\n}): Storage {\n const sign = refreshingSigner({ region: opts.region, credentials: opts.credentials });\n return new S3HttpStorage({ endpoint: opts.endpoint, bucket: opts.bucket, sign });\n}\n\n/**\n * AWS S3 `Storage` factory. Wraps `S3HttpStorage` with the standard\n * `aws4fetch` SigV4 signer. The endpoint is derived from the region as\n * `https://s3.<region>.amazonaws.com`.\n *\n * @example Static credentials\n * ```ts\n * import { s3Storage } from \"@gusto/baerly-storage/node\";\n *\n * const storage = s3Storage({\n * region: process.env[\"AWS_REGION\"] ?? \"us-east-1\",\n * bucket: process.env[\"BUCKET\"]!,\n * credentials: {\n * accessKeyId: process.env[\"AWS_ACCESS_KEY_ID\"]!,\n * secretAccessKey: process.env[\"AWS_SECRET_ACCESS_KEY\"]!,\n * },\n * });\n * ```\n *\n * @example EKS Pod Identity (refreshing)\n * ```ts\n * import { s3Storage, fromEksPodIdentity } from \"@gusto/baerly-storage/node\";\n *\n * const storage = s3Storage({\n * region: process.env[\"AWS_REGION\"] ?? \"us-east-1\",\n * bucket: process.env[\"BUCKET\"]!,\n * credentials: fromEksPodIdentity(),\n * });\n * ```\n */\nexport function s3Storage(opts: {\n region: string;\n bucket: string;\n credentials: Credentials | CredentialsProvider;\n}): Storage {\n return buildS3Storage({\n endpoint: `https://s3.${opts.region}.amazonaws.com`,\n region: opts.region,\n bucket: opts.bucket,\n credentials: opts.credentials,\n });\n}\n\n/**\n * Cloudflare R2 `Storage` factory (S3-compat endpoint). Derives the\n * endpoint from `accountId` as\n * `https://<accountId>.r2.cloudflarestorage.com` and pins region\n * `\"auto\"` — R2 ignores region but `aws4fetch`'s signer requires\n * the field to be set.\n *\n * For Workers that have a native R2 binding (no HTTP hop), see\n * `r2BindingStorage` in `@baerly/adapter-cloudflare`. This factory\n * is for Node hosts that talk to R2 over its public S3-compat URL.\n *\n * @example\n * ```ts\n * import { r2Storage } from \"@gusto/baerly-storage/node\";\n *\n * const storage = r2Storage({\n * accountId: process.env[\"R2_ACCOUNT_ID\"]!,\n * bucket: process.env[\"BUCKET\"]!,\n * credentials: {\n * accessKeyId: process.env[\"AWS_ACCESS_KEY_ID\"]!,\n * secretAccessKey: process.env[\"AWS_SECRET_ACCESS_KEY\"]!,\n * },\n * });\n * ```\n */\nexport function r2Storage(opts: {\n accountId: string;\n bucket: string;\n credentials: Credentials | CredentialsProvider;\n}): Storage {\n return buildS3Storage({\n endpoint: `https://${opts.accountId}.r2.cloudflarestorage.com`,\n region: \"auto\",\n bucket: opts.bucket,\n credentials: opts.credentials,\n });\n}\n\n/**\n * Minio `Storage` factory — for local-dev / self-hosted S3-compat.\n * Endpoint is fully caller-supplied (e.g. `http://localhost:9102`)\n * because Minio deployments don't follow a URL template. Region is\n * pinned to `\"us-east-1\"`; Minio ignores it but `aws4fetch` requires\n * a value.\n *\n * @example\n * ```ts\n * import { minioStorage } from \"@gusto/baerly-storage/node\";\n *\n * const storage = minioStorage({\n * endpoint: process.env[\"BAERLY_S3_ENDPOINT\"] ?? \"http://localhost:9102\",\n * bucket: \"baerly\",\n * credentials: {\n * accessKeyId: process.env[\"MINIO_ACCESS_KEY\"]!,\n * secretAccessKey: process.env[\"MINIO_SECRET_KEY\"]!,\n * },\n * });\n * ```\n */\nexport function minioStorage(opts: {\n endpoint: string;\n bucket: string;\n credentials: Credentials | CredentialsProvider;\n}): Storage {\n return buildS3Storage({\n endpoint: opts.endpoint,\n region: \"us-east-1\",\n bucket: opts.bucket,\n credentials: opts.credentials,\n });\n}\n\n/**\n * Google Cloud Storage `Storage` factory via the S3-compat endpoint\n * at `https://storage.googleapis.com`. Authentication uses GCS HMAC\n * keys (Console → Settings → Interoperability) — the HMAC access key\n * goes into `credentials.accessKeyId` and the HMAC secret goes into\n * `credentials.secretAccessKey`. Region is pinned to `\"auto\"`.\n *\n * GCS's S3-compat surface covers the four `Storage` methods\n * (`get`/`put`/`delete`/`list`), but Google documents the\n * `If-Match`/`If-None-Match` headers this kernel coordinates on as\n * read-only (native conditional writes use `x-goog-if-generation-match`).\n * Whether GCS's interop layer enforces S3-style conditional *writes* is\n * unverified — run `baerly doctor --bucket=<your-gcs-bucket>` before\n * relying on it; a backend that fails the CAS probe is not a safe baerly\n * store. See ADR-004.\n *\n * @example\n * ```ts\n * import { gcsStorage } from \"@gusto/baerly-storage/node\";\n *\n * const storage = gcsStorage({\n * bucket: process.env[\"BUCKET\"]!,\n * credentials: {\n * accessKeyId: process.env[\"GCS_HMAC_ACCESS_KEY_ID\"]!,\n * secretAccessKey: process.env[\"GCS_HMAC_SECRET\"]!,\n * },\n * });\n * ```\n */\nexport function gcsStorage(opts: {\n bucket: string;\n credentials: Credentials | CredentialsProvider;\n}): Storage {\n return buildS3Storage({\n endpoint: \"https://storage.googleapis.com\",\n region: \"auto\",\n bucket: opts.bucket,\n credentials: opts.credentials,\n });\n}\n","/**\n * Bucket URI parsing for the CLI surface. Consumed by every\n * `baerly admin <cmd>`, `baerly inspect`, and `baerly export`.\n *\n * Grammar:\n * - `s3://<bucket>[/<prefix>]` — S3-compatible HTTP. Creds via env\n * vars (`BAERLY_S3_ENDPOINT`, `BAERLY_S3_ACCESS_KEY_ID`,\n * `BAERLY_S3_SECRET_ACCESS_KEY`, `BAERLY_S3_REGION` — region\n * defaults to `us-east-1`).\n * - `file:///<absolute-path>` — `LocalFsStorage` rooted at the path.\n * Relative paths are rejected by the three-slash prefix.\n * - `memory://<bucket>` — `MemoryStorage` keyed via\n * `getOrCreateMemoryStorageForBucket`. Test-only.\n */\n\nimport { LocalFsStorage } from \"@baerly/dev\";\nimport { minioStorage, r2Storage, s3Storage } from \"@baerly/adapter-node\";\nimport { BaerlyError, getOrCreateMemoryStorageForBucket, type Storage } from \"@baerly/protocol\";\n\n/**\n * Result of `parseBucketUri`. `storage` is a constructed `Storage`\n * handle; `keyPrefix` is \"\" for an unprefixed bucket, or a non-empty\n * string ending in `/` for a prefixed one. The target side prepends\n * this to every emitted key.\n */\nexport interface ParsedBucketUri {\n storage: Storage;\n /** Empty for no-prefix; non-empty always ends with \"/\". */\n keyPrefix: string;\n}\n\n/**\n * Parse a bucket URI into a constructed `Storage` handle + optional\n * key prefix.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — unsupported scheme, or an\n * `s3://` URI with a missing env var.\n */\nexport const parseBucketUri = async (uri: string): Promise<ParsedBucketUri> => {\n if (uri.startsWith(\"s3://\")) {\n const rest = uri.slice(5);\n const slash = rest.indexOf(\"/\");\n const bucket = slash === -1 ? rest : rest.slice(0, slash);\n const prefix = slash === -1 ? \"\" : rest.slice(slash + 1);\n if (bucket.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `bucket URI: s3:// URI requires a bucket name (got ${JSON.stringify(uri)})`,\n );\n }\n const accessKeyId = requireEnv(\"BAERLY_S3_ACCESS_KEY_ID\");\n const secretAccessKey = requireEnv(\"BAERLY_S3_SECRET_ACCESS_KEY\");\n const region = process.env[\"BAERLY_S3_REGION\"] ?? \"us-east-1\";\n const endpoint = requireEnv(\"BAERLY_S3_ENDPOINT\");\n // Endpoint-pattern dispatch. AWS-shaped → `s3Storage`; R2-shaped →\n // `r2Storage`; anything else (user-supplied / Minio) → `minioStorage`\n // so the full endpoint flows through verbatim.\n const r2Host = endpoint.match(/^https?:\\/\\/([^./]+)\\.r2\\.cloudflarestorage\\.com\\b/i);\n const isAws = /^https?:\\/\\/s3(\\.[^.]+)?\\.amazonaws\\.com\\b/i.test(endpoint);\n const storage: Storage = pickS3Storage({\n r2Host,\n isAws,\n endpoint,\n bucket,\n accessKeyId,\n secretAccessKey,\n region,\n });\n return {\n storage,\n keyPrefix: normalizeKeyPrefix(prefix),\n };\n }\n if (uri.startsWith(\"file:///\")) {\n return { storage: new LocalFsStorage({ root: uri.slice(7) }), keyPrefix: \"\" };\n }\n if (uri.startsWith(\"memory://\")) {\n const bucket = uri.slice(9);\n if (bucket.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `bucket URI: memory:// URI requires a bucket name (got ${JSON.stringify(uri)})`,\n );\n }\n return { storage: getOrCreateMemoryStorageForBucket(bucket), keyPrefix: \"\" };\n }\n throw new BaerlyError(\"InvalidConfig\", `bucket URI: unsupported URI ${JSON.stringify(uri)}`);\n};\n\nconst requireEnv = (name: string): string => {\n const v = process.env[name];\n if (v === undefined || v === \"\") {\n throw new BaerlyError(\"InvalidConfig\", `bucket URI: env var ${name} unset`);\n }\n return v;\n};\n\n// Endpoint-shape dispatch for `s3://...` URIs. Extracted so the parser\n// doesn't carry an inline nested ternary.\ninterface S3StoragePick {\n readonly r2Host: RegExpMatchArray | null;\n readonly isAws: boolean;\n readonly endpoint: string;\n readonly bucket: string;\n readonly accessKeyId: string;\n readonly secretAccessKey: string;\n readonly region: string;\n}\nconst pickS3Storage = (opts: S3StoragePick): Storage => {\n const { r2Host, isAws, endpoint, bucket, accessKeyId, secretAccessKey, region } = opts;\n if (r2Host !== null) {\n return r2Storage({\n accountId: r2Host[1]!,\n bucket,\n credentials: { accessKeyId, secretAccessKey },\n });\n }\n if (isAws) {\n return s3Storage({ region, bucket, credentials: { accessKeyId, secretAccessKey } });\n }\n return minioStorage({ endpoint, bucket, credentials: { accessKeyId, secretAccessKey } });\n};\n\n// \"/foo\" → \"foo/\"; \"\" → \"\"; \"foo/\" stays \"foo/\". S3 prefixes are\n// keystroke-significant; canonicalize to ensure the manifest pointer\n// at the target matches its source's encoding.\nconst normalizeKeyPrefix = (prefix: string): string => {\n if (prefix === \"\") {\n return \"\";\n }\n if (prefix.endsWith(\"/\")) {\n return prefix;\n }\n return `${prefix}/`;\n};\n","/**\n * `baerly.config.ts` loader for `baerly deploy` / `baerly doctor`.\n *\n * Mirrors the shape of `BaerlyAppConfig` from `@gusto/baerly-storage/config`\n * but lives in `@baerly/cli` so the validator/loader doesn't depend on\n * the rolldown'd umbrella bundle. The scaffolder emits the config file;\n * the CLI reads it. Both sides agree on the wire shape (informally —\n * the duplication is small and intentional).\n *\n * Resolution order:\n * 1. `<cwd>/baerly.config.ts`\n * 2. `<cwd>/baerly.config.js`\n * 3. `<cwd>/baerly.config.mjs`\n * 4. `<cwd>/baerly.config.json`\n *\n * The `.ts` form requires the user to have a TS-aware Node entry\n * point (`tsx`, `--experimental-strip-types`, or a build step that\n * produced the `.js` alongside). If `import()` throws on the `.ts`\n * file, we re-wrap as `InvalidConfig` with a hint pointing at the\n * `.js` / `.json` fallbacks.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport {\n AUTH_CONFIG_VALUES,\n type AuthConfig,\n type BaerlyConfig,\n BaerlyError,\n type IndexDefinition,\n} from \"@baerly/protocol\";\n\nexport interface AppConfig {\n readonly app: string;\n readonly tenant: string;\n readonly target: \"cloudflare\" | \"node\";\n /**\n * Required. See `AuthConfig` for the per-value semantics. The loader\n * throws `BaerlyError(\"InvalidConfig\", ...)` when `auth` is missing or\n * not a member of `AUTH_CONFIG_VALUES`.\n */\n readonly auth: AuthConfig;\n readonly domain?: string;\n readonly requiredSecrets?: readonly string[];\n readonly cloudflareAccess?: {\n readonly teamDomain: string;\n readonly audienceTag: string;\n };\n /** Absolute path to the repo root that contained the config. */\n readonly repoRoot: string;\n}\n\nconst CONFIG_BASENAMES: readonly string[] = [\n \"baerly.config.ts\",\n \"baerly.config.js\",\n \"baerly.config.mjs\",\n \"baerly.config.json\",\n];\n\n/**\n * Locate the first `baerly.config.*` file under `cwd`. Returns the\n * absolute path or `null` if none exists.\n *\n * Exported so the collection-aware loader (and future consumers) can\n * reuse the same resolution order without re-implementing it.\n */\nexport const locateConfig = (cwd: string): string | null => {\n for (const base of CONFIG_BASENAMES) {\n const abs = resolve(cwd, base);\n if (existsSync(abs)) {\n return abs;\n }\n }\n return null;\n};\n\n/**\n * Load `baerly.config.{ts,js,mjs,json}` from `cwd` (defaults to\n * `process.cwd()`). Validates the required fields and the\n * locked-shape optionals; returns an `AppConfig` decorated with the\n * `repoRoot` it was loaded from.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — file missing, default\n * export missing, or any field has the wrong shape / type.\n */\nexport const loadAppConfig = async (cwd: string = process.cwd()): Promise<AppConfig> => {\n const cfgPath = locateConfig(cwd);\n if (cfgPath === null) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: no baerly.config.{ts,js,mjs,json} at ${cwd}. Are you in a baerly app directory?`,\n );\n }\n\n let raw: unknown;\n if (cfgPath.endsWith(\".json\")) {\n let text: string;\n try {\n text = await readFile(cfgPath, \"utf8\");\n } catch (error) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: failed to read ${cfgPath}: ${(error as Error).message}`,\n error,\n );\n }\n try {\n raw = JSON.parse(text) as unknown;\n } catch (error) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: failed to parse ${cfgPath}: ${(error as Error).message}`,\n error,\n );\n }\n } else {\n let mod: { default?: unknown };\n try {\n mod = (await import(pathToFileURL(cfgPath).href)) as { default?: unknown };\n } catch (error) {\n const hint = cfgPath.endsWith(\".ts\")\n ? \" (Node cannot import .ts directly without a TS loader — point at the compiled .js or use a .json config)\"\n : \"\";\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: failed to load ${cfgPath}: ${(error as Error).message}${hint}`,\n error,\n );\n }\n raw = mod.default;\n }\n\n if (raw === undefined || typeof raw !== \"object\" || raw === null) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath} must default-export a BaerlyAppConfig object`,\n );\n }\n\n const obj = raw as Record<string, unknown>;\n const app = obj[\"app\"];\n const tenant = obj[\"tenant\"];\n const target = obj[\"target\"];\n if (typeof app !== \"string\" || app.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`app\\` must be a non-empty string`,\n );\n }\n if (typeof tenant !== \"string\" || tenant.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`tenant\\` must be a non-empty string`,\n );\n }\n if (target !== \"cloudflare\" && target !== \"node\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`target\\` must be \"cloudflare\" or \"node\" (got ${JSON.stringify(target)})`,\n );\n }\n\n // `auth` is a required typed posture as of the graduated-auth\n // redesign. The widening cast to `readonly string[]` is needed\n // because `.includes` on a tuple narrows its parameter to the\n // tuple's element type; widening locally is the standard idiom.\n const authRaw = obj[\"auth\"];\n if (typeof authRaw !== \"string\" || !(AUTH_CONFIG_VALUES as readonly string[]).includes(authRaw)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`auth\\` is required and must be one of ${JSON.stringify(AUTH_CONFIG_VALUES)} (got ${JSON.stringify(authRaw)})`,\n );\n }\n const auth = authRaw as AuthConfig;\n\n const domainRaw = obj[\"domain\"];\n if (domainRaw !== undefined && typeof domainRaw !== \"string\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`domain\\` must be a string when set`,\n );\n }\n\n const secretsRaw = obj[\"requiredSecrets\"];\n let requiredSecrets: readonly string[] | undefined;\n if (secretsRaw !== undefined) {\n if (!Array.isArray(secretsRaw) || !secretsRaw.every((s) => typeof s === \"string\")) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`requiredSecrets\\` must be an array of strings`,\n );\n }\n requiredSecrets = secretsRaw as readonly string[];\n }\n\n const cfaRaw = obj[\"cloudflareAccess\"];\n let cloudflareAccess: AppConfig[\"cloudflareAccess\"];\n if (cfaRaw !== undefined) {\n if (typeof cfaRaw !== \"object\" || cfaRaw === null) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`cloudflareAccess\\` must be an object when set`,\n );\n }\n const cfa = cfaRaw as Record<string, unknown>;\n const td = cfa[\"teamDomain\"];\n const aud = cfa[\"audienceTag\"];\n if (typeof td !== \"string\" || td.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`cloudflareAccess.teamDomain\\` must be a non-empty string`,\n );\n }\n if (typeof aud !== \"string\" || aud.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`cloudflareAccess.audienceTag\\` must be a non-empty string`,\n );\n }\n cloudflareAccess = { teamDomain: td, audienceTag: aud };\n }\n\n return {\n app,\n tenant,\n target,\n auth,\n ...(domainRaw !== undefined && { domain: domainRaw }),\n ...(requiredSecrets !== undefined && { requiredSecrets }),\n ...(cloudflareAccess !== undefined && { cloudflareAccess }),\n repoRoot: cwd,\n };\n};\n\n/**\n * Lightweight per-collection index reflection. Mirrors the shape the\n * runtime `BaerlyConfig` carries, but only the fields the doctor needs.\n *\n * `indexes` is an empty array when the collection declared none.\n */\nexport interface LoadedCollection {\n readonly name: string;\n readonly indexes: readonly IndexDefinition[];\n}\n\n/**\n * Load `baerly.config.{ts,js,mjs,json}` AND return the parsed\n * `collections[*]` shape alongside the narrow {@link AppConfig}. Lets\n * the doctor reflect on declared indexes without forcing every consumer\n * to widen `AppConfig`. Returns `undefined` for `collections` when the\n * config doesn't declare any (the doctor downgrades the drift check to\n * a no-op `info` finding in that case).\n *\n * Re-uses {@link loadAppConfig}'s parse/validate path, so the\n * `AppConfig` invariants are still enforced.\n */\nexport const loadAppConfigWithCollections = async (\n cwd: string = process.cwd(),\n): Promise<{\n readonly config: AppConfig;\n readonly collections: readonly LoadedCollection[] | undefined;\n}> => {\n const config = await loadAppConfig(cwd);\n const cfgPath = locateConfig(cwd);\n if (cfgPath === null) {\n return { config, collections: undefined };\n }\n\n // Re-parse the raw default-export to pluck `collections[*]`. We\n // don't validate the inner shape here — at the doctor surface,\n // anything that isn't an object is reported as \"no filtered\n // indexes\" rather than throwing, so a partially-typed config\n // doesn't fail the whole check.\n let raw: unknown;\n if (cfgPath.endsWith(\".json\")) {\n let text: string;\n try {\n text = await readFile(cfgPath, \"utf8\");\n } catch {\n return { config, collections: undefined };\n }\n try {\n raw = JSON.parse(text);\n } catch {\n return { config, collections: undefined };\n }\n } else {\n try {\n const mod = (await import(pathToFileURL(cfgPath).href)) as { default?: unknown };\n raw = mod.default;\n } catch {\n // Node can't `import` a .ts file without a TS loader. The\n // narrow `loadAppConfig` already surfaced the InvalidConfig if\n // that path was unreadable; here we silently downgrade to\n // \"no collections\" rather than re-throw.\n return { config, collections: undefined };\n }\n }\n\n if (raw === undefined || raw === null || typeof raw !== \"object\") {\n return { config, collections: undefined };\n }\n const colsRaw = (raw as { collections?: unknown }).collections;\n if (colsRaw === undefined || colsRaw === null || typeof colsRaw !== \"object\") {\n return { config, collections: undefined };\n }\n\n const out: LoadedCollection[] = [];\n for (const [name, decl] of Object.entries(colsRaw as Record<string, unknown>)) {\n if (decl === null || typeof decl !== \"object\") {\n continue;\n }\n const indexes = (decl as { indexes?: unknown }).indexes;\n if (!Array.isArray(indexes)) {\n out.push({ name, indexes: [] });\n continue;\n }\n // Pass-through cast: the runtime IndexDefinition validation\n // lives in `@baerly/server`; the doctor only reads `name`, `on`,\n // and `predicate`, so a partial shape still gives an actionable\n // finding rather than a SchemaError throw at config-load time.\n out.push({ name, indexes: indexes as readonly IndexDefinition[] });\n }\n return { config, collections: out };\n};\n\n/**\n * Load the declared `IndexDefinition[]` for a single collection from a\n * `baerly.config.{js,mjs,json}`. Used by `baerly inspect` (key-count\n * probes) and `baerly admin rebuild-index` (resolving the `on` field).\n *\n * `.ts` configs are rejected — Node can't `import` them without a TS\n * loader; point at the compiled `.js` output instead.\n *\n * `commandName` is woven into thrown error messages so the operator\n * sees the calling command name in the prefix.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — `.ts` extension, JSON\n * parse error, missing default export, or missing\n * `collections[collection]`.\n */\nexport const loadCollectionIndexes = async (\n configPath: string,\n collection: string,\n commandName: string,\n): Promise<readonly IndexDefinition[]> => {\n if (configPath.endsWith(\".ts\")) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${commandName}: --config must point at compiled JS / JSON (got .ts: ${JSON.stringify(configPath)})`,\n );\n }\n let cfg: BaerlyConfig;\n if (configPath.endsWith(\".json\")) {\n const text = await readFile(configPath, \"utf8\");\n try {\n cfg = JSON.parse(text) as BaerlyConfig;\n } catch (error) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${commandName}: --config JSON parse error in ${JSON.stringify(configPath)}: ${(error as Error).message}`,\n );\n }\n } else {\n const abs = configPath.startsWith(\"file://\") ? fileURLToPath(configPath) : resolve(configPath);\n const mod = (await import(pathToFileURL(abs).href)) as { default?: BaerlyConfig };\n if (mod.default === undefined) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${commandName}: --config ${JSON.stringify(configPath)} has no default export`,\n );\n }\n cfg = mod.default;\n }\n return cfg.collections?.[collection]?.indexes ?? [];\n};\n"],"x_google_ignoreList":[5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,23],"mappings":";;;;;;;;;;;;;AAKA,MAAa,gBAAgB;;;;;AAuG7B,MAAa,4BAAoC;;;;;;;;;;AAoDjD,MAAa,wBAAgC;;;;;;;;AAsB7C,MAAa,4BAAoC;;;;;;AAoB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