@bitakit/core 0.2.3 → 0.2.5

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/AGENTS.md ADDED
@@ -0,0 +1,46 @@
1
+ # @bitakit/core — guide for agents
2
+
3
+ > For agents building an app with this package (it ships in `node_modules/@bitakit/core`). To
4
+ > change the package itself, follow the repository's own AGENTS.md instead.
5
+
6
+ The framework-independent runtime: plugins, services, Actions, events, settings, slots,
7
+ interceptors and configuration. It has no React; React bindings are in `@bitakit/ui`. Apps
8
+ rarely call the runtime directly: files in `src/plugins/<id>/` are discovered, and the
9
+ `bitakit-app-development` skill has a recipe for each kind.
10
+
11
+ ## The define helpers (import from `@bitakit/core`)
12
+
13
+ | File (in a plugin) | Helper | ID |
14
+ | ------------------------ | -------------------------------------------------------------- | ------------------ |
15
+ | `services/<name>.ts` | `defineService(({ store, events, settings, onStart }) => ...)` | `<plugin>.<name>` |
16
+ | `actions/<name>.ts` | `defineAction({ title, enabled, execute, ... })` | `<plugin>.<name>` |
17
+ | `events.ts` | `defineEvents({ changed: event<T>() })` | `<plugin>.changed` |
18
+ | `settings.ts` | `defineSettings({ name: setting({ default }) }, page)` | `<plugin>.<name>` |
19
+ | `slots/<name>.ts` | `defineSlot({ accepts, policy?, payload? })` | `<plugin>.<name>` |
20
+ | `interceptors/<name>.ts` | `defineInterceptor({ action, before, after })` | — |
21
+ | `configs/<name>.ts` | `defineConfig({ defaults, schema? })` | `<plugin>.<name>` |
22
+ | `setup.ts` | `Setup` function (`scope.slots.attach`, cleanup) | — |
23
+
24
+ ## Slots and replaceable parts
25
+
26
+ - `policy: 'list'` (default): every contribution renders. `'keyed'`: outlets pick one by key.
27
+ - `policy: 'single'`: a replaceable part. Several plugins may offer a candidate; one renders:
28
+ the app's `choose` entry in `bitakit.config.ts`, else the app's own contribution, else the
29
+ only candidate; a tie renders the owner's default. `selectSingle(candidates, { choice, appId })`
30
+ is the rule, exported for tools.
31
+ - Layout families are `single` slots named `layout.<family>`; screens such as
32
+ `screen.not-found` are `single` slots too.
33
+
34
+ ## Testing
35
+
36
+ `mountPlugin(folder, { plugins, services })` from `@bitakit/core/testing` discovers and starts
37
+ one plugin under Node (no browser); `plugin.execute(id, input)` resolves to the outcome
38
+ (`completed` or `skipped`) and rejects on failure; `plugin.events.recorded` lists emitted events.
39
+
40
+ ## Rules
41
+
42
+ - One `defineAction` shape; state belongs in a service `store()`, replaced with `state.set`.
43
+ - Reading a missing service throws; list other plugins' services in `requires`, or check
44
+ `app.has(name)` for optional ones.
45
+ - Only the declaring plugin emits its events; others listen.
46
+ - `enabled`, `visible` and interceptors are client rules; authorize on the server.
package/dist/core.d.ts CHANGED
@@ -31,7 +31,7 @@ export { resolveContribution, fallbackTitle } from './conventions.js';
31
31
  export { ConfirmationController, type Confirmation } from './confirmation.js';
32
32
  export * from './contracts.js';
33
33
  export { resolveText, createTranslationPlugin } from './translation.js';
34
- export { findPluginPage, validatePluginPages, pluginPage, pluginSlot, pluginProvider, pluginSettingsPage, pluginLayout, } from './pages.js';
34
+ export { findPluginPage, validatePluginPages, pluginPage, pluginSlot, pluginProvider, pluginSettingsPage, pluginLayout, layoutSlots, layoutFamilies, type LayoutSlot, } from './pages.js';
35
35
  export { destinationMetadata, type Destination, type DestinationKind } from './destinations.js';
36
36
  export * from './actions/core.js';
37
37
  export { pluginMetadata } from './metadata.js';
@@ -42,7 +42,8 @@ export type * from './slots/define.js';
42
42
  export type * from './slots/types.js';
43
43
  export type { ActionSlotPlacement } from './slots/action-placement.js';
44
44
  export { SlotError } from './slots/runtime.js';
45
+ export { selectSingle, candidateNames, type SingleSelection } from './slots/select.js';
45
46
  export { configureAuthPaths, resolveAuthReturnTo, authSignInHref, type AuthPaths, type AuthSignInOptions, } from './auth-navigation.js';
46
- export type { PluginUpdateResult, PluginChangeResult, PluginDependentOptions, } from './lifecycle/reconcile.js';
47
+ export type { PluginUpdateResult, PluginChangeResult, PluginDependentOptions, PluginChangeOptions, PluginToggleRequest, PluginChangePreview, PluginChangeReason, } from './lifecycle/reconcile.js';
47
48
  export { createInventory, inspectRuntime, observeRuntimeInventory, inventoryMetadata, } from './inspection/inventory.js';
48
49
  export type { RuntimeInventory, InventoryPlugin, InventoryDeclaration, InventoryMetadata, InventoryKind, InventoryLive, } from './inspection/inventory.js';
package/dist/core.js CHANGED
@@ -21,12 +21,13 @@ export { resolveContribution, fallbackTitle } from './conventions.js';
21
21
  export { ConfirmationController } from './confirmation.js';
22
22
  export * from './contracts.js';
23
23
  export { resolveText, createTranslationPlugin } from './translation.js';
24
- export { findPluginPage, validatePluginPages, pluginPage, pluginSlot, pluginProvider, pluginSettingsPage, pluginLayout, } from './pages.js';
24
+ export { findPluginPage, validatePluginPages, pluginPage, pluginSlot, pluginProvider, pluginSettingsPage, pluginLayout, layoutSlots, layoutFamilies, } from './pages.js';
25
25
  export { destinationMetadata } from './destinations.js';
26
26
  export * from './actions/core.js';
27
27
  export { pluginMetadata } from './metadata.js';
28
28
  export * from './discovered.js';
29
29
  export { defineSlot, isSlotDefinition } from './slots/define.js';
30
30
  export { SlotError } from './slots/runtime.js';
31
+ export { selectSingle, candidateNames } from './slots/select.js';
31
32
  export { configureAuthPaths, resolveAuthReturnTo, authSignInHref, } from './auth-navigation.js';
32
33
  export { createInventory, inspectRuntime, observeRuntimeInventory, inventoryMetadata, } from './inspection/inventory.js';
@@ -326,6 +326,11 @@ export type BitaKitRuntimeConfig = Omit<Plugin, 'id' | 'dependencies' | 'parent'
326
326
  enabled?: boolean;
327
327
  visible?: boolean;
328
328
  }>>;
329
+ /**
330
+ * The occupant of each `single` slot the app decides, by slot ID: `<plugin>`, `<plugin>:<key>`
331
+ * or `<key>` of a contribution. From `choose` in bitakit.config.ts; see `selectSingle`.
332
+ */
333
+ choose?: Readonly<Record<string, string>>;
329
334
  plugins?: readonly Plugin[];
330
335
  };
331
336
  /** A literal string wins; a widened `string` or a missing value falls back. */
@@ -7,10 +7,40 @@ export type PluginUpdateResult = Readonly<{
7
7
  affected: readonly string[];
8
8
  reasons: readonly string[];
9
9
  }>;
10
+ /** Host constraints are checked again immediately before a structural update. */
11
+ export type PluginChangeOptions = Readonly<{
12
+ expectedRevision?: number;
13
+ /** Owners that must remain enabled, for example the host's management surface. */
14
+ preserve?: readonly string[];
15
+ }>;
10
16
  /** Explicit host policy when other enabled plugins require the selected owner. */
11
- export type PluginDependentOptions = Readonly<{
17
+ export type PluginDependentOptions = PluginChangeOptions & Readonly<{
18
+ dependents: 'stop' | 'refuse';
19
+ }>;
20
+ export type PluginToggleRequest = PluginChangeOptions & (Readonly<{
21
+ operation: 'enable';
22
+ id: string;
23
+ }> | Readonly<{
24
+ operation: 'disable';
25
+ id: string;
12
26
  dependents: 'stop' | 'refuse';
27
+ }>);
28
+ export type PluginChangeReason = 'busy' | 'cleanup-failed' | 'stale' | 'protected' | 'dependents' | 'owner-disabled' | 'composition' | 'invalid' | 'pending-settings';
29
+ /** Read-only planning result. It grants no authority to execute a stale operation. */
30
+ export type PluginChangePreview = Readonly<{
31
+ status: 'ready' | 'blocked' | 'restart-required';
32
+ revision: number;
33
+ changed: readonly string[];
34
+ affected: readonly string[];
35
+ dependents: readonly string[];
36
+ reason: PluginChangeReason | null;
37
+ blockers: readonly string[];
38
+ reasons: readonly string[];
13
39
  }>;
40
+ export type PlannedPluginChange = {
41
+ preview: PluginChangePreview;
42
+ apply?: () => Promise<PluginUpdateResult>;
43
+ };
14
44
  export type PluginChangeResult = PluginUpdateResult;
15
45
  /** Lifecycle edges include required service aliases, not just explicit plugin dependencies. */
16
46
  export declare function pluginDependencies(modules: readonly NormalizedPlugin[]): Map<string, Set<string>>;
package/dist/pages.d.ts CHANGED
@@ -32,8 +32,32 @@ type Exported<T> = {
32
32
  export declare function pluginPage(module: Exported<unknown>, path: string): PluginPageDefinition;
33
33
  /** A slot view from `ui/slots/<slot>.tsx`. */
34
34
  export declare function pluginSlot(module: Exported<unknown>, slot: string, source?: string): PluginView;
35
- /** A layout from `src/layouts/<name>.tsx`: the default export wraps pages that name it. */
36
- export declare function pluginLayout(module: Exported<unknown>): PresentationType<'component'>;
35
+ /**
36
+ * A layout file, `src/layouts/<family>[/<variant>].tsx` or a plugin's `ui/layouts/...`: a
37
+ * candidate for the `layout.<family>` slot whose key is the variant (`default` for a flat file).
38
+ * Its default export wraps the pages that name the family.
39
+ */
40
+ export declare function pluginLayout(module: Exported<unknown>, family: string, variant?: string, source?: string): PluginView;
41
+ /** The declaration of a layout family: a replaceable component part that wraps pages. */
42
+ export type LayoutSlot = Readonly<{
43
+ kind: 'slot';
44
+ accepts: 'component';
45
+ policy: 'single';
46
+ conflict: 'error';
47
+ }>;
48
+ /** App-owned declarations for layout families that only layout files name (generated by discovery). */
49
+ export declare function layoutSlots(families: readonly string[]): (LayoutSlot & {
50
+ id: string;
51
+ })[];
52
+ /** The layout families pages may name: declared `layout.<family>` slots and legacy app layouts. */
53
+ export declare function layoutFamilies(modules: readonly {
54
+ slots: readonly {
55
+ id: string;
56
+ }[];
57
+ ui?: {
58
+ layouts?: object;
59
+ };
60
+ }[]): ReadonlySet<string>;
37
61
  /** The settings page from `ui/settings/page.tsx`; it replaces the generated page of the plugin. */
38
62
  export declare function pluginSettingsPage(module: Exported<unknown>): PluginSettingsPage;
39
63
  /** A React provider from `ui/providers/<name>.tsx`. */
package/dist/pages.js CHANGED
@@ -2,6 +2,7 @@ import { setContributionSource } from './contribution-origin.js';
2
2
  import { BitaKitStartupError } from './startup-error.js';
3
3
  /** Exact, canonical paths only. Routers remain responsible for dynamic parameters. */
4
4
  export function validatePluginPages(plugins, layouts = new Set()) {
5
+ const known = [...layouts].sort();
5
6
  const owners = new Map();
6
7
  for (const plugin of plugins) {
7
8
  for (const page of plugin.pages ?? []) {
@@ -9,7 +10,7 @@ export function validatePluginPages(plugins, layouts = new Set()) {
9
10
  page.layout !== 'app' &&
10
11
  page.layout !== 'blank' &&
11
12
  !layouts.has(page.layout))
12
- throw new BitaKitStartupError(`Page ${page.path} of plugin "${plugin.id}" names layout "${page.layout}", but src/layouts/${page.layout}.tsx does not exist.${layouts.size ? ` Known layouts: ${[...layouts].join(', ')}.` : ''} Use "app", "blank" or an existing layout.`, plugin.id);
13
+ throw new BitaKitStartupError(`Page ${page.path} of plugin "${plugin.id}" names layout "${page.layout}", but no layout family "${page.layout}" exists. Add src/layouts/${page.layout}.tsx (or src/layouts/${page.layout}/<variant>.tsx), or a plugin's ui/layouts/${page.layout}.tsx.${known.length ? ` Known layouts: ${known.join(', ')}.` : ''} Use "app", "blank" or an existing layout.`, plugin.id);
13
14
  if (!/^\/(?:(?:[a-zA-Z0-9_-]+|\[[a-zA-Z0-9_-]+\])(?:\/(?:[a-zA-Z0-9_-]+|\[[a-zA-Z0-9_-]+\]))*)?$/.test(page.path))
14
15
  throw new BitaKitStartupError(`Invalid plugin page path "${page.path}" in plugin "${plugin.id}". Use a root-relative path such as /todos.`, plugin.id);
15
16
  const owner = owners.get(page.path);
@@ -80,9 +81,42 @@ export function pluginSlot(module, slot, source) {
80
81
  setContributionSource(view, source);
81
82
  return view;
82
83
  }
83
- /** A layout from `src/layouts/<name>.tsx`: the default export wraps pages that name it. */
84
- export function pluginLayout(module) {
85
- return module.default;
84
+ /**
85
+ * A layout file, `src/layouts/<family>[/<variant>].tsx` or a plugin's `ui/layouts/...`: a
86
+ * candidate for the `layout.<family>` slot whose key is the variant (`default` for a flat file).
87
+ * Its default export wraps the pages that name the family.
88
+ */
89
+ export function pluginLayout(module, family, variant = 'default', source) {
90
+ const view = {
91
+ slot: `layout.${family}`,
92
+ key: variant,
93
+ component: module.default,
94
+ };
95
+ if (source)
96
+ setContributionSource(view, source);
97
+ return view;
98
+ }
99
+ /** App-owned declarations for layout families that only layout files name (generated by discovery). */
100
+ export function layoutSlots(families) {
101
+ return families.map((family) => Object.freeze({
102
+ kind: 'slot',
103
+ accepts: 'component',
104
+ policy: 'single',
105
+ conflict: 'error',
106
+ id: `layout.${family}`,
107
+ }));
108
+ }
109
+ /** The layout families pages may name: declared `layout.<family>` slots and legacy app layouts. */
110
+ export function layoutFamilies(modules) {
111
+ const families = new Set();
112
+ for (const module of modules) {
113
+ for (const slot of module.slots)
114
+ if (slot.id.startsWith('layout.'))
115
+ families.add(slot.id.slice('layout.'.length));
116
+ for (const name of Object.keys(module.ui?.layouts ?? {}))
117
+ families.add(name);
118
+ }
119
+ return families;
86
120
  }
87
121
  /** The settings page from `ui/settings/page.tsx`; it replaces the generated page of the plugin. */
88
122
  export function pluginSettingsPage(module) {
package/dist/runtime.d.ts CHANGED
@@ -4,7 +4,7 @@ import type { SlotReader } from './slots/types.js';
4
4
  import { ConfigService } from './config-service.js';
5
5
  import { type Destination } from './destinations.js';
6
6
  import { ActionGroup, type ActionList, type ActionSnapshot } from '@bitakit/core/actions';
7
- import type { ContributionMap, ResolvedContribution, BitaKitRuntimeConfig, Plugin, PluginPageDefinition, PluginView, ProviderDefinition, ServiceDefinition, Services, Translator } from './definitions.js';
7
+ import type { ActionSpec, ContributionMap, ResolvedContribution, BitaKitRuntimeConfig, Plugin, PluginPageDefinition, PluginView, ProviderDefinition, ServiceDefinition, Services, Translator } from './definitions.js';
8
8
  import { SettingsStore } from './settings/store.js';
9
9
  import { type SettingsAccess } from './settings/access.js';
10
10
  import type { BitaKitApp } from './app/types.js';
@@ -12,7 +12,7 @@ import { type Feedback, type MessageValues } from './actions/feedback.js';
12
12
  import { type ContributionHost, type DialogState, type FeedbackOutcome, type OpenableDefinition, type Override } from './contributions/index.js';
13
13
  import type { Confirmation } from './confirmation.js';
14
14
  import { type LifecycleState } from './lifecycle/state.js';
15
- import { type PluginUpdateResult, type PluginDependentOptions } from './lifecycle/reconcile.js';
15
+ import { type PluginUpdateResult, type PluginDependentOptions, type PluginChangeOptions, type PluginToggleRequest, type PluginChangePreview } from './lifecycle/reconcile.js';
16
16
  export type { DialogState } from './contributions/index.js';
17
17
  /** A plugin after normalization: records resolved to arrays with IDs, `ui` merged with the legacy fields. */
18
18
  export type NormalizedPlugin = Omit<Plugin, 'services' | 'actions' | 'slots'> & {
@@ -85,7 +85,7 @@ export declare class BitaKitRuntime implements ContributionHost {
85
85
  affected: readonly string[];
86
86
  reasons: readonly string[];
87
87
  }>>;
88
- enable: (id: string) => Promise<Readonly<{
88
+ enable: (id: string, options?: PluginChangeOptions) => Promise<Readonly<{
89
89
  status: "applied" | "blocked" | "failed" | "restart-required";
90
90
  revision: number;
91
91
  changed: readonly string[];
@@ -99,6 +99,8 @@ export declare class BitaKitRuntime implements ContributionHost {
99
99
  affected: readonly string[];
100
100
  reasons: readonly string[];
101
101
  }>>;
102
+ /** Preview uses the execution planner without stopping owners or changing retained intent. */
103
+ preview: (request: PluginToggleRequest) => PluginChangePreview;
102
104
  }>;
103
105
  private revision;
104
106
  getRevision: () => number;
@@ -204,12 +206,22 @@ export declare class BitaKitRuntime implements ContributionHost {
204
206
  /** Resolves required names to container keys; a missing one is attributed to `module`. */
205
207
  private requireServices;
206
208
  private attribute;
209
+ /**
210
+ * Bind a host-owned defineAction to the existing root scope and adapter. Call only from
211
+ * the host after ready, never from a plugin. The returned cleanup is idempotent; full
212
+ * runtime shutdown also releases it. Host Actions must not await this runtime's stop.
213
+ */
214
+ bindHostAction<Input, Output>(id: string, definition: ActionSpec<Input, Output>): () => void;
215
+ /** Include live host Action requirements in update planning without copying their state. */
216
+ private dependencyModules;
207
217
  /** One path for every action: adapt, check dependencies, register, remember for re-translation. */
208
218
  private install;
209
219
  /** Reconcile subscriptions over the existing container; never mirror service state. */
210
220
  private observe;
211
- /** Plan structural changes before touching scopes; use the existing update exclusion and executor. */
221
+ /** Execute the same plan used by preview; there is no await between validation and exclusion. */
212
222
  private changePlugins;
223
+ /** Validate without starting services, invoking hooks or mutating retained lifecycle intent. */
224
+ private planPluginChange;
213
225
  /** Explicit host update of already-loaded immutable plugin definitions; never installs code. */
214
226
  reconcilePlugins(next: readonly Plugin[]): Promise<PluginUpdateResult>;
215
227
  private stopPlugins;
package/dist/runtime.js CHANGED
@@ -5,7 +5,7 @@ import { ConfigService } from './config-service.js';
5
5
  import { contributionPath, contributionSource, preserveContributionPath, setContributionPath, } from './contribution-origin.js';
6
6
  import { ServiceNames } from './service-names.js';
7
7
  import { BitaKitStartupError, isBitaKitStartupError, moduleLabel } from './startup-error.js';
8
- import { findPluginPage, validatePluginPages } from './pages.js';
8
+ import { findPluginPage, layoutFamilies, validatePluginPages } from './pages.js';
9
9
  import { projectedDestination } from './destinations.js';
10
10
  import { resolveText } from './translation.js';
11
11
  import { ActionGroup, createActionList, } from '@bitakit/core/actions';
@@ -199,8 +199,10 @@ export class BitaKitRuntime {
199
199
  plugins = Object.freeze({
200
200
  add: (plugins) => this.changePlugins('add', [...plugins]),
201
201
  remove: (ids, options) => this.changePlugins('remove', [...ids], options),
202
- enable: (id) => this.changePlugins('enable', [id]),
202
+ enable: (id, options) => this.changePlugins('enable', [id], options),
203
203
  disable: (id, options) => this.changePlugins('disable', [id], options),
204
+ /** Preview uses the execution planner without stopping owners or changing retained intent. */
205
+ preview: (request) => this.planPluginChange(request.operation, [request.id], request).preview,
204
206
  });
205
207
  revision = 0;
206
208
  getRevision = () => this.revision;
@@ -310,7 +312,7 @@ export class BitaKitRuntime {
310
312
  catch (error) {
311
313
  throw attributed(error, this.appId, 'Configuration', this.appId);
312
314
  }
313
- validatePluginPages(this.modules, new Set(Object.keys(this.modules.find((module) => module.id === this.appId)?.ui?.layouts ?? {})));
315
+ validatePluginPages(this.modules, layoutFamilies(this.modules));
314
316
  const groups = config.groups ?? [];
315
317
  const duplicate = groups.find((id, index) => groups.indexOf(id) !== index);
316
318
  if (duplicate)
@@ -974,6 +976,51 @@ export class BitaKitRuntime {
974
976
  const message = error instanceof Error ? error.message : String(error);
975
977
  return new BitaKitStartupError(`${what} in ${moduleLabel(module, this.appId)} failed to start: ${message}${source ? `\nSource: ${source}` : ''}`, module, { cause: error, source, app: module === this.appId });
976
978
  }
979
+ /**
980
+ * Bind a host-owned defineAction to the existing root scope and adapter. Call only from
981
+ * the host after ready, never from a plugin. The returned cleanup is idempotent; full
982
+ * runtime shutdown also releases it. Host Actions must not await this runtime's stop.
983
+ */
984
+ bindHostAction(id, definition) {
985
+ if (!this.isReady() || this.updating || this.stopCompletion)
986
+ throw new Error('Host Actions can only be bound to a ready, idle runtime.');
987
+ const scope = this.scopes.find((entry) => scopeModule(entry).id === this.appId);
988
+ const contribution = resolveContribution(definition, id);
989
+ if (this.actions.get(contribution.id))
990
+ throw new Error(`Action "${contribution.id}" is already registered.`);
991
+ const start = this.registrations.length;
992
+ this.install(scope, contribution, this.appId, this.pluginEvents.get(this.appId).events);
993
+ const owned = this.registrations.slice(start);
994
+ let disposed = false;
995
+ return () => {
996
+ if (disposed)
997
+ return;
998
+ disposed = true;
999
+ for (const entry of owned) {
1000
+ if (!this.registrations.includes(entry))
1001
+ continue;
1002
+ entry.handle.unregister();
1003
+ this.actionConfigs.delete(entry.definition.id);
1004
+ }
1005
+ this.registrations = this.registrations.filter((entry) => !owned.includes(entry));
1006
+ };
1007
+ }
1008
+ /** Include live host Action requirements in update planning without copying their state. */
1009
+ dependencyModules() {
1010
+ return this.modules.map((module) => module.id !== this.appId
1011
+ ? module
1012
+ : {
1013
+ ...module,
1014
+ actions: [
1015
+ ...new Map([
1016
+ ...module.actions.map((action) => [action.id, action]),
1017
+ ...this.registrations
1018
+ .filter(({ definition }) => this.actionConfigs.get(definition.id)?.module === this.appId)
1019
+ .map(({ definition }) => [definition.id, definition]),
1020
+ ]).values(),
1021
+ ],
1022
+ });
1023
+ }
977
1024
  /** One path for every action: adapt, check dependencies, register, remember for re-translation. */
978
1025
  install(scope, contribution, module, events) {
979
1026
  const path = contributionPath(contribution) ?? contribution.id.split('.');
@@ -1043,34 +1090,59 @@ export class BitaKitRuntime {
1043
1090
  if (refresh && observed.size)
1044
1091
  this.actions.refresh();
1045
1092
  }
1046
- /** Plan structural changes before touching scopes; use the existing update exclusion and executor. */
1093
+ /** Execute the same plan used by preview; there is no await between validation and exclusion. */
1047
1094
  changePlugins(operation, values, options) {
1048
- const result = (status, reasons, changed = []) => Promise.resolve(Object.freeze({
1049
- status,
1050
- reasons: Object.freeze(reasons),
1051
- changed: Object.freeze(changed),
1052
- affected: Object.freeze([]),
1053
- revision: this.revision,
1054
- }));
1095
+ const plan = this.planPluginChange(operation, values, options);
1096
+ if (plan.apply)
1097
+ return plan.apply();
1098
+ const { status, revision, changed, affected, reasons } = plan.preview;
1099
+ return Promise.resolve({
1100
+ status: status === 'ready' ? 'applied' : status,
1101
+ revision,
1102
+ changed,
1103
+ affected,
1104
+ reasons,
1105
+ });
1106
+ }
1107
+ /** Validate without starting services, invoking hooks or mutating retained lifecycle intent. */
1108
+ planPluginChange(operation, values, options) {
1109
+ let changed = [];
1110
+ let affected = [];
1111
+ let dependents = [];
1112
+ const result = (status, reasons, reason = status === 'ready' ? null : 'invalid', blockers = []) => ({
1113
+ preview: Object.freeze({
1114
+ status,
1115
+ reason,
1116
+ revision: this.revision,
1117
+ changed: Object.freeze([...changed]),
1118
+ affected: Object.freeze([...affected]),
1119
+ dependents: Object.freeze([...dependents]),
1120
+ blockers: Object.freeze([...blockers]),
1121
+ reasons: Object.freeze(reasons),
1122
+ }),
1123
+ });
1055
1124
  if (this.updating ||
1056
1125
  this.mounting ||
1057
1126
  this.tearingDown ||
1058
1127
  this.stopCompletion ||
1059
1128
  !this.container ||
1060
1129
  this.startPending)
1061
- return result('blocked', ['A lifecycle operation is active or the runtime is not mounted.']);
1130
+ return result('blocked', ['A lifecycle operation is active or the runtime is not mounted.'], 'busy');
1062
1131
  if (this.lifecycle.get().cleanup === 'failed')
1063
- return result('blocked', ['Failed cleanup requires resource recovery and a new runtime.']);
1132
+ return result('blocked', ['Failed cleanup requires resource recovery and a new runtime.'], 'cleanup-failed');
1133
+ if (options?.expectedRevision !== undefined && options.expectedRevision !== this.revision)
1134
+ return result('blocked', ['The composition changed; review the operation again.'], 'stale');
1064
1135
  try {
1136
+ const modules = this.dependencyModules();
1065
1137
  const installed = [...(this.config.plugins ?? [])];
1066
1138
  const disabled = new Set(this.disabledPlugins);
1067
1139
  const ids = operation === 'add'
1068
1140
  ? values.map((plugin) => plugin.id)
1069
- : values;
1141
+ : [...values];
1070
1142
  if (new Set(ids).size !== ids.length)
1071
1143
  return result('blocked', ['Plugin IDs must be unique.']);
1072
1144
  if (ids.includes(this.appId))
1073
- return result('blocked', ['The app module cannot be changed through plugins.']);
1145
+ return result('blocked', ['The app module cannot be changed through plugins.'], 'protected', [this.appId]);
1074
1146
  if ((operation === 'remove' || operation === 'disable') &&
1075
1147
  !['stop', 'refuse'].includes(options?.dependents ?? ''))
1076
1148
  return result('blocked', ['Choose dependents: stop or refuse.']);
@@ -1095,21 +1167,21 @@ export class BitaKitRuntime {
1095
1167
  if (parent && disabled.has(parent) && !ids.includes(parent))
1096
1168
  return result('blocked', [
1097
1169
  `Plugin "${id}" belongs to "${parent}", which is disabled. Enable "${parent}" first.`,
1098
- ]);
1170
+ ], 'owner-disabled', [parent]);
1099
1171
  ids.push(...(cascaded.get(id) ?? []).filter((child) => !ids.includes(child)));
1100
1172
  cascaded.delete(id);
1101
1173
  }
1102
1174
  const activeIds = new Set(this.modules.map((module) => module.id));
1103
- let changed = [...ids];
1175
+ changed = [...ids];
1104
1176
  if (operation === 'disable' || operation === 'remove') {
1105
1177
  const seeds = [...ids, ...owned].filter((id) => activeIds.has(id));
1106
1178
  if (operation === 'remove')
1107
1179
  seeds.push(...this.slotRuntime.contributorsTo(new Set(ids)));
1108
- const closure = updateClosure(this.modules, seeds);
1109
- const dependents = closure.filter((id) => !ids.includes(id) && !owned.includes(id));
1110
- if (dependents.length && options?.dependents === 'refuse')
1111
- return result('blocked', [`Enabled dependents: ${dependents.join(', ')}.`]);
1180
+ const closure = updateClosure(modules, seeds);
1181
+ dependents = closure.filter((id) => !ids.includes(id) && !owned.includes(id));
1112
1182
  changed = [...new Set([...ids, ...owned, ...dependents])];
1183
+ if (dependents.length && options?.dependents === 'refuse')
1184
+ return result('blocked', [`Enabled dependents: ${dependents.join(', ')}.`], 'dependents', dependents);
1113
1185
  if (operation === 'disable') {
1114
1186
  const switchedOff = owned.filter((id) => !disabled.has(id));
1115
1187
  for (const id of ids)
@@ -1134,20 +1206,29 @@ export class BitaKitRuntime {
1134
1206
  disabled.delete(id);
1135
1207
  if (operation === 'disable')
1136
1208
  changed = changed.filter((id) => !this.disabledPlugins.has(id));
1209
+ const protectedOwners = changed.filter((id) => options?.preserve?.includes(id));
1210
+ if ((operation === 'disable' || operation === 'remove') && protectedOwners.length)
1211
+ return result('blocked', ['The host requires these plugins to remain enabled.'], 'protected', protectedOwners);
1137
1212
  if (!changed.length) {
1138
- // An explicit disable of a child its parent already switched off: remember the intent.
1139
- this.disabledWithParent = cascaded;
1140
- return result('applied', []);
1213
+ const plan = result('ready', []);
1214
+ return {
1215
+ ...plan,
1216
+ apply: async () => {
1217
+ // Only execution records an explicit disable of an already-disabled owned child.
1218
+ this.disabledWithParent = cascaded;
1219
+ return { ...plan.preview, status: 'applied' };
1220
+ },
1221
+ };
1141
1222
  }
1142
1223
  const normalized = nextInstalled
1143
1224
  .filter((plugin) => !disabled.has(plugin.id))
1144
1225
  .map((plugin) => normalize(plugin, this.appId));
1145
- const app = this.modules.find((module) => module.id === this.appId);
1226
+ const app = modules.find((module) => module.id === this.appId);
1146
1227
  const all = [app, ...normalized];
1147
1228
  const declarations = [app, ...nextInstalled.map((plugin) => normalize(plugin, this.appId))];
1148
1229
  orderPlugins(all, this.appId);
1149
1230
  validateSlotDeclarations(declarations, this.appId);
1150
- validatePluginPages(all, new Set(Object.keys(app.ui?.layouts ?? {})));
1231
+ validatePluginPages(all, layoutFamilies(all));
1151
1232
  // Failed updates may have already disposed a projection's scope. Recover its recorded
1152
1233
  // failure cohort when the host retries one of those owners, without restarting other failures.
1153
1234
  const lifecycle = this.lifecycle.get();
@@ -1166,12 +1247,12 @@ export class BitaKitRuntime {
1166
1247
  .map((entry) => entry.id),
1167
1248
  ]),
1168
1249
  ];
1169
- const before = updateClosure(this.modules, [
1250
+ const before = updateClosure(modules, [
1170
1251
  ...changed.filter((id) => activeIds.has(id)),
1171
1252
  ...readers,
1172
1253
  ]);
1173
1254
  const after = updateClosure(all, [...changed, ...readers].filter((id) => all.some((module) => module.id === id)));
1174
- const affected = [...new Set([...before, ...after])];
1255
+ affected = [...new Set([...before, ...after])];
1175
1256
  const reasons = [];
1176
1257
  for (const module of [...this.modules, ...all].filter((module) => affected.includes(module.id))) {
1177
1258
  if (module.id === this.appId ||
@@ -1185,7 +1266,7 @@ export class BitaKitRuntime {
1185
1266
  reasons.push(`${module.id}: host identity, translation or storage service requires composition replacement.`);
1186
1267
  }
1187
1268
  if (reasons.length)
1188
- return result('restart-required', [...new Set(reasons)], changed);
1269
+ return result('restart-required', [...new Set(reasons)], 'composition', affected);
1189
1270
  const entries = this.serviceEntries(all);
1190
1271
  const names = new ServiceNames(entries, this.appId);
1191
1272
  for (const module of all)
@@ -1205,7 +1286,7 @@ export class BitaKitRuntime {
1205
1286
  for (const entry of this.settings.entries())
1206
1287
  if (!settings.some((next) => next.key === entry.key) &&
1207
1288
  this.settings.state(entry.key).pending)
1208
- return result('blocked', [`Setting "${entry.key}" has a pending write.`]);
1289
+ return result('blocked', [`Setting "${entry.key}" has a pending write.`], 'pending-settings');
1209
1290
  createSettingsAccess(new SettingsStore(settings, () => this.storage()));
1210
1291
  const overrides = Object.fromEntries(Object.entries(this.config.configOverrides ?? {}).filter(([id]) => declarations.some((module) => module.id === id)));
1211
1292
  const configuration = new ConfigService(declarations, overrides);
@@ -1214,34 +1295,40 @@ export class BitaKitRuntime {
1214
1295
  for (const module of declarations)
1215
1296
  if (module.events)
1216
1297
  eventCheck.declare(module.id, module.events);
1217
- const controller = new AbortController();
1218
- this.updateController = controller;
1219
- this.updating = Promise.resolve().then(() => this.applyPluginUpdate(nextInstalled, normalized, changed, affected, controller, () => {
1220
- // Writes may begin while awaited Action/scope cleanup is in progress.
1221
- for (const entry of this.settings.entries())
1222
- if (!settings.some((next) => next.key === entry.key) &&
1223
- this.settings.state(entry.key).pending)
1224
- return `Setting "${entry.key}" began writing during cleanup; await it before retrying.`;
1225
- this.disabledPlugins = disabled;
1226
- this.disabledWithParent = cascaded;
1227
- this.names.replace(entries);
1228
- this.configuration.replace(configuration);
1229
- for (const plugin of this.config.plugins ?? [])
1230
- this.events.undeclare(plugin.id);
1231
- this.events.undeclare(this.appId);
1232
- for (const module of declarations)
1233
- if (module.events)
1234
- this.events.declare(module.id, module.events);
1235
- this.slotRuntime.replace(declarations.flatMap((module) => module.slots));
1236
- this.settings.replace(settings);
1237
- }, before, after));
1238
- void this.updating
1239
- .finally(() => {
1240
- this.updating = undefined;
1241
- this.updateController = undefined;
1242
- })
1243
- .catch(() => { });
1244
- return this.updating;
1298
+ return {
1299
+ ...result('ready', []),
1300
+ apply: () => {
1301
+ const controller = new AbortController();
1302
+ this.updateController = controller;
1303
+ this.updating = Promise.resolve().then(() => this.applyPluginUpdate(nextInstalled, normalized, changed, affected, controller, () => {
1304
+ // Writes may begin while awaited Action/scope cleanup is in progress.
1305
+ for (const entry of this.settings.entries())
1306
+ if (!settings.some((next) => next.key === entry.key) &&
1307
+ this.settings.state(entry.key).pending)
1308
+ return `Setting "${entry.key}" began writing during cleanup; await it before retrying.`;
1309
+ this.disabledPlugins = disabled;
1310
+ this.disabledWithParent = cascaded;
1311
+ this.names.replace(entries);
1312
+ this.configuration.replace(configuration);
1313
+ for (const plugin of this.config.plugins ?? [])
1314
+ this.events.undeclare(plugin.id);
1315
+ this.events.undeclare(this.appId);
1316
+ for (const module of declarations)
1317
+ if (module.events)
1318
+ this.events.declare(module.id, module.events);
1319
+ this.slotRuntime.replace(declarations.flatMap((module) => module.slots));
1320
+ this.settings.replace(settings);
1321
+ }, before, after));
1322
+ void this.updating
1323
+ .finally(() => {
1324
+ this.updating = undefined;
1325
+ this.updateController = undefined;
1326
+ this.actions.refresh();
1327
+ })
1328
+ .catch(() => { });
1329
+ return this.updating;
1330
+ },
1331
+ };
1245
1332
  }
1246
1333
  catch (error) {
1247
1334
  return result('blocked', [error instanceof Error ? error.message : String(error)]);
@@ -1287,10 +1374,13 @@ export class BitaKitRuntime {
1287
1374
  return Promise.resolve(result('applied', []));
1288
1375
  try {
1289
1376
  normalized = next.map((plugin) => normalize(plugin, this.appId));
1290
- const all = [this.modules.find((plugin) => plugin.id === this.appId), ...normalized];
1377
+ const all = [
1378
+ this.dependencyModules().find((plugin) => plugin.id === this.appId),
1379
+ ...normalized,
1380
+ ];
1291
1381
  orderPlugins(all, this.appId);
1292
1382
  validateSlotDeclarations(all, this.appId);
1293
- validatePluginPages(all, new Set(Object.keys(all[0].ui?.layouts ?? {})));
1383
+ validatePluginPages(all, layoutFamilies(all));
1294
1384
  // A projection that captured the composition is an explicit consumer of every revision.
1295
1385
  affected = updateClosure(all, [
1296
1386
  ...changed,
@@ -1322,6 +1412,7 @@ export class BitaKitRuntime {
1322
1412
  .finally(() => {
1323
1413
  this.updating = undefined;
1324
1414
  this.updateController = undefined;
1415
+ this.actions.refresh();
1325
1416
  })
1326
1417
  .catch(() => { });
1327
1418
  return this.updating;
@@ -1,5 +1,10 @@
1
1
  import type { InputSchema, SchemaOutput, EffectiveActionId } from '../definitions.js';
2
2
  import type { SlotMap } from '../presentation.js';
3
+ /**
4
+ * `list`: every contribution renders, sorted by `order`. `single`: a replaceable part; several
5
+ * contributors may offer a candidate and outlets render the one `selectSingle` picks, or the
6
+ * owner's fallback. `keyed`: contributions need unique keys and an outlet picks one by key.
7
+ */
3
8
  export type SlotPolicy = 'list' | 'single' | 'keyed';
4
9
  /** Payload is supplied by the owner; schema describes contributed data, not UI. */
5
10
  export type SlotOptions = {
@@ -154,10 +154,13 @@ export class SlotRuntime {
154
154
  (typeof contribution.key !== 'string' || !contribution.key))
155
155
  throw error('invalid-contribution', 'a keyed slot requires a non-empty key.');
156
156
  const id = `${plugin}:${contribution.id ?? ++this.serial}`;
157
+ // A single slot collects candidates from several contributors; outlets select one.
157
158
  for (const current of this.attachments)
158
159
  if (current.slot === name &&
159
160
  (current.id === id ||
160
- definition.policy === 'single' ||
161
+ (definition.policy === 'single' &&
162
+ current.plugin === plugin &&
163
+ current.key === contribution.key) ||
161
164
  (definition.policy === 'keyed' && current.key === contribution.key)))
162
165
  throw error('conflict', `contribution "${id}" conflicts with "${current.id}"; remove it explicitly first.`);
163
166
  let resolve, reject;
@@ -0,0 +1,23 @@
1
+ import type { SlotItem } from './types.js';
2
+ /**
3
+ * The result of selecting the occupant of a `single` slot. `reason` explains why no candidate
4
+ * was selected: several candidates without a decision (`ambiguous`), or a choice that names no
5
+ * available candidate (`choice-unavailable`). Without candidates, both are absent.
6
+ */
7
+ export type SingleSelection<T extends Pick<SlotItem, 'plugin' | 'key'> = SlotItem> = Readonly<{
8
+ selected?: T;
9
+ reason?: 'ambiguous' | 'choice-unavailable';
10
+ candidates: readonly T[];
11
+ }>;
12
+ /** The names a choice may use for a candidate: `<plugin>`, `<plugin>:<key>` and `<key>`. */
13
+ export declare function candidateNames(item: Pick<SlotItem, 'plugin' | 'key'>): readonly string[];
14
+ /**
15
+ * Selects the occupant of a `single` slot from its eligible candidates. The app's choice wins
16
+ * (`choose` in bitakit.config.ts), then a contribution of the app itself, then the only
17
+ * candidate. Several candidates without a decision select none, so owners render their default
18
+ * instead of an arbitrary contribution.
19
+ */
20
+ export declare function selectSingle<T extends Pick<SlotItem, 'plugin' | 'key'>>(candidates: readonly T[], options: {
21
+ choice?: string;
22
+ appId: string;
23
+ }): SingleSelection<T>;
@@ -0,0 +1,25 @@
1
+ /** The names a choice may use for a candidate: `<plugin>`, `<plugin>:<key>` and `<key>`. */
2
+ export function candidateNames(item) {
3
+ return item.key === undefined
4
+ ? [item.plugin]
5
+ : [item.plugin, `${item.plugin}:${item.key}`, item.key];
6
+ }
7
+ /**
8
+ * Selects the occupant of a `single` slot from its eligible candidates. The app's choice wins
9
+ * (`choose` in bitakit.config.ts), then a contribution of the app itself, then the only
10
+ * candidate. Several candidates without a decision select none, so owners render their default
11
+ * instead of an arbitrary contribution.
12
+ */
13
+ export function selectSingle(candidates, options) {
14
+ if (options.choice !== undefined) {
15
+ const matches = candidates.filter((item) => candidateNames(item).includes(options.choice));
16
+ if (matches.length === 1)
17
+ return { selected: matches[0], candidates };
18
+ return { reason: matches.length ? 'ambiguous' : 'choice-unavailable', candidates };
19
+ }
20
+ const own = candidates.filter((item) => item.plugin === options.appId);
21
+ const pool = own.length ? own : candidates;
22
+ if (pool.length === 1)
23
+ return { selected: pool[0], candidates };
24
+ return pool.length ? { reason: 'ambiguous', candidates } : { candidates };
25
+ }
package/package.json CHANGED
@@ -1,11 +1,12 @@
1
1
  {
2
2
  "name": "@bitakit/core",
3
- "version": "0.2.3",
3
+ "version": "0.2.5",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "files": [
7
7
  "dist",
8
8
  "README.md",
9
+ "AGENTS.md",
9
10
  "assets",
10
11
  "discovery",
11
12
  "examples",
@@ -51,7 +52,7 @@
51
52
  }
52
53
  },
53
54
  "devDependencies": {
54
- "@bitakit/discovery": "^0.2.2",
55
+ "@bitakit/discovery": "^0.2.3",
55
56
  "jiti": "^2.7.0",
56
57
  "typescript": "^5.9.3"
57
58
  },