@bitakit/core 0.2.8 → 0.3.0

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 (40) hide show
  1. package/AGENTS.md +42 -0
  2. package/dist/actions/action-list.d.ts +3 -2
  3. package/dist/actions/action-list.js +5 -0
  4. package/dist/actions/dependencies.js +4 -1
  5. package/dist/actions/execution.js +1 -0
  6. package/dist/actions/types.d.ts +7 -2
  7. package/dist/app/access.js +3 -2
  8. package/dist/app/action-access.js +2 -0
  9. package/dist/config-service.js +11 -3
  10. package/dist/configuration.js +3 -2
  11. package/dist/core.d.ts +4 -1
  12. package/dist/core.js +2 -0
  13. package/dist/definitions.d.ts +10 -0
  14. package/dist/discovered.d.ts +11 -0
  15. package/dist/discovered.js +29 -5
  16. package/dist/events/service.d.ts +2 -0
  17. package/dist/events/service.js +44 -9
  18. package/dist/events/types.d.ts +10 -6
  19. package/dist/interceptors/define.d.ts +6 -1
  20. package/dist/interceptors/define.js +7 -3
  21. package/dist/interceptors/service-observers.d.ts +1 -1
  22. package/dist/interceptors/service-observers.js +9 -2
  23. package/dist/lifecycle/controller.js +8 -7
  24. package/dist/lifecycle/reconcile.js +3 -2
  25. package/dist/name-resolution.d.ts +11 -0
  26. package/dist/name-resolution.js +24 -0
  27. package/dist/names.d.ts +4 -0
  28. package/dist/permissions.d.ts +103 -0
  29. package/dist/permissions.js +172 -0
  30. package/dist/runtime.js +68 -8
  31. package/dist/service-key.js +7 -1
  32. package/dist/service-names.js +6 -5
  33. package/dist/settings/access.js +5 -3
  34. package/dist/settings/define.d.ts +2 -1
  35. package/dist/settings/store.js +3 -2
  36. package/dist/slots/define.d.ts +2 -1
  37. package/dist/slots/runtime.js +4 -2
  38. package/dist/slots/select.js +4 -1
  39. package/dist/slots/types.d.ts +12 -10
  40. package/package.json +3 -3
package/AGENTS.md CHANGED
@@ -16,11 +16,31 @@ rarely call the runtime directly: files in `src/plugins/<id>/` are discovered, a
16
16
  | `actions/<name>.ts` | `defineAction({ title, enabled, execute, ... })` | `<plugin>.<name>` |
17
17
  | `events.ts` | `defineEvents({ changed: event<T>() })` | `<plugin>.changed` |
18
18
  | `settings.ts` | `defineSettings({ name: setting({ default }) }, page)` | `<plugin>.<name>` |
19
+ | `permissions.ts` | `definePermissions({ content: ['read', 'edit'] })` | `<resource>` |
19
20
  | `slots/<name>.ts` | `defineSlot({ accepts, policy?, payload? })` | `<plugin>.<name>` |
20
21
  | `interceptors/<name>.ts` | `defineInterceptor({ action or service, before, after })` | — |
21
22
  | `configs/<name>.ts` | `defineConfig({ defaults, schema? })` | `<plugin>.<name>` |
22
23
  | `setup.ts` | `Setup` function (`scope.slots.attach`, cleanup) | — |
23
24
 
25
+ The app declares its base roles once in `src/roles.ts` with `defineRoles({ ... }, { customRoles })`.
26
+
27
+ ## Roles and permissions
28
+
29
+ - Core holds only the vocabulary: `definePermissions`, `defineRoles`, the composed catalog and
30
+ its checks. It stores nothing and authorizes nothing; the authorization provider (for example
31
+ the Better Auth adapter) translates the declarations and decides every check on the server.
32
+ - A plugin declares the resources and operations it owns, never roles. One resource has one
33
+ owning plugin.
34
+ - Only the app declares base roles (`src/roles.ts`): `standard` extends the provider's built-in
35
+ `owner`, `admin` or `member`; `label` and `description` are defaults that translations
36
+ override; `grants` lists operations from the catalog (typed by `bitakit generate`). Declaration
37
+ order is display order, never a permission hierarchy.
38
+ - `bitakit generate` writes `bitakit.gen.access.ts` with the composed `accessConfiguration`
39
+ (server-safe data) for authorization adapters.
40
+ - Conflicts fail before the app runs, at generation and again at startup: a resource claimed
41
+ twice, a grant of an unknown resource or operation, a standard role extended twice, roles in a
42
+ plugin. Nothing is resolved by registration order or merging.
43
+
24
44
  ## Slots and replaceable parts
25
45
 
26
46
  - `policy: 'list'` (default): every contribution renders. `'keyed'`: outlets pick one by key.
@@ -45,6 +65,28 @@ one plugin under Node (no browser); `plugin.execute(id, input)` resolves to the
45
65
  - Only the declaring plugin emits its events; others listen.
46
66
  - `enabled`, `visible` and interceptors are client rules; authorize on the server.
47
67
 
68
+ ## Identifier compatibility and integration contexts
69
+
70
+ Registered spellings and exact matches remain authoritative, including existing case-only
71
+ names. Service/contract lookup, declared events, Actions, plugin references and dependencies
72
+ also accept an unambiguous case-insensitive match. An ambiguous non-exact reference throws;
73
+ use an existing exact spelling. Generated map keys and namespace property types preserve
74
+ original spellings. String-based Action/event/service hooks resolve mixed case with payload
75
+ checking. Undeclared event strings retain their existing open-bus semantics; declare events
76
+ for a typed, resolvable public name. Filesystem paths, URLs and service method names are unchanged.
77
+
78
+ Optional integrations reuse `expandContributions` for folder/dotted/record declarations.
79
+ `ContributionInstallerContext` describes the full contributing owner context (config, events and
80
+ settings) supplied by the runtime. Installer callbacks retain `ContributionContext`, where these
81
+ fields are optional for legacy direct invocations. Installed cleanup
82
+ belongs to the contributor. Do not introduce a parallel context, registry or event bus.
83
+
84
+ Service interceptors receive `callId` and epoch `startedAt`, plus `durationMs` on completion or
85
+ failure (optional in the types for legacy manually constructed calls). Async settlement is observed without replacing the original promise or awaiting the
86
+ observer. These IDs are local to one runtime. Trusted observers may see arguments/results;
87
+ public inventory does not. Self-calls still bypass the service proxy; a producer that promises
88
+ observable execution must enter its public method through the service container.
89
+
48
90
  ## Plugin identity and inspection
49
91
 
50
92
  Discovery records provenance on definitions. `withPluginOrigin(plugin, record)` is the trusted
@@ -1,7 +1,8 @@
1
+ import type { CheckedName } from '../names.js';
1
2
  import { ActionStatus } from './state.js';
2
3
  import { type RegistrationOptions } from './groups.js';
3
4
  import { Action } from './action.js';
4
- import type { ActionDefinition, ActionSnapshot, ActionPatch, ActionRegistration, ActionId, ActionInput, ActionResult, ExecutionResult } from './types.js';
5
+ import type { ActionDefinition, ActionSnapshot, ActionPatch, ActionRegistration, KnownActionId, ActionInput, ActionResult, ExecutionResult } from './types.js';
5
6
  type State = {
6
7
  actions: Readonly<Record<string, ActionSnapshot>>;
7
8
  };
@@ -61,7 +62,7 @@ export declare function createActionList(initialActions?: readonly (ActionDefini
61
62
  attach(id: string, group: import("./groups.js").ActionGroup): () => void;
62
63
  update: (id: string, patch: ActionPatch) => boolean;
63
64
  /** Known IDs from ActionMap type their input and result; other IDs stay untyped. */
64
- execute: <Id extends ActionId>(id: Id, input?: ActionInput<Id>) => Promise<ExecutionResult<ActionResult<Id>>>;
65
+ execute: <Id extends string>(id: Id & CheckedName<Id, KnownActionId>, input?: ActionInput<Id>) => Promise<ExecutionResult<ActionResult<Id>>>;
65
66
  dispose: () => void;
66
67
  mount: (navigate?: (href: string) => void) => () => void;
67
68
  /** Read-only subscription surface; mutation stays in the methods above. */
@@ -1,3 +1,4 @@
1
+ import { resolveName } from '../name-resolution.js';
1
2
  import { ActionStatus } from './state.js';
2
3
  import { freezeGroups } from './groups.js';
3
4
  import { ExecutionLifecycle } from './interceptors.js';
@@ -107,10 +108,12 @@ export function createActionList(initialActions = [], options = {}) {
107
108
  publish(id);
108
109
  }
109
110
  const get = (id) => {
111
+ id = resolveName(id, Object.keys(definitions));
110
112
  const { actions } = store.getState();
111
113
  return Object.hasOwn(actions, id) ? actions[id] : undefined;
112
114
  };
113
115
  function resolve(id, input) {
116
+ id = resolveName(id, Object.keys(definitions));
114
117
  const action = source(id);
115
118
  if (!action)
116
119
  return undefined;
@@ -133,6 +136,7 @@ export function createActionList(initialActions = [], options = {}) {
133
136
  return Object.freeze({ ...resolved, ...options.project?.(resolved) });
134
137
  }
135
138
  function update(id, patch) {
139
+ id = resolveName(id, Object.keys(definitions));
136
140
  const current = source(id);
137
141
  if (!current || disposed)
138
142
  return false;
@@ -292,6 +296,7 @@ export function createActionList(initialActions = [], options = {}) {
292
296
  register,
293
297
  /** Attach an existing action without duplicating it; cleanup owns only this placement. */
294
298
  attach(id, group) {
299
+ id = resolveName(id, Object.keys(definitions));
295
300
  const action = get(id);
296
301
  const owner = owners.get(id);
297
302
  if (!action || !owner)
@@ -1,8 +1,10 @@
1
+ import { resolveName } from '../name-resolution.js';
1
2
  export function freezeDependencies(ids) {
2
3
  return ids ? Object.freeze([...new Set(ids)]) : undefined;
3
4
  }
4
5
  /** Missing nodes and cycles fail closed. No dependency handler is executed. */
5
6
  export function dependencyEnabled(id, actions, enabled, visiting = new Set(), cache = new Map()) {
7
+ id = resolveName(id, Object.keys(actions));
6
8
  if (cache.has(id))
7
9
  return cache.get(id);
8
10
  if (!Object.hasOwn(actions, id) || visiting.has(id))
@@ -20,7 +22,8 @@ export function affectedActions(actions, changed) {
20
22
  const affected = new Set([changed]);
21
23
  const dependents = new Map();
22
24
  for (const action of Object.values(actions)) {
23
- for (const id of action.dependsOn ?? []) {
25
+ for (const reference of action.dependsOn ?? []) {
26
+ const id = resolveName(reference, Object.keys(actions));
24
27
  const items = dependents.get(id) ?? [];
25
28
  items.push(action.id);
26
29
  dependents.set(id, items);
@@ -10,6 +10,7 @@ const keyOf = (action, input) => action.concurrency !== 'per-input'
10
10
  : String(input);
11
11
  export function createExecutor(setPending, owners, environment, get, resolve, update, lifecycle, running) {
12
12
  return async function execute(id, input) {
13
+ id = get(id)?.id ?? id;
13
14
  const owner = owners.get(id);
14
15
  const controller = new AbortController();
15
16
  const context = Object.freeze({
@@ -1,3 +1,4 @@
1
+ import type { NamedValue } from '../name-resolution.js';
1
2
  import type { ActionStatus } from './state.js';
2
3
  import type { PresentationType } from '../presentation.js';
3
4
  import type { RegistrationOptions } from './groups.js';
@@ -105,7 +106,11 @@ export type ActionId = ActionMapOptions extends {
105
106
  } ? KnownActionId : KnownActionId | (string & {});
106
107
  export type ActionInput<Id extends string = string> = Id extends KnownActionId ? ActionMap[Id] extends {
107
108
  input: infer Input;
108
- } ? Input : unknown : unknown;
109
+ } ? Input : unknown : NamedValue<ActionMap, Id> extends {
110
+ input: infer Input;
111
+ } ? Input : unknown;
109
112
  export type ActionResult<Id extends string = string> = Id extends KnownActionId ? ActionMap[Id] extends {
110
113
  result: infer Result;
111
- } ? Result : unknown : unknown;
114
+ } ? Result : unknown : NamedValue<ActionMap, Id> extends {
115
+ result: infer Result;
116
+ } ? Result : unknown;
@@ -1,3 +1,4 @@
1
+ import { namedRecord } from '../name-resolution.js';
1
2
  import { BitaKitServiceError } from './service-error.js';
2
3
  import { createActionAccess } from './action-access.js';
3
4
  /** Projects the runtime onto the app facade. Nothing is copied; every read is live. */
@@ -33,10 +34,10 @@ export function createBitaKitApp(runtime) {
33
34
  events: Object.freeze({ on: runtime.events.on.bind(runtime.events) }),
34
35
  actions: createActionAccess(runtime.actions),
35
36
  get config() {
36
- return Object.freeze(Object.fromEntries(runtime.modules.map((module) => [
37
+ return Object.freeze(namedRecord(Object.fromEntries(runtime.modules.map((module) => [
37
38
  module.id,
38
39
  runtime.configuration.plugin(module.id).snapshot(),
39
- ])));
40
+ ]))));
40
41
  },
41
42
  services,
42
43
  settings: runtime.settingsAccess,
@@ -1,8 +1,10 @@
1
+ import { resolveName } from '../name-resolution.js';
1
2
  import { createActionReference } from '../actions/reference.js';
2
3
  /** Projects dotted IDs onto stable handles; enumeration reads only current public registrations. */
3
4
  export function createActionAccess(list) {
4
5
  const references = new Map();
5
6
  const at = (path) => {
7
+ path = resolveName(path, Object.keys(list.getState().actions).flatMap((id) => id.split('.').map((_, index, parts) => parts.slice(0, index + 1).join('.'))));
6
8
  const cached = references.get(path);
7
9
  if (cached)
8
10
  return cached;
@@ -1,3 +1,4 @@
1
+ import { resolveName } from './name-resolution.js';
1
2
  const configDefinition = Symbol.for('bitakit.core.config');
2
3
  export function defineConfig(value) {
3
4
  if (!value || typeof value !== 'object' || (!('defaults' in value) && !('schema' in value)))
@@ -71,13 +72,20 @@ export class ConfigScope {
71
72
  export class ConfigService {
72
73
  modules = new Map();
73
74
  constructor(modules, overrides = {}) {
75
+ const resolvedOverrides = Object.create(null);
76
+ for (const [id, value] of Object.entries(overrides)) {
77
+ const resolved = resolveName(id, modules.map((module) => module.id));
78
+ if (Object.hasOwn(resolvedOverrides, resolved))
79
+ throw new Error(`Duplicate config override for "${resolved}".`);
80
+ resolvedOverrides[resolved] = value;
81
+ }
74
82
  for (const module of modules) {
75
83
  if (this.modules.has(module.id))
76
84
  throw new Error(`Duplicate config module "${module.id}".`);
77
- this.modules.set(module.id, new ConfigScope(resolve(module.config ?? {}, overrides[module.id])));
85
+ this.modules.set(module.id, new ConfigScope(resolve(module.config ?? {}, resolvedOverrides[module.id])));
78
86
  }
79
87
  for (const id of Object.keys(overrides))
80
- if (!this.modules.has(id))
88
+ if (!this.modules.has(resolveName(id, this.modules.keys())))
81
89
  throw new Error(`configOverrides names "${id}", but no plugin with that ID is enabled. Known: ${[...this.modules.keys()].join(', ')}.`);
82
90
  }
83
91
  /** Adopt prevalidated module scopes without replacing the public configuration service. */
@@ -87,7 +95,7 @@ export class ConfigService {
87
95
  this.modules.set(id, scope);
88
96
  }
89
97
  plugin(id) {
90
- const scope = this.modules.get(id);
98
+ const scope = this.modules.get(resolveName(id, this.modules.keys()));
91
99
  if (!scope)
92
100
  throw new Error(`Unknown config module "${id}".`);
93
101
  return scope;
@@ -1,3 +1,4 @@
1
+ import { resolveName } from './name-resolution.js';
1
2
  import { preservePluginOrigin } from './inspection/plugin-origin.js';
2
3
  const providersOf = (plugin) => plugin.ui?.providers ?? [];
3
4
  /** Undefined inherits. An explicit list replaces that domain, including an empty list. */
@@ -19,7 +20,7 @@ export function resolveBitaKitConfig(discovered, overrides = {}) {
19
20
  .filter((plugin) => !selectedPlugins.some((selected) => selected.id === plugin.id))
20
21
  .map((plugin) => plugin.id));
21
22
  if (config.configOverrides)
22
- config.configOverrides = Object.fromEntries(Object.entries(config.configOverrides).filter(([id]) => !removed.has(id)));
23
+ config.configOverrides = Object.fromEntries(Object.entries(config.configOverrides).filter(([id]) => !removed.has(resolveName(id, (discovered.plugins ?? []).map((plugin) => plugin.id)))));
23
24
  const pluginIds = new Set();
24
25
  for (const plugin of config.plugins ?? []) {
25
26
  if (!plugin.id || pluginIds.has(plugin.id))
@@ -35,7 +36,7 @@ export function resolveBitaKitConfig(discovered, overrides = {}) {
35
36
  if (!provider.id || seen.has(provider.id))
36
37
  throw new Error(`Invalid or duplicate provider "${provider.id}".`);
37
38
  for (const id of provider.requires ?? []) {
38
- if (!seen.has(id))
39
+ if (!seen.has(resolveName(id, providers.map((provider) => provider.id))))
39
40
  throw new Error(`Provider "${provider.id}" requires "${id}" before it.`);
40
41
  }
41
42
  seen.add(provider.id);
package/dist/core.d.ts CHANGED
@@ -3,8 +3,10 @@ export type * from './definitions.js';
3
3
  export { defineEvents, event, isEventsDefinition } from './events/define.js';
4
4
  export type { EventsDefinition, EventSpec, EventsOf, CancelableOf } from './events/define.js';
5
5
  export type * from './events/types.js';
6
- export type { GeneratedName } from './names.js';
6
+ export type { GeneratedName, CheckedName } from './names.js';
7
7
  export { EventService } from './events/service.js';
8
+ export { definePermissions, defineRoles, isPermissionsDefinition, isRolesDefinition, standardRoles, composePermissions, composeAccessConfiguration, roleProblems, AccessConfigurationError, } from './permissions.js';
9
+ export type { PermissionMap, RoleMap, PermissionSpec, PermissionsDefinition, StandardRole, RoleSpec, RolesOptions, RolesDefinition, PermissionResource, PermissionCatalog, AccessConfiguration, PermissionsOf, RoleIdsOf, } from './permissions.js';
8
10
  export { defineSettings, setting, isSettingsDefinition, isSettingSpec, parseSetting, } from './settings/define.js';
9
11
  export type { SettingSpec, SettingScope, SettingControl, SettingOption, SettingsDefinition, SettingsSectionOptions, SettingsMap, SettingKey, SettingValue, SettingsOf, } from './settings/define.js';
10
12
  export { SettingsStore, type SettingState, type SaveResult, type SettingsIdentity, type SettingEntry, } from './settings/store.js';
@@ -49,3 +51,4 @@ export { configureAuthPaths, resolveAuthReturnTo, authSignInHref, type AuthPaths
49
51
  export type { PluginUpdateResult, PluginChangeResult, PluginDependentOptions, PluginChangeOptions, PluginToggleRequest, PluginReplacementRequest, PluginChangePreview, PluginChangeReason, } from './lifecycle/reconcile.js';
50
52
  export { createInventory, inspectRuntime, observeRuntimeInventory, inventoryMetadata, } from './inspection/inventory.js';
51
53
  export type { RuntimeInventory, InventoryPlugin, InventoryDeclaration, InventoryMetadata, InventoryKind, InventoryLive, } from './inspection/inventory.js';
54
+ export { resolveName, namedRecord, type NameKey, type NamedValue } from './name-resolution.js';
package/dist/core.js CHANGED
@@ -1,6 +1,7 @@
1
1
  export { defineService, defineAction, definePlugin, dialogOf, isActionSpec, isServiceDefinition, } from './definitions.js';
2
2
  export { defineEvents, event, isEventsDefinition } from './events/define.js';
3
3
  export { EventService } from './events/service.js';
4
+ export { definePermissions, defineRoles, isPermissionsDefinition, isRolesDefinition, standardRoles, composePermissions, composeAccessConfiguration, roleProblems, AccessConfigurationError, } from './permissions.js';
4
5
  export { defineSettings, setting, isSettingsDefinition, isSettingSpec, parseSetting, } from './settings/define.js';
5
6
  export { SettingsStore, } from './settings/store.js';
6
7
  export { settingsStorage, settingsOwner, createMemorySettingsStorage, createLocalSettingsStorage, } from './settings/storage.js';
@@ -32,3 +33,4 @@ export { SlotError } from './slots/runtime.js';
32
33
  export { selectSingle, candidateNames } from './slots/select.js';
33
34
  export { configureAuthPaths, resolveAuthReturnTo, authSignInHref, } from './auth-navigation.js';
34
35
  export { createInventory, inspectRuntime, observeRuntimeInventory, inventoryMetadata, } from './inspection/inventory.js';
36
+ export { resolveName, namedRecord } from './name-resolution.js';
@@ -289,7 +289,13 @@ export type ContributionContext = {
289
289
  module: string;
290
290
  app: boolean;
291
291
  services: Services;
292
+ /** Context and event ownership of the contributing plugin, not the installer. */
293
+ config?: ConfigContext;
294
+ events?: Events;
295
+ settings?: SettingsAccess;
292
296
  };
297
+ /** Runtime installers always receive the full owner context; legacy manual contexts remain valid. */
298
+ export type ContributionInstallerContext = ContributionContext & Pick<ServiceContext, 'config' | 'events' | 'settings'>;
293
299
  export type ContributionInstaller<T = unknown> = (values: readonly T[], context: ContributionContext) => void | Cleanup;
294
300
  export type ContributionInstallers = {
295
301
  readonly [K in keyof ContributionMap]?: ContributionInstaller<ContributionMap[K]>;
@@ -313,6 +319,8 @@ export type Plugin = {
313
319
  slots?: SlotDefinitions | readonly SlotDefinition[];
314
320
  events?: EventsDefinition<any>;
315
321
  settings?: SettingsDefinition<any>;
322
+ /** Resources and operations this module owns (`permissions.ts`); never roles. */
323
+ permissions?: import('./permissions.js').PermissionsDefinition;
316
324
  config?: ConfigValues | ConfigDefinition;
317
325
  interceptors?: readonly InterceptorSpec[];
318
326
  setup?: Setup;
@@ -325,6 +333,8 @@ export type Plugin = {
325
333
  export declare function definePlugin<const T extends Plugin>(plugin: T): T;
326
334
  export type BitaKitRuntimeConfig = Omit<Plugin, 'id' | 'dependencies' | 'parent'> & {
327
335
  appId?: string;
336
+ /** The app's base roles (`src/roles.ts`); only the app declares roles. */
337
+ roles?: import('./permissions.js').RolesDefinition;
328
338
  dependencies?: readonly string[];
329
339
  /** Receives synchronous throws and async rejections from event handlers. */
330
340
  onEventError?: import('./events/types.js').EventErrorHandler;
@@ -1,5 +1,6 @@
1
1
  import { type Contribution, type ServiceDefinition, type ActionEntry } from './definitions.js';
2
2
  import { type ResolvedSlotDefinition, type SlotEntry } from './slots/define.js';
3
+ import { type PermissionsDefinition, type RolesDefinition } from './permissions.js';
3
4
  import type { ContractName } from './service-key.js';
4
5
  import { type InterceptorSpec } from './interceptors/define.js';
5
6
  import { type CancelableOf, type EventsDefinition, type EventsOf } from './events/define.js';
@@ -11,6 +12,12 @@ export type DiscoveredFile<T = unknown, P extends string = string> = {
11
12
  source: string;
12
13
  };
13
14
  export declare function discoveredFile<T, const P extends string>(value: T, path: P, source: string): DiscoveredFile<T, P>;
15
+ /** Expands folder/dotted/record contributions for optional integration normalizers. */
16
+ export declare function expandContributions(files: readonly DiscoveredFile[], leaf: (value: any) => boolean, arrays?: boolean, failure?: (message: string, _source: string) => Error): {
17
+ value: any;
18
+ path: string[];
19
+ source: string;
20
+ }[];
14
21
  export declare function discoverActions(files: readonly DiscoveredFile[], moduleId?: string): Contribution[];
15
22
  export declare function discoverServices(files: readonly DiscoveredFile[], moduleId?: string): ServiceDefinition[];
16
23
  /** Slot leaves use the same record/path expansion as Actions and services. Explicit IDs are absolute. */
@@ -20,6 +27,10 @@ export declare function discoverInterceptors(files: readonly DiscoveredFile[]):
20
27
  export declare function discoverEvents(files: readonly DiscoveredFile[]): EventsDefinition | undefined;
21
28
  /** The one `settings.ts` of a module. */
22
29
  export declare function discoverSettings(files: readonly DiscoveredFile[]): SettingsDefinition | undefined;
30
+ /** A module's `permissions.ts`: one file, `definePermissions({ ... })`; the source is kept for diagnostics. */
31
+ export declare function discoverPermissions(files: readonly DiscoveredFile[]): PermissionsDefinition | undefined;
32
+ /** The app's `roles.ts`: one file, `defineRoles({ ... })`; the source is kept for diagnostics. */
33
+ export declare function discoverRoles(files: readonly DiscoveredFile[]): RolesDefinition | undefined;
23
34
  /** File assembly rejects overlapping leaves; intentional overrides happen later in ConfigService. */
24
35
  export declare function discoverConfig(files: readonly DiscoveredFile[]): ConfigValues | ConfigDefinition;
25
36
  type Join<A extends string, B extends string> = A extends '' ? B : B extends '' ? A : `${A}.${B}`;
@@ -4,6 +4,7 @@ import { resolveContribution } from './conventions.js';
4
4
  import { actionIdPattern } from './conventions.js';
5
5
  import { isSlotDefinition } from './slots/define.js';
6
6
  import { BitaKitStartupError } from './startup-error.js';
7
+ import { isPermissionsDefinition, isRolesDefinition, } from './permissions.js';
7
8
  import { defineInterceptor } from './interceptors/define.js';
8
9
  import { isEventsDefinition, } from './events/define.js';
9
10
  import { isConfigDefinition, isConfigObject, } from './config-service.js';
@@ -11,7 +12,8 @@ import { isSettingsDefinition, } from './settings/define.js';
11
12
  export function discoveredFile(value, path, source) {
12
13
  return { value, path, source };
13
14
  }
14
- function expand(files, leaf, arrays = false, failure = (message, _source) => new Error(message)) {
15
+ /** Expands folder/dotted/record contributions for optional integration normalizers. */
16
+ export function expandContributions(files, leaf, arrays = false, failure = (message, _source) => new Error(message)) {
15
17
  const results = [];
16
18
  const seen = new Map();
17
19
  function visit(value, segments, source) {
@@ -46,7 +48,7 @@ const isActionLike = (value) => isActionSpec(value) ||
46
48
  !('create' in value) &&
47
49
  !('kind' in value));
48
50
  export function discoverActions(files, moduleId = '') {
49
- return expand(files, isActionLike).map(({ value, path, source }) => {
51
+ return expandContributions(files, isActionLike).map(({ value, path, source }) => {
50
52
  const spec = isActionSpec(value) ? value : defineAction(value);
51
53
  const resolved = resolveContribution(spec, [moduleId, ...path].filter(Boolean).join('.'));
52
54
  setContributionPath(resolved, path, source);
@@ -55,7 +57,7 @@ export function discoverActions(files, moduleId = '') {
55
57
  }
56
58
  const isServiceLike = (value) => isServiceDefinition(value) || typeof value === 'function';
57
59
  export function discoverServices(files, moduleId = '') {
58
- return expand(files, isServiceLike).map(({ value, path, source }) => {
60
+ return expandContributions(files, isServiceLike).map(({ value, path, source }) => {
59
61
  const service = isServiceDefinition(value)
60
62
  ? value
61
63
  : defineService(value);
@@ -70,7 +72,7 @@ export function discoverServices(files, moduleId = '') {
70
72
  /** Slot leaves use the same record/path expansion as Actions and services. Explicit IDs are absolute. */
71
73
  export function discoverSlots(files, moduleId = '') {
72
74
  const seen = new Map();
73
- return expand(files, isSlotDefinition, false, (message, source) => new BitaKitStartupError(message, moduleId || 'app', { source, app: !moduleId })).map(({ value, path, source }) => {
75
+ return expandContributions(files, isSlotDefinition, false, (message, source) => new BitaKitStartupError(message, moduleId || 'app', { source, app: !moduleId })).map(({ value, path, source }) => {
74
76
  const id = value.id ?? [moduleId, ...path].filter(Boolean).join('.');
75
77
  if (typeof id !== 'string' || !actionIdPattern.test(id))
76
78
  throw new BitaKitStartupError(`Invalid slot ID "${id}" in ${source}.`, moduleId || 'app', {
@@ -86,7 +88,7 @@ export function discoverSlots(files, moduleId = '') {
86
88
  });
87
89
  }
88
90
  export function discoverInterceptors(files) {
89
- return expand(files, (value) => typeof value === 'function' ||
91
+ return expandContributions(files, (value) => typeof value === 'function' ||
90
92
  (!!value &&
91
93
  typeof value === 'object' &&
92
94
  !Array.isArray(value) &&
@@ -125,6 +127,28 @@ export function discoverSettings(files) {
125
127
  throw new Error(`${file.source} must default-export defineSettings({ ... }).`);
126
128
  return file.value;
127
129
  }
130
+ /** A module's `permissions.ts`: one file, `definePermissions({ ... })`; the source is kept for diagnostics. */
131
+ export function discoverPermissions(files) {
132
+ if (!files.length)
133
+ return undefined;
134
+ if (files.length > 1)
135
+ throw new Error(`A module declares its permissions in one file: ${files.map((file) => file.source).join(', ')}`);
136
+ const [file] = files;
137
+ if (!isPermissionsDefinition(file.value))
138
+ throw new Error(`${file.source} must default-export definePermissions({ ... }).`);
139
+ return Object.freeze({ ...file.value, source: file.source });
140
+ }
141
+ /** The app's `roles.ts`: one file, `defineRoles({ ... })`; the source is kept for diagnostics. */
142
+ export function discoverRoles(files) {
143
+ if (!files.length)
144
+ return undefined;
145
+ if (files.length > 1)
146
+ throw new Error(`The app declares its roles in one file: ${files.map((file) => file.source).join(', ')}`);
147
+ const [file] = files;
148
+ if (!isRolesDefinition(file.value))
149
+ throw new Error(`${file.source} must default-export defineRoles({ ... }).`);
150
+ return Object.freeze({ ...file.value, source: file.source });
151
+ }
128
152
  /** File assembly rejects overlapping leaves; intentional overrides happen later in ConfigService. */
129
153
  export function discoverConfig(files) {
130
154
  const schemaRoot = files.find((file) => !file.path && isConfigDefinition(file.value));
@@ -13,6 +13,7 @@ export declare class EventService implements Events {
13
13
  private observers;
14
14
  private declared;
15
15
  private reserved;
16
+ private reservedEvents;
16
17
  constructor(onError?: EventErrorHandler);
17
18
  /** Registers a plugin's `events.ts`; its names live under `<plugin>.`. */
18
19
  declare(plugin: string, definition: EventsDefinition): void;
@@ -20,6 +21,7 @@ export declare class EventService implements Events {
20
21
  undeclare(plugin: string): void;
21
22
  /** The plugin that declared the namespace of an event name, if any. */
22
23
  ownerOf(name: string): string | undefined;
24
+ resolve(name: string): string;
23
25
  isCancelable(name: string): boolean;
24
26
  /** Reserves a runtime-owned namespace and returns its private publishing capability. */
25
27
  reserve(namespace: string): (name: string, data: unknown) => void;
@@ -1,3 +1,4 @@
1
+ import { resolveName } from '../name-resolution.js';
1
2
  /**
2
3
  * One bus per runtime. Delivery is synchronous and ordered; async handlers are awaited only
3
4
  * for error reporting, or fully for cancelable events. Declared namespaces belong to the
@@ -11,6 +12,7 @@ export class EventService {
11
12
  observers = new Set();
12
13
  declared = new Map();
13
14
  reserved = new Set();
15
+ reservedEvents = new Set();
14
16
  constructor(onError = (error, event) => {
15
17
  console.error(`Event handler failed for "${event.type}".`, error);
16
18
  }) {
@@ -31,18 +33,30 @@ export class EventService {
31
33
  if (spec.schema)
32
34
  schemas.set(`${plugin}.${name}`, spec.schema);
33
35
  }
34
- this.declared.set(plugin, { plugin, cancelable, schemas });
36
+ this.declared.set(plugin, {
37
+ plugin,
38
+ names: Object.keys(definition.events).map((name) => `${plugin}.${name}`),
39
+ cancelable,
40
+ schemas,
41
+ });
35
42
  }
36
43
  /** Release a stopped owner’s declaration without removing other owners’ listeners. */
37
44
  undeclare(plugin) {
38
- this.declared.delete(plugin);
45
+ this.declared.delete(resolveName(plugin, this.declared.keys()));
39
46
  }
40
47
  /** The plugin that declared the namespace of an event name, if any. */
41
48
  ownerOf(name) {
42
- const prefix = name.split('.')[0];
49
+ const prefix = resolveName(name.split('.')[0], [...this.declared.keys(), ...this.reserved]);
43
50
  return this.declared.has(prefix) ? prefix : undefined;
44
51
  }
52
+ resolve(name) {
53
+ return resolveName(name, [
54
+ ...this.reservedEvents,
55
+ ...[...this.declared.values()].flatMap((entry) => entry.names),
56
+ ]);
57
+ }
45
58
  isCancelable(name) {
59
+ name = this.resolve(name);
46
60
  return this.declared.get(name.split('.')[0])?.cancelable.has(name) ?? false;
47
61
  }
48
62
  /** Reserves a runtime-owned namespace and returns its private publishing capability. */
@@ -53,15 +67,17 @@ export class EventService {
53
67
  return (name, data) => {
54
68
  if (!name.startsWith(`${namespace}.`))
55
69
  throw new Error('Event is outside the reserved namespace.');
70
+ this.reservedEvents.add(name);
56
71
  this.dispatch(name, data);
57
72
  };
58
73
  }
59
74
  emit = ((name, data) => {
60
- if (this.reserved.has(name.split('.')[0]))
75
+ if (this.reserved.has(resolveName(name.split('.')[0], [...this.reserved, ...this.declared.keys()])))
61
76
  throw new Error(`Event "${name}" is emitted only by the runtime.`);
62
77
  return this.dispatch(name, data);
63
78
  });
64
79
  dispatch = (name, data) => {
80
+ name = this.resolve(name);
65
81
  const schema = this.declared.get(name.split('.')[0])?.schemas.get(name);
66
82
  if (this.isCancelable(name)) {
67
83
  // Cancelable emits return a promise, so an invalid payload rejects it instead of throwing.
@@ -130,11 +146,22 @@ export class EventService {
130
146
  return !cancelled;
131
147
  }
132
148
  listenersFor(name) {
133
- const result = [...(this.exact.get(name) ?? [])];
149
+ const result = [];
150
+ const select = (listeners, matches) => {
151
+ try {
152
+ if (matches())
153
+ result.push(...listeners);
154
+ }
155
+ catch (error) {
156
+ this.report(error, Object.freeze({ type: name, data: undefined }));
157
+ }
158
+ };
159
+ for (const [requested, listeners] of this.exact)
160
+ select(listeners, () => this.resolve(requested) === name);
161
+ const namespaces = [...this.declared.keys(), ...this.reserved];
134
162
  for (const [prefix, listeners] of this.prefixes)
135
- if (name.startsWith(prefix))
136
- result.push(...listeners);
137
- return result;
163
+ select(listeners, () => name.startsWith(prefix ? `${resolveName(prefix.slice(0, -1), namespaces)}.` : ''));
164
+ return [...new Set(result)];
138
165
  }
139
166
  report(error, event) {
140
167
  try {
@@ -147,6 +174,12 @@ export class EventService {
147
174
  on = ((names, handler) => {
148
175
  const controller = new AbortController();
149
176
  const keys = [...new Set(typeof names === 'string' ? [names] : names)];
177
+ for (const name of keys) {
178
+ if (name.endsWith('.*'))
179
+ resolveName(name.slice(0, -2), [...this.declared.keys(), ...this.reserved]);
180
+ else if (name !== '*')
181
+ this.resolve(name);
182
+ }
150
183
  const invoke = (event) => {
151
184
  if (controller.signal.aborted)
152
185
  return;
@@ -210,7 +243,9 @@ export function createEventScope(events, owner) {
210
243
  if (!active)
211
244
  return undefined;
212
245
  const declaredBy = events.ownerOf(name);
213
- if (owner !== undefined && declaredBy !== undefined && declaredBy !== owner)
246
+ if (owner !== undefined &&
247
+ declaredBy !== undefined &&
248
+ declaredBy !== (events.ownerOf(`${owner}.__owner`) ?? owner))
214
249
  throw new Error(`"${owner}" cannot emit "${name}": that event belongs to plugin "${declaredBy}". Only the declaring plugin emits its events; listen with events.on instead.`);
215
250
  return events.emit(name, ...data);
216
251
  }),
@@ -1,4 +1,5 @@
1
- import type { GeneratedName } from '../names.js';
1
+ import type { NamedValue, NameKey } from '../name-resolution.js';
2
+ import type { GeneratedName, CheckedName } from '../names.js';
2
3
  /** Event names and payloads. Generated from every plugin's `events.ts`; may also be augmented by hand. */
3
4
  export interface EventMap {
4
5
  }
@@ -11,9 +12,12 @@ export type EventName = GeneratedName<KnownEventName>;
11
12
  type PatternOf<Name extends string> = Name extends `${infer Prefix}.${string}` ? `${Prefix}.*` : never;
12
13
  /** What a listener selects: an event, a `<prefix>.*` pattern of declared events, or `*`. */
13
14
  export type EventSelector = EventName | PatternOf<KnownEventName> | '*';
14
- export type EventData<Name extends string> = Name extends keyof EventMap ? EventMap[Name] : unknown;
15
+ export type EventData<Name extends string> = NamedValue<EventMap, Name>;
15
16
  /** `todos.*` matches every declared `todos.<name>` event. */
16
- export type EventsMatching<Pattern extends string> = Pattern extends `${infer Prefix}.*` ? Extract<keyof EventMap, `${Prefix}.${string}`> extends never ? string : Extract<keyof EventMap, `${Prefix}.${string}`> : Pattern;
17
+ type MatchingPrefix<Prefix extends string> = {
18
+ [K in KnownEventName]: K extends `${infer Owner}.${string}` ? Lowercase<Owner> extends Lowercase<Prefix> ? K : never : never;
19
+ }[KnownEventName];
20
+ export type EventsMatching<Pattern extends string> = Pattern extends unknown ? Pattern extends `${infer Prefix}.*` ? [MatchingPrefix<Prefix>] extends [never] ? string : MatchingPrefix<Prefix> : [NameKey<EventMap, Pattern>] extends [never] ? Pattern : NameKey<EventMap, Pattern> : never;
17
21
  export type BitaKitEvent<Name extends string = string> = Name extends string ? Readonly<{
18
22
  type: Name;
19
23
  data: EventData<Name>;
@@ -25,15 +29,15 @@ export type EventHandler<Name extends string = string> = (event: BitaKitEvent<Ev
25
29
  signal: AbortSignal;
26
30
  }) => void | Promise<void>;
27
31
  export type EventErrorHandler = (error: unknown, event: BitaKitEvent) => void;
28
- export type EmitResult<Name extends string> = Name extends keyof CancelableEventMap ? Promise<boolean> : void;
32
+ export type EmitResult<Name extends string> = [NameKey<CancelableEventMap, Name>] extends [never] ? void : NameKey<CancelableEventMap, Name> extends keyof CancelableEventMap ? Promise<boolean> : void;
29
33
  type EmitArguments<Name extends string> = undefined extends EventData<Name> ? [data?: EventData<Name>] : [data: EventData<Name>];
30
34
  export interface Events {
31
35
  /** Each matching event invokes the handler once. Returns the unsubscribe function. */
32
- on<const Name extends EventSelector>(names: Name | readonly Name[], handler: EventHandler<Name>): () => void;
36
+ on<const Name extends string>(names: (Name & CheckedName<Name, KnownEventName | PatternOf<KnownEventName> | '*'>) | readonly (Name & CheckedName<Name, KnownEventName | PatternOf<KnownEventName> | '*'>)[], handler: EventHandler<Name>): () => void;
33
37
  /**
34
38
  * Synchronous delivery; async handlers are observed for errors, not awaited. A cancelable
35
39
  * event waits for its handlers and resolves to false when one of them cancelled.
36
40
  */
37
- emit<Name extends EventName>(name: Name, ...data: EmitArguments<Name>): EmitResult<Name>;
41
+ emit<Name extends string>(name: Name & CheckedName<Name, KnownEventName>, ...data: EmitArguments<Name>): EmitResult<Name>;
38
42
  }
39
43
  export {};
@@ -38,6 +38,9 @@ export type ServiceCall<Name extends string = string, Key extends string = strin
38
38
  /** The called service's ID; a glob or alias target still reports the actual ID. */
39
39
  readonly service: string;
40
40
  readonly method: Key;
41
+ /** Supplied by runtime observers; optional to preserve manually constructed legacy calls. */
42
+ readonly callId?: number;
43
+ readonly startedAt?: number;
41
44
  readonly args: Readonly<Parameters<MethodOf<Name, Key>>>;
42
45
  };
43
46
  /**
@@ -59,9 +62,11 @@ export type ServiceInterceptorSpec<Name extends string = string, Key extends str
59
62
  order?: number;
60
63
  before?(call: ServiceCall<Name, Key> & ServiceHookContext): void;
61
64
  after?(call: ServiceCall<Name, Key> & ServiceHookContext & {
65
+ readonly durationMs?: number;
62
66
  readonly result: Awaited<ReturnType<MethodOf<Name, Key>>>;
63
67
  }): void;
64
68
  onError?(call: ServiceCall<Name, Key> & ServiceHookContext & {
69
+ readonly durationMs?: number;
65
70
  readonly error: unknown;
66
71
  }): void;
67
72
  };
@@ -81,5 +86,5 @@ export declare function isServiceInterceptor(spec: object): spec is ServiceInter
81
86
  kind: 'interceptor';
82
87
  };
83
88
  /** Glob matching for action IDs and service names: exact, `prefix.*`, or `*`. */
84
- export declare function matchesTarget(target: InterceptorTarget, id: string): boolean;
89
+ export declare function matchesTarget(target: InterceptorTarget, id: string, names?: readonly string[]): boolean;
85
90
  export {};