@bitakit/core 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +137 -337
- package/discovery/generate.mjs +2 -8
- package/dist/actions/action-list.d.ts +1 -1
- package/dist/actions/action-list.js +53 -4
- package/dist/actions/action.d.ts +3 -3
- package/dist/actions/types.d.ts +4 -0
- package/dist/app/access.js +2 -1
- package/dist/app/service-aliases.d.ts +4 -0
- package/dist/app/service-aliases.js +14 -0
- package/dist/app/types.d.ts +12 -1
- package/dist/auth-navigation.d.ts +13 -0
- package/dist/auth-navigation.js +33 -0
- package/dist/contracts.d.ts +5 -0
- package/dist/contributions/command.js +9 -0
- package/dist/contributions/index.d.ts +1 -0
- package/dist/core.d.ts +4 -0
- package/dist/core.js +2 -0
- package/dist/definitions.d.ts +30 -4
- package/dist/discovered.d.ts +9 -5
- package/dist/discovered.js +3 -2
- package/dist/events/action-setup.d.ts +19 -0
- package/dist/events/action-setup.js +24 -0
- package/dist/events/service.d.ts +18 -0
- package/dist/events/service.js +98 -0
- package/dist/events/types.d.ts +19 -0
- package/dist/events/types.js +1 -0
- package/dist/replacements.d.ts +1 -1
- package/dist/runtime.d.ts +2 -0
- package/dist/runtime.js +18 -2
- package/dist/service-key.d.ts +6 -0
- package/dist/service-key.js +0 -1
- package/dist/services.d.ts +2 -1
- package/dist/services.js +5 -1
- package/docs/auth.md +106 -0
- package/docs/events.md +157 -0
- package/docs/file-contributions.md +13 -0
- package/docs/reference.md +404 -0
- package/docs/todo-tutorial.md +88 -0
- package/examples/todos/actions/create.mjs +7 -0
- package/examples/todos/actions/delete.mjs +14 -0
- package/examples/todos/actions/list.mjs +7 -0
- package/examples/todos/plugin.mjs +11 -0
- package/examples/todos/services/tasks.mjs +30 -0
- package/examples/todos.mjs +17 -0
- package/package.json +4 -2
package/dist/runtime.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { EventService } from './events/service.js';
|
|
1
2
|
import { ConfigService } from './config-service.js';
|
|
2
3
|
import { ActionGroup, type ActionList } from '@bitakit/core/actions';
|
|
3
4
|
import type { ContributionMap, ResolvedContribution, ResolvedForm, Field, FoundationConfig, Plugin, Services, Translator } from './definitions.js';
|
|
@@ -14,6 +15,7 @@ export declare class FoundationRuntime implements ContributionHost {
|
|
|
14
15
|
readonly config: FoundationConfig;
|
|
15
16
|
private providedServices;
|
|
16
17
|
readonly app: FoundationApp;
|
|
18
|
+
readonly events: EventService;
|
|
17
19
|
readonly configuration: ConfigService;
|
|
18
20
|
readonly modules: readonly Plugin[];
|
|
19
21
|
private readonly actionConfigs;
|
package/dist/runtime.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { EventService, createEventScope } from './events/service.js';
|
|
2
|
+
import { setupAction } from './events/action-setup.js';
|
|
1
3
|
import { serviceObserver } from './interceptors/service-observers.js';
|
|
2
4
|
import { isServiceInterceptor } from './interceptors/service.js';
|
|
3
5
|
import { ConfigService } from './config-service.js';
|
|
@@ -9,6 +11,7 @@ import { ActionGroup, } from '@bitakit/core/actions';
|
|
|
9
11
|
import { PluginScope, assignScopeModule } from './scope.js';
|
|
10
12
|
import { createServices } from './services.js';
|
|
11
13
|
import { createFoundationApp } from './app/access.js';
|
|
14
|
+
import { serviceAliases } from './app/service-aliases.js';
|
|
12
15
|
import { fallbackTitle } from './conventions.js';
|
|
13
16
|
import { ActionFailure, evaluateFeedback, } from './actions/feedback.js';
|
|
14
17
|
import { adaptContribution, } from './contributions/index.js';
|
|
@@ -35,6 +38,7 @@ export class FoundationRuntime {
|
|
|
35
38
|
config;
|
|
36
39
|
providedServices;
|
|
37
40
|
app;
|
|
41
|
+
events;
|
|
38
42
|
configuration;
|
|
39
43
|
modules;
|
|
40
44
|
actionConfigs = new Map();
|
|
@@ -75,7 +79,8 @@ export class FoundationRuntime {
|
|
|
75
79
|
this.modules = [
|
|
76
80
|
{ ...config, id: config.appId ?? '@foundation/app' },
|
|
77
81
|
...(config.plugins ?? []),
|
|
78
|
-
];
|
|
82
|
+
].map((module) => ({ ...module, publicServices: serviceAliases(module) }));
|
|
83
|
+
this.events = new EventService(config.onEventError);
|
|
79
84
|
this.app = createFoundationApp(this);
|
|
80
85
|
this.configuration = new ConfigService([{ id: config.appId ?? '@foundation/app', config: config.config }, ...(config.plugins ?? [])], config.configOverrides);
|
|
81
86
|
validatePluginPages(this.modules);
|
|
@@ -262,7 +267,7 @@ export class FoundationRuntime {
|
|
|
262
267
|
...selected.plugins,
|
|
263
268
|
]);
|
|
264
269
|
const serviceModules = new Map(plugins.flatMap((plugin) => (plugin.services ?? []).map((service) => [service, plugin.id])));
|
|
265
|
-
this.container = createServices(plugins.flatMap((plugin) => plugin.services ?? []), this.providedServices, (definition) => this.configuration.context(serviceModules.get(definition)), serviceObserver(this.modules));
|
|
270
|
+
this.container = createServices(plugins.flatMap((plugin) => plugin.services ?? []), this.providedServices, (definition) => this.configuration.context(serviceModules.get(definition)), serviceObserver(this.modules), this.events);
|
|
266
271
|
try {
|
|
267
272
|
this.extensionCleanups.push(this.actions.subscribeExecution((event) => {
|
|
268
273
|
if (event.phase === 'failed' &&
|
|
@@ -398,6 +403,16 @@ export class FoundationRuntime {
|
|
|
398
403
|
? this.actions.add(registration.id, registration.instance, registration.placement)
|
|
399
404
|
: this.actions.register(registration.definition, registration.placement);
|
|
400
405
|
scope.own(handle.unregister);
|
|
406
|
+
if (adapted.setup) {
|
|
407
|
+
const eventScope = createEventScope(this.events);
|
|
408
|
+
handle.onDispose(eventScope.dispose);
|
|
409
|
+
const cleanup = adapted.setup({
|
|
410
|
+
events: eventScope.events, services: this.services,
|
|
411
|
+
action: setupAction(handle), app: this.app, config,
|
|
412
|
+
});
|
|
413
|
+
if (cleanup)
|
|
414
|
+
handle.onDispose(cleanup);
|
|
415
|
+
}
|
|
401
416
|
this.registrations.push({ definition: adapted.definition, handle });
|
|
402
417
|
}
|
|
403
418
|
}
|
|
@@ -435,6 +450,7 @@ export class FoundationRuntime {
|
|
|
435
450
|
catch (error) {
|
|
436
451
|
errors.push(error);
|
|
437
452
|
}
|
|
453
|
+
this.events.clear();
|
|
438
454
|
this.container = undefined;
|
|
439
455
|
this.registrations = [];
|
|
440
456
|
this.actionConfigs.clear();
|
package/dist/service-key.d.ts
CHANGED
|
@@ -7,6 +7,12 @@ export type ServiceKey<T> = string & {
|
|
|
7
7
|
export declare function serviceKey<T>(id: string): ServiceKey<T>;
|
|
8
8
|
export declare function getService<T>(services: Partial<Services>, key: ServiceKey<T>): T;
|
|
9
9
|
/** The provider must implement the shared contract; registration and cleanup use the normal container. */
|
|
10
|
+
export declare function provideService<T, const Name extends string>(key: ServiceKey<T>, definition: Omit<ServiceDefinition<NoInfer<T>>, 'id'> & {
|
|
11
|
+
exposeAs: Name;
|
|
12
|
+
}): ServiceDefinition<T> & {
|
|
13
|
+
id: ServiceKey<T>;
|
|
14
|
+
exposeAs: Name;
|
|
15
|
+
};
|
|
10
16
|
export declare function provideService<T>(key: ServiceKey<T>, definition: Omit<ServiceDefinition<NoInfer<T>>, 'id'>): ServiceDefinition<T> & {
|
|
11
17
|
id: ServiceKey<T>;
|
|
12
18
|
};
|
package/dist/service-key.js
CHANGED
|
@@ -8,7 +8,6 @@ export function getService(services, key) {
|
|
|
8
8
|
throw new Error(`Missing service "${key}".`);
|
|
9
9
|
return services[key];
|
|
10
10
|
}
|
|
11
|
-
/** The provider must implement the shared contract; registration and cleanup use the normal container. */
|
|
12
11
|
export function provideService(key, definition) {
|
|
13
12
|
return { ...definition, id: key };
|
|
14
13
|
}
|
package/dist/services.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
+
import type { Events } from './events/types.js';
|
|
1
2
|
import { type ConfigContext } from './config-service.js';
|
|
2
3
|
import type { ServiceDefinition, Services } from './definitions.js';
|
|
3
|
-
export declare function createServices(definitions: readonly ServiceDefinition<any>[], provided?: Partial<Services>, configFor?: (definition: ServiceDefinition<any>) => ConfigContext, decorate?: (id: string, instance: any, active: () => boolean) => any): {
|
|
4
|
+
export declare function createServices(definitions: readonly ServiceDefinition<any>[], provided?: Partial<Services>, configFor?: (definition: ServiceDefinition<any>) => ConfigContext, decorate?: (id: string, instance: any, active: () => boolean) => any, events?: Events): {
|
|
4
5
|
services: Services;
|
|
5
6
|
dispose: () => void;
|
|
6
7
|
};
|
package/dist/services.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
import { EventService, createEventScope } from './events/service.js';
|
|
1
2
|
import { ConfigService } from './config-service.js';
|
|
2
|
-
export function createServices(definitions, provided = {}, configFor = () => new ConfigService([{ id: 'app' }]).context('app'), decorate = (_id, instance) => instance) {
|
|
3
|
+
export function createServices(definitions, provided = {}, configFor = () => new ConfigService([{ id: 'app' }]).context('app'), decorate = (_id, instance) => instance, events = new EventService()) {
|
|
3
4
|
let active = true;
|
|
4
5
|
const pending = new Map();
|
|
5
6
|
const instances = Object.create(null);
|
|
@@ -31,7 +32,10 @@ export function createServices(definitions, provided = {}, configFor = () => new
|
|
|
31
32
|
for (const [id, definition] of pending) {
|
|
32
33
|
if (definition.requires?.some((key) => !Object.hasOwn(instances, key)))
|
|
33
34
|
continue;
|
|
35
|
+
const eventScope = createEventScope(events);
|
|
36
|
+
cleanups.push(eventScope.dispose);
|
|
34
37
|
const instance = definition.create({
|
|
38
|
+
events: eventScope.events,
|
|
35
39
|
services: instances,
|
|
36
40
|
config: configFor(definition),
|
|
37
41
|
});
|
package/docs/auth.md
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
# Client authentication
|
|
2
|
+
|
|
3
|
+
These APIs are available in the workspace; they require a release before use from npm.
|
|
4
|
+
Core owns the `AuthService` contract. Optional provider plugins supply the session;
|
|
5
|
+
`@bitakit/ui` observes it and uses the existing framework navigation binding.
|
|
6
|
+
There is no second session store. Server authentication and authorization remain
|
|
7
|
+
with the provider and application server.
|
|
8
|
+
|
|
9
|
+
## Better Auth and external paths
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { betterAuthPlugin } from '@bitakit/better-auth';
|
|
13
|
+
|
|
14
|
+
const authPlugin = betterAuthPlugin(client, {
|
|
15
|
+
paths: {
|
|
16
|
+
signIn: '/account/login',
|
|
17
|
+
afterSignIn: '/customers',
|
|
18
|
+
afterSignOut: '/',
|
|
19
|
+
},
|
|
20
|
+
});
|
|
21
|
+
// Add authPlugin to the existing FoundationProvider plugin list.
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Paths are application-owned, safe root-relative URLs. No routes are created.
|
|
25
|
+
`useAuth().signIn({ returnTo })` navigates to the configured login page with a
|
|
26
|
+
`returnTo` query parameter, unless the adapter supplies a native `signIn` handler.
|
|
27
|
+
External or login-loop return destinations fall back to `afterSignIn`.
|
|
28
|
+
|
|
29
|
+
The login page must pass `resolveAuthReturnTo(paths, returnToFromURL)` to the native
|
|
30
|
+
provider login API as its completion destination. `afterSignIn` is a fallback,
|
|
31
|
+
not an automatic session-change redirect. Providers requiring absolute callbacks
|
|
32
|
+
should resolve the validated path against the configured **application** origin,
|
|
33
|
+
not the authentication-server origin. Keep secrets and server configuration on the server.
|
|
34
|
+
|
|
35
|
+
```tsx
|
|
36
|
+
import { AuthBoundary, useAuth } from '@bitakit/ui';
|
|
37
|
+
import { LoadingPage, ErrorPage } from '@bitakit/shell/pages';
|
|
38
|
+
|
|
39
|
+
function ProtectedContent({ children }) {
|
|
40
|
+
return (
|
|
41
|
+
<AuthBoundary
|
|
42
|
+
pending={<LoadingPage />}
|
|
43
|
+
renderError={() => <ErrorPage />}
|
|
44
|
+
>
|
|
45
|
+
{children}
|
|
46
|
+
</AuthBoundary>
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function AccountControls() {
|
|
51
|
+
const { user, pending, signOut } = useAuth();
|
|
52
|
+
// Bind signOut to the application's existing Action or button handler.
|
|
53
|
+
// Handle a rejected promise using the application's existing error presentation.
|
|
54
|
+
}
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
`AuthBoundary` waits for pending session resolution and does not redirect on session
|
|
58
|
+
errors. `redirect={false}` allows host-owned unauthenticated presentation. It is a
|
|
59
|
+
client rendering convenience, never a security boundary. Keep native server checks.
|
|
60
|
+
`useAuth().signOut()` awaits the adapter and then navigates to `afterSignOut`;
|
|
61
|
+
the boundary does not race that operation with a login redirect. A subsequent
|
|
62
|
+
protected route can start login normally. Calling a native SDK or service directly
|
|
63
|
+
does not invoke this UI navigation policy. Configure only one owner for logout navigation.
|
|
64
|
+
|
|
65
|
+
## Writing another adapter
|
|
66
|
+
|
|
67
|
+
Implement the existing `AuthService`, register it with `provideService(authService, ...)`,
|
|
68
|
+
and use an ordinary plugin. No Core change, provider registry or host bootstrap is needed.
|
|
69
|
+
The following is an adapter template: `source` is a normalized SDK bridge that the
|
|
70
|
+
adapter author implements using their provider's public APIs, not an Auth.js or Clerk API.
|
|
71
|
+
|
|
72
|
+
```ts
|
|
73
|
+
import {
|
|
74
|
+
authService, configureAuthPaths, definePlugin, provideService,
|
|
75
|
+
type AuthPaths, type AuthService,
|
|
76
|
+
} from '@bitakit/core';
|
|
77
|
+
|
|
78
|
+
export function customAuthPlugin(source: AuthService, paths: AuthPaths) {
|
|
79
|
+
return definePlugin({
|
|
80
|
+
id: 'custom-auth',
|
|
81
|
+
services: [provideService(authService, {
|
|
82
|
+
create: () => ({
|
|
83
|
+
paths: configureAuthPaths(paths),
|
|
84
|
+
getSnapshot: () => source.getSnapshot(),
|
|
85
|
+
subscribe: listener => source.subscribe(listener),
|
|
86
|
+
signOut: () => source.signOut(),
|
|
87
|
+
...(source.signIn
|
|
88
|
+
? { signIn: options => source.signIn!(options) }
|
|
89
|
+
: {}),
|
|
90
|
+
}),
|
|
91
|
+
})],
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
The bridge must return a stable `{ user, pending, error }` snapshot until it changes;
|
|
97
|
+
`user` contains at least `id`, and `null` means signed out only once `pending` is false
|
|
98
|
+
and `error` is absent. Subscribe to native SDK updates and return an unsubscribe
|
|
99
|
+
function. Preserve SDK failures, await sign-out, and release any adapter-owned
|
|
100
|
+
resources through the ordinary service/plugin lifecycle. Keep React-only SDK providers
|
|
101
|
+
inside the optional integration package using existing plugin providers.
|
|
102
|
+
|
|
103
|
+
Auth.js and Clerk adapters are not implemented here. Their native session/login APIs
|
|
104
|
+
must be mapped inside their optional packages; organizations, registration and password
|
|
105
|
+
recovery are not standardized by this small contract. Better Auth remains the working
|
|
106
|
+
reference in `packages/better-auth/src/index.ts`.
|
package/docs/events.md
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
# Events and action setup
|
|
2
|
+
|
|
3
|
+
Workspace API, pending publication. Core owns one mitt-backed event bus per
|
|
4
|
+
`FoundationRuntime`, available as `runtime.events` and `app.events`. There is no
|
|
5
|
+
global bus, React dependency, replay buffer, persistence, or cross-process delivery.
|
|
6
|
+
|
|
7
|
+
## Sending and receiving
|
|
8
|
+
|
|
9
|
+
Service `create({ events })` and action `setup({ events, services, action, app, config })`
|
|
10
|
+
receive scoped views of the same bus. Emit after the source data has changed:
|
|
11
|
+
|
|
12
|
+
```ts
|
|
13
|
+
events.emit('todos.changed', { kind: 'added', id: 42 });
|
|
14
|
+
|
|
15
|
+
events.watch(['todos.loaded', 'todos.changed'], (event, { signal }) => {
|
|
16
|
+
console.log(event.type, event.data, signal.aborted);
|
|
17
|
+
});
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Each event invokes the handler once, even if its name appears twice in the array.
|
|
21
|
+
The array means OR, not waiting for all events or batching them. Names are literal;
|
|
22
|
+
`*` is not a wildcard. Callbacks may emit further events synchronously, so applications
|
|
23
|
+
must avoid event cycles.
|
|
24
|
+
|
|
25
|
+
`watch` returns an idempotent function for optional early unsubscription. In action
|
|
26
|
+
setup and service creation, ownership is automatic. Direct `app.events.watch` calls
|
|
27
|
+
are caller-owned until runtime unmount; use the returned cleanup outside these scopes.
|
|
28
|
+
|
|
29
|
+
## Declarative Action events
|
|
30
|
+
|
|
31
|
+
For a fixed set of custom events, declare one shared handler:
|
|
32
|
+
|
|
33
|
+
```ts
|
|
34
|
+
export default defineAction({
|
|
35
|
+
events: ['todos.changed', 'selection.changed'],
|
|
36
|
+
onEvent(event, { services, action, signal }) {
|
|
37
|
+
switch (event.type) {
|
|
38
|
+
case 'todos.changed':
|
|
39
|
+
action.enabled = services.todos.list().length > 0;
|
|
40
|
+
break;
|
|
41
|
+
case 'selection.changed':
|
|
42
|
+
// Use event.data or call a feature-specific function.
|
|
43
|
+
break;
|
|
44
|
+
}
|
|
45
|
+
},
|
|
46
|
+
});
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
The handler receives the same context as setup, plus the subscription's AbortSignal.
|
|
50
|
+
It may be async. Subscriptions are installed before `setup` and share its owned
|
|
51
|
+
scope, including rollback when setup fails. Declaring events does not synthesize
|
|
52
|
+
an initial event, execute the Action, or automatically refresh all Actions. Use
|
|
53
|
+
setup for an initial check; use onEvent for the reaction you actually need.
|
|
54
|
+
Known payloads are inferred from the event names when defineAction's generics are
|
|
55
|
+
inferred. Supplying explicit type arguments uses the default event-name type unless
|
|
56
|
+
that parameter is also specified; events.watch can infer its names independently.
|
|
57
|
+
|
|
58
|
+
For local form input, prefer the existing per-binding input rather than writing a
|
|
59
|
+
shared enabled flag from text-change events:
|
|
60
|
+
|
|
61
|
+
```ts
|
|
62
|
+
export default defineAction({
|
|
63
|
+
resolve: (text: string) => ({ enabled: typeof text === 'string' && text.length > 0 }),
|
|
64
|
+
execute: ({ input, services }) => services.todos.add(input),
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
// Inside the React form; text is the current form value.
|
|
68
|
+
<ActionButton action="todos.add" input={text} />
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Each binding evaluates its own input. Two forms using the same Action can therefore
|
|
72
|
+
have different enabled states. Mutating nested input fields in place is not observed;
|
|
73
|
+
pass updated input values through the existing form/React state. A custom event
|
|
74
|
+
that writes action.enabled instead changes the shared registration for all bindings.
|
|
75
|
+
|
|
76
|
+
## Action lifecycle
|
|
77
|
+
|
|
78
|
+
`setup` runs synchronously once per registration, after the services exist. It can
|
|
79
|
+
return a cleanup for other resources. Register async event handlers inside setup;
|
|
80
|
+
do not make setup itself async. Public `app.services` becomes available only after
|
|
81
|
+
runtime mount; setup uses its directly supplied `services` context.
|
|
82
|
+
|
|
83
|
+
`action.enabled`, `visible`, `checked`, and other presentation properties write to
|
|
84
|
+
the existing ActionList store. `action.get()` reads the current snapshot;
|
|
85
|
+
`action.update(patch)` supports combined updates. There is no mirrored action store.
|
|
86
|
+
Writes after removal are ignored, including writes from a previous registration
|
|
87
|
+
after another action takes its ID.
|
|
88
|
+
|
|
89
|
+
Run the initial check explicitly after subscribing. Events are notifications, not
|
|
90
|
+
stored state. The service remains the source of truth. Existing `resolve(input, context)`
|
|
91
|
+
can derive input-specific guards at execution time; changing `enabled` is only a
|
|
92
|
+
presentation/global execution guard, not server authorization or input validation.
|
|
93
|
+
|
|
94
|
+
Action removal, list disposal, runtime unmount, and failed setup release subscriptions.
|
|
95
|
+
Service subscriptions follow service disposal. Runtime remount creates fresh owned
|
|
96
|
+
subscriptions. A disposed scoped sender cannot emit into a later mount.
|
|
97
|
+
|
|
98
|
+
Definition-level `watch: ['serviceId']` keeps its existing meaning: subscribe to an
|
|
99
|
+
observable service and refresh presentation. `events.watch(...)` listens to named
|
|
100
|
+
events; it does not reinterpret that older property.
|
|
101
|
+
|
|
102
|
+
## Async handlers and errors
|
|
103
|
+
|
|
104
|
+
`emit` dispatches synchronously in registration order and returns `void`. An async
|
|
105
|
+
handler starts immediately, but the emitter does not await its promise. Handlers
|
|
106
|
+
can overlap; there is no serialization or latest-request-wins behavior.
|
|
107
|
+
|
|
108
|
+
Both synchronous throws and promise rejections go to
|
|
109
|
+
`FoundationConfig.onEventError(error, event)`. The default reports to `console.error`.
|
|
110
|
+
One failing handler does not prevent other handlers from receiving the event.
|
|
111
|
+
Errors are reported even if the handler rejects after unsubscription.
|
|
112
|
+
|
|
113
|
+
Each subscription supplies an `AbortSignal`, aborted when unsubscribed. Pass it to
|
|
114
|
+
abort-aware operations and check it before external side effects after `await`:
|
|
115
|
+
|
|
116
|
+
```ts
|
|
117
|
+
events.watch('documents.reload', async (event, { signal }) => {
|
|
118
|
+
const response = await fetch('/api/documents', { signal });
|
|
119
|
+
const documents = await response.json();
|
|
120
|
+
if (!signal.aborted) updateDocuments(documents);
|
|
121
|
+
});
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
Unsubscription cannot forcibly cancel arbitrary JavaScript or undo side effects.
|
|
125
|
+
Applications decide how to handle expected cancellation in their handler/error reporter.
|
|
126
|
+
|
|
127
|
+
## Typed payloads
|
|
128
|
+
|
|
129
|
+
Augment the shared event map for known names. This does not register anything at runtime:
|
|
130
|
+
|
|
131
|
+
```ts
|
|
132
|
+
declare module '@bitakit/core' {
|
|
133
|
+
interface EventMap {
|
|
134
|
+
'todos.changed': { kind: 'added' | 'removed'; id: number };
|
|
135
|
+
'todos.loaded': undefined;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
Known events require matching payloads. Multi-event handlers receive a discriminated
|
|
141
|
+
`{ type, data }` union. Unknown names remain permitted with an `unknown` payload,
|
|
142
|
+
so independently developed plugins can participate without a global registry.
|
|
143
|
+
|
|
144
|
+
## React
|
|
145
|
+
|
|
146
|
+
```ts
|
|
147
|
+
import { useWatchEvent } from '@bitakit/ui';
|
|
148
|
+
|
|
149
|
+
useWatchEvent(['todos.loaded', 'todos.changed'], (event) => {
|
|
150
|
+
// React to event.type and event.data.
|
|
151
|
+
});
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
The hook subscribes once the Foundation runtime is ready, follows current callbacks,
|
|
155
|
+
and unsubscribes when names/runtime change or the component unmounts. Inline name
|
|
156
|
+
arrays do not resubscribe when their contents stay the same. Events emitted before
|
|
157
|
+
the subscription are not replayed; read source state for initial rendering.
|
|
@@ -159,3 +159,16 @@ object collections and arrays. `interceptors/actions/save.ts` and
|
|
|
159
159
|
Use defineActionInterceptor or defineServiceInterceptor to set that discriminator automatically.
|
|
160
160
|
The legacy defineInterceptor remains an Action definition. Service observers can select one method
|
|
161
161
|
or all methods; see the Core README for lifecycle and observation boundaries.
|
|
162
|
+
|
|
163
|
+
## Inline service names
|
|
164
|
+
|
|
165
|
+
`defineService({ exposeAs: 'clock', create: ... })` and
|
|
166
|
+
`provideService(clockKey, { exposeAs: 'clock', create: ... })` expose the same container
|
|
167
|
+
instance through `app.services.clock`. Omit `exposeAs` in ordinary discovered files:
|
|
168
|
+
Core uses the explicit service ID or relative file path. An explicit name changes only
|
|
169
|
+
the app facade, not the internal module-scoped key used by `requires` and factory contexts.
|
|
170
|
+
|
|
171
|
+
Generated hosts carry this name on each service definition instead of emitting a separate
|
|
172
|
+
`publicServices` map. Runtime name resolution and collision checks are shared with manual
|
|
173
|
+
composition. Existing public mappings and `discoverPublicServices` remain compatible.
|
|
174
|
+
Generated and manual plugin types infer inline names, including dotted namespaces.
|