@bitakit/core 0.3.0 → 0.3.2

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 (52) hide show
  1. package/AGENTS.md +58 -2
  2. package/README.md +61 -18
  3. package/dist/actions/execution.js +4 -0
  4. package/dist/contributions/action.d.ts +0 -5
  5. package/dist/contributions/action.js +21 -1
  6. package/dist/contributions/host.d.ts +3 -0
  7. package/dist/core.d.ts +4 -0
  8. package/dist/core.js +1 -0
  9. package/dist/definitions.d.ts +10 -0
  10. package/dist/events/service.d.ts +14 -0
  11. package/dist/events/service.js +109 -39
  12. package/dist/events/types.d.ts +5 -1
  13. package/dist/inspection/inventory.d.ts +1 -1
  14. package/dist/operation-error.d.ts +75 -0
  15. package/dist/operation-error.js +123 -0
  16. package/dist/remote.d.ts +60 -0
  17. package/dist/remote.js +156 -0
  18. package/dist/request-context.d.ts +62 -0
  19. package/dist/request-context.js +2 -0
  20. package/dist/runtime-mode.d.ts +35 -0
  21. package/dist/runtime-mode.js +6 -0
  22. package/dist/runtime.d.ts +17 -1
  23. package/dist/runtime.js +118 -50
  24. package/dist/server/access.d.ts +31 -0
  25. package/dist/server/access.js +109 -0
  26. package/dist/server/compile.d.ts +59 -0
  27. package/dist/server/compile.js +211 -0
  28. package/dist/server/contributions.d.ts +13 -0
  29. package/dist/server/contributions.js +17 -0
  30. package/dist/server/create-server.d.ts +15 -0
  31. package/dist/server/create-server.js +132 -0
  32. package/dist/server/define.d.ts +40 -0
  33. package/dist/server/define.js +15 -0
  34. package/dist/server/fetch-handler.d.ts +17 -0
  35. package/dist/server/fetch-handler.js +139 -0
  36. package/dist/server/index.d.ts +22 -0
  37. package/dist/server/index.js +21 -0
  38. package/dist/server/kernel.d.ts +44 -0
  39. package/dist/server/kernel.js +278 -0
  40. package/dist/server/types.d.ts +208 -0
  41. package/dist/server/types.js +1 -0
  42. package/dist/server/validate.d.ts +31 -0
  43. package/dist/server/validate.js +60 -0
  44. package/dist/services.d.ts +5 -1
  45. package/dist/services.js +5 -1
  46. package/dist/settings/access.d.ts +5 -2
  47. package/dist/settings/access.js +7 -4
  48. package/dist/settings/server.d.ts +28 -0
  49. package/dist/settings/server.js +94 -0
  50. package/package.json +7 -3
  51. package/testing/index.d.ts +104 -0
  52. package/testing/index.mjs +349 -14
package/dist/remote.js ADDED
@@ -0,0 +1,156 @@
1
+ import { isOperationErrorCode, OperationError, operationCodeOf, operationErrorFrom, } from './operation-error.js';
2
+ export const organizationHeader = 'x-bitakit-organization';
3
+ /**
4
+ * Name segments no server Action ID may use. As properties of `remote` or the in-process caller
5
+ * they would make a namespace thenable (`then`), observable (`subscribe`), or called by
6
+ * serialization and conversion (`toJSON`, `valueOf`, `toString`), or shadow Promise and object
7
+ * plumbing (`catch`, `finally`, `constructor`, `prototype`). The kernel refuses such IDs at
8
+ * startup; `remote` and the caller never offer them.
9
+ */
10
+ export const reservedSegments = new Set([
11
+ 'then',
12
+ 'catch',
13
+ 'finally',
14
+ 'subscribe',
15
+ 'toJSON',
16
+ 'valueOf',
17
+ 'toString',
18
+ 'constructor',
19
+ 'prototype',
20
+ ]);
21
+ /** The first reserved segment of an operation ID, if it has one. */
22
+ export const reservedSegmentOf = (id) => id.split('.').find((segment) => reservedSegments.has(segment));
23
+ /**
24
+ * Builds `remote` once per runtime: nested plain, frozen functions (never a Proxy, never
25
+ * observable), one per configured operation, each a `POST <endpoint>/<id>` with a JSON body.
26
+ * `organization` reads the default organization header at call time (undefined: no header).
27
+ * Without a configuration every call rejects with SERVICE_UNAVAILABLE instead of a TypeError.
28
+ * IDs with a reserved segment (`reservedSegments`) are left out with one warning.
29
+ */
30
+ export function createRemote(config, organization = () => undefined) {
31
+ if (!config)
32
+ return unconfiguredRemote();
33
+ const endpoint = config.endpoint.replace(/\/+$/, '');
34
+ const root = {};
35
+ const reserved = [];
36
+ for (const id of new Set(config.operations)) {
37
+ if (reservedSegmentOf(id) !== undefined) {
38
+ reserved.push(id);
39
+ continue;
40
+ }
41
+ const call = (input, options) => callOperation(`${endpoint}/${id}`, input, options, organization);
42
+ const parts = id.split('.');
43
+ let node = root;
44
+ parts.forEach((part, index) => {
45
+ const existing = Object.hasOwn(node, part) ? node[part] : undefined;
46
+ if (index === parts.length - 1) {
47
+ // An ID that is also a prefix (`todos` and `todos.add`) keeps its children on the function.
48
+ const leaf = existing
49
+ ? Object.defineProperties(call, Object.getOwnPropertyDescriptors(existing))
50
+ : call;
51
+ Object.defineProperty(node, part, {
52
+ value: leaf,
53
+ enumerable: true,
54
+ writable: true,
55
+ configurable: true,
56
+ });
57
+ }
58
+ else {
59
+ if (!existing)
60
+ Object.defineProperty(node, part, {
61
+ value: {},
62
+ enumerable: true,
63
+ writable: true,
64
+ configurable: true,
65
+ });
66
+ node = node[part];
67
+ }
68
+ });
69
+ }
70
+ if (reserved.length)
71
+ console.warn(`[bitakit] remote leaves out ${reserved.map((id) => `"${id}"`).join(', ')}: ${[...reservedSegments].join(', ')} are reserved names and cannot be server Action names.`);
72
+ return deepFreeze(root);
73
+ }
74
+ function deepFreeze(value) {
75
+ for (const child of Object.values(value))
76
+ if (child && !Object.isFrozen(child))
77
+ deepFreeze(child);
78
+ return Object.freeze(value);
79
+ }
80
+ async function callOperation(url, input, options, organization) {
81
+ const headers = { 'content-type': 'application/json' };
82
+ const expected = options?.organizationId !== undefined ? (options.organizationId ?? '') : organization();
83
+ if (expected !== undefined)
84
+ headers[organizationHeader] = expected;
85
+ const signal = options?.signal;
86
+ let response;
87
+ let text;
88
+ try {
89
+ response = await fetch(url, {
90
+ method: 'POST',
91
+ headers,
92
+ body: input === undefined ? undefined : JSON.stringify(input),
93
+ signal,
94
+ });
95
+ text = await response.text();
96
+ }
97
+ catch (error) {
98
+ if (signal?.aborted)
99
+ throw signal.reason ?? error;
100
+ throw new OperationError('SERVICE_UNAVAILABLE', 'The server could not be reached.', {
101
+ cause: error,
102
+ });
103
+ }
104
+ return envelope(response, text);
105
+ }
106
+ const unexpected = 'The server sent an unexpected answer.';
107
+ /**
108
+ * Reads the RPC envelope. Only a 2xx `{ "data": ... }` (or `{}`: no result) resolves, and
109
+ * `{ "error": {...} }` rejects with the rebuilt OperationError (an unknown code takes the HTTP
110
+ * status's). Anything else is never a success, whatever its status: a proxy's or middleware's
111
+ * own answer (`429 { "message": ... }`), a 2xx body without `data`, a non-JSON page. It rejects
112
+ * with the code of the HTTP status (429 → TOO_MANY_REQUESTS, 503 → SERVICE_UNAVAILABLE, a 2xx
113
+ * or unknown status → INTERNAL_SERVER_ERROR) and a fixed message.
114
+ */
115
+ function envelope(response, text) {
116
+ const fallback = response.ok ? 'INTERNAL_SERVER_ERROR' : operationCodeOf(response.status);
117
+ let body;
118
+ try {
119
+ body = JSON.parse(text);
120
+ }
121
+ catch (error) {
122
+ throw new OperationError(fallback, unexpected, { cause: error });
123
+ }
124
+ if (body && typeof body === 'object' && !Array.isArray(body)) {
125
+ const { error } = body;
126
+ if (error && typeof error === 'object' && !Array.isArray(error)) {
127
+ const { code } = error;
128
+ throw operationErrorFrom(isOperationErrorCode(code) ? error : { ...error, code: fallback });
129
+ }
130
+ if (response.ok && !Object.hasOwn(body, 'error')) {
131
+ if (Object.hasOwn(body, 'data'))
132
+ return body.data;
133
+ if (Object.keys(body).length === 0)
134
+ return undefined;
135
+ }
136
+ }
137
+ throw new OperationError(fallback, unexpected);
138
+ }
139
+ /**
140
+ * Without a configured endpoint, any operation name rejects with SERVICE_UNAVAILABLE. This is the
141
+ * one place `remote` is a Proxy: names are unknown, so a plain object would throw a TypeError.
142
+ * Reserved segments read as undefined at every depth, exactly as on a configured `remote`, where
143
+ * no operation can have them: it is never thenable, never observable and never called by
144
+ * serialization or conversion.
145
+ */
146
+ function unconfiguredRemote() {
147
+ const fail = () => Promise.reject(new OperationError('SERVICE_UNAVAILABLE', 'No server operations are configured.'));
148
+ const node = () => new Proxy(fail, {
149
+ get: (_target, name) => typeof name !== 'string' || reservedSegments.has(name) ? undefined : node(),
150
+ apply: () => fail(),
151
+ set: () => false,
152
+ defineProperty: () => false,
153
+ deleteProperty: () => false,
154
+ });
155
+ return node();
156
+ }
@@ -0,0 +1,62 @@
1
+ import type { PermissionMap } from './permissions.js';
2
+ /**
3
+ * Operations to check with `access: { permission }`: resources and their operations, typed against
4
+ * the generated permission catalog when one exists.
5
+ */
6
+ export type PermissionRequest = keyof PermissionMap extends never ? Readonly<Record<string, readonly string[]>> : {
7
+ readonly [Resource in keyof PermissionMap]?: readonly PermissionMap[Resource][];
8
+ };
9
+ /** Who may call a server Action. Required on every server Action. */
10
+ export type Access = 'public' | 'user' | 'organization' | {
11
+ readonly permission: PermissionRequest;
12
+ };
13
+ export type RequestUser = {
14
+ readonly id: string;
15
+ readonly name?: string;
16
+ readonly email?: string;
17
+ } & Readonly<Record<string, unknown>>;
18
+ export type RequestMember = {
19
+ readonly id?: string;
20
+ readonly role?: string | readonly string[];
21
+ } & Readonly<Record<string, unknown>>;
22
+ /** What a `requestContext` provider answers for one request; the kernel normalizes it. */
23
+ export type RequestIdentity = {
24
+ user: RequestUser | null;
25
+ /** Only for an active, non-disabled membership; never just an active organization ID. */
26
+ organization?: {
27
+ id: string;
28
+ } | null;
29
+ member?: RequestMember | null;
30
+ reason?: 'NO_ACTIVE_ORGANIZATION' | 'NOT_A_MEMBER';
31
+ /** For `access: { permission }`. Only a result `=== true` grants. May be async. */
32
+ can?(permission: PermissionRequest): boolean | Promise<boolean>;
33
+ };
34
+ /**
35
+ * Resolves the verified identity of a request. One app service provides it
36
+ * (`provides: requestContext`, usually `src/server/services/request-context.ts`); `resolve`
37
+ * receives the same `Request` object that was passed to `server.as()` or `server.call()`.
38
+ */
39
+ export type RequestContextProvider = {
40
+ resolve(request: Request): RequestIdentity | Promise<RequestIdentity>;
41
+ };
42
+ export declare const requestContext: import("./service-key.js").ServiceKey<RequestContextProvider, "requestContext">;
43
+ /** What every operation receives as `ctx`. Frozen. */
44
+ export type PublicContext = {
45
+ readonly requestId: string;
46
+ readonly signal: AbortSignal;
47
+ };
48
+ export type UserContext = PublicContext & {
49
+ readonly user: RequestUser;
50
+ };
51
+ export type OrganizationContext = UserContext & {
52
+ readonly organization: {
53
+ readonly id: string;
54
+ };
55
+ readonly member: RequestMember | null;
56
+ /** True only when the provider's `can` answers exactly `true`; a throw answers false. */
57
+ can(permission: PermissionRequest): Promise<boolean>;
58
+ };
59
+ /** The `ctx` an operation with access rule `A` receives. */
60
+ export type ContextFor<A> = A extends 'public' ? PublicContext : A extends 'user' ? UserContext : OrganizationContext;
61
+ /** What event listeners and settings receive: whatever the call had. */
62
+ export type RequestContext = PublicContext & Partial<Omit<OrganizationContext, keyof PublicContext>>;
@@ -0,0 +1,2 @@
1
+ import { defineContract } from './service-key.js';
2
+ export const requestContext = defineContract('requestContext').of();
@@ -0,0 +1,35 @@
1
+ import type { ConfigContext } from './config-service.js';
2
+ import type { Events } from './events/types.js';
3
+ import type { RequestContext } from './request-context.js';
4
+ import type { NormalizedPlugin } from './runtime.js';
5
+ import type { ServiceRequester } from './service-names.js';
6
+ import type { Remote } from './remote.js';
7
+ /**
8
+ * `client` (the default) registers Actions in the ActionList and follows the `auth` identity;
9
+ * `server` is the headless mode under `createServer`: no ActionList registration, no store
10
+ * observation, no settings activation, per-request settings `load()` and no structural updates.
11
+ */
12
+ export type RuntimeMode = 'client' | 'server';
13
+ export type RuntimeOptions = {
14
+ mode?: RuntimeMode;
15
+ /** Replaces the `remote` built from `config.remote` (tests and in-process hosts). */
16
+ remote?: Remote;
17
+ };
18
+ /** What the server kernel needs from a starting runtime. Internal to Core. */
19
+ export type ServerStartParts = {
20
+ readonly modules: readonly NormalizedPlugin[];
21
+ readonly appId: string;
22
+ config(module: string, path?: readonly string[]): ConfigContext;
23
+ events(module: string): {
24
+ readonly events: Events;
25
+ withContext(ctx: RequestContext): Events;
26
+ };
27
+ require(module: string, ids: readonly string[] | undefined, requester: ServiceRequester): void;
28
+ attribute(error: unknown, module: string, what: string, source?: string): Error;
29
+ };
30
+ /**
31
+ * The kernel registers its compiler here before mounting; a server-mode runtime calls it once,
32
+ * synchronously, where a client runtime installs its Actions. A module-scoped WeakMap keeps the
33
+ * hook off the public runtime API.
34
+ */
35
+ export declare const serverStartHooks: WeakMap<object, (parts: ServerStartParts) => void>;
@@ -0,0 +1,6 @@
1
+ /**
2
+ * The kernel registers its compiler here before mounting; a server-mode runtime calls it once,
3
+ * synchronously, where a client runtime installs its Actions. A module-scoped WeakMap keeps the
4
+ * hook off the public runtime API.
5
+ */
6
+ export const serverStartHooks = new WeakMap();
package/dist/runtime.d.ts CHANGED
@@ -7,6 +7,8 @@ import { ActionGroup, type ActionList, type ActionSnapshot } from '@bitakit/core
7
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
+ import { type Remote } from './remote.js';
11
+ import { type RuntimeMode, type RuntimeOptions } from './runtime-mode.js';
10
12
  import type { BitaKitApp } from './app/types.js';
11
13
  import { type Feedback, type MessageValues } from './actions/feedback.js';
12
14
  import { type ContributionHost, type DialogState, type FeedbackOutcome, type OpenableDefinition, type Override } from './contributions/index.js';
@@ -141,11 +143,18 @@ export declare class BitaKitRuntime implements ContributionHost {
141
143
  private notifier?;
142
144
  private confirmHandler?;
143
145
  private confirmWarned;
144
- constructor(actions: ActionList, config: BitaKitRuntimeConfig, providedServices?: Readonly<Record<string, unknown>>);
146
+ /** `client` by default; `server` under `createServer` (see `RuntimeMode`). */
147
+ readonly mode: RuntimeMode;
148
+ /** The exposed server operations, as client Actions and services receive them. */
149
+ readonly remote: Remote;
150
+ constructor(actions: ActionList, config: BitaKitRuntimeConfig, providedServices?: Readonly<Record<string, unknown>>, options?: RuntimeOptions);
145
151
  private serviceEntries;
146
152
  private settingEntries;
147
153
  /** The `settings.storage` contract when a service provides it, otherwise browser storage. */
148
154
  private storage;
155
+ private storageProvider;
156
+ /** The organization header `remote` sends: only while the `auth` contract has a user. */
157
+ private organizationHeader;
149
158
  /**
150
159
  * Loads settings for the identity the `auth` contract reports. Runs after setup and whenever
151
160
  * an observed service changes, so no extra subscription is needed; without authentication the
@@ -209,6 +218,8 @@ export declare class BitaKitRuntime implements ContributionHost {
209
218
  private startFailed;
210
219
  /** Routes each contribution kind to the one module that installs it; cleanup stays with the contributor. */
211
220
  private installContributions;
221
+ /** Server mode: hands the started composition to the kernel's compiler instead of the ActionList. */
222
+ private startServer;
212
223
  private connectTranslation;
213
224
  private installInterceptors;
214
225
  /** Resolves required names to container keys; a missing one is attributed to `module`. */
@@ -232,6 +243,7 @@ export declare class BitaKitRuntime implements ContributionHost {
232
243
  private planPluginChange;
233
244
  /** Explicit host update of already-loaded immutable plugin definitions; never installs code. */
234
245
  reconcilePlugins(next: readonly Plugin[]): Promise<PluginUpdateResult>;
246
+ private assertClientMode;
235
247
  private stopPlugins;
236
248
  private applyPluginUpdate;
237
249
  private unmount;
@@ -245,4 +257,8 @@ export declare class BitaKitRuntime implements ContributionHost {
245
257
  export declare function createRuntime(config: BitaKitRuntimeConfig, options?: {
246
258
  actions?: ActionList;
247
259
  services?: Readonly<Record<string, unknown>>;
260
+ /** Replaces the `remote` built from `config.remote`, for tests and in-process hosts. */
261
+ remote?: Remote;
262
+ /** `server` is the headless mode `createServer` uses; see `RuntimeMode`. */
263
+ mode?: RuntimeMode;
248
264
  }): BitaKitRuntime;
package/dist/runtime.js CHANGED
@@ -17,6 +17,10 @@ import { createSettingsAccess } from './settings/access.js';
17
17
  import { createLocalSettingsStorage } from './settings/storage.js';
18
18
  import { isSettingsDefinition } from './settings/define.js';
19
19
  import { translationService } from './contracts.js';
20
+ import { serverSettingHandle } from './settings/server.js';
21
+ import { createRemote } from './remote.js';
22
+ import { isOperationError } from './operation-error.js';
23
+ import { serverStartHooks } from './runtime-mode.js';
20
24
  import { getService } from './service-key.js';
21
25
  import { createServices } from './services.js';
22
26
  import { createBitaKitApp } from './app/access.js';
@@ -284,7 +288,7 @@ export class BitaKitRuntime {
284
288
  }
285
289
  }
286
290
  // Presentation may read app.ready.
287
- if (this.container) {
291
+ if (this.container && this.mode === 'client') {
288
292
  try {
289
293
  this.actions.refresh();
290
294
  }
@@ -313,9 +317,17 @@ export class BitaKitRuntime {
313
317
  notifier;
314
318
  confirmHandler;
315
319
  confirmWarned = false;
316
- constructor(actions, config, providedServices = {}) {
320
+ /** `client` by default; `server` under `createServer` (see `RuntimeMode`). */
321
+ mode;
322
+ /** The exposed server operations, as client Actions and services receive them. */
323
+ remote;
324
+ constructor(actions, config, providedServices = {}, options = {}) {
317
325
  this.actions = actions;
318
326
  this.providedServices = providedServices;
327
+ this.mode = options.mode === 'server' ? 'server' : 'client';
328
+ this.remote =
329
+ options.remote ??
330
+ createRemote(this.mode === 'server' ? undefined : config.remote, () => this.organizationHeader());
319
331
  this.currentConfig = config;
320
332
  this.appId = config.appId ?? 'app';
321
333
  const { plugins = [], appId: _appId, ...appModule } = config;
@@ -344,7 +356,10 @@ export class BitaKitRuntime {
344
356
  this.names = new ServiceNames(this.serviceEntries(), this.appId);
345
357
  try {
346
358
  this.settings = new SettingsStore(this.settingEntries(), () => this.storage());
347
- this.settingsAccess = createSettingsAccess(this.settings);
359
+ this.settingsAccess =
360
+ this.mode === 'server'
361
+ ? createSettingsAccess(this.settings, (_store, key, spec) => serverSettingHandle(key, spec, () => this.storageProvider()))
362
+ : createSettingsAccess(this.settings);
348
363
  }
349
364
  catch (error) {
350
365
  throw attributed(error, this.appId, 'Settings', this.appId);
@@ -393,18 +408,35 @@ export class BitaKitRuntime {
393
408
  }
394
409
  /** The `settings.storage` contract when a service provides it, otherwise browser storage. */
395
410
  storage() {
396
- const name = 'settings.storage';
397
- if (this.hasService(name))
398
- return this.container.services[this.names.key(name)];
411
+ const provider = this.storageProvider();
412
+ if (provider)
413
+ return provider;
414
+ // A server never keeps setting values in process memory.
415
+ if (this.mode === 'server')
416
+ throw new Error('No service provides settings.storage; settings cannot load on the server.');
399
417
  return (this.defaultStorage ??= createLocalSettingsStorage());
400
418
  }
419
+ storageProvider() {
420
+ const name = 'settings.storage';
421
+ return this.hasService(name)
422
+ ? this.container.services[this.names.key(name)]
423
+ : undefined;
424
+ }
425
+ /** The organization header `remote` sends: only while the `auth` contract has a user. */
426
+ organizationHeader() {
427
+ if (!this.container || !this.hasService('auth'))
428
+ return undefined;
429
+ const auth = this.container.services[this.names.key('auth')];
430
+ const snapshot = typeof auth?.getSnapshot === 'function' ? auth.getSnapshot() : undefined;
431
+ return snapshot?.user ? (snapshot.organizationId ?? '') : undefined;
432
+ }
401
433
  /**
402
434
  * Loads settings for the identity the `auth` contract reports. Runs after setup and whenever
403
435
  * an observed service changes, so no extra subscription is needed; without authentication the
404
436
  * anonymous device identity applies. Never blocks readiness.
405
437
  */
406
438
  syncIdentity() {
407
- if (!this.container)
439
+ if (!this.container || this.mode === 'server')
408
440
  return;
409
441
  const auth = this.hasService('auth')
410
442
  ? this.container.services[this.names.key('auth')]
@@ -748,53 +780,57 @@ export class BitaKitRuntime {
748
780
  this.modules.find((module) => module.services.includes(definition))?.id ??
749
781
  this.appId,
750
782
  sourceOf: (definition) => contributionSource(definition),
751
- }, (definition) => definition.id, this.settingsAccess, (id, phase, error) => this.servicePhase(id, phase, error));
783
+ }, (definition) => definition.id, this.settingsAccess, (id, phase, error) => this.servicePhase(id, phase, error), this.mode === 'client' ? { remote: this.remote } : {});
752
784
  // Contexts exist only after the container does; readiness is the public facade's concern.
753
785
  this.view = this.names.tree(this.container.services);
754
786
  const moduleEvents = new Map();
787
+ const server = this.mode === 'server';
755
788
  try {
756
789
  this.container.initialize();
757
- this.extensionCleanups.push(this.actions.subscribeExecution((event) => {
758
- if (event.phase === 'started' &&
759
- (this.registrations.some((entry) => entry.definition.id === event.id) ||
760
- this.scopes.some((scope) => scope.ownsAction(event.id)))) {
761
- const pending = deferred();
762
- this.activeRuns.set(event.context, {
763
- ...pending,
764
- plugin: this.actionConfigs.get(event.id)?.module ??
765
- (this.scopes.find((scope) => scope.ownsAction(event.id))
766
- ? scopeModule(this.scopes.find((scope) => scope.ownsAction(event.id))).id
767
- : undefined),
768
- });
769
- }
770
- else if (event.phase !== 'started') {
771
- this.activeRuns.get(event.context)?.resolve();
772
- this.activeRuns.delete(event.context);
773
- }
774
- }), this.actions.use({
775
- before: ({ id }) => {
776
- const phase = this.lifecycle.get().phase;
777
- const scope = this.scopes.find((entry) => entry.ownsAction(id));
778
- const owner = this.actionConfigs.get(id)?.module ?? (scope && scopeModule(scope).id);
779
- if (owner &&
780
- (this.stopCompletion ||
781
- phase === 'stopping' ||
782
- phase === 'stopped' ||
783
- (phase === 'failed' && !this.isReady()) ||
784
- (this.isReady() && !this.isReady(owner))))
785
- return false;
786
- },
787
- }), this.actions.subscribeExecution((event) => {
788
- if (event.phase === 'failed' && event.context.get() && isActionFailure(event.error))
789
- this.notify(event.error.feedback, 'failure');
790
- }));
790
+ if (!server)
791
+ this.extensionCleanups.push(this.actions.subscribeExecution((event) => {
792
+ if (event.phase === 'started' &&
793
+ (this.registrations.some((entry) => entry.definition.id === event.id) ||
794
+ this.scopes.some((scope) => scope.ownsAction(event.id)))) {
795
+ const pending = deferred();
796
+ this.activeRuns.set(event.context, {
797
+ ...pending,
798
+ plugin: this.actionConfigs.get(event.id)?.module ??
799
+ (this.scopes.find((scope) => scope.ownsAction(event.id))
800
+ ? scopeModule(this.scopes.find((scope) => scope.ownsAction(event.id))).id
801
+ : undefined),
802
+ });
803
+ }
804
+ else if (event.phase !== 'started') {
805
+ this.activeRuns.get(event.context)?.resolve();
806
+ this.activeRuns.delete(event.context);
807
+ }
808
+ }), this.actions.use({
809
+ before: ({ id }) => {
810
+ const phase = this.lifecycle.get().phase;
811
+ const scope = this.scopes.find((entry) => entry.ownsAction(id));
812
+ const owner = this.actionConfigs.get(id)?.module ?? (scope && scopeModule(scope).id);
813
+ if (owner &&
814
+ (this.stopCompletion ||
815
+ phase === 'stopping' ||
816
+ phase === 'stopped' ||
817
+ (phase === 'failed' && !this.isReady()) ||
818
+ (this.isReady() && !this.isReady(owner))))
819
+ return false;
820
+ },
821
+ }), this.actions.subscribeExecution((event) => {
822
+ if (event.phase === 'failed' && event.context.get() && isActionFailure(event.error))
823
+ this.notify(event.error.feedback, 'failure');
824
+ }));
791
825
  for (const plugin of plugins) {
792
826
  const scope = createEventScope(this.events, plugin.id);
793
827
  this.pluginEvents.set(plugin.id, scope);
794
828
  moduleEvents.set(plugin.id, scope.events);
795
829
  }
796
830
  this.connectTranslation();
797
- this.installInterceptors(plugins);
831
+ // On the server, action interceptors are compiled with the operations.
832
+ if (!server)
833
+ this.installInterceptors(plugins);
798
834
  const composed = Object.freeze(plugins
799
835
  .filter((plugin) => plugin.id !== this.appId)
800
836
  .map((plugin) => Object.freeze({ id: plugin.id, metadata: plugin.metadata })));
@@ -818,13 +854,18 @@ export class BitaKitRuntime {
818
854
  scope.onClose(this.pluginEvents.get(plugin.id).dispose);
819
855
  }
820
856
  this.installContributions(plugins);
821
- plugins.forEach((plugin, index) => {
822
- for (const contribution of plugin.actions)
823
- this.install(this.scopes[index], contribution, plugin.id, moduleEvents.get(plugin.id));
824
- });
857
+ if (server)
858
+ this.startServer(plugins);
859
+ else
860
+ plugins.forEach((plugin, index) => {
861
+ for (const contribution of plugin.actions)
862
+ this.install(this.scopes[index], contribution, plugin.id, moduleEvents.get(plugin.id));
863
+ });
825
864
  // Declared targets and programmatic contributions share the same owned attachment path.
826
865
  // Undeclared UI slots retain their existing rendering until the placement migration.
827
866
  plugins.forEach((plugin, index) => {
867
+ if (server)
868
+ return;
828
869
  for (const [viewIndex, view] of plugin.views.entries()) {
829
870
  if (!this.slots.has(view.slot))
830
871
  continue;
@@ -847,7 +888,8 @@ export class BitaKitRuntime {
847
888
  }
848
889
  }
849
890
  });
850
- this.observe(new Set([...this.container.observed, this.settings]));
891
+ if (!server)
892
+ this.observe(new Set([...this.container.observed, this.settings]));
851
893
  plugins.forEach((plugin, index) => {
852
894
  const scope = this.scopes[index];
853
895
  try {
@@ -928,7 +970,8 @@ export class BitaKitRuntime {
928
970
  throw new BitaKitStartupError(`Contribution kind "${kind}" is installed by both "${existing.module}" and "${plugin.id}".`, plugin.id);
929
971
  installers.set(kind, { module: plugin.id, install });
930
972
  }
931
- for (const plugin of plugins)
973
+ // Server kinds have no installers yet; their values stay readable through contributionsOf.
974
+ for (const plugin of this.mode === 'server' ? [] : plugins)
932
975
  for (const [kind, values] of Object.entries(plugin.contributions ?? {}))
933
976
  if (values?.length && !installers.has(kind))
934
977
  throw new BitaKitStartupError(`"${plugin.id}" contributes "${kind}", but no enabled plugin installs that kind.`, plugin.id, { app: plugin.id === this.appId });
@@ -954,6 +997,17 @@ export class BitaKitRuntime {
954
997
  }
955
998
  });
956
999
  }
1000
+ /** Server mode: hands the started composition to the kernel's compiler instead of the ActionList. */
1001
+ startServer(plugins) {
1002
+ serverStartHooks.get(this)?.({
1003
+ modules: plugins,
1004
+ appId: this.appId,
1005
+ config: (module, path) => this.configuration.context(module, path),
1006
+ events: (module) => this.pluginEvents.get(module),
1007
+ require: (module, ids, requester) => void this.requireServices(module, ids, requester),
1008
+ attribute: (error, module, what, source) => this.attribute(error, module, what, source),
1009
+ });
1010
+ }
957
1011
  connectTranslation() {
958
1012
  const i18n = this.hasService('i18n')
959
1013
  ? getService(this.services, translationService)
@@ -1040,6 +1094,8 @@ export class BitaKitRuntime {
1040
1094
  * runtime shutdown also releases it. Host Actions must not await this runtime's stop.
1041
1095
  */
1042
1096
  bindHostAction(id, definition) {
1097
+ if (this.mode === 'server')
1098
+ throw new Error('Host Actions are not supported in server mode.');
1043
1099
  if (!this.isReady() || this.updating || this.stopCompletion)
1044
1100
  throw new Error('Host Actions can only be bound to a ready, idle runtime.');
1045
1101
  const scope = this.scopes.find((entry) => scopeModule(entry).id === this.appId);
@@ -1164,6 +1220,7 @@ export class BitaKitRuntime {
1164
1220
  }
1165
1221
  /** Validate without starting services, invoking hooks or mutating retained lifecycle intent. */
1166
1222
  planPluginChange(operation, values, options, replacement = []) {
1223
+ this.assertClientMode();
1167
1224
  let changed = [];
1168
1225
  let affected = [];
1169
1226
  let dependents = [];
@@ -1424,6 +1481,7 @@ export class BitaKitRuntime {
1424
1481
  }
1425
1482
  /** Explicit host update of already-loaded immutable plugin definitions; never installs code. */
1426
1483
  reconcilePlugins(next) {
1484
+ this.assertClientMode();
1427
1485
  next = [...next];
1428
1486
  const result = (status, reasons, changed = [], affected = []) => Object.freeze({
1429
1487
  status,
@@ -1506,6 +1564,10 @@ export class BitaKitRuntime {
1506
1564
  .catch(() => { });
1507
1565
  return this.updating;
1508
1566
  }
1567
+ assertClientMode() {
1568
+ if (this.mode === 'server')
1569
+ throw new Error('Structural plugin updates are not supported in server mode. Restart the server with the new composition.');
1570
+ }
1509
1571
  async stopPlugins(ids) {
1510
1572
  const selected = new Set(ids);
1511
1573
  const scopes = this.scopes.filter((scope) => selected.has(scopeModule(scope).id));
@@ -1859,6 +1921,9 @@ export class BitaKitRuntime {
1859
1921
  }
1860
1922
  }
1861
1923
  function defaultFailure(error) {
1924
+ // An OperationError's message is written for its caller, in every environment.
1925
+ if (isOperationError(error))
1926
+ return error.safeMessage;
1862
1927
  let development = true;
1863
1928
  try {
1864
1929
  development = process.env.NODE_ENV !== 'production';
@@ -1876,5 +1941,8 @@ function defaultFailure(error) {
1876
1941
  * services, such as authentication, under their contract names.
1877
1942
  */
1878
1943
  export function createRuntime(config, options = {}) {
1879
- return new BitaKitRuntime(options.actions ?? createActionList(), config, options.services);
1944
+ return new BitaKitRuntime(options.actions ?? createActionList(), config, options.services, {
1945
+ mode: options.mode,
1946
+ remote: options.remote,
1947
+ });
1880
1948
  }
@@ -0,0 +1,31 @@
1
+ import type { PermissionCatalog } from '../permissions.js';
2
+ import type { Access, PermissionRequest, RequestMember, RequestUser } from '../request-context.js';
3
+ /**
4
+ * The startup check of `access`: exactly one of the three levels, or `{ permission }` with at least
5
+ * one resource, each a non-empty list of operation names. With a permission catalog, every
6
+ * resource and operation must be declared. Returns the problem, or undefined.
7
+ */
8
+ export declare function accessProblem(access: unknown, catalog: PermissionCatalog): string | undefined;
9
+ /** The provider's answer after normalization; never trusted as-is. */
10
+ export type Identity = {
11
+ readonly user: RequestUser | null;
12
+ readonly organization: {
13
+ readonly id: string;
14
+ } | null;
15
+ readonly member: RequestMember | null;
16
+ readonly reason?: 'NO_ACTIVE_ORGANIZATION' | 'NOT_A_MEMBER';
17
+ readonly can?: (permission: PermissionRequest) => boolean | Promise<boolean>;
18
+ };
19
+ /**
20
+ * A user only with a non-empty string `id`; an organization only with a user and a non-empty
21
+ * `id`; a non-function `can` is dropped. Each declared field (`id`, `name`, `email`; the
22
+ * organization's `id`; the member's `id` and `role`) is read once and checked on the value the
23
+ * copy holds. Copies are frozen, so no interceptor or listener can change the identity in the
24
+ * middle of a call.
25
+ */
26
+ export declare function normalizeIdentity(raw: unknown): Identity;
27
+ /** `ctx.can`: only an answer `=== true` grants; a throw or anything else denies. */
28
+ export declare function permissionCheck(identity: Identity, report: (error: unknown) => void): (permission: PermissionRequest) => Promise<boolean>;
29
+ export declare const isOrganizationAccess: (access: Access) => access is {
30
+ readonly permission: PermissionRequest;
31
+ } | "organization";