@bitakit/core 0.2.2 → 0.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -44,19 +44,19 @@ resolve within a repository checkout and follow the branch viewed on GitHub. Run
44
44
  `npm run dev:docs` from the repository root to read the rendered handbook at
45
45
  `http://localhost:3002/docs`. A public documentation address is not configured yet.
46
46
 
47
- | Topic | Guide |
48
- | --- | --- |
49
- | Services and cleanup | [Service reference](../../apps/docs/content/docs/reference/services.mdx) |
50
- | Actions and React bindings | [Action reference](../../apps/docs/content/docs/reference/actions.mdx) |
51
- | Events and interception | [Events](../../apps/docs/content/docs/concepts/events.mdx), [Interceptors](../../apps/docs/content/docs/concepts/interceptors.mdx) |
52
- | Files and developer configuration | [Discovery](../../apps/docs/content/docs/concepts/discovery.mdx), [Configuration](../../apps/docs/content/docs/concepts/configuration.mdx) |
53
- | Extension points and preferences | [Slots](../../apps/docs/content/docs/reference/slots.mdx), [Settings](../../apps/docs/content/docs/reference/settings.mdx) |
54
- | Runtime updates and diagnostics | [Runtime management](../../apps/docs/content/docs/concepts/runtime-management.mdx) |
55
- | Enable, disable, add and remove plugins | [Plugin manager](../../apps/docs/content/docs/plugin-management.mdx) |
56
- | Activate a trusted package catalog | [Package manager](../../apps/docs/content/docs/package-management.mdx) |
57
- | Authentication contract | [Client authentication](../../apps/docs/content/docs/reference/authentication.mdx) |
58
- | Test a plugin folder | [Testing](../../apps/docs/content/docs/reference/testing.mdx) |
59
- | Standalone example | [To-do walkthrough](../../apps/docs/content/docs/concepts/tutorial.mdx); runnable JavaScript files in `examples/` |
47
+ | Topic | Guide |
48
+ | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
49
+ | Services and cleanup | [Service reference](../../apps/docs/content/docs/reference/services.mdx) |
50
+ | Actions and React bindings | [Action reference](../../apps/docs/content/docs/reference/actions.mdx) |
51
+ | Events and interception | [Events](../../apps/docs/content/docs/concepts/events.mdx), [Interceptors](../../apps/docs/content/docs/concepts/interceptors.mdx) |
52
+ | Files and developer configuration | [Discovery](../../apps/docs/content/docs/concepts/discovery.mdx), [Configuration](../../apps/docs/content/docs/concepts/configuration.mdx) |
53
+ | Extension points and preferences | [Slots](../../apps/docs/content/docs/reference/slots.mdx), [Settings](../../apps/docs/content/docs/reference/settings.mdx) |
54
+ | Runtime updates and diagnostics | [Runtime management](../../apps/docs/content/docs/concepts/runtime-management.mdx) |
55
+ | Enable, disable, add and remove plugins | [Plugin manager](../../apps/docs/content/docs/plugin-management.mdx) |
56
+ | Activate a trusted package catalog | [Package manager](../../apps/docs/content/docs/package-management.mdx) |
57
+ | Authentication contract | [Client authentication](../../apps/docs/content/docs/reference/authentication.mdx) |
58
+ | Test a plugin folder | [Testing](../../apps/docs/content/docs/reference/testing.mdx) |
59
+ | Standalone example | [To-do walkthrough](../../apps/docs/content/docs/concepts/tutorial.mdx); runnable JavaScript files in `examples/` |
60
60
 
61
61
  Plugins are trusted application code. Core is not a sandbox, package installer or remote
62
62
  marketplace. Services own state and resources; the host owns routing, persistence providers
@@ -58,7 +58,9 @@ export type PublicEventsOf<Plugins extends readonly Plugin[]> = [Plugins[number]
58
58
  events: infer E;
59
59
  } ? EventsOf<E, Id> : {} : never>;
60
60
  /** `CancelableEventMap` entries of manually composed or installed package plugins. */
61
- export type PublicCancelableOf<Plugins extends readonly Plugin[]> = [Plugins[number]] extends [never] ? {} : Intersection<Plugins[number] extends infer P ? P extends {
61
+ export type PublicCancelableOf<Plugins extends readonly Plugin[]> = [Plugins[number]] extends [
62
+ never
63
+ ] ? {} : Intersection<Plugins[number] extends infer P ? P extends {
62
64
  id: infer Id extends string;
63
65
  events: infer E;
64
66
  } ? CancelableOf<E, Id> : {} : never>;
package/dist/core.d.ts CHANGED
@@ -43,6 +43,6 @@ 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
45
  export { configureAuthPaths, resolveAuthReturnTo, authSignInHref, type AuthPaths, type AuthSignInOptions, } from './auth-navigation.js';
46
- export type { PluginUpdateResult, PluginChangeResult, PluginDependentOptions, } from './lifecycle/reconcile.js';
46
+ export type { PluginUpdateResult, PluginChangeResult, PluginDependentOptions, PluginChangeOptions, PluginToggleRequest, PluginChangePreview, PluginChangeReason, } from './lifecycle/reconcile.js';
47
47
  export { createInventory, inspectRuntime, observeRuntimeInventory, inventoryMetadata, } from './inspection/inventory.js';
48
48
  export type { RuntimeInventory, InventoryPlugin, InventoryDeclaration, InventoryMetadata, InventoryKind, InventoryLive, } from './inspection/inventory.js';
@@ -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/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
@@ -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;
@@ -895,7 +897,9 @@ export class BitaKitRuntime {
895
897
  });
896
898
  }
897
899
  connectTranslation() {
898
- const i18n = this.hasService('i18n') ? getService(this.services, translationService) : undefined;
900
+ const i18n = this.hasService('i18n')
901
+ ? getService(this.services, translationService)
902
+ : undefined;
899
903
  if (!i18n)
900
904
  return;
901
905
  this.setTranslations(i18n.translate);
@@ -972,6 +976,51 @@ export class BitaKitRuntime {
972
976
  const message = error instanceof Error ? error.message : String(error);
973
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 });
974
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
+ }
975
1024
  /** One path for every action: adapt, check dependencies, register, remember for re-translation. */
976
1025
  install(scope, contribution, module, events) {
977
1026
  const path = contributionPath(contribution) ?? contribution.id.split('.');
@@ -1041,34 +1090,59 @@ export class BitaKitRuntime {
1041
1090
  if (refresh && observed.size)
1042
1091
  this.actions.refresh();
1043
1092
  }
1044
- /** 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. */
1045
1094
  changePlugins(operation, values, options) {
1046
- const result = (status, reasons, changed = []) => Promise.resolve(Object.freeze({
1047
- status,
1048
- reasons: Object.freeze(reasons),
1049
- changed: Object.freeze(changed),
1050
- affected: Object.freeze([]),
1051
- revision: this.revision,
1052
- }));
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
+ });
1053
1124
  if (this.updating ||
1054
1125
  this.mounting ||
1055
1126
  this.tearingDown ||
1056
1127
  this.stopCompletion ||
1057
1128
  !this.container ||
1058
1129
  this.startPending)
1059
- 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');
1060
1131
  if (this.lifecycle.get().cleanup === 'failed')
1061
- 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');
1062
1135
  try {
1136
+ const modules = this.dependencyModules();
1063
1137
  const installed = [...(this.config.plugins ?? [])];
1064
1138
  const disabled = new Set(this.disabledPlugins);
1065
1139
  const ids = operation === 'add'
1066
1140
  ? values.map((plugin) => plugin.id)
1067
- : values;
1141
+ : [...values];
1068
1142
  if (new Set(ids).size !== ids.length)
1069
1143
  return result('blocked', ['Plugin IDs must be unique.']);
1070
1144
  if (ids.includes(this.appId))
1071
- 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]);
1072
1146
  if ((operation === 'remove' || operation === 'disable') &&
1073
1147
  !['stop', 'refuse'].includes(options?.dependents ?? ''))
1074
1148
  return result('blocked', ['Choose dependents: stop or refuse.']);
@@ -1093,21 +1167,21 @@ export class BitaKitRuntime {
1093
1167
  if (parent && disabled.has(parent) && !ids.includes(parent))
1094
1168
  return result('blocked', [
1095
1169
  `Plugin "${id}" belongs to "${parent}", which is disabled. Enable "${parent}" first.`,
1096
- ]);
1170
+ ], 'owner-disabled', [parent]);
1097
1171
  ids.push(...(cascaded.get(id) ?? []).filter((child) => !ids.includes(child)));
1098
1172
  cascaded.delete(id);
1099
1173
  }
1100
1174
  const activeIds = new Set(this.modules.map((module) => module.id));
1101
- let changed = [...ids];
1175
+ changed = [...ids];
1102
1176
  if (operation === 'disable' || operation === 'remove') {
1103
1177
  const seeds = [...ids, ...owned].filter((id) => activeIds.has(id));
1104
1178
  if (operation === 'remove')
1105
1179
  seeds.push(...this.slotRuntime.contributorsTo(new Set(ids)));
1106
- const closure = updateClosure(this.modules, seeds);
1107
- const dependents = closure.filter((id) => !ids.includes(id) && !owned.includes(id));
1108
- if (dependents.length && options?.dependents === 'refuse')
1109
- return result('blocked', [`Enabled dependents: ${dependents.join(', ')}.`]);
1180
+ const closure = updateClosure(modules, seeds);
1181
+ dependents = closure.filter((id) => !ids.includes(id) && !owned.includes(id));
1110
1182
  changed = [...new Set([...ids, ...owned, ...dependents])];
1183
+ if (dependents.length && options?.dependents === 'refuse')
1184
+ return result('blocked', [`Enabled dependents: ${dependents.join(', ')}.`], 'dependents', dependents);
1111
1185
  if (operation === 'disable') {
1112
1186
  const switchedOff = owned.filter((id) => !disabled.has(id));
1113
1187
  for (const id of ids)
@@ -1132,15 +1206,24 @@ export class BitaKitRuntime {
1132
1206
  disabled.delete(id);
1133
1207
  if (operation === 'disable')
1134
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);
1135
1212
  if (!changed.length) {
1136
- // An explicit disable of a child its parent already switched off: remember the intent.
1137
- this.disabledWithParent = cascaded;
1138
- 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
+ };
1139
1222
  }
1140
1223
  const normalized = nextInstalled
1141
1224
  .filter((plugin) => !disabled.has(plugin.id))
1142
1225
  .map((plugin) => normalize(plugin, this.appId));
1143
- const app = this.modules.find((module) => module.id === this.appId);
1226
+ const app = modules.find((module) => module.id === this.appId);
1144
1227
  const all = [app, ...normalized];
1145
1228
  const declarations = [app, ...nextInstalled.map((plugin) => normalize(plugin, this.appId))];
1146
1229
  orderPlugins(all, this.appId);
@@ -1164,12 +1247,12 @@ export class BitaKitRuntime {
1164
1247
  .map((entry) => entry.id),
1165
1248
  ]),
1166
1249
  ];
1167
- const before = updateClosure(this.modules, [
1250
+ const before = updateClosure(modules, [
1168
1251
  ...changed.filter((id) => activeIds.has(id)),
1169
1252
  ...readers,
1170
1253
  ]);
1171
1254
  const after = updateClosure(all, [...changed, ...readers].filter((id) => all.some((module) => module.id === id)));
1172
- const affected = [...new Set([...before, ...after])];
1255
+ affected = [...new Set([...before, ...after])];
1173
1256
  const reasons = [];
1174
1257
  for (const module of [...this.modules, ...all].filter((module) => affected.includes(module.id))) {
1175
1258
  if (module.id === this.appId ||
@@ -1183,7 +1266,7 @@ export class BitaKitRuntime {
1183
1266
  reasons.push(`${module.id}: host identity, translation or storage service requires composition replacement.`);
1184
1267
  }
1185
1268
  if (reasons.length)
1186
- return result('restart-required', [...new Set(reasons)], changed);
1269
+ return result('restart-required', [...new Set(reasons)], 'composition', affected);
1187
1270
  const entries = this.serviceEntries(all);
1188
1271
  const names = new ServiceNames(entries, this.appId);
1189
1272
  for (const module of all)
@@ -1203,7 +1286,7 @@ export class BitaKitRuntime {
1203
1286
  for (const entry of this.settings.entries())
1204
1287
  if (!settings.some((next) => next.key === entry.key) &&
1205
1288
  this.settings.state(entry.key).pending)
1206
- return result('blocked', [`Setting "${entry.key}" has a pending write.`]);
1289
+ return result('blocked', [`Setting "${entry.key}" has a pending write.`], 'pending-settings');
1207
1290
  createSettingsAccess(new SettingsStore(settings, () => this.storage()));
1208
1291
  const overrides = Object.fromEntries(Object.entries(this.config.configOverrides ?? {}).filter(([id]) => declarations.some((module) => module.id === id)));
1209
1292
  const configuration = new ConfigService(declarations, overrides);
@@ -1212,34 +1295,40 @@ export class BitaKitRuntime {
1212
1295
  for (const module of declarations)
1213
1296
  if (module.events)
1214
1297
  eventCheck.declare(module.id, module.events);
1215
- const controller = new AbortController();
1216
- this.updateController = controller;
1217
- this.updating = Promise.resolve().then(() => this.applyPluginUpdate(nextInstalled, normalized, changed, affected, controller, () => {
1218
- // Writes may begin while awaited Action/scope cleanup is in progress.
1219
- for (const entry of this.settings.entries())
1220
- if (!settings.some((next) => next.key === entry.key) &&
1221
- this.settings.state(entry.key).pending)
1222
- return `Setting "${entry.key}" began writing during cleanup; await it before retrying.`;
1223
- this.disabledPlugins = disabled;
1224
- this.disabledWithParent = cascaded;
1225
- this.names.replace(entries);
1226
- this.configuration.replace(configuration);
1227
- for (const plugin of this.config.plugins ?? [])
1228
- this.events.undeclare(plugin.id);
1229
- this.events.undeclare(this.appId);
1230
- for (const module of declarations)
1231
- if (module.events)
1232
- this.events.declare(module.id, module.events);
1233
- this.slotRuntime.replace(declarations.flatMap((module) => module.slots));
1234
- this.settings.replace(settings);
1235
- }, before, after));
1236
- void this.updating
1237
- .finally(() => {
1238
- this.updating = undefined;
1239
- this.updateController = undefined;
1240
- })
1241
- .catch(() => { });
1242
- 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
+ };
1243
1332
  }
1244
1333
  catch (error) {
1245
1334
  return result('blocked', [error instanceof Error ? error.message : String(error)]);
@@ -1285,7 +1374,10 @@ export class BitaKitRuntime {
1285
1374
  return Promise.resolve(result('applied', []));
1286
1375
  try {
1287
1376
  normalized = next.map((plugin) => normalize(plugin, this.appId));
1288
- 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
+ ];
1289
1381
  orderPlugins(all, this.appId);
1290
1382
  validateSlotDeclarations(all, this.appId);
1291
1383
  validatePluginPages(all, new Set(Object.keys(all[0].ui?.layouts ?? {})));
@@ -1320,6 +1412,7 @@ export class BitaKitRuntime {
1320
1412
  .finally(() => {
1321
1413
  this.updating = undefined;
1322
1414
  this.updateController = undefined;
1415
+ this.actions.refresh();
1323
1416
  })
1324
1417
  .catch(() => { });
1325
1418
  return this.updating;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bitakit/core",
3
- "version": "0.2.2",
3
+ "version": "0.2.4",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "files": [
@@ -1,4 +1,5 @@
1
1
  import type {
2
+ AuthService,
2
3
  EventService,
3
4
  BitaKitApp,
4
5
  BitaKitEvent,
@@ -57,3 +58,19 @@ export function mountPlugin(
57
58
  configOverrides?: Readonly<Record<string, Record<string, unknown>>>;
58
59
  },
59
60
  ): Promise<MountedPlugin>;
61
+
62
+ /**
63
+ * Checks an `auth` provider against the AuthService contract, for the provider's own tests:
64
+ * a stable snapshot, working subscribe/unsubscribe, a string `user.id` after `signIn`, an
65
+ * awaited `signOut` that clears the user, and valid optional `paths` and `signIn`. Rejects with
66
+ * the first broken rule.
67
+ */
68
+ export function assertAuthContract(
69
+ service: AuthService,
70
+ options: {
71
+ /** Signs a test user in through the provider's own login. Called twice. */
72
+ signIn(): Promise<unknown>;
73
+ /** Milliseconds to wait for a pending session or a sign-in to settle (default 2000). */
74
+ timeout?: number;
75
+ },
76
+ ): Promise<void>;
package/testing/index.mjs CHANGED
@@ -13,6 +13,7 @@ import {
13
13
  discoverServices,
14
14
  discoverSlots,
15
15
  discoveredFile,
16
+ configureAuthPaths,
16
17
  } from '../dist/core.js';
17
18
 
18
19
  /** The plugin ID a package declares (`bitakit.id`), or one derived from its name. */
@@ -104,9 +105,7 @@ export async function mountPlugin(directory = 'src', options = {}) {
104
105
  const plugin = await loadPlugin(directory, options.id);
105
106
  const { id } = plugin;
106
107
  const others = await Promise.all(
107
- (options.plugins ?? []).map((other) =>
108
- typeof other === 'string' ? loadPlugin(other) : other,
109
- ),
108
+ (options.plugins ?? []).map((other) => (typeof other === 'string' ? loadPlugin(other) : other)),
110
109
  );
111
110
  const runtime = createRuntime(
112
111
  { plugins: [plugin, ...others], configOverrides: options.configOverrides },
@@ -129,7 +128,9 @@ export async function mountPlugin(directory = 'src', options = {}) {
129
128
  runtime.mount();
130
129
  await runtime.ready;
131
130
  } catch (error) {
132
- try { await release(); } catch (cleanupError) {
131
+ try {
132
+ await release();
133
+ } catch (cleanupError) {
133
134
  throw new AggregateError([error, cleanupError], 'Plugin startup and cleanup failed.');
134
135
  }
135
136
  throw error;
@@ -148,3 +149,72 @@ export async function mountPlugin(directory = 'src', options = {}) {
148
149
  [Symbol.asyncDispose]: release,
149
150
  };
150
151
  }
152
+
153
+ const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
154
+
155
+ /** Waits until `ready()` holds, failing with `message` after `timeout` milliseconds. */
156
+ async function until(ready, message, timeout) {
157
+ const deadline = Date.now() + timeout;
158
+ while (!ready()) {
159
+ if (Date.now() > deadline) throw new Error(`auth contract: ${message}`);
160
+ await new Promise((resolve) => setTimeout(resolve, 5));
161
+ }
162
+ }
163
+
164
+ /**
165
+ * Checks an `auth` provider against the AuthService contract, for the provider's own tests:
166
+ * a stable snapshot, working subscribe/unsubscribe, a string `user.id` after `signIn`, an
167
+ * awaited `signOut` that clears the user, and valid optional `paths`/`signIn`. `signIn` drives
168
+ * the provider's own login. Rejects with the first broken rule.
169
+ */
170
+ export async function assertAuthContract(service, { signIn, timeout = 2000 }) {
171
+ const fail = (rule) => {
172
+ throw new Error(`auth contract: ${rule}`);
173
+ };
174
+ for (const method of ['getSnapshot', 'subscribe', 'signOut'])
175
+ if (typeof service?.[method] !== 'function') fail(`${method}() is missing.`);
176
+ if (service.signIn !== undefined && typeof service.signIn !== 'function')
177
+ fail('signIn must be a function when present.');
178
+ if (service.paths !== undefined) {
179
+ try {
180
+ configureAuthPaths(service.paths);
181
+ } catch (error) {
182
+ fail(`paths are invalid: ${error.message}`);
183
+ }
184
+ }
185
+ await until(() => !service.getSnapshot().pending, 'the snapshot stays pending.', timeout);
186
+ const initial = service.getSnapshot();
187
+ for (const key of ['user', 'pending', 'error'])
188
+ if (!(key in initial)) fail(`the snapshot has no "${key}".`);
189
+ if (service.getSnapshot() !== initial)
190
+ fail('getSnapshot() must return the same object until it changes.');
191
+ if (initial.user !== null && !initial.error) await service.signOut();
192
+
193
+ let notified = 0;
194
+ const unsubscribe = service.subscribe(() => notified++);
195
+ if (typeof unsubscribe !== 'function') fail('subscribe() must return an unsubscribe function.');
196
+ await signIn();
197
+ await until(() => service.getSnapshot().user !== null, 'no user after signIn.', timeout);
198
+ const signedIn = service.getSnapshot();
199
+ if (typeof signedIn.user.id !== 'string' || !signedIn.user.id)
200
+ fail('user.id must be a non-empty string.');
201
+ if (signedIn.pending) fail('pending must be false once the user is known.');
202
+ if (signedIn.error) fail('a signed-in snapshot must not carry an error.');
203
+ if (signedIn === initial) fail('the snapshot must be a new object after a change.');
204
+ if (service.getSnapshot() !== signedIn) fail('the signed-in snapshot must be stable.');
205
+ if (notified === 0) fail('subscribe() listeners must be called when the session changes.');
206
+
207
+ const result = service.signOut();
208
+ if (typeof result?.then !== 'function') fail('signOut() must return a promise.');
209
+ await result;
210
+ const signedOut = service.getSnapshot();
211
+ if (signedOut.user !== null) fail('signOut() must resolve after the user is cleared.');
212
+ if (signedOut.pending) fail('pending must be false after signOut().');
213
+
214
+ unsubscribe();
215
+ const after = notified;
216
+ await signIn();
217
+ await settle();
218
+ if (notified !== after) fail('listeners must not be called after unsubscribe.');
219
+ await service.signOut();
220
+ }