@wtf/platform
v3.2.0
Published
The Platform type your code takes instead of globals, with helpers such as sleep and randomId, and a test double for each member. Web standards first: timers, crypto, console, locks, storage, channels, workers and fetch keep the standards' names; env, pat
Readme
@wtf/platform
Write code that takes its platform as a parameter, so it runs the same in Node, in a browser and
in a test. This package gives you the Platform type your code takes, the helpers that use it,
and a test double for each member. Where a web standard defines a member, it has the standard's
name and signature, cut down to the parts the helpers call, so a browser's window and Node's own
objects fit as they are. Where no standard exists, the member is defined here, as in Effect's
platform. Each subpath covers one concern: its types, its helpers, which ask only for the members
they use, and its doubles.
This package has no platform code. Node's platform comes from @wtf/platform-node, a page's
from @wtf/platform-browser, one in memory from @wtf/platform-memory, and a test's from
testPlatform().
| Subpath | Types | Helpers and doubles |
| ------------ | -------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
| . | Platform, WebPlatform, ProcessPlatform | |
| ./timers | SetTimeout, ClearTimeout, Performance (HTML, HR Time) | sleep(ms, timers, signal), sleepUntil(at, timers, signal), wallTime({ performance }); fakeTimers() |
| ./random | Crypto, SubtleCrypto (Web Cryptography), UUID | randomInt(max, { crypto }), randomFloat, randomBytes, randomId; seededCrypto(seed), softwareSubtle |
| ./console | Console (the Console Standard) | consoleOf({ print }), streamConsole({ stdout, stderr }), format; memoryConsole() |
| ./locks | LockManager, Lock, LockOptions (Web Locks) | memoryLocks() |
| ./fs | FileSystemDirectoryHandle, FileSystemFileHandle, … (File System) | types only |
| ./storage | StorageManager (Storage, File System) | directoryStorage(directory), noStorage |
| ./channel | BroadcastChannel (HTML) | memoryBroadcastChannel({ origin }) |
| ./worker | Worker, MessageChannel, MessagePort (HTML) | MemoryMessageChannel, MemoryMessagePort; memoryWorker(scripts) |
| ./fetch | Fetch (the Fetch Standard) | memoryFetch(handler), offlineFetch |
| ./env | Env, Parser, EnvShape | pick, prefixed, omit, layer, parse and its parsers; a plain object |
| ./path | Path (as node:path) | posixPath({ cwd }), win32Path({ cwd }), pure |
| ./dirs | Dirs, PlatformFacts (cwd too), AppDirs | dirsOf({ facts, env }); testDirs(facts) |
| ./terminal | Terminal | colorDepthOf(stream, env); testTerminal({ input }) |
| ./open | Open | printOpen({ console }); memoryOpen() |
| ./module | Modules, LoadModule | loadModuleOf(modules, root, beside); memoryModules(modules) |
| ./process | Spawn, ChildProcess, ProcessStatus, ProcessSignal, Kill, … | exec(spawn, command, args, { cwd, env, input, signal }); memoryKill(pid) |
| ./runtime | Program, Interrupts, Exit, ExitCode | runMain(program, { platform, interrupts, exit }); manualInterrupts() |
| ./errors | PlatformError | BadArgument, SystemError with a reason, isPlatformError |
| ./test | TestPlatform, TestPlatformOptions | testPlatform({ directory, ...members }), every double |
import type { Platform } from '@wtf/platform'
import { testPlatform } from '@wtf/platform/test'
import { sleep, wallTime } from '@wtf/platform/timers'
const greet = async (
platform: Pick<Platform, 'console' | 'setTimeout' | 'clearTimeout' | 'performance'>
) => {
await sleep(1000, platform)
platform.console.log('Hello at %d', wallTime(platform))
}
const platform = testPlatform()
const done = greet(platform)
await platform.timers.advance(1000)
await done
platform.console.records // [{ level: 'info', method: 'log', message: 'Hello at 1000', … }]Each double of a standard member behaves as the standard says, and is held to its Web Platform
Tests. Locks, channels, ports and workers run in this realm: they copy each message with
structuredClone and grant each lock in a task of its own. The console double is the standard's
namespace object.
When a member defined here fails, it throws a PlatformError, as Effect's does: a BadArgument
for something the caller passed, or a SystemError with a reason (NotFound,
PermissionDenied, UnexpectedEof, …). Each names its module and method. A member from a web
standard fails as the standard says, with a DOMException named InvalidStateError,
DataCloneError, NotSupportedError or QuotaExceededError. The environment's errors name the
variable and never its value.
Processes
No web standard starts a process, so ./process builds one from standard parts, as Deno's
Command does. A Spawn starts a command with its arguments, with no shell, and gives you a
ChildProcess: its stdin is a WritableStream of bytes, its stdout and stderr are
ReadableStreams of bytes, and its status is a promise of how it ended, { code, signal? }. An
AbortSignal you pass ends it with SIGTERM, and kill(signal) sends it a signal, as Deno's
ChildProcess does. exec runs one to its end and gives you its output as text:
import type { ProcessPlatform } from '@wtf/platform'
import { exec } from '@wtf/platform/process'
const head = async (platform: Pick<ProcessPlatform, 'spawn' | 'dirs'>) => {
const { stdout, code } = await exec(platform.spawn, 'git', ['rev-parse', 'HEAD'], {
cwd: platform.dirs.cwd
})
return code === 0 ? stdout.trim() : undefined
}Platform has no spawn, since a browser starts no process. A platform that does is a
ProcessPlatform: Node's, from nodePlatform, and one in memory, from memoryPlatform. A
process gets the env you give it, whole, or else the platform's, and works in the cwd you give
it, or else the platform's working folder. A command that is not there rejects its status, and
exec, with a SystemError whose reason is NotFound. A non-zero exit code is not an error:
exec gives it to you to decide. spawn itself never throws: a process that could not start, for
any reason, rejects its status. Its stdin takes bytes alone: a chunk that is no Uint8Array
rejects with a TypeError, and the process sees its input end.
A process may catch or ignore SIGTERM. To be sure it ends, send it SIGKILL after a grace of
your own, by the platform's timers:
import type { ProcessPlatform } from '@wtf/platform'
declare const platform: ProcessPlatform
const child = platform.spawn('server', [])
// …
const grace = platform.setTimeout(() => child.kill('SIGKILL'), 2000)
child.kill() // SIGTERM
const { code, signal } = await child.status.finally(() => platform.clearTimeout(grace))kill sends nothing to a process that has ended, and throws a BadArgument of a name that is no
ProcessSignal. A platform's own spawn builds on signalled(signal), the status of a process a
signal ended, sendable(signal), the signal a kill sends, checked, and
notStarted(command, reason), the error of one that could not start.
A ProcessPlatform also knows the process your program runs as: pid, its id; execArgv, the
runtime's own flags, which are not in argv; and execPath, the runtime's executable. Its
kill(pid, 0) asks whether another process is still there, as Node's process.kill(pid, 0) does:
it sends no signal, and throws an error whose code is ESRCH when the process is gone. A lock
that records its holder's pid uses it to take over from a holder that died. memoryKill(pid) is
its double, for a platform whose only process is its own: it finds pid, and throws a
SystemError of NotFound, its code ESRCH, for any other. testPlatform runs as the pid 1.
Modules
A ProcessPlatform also loads a module by its name, as a tool loads a plugin its configuration
names. No web standard says which folder a name is looked for from, so ./module defines
Modules: resolve(specifier, from) gives the file a path or a package name stands for, seen
from a folder, or from a module's file: URL, and load(file) imports it.
loadModuleOf(modules, root, beside) gives a LoadModule: a path is read from root, and a
package is looked for in root, then beside beside, as your tool gives its own
import.meta.url:
import type { ProcessPlatform } from '@wtf/platform'
import { loadModuleOf } from '@wtf/platform/module'
declare const platform: ProcessPlatform
declare const root: string
const load = loadModuleOf(platform.modules, root, import.meta.url)
const formatters = await load('@acme/formatters')A module that is not there is a SystemError of NotFound. memoryModules(modules) is the
double: it holds the exports of each module by its name, and finds no other. testPlatform's
modules holds none.
The file system
navigator.storage.getDirectory() returns the root of the platform's file system, a
FileSystemDirectoryHandle typed by ./fs, the File System Standard's types. That is a page's
origin private file system, the folder Node's entry point passes in, or the folder a test gives
testPlatform({ directory }). To reach a path, resolve it against dirs.cwd with path, and
walk down from the root, as at from @wtf/platform-fs/path does. Without a directory, testPlatform() has no file
system: getDirectory() rejects with a SecurityError, as the Storage Standard says a page
without storage does.
The types follow a web standard where one exists, and are defined here otherwise. The doubles are
real exports. The only dependency is @standard-schema/spec, for the types of parse. The file
system types are this package's own, in ./fs, so any file system that keeps to the standard fits
them; @wtf/platform-fs builds on them, and its errors are this package's PlatformErrors.
