@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.
- package/AGENTS.md +58 -2
- package/README.md +61 -18
- package/dist/actions/execution.js +4 -0
- package/dist/contributions/action.d.ts +0 -5
- package/dist/contributions/action.js +21 -1
- package/dist/contributions/host.d.ts +3 -0
- package/dist/core.d.ts +4 -0
- package/dist/core.js +1 -0
- package/dist/definitions.d.ts +10 -0
- package/dist/events/service.d.ts +14 -0
- package/dist/events/service.js +109 -39
- package/dist/events/types.d.ts +5 -1
- package/dist/inspection/inventory.d.ts +1 -1
- package/dist/operation-error.d.ts +75 -0
- package/dist/operation-error.js +123 -0
- package/dist/remote.d.ts +60 -0
- package/dist/remote.js +156 -0
- package/dist/request-context.d.ts +62 -0
- package/dist/request-context.js +2 -0
- package/dist/runtime-mode.d.ts +35 -0
- package/dist/runtime-mode.js +6 -0
- package/dist/runtime.d.ts +17 -1
- package/dist/runtime.js +118 -50
- package/dist/server/access.d.ts +31 -0
- package/dist/server/access.js +109 -0
- package/dist/server/compile.d.ts +59 -0
- package/dist/server/compile.js +211 -0
- package/dist/server/contributions.d.ts +13 -0
- package/dist/server/contributions.js +17 -0
- package/dist/server/create-server.d.ts +15 -0
- package/dist/server/create-server.js +132 -0
- package/dist/server/define.d.ts +40 -0
- package/dist/server/define.js +15 -0
- package/dist/server/fetch-handler.d.ts +17 -0
- package/dist/server/fetch-handler.js +139 -0
- package/dist/server/index.d.ts +22 -0
- package/dist/server/index.js +21 -0
- package/dist/server/kernel.d.ts +44 -0
- package/dist/server/kernel.js +278 -0
- package/dist/server/types.d.ts +208 -0
- package/dist/server/types.js +1 -0
- package/dist/server/validate.d.ts +31 -0
- package/dist/server/validate.js +60 -0
- package/dist/services.d.ts +5 -1
- package/dist/services.js +5 -1
- package/dist/settings/access.d.ts +5 -2
- package/dist/settings/access.js +7 -4
- package/dist/settings/server.d.ts +28 -0
- package/dist/settings/server.js +94 -0
- package/package.json +7 -3
- package/testing/index.d.ts +104 -0
- package/testing/index.mjs +349 -14
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
import type { Namespace } from '../app/types.js';
|
|
2
|
+
import type { ConfigContext } from '../config-service.js';
|
|
3
|
+
import type { ActionSpec, BitaKitRuntimeConfig, InputSchema, Plugin, ServiceContext } from '../definitions.js';
|
|
4
|
+
import type { DiscoveredFile } from '../discovered.js';
|
|
5
|
+
import type { Events } from '../events/types.js';
|
|
6
|
+
import type { InterceptorTarget } from '../interceptors/define.js';
|
|
7
|
+
import type { OperationFunction, RemoteCallOptions, ServerActionMap, ServerServiceMap } from '../remote.js';
|
|
8
|
+
import type { Access, ContextFor, RequestContext } from '../request-context.js';
|
|
9
|
+
import type { ServerSettingsAccess } from '../settings/server.js';
|
|
10
|
+
/** Server services as server contexts see them; never the client `ServiceMap`. */
|
|
11
|
+
export type ServerServices = Namespace<ServerServiceMap>;
|
|
12
|
+
/** What a server Action's `execute` receives. `ctx` follows the Action's `access`. */
|
|
13
|
+
export type ServerExecuteContext<Input = unknown, A = Access> = {
|
|
14
|
+
readonly id: string;
|
|
15
|
+
/** Validated by the `input` schema; `undefined` for an Action without one. */
|
|
16
|
+
readonly input: Input;
|
|
17
|
+
readonly ctx: ContextFor<A>;
|
|
18
|
+
readonly services: ServerServices;
|
|
19
|
+
readonly config: ConfigContext;
|
|
20
|
+
/** The plugin's events; listeners receive this call's `ctx`. */
|
|
21
|
+
readonly events: Events;
|
|
22
|
+
/** Setting handles; `load()` uses this call's `ctx`. */
|
|
23
|
+
readonly settings: ServerSettingsAccess;
|
|
24
|
+
readonly signal: AbortSignal;
|
|
25
|
+
};
|
|
26
|
+
/** Fields of a client Action (the button) that a server Action (the operation) never has. */
|
|
27
|
+
export type ClientOnlyActionField = 'enabled' | 'visible' | 'href' | 'dialog' | 'dialogSize' | 'confirm' | 'slots' | 'groups' | 'order' | 'dividerBefore' | 'shortcut' | 'icon' | 'tooltip' | 'variant' | 'checked' | 'value' | 'concurrency' | 'concurrencyKey' | 'success' | 'failure' | 'internal';
|
|
28
|
+
export type ServerActionSpecInput<Input, Result, A extends Access> = {
|
|
29
|
+
/** Manual composition only; discovery derives `<plugin>.<file>`. */
|
|
30
|
+
id?: string;
|
|
31
|
+
title?: string;
|
|
32
|
+
description?: string;
|
|
33
|
+
/** Required: `public`, `user`, `organization` or `{ permission: { resource: ['operation'] } }`. */
|
|
34
|
+
access: A;
|
|
35
|
+
/** `true` publishes the operation over HTTP and in `remote`; otherwise it is in-process only. */
|
|
36
|
+
expose?: boolean;
|
|
37
|
+
/** Validates and types the input. Without it the input must be `undefined`. */
|
|
38
|
+
input?: InputSchema<Input>;
|
|
39
|
+
/**
|
|
40
|
+
* Validates the result; the caller receives the validator's value. Whether extra keys are
|
|
41
|
+
* stripped depends on the validator (zod/valibot objects strip; passthrough, ArkType and
|
|
42
|
+
* TypeBox keep them).
|
|
43
|
+
*/
|
|
44
|
+
output?: InputSchema<unknown>;
|
|
45
|
+
/** Services from other plugins this operation uses; an explicit startup check. */
|
|
46
|
+
requires?: readonly string[];
|
|
47
|
+
execute(context: ServerExecuteContext<Input, A>): Result | Promise<Result>;
|
|
48
|
+
/** Opaque host metadata; Core never interprets it. */
|
|
49
|
+
metadata?: unknown;
|
|
50
|
+
} & {
|
|
51
|
+
readonly [K in ClientOnlyActionField]?: never;
|
|
52
|
+
};
|
|
53
|
+
declare const serverSignature: unique symbol;
|
|
54
|
+
/**
|
|
55
|
+
* A defined server Action. It is an ordinary `defineAction` result (`kind: 'action'`), so plugins
|
|
56
|
+
* hold it like any Action; the phantom member carries its input, result and access for
|
|
57
|
+
* `ServerActionEntry`.
|
|
58
|
+
*/
|
|
59
|
+
export type ServerActionSpec<Input = unknown, Result = unknown, A extends Access = Access> = {
|
|
60
|
+
readonly kind: 'action';
|
|
61
|
+
readonly id?: string;
|
|
62
|
+
readonly title?: string;
|
|
63
|
+
readonly description?: string;
|
|
64
|
+
readonly access: A;
|
|
65
|
+
readonly expose?: boolean;
|
|
66
|
+
readonly input?: InputSchema<Input>;
|
|
67
|
+
readonly output?: InputSchema<unknown>;
|
|
68
|
+
readonly requires?: readonly string[];
|
|
69
|
+
readonly metadata?: unknown;
|
|
70
|
+
execute(context: any): unknown;
|
|
71
|
+
readonly [serverSignature]?: {
|
|
72
|
+
readonly input: Input;
|
|
73
|
+
readonly result: Result;
|
|
74
|
+
readonly access: A;
|
|
75
|
+
};
|
|
76
|
+
};
|
|
77
|
+
type ValueAt<T, Key extends string> = Key extends '' ? T : Key extends `${infer Head}.${infer Rest}` ? Head extends keyof T ? ValueAt<T[Head], Rest> : never : Key extends keyof T ? T[Key] : never;
|
|
78
|
+
type SignatureOf<T> = T extends {
|
|
79
|
+
readonly [serverSignature]?: infer S;
|
|
80
|
+
} ? NonNullable<S> extends {
|
|
81
|
+
input: infer Input;
|
|
82
|
+
result: infer Result;
|
|
83
|
+
} ? {
|
|
84
|
+
input: Input;
|
|
85
|
+
result: Result;
|
|
86
|
+
} : {
|
|
87
|
+
input: unknown;
|
|
88
|
+
result: unknown;
|
|
89
|
+
} : T extends ActionSpec<infer Input, infer Result> ? {
|
|
90
|
+
input: Input;
|
|
91
|
+
result: Awaited<Result>;
|
|
92
|
+
} : {
|
|
93
|
+
input: unknown;
|
|
94
|
+
result: unknown;
|
|
95
|
+
};
|
|
96
|
+
/**
|
|
97
|
+
* One `ServerActionMap` entry, written by the generated server file under the Action's ID:
|
|
98
|
+
* `'todos.add': ServerActionEntry<typeof file3, 'todos', true>`. `F` is the discovered file (or
|
|
99
|
+
* the Action's type); `Key` selects one entry of a record file (`'add'` in `server/actions.ts`).
|
|
100
|
+
* `Module` names the owner for readers of the generated file; the map key carries the ID.
|
|
101
|
+
*/
|
|
102
|
+
export type ServerActionEntry<F, _Module extends string = string, Exposed extends boolean = boolean, Key extends string = ''> = SignatureOf<ValueAt<F extends DiscoveredFile<infer T, any> ? T : F, Key>> & {
|
|
103
|
+
exposed: Exposed;
|
|
104
|
+
};
|
|
105
|
+
/** Per-call options of the in-process `Caller` and `server.call`. */
|
|
106
|
+
export type CallOptions = RemoteCallOptions & {
|
|
107
|
+
/** Correlates the call with logs; `crypto.randomUUID()` when absent. */
|
|
108
|
+
requestId?: string;
|
|
109
|
+
};
|
|
110
|
+
/** Every server operation, also private ones, as nested functions: `caller.todos.add(input)`. */
|
|
111
|
+
export type Caller = Namespace<{
|
|
112
|
+
[K in keyof ServerActionMap & string]: OperationFunction<ServerActionMap[K], CallOptions>;
|
|
113
|
+
}>;
|
|
114
|
+
/** One compiled operation, as `server.operations()` lists it. */
|
|
115
|
+
export type OperationInfo = Readonly<{
|
|
116
|
+
id: string;
|
|
117
|
+
plugin: string;
|
|
118
|
+
access: Access;
|
|
119
|
+
exposed: boolean;
|
|
120
|
+
title?: string;
|
|
121
|
+
description?: string;
|
|
122
|
+
source?: string;
|
|
123
|
+
}>;
|
|
124
|
+
/** Server services' context: the client keys, with server services and per-request settings. */
|
|
125
|
+
export type ServerServiceContext = Omit<ServiceContext, 'services' | 'settings' | 'remote'> & {
|
|
126
|
+
services: ServerServices;
|
|
127
|
+
/** Per-request setting handles: `await settings.todos.limit.load(ctx)`. */
|
|
128
|
+
settings: ServerSettingsAccess;
|
|
129
|
+
};
|
|
130
|
+
/** What a server interceptor sees: the validated input and the call's `ctx`. */
|
|
131
|
+
export type ServerInterceptorContext = {
|
|
132
|
+
readonly id: string;
|
|
133
|
+
readonly input: unknown;
|
|
134
|
+
readonly ctx: RequestContext;
|
|
135
|
+
readonly services: ServerServices;
|
|
136
|
+
readonly config: ConfigContext;
|
|
137
|
+
readonly signal: AbortSignal;
|
|
138
|
+
};
|
|
139
|
+
/**
|
|
140
|
+
* An interceptor around server operations. `before` runs after access and input validation;
|
|
141
|
+
* a throw rejects the call (an OperationError passes through) and returning `false` rejects it
|
|
142
|
+
* with FORBIDDEN (`INTERCEPTED`). `after` and `onError` observe and are not awaited.
|
|
143
|
+
*/
|
|
144
|
+
export type ServerInterceptorSpec = {
|
|
145
|
+
readonly kind?: 'interceptor';
|
|
146
|
+
/** Exact IDs, `todos.*`, or `*` (the default). */
|
|
147
|
+
action?: InterceptorTarget;
|
|
148
|
+
service?: never;
|
|
149
|
+
method?: never;
|
|
150
|
+
order?: number;
|
|
151
|
+
/** `plugin` (default for plugins) sees its own operations; `global` (default for the app) sees all. */
|
|
152
|
+
scope?: 'plugin' | 'global';
|
|
153
|
+
requires?: readonly string[];
|
|
154
|
+
before?(context: ServerInterceptorContext): void | false | Promise<void | false>;
|
|
155
|
+
after?(context: ServerInterceptorContext & {
|
|
156
|
+
readonly result: unknown;
|
|
157
|
+
}): void | Promise<void>;
|
|
158
|
+
onError?(context: ServerInterceptorContext & {
|
|
159
|
+
readonly error: unknown;
|
|
160
|
+
}): void | Promise<void>;
|
|
161
|
+
};
|
|
162
|
+
/** The composition a server runs: the client configuration without UI-only fields. */
|
|
163
|
+
export type ServerConfig = Omit<BitaKitRuntimeConfig, 'ui' | 'slots' | 'choose' | 'groups' | 'actionOverrides' | 'remote'>;
|
|
164
|
+
export type ServerOptions = {
|
|
165
|
+
/** Host-provided services, as in `createRuntime`. */
|
|
166
|
+
services?: Readonly<Record<string, unknown>>;
|
|
167
|
+
/** Extra host plugins, for example installers for server contribution kinds. */
|
|
168
|
+
plugins?: readonly Plugin[];
|
|
169
|
+
/** The HTTP prefix `fetchHandler` serves; default `/api/rpc`. */
|
|
170
|
+
endpoint?: string;
|
|
171
|
+
/** Process-wide registration name; the generated server file passes `'bitakit'`. */
|
|
172
|
+
instance?: string;
|
|
173
|
+
/** Content hash of the generated server file; a different stamp replaces the kernel in development. */
|
|
174
|
+
stamp?: string;
|
|
175
|
+
/**
|
|
176
|
+
* The exposed operation IDs the client's `remote` knows (read statically by discovery). When
|
|
177
|
+
* given, an exposed operation missing from it logs one warning at boot.
|
|
178
|
+
*/
|
|
179
|
+
operations?: readonly string[];
|
|
180
|
+
};
|
|
181
|
+
/** In-process and HTTP entry to the server kernel. Importing it never boots anything. */
|
|
182
|
+
export interface Server {
|
|
183
|
+
readonly endpoint: string;
|
|
184
|
+
/** The first access boots the kernel; resolves when every service's `onStart` finished. */
|
|
185
|
+
readonly ready: Promise<void>;
|
|
186
|
+
/**
|
|
187
|
+
* An in-process caller with the identity the `requestContext` provider resolves for this
|
|
188
|
+
* request; `Headers` are wrapped in `new Request('http://bitakit.internal/', { headers })`.
|
|
189
|
+
* Every operation is callable, also private ones, with the same checks as over HTTP.
|
|
190
|
+
*/
|
|
191
|
+
as(request: Request | Headers): Caller;
|
|
192
|
+
/**
|
|
193
|
+
* One call by ID. `exposedOnly` (default true, always over HTTP) admits only exposed operations
|
|
194
|
+
* by their exact ID; `false` also reaches private ones and folds case like Core.
|
|
195
|
+
*/
|
|
196
|
+
call(id: string, input: unknown, request: Request | Headers, options?: CallOptions & {
|
|
197
|
+
exposedOnly?: boolean;
|
|
198
|
+
}): Promise<unknown>;
|
|
199
|
+
/** The compiled operations (boots first); SERVICE_UNAVAILABLE once stopped, never a new boot. */
|
|
200
|
+
operations(): Promise<readonly OperationInfo[]>;
|
|
201
|
+
/**
|
|
202
|
+
* Drains in-flight calls, then stops the services. Later calls answer SERVICE_UNAVAILABLE. With
|
|
203
|
+
* `instance` it stops the instance's kernel for every handle, unless a newer module copy's
|
|
204
|
+
* kernel has replaced this handle's code (then only this handle stops).
|
|
205
|
+
*/
|
|
206
|
+
stop(): Promise<void>;
|
|
207
|
+
}
|
|
208
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { InputSchema } from '../definitions.js';
|
|
2
|
+
import { type OperationIssue } from '../operation-error.js';
|
|
3
|
+
/**
|
|
4
|
+
* The outcome of one validation:
|
|
5
|
+
* - `ok`: the validator's value;
|
|
6
|
+
* - `issues`: the value is invalid. `cause` is set when a `parse` threw without structured
|
|
7
|
+
* issues; its message never reaches the caller (the kernel logs it), the issue is a fixed text;
|
|
8
|
+
* - `fault`: the schema itself failed (a Standard Schema `validate` threw or rejected, which is
|
|
9
|
+
* never how it reports invalid values): a server error.
|
|
10
|
+
* An `OperationError` thrown by `parse` is rethrown as it is, so hand-written parsers can still
|
|
11
|
+
* send a safe message of their own.
|
|
12
|
+
*/
|
|
13
|
+
export type Checked = {
|
|
14
|
+
ok: true;
|
|
15
|
+
value: unknown;
|
|
16
|
+
} | {
|
|
17
|
+
ok: false;
|
|
18
|
+
issues: OperationIssue[];
|
|
19
|
+
cause?: unknown;
|
|
20
|
+
} | {
|
|
21
|
+
ok: false;
|
|
22
|
+
fault: unknown;
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* Validates once and keeps each issue's path. Standard Schema is preferred because its issues
|
|
26
|
+
* are structured and it may be async; `parse` is the fallback and may return a promise too.
|
|
27
|
+
* Returns a promise only when the schema validates asynchronously.
|
|
28
|
+
*/
|
|
29
|
+
export declare function check(schema: InputSchema<unknown>, value: unknown): Checked | Promise<Checked>;
|
|
30
|
+
/** A value usable as `input`/`output`: `{ parse }` or a Standard Schema. */
|
|
31
|
+
export declare function isSchema(value: unknown): boolean;
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { isOperationError } from '../operation-error.js';
|
|
2
|
+
import { isThenable } from '../schema.js';
|
|
3
|
+
const segment = (part) => typeof part === 'number'
|
|
4
|
+
? part
|
|
5
|
+
: part && typeof part === 'object' && 'key' in part
|
|
6
|
+
? segment(part.key)
|
|
7
|
+
: String(part);
|
|
8
|
+
function issuesOf(raw) {
|
|
9
|
+
return raw.map((issue) => ({
|
|
10
|
+
path: Array.isArray(issue.path) ? issue.path.map(segment) : [],
|
|
11
|
+
message: typeof issue.message === 'string' ? issue.message : 'Invalid value.',
|
|
12
|
+
}));
|
|
13
|
+
}
|
|
14
|
+
/** A `parse` failure: its `issues` (zod, valibot and friends), else a fixed root issue. */
|
|
15
|
+
function parseFailure(error) {
|
|
16
|
+
if (isOperationError(error))
|
|
17
|
+
throw error;
|
|
18
|
+
const issues = error?.issues;
|
|
19
|
+
if (Array.isArray(issues) && issues.length)
|
|
20
|
+
return { ok: false, issues: issuesOf(issues) };
|
|
21
|
+
return { ok: false, issues: [{ path: [], message: 'Invalid value.' }], cause: error };
|
|
22
|
+
}
|
|
23
|
+
const fault = (error) => ({ ok: false, fault: error });
|
|
24
|
+
function settle(result) {
|
|
25
|
+
const outcome = result;
|
|
26
|
+
return outcome && Array.isArray(outcome.issues)
|
|
27
|
+
? { ok: false, issues: issuesOf(outcome.issues) }
|
|
28
|
+
: { ok: true, value: outcome?.value };
|
|
29
|
+
}
|
|
30
|
+
const parsed = (value) => ({ ok: true, value });
|
|
31
|
+
/**
|
|
32
|
+
* Validates once and keeps each issue's path. Standard Schema is preferred because its issues
|
|
33
|
+
* are structured and it may be async; `parse` is the fallback and may return a promise too.
|
|
34
|
+
* Returns a promise only when the schema validates asynchronously.
|
|
35
|
+
*/
|
|
36
|
+
export function check(schema, value) {
|
|
37
|
+
if ('~standard' in schema && typeof schema['~standard']?.validate === 'function') {
|
|
38
|
+
try {
|
|
39
|
+
const result = schema['~standard'].validate(value);
|
|
40
|
+
return isThenable(result) ? Promise.resolve(result).then(settle, fault) : settle(result);
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
return fault(error);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
try {
|
|
47
|
+
const result = schema.parse(value);
|
|
48
|
+
return isThenable(result) ? Promise.resolve(result).then(parsed, parseFailure) : parsed(result);
|
|
49
|
+
}
|
|
50
|
+
catch (error) {
|
|
51
|
+
return parseFailure(error);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
/** A value usable as `input`/`output`: `{ parse }` or a Standard Schema. */
|
|
55
|
+
export function isSchema(value) {
|
|
56
|
+
if (!value || (typeof value !== 'object' && typeof value !== 'function'))
|
|
57
|
+
return false;
|
|
58
|
+
const candidate = value;
|
|
59
|
+
return (typeof candidate.parse === 'function' || typeof candidate['~standard']?.validate === 'function');
|
|
60
|
+
}
|
package/dist/services.d.ts
CHANGED
|
@@ -14,7 +14,11 @@ export type Observable = {
|
|
|
14
14
|
subscribe(listener: () => void): () => void;
|
|
15
15
|
};
|
|
16
16
|
/** Allocates ownership before initialization, so partial factory failures can be fully stopped. */
|
|
17
|
-
export declare function createServices(definitions: readonly ServiceDefinition<any>[], provided?: Readonly<Record<string, unknown>>, configFor?: (definition: ServiceDefinition<any>) => ConfigContext, decorate?: (id: string, instance: any, active: () => boolean) => any, events?: EventService, scope?: ServiceScope, idOf?: (definition: ServiceDefinition<any>) => string, settings?: SettingsAccess, onPhase?: (id: string, phase: LifecyclePhase, error?: unknown) => void
|
|
17
|
+
export declare function createServices(definitions: readonly ServiceDefinition<any>[], provided?: Readonly<Record<string, unknown>>, configFor?: (definition: ServiceDefinition<any>) => ConfigContext, decorate?: (id: string, instance: any, active: () => boolean) => any, events?: EventService, scope?: ServiceScope, idOf?: (definition: ServiceDefinition<any>) => string, settings?: SettingsAccess, onPhase?: (id: string, phase: LifecyclePhase, error?: unknown) => void,
|
|
18
|
+
/** Extra context keys every factory receives; the client runtime passes `remote`. */
|
|
19
|
+
extras?: {
|
|
20
|
+
readonly remote?: unknown;
|
|
21
|
+
}): {
|
|
18
22
|
services: Readonly<Record<string, unknown>>;
|
|
19
23
|
observed: Set<Observable>;
|
|
20
24
|
initialize: () => void;
|
package/dist/services.js
CHANGED
|
@@ -4,7 +4,9 @@ import { BitaKitStartupError, isBitaKitStartupError, moduleLabel } from './start
|
|
|
4
4
|
import { createStore, isObservable, isStore } from './store.js';
|
|
5
5
|
import { cleanupSequence, cleanupFailure } from './lifecycle/cleanup.js';
|
|
6
6
|
/** Allocates ownership before initialization, so partial factory failures can be fully stopped. */
|
|
7
|
-
export function createServices(definitions, provided = {}, configFor = () => new ConfigService([{ id: 'app' }]).context('app'), decorate = (_id, instance) => instance, events = new EventService(), scope, idOf = (definition) => definition.id, settings = Object.freeze({}), onPhase = () => { }
|
|
7
|
+
export function createServices(definitions, provided = {}, configFor = () => new ConfigService([{ id: 'app' }]).context('app'), decorate = (_id, instance) => instance, events = new EventService(), scope, idOf = (definition) => definition.id, settings = Object.freeze({}), onPhase = () => { },
|
|
8
|
+
/** Extra context keys every factory receives; the client runtime passes `remote`. */
|
|
9
|
+
extras = {}) {
|
|
8
10
|
let active = true;
|
|
9
11
|
let initialized = false;
|
|
10
12
|
let stopping = false;
|
|
@@ -75,7 +77,9 @@ export function createServices(definitions, provided = {}, configFor = () => new
|
|
|
75
77
|
onPhase(id, 'starting');
|
|
76
78
|
let instance;
|
|
77
79
|
try {
|
|
80
|
+
// Server services get no `remote`; the client runtime always passes one.
|
|
78
81
|
instance = definition.create({
|
|
82
|
+
...(extras.remote ? { remote: extras.remote } : {}),
|
|
79
83
|
events: eventScope.events,
|
|
80
84
|
services: view,
|
|
81
85
|
config: configFor(definition),
|
|
@@ -15,5 +15,8 @@ export type SettingHandle<T = unknown> = {
|
|
|
15
15
|
export type SettingsAccess = Namespace<{
|
|
16
16
|
[K in keyof SettingsMap]: SettingHandle<SettingsMap[K]>;
|
|
17
17
|
}>;
|
|
18
|
-
/**
|
|
19
|
-
|
|
18
|
+
/**
|
|
19
|
+
* Validates declarations; namespace proxies follow the current store without copying values.
|
|
20
|
+
* `makeHandle` builds each leaf; server mode passes handles that load per request.
|
|
21
|
+
*/
|
|
22
|
+
export declare function createSettingsAccess(store: SettingsStore, makeHandle?: (store: SettingsStore, key: string, definition: SettingSpec<any>) => SettingHandle): SettingsAccess;
|
package/dist/settings/access.js
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
import { resolveName } from '../name-resolution.js';
|
|
2
2
|
const reserved = new Set(['then', 'toJSON', 'constructor', '__proto__']);
|
|
3
|
-
/**
|
|
4
|
-
|
|
3
|
+
/**
|
|
4
|
+
* Validates declarations; namespace proxies follow the current store without copying values.
|
|
5
|
+
* `makeHandle` builds each leaf; server mode passes handles that load per request.
|
|
6
|
+
*/
|
|
7
|
+
export function createSettingsAccess(store, makeHandle = handle) {
|
|
5
8
|
const root = { children: new Map(), path: '' };
|
|
6
9
|
for (const entry of store.entries()) {
|
|
7
10
|
const segments = entry.key.split('.');
|
|
@@ -16,7 +19,7 @@ export function createSettingsAccess(store) {
|
|
|
16
19
|
if (index === segments.length - 1) {
|
|
17
20
|
if (child.children.size)
|
|
18
21
|
throw new Error(`Setting "${entry.key}" clashes with the settings of plugin "${path}". Rename the app setting.`);
|
|
19
|
-
child.handle =
|
|
22
|
+
child.handle = makeHandle(store, entry.key, entry.spec);
|
|
20
23
|
}
|
|
21
24
|
else if (child.handle)
|
|
22
25
|
throw new Error(`Plugin "${path}" declares settings, but the app also declares a setting named "${path}". Rename the app setting.`);
|
|
@@ -45,7 +48,7 @@ export function createSettingsAccess(store) {
|
|
|
45
48
|
if (store.has(key)) {
|
|
46
49
|
const spec = store.definition(key).spec;
|
|
47
50
|
if (handles.get(key)?.spec !== spec)
|
|
48
|
-
handles.set(key, { spec, value:
|
|
51
|
+
handles.set(key, { spec, value: makeHandle(store, key, spec) });
|
|
49
52
|
return handles.get(key).value;
|
|
50
53
|
}
|
|
51
54
|
if (keys().includes(resolveName(name, keys())))
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { Namespace } from '../app/types.js';
|
|
2
|
+
import type { RequestContext } from '../request-context.js';
|
|
3
|
+
import { type SettingSpec, type SettingsMap } from './define.js';
|
|
4
|
+
import type { SettingHandle } from './access.js';
|
|
5
|
+
import type { SettingsStorage } from './storage.js';
|
|
6
|
+
/**
|
|
7
|
+
* A setting on the server: values are loaded per request, never held in process memory. In an
|
|
8
|
+
* operation `load()` uses the call's `ctx`; services and listeners pass theirs: `load(ctx)`.
|
|
9
|
+
*/
|
|
10
|
+
export type ServerSettingHandle<T = unknown> = {
|
|
11
|
+
readonly key: string;
|
|
12
|
+
readonly definition: SettingSpec<T>;
|
|
13
|
+
load(ctx?: RequestContext): Promise<T>;
|
|
14
|
+
};
|
|
15
|
+
export type ServerSettingsAccess = Namespace<{
|
|
16
|
+
[K in keyof SettingsMap]: ServerSettingHandle<SettingsMap[K]>;
|
|
17
|
+
}>;
|
|
18
|
+
/**
|
|
19
|
+
* The handle the runtime builds in server mode. The storage is never called without the owner
|
|
20
|
+
* ID the setting's scope needs: without it, `load` answers the declared default. `storage`
|
|
21
|
+
* returns the `settings.storage` provider, or undefined when none is installed.
|
|
22
|
+
*/
|
|
23
|
+
export declare function serverSettingHandle(key: string, definition: SettingSpec<any>, storage: () => SettingsStorage | undefined): SettingHandle & ServerSettingHandle;
|
|
24
|
+
/**
|
|
25
|
+
* The `settings` an operation receives: the same namespaces, with `load()` defaulting to the
|
|
26
|
+
* call's `ctx`. A lazy Proxy over the server access, so building it per call costs nothing.
|
|
27
|
+
*/
|
|
28
|
+
export declare function bindSettings(access: object, ctx: RequestContext): ServerSettingsAccess;
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { parseSetting } from './define.js';
|
|
2
|
+
const clientOnly = (key) => () => {
|
|
3
|
+
throw new Error(`Setting "${key}" has no process-wide value on the server; use await settings.${key}.load().`);
|
|
4
|
+
};
|
|
5
|
+
/**
|
|
6
|
+
* The handle the runtime builds in server mode. The storage is never called without the owner
|
|
7
|
+
* ID the setting's scope needs: without it, `load` answers the declared default. `storage`
|
|
8
|
+
* returns the `settings.storage` provider, or undefined when none is installed.
|
|
9
|
+
*/
|
|
10
|
+
export function serverSettingHandle(key, definition, storage) {
|
|
11
|
+
const unsupported = clientOnly(key);
|
|
12
|
+
const handle = Object.freeze({
|
|
13
|
+
key,
|
|
14
|
+
definition,
|
|
15
|
+
get: unsupported,
|
|
16
|
+
state: unsupported,
|
|
17
|
+
set: unsupported,
|
|
18
|
+
reset: unsupported,
|
|
19
|
+
subscribe: unsupported,
|
|
20
|
+
load: (ctx) => loadSetting(key, definition, storage, ctx),
|
|
21
|
+
});
|
|
22
|
+
serverHandles.add(handle);
|
|
23
|
+
return handle;
|
|
24
|
+
}
|
|
25
|
+
/** Leaves of the server access; namespaces are Proxies that throw on unknown names. */
|
|
26
|
+
const serverHandles = new WeakSet();
|
|
27
|
+
async function loadSetting(key, spec, storage, ctx) {
|
|
28
|
+
if (!ctx || typeof ctx !== 'object')
|
|
29
|
+
throw new Error(`Setting "${key}" needs the request context outside an operation: settings.${key}.load(ctx).`);
|
|
30
|
+
if (spec.scope === 'device')
|
|
31
|
+
throw new Error(`Setting "${key}" belongs to the browser (scope "device"); the server cannot load it.`);
|
|
32
|
+
const scope = spec.scope ?? 'user';
|
|
33
|
+
const userId = typeof ctx.user?.id === 'string' && ctx.user.id ? ctx.user.id : undefined;
|
|
34
|
+
const organizationId = typeof ctx.organization?.id === 'string' && ctx.organization.id
|
|
35
|
+
? ctx.organization.id
|
|
36
|
+
: undefined;
|
|
37
|
+
// Never ask the storage without the owner: an undefined ID can drop a tenant filter.
|
|
38
|
+
if ((scope === 'user' && !userId) || (scope === 'organization' && !organizationId))
|
|
39
|
+
return spec.default;
|
|
40
|
+
const provider = storage();
|
|
41
|
+
if (!provider)
|
|
42
|
+
throw new Error(`Setting "${key}" cannot load: no service provides settings.storage. Add a server service with provides: settingsStorage.`);
|
|
43
|
+
const context = Object.freeze({
|
|
44
|
+
scope,
|
|
45
|
+
...(userId ? { userId } : {}),
|
|
46
|
+
...(organizationId ? { organizationId } : {}),
|
|
47
|
+
});
|
|
48
|
+
const stored = await provider.load(key, context);
|
|
49
|
+
if (stored?.value === undefined)
|
|
50
|
+
return spec.default;
|
|
51
|
+
try {
|
|
52
|
+
return parseSetting(spec, stored.value, key);
|
|
53
|
+
}
|
|
54
|
+
catch (error) {
|
|
55
|
+
console.warn(`[bitakit] The stored value of setting "${key}" is invalid; using the default.`, error);
|
|
56
|
+
return spec.default;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
const reserved = new Set(['then', 'toJSON', 'constructor', '__proto__']);
|
|
60
|
+
/**
|
|
61
|
+
* The `settings` an operation receives: the same namespaces, with `load()` defaulting to the
|
|
62
|
+
* call's `ctx`. A lazy Proxy over the server access, so building it per call costs nothing.
|
|
63
|
+
*/
|
|
64
|
+
export function bindSettings(access, ctx) {
|
|
65
|
+
const bound = new Map();
|
|
66
|
+
const wrap = (node) => {
|
|
67
|
+
let view = bound.get(node);
|
|
68
|
+
if (view)
|
|
69
|
+
return view;
|
|
70
|
+
if (serverHandles.has(node)) {
|
|
71
|
+
const handle = node;
|
|
72
|
+
view = Object.freeze({
|
|
73
|
+
key: handle.key,
|
|
74
|
+
definition: handle.definition,
|
|
75
|
+
load: (other) => handle.load(other ?? ctx),
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
else
|
|
79
|
+
view = new Proxy(node, {
|
|
80
|
+
get: (target, name) => {
|
|
81
|
+
if (typeof name !== 'string' || reserved.has(name))
|
|
82
|
+
return undefined;
|
|
83
|
+
const value = Reflect.get(target, name);
|
|
84
|
+
return value && typeof value === 'object' ? wrap(value) : value;
|
|
85
|
+
},
|
|
86
|
+
set: () => false,
|
|
87
|
+
defineProperty: () => false,
|
|
88
|
+
deleteProperty: () => false,
|
|
89
|
+
});
|
|
90
|
+
bound.set(node, view);
|
|
91
|
+
return view;
|
|
92
|
+
};
|
|
93
|
+
return wrap(access);
|
|
94
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bitakit/core",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.2",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"sideEffects": false,
|
|
6
6
|
"files": [
|
|
@@ -22,6 +22,10 @@
|
|
|
22
22
|
"types": "./dist/actions/core.d.ts",
|
|
23
23
|
"default": "./dist/actions/core.js"
|
|
24
24
|
},
|
|
25
|
+
"./server": {
|
|
26
|
+
"types": "./dist/server/index.d.ts",
|
|
27
|
+
"default": "./dist/server/index.js"
|
|
28
|
+
},
|
|
25
29
|
"./discovery": {
|
|
26
30
|
"types": "./discovery/index.d.ts",
|
|
27
31
|
"default": "./discovery/index.mjs"
|
|
@@ -42,7 +46,7 @@
|
|
|
42
46
|
"zustand": "^5.0.0"
|
|
43
47
|
},
|
|
44
48
|
"peerDependencies": {
|
|
45
|
-
"@bitakit/discovery": "^0.3.
|
|
49
|
+
"@bitakit/discovery": "^0.3.1",
|
|
46
50
|
"jiti": "^2.7.0"
|
|
47
51
|
},
|
|
48
52
|
"peerDependenciesMeta": {
|
|
@@ -54,7 +58,7 @@
|
|
|
54
58
|
}
|
|
55
59
|
},
|
|
56
60
|
"devDependencies": {
|
|
57
|
-
"@bitakit/discovery": "^0.3.
|
|
61
|
+
"@bitakit/discovery": "^0.3.1",
|
|
58
62
|
"jiti": "^2.7.0",
|
|
59
63
|
"typescript": "^5.9.3"
|
|
60
64
|
},
|
package/testing/index.d.ts
CHANGED
|
@@ -5,8 +5,16 @@ import type {
|
|
|
5
5
|
BitaKitEvent,
|
|
6
6
|
BitaKitRuntime,
|
|
7
7
|
Plugin,
|
|
8
|
+
Remote,
|
|
8
9
|
Services,
|
|
9
10
|
} from '@bitakit/core';
|
|
11
|
+
import type {
|
|
12
|
+
Caller,
|
|
13
|
+
RequestIdentity,
|
|
14
|
+
RequestMember,
|
|
15
|
+
RequestUser,
|
|
16
|
+
Server,
|
|
17
|
+
} from '@bitakit/core/server';
|
|
10
18
|
import type {
|
|
11
19
|
ActionId,
|
|
12
20
|
ActionInput,
|
|
@@ -56,9 +64,105 @@ export function mountPlugin(
|
|
|
56
64
|
/** Host-provided services, such as a fake authentication service. */
|
|
57
65
|
services?: Readonly<Record<string, unknown>>;
|
|
58
66
|
configOverrides?: Readonly<Record<string, Record<string, unknown>>>;
|
|
67
|
+
/**
|
|
68
|
+
* Replaces the client `remote` in Action and service contexts: a stub, or
|
|
69
|
+
* `mountServer(...).as(identity(...))` so the client half calls its real server half in-process.
|
|
70
|
+
*/
|
|
71
|
+
remote?: Remote | Caller;
|
|
59
72
|
},
|
|
60
73
|
): Promise<MountedPlugin>;
|
|
61
74
|
|
|
75
|
+
export type MountedServer = {
|
|
76
|
+
/** The mounted plugin's ID, or the app module's (`'app'` unless its `plugin.config.ts` names one). */
|
|
77
|
+
id: string;
|
|
78
|
+
/** The booted server handle (`operations()`, `call()`); `as()` below is the usual entry. */
|
|
79
|
+
server: Server;
|
|
80
|
+
/**
|
|
81
|
+
* An in-process caller with this identity over every operation, also private ones, with the
|
|
82
|
+
* same access checks, input validation and interceptors as over HTTP:
|
|
83
|
+
* `await mounted.as(identity({ organization: 'org-1' })).todos.add({ title: 'A' })`.
|
|
84
|
+
*/
|
|
85
|
+
as(identity: RequestIdentity): Caller;
|
|
86
|
+
/**
|
|
87
|
+
* Loads a server module through the loader the mounted files use, so a test seeds or inspects
|
|
88
|
+
* the same instance its Actions and services see: `await mounted.import('src/server/db.ts')`.
|
|
89
|
+
* Takes a path relative to the working directory (as `mountServer` takes folders), an absolute
|
|
90
|
+
* path, a tsconfig `paths` alias or a package. A module imported natively (`import ... from`)
|
|
91
|
+
* is a second copy.
|
|
92
|
+
*/
|
|
93
|
+
import<Module = Record<string, any>>(specifier: string): Promise<Module>;
|
|
94
|
+
stop(): Promise<void>;
|
|
95
|
+
[Symbol.asyncDispose](): Promise<void>;
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
/** An integration contribution kind, as `kinds` of bitakit.config.ts declares it. */
|
|
99
|
+
export type TestContributionKind = {
|
|
100
|
+
name: string;
|
|
101
|
+
directory: string;
|
|
102
|
+
/** The module exporting the normalizer; a relative path resolves against the app folder. */
|
|
103
|
+
from: string;
|
|
104
|
+
normalize: string;
|
|
105
|
+
/** Only `server` kinds load: their files in `server/contributions/<directory>`. */
|
|
106
|
+
runtime?: 'client' | 'server' | 'both';
|
|
107
|
+
types?: { entry: string; map: string };
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Mounts the server half of one folder for tests and boots it: the shared `events.ts`,
|
|
112
|
+
* `settings.ts`, `permissions.ts` and `configs/`, plus `server/services`, `server/actions`,
|
|
113
|
+
* `server/interceptors` and the files of server-only contribution kinds. The app folder
|
|
114
|
+
* (`directory` of bitakit.config.ts, `src` by default) mounts as the app module, whose
|
|
115
|
+
* operations are unprefixed (`whoami`, as in the generated server file); any other folder mounts
|
|
116
|
+
* as a plugin. Files load through jiti with the nearest tsconfig.json's `paths`, so server files
|
|
117
|
+
* may import `@/server/db` or `./helpers`; read their modules in the test through `import()`. A
|
|
118
|
+
* test `requestContext` provider answers every `as()` caller with its identity; it replaces any
|
|
119
|
+
* provider the mounted folders declare. A folder keeps only its `dependencies` on mounted modules,
|
|
120
|
+
* as the generated server file drops package plugins (they have no server half): mount a local
|
|
121
|
+
* plugin the code needs through `plugins`. Rejects with the attributed startup error, and names
|
|
122
|
+
* the required `@bitakit/discovery` version when the installed one does not report `server/`
|
|
123
|
+
* folders.
|
|
124
|
+
*/
|
|
125
|
+
export function mountServer(
|
|
126
|
+
directory?: string,
|
|
127
|
+
options?: {
|
|
128
|
+
/**
|
|
129
|
+
* A plugin defaults to `id` in the folder's `plugin.config.ts`, the folder under `plugins/`,
|
|
130
|
+
* or the package name; the app module to its `plugin.config.ts` `id`, else `'app'`.
|
|
131
|
+
*/
|
|
132
|
+
id?: string;
|
|
133
|
+
/** Mount the folder as the app module (unprefixed) or as a plugin; detected by default. */
|
|
134
|
+
app?: boolean;
|
|
135
|
+
/** Further plugin folders (their server halves) or `Plugin` objects. */
|
|
136
|
+
plugins?: readonly (Plugin | string)[];
|
|
137
|
+
/** Host-provided services; `requestContext` is the test provider's and cannot be passed. */
|
|
138
|
+
services?: Readonly<Record<string, unknown>>;
|
|
139
|
+
configOverrides?: Readonly<Record<string, Record<string, unknown>>>;
|
|
140
|
+
/**
|
|
141
|
+
* Contribution kinds besides `kinds` of bitakit.config.ts, such as the ones a package declares
|
|
142
|
+
* through its discovery hook; the same name replaces the configured kind.
|
|
143
|
+
*/
|
|
144
|
+
kinds?: readonly TestContributionKind[];
|
|
145
|
+
},
|
|
146
|
+
): Promise<MountedServer>;
|
|
147
|
+
|
|
148
|
+
export type TestIdentityOptions = {
|
|
149
|
+
/** A user ID or user; `null` is a signed-out caller. Default `{ id: 'user-1' }`. */
|
|
150
|
+
user?: string | RequestUser | null;
|
|
151
|
+
/** The organization of a verified, active membership: an ID or `{ id }`. Default none. */
|
|
152
|
+
organization?: string | { readonly id: string } | null;
|
|
153
|
+
/** The membership record `ctx.member` receives. Default `null`. */
|
|
154
|
+
member?: RequestMember | null;
|
|
155
|
+
/**
|
|
156
|
+
* What `can` grants, and nothing else: `{ todos: ['create'] }`, a resource's `'*'` for every
|
|
157
|
+
* operation, or `'*'` for everything. Default nothing.
|
|
158
|
+
*/
|
|
159
|
+
permissions?: '*' | Readonly<Record<string, '*' | readonly string[]>>;
|
|
160
|
+
/** Why there is no organization: `'NO_ACTIVE_ORGANIZATION'` or `'NOT_A_MEMBER'`. */
|
|
161
|
+
reason?: RequestIdentity['reason'];
|
|
162
|
+
};
|
|
163
|
+
/** A test identity for `mountServer(...).as()`; see `TestIdentityOptions`. */
|
|
164
|
+
export function identity(options?: TestIdentityOptions): RequestIdentity;
|
|
165
|
+
|
|
62
166
|
/**
|
|
63
167
|
* Checks an `auth` provider against the AuthService contract, for the provider's own tests:
|
|
64
168
|
* a stable snapshot, working subscribe/unsubscribe, a string `user.id` after `signIn`, an
|