Client registries, environments, services and patches
UI4 BASE API under ADR 0030; implementation and validation evidence is in the slice review report. Register contributions from an
addon’s exported synchronous register(ctx) callback. The assembler supplies
callbacks in the server module load order; importing a module alone must never
patch or register anything. UI3 owns connecting that callback list to bundle output.
Define each category once with a runtime type guard, then use its typed registry.
Guards run on every insertion and forced replacement, including production mode.
Addon types extend Registries in @erpforall/elang; service aliases extend
Services. Executable examples are in web/tests/extensions.test.ts; final validation evidence
is recorded in docs/design/m4-ui4.md.
import { RegistryHub } from "@erpforall/elang";
declare module "@erpforall/elang" { interface Registries { badges: { title: string }; }}const registry = new RegistryHub();const badges = registry.define("badges", (value: unknown): value is { title: string } => typeof value === "object" && value !== null && "title" in value && typeof value.title === "string");badges.add("my_addon.ready", { title: "Ready" }, { sequence: 20 });getEntries() and getAll() participate in reactive bindings. Adding/removing an
entry updates a mounted consumer without reloading. Returned arrays and entry
pairs are copies. The payload is shared: publish a replacement with force: true
to notify consumers. Sequences default to 50, forced replacement preserves the
previous sequence, and equal sequences retain insertion order. Duplicate keys,
missing keys and missing categories have typed ExtensionError codes; get(key, fallback) explicitly opts into an optional lookup. An omitted schema is an error.
Create one ServiceContainer and createEnv({services}) per mounted application.
Register classes with add(Class, alias?), await services.start(env), then pass
env to mount. A class declares static dependencies = [OtherService] and a
static start(env, dependencies) returning its instance (or a promise). The
resolver’s get(Class) returns typed dependency instances. A dependency may be
used only if declared. Startup validates missing dependencies and cycles before
starting anything; independent services start in parallel. Failure rejects with a
service-named error and original cause; retry needs a fresh container.
In component setup(), useService(Class) returns an instance-shaped facade;
useService("alias") is typed through Services. Methods keep the original
instance receiver. Declare static asyncMethods = ["read", "save"] (or static readonly asyncMethods = true
to inspect every method result) for async protection: pending results and errors stop reaching
the component when it is destroyed; later calls reject with service-destroyed.
This suppresses delivery and does not abort the service’s underlying remote work.
The service must own any transport cancellation it needs. Synchronous errors and
live async failures propagate to the caller.
useEnv() returns the component’s environment; Component.env exposes it after
construction. useSubEnv({context: ...}) creates a shallow frozen environment
inheriting from the current one. The component and descendants see that scope;
siblings and other mounted applications retain their own scope. All hooks above
require setup. The environment holds services, an EventTarget bus, debug,
isSmall and action context; freezing the container does not deeply freeze
service instances or other supplied objects.
Use ctx.patch(Class, sup => ({ method() { return sup.method.call(this); } }))
for instance methods and ctx.patchStatic(Class, factory) for static members.
Plain objects are also supported. Override signatures must match the target;
augment the target interface first when declaring new members. Constructors and
ES class fields cannot be intercepted: initialize patchable state in setup().
Each call returns an idempotent undo function. Undoing a middle patch keeps other
patches in their original order. Factories may run again when an earlier patch is
removed, so keep factories free of side effects and put work in the returned
methods. Descriptors and symbol members are preserved; a getter-only patch keeps
the existing setter. Within a patched getter, use Reflect.get(sup, "name", this)
to evaluate the predecessor getter against the live receiver. Non-configurable
members cannot be patched reversibly and fail loudly.
registerAddons returns a read-only map from addon id to its PatchSet.
Its context’s patch functions are bound to that set, so host addon removal can
call sets.get(addonId).unpatchAll(). It removes that addon’s patches in reverse
order, preserving other addons’ layers. A standalone new PatchSet(addonId)
offers the same typed patch and patchStatic functions. Each set admits 4096
active patches; addon ids contain 1..256 UTF-16 code units. getPatches() copies
the active (addon,target,member) metadata without executing factories. Class
instance targets appear as their prototypes; symbol member identity is retained.
UI6 still owns automatic rollback for its test harness. Default business
services are outside this API.
unpatchAll() closes the set to further installation, including saved context
functions and late asynchronous code. Repeated removal is safe. When a factory
rebuild refuses removal, the failed handles remain available for retry. If both
registration and cleanup fail, AddonRegistrationError retains the original
cause, all errors, and a patchSets index for explicit cleanup retry.
The build-host conflict lint is run with the pinned Node toolchain:
node web/scripts/lint-patches.mjs path/to/tsconfig.json path/to/patches.jsonThe JSON manifest is an ordered array of {"addon":"my_addon","file":"./register.ts"}
entries, with files relative to the manifest. Supply server/assembler load order;
the lint does not infer dependencies. It prints JSON diagnostics and exits 1 on
conflicts or unanalysable syntax, 2 on malformed inputs or syntax/project failures, and
0 on a clean analysis. It resolves imported class/object aliases, distinguishes
static and instance targets, and flags later addon replacements without a sup
call to the same member. A mention in a comment or string is insufficient.
This tooling uses the pinned TypeScript 7 native API; it is not in browser bundles.
Use direct ctx.patch / ctx.patchStatic statements in a named register(ctx)
function with inline factories returning object literals. Dynamic execution,
computed symbol keys, spread descriptors, aliased patch functions and indirect
factory returns produce explicit unanalysable diagnostics. This conservative
lint is not a proof that arbitrary JavaScript delegates on every execution path.
UI3 owns emitting the final bundle’s ordered manifest; no automatic bundle lint
integration is claimed by this runtime helper.
Registries allow 4096 entries/category and 256 categories/hub. Names and keys contain 1..256 UTF-16 code units; sequences are integers in -1000000..1000000. Bounds reject before publishing; replacing an existing entry at capacity works. The service container accepts at most 256 classes; registration closes when startup begins. A lazy bundle must import the canonical service class from the same defining module as the host. Two separately evaluated classes sharing a name are different keys. String aliases are unique typed lookup keys, not class-name matching or automatic deduplication.
Patches refuse the shared Object, Function and Array prototypes and the reserved keys constructor, prototype and proto. Override descriptors must be configurable to permit removal. Factory failures retain the current chain. Addon registration failure stops the sequence and removes its owned patches. Already published registry contributions still require the host to abort/rebuild its app; there is no transaction across all addon side effects. Removal failures surface to the caller and retain failed patch ownership for retry.
Async protection preserves synchronous return values and synchronous throws; it
wraps actual thenables only. Declaring asyncMethods=true does not turn synchronous
methods into Promise-returning methods. The facade forwards property reads and
method calls, but raw own-field reflection (Object.keys, object spread and own
fields checked with in) is not forwarded by BASE. Use service methods/property
reads for component access rather than assuming raw-instance reflection.