@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.
Files changed (45) hide show
  1. package/README.md +137 -337
  2. package/discovery/generate.mjs +2 -8
  3. package/dist/actions/action-list.d.ts +1 -1
  4. package/dist/actions/action-list.js +53 -4
  5. package/dist/actions/action.d.ts +3 -3
  6. package/dist/actions/types.d.ts +4 -0
  7. package/dist/app/access.js +2 -1
  8. package/dist/app/service-aliases.d.ts +4 -0
  9. package/dist/app/service-aliases.js +14 -0
  10. package/dist/app/types.d.ts +12 -1
  11. package/dist/auth-navigation.d.ts +13 -0
  12. package/dist/auth-navigation.js +33 -0
  13. package/dist/contracts.d.ts +5 -0
  14. package/dist/contributions/command.js +9 -0
  15. package/dist/contributions/index.d.ts +1 -0
  16. package/dist/core.d.ts +4 -0
  17. package/dist/core.js +2 -0
  18. package/dist/definitions.d.ts +30 -4
  19. package/dist/discovered.d.ts +9 -5
  20. package/dist/discovered.js +3 -2
  21. package/dist/events/action-setup.d.ts +19 -0
  22. package/dist/events/action-setup.js +24 -0
  23. package/dist/events/service.d.ts +18 -0
  24. package/dist/events/service.js +98 -0
  25. package/dist/events/types.d.ts +19 -0
  26. package/dist/events/types.js +1 -0
  27. package/dist/replacements.d.ts +1 -1
  28. package/dist/runtime.d.ts +2 -0
  29. package/dist/runtime.js +18 -2
  30. package/dist/service-key.d.ts +6 -0
  31. package/dist/service-key.js +0 -1
  32. package/dist/services.d.ts +2 -1
  33. package/dist/services.js +5 -1
  34. package/docs/auth.md +106 -0
  35. package/docs/events.md +157 -0
  36. package/docs/file-contributions.md +13 -0
  37. package/docs/reference.md +404 -0
  38. package/docs/todo-tutorial.md +88 -0
  39. package/examples/todos/actions/create.mjs +7 -0
  40. package/examples/todos/actions/delete.mjs +14 -0
  41. package/examples/todos/actions/list.mjs +7 -0
  42. package/examples/todos/plugin.mjs +11 -0
  43. package/examples/todos/services/tasks.mjs +30 -0
  44. package/examples/todos.mjs +17 -0
  45. package/package.json +4 -2
@@ -13,6 +13,23 @@ export function createActionList(initialActions = [], options = {}) {
13
13
  const store = createStore(() => ({ actions: Object.create(null) }));
14
14
  const lifecycle = new ExecutionLifecycle();
15
15
  const owners = new Map();
16
+ const disposal = new Map();
17
+ function release(owner) {
18
+ const cleanups = disposal.get(owner);
19
+ disposal.delete(owner);
20
+ const errors = [];
21
+ for (const cleanup of [...(cleanups ?? [])].reverse()) {
22
+ try {
23
+ cleanup();
24
+ }
25
+ catch (error) {
26
+ errors.push(error);
27
+ }
28
+ }
29
+ cleanups?.clear();
30
+ if (errors.length)
31
+ throw new AggregateError(errors, 'Action cleanup failed.');
32
+ }
16
33
  const placements = new Map();
17
34
  let disposed = false;
18
35
  const bindings = new InstanceBindings(environment);
@@ -143,7 +160,18 @@ export function createActionList(initialActions = [], options = {}) {
143
160
  definitions = { ...definitions, [id]: action };
144
161
  publish(id);
145
162
  return {
146
- update: (patch) => owners.get(id) === owner && update(id, patch),
163
+ get: () => (owners.get(id) === owner && !disposed ? get(id) : undefined),
164
+ onDispose(cleanup) {
165
+ if (owners.get(id) !== owner || disposed) {
166
+ cleanup();
167
+ return;
168
+ }
169
+ let cleanups = disposal.get(owner);
170
+ if (!cleanups)
171
+ disposal.set(owner, (cleanups = new Set()));
172
+ cleanups.add(cleanup);
173
+ },
174
+ update: (patch) => !disposed && owners.get(id) === owner && update(id, patch),
147
175
  unregister() {
148
176
  if (owners.get(id) !== owner)
149
177
  return;
@@ -154,7 +182,12 @@ export function createActionList(initialActions = [], options = {}) {
154
182
  const next = { ...definitions };
155
183
  delete next[id];
156
184
  definitions = next;
157
- publish(id);
185
+ try {
186
+ release(owner);
187
+ }
188
+ finally {
189
+ publish(id);
190
+ }
158
191
  },
159
192
  };
160
193
  }
@@ -168,7 +201,7 @@ export function createActionList(initialActions = [], options = {}) {
168
201
  };
169
202
  const registration = register(definition, placement);
170
203
  return {
171
- update: registration.update,
204
+ ...registration,
172
205
  unregister: bindings.attach(id, action, registration),
173
206
  };
174
207
  }
@@ -177,12 +210,28 @@ export function createActionList(initialActions = [], options = {}) {
177
210
  if (disposed)
178
211
  return;
179
212
  disposed = true;
180
- bindings.dispose();
213
+ const errors = [];
214
+ try {
215
+ bindings.dispose();
216
+ }
217
+ catch (error) {
218
+ errors.push(error);
219
+ }
220
+ for (const owner of [...disposal.keys()]) {
221
+ try {
222
+ release(owner);
223
+ }
224
+ catch (error) {
225
+ errors.push(error);
226
+ }
227
+ }
181
228
  lifecycle.clear();
182
229
  owners.clear();
183
230
  placements.clear();
184
231
  definitions = Object.create(null);
185
232
  store.setState({ actions: Object.create(null) });
233
+ if (errors.length)
234
+ throw new AggregateError(errors, 'Action list cleanup failed.');
186
235
  }
187
236
  for (const action of initialActions)
188
237
  register(action);
@@ -72,17 +72,17 @@ export declare class Action<Input = void, Result = unknown> {
72
72
  get metadata(): unknown;
73
73
  set metadata(value: unknown);
74
74
  snapshot(): {
75
- enabled?: boolean | undefined;
76
- visible?: boolean | undefined;
75
+ icon?: ActionIcon;
77
76
  id?: string | undefined;
78
77
  title: string;
79
78
  description?: string | undefined;
80
79
  tooltip?: string | undefined;
81
80
  shortcut?: ActionShortcut<Input> | undefined;
82
81
  variant?: "default" | "destructive" | undefined;
83
- icon?: ActionIcon;
84
82
  href?: string | undefined;
83
+ enabled?: boolean | undefined;
85
84
  dependsOn?: readonly string[] | undefined;
85
+ visible?: boolean | undefined;
86
86
  checked?: boolean | undefined;
87
87
  value?: Input | undefined;
88
88
  initialState?: object | undefined;
@@ -65,6 +65,10 @@ export interface ActionContext<Input = unknown> {
65
65
  update(patch: ActionPatch): boolean;
66
66
  }
67
67
  export interface ActionRegistration {
68
+ /** Registration-owned cleanup, including external subscriptions. */
69
+ onDispose(cleanup: () => void): void;
70
+ /** Reads only this registration; undefined after removal or replacement. */
71
+ get(): ActionSnapshot | undefined;
68
72
  update(patch: ActionPatch): boolean;
69
73
  /** Idempotent. Cannot remove a newer registration of the same ID. */
70
74
  unregister(): void;
@@ -62,13 +62,14 @@ export function createFoundationApp(runtime) {
62
62
  for (const plugin of runtime.modules) {
63
63
  for (const [name, create] of Object.entries(plugin.appExtensions ?? {})) {
64
64
  if (Object.hasOwn(extensions, name) ||
65
- ['actions', 'config', 'services', 'ready', 'optional'].includes(name))
65
+ ['actions', 'events', 'config', 'services', 'ready', 'optional'].includes(name))
66
66
  throw new Error(`Duplicate app extension "${name}" in plugin "${plugin.id}".`);
67
67
  extensions[name] = create(runtime);
68
68
  }
69
69
  }
70
70
  return Object.freeze({
71
71
  ...extensions,
72
+ events: runtime.events,
72
73
  actions: createActionAccess(runtime.actions),
73
74
  get config() {
74
75
  return Object.freeze(Object.fromEntries(runtime.modules.map((module) => [
@@ -0,0 +1,4 @@
1
+ import type { Plugin } from '../definitions.js';
2
+ import type { PublicServiceKeys } from './types.js';
3
+ /** Resolves names onto existing container keys; this does not create or store service instances. */
4
+ export declare function serviceAliases(module: Pick<Plugin, 'id' | 'services' | 'publicServices'>): PublicServiceKeys;
@@ -0,0 +1,14 @@
1
+ import { serviceKey } from '../service-key.js';
2
+ /** Resolves names onto existing container keys; this does not create or store service instances. */
3
+ export function serviceAliases(module) {
4
+ const aliases = Object.assign(Object.create(null), module.publicServices);
5
+ for (const service of module.services ?? []) {
6
+ if (service.exposeAs === undefined)
7
+ continue;
8
+ const name = service.exposeAs;
9
+ if (Object.hasOwn(aliases, name) && aliases[name] !== service.id)
10
+ throw new Error(`Duplicate public service "${name}" in plugin "${module.id}".`);
11
+ aliases[name] = serviceKey(service.id);
12
+ }
13
+ return aliases;
14
+ }
@@ -10,11 +10,21 @@ export interface PublicServiceMap {
10
10
  /** Optional packages contribute their own typed facades without Core depending on them. */
11
11
  export interface AppExtensionMap {
12
12
  }
13
- type Published<P> = P extends {
13
+ type PublishedKeys<P> = P extends {
14
14
  publicServices: infer Keys extends PublicServiceKeys;
15
15
  } ? {
16
16
  readonly [K in keyof Keys]: Keys[K] extends ServiceKey<infer T> ? T : never;
17
17
  } : {};
18
+ type PublishedDefinition<D> = D extends {
19
+ exposeAs: infer Name extends string;
20
+ create: (...args: any[]) => infer T;
21
+ } ? {
22
+ readonly [K in Name]: T;
23
+ } : {};
24
+ type PublishedDefinitions<P> = P extends {
25
+ services: readonly (infer D)[];
26
+ } ? Intersection<PublishedDefinition<D>> : {};
27
+ type Published<P> = P extends unknown ? PublishedKeys<P> & PublishedDefinitions<P> : never;
18
28
  type Intersection<U> = (U extends unknown ? (value: U) => void : never) extends (value: infer I) => void ? I : never;
19
29
  export type PublicServicesOf<Plugins extends readonly Plugin[]> = [Plugins[number]] extends [never] ? {} : Intersection<Published<Plugins[number]>>;
20
30
  /** Service reads resolve the current runtime container; they never copy or own service state. */
@@ -34,6 +44,7 @@ export type FoundationActions = Namespace<{
34
44
  [K in KnownActionId]: ActionReference<K>;
35
45
  }>;
36
46
  export interface FoundationApp<Public extends object = PublicServiceMap> extends AppExtensionMap {
47
+ readonly events: import('../events/types.js').Events;
37
48
  readonly actions: FoundationActions;
38
49
  readonly config: Namespace<Immutable<ConfigMap>>;
39
50
  readonly services: Namespace<Public>;
@@ -0,0 +1,13 @@
1
+ /** Application-owned destinations, independent of provider SDKs and routers. */
2
+ export type AuthPaths = Readonly<{
3
+ signIn: string;
4
+ afterSignIn: string;
5
+ afterSignOut: string;
6
+ }>;
7
+ export type AuthSignInOptions = {
8
+ returnTo?: string;
9
+ };
10
+ export declare function configureAuthPaths(paths: AuthPaths): AuthPaths;
11
+ /** Reject external return URLs and login loops; the configured fallback is authoritative. */
12
+ export declare function resolveAuthReturnTo(paths: AuthPaths, returnTo?: string): string;
13
+ export declare function authSignInHref(paths: AuthPaths, returnTo?: string): string;
@@ -0,0 +1,33 @@
1
+ import { safeHref } from './actions/navigation.js';
2
+ function internalPath(value) {
3
+ if (!value?.startsWith('/') || value.startsWith('//') || !safeHref(value))
4
+ return undefined;
5
+ // URL normalization must not turn a root-relative path into a protocol-relative target.
6
+ if (new URL(value, 'https://foundation.invalid').pathname.startsWith('//'))
7
+ return undefined;
8
+ return value;
9
+ }
10
+ export function configureAuthPaths(paths) {
11
+ for (const value of [paths.signIn, paths.afterSignIn, paths.afterSignOut]) {
12
+ if (!internalPath(value))
13
+ throw new Error('Auth paths must be safe root-relative application URLs.');
14
+ }
15
+ if (pathname(paths.signIn) === pathname(paths.afterSignIn)) {
16
+ throw new Error('The post-login destination must differ from the login page.');
17
+ }
18
+ return Object.freeze({ ...paths });
19
+ }
20
+ function pathname(value) {
21
+ return new URL(value, 'https://foundation.invalid').pathname.replace(/\/+$/, '') || '/';
22
+ }
23
+ /** Reject external return URLs and login loops; the configured fallback is authoritative. */
24
+ export function resolveAuthReturnTo(paths, returnTo) {
25
+ configureAuthPaths(paths);
26
+ const target = internalPath(returnTo);
27
+ return target && pathname(target) !== pathname(paths.signIn) ? target : paths.afterSignIn;
28
+ }
29
+ export function authSignInHref(paths, returnTo) {
30
+ const url = new URL(paths.signIn, 'https://foundation.invalid');
31
+ url.searchParams.set('returnTo', resolveAuthReturnTo(paths, returnTo));
32
+ return `${url.pathname}${url.search}${url.hash}`;
33
+ }
@@ -1,3 +1,4 @@
1
+ import type { AuthPaths, AuthSignInOptions } from './auth-navigation.js';
1
2
  import type { Translator } from './definitions.js';
2
3
  export type AuthSnapshot = {
3
4
  user: {
@@ -9,6 +10,10 @@ export type AuthSnapshot = {
9
10
  error: unknown;
10
11
  };
11
12
  export interface AuthService {
13
+ /** Optional application-owned navigation configuration. */
14
+ readonly paths?: AuthPaths;
15
+ /** Optional SDK-native login flow; UI otherwise navigates to paths.signIn. */
16
+ signIn?(options?: AuthSignInOptions): Promise<void>;
12
17
  getSnapshot(): AuthSnapshot;
13
18
  subscribe(listener: () => void): () => void;
14
19
  signOut(): Promise<void>;
@@ -7,6 +7,15 @@ export function adaptCommand(resolved, host, config) {
7
7
  const execute = definition.execute;
8
8
  return {
9
9
  definition,
10
+ setup: definition.setup || definition.onEvent
11
+ ? (context) => {
12
+ if (definition.onEvent && definition.events?.length) {
13
+ const onEvent = definition.onEvent;
14
+ context.events.watch(definition.events, (event, { signal }) => onEvent(event, { ...context, signal }));
15
+ }
16
+ return definition.setup?.(context);
17
+ }
18
+ : undefined,
10
19
  requires: definition.requires ?? [],
11
20
  watch: definition.watch ?? [],
12
21
  registrations: [
@@ -16,6 +16,7 @@ export type Registration = {
16
16
  });
17
17
  /** The normalized shape every contribution kind reduces to. */
18
18
  export type Adapted = {
19
+ setup?: import('../events/action-setup.js').ActionSetup;
19
20
  /** Final definition after conventions and overrides; the runtime re-translates from it. */
20
21
  definition: ResolvedContribution;
21
22
  requires: readonly string[];
package/dist/core.d.ts CHANGED
@@ -19,3 +19,7 @@ export * from './discovered.js';
19
19
  export type { PresentationTypes, PresentationType } from './presentation.js';
20
20
  export type { ActionInstance, StatefulDefinition, StatefulBuilder, } from './contributions/stateful-action.js';
21
21
  export { defineServiceInterceptor, type ServiceInterceptor } from './interceptors/service.js';
22
+ export type * from './events/types.js';
23
+ export type { ActionSetup, ActionSetupContext, SetupAction } from './events/action-setup.js';
24
+ export { EventService } from './events/service.js';
25
+ export { configureAuthPaths, resolveAuthReturnTo, authSignInHref, type AuthPaths, type AuthSignInOptions } from './auth-navigation.js';
package/dist/core.js CHANGED
@@ -16,3 +16,5 @@ export { pluginMetadata } from './metadata.js';
16
16
  export { ConfigService, ConfigScope, defineConfig, } from './config-service.js';
17
17
  export * from './discovered.js';
18
18
  export { defineServiceInterceptor } from './interceptors/service.js';
19
+ export { EventService } from './events/service.js';
20
+ export { configureAuthPaths, resolveAuthReturnTo, authSignInHref } from './auth-navigation.js';
@@ -1,3 +1,5 @@
1
+ import type { Events, EventErrorHandler, FoundationEvent } from './events/types.js';
2
+ import type { ActionSetup, ActionSetupContext } from './events/action-setup.js';
1
3
  import type { ServiceInterceptor } from './interceptors/service.js';
2
4
  import { type StatefulBuilder } from './contributions/stateful-action.js';
3
5
  import type { ConfigContext, ConfigValues, ConfigDefinition } from './config-service.js';
@@ -19,13 +21,28 @@ export type Translator = ((key: string, values?: MessageValues) => string) & {
19
21
  };
20
22
  export interface ServiceDefinition<T = unknown> {
21
23
  id: string;
24
+ /** Optional name for this same instance in app.services. Discovery defaults to the file path. */
25
+ exposeAs?: string;
22
26
  requires?: readonly string[];
23
27
  create(context: {
24
28
  services: Services;
25
29
  config: ConfigContext;
30
+ events: Events;
26
31
  }): T;
27
32
  dispose?: (instance: T) => void;
28
33
  }
34
+ export declare function defineService<const ID extends string, T, const Name extends string>(definition: ServiceDefinition<T> & {
35
+ id: ID;
36
+ exposeAs: Name;
37
+ }): ServiceDefinition<T> & {
38
+ id: ID;
39
+ exposeAs: Name;
40
+ };
41
+ export declare function defineService<T, const Name extends string>(definition: Omit<ServiceDefinition<T>, 'id'> & {
42
+ exposeAs: Name;
43
+ }): Omit<ServiceDefinition<T>, 'id'> & {
44
+ exposeAs: Name;
45
+ };
29
46
  export declare function defineService<const ID extends string, T>(definition: ServiceDefinition<T> & {
30
47
  id: ID;
31
48
  }): ServiceDefinition<T> & {
@@ -165,9 +182,16 @@ export type NativeDefinition = ActionConventions & {
165
182
  export declare function defineURLAction<const Id extends string = string, const Replaces extends string = string>(definition: Omit<ActionConventions, 'id' | 'replaces'> & Identity<Id, Replaces> & {
166
183
  href: string;
167
184
  }): NativeDefinition & Identity<Id, Replaces>;
168
- export type PlainDefinition<Input = unknown, Result = unknown> = Omit<ActionConventions, 'shortcut'> & Omit<ActionDefinition, 'id' | 'title' | 'groups' | 'execute' | 'resolve' | 'shortcut'> & {
185
+ export type PlainDefinition<Input = unknown, Result = unknown, Name extends string = string> = Omit<ActionConventions, 'shortcut'> & Omit<ActionDefinition, 'id' | 'title' | 'groups' | 'execute' | 'resolve' | 'shortcut'> & {
169
186
  shortcut?: ActionShortcut<NoInfer<Input>>;
170
187
  kind: 'action';
188
+ /** Runs once per registration; events.watch subscriptions are automatically owned. */
189
+ setup?: ActionSetup;
190
+ /** Named custom events delivered to onEvent; independent of observable-service watch. */
191
+ events?: readonly Name[];
192
+ onEvent?(event: FoundationEvent<NoInfer<Name>>, context: ActionSetupContext & {
193
+ signal: AbortSignal;
194
+ }): void | Promise<void>;
171
195
  requires?: readonly string[];
172
196
  /** Observable services that invalidate presentation; subscribed once per runtime. */
173
197
  watch?: readonly string[];
@@ -196,11 +220,11 @@ export type PlainDefinition<Input = unknown, Result = unknown> = Omit<ActionConv
196
220
  * parameter, or pass both arguments explicitly: `defineAction<MemberContext, void>({...})`.
197
221
  */
198
222
  export declare function defineAction<Input>(): StatefulBuilder<Input>;
199
- export declare function defineAction<Input = unknown, Result = void, const Id extends string = string, const Replaces extends string = string>(definition: Omit<PlainDefinition<Input, Result>, 'kind' | 'id' | 'replaces'> & Identity<Id, Replaces> & {
223
+ export declare function defineAction<Input = unknown, Result = void, const Id extends string = string, const Replaces extends string = string, const Name extends string = string>(definition: Omit<PlainDefinition<Input, Result, Name>, 'kind' | 'id' | 'replaces'> & Identity<Id, Replaces> & {
200
224
  unavailable?: {
201
225
  messageKey: string;
202
226
  };
203
- }): PlainDefinition<Input, Result> & Identity<Id, Replaces>;
227
+ }): PlainDefinition<Input, Result, Name> & Identity<Id, Replaces>;
204
228
  export type Contribution = FormDefinition<any, any> | DialogDefinition<any> | NativeDefinition | PlainDefinition<any, any> | ActionExport;
205
229
  export type ResolvedContribution = Exclude<Contribution, ActionExport> & {
206
230
  id: string;
@@ -287,7 +311,7 @@ export type PluginPageDefinition = {
287
311
  };
288
312
  export declare function definePage(page: PluginPageDefinition): PluginPageDefinition;
289
313
  export type Plugin = {
290
- /** Public app aliases for existing typed service keys; internal services remain private. */
314
+ /** Aliases for externally supplied services or existing compositions. Prefer service.exposeAs. */
291
315
  publicServices?: PublicServiceKeys;
292
316
  /** Instance-local projections owned by optional packages; never a second state store. */
293
317
  appExtensions?: Readonly<Record<string, (runtime: import('./runtime.js').FoundationRuntime) => unknown>>;
@@ -309,6 +333,8 @@ export type Plugin = {
309
333
  };
310
334
  export declare function definePlugin<const T extends Plugin>(plugin: T): T;
311
335
  export type FoundationConfig = {
336
+ /** Receives synchronous throws and async rejections from event handlers. */
337
+ onEventError?: EventErrorHandler;
312
338
  publicServices?: PublicServiceKeys;
313
339
  /** Instance-local projections owned by optional packages; never a second state store. */
314
340
  appExtensions?: Readonly<Record<string, (runtime: import('./runtime.js').FoundationRuntime) => unknown>>;
@@ -9,7 +9,7 @@ export type DiscoveredFile<T = unknown, P extends string = string> = {
9
9
  export declare function discoveredFile<T, const P extends string>(value: T, path: P, source: string): DiscoveredFile<T, P>;
10
10
  export declare function discoverActions(files: readonly DiscoveredFile[], moduleId?: string, conventions?: boolean): Contribution[];
11
11
  export declare function discoverServices(files: readonly DiscoveredFile[], moduleId?: string): ServiceDefinition[];
12
- /** Public names follow explicit IDs or local file paths; storage IDs retain their module scope. */
12
+ /** Compatibility projection. New generated hosts carry names directly on discovered services. */
13
13
  export declare function discoverPublicServices(files: readonly DiscoveredFile[], moduleId?: string): PublicServiceKeys;
14
14
  export declare function discoverInterceptors(files: readonly DiscoveredFile[]): InterceptorEntry[];
15
15
  /** File assembly rejects overlapping leaves; intentional overrides happen later in ConfigService. */
@@ -26,17 +26,21 @@ type ActionTree<T, P extends string> = T extends (...args: any[]) => any ? {} :
26
26
  [K in keyof T & string]: ActionTree<T[K], Join<P, K>>;
27
27
  }[keyof T & string]> : {};
28
28
  export type DiscoveredActionEntry<F, Module extends string = '', Conventions extends boolean = true> = F extends DiscoveredFile<infer T, infer P> ? ActionTree<T, Conventions extends false ? never : Join<Module, P>> : {};
29
- type ServiceTree<T, P extends string> = T extends {
29
+ type ServiceTree<T, P extends string, Public extends boolean = false> = T extends {
30
30
  create: (...args: any[]) => infer R;
31
31
  } ? {
32
- [K in T extends {
32
+ [K in Public extends true ? T extends {
33
+ exposeAs: infer Name extends string;
34
+ } ? Name : T extends {
35
+ id: infer ID extends string;
36
+ } ? ID : P : T extends {
33
37
  id: infer ID extends string;
34
38
  } ? ID : P]: R;
35
39
  } : T extends object ? UnionToIntersection<{
36
- [K in keyof T & string]: ServiceTree<T[K], Join<P, K>>;
40
+ [K in keyof T & string]: ServiceTree<T[K], Join<P, K>, Public>;
37
41
  }[keyof T & string]> : {};
38
42
  export type DiscoveredServiceEntry<F, Module extends string = ''> = F extends DiscoveredFile<infer T, infer P> ? ServiceTree<T, Join<Module, P>> : {};
39
- export type DiscoveredPublicServiceEntry<F> = DiscoveredServiceEntry<F>;
43
+ export type DiscoveredPublicServiceEntry<F> = F extends DiscoveredFile<infer T, infer P> ? ServiceTree<T, P, true> : {};
40
44
  type ConfigOutput<T> = T extends ConfigDefinition<infer V> ? V : T extends readonly unknown[] ? T : T extends object ? {
41
45
  [K in keyof T]: ConfigOutput<T[K]>;
42
46
  } : T;
@@ -48,14 +48,15 @@ export function discoverServices(files, moduleId = '') {
48
48
  return expand(files, (value) => !!value && typeof value.create === 'function').map(({ value, path }) => ({
49
49
  ...value,
50
50
  id: value.id ?? [moduleId, ...path].filter(Boolean).join('.'),
51
+ exposeAs: value.exposeAs ?? value.id ?? path.join('.'),
51
52
  }));
52
53
  }
53
- /** Public names follow explicit IDs or local file paths; storage IDs retain their module scope. */
54
+ /** Compatibility projection. New generated hosts carry names directly on discovered services. */
54
55
  export function discoverPublicServices(files, moduleId = '') {
55
56
  const aliases = Object.create(null);
56
57
  const sources = new Map();
57
58
  for (const { value, path, source } of expand(files, (value) => !!value && typeof value.create === 'function')) {
58
- const name = value.id ?? path.join('.');
59
+ const name = value.exposeAs ?? value.id ?? path.join('.');
59
60
  if (sources.has(name))
60
61
  throw new Error(`Duplicate public service "${name}": ${sources.get(name)} and ${source}`);
61
62
  sources.set(name, source);
@@ -0,0 +1,19 @@
1
+ import type { ActionRegistration, ActionPresentation } from '../actions/types.js';
2
+ import type { FoundationApp } from '../app/types.js';
3
+ import type { ConfigContext } from '../config-service.js';
4
+ import type { Services } from '../definitions.js';
5
+ import type { Events } from './types.js';
6
+ /** Presentation writes use the existing ActionList store and registration identity guards. */
7
+ export type SetupAction = ActionPresentation & {
8
+ get: ActionRegistration['get'];
9
+ update: ActionRegistration['update'];
10
+ };
11
+ export type ActionSetupContext = {
12
+ events: Events;
13
+ services: Services;
14
+ action: SetupAction;
15
+ app: FoundationApp;
16
+ config: ConfigContext;
17
+ };
18
+ export type ActionSetup = (context: ActionSetupContext) => void | (() => void);
19
+ export declare function setupAction(handle: ActionRegistration): SetupAction;
@@ -0,0 +1,24 @@
1
+ export function setupAction(handle) {
2
+ const action = { get: handle.get, update: handle.update };
3
+ const keys = [
4
+ 'enabled',
5
+ 'visible',
6
+ 'checked',
7
+ 'title',
8
+ 'description',
9
+ 'tooltip',
10
+ 'icon',
11
+ 'href',
12
+ 'value',
13
+ 'variant',
14
+ ];
15
+ for (const key of keys)
16
+ Object.defineProperty(action, key, {
17
+ enumerable: true,
18
+ get: () => handle.get()?.[key],
19
+ set: (value) => {
20
+ handle.update({ [key]: value });
21
+ },
22
+ });
23
+ return Object.freeze(action);
24
+ }
@@ -0,0 +1,18 @@
1
+ import type { Events, EventErrorHandler } from './types.js';
2
+ /** One bus per runtime. Mitt owns dispatch; Foundation owns lifetimes and error reporting. */
3
+ export declare class EventService implements Events {
4
+ private onError;
5
+ private bus;
6
+ private subscriptions;
7
+ constructor(onError?: EventErrorHandler);
8
+ emit: Events['emit'];
9
+ watch: Events['watch'];
10
+ /** Diagnostics for lifecycle tests; counts watch calls, not individual event names. */
11
+ get subscriptionCount(): number;
12
+ clear(): void;
13
+ }
14
+ /** A scoped view shares the bus and releases callback references on disposal. */
15
+ export declare function createEventScope(events: Events): {
16
+ events: Events;
17
+ dispose(): void;
18
+ };
@@ -0,0 +1,98 @@
1
+ import mitt from 'mitt';
2
+ /** One bus per runtime. Mitt owns dispatch; Foundation owns lifetimes and error reporting. */
3
+ export class EventService {
4
+ onError;
5
+ bus = mitt();
6
+ subscriptions = new Set();
7
+ constructor(onError = (error, event) => {
8
+ console.error(`Event handler failed for "${event.type}".`, error);
9
+ }) {
10
+ this.onError = onError;
11
+ }
12
+ emit = (type, ...payload) => {
13
+ this.bus.emit(`event:${type}`, Object.freeze({ type, data: payload[0] }));
14
+ };
15
+ watch = (names, handler) => {
16
+ const controller = new AbortController();
17
+ const keys = [...new Set(typeof names === 'string' ? [names] : names)];
18
+ // Prefix keys to keep mitt's wildcard private; event names are always literal.
19
+ const invoke = (event) => {
20
+ if (controller.signal.aborted)
21
+ return;
22
+ const report = (error) => {
23
+ try {
24
+ this.onError(error, event);
25
+ }
26
+ catch (reportError) {
27
+ console.error('Event error reporter failed.', reportError);
28
+ }
29
+ };
30
+ try {
31
+ const result = handler(event, { signal: controller.signal });
32
+ if (result)
33
+ void Promise.resolve(result).catch(report);
34
+ }
35
+ catch (error) {
36
+ report(error);
37
+ }
38
+ };
39
+ for (const key of keys)
40
+ this.bus.on(`event:${key}`, invoke);
41
+ const unsubscribe = () => {
42
+ if (controller.signal.aborted)
43
+ return;
44
+ for (const key of keys) {
45
+ const name = `event:${key}`;
46
+ this.bus.off(name, invoke);
47
+ if (!this.bus.all.get(name)?.length)
48
+ this.bus.all.delete(name);
49
+ }
50
+ this.subscriptions.delete(unsubscribe);
51
+ controller.abort();
52
+ };
53
+ this.subscriptions.add(unsubscribe);
54
+ return unsubscribe;
55
+ };
56
+ /** Diagnostics for lifecycle tests; counts watch calls, not individual event names. */
57
+ get subscriptionCount() {
58
+ return this.subscriptions.size;
59
+ }
60
+ clear() {
61
+ for (const unsubscribe of [...this.subscriptions])
62
+ unsubscribe();
63
+ this.bus.all.clear();
64
+ }
65
+ }
66
+ /** A scoped view shares the bus and releases callback references on disposal. */
67
+ export function createEventScope(events) {
68
+ let active = true;
69
+ const cleanups = new Set();
70
+ const scoped = {
71
+ emit: (name, ...data) => {
72
+ if (active)
73
+ events.emit(name, ...data);
74
+ },
75
+ watch: (names, handler) => {
76
+ if (!active)
77
+ throw new Error('Event scope is no longer active.');
78
+ const unsubscribe = events.watch(names, handler);
79
+ const release = () => {
80
+ cleanups.delete(release);
81
+ unsubscribe();
82
+ };
83
+ cleanups.add(release);
84
+ return release;
85
+ },
86
+ };
87
+ return {
88
+ events: scoped,
89
+ dispose() {
90
+ if (!active)
91
+ return;
92
+ active = false;
93
+ for (const release of [...cleanups])
94
+ release();
95
+ cleanups.clear();
96
+ },
97
+ };
98
+ }
@@ -0,0 +1,19 @@
1
+ /** Extend this interface with application event names and payloads. */
2
+ export interface EventMap {
3
+ }
4
+ export type EventName = Extract<keyof EventMap, string> | (string & {});
5
+ export type EventData<Name extends string> = Name extends keyof EventMap ? EventMap[Name] : unknown;
6
+ export type FoundationEvent<Name extends string = string> = Name extends string ? Readonly<{
7
+ type: Name;
8
+ data: EventData<Name>;
9
+ }> : never;
10
+ export type EventHandler<Name extends string = string> = (event: FoundationEvent<Name>, context: {
11
+ signal: AbortSignal;
12
+ }) => void | Promise<void>;
13
+ export type EventErrorHandler = (error: unknown, event: FoundationEvent) => void;
14
+ export interface Events {
15
+ /** Each matching event invokes the handler once. Returns an optional early unsubscribe. */
16
+ watch<const Name extends EventName>(names: Name | readonly Name[], handler: EventHandler<Name>): () => void;
17
+ /** Synchronous delivery; promises are observed for errors, not awaited. */
18
+ emit<Name extends EventName>(name: Name, ...data: undefined extends EventData<Name> ? [data?: EventData<Name>] : [data: EventData<Name>]): void;
19
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -2,7 +2,7 @@ import type { Contribution, Plugin } from './definitions.js';
2
2
  /** Replace only a named plugin contribution, retaining its public ID and placements. */
3
3
  export declare function applyActionReplacements(plugins: readonly Plugin[], appActions: readonly Contribution[]): {
4
4
  plugins: {
5
- actions: (import("./definitions.js").FormDefinition<any, any> | import("./definitions.js").DialogDefinition<any> | import("./definitions.js").NativeDefinition | import("./definitions.js").PlainDefinition<any, any> | (new (context: import("./definitions.js").ActionEnvironment) => import("./core.js").Action<any, any>) | ((context: import("./definitions.js").ActionEnvironment) => import("./core.js").Action<any, any>))[];
5
+ actions: (import("./definitions.js").FormDefinition<any, any> | import("./definitions.js").DialogDefinition<any> | import("./definitions.js").NativeDefinition | import("./definitions.js").PlainDefinition<any, any, string> | (new (context: import("./definitions.js").ActionEnvironment) => import("./core.js").Action<any, any>) | ((context: import("./definitions.js").ActionEnvironment) => import("./core.js").Action<any, any>))[];
6
6
  publicServices?: import("./core.js").PublicServiceKeys;
7
7
  appExtensions?: Readonly<Record<string, (runtime: import("./runtime.js").FoundationRuntime) => unknown>>;
8
8
  config?: import("./config-service.js").ConfigValues | import("./config-service.js").ConfigDefinition;