@blamejs/blamejs-shop 0.2.15 → 0.2.17

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.
Files changed (51) hide show
  1. package/CHANGELOG.md +3 -1
  2. package/README.md +1 -1
  3. package/lib/asset-manifest.json +5 -1
  4. package/lib/customers.js +71 -4
  5. package/lib/storefront.js +462 -0
  6. package/lib/vendor/MANIFEST.json +2 -2
  7. package/lib/vendor/blamejs/CHANGELOG.md +20 -0
  8. package/lib/vendor/blamejs/api-snapshot.json +6 -2
  9. package/lib/vendor/blamejs/examples/wiki/docker-compose.prod.yml +29 -0
  10. package/lib/vendor/blamejs/examples/wiki/docker-compose.yml +7 -0
  11. package/lib/vendor/blamejs/lib/agent-idempotency.js +15 -3
  12. package/lib/vendor/blamejs/lib/agent-orchestrator.js +39 -0
  13. package/lib/vendor/blamejs/lib/app-shutdown.js +32 -0
  14. package/lib/vendor/blamejs/lib/bounded-map.js +102 -0
  15. package/lib/vendor/blamejs/lib/cache.js +184 -23
  16. package/lib/vendor/blamejs/lib/cert.js +68 -11
  17. package/lib/vendor/blamejs/lib/cluster-storage.js +114 -10
  18. package/lib/vendor/blamejs/lib/db.js +205 -15
  19. package/lib/vendor/blamejs/lib/dual-control.js +139 -143
  20. package/lib/vendor/blamejs/lib/i18n.js +10 -1
  21. package/lib/vendor/blamejs/lib/mail-crypto-smime.js +43 -9
  22. package/lib/vendor/blamejs/lib/network-dns.js +10 -2
  23. package/lib/vendor/blamejs/lib/nonce-store.js +39 -12
  24. package/lib/vendor/blamejs/lib/queue-local.js +2 -2
  25. package/lib/vendor/blamejs/lib/redis-client.js +14 -1
  26. package/lib/vendor/blamejs/lib/subject.js +8 -1
  27. package/lib/vendor/blamejs/package.json +1 -1
  28. package/lib/vendor/blamejs/release-notes/v0.13.33.json +26 -0
  29. package/lib/vendor/blamejs/release-notes/v0.13.34.json +48 -0
  30. package/lib/vendor/blamejs/release-notes/v0.13.35.json +35 -0
  31. package/lib/vendor/blamejs/release-notes/v0.13.36.json +27 -0
  32. package/lib/vendor/blamejs/release-notes/v0.13.37.json +18 -0
  33. package/lib/vendor/blamejs/release-notes/v0.13.38.json +27 -0
  34. package/lib/vendor/blamejs/release-notes/v0.13.39.json +27 -0
  35. package/lib/vendor/blamejs/release-notes/v0.13.40.json +22 -0
  36. package/lib/vendor/blamejs/release-notes/v0.13.41.json +27 -0
  37. package/lib/vendor/blamejs/release-notes/v0.13.42.json +18 -0
  38. package/lib/vendor/blamejs/test/20-db.js +191 -0
  39. package/lib/vendor/blamejs/test/layer-0-primitives/agent-idempotency.test.js +20 -0
  40. package/lib/vendor/blamejs/test/layer-0-primitives/agent-orchestrator.test.js +33 -0
  41. package/lib/vendor/blamejs/test/layer-0-primitives/api-encrypt.test.js +35 -0
  42. package/lib/vendor/blamejs/test/layer-0-primitives/app-shutdown.test.js +64 -0
  43. package/lib/vendor/blamejs/test/layer-0-primitives/bounded-map.test.js +87 -0
  44. package/lib/vendor/blamejs/test/layer-0-primitives/cache.test.js +48 -0
  45. package/lib/vendor/blamejs/test/layer-0-primitives/cert.test.js +170 -0
  46. package/lib/vendor/blamejs/test/layer-0-primitives/cluster-storage.test.js +125 -0
  47. package/lib/vendor/blamejs/test/layer-0-primitives/codebase-patterns.test.js +92 -1
  48. package/lib/vendor/blamejs/test/layer-0-primitives/dual-control.test.js +32 -0
  49. package/lib/vendor/blamejs/test/layer-0-primitives/mail-crypto-smime.test.js +31 -0
  50. package/lib/vendor/blamejs/test/layer-0-primitives/redis-client.test.js +14 -0
  51. package/package.json +1 -1
@@ -8,6 +8,26 @@ upgrading across more than a few patches at a time.
8
8
 
9
9
  ## v0.13.x
10
10
 
11
+ - v0.13.42 (2026-05-29) — **S/MIME trust-chain validation binds the leaf to the key that verified the signature.** When b.mail.crypto.smime.verify is given trust anchors, it validates the supplied certificate chain — but it picked the chain leaf unconditionally (the first cert) and never tied it to signerPublicKey, the key that actually verified the signature. A SignedData blob could therefore carry a validly-chained certificate for one identity while the signature was verified under an unrelated key, and the chain-validated result would imply a cert↔signer binding the code never made. Chain validation now selects the leaf as the certificate whose public key matches signerPublicKey, and refuses (signer-not-in-chain) when no certificate in the chain carries that key — so a chain-validated signature is bound to the cert it claims. **Security:** *Trust-chain leaf is bound to the verified signer key* — `smime.verify({ trustAnchorCertsPem })` validated the supplied chain starting from `chain[0]` without checking that the leaf's public key was the one that verified the signature (the operator-supplied `signerPublicKey`). A crafted `SignedData` could pair a validly-chained certificate for identity A with a signature verified under an unrelated key, and the chain-valid result would assert a binding that didn't hold. The chain walk now selects the leaf as the certificate whose public key equals `signerPublicKey` (matched against the certificate's SPKI, raw key or full-encoding form), and throws `mail-crypto/smime/signer-not-in-chain` when no certificate in `SignedData.certificates` carries that key. A certificate whose key cannot be extracted is treated as a non-match, so validation fails closed rather than trusting an unverifiable binding.
12
+
13
+ - v0.13.41 (2026-05-29) — **Agent registry reads can be tenant-scoped; compliance-erasure docs clarify actor is an audit field.** The agent orchestrator's registry reads (list and lookup) gated only on the flat agent-registry:read scope, so any holder could enumerate every tenant's agents and resolve a handle to one — even though the event bus already scopes subscribe and delivery by tenant. The orchestrator now mirrors that: with the new tenantScope option enabled, list returns only the actor's own tenant's agents and lookup refuses a cross-tenant name, unless the actor holds the framework cross-tenant-admin scope. Off by default, so single-tenant deployments are unaffected. Separately, the subject-erasure docs now state explicitly that the recorded actor is an audit field, not authentication — the caller must be authorized upstream. **Added:** *Tenant-scoped agent registry reads (opts.tenantScope)* — `b.agent.orchestrator.create({ tenantScope: true })` now scopes `list` and `lookup` to the calling actor's tenant: `list` filters out agents in other tenants and `lookup` returns null for a cross-tenant name, unless the actor holds the cross-tenant-admin scope (`b.agent.tenant.CROSS_TENANT_ADMIN_SCOPE`). This closes a cross-tenant metadata-enumeration and handle-acquisition path — `agent-registry:read` alone no longer exposes other tenants' agents — and mirrors the tenant scoping the event bus enforces on subscribe and delivery. The option defaults off; existing single-tenant orchestrators behave exactly as before. The `tenantId` argument to `list` remains a convenience filter, distinct from this authorization boundary. **Changed:** *Subject-erasure docs clarify the actor is an audit field, not authentication* — `b.subject.erase` and `b.subject.eraseHard` gate the deletion on operator acknowledgements and the legal-hold registry, not on caller identity. Their documentation now states explicitly that the recorded `actor` is an audit-record field, not authentication — the caller MUST be authenticated and authorized by the route before invoking. No behavior change; this removes an implicit assumption that could otherwise be read as the primitive authorizing the call.
14
+
15
+ - v0.13.40 (2026-05-29) — **Redis client stops leaking a socket and blocking exit after close; DB exit-handler registers once.** Two handle-lifecycle fixes. The Redis client's reconnect backoff used an untracked, non-unref'd timer: during a backoff window it alone could keep the event loop alive (a process that won't exit), and a reconnect scheduled before close() fired afterward and opened a fresh socket because the connect path didn't re-check the closing flag. The timer is now tracked, unref'd, cancelled in close(), and the connect path refuses to re-open once closing. Separately, the encrypted database registered its process-exit final-flush handler on every init(), so repeated init/close cycles (long test runs, hot reload) accumulated 'exit' listeners toward the MaxListenersExceeded warning; it now registers once for the process lifetime. **Fixed:** *Redis client cancels its reconnect timer on close and won't re-open a closed connection* — The reconnect backoff scheduled `setTimeout(reconnect, delay)` without keeping a handle, without `unref()`, and the reconnect path checked only `connected`/`connecting` — not `closing`. So a backoff window could by itself hold the process open (it won't exit), and a reconnect scheduled before `close()` would fire afterward and open a fresh socket with listeners — a leak after explicit close. The timer is now tracked and `unref()`'d (a backoff no longer blocks exit), cancelled in `close()`, and the connect path returns early once closing so no socket is opened after close. · *Encrypted DB registers its process-exit flush handler once, not per init()* — `b.db.init()` in encrypted mode added a `process.on("exit")` final-flush handler on every call. Across repeated init/close cycles — long test suites, hot reload, embedded re-inits — these accumulated and tripped Node's MaxListenersExceeded warning (and grew memory slightly). The handler is now registered once for the process lifetime, guarded by a module flag, and still flushes whichever encrypted DB is open at exit time.
16
+
17
+ - v0.13.39 (2026-05-29) — **Dual-control approvals are atomic — no quorum bypass or double-consume under concurrency.** The dual-control approval store read a grant, mutated it in memory, and wrote it back with an await in between — a non-atomic read-modify-write. Under concurrent calls (two approvals, or a retried one) each could act on a stale snapshot: the same approver could be appended twice and reach the M-of-N quorum with a single human, or a single-use grant could be consumed twice. approve / consume / revoke / cancel now commit through a new atomic cache.update primitive, so the check and the mutation are one indivisible step. The new b.cache.update is available to application code too — the memory backend is atomic by single-thread, and the cluster backend uses a transaction with compare-and-set so a concurrent writer on another node cannot lose an update. **Added:** *b.cache.update(key, mutatorFn, opts?) — atomic read-modify-write* — Reads the current value, calls `mutatorFn(current | null)`, and commits the result in one operation so a concurrent writer cannot clobber the change — the lost-update race that makes a plain `get` → mutate → `set` unsafe for counters, sets, and quorum state. The memory backend is atomic by single-thread; the cluster backend runs a transaction with a compare-and-set (and retries on contention) so the guarantee holds across nodes. `mutatorFn` returns `{ value }` to commit, `{ abort: data }` to leave the entry untouched and surface `data`, or `{ delete: true }` to remove it; the call resolves to `{ updated, value }`, `{ updated, deleted }`, or `{ aborted }`. **Security:** *Dual-control quorum and single-use guarantees hold under concurrent approvals* — `b.dualControl` persisted each grant through a cache read → in-memory mutate → write-back. Because the read and the write were separate awaited steps, two concurrent `approve` calls (or a retried one behind a load balancer) could each read the same pre-approval snapshot, so the duplicate-approver guard passed twice and the same approver was counted toward the M-of-N quorum twice — reaching quorum with one human. The same shape let two concurrent `consume` calls each see an unconsumed grant and both run the destructive operation. `approve` / `consume` / `revoke` / `cancel` now perform the check-and-mutate atomically via `cache.update`, so exactly one concurrent caller wins each transition.
18
+
19
+ - v0.13.38 (2026-05-29) — **Atomic cache tag invalidation, and a clusterStorage.transaction primitive for multi-statement framework writes.** The cluster cache stored a value and its tag index with separate statements, so two concurrent writes to the same key could interleave their tag updates and leave the index out of step with the value — a later tag-based invalidation would then miss the key, letting a stale (possibly authorization-bearing) value survive a wipe. The value and tag writes now commit as one atomic unit. The enabling piece is a new b.clusterStorage.transaction primitive that runs a multi-statement read-modify-write all-or-nothing against the active backend — the external DB's pooled transaction in cluster mode, and a serialized transaction on the shared SQLite connection in single-node mode (so no concurrent statement can interleave into an open transaction). **Added:** *b.clusterStorage.transaction(fn) — atomic multi-statement framework-state writes* — Runs `fn` inside one transaction against the active backend so a multi-statement read-modify-write commits all-or-nothing. `fn` receives a transaction handle with the same `execute` / `executeOne` / `executeAll` surface, scoped to the open transaction. Cluster mode uses the external DB's pooled transaction (with its deadlock retry); single-node mode serializes against other transactions and against `execute` on the shared SQLite connection, so a concurrent statement cannot interleave into an open transaction. Use the handle's methods inside `fn` — calling the module-level `execute` from within `fn` would wait on the very transaction it is running. **Fixed:** *Cluster cache tag invalidation can no longer miss a key under concurrent writes* — The cluster cache wrote a value (`INSERT ... ON CONFLICT DO UPDATE`) and then rewrote its tag index (`DELETE` prior tags, `INSERT` new ones) as separate statements. Two concurrent `set()`s on the same key could interleave those tag statements, leaving the tag index inconsistent with the value — so a later `invalidateTag` could miss the key and a stale value would survive the wipe. The value and tag writes now run inside a single `clusterStorage.transaction`, so a concurrent writer observes either the whole prior state or the whole new state, never a mix.
20
+
21
+ - v0.13.37 (2026-05-29) — **Encrypted-mode DB refuses writes before a full tmpfs corrupts it.** In encrypted-at-rest mode the live SQLite working copy is on a tmpfs (Docker's /dev/shm defaults to 64 MiB). If that fills — an append-only audit chain and session rows grow over time — SQLite hits ENOSPC and the working copy is corrupted. Earlier releases made that corruption self-heal on the next boot by rolling back to the last encrypted snapshot, but the rollback still loses writes since the last flush. This adds the prevention side: a periodic free-space probe refuses growth writes (INSERT / UPDATE / REPLACE) with a clear db/storage-low error once free space drops below a threshold, before the tmpfs fills. DELETE and reads stay available so retention can reclaim space and the application keeps serving, and the refusal lifts automatically once free space recovers. The threshold defaults to 16 MiB of headroom and is tunable; the guard is encrypted-mode only. **Security:** *Free-space guard refuses growth writes before the tmpfs working copy fills* — `b.db` in encrypted-at-rest mode now probes free space on the tmpfs holding the working copy and, when it falls below `minFreeBytes` (default 16 MiB), refuses `INSERT` / `UPDATE` / `REPLACE` with a clear `db/storage-low` error instead of letting the write run the mount out of space and corrupt the database. `DELETE`, reads, and DDL stay available so retention can prune and the app keeps serving; the refusal clears automatically when free space recovers. The error message points at the cause (Docker's 64 MiB `/dev/shm` default) and the fix (`shm_size` / `--shm-size`, or pruning). Set `minFreeBytes` to tune the headroom, or `0` to disable. This complements the existing boot-time recovery: prevention (fail clear, keep recent writes) ahead of recovery (roll back to the last snapshot).
22
+
23
+ - v0.13.36 (2026-05-29) — **Certificate renewal trusts the sealed cert's own expiry, not the plaintext index.** The managed-certificate renewal check decided a cached cert was still fresh by reading expiresAt from the plaintext meta.json index that sits beside the sealed cert, rather than from the certificate itself. If that index drifted from — or was tampered relative to — the actual cert (a far-future expiry recorded over a certificate that is in fact near expiry), the manager would skip renewal and keep serving a cert that was about to expire or already had. Renewal now re-derives the expiry and fingerprint from the sealed certificate itself; meta.json is treated as an advisory convenience copy. A sealed cert that no longer parses is re-issued (the same recovery as an unreadable one), and a corrupt meta.json over a valid cert now loads cleanly from the cert instead of forcing a needless re-issue. The local job queue also bounds the size of a job payload it parses back from a stored row, matching the cap the dead-letter listing already used. **Fixed:** *Local job queue bounds the size of a payload parsed back from a stored row* — When the local queue leased a job or re-enqueued a repeating one, it parsed the job payload back from its stored row without an upper size bound, unlike the dead-letter listing which already capped it. A row with an oversized payload (a corrupted or tampered store) could force an unbounded parse. Both paths now cap the parse at the same 64 MiB ceiling the dead-letter path uses. **Security:** *Cert renewal re-derives expiry from the sealed certificate, not the meta.json index* — `b.cert`'s renewal short-circuit read `expiresAt` from the plaintext `meta.json` written beside each sealed cert. Because that index can drift from the actual certificate (or be altered independently of it), a far-future value over an actually-expiring cert would suppress renewal and serve a cert past — or about to pass — its validity. The renewal decision now parses the expiry and fingerprint from the sealed certificate itself on load, so `meta.json` is advisory only. A sealed cert that will not parse is treated as corrupt and re-issued; a corrupt `meta.json` over an otherwise-valid cert loads from the cert without a needless re-issue.
24
+
25
+ - v0.13.35 (2026-05-29) — **In-memory replay, idempotency, DNS, and i18n stores gain entry-count ceilings.** Several framework caches keyed on request-influenced input grew without an upper bound between their periodic sweeps, so a flood of unique keys could exhaust process memory faster than the sweep reclaimed it. Each now enforces a hard entry ceiling. The replay-protection nonce store is the security-sensitive one: rather than evict a live nonce to admit a new one — which would reopen a replay window for the evicted nonce — it purges expired entries and then fails closed at capacity, refusing the unrecordable request instead of admitting it unprotected. The idempotency, DNS, and i18n caches hold re-derivable values, so they evict the oldest entry instead (the worst case is a recomputed value or a single re-executed retry under flood). Ceilings are generous defaults that normal traffic never reaches; the nonce store and the agent idempotency in-memory backend expose options to tune them. **Fixed:** *Agent idempotency in-memory backend no longer grows without bound* — The default in-memory backend for `b.agent.idempotency` is keyed on the request-supplied idempotency key, and its garbage collector only reclaims expired rows when an operator wires a scheduler to call it — so a flood of distinct keys could grow it until the process ran out of memory. It now caps its entry count and evicts oldest-first; a dropped record just means that one key re-executes on a later retry, never a crash. A new `maxInMemoryEntries` option tunes the ceiling (default 100,000); deployments needing a hard guarantee at scale still supply a durable `store`. · *DNS resolver cache is bounded* — The positive and negative resolver caches in `b.network.dns` reclaimed an expired entry only when the same hostname was looked up again, so entries for never-requeried hostnames persisted — and hostnames reaching the resolver are request-influenced (outbound request targets, mail MX lookups). Both caches now cap their entry count and evict oldest-first; DNS simply re-resolves on the next miss. · *i18n formatter cache is bounded* — Per-instance `Intl` formatter caches in `b.i18n` are keyed on the locale plus a hash of the format options. The format-options shape is open-ended and caller-supplied, so the key space was request-influenced and uncapped. The cache now enforces an entry ceiling and evicts oldest-first — a formatter is pure-derived and re-created on the next miss. **Security:** *Replay-nonce store bounds memory and fails closed under a nonce flood* — The in-memory `b.nonceStore` backend recorded every request-supplied nonce until a periodic sweep ran, so a stream of unique nonces could exhaust memory between sweeps (a memory-amplification denial of service). It now caps its entry count. Because a replay-protection store must never evict a live nonce to make room — doing so would reopen a replay window for the evicted nonce — it instead purges expired entries inline and, if still at capacity with live nonces, fails closed: the new request is refused rather than admitted without replay protection. A new `maxEntries` option tunes the ceiling (default 1,000,000).
26
+
27
+ - v0.13.34 (2026-05-29) — **Corrupt TLS certs self-heal at boot, and graceful shutdown no longer loses the final DB flush.** Two failure-mode fixes in the same family as the encrypted-DB recovery in 0.13.33. The cert manager treated a corrupt sealed cert or key worse than a missing one: a missing file re-issues via ACME, but a corrupt one let a raw decrypt error escape out of start(), so the same bad file was read on every boot — an unrecoverable crash loop. A corrupt sealed cert/key is now treated like an absent one and re-issued, and a corrupt derived meta.json is re-derived rather than fatal; the ACME account key (which binds order history) instead fails with an actionable error rather than a raw throw. On the shutdown side, an encrypted database that failed its final re-encrypt used to delete its plaintext working copy anyway, discarding every write since the last periodic flush; it now keeps the working copy so the next boot recovers it. The shutdown orchestrator also gains a hard-deadline watchdog: when the operator delegates signal handling to it, a phase that never settles can no longer hold the process open until the supervisor SIGKILLs it (which would skip the final DB re-encrypt) — the watchdog forces a clean exit, so exit handlers still flush. The wiki production and base compose files set a stop_grace_period above that budget so a docker stop or rolling redeploy lets the re-encrypt finish. **Changed:** *Shutdown watchdog forces a clean, DB-flushing exit if a phase hangs* — The graceful-shutdown orchestrator uses soft per-phase timeouts — on expiry the underlying work keeps running — so a phase that never settles could hold the event loop open past the grace window, after which a container supervisor SIGKILLs the process and skips the final DB re-encrypt. When the operator opts into signal handling, a watchdog now forces `process.exit` `graceMs + forceExitMarginMs` after the signal; exit runs the registered handlers (the DB re-encrypt), so the last flush still happens. A new `forceExitMarginMs` option (default 5000) tunes the headroom; set the container stop grace above `graceMs + forceExitMarginMs`. · *Wiki compose sets stop_grace_period above the shutdown budget* — `examples/wiki/docker-compose.yml` and `docker-compose.prod.yml` now set `stop_grace_period: 40s`. Docker's 10s default would SIGKILL the container before the 30s shutdown budget reaches the DB re-encrypt phase, losing the final flush on a `docker stop` or rolling redeploy. The production note also reminds PaaS platforms that regenerate the compose (Coolify, Dokku, CapRover) to set the stop grace via the platform UI alongside the persistent-storage mount and `--shm-size`. **Fixed:** *A corrupt sealed TLS cert or key re-issues instead of crash-looping at boot* — `b.cert`'s start path read the sealed `cert.pem`/`key.pem` and let a raw unseal/decrypt error escape if the file was truncated or corrupt, so a managed restart read the same bad file on every boot — a crash loop, and worse handling than an absent file (which already re-issues). A corrupt sealed cert/key is now treated like a missing one: it is logged, an audit event is emitted, and the certificate is re-issued via ACME. A corrupt derived `meta.json` is likewise re-derived rather than throwing `cert/bad-meta`. · *Unreadable ACME account key fails with an actionable error, not a raw decrypt throw* — Unlike a re-issuable certificate, the ACME account key binds existing order and authorization history, so it is not silently regenerated on corruption. An unreadable `account/jwk.json.sealed` now raises `cert/account-key-unreadable` naming the file and the recovery (restore from backup, or delete to register a fresh account) instead of letting a raw decrypt/parse error escape out of start(). · *Encrypted DB keeps its working copy when the final shutdown re-encrypt fails* — `db.close()` re-encrypts the tmpfs working copy to `db.enc`, then deletes the working copy. If that final re-encrypt failed (a full `/dev/shm`, a full disk), the delete still ran, discarding every write since the last periodic flush and leaving only the older `db.enc`. The working copy is now kept whenever the re-encrypt fails, so the next boot's integrity-probed recovery picks up the latest writes (and still falls back to `db.enc` if the working copy is itself corrupt). `db.enc` is never modified by this path. **Detectors:** *Cross-artifact guard that stop_grace_period covers the shutdown budget* — A new codebase check fails if either wiki compose file omits `stop_grace_period` or sets it below the orchestrator's `graceMs` plus the watchdog margin read from `lib/app-shutdown.js`, so raising the shutdown budget without bumping the compose — or dropping the setting — cannot silently reopen the SIGKILL-before-re-encrypt data-loss window.
28
+
29
+ - v0.13.33 (2026-05-28) — **Encrypted-mode DB recovers from a corrupt tmpfs working copy instead of crash-looping.** In encrypted-at-rest mode the live SQLite copy is decrypted into a tmpfs working file and re-encrypted to db.enc periodically. If that working copy was corrupted (an unclean shutdown, or a full tmpfs — Docker's /dev/shm defaults to 64 MiB), the boot path trusted it because its mtime was newer than db.enc, so db.init failed its integrity gate with "database disk image is malformed" identically on every boot — an unrecoverable crash loop. db now integrity-probes the newer working copy before trusting it: if it is unreadable, the working copy is discarded and db.enc (the last-good encrypted snapshot) is re-decrypted, so the next boot self-heals. db.enc is never modified by this path, and a genuinely-corrupt db.enc still fails loudly rather than wiping data. The boot error on an unreadable database is now actionable (it names the tmpfs-size cause and the recovery). The wiki production compose also gains the storage settings encrypted mode needs. **Fixed:** *Corrupt tmpfs working copy no longer causes a boot crash loop (encrypted-at-rest mode)* — `db.init`'s crash-recovery path preferred a newer tmpfs working copy over `db.enc` unconditionally. When that copy was corrupt (truncated by an unclean shutdown or a full `/dev/shm`), every boot trusted it and failed the integrity gate the same way — an unrecoverable loop. The newer working copy is now integrity-probed (`PRAGMA quick_check`); if it is unreadable it is discarded and `db.enc` — the last-good encrypted snapshot — is re-decrypted, so boot self-heals. `db.enc` is never modified, so this only ever rolls back to the persistent copy; if `db.enc` is also corrupt, boot still fails loudly (no silent data loss). A regression test pins the recovery. · *Actionable boot error when the database is unreadable* — When SQLite reports a database too corrupt to even run an integrity check, the boot error now names the likely cause and recovery instead of surfacing the raw "database disk image is malformed": in encrypted mode it points at the tmpfs working copy and the most common operational cause (Docker's 64 MiB `/dev/shm` default — raise it via `shm_size` / `--shm-size`), or restoring `db.enc` / the DB file from backup. · *Wiki production compose ships the storage encrypted mode needs* — `examples/wiki/docker-compose.prod.yml` now sets `shm_size: '512m'` (so the encrypted-mode tmpfs working copy has headroom above Docker's 64 MiB default) and mounts a persistent `wiki-data` volume at `/data` (so `db.enc` + sealed keys survive container recreate, host reboot, and image redeploys, and give a restore point). A note flags that PaaS platforms which regenerate the compose on deploy (Coolify, Dokku, CapRover, …) must set both via the platform UI — a persistent-storage mount for `/data` and a `--shm-size 512m` custom option.
30
+
11
31
  - v0.13.32 (2026-05-28) — **`b.auditDailyReview` enforces notify under the sox-404 posture; compliance doc corrections.** b.auditDailyReview documented `sox-404` (SOX §404 ICFR — the internal-controls regime this primitive serves) as one of the postures that make a `notify` callback mandatory at construction, but the enforcement set used only `sox`, so pinning `posture: "sox-404"` without a notify channel was silently accepted. `sox-404` is now in the mandatory-notify set, so the advertised guarantee holds (a regression test pins it). The rest are documentation corrections with no behavior change: b.compliance.posturesByDomain / posturesByJurisdiction examples showed small fixed arrays where the functions return every matching posture (the catalog has grown); b.dataAct's surface list named two methods that do not exist (the real surface is declareProduct / recordUserAccess / shareWithThirdParty / recordSwitchRequest, with gatekeeper refusal folded into shareWithThirdParty); b.secCyber.eightKArtifact's documented return key `audit` is actually `deadlineBusinessDays`; and b.compliance.aiAct.transparency's helper summary named `cspMetaTag` / a `watermark({ kind })` argument that are really `metaTags` / `watermark({ mediaKind })`. **Fixed:** *`b.auditDailyReview` requires a notify channel under the `sox-404` posture* — The docs listed `sox-404` among the postures that make a `notify` callback mandatory at create-time, but the enforcement set contained only `sox` — so `posture: "sox-404"` without `notify` was accepted instead of refused. `sox-404` (SOX §404 ICFR) is now in the mandatory-notify set, matching the documented guarantee; constructing without a notify channel under it throws `auditDailyReview/notify-required-under-posture`. · *`b.compliance` jurisdiction/domain lister examples no longer enumerate a stale fixed set* — `posturesByDomain` and `posturesByJurisdiction` return every posture matching the domain/jurisdiction, but their `@example`s showed small fixed arrays from before the posture catalog grew. The examples now show a representative prefix with `...` and note they return the full matching set. · *`b.dataAct` surface list matches the real methods* — The module surface listed `userAccessible(...)` and `refuseGatekeeper(...)`, neither of which exists. The real surface is `declareProduct` / `recordUserAccess` / `shareWithThirdParty` / `recordSwitchRequest`, and DMA-gatekeeper refusal (Art 32 §1) is enforced inside `shareWithThirdParty`. The doc now reflects that. · *`b.secCyber.eightKArtifact` documented return shape corrected* — The signature line showed `{ artifact, deadline, audit }`; the function returns `{ artifact, deadline, deadlineBusinessDays }` (there is no `audit` key). The doc now matches. · *`b.compliance.aiAct.transparency` helper names corrected* — The helper summary named a `cspMetaTag(...)` function and a `watermark({ kind })` argument; the real names are `metaTags(...)` and `watermark({ mediaKind })`. Calling the documented names threw. Also corrected: a `b.aiAdverseDecision` illustration showed an ECOA `statutoryDeadlines` shape that didn't match the regime's actual deadlines.
12
32
 
13
33
  - v0.13.31 (2026-05-28) — **Circuit-breaker onStateChange callback now fires; mcp / vault-aad doc corrections.** b.circuitBreaker documented an `onStateChange` callback (both an option and an `onStateChange(handler)` registration method) plus a state-change payload, but the callback was never invoked — only an observability event fired. The callback is now implemented: it fires on every transition with `{ name, from, to, at }`, the registration method works, and a non-function handler is rejected at construction. The same primitive's docs are corrected to name the real accessor (`getState()`, not `state()`) and drop a never-read `audit` option. Plus two doc-only corrections: b.mcp.toolResult.sanitize described composing b.guardHtml / b.ai.input.classify (it uses built-in detection) and documented a `classifyInput` option it never read; and b.vault.aad's prose said HKDF-SHAKE256 where the derivation is SHAKE256 (the AEAD AAD-binding itself is unchanged and sound). **Fixed:** *`b.circuitBreaker` onStateChange callback is invoked on every transition* — The `onStateChange` option and the `onStateChange(handler)` registration method are now wired: each registered handler is called with `{ name, from, to, at }` on every state transition (closed→open, open→half, half→closed/open), alongside the existing `breaker.state.change` observability event. A non-function `onStateChange` is rejected at construction. Previously the documented callback never fired. The docs are also corrected to name the real state accessor `getState()` (there is a `state` property, so `state()` was never a method) and to drop a never-read `audit` option. · *`b.mcp.toolResult.sanitize` documents its actual detection and options* — The prose said the sanitizer composes `b.guardHtml`'s strict profile and `b.ai.input.classify`; it uses built-in dangerous-HTML and prompt-injection-marker detection. The `@opts` also listed a `classifyInput` override the function never read. The prose now describes the built-in detection and the unwired `classifyInput` option is removed. The fail-closed refusal behavior (default `posture: "refuse"`) is unchanged. · *`b.vault.aad` derivation named correctly (SHAKE256)* — The module prose described the per-binding key derivation as HKDF-SHAKE256; it is SHAKE256 over the vault root concatenated with the binding inputs (no HKDF extract/expand). The AEAD AAD-binding to (table, row, column, schema version) — the file's actual security guarantee — is unchanged and sound; only the KDF name in the doc was wrong.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 1,
3
- "frameworkVersion": "0.13.32",
4
- "createdAt": "2026-05-29T01:45:58.287Z",
3
+ "frameworkVersion": "0.13.42",
4
+ "createdAt": "2026-05-29T18:46:45.251Z",
5
5
  "exports": {
6
6
  "a2a": {
7
7
  "type": "object",
@@ -6425,6 +6425,10 @@
6425
6425
  "tableName": {
6426
6426
  "type": "function",
6427
6427
  "arity": 1
6428
+ },
6429
+ "transaction": {
6430
+ "type": "function",
6431
+ "arity": 1
6428
6432
  }
6429
6433
  }
6430
6434
  },
@@ -53,6 +53,34 @@ services:
53
53
  ports: !override []
54
54
  expose:
55
55
  - "3008"
56
+ # Encrypted-at-rest mode (WIKI_DB_AT_REST=encrypted) keeps the live
57
+ # SQLite working copy in a tmpfs (BLAMEJS_TMPDIR=/dev/shm below);
58
+ # plaintext only ever touches RAM. Docker's default /dev/shm is just
59
+ # 64 MiB, which the DB outgrows over time (append-only audit chain,
60
+ # sessions) — and a tmpfs overflow truncates the working copy mid-
61
+ # write, surfacing as "database disk image is malformed" on the next
62
+ # boot. Give it real headroom.
63
+ shm_size: '512m'
64
+ # Persist the encrypted-at-rest copy (db.enc) + sealed keys so they
65
+ # survive `docker rm`, host reboot, and image redeploys, and give a
66
+ # restore point. Without a volume, /data lives in the container's
67
+ # writable layer and is destroyed on every recreate — a corrupt boot
68
+ # then has nothing to roll back to.
69
+ volumes:
70
+ - wiki-data:/data
71
+ # Stop grace must exceed the app's 30s shutdown budget (graceMs) plus
72
+ # the forced-exit watchdog margin, so a `docker stop` / rolling redeploy
73
+ # lets the DB re-encrypt phase finish before SIGKILL — otherwise the
74
+ # final flush is lost and the next boot rolls back to the prior db.enc
75
+ # snapshot. (Inherited from the base compose; restated here because the
76
+ # data-loss risk is highest in encrypted mode.)
77
+ stop_grace_period: 40s
78
+ # NOTE for PaaS platforms (Coolify, Dokku, CapRover, …) that
79
+ # regenerate this compose file on deploy: set the above via the platform
80
+ # UI instead of hand-editing here — a "Persistent Storage" mount for
81
+ # /data, a custom docker run option `--shm-size 512m`, and a stop grace
82
+ # period of at least 40s. Edits to this file are otherwise overwritten
83
+ # on the next deploy.
56
84
  # Full operator-facing environment surface. Every value is
57
85
  # overridable from the .env file; defaults match the framework's
58
86
  # built-in defaults so an operator who just wants the basics can
@@ -227,5 +255,6 @@ services:
227
255
  condition: service_healthy
228
256
 
229
257
  volumes:
258
+ wiki-data: # encrypted-at-rest DB (db.enc) + sealed keys — persistent, survives recreate/redeploy
230
259
  caddy-data:
231
260
  caddy-config:
@@ -17,6 +17,13 @@ services:
17
17
  image: blamejs-wiki:0.11.45
18
18
  container_name: blamejs-wiki
19
19
  restart: unless-stopped
20
+ # Graceful-shutdown budget. The app's shutdown orchestrator runs its
21
+ # phases within a 30s grace (graceMs) — drain in-flight, close the HTTP
22
+ # server, then the DB phase that WAL-checkpoints and (in encrypted mode)
23
+ # re-encrypts to db.enc. Docker's default 10s stop grace SIGKILLs before
24
+ # the DB phase gets to run, losing the final flush. Allow more than
25
+ # graceMs plus the forced-exit watchdog margin.
26
+ stop_grace_period: 40s
20
27
  ports:
21
28
  - "3008:3008"
22
29
  environment:
@@ -68,6 +68,16 @@ var bCrypto = require("./crypto");
68
68
  var safeJson = require("./safe-json");
69
69
  var guardIdempotencyKey = require("./guard-idempotency-key");
70
70
  var agentAudit = require("./agent-audit");
71
+ var { boundedMap } = require("./bounded-map");
72
+
73
+ // The default in-memory backend is keyed on (method, actorId, keyHash) —
74
+ // the key hash comes from request-supplied idempotency keys, so a flood of
75
+ // distinct keys would grow the Map without bound (gc only reclaims EXPIRED
76
+ // rows, and only if the operator wires a scheduler to call it). Cap it.
77
+ // Evict-oldest degrades gracefully under flood: the worst case is a dropped
78
+ // dedup record, so a retry of that one key re-executes — never an OOM.
79
+ // Operators who need a hard guarantee at scale supply a durable `opts.store`.
80
+ var DEFAULT_IN_MEMORY_MAX_ENTRIES = 100000;
71
81
 
72
82
  var audit = lazyRequire(function () { return require("./audit"); });
73
83
  var cryptoField = lazyRequire(function () { return require("./crypto-field"); });
@@ -130,7 +140,7 @@ function _ensureSealTable() {
130
140
  */
131
141
  function create(opts) {
132
142
  opts = opts || {};
133
- var store = opts.store || _inMemoryBackend();
143
+ var store = opts.store || _inMemoryBackend(opts.maxInMemoryEntries);
134
144
  if (typeof store.get !== "function" || typeof store.put !== "function" ||
135
145
  typeof store.delete !== "function") {
136
146
  throw new AgentIdempotencyError("agent-idempotency/bad-store",
@@ -470,8 +480,10 @@ function _checkArgs(method, actorId, key) {
470
480
  // key is validated separately via guardIdempotencyKey.validate.
471
481
  }
472
482
 
473
- function _inMemoryBackend() {
474
- var map = new Map();
483
+ function _inMemoryBackend(maxEntries) {
484
+ // boundedMap validates maxEntries (throws bounded-map/bad-max-entries on a
485
+ // non-positive-int); undefined falls back to the default ceiling.
486
+ var map = boundedMap({ maxEntries: maxEntries || DEFAULT_IN_MEMORY_MAX_ENTRIES, policy: "evict-oldest" });
475
487
  function _k(method, actorId, hash) { return method + "\0" + actorId + "\0" + hash; }
476
488
  return {
477
489
  get: function (method, actorId, hash) {
@@ -64,6 +64,7 @@ var cluster = lazyRequire(function () { return require("./cluster"); }
64
64
  var vault = lazyRequire(function () { return require("./vault"); });
65
65
  var cryptoField = lazyRequire(function () { return require("./crypto-field"); });
66
66
  var safeJson = require("./safe-json");
67
+ var agentTenant = lazyRequire(function () { return require("./agent-tenant"); });
67
68
 
68
69
  var AgentOrchestratorError = defineClass("AgentOrchestratorError", { alwaysPermanent: true });
69
70
 
@@ -168,6 +169,12 @@ function create(opts) {
168
169
  cluster: clusterImpl,
169
170
  audit: auditImpl,
170
171
  permissions: permissions,
172
+ // When true, registry reads (list / lookup) are scoped to the actor's
173
+ // tenant — an actor only sees / resolves agents in its own tenant
174
+ // unless it holds the cross-tenant-admin scope. Mirrors the tenant
175
+ // scoping agent-event-bus enforces on subscribe / delivery. Off by
176
+ // default (single-tenant deployments are unaffected).
177
+ tenantScope: opts.tenantScope === true,
171
178
  spawnedConsumers: [],
172
179
  streams: new Map(),
173
180
  elections: new Map(),
@@ -358,6 +365,19 @@ async function _unregister(ctx, name, args) {
358
365
  async function _lookup(ctx, name, args) {
359
366
  guardAgentRegistry.validate({ kind: "lookup", name: name }, {});
360
367
  _checkPermission(ctx, args.actor, "agent-registry:read");
368
+ // Tenant-scope gate: the row's declared tenant gates access even to a
369
+ // live in-process ref, so an actor can't acquire a handle to another
370
+ // tenant's agent. Consult the backend row (it exists as a metadata
371
+ // declaration even where a live ref is hydrated).
372
+ if (ctx.tenantScope) {
373
+ var sealedRow = await ctx.backend.get(name);
374
+ var declRow = sealedRow ? _unsealRegistryRow(sealedRow) : null;
375
+ if (declRow && !_tenantAllows(ctx, args.actor, declRow.tenantId)) {
376
+ _safeAudit(ctx, "agent.orchestrator.lookup_denied", args.actor,
377
+ { name: name, reason: "cross-tenant" });
378
+ return null;
379
+ }
380
+ }
361
381
  // Live agent ref lives in-process; the backend row exists only as
362
382
  // a metadata declaration. In multi-process deployments each process
363
383
  // hydrates its own liveAgents map by calling register() locally.
@@ -383,6 +403,10 @@ async function _list(ctx, args) {
383
403
  return rows.filter(function (r) {
384
404
  if (args.kind && r.kind !== args.kind) return false;
385
405
  if (args.tenantId && r.tenantId !== args.tenantId) return false;
406
+ // Tenant-scope gate: drop rows the actor's tenant may not see, so
407
+ // enumeration can't disclose other tenants' agents. The args.tenantId
408
+ // above is a caller-supplied FILTER, not an authorization boundary.
409
+ if (!_tenantAllows(ctx, args.actor, r.tenantId)) return false;
386
410
  return true;
387
411
  }).map(function (r) {
388
412
  return {
@@ -753,6 +777,21 @@ function _checkPermission(ctx, actor, scope) {
753
777
  }
754
778
  }
755
779
 
780
+ // Tenant-scope gate for registry reads. Returns true when the actor may
781
+ // see / resolve an agent row in `rowTenantId`: scoping disabled, the actor
782
+ // holds the cross-tenant-admin scope, or the actor's tenant matches the
783
+ // row's. Mirrors agent-tenant's CROSS_TENANT_ADMIN_SCOPE check so registry
784
+ // enumeration can't leak agents (or hand out live refs) across tenants.
785
+ function _tenantAllows(ctx, actor, rowTenantId) {
786
+ if (!ctx.tenantScope) return true;
787
+ if (ctx.permissions && actor &&
788
+ ctx.permissions.check(actor, agentTenant().CROSS_TENANT_ADMIN_SCOPE)) {
789
+ return true;
790
+ }
791
+ var actorTenant = (actor && actor.tenantId) || null;
792
+ return actorTenant !== null && actorTenant === (rowTenantId || null);
793
+ }
794
+
756
795
  function _safeAudit(ctx, action, actor, metadata) {
757
796
  agentAudit.safeAudit(ctx.audit, action, actor, metadata);
758
797
  }
@@ -53,6 +53,10 @@ var AppShutdownError = defineClass("AppShutdownError", { alwaysPermanent: true }
53
53
  var log = boot("app-shutdown");
54
54
 
55
55
  var DEFAULT_GRACE_MS = C.TIME.seconds(30);
56
+ // Headroom between the shutdown grace budget and the hard forced-exit
57
+ // watchdog, so the watchdog fires before a container supervisor's own
58
+ // stop-grace SIGKILL (set stop_grace_period > graceMs + this margin).
59
+ var FORCE_EXIT_MARGIN_MS = C.TIME.seconds(5);
56
60
 
57
61
  /**
58
62
  * @primitive b.appShutdown.create
@@ -71,6 +75,7 @@ var DEFAULT_GRACE_MS = C.TIME.seconds(30);
71
75
  *
72
76
  * @opts
73
77
  * graceMs: number, // total budget across all phases (default 30000)
78
+ * forceExitMarginMs: number, // headroom after graceMs before the signal-handler watchdog forces exit (default 5000); set the container stop grace above graceMs + this
74
79
  * phases: array, // [{ name, run: async fn, timeoutMs? }]
75
80
  * installSignalHandlers: boolean, // wire SIGTERM/SIGINT (default false)
76
81
  * signals: array, // signal names (default ["SIGTERM","SIGINT"])
@@ -94,6 +99,9 @@ function create(opts) {
94
99
  numericBounds.requirePositiveFiniteIntIfPresent(opts.graceMs,
95
100
  "app-shutdown.create: opts.graceMs", AppShutdownError, "app-shutdown/bad-grace-ms");
96
101
  var graceMs = opts.graceMs !== undefined ? opts.graceMs : DEFAULT_GRACE_MS;
102
+ numericBounds.requirePositiveFiniteIntIfPresent(opts.forceExitMarginMs,
103
+ "app-shutdown.create: opts.forceExitMarginMs", AppShutdownError, "app-shutdown/bad-force-exit-margin-ms");
104
+ var forceExitMarginMs = opts.forceExitMarginMs !== undefined ? opts.forceExitMarginMs : FORCE_EXIT_MARGIN_MS;
97
105
  var phases = Array.isArray(opts.phases) ? opts.phases.slice() : [];
98
106
  var installSignalHandlers = !!opts.installSignalHandlers;
99
107
  for (var i = 0; i < phases.length; i++) {
@@ -224,6 +232,30 @@ function create(opts) {
224
232
  function _signalCallback(sig) {
225
233
  return function () {
226
234
  log("received " + sig + " — initiating graceful shutdown");
235
+ // Hard-deadline safety net. Per-phase budgets use a SOFT timeout
236
+ // (withTimeout lets the underlying work keep running on expiry), so
237
+ // shutdown() RESOLVING does not guarantee the process EXITS: a hung
238
+ // phase's leaked handle (a socket that won't close, a timer that keeps
239
+ // firing) can hold the event loop alive past the grace window, after
240
+ // which the supervisor SIGKILLs us and the final DB re-encrypt is lost.
241
+ // Arm an unref'd watchdog that forces a clean exit at the deadline.
242
+ // It is deliberately NOT cleared when shutdown() resolves — the whole
243
+ // point is to catch the case where the orchestration finished but the
244
+ // process won't die. unref() so it never itself keeps us alive: a clean
245
+ // shutdown with no leaked handles exits naturally well before it fires.
246
+ // process.exit() runs the registered exit handlers (db re-encrypts
247
+ // there), so the last flush still happens.
248
+ var watchdog = setTimeout(function () {
249
+ log.error("shutdown exceeded " + (graceMs + forceExitMarginMs) +
250
+ "ms without the process exiting — forcing exit (exit handlers run " +
251
+ "the final DB flush) before the supervisor SIGKILLs");
252
+ // Bounded forced exit after the grace deadline, armed ONLY inside the
253
+ // signal handler (operator opted into installSignalHandlers,
254
+ // delegating process lifecycle to the orchestrator).
255
+ // allow:process-exit — operator-delegated lifecycle, watchdog only
256
+ process.exit(process.exitCode || 1);
257
+ }, graceMs + forceExitMarginMs);
258
+ if (typeof watchdog.unref === "function") watchdog.unref();
227
259
  shutdown().then(function (result) {
228
260
  if (process.exitCode === undefined || process.exitCode === 0) {
229
261
  process.exitCode = result.ok ? 0 : 1;
@@ -0,0 +1,102 @@
1
+ "use strict";
2
+ /**
3
+ * bounded-map — a Map facade that caps its entry count.
4
+ *
5
+ * Defends the unbounded-in-bounded resource-exhaustion class: an in-memory
6
+ * store keyed on request-derived input (a locale, a hostname, an
7
+ * idempotency key, a replay nonce) grows without limit between sweeps
8
+ * unless something enforces a ceiling. A periodic TTL sweep alone does not
9
+ * bound peak memory — a flood of unique keys arrives faster than the sweep
10
+ * interval. This adds the missing ceiling.
11
+ *
12
+ * Two policies for what happens on `set` when already at `maxEntries`:
13
+ *
14
+ * "evict-oldest" (default) — drop the oldest entry (insertion order)
15
+ * to make room, then store the new one. For caches whose entries are
16
+ * re-derivable on demand (Intl formatters, DNS results, idempotency
17
+ * records) eviction is cheap — the worst case is a recomputed value or
18
+ * a missed dedup under active flood, never a correctness or security
19
+ * hole. `set` always stores and returns true.
20
+ *
21
+ * "reject" — refuse the new entry (do NOT evict a live one) and return
22
+ * false. For stores where evicting an unexpired entry would be unsafe:
23
+ * a replay-protection nonce store must not drop a live nonce to admit a
24
+ * new one, because that reopens a replay window for the dropped nonce.
25
+ * The caller fails closed on a false return (treats the request as
26
+ * un-recordable → reject it). Callers should purge expired entries
27
+ * before relying on this so the ceiling is hit only under genuine flood.
28
+ *
29
+ * This is deliberately NOT `b.cache` — that is an operator-facing primitive
30
+ * with TTL, LRU-touch, observability, and pluggable backends. This is the
31
+ * minimal internal ceiling the framework's own request-keyed Maps need, and
32
+ * leaves TTL/expiry semantics to the caller (which already owns them).
33
+ *
34
+ * `onEvict(key, value)` (optional) fires when an entry is dropped to make
35
+ * room under "evict-oldest" — for an observability counter, say. It never
36
+ * fires under "reject" (nothing is evicted; the new entry is dropped).
37
+ */
38
+
39
+ var numericBounds = require("./numeric-bounds");
40
+ var { defineClass } = require("./framework-error");
41
+
42
+ var BoundedMapError = defineClass("BoundedMapError");
43
+
44
+ /**
45
+ * @param {object} opts
46
+ * @param {number} opts.maxEntries - hard ceiling; throws if not a positive finite int
47
+ * @param {string} [opts.policy] - "evict-oldest" (default) | "reject"
48
+ * @param {function} [opts.onEvict] - (key, value) called on eviction under "evict-oldest"
49
+ * @returns Map-like facade: get/has/set/delete/clear, size getter, keys/values/entries/forEach, [Symbol.iterator]
50
+ */
51
+ function boundedMap(opts) {
52
+ opts = opts || {};
53
+ if (!numericBounds.isPositiveFiniteInt(opts.maxEntries)) {
54
+ throw new BoundedMapError("bounded-map/bad-max-entries",
55
+ "boundedMap: opts.maxEntries must be a positive finite integer, got " + JSON.stringify(opts.maxEntries));
56
+ }
57
+ var maxEntries = opts.maxEntries;
58
+ var policy = opts.policy || "evict-oldest";
59
+ if (policy !== "evict-oldest" && policy !== "reject") {
60
+ throw new BoundedMapError("bounded-map/bad-policy",
61
+ "boundedMap: opts.policy must be 'evict-oldest' | 'reject', got " + JSON.stringify(policy));
62
+ }
63
+ var onEvict = typeof opts.onEvict === "function" ? opts.onEvict : null;
64
+ var inner = new Map();
65
+
66
+ function set(key, value) {
67
+ // Updating an existing key never grows the map — always allowed.
68
+ if (inner.has(key)) { inner.set(key, value); return true; }
69
+ if (inner.size >= maxEntries) {
70
+ if (policy === "reject") return false;
71
+ // evict-oldest: the first key in insertion order is the oldest.
72
+ var oldest = inner.keys().next().value;
73
+ if (oldest !== undefined || inner.has(oldest)) {
74
+ var evictedVal = inner.get(oldest);
75
+ inner.delete(oldest);
76
+ if (onEvict) { try { onEvict(oldest, evictedVal); } catch (_e) { /* obs hook — drop-silent */ } }
77
+ }
78
+ }
79
+ inner.set(key, value);
80
+ return true;
81
+ }
82
+
83
+ return {
84
+ get: function (k) { return inner.get(k); },
85
+ has: function (k) { return inner.has(k); },
86
+ set: set,
87
+ delete: function (k) { return inner.delete(k); },
88
+ clear: function () { inner.clear(); },
89
+ keys: function () { return inner.keys(); },
90
+ values: function () { return inner.values(); },
91
+ entries: function () { return inner.entries(); },
92
+ forEach: function (fn, thisArg) { return inner.forEach(fn, thisArg); },
93
+ get size() { return inner.size; },
94
+ get maxEntries() { return maxEntries; },
95
+ get policy() { return policy; },
96
+ // Iterable like a Map, so `for (var e of bmap)` yields [key, value]
97
+ // entries — callers that iterate a plain Map keep working unchanged.
98
+ [Symbol.iterator]: function () { return inner[Symbol.iterator](); },
99
+ };
100
+ }
101
+
102
+ module.exports = { boundedMap: boundedMap, BoundedMapError: BoundedMapError };