Skip to content

release: v3.9.0 - Browser mode - #119

Merged
Shinrai merged 29 commits into
masterfrom
next
May 29, 2026
Merged

Shinrai merged 29 commits into
masterfrom
next

Conversation

@cldmv-bot

@cldmv-bot cldmv-bot Bot commented May 29, 2026

Copy link
Copy Markdown
Contributor

🚀 What's Changed

💥 Breaking Changes

No breaking changes

✨ Features

🐛 Bug Fixes

  • feat(browser): add generateManifest helper, auto-detect browser mode, deprecate dir→base #116
    • fix: use mkdtemp for the no-package-root cache fallback (CWE-377) (43c22db)
    • fix: close file-system-race (TOCTOU/CWE-367) windows flagged by CodeQL (4a7be9c)
    • fix(browser): split env into platform (target) + env (process.env snapshot) (96cd508)
    • fix(types): reference SlothletOptions typedef in entry points (5eda087)
    • fix: resolve CodeQL useless-conditional and useless-assignment warnings (0d495e3)
    • fix: two pre-existing failures on feat/browser-mode (55f8a44)
    • fix(browser): defer node:* imports so browser-mode bundle never loads them (8aa08f1)
    • fix(core): skip env snapshot in browser mode to prevent process.env access (230970a)
    • fix(builder): include category prefix in C03_116 hoisted wrapper apiPath (cf86b37)
    • fix(browser): auto-convert plain filesystem base to file:// URL in default resolver (fa1c8ed)
    • fix(flatten): wire flattenToRoot consumer for C03 multi-default files (470e82b)

🔧 Other Changes

  • feat(browser): add generateManifest helper, auto-detect browser mode, deprecate dir→base #116
    • chore(coverage): split v8 ignore so the second || '' arm is also marked (5d1ba09)
    • test+chore: refine loader v8 ignores after caller-path verification (ca1eff8)
    • test+chore: close remaining coverage gaps toward 100% (5ba2966)
    • test(browser): cover #loadModuleBrowser default-resolver base-URL variants (2ee1d45)
    • test: cover config.normalizeSuppressFixes + loader browser-mode edge cases (50dc0ad)
    • test(helpers): unit tests for manifest-resolver + generate-manifest (8a5f3ab)
    • i18n: translate English leakage flagged by script-purity audit (3e1f206)
    • chore(tests): finish dir→base migration in BASE_DIRS destructure pattern (8bc2c06)
    • docs(types): expose browser-mode + suppressFixes options on SlothletOptions (a17af3f)
    • chore: migrate slothlet({ dir }) callsites to base (7f43c30)
    • test(debug): trim notifications calls to only callable exports for after-fix comparison (39b5160)
    • test(fixtures): add multi-default notifications fixture to api_test for debug comparison (0a30290)
👥 Contributors

Shinrai and others added 29 commits May 27, 2026 19:19
Rule 5 / C03 in flatten.mjs has always returned flattenToRoot: true for
named-only files in a multi-default folder, but modes-processor.mjs had no
consumer for that flag. The exports silently fell through to the normal
namespace-wrapping path, causing helpers.mjs exports to appear at
api.notifications.helpers.formatPhone instead of api.notifications.formatPhone.

Add a flattenToRoot block in modes-processor.mjs before flattenToCategory that
iterates moduleContent keys and assigns each directly into targetApi using
assignToApiPath with collision detection and ownership registration. Mirrors
the addapi object-default block.

Also:
- Revert C03 in flatten.mjs from preserveAsNamespace (incorrect Fix Path 2)
  back to flattenToRoot: true
- Fix C03 unit tests to assert flattenToRoot: true instead of preserveAsNamespace
- Update docs: API-RULES-CONDITIONS.md C03 section and API-RULES.md Rule 5
- Add api_tests/api_test_multi_default/ fixture and integration tests
Introduces suppressFixes config option — an array of rule IDs
(format: <rule>_<PR>, e.g. "C03_116") that temporarily opt out of
specific v3 bug-fix behaviors. When a rule is suppressed:
- A SlothletWarning is emitted with the PR URL for context
- The corrected behavior is skipped (legacy broken behavior restored)

C03_116: named-only files in multi-default folders now correctly
hoist exports to the parent namespace instead of nesting under the
filename. Users who depended on the broken nesting can pass
suppressFixes: ["C03_116"] to preserve their current behavior
until they can migrate. This option will be removed in v4.

All 12 locale files updated with translated warning messages.
Docs updated: CONFIGURATION.md, API-RULES.md, API-RULES-CONDITIONS.md.
Auto-detects execution environment at init time via process.versions.node.
In browser/worker/Electron-renderer contexts (where that sentinel is absent),
all filesystem operations are bypassed and the API tree is built from a
pre-generated manifest instead.

Config shape for browser environments:
  - manifest: { files, directories } — pre-generated directory structure
  - resolveModuleSpecifier: (fileEntry) => string — maps manifest entries
    to importable module URLs/specifiers
  - dir: optional (used in node mode; ignored in browser mode)
  - env: 'browser' | 'node' — explicit override for edge cases only;
    omit to rely on auto-detection (process.versions.node check)

The same slothlet({ dir, manifest, resolveModuleSpecifier }) config can be
shipped to both Electron main (node path) and renderer (browser path) without
any environment-specific branching in user code.

Node mode behavior is entirely unchanged; all existing tests pass as-is.
… deprecate dir→base

- generate-manifest.mjs: build-time Node.js helper for scanning a directory into a manifest object
- manifest-resolver.mjs: browser-safe createManifestResolver(base) factory (optional helper)
- config: manifest presence auto-triggers browser mode (no env:"browser" required)
- config: resolveModuleSpecifier is now optional — defaults to new URL(path, base).href
- config: rename dir→base as primary option; dir still accepted with V3_CONFIG_DEPRECATED warning
- config: normalizeEnvTarget now accepts hasManifest param to signal browser mode
- loader: fix #scanDirectoryBrowser root detection for file:// base URLs
- i18n: add V3_CONFIG_DEPRECATED and HINT_V3_CONFIG_DEPRECATED to all 12 language files
- browser tests: updated to use base+manifest-only config (no env:"browser", no resolveModuleSpecifier)
…fault resolver

The default resolveModuleSpecifier fallback in #loadModuleBrowser previously
called new URL(path, config.dir) directly. When base is a plain filesystem
path (e.g. "/srv/repos/.../api_test_browser") this throws because non-URL
strings are not valid bases for the URL constructor.

The fallback now detects whether base already has a URL scheme (file://,
https://, etc.) and, if not, prefixes it with file:// and appends a trailing
slash before resolving. URLs with an existing scheme pass through unchanged
(trailing slash appended if missing).

This means callers can write:
  slothlet({ base: "/path/to/api", manifest })
and module loading works without manually adding a file:// prefix or providing
a custom resolveModuleSpecifier. createManifestResolver remains available for
advanced use cases (e.g. CDN-relative URLs in real browser environments).

Updated browser-api tests to exercise this path: browserConfig() now uses
base: FIXTURE_DIR (plain path); the module-level resolveSpecifier variable
and its createManifestResolver setup are removed. The fileEntry-shape test
inlines its resolver to keep the test self-contained.
When `flattenToRoot` (Rule 5 / C03_116) hoisted a no-default file's exports
into the parent folder namespace, the wrapper's `apiPath` was computed from
`apiPathPrefix` only — falling back to a bare `key` when `apiPathPrefix` was
empty (the case for a top-level multi-default folder like `notifications/`).
The ownership calculation at the same site uses `categoryName` as the
fallback, so the two diverged: the wrapper's `apiPath` was `"formatPhone"`
while ownership registered `"notifications.formatPhone"`.

Anything that consults the wrapper's apiPath (hook dispatch, metadata, debug
output, permissions) saw the wrong path. Hooks registered on
`before:notifications.formatPhone` silently never fired; metadata queries
returned the wrong path. The existing C03 integration tests only assert
callability, so this slipped through.

Match the ownership calculation so wrapper and ownership agree.
Use `base:` instead of the deprecated `dir:` alias for every slothlet
configuration site that goes through `transformConfig`:

- src/lib/typegen/typegen.mjs — internal slothlet call (was emitting
  V3_CONFIG_DEPRECATED on every typegen invocation, breaking the
  typegen-cli stderr-equals-empty assertion)
- src/slothlet.mjs JSDoc @example blocks, including the auto-rendered
  %%example%% strings on the SlothletAPI typedef
- src/lib/handlers/materialize-manager.mjs JSDoc @example
- All tests under tests/ that call slothlet(), slothlet.load(), or
  pass a config slice through these (264 files)

Kept as `dir:` because those APIs literally destructure `dir` and do
not normalize via transformConfig:
- typegen's own options.dir (CLI + programmatic generateTypes)
- package.json#slothlet.typegen.dir (CLI reads fromPkg.dir)
- builder.buildAPI({ dir }) / modes.eager.buildAPI / modes.lazy.buildAPI
…ccess

In a real browser, `process` is undefined; `_captureEnvSnapshot()` would
crash. Even running browser-mode tests under Node, capturing process.env
incorrectly leaked Node env into `api.slothlet.env` — defeating the point
of an isolated browser-mode env surface.

When `envTarget === "browser"` (auto-detected via `manifest` presence or
set via `env: "browser"`), bypass `_captureEnvSnapshot()` entirely and use
a frozen empty object as the snapshot. Node mode behavior is unchanged.

Adds `browser-env-snapshot.test.vitest.mjs` covering the contract:
- snapshot is defined and frozen
- snapshot is empty regardless of process.env content
- `env.include` allowlist is ignored in browser mode

Also reverts the bulk dir→base migration's effect on two tests in
browser-config.test that were specifically asserting the `dir:` deprecation
warning fires — those need `dir:` literally to test the deprecation path.
…ptions

Add the following to the public `SlothletOptions` typedef so TypeScript
consumers can use the newly-public config surface without `// @ts-expect-error`:

- `base` (replaces `dir`; `dir` retained as deprecated alias with v4 removal note)
- `manifest` for browser-mode pre-generated directory structure
- `resolveModuleSpecifier` browser-mode module resolver function
- `env: "browser" | "node"` string variants (in addition to existing object form)
- `suppressFixes: string[]` opt-out array for v3 bug-fix behaviors

Also update the internal `Slothlet.load()` `@param` JSDoc to match.

Fixes the JSDoc `@example` in `Config.normalizeSuppressFixes()` to use the
correct `<rule>_<PR>` form (`"C03_116"`) instead of the bare rule name
(`"C03"`), which the implementation silently drops.

Regenerates `types/` via `npm run build:types`.
… them

Five Node-only modules (api-manager, loader, resolve-from-caller,
module-discovery, module-manifest-validator) were unconditionally importing
`node:*` at the top level. Bundlers/browsers would resolve those imports
during the static-import phase before any code path runs, breaking the
browser-mode promise — even though `_initializeComponentsBrowser` never
calls the methods that need them.

Replace each top-level `import x from "node:y"` with a top-level-await IIFE
gated on `typeof process !== "undefined" && process.versions?.node`. In
Node the IIFE awaits `import("node:y")` and exposes the same bindings via
const destructuring, so the rest of each file is unchanged. In a real
browser the env check short-circuits and the bindings are `null`; the
methods that consume them (filesystem scanning, CJS loader, stack-trace
resolution, manifest validation) are never reached in browser mode.

The browser false-arm of the env ternary cannot be exercised under our
Node-only vitest runner without stubbing the `process` global (which
destabilizes vitest itself), so it carries a v8 ignore with the rationale
inline. This is not a lazy ignore — it's a fundamentally separate-runtime
branch that requires a browser test harness to cover.

Note on loader.mjs: do NOT spread `node:url`'s namespace alongside
`node:path` — `url.resolve` (deprecated) shadows `path.resolve` and breaks
scanDirectory. Named exports are picked explicitly.
resolve-from-caller: null-safe access to slothlet.envTarget. The browser-mode
guard added in 446c986 unconditionally dereferenced this.slothlet.envTarget,
but Resolver may be instantiated with `null` for unit tests that exercise
the pure-resolution logic. Use optional chaining so the bare instantiation
path returns the same node-mode behavior as before.

modes-processor: scope the C03_116 (Rule 5) flattenToRoot consumer to
non-root processing. The fix wired in 470e82b applied to any directory with
multiple defaults — including root. C03's documented contract ("merge into
parent FOLDER namespace") has no equivalent at root, where applying it
would dissolve every no-default root file's exports onto the API surface,
removing the file-level namespace entirely. Loader test "loads ESM/CJS
export patterns" depends on `api.single.notMatching`, `api.namednamespace.first`
etc. — the preserved per-file namespaces at root.

The nested-folder case (notifications/helpers.mjs hoisting into
api.notifications) still works, covered by the C03_116 regression test
and the existing multi-default integration tests.
The bulk dir→base sed in 7f43c30 changed the key in `BASE_DIRS` array
literals (e.g. `{ label: "api-test", base: TEST_DIRS.API_TEST }`) but did
not touch the matching destructure (`{ label, dir }`) or shorthand-spread
(`{ ...config, dir }`) that referenced the same property. Result: `dir`
was destructured as `undefined`, spread into config as `dir: undefined`,
and `transformConfig` rejected the call with INVALID_CONFIG_DIR_MISSING.

Update each of the 7 affected test files:
- destructure `{ label, base }` instead of `{ label, dir }`
- spread `{ ...config, base }` instead of `{ ...config, dir }`
- reference `config.base` instead of `config.dir`

Affected files all share the same template:
- api-manager-basic / -hooks / -advanced / -reference-identity /
  -test-remove-reload-isolated / -mutations-control
- collision-config

The `getMathAdd(api, dir)` / `getMath(api, dir)` helper signatures are
unchanged — they take the dir/base value as a positional arg.
Extends the existing check-i18n-languages.mjs (key parity + duplicate values)
with a third dimension: detect Latin-letter leakage in non-Latin-script
locales (hi-in, ja-jp, ko-kr, ru-ru, zh-cn). The check is intentionally
strict — minimum run length of 2 ASCII letters — paired with three
acceptance layers so the noise stays bounded:

  1. Implicit: placeholder tokens `{x}` and bracket-wrapped debug tags
     `[TAG-NAME]` are stripped before scanning. A bare tag (unwrapped)
     is still flagged so the format gets normalized over time.
  2. Token allowlist (tools/ci/i18n-latin-tokens-accepted.json): tokens
     accepted whenever they appear in a non-Latin locale — public API
     surface names (slothlet, apiPath, moduleID), internal function names
     in debug messages (syncWrapper, mergeApiObjects), config option
     values (merge/replace/lazy/eager), file extensions (mjs/cjs/json),
     JS primitives (undefined/null/Promise), etc. About 200 entries.
  3. Full-value allowlist (tools/ci/i18n-script-purity-accepted.json):
     exact full translation strings that have legitimate Latin content
     not covered by token allowlist. Empty in this commit; populated
     case-by-case as edge cases come up.

Also bracket-wraps the bare debug-tag prefixes in DEBUG_MODE_* values
across en-us and the 5 other locales that had them (de-de, en-gb, es-es,
es-mx, pt-br, hi-in, ru-ru, zh-cn). Pattern: `TAG-NAME: text` becomes
`[TAG-NAME]: text` — visually marks the tag and exempts it from the
scan. 4 locales (fr-fr, ja-jp, ko-kr, zh-cn except one fullwidth-colon
holdout) already lacked the bare prefix in some keys; they remain
non-uniform but unflagged.

Wires `npm run i18n:check` into the precommit chain
(tools/dev/precommit-validation.mjs) so the audit runs locally before
every commit. CI is unchanged for now per request.

Updates the .github/instructions/rules/i18n-languages.instructions.md
rule to remove the [LANG: TODO] stub exception (per the new
no-stubs-allowed policy) and document the three-layer acceptance model.

Audit goes from 1,289 raw flags down to 23 after allowlist + tag wrap.
The remaining 23 are real translation candidates handled in followups.
⚠️ machine-translated, native-speaker review requested before release

Cleans up the 19 real English-leakage flags reported by the new
script-purity audit. Two kinds of fix:

1. Token allowlist additions (JS language terms and slothlet primitives
   that legitimately appear untranslated across locales):
     function, object, array(s), Array, Object, Function, Hook, data

2. Per-locale value translations:

hi-in (3):
- INVALID_CONFIG_BROWSER_MANIFEST_INVALID: "plain object" → "सादा object"
- HINT_ERROR_RUNTIME_IMPORT_FAILED: drop redundant "(circular dependency)"
  parenthetical (Hindi `वृत्तीय निर्भरता` already says it)
- NO_CONTEXT_MANAGER: drop redundant "(context manager)" parenthetical

ja-jp (2):
- DEBUG_MODE_COLLISION_TRIGGER_EARLY_MAT: "(fire-and-forget)" →
  "(ファイア・アンド・フォーゲット)" katakana transliteration
- DEBUG_MODE_RULE_13_DEDUP_HOISTED_KEY: drop redundant "(hoisted)" — the
  Japanese `重複キーを引き上げました` already conveys the meaning

ko-kr (2):
- DEBUG_MODE_COLLISION_TRIGGER_EARLY_MAT: "(fire-and-forget)" →
  "(비동기 즉시 반환)" descriptive Korean equivalent
- FLATTEN_REASON_BASENAME_MATCHES_CATEGORY: drop redundant "(basename)" —
  the Korean `베이스네임` is the transliteration

ru-ru (6):
- NO_ACTIVE_CONTEXT_LIVE: "live bindings" → "живых привязок"
- WARNING_MULTIPLE_ROOT_CONTRIBUTORS: "root-level default экспортов" →
  "default экспортов корневого уровня"
- DEBUG_MODE_COLLISION_TRIGGER_EARLY_MAT: "(fire-and-forget)" →
  "(запустил-и-забыл)"
- DEBUG_MODE_MERGE_API_OBJECTS_RECURSING: "оба plain object" →
  "оба простые object"
- DEBUG_MODE_MUTATE_API_VALUE_SETIMPL_FALLBACK: "fallback ___setImpl" →
  "резервного ___setImpl"
- DEBUG_MODE_WAITING_GET_IMMEDIATE_MAT: "collision-merged папки" →
  "объединённой при коллизии папки"

zh-cn (6):
- COLLISION_ERROR: "冲突错误 at" → "冲突错误位于"
- INTERNAL_HOOK_STATE_CORRUPT: "Slothlet 的 bug" → "Slothlet 的缺陷"
- HINT_INVALID_CONFIG: "类型 and 格式" → "类型和格式"
- HINT_INTERNAL_INVALID_STATE: "一个 bug —" → "一个缺陷 —"
- HINT_INTERNAL_HOOK_STATE_CORRUPT: "提交 bug 报告" → "提交缺陷报告"
- HINT_SCOPE_DISABLED: "and api.slothlet.scope()" → "和 api.slothlet.scope()"

Audit now reports OK across all 12 locales (1289 → 0 flags).
The browser integration suite covers happy-path use only. This adds direct
unit coverage for the validation throws, empty-directory handling, file/dir
prefix skipping, base-URL normalisation, and cross-platform path
forward-slash behavior that the integration tests never reach.

Coverage impact:
- generate-manifest.mjs lines 88.88% → 97%, branches 60% → 90%
- manifest-resolver.mjs lines 71% → ~100%, branches 67% → ~100%
- Overall branches 98.38% → 98.61%, functions stay at 100%

25 new tests, all passing.
…cases

config.mjs:
- Refactor the auto-detect browser fallback (line 281) from a ternary into
  an if/return + fallback statement so the unreachable browser arm can be
  v8-ignored without losing coverage on the Node arm. Browser detection is
  exercised only in real browser/worker contexts; stubbing `process` under
  vitest destabilizes the test runner.
- 16 new tests for normalizeSuppressFixes covering input-shape validation
  (undefined, null, empty array, non-array primitives), per-rule filtering
  (non-string entries, unknown IDs, dedup), and warning emission (silent
  on/off, URL construction from PR-suffix segment).

loader.mjs:
- 17 new tests for the browser-mode methods (#scanDirectoryBrowser,
  #findManifestNode, #manifestNodeToStructure) using both the real fixture
  and synthetic manifests:
  - api.add to a non-existent manifest path → INVALID_DIRECTORY (line 491)
  - Fallback field handling (file.relativePath, missing fullName/name,
    dir.name without dir.path, flattened directory nodes without .children)
  - Filtering (.json/.md extensions skipped, __ prefix skipped)
  - Nested manifest recursion through api.add to a sub-folder
…iants

The default resolver in loader.mjs `#loadModuleBrowser` branches on whether
`config.base` is already a URL with a scheme and whether it ends with a
slash. The standard browser integration suite always passes a no-scheme
filesystem path without a trailing slash, leaving the file://-URL-with-/,
file://-URL-without-/, and config.dir-fallback branches uncovered.

4 new tests exercise each combination:
  - file:// URL ending with /
  - file:// URL not ending with /
  - filesystem path ending with /
  - config.dir (deprecated alias) fallback via silent: true
Source cleanups (removing dead-code branches the analyzer was flagging):

- modes-processor.mjs L751: the `isRoot ? key` arm of the C03 hoist keyPath
  ternary is unreachable because the surrounding if requires `!isRoot`.
  Removed the dead branch.
- api-manager.mjs L240: `.split("/").pop() || ""` defensive fallback is dead
  — `.split("/")` always returns ≥1 element and `.pop()` on a string array
  always returns a string. Removed the `|| ""`.
- generate-manifest.mjs L96: the `SKIP_PREFIXES` check inside `isApiFile` is
  dead — `scanDir` already filters prefixed names before calling. Removed
  the redundant check.
- config.mjs: hoisted the `IS_NODE` runtime detect to a module-scope
  constant with a single v8 ignore, instead of inline ternary in
  normalizeEnvTarget that would have hidden the covered Node arm too.

Test additions:

- resolve-from-caller.test: 4 new tests covering the browser-mode `rel || ''`
  fallback (L222) when `rel` is empty / null / undefined.
- modules/sort.test: new test covering the comparator's final `return 0`
  branch when two modules have identical priority AND identical packageName.
- manifest-helpers.test: 2 new tests covering scanDir's resilience to
  broken symlinks (entry isFile=false AND isDirectory=false) and unreadable
  subdirectories (chmod 000 → readdir catch → empty children → pruned).
- browser-loader-edge-cases.test: 7 new tests covering #findManifestNode
  recursive descent, #manifestNodeToStructure nested-child missing-key
  fallbacks (no files key, no directories key), file-without-extension
  filtering, fileFilter rejection, dir entries with both path+name missing.

eventemitter-context.mjs: 6 v8 ignores added with rationale comments for
defensive guards inside private tracking helpers. The `length === 0` arms
of `wrappers` checks and the `!eventTracking` arms are unreachable because
the cleanup logic atomically deletes empty entries downstream — by the
time a subsequent .get() runs, those would already be undefined and the
`!wrappers`/`!eventTracking` arm fires first. Patch-ordering fallback in
runtime_patchOnce / runtime_patchPrependOnceListener (lines 366, 437) is
unreachable in the current patch order; ignored with note that future
order changes would activate it.
In response to "Are those truly unreachable?" — re-examined each round-2
v8 ignore against actual caller paths and corrected the over-applied ones:

- loader.mjs L485: the `dir || ""` arm IS reachable via scanDirectory()
  which is package-public (no #). However, the reachable sub-case is a
  relative-name dir like "utils" (not the empty-string fallback). Added a
  test that calls api.add("rel", "utils") to exercise the configBase
  startsWith false sub-arm. Kept v8 ignore on the empty-string fallback
  arms with clarified rationale (defensive against direct internal calls,
  not against real callers which always pass non-empty).

- loader.mjs L617: extracted `leadingSlash` to a separate const so the v8
  ignore targets ONLY the Windows-style-path inline conditional rather
  than the outer ternary's still-covered POSIX branches.

Confirmed unreachable (after tracing callers):
- eventemitter-context L212, L215: runtime_untrackListener only called at
  L511 AFTER runtime_getWrappedListener returned non-undefined; single-
  threaded JS guarantees the maps are still populated.
- eventemitter-context L253, L256, L259: runtime_untrackSpecificWrapper
  only called from runtime_onceWrapper (L410, L482) which holds closure
  ref to its exact wrapper + the wrapper was tracked at registration.
- eventemitter-context L366, L437: enableEventEmitterPatching patches in
  fixed order on→once→prepend→prependOnce→...; the ?? fallback only fires
  if order changes.
- eventemitter-context L190: cleanup atomicity (single-threaded JS).
- config.mjs IS_NODE: `process` always defined under vitest.
- loader.mjs L607: #loadModuleBrowser is private, only callable after
  transformConfig populates both base + dir fields.
- loader.mjs L557, L646: files reaching the name/loader code have passed
  ALLOWED_EXTS filter which requires a dot — `lastDot >= 0` always true.
- loader.mjs L513, L516: defensive fallbacks for malformed user-supplied
  manifests (private method, no real-caller path exercises).
…rked

`/* v8 ignore next 2 */` only covered the first const declaration; the
following `let relativePath = ...` line still flagged its `(dir || "")`
arm-1. Splitting into two single-line `/* v8 ignore next */` markers
covers both empty-input fallback arms.

Final coverage: 100% lines / 100% statements / 100% functions / 100%
branches across 4589 lines / 4278 branches / 626 functions.
- modes-processor: drop dead `isRoot` ternary arm in the flattenToRoot
  ownership registration loop (the enclosing `!isRoot` guard already
  guarantees it is false; mirrors the sibling keyPath computation)
- check-i18n-languages: remove the always-overwritten `new Set()`
  initializer for latinTokenAllowlist
index.mjs/index.cjs hand-rolled an options @PARAM list that had drifted from the canonical SlothletOptions typedef: it declared the removed `dir` instead of the current `base`, plus the long-dead `lazy`/`engine`/`api_mode` options. That broke `npm run build:ci` (test:types -> TS2353: 'base' not assignable). Replace the duplicated list with `@param {import("./src/slothlet.mjs").SlothletOptions}` so both entry points inherit the single source of truth, exactly as the SlothletAPI return type already does, and update validate-typescript.mjs to canonical options.

Includes the regenerated types/ artifacts and a fix:headers correction to browser-hooks.test.vitest.mjs.
…pshot)

The single `env` option was overloaded: normalizeEnvTarget read it for the browser/node execution target while normalizeEnv read it for the process.env snapshot allowlist. The two were mutually exclusive — `env: "browser"` forced a null snapshot and `env: { include }` forced an auto-detected target — so a browser-mode instance could never use the env-snapshot allowlist.

Split into two independent options: `platform: "browser"|"node"` (execution target, read by Config.normalizeEnvTarget and the early detector in Slothlet.load; manifest presence still auto-triggers browser) and `env` (process.env snapshot config only). The browser-mode `env: "browser"` form was unreleased (branch-only), so no deprecation path is needed. Browser test suite migrated to `platform:`.
CodeQL js/file-system-race flagged a check-then-write in the TS transform cache. An audit of all 22 existsSync/statSync candidates across src/ and tools/ found 5 real check-then-use races (17 were benign existence guards / dir-walk probes, left unchanged):

- src/lib/processors/typescript.mjs: existsSync(cachePath)+writeFile → atomic writeFile({ flag: "wx" }) catching EEXIST. The cache is content-addressed (cacheName is a sha256 of the closure), so an existing file is byte-identical; this writes once and no-ops on EEXIST, also closing the concurrent double-writer truncation window.

- src/lib/processors/type-generator.mjs: existsSync(outputDir)+mkdirSync → unconditional mkdirSync({ recursive: true }) (idempotent, no pre-check).

- tools/build/build-exports.mjs (×3): existsSync→readFileSync→writeFileSync d.ts/.map patchers → read directly inside try/catch handling ENOENT (skip silently when absent), eliminating the check-then-read gap while preserving patch-only-if-present behavior.
CodeQL js/insecure-temporary-file flagged the TS transform cache: when no package.json is found above the source, the cache fell back to writing under the shared, world-readable os.tmpdir() at a predictable path (<tmpdir>/.slothlet-cache/...), exposing it to other users (CWE-377/378).

Route that fallback through fs.mkdtempSync(path.join(tmpdir(), "slothlet-")) — Node's built-in secure-temp-dir primitive (unpredictable name, 0o700 owner-only), the zero-dependency equivalent of the tmp package (slothlet keeps zero runtime deps). Memoized per-process so all fallback caches share one stable root, preserving cross-call reuse. The project-local .slothlet-cache/ path (the normal case) is unchanged.

Strengthened the two fallback coverage tests to assert the cache lives under a private slothlet- mkdtemp dir (0o700 owner-only), which fails on the old <tmpdir>/.slothlet-cache/ path.
… deprecate dir→base (#116)

## 🚀 What's Changed

### 💥 Breaking Changes
_No breaking changes_

### ✨ Features
- i18n(check): add script-purity audit for non-Latin locales (#116)
(005fcdd)
- feat(browser): add generateManifest helper, auto-detect browser mode,
deprecate dir→base (#116) (f378711)
- feat(core): add browser/worker env mode with manifest-based API
loading (#116) (446c986)
- feat(config): add suppressFixes opt-out for C03 bug-fix behavior
(#116) (c6e1eca)

### 🐛 Bug Fixes
- fix: use mkdtemp for the no-package-root cache fallback (CWE-377)
(#116) (43c22db)
- fix: close file-system-race (TOCTOU/CWE-367) windows flagged by CodeQL
(#116) (4a7be9c)
- fix(browser): split env into platform (target) + env (process.env
snapshot) (#116) (96cd508)
- fix(types): reference SlothletOptions typedef in entry points (#116)
(5eda087)
- fix: resolve CodeQL useless-conditional and useless-assignment
warnings (#116) (0d495e3)
- fix: two pre-existing failures on feat/browser-mode (#116) (55f8a44)
- fix(browser): defer node:* imports so browser-mode bundle never loads
them (#116) (8aa08f1)
- fix(core): skip env snapshot in browser mode to prevent process.env
access (#116) (230970a)
- fix(builder): include category prefix in C03_116 hoisted wrapper
apiPath (#116) (cf86b37)
- fix(browser): auto-convert plain filesystem base to file:// URL in
default resolver (#116) (fa1c8ed)
- fix(flatten): wire flattenToRoot consumer for C03 multi-default files
(#116) (470e82b)

### 🔧 Other Changes
- chore(coverage): split v8 ignore so the second `|| ''` arm is also
marked (#116) (5d1ba09)
- test+chore: refine loader v8 ignores after caller-path verification
(#116) (ca1eff8)
- test+chore: close remaining coverage gaps toward 100% (#116) (5ba2966)
- test(browser): cover #loadModuleBrowser default-resolver base-URL
variants (#116) (2ee1d45)
- test: cover config.normalizeSuppressFixes + loader browser-mode edge
cases (#116) (50dc0ad)
- test(helpers): unit tests for manifest-resolver + generate-manifest
(#116) (8a5f3ab)
- i18n: translate English leakage flagged by script-purity audit (#116)
(3e1f206)
- chore(tests): finish dir→base migration in BASE_DIRS destructure
pattern (#116) (8bc2c06)
- docs(types): expose browser-mode + suppressFixes options on
SlothletOptions (#116) (a17af3f)
- chore: migrate slothlet({ dir }) callsites to base (#116) (7f43c30)
- test(debug): trim notifications calls to only callable exports for
after-fix comparison (#116) (39b5160)
- test(fixtures): add multi-default notifications fixture to api_test
for debug comparison (#116) (0a30290)



<details>
<summary>👥 Contributors</summary>

- @Shinrai

</details>
@cldmv-bot cldmv-bot Bot added release Marks a pull request as a pending release — merge to publish a new version semver: minor This release adds new functionality in a backwards-compatible way type: bug Something is broken or not behaving as expected type: feature request A request to add new functionality that does not currently exist labels May 29, 2026
@github-actions

This comment was marked as resolved.

@cldmv-bot cldmv-bot Bot added area: core type: dependencies Relates to dependency updates, version bumps, or package management type: documentation Relates to docs, README updates, guides, or inline code comments labels May 29, 2026
@cldmv-bot

This comment was marked as resolved.

@Shinrai Shinrai changed the title release: v3.9.0 - add suppressFixes opt-out for C03 bug-fix behavior release: v3.9.0 - Browser mode May 29, 2026
@Shinrai Shinrai self-assigned this May 29, 2026
@Shinrai
Shinrai merged commit f78c04a into master May 29, 2026
37 checks passed
@cldmv-bot
cldmv-bot Bot deleted the next branch May 29, 2026 18:42
Shinrai added a commit that referenced this pull request May 31, 2026
…g); refresh README What's New

v3.9.0 shipped browser mode (#119/#116) but never got a changelog or a README
update; v3.9.1 (this PR) had neither yet. Back-fill both and bring the README
"What's New" section current.

- docs/changelog/v3/v3.9.0.md — browser/worker mode introduction: manifest-based
  api loading (no fs), generateManifest() build-time helper, platform vs env
  split, dir->base migration, suppressFixes (C03), security/CodeQL fixes.
- docs/changelog/v3/v3.9.1.md — browser-mode hardening: #123 live-binding
  self/context crash (node:* gating consolidated into a platform helper), #91
  full-instance reload(), eager api.remove mount deletion + impl:removed, browser
  shutdown crash, i18n currentLanguage consistency; new setLanguageAsync(); Node
  minimum raised to 22 (import attributes for bundled i18n — noted, shipped as a
  patch by decision); CodeQL cleanup (#122); browser test suites + matrix sweep.
- README: Latest -> v3.9.1; Recent Releases -> v3.9.0, v3.8.0, v3.7.0, v3.6.0
  (4-entry cap per readme-whats-new rules; v3.5.1/v3.5.0 drop off).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release Marks a pull request as a pending release — merge to publish a new version semver: minor This release adds new functionality in a backwards-compatible way type: bug Something is broken or not behaving as expected type: dependencies Relates to dependency updates, version bumps, or package management type: documentation Relates to docs, README updates, guides, or inline code comments type: feature request A request to add new functionality that does not currently exist

Projects

None yet

1 participant