@sinemacula/foundation is the platform-agnostic core of the Sine Macula application kernels: configuration, HTTP,
sessions, queries, realtime, storage and the rest of the shared client logic, as small port-driven TypeScript units
with no framework, DOM or Node-only dependencies.
Applications do not consume this package directly. Each platform kernel (web, mobile) boots the foundation core, binds its generic contracts to the platform's router and UI, and layers its own services on top. Everything platform-specific arrives through a port.
| Area | What it provides | Port / contract |
|---|---|---|
src/analytics/ |
Records product events through a swappable tracker (console + no-op adapters), plus route page tracking | AnalyticsTracker |
src/app/ |
The boot core: bootFoundationCore runs the agnostic phases, plus the service registry and base wiring |
bootFoundationCore |
src/authorization/ |
Evaluates flat permission grants with the server's * glob grammar |
PermissionSet (no port) |
src/config/ |
Reads typed configuration from environment sources, fetches the runtime document and freezes the repository | EnvironmentSource |
src/connectivity/ |
The connectivity-observation contract each platform adapts | ConnectivityMonitor |
src/feature-flags/ |
Resolves feature flags through a swappable provider (static adapter included) | FeatureFlags |
src/http/ |
HTTP client: a fetch adapter behind a port, a typed error hierarchy, and bearer-token attach + refresh-and-retry | HttpClient |
src/i18n/ |
Locale detection, persistence and negotiation, free of any rendering library | LocaleService |
src/logging/ |
A minimal logging port with console and no-op adapters | Logger |
src/notifications/ |
The toast and confirm-dialog ports each platform's notification services implement | Toaster / Confirmer |
src/query/ |
Resource queries: the ApiQuery builder, a typed filter DSL, envelope mapping and ResourceClient |
ResourceClient |
src/realtime/ |
Live connections behind a port: a WebSocket adapter plus the exponential-backoff reconnect platform adapters share | RealtimeConnection |
src/reporting/ |
Error reporting through a swappable reporter and a breadcrumb trail | ErrorReporter |
src/router/ |
The navigation middleware contract and pipeline, generic over each platform's route and location types | RouteMiddleware |
src/session/ |
The session core: lifecycle, refresh outcomes, async persistence and a default auth gateway (body or cookie) | SessionApi |
src/storage/ |
A synchronous key-value storage port with in-memory and key-namespacing adapters | KeyValueStorage |
src/support/ |
Shared primitives: service holders, deep freeze and record guards | - |
src/theme/ |
Colour-scheme state: preference resolution and the OS-source and applier ports | ColorSchemeService |
npm install @sinemacula/foundationThe exports map resolves to the compiled dist/ and the prepare script builds it, so a git dependency
(github:sinemacula/foundation-ts#<ref>) installs the same output as the registry tarball.
There is no barrel: import each module by its subpath. The exports map is the public surface; anything unlisted is
internal.
import { Environment } from '@sinemacula/foundation/config/environment';
import { MemoryStorage } from '@sinemacula/foundation/storage/memory-storage';A kernel boots the core through @sinemacula/foundation/app/boot-foundation-core, supplying its storage,
notification and fetch seams. The core runs the runtime environment, configuration, storage, feature flags,
notifications, observability and HTTP client phases in that order, and calls the kernel's module registration before
building the client so modules can contribute interceptors.
const core = await bootFoundationCore({ ...options, runtime: { url: '/runtime-env.json' } }, { fetchFn });runtime is optional; omit it where configuration ships with the build, as on mobile. When set, the document must
load within timeout (default 5000 ms). A 404 counts as empty, an invalid timeout rejects with a RangeError, and
any other failure rejects with a RuntimeEnvironmentError. The installed services are then available through
@sinemacula/foundation/app/services.
ApiQuery speaks the sinemacula/laravel-api-toolkit query grammar. It is immutable: every call returns a new
query.
const query = ApiQuery.create()
.where('status', 'active')
.orWhere([q => q.where('role', 'admin').where('verified', true), q => q.where('role', 'owner')])
.whereHas('posts', q => q.where('published', true))
.search('ada')
.orderBy('name')
.limit(25)
.fieldsFor('user', ['id', 'name', 'aggregates'])
.aggregatesFor('user', ['posts_count']);
// filters={"status":"active","$or":[{"role":"admin","verified":true},{"role":"owner"}],
// "$has":{"posts":{"published":true}}}&search=ada&order=name&limit=25
// &fields[user]=id,name,aggregates&aggregates[user]=posts_count- Filter calls AND together and never replace or widen an earlier condition: a different value for a field, a
colliding operator or a second
orWheregroup is ANDed beside the first under$and. Rebuild from a base query to change a condition. andWhere/orWheretake one builder per document; keys inside a document AND together. An empty group or document throws aQueryError.- Repeated
whereRelationcalls on one relation merge into one document, as do repeatedwhereHascalls, so the same related row must match all of them.whereHasNotconditions never merge. - Free-text search is the
searchparameter (search(term)), never a filter operator. - Aggregates render under the record's
aggregatesfield only whenaggregatesis infields[type]or the resource's default fields. withTrashed()/onlyTrashed()settrashed=with/trashed=only.- Changing the filters, search, soft-delete visibility or order drops any cursor token but keeps cursor pagination;
limitandpagekeep it. Random order under cursor pagination throws. fieldsFor(type, [])requests only the fixed fields andaggregatesFor(type, [])suppresses the default aggregates.$-prefixed field or relation names, non-finite numbers, blank field or aggregate names, and a page or limit that is not a positive integer throw aQueryError.ResourceClientpercent-encodes each/-separated id segment and rejects an id with an empty,.or..segment before sending a request.ResourceClient.listreturns the mappeditems,meta({ mode: 'length-aware', total, count, hasMore },{ mode: 'cursor', hasMore }, ornull), the paginationlinks, andnextCursor/prevCursorread from them.
The toolkit enforces cost caps server-side and answers a request over one with a 422. The defaults are: limit 100,
3 order keys, 5 aggregates, an offset of 500000 rows, 500 $in items, 100 filter nodes, a filter depth of 3, and
8192 bytes of encoded filters.
WebSocketConnection (realtime/web-socket-connection) reconnects after any close or socket error it did not initiate,
with an equal-jittered ExponentialBackoff by default so clients dropped together do not return together. The backoff
resets only once a socket has stayed open for STABLE_CONNECTION_MS (5 s), so a server that accepts and closes at once
still sees growing delays. disconnect() stops reconnecting until the next connect().
beforeReconnect receives an AbortSignal that aborts on disconnect(), and skips the attempt when it resolves
false or rejects. Map a classified refresh explicitly and act on its outcome only while the signal is live:
const connection = new WebSocketConnection({
url: () => `wss://example.test/realtime?token=${readAccessToken()}`,
beforeReconnect: async signal => {
const outcome = await coordinator.refresh();
if (signal.aborted) {
return false;
}
switch (outcome.kind) {
case 'refreshed':
return true;
case 'retryable':
case 'superseded':
return false;
case 'failed':
reporter.captureError(outcome.error);
if (!signal.aborted) {
connection.disconnect();
}
return false;
case 'rejected':
case 'interactionRequired':
connection.disconnect();
return false;
}
},
onError: error => reporter.captureError(error),
});
connection.on('order.updated', message => applyOrderUpdate(JSON.parse(message.data)));
connection.connect();on('message') receives every text frame; a { event, data } envelope also reaches that event's subscribers, with a
non-string data re-serialised as JSON. Binary frames are dropped and reported to onError, and send() throws
unless the socket is open. Each on / onStateChange call is its own registration, a delivery reaches the handlers
registered when it started, and state changes made from a handler are delivered in order after the current one.
onError receives failures the connection contains (a throwing subscriber, url() builder or socket factory); the
same failure inside connect() throws a RealtimeError with the original as its cause. realtime/subscribers
exports the registries behind these rules for other transport adapters, and support/subscriber-list the list itself.
StaticFeatureFlags, ColorSchemeService and installPageTracking take an optional onError sink, as
WebSocketConnection does: a synchronous throw from a change handler, listener, tracker or breadcrumb trail goes to the
sink and never stops the others or reaches the caller. Flag-change handlers and scheme listeners follow the realtime
registration rules: each subscribe is its own registration, a change reaches the handlers registered when it was made,
and a change made from a handler is delivered after the current one. Page tracking records only completed navigations,
by path: query strings and hashes never reach the tracker or the trail.
Each port a platform adapts ships a Vitest contract suite to run against its adapters, under the area's test-support:
describeFeatureFlagsContract, describeRealtimeContract, describeSessionPersistenceContract,
describeSessionRecordStoreContract, describeSessionLockContract, describeKeyValueStorageContract and
describeConnectivityMonitorContract. An adapter
proves its behaviour by running the suite from its own tests:
import { describeFeatureFlagsContract } from '@sinemacula/foundation/feature-flags/test-support/feature-flags-contract';
describeFeatureFlagsContract({
create(initial) {
const flags = new RemoteFeatureFlags(initial);
return { flags, change: next => flags.update(next) };
},
});session/test-support/fake-auth-server serves the session endpoints from memory, with rotation, its grace window,
replay revocation and cookie sign-out, for integration tests of a session wiring.
ConfirmedConnectivityMonitor wraps a platform ConnectivityMonitor and publishes a change only once a
ReachabilityProbe confirms it: two or more consecutive results disagreeing with the published state, spanning
offlineAfter to go offline or onlineAfter to come back (5 seconds each by default). One agreeing result discards the
run, so an intermittent connection keeps its current state instead of flapping. It probes every probeInterval (1.5
seconds) while confirming, every heartbeatInterval (30 seconds) while online so a silent loss is still found, and on a
backoff capped at 30 seconds while offline. A probe that rejects, resolves anything but true or outlives
probeTimeout (5 seconds) is unreachable. Platform events and hint(reachable) only bring the next probe forward:
pass http.onTransport: reachable => monitor.hint(reachable) to bootFoundationCore so a failing request triggers a
check. The initial state is the platform's, unconfirmed. Stop the monitor while the application is in the background;
results further apart than a probe cycle never count towards one window.
Every subpath resolves under Metro and Jest through the default export condition, and CI loads the whole public
surface under Metro, Hermes and React Native's Jest preset. The package ships ES modules, so add it to Jest's
transformIgnorePatterns allow-list. KeyValueStorage is synchronous, so back it with a synchronous store; an
asynchronous secure store implements SessionPersistence directly.
Every context sharing the session must see each write before it next reads, or one tab presents a refresh token another
has spent. Browser tabs sharing localStorage do not: a tab can be granted a lock before another tab's write reaches
it. Persist the session through RecordSessionPersistence over a SessionRecordStore that reads and swaps one record
atomically across tabs, such as one IndexedDB key in a readwrite transaction, and keep a shared exchangeLock.
KeyValueSessionPersistence suits a single context, or contexts sharing a store that is visible to each at once.
- Node.js 22+
- Vitest 3.1+, only for the contract suites under
*/test-support
npm test # unit suite
npm run test:coverage # unit suite with 100% coverage enforced
npm run test:mutation # Stryker mutation gate (break 95)
npm run typecheck # type-check
npm run check # static analysis and lint via qlty
npm run fmt # format via qlty
npm run smells # duplication / complexity smells via qlty
npm run deadcode # dead-code detection via knip
npm run check:pkg # publint + attw on the packed tarball
npm run smoke:node # import and type-check the packed tarball as Node16 and bundler consumers
npm run smoke:react-native # type-check, bundle and run the packed tarball under Metro, Hermes and Jest
npm run api:check # compare the public API with api/foundation.api.md
npm run bench # benchmark the hot paths (not gated)After a deliberate API change, run npm run api:report and commit the regenerated report. To compare performance, run
npm run bench:baseline on master, switch to your branch and run npm run bench:compare; the baseline stays local
in build/bench/, since timings only compare on the same machine.
See CHANGELOG.md for a list of notable changes.
Contributions are welcome. Please read CONTRIBUTING.md for guidelines on branching, commits, code quality, and pull requests.
If you discover a security vulnerability, please report it responsibly. See SECURITY.md for the disclosure policy and contact details.
Licensed under the Apache License, Version 2.0.