@persist-kit/base-storage
v0.1.6
Published
A tiny, zero-dependency, fully pluggable base class for encrypted key/value storage with typed events. No storage, environment, or runtime assumptions.
Maintainers
Readme
@persist-kit/base-storage
A tiny, zero-dependency base class for encrypted key/value storage — with typed events built in. Pure TypeScript, no DOM types, no runtime assumptions: storage, environment, and diagnostics are all injected by the consumer.
- Zero runtime dependencies — includes its own ~70-line typed event
emitter (design inspired by
mittv3.0.1), nothing else. - Fully pluggable storage — the package ships no storage
implementation at all. You inject anything shaped like
localStorage(getItem/setItem/removeItem) viainitialize(). - SSR-safe by construction — the constructor never touches storage,
so a manager can be created before an environment exists. Attach the
real backend once it does (e.g.
manager.initialize(localStorage)after mounting in the browser). - Pluggable encryption — pass your own
encrypt/decryptpair, or skip it and get plaintext (reported throughdebug, see below). - Typed events —
get,set,remove, and a per-fieldset:<key>event, all typed end to end. - Injected environment/debug hooks — no
process.env, noimport.meta.env, noconsole.*calls anywhere in the package.
Production readiness — read this before adopting
Honest, not just "tests pass": this package has been through two audit
passes (see docs/audit.md) checking correctness, type safety, memory
lifecycle, error handling, and security-relevant behavior, not just
whether the existing tests were green. Real bugs were found and fixed
both times — that history is documented, not hidden.
Known, deliberate architectural limit: storage must be synchronous
(see "A real architectural limit" below). If your target backend is
inherently async (a real Redis client, IndexedDB, React Native's
AsyncStorage), this package does not support it — that's not a bug to
report, it's a design boundary to know about upfront.
Verification gap, not a code-confidence gap: the real tsup/pnpm
build has never actually been run in the environment this package was
developed in (no package-registry network access there). Every claim
about the build output is either a real tsc-based verification (with
output actually inspected) or an explicitly labeled inference about
tsup/esbuild's well-documented bundling behavior — see docs/audit.md
§7.1 for exactly which is which. Run pnpm build && pnpm pack --dry-run
once for real before shipping, to confirm.
Install
npm install @persist-kit/base-storageQuick start
Extend BaseStorageManager for each thing you want to persist. Declare a
private _<field> backing field for every key in your values type, and a
public getter/setter pair that calls this._set(key, value):
import { BaseStorageManager, type BaseManagerConfig } from '@persist-kit/base-storage';
interface PreferencesValues {
theme: 'light' | 'dark';
currency: string;
}
class PreferencesManager extends BaseStorageManager<PreferencesValues> {
private _theme: PreferencesValues['theme'] = 'light';
private _currency: PreferencesValues['currency'] = 'USD';
constructor(config: BaseManagerConfig = {}) {
super(config);
this._keys = { theme: 'prefs:theme', currency: 'prefs:currency' };
}
get theme() {
return this._theme;
}
set theme(value: PreferencesValues['theme']) {
this._set('theme', value);
}
get currency() {
return this._currency;
}
set currency(value: PreferencesValues['currency']) {
this._set('currency', value);
}
}
// Constructing never touches storage — safe to do anywhere, including SSR.
const prefs = new PreferencesManager();
// Attach the real backend once it's available.
prefs.initialize(localStorage);
prefs.on('set:theme', ({ value, oldValue }) => {
console.log(`theme changed: ${oldValue} -> ${value}`);
});
prefs.theme = 'dark'; // persists, updates the field, emits 'set:theme'Every subclass setter is one line (this._set(key, value)). _set skips
persisting and emitting entirely when the value hasn't changed.
Storage: always injected, never assumed
BaseStorageManager ships no storage implementation — not
localStorage, not an in-memory map, nothing runtime-specific. It only
depends on this contract:
interface StorageLike {
getItem(key: string): string | null;
setItem(key: string, value: string): void;
removeItem(key: string): void;
}Why initialize() and not the constructor
The constructor only configures the manager (encryption, metadata, dev/
debug hooks) — it deliberately does not require storage. That's what
makes it safe to construct a manager before an environment is ready, e.g.
during server-side rendering, before window/localStorage exist.
initialize(storage) is the one place a StorageLike gets attached:
const prefs = new PreferencesManager(); // safe on the server, no storage yet
// ...later, once mounted in the browser:
prefs.initialize(localStorage);Using the manager before initialize() has been called is a well-defined
no-op: reads return null, writes and removals are silently dropped.
Nothing throws.
Calling initialize() more than once
Well-defined, not accidental: each call replaces the current storage
backend with the new one. This is what makes the SSR handoff above work,
and it also supports intentional swaps (tests, backend migrations). Every
attach — including the first — is reported via debug('debug', 'storage_initialized' | 'storage_reinitialized', ...),
so a swap is never silently invisible if you're listening for it.
Bring your own backend
prefs.initialize(localStorage); // browser
prefs.initialize(myInMemorySessionStore); // server
prefs.initialize(myInMemoryTestDouble); // testsAnything satisfying StorageLike works — as long as it's synchronous.
A real architectural limit, not just a gap: synchronous storage only
StorageLike's methods return string | null and void, not
Promise<...>. This is a deliberate consequence of the public API being
plain property getters/setters (set theme(v) { this._set('theme', v); })
— property setters cannot be async in JavaScript, so the whole call
chain underneath them (_set → _setItem → _writeCiphertext →
StorageLike.setItem) has to stay synchronous too.
This is fine for localStorage/sessionStorage, an in-memory Map, or
anything else that's inherently synchronous. It does not work for a
genuinely async backend — a real Redis client, IndexedDB, React Native's
AsyncStorage — without wrapping it in something that either blocks
(not actually possible for most async I/O in JS) or silently drops the
async nature (e.g. fire-and-forget, racing reads against in-flight
writes). If your production storage target is inherently async, this
package's current design does not support it cleanly, and no wrapper
fixes that — it would need a different, async-first API (a genuinely
different, larger design, and a breaking change from what's here).
Know this going in rather than discovering it after adopting the package.
Encryption
Pass an Encryptor — an object with synchronous encrypt/decrypt
functions that are inverses of each other:
const encryption = {
encrypt: (value: string) => myEncrypt(value),
decrypt: (value: string) => myDecrypt(value)
};
const tokens = new TokenManager({ encryption });If you omit encryption, values are stored in plaintext. This is always
reported via debug('warn', 'no_encryption', ...), regardless of isDev
— unlike the other checks below, this isn't a dev-only nicety: it's a
one-time, constructor-only check (no hot-path cost either way), and
"this manager is about to store data in plaintext" is exactly the kind
of thing that needs to stay visible in production, not just development.
decrypt() throwing is treated as "no value", not left to crash the
caller — a getter backed by _readRaw/_getItem isn't somewhere a
consumer expects an exception, and stale ciphertext (a rotated key,
hand-edited storage, a cross-version format change) is a realistic event,
not a programming error. Reported via debug('error', 'decrypt_failed', ...).
encrypt() throwing, by contrast, is left to propagate — it isn't
expected to fail on ordinary input the way decrypt can on foreign data,
so a throw there almost always means a genuinely broken Encryptor,
which should surface loudly rather than silently drop a write the caller
believes succeeded.
Environment and debug hooks (both injected)
This package never reads process.env, never reads import.meta.env,
and never calls console.* directly — both are configuration you inject:
type DebugType = 'info' | 'warn' | 'error' | 'debug' | 'trace' | 'log';
type Debug = (type: DebugType, code: string, messageOrData?: unknown) => void;
const manager = new PreferencesManager({
isDev: process.env.NODE_ENV !== 'production', // your call, your runtime
debug: (type, code, data) => console[type](`[prefs:${code}]`, data)
});isDev(boolean, defaultfalse) gates non-essential runtime checks that are worth their cost in development but skipped otherwise for performance — e.g. the missing-backing-field check in_set, and the uninitialized-storage notice. It does not gate the no-encryption or missing-storage-key notices (see above / below) — those are one-time or security-relevant checks with no meaningful perf cost, so they always fire.debug(optional) is the sink for those checks, plus storage lifecycle notices and sync errors. If you don't provide one, it's initialized internally to a safe no-op — the rest of the implementation callsthis.debug(...)unconditionally, with noif (this.debug)checks scattered around.
code is a short, stable identifier suited to filtering/aggregating:
no_encryption, storage_initialized, storage_reinitialized,
storage_not_initialized, set_missing_backing_field,
set_missing_storage_key, decrypt_failed, storage_sync_failed.
Events
Every manager is an event emitter:
| Event | Payload | When |
| ------------- | ----------------------- | ------------------------------------------ |
| get | { key, value } | after _getItem reads a value |
| set | { key, value } | after _setItem writes a value |
| remove | { key } | after _removeItem deletes a value |
| set:<field> | { value, oldValue } | after _set changes a field, per field |
prefs.on('set', ({ key, value }) => console.log('wrote', key, value));
prefs.on('*', (type, event) => console.log('event:', type, event));
prefs.once('set:theme', ({ value }) => console.log('theme set for the first time:', value));emit's payload argument is only optional for events whose type allows
undefined (e.g. { tick: undefined }) — emitter.emit('tick') is fine,
but an event with a required payload still requires one at compile time
(emitter.emit('ping') is a type error if ping's payload doesn't include
undefined). This mirrors mitt's
own emit overloads rather than making the argument unconditionally
optional, which would silently let required payloads go missing.
once(type, handler) registers a handler that fires at most one time,
unregistering itself immediately before that first call — so a handler
that triggers a recursive emit of the same event from inside itself
cannot re-invoke itself. It's supported for named event types only (not
the '*' wildcard). A pending once() can still be cancelled the normal
way, with the original handler reference: emitter.off('set:theme', handler).
Registering the same handler reference more than once (via on() or
once()) is allowed and not deduplicated — each registration fires
independently, same as mitt; off(type, handler) removes only the
first matching registration.
If a handler throws, the error propagates synchronously out of emit()
and any remaining handlers for that call — both same-type and wildcard —
are not invoked. This matches mitt and Node's EventEmitter; it's not
this package's job to isolate misbehaving handlers from each other.
Call manager.destroy() to remove every listener and any cross-tab sync
handler registered on the instance.
Cross-tab sync (optional)
If your manager runs somewhere with a global event target (e.g. a browser
window), you can react to storage changes made in other tabs:
class PreferencesManager extends BaseStorageManager<PreferencesValues> {
// ...
constructor(config: BaseManagerConfig = {}) {
super(config);
this._keys = { theme: 'prefs:theme', currency: 'prefs:currency' };
this._handleStorageChange({
[this._keys.theme]: (value) => {
if (value === 'light' || value === 'dark') this._theme = value;
}
});
}
}Handlers receive the value already decrypted. In an environment with no
global window (e.g. plain Node), _handleStorageChange is a no-op —
there's nothing to listen to, and nothing breaks.
Lifecycle warning — this is a real memory leak risk if you skip it.
Calling _handleStorageChange attaches a real
window.addEventListener('storage', ...). window holds a strong
reference to that listener — and therefore to the whole manager instance
— for as long as the page is open, unless destroy() removes it. For a
manager that lives for the app's entire lifetime this doesn't matter; for
one created and discarded repeatedly (per-request in SSR, tied to a
component's mount/unmount cycle, etc.) without calling destroy() on
teardown, every discarded instance stays reachable via window and never
gets garbage collected. Always call destroy() when a manager using
cross-tab sync is done being used.
Manager metadata (info)
Every manager exposes a public, readonly info: ManagerInfo — by
default { version: '0.0.1' }, merged with whatever you pass as
config.info. It's a schema-version tag for the manager's persisted data
shape; readable from outside, not reassignable.
const prefs = new PreferencesManager({ info: { version: '2.0.0' } });
prefs.info.version; // '2.0.0'Per-manager typed events (TEvents)
BaseStorageManager takes a second, optional generic parameter for the
event map, defaulting to StorageManagerEvents:
class BaseStorageManager<
TAttrs extends Record<string, any> = Record<string, any>,
TEvents extends StorageManagerEvents = StorageManagerEvents
> extends EventEmitter<TEvents>By default, every set:<field> event is typed { value: any; oldValue?:
any } — the base class has no way to know your subclass's specific
per-field types. If you want on('set:theme', ...) typed precisely, supply
your own event map that extends StorageManagerEvents:
interface PreferencesEvents extends StorageManagerEvents {
'set:theme': { value: PreferencesValues['theme']; oldValue: PreferencesValues['theme'] };
}
class PreferencesManager extends BaseStorageManager<PreferencesValues, PreferencesEvents> {
/* ... */
}
prefs.on('set:theme', ({ value }) => {
value; // typed as 'light' | 'dark', not unknown
});The bound is TEvents extends StorageManagerEvents, not the more general
EventMap — that's what lets every internal get/set/remove event
emitted by the base class itself stay type-checked, no matter what a
subclass supplies for TEvents.
What's exported
import {
BaseStorageManager,
EventEmitter,
type StorageLike,
type Encryptor,
type ManagerInfo,
type BaseManagerConfig,
type StorageSyncHandler,
type StorageManagerEvents,
type Debug,
type DebugType,
type StorageChangeEvent,
type Handler,
type WildcardHandler,
type EventMap
} from '@persist-kit/base-storage';Build output
npm run build (via tsup) produces a single ESM bundle:
dist/
index.js # minified, single file, no code-splitting
index.d.ts # type declarationsNo .cjs, .cjs.map, .js.map, or .cts files are emitted — this
package is ESM-only (no CJS require() support) and ships without
sourcemaps, since the published artifact is a small, minified bundle
meant to be read as-is rather than stepped through in a debugger. main
and the exports map both point at the same ESM file; types points at
the declaration file.
Design notes
- No code duplication:
_getItem/_setItem/_removeItem(the event-emitting API) are thin wrappers over_readRaw/_writeRaw/_deleteRaw(the raw, non-emitting API used for sensitive values like tokens) — the encrypt/decrypt/storage-access logic exists in exactly one place each. Every actual storage write, from either path, funnels through one private choke point (_writeCiphertext), which is also the single place_ensureStorage()'s guard lives for writes. - One event emitter, no wrapper layer:
EventEmitteris a single class (design inspired bymitt); there's no separate internal factory-function abstraction underneath it. EventEmitter<Events>'s constraint isEvents extends EventMap, whereEventMap = Record<string, any>—any, notunknown, deliberately. Withunknown, a plaininterfacewith no explicit index signature (interface FooEvents { foo: Bar }) fails to satisfy the constraint at all ("Index signature for type 'string' is missing"), even though its shape is otherwise fine — every consumer would need to writeinterface FooEvents extends Record<string, unknown> { ... }or switch to atypealias instead.Record<string, any>doesn't have that restriction: an ordinary interface, written the way most people reach for first, just works. This only loosens what's accepted asEvents; a handler's actual parameter type is still the event's own declared payload type (e.g.Bar), never widened toany.- No DOM dependency:
StorageLikereplaces the DOMStoragetype, and the package'stsconfiguseslib: ["ES2022"]with no"dom". Cross-tab sync (_handleStorageChange) similarly uses its own locally declaredStorageEventTarget/StorageChangeListenertypes instead of the globalEventTarget/EventListener— those only resolve via@types/node's incidental ambient declarations, which some declaration-bundling tools (e.g.tsup'sdtsstep under certainpnpmlayouts) fail to see, breaking the build with no useful error. - Nothing assumed about the runtime: no
localStorage, noutil, noprocess, noimport.meta. Storage,isDev, anddebugare all injected; the only optional runtime feature (cross-tab sync) degrades to a no-op when its global isn't present. src/has zero dependency on@types/node:tsconfig.jsonsets"types": [], verified by a clean typecheck against it. Only the test suite (node:test/node:assert/strict) needs@types/node, sotsconfig.test.jsonopts back in just fortest/. This keeps the shipped source honest about the "no runtime assumptions" claim above, rather than relying on it by omission.
License
MIT
